privatebin.js 165 KB

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