privatebin.js 202 KB

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