privatebin.js 201 KB

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