privatebin.js 164 KB

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