privatebin.js 169 KB

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