privatebin.js 168 KB

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