privatebin.js 203 KB

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