privatebin.js 172 KB

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