privatebin.js 147 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810
  1. /**
  2. * PrivateBin
  3. *
  4. * a zero-knowledge paste bin
  5. *
  6. * @see {@link https://github.com/PrivateBin/PrivateBin}
  7. * @copyright 2012 Sébastien SAUVAGE ({@link http://sebsauvage.net})
  8. * @license {@link https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License}
  9. * @version 1.2.1
  10. * @name PrivateBin
  11. * @namespace
  12. */
  13. /** global: Base64 */
  14. /** global: DOMPurify */
  15. /** global: FileReader */
  16. /** global: RawDeflate */
  17. /** global: history */
  18. /** global: navigator */
  19. /** global: prettyPrint */
  20. /** global: prettyPrintOne */
  21. /** global: showdown */
  22. /** global: kjua */
  23. // main application start, called when DOM is fully loaded
  24. jQuery(document).ready(function() {
  25. 'use strict';
  26. // run main controller
  27. $.PrivateBin.Controller.init();
  28. });
  29. jQuery.PrivateBin = (function($, RawDeflate) {
  30. 'use strict';
  31. /**
  32. * zlib library interface
  33. *
  34. * @private
  35. */
  36. let z;
  37. /**
  38. * CryptoData class
  39. *
  40. * bundles helper fuctions used in both paste and comment formats
  41. *
  42. * @name CryptoData
  43. * @class
  44. */
  45. function CryptoData(data) {
  46. this.v = 1;
  47. // store all keys in the default locations for drop-in replacement
  48. for (let key in data) {
  49. this[key] = data[key];
  50. }
  51. /**
  52. * gets the cipher data (cipher text + adata)
  53. *
  54. * @name Paste.getCipherData
  55. * @function
  56. * @return {Array}|{string}
  57. */
  58. this.getCipherData = function()
  59. {
  60. return this.v === 1 ? this.data : [this.ct, this.adata];
  61. }
  62. }
  63. /**
  64. * Paste class
  65. *
  66. * bundles helper fuctions around the paste formats
  67. *
  68. * @name Paste
  69. * @class
  70. */
  71. function Paste(data) {
  72. // inherit constructor and methods of CryptoData
  73. CryptoData.call(this, data);
  74. /**
  75. * gets the used formatter
  76. *
  77. * @name Paste.getFormat
  78. * @function
  79. * @return {string}
  80. */
  81. this.getFormat = function()
  82. {
  83. return this.v === 1 ? this.meta.formatter : this.adata[1];
  84. }
  85. /**
  86. * gets the remaining seconds before the paste expires
  87. *
  88. * returns 0 if there is no expiration
  89. *
  90. * @name Paste.getTimeToLive
  91. * @function
  92. * @return {string}
  93. */
  94. this.getTimeToLive = function()
  95. {
  96. return (this.v === 1 ? this.meta.remaining_time : this.meta.time_to_live) || 0;
  97. }
  98. /**
  99. * is burn-after-reading enabled
  100. *
  101. * @name Paste.isBurnAfterReadingEnabled
  102. * @function
  103. * @return {bool}
  104. */
  105. this.isBurnAfterReadingEnabled = function()
  106. {
  107. return (this.v === 1 ? this.meta.burnafterreading : this.adata[3]);
  108. }
  109. /**
  110. * are discussions enabled
  111. *
  112. * @name Paste.isDiscussionEnabled
  113. * @function
  114. * @return {bool}
  115. */
  116. this.isDiscussionEnabled = function()
  117. {
  118. return (this.v === 1 ? this.meta.opendiscussion : this.adata[2]);
  119. }
  120. }
  121. /**
  122. * Comment class
  123. *
  124. * bundles helper fuctions around the comment formats
  125. *
  126. * @name Comment
  127. * @class
  128. */
  129. function Comment(data) {
  130. // inherit constructor and methods of CryptoData
  131. CryptoData.call(this, data);
  132. /**
  133. * gets the UNIX timestamp of the comment creation
  134. *
  135. * @name Paste.getCreated
  136. * @function
  137. * @return {int}
  138. */
  139. this.getCreated = function()
  140. {
  141. return this.meta[this.v === 1 ? 'postdate' : 'created'];
  142. }
  143. /**
  144. * gets the icon of the comment submitter
  145. *
  146. * @name Paste.getIcon
  147. * @function
  148. * @return {string}
  149. */
  150. this.getIcon = function()
  151. {
  152. return this.meta[this.v === 1 ? 'vizhash' : 'icon'] || '';
  153. }
  154. }
  155. /**
  156. * static Helper methods
  157. *
  158. * @name Helper
  159. * @class
  160. */
  161. const Helper = (function () {
  162. const me = {};
  163. /**
  164. * blacklist of UserAgents (parts) known to belong to a bot
  165. *
  166. * @private
  167. * @enum {Object}
  168. * @readonly
  169. */
  170. const BadBotUA = [
  171. 'Bot',
  172. 'bot'
  173. ];
  174. /**
  175. * cache for script location
  176. *
  177. * @name Helper.baseUri
  178. * @private
  179. * @enum {string|null}
  180. */
  181. let baseUri = null;
  182. /**
  183. * converts a duration (in seconds) into human friendly approximation
  184. *
  185. * @name Helper.secondsToHuman
  186. * @function
  187. * @param {number} seconds
  188. * @return {Array}
  189. */
  190. me.secondsToHuman = function(seconds)
  191. {
  192. let v;
  193. if (seconds < 60)
  194. {
  195. v = Math.floor(seconds);
  196. return [v, 'second'];
  197. }
  198. if (seconds < 60 * 60)
  199. {
  200. v = Math.floor(seconds / 60);
  201. return [v, 'minute'];
  202. }
  203. if (seconds < 60 * 60 * 24)
  204. {
  205. v = Math.floor(seconds / (60 * 60));
  206. return [v, 'hour'];
  207. }
  208. // If less than 2 months, display in days:
  209. if (seconds < 60 * 60 * 24 * 60)
  210. {
  211. v = Math.floor(seconds / (60 * 60 * 24));
  212. return [v, 'day'];
  213. }
  214. v = Math.floor(seconds / (60 * 60 * 24 * 30));
  215. return [v, 'month'];
  216. };
  217. /**
  218. * text range selection
  219. *
  220. * @see {@link https://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse}
  221. * @name Helper.selectText
  222. * @function
  223. * @param {HTMLElement} element
  224. */
  225. me.selectText = function(element)
  226. {
  227. let range, selection;
  228. // MS
  229. if (document.body.createTextRange) {
  230. range = document.body.createTextRange();
  231. range.moveToElementText(element);
  232. range.select();
  233. } else if (window.getSelection) {
  234. selection = window.getSelection();
  235. range = document.createRange();
  236. range.selectNodeContents(element);
  237. selection.removeAllRanges();
  238. selection.addRange(range);
  239. }
  240. };
  241. /**
  242. * convert URLs to clickable links.
  243. *
  244. * URLs to handle:
  245. * <pre>
  246. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  247. * https://example.com:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  248. * http://user:example.com@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  249. * </pre>
  250. *
  251. * @name Helper.urls2links
  252. * @function
  253. * @param {string} html
  254. * @return {string}
  255. */
  256. me.urls2links = function(html)
  257. {
  258. return html.replace(
  259. /(((https?|ftp):\/\/[\w?!=&.\/-;#@~%+*-]+(?![\w\s?!&.\/;#~%"=-]*>))|((magnet):[\w?=&.\/-;#@~%+*-]+))/ig,
  260. '<a href="$1" rel="nofollow">$1</a>'
  261. );
  262. };
  263. /**
  264. * minimal sprintf emulation for %s and %d formats
  265. *
  266. * Note that this function needs the parameters in the same order as the
  267. * format strings appear in the string, contrary to the original.
  268. *
  269. * @see {@link https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914}
  270. * @name Helper.sprintf
  271. * @function
  272. * @param {string} format
  273. * @param {...*} args - one or multiple parameters injected into format string
  274. * @return {string}
  275. */
  276. me.sprintf = function()
  277. {
  278. const args = Array.prototype.slice.call(arguments);
  279. let format = args[0],
  280. i = 1;
  281. return format.replace(/%(s|d)/g, function (m) {
  282. // m is the matched format, e.g. %s, %d
  283. let val = args[i];
  284. // A switch statement so that the formatter can be extended.
  285. switch (m)
  286. {
  287. case '%d':
  288. val = parseFloat(val);
  289. if (isNaN(val)) {
  290. val = 0;
  291. }
  292. break;
  293. default:
  294. // Default is %s
  295. }
  296. ++i;
  297. return val;
  298. });
  299. };
  300. /**
  301. * get value of cookie, if it was set, empty string otherwise
  302. *
  303. * @see {@link http://www.w3schools.com/js/js_cookies.asp}
  304. * @name Helper.getCookie
  305. * @function
  306. * @param {string} cname - may not be empty
  307. * @return {string}
  308. */
  309. me.getCookie = function(cname) {
  310. const name = cname + '=',
  311. ca = document.cookie.split(';');
  312. for (let i = 0; i < ca.length; ++i) {
  313. let c = ca[i];
  314. while (c.charAt(0) === ' ')
  315. {
  316. c = c.substring(1);
  317. }
  318. if (c.indexOf(name) === 0)
  319. {
  320. return c.substring(name.length, c.length);
  321. }
  322. }
  323. return '';
  324. };
  325. /**
  326. * get the current location (without search or hash part of the URL),
  327. * eg. https://example.com/path/?aaaa#bbbb --> https://example.com/path/
  328. *
  329. * @name Helper.baseUri
  330. * @function
  331. * @return {string}
  332. */
  333. me.baseUri = function()
  334. {
  335. // check for cached version
  336. if (baseUri !== null) {
  337. return baseUri;
  338. }
  339. baseUri = window.location.origin + window.location.pathname;
  340. return baseUri;
  341. };
  342. /**
  343. * checks whether this is a bot we dislike
  344. *
  345. * @name Helper.isBadBot
  346. * @function
  347. * @return {bool}
  348. */
  349. me.isBadBot = function() {
  350. // check whether a bot user agent part can be found in the current
  351. // user agent
  352. for (let i = 0; i < BadBotUA.length; ++i) {
  353. if (navigator.userAgent.indexOf(BadBotUA) >= 0) {
  354. return true;
  355. }
  356. }
  357. return false;
  358. }
  359. /**
  360. * wrap an object into a Paste, used for mocking in the unit tests
  361. *
  362. * @name Helper.PasteFactory
  363. * @function
  364. * @param {object} data
  365. * @return {Paste}
  366. */
  367. me.PasteFactory = function(data)
  368. {
  369. return new Paste(data);
  370. };
  371. /**
  372. * wrap an object into a Comment, used for mocking in the unit tests
  373. *
  374. * @name Helper.CommentFactory
  375. * @function
  376. * @param {object} data
  377. * @return {Comment}
  378. */
  379. me.CommentFactory = function(data)
  380. {
  381. return new Comment(data);
  382. };
  383. /**
  384. * resets state, used for unit testing
  385. *
  386. * @name Helper.reset
  387. * @function
  388. */
  389. me.reset = function()
  390. {
  391. baseUri = null;
  392. };
  393. return me;
  394. })();
  395. /**
  396. * internationalization module
  397. *
  398. * @name I18n
  399. * @class
  400. */
  401. const I18n = (function () {
  402. const me = {};
  403. /**
  404. * const for string of loaded language
  405. *
  406. * @name I18n.languageLoadedEvent
  407. * @private
  408. * @prop {string}
  409. * @readonly
  410. */
  411. const languageLoadedEvent = 'languageLoaded';
  412. /**
  413. * supported languages, minus the built in 'en'
  414. *
  415. * @name I18n.supportedLanguages
  416. * @private
  417. * @prop {string[]}
  418. * @readonly
  419. */
  420. const supportedLanguages = ['de', 'es', 'fr', 'it', 'hu', 'no', 'nl', 'pl', 'pt', 'oc', 'ru', 'sl', 'zh'];
  421. /**
  422. * built in language
  423. *
  424. * @name I18n.language
  425. * @private
  426. * @prop {string|null}
  427. */
  428. let language = null;
  429. /**
  430. * translation cache
  431. *
  432. * @name I18n.translations
  433. * @private
  434. * @enum {Object}
  435. */
  436. let translations = {};
  437. /**
  438. * translate a string, alias for I18n.translate
  439. *
  440. * @name I18n._
  441. * @function
  442. * @param {jQuery} $element - optional
  443. * @param {string} messageId
  444. * @param {...*} args - one or multiple parameters injected into placeholders
  445. * @return {string}
  446. */
  447. me._ = function()
  448. {
  449. return me.translate.apply(this, arguments);
  450. };
  451. /**
  452. * translate a string
  453. *
  454. * Optionally pass a jQuery element as the first parameter, to automatically
  455. * let the text of this element be replaced. In case the (asynchronously
  456. * loaded) language is not downloadet yet, this will make sure the string
  457. * is replaced when it is actually loaded.
  458. * So for easy translations passing the jQuery object to apply it to is
  459. * more save, especially when they are loaded in the beginning.
  460. *
  461. * @name I18n.translate
  462. * @function
  463. * @param {jQuery} $element - optional
  464. * @param {string} messageId
  465. * @param {...*} args - one or multiple parameters injected into placeholders
  466. * @return {string}
  467. */
  468. me.translate = function()
  469. {
  470. // convert parameters to array
  471. let args = Array.prototype.slice.call(arguments),
  472. messageId,
  473. $element = null;
  474. // parse arguments
  475. if (args[0] instanceof jQuery) {
  476. // optional jQuery element as first parameter
  477. $element = args[0];
  478. args.shift();
  479. }
  480. // extract messageId from arguments
  481. let usesPlurals = $.isArray(args[0]);
  482. if (usesPlurals) {
  483. // use the first plural form as messageId, otherwise the singular
  484. messageId = args[0].length > 1 ? args[0][1] : args[0][0];
  485. } else {
  486. messageId = args[0];
  487. }
  488. if (messageId.length === 0) {
  489. return messageId;
  490. }
  491. // if no translation string cannot be found (in translations object)
  492. if (!translations.hasOwnProperty(messageId) || language === null) {
  493. // if language is still loading and we have an elemt assigned
  494. if (language === null && $element !== null) {
  495. // handle the error by attaching the language loaded event
  496. let orgArguments = arguments;
  497. $(document).on(languageLoadedEvent, function () {
  498. // log to show that the previous error could be mitigated
  499. console.warn('Fix missing translation of \'' + messageId + '\' with now loaded language ' + language);
  500. // re-execute this function
  501. me.translate.apply(this, orgArguments);
  502. });
  503. // and fall back to English for now until the real language
  504. // file is loaded
  505. }
  506. // for all other languages than English for which this behaviour
  507. // is expected as it is built-in, log error
  508. if (language !== null && language !== 'en') {
  509. console.error('Missing translation for: \'' + messageId + '\' in language ' + language);
  510. // fallback to English
  511. }
  512. // save English translation (should be the same on both sides)
  513. translations[messageId] = args[0];
  514. }
  515. // lookup plural translation
  516. if (usesPlurals && $.isArray(translations[messageId])) {
  517. let n = parseInt(args[1] || 1, 10),
  518. key = me.getPluralForm(n),
  519. maxKey = translations[messageId].length - 1;
  520. if (key > maxKey) {
  521. key = maxKey;
  522. }
  523. args[0] = translations[messageId][key];
  524. args[1] = n;
  525. } else {
  526. // lookup singular translation
  527. args[0] = translations[messageId];
  528. }
  529. // format string
  530. let output = Helper.sprintf.apply(this, args);
  531. // if $element is given, apply text to element
  532. if ($element !== null) {
  533. // get last text node of element
  534. let content = $element.contents();
  535. if (content.length > 1) {
  536. content[content.length - 1].nodeValue = ' ' + output;
  537. } else {
  538. $element.text(output);
  539. }
  540. }
  541. return output;
  542. };
  543. /**
  544. * per language functions to use to determine the plural form
  545. *
  546. * @see {@link http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html}
  547. * @name I18n.getPluralForm
  548. * @function
  549. * @param {int} n
  550. * @return {int} array key
  551. */
  552. me.getPluralForm = function(n) {
  553. switch (language)
  554. {
  555. case 'fr':
  556. case 'oc':
  557. case 'zh':
  558. return n > 1 ? 1 : 0;
  559. case 'pl':
  560. return n === 1 ? 0 : (n % 10 >= 2 && n %10 <=4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  561. case 'ru':
  562. return n % 10 === 1 && n % 100 !== 11 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  563. case 'sl':
  564. return n % 100 === 1 ? 1 : (n % 100 === 2 ? 2 : (n % 100 === 3 || n % 100 === 4 ? 3 : 0));
  565. // de, en, es, hu, it, nl, no, pt
  566. default:
  567. return n !== 1 ? 1 : 0;
  568. }
  569. };
  570. /**
  571. * load translations into cache
  572. *
  573. * @name I18n.loadTranslations
  574. * @function
  575. */
  576. me.loadTranslations = function()
  577. {
  578. let newLanguage = Helper.getCookie('lang');
  579. // auto-select language based on browser settings
  580. if (newLanguage.length === 0) {
  581. newLanguage = (navigator.language || navigator.userLanguage || 'en').substring(0, 2);
  582. }
  583. // if language is already used skip update
  584. if (newLanguage === language) {
  585. return;
  586. }
  587. // if language is built-in (English) skip update
  588. if (newLanguage === 'en') {
  589. language = 'en';
  590. return;
  591. }
  592. // if language is not supported, show error
  593. if (supportedLanguages.indexOf(newLanguage) === -1) {
  594. console.error('Language \'%s\' is not supported. Translation failed, fallback to English.', newLanguage);
  595. language = 'en';
  596. return;
  597. }
  598. // load strings from JSON
  599. $.getJSON('i18n/' + newLanguage + '.json', function(data) {
  600. language = newLanguage;
  601. translations = data;
  602. $(document).triggerHandler(languageLoadedEvent);
  603. }).fail(function (data, textStatus, errorMsg) {
  604. console.error('Language \'%s\' could not be loaded (%s: %s). Translation failed, fallback to English.', newLanguage, textStatus, errorMsg);
  605. language = 'en';
  606. });
  607. };
  608. /**
  609. * resets state, used for unit testing
  610. *
  611. * @name I18n.reset
  612. * @function
  613. */
  614. me.reset = function(mockLanguage, mockTranslations)
  615. {
  616. language = mockLanguage || null;
  617. translations = mockTranslations || {};
  618. };
  619. return me;
  620. })();
  621. /**
  622. * handles everything related to en/decryption
  623. *
  624. * @name CryptTool
  625. * @class
  626. */
  627. const CryptTool = (function () {
  628. const me = {};
  629. /**
  630. * base58 encoder & decoder
  631. *
  632. * @private
  633. */
  634. let base58 = new baseX('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
  635. /**
  636. * convert UTF-8 string stored in a DOMString to a standard UTF-16 DOMString
  637. *
  638. * Iterates over the bytes of the message, converting them all hexadecimal
  639. * percent encoded representations, then URI decodes them all
  640. *
  641. * @name CryptTool.utf8To16
  642. * @function
  643. * @private
  644. * @param {string} message UTF-8 string
  645. * @return {string} UTF-16 string
  646. */
  647. function utf8To16(message)
  648. {
  649. return decodeURIComponent(
  650. message.split('').map(
  651. function(character)
  652. {
  653. return '%' + ('00' + character.charCodeAt(0).toString(16)).slice(-2);
  654. }
  655. ).join('')
  656. );
  657. }
  658. /**
  659. * convert DOMString (UTF-16) to a UTF-8 string stored in a DOMString
  660. *
  661. * URI encodes the message, then finds the percent encoded characters
  662. * and transforms these hexadecimal representation back into bytes
  663. *
  664. * @name CryptTool.utf16To8
  665. * @function
  666. * @private
  667. * @param {string} message UTF-16 string
  668. * @return {string} UTF-8 string
  669. */
  670. function utf16To8(message)
  671. {
  672. return encodeURIComponent(message).replace(
  673. /%([0-9A-F]{2})/g,
  674. function (match, hexCharacter)
  675. {
  676. return String.fromCharCode('0x' + hexCharacter);
  677. }
  678. );
  679. }
  680. /**
  681. * convert ArrayBuffer into a UTF-8 string
  682. *
  683. * Iterates over the bytes of the array, catenating them into a string
  684. *
  685. * @name CryptTool.arraybufferToString
  686. * @function
  687. * @private
  688. * @param {ArrayBuffer} messageArray
  689. * @return {string} message
  690. */
  691. function arraybufferToString(messageArray)
  692. {
  693. const array = new Uint8Array(messageArray);
  694. let message = '',
  695. i = 0;
  696. while(i < array.length) {
  697. message += String.fromCharCode(array[i++]);
  698. }
  699. return message;
  700. }
  701. /**
  702. * convert UTF-8 string into a Uint8Array
  703. *
  704. * Iterates over the bytes of the message, writing them to the array
  705. *
  706. * @name CryptTool.stringToArraybuffer
  707. * @function
  708. * @private
  709. * @param {string} message UTF-8 string
  710. * @return {Uint8Array} array
  711. */
  712. function stringToArraybuffer(message)
  713. {
  714. const messageArray = new Uint8Array(message.length);
  715. for (let i = 0; i < message.length; ++i) {
  716. messageArray[i] = message.charCodeAt(i);
  717. }
  718. return messageArray;
  719. }
  720. /**
  721. * compress a string (deflate compression), returns buffer
  722. *
  723. * @name CryptTool.compress
  724. * @async
  725. * @function
  726. * @private
  727. * @param {string} message
  728. * @param {string} mode
  729. * @return {ArrayBuffer} data
  730. */
  731. async function compress(message, mode)
  732. {
  733. message = stringToArraybuffer(
  734. utf16To8(message)
  735. );
  736. if (mode === 'zlib') {
  737. return z.deflate(message).buffer;
  738. }
  739. return message;
  740. }
  741. /**
  742. * decompress potentially base64 encoded, deflate compressed buffer, returns string
  743. *
  744. * @name CryptTool.decompress
  745. * @async
  746. * @function
  747. * @private
  748. * @param {ArrayBuffer} data
  749. * @param {string} mode
  750. * @return {string} message
  751. */
  752. async function decompress(data, mode)
  753. {
  754. if (mode === 'zlib' || mode === 'none') {
  755. if (mode === 'zlib') {
  756. data = z.inflate(
  757. new Uint8Array(data)
  758. ).buffer;
  759. }
  760. return utf8To16(
  761. arraybufferToString(data)
  762. );
  763. }
  764. // detect presence of Base64.js, indicating legacy ZeroBin paste
  765. if (typeof Base64 === 'undefined') {
  766. return utf8To16(
  767. RawDeflate.inflate(
  768. utf8To16(
  769. atob(
  770. arraybufferToString(data)
  771. )
  772. )
  773. )
  774. );
  775. } else {
  776. return Base64.btou(
  777. RawDeflate.inflate(
  778. Base64.fromBase64(
  779. arraybufferToString(data)
  780. )
  781. )
  782. );
  783. }
  784. }
  785. /**
  786. * returns specified number of random bytes
  787. *
  788. * @name CryptTool.getRandomBytes
  789. * @function
  790. * @private
  791. * @param {int} length number of random bytes to fetch
  792. * @throws {string}
  793. * @return {string} random bytes
  794. */
  795. function getRandomBytes(length)
  796. {
  797. if (
  798. typeof window !== 'undefined' &&
  799. typeof Uint8Array !== 'undefined' &&
  800. String.fromCodePoint &&
  801. (
  802. typeof window.crypto !== 'undefined' ||
  803. typeof window.msCrypto !== 'undefined'
  804. )
  805. ) {
  806. // modern browser environment
  807. let bytes = '';
  808. const byteArray = new Uint8Array(length),
  809. crypto = window.crypto || window.msCrypto;
  810. crypto.getRandomValues(byteArray);
  811. for (let i = 0; i < length; ++i) {
  812. bytes += String.fromCharCode(byteArray[i]);
  813. }
  814. return bytes;
  815. } else {
  816. // legacy browser or unsupported environment
  817. throw 'No supported crypto API detected, you may read pastes and comments, but can\'t create pastes or add new comments.';
  818. }
  819. }
  820. /**
  821. * derive cryptographic key from key string and password
  822. *
  823. * @name CryptTool.deriveKey
  824. * @async
  825. * @function
  826. * @private
  827. * @param {string} key
  828. * @param {string} password
  829. * @param {array} spec cryptographic specification
  830. * @return {CryptoKey} derived key
  831. */
  832. async function deriveKey(key, password, spec)
  833. {
  834. let keyArray = stringToArraybuffer(key);
  835. if (password.length > 0) {
  836. // version 1 pastes did append the passwords SHA-256 hash in hex
  837. if (spec[7] === 'rawdeflate') {
  838. let passwordBuffer = await window.crypto.subtle.digest(
  839. {name: 'SHA-256'},
  840. stringToArraybuffer(
  841. utf16To8(password)
  842. )
  843. );
  844. password = Array.prototype.map.call(
  845. new Uint8Array(passwordBuffer),
  846. x => ('00' + x.toString(16)).slice(-2)
  847. ).join('');
  848. }
  849. let passwordArray = stringToArraybuffer(password),
  850. newKeyArray = new Uint8Array(keyArray.length + passwordArray.length);
  851. newKeyArray.set(keyArray, 0);
  852. newKeyArray.set(passwordArray, keyArray.length);
  853. keyArray = newKeyArray;
  854. }
  855. // import raw key
  856. const importedKey = await window.crypto.subtle.importKey(
  857. 'raw', // only 'raw' is allowed
  858. keyArray,
  859. {name: 'PBKDF2'}, // we use PBKDF2 for key derivation
  860. false, // the key may not be exported
  861. ['deriveKey'] // we may only use it for key derivation
  862. );
  863. // derive a stronger key for use with AES
  864. return window.crypto.subtle.deriveKey(
  865. {
  866. name: 'PBKDF2', // we use PBKDF2 for key derivation
  867. salt: stringToArraybuffer(spec[1]), // salt used in HMAC
  868. iterations: spec[2], // amount of iterations to apply
  869. hash: {name: 'SHA-256'} // can be "SHA-1", "SHA-256", "SHA-384" or "SHA-512"
  870. },
  871. importedKey,
  872. {
  873. name: 'AES-' + spec[6].toUpperCase(), // can be any supported AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH" or "HMAC")
  874. length: spec[3] // can be 128, 192 or 256
  875. },
  876. false, // the key may not be exported
  877. ['encrypt', 'decrypt'] // we may only use it for en- and decryption
  878. );
  879. }
  880. /**
  881. * gets crypto settings from specification and authenticated data
  882. *
  883. * @name CryptTool.cryptoSettings
  884. * @function
  885. * @private
  886. * @param {string} adata authenticated data
  887. * @param {array} spec cryptographic specification
  888. * @return {object} crypto settings
  889. */
  890. function cryptoSettings(adata, spec)
  891. {
  892. return {
  893. name: 'AES-' + spec[6].toUpperCase(), // can be any supported AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH" or "HMAC")
  894. iv: stringToArraybuffer(spec[0]), // the initialization vector you used to encrypt
  895. additionalData: stringToArraybuffer(adata), // the addtional data you used during encryption (if any)
  896. tagLength: spec[4] // the length of the tag you used to encrypt (if any)
  897. };
  898. }
  899. /**
  900. * compress, then encrypt message with given key and password
  901. *
  902. * @name CryptTool.cipher
  903. * @async
  904. * @function
  905. * @param {string} key
  906. * @param {string} password
  907. * @param {string} message
  908. * @param {array} adata
  909. * @return {array} encrypted message in base64 encoding & adata containing encryption spec
  910. */
  911. me.cipher = async function(key, password, message, adata)
  912. {
  913. // AES in Galois Counter Mode, keysize 256 bit,
  914. // authentication tag 128 bit, 10000 iterations in key derivation
  915. const spec = [
  916. getRandomBytes(16), // initialization vector
  917. getRandomBytes(8), // salt
  918. 100000, // iterations
  919. 256, // key size
  920. 128, // tag size
  921. 'aes', // algorithm
  922. 'gcm', // algorithm mode
  923. 'zlib' // compression
  924. ], encodedSpec = [];
  925. for (let i = 0; i < spec.length; ++i) {
  926. encodedSpec[i] = i < 2 ? btoa(spec[i]) : spec[i];
  927. }
  928. if (adata.length === 0) {
  929. // comment
  930. adata = encodedSpec;
  931. } else if (adata[0] === null) {
  932. // paste
  933. adata[0] = encodedSpec;
  934. }
  935. // finally, encrypt message
  936. return [
  937. btoa(
  938. arraybufferToString(
  939. await window.crypto.subtle.encrypt(
  940. cryptoSettings(JSON.stringify(adata), spec),
  941. await deriveKey(key, password, spec),
  942. await compress(message, spec[7])
  943. )
  944. )
  945. ),
  946. adata
  947. ];
  948. };
  949. /**
  950. * decrypt message with key, then decompress
  951. *
  952. * @name CryptTool.decipher
  953. * @async
  954. * @function
  955. * @param {string} key
  956. * @param {string} password
  957. * @param {string|object} data encrypted message
  958. * @return {string} decrypted message, empty if decryption failed
  959. */
  960. me.decipher = async function(key, password, data)
  961. {
  962. let adataString, spec, cipherMessage;
  963. if (data instanceof Array) {
  964. // version 2
  965. adataString = JSON.stringify(data[1]);
  966. // clone the array instead of passing the reference
  967. spec = (data[1][0] instanceof Array ? data[1][0] : data[1]).slice();
  968. cipherMessage = data[0];
  969. } else if (typeof data === 'string') {
  970. // version 1
  971. let object = JSON.parse(data);
  972. adataString = atob(object.adata);
  973. spec = [
  974. object.iv,
  975. object.salt,
  976. object.iter,
  977. object.ks,
  978. object.ts,
  979. object.cipher,
  980. object.mode,
  981. 'rawdeflate'
  982. ];
  983. cipherMessage = object.ct;
  984. } else {
  985. throw 'unsupported message format';
  986. }
  987. spec[0] = atob(spec[0]);
  988. spec[1] = atob(spec[1]);
  989. try {
  990. return await decompress(
  991. await window.crypto.subtle.decrypt(
  992. cryptoSettings(adataString, spec),
  993. await deriveKey(key, password, spec),
  994. stringToArraybuffer(
  995. atob(cipherMessage)
  996. )
  997. ),
  998. spec[7]
  999. );
  1000. } catch(err) {
  1001. return '';
  1002. }
  1003. };
  1004. /**
  1005. * returns a random symmetric key
  1006. *
  1007. * generates 256 bit long keys (8 Bits * 32) for AES with 256 bit long blocks
  1008. *
  1009. * @name CryptTool.getSymmetricKey
  1010. * @function
  1011. * @throws {string}
  1012. * @return {string} raw bytes
  1013. */
  1014. me.getSymmetricKey = function()
  1015. {
  1016. return getRandomBytes(32);
  1017. };
  1018. /**
  1019. * base58 encode a DOMString (UTF-16)
  1020. *
  1021. * @name CryptTool.base58encode
  1022. * @function
  1023. * @param {string} input
  1024. * @return {string} output
  1025. */
  1026. me.base58encode = function(input)
  1027. {
  1028. return base58.encode(
  1029. stringToArraybuffer(input)
  1030. );
  1031. }
  1032. /**
  1033. * base58 decode a DOMString (UTF-16)
  1034. *
  1035. * @name CryptTool.base58decode
  1036. * @function
  1037. * @param {string} input
  1038. * @return {string} output
  1039. */
  1040. me.base58decode = function(input)
  1041. {
  1042. return arraybufferToString(
  1043. base58.decode(input)
  1044. );
  1045. }
  1046. return me;
  1047. })();
  1048. /**
  1049. * (Model) Data source (aka MVC)
  1050. *
  1051. * @name Model
  1052. * @class
  1053. */
  1054. const Model = (function () {
  1055. const me = {};
  1056. let id = null,
  1057. pasteData = null,
  1058. symmetricKey = null,
  1059. $templates;
  1060. /**
  1061. * returns the expiration set in the HTML
  1062. *
  1063. * @name Model.getExpirationDefault
  1064. * @function
  1065. * @return string
  1066. */
  1067. me.getExpirationDefault = function()
  1068. {
  1069. return $('#pasteExpiration').val();
  1070. };
  1071. /**
  1072. * returns the format set in the HTML
  1073. *
  1074. * @name Model.getFormatDefault
  1075. * @function
  1076. * @return string
  1077. */
  1078. me.getFormatDefault = function()
  1079. {
  1080. return $('#pasteFormatter').val();
  1081. };
  1082. /**
  1083. * returns the paste data (including the cipher data)
  1084. *
  1085. * @name Model.getPasteData
  1086. * @function
  1087. * @param {function} callback (optional) Called when data is available
  1088. * @param {function} useCache (optional) Whether to use the cache or
  1089. * force a data reload. Default: true
  1090. * @return string
  1091. */
  1092. me.getPasteData = function(callback, useCache)
  1093. {
  1094. // use cache if possible/allowed
  1095. if (useCache !== false && pasteData !== null) {
  1096. //execute callback
  1097. if (typeof callback === 'function') {
  1098. return callback(pasteData);
  1099. }
  1100. // alternatively just using inline
  1101. return pasteData;
  1102. }
  1103. // reload data
  1104. ServerInteraction.prepare();
  1105. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + me.getPasteId());
  1106. ServerInteraction.setFailure(function (status, data) {
  1107. // revert loading status…
  1108. Alert.hideLoading();
  1109. TopNav.showViewButtons();
  1110. // show error message
  1111. Alert.showError(ServerInteraction.parseUploadError(status, data, 'get paste data'));
  1112. });
  1113. ServerInteraction.setSuccess(function (status, data) {
  1114. pasteData = new Paste(data);
  1115. if (typeof callback === 'function') {
  1116. return callback(pasteData);
  1117. }
  1118. });
  1119. ServerInteraction.run();
  1120. };
  1121. /**
  1122. * get the pastes unique identifier from the URL,
  1123. * eg. https://example.com/path/?c05354954c49a487#dfdsdgdgdfgdf returns c05354954c49a487
  1124. *
  1125. * @name Model.getPasteId
  1126. * @function
  1127. * @return {string} unique identifier
  1128. * @throws {string}
  1129. */
  1130. me.getPasteId = function()
  1131. {
  1132. const idRegEx = /^[a-z0-9]{16}$/;
  1133. const idRegExFind = /[a-z0-9]{16}/;
  1134. // return cached value
  1135. if (id !== null) {
  1136. return id;
  1137. }
  1138. // do use URL interface, if possible
  1139. if (window.URL && window.URL.prototype && ('searchParams' in window.URL.prototype)) {
  1140. try {
  1141. const url = new URL(window.location);
  1142. for (const param of url.searchParams) {
  1143. const key = param[0];
  1144. const value = param[1];
  1145. if (value === '' && idRegEx.test(key)) {
  1146. // safe, as the whole regex is matched
  1147. id = key;
  1148. return id;
  1149. }
  1150. }
  1151. } catch (e) {
  1152. // fallback below
  1153. console.error('URL interface not properly supported, error:', e);
  1154. }
  1155. }
  1156. // Attention: This also returns the delete token inside of the ID, if it is specified
  1157. id = (window.location.search.match(idRegExFind) || [''])[0];
  1158. if (id === '') {
  1159. throw 'no paste id given';
  1160. }
  1161. return id;
  1162. }
  1163. /**
  1164. * returns true, when the URL has a delete token and the current call was used for deleting a paste.
  1165. *
  1166. * @name Model.hasDeleteToken
  1167. * @function
  1168. * @return {bool}
  1169. */
  1170. me.hasDeleteToken = function()
  1171. {
  1172. return window.location.search.indexOf('deletetoken') !== -1;
  1173. }
  1174. /**
  1175. * return the deciphering key stored in anchor part of the URL
  1176. *
  1177. * @name Model.getPasteKey
  1178. * @function
  1179. * @return {string|null} key
  1180. * @throws {string}
  1181. */
  1182. me.getPasteKey = function()
  1183. {
  1184. if (symmetricKey === null) {
  1185. let newKey = window.location.hash.substring(1);
  1186. if (newKey === '') {
  1187. throw 'no encryption key given';
  1188. }
  1189. // Some web 2.0 services and redirectors add data AFTER the anchor
  1190. // (such as &utm_source=...). We will strip any additional data.
  1191. let ampersandPos = newKey.indexOf('&');
  1192. if (ampersandPos > -1)
  1193. {
  1194. newKey = newKey.substring(0, ampersandPos);
  1195. }
  1196. // version 2 uses base58, version 1 uses base64 without decoding
  1197. try {
  1198. // base58 encode strips NULL bytes at the beginning of the
  1199. // string, so we re-add them if necessary
  1200. symmetricKey = CryptTool.base58decode(newKey).padStart(32, '\u0000');
  1201. } catch(e) {
  1202. symmetricKey = newKey;
  1203. }
  1204. }
  1205. return symmetricKey;
  1206. };
  1207. /**
  1208. * returns a jQuery copy of the HTML template
  1209. *
  1210. * @name Model.getTemplate
  1211. * @function
  1212. * @param {string} name - the name of the template
  1213. * @return {jQuery}
  1214. */
  1215. me.getTemplate = function(name)
  1216. {
  1217. // find template
  1218. let $element = $templates.find('#' + name + 'template').clone(true);
  1219. // change ID to avoid collisions (one ID should really be unique)
  1220. return $element.prop('id', name);
  1221. };
  1222. /**
  1223. * resets state, used for unit testing
  1224. *
  1225. * @name Model.reset
  1226. * @function
  1227. */
  1228. me.reset = function()
  1229. {
  1230. pasteData = $templates = id = symmetricKey = null;
  1231. };
  1232. /**
  1233. * init navigation manager
  1234. *
  1235. * preloads jQuery elements
  1236. *
  1237. * @name Model.init
  1238. * @function
  1239. */
  1240. me.init = function()
  1241. {
  1242. $templates = $('#templates');
  1243. };
  1244. return me;
  1245. })();
  1246. /**
  1247. * Helper functions for user interface
  1248. *
  1249. * everything directly UI-related, which fits nowhere else
  1250. *
  1251. * @name UiHelper
  1252. * @class
  1253. */
  1254. const UiHelper = (function () {
  1255. const me = {};
  1256. /**
  1257. * handle history (pop) state changes
  1258. *
  1259. * currently this does only handle redirects to the home page.
  1260. *
  1261. * @name UiHelper.historyChange
  1262. * @private
  1263. * @function
  1264. * @param {Event} event
  1265. */
  1266. function historyChange(event)
  1267. {
  1268. let currentLocation = Helper.baseUri();
  1269. if (event.originalEvent.state === null && // no state object passed
  1270. event.target.location.href === currentLocation && // target location is home page
  1271. window.location.href === currentLocation // and we are not already on the home page
  1272. ) {
  1273. // redirect to home page
  1274. window.location.href = currentLocation;
  1275. }
  1276. }
  1277. /**
  1278. * reload the page
  1279. *
  1280. * This takes the user to the PrivateBin homepage.
  1281. *
  1282. * @name UiHelper.reloadHome
  1283. * @function
  1284. */
  1285. me.reloadHome = function()
  1286. {
  1287. window.location.href = Helper.baseUri();
  1288. };
  1289. /**
  1290. * checks whether the element is currently visible in the viewport (so
  1291. * the user can actually see it)
  1292. *
  1293. * @see {@link https://stackoverflow.com/a/40658647}
  1294. * @name UiHelper.isVisible
  1295. * @function
  1296. * @param {jQuery} $element The link hash to move to.
  1297. */
  1298. me.isVisible = function($element)
  1299. {
  1300. let elementTop = $element.offset().top,
  1301. viewportTop = $(window).scrollTop(),
  1302. viewportBottom = viewportTop + $(window).height();
  1303. return elementTop > viewportTop && elementTop < viewportBottom;
  1304. };
  1305. /**
  1306. * scrolls to a specific element
  1307. *
  1308. * @see {@link https://stackoverflow.com/questions/4198041/jquery-smooth-scroll-to-an-anchor#answer-12714767}
  1309. * @name UiHelper.scrollTo
  1310. * @function
  1311. * @param {jQuery} $element The link hash to move to.
  1312. * @param {(number|string)} animationDuration passed to jQuery .animate, when set to 0 the animation is skipped
  1313. * @param {string} animationEffect passed to jQuery .animate
  1314. * @param {function} finishedCallback function to call after animation finished
  1315. */
  1316. me.scrollTo = function($element, animationDuration, animationEffect, finishedCallback)
  1317. {
  1318. let $body = $('html, body'),
  1319. margin = 50,
  1320. callbackCalled = false,
  1321. dest = 0;
  1322. // calculate destination place
  1323. // if it would scroll out of the screen at the bottom only scroll it as
  1324. // far as the screen can go
  1325. if ($element.offset().top > $(document).height() - $(window).height()) {
  1326. dest = $(document).height() - $(window).height();
  1327. } else {
  1328. dest = $element.offset().top - margin;
  1329. }
  1330. // skip animation if duration is set to 0
  1331. if (animationDuration === 0) {
  1332. window.scrollTo(0, dest);
  1333. } else {
  1334. // stop previous animation
  1335. $body.stop();
  1336. // scroll to destination
  1337. $body.animate({
  1338. scrollTop: dest
  1339. }, animationDuration, animationEffect);
  1340. }
  1341. // as we have finished we can enable scrolling again
  1342. $body.queue(function (next) {
  1343. if (!callbackCalled) {
  1344. // call user function if needed
  1345. if (typeof finishedCallback !== 'undefined') {
  1346. finishedCallback();
  1347. }
  1348. // prevent calling this function twice
  1349. callbackCalled = true;
  1350. }
  1351. next();
  1352. });
  1353. };
  1354. /**
  1355. * trigger a history (pop) state change
  1356. *
  1357. * used to test the UiHelper.historyChange private function
  1358. *
  1359. * @name UiHelper.mockHistoryChange
  1360. * @function
  1361. * @param {string} state (optional) state to mock
  1362. */
  1363. me.mockHistoryChange = function(state)
  1364. {
  1365. if (typeof state === 'undefined') {
  1366. state = null;
  1367. }
  1368. historyChange($.Event('popstate', {originalEvent: new PopStateEvent('popstate', {state: state}), target: window}));
  1369. };
  1370. /**
  1371. * initialize
  1372. *
  1373. * @name UiHelper.init
  1374. * @function
  1375. */
  1376. me.init = function()
  1377. {
  1378. // update link to home page
  1379. $('.reloadlink').prop('href', Helper.baseUri());
  1380. $(window).on('popstate', historyChange);
  1381. };
  1382. return me;
  1383. })();
  1384. /**
  1385. * Alert/error manager
  1386. *
  1387. * @name Alert
  1388. * @class
  1389. */
  1390. const Alert = (function () {
  1391. const me = {};
  1392. let $errorMessage,
  1393. $loadingIndicator,
  1394. $statusMessage,
  1395. $remainingTime,
  1396. currentIcon,
  1397. customHandler;
  1398. const alertType = [
  1399. 'loading', // not in bootstrap CSS, but using a plausible value here
  1400. 'info', // status icon
  1401. 'warning', // not used yet
  1402. 'danger' // error icon
  1403. ];
  1404. /**
  1405. * forwards a request to the i18n module and shows the element
  1406. *
  1407. * @name Alert.handleNotification
  1408. * @private
  1409. * @function
  1410. * @param {int} id - id of notification
  1411. * @param {jQuery} $element - jQuery object
  1412. * @param {string|array} args
  1413. * @param {string|null} icon - optional, icon
  1414. */
  1415. function handleNotification(id, $element, args, icon)
  1416. {
  1417. // basic parsing/conversion of parameters
  1418. if (typeof icon === 'undefined') {
  1419. icon = null;
  1420. }
  1421. if (typeof args === 'undefined') {
  1422. args = null;
  1423. } else if (typeof args === 'string') {
  1424. // convert string to array if needed
  1425. args = [args];
  1426. }
  1427. // pass to custom handler if defined
  1428. if (typeof customHandler === 'function') {
  1429. let handlerResult = customHandler(alertType[id], $element, args, icon);
  1430. if (handlerResult === true) {
  1431. // if it returns true, skip own handler
  1432. return;
  1433. }
  1434. if (handlerResult instanceof jQuery) {
  1435. // continue processing with new element
  1436. $element = handlerResult;
  1437. icon = null; // icons not supported in this case
  1438. }
  1439. }
  1440. // handle icon
  1441. if (icon !== null && // icon was passed
  1442. icon !== currentIcon[id] // and it differs from current icon
  1443. ) {
  1444. let $glyphIcon = $element.find(':first');
  1445. // remove (previous) icon
  1446. $glyphIcon.removeClass(currentIcon[id]);
  1447. // any other thing as a string (e.g. 'null') (only) removes the icon
  1448. if (typeof icon === 'string') {
  1449. // set new icon
  1450. currentIcon[id] = 'glyphicon-' + icon;
  1451. $glyphIcon.addClass(currentIcon[id]);
  1452. }
  1453. }
  1454. // show text
  1455. if (args !== null) {
  1456. // add jQuery object to it as first parameter
  1457. args.unshift($element);
  1458. // pass it to I18n
  1459. I18n._.apply(this, args);
  1460. }
  1461. // show notification
  1462. $element.removeClass('hidden');
  1463. }
  1464. /**
  1465. * display a status message
  1466. *
  1467. * This automatically passes the text to I18n for translation.
  1468. *
  1469. * @name Alert.showStatus
  1470. * @function
  1471. * @param {string|array} message string, use an array for %s/%d options
  1472. * @param {string|null} icon optional, the icon to show,
  1473. * default: leave previous icon
  1474. */
  1475. me.showStatus = function(message, icon)
  1476. {
  1477. handleNotification(1, $statusMessage, message, icon);
  1478. };
  1479. /**
  1480. * display an error message
  1481. *
  1482. * This automatically passes the text to I18n for translation.
  1483. *
  1484. * @name Alert.showError
  1485. * @function
  1486. * @param {string|array} message string, use an array for %s/%d options
  1487. * @param {string|null} icon optional, the icon to show, default:
  1488. * leave previous icon
  1489. */
  1490. me.showError = function(message, icon)
  1491. {
  1492. handleNotification(3, $errorMessage, message, icon);
  1493. };
  1494. /**
  1495. * display remaining message
  1496. *
  1497. * This automatically passes the text to I18n for translation.
  1498. *
  1499. * @name Alert.showRemaining
  1500. * @function
  1501. * @param {string|array} message string, use an array for %s/%d options
  1502. */
  1503. me.showRemaining = function(message)
  1504. {
  1505. handleNotification(1, $remainingTime, message);
  1506. };
  1507. /**
  1508. * shows a loading message, optionally with a percentage
  1509. *
  1510. * This automatically passes all texts to the i10s module.
  1511. *
  1512. * @name Alert.showLoading
  1513. * @function
  1514. * @param {string|array|null} message optional, use an array for %s/%d options, default: 'Loading…'
  1515. * @param {string|null} icon optional, the icon to show, default: leave previous icon
  1516. */
  1517. me.showLoading = function(message, icon)
  1518. {
  1519. // default message text
  1520. if (typeof message === 'undefined') {
  1521. message = 'Loading…';
  1522. }
  1523. handleNotification(0, $loadingIndicator, message, icon);
  1524. // show loading status (cursor)
  1525. $('body').addClass('loading');
  1526. };
  1527. /**
  1528. * hides the loading message
  1529. *
  1530. * @name Alert.hideLoading
  1531. * @function
  1532. */
  1533. me.hideLoading = function()
  1534. {
  1535. $loadingIndicator.addClass('hidden');
  1536. // hide loading cursor
  1537. $('body').removeClass('loading');
  1538. };
  1539. /**
  1540. * hides any status/error messages
  1541. *
  1542. * This does not include the loading message.
  1543. *
  1544. * @name Alert.hideMessages
  1545. * @function
  1546. */
  1547. me.hideMessages = function()
  1548. {
  1549. // also possible: $('.statusmessage').addClass('hidden');
  1550. $statusMessage.addClass('hidden');
  1551. $errorMessage.addClass('hidden');
  1552. };
  1553. /**
  1554. * set a custom handler, which gets all notifications.
  1555. *
  1556. * This handler gets the following arguments:
  1557. * alertType (see array), $element, args, icon
  1558. * If it returns true, the own processing will be stopped so the message
  1559. * will not be displayed. Otherwise it will continue.
  1560. * As an aditional feature it can return q jQuery element, which will
  1561. * then be used to add the message there. Icons are not supported in
  1562. * that case and will be ignored.
  1563. * Pass 'null' to reset/delete the custom handler.
  1564. * Note that there is no notification when a message is supposed to get
  1565. * hidden.
  1566. *
  1567. * @name Alert.setCustomHandler
  1568. * @function
  1569. * @param {function|null} newHandler
  1570. */
  1571. me.setCustomHandler = function(newHandler)
  1572. {
  1573. customHandler = newHandler;
  1574. };
  1575. /**
  1576. * init status manager
  1577. *
  1578. * preloads jQuery elements
  1579. *
  1580. * @name Alert.init
  1581. * @function
  1582. */
  1583. me.init = function()
  1584. {
  1585. // hide "no javascript" error message
  1586. $('#noscript').hide();
  1587. // not a reset, but first set of the elements
  1588. $errorMessage = $('#errormessage');
  1589. $loadingIndicator = $('#loadingindicator');
  1590. $statusMessage = $('#status');
  1591. $remainingTime = $('#remainingtime');
  1592. currentIcon = [
  1593. 'glyphicon-time', // loading icon
  1594. 'glyphicon-info-sign', // status icon
  1595. '', // reserved for warning, not used yet
  1596. 'glyphicon-alert' // error icon
  1597. ];
  1598. };
  1599. return me;
  1600. })();
  1601. /**
  1602. * handles paste status/result
  1603. *
  1604. * @name PasteStatus
  1605. * @class
  1606. */
  1607. const PasteStatus = (function () {
  1608. const me = {};
  1609. let $pasteSuccess,
  1610. $pasteUrl,
  1611. $remainingTime,
  1612. $shortenButton;
  1613. /**
  1614. * forward to URL shortener
  1615. *
  1616. * @name PasteStatus.sendToShortener
  1617. * @private
  1618. * @function
  1619. */
  1620. function sendToShortener()
  1621. {
  1622. window.location.href = $shortenButton.data('shortener') +
  1623. encodeURIComponent($pasteUrl.attr('href'));
  1624. }
  1625. /**
  1626. * Forces opening the paste if the link does not do this automatically.
  1627. *
  1628. * This is necessary as browsers will not reload the page when it is
  1629. * already loaded (which is fake as it is set via history.pushState()).
  1630. *
  1631. * @name PasteStatus.pasteLinkClick
  1632. * @function
  1633. */
  1634. function pasteLinkClick()
  1635. {
  1636. // check if location is (already) shown in URL bar
  1637. if (window.location.href === $pasteUrl.attr('href')) {
  1638. // if so we need to load link by reloading the current site
  1639. window.location.reload(true);
  1640. }
  1641. }
  1642. /**
  1643. * creates a notification after a successfull paste upload
  1644. *
  1645. * @name PasteStatus.createPasteNotification
  1646. * @function
  1647. * @param {string} url
  1648. * @param {string} deleteUrl
  1649. */
  1650. me.createPasteNotification = function(url, deleteUrl)
  1651. {
  1652. $('#pastelink').html(
  1653. I18n._(
  1654. 'Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>',
  1655. url, url
  1656. )
  1657. );
  1658. // save newly created element
  1659. $pasteUrl = $('#pasteurl');
  1660. // and add click event
  1661. $pasteUrl.click(pasteLinkClick);
  1662. // shorten button
  1663. $('#deletelink').html('<a href="' + deleteUrl + '">' + I18n._('Delete data') + '</a>');
  1664. // show result
  1665. $pasteSuccess.removeClass('hidden');
  1666. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1667. Helper.selectText($pasteUrl[0]);
  1668. };
  1669. /**
  1670. * shows the remaining time
  1671. *
  1672. * @name PasteStatus.showRemainingTime
  1673. * @function
  1674. * @param {Paste} paste
  1675. */
  1676. me.showRemainingTime = function(paste)
  1677. {
  1678. if (paste.isBurnAfterReadingEnabled()) {
  1679. // display paste "for your eyes only" if it is deleted
  1680. // the paste has been deleted when the JSON with the ciphertext
  1681. // has been downloaded
  1682. Alert.showRemaining('FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.');
  1683. $remainingTime.addClass('foryoureyesonly');
  1684. // discourage cloning (it cannot really be prevented)
  1685. TopNav.hideCloneButton();
  1686. } else if (paste.getTimeToLive() > 0) {
  1687. // display paste expiration
  1688. let expiration = Helper.secondsToHuman(paste.getTimeToLive()),
  1689. expirationLabel = [
  1690. 'This document will expire in %d ' + expiration[1] + '.',
  1691. 'This document will expire in %d ' + expiration[1] + 's.'
  1692. ];
  1693. Alert.showRemaining([expirationLabel, expiration[0]]);
  1694. $remainingTime.removeClass('foryoureyesonly');
  1695. } else {
  1696. // never expires
  1697. return;
  1698. }
  1699. // in the end, display notification
  1700. $remainingTime.removeClass('hidden');
  1701. };
  1702. /**
  1703. * hides the remaining time and successful upload notification
  1704. *
  1705. * @name PasteStatus.hideMessages
  1706. * @function
  1707. */
  1708. me.hideMessages = function()
  1709. {
  1710. $remainingTime.addClass('hidden');
  1711. $pasteSuccess.addClass('hidden');
  1712. };
  1713. /**
  1714. * init status manager
  1715. *
  1716. * preloads jQuery elements
  1717. *
  1718. * @name PasteStatus.init
  1719. * @function
  1720. */
  1721. me.init = function()
  1722. {
  1723. $pasteSuccess = $('#pastesuccess');
  1724. // $pasteUrl is saved in me.createPasteNotification() after creation
  1725. $remainingTime = $('#remainingtime');
  1726. $shortenButton = $('#shortenbutton');
  1727. // bind elements
  1728. $shortenButton.click(sendToShortener);
  1729. };
  1730. return me;
  1731. })();
  1732. /**
  1733. * password prompt
  1734. *
  1735. * @name Prompt
  1736. * @class
  1737. */
  1738. const Prompt = (function () {
  1739. const me = {};
  1740. let $passwordDecrypt,
  1741. $passwordForm,
  1742. $passwordModal,
  1743. password = '';
  1744. /**
  1745. * submit a password in the modal dialog
  1746. *
  1747. * @name Prompt.submitPasswordModal
  1748. * @private
  1749. * @function
  1750. * @param {Event} event
  1751. */
  1752. function submitPasswordModal(event)
  1753. {
  1754. event.preventDefault();
  1755. // get input
  1756. password = $passwordDecrypt.val();
  1757. // hide modal
  1758. $passwordModal.modal('hide');
  1759. PasteDecrypter.run();
  1760. }
  1761. /**
  1762. * ask the user for the password and set it
  1763. *
  1764. * @name Prompt.requestPassword
  1765. * @function
  1766. */
  1767. me.requestPassword = function()
  1768. {
  1769. // show new bootstrap method (if available)
  1770. if ($passwordModal.length !== 0) {
  1771. $passwordModal.modal({
  1772. backdrop: 'static',
  1773. keyboard: false
  1774. });
  1775. return;
  1776. }
  1777. // fallback to old method for page template
  1778. password = prompt(I18n._('Please enter the password for this paste:'), '');
  1779. if (password === null) {
  1780. throw 'password prompt canceled';
  1781. }
  1782. if (password.length === 0) {
  1783. // recurse…
  1784. return me.requestPassword();
  1785. }
  1786. PasteDecrypter.run();
  1787. };
  1788. /**
  1789. * get the cached password
  1790. *
  1791. * If you do not get a password with this function
  1792. * (returns an empty string), use requestPassword.
  1793. *
  1794. * @name Prompt.getPassword
  1795. * @function
  1796. * @return {string}
  1797. */
  1798. me.getPassword = function()
  1799. {
  1800. return password;
  1801. };
  1802. /**
  1803. * resets the password to an empty string
  1804. *
  1805. * @name Prompt.reset
  1806. * @function
  1807. */
  1808. me.reset = function()
  1809. {
  1810. // reset internal
  1811. password = '';
  1812. // and also reset UI
  1813. $passwordDecrypt.val('');
  1814. }
  1815. /**
  1816. * init status manager
  1817. *
  1818. * preloads jQuery elements
  1819. *
  1820. * @name Prompt.init
  1821. * @function
  1822. */
  1823. me.init = function()
  1824. {
  1825. $passwordDecrypt = $('#passworddecrypt');
  1826. $passwordForm = $('#passwordform');
  1827. $passwordModal = $('#passwordmodal');
  1828. // bind events
  1829. // focus password input when it is shown
  1830. $passwordModal.on('shown.bs.Model', function () {
  1831. $passwordDecrypt.focus();
  1832. });
  1833. // handle Model password submission
  1834. $passwordForm.submit(submitPasswordModal);
  1835. };
  1836. return me;
  1837. })();
  1838. /**
  1839. * Manage paste/message input, and preview tab
  1840. *
  1841. * Note that the actual preview is handled by PasteViewer.
  1842. *
  1843. * @name Editor
  1844. * @class
  1845. */
  1846. const Editor = (function () {
  1847. const me = {};
  1848. let $editorTabs,
  1849. $messageEdit,
  1850. $messagePreview,
  1851. $message,
  1852. isPreview = false;
  1853. /**
  1854. * support input of tab character
  1855. *
  1856. * @name Editor.supportTabs
  1857. * @function
  1858. * @param {Event} event
  1859. * @this $message (but not used, so it is jQuery-free, possibly faster)
  1860. */
  1861. function supportTabs(event)
  1862. {
  1863. const keyCode = event.keyCode || event.which;
  1864. // tab was pressed
  1865. if (keyCode === 9) {
  1866. // get caret position & selection
  1867. const val = this.value,
  1868. start = this.selectionStart,
  1869. end = this.selectionEnd;
  1870. // set textarea value to: text before caret + tab + text after caret
  1871. this.value = val.substring(0, start) + '\t' + val.substring(end);
  1872. // put caret at right position again
  1873. this.selectionStart = this.selectionEnd = start + 1;
  1874. // prevent the textarea to lose focus
  1875. event.preventDefault();
  1876. }
  1877. }
  1878. /**
  1879. * view the Editor tab
  1880. *
  1881. * @name Editor.viewEditor
  1882. * @function
  1883. * @param {Event} event - optional
  1884. */
  1885. function viewEditor(event)
  1886. {
  1887. // toggle buttons
  1888. $messageEdit.addClass('active');
  1889. $messagePreview.removeClass('active');
  1890. PasteViewer.hide();
  1891. // reshow input
  1892. $message.removeClass('hidden');
  1893. me.focusInput();
  1894. // finish
  1895. isPreview = false;
  1896. // prevent jumping of page to top
  1897. if (typeof event !== 'undefined') {
  1898. event.preventDefault();
  1899. }
  1900. }
  1901. /**
  1902. * view the preview tab
  1903. *
  1904. * @name Editor.viewPreview
  1905. * @function
  1906. * @param {Event} event
  1907. */
  1908. function viewPreview(event)
  1909. {
  1910. // toggle buttons
  1911. $messageEdit.removeClass('active');
  1912. $messagePreview.addClass('active');
  1913. // hide input as now preview is shown
  1914. $message.addClass('hidden');
  1915. // show preview
  1916. PasteViewer.setText($message.val());
  1917. if (AttachmentViewer.hasAttachmentData()) {
  1918. const attachment = AttachmentViewer.getAttachment();
  1919. AttachmentViewer.handleBlobAttachmentPreview(
  1920. AttachmentViewer.getAttachmentPreview(),
  1921. attachment[0], attachment[1]
  1922. );
  1923. }
  1924. PasteViewer.run();
  1925. // finish
  1926. isPreview = true;
  1927. // prevent jumping of page to top
  1928. if (typeof event !== 'undefined') {
  1929. event.preventDefault();
  1930. }
  1931. }
  1932. /**
  1933. * get the state of the preview
  1934. *
  1935. * @name Editor.isPreview
  1936. * @function
  1937. */
  1938. me.isPreview = function()
  1939. {
  1940. return isPreview;
  1941. };
  1942. /**
  1943. * reset the Editor view
  1944. *
  1945. * @name Editor.resetInput
  1946. * @function
  1947. */
  1948. me.resetInput = function()
  1949. {
  1950. // go back to input
  1951. if (isPreview) {
  1952. viewEditor();
  1953. }
  1954. // clear content
  1955. $message.val('');
  1956. };
  1957. /**
  1958. * shows the Editor
  1959. *
  1960. * @name Editor.show
  1961. * @function
  1962. */
  1963. me.show = function()
  1964. {
  1965. $message.removeClass('hidden');
  1966. $editorTabs.removeClass('hidden');
  1967. };
  1968. /**
  1969. * hides the Editor
  1970. *
  1971. * @name Editor.reset
  1972. * @function
  1973. */
  1974. me.hide = function()
  1975. {
  1976. $message.addClass('hidden');
  1977. $editorTabs.addClass('hidden');
  1978. };
  1979. /**
  1980. * focuses the message input
  1981. *
  1982. * @name Editor.focusInput
  1983. * @function
  1984. */
  1985. me.focusInput = function()
  1986. {
  1987. $message.focus();
  1988. };
  1989. /**
  1990. * sets a new text
  1991. *
  1992. * @name Editor.setText
  1993. * @function
  1994. * @param {string} newText
  1995. */
  1996. me.setText = function(newText)
  1997. {
  1998. $message.val(newText);
  1999. };
  2000. /**
  2001. * returns the current text
  2002. *
  2003. * @name Editor.getText
  2004. * @function
  2005. * @return {string}
  2006. */
  2007. me.getText = function()
  2008. {
  2009. return $message.val();
  2010. };
  2011. /**
  2012. * init status manager
  2013. *
  2014. * preloads jQuery elements
  2015. *
  2016. * @name Editor.init
  2017. * @function
  2018. */
  2019. me.init = function()
  2020. {
  2021. $editorTabs = $('#editorTabs');
  2022. $message = $('#message');
  2023. // bind events
  2024. $message.keydown(supportTabs);
  2025. // bind click events to tab switchers (a), but save parent of them
  2026. // (li)
  2027. $messageEdit = $('#messageedit').click(viewEditor).parent();
  2028. $messagePreview = $('#messagepreview').click(viewPreview).parent();
  2029. };
  2030. return me;
  2031. })();
  2032. /**
  2033. * (view) Parse and show paste.
  2034. *
  2035. * @name PasteViewer
  2036. * @class
  2037. */
  2038. const PasteViewer = (function () {
  2039. const me = {};
  2040. let $placeholder,
  2041. $prettyMessage,
  2042. $prettyPrint,
  2043. $plainText,
  2044. text,
  2045. format = 'plaintext',
  2046. isDisplayed = false,
  2047. isChanged = true; // by default true as nothing was parsed yet
  2048. /**
  2049. * apply the set format on paste and displays it
  2050. *
  2051. * @name PasteViewer.parsePaste
  2052. * @private
  2053. * @function
  2054. */
  2055. function parsePaste()
  2056. {
  2057. // skip parsing if no text is given
  2058. if (text === '') {
  2059. return;
  2060. }
  2061. // escape HTML entities, link URLs, sanitize
  2062. const escapedLinkedText = Helper.urls2links(
  2063. $('<div />').text(text).html()
  2064. ),
  2065. sanitizedLinkedText = DOMPurify.sanitize(escapedLinkedText);
  2066. $plainText.html(sanitizedLinkedText);
  2067. $prettyPrint.html(sanitizedLinkedText);
  2068. switch (format) {
  2069. case 'markdown':
  2070. const converter = new showdown.Converter({
  2071. strikethrough: true,
  2072. tables: true,
  2073. tablesHeaderId: true,
  2074. simplifiedAutoLink: true,
  2075. excludeTrailingPunctuationFromURLs: true
  2076. });
  2077. // let showdown convert the HTML and sanitize HTML *afterwards*!
  2078. $plainText.html(
  2079. DOMPurify.sanitize(
  2080. converter.makeHtml(text)
  2081. )
  2082. );
  2083. // add table classes from bootstrap css
  2084. $plainText.find('table').addClass('table-condensed table-bordered');
  2085. break;
  2086. case 'syntaxhighlighting':
  2087. // yes, this is really needed to initialize the environment
  2088. if (typeof prettyPrint === 'function')
  2089. {
  2090. prettyPrint();
  2091. }
  2092. $prettyPrint.html(
  2093. DOMPurify.sanitize(
  2094. prettyPrintOne(escapedLinkedText, null, true)
  2095. )
  2096. );
  2097. // fall through, as the rest is the same
  2098. default: // = 'plaintext'
  2099. $prettyPrint.css('white-space', 'pre-wrap');
  2100. $prettyPrint.css('word-break', 'normal');
  2101. $prettyPrint.removeClass('prettyprint');
  2102. }
  2103. }
  2104. /**
  2105. * displays the paste
  2106. *
  2107. * @name PasteViewer.showPaste
  2108. * @private
  2109. * @function
  2110. */
  2111. function showPaste()
  2112. {
  2113. // instead of "nothing" better display a placeholder
  2114. if (text === '') {
  2115. $placeholder.removeClass('hidden');
  2116. return;
  2117. }
  2118. // otherwise hide the placeholder
  2119. $placeholder.addClass('hidden');
  2120. switch (format) {
  2121. case 'markdown':
  2122. $plainText.removeClass('hidden');
  2123. $prettyMessage.addClass('hidden');
  2124. break;
  2125. default:
  2126. $plainText.addClass('hidden');
  2127. $prettyMessage.removeClass('hidden');
  2128. break;
  2129. }
  2130. }
  2131. /**
  2132. * sets the format in which the text is shown
  2133. *
  2134. * @name PasteViewer.setFormat
  2135. * @function
  2136. * @param {string} newFormat the new format
  2137. */
  2138. me.setFormat = function(newFormat)
  2139. {
  2140. // skip if there is no update
  2141. if (format === newFormat) {
  2142. return;
  2143. }
  2144. // needs to update display too, if we switch from or to Markdown
  2145. if (format === 'markdown' || newFormat === 'markdown') {
  2146. isDisplayed = false;
  2147. }
  2148. format = newFormat;
  2149. isChanged = true;
  2150. };
  2151. /**
  2152. * returns the current format
  2153. *
  2154. * @name PasteViewer.getFormat
  2155. * @function
  2156. * @return {string}
  2157. */
  2158. me.getFormat = function()
  2159. {
  2160. return format;
  2161. };
  2162. /**
  2163. * returns whether the current view is pretty printed
  2164. *
  2165. * @name PasteViewer.isPrettyPrinted
  2166. * @function
  2167. * @return {bool}
  2168. */
  2169. me.isPrettyPrinted = function()
  2170. {
  2171. return $prettyPrint.hasClass('prettyprinted');
  2172. };
  2173. /**
  2174. * sets the text to show
  2175. *
  2176. * @name PasteViewer.setText
  2177. * @function
  2178. * @param {string} newText the text to show
  2179. */
  2180. me.setText = function(newText)
  2181. {
  2182. if (text !== newText) {
  2183. text = newText;
  2184. isChanged = true;
  2185. }
  2186. };
  2187. /**
  2188. * gets the current cached text
  2189. *
  2190. * @name PasteViewer.getText
  2191. * @function
  2192. * @return {string}
  2193. */
  2194. me.getText = function()
  2195. {
  2196. return text;
  2197. };
  2198. /**
  2199. * show/update the parsed text (preview)
  2200. *
  2201. * @name PasteViewer.run
  2202. * @function
  2203. */
  2204. me.run = function()
  2205. {
  2206. if (isChanged) {
  2207. parsePaste();
  2208. isChanged = false;
  2209. }
  2210. if (!isDisplayed) {
  2211. showPaste();
  2212. isDisplayed = true;
  2213. }
  2214. };
  2215. /**
  2216. * hide parsed text (preview)
  2217. *
  2218. * @name PasteViewer.hide
  2219. * @function
  2220. */
  2221. me.hide = function()
  2222. {
  2223. if (!isDisplayed) {
  2224. return;
  2225. }
  2226. $plainText.addClass('hidden');
  2227. $prettyMessage.addClass('hidden');
  2228. $placeholder.addClass('hidden');
  2229. AttachmentViewer.hideAttachmentPreview();
  2230. isDisplayed = false;
  2231. };
  2232. /**
  2233. * init status manager
  2234. *
  2235. * preloads jQuery elements
  2236. *
  2237. * @name PasteViewer.init
  2238. * @function
  2239. */
  2240. me.init = function()
  2241. {
  2242. $placeholder = $('#placeholder');
  2243. $plainText = $('#plaintext');
  2244. $prettyMessage = $('#prettymessage');
  2245. $prettyPrint = $('#prettyprint');
  2246. // check requirements
  2247. if (typeof prettyPrintOne !== 'function') {
  2248. Alert.showError([
  2249. 'The library %s is not available. This may cause display errors.',
  2250. 'pretty print'
  2251. ]);
  2252. }
  2253. if (typeof showdown !== 'object') {
  2254. Alert.showError([
  2255. 'The library %s is not available. This may cause display errors.',
  2256. 'showdown'
  2257. ]);
  2258. }
  2259. // get default option from template/HTML or fall back to set value
  2260. format = Model.getFormatDefault() || format;
  2261. text = '';
  2262. isDisplayed = false;
  2263. isChanged = true;
  2264. };
  2265. return me;
  2266. })();
  2267. /**
  2268. * (view) Show attachment and preview if possible
  2269. *
  2270. * @name AttachmentViewer
  2271. * @class
  2272. */
  2273. const AttachmentViewer = (function () {
  2274. const me = {};
  2275. let $attachmentLink,
  2276. $attachmentPreview,
  2277. $attachment,
  2278. attachmentData,
  2279. file,
  2280. $fileInput,
  2281. $dragAndDropFileName,
  2282. attachmentHasPreview = false;
  2283. /**
  2284. * sets the attachment but does not yet show it
  2285. *
  2286. * @name AttachmentViewer.setAttachment
  2287. * @function
  2288. * @param {string} attachmentData - base64-encoded data of file
  2289. * @param {string} fileName - optional, file name
  2290. */
  2291. me.setAttachment = function(attachmentData, fileName)
  2292. {
  2293. // data URI format: data:[<mediaType>][;base64],<data>
  2294. // position in data URI string of where data begins
  2295. const base64Start = attachmentData.indexOf(',') + 1;
  2296. // position in data URI string of where mediaType ends
  2297. const mediaTypeEnd = attachmentData.indexOf(';');
  2298. // extract mediaType
  2299. const mediaType = attachmentData.substring(5, mediaTypeEnd);
  2300. // extract data and convert to binary
  2301. const decodedData = atob(attachmentData.substring(base64Start));
  2302. // Transform into a Blob
  2303. const buf = new Uint8Array(decodedData.length);
  2304. for (let i = 0; i < decodedData.length; ++i) {
  2305. buf[i] = decodedData.charCodeAt(i);
  2306. }
  2307. const blob = new window.Blob([ buf ], { type: mediaType });
  2308. // Get Blob URL
  2309. const blobUrl = window.URL.createObjectURL(blob);
  2310. // IE does not support setting a data URI on an a element
  2311. // Using msSaveBlob to download
  2312. if (window.Blob && navigator.msSaveBlob) {
  2313. $attachmentLink.off('click').on('click', function () {
  2314. navigator.msSaveBlob(blob, fileName);
  2315. });
  2316. } else {
  2317. $attachmentLink.attr('href', blobUrl);
  2318. }
  2319. if (typeof fileName !== 'undefined') {
  2320. $attachmentLink.attr('download', fileName);
  2321. }
  2322. me.handleBlobAttachmentPreview($attachmentPreview, blobUrl, mediaType);
  2323. };
  2324. /**
  2325. * displays the attachment
  2326. *
  2327. * @name AttachmentViewer.showAttachment
  2328. * @function
  2329. */
  2330. me.showAttachment = function()
  2331. {
  2332. $attachment.removeClass('hidden');
  2333. if (attachmentHasPreview) {
  2334. $attachmentPreview.removeClass('hidden');
  2335. }
  2336. };
  2337. /**
  2338. * removes the attachment
  2339. *
  2340. * This automatically hides the attachment containers too, to
  2341. * prevent an inconsistent display.
  2342. *
  2343. * @name AttachmentViewer.removeAttachment
  2344. * @function
  2345. */
  2346. me.removeAttachment = function()
  2347. {
  2348. if (!$attachment.length) {
  2349. return;
  2350. }
  2351. me.hideAttachment();
  2352. me.hideAttachmentPreview();
  2353. $attachmentLink.removeAttr('href');
  2354. $attachmentLink.removeAttr('download');
  2355. $attachmentLink.off('click');
  2356. $attachmentPreview.html('');
  2357. AttachmentViewer.removeAttachmentData();
  2358. };
  2359. /**
  2360. * removes the attachment data
  2361. *
  2362. * This removes the data, which would be uploaded otherwise.
  2363. *
  2364. * @name AttachmentViewer.removeAttachmentData
  2365. * @function
  2366. */
  2367. me.removeAttachmentData = function()
  2368. {
  2369. file = undefined;
  2370. attachmentData = undefined;
  2371. };
  2372. /**
  2373. * Cleares the drag & drop data.
  2374. *
  2375. * @name AttachmentViewer.clearDragAndDrop
  2376. * @function
  2377. */
  2378. me.clearDragAndDrop = function()
  2379. {
  2380. $dragAndDropFileName.text('');
  2381. };
  2382. /**
  2383. * hides the attachment
  2384. *
  2385. * This will not hide the preview (see AttachmentViewer.hideAttachmentPreview
  2386. * for that) nor will it hide the attachment link if it was moved somewhere
  2387. * else (see AttachmentViewer.moveAttachmentTo).
  2388. *
  2389. * @name AttachmentViewer.hideAttachment
  2390. * @function
  2391. */
  2392. me.hideAttachment = function()
  2393. {
  2394. $attachment.addClass('hidden');
  2395. };
  2396. /**
  2397. * hides the attachment preview
  2398. *
  2399. * @name AttachmentViewer.hideAttachmentPreview
  2400. * @function
  2401. */
  2402. me.hideAttachmentPreview = function()
  2403. {
  2404. if ($attachmentPreview) {
  2405. $attachmentPreview.addClass('hidden');
  2406. }
  2407. };
  2408. /**
  2409. * checks if there is an attachment displayed
  2410. *
  2411. * @name AttachmentViewer.hasAttachment
  2412. * @function
  2413. */
  2414. me.hasAttachment = function()
  2415. {
  2416. if (!$attachment.length) {
  2417. return false;
  2418. }
  2419. const link = $attachmentLink.prop('href');
  2420. return (typeof link !== 'undefined' && link !== '');
  2421. };
  2422. /**
  2423. * checks if there is attachment data (for preview!) available
  2424. *
  2425. * It returns true, when there is data that needs to be encrypted.
  2426. *
  2427. * @name AttachmentViewer.hasAttachmentData
  2428. * @function
  2429. */
  2430. me.hasAttachmentData = function()
  2431. {
  2432. if ($attachment.length) {
  2433. return true;
  2434. }
  2435. return false;
  2436. };
  2437. /**
  2438. * return the attachment
  2439. *
  2440. * @name AttachmentViewer.getAttachment
  2441. * @function
  2442. * @returns {array}
  2443. */
  2444. me.getAttachment = function()
  2445. {
  2446. return [
  2447. $attachmentLink.prop('href'),
  2448. $attachmentLink.prop('download')
  2449. ];
  2450. };
  2451. /**
  2452. * moves the attachment link to another element
  2453. *
  2454. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  2455. *
  2456. * @name AttachmentViewer.moveAttachmentTo
  2457. * @function
  2458. * @param {jQuery} $element - the wrapper/container element where this should be moved to
  2459. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  2460. */
  2461. me.moveAttachmentTo = function($element, label)
  2462. {
  2463. // move elemement to new place
  2464. $attachmentLink.appendTo($element);
  2465. // update text
  2466. I18n._($attachmentLink, label, $attachmentLink.attr('download'));
  2467. };
  2468. /**
  2469. * read file data as data URL using the FileReader API
  2470. *
  2471. * @name AttachmentViewer.readFileData
  2472. * @private
  2473. * @function
  2474. * @param {object} loadedFile (optional) loaded file object
  2475. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsDataURL()}
  2476. */
  2477. function readFileData(loadedFile) {
  2478. if (typeof FileReader === 'undefined') {
  2479. // revert loading status…
  2480. me.hideAttachment();
  2481. me.hideAttachmentPreview();
  2482. Alert.showError('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2483. return;
  2484. }
  2485. const fileReader = new FileReader();
  2486. if (loadedFile === undefined) {
  2487. loadedFile = $fileInput[0].files[0];
  2488. $dragAndDropFileName.text('');
  2489. } else {
  2490. $dragAndDropFileName.text(loadedFile.name);
  2491. }
  2492. file = loadedFile;
  2493. fileReader.onload = function (event) {
  2494. const dataURL = event.target.result;
  2495. attachmentData = dataURL;
  2496. if (Editor.isPreview()) {
  2497. me.setAttachment(dataURL, loadedFile.name || '');
  2498. $attachmentPreview.removeClass('hidden');
  2499. }
  2500. };
  2501. fileReader.readAsDataURL(loadedFile);
  2502. }
  2503. /**
  2504. * handle the preview of files decoded to blob that can either be an image, video, audio or pdf element
  2505. *
  2506. * @name AttachmentViewer.handleBlobAttachmentPreview
  2507. * @function
  2508. * @argument {jQuery} $targetElement element where the preview should be appended
  2509. * @argument {string} file as a blob URL
  2510. * @argument {string} mime type
  2511. */
  2512. me.handleBlobAttachmentPreview = function ($targetElement, blobUrl, mimeType) {
  2513. if (blobUrl) {
  2514. attachmentHasPreview = true;
  2515. if (mimeType.match(/image\//i)) {
  2516. $targetElement.html(
  2517. $(document.createElement('img'))
  2518. .attr('src', blobUrl)
  2519. .attr('class', 'img-thumbnail')
  2520. );
  2521. } else if (mimeType.match(/video\//i)) {
  2522. $targetElement.html(
  2523. $(document.createElement('video'))
  2524. .attr('controls', 'true')
  2525. .attr('autoplay', 'true')
  2526. .attr('class', 'img-thumbnail')
  2527. .append($(document.createElement('source'))
  2528. .attr('type', mimeType)
  2529. .attr('src', blobUrl))
  2530. );
  2531. } else if (mimeType.match(/audio\//i)) {
  2532. $targetElement.html(
  2533. $(document.createElement('audio'))
  2534. .attr('controls', 'true')
  2535. .attr('autoplay', 'true')
  2536. .append($(document.createElement('source'))
  2537. .attr('type', mimeType)
  2538. .attr('src', blobUrl))
  2539. );
  2540. } else if (mimeType.match(/\/pdf/i)) {
  2541. // PDFs are only displayed if the filesize is smaller than about 1MB (after base64 encoding).
  2542. // Bigger filesizes currently cause crashes in various browsers.
  2543. // See also: https://code.google.com/p/chromium/issues/detail?id=69227
  2544. // Firefox crashes with files that are about 1.5MB
  2545. // The performance with 1MB files is bearable
  2546. /*if (data.length > 1398488) {
  2547. Alert.showError('File too large, to display a preview. Please download the attachment.'); //TODO: is this error really necessary?
  2548. return;
  2549. }*/
  2550. // Fallback for browsers, that don't support the vh unit
  2551. var clientHeight = $(window).height();
  2552. $targetElement.html(
  2553. $(document.createElement('embed'))
  2554. .attr('src', blobUrl)
  2555. .attr('type', 'application/pdf')
  2556. .attr('class', 'pdfPreview')
  2557. .css('height', clientHeight)
  2558. );
  2559. } else {
  2560. attachmentHasPreview = false;
  2561. }
  2562. }
  2563. };
  2564. /**
  2565. * attaches the file attachment drag & drop handler to the page
  2566. *
  2567. * @name AttachmentViewer.addDragDropHandler
  2568. * @private
  2569. * @function
  2570. */
  2571. function addDragDropHandler() {
  2572. if (typeof $fileInput === 'undefined' || $fileInput.length === 0) {
  2573. return;
  2574. }
  2575. const ignoreDragDrop = function(event) {
  2576. event.stopPropagation();
  2577. event.preventDefault();
  2578. };
  2579. const drop = function(event) {
  2580. const evt = event.originalEvent;
  2581. evt.stopPropagation();
  2582. evt.preventDefault();
  2583. if ($fileInput) {
  2584. const file = evt.dataTransfer.files[0];
  2585. //Clear the file input:
  2586. $fileInput.wrap('<form>').closest('form').get(0).reset();
  2587. $fileInput.unwrap();
  2588. //Only works in Chrome:
  2589. //fileInput[0].files = e.dataTransfer.files;
  2590. readFileData(file);
  2591. }
  2592. };
  2593. $(document).on('drop', drop);
  2594. $(document).on('dragenter', ignoreDragDrop);
  2595. $(document).on('dragover', ignoreDragDrop);
  2596. $fileInput.on('change', function () {
  2597. readFileData();
  2598. });
  2599. }
  2600. /**
  2601. * attaches the clipboard attachment handler to the page
  2602. *
  2603. * @name AttachmentViewer.addClipboardEventHandler
  2604. * @private
  2605. * @function
  2606. */
  2607. function addClipboardEventHandler() {
  2608. $(document).on('paste', function (event) {
  2609. const items = (event.clipboardData || event.originalEvent.clipboardData).items;
  2610. for (let i = 0; i < items.length; ++i) {
  2611. if (items[i].kind === 'file') {
  2612. //Clear the file input:
  2613. $fileInput.wrap('<form>').closest('form').get(0).reset();
  2614. $fileInput.unwrap();
  2615. readFileData(items[i].getAsFile());
  2616. }
  2617. }
  2618. });
  2619. }
  2620. /**
  2621. * getter for attachment data
  2622. *
  2623. * @name AttachmentViewer.getAttachmentData
  2624. * @function
  2625. * @return {jQuery}
  2626. */
  2627. me.getAttachmentData = function () {
  2628. return attachmentData;
  2629. };
  2630. /**
  2631. * getter for attachment link
  2632. *
  2633. * @name AttachmentViewer.getAttachmentLink
  2634. * @function
  2635. * @return {jQuery}
  2636. */
  2637. me.getAttachmentLink = function () {
  2638. return $attachmentLink;
  2639. };
  2640. /**
  2641. * getter for attachment preview
  2642. *
  2643. * @name AttachmentViewer.getAttachmentPreview
  2644. * @function
  2645. * @return {jQuery}
  2646. */
  2647. me.getAttachmentPreview = function () {
  2648. return $attachmentPreview;
  2649. };
  2650. /**
  2651. * getter for file data, returns the file contents
  2652. *
  2653. * @name AttachmentViewer.getFile
  2654. * @function
  2655. * @return {string}
  2656. */
  2657. me.getFile = function () {
  2658. return file;
  2659. };
  2660. /**
  2661. * initiate
  2662. *
  2663. * preloads jQuery elements
  2664. *
  2665. * @name AttachmentViewer.init
  2666. * @function
  2667. */
  2668. me.init = function()
  2669. {
  2670. $attachment = $('#attachment');
  2671. if($attachment.length){
  2672. $attachmentLink = $('#attachment a');
  2673. $attachmentPreview = $('#attachmentPreview');
  2674. $dragAndDropFileName = $('#dragAndDropFileName');
  2675. $fileInput = $('#file');
  2676. addDragDropHandler();
  2677. addClipboardEventHandler();
  2678. }
  2679. }
  2680. return me;
  2681. })();
  2682. /**
  2683. * (view) Shows discussion thread and handles replies
  2684. *
  2685. * @name DiscussionViewer
  2686. * @class
  2687. */
  2688. const DiscussionViewer = (function () {
  2689. const me = {};
  2690. let $commentTail,
  2691. $discussion,
  2692. $reply,
  2693. $replyMessage,
  2694. $replyNickname,
  2695. $replyStatus,
  2696. $commentContainer,
  2697. replyCommentId;
  2698. /**
  2699. * initializes the templates
  2700. *
  2701. * @name DiscussionViewer.initTemplates
  2702. * @private
  2703. * @function
  2704. */
  2705. function initTemplates()
  2706. {
  2707. $reply = Model.getTemplate('reply');
  2708. $replyMessage = $reply.find('#replymessage');
  2709. $replyNickname = $reply.find('#nickname');
  2710. $replyStatus = $reply.find('#replystatus');
  2711. // cache jQuery elements
  2712. $commentTail = Model.getTemplate('commenttail');
  2713. }
  2714. /**
  2715. * open the comment entry when clicking the "Reply" button of a comment
  2716. *
  2717. * @name DiscussionViewer.openReply
  2718. * @private
  2719. * @function
  2720. * @param {Event} event
  2721. */
  2722. function openReply(event)
  2723. {
  2724. const $source = $(event.target);
  2725. // clear input
  2726. $replyMessage.val('');
  2727. $replyNickname.val('');
  2728. // get comment id from source element
  2729. replyCommentId = $source.parent().prop('id').split('_')[1];
  2730. // move to correct position
  2731. $source.after($reply);
  2732. // show
  2733. $reply.removeClass('hidden');
  2734. $replyMessage.focus();
  2735. event.preventDefault();
  2736. }
  2737. /**
  2738. * custom handler for displaying notifications in own status message area
  2739. *
  2740. * @name DiscussionViewer.handleNotification
  2741. * @function
  2742. * @param {string} alertType
  2743. * @return {bool|jQuery}
  2744. */
  2745. me.handleNotification = function(alertType)
  2746. {
  2747. // ignore loading messages
  2748. if (alertType === 'loading') {
  2749. return false;
  2750. }
  2751. if (alertType === 'danger') {
  2752. $replyStatus.removeClass('alert-info');
  2753. $replyStatus.addClass('alert-danger');
  2754. $replyStatus.find(':first').removeClass('glyphicon-alert');
  2755. $replyStatus.find(':first').addClass('glyphicon-info-sign');
  2756. } else {
  2757. $replyStatus.removeClass('alert-danger');
  2758. $replyStatus.addClass('alert-info');
  2759. $replyStatus.find(':first').removeClass('glyphicon-info-sign');
  2760. $replyStatus.find(':first').addClass('glyphicon-alert');
  2761. }
  2762. return $replyStatus;
  2763. };
  2764. /**
  2765. * adds another comment
  2766. *
  2767. * @name DiscussionViewer.addComment
  2768. * @function
  2769. * @param {Comment} comment
  2770. * @param {string} commentText
  2771. * @param {string} nickname
  2772. */
  2773. me.addComment = function(comment, commentText, nickname)
  2774. {
  2775. if (commentText === '') {
  2776. commentText = 'comment decryption failed';
  2777. }
  2778. // create new comment based on template
  2779. const $commentEntry = Model.getTemplate('comment');
  2780. $commentEntry.prop('id', 'comment_' + comment.id);
  2781. const $commentEntryData = $commentEntry.find('div.commentdata');
  2782. // set & parse text
  2783. $commentEntryData.html(
  2784. DOMPurify.sanitize(
  2785. Helper.urls2links(commentText)
  2786. )
  2787. );
  2788. // set nickname
  2789. if (nickname.length > 0) {
  2790. $commentEntry.find('span.nickname').text(nickname);
  2791. } else {
  2792. $commentEntry.find('span.nickname').html('<i></i>');
  2793. I18n._($commentEntry.find('span.nickname i'), 'Anonymous');
  2794. }
  2795. // set date
  2796. $commentEntry.find('span.commentdate')
  2797. .text(' (' + (new Date(comment.getCreated() * 1000).toLocaleString()) + ')')
  2798. .attr('title', 'CommentID: ' + comment.id);
  2799. // if an avatar is available, display it
  2800. const icon = comment.getIcon();
  2801. if (icon) {
  2802. $commentEntry.find('span.nickname')
  2803. .before(
  2804. '<img src="' + icon + '" class="vizhash" /> '
  2805. );
  2806. $(document).on('languageLoaded', function () {
  2807. $commentEntry.find('img.vizhash')
  2808. .prop('title', I18n._('Avatar generated from IP address'));
  2809. });
  2810. }
  2811. // starting point (default value/fallback)
  2812. let $place = $commentContainer;
  2813. // if parent comment exists
  2814. const $parentComment = $('#comment_' + comment.parentid);
  2815. if ($parentComment.length) {
  2816. // use parent as position for new comment, so it is shifted
  2817. // to the right
  2818. $place = $parentComment;
  2819. }
  2820. // finally append comment
  2821. $place.append($commentEntry);
  2822. };
  2823. /**
  2824. * finishes the discussion area after last comment
  2825. *
  2826. * @name DiscussionViewer.finishDiscussion
  2827. * @function
  2828. */
  2829. me.finishDiscussion = function()
  2830. {
  2831. // add 'add new comment' area
  2832. $commentContainer.append($commentTail);
  2833. // show discussions
  2834. $discussion.removeClass('hidden');
  2835. };
  2836. /**
  2837. * removes the old discussion and prepares everything for creating a new
  2838. * one.
  2839. *
  2840. * @name DiscussionViewer.prepareNewDiscussion
  2841. * @function
  2842. */
  2843. me.prepareNewDiscussion = function()
  2844. {
  2845. $commentContainer.html('');
  2846. $discussion.addClass('hidden');
  2847. // (re-)init templates
  2848. initTemplates();
  2849. };
  2850. /**
  2851. * returns the users message from the reply form
  2852. *
  2853. * @name DiscussionViewer.getReplyMessage
  2854. * @function
  2855. * @return {String}
  2856. */
  2857. me.getReplyMessage = function()
  2858. {
  2859. return $replyMessage.val();
  2860. };
  2861. /**
  2862. * returns the users nickname (if any) from the reply form
  2863. *
  2864. * @name DiscussionViewer.getReplyNickname
  2865. * @function
  2866. * @return {String}
  2867. */
  2868. me.getReplyNickname = function()
  2869. {
  2870. return $replyNickname.val();
  2871. };
  2872. /**
  2873. * returns the id of the parent comment the user is replying to
  2874. *
  2875. * @name DiscussionViewer.getReplyCommentId
  2876. * @function
  2877. * @return {int|undefined}
  2878. */
  2879. me.getReplyCommentId = function()
  2880. {
  2881. return replyCommentId;
  2882. };
  2883. /**
  2884. * highlights a specific comment and scrolls to it if necessary
  2885. *
  2886. * @name DiscussionViewer.highlightComment
  2887. * @function
  2888. * @param {string} commentId
  2889. * @param {bool} fadeOut - whether to fade out the comment
  2890. */
  2891. me.highlightComment = function(commentId, fadeOut)
  2892. {
  2893. const $comment = $('#comment_' + commentId);
  2894. // in case comment does not exist, cancel
  2895. if ($comment.length === 0) {
  2896. return;
  2897. }
  2898. $comment.addClass('highlight');
  2899. const highlightComment = function () {
  2900. if (fadeOut === true) {
  2901. setTimeout(function () {
  2902. $comment.removeClass('highlight');
  2903. }, 300);
  2904. }
  2905. };
  2906. if (UiHelper.isVisible($comment)) {
  2907. return highlightComment();
  2908. }
  2909. UiHelper.scrollTo($comment, 100, 'swing', highlightComment);
  2910. };
  2911. /**
  2912. * initiate
  2913. *
  2914. * preloads jQuery elements
  2915. *
  2916. * @name DiscussionViewer.init
  2917. * @function
  2918. */
  2919. me.init = function()
  2920. {
  2921. // bind events to templates (so they are later cloned)
  2922. $('#commenttailtemplate, #commenttemplate').find('button').on('click', openReply);
  2923. $('#replytemplate').find('button').on('click', PasteEncrypter.sendComment);
  2924. $commentContainer = $('#commentcontainer');
  2925. $discussion = $('#discussion');
  2926. };
  2927. return me;
  2928. })();
  2929. /**
  2930. * Manage top (navigation) bar
  2931. *
  2932. * @name TopNav
  2933. * @param {object} window
  2934. * @param {object} document
  2935. * @class
  2936. */
  2937. const TopNav = (function (window, document) {
  2938. const me = {};
  2939. let createButtonsDisplayed = false,
  2940. viewButtonsDisplayed = false,
  2941. $attach,
  2942. $burnAfterReading,
  2943. $burnAfterReadingOption,
  2944. $cloneButton,
  2945. $customAttachment,
  2946. $expiration,
  2947. $fileRemoveButton,
  2948. $fileWrap,
  2949. $formatter,
  2950. $newButton,
  2951. $openDiscussion,
  2952. $openDiscussionOption,
  2953. $password,
  2954. $passwordInput,
  2955. $rawTextButton,
  2956. $qrCodeLink,
  2957. $sendButton,
  2958. $retryButton,
  2959. pasteExpiration = '1week',
  2960. retryButtonCallback;
  2961. /**
  2962. * set the expiration on bootstrap templates in dropdown
  2963. *
  2964. * @name TopNav.updateExpiration
  2965. * @private
  2966. * @function
  2967. * @param {Event} event
  2968. */
  2969. function updateExpiration(event)
  2970. {
  2971. // get selected option
  2972. const target = $(event.target);
  2973. // update dropdown display and save new expiration time
  2974. $('#pasteExpirationDisplay').text(target.text());
  2975. pasteExpiration = target.data('expiration');
  2976. event.preventDefault();
  2977. }
  2978. /**
  2979. * set the format on bootstrap templates in dropdown
  2980. *
  2981. * @name TopNav.updateFormat
  2982. * @private
  2983. * @function
  2984. * @param {Event} event
  2985. */
  2986. function updateFormat(event)
  2987. {
  2988. // get selected option
  2989. const $target = $(event.target);
  2990. // update dropdown display and save new format
  2991. const newFormat = $target.data('format');
  2992. $('#pasteFormatterDisplay').text($target.text());
  2993. PasteViewer.setFormat(newFormat);
  2994. // update preview
  2995. if (Editor.isPreview()) {
  2996. PasteViewer.run();
  2997. }
  2998. event.preventDefault();
  2999. }
  3000. /**
  3001. * when "burn after reading" is checked, disable discussion
  3002. *
  3003. * @name TopNav.changeBurnAfterReading
  3004. * @private
  3005. * @function
  3006. */
  3007. function changeBurnAfterReading()
  3008. {
  3009. if ($burnAfterReading.is(':checked')) {
  3010. $openDiscussionOption.addClass('buttondisabled');
  3011. $openDiscussion.prop('checked', false);
  3012. // if button is actually disabled, force-enable it and uncheck other button
  3013. $burnAfterReadingOption.removeClass('buttondisabled');
  3014. } else {
  3015. $openDiscussionOption.removeClass('buttondisabled');
  3016. }
  3017. }
  3018. /**
  3019. * when discussion is checked, disable "burn after reading"
  3020. *
  3021. * @name TopNav.changeOpenDiscussion
  3022. * @private
  3023. * @function
  3024. */
  3025. function changeOpenDiscussion()
  3026. {
  3027. if ($openDiscussion.is(':checked')) {
  3028. $burnAfterReadingOption.addClass('buttondisabled');
  3029. $burnAfterReading.prop('checked', false);
  3030. // if button is actually disabled, force-enable it and uncheck other button
  3031. $openDiscussionOption.removeClass('buttondisabled');
  3032. } else {
  3033. $burnAfterReadingOption.removeClass('buttondisabled');
  3034. }
  3035. }
  3036. /**
  3037. * return raw text
  3038. *
  3039. * @name TopNav.rawText
  3040. * @private
  3041. * @function
  3042. */
  3043. function rawText()
  3044. {
  3045. TopNav.hideAllButtons();
  3046. Alert.showLoading('Showing raw text…', 'time');
  3047. let paste = PasteViewer.getText();
  3048. // push a new state to allow back navigation with browser back button
  3049. history.pushState(
  3050. {type: 'raw'},
  3051. document.title,
  3052. // recreate paste URL
  3053. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  3054. CryptTool.base58encode(Model.getPasteKey())
  3055. );
  3056. // we use text/html instead of text/plain to avoid a bug when
  3057. // reloading the raw text view (it reverts to type text/html)
  3058. const $head = $('head').children().not('noscript, script, link[type="text/css"]'),
  3059. newDoc = document.open('text/html', 'replace');
  3060. newDoc.write('<!DOCTYPE html><html><head>');
  3061. for (let i = 0; i < $head.length; ++i) {
  3062. newDoc.write($head[i].outerHTML);
  3063. }
  3064. newDoc.write('</head><body><pre>' + DOMPurify.sanitize($('<div />').text(paste).html()) + '</pre></body></html>');
  3065. newDoc.close();
  3066. }
  3067. /**
  3068. * saves the language in a cookie and reloads the page
  3069. *
  3070. * @name TopNav.setLanguage
  3071. * @private
  3072. * @function
  3073. * @param {Event} event
  3074. */
  3075. function setLanguage(event)
  3076. {
  3077. document.cookie = 'lang=' + $(event.target).data('lang');
  3078. UiHelper.reloadHome();
  3079. }
  3080. /**
  3081. * hides all messages and creates a new paste
  3082. *
  3083. * @name TopNav.clickNewPaste
  3084. * @private
  3085. * @function
  3086. */
  3087. function clickNewPaste()
  3088. {
  3089. Controller.hideStatusMessages();
  3090. Controller.newPaste();
  3091. }
  3092. /**
  3093. * retrys some callback registered before
  3094. *
  3095. * @name TopNav.clickRetryButton
  3096. * @private
  3097. * @function
  3098. * @param {Event} event
  3099. */
  3100. function clickRetryButton(event)
  3101. {
  3102. retryButtonCallback(event);
  3103. }
  3104. /**
  3105. * removes the existing attachment
  3106. *
  3107. * @name TopNav.removeAttachment
  3108. * @private
  3109. * @function
  3110. * @param {Event} event
  3111. */
  3112. function removeAttachment(event)
  3113. {
  3114. // if custom attachment is used, remove it first
  3115. if (!$customAttachment.hasClass('hidden')) {
  3116. AttachmentViewer.removeAttachment();
  3117. $customAttachment.addClass('hidden');
  3118. $fileWrap.removeClass('hidden');
  3119. }
  3120. // in any case, remove saved attachment data
  3121. AttachmentViewer.removeAttachmentData();
  3122. // hide UI for selected files
  3123. // our up-to-date jQuery can handle it :)
  3124. $fileWrap.find('input').val('');
  3125. AttachmentViewer.clearDragAndDrop();
  3126. // pevent '#' from appearing in the URL
  3127. event.preventDefault();
  3128. }
  3129. /**
  3130. * Shows the QR code of the current paste (URL).
  3131. *
  3132. * @name TopNav.displayQrCode
  3133. * @private
  3134. * @function
  3135. */
  3136. function displayQrCode()
  3137. {
  3138. const qrCanvas = kjua({
  3139. render: 'canvas',
  3140. text: window.location.href
  3141. });
  3142. $('#qrcode-display').html(qrCanvas);
  3143. }
  3144. /**
  3145. * Shows all navigation elements for viewing an existing paste
  3146. *
  3147. * @name TopNav.showViewButtons
  3148. * @function
  3149. */
  3150. me.showViewButtons = function()
  3151. {
  3152. if (viewButtonsDisplayed) {
  3153. return;
  3154. }
  3155. $newButton.removeClass('hidden');
  3156. $cloneButton.removeClass('hidden');
  3157. $rawTextButton.removeClass('hidden');
  3158. $qrCodeLink.removeClass('hidden');
  3159. viewButtonsDisplayed = true;
  3160. };
  3161. /**
  3162. * Hides all navigation elements for viewing an existing paste
  3163. *
  3164. * @name TopNav.hideViewButtons
  3165. * @function
  3166. */
  3167. me.hideViewButtons = function()
  3168. {
  3169. if (!viewButtonsDisplayed) {
  3170. return;
  3171. }
  3172. $cloneButton.addClass('hidden');
  3173. $newButton.addClass('hidden');
  3174. $rawTextButton.addClass('hidden');
  3175. $qrCodeLink.addClass('hidden');
  3176. viewButtonsDisplayed = false;
  3177. };
  3178. /**
  3179. * Hides all elements belonging to existing pastes
  3180. *
  3181. * @name TopNav.hideAllButtons
  3182. * @function
  3183. */
  3184. me.hideAllButtons = function()
  3185. {
  3186. me.hideViewButtons();
  3187. me.hideCreateButtons();
  3188. };
  3189. /**
  3190. * shows all elements needed when creating a new paste
  3191. *
  3192. * @name TopNav.showCreateButtons
  3193. * @function
  3194. */
  3195. me.showCreateButtons = function()
  3196. {
  3197. if (createButtonsDisplayed) {
  3198. return;
  3199. }
  3200. $attach.removeClass('hidden');
  3201. $burnAfterReadingOption.removeClass('hidden');
  3202. $expiration.removeClass('hidden');
  3203. $formatter.removeClass('hidden');
  3204. $newButton.removeClass('hidden');
  3205. $openDiscussionOption.removeClass('hidden');
  3206. $password.removeClass('hidden');
  3207. $sendButton.removeClass('hidden');
  3208. createButtonsDisplayed = true;
  3209. };
  3210. /**
  3211. * shows all elements needed when creating a new paste
  3212. *
  3213. * @name TopNav.hideCreateButtons
  3214. * @function
  3215. */
  3216. me.hideCreateButtons = function()
  3217. {
  3218. if (!createButtonsDisplayed) {
  3219. return;
  3220. }
  3221. $newButton.addClass('hidden');
  3222. $sendButton.addClass('hidden');
  3223. $expiration.addClass('hidden');
  3224. $formatter.addClass('hidden');
  3225. $burnAfterReadingOption.addClass('hidden');
  3226. $openDiscussionOption.addClass('hidden');
  3227. $password.addClass('hidden');
  3228. $attach.addClass('hidden');
  3229. createButtonsDisplayed = false;
  3230. };
  3231. /**
  3232. * only shows the "new paste" button
  3233. *
  3234. * @name TopNav.showNewPasteButton
  3235. * @function
  3236. */
  3237. me.showNewPasteButton = function()
  3238. {
  3239. $newButton.removeClass('hidden');
  3240. };
  3241. /**
  3242. * only shows the "retry" button
  3243. *
  3244. * @name TopNav.showRetryButton
  3245. * @function
  3246. */
  3247. me.showRetryButton = function()
  3248. {
  3249. $retryButton.removeClass('hidden');
  3250. }
  3251. /**
  3252. * hides the "retry" button
  3253. *
  3254. * @name TopNav.hideRetryButton
  3255. * @function
  3256. */
  3257. me.hideRetryButton = function()
  3258. {
  3259. $retryButton.addClass('hidden');
  3260. }
  3261. /**
  3262. * only hides the clone button
  3263. *
  3264. * @name TopNav.hideCloneButton
  3265. * @function
  3266. */
  3267. me.hideCloneButton = function()
  3268. {
  3269. $cloneButton.addClass('hidden');
  3270. };
  3271. /**
  3272. * only hides the raw text button
  3273. *
  3274. * @name TopNav.hideRawButton
  3275. * @function
  3276. */
  3277. me.hideRawButton = function()
  3278. {
  3279. $rawTextButton.addClass('hidden');
  3280. };
  3281. /**
  3282. * hides the file selector in attachment
  3283. *
  3284. * @name TopNav.hideFileSelector
  3285. * @function
  3286. */
  3287. me.hideFileSelector = function()
  3288. {
  3289. $fileWrap.addClass('hidden');
  3290. };
  3291. /**
  3292. * shows the custom attachment
  3293. *
  3294. * @name TopNav.showCustomAttachment
  3295. * @function
  3296. */
  3297. me.showCustomAttachment = function()
  3298. {
  3299. $customAttachment.removeClass('hidden');
  3300. };
  3301. /**
  3302. * collapses the navigation bar, only if expanded
  3303. *
  3304. * @name TopNav.collapseBar
  3305. * @function
  3306. */
  3307. me.collapseBar = function()
  3308. {
  3309. if ($('#navbar').attr('aria-expanded') === 'true') {
  3310. $('.navbar-toggle').click();
  3311. }
  3312. };
  3313. /**
  3314. * returns the currently set expiration time
  3315. *
  3316. * @name TopNav.getExpiration
  3317. * @function
  3318. * @return {int}
  3319. */
  3320. me.getExpiration = function()
  3321. {
  3322. return pasteExpiration;
  3323. };
  3324. /**
  3325. * returns the currently selected file(s)
  3326. *
  3327. * @name TopNav.getFileList
  3328. * @function
  3329. * @return {FileList|null}
  3330. */
  3331. me.getFileList = function()
  3332. {
  3333. const $file = $('#file');
  3334. // if no file given, return null
  3335. if (!$file.length || !$file[0].files.length) {
  3336. return null;
  3337. }
  3338. // ensure the selected file is still accessible
  3339. if (!($file[0].files && $file[0].files[0])) {
  3340. return null;
  3341. }
  3342. return $file[0].files;
  3343. };
  3344. /**
  3345. * returns the state of the burn after reading checkbox
  3346. *
  3347. * @name TopNav.getExpiration
  3348. * @function
  3349. * @return {bool}
  3350. */
  3351. me.getBurnAfterReading = function()
  3352. {
  3353. return $burnAfterReading.is(':checked');
  3354. };
  3355. /**
  3356. * returns the state of the discussion checkbox
  3357. *
  3358. * @name TopNav.getOpenDiscussion
  3359. * @function
  3360. * @return {bool}
  3361. */
  3362. me.getOpenDiscussion = function()
  3363. {
  3364. return $openDiscussion.is(':checked');
  3365. };
  3366. /**
  3367. * returns the entered password
  3368. *
  3369. * @name TopNav.getPassword
  3370. * @function
  3371. * @return {string}
  3372. */
  3373. me.getPassword = function()
  3374. {
  3375. return $passwordInput.val();
  3376. };
  3377. /**
  3378. * returns the element where custom attachments can be placed
  3379. *
  3380. * Used by AttachmentViewer when an attachment is cloned here.
  3381. *
  3382. * @name TopNav.getCustomAttachment
  3383. * @function
  3384. * @return {jQuery}
  3385. */
  3386. me.getCustomAttachment = function()
  3387. {
  3388. return $customAttachment;
  3389. };
  3390. /**
  3391. * Set a function to call when the retry button is clicked.
  3392. *
  3393. * @name TopNav.setRetryCallback
  3394. * @function
  3395. * @param {function} callback
  3396. */
  3397. me.setRetryCallback = function(callback)
  3398. {
  3399. retryButtonCallback = callback;
  3400. }
  3401. /**
  3402. * init navigation manager
  3403. *
  3404. * preloads jQuery elements
  3405. *
  3406. * @name TopNav.init
  3407. * @function
  3408. */
  3409. me.init = function()
  3410. {
  3411. $attach = $('#attach');
  3412. $burnAfterReading = $('#burnafterreading');
  3413. $burnAfterReadingOption = $('#burnafterreadingoption');
  3414. $cloneButton = $('#clonebutton');
  3415. $customAttachment = $('#customattachment');
  3416. $expiration = $('#expiration');
  3417. $fileRemoveButton = $('#fileremovebutton');
  3418. $fileWrap = $('#filewrap');
  3419. $formatter = $('#formatter');
  3420. $newButton = $('#newbutton');
  3421. $openDiscussion = $('#opendiscussion');
  3422. $openDiscussionOption = $('#opendiscussionoption');
  3423. $password = $('#password');
  3424. $passwordInput = $('#passwordinput');
  3425. $rawTextButton = $('#rawtextbutton');
  3426. $retryButton = $('#retrybutton');
  3427. $sendButton = $('#sendbutton');
  3428. $qrCodeLink = $('#qrcodelink');
  3429. // bootstrap template drop down
  3430. $('#language ul.dropdown-menu li a').click(setLanguage);
  3431. // page template drop down
  3432. $('#language select option').click(setLanguage);
  3433. // bind events
  3434. $burnAfterReading.change(changeBurnAfterReading);
  3435. $openDiscussionOption.change(changeOpenDiscussion);
  3436. $newButton.click(clickNewPaste);
  3437. $sendButton.click(PasteEncrypter.sendPaste);
  3438. $cloneButton.click(Controller.clonePaste);
  3439. $rawTextButton.click(rawText);
  3440. $retryButton.click(clickRetryButton);
  3441. $fileRemoveButton.click(removeAttachment);
  3442. $qrCodeLink.click(displayQrCode);
  3443. // bootstrap template drop downs
  3444. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  3445. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  3446. // initiate default state of checkboxes
  3447. changeBurnAfterReading();
  3448. changeOpenDiscussion();
  3449. // get default value from template or fall back to set value
  3450. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  3451. createButtonsDisplayed = false;
  3452. viewButtonsDisplayed = false;
  3453. };
  3454. return me;
  3455. })(window, document);
  3456. /**
  3457. * Responsible for AJAX requests, transparently handles encryption…
  3458. *
  3459. * @name ServerInteraction
  3460. * @class
  3461. */
  3462. const ServerInteraction = (function () {
  3463. const me = {};
  3464. let successFunc = null,
  3465. failureFunc = null,
  3466. symmetricKey = null,
  3467. url,
  3468. data,
  3469. password;
  3470. /**
  3471. * public variable ('constant') for errors to prevent magic numbers
  3472. *
  3473. * @name ServerInteraction.error
  3474. * @readonly
  3475. * @enum {Object}
  3476. */
  3477. me.error = {
  3478. okay: 0,
  3479. custom: 1,
  3480. unknown: 2,
  3481. serverError: 3
  3482. };
  3483. /**
  3484. * ajaxHeaders to send in AJAX requests
  3485. *
  3486. * @name ServerInteraction.ajaxHeaders
  3487. * @private
  3488. * @readonly
  3489. * @enum {Object}
  3490. */
  3491. const ajaxHeaders = {'X-Requested-With': 'JSONHttpRequest'};
  3492. /**
  3493. * called after successful upload
  3494. *
  3495. * @name ServerInteraction.success
  3496. * @private
  3497. * @function
  3498. * @param {int} status
  3499. * @param {int} result - optional
  3500. */
  3501. function success(status, result)
  3502. {
  3503. if (successFunc !== null) {
  3504. // add useful data to result
  3505. result.encryptionKey = symmetricKey;
  3506. successFunc(status, result);
  3507. }
  3508. }
  3509. /**
  3510. * called after a upload failure
  3511. *
  3512. * @name ServerInteraction.fail
  3513. * @private
  3514. * @function
  3515. * @param {int} status - internal code
  3516. * @param {int} result - original error code
  3517. */
  3518. function fail(status, result)
  3519. {
  3520. if (failureFunc !== null) {
  3521. failureFunc(status, result);
  3522. }
  3523. }
  3524. /**
  3525. * actually uploads the data
  3526. *
  3527. * @name ServerInteraction.run
  3528. * @function
  3529. */
  3530. me.run = function()
  3531. {
  3532. let isPost = Object.keys(data).length > 0,
  3533. ajaxParams = {
  3534. type: isPost ? 'POST' : 'GET',
  3535. url: url,
  3536. headers: ajaxHeaders,
  3537. dataType: 'json',
  3538. success: function(result) {
  3539. if (result.status === 0) {
  3540. success(0, result);
  3541. } else if (result.status === 1) {
  3542. fail(1, result);
  3543. } else {
  3544. fail(2, result);
  3545. }
  3546. }
  3547. };
  3548. if (isPost) {
  3549. ajaxParams.data = JSON.stringify(data);
  3550. }
  3551. $.ajax(ajaxParams).fail(function(jqXHR, textStatus, errorThrown) {
  3552. console.error(textStatus, errorThrown);
  3553. fail(3, jqXHR);
  3554. });
  3555. };
  3556. /**
  3557. * return currently set data, used in unit testing
  3558. *
  3559. * @name ServerInteraction.getData
  3560. * @function
  3561. */
  3562. me.getData = function()
  3563. {
  3564. return data;
  3565. };
  3566. /**
  3567. * set success function
  3568. *
  3569. * @name ServerInteraction.setUrl
  3570. * @function
  3571. * @param {function} newUrl
  3572. */
  3573. me.setUrl = function(newUrl)
  3574. {
  3575. url = newUrl;
  3576. };
  3577. /**
  3578. * sets the password to use (first value) and optionally also the
  3579. * encryption key (not recommended, it is automatically generated).
  3580. *
  3581. * Note: Call this after prepare() as prepare() resets these values.
  3582. *
  3583. * @name ServerInteraction.setCryptValues
  3584. * @function
  3585. * @param {string} newPassword
  3586. * @param {string} newKey - optional
  3587. */
  3588. me.setCryptParameters = function(newPassword, newKey)
  3589. {
  3590. password = newPassword;
  3591. if (typeof newKey !== 'undefined') {
  3592. symmetricKey = newKey;
  3593. }
  3594. };
  3595. /**
  3596. * set success function
  3597. *
  3598. * @name ServerInteraction.setSuccess
  3599. * @function
  3600. * @param {function} func
  3601. */
  3602. me.setSuccess = function(func)
  3603. {
  3604. successFunc = func;
  3605. };
  3606. /**
  3607. * set failure function
  3608. *
  3609. * @name ServerInteraction.setFailure
  3610. * @function
  3611. * @param {function} func
  3612. */
  3613. me.setFailure = function(func)
  3614. {
  3615. failureFunc = func;
  3616. };
  3617. /**
  3618. * prepares a new upload
  3619. *
  3620. * Call this when doing a new upload to reset any data from potential
  3621. * previous uploads. Must be called before any other method of this
  3622. * module.
  3623. *
  3624. * @name ServerInteraction.prepare
  3625. * @function
  3626. * @return {object}
  3627. */
  3628. me.prepare = function()
  3629. {
  3630. // entropy should already be checked!
  3631. // reset password
  3632. password = '';
  3633. // reset key, so it a new one is generated when it is used
  3634. symmetricKey = null;
  3635. // reset data
  3636. successFunc = null;
  3637. failureFunc = null;
  3638. url = Helper.baseUri();
  3639. data = {};
  3640. };
  3641. /**
  3642. * encrypts and sets the data
  3643. *
  3644. * @name ServerInteraction.setCipherMessage
  3645. * @async
  3646. * @function
  3647. * @param {object} cipherMessage
  3648. */
  3649. me.setCipherMessage = async function(cipherMessage)
  3650. {
  3651. if (
  3652. symmetricKey === null ||
  3653. (typeof symmetricKey === 'string' && symmetricKey === '')
  3654. ) {
  3655. symmetricKey = CryptTool.getSymmetricKey();
  3656. }
  3657. if (!data.hasOwnProperty('adata')) {
  3658. data['adata'] = [];
  3659. }
  3660. let cipherResult = await CryptTool.cipher(symmetricKey, password, JSON.stringify(cipherMessage), data['adata']);
  3661. data['v'] = 2;
  3662. data['ct'] = cipherResult[0];
  3663. data['adata'] = cipherResult[1];
  3664. };
  3665. /**
  3666. * set the additional metadata to send unencrypted
  3667. *
  3668. * @name ServerInteraction.setUnencryptedData
  3669. * @function
  3670. * @param {string} index
  3671. * @param {mixed} element
  3672. */
  3673. me.setUnencryptedData = function(index, element)
  3674. {
  3675. data[index] = element;
  3676. };
  3677. /**
  3678. * Helper, which parses shows a general error message based on the result of the ServerInteraction
  3679. *
  3680. * @name ServerInteraction.parseUploadError
  3681. * @function
  3682. * @param {int} status
  3683. * @param {object} data
  3684. * @param {string} doThisThing - a human description of the action, which was tried
  3685. * @return {array}
  3686. */
  3687. me.parseUploadError = function(status, data, doThisThing) {
  3688. let errorArray;
  3689. switch (status) {
  3690. case me.error.custom:
  3691. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  3692. break;
  3693. case me.error.unknown:
  3694. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  3695. break;
  3696. case me.error.serverError:
  3697. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  3698. break;
  3699. default:
  3700. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  3701. break;
  3702. }
  3703. return errorArray;
  3704. };
  3705. return me;
  3706. })();
  3707. /**
  3708. * (controller) Responsible for encrypting paste and sending it to server.
  3709. *
  3710. * Does upload, encryption is done transparently by ServerInteraction.
  3711. *
  3712. * @name PasteEncrypter
  3713. * @class
  3714. */
  3715. const PasteEncrypter = (function () {
  3716. const me = {};
  3717. let requirementsChecked = false;
  3718. /**
  3719. * called after successful paste upload
  3720. *
  3721. * @name PasteEncrypter.showCreatedPaste
  3722. * @private
  3723. * @function
  3724. * @param {int} status
  3725. * @param {object} data
  3726. */
  3727. function showCreatedPaste(status, data) {
  3728. Alert.hideLoading();
  3729. Alert.hideMessages();
  3730. // show notification
  3731. const baseUri = Helper.baseUri() + '?',
  3732. url = baseUri + data.id + '#' + CryptTool.base58encode(data.encryptionKey),
  3733. deleteUrl = baseUri + 'pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  3734. PasteStatus.createPasteNotification(url, deleteUrl);
  3735. // show new URL in browser bar
  3736. history.pushState({type: 'newpaste'}, document.title, url);
  3737. TopNav.showViewButtons();
  3738. TopNav.hideRawButton();
  3739. Editor.hide();
  3740. // parse and show text
  3741. // (preparation already done in me.sendPaste())
  3742. PasteViewer.run();
  3743. }
  3744. /**
  3745. * called after successful comment upload
  3746. *
  3747. * @name PasteEncrypter.showUploadedComment
  3748. * @private
  3749. * @function
  3750. * @param {int} status
  3751. * @param {object} data
  3752. */
  3753. function showUploadedComment(status, data) {
  3754. // show success message
  3755. Alert.showStatus('Comment posted.');
  3756. // reload paste
  3757. Controller.refreshPaste(function () {
  3758. // highlight sent comment
  3759. DiscussionViewer.highlightComment(data.id, true);
  3760. // reset error handler
  3761. Alert.setCustomHandler(null);
  3762. });
  3763. }
  3764. /**
  3765. * send a reply in a discussion
  3766. *
  3767. * @name PasteEncrypter.sendComment
  3768. * @async
  3769. * @function
  3770. */
  3771. me.sendComment = async function()
  3772. {
  3773. Alert.hideMessages();
  3774. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  3775. // UI loading state
  3776. TopNav.hideAllButtons();
  3777. Alert.showLoading('Sending comment…', 'cloud-upload');
  3778. // get data
  3779. const plainText = DiscussionViewer.getReplyMessage(),
  3780. nickname = DiscussionViewer.getReplyNickname(),
  3781. parentid = DiscussionViewer.getReplyCommentId();
  3782. // do not send if there is no data
  3783. if (plainText.length === 0) {
  3784. // revert loading status…
  3785. Alert.hideLoading();
  3786. Alert.setCustomHandler(null);
  3787. TopNav.showViewButtons();
  3788. return;
  3789. }
  3790. // prepare server interaction
  3791. ServerInteraction.prepare();
  3792. ServerInteraction.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  3793. // set success/fail functions
  3794. ServerInteraction.setSuccess(showUploadedComment);
  3795. ServerInteraction.setFailure(function (status, data) {
  3796. // revert loading status…
  3797. Alert.hideLoading();
  3798. TopNav.showViewButtons();
  3799. // …show error message…
  3800. Alert.showError(
  3801. ServerInteraction.parseUploadError(status, data, 'post comment')
  3802. );
  3803. // …and reset error handler
  3804. Alert.setCustomHandler(null);
  3805. });
  3806. // fill it with unencrypted params
  3807. ServerInteraction.setUnencryptedData('pasteid', Model.getPasteId());
  3808. if (typeof parentid === 'undefined') {
  3809. // if parent id is not set, this is the top-most comment, so use
  3810. // paste id as parent, as the root element of the discussion tree
  3811. ServerInteraction.setUnencryptedData('parentid', Model.getPasteId());
  3812. } else {
  3813. ServerInteraction.setUnencryptedData('parentid', parentid);
  3814. }
  3815. // prepare cypher message
  3816. let cipherMessage = {
  3817. 'comment': plainText
  3818. };
  3819. if (nickname.length > 0) {
  3820. cipherMessage['nickname'] = nickname;
  3821. }
  3822. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  3823. ServerInteraction.run();
  3824. };
  3825. /**
  3826. * sends a new paste to server
  3827. *
  3828. * @name PasteEncrypter.sendPaste
  3829. * @async
  3830. * @function
  3831. */
  3832. me.sendPaste = async function()
  3833. {
  3834. // hide previous (error) messages
  3835. Controller.hideStatusMessages();
  3836. // UI loading state
  3837. TopNav.hideAllButtons();
  3838. Alert.showLoading('Sending paste…', 'cloud-upload');
  3839. TopNav.collapseBar();
  3840. // get data
  3841. const plainText = Editor.getText(),
  3842. format = PasteViewer.getFormat(),
  3843. // the methods may return different values if no files are attached (null, undefined or false)
  3844. files = TopNav.getFileList() || AttachmentViewer.getFile() || AttachmentViewer.hasAttachment();
  3845. // do not send if there is no data
  3846. if (plainText.length === 0 && !files) {
  3847. // revert loading status…
  3848. Alert.hideLoading();
  3849. TopNav.showCreateButtons();
  3850. return;
  3851. }
  3852. // prepare server interaction
  3853. ServerInteraction.prepare();
  3854. ServerInteraction.setCryptParameters(TopNav.getPassword());
  3855. // set success/fail functions
  3856. ServerInteraction.setSuccess(showCreatedPaste);
  3857. ServerInteraction.setFailure(function (status, data) {
  3858. // revert loading status…
  3859. Alert.hideLoading();
  3860. TopNav.showCreateButtons();
  3861. // show error message
  3862. Alert.showError(
  3863. ServerInteraction.parseUploadError(status, data, 'create paste')
  3864. );
  3865. });
  3866. // fill it with unencrypted submitted options
  3867. ServerInteraction.setUnencryptedData('adata', [
  3868. null, format,
  3869. TopNav.getOpenDiscussion() ? 1 : 0,
  3870. TopNav.getBurnAfterReading() ? 1 : 0
  3871. ]);
  3872. ServerInteraction.setUnencryptedData('meta', {'expire': TopNav.getExpiration()});
  3873. // prepare PasteViewer for later preview
  3874. PasteViewer.setText(plainText);
  3875. PasteViewer.setFormat(format);
  3876. // prepare cypher message
  3877. let file = AttachmentViewer.getAttachmentData(),
  3878. cipherMessage = {
  3879. 'paste': plainText
  3880. };
  3881. if (typeof file !== 'undefined' && file !== null) {
  3882. cipherMessage['attachment'] = file;
  3883. cipherMessage['attachment_name'] = AttachmentViewer.getFile().name;
  3884. } else if (AttachmentViewer.hasAttachment()) {
  3885. // fall back to cloned part
  3886. let attachment = AttachmentViewer.getAttachment();
  3887. cipherMessage['attachment'] = attachment[0];
  3888. cipherMessage['attachment_name'] = attachment[1];
  3889. }
  3890. // encrypt message
  3891. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  3892. // send data
  3893. ServerInteraction.run();
  3894. };
  3895. return me;
  3896. })();
  3897. /**
  3898. * (controller) Responsible for decrypting cipherdata and passing data to view.
  3899. *
  3900. * Only decryption, no download.
  3901. *
  3902. * @name PasteDecrypter
  3903. * @class
  3904. */
  3905. const PasteDecrypter = (function () {
  3906. const me = {};
  3907. /**
  3908. * decrypt data or prompts for password in case of failure
  3909. *
  3910. * @name PasteDecrypter.decryptOrPromptPassword
  3911. * @private
  3912. * @async
  3913. * @function
  3914. * @param {string} key
  3915. * @param {string} password - optional, may be an empty string
  3916. * @param {string} cipherdata
  3917. * @throws {string}
  3918. * @return {false|string} false, when unsuccessful or string (decrypted data)
  3919. */
  3920. async function decryptOrPromptPassword(key, password, cipherdata)
  3921. {
  3922. // try decryption without password
  3923. const plaindata = await CryptTool.decipher(key, password, cipherdata);
  3924. // if it fails, request password
  3925. if (plaindata.length === 0 && password.length === 0) {
  3926. // show prompt
  3927. Prompt.requestPassword();
  3928. // Thus, we cannot do anything yet, we need to wait for the user
  3929. // input.
  3930. return false;
  3931. }
  3932. // if all tries failed, we can only return an error
  3933. if (plaindata.length === 0) {
  3934. throw 'failed to decipher data';
  3935. }
  3936. return plaindata;
  3937. }
  3938. /**
  3939. * decrypt the actual paste text
  3940. *
  3941. * @name PasteDecrypter.decryptPaste
  3942. * @private
  3943. * @async
  3944. * @function
  3945. * @param {Paste} paste - paste data in object form
  3946. * @param {string} key
  3947. * @param {string} password
  3948. * @throws {string}
  3949. * @return {Promise}
  3950. */
  3951. async function decryptPaste(paste, key, password)
  3952. {
  3953. let pastePlain = await decryptOrPromptPassword(
  3954. key, password,
  3955. paste.getCipherData()
  3956. );
  3957. if (pastePlain === false) {
  3958. if (password.length === 0) {
  3959. throw 'waiting on user to provide a password';
  3960. } else {
  3961. displayDecryptionError('failed to decipher paste text: Incorrect password?');
  3962. throw 'waiting on user to provide correct password';
  3963. }
  3964. }
  3965. let format = '',
  3966. text = '';
  3967. if (paste.v > 1) {
  3968. // version 2 paste
  3969. const pasteMessage = JSON.parse(pastePlain);
  3970. if (pasteMessage.hasOwnProperty('attachment') && pasteMessage.hasOwnProperty('attachment_name')) {
  3971. AttachmentViewer.setAttachment(pasteMessage.attachment, pasteMessage.attachment_name);
  3972. AttachmentViewer.showAttachment();
  3973. }
  3974. pastePlain = pasteMessage.paste;
  3975. } else {
  3976. // version 1 paste
  3977. if (paste.hasOwnProperty('attachment') && paste.hasOwnProperty('attachmentname')) {
  3978. Promise.all([
  3979. CryptTool.decipher(key, password, paste.attachment),
  3980. CryptTool.decipher(key, password, paste.attachmentname)
  3981. ]).then((attachment) => {
  3982. AttachmentViewer.setAttachment(attachment[0], attachment[1]);
  3983. AttachmentViewer.showAttachment();
  3984. });
  3985. }
  3986. }
  3987. PasteViewer.setFormat(paste.getFormat());
  3988. PasteViewer.setText(pastePlain);
  3989. PasteViewer.run();
  3990. }
  3991. /**
  3992. * decrypts all comments and shows them
  3993. *
  3994. * @name PasteDecrypter.decryptComments
  3995. * @private
  3996. * @async
  3997. * @function
  3998. * @param {Paste} paste - paste data in object form
  3999. * @param {string} key
  4000. * @param {string} password
  4001. * @return {Promise}
  4002. */
  4003. async function decryptComments(paste, key, password)
  4004. {
  4005. // remove potential previous discussion
  4006. DiscussionViewer.prepareNewDiscussion();
  4007. const commentDecryptionPromises = [];
  4008. // iterate over comments
  4009. for (let i = 0; i < paste.comments.length; ++i) {
  4010. const comment = new Comment(paste.comments[i]),
  4011. commentPromise = CryptTool.decipher(key, password, comment.getCipherData());
  4012. paste.comments[i] = comment;
  4013. if (comment.v > 1) {
  4014. // version 2 comment
  4015. commentDecryptionPromises.push(
  4016. commentPromise.then(function (commentJson) {
  4017. const commentMessage = JSON.parse(commentJson);
  4018. return [
  4019. commentMessage.comment || '',
  4020. commentMessage.nickname || ''
  4021. ];
  4022. })
  4023. );
  4024. } else {
  4025. // version 1 comment
  4026. commentDecryptionPromises.push(
  4027. Promise.all([
  4028. commentPromise,
  4029. paste.comments[i].meta.hasOwnProperty('nickname') ?
  4030. CryptTool.decipher(key, password, paste.comments[i].meta.nickname) :
  4031. Promise.resolve('')
  4032. ])
  4033. );
  4034. }
  4035. }
  4036. return Promise.all(commentDecryptionPromises).then(function (plaintexts) {
  4037. for (let i = 0; i < paste.comments.length; ++i) {
  4038. if (plaintexts[i][0].length === 0) {
  4039. continue;
  4040. }
  4041. DiscussionViewer.addComment(
  4042. paste.comments[i],
  4043. plaintexts[i][0],
  4044. plaintexts[i][1]
  4045. );
  4046. }
  4047. DiscussionViewer.finishDiscussion();
  4048. });
  4049. }
  4050. /**
  4051. * displays and logs decryption errors
  4052. *
  4053. * @name PasteDecrypter.displayDecryptionError
  4054. * @private
  4055. * @function
  4056. * @param {string} message
  4057. */
  4058. function displayDecryptionError(message)
  4059. {
  4060. Alert.hideLoading();
  4061. // log detailed error, but display generic translation
  4062. console.error(message);
  4063. Alert.showError('Could not decrypt data. Did you enter a wrong password? Retry with the button at the top.');
  4064. // reset password, so it can be re-entered
  4065. Prompt.reset();
  4066. TopNav.showRetryButton();
  4067. }
  4068. /**
  4069. * show decrypted text in the display area, including discussion (if open)
  4070. *
  4071. * @name PasteDecrypter.run
  4072. * @function
  4073. * @param {Paste} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  4074. */
  4075. me.run = function(paste)
  4076. {
  4077. Alert.hideMessages();
  4078. Alert.showLoading('Decrypting paste…', 'cloud-download');
  4079. if (typeof paste === 'undefined') {
  4080. // get cipher data and wait until it is available
  4081. Model.getPasteData(me.run);
  4082. return;
  4083. }
  4084. let key = Model.getPasteKey(),
  4085. password = Prompt.getPassword(),
  4086. decryptionPromises = [];
  4087. TopNav.setRetryCallback(function () {
  4088. TopNav.hideRetryButton();
  4089. me.run(paste);
  4090. });
  4091. // decrypt paste & attachments
  4092. decryptionPromises.push(decryptPaste(paste, key, password));
  4093. // if the discussion is opened on this paste, display it
  4094. if (paste.isDiscussionEnabled()) {
  4095. decryptionPromises.push(decryptComments(paste, key, password));
  4096. }
  4097. // shows the remaining time (until) deletion
  4098. PasteStatus.showRemainingTime(paste);
  4099. Promise.all(decryptionPromises)
  4100. .then(() => {
  4101. Alert.hideLoading();
  4102. TopNav.showViewButtons();
  4103. })
  4104. .catch((err) => {
  4105. // wait for the user to type in the password,
  4106. // then PasteDecrypter.run will be called again
  4107. console.error(err);
  4108. });
  4109. };
  4110. return me;
  4111. })();
  4112. /**
  4113. * (controller) main PrivateBin logic
  4114. *
  4115. * @name Controller
  4116. * @param {object} window
  4117. * @param {object} document
  4118. * @class
  4119. */
  4120. const Controller = (function (window, document) {
  4121. const me = {};
  4122. /**
  4123. * hides all status messages no matter which module showed them
  4124. *
  4125. * @name Controller.hideStatusMessages
  4126. * @function
  4127. */
  4128. me.hideStatusMessages = function()
  4129. {
  4130. PasteStatus.hideMessages();
  4131. Alert.hideMessages();
  4132. };
  4133. /**
  4134. * creates a new paste
  4135. *
  4136. * @name Controller.newPaste
  4137. * @function
  4138. */
  4139. me.newPaste = function()
  4140. {
  4141. // Important: This *must not* run Alert.hideMessages() as previous
  4142. // errors from viewing a paste should be shown.
  4143. TopNav.hideAllButtons();
  4144. Alert.showLoading('Preparing new paste…', 'time');
  4145. PasteStatus.hideMessages();
  4146. PasteViewer.hide();
  4147. Editor.resetInput();
  4148. Editor.show();
  4149. Editor.focusInput();
  4150. AttachmentViewer.removeAttachment();
  4151. TopNav.showCreateButtons();
  4152. Alert.hideLoading();
  4153. };
  4154. /**
  4155. * shows how we much we love bots that execute JS ;)
  4156. *
  4157. * @name Controller.showBadBotMessage
  4158. * @function
  4159. */
  4160. me.showBadBotMessage = function()
  4161. {
  4162. TopNav.hideAllButtons();
  4163. Alert.showError('I love you too, bot…');
  4164. }
  4165. /**
  4166. * shows the loaded paste
  4167. *
  4168. * @name Controller.showPaste
  4169. * @function
  4170. */
  4171. me.showPaste = function()
  4172. {
  4173. try {
  4174. Model.getPasteKey();
  4175. } catch (err) {
  4176. console.error(err);
  4177. // missing decryption key (or paste ID) in URL?
  4178. if (window.location.hash.length === 0) {
  4179. Alert.showError('Cannot decrypt paste: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL?)');
  4180. return;
  4181. }
  4182. }
  4183. // show proper elements on screen
  4184. PasteDecrypter.run();
  4185. };
  4186. /**
  4187. * refreshes the loaded paste to show potential new data
  4188. *
  4189. * @name Controller.refreshPaste
  4190. * @function
  4191. * @param {function} callback
  4192. */
  4193. me.refreshPaste = function(callback)
  4194. {
  4195. // save window position to restore it later
  4196. const orgPosition = $(window).scrollTop();
  4197. Model.getPasteData(function (data) {
  4198. ServerInteraction.prepare();
  4199. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + Model.getPasteId());
  4200. ServerInteraction.setFailure(function (status, data) {
  4201. // revert loading status…
  4202. Alert.hideLoading();
  4203. TopNav.showViewButtons();
  4204. // show error message
  4205. Alert.showError(
  4206. ServerInteraction.parseUploadError(status, data, 'refresh display')
  4207. );
  4208. });
  4209. ServerInteraction.setSuccess(function (status, data) {
  4210. PasteDecrypter.run(new Paste(data));
  4211. // restore position
  4212. window.scrollTo(0, orgPosition);
  4213. // NOTE: could create problems as callback may be called
  4214. // asyncronously if PasteDecrypter e.g. needs to wait for a
  4215. // password being entered
  4216. callback();
  4217. });
  4218. ServerInteraction.run();
  4219. }, false); // this false is important as it circumvents the cache
  4220. }
  4221. /**
  4222. * clone the current paste
  4223. *
  4224. * @name Controller.clonePaste
  4225. * @function
  4226. */
  4227. me.clonePaste = function()
  4228. {
  4229. TopNav.collapseBar();
  4230. TopNav.hideAllButtons();
  4231. // hide messages from previous paste
  4232. me.hideStatusMessages();
  4233. // erase the id and the key in url
  4234. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  4235. if (AttachmentViewer.hasAttachment()) {
  4236. AttachmentViewer.moveAttachmentTo(
  4237. TopNav.getCustomAttachment(),
  4238. 'Cloned: \'%s\''
  4239. );
  4240. TopNav.hideFileSelector();
  4241. AttachmentViewer.hideAttachment();
  4242. // NOTE: it also looks nice without removing the attachment
  4243. // but for a consistent display we remove it…
  4244. AttachmentViewer.hideAttachmentPreview();
  4245. TopNav.showCustomAttachment();
  4246. // show another status message to make the user aware that the
  4247. // file was cloned too!
  4248. Alert.showStatus(
  4249. [
  4250. 'The cloned file \'%s\' was attached to this paste.',
  4251. AttachmentViewer.getAttachment()[1]
  4252. ],
  4253. 'copy'
  4254. );
  4255. }
  4256. Editor.setText(PasteViewer.getText());
  4257. PasteViewer.hide();
  4258. Editor.show();
  4259. TopNav.showCreateButtons();
  4260. };
  4261. /**
  4262. * application start
  4263. *
  4264. * @name Controller.init
  4265. * @function
  4266. */
  4267. me.init = async function()
  4268. {
  4269. // first load translations
  4270. I18n.loadTranslations();
  4271. DOMPurify.setConfig({SAFE_FOR_JQUERY: true});
  4272. // initialize other modules/"classes"
  4273. Alert.init();
  4274. Model.init();
  4275. AttachmentViewer.init();
  4276. DiscussionViewer.init();
  4277. Editor.init();
  4278. PasteStatus.init();
  4279. PasteViewer.init();
  4280. Prompt.init();
  4281. TopNav.init();
  4282. UiHelper.init();
  4283. z = (await zlib);
  4284. // check whether existing paste needs to be shown
  4285. try {
  4286. Model.getPasteId();
  4287. } catch (e) {
  4288. // otherwise create a new paste
  4289. return me.newPaste();
  4290. }
  4291. // if delete token is passed (i.e. paste has been deleted by this access)
  4292. // there is no more stuf we need to do
  4293. if (Model.hasDeleteToken()) {
  4294. return;
  4295. }
  4296. // prevent bots from viewing a paste and potentially deleting data
  4297. // when burn-after-reading is set
  4298. // see https://github.com/elrido/ZeroBin/issues/11
  4299. if (Helper.isBadBot()) {
  4300. return me.showBadBotMessage();
  4301. }
  4302. // display an existing paste
  4303. return me.showPaste();
  4304. }
  4305. return me;
  4306. })(window, document);
  4307. return {
  4308. Helper: Helper,
  4309. I18n: I18n,
  4310. CryptTool: CryptTool,
  4311. Model: Model,
  4312. UiHelper: UiHelper,
  4313. Alert: Alert,
  4314. PasteStatus: PasteStatus,
  4315. Prompt: Prompt,
  4316. Editor: Editor,
  4317. PasteViewer: PasteViewer,
  4318. AttachmentViewer: AttachmentViewer,
  4319. DiscussionViewer: DiscussionViewer,
  4320. TopNav: TopNav,
  4321. ServerInteraction: ServerInteraction,
  4322. PasteEncrypter: PasteEncrypter,
  4323. PasteDecrypter: PasteDecrypter,
  4324. Controller: Controller
  4325. };
  4326. })(jQuery, RawDeflate);