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