privatebin.js 198 KB

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