privatebin.js 169 KB

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