privatebin.js 165 KB

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