privatebin.js 175 KB

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