privatebin.js 171 KB

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