privatebin.js 165 KB

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