privatebin.js 166 KB

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