privatebin.js 200 KB

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