privatebin.js 166 KB

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