privatebin.js 166 KB

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