privatebin.js 202 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162
  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.originalEvent.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. * trigger a history (pop) state change
  1494. *
  1495. * used to test the UiHelper.historyChange private function
  1496. *
  1497. * @name UiHelper.mockHistoryChange
  1498. * @function
  1499. * @param {string} state (optional) state to mock
  1500. */
  1501. me.mockHistoryChange = function (state) {
  1502. if (typeof state === 'undefined') {
  1503. state = null;
  1504. }
  1505. historyChange({ originalEvent: new PopStateEvent('popstate', { state: state }), target: window });
  1506. };
  1507. /**
  1508. * initialize
  1509. *
  1510. * @name UiHelper.init
  1511. * @function
  1512. */
  1513. me.init = function () {
  1514. // update link to home page
  1515. document.querySelectorAll('.reloadlink').forEach(link => (link.href = Helper.baseUri()));
  1516. window.addEventListener('popstate', historyChange);
  1517. };
  1518. return me;
  1519. })();
  1520. /**
  1521. * Alert/error manager
  1522. *
  1523. * @name Alert
  1524. * @class
  1525. */
  1526. const Alert = (function () {
  1527. const me = {};
  1528. let errorMessage,
  1529. loadingIndicator,
  1530. statusMessage,
  1531. remainingTime,
  1532. currentIcon,
  1533. customHandler;
  1534. const alertType = [
  1535. 'loading', // not in bootstrap CSS, but using a plausible value here
  1536. 'info', // status icon
  1537. 'warning', // warning icon
  1538. 'danger' // error icon
  1539. ];
  1540. /**
  1541. * forwards a request to the i18n module and shows the element
  1542. *
  1543. * @name Alert.handleNotification
  1544. * @private
  1545. * @function
  1546. * @param {number} id - id of notification
  1547. * @param {HTMLElement} element - HTML element
  1548. * @param {string|array} args
  1549. * @param {string|null} icon - optional, icon
  1550. */
  1551. function handleNotification(id, element, args, icon) {
  1552. // basic parsing/conversion of parameters
  1553. if (typeof icon === 'undefined') {
  1554. icon = null;
  1555. }
  1556. if (typeof args === 'undefined') {
  1557. args = null;
  1558. } else if (typeof args === 'string') {
  1559. // convert string to array if needed
  1560. args = [args];
  1561. } else if (args instanceof Error) {
  1562. // extract message into array if needed
  1563. args = [args.message];
  1564. }
  1565. // function guard
  1566. if (!element) {
  1567. throw new TypeError(`invalid/no element (${element}) given for alert type ${alertType[id]} with ID ${id}`);
  1568. }
  1569. // pass to custom handler if defined
  1570. if (typeof customHandler === 'function') {
  1571. let handlerResult = customHandler(alertType[id], element, args, icon);
  1572. if (handlerResult === true) {
  1573. // if it returns true, skip own handler
  1574. return;
  1575. }
  1576. if (handlerResult instanceof HTMLElement) {
  1577. // continue processing with new element
  1578. element = handlerResult;
  1579. icon = null; // icons not supported in this case
  1580. }
  1581. }
  1582. let translationTarget = element;
  1583. // handle icon, if template uses one
  1584. const glyphIcon = element.querySelector(':first-child');
  1585. if (glyphIcon) {
  1586. // if there is an icon, we need to provide an inner element
  1587. // to translate the message into, instead of the parent
  1588. translationTarget = document.createElement('span');
  1589. element.innerHTML = ' ';
  1590. element.prepend(glyphIcon);
  1591. element.appendChild(translationTarget);
  1592. if (icon !== null && // icon was passed
  1593. icon !== currentIcon[id] // and it differs from current icon
  1594. ) {
  1595. // remove (previous) icon
  1596. glyphIcon.classList.remove(currentIcon[id]);
  1597. // any other thing as a string (e.g. 'null') (only) removes the icon
  1598. if (typeof icon === 'string') {
  1599. // set new icon
  1600. currentIcon[id] = 'glyphicon-' + icon;
  1601. glyphIcon.classList.add(currentIcon[id]);
  1602. }
  1603. }
  1604. }
  1605. // translate and insert message
  1606. I18n._(translationTarget, ...args);
  1607. // show element
  1608. element.classList.remove('hidden');
  1609. }
  1610. /**
  1611. * display a status message
  1612. *
  1613. * This automatically passes the text to I18n for translation.
  1614. *
  1615. * @name Alert.showStatus
  1616. * @function
  1617. * @param {string|array} message string, use an array for %s/%d options
  1618. * @param {string|null} icon optional, the icon to show,
  1619. * default: leave previous icon
  1620. */
  1621. me.showStatus = function (message, icon) {
  1622. handleNotification(1, statusMessage, message, icon);
  1623. };
  1624. /**
  1625. * display a warning message
  1626. *
  1627. * This automatically passes the text to I18n for translation.
  1628. *
  1629. * @name Alert.showWarning
  1630. * @function
  1631. * @param {string|array} message string, use an array for %s/%d options
  1632. * @param {string|null} icon optional, the icon to show, default:
  1633. * leave previous icon
  1634. */
  1635. me.showWarning = function (message, icon) {
  1636. const glyphIcon = errorMessage.querySelector(':first-child');
  1637. if (glyphIcon) {
  1638. glyphIcon.classList.remove(currentIcon[3]);
  1639. glyphIcon.classList.add(currentIcon[2]);
  1640. }
  1641. handleNotification(2, errorMessage, message, icon);
  1642. };
  1643. /**
  1644. * display an error message
  1645. *
  1646. * This automatically passes the text to I18n for translation.
  1647. *
  1648. * @name Alert.showError
  1649. * @function
  1650. * @param {string|array} message string, use an array for %s/%d options
  1651. * @param {string|null} icon optional, the icon to show, default:
  1652. * leave previous icon
  1653. */
  1654. me.showError = function (message, icon) {
  1655. handleNotification(3, errorMessage, message, icon);
  1656. };
  1657. /**
  1658. * display remaining message
  1659. *
  1660. * This automatically passes the text to I18n for translation.
  1661. *
  1662. * @name Alert.showRemaining
  1663. * @function
  1664. * @param {string|array} message string, use an array for %s/%d options
  1665. */
  1666. me.showRemaining = function (message) {
  1667. handleNotification(1, remainingTime, message);
  1668. };
  1669. /**
  1670. * shows a loading message, optionally with a percentage
  1671. *
  1672. * This automatically passes all texts to the i10s module.
  1673. *
  1674. * @name Alert.showLoading
  1675. * @function
  1676. * @param {string|array|null} message optional, use an array for %s/%d options, default: 'Loading…'
  1677. * @param {string|null} icon optional, the icon to show, default: leave previous icon
  1678. */
  1679. me.showLoading = function (message, icon) {
  1680. // default message text
  1681. if (typeof message === 'undefined') {
  1682. message = 'Loading…';
  1683. }
  1684. handleNotification(0, loadingIndicator, message, icon);
  1685. // show loading status (cursor)
  1686. document.body.classList.add('loading');
  1687. };
  1688. /**
  1689. * hides the loading message
  1690. *
  1691. * @name Alert.hideLoading
  1692. * @function
  1693. */
  1694. me.hideLoading = function () {
  1695. loadingIndicator.classList.add('hidden');
  1696. // hide loading cursor
  1697. document.body.classList.remove('loading');
  1698. };
  1699. /**
  1700. * hides any status/error messages
  1701. *
  1702. * This does not include the loading message.
  1703. *
  1704. * @name Alert.hideMessages
  1705. * @function
  1706. */
  1707. me.hideMessages = function () {
  1708. statusMessage.classList.add('hidden');
  1709. errorMessage.classList.add('hidden');
  1710. };
  1711. /**
  1712. * set a custom handler, which gets all notifications.
  1713. *
  1714. * This handler gets the following arguments:
  1715. * alertType (see array), $element, args, icon
  1716. * If it returns true, the own processing will be stopped so the message
  1717. * will not be displayed. Otherwise it will continue.
  1718. * As an aditional feature it can return a HTMLElement, which will
  1719. * then be used to add the message there. Icons are not supported in
  1720. * that case and will be ignored.
  1721. * Pass 'null' to reset/delete the custom handler.
  1722. * Note that there is no notification when a message is supposed to get
  1723. * hidden.
  1724. *
  1725. * @name Alert.setCustomHandler
  1726. * @function
  1727. * @param {function|null} newHandler
  1728. */
  1729. me.setCustomHandler = function (newHandler) {
  1730. customHandler = newHandler;
  1731. };
  1732. /**
  1733. * init status manager
  1734. *
  1735. * preloads HTMLElements
  1736. *
  1737. * @name Alert.init
  1738. * @function
  1739. */
  1740. me.init = function () {
  1741. // hide "no javascript" error message (guard in test environments)
  1742. const noscriptEl = document.getElementById('noscript');
  1743. if (noscriptEl) {
  1744. noscriptEl.style.display = 'none';
  1745. }
  1746. // not a reset, but first set of the elements
  1747. errorMessage = document.getElementById('errormessage');
  1748. loadingIndicator = document.getElementById('loadingindicator');
  1749. statusMessage = document.getElementById('status');
  1750. remainingTime = document.getElementById('remainingtime');
  1751. currentIcon = [
  1752. 'glyphicon-time', // loading icon
  1753. 'glyphicon-info-sign', // status icon
  1754. 'glyphicon-warning-sign', // warning icon
  1755. 'glyphicon-alert' // error icon
  1756. ];
  1757. };
  1758. return me;
  1759. })();
  1760. /**
  1761. * handles paste status/result
  1762. *
  1763. * @name PasteStatus
  1764. * @class
  1765. */
  1766. const PasteStatus = (function () {
  1767. const me = {};
  1768. let pasteSuccess,
  1769. pasteUrl,
  1770. remainingTime,
  1771. shortenButton;
  1772. /**
  1773. * forward to URL shortener
  1774. *
  1775. * @name PasteStatus.sendToShortener
  1776. * @private
  1777. * @function
  1778. */
  1779. function sendToShortener() {
  1780. if (shortenButton.classList.contains('buttondisabled')) {
  1781. return;
  1782. }
  1783. fetch(`${shortenButton.dataset.shortener}${encodeURIComponent(pasteUrl.href)}`, {
  1784. method: 'GET',
  1785. headers: { 'Accept': 'text/html, application/xhtml+xml, application/xml, application/json' },
  1786. credentials: 'omit',
  1787. signal: AbortSignal.timeout(10000)
  1788. })
  1789. .then(response => {
  1790. if (!response.ok) {
  1791. throw new Error('HTTP ' + response.status);
  1792. }
  1793. return response.text();
  1794. })
  1795. .then(data => PasteStatus.extractUrl(data))
  1796. .catch(error => {
  1797. console.error('Shortener error:', error);
  1798. // we don't know why it failed, could be CORS of the external
  1799. // server not setup properly, in which case we follow old
  1800. // behavior to open it in new tab
  1801. window.open(
  1802. `${shortenButton.dataset.shortener}${encodeURIComponent(pasteUrl.href)}`,
  1803. '_blank',
  1804. 'noopener, noreferrer'
  1805. );
  1806. });
  1807. }
  1808. /**
  1809. * Forces opening the document if the link does not do this automatically.
  1810. *
  1811. * This is necessary as browsers will not reload the page when it is
  1812. * already loaded (which is fake as it is set via history.pushState()).
  1813. *
  1814. * @name PasteStatus.pasteLinkClick
  1815. * @function
  1816. */
  1817. function pasteLinkClick() {
  1818. // check if location is (already) shown in URL bar
  1819. if (window.location.href === pasteUrl.href) {
  1820. // if so we need to load link by reloading the current site
  1821. window.location.reload(true);
  1822. }
  1823. }
  1824. /**
  1825. * creates a notification after a successful document upload
  1826. *
  1827. * @name PasteStatus.createPasteNotification
  1828. * @function
  1829. * @param {string} url
  1830. * @param {string} deleteUrl
  1831. */
  1832. me.createPasteNotification = function(url, deleteUrl)
  1833. {
  1834. const ua = navigator.userAgent;
  1835. const isMac = /Mac/.test(ua);
  1836. const hotkey = isMac ? I18n._('Cmd') : I18n._('Ctrl');
  1837. I18n._(
  1838. document.getElementById('pastelink'),
  1839. 'Your document is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit <kbd>%s</kbd>+<kbd>c</kbd> to copy)</span>',
  1840. url, url, hotkey
  1841. );
  1842. // save newly created element
  1843. pasteUrl = document.getElementById('pasteurl');
  1844. // and add click event
  1845. if (pasteUrl) {
  1846. pasteUrl.addEventListener('click', pasteLinkClick);
  1847. }
  1848. // delete link
  1849. const deleteLink = document.getElementById('deletelink');
  1850. if (deleteLink) {
  1851. deleteLink.href = deleteUrl;
  1852. }
  1853. I18n._(document.querySelector('#deletelink span:not(.glyphicon)'), 'Delete data');
  1854. // enable shortener button
  1855. if (shortenButton) {
  1856. shortenButton.classList.remove('buttondisabled');
  1857. }
  1858. // show result
  1859. if (pasteSuccess) {
  1860. pasteSuccess.classList.remove('hidden');
  1861. }
  1862. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1863. Helper.selectText(pasteUrl);
  1864. };
  1865. /**
  1866. * Checks if auto-shortening is enabled and sends the link to the shortener if it is.
  1867. *
  1868. * @name PasteStatus.checkAutoShorten
  1869. * @function
  1870. */
  1871. me.checkAutoShorten = function () {
  1872. // check if auto-shortening is enabled
  1873. if (shortenButton && shortenButton.dataset.autoshorten === 'true') {
  1874. // if so, we send the link to the shortener
  1875. // we do not remove the button, in case shortener fails
  1876. sendToShortener();
  1877. }
  1878. };
  1879. /**
  1880. * extracts URLs from given string
  1881. *
  1882. * if at least one is found, it disables the shortener button and
  1883. * replaces the document URL
  1884. *
  1885. * @name PasteStatus.extractUrl
  1886. * @function
  1887. * @param {string} response
  1888. */
  1889. me.extractUrl = function (response) {
  1890. if (typeof response === 'object') {
  1891. response = JSON.stringify(response);
  1892. }
  1893. if (typeof response === 'string' && response.length > 0) {
  1894. const shortUrlMatcher = /https?:\/\/[^\s"<]+/g; // JSON API will have URL in quotes, XML in tags
  1895. const shortUrl = (response.match(shortUrlMatcher) || []).filter(function (urlRegExMatch) {
  1896. if (typeof URL.canParse === 'function') {
  1897. return URL.canParse(urlRegExMatch);
  1898. }
  1899. // polyfill for older browsers (< 120) & node (< 19.9 & < 18.17)
  1900. try {
  1901. return !!new URL(urlRegExMatch);
  1902. } catch (error) {
  1903. return false;
  1904. }
  1905. }).sort(function (a, b) {
  1906. return a.length - b.length; // shortest first
  1907. })[0];
  1908. if (typeof shortUrl === 'string' && shortUrl.length > 0) {
  1909. // we disable the button to avoid calling shortener again
  1910. if (shortenButton) {
  1911. shortenButton.classList.add('buttondisabled');
  1912. }
  1913. // update link
  1914. pasteUrl.textContent = shortUrl;
  1915. pasteUrl.href = shortUrl;
  1916. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1917. Helper.selectText(pasteUrl);
  1918. CopyToClipboard.setUrl(shortUrl);
  1919. return;
  1920. }
  1921. }
  1922. Alert.showError('Cannot parse response from URL shortener.');
  1923. };
  1924. /**
  1925. * shows the remaining time
  1926. *
  1927. * @name PasteStatus.showRemainingTime
  1928. * @function
  1929. * @param {Paste} paste
  1930. */
  1931. me.showRemainingTime = function (paste) {
  1932. if (paste.isBurnAfterReadingEnabled()) {
  1933. // display document "for your eyes only" if it is deleted
  1934. // the document has been deleted when the JSON with the ciphertext
  1935. // has been downloaded
  1936. Alert.showRemaining('FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.');
  1937. remainingTime.classList.add('foryoureyesonly');
  1938. } else if (paste.getTimeToLive() > 0) {
  1939. // display document expiration
  1940. let expiration = Helper.secondsToHuman(paste.getTimeToLive()),
  1941. expirationLabel = [
  1942. 'This document will expire in %d ' + expiration[1] + '.',
  1943. 'This document will expire in %d ' + expiration[1] + 's.'
  1944. ];
  1945. Alert.showRemaining([expirationLabel, expiration[0]]);
  1946. remainingTime.classList.remove('foryoureyesonly');
  1947. } else {
  1948. // never expires
  1949. return;
  1950. }
  1951. // in the end, display notification
  1952. remainingTime.classList.remove('hidden');
  1953. };
  1954. /**
  1955. * hides the remaining time and successful upload notification
  1956. *
  1957. * @name PasteStatus.hideMessages
  1958. * @function
  1959. */
  1960. me.hideMessages = function () {
  1961. remainingTime.classList.add('hidden');
  1962. pasteSuccess.classList.add('hidden');
  1963. };
  1964. /**
  1965. * init status manager
  1966. *
  1967. * preloads HTMLElements
  1968. *
  1969. * @name PasteStatus.init
  1970. * @function
  1971. */
  1972. me.init = function () {
  1973. pasteSuccess = document.getElementById('pastesuccess');
  1974. // pasteUrl is saved in me.createPasteNotification() after creation
  1975. remainingTime = document.getElementById('remainingtime');
  1976. shortenButton = document.getElementById('shortenbutton');
  1977. // bind elements
  1978. if (shortenButton) {
  1979. shortenButton.addEventListener('click', sendToShortener);
  1980. }
  1981. };
  1982. return me;
  1983. })();
  1984. /**
  1985. * password prompt
  1986. *
  1987. * @name Prompt
  1988. * @class
  1989. */
  1990. const Prompt = (function () {
  1991. const me = {};
  1992. let passwordDecrypt,
  1993. passwordModal,
  1994. bootstrap5PasswordModal = null,
  1995. password = '';
  1996. /**
  1997. * submit a password in the modal dialog
  1998. *
  1999. * @name Prompt.submitPasswordModal
  2000. * @private
  2001. * @function
  2002. * @param {Event} event
  2003. */
  2004. function submitPasswordModal(event) {
  2005. event.preventDefault();
  2006. // get input
  2007. password = passwordDecrypt.value;
  2008. // hide modal
  2009. if (bootstrap5PasswordModal) {
  2010. bootstrap5PasswordModal.hide();
  2011. } else {
  2012. if (passwordModal) {
  2013. passwordModal.classList.remove('show');
  2014. passwordModal.style.display = 'none';
  2015. }
  2016. }
  2017. PasteDecrypter.run();
  2018. }
  2019. /**
  2020. * Request users confirmation to load possibly burn after reading document
  2021. *
  2022. * @name Prompt.requestLoadConfirmation
  2023. * @function
  2024. */
  2025. me.requestLoadConfirmation = function () {
  2026. const loadconfirmmodal = document.getElementById('loadconfirmmodal');
  2027. const loadconfirmOpenNow = loadconfirmmodal.querySelector('#loadconfirm-open-now');
  2028. loadconfirmOpenNow.removeEventListener('click', PasteDecrypter.run);
  2029. loadconfirmOpenNow.addEventListener('click', PasteDecrypter.run);
  2030. const loadconfirmClose = loadconfirmmodal.querySelector('.btn-close');
  2031. loadconfirmClose.removeEventListener('click', Controller.newPaste);
  2032. loadconfirmClose.addEventListener('click', Controller.newPaste);
  2033. loadconfirmmodal.addEventListener('shown.bs.modal', () => {
  2034. loadconfirmOpenNow.focus();
  2035. });
  2036. if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip && typeof bootstrap.Modal === 'function') {
  2037. (new bootstrap.Modal(loadconfirmmodal)).show();
  2038. } else {
  2039. // minimal fallback: make element visible
  2040. loadconfirmmodal.classList.add('show');
  2041. }
  2042. };
  2043. /**
  2044. * ask the user for the password and set it
  2045. *
  2046. * @name Prompt.requestPassword
  2047. * @function
  2048. */
  2049. me.requestPassword = function () {
  2050. // show new bootstrap method (if available)
  2051. if (passwordModal !== null) {
  2052. if (bootstrap5PasswordModal) {
  2053. bootstrap5PasswordModal.show();
  2054. }
  2055. return;
  2056. }
  2057. PasteDecrypter.run();
  2058. };
  2059. /**
  2060. * get the cached password
  2061. *
  2062. * If you do not get a password with this function
  2063. * (returns an empty string), use requestPassword.
  2064. *
  2065. * @name Prompt.getPassword
  2066. * @function
  2067. * @return {string}
  2068. */
  2069. me.getPassword = function () {
  2070. return password;
  2071. };
  2072. /**
  2073. * resets the password to an empty string
  2074. *
  2075. * @name Prompt.reset
  2076. * @function
  2077. */
  2078. me.reset = function () {
  2079. // reset internal
  2080. password = '';
  2081. // and also reset UI
  2082. passwordDecrypt.value = '';
  2083. };
  2084. /**
  2085. * init status manager
  2086. *
  2087. * preloads HTMLElements
  2088. *
  2089. * @name Prompt.init
  2090. * @function
  2091. */
  2092. me.init = function () {
  2093. passwordDecrypt = document.getElementById('passworddecrypt');
  2094. passwordModal = document.getElementById('passwordmodal');
  2095. // bind events - handle Model password submission
  2096. if (passwordModal) {
  2097. const passwordForm = document.getElementById('passwordform');
  2098. if (passwordForm) {
  2099. passwordForm.addEventListener('submit', submitPasswordModal);
  2100. }
  2101. const disableClosingConfig = {
  2102. backdrop: 'static',
  2103. keyboard: false,
  2104. show: false
  2105. };
  2106. if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip && typeof bootstrap.Modal === 'function') {
  2107. bootstrap5PasswordModal = new bootstrap.Modal(passwordModal, disableClosingConfig);
  2108. } else {
  2109. // fallback: keep modal hidden until explicitly shown
  2110. passwordModal.style.display = 'none';
  2111. }
  2112. // ensure focus when modal shown (works for bootstrap5)
  2113. passwordModal.addEventListener('shown.bs.modal', () => {
  2114. passwordDecrypt.focus();
  2115. });
  2116. }
  2117. };
  2118. return me;
  2119. })();
  2120. /**
  2121. * Manage paste/message input, and preview tab
  2122. *
  2123. * Note that the actual preview is handled by PasteViewer.
  2124. *
  2125. * @name Editor
  2126. * @class
  2127. */
  2128. const Editor = (function () {
  2129. const me = {};
  2130. let editorTabs,
  2131. messageEdit,
  2132. messageEditParent,
  2133. messagePreview,
  2134. messagePreviewParent,
  2135. messageTab,
  2136. messageTabParent,
  2137. message,
  2138. isPreview = false,
  2139. isTabSupported = true;
  2140. /**
  2141. * support input of tab character
  2142. *
  2143. * @name Editor.supportTabs
  2144. * @function
  2145. * @param {KeyboardEvent} event
  2146. * @this message
  2147. */
  2148. function supportTabs(event) {
  2149. // support disabling tab support using [Esc] and [Ctrl]+[m]
  2150. if (event.key === 'Escape' || (event.ctrlKey && event.key === 'm')) {
  2151. toggleTabSupport();
  2152. if (messageTab) messageTab.checked = isTabSupported;
  2153. event.preventDefault();
  2154. }
  2155. else if (isTabSupported && event.key === 'Tab') {
  2156. // get caret position & selection
  2157. const val = this.value,
  2158. start = this.selectionStart,
  2159. end = this.selectionEnd;
  2160. // set textarea value to: text before caret + tab + text after caret
  2161. this.value = val.substring(0, start) + '\t' + val.substring(end);
  2162. // put caret at right position again
  2163. this.selectionStart = this.selectionEnd = start + 1;
  2164. // prevent the textarea to lose focus
  2165. event.preventDefault();
  2166. }
  2167. }
  2168. /**
  2169. * toggle tab support in message textarea
  2170. *
  2171. * @name Editor.toggleTabSupport
  2172. * @private
  2173. * @function
  2174. */
  2175. function toggleTabSupport() {
  2176. isTabSupported = !isTabSupported;
  2177. }
  2178. /**
  2179. * view the Editor tab
  2180. *
  2181. * @name Editor.viewEditor
  2182. * @function
  2183. * @param {Event} event - optional
  2184. */
  2185. function viewEditor(event) {
  2186. // toggle buttons
  2187. messageEdit.classList.add('active');
  2188. messageEditParent.classList.add('active');
  2189. messagePreview.classList.remove('active');
  2190. messagePreviewParent.classList.remove('active');
  2191. messageEdit.setAttribute('aria-selected', 'true');
  2192. messagePreview.setAttribute('aria-selected', 'false');
  2193. PasteViewer.hide();
  2194. // reshow input
  2195. message.classList.remove('hidden');
  2196. messageTabParent.classList.remove('hidden');
  2197. me.focusInput();
  2198. // finish
  2199. isPreview = false;
  2200. // prevent jumping of page to top
  2201. if (typeof event !== 'undefined') {
  2202. event.preventDefault();
  2203. }
  2204. }
  2205. /**
  2206. * view the preview tab
  2207. *
  2208. * @name Editor.viewPreview
  2209. * @function
  2210. * @param {Event} event
  2211. */
  2212. function viewPreview(event) {
  2213. // toggle buttons
  2214. messageEdit.classList.remove('active');
  2215. messageEditParent.classList.remove('active');
  2216. messagePreview.classList.add('active');
  2217. messagePreviewParent.classList.add('active');
  2218. messageEdit.setAttribute('aria-selected', 'false');
  2219. messagePreview.setAttribute('aria-selected', 'true');
  2220. // hide input as now preview is shown
  2221. message.classList.add('hidden');
  2222. messageTabParent.classList.add('hidden');
  2223. // show preview
  2224. PasteViewer.setText(message.value);
  2225. if (AttachmentViewer.hasAttachmentData()) {
  2226. const attachmentsData = AttachmentViewer.getAttachmentsData();
  2227. attachmentsData.forEach(attachmentData => {
  2228. const mimeType = AttachmentViewer.getAttachmentMimeType(attachmentData);
  2229. AttachmentViewer.handleBlobAttachmentPreview(
  2230. AttachmentViewer.getAttachmentPreview(),
  2231. attachmentData, mimeType
  2232. );
  2233. });
  2234. AttachmentViewer.showAttachment();
  2235. }
  2236. PasteViewer.run();
  2237. // finish
  2238. isPreview = true;
  2239. // prevent jumping of page to top
  2240. if (typeof event !== 'undefined') {
  2241. event.preventDefault();
  2242. }
  2243. }
  2244. /**
  2245. * get the state of the preview
  2246. *
  2247. * @name Editor.isPreview
  2248. * @function
  2249. */
  2250. me.isPreview = function () {
  2251. return isPreview;
  2252. };
  2253. /**
  2254. * reset the Editor view
  2255. *
  2256. * @name Editor.resetInput
  2257. * @function
  2258. */
  2259. me.resetInput = function () {
  2260. // go back to input
  2261. if (isPreview) {
  2262. viewEditor();
  2263. }
  2264. // clear content
  2265. message.value = '';
  2266. };
  2267. /**
  2268. * shows the Editor
  2269. *
  2270. * @name Editor.show
  2271. * @function
  2272. */
  2273. me.show = function () {
  2274. message.classList.remove('hidden');
  2275. messageTabParent.classList.remove('hidden');
  2276. editorTabs.classList.remove('hidden');
  2277. };
  2278. /**
  2279. * hides the Editor
  2280. *
  2281. * @name Editor.hide
  2282. * @function
  2283. */
  2284. me.hide = function () {
  2285. message.classList.add('hidden');
  2286. messageTabParent.classList.add('hidden');
  2287. editorTabs.classList.add('hidden');
  2288. };
  2289. /**
  2290. * focuses the message input
  2291. *
  2292. * @name Editor.focusInput
  2293. * @function
  2294. */
  2295. me.focusInput = function () {
  2296. message.focus();
  2297. };
  2298. /**
  2299. * sets a new text
  2300. *
  2301. * @name Editor.setText
  2302. * @function
  2303. * @param {string} newText
  2304. */
  2305. me.setText = function (newText) {
  2306. message.value = newText;
  2307. };
  2308. /**
  2309. * returns the current text
  2310. *
  2311. * @name Editor.getText
  2312. * @function
  2313. * @return {string}
  2314. */
  2315. me.getText = function () {
  2316. return message.value;
  2317. };
  2318. /**
  2319. * init editor
  2320. *
  2321. * preloads HTMLElements and binds events
  2322. *
  2323. * @name Editor.init
  2324. * @function
  2325. */
  2326. me.init = function () {
  2327. editorTabs = document.getElementById('editorTabs');
  2328. message = document.getElementById('message');
  2329. messageTab = document.getElementById('messagetab');
  2330. messageTabParent = messageTab ? messageTab.parentElement : null;
  2331. // bind events
  2332. if (message) {
  2333. message.addEventListener('keydown', supportTabs);
  2334. }
  2335. if (messageTab) {
  2336. messageTab.addEventListener('change', toggleTabSupport);
  2337. }
  2338. // bind click events to tab switchers (a), and save parents (li)
  2339. messageEdit = document.getElementById('messageedit');
  2340. if (messageEdit) {
  2341. messageEdit.addEventListener('click', viewEditor);
  2342. messageEditParent = messageEdit.parentElement;
  2343. }
  2344. messagePreview = document.getElementById('messagepreview');
  2345. if (messagePreview) {
  2346. messagePreview.addEventListener('click', viewPreview);
  2347. messagePreviewParent = messagePreview.parentElement;
  2348. }
  2349. };
  2350. return me;
  2351. })();
  2352. /**
  2353. * (view) Parse and show document.
  2354. *
  2355. * @name PasteViewer
  2356. * @class
  2357. */
  2358. const PasteViewer = (function () {
  2359. const me = {};
  2360. let messageTabParent,
  2361. placeholder,
  2362. prettyMessage,
  2363. prettyPrintEl,
  2364. plainText,
  2365. text,
  2366. format = 'plaintext',
  2367. isDisplayed = false,
  2368. isChanged = true; // by default true as nothing was parsed yet
  2369. /**
  2370. * apply the set format on paste and displays it
  2371. *
  2372. * @name PasteViewer.parsePaste
  2373. * @private
  2374. * @function
  2375. */
  2376. function parsePaste() {
  2377. // skip parsing if no text is given
  2378. if (text === '') {
  2379. return;
  2380. }
  2381. if (format === 'markdown') {
  2382. const converter = new showdown.Converter({
  2383. strikethrough: true,
  2384. tables: true,
  2385. tablesHeaderId: true,
  2386. simplifiedAutoLink: true,
  2387. excludeTrailingPunctuationFromURLs: true
  2388. });
  2389. // let showdown convert the HTML and sanitize HTML *afterwards*!
  2390. if (plainText) {
  2391. plainText.innerHTML = DOMPurify.sanitize(
  2392. converter.makeHtml(text),
  2393. purifyHtmlConfig
  2394. );
  2395. // add table classes from bootstrap css
  2396. plainText.querySelectorAll('table').forEach(t => {
  2397. t.classList.add('table-condensed', 'table-bordered');
  2398. });
  2399. }
  2400. } else {
  2401. if (format === 'syntaxhighlighting') {
  2402. // yes, this is really needed to initialize the environment
  2403. if (typeof prettyPrint === 'function') {
  2404. prettyPrint();
  2405. }
  2406. if (prettyPrintEl) {
  2407. prettyPrintEl.innerHTML = prettyPrintOne(
  2408. Helper.htmlEntities(text), null, true
  2409. );
  2410. }
  2411. } else {
  2412. // = 'plaintext'
  2413. if (prettyPrintEl) {
  2414. prettyPrintEl.textContent = text;
  2415. }
  2416. }
  2417. if (prettyPrintEl) {
  2418. Helper.urls2links(prettyPrintEl, format !== 'syntaxhighlighting');
  2419. prettyPrintEl.style.whiteSpace = 'pre-wrap';
  2420. prettyPrintEl.style.wordBreak = 'normal';
  2421. prettyPrintEl.classList.remove('prettyprint', 'prettyprinted');
  2422. }
  2423. }
  2424. }
  2425. /**
  2426. * displays the document
  2427. *
  2428. * NOTE: FOr some obscure reaosn, Markdown is shown in the "plaintext" class
  2429. * and all other ones are rendered in the "prettyPrintEl" one.
  2430. *
  2431. * @name PasteViewer.showPaste
  2432. * @private
  2433. * @function
  2434. */
  2435. function showPaste() {
  2436. // instead of "nothing" better display a placeholder
  2437. if (text === '') {
  2438. if (placeholder) placeholder.classList.remove('hidden');
  2439. return;
  2440. }
  2441. // otherwise hide the placeholder
  2442. if (placeholder) placeholder.classList.add('hidden');
  2443. if (messageTabParent) messageTabParent.classList.add('hidden');
  2444. if (format === 'markdown') {
  2445. if (plainText) plainText.classList.remove('hidden');
  2446. if (prettyMessage) prettyMessage.classList.add('hidden');
  2447. } else {
  2448. if (plainText) plainText.classList.add('hidden');
  2449. if (prettyMessage) prettyMessage.classList.remove('hidden');
  2450. }
  2451. }
  2452. /**
  2453. * sets the format in which the text is shown
  2454. *
  2455. * @name PasteViewer.setFormat
  2456. * @function
  2457. * @param {string} newFormat the new format
  2458. */
  2459. me.setFormat = function (newFormat) {
  2460. // skip if there is no update
  2461. if (format === newFormat) {
  2462. return;
  2463. }
  2464. // needs to update display too, if we switch from or to Markdown
  2465. if (format === 'markdown' || newFormat === 'markdown') {
  2466. isDisplayed = false;
  2467. }
  2468. format = newFormat;
  2469. isChanged = true;
  2470. // update preview
  2471. if (Editor.isPreview()) {
  2472. PasteViewer.run();
  2473. }
  2474. };
  2475. /**
  2476. * returns the current format
  2477. *
  2478. * @name PasteViewer.getFormat
  2479. * @function
  2480. * @return {string}
  2481. */
  2482. me.getFormat = function () {
  2483. return format;
  2484. };
  2485. /**
  2486. * returns whether the current view is pretty printed
  2487. *
  2488. * @name PasteViewer.isPrettyPrinted
  2489. * @function
  2490. * @return {bool}
  2491. */
  2492. me.isPrettyPrinted = function () {
  2493. return prettyPrintEl ? prettyPrintEl.classList.contains('prettyprinted') : false;
  2494. };
  2495. /**
  2496. * sets the text to show
  2497. *
  2498. * @name PasteViewer.setText
  2499. * @function
  2500. * @param {string} newText the text to show
  2501. */
  2502. me.setText = function (newText) {
  2503. if (text !== newText) {
  2504. text = newText;
  2505. isChanged = true;
  2506. }
  2507. };
  2508. /**
  2509. * gets the current cached text
  2510. *
  2511. * @name PasteViewer.getText
  2512. * @function
  2513. * @return {string}
  2514. */
  2515. me.getText = function () {
  2516. return text;
  2517. };
  2518. /**
  2519. * show/update the parsed text (preview)
  2520. *
  2521. * @name PasteViewer.run
  2522. * @function
  2523. */
  2524. me.run = function () {
  2525. if (isChanged) {
  2526. parsePaste();
  2527. isChanged = false;
  2528. }
  2529. if (!isDisplayed) {
  2530. showPaste();
  2531. isDisplayed = true;
  2532. }
  2533. };
  2534. /**
  2535. * hide parsed text (preview)
  2536. *
  2537. * @name PasteViewer.hide
  2538. * @function
  2539. */
  2540. me.hide = function () {
  2541. if (!isDisplayed) {
  2542. return;
  2543. }
  2544. if (plainText) plainText.classList.add('hidden');
  2545. if (prettyMessage) prettyMessage.classList.add('hidden');
  2546. if (placeholder) placeholder.classList.add('hidden');
  2547. AttachmentViewer.hideAttachmentPreview();
  2548. isDisplayed = false;
  2549. };
  2550. /**
  2551. * init status manager
  2552. *
  2553. * preloads DOM elements
  2554. *
  2555. * @name PasteViewer.init
  2556. * @function
  2557. */
  2558. me.init = function () {
  2559. const messagetab = document.getElementById('messagetab');
  2560. messageTabParent = messagetab ? messagetab.parentElement : null;
  2561. placeholder = document.getElementById('placeholder');
  2562. plainText = document.getElementById('plaintext');
  2563. prettyMessage = document.getElementById('prettymessage');
  2564. prettyPrintEl = document.getElementById('prettyprint');
  2565. // get default option from template/HTML or fall back to set value
  2566. format = Model.getFormatDefault() || format;
  2567. text = '';
  2568. isDisplayed = false;
  2569. isChanged = true;
  2570. };
  2571. return me;
  2572. })();
  2573. /**
  2574. * (view) Show attachment and preview if possible
  2575. *
  2576. * @name AttachmentViewer
  2577. * @class
  2578. */
  2579. const AttachmentViewer = (function () {
  2580. const me = {};
  2581. let attachmentPreview,
  2582. attachment,
  2583. attachmentsData = [],
  2584. files,
  2585. fileInput,
  2586. dragAndDropFileNames,
  2587. dropzone;
  2588. /**
  2589. * get blob URL from string data and mime type
  2590. *
  2591. * @name AttachmentViewer.getBlobUrl
  2592. * @private
  2593. * @function
  2594. * @param {string} data - raw data of attachment
  2595. * @param {string} data - mime type of attachment
  2596. * @return {string} objectURL
  2597. */
  2598. function getBlobUrl(data, mimeType) {
  2599. // Transform into a Blob
  2600. const buf = new Uint8Array(data.length);
  2601. for (let i = 0; i < data.length; ++i) {
  2602. buf[i] = data.charCodeAt(i);
  2603. }
  2604. const blob = new window.Blob(
  2605. [buf],
  2606. {
  2607. type: mimeType
  2608. }
  2609. );
  2610. // Get blob URL
  2611. return window.URL.createObjectURL(blob);
  2612. }
  2613. /**
  2614. * sets the attachment but does not yet show it
  2615. *
  2616. * @name AttachmentViewer.setAttachment
  2617. * @function
  2618. * @param {string} attachmentData - base64-encoded data of file
  2619. * @param {string} fileName - optional, file name
  2620. */
  2621. me.setAttachment = function (attachmentData, fileName) {
  2622. // skip, if attachments got disabled
  2623. if (!attachment) return;
  2624. // data URI format: data:[<mimeType>][;base64],<data>
  2625. const template = Model.getTemplate('attachment');
  2626. const attachmentLink = template.querySelector('a');
  2627. // position in data URI string of where data begins
  2628. const base64Start = attachmentData.indexOf(',') + 1;
  2629. const mimeType = me.getAttachmentMimeType(attachmentData);
  2630. // We explicitly do _not_ use the original mime type for the download link
  2631. // to always force a download instead of potentially dangerous browser rendering/parsing/interpretation
  2632. let safeMimeType = 'application/octet-stream';
  2633. if (me.isSafeMimeType(mimeType)) {
  2634. safeMimeType = mimeType;
  2635. }
  2636. // extract data and convert to binary
  2637. const rawData = attachmentData.substring(base64Start);
  2638. const decodedData = rawData.length > 0 ? atob(rawData) : '';
  2639. let blobUrl = getBlobUrl(decodedData, safeMimeType);
  2640. attachmentLink.setAttribute('href', blobUrl);
  2641. if (typeof fileName !== 'undefined') {
  2642. attachmentLink.setAttribute('download', fileName);
  2643. const fileSize = Helper.formatBytes(decodedData.length);
  2644. const spans = template.querySelectorAll('span');
  2645. const span = spans[spans.length - 1];
  2646. span.textContent += ` (${fileName}, ${fileSize})`;
  2647. }
  2648. // sanitize SVG preview
  2649. // prevents executing embedded scripts when CSP is not set and user
  2650. // right-clicks/long-taps and opens the SVG in a new tab - prevented
  2651. // in the preview by use of an img tag, which disables scripts, too
  2652. if (mimeType.match(/^image\/.*svg/i)) {
  2653. const sanitizedData = DOMPurify.sanitize(
  2654. decodedData,
  2655. purifySvgConfig
  2656. );
  2657. blobUrl = getBlobUrl(sanitizedData, mimeType);
  2658. }
  2659. template.classList.remove('hidden');
  2660. attachment.appendChild(template);
  2661. me.handleBlobAttachmentPreview(attachmentPreview, blobUrl, mimeType);
  2662. };
  2663. /**
  2664. * Evaluates whether this is known a safe mime type.
  2665. *
  2666. * This means, the media can safely be displayed and e.g. no XSS should be possible.
  2667. *
  2668. * @name AttachmentViewer.isSafeMimeType
  2669. * @function
  2670. * @param {string}
  2671. * @returns {bool}
  2672. */
  2673. me.isSafeMimeType = function(mimeType) {
  2674. return (
  2675. mimeType.startsWith('image/') &&
  2676. !mimeType.includes('svg')
  2677. ) ||
  2678. mimeType.startsWith('video/') ||
  2679. mimeType.startsWith('audio/') ||
  2680. mimeType.endsWith('/pdf') ||
  2681. mimeType === 'text/plain';
  2682. };
  2683. /**
  2684. * Evaluates whether this is known a safe mime type.
  2685. *
  2686. * This means, the media can safely be displayed and e.g. no XSS should be possible.
  2687. *
  2688. * @name AttachmentViewer.isSafeMimeType
  2689. * @function
  2690. * @param {string}
  2691. * @returns {bool}
  2692. */
  2693. me.isSafeMimeType = function(mimeType) {
  2694. return (
  2695. mimeType.startsWith('image/') &&
  2696. !mimeType.includes('svg')
  2697. ) ||
  2698. mimeType.startsWith('video/') ||
  2699. mimeType.startsWith('audio/') ||
  2700. mimeType.endsWith('/pdf') ||
  2701. mimeType === 'text/plain';
  2702. };
  2703. /**
  2704. * displays the attachment and (if possible) the preview
  2705. *
  2706. * @name AttachmentViewer.showAttachment
  2707. * @function
  2708. */
  2709. me.showAttachment = function () {
  2710. if (!attachment) {
  2711. return;
  2712. }
  2713. attachment.classList.remove('hidden');
  2714. if (attachmentPreview && me.hasAttachmentPreview()) {
  2715. attachmentPreview.classList.remove('hidden');
  2716. }
  2717. };
  2718. /**
  2719. * removes the attachment
  2720. *
  2721. * This automatically hides the attachment containers too, to
  2722. * prevent an inconsistent display.
  2723. *
  2724. * @name AttachmentViewer.removeAttachment
  2725. * @function
  2726. */
  2727. me.removeAttachment = function () {
  2728. if (!attachment) {
  2729. return;
  2730. }
  2731. me.hideAttachment();
  2732. me.hideAttachmentPreview();
  2733. attachment.innerHTML = '';
  2734. if (attachmentPreview) {
  2735. attachmentPreview.innerHTML = '';
  2736. }
  2737. me.clearDragAndDrop();
  2738. AttachmentViewer.removeAttachmentData();
  2739. };
  2740. /**
  2741. * removes the attachment data
  2742. *
  2743. * This removes the data, which would be uploaded otherwise.
  2744. *
  2745. * @name AttachmentViewer.removeAttachmentData
  2746. * @function
  2747. */
  2748. me.removeAttachmentData = function () {
  2749. files = [];
  2750. attachmentsData = [];
  2751. };
  2752. /**
  2753. * Cleares the drag & drop data.
  2754. *
  2755. * @name AttachmentViewer.clearDragAndDrop
  2756. * @function
  2757. */
  2758. me.clearDragAndDrop = function () {
  2759. if (dragAndDropFileNames) {
  2760. dragAndDropFileNames.innerHTML = '';
  2761. }
  2762. };
  2763. /**
  2764. * Print file names added via drag & drop
  2765. *
  2766. * @name AttachmentViewer.printDragAndDropFileNames
  2767. * @private
  2768. * @function
  2769. * @param {string[]} fileNames
  2770. */
  2771. function printDragAndDropFileNames(fileNames) {
  2772. me.clearDragAndDrop();
  2773. fileNames.forEach(fileName => {
  2774. const name = document.createTextNode(fileName);
  2775. dragAndDropFileNames.appendChild(name);
  2776. dragAndDropFileNames.appendChild(document.createElement('br'));
  2777. });
  2778. }
  2779. /**
  2780. * hides the attachment
  2781. *
  2782. * This will not hide the preview (see {@see AttachmentViewer.hideAttachmentPreview}
  2783. * for that) nor will it hide the attachment link if it was moved somewhere
  2784. * else (see {@see AttachmentViewer.moveAttachmentTo}).
  2785. *
  2786. * @name AttachmentViewer.hideAttachment
  2787. * @function
  2788. */
  2789. me.hideAttachment = function () {
  2790. attachment.classList.add('hidden');
  2791. };
  2792. /**
  2793. * hides the attachment preview
  2794. *
  2795. * @name AttachmentViewer.hideAttachmentPreview
  2796. * @function
  2797. */
  2798. me.hideAttachmentPreview = function () {
  2799. if (attachmentPreview) {
  2800. attachmentPreview.classList.add('hidden');
  2801. }
  2802. };
  2803. /**
  2804. * checks if has any attachment preview that is currently rendered
  2805. *
  2806. * Note: This does not verify if the attachment preview is actually shown to the user, as it might be hidden ({@see AttachmentViewer.hideAttachmentPreview}).
  2807. *
  2808. * @name AttachmentViewer.hasAttachmentPreview
  2809. * @function
  2810. * @return {boolean}
  2811. */
  2812. me.hasAttachmentPreview = function () {
  2813. return attachmentPreview.children.length > 0;
  2814. };
  2815. /**
  2816. * checks if there is an attachment displayed
  2817. *
  2818. * @name AttachmentViewer.hasAttachment
  2819. * @function
  2820. */
  2821. me.hasAttachment = function () {
  2822. if (!attachment) {
  2823. return false;
  2824. }
  2825. // Check if there are actual attachment data items (not just UI elements)
  2826. if (attachmentsData.length > 0) {
  2827. return true;
  2828. }
  2829. // Also check UI elements in case data was removed but UI wasn't updated
  2830. return attachment.children.length > 0;
  2831. };
  2832. /**
  2833. * checks if there is attachment data (for preview!) available
  2834. *
  2835. * It returns true, when there is data that needs to be encrypted.
  2836. *
  2837. * @name AttachmentViewer.hasAttachmentData
  2838. * @function
  2839. */
  2840. me.hasAttachmentData = function()
  2841. {
  2842. // Check if there are actual attachment data items (not just UI elements)
  2843. return attachmentsData.length > 0;
  2844. };
  2845. /**
  2846. * return the attachments
  2847. *
  2848. * @name AttachmentViewer.getAttachments
  2849. * @function
  2850. * @returns {array}
  2851. */
  2852. me.getAttachments = function () {
  2853. return [...attachment.querySelectorAll('a')].map(link => (
  2854. [
  2855. link.href,
  2856. link.download
  2857. ]
  2858. ));
  2859. };
  2860. /**
  2861. * Get attachment mime type
  2862. *
  2863. * @name AttachmentViewer.getAttachmentMimeType
  2864. * @function
  2865. * @param {string} attachmentData - Base64 string
  2866. */
  2867. me.getAttachmentMimeType = function (attachmentData) {
  2868. // position in data URI string of where mimeType ends
  2869. const mimeTypeEnd = attachmentData.indexOf(';');
  2870. // extract mimeType
  2871. return attachmentData.substring(5, mimeTypeEnd);
  2872. };
  2873. /**
  2874. * moves the attachment link to another element
  2875. *
  2876. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  2877. *
  2878. * @name AttachmentViewer.moveAttachmentTo
  2879. * @function
  2880. * @param {HTMLElement} element - the wrapper/container element where this should be moved to
  2881. * @param {array} attachment - attachment data
  2882. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  2883. */
  2884. me.moveAttachmentTo = function (element, attachment, label) {
  2885. const attachmentLink = document.createElement('a');
  2886. attachmentLink.className = 'alert-link';
  2887. attachmentLink.href = attachment[0];
  2888. attachmentLink.download = attachment[1];
  2889. // move element to new place
  2890. element.appendChild(attachmentLink);
  2891. // update text - ensuring no HTML is inserted into the text node
  2892. I18n._(attachmentLink, label, attachment[1]);
  2893. };
  2894. /**
  2895. * read files data as data URL using the FileReader API
  2896. *
  2897. * @name AttachmentViewer.readFileData
  2898. * @private
  2899. * @function
  2900. * @param {FileList[]} loadedFiles (optional) loaded files array
  2901. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsDataURL()}
  2902. */
  2903. function readFileData(loadedFiles = []) {
  2904. // Clear old cache
  2905. me.removeAttachmentData();
  2906. if (typeof FileReader === 'undefined') {
  2907. // revert loading status…
  2908. me.hideAttachment();
  2909. me.hideAttachmentPreview();
  2910. Alert.showWarning('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2911. return;
  2912. }
  2913. if (loadedFiles && loadedFiles.length > 0) {
  2914. const fileNames = loadedFiles.map((loadedFile => loadedFile.name));
  2915. printDragAndDropFileNames(fileNames);
  2916. } else {
  2917. const fileInput = document.getElementById('file');
  2918. if (fileInput && fileInput.files) {
  2919. loadedFiles = [...fileInput.files];
  2920. }
  2921. me.clearDragAndDrop();
  2922. }
  2923. if (loadedFiles.length > 0) {
  2924. files = loadedFiles;
  2925. loadedFiles.forEach((loadedFile, index) => {
  2926. const fileReader = new FileReader();
  2927. fileReader.onload = function (event) {
  2928. const dataURL = event.target.result;
  2929. if (dataURL) {
  2930. attachmentsData[index] = dataURL;
  2931. }
  2932. if (Editor.isPreview()) {
  2933. me.handleAttachmentPreview(attachmentPreview, dataURL);
  2934. attachmentPreview.classList.remove('hidden');
  2935. }
  2936. TopNav.highlightFileupload();
  2937. };
  2938. fileReader.readAsDataURL(loadedFile);
  2939. });
  2940. } else {
  2941. me.removeAttachmentData();
  2942. }
  2943. }
  2944. /**
  2945. * handle the preview of files decoded to blob that can either be an image, video, audio or pdf element
  2946. *
  2947. * @name AttachmentViewer.handleBlobAttachmentPreview
  2948. * @function
  2949. * @argument {HTMLElement?} targetElement element where the preview should be appended
  2950. * @argument {string} blobUrl as a blob URL
  2951. * @argument {string} mimeType type
  2952. */
  2953. me.handleBlobAttachmentPreview = function (targetElement, blobUrl, mimeType) {
  2954. if (!targetElement) {
  2955. console.log('Attachment preview element not found/disabled, cannot show attachment preview.');
  2956. return;
  2957. }
  2958. const alreadyIncludesCurrentAttachment = targetElement.querySelectorAll(`[src='${blobUrl}']`).length > 0;
  2959. if (blobUrl && !alreadyIncludesCurrentAttachment) {
  2960. if (mimeType.toLowerCase().startsWith('image/')) {
  2961. const image = document.createElement('img');
  2962. image.setAttribute('src', blobUrl);
  2963. image.setAttribute('class', 'img-thumbnail');
  2964. targetElement.appendChild(image);
  2965. } else if (mimeType.toLowerCase().startsWith('video/')) {
  2966. const video = document.createElement('video');
  2967. video.setAttribute('controls', 'true');
  2968. video.setAttribute('autoplay', 'true');
  2969. video.setAttribute('class', 'img-thumbnail');
  2970. const source = document.createElement('source');
  2971. source.setAttribute('type', mimeType);
  2972. source.setAttribute('src', blobUrl);
  2973. video.appendChild(source);
  2974. targetElement.appendChild(video);
  2975. } else if (mimeType.toLowerCase().startsWith('audio/')) {
  2976. const audio = document.createElement('audio');
  2977. audio.setAttribute('controls', 'true');
  2978. audio.setAttribute('autoplay', 'true');
  2979. const source = document.createElement('source');
  2980. source.setAttribute('type', mimeType);
  2981. source.setAttribute('src', blobUrl);
  2982. audio.appendChild(source);
  2983. targetElement.appendChild(audio);
  2984. } else if (mimeType.toLowerCase().endsWith('/pdf')) {
  2985. const embed = document.createElement('embed');
  2986. embed.setAttribute('src', blobUrl);
  2987. embed.setAttribute('type', 'application/pdf');
  2988. embed.setAttribute('class', 'pdfPreview');
  2989. // Fallback for browsers, that don't support the vh unit
  2990. embed.style.height = window.innerHeight + 'px';
  2991. targetElement.appendChild(embed);
  2992. }
  2993. }
  2994. };
  2995. /**
  2996. * attaches the file attachment drag & drop handler to the page
  2997. *
  2998. * @name AttachmentViewer.addDragDropHandler
  2999. * @private
  3000. * @function
  3001. */
  3002. function addDragDropHandler() {
  3003. if (typeof fileInput === 'undefined' || fileInput === null) {
  3004. return;
  3005. }
  3006. const handleDragEnterOrOver = function (event) {
  3007. event.stopPropagation();
  3008. event.preventDefault();
  3009. return false;
  3010. };
  3011. const handleDrop = function (event) {
  3012. event.stopPropagation();
  3013. event.preventDefault();
  3014. if (TopNav.isAttachmentReadonly()) {
  3015. return false;
  3016. }
  3017. if (fileInput) {
  3018. const files = [...event.dataTransfer.files];
  3019. //Clear the file input:
  3020. fileInput.value = '';
  3021. //Only works in Chrome:
  3022. //fileInput.files = event.dataTransfer.files;
  3023. readFileData(files);
  3024. }
  3025. };
  3026. draghover(document);
  3027. document.addEventListener('draghoverstart', function (e) {
  3028. if (TopNav.isAttachmentReadonly()) {
  3029. e.stopPropagation();
  3030. e.preventDefault();
  3031. return false;
  3032. }
  3033. // show dropzone to indicate drop support
  3034. dropzone.classList.remove('hidden');
  3035. });
  3036. document.addEventListener('draghoverend', function () {
  3037. dropzone.classList.add('hidden');
  3038. });
  3039. document.addEventListener('drop', handleDrop);
  3040. document.addEventListener('dragenter', handleDragEnterOrOver);
  3041. document.addEventListener('dragover', handleDragEnterOrOver);
  3042. fileInput.addEventListener('change', function () {
  3043. readFileData();
  3044. });
  3045. }
  3046. /**
  3047. * attaches the clipboard attachment handler to the page
  3048. *
  3049. * @name AttachmentViewer.addClipboardEventHandler
  3050. * @private
  3051. * @function
  3052. */
  3053. function addClipboardEventHandler() {
  3054. document.addEventListener('paste', (event) => {
  3055. const items = (event.clipboardData || event.originalEvent.clipboardData).items;
  3056. const files = [...items]
  3057. .filter(item => item.kind === 'file')
  3058. .map(item => item.getAsFile());
  3059. if (TopNav.isAttachmentReadonly() && files.length) {
  3060. event.stopPropagation();
  3061. event.preventDefault();
  3062. return false;
  3063. }
  3064. if (files.length) {
  3065. readFileData(files);
  3066. }
  3067. });
  3068. }
  3069. /**
  3070. * getter for attachment data
  3071. *
  3072. * @name AttachmentViewer.getAttachmentsData
  3073. * @function
  3074. * @return {string[]}
  3075. */
  3076. me.getAttachmentsData = function () {
  3077. return attachmentsData;
  3078. };
  3079. /**
  3080. * getter for attachment preview
  3081. *
  3082. * @name AttachmentViewer.getAttachmentPreview
  3083. * @function
  3084. * @return {HTMLElement}
  3085. */
  3086. me.getAttachmentPreview = function () {
  3087. return attachmentPreview;
  3088. };
  3089. /**
  3090. * getter for files data, returns the file list
  3091. *
  3092. * @name AttachmentViewer.getFiles
  3093. * @function
  3094. * @return {FileList[]}
  3095. */
  3096. me.getFiles = function () {
  3097. return files;
  3098. };
  3099. /**
  3100. * initiate
  3101. *
  3102. * preloads HTMLElements
  3103. *
  3104. * @name AttachmentViewer.init
  3105. * @function
  3106. */
  3107. me.init = function () {
  3108. attachment = document.getElementById('attachment');
  3109. dragAndDropFileNames = document.getElementById('dragAndDropFileName');
  3110. dropzone = document.getElementById('dropzone');
  3111. if (attachment) {
  3112. attachmentPreview = document.getElementById('attachmentPreview');
  3113. fileInput = document.getElementById('file');
  3114. addDragDropHandler();
  3115. addClipboardEventHandler();
  3116. }
  3117. };
  3118. return me;
  3119. })();
  3120. /**
  3121. * (view) Shows discussion thread and handles replies
  3122. *
  3123. * @name DiscussionViewer
  3124. * @class
  3125. */
  3126. const DiscussionViewer = (function () {
  3127. const me = {};
  3128. let commentTail,
  3129. discussion,
  3130. reply,
  3131. replyMessage,
  3132. replyNickname,
  3133. replyStatus,
  3134. commentContainer,
  3135. replyCommentId;
  3136. /**
  3137. * initializes the templates
  3138. *
  3139. * @name DiscussionViewer.initTemplates
  3140. * @private
  3141. * @function
  3142. */
  3143. function initTemplates() {
  3144. reply = Model.getTemplate('reply');
  3145. replyMessage = reply.querySelector('#replymessage');
  3146. replyNickname = reply.querySelector('#nickname');
  3147. replyStatus = reply.querySelector('#replystatus');
  3148. // cache elements
  3149. commentTail = Model.getTemplate('commenttail');
  3150. const replyButton = reply.querySelector('#replybutton');
  3151. if (replyButton) {
  3152. replyButton.addEventListener('click', PasteEncrypter.sendComment);
  3153. }
  3154. addEventListeners();
  3155. }
  3156. /**
  3157. * open the comment entry when clicking the "Reply" button of a comment
  3158. *
  3159. * @name DiscussionViewer.openReply
  3160. * @private
  3161. * @function
  3162. * @param {Event} event
  3163. */
  3164. function openReply(event) {
  3165. const source = event.currentTarget || event.target;
  3166. // show all reply buttons
  3167. commentContainer.querySelectorAll('button').forEach(btn => btn.classList.remove('hidden'));
  3168. // hide the current reply button
  3169. source.classList.add('hidden');
  3170. // clear input
  3171. replyMessage.value = '';
  3172. replyNickname.value = '';
  3173. // get comment id from source element
  3174. replyCommentId = source.parentElement.id.split('_')[1];
  3175. // move to correct position
  3176. const parent = source.parentNode;
  3177. if (parent && !reply.contains(source)) {
  3178. if (typeof source.after === 'function') {
  3179. source.after(reply);
  3180. } else if (source.nextSibling) {
  3181. parent.insertBefore(reply, source.nextSibling);
  3182. } else {
  3183. parent.appendChild(reply);
  3184. }
  3185. }
  3186. // show
  3187. reply.classList.remove('hidden');
  3188. replyMessage.focus();
  3189. event.preventDefault();
  3190. }
  3191. /**
  3192. * custom handler for displaying notifications in own status message area
  3193. *
  3194. * @name DiscussionViewer.handleNotification
  3195. * @function
  3196. * @param {string} alertType
  3197. * @return {Boolean|HTMLElement}
  3198. */
  3199. me.handleNotification = function (alertType) {
  3200. // ignore loading messages
  3201. if (alertType === 'loading') {
  3202. return false;
  3203. }
  3204. if (alertType === 'danger') {
  3205. replyStatus.classList.remove('alert-info');
  3206. replyStatus.classList.add('alert-danger');
  3207. const replyIcon = replyStatus.querySelector(':first-child');
  3208. if (replyIcon) {
  3209. replyIcon.classList.remove('glyphicon-alert');
  3210. replyIcon.classList.add('glyphicon-info-sign');
  3211. }
  3212. } else {
  3213. replyStatus.classList.remove('alert-danger');
  3214. replyStatus.classList.add('alert-info');
  3215. const replyIcon = replyStatus.querySelector(':first-child');
  3216. if (replyIcon) {
  3217. replyIcon.classList.remove('glyphicon-info-sign');
  3218. replyIcon.classList.add('glyphicon-alert');
  3219. }
  3220. }
  3221. return replyStatus;
  3222. };
  3223. /**
  3224. * adds another comment
  3225. *
  3226. * @name DiscussionViewer.addComment
  3227. * @function
  3228. * @param {Comment} comment
  3229. * @param {string} commentText
  3230. * @param {string} nickname
  3231. */
  3232. me.addComment = function (comment, commentText, nickname) {
  3233. if (commentText === '') {
  3234. commentText = 'comment decryption failed';
  3235. }
  3236. // create new comment based on template
  3237. const commentEntry = Model.getTemplate('comment');
  3238. if (!commentEntry) {
  3239. return;
  3240. }
  3241. commentEntry.id = 'comment_' + comment.id;
  3242. const commentEntryData = commentEntry.querySelector('div.commentdata');
  3243. if (!commentEntryData) {
  3244. return;
  3245. }
  3246. // set & parse text
  3247. commentEntryData.textContent = commentText;
  3248. Helper.urls2links(commentEntryData);
  3249. // set nickname
  3250. if (nickname.length > 0) {
  3251. const nicknameElement = commentEntry.querySelector('span.nickname');
  3252. if (nicknameElement) {
  3253. nicknameElement.textContent = nickname;
  3254. }
  3255. } else {
  3256. const anonCommenter = document.createElement('em');
  3257. anonCommenter.textContent = I18n._('Anonymous');
  3258. const nicknameElement = commentEntry.querySelector('span.nickname');
  3259. if (nicknameElement) {
  3260. nicknameElement.innerHTML = '';
  3261. nicknameElement.appendChild(anonCommenter);
  3262. }
  3263. }
  3264. // set date
  3265. const created = comment.getCreated();
  3266. const commentDate = created === 0 ? '' : ' (' + (new Date(created * 1000).toLocaleString()) + ')';
  3267. const dateSpan = commentEntry.querySelector('span.commentdate');
  3268. if (dateSpan) {
  3269. dateSpan.textContent = commentDate;
  3270. dateSpan.setAttribute('title', 'CommentID: ' + comment.id);
  3271. }
  3272. // if an avatar is available, display it
  3273. const icon = comment.getIcon();
  3274. if (icon) {
  3275. const image = document.createElement('img');
  3276. image.setAttribute('src', icon);
  3277. image.setAttribute('class', 'vizhash');
  3278. const nickSpan = commentEntry.querySelector('span.nickname');
  3279. if (nickSpan) {
  3280. nickSpan.prepend(' ');
  3281. nickSpan.prepend(image);
  3282. }
  3283. }
  3284. // starting point (default value/fallback)
  3285. let place = commentContainer;
  3286. // if parent comment exists
  3287. const parentComment = document.getElementById('comment_' + comment.parentid);
  3288. if (parentComment) {
  3289. // use parent as position for new comment, so it is shifted
  3290. // to the right
  3291. place = parentComment;
  3292. }
  3293. // attach button handler before inserting
  3294. const replyButton = commentEntry.querySelector('button');
  3295. if (replyButton) {
  3296. replyButton.addEventListener('click', openReply);
  3297. }
  3298. // finally append comment
  3299. place.appendChild(commentEntry);
  3300. };
  3301. /**
  3302. * finishes the discussion area after last comment
  3303. *
  3304. * @name DiscussionViewer.finishDiscussion
  3305. * @function
  3306. */
  3307. me.finishDiscussion = function () {
  3308. // add 'add new comment' area
  3309. const tail = commentTail.cloneNode(true);
  3310. const tailButton = tail.querySelector('button');
  3311. if (tailButton) {
  3312. tailButton.addEventListener('click', openReply);
  3313. }
  3314. commentContainer.appendChild(tail);
  3315. // show discussions
  3316. discussion.classList.remove('hidden');
  3317. };
  3318. /**
  3319. * removes the old discussion and prepares everything for creating a new
  3320. * one.
  3321. *
  3322. * @name DiscussionViewer.prepareNewDiscussion
  3323. * @function
  3324. */
  3325. me.prepareNewDiscussion = function () {
  3326. commentContainer.innerHTML = '';
  3327. discussion.classList.add('hidden');
  3328. // (re-)init templates
  3329. initTemplates();
  3330. };
  3331. /**
  3332. * returns the users message from the reply form
  3333. *
  3334. * @name DiscussionViewer.getReplyMessage
  3335. * @function
  3336. * @return {String}
  3337. */
  3338. me.getReplyMessage = function () {
  3339. return replyMessage.value;
  3340. };
  3341. /**
  3342. * returns the users nickname (if any) from the reply form
  3343. *
  3344. * @name DiscussionViewer.getReplyNickname
  3345. * @function
  3346. * @return {String}
  3347. */
  3348. me.getReplyNickname = function () {
  3349. return replyNickname.value;
  3350. };
  3351. /**
  3352. * returns the id of the parent comment the user is replying to
  3353. *
  3354. * @name DiscussionViewer.getReplyCommentId
  3355. * @function
  3356. * @return {number|undefined}
  3357. */
  3358. me.getReplyCommentId = function () {
  3359. return replyCommentId;
  3360. };
  3361. /**
  3362. * highlights a specific comment and scrolls to it if necessary
  3363. *
  3364. * @name DiscussionViewer.highlightComment
  3365. * @function
  3366. * @param {string} commentId
  3367. * @param {Boolean} fadeOut - whether to fade out the comment
  3368. */
  3369. me.highlightComment = function (commentId, fadeOut) {
  3370. const comment = document.getElementById('comment_' + commentId);
  3371. // in case comment does not exist, cancel
  3372. if (!comment) {
  3373. return;
  3374. }
  3375. comment.classList.add('highlight');
  3376. if (fadeOut === true) {
  3377. setTimeout(function () {
  3378. comment.classList.remove('highlight');
  3379. }, 300);
  3380. }
  3381. if (('checkVisibility' in comment ? comment.checkVisibility() : comment.offsetParent !== null) === false) {
  3382. if (typeof comment.scrollIntoView === 'function') {
  3383. comment.scrollIntoView({ block: 'center' });
  3384. }
  3385. }
  3386. };
  3387. /**
  3388. * Binds events to templates (**and** all )
  3389. */
  3390. function addEventListeners() {
  3391. //
  3392. document.querySelectorAll('#commenttail button')
  3393. .forEach(btn => btn.addEventListener('click', openReply));
  3394. document.querySelectorAll('#comment button')
  3395. .forEach(btn => btn.addEventListener('click', openReply));
  3396. }
  3397. /**
  3398. * initiate
  3399. *
  3400. * preloads HTML elements
  3401. *
  3402. * @name DiscussionViewer.init
  3403. * @function
  3404. */
  3405. me.init = function () {
  3406. // todo: remove
  3407. addEventListeners();
  3408. commentContainer = document.getElementById('commentcontainer');
  3409. discussion = document.getElementById('discussion');
  3410. };
  3411. return me;
  3412. })();
  3413. /**
  3414. * Manage top (navigation) bar
  3415. *
  3416. * @name TopNav
  3417. * @param {object} window
  3418. * @param {object} document
  3419. * @class
  3420. */
  3421. const TopNav = (function (window, document) {
  3422. const me = {};
  3423. let createButtonsDisplayed = false,
  3424. viewButtonsDisplayed = false,
  3425. burnAfterReadingDefault = false,
  3426. openDiscussionDefault = false,
  3427. attach,
  3428. burnAfterReading,
  3429. burnAfterReadingOption,
  3430. cloneButton,
  3431. customAttachment,
  3432. expiration,
  3433. fileRemoveButton,
  3434. fileWrap,
  3435. formatter,
  3436. newButton,
  3437. openDiscussion,
  3438. openDiscussionOption,
  3439. password,
  3440. passwordInput,
  3441. rawTextButton,
  3442. downloadTextButton,
  3443. qrCodeLink,
  3444. emailLink,
  3445. sendButton,
  3446. retryButton,
  3447. pasteExpiration = null,
  3448. retryButtonCallback;
  3449. /**
  3450. * set the expiration on bootstrap templates in dropdown
  3451. *
  3452. * @name TopNav.updateExpiration
  3453. * @private
  3454. * @function
  3455. * @param {Event} event
  3456. */
  3457. function updateExpiration(event) {
  3458. // get selected option
  3459. const target = event.target;
  3460. // update dropdown display and save new expiration time
  3461. const display = document.getElementById('pasteExpirationDisplay');
  3462. if (display) {
  3463. display.textContent = target.textContent;
  3464. }
  3465. pasteExpiration = target.getAttribute('data-expiration');
  3466. event.preventDefault();
  3467. }
  3468. /**
  3469. * set the format on bootstrap templates in dropdown from user interaction
  3470. *
  3471. * @name TopNav.updateFormat
  3472. * @private
  3473. * @function
  3474. * @param {Event} event
  3475. */
  3476. function updateFormat(event) {
  3477. // get selected option
  3478. const target = event.target;
  3479. // update dropdown display and save new format
  3480. const newFormat = target.getAttribute('data-format');
  3481. const display = document.getElementById('pasteFormatterDisplay');
  3482. if (display) {
  3483. display.textContent = target.textContent;
  3484. }
  3485. PasteViewer.setFormat(newFormat);
  3486. event.preventDefault();
  3487. }
  3488. /**
  3489. * when "burn after reading" is checked, disable discussion
  3490. *
  3491. * @name TopNav.changeBurnAfterReading
  3492. * @private
  3493. * @function
  3494. */
  3495. function changeBurnAfterReading() {
  3496. if (me.getBurnAfterReading()) {
  3497. if (openDiscussionOption) {
  3498. openDiscussionOption.classList.add('buttondisabled');
  3499. }
  3500. if (openDiscussion) {
  3501. openDiscussion.checked = false;
  3502. }
  3503. // if button is actually disabled, force-enable it and uncheck other button
  3504. if (burnAfterReadingOption) {
  3505. burnAfterReadingOption.classList.remove('buttondisabled');
  3506. }
  3507. } else {
  3508. if (openDiscussionOption) {
  3509. openDiscussionOption.classList.remove('buttondisabled');
  3510. }
  3511. }
  3512. }
  3513. /**
  3514. * when discussion is checked, disable "burn after reading"
  3515. *
  3516. * @name TopNav.changeOpenDiscussion
  3517. * @private
  3518. * @function
  3519. */
  3520. function changeOpenDiscussion() {
  3521. if (me.getOpenDiscussion()) {
  3522. if (burnAfterReadingOption) {
  3523. burnAfterReadingOption.classList.add('buttondisabled');
  3524. }
  3525. if (burnAfterReading) {
  3526. burnAfterReading.checked = false;
  3527. }
  3528. // if button is actually disabled, force-enable it and uncheck other button
  3529. if (openDiscussionOption) {
  3530. openDiscussionOption.classList.remove('buttondisabled');
  3531. }
  3532. } else {
  3533. if (burnAfterReadingOption) {
  3534. burnAfterReadingOption.classList.remove('buttondisabled');
  3535. }
  3536. }
  3537. }
  3538. /**
  3539. * Clear the password input in the top navigation
  3540. *
  3541. * @name TopNav.clearPasswordInput
  3542. * @function
  3543. */
  3544. function clearPasswordInput() {
  3545. if (passwordInput) {
  3546. passwordInput.value = '';
  3547. }
  3548. }
  3549. /**
  3550. * Clear the attachment input in the top navigation.
  3551. *
  3552. * @name TopNav.clearAttachmentInput
  3553. * @function
  3554. */
  3555. function clearAttachmentInput() {
  3556. // hide UI for selected files
  3557. const inputElement = fileWrap && fileWrap.querySelector('input');
  3558. if (inputElement) {
  3559. inputElement.value = '';
  3560. }
  3561. }
  3562. /**
  3563. * return raw text
  3564. *
  3565. * @name TopNav.rawText
  3566. * @private
  3567. * @function
  3568. */
  3569. function rawText() {
  3570. TopNav.hideAllButtons();
  3571. Alert.showLoading('Showing raw text…', 'time');
  3572. let paste = PasteViewer.getText();
  3573. // push a new state to allow back navigation with browser back button
  3574. history.pushState(
  3575. { type: 'raw' },
  3576. document.title,
  3577. // recreate document URL
  3578. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  3579. CryptTool.base58encode(Model.getPasteKey())
  3580. );
  3581. // we use text/html instead of text/plain to avoid a bug when
  3582. // reloading the raw text view (it reverts to type text/html)
  3583. const headElements = document.head.querySelectorAll(':not(noscript):not(script):not(link[type="text/css"])');
  3584. const newDoc = document.open('text/html', 'replace');
  3585. newDoc.write('<!DOCTYPE html><html><head>');
  3586. for (let i = 0; i < headElements.length; ++i) {
  3587. newDoc.write(headElements[i].outerHTML);
  3588. }
  3589. newDoc.write(
  3590. '</head><body><pre>' +
  3591. DOMPurify.sanitize(
  3592. Helper.htmlEntities(paste),
  3593. purifyHtmlConfig
  3594. ) +
  3595. '</pre></body></html>'
  3596. );
  3597. newDoc.close();
  3598. }
  3599. /**
  3600. * download text
  3601. *
  3602. * @name TopNav.downloadText
  3603. * @private
  3604. * @function
  3605. */
  3606. function downloadText() {
  3607. const fileFormat = PasteViewer.getFormat() === 'markdown' ? '.md' : '.txt';
  3608. const filename = 'document-' + Model.getPasteId() + fileFormat;
  3609. const text = PasteViewer.getText();
  3610. const element = document.createElement('a');
  3611. element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  3612. element.setAttribute('download', filename);
  3613. element.style.display = 'none';
  3614. document.body.appendChild(element);
  3615. element.click();
  3616. document.body.removeChild(element);
  3617. }
  3618. /**
  3619. * saves the language in a cookie and reloads the page
  3620. *
  3621. * @name TopNav.setLanguage
  3622. * @private
  3623. * @function
  3624. * @param {Event} event
  3625. */
  3626. function setLanguage(event) {
  3627. let lang = event.target.getAttribute('data-lang') || event.target.value;
  3628. document.cookie = 'lang=' + lang + '; SameSite=Lax; Secure';
  3629. window.location.reload();
  3630. event.preventDefault();
  3631. }
  3632. /**
  3633. * save the template in a cookie and reloads the page
  3634. *
  3635. * @name TopNav.setTemplate
  3636. * @private
  3637. * @function
  3638. * @param {Event} event
  3639. */
  3640. function setTemplate(event) {
  3641. let template = event.target.getAttribute('data-template') || event.target.value;
  3642. document.cookie = 'template=' + template + '; SameSite=Lax; Secure';
  3643. window.location.reload();
  3644. event.preventDefault();
  3645. }
  3646. /**
  3647. * hides all messages and creates a new document
  3648. *
  3649. * @name TopNav.clickNewPaste
  3650. * @private
  3651. * @function
  3652. */
  3653. function clickNewPaste() {
  3654. Controller.hideStatusMessages();
  3655. Controller.newPaste();
  3656. }
  3657. /**
  3658. * retrys some callback registered before
  3659. *
  3660. * @name TopNav.clickRetryButton
  3661. * @private
  3662. * @function
  3663. * @param {Event} event
  3664. */
  3665. function clickRetryButton(event) {
  3666. retryButtonCallback(event);
  3667. }
  3668. /**
  3669. * removes the existing attachment
  3670. *
  3671. * @name TopNav.removeAttachment
  3672. * @private
  3673. * @function
  3674. * @param {Event} event
  3675. */
  3676. function removeAttachment(event) {
  3677. // if custom attachment is used, remove it first
  3678. if (customAttachment && !customAttachment.classList.contains('hidden')) {
  3679. AttachmentViewer.removeAttachment();
  3680. customAttachment.classList.add('hidden');
  3681. fileWrap.classList.remove('hidden');
  3682. }
  3683. // in any case, remove saved attachment data
  3684. AttachmentViewer.removeAttachmentData();
  3685. clearAttachmentInput();
  3686. AttachmentViewer.clearDragAndDrop();
  3687. // pevent '#' from appearing in the URL
  3688. event.preventDefault();
  3689. }
  3690. /**
  3691. * Shows the QR code of the current document (URL).
  3692. *
  3693. * @name TopNav.displayQrCode
  3694. * @private
  3695. * @function
  3696. */
  3697. function displayQrCode() {
  3698. const qrCanvas = kjua({
  3699. render: 'canvas',
  3700. text: window.location.href
  3701. });
  3702. const qrDisplay = document.getElementById('qrcode-display');
  3703. if (qrDisplay) {
  3704. qrDisplay.innerHTML = '';
  3705. qrDisplay.appendChild(qrCanvas);
  3706. }
  3707. }
  3708. /**
  3709. * Template Email body.
  3710. *
  3711. * @name TopNav.templateEmailBody
  3712. * @private
  3713. * @param {string} expirationDateString
  3714. * @param {bool} isBurnafterreading
  3715. */
  3716. function templateEmailBody(expirationDateString, isBurnafterreading) {
  3717. const EOL = '\n';
  3718. const BULLET = ' - ';
  3719. let emailBody = '';
  3720. if (expirationDateString !== null || isBurnafterreading) {
  3721. emailBody += I18n._('Notice:');
  3722. emailBody += EOL;
  3723. if (expirationDateString !== null) {
  3724. emailBody += EOL;
  3725. emailBody += BULLET;
  3726. // avoid DOMPurify mess with forward slash in expirationDateString
  3727. emailBody += Helper.sprintf(
  3728. I18n._(
  3729. 'This link will expire after %s.',
  3730. '%s'
  3731. ),
  3732. expirationDateString
  3733. );
  3734. }
  3735. if (isBurnafterreading) {
  3736. emailBody += EOL;
  3737. emailBody += BULLET;
  3738. emailBody += I18n._(
  3739. 'This link can only be accessed once, do not use back or refresh button in your browser.'
  3740. );
  3741. }
  3742. emailBody += EOL;
  3743. emailBody += EOL;
  3744. }
  3745. emailBody += I18n._('Link:');
  3746. emailBody += EOL;
  3747. const pasteUrlElement = document.getElementById('pasteurl');
  3748. emailBody += (pasteUrlElement && pasteUrlElement.getAttribute('href')) || window.location.href; // href is tried first as it might have been shortened
  3749. return emailBody;
  3750. }
  3751. /**
  3752. * Trigger Email send.
  3753. *
  3754. * @name TopNav.triggerEmailSend
  3755. * @private
  3756. * @param {string} emailBody
  3757. */
  3758. function triggerEmailSend(emailBody) {
  3759. window.open(
  3760. `mailto:?body=${encodeURIComponent(emailBody)}`,
  3761. '_self',
  3762. 'noopener, noreferrer'
  3763. );
  3764. }
  3765. /**
  3766. * Send Email with current document (URL).
  3767. *
  3768. * @name TopNav.sendEmail
  3769. * @private
  3770. * @function
  3771. * @param {Date|null} expirationDate date of expiration
  3772. * @param {bool} isBurnafterreading whether it is burn after reading
  3773. */
  3774. function sendEmail(expirationDate, isBurnafterreading) {
  3775. const expirationDateRoundedToSecond = new Date(expirationDate);
  3776. // round down at least 30 seconds to make up for the delay of request
  3777. expirationDateRoundedToSecond.setUTCSeconds(
  3778. expirationDateRoundedToSecond.getUTCSeconds() - 30
  3779. );
  3780. expirationDateRoundedToSecond.setUTCSeconds(0);
  3781. const emailconfirmmodal = document.getElementById('emailconfirmmodal');
  3782. if (expirationDate !== null) {
  3783. const emailconfirmTimezoneCurrent = emailconfirmmodal.querySelector('#emailconfirm-timezone-current');
  3784. const emailconfirmTimezoneUtc = emailconfirmmodal.querySelector('#emailconfirm-timezone-utc');
  3785. let localeConfiguration = { dateStyle: 'long', timeStyle: 'long' };
  3786. const bootstrap5EmailConfirmModal = typeof bootstrap !== 'undefined' && bootstrap.Tooltip && bootstrap.Tooltip.VERSION ?
  3787. new bootstrap.Modal(emailconfirmmodal) : null;
  3788. function sendEmailAndHideModal() {
  3789. const emailBody = templateEmailBody(
  3790. // we don't use Date.prototype.toUTCString() because we would like to avoid GMT
  3791. expirationDateRoundedToSecond.toLocaleString(
  3792. [], localeConfiguration
  3793. ), isBurnafterreading
  3794. );
  3795. if (bootstrap5EmailConfirmModal) {
  3796. bootstrap5EmailConfirmModal.hide();
  3797. }
  3798. triggerEmailSend(emailBody);
  3799. }
  3800. emailconfirmmodal.addEventListener('shown.bs.modal', () => {
  3801. emailconfirmTimezoneUtc.focus();
  3802. });
  3803. emailconfirmTimezoneCurrent.removeEventListener('click', sendEmailAndHideModal);
  3804. emailconfirmTimezoneCurrent.addEventListener('click', sendEmailAndHideModal);
  3805. emailconfirmTimezoneUtc.removeEventListener('click', sendEmailAndHideModal);
  3806. emailconfirmTimezoneUtc.addEventListener('click', () => {
  3807. localeConfiguration.timeZone = 'UTC';
  3808. sendEmailAndHideModal();
  3809. });
  3810. if (bootstrap5EmailConfirmModal) {
  3811. bootstrap5EmailConfirmModal.show();
  3812. }
  3813. } else {
  3814. triggerEmailSend(templateEmailBody(null, isBurnafterreading));
  3815. }
  3816. }
  3817. /**
  3818. * Shows all navigation elements for viewing an existing document
  3819. *
  3820. * @name TopNav.showViewButtons
  3821. * @function
  3822. */
  3823. me.showViewButtons = function () {
  3824. if (viewButtonsDisplayed) {
  3825. return;
  3826. }
  3827. newButton.classList.remove('hidden');
  3828. cloneButton.classList.remove('hidden');
  3829. rawTextButton.classList.remove('hidden');
  3830. downloadTextButton.classList.remove('hidden');
  3831. qrCodeLink.classList.remove('hidden');
  3832. viewButtonsDisplayed = true;
  3833. };
  3834. /**
  3835. * Hides all navigation elements for viewing an existing document
  3836. *
  3837. * @name TopNav.hideViewButtons
  3838. * @function
  3839. */
  3840. me.hideViewButtons = function () {
  3841. if (!viewButtonsDisplayed) {
  3842. return;
  3843. }
  3844. cloneButton.classList.add('hidden');
  3845. newButton.classList.add('hidden');
  3846. rawTextButton.classList.add('hidden');
  3847. downloadTextButton.classList.add('hidden');
  3848. qrCodeLink.classList.add('hidden');
  3849. me.hideEmailButton();
  3850. viewButtonsDisplayed = false;
  3851. };
  3852. /**
  3853. * Hides all elements belonging to existing documents
  3854. *
  3855. * @name TopNav.hideAllButtons
  3856. * @function
  3857. */
  3858. me.hideAllButtons = function () {
  3859. me.hideViewButtons();
  3860. me.hideCreateButtons();
  3861. };
  3862. /**
  3863. * shows all elements needed when creating a new document
  3864. *
  3865. * @name TopNav.showCreateButtons
  3866. * @function
  3867. */
  3868. me.showCreateButtons = function () {
  3869. if (createButtonsDisplayed) {
  3870. return;
  3871. }
  3872. if (attach) {
  3873. attach.classList.remove('hidden');
  3874. }
  3875. burnAfterReadingOption.classList.remove('hidden');
  3876. expiration.classList.remove('hidden');
  3877. formatter.classList.remove('hidden');
  3878. newButton.classList.remove('hidden');
  3879. openDiscussionOption.classList.remove('hidden');
  3880. password.classList.remove('hidden');
  3881. sendButton.classList.remove('hidden');
  3882. createButtonsDisplayed = true;
  3883. };
  3884. /**
  3885. * shows all elements needed when creating a new document
  3886. *
  3887. * @name TopNav.hideCreateButtons
  3888. * @function
  3889. */
  3890. me.hideCreateButtons = function () {
  3891. if (!createButtonsDisplayed) {
  3892. return;
  3893. }
  3894. newButton.classList.add('hidden');
  3895. sendButton.classList.add('hidden');
  3896. expiration.classList.add('hidden');
  3897. formatter.classList.add('hidden');
  3898. burnAfterReadingOption.classList.add('hidden');
  3899. openDiscussionOption.classList.add('hidden');
  3900. password.classList.add('hidden');
  3901. if (attach) {
  3902. attach.classList.add('hidden');
  3903. }
  3904. createButtonsDisplayed = false;
  3905. };
  3906. /**
  3907. * only shows the "new document" button
  3908. *
  3909. * @name TopNav.showNewPasteButton
  3910. * @function
  3911. */
  3912. me.showNewPasteButton = function () {
  3913. newButton.classList.remove('hidden');
  3914. };
  3915. /**
  3916. * only shows the "retry" button
  3917. *
  3918. * @name TopNav.showRetryButton
  3919. * @function
  3920. */
  3921. me.showRetryButton = function () {
  3922. retryButton.classList.remove('hidden');
  3923. };
  3924. /**
  3925. * hides the "retry" button
  3926. *
  3927. * @name TopNav.hideRetryButton
  3928. * @function
  3929. */
  3930. me.hideRetryButton = function () {
  3931. retryButton.classList.add('hidden');
  3932. };
  3933. /**
  3934. * show the "email" button
  3935. *
  3936. * @name TopNav.showEmailbutton
  3937. * @function
  3938. * @param {number|undefined} optionalRemainingTimeInSeconds
  3939. * @param {bool|undefined} optionalBurnAfterReading
  3940. */
  3941. me.showEmailButton = function (optionalRemainingTimeInSeconds, optionalBurnAfterReading) {
  3942. try {
  3943. // we cache expiration date in closure to avoid inaccurate expiration datetime
  3944. const expirationDate = Helper.calculateExpirationDate(
  3945. new Date(),
  3946. typeof optionalRemainingTimeInSeconds === 'number' ? optionalRemainingTimeInSeconds : TopNav.getExpiration()
  3947. );
  3948. const isBurnafterreading = typeof optionalBurnAfterReading === 'boolean' ?
  3949. optionalBurnAfterReading : TopNav.getBurnAfterReading();
  3950. emailLink.classList.remove('hidden');
  3951. emailLink.removeEventListener('click', sendEmail);
  3952. emailLink.addEventListener('click', () => {
  3953. sendEmail(expirationDate, isBurnafterreading);
  3954. });
  3955. } catch (error) {
  3956. console.error(error);
  3957. Alert.showError('Cannot calculate expiration date.');
  3958. }
  3959. };
  3960. /**
  3961. * hide the "email" button
  3962. *
  3963. * @name TopNav.hideEmailButton
  3964. * @function
  3965. */
  3966. me.hideEmailButton = function () {
  3967. if (!emailLink) {
  3968. return;
  3969. }
  3970. emailLink.classList.add('hidden');
  3971. emailLink.removeEventListener('click', sendEmail);
  3972. };
  3973. /**
  3974. * only hides the clone button
  3975. *
  3976. * @name TopNav.hideCloneButton
  3977. * @function
  3978. */
  3979. me.hideCloneButton = function () {
  3980. cloneButton.classList.add('hidden');
  3981. };
  3982. /**
  3983. * only hides the raw text button
  3984. *
  3985. * @name TopNav.hideRawButton
  3986. * @function
  3987. */
  3988. me.hideRawButton = function () {
  3989. rawTextButton.classList.add('hidden');
  3990. };
  3991. /**
  3992. * only hides the download text button
  3993. *
  3994. * @name TopNav.hideRawButton
  3995. * @function
  3996. */
  3997. me.hideDownloadButton = function () {
  3998. downloadTextButton.classList.add('hidden');
  3999. };
  4000. /**
  4001. * only hides the qr code button
  4002. *
  4003. * @name TopNav.hideQrCodeButton
  4004. * @function
  4005. */
  4006. me.hideQrCodeButton = function () {
  4007. qrCodeLink.classList.add('hidden');
  4008. };
  4009. /**
  4010. * hide irrelevant buttons when viewing burn after reading document
  4011. *
  4012. * @name TopNav.hideBurnAfterReadingButtons
  4013. * @function
  4014. */
  4015. me.hideBurnAfterReadingButtons = function () {
  4016. me.hideCloneButton();
  4017. me.hideQrCodeButton();
  4018. me.hideEmailButton();
  4019. };
  4020. /**
  4021. * hides the file selector in attachment
  4022. *
  4023. * @name TopNav.hideFileSelector
  4024. * @function
  4025. */
  4026. me.hideFileSelector = function () {
  4027. fileWrap.classList.add('hidden');
  4028. };
  4029. /**
  4030. * shows the custom attachment
  4031. *
  4032. * @name TopNav.showCustomAttachment
  4033. * @function
  4034. */
  4035. me.showCustomAttachment = function () {
  4036. if (!customAttachment) {
  4037. return;
  4038. }
  4039. customAttachment.classList.remove('hidden');
  4040. };
  4041. /**
  4042. * hides the custom attachment
  4043. *
  4044. * @name TopNav.hideCustomAttachment
  4045. * @function
  4046. */
  4047. me.hideCustomAttachment = function () {
  4048. if (customAttachment) {
  4049. customAttachment.classList.add('hidden');
  4050. }
  4051. if (fileWrap) {
  4052. fileWrap.classList.remove('hidden');
  4053. }
  4054. };
  4055. /**
  4056. * collapses the navigation bar, only if expanded
  4057. *
  4058. * @name TopNav.collapseBar
  4059. * @function
  4060. */
  4061. me.collapseBar = function () {
  4062. const navbar = document.getElementById('navbar');
  4063. if (navbar && navbar.getAttribute('aria-expanded') === 'true') {
  4064. const toggle = document.querySelector('.navbar-toggle');
  4065. if (toggle) {
  4066. toggle.click();
  4067. }
  4068. }
  4069. };
  4070. /**
  4071. * Reset the top navigation back to it's default values.
  4072. *
  4073. * @name TopNav.resetInput
  4074. * @function
  4075. */
  4076. me.resetInput = function () {
  4077. clearAttachmentInput();
  4078. clearPasswordInput();
  4079. if (burnAfterReading) {
  4080. burnAfterReading.checked = burnAfterReadingDefault;
  4081. }
  4082. if (openDiscussion) {
  4083. openDiscussion.checked = openDiscussionDefault;
  4084. }
  4085. if (openDiscussionDefault || !burnAfterReadingDefault) {
  4086. openDiscussionOption.classList.remove('buttondisabled');
  4087. }
  4088. if (burnAfterReadingDefault || !openDiscussionDefault) {
  4089. burnAfterReadingOption.classList.remove('buttondisabled');
  4090. }
  4091. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  4092. const pasteExpirationSelect = document.getElementById('pasteExpiration');
  4093. if (pasteExpirationSelect) {
  4094. pasteExpirationSelect.querySelectorAll('option').forEach((option) => {
  4095. if (option.value === pasteExpiration) {
  4096. const display = document.getElementById('pasteExpirationDisplay');
  4097. if (display) {
  4098. display.textContent = option.textContent;
  4099. }
  4100. }
  4101. });
  4102. }
  4103. };
  4104. /**
  4105. * returns the currently set expiration time
  4106. *
  4107. * @name TopNav.getExpiration
  4108. * @function
  4109. * @return {int}
  4110. */
  4111. me.getExpiration = function () {
  4112. return pasteExpiration;
  4113. };
  4114. /**
  4115. * returns the currently selected file(s)
  4116. *
  4117. * @name TopNav.getFileList
  4118. * @function
  4119. * @return {FileList|null}
  4120. */
  4121. me.getFileList = function () {
  4122. const file = document.getElementById('file');
  4123. // if no file given, return null
  4124. if (!file || !file.files || !file.files.length) {
  4125. return null;
  4126. }
  4127. // ensure the selected file is still accessible
  4128. if (!file.files[0]) {
  4129. return null;
  4130. }
  4131. return file.files;
  4132. };
  4133. /**
  4134. * returns the state of the burn after reading checkbox
  4135. *
  4136. * @name TopNav.getBurnAfterReading
  4137. * @function
  4138. * @return {bool}
  4139. */
  4140. me.getBurnAfterReading = function () {
  4141. return burnAfterReading ? !!burnAfterReading.checked : false;
  4142. };
  4143. /**
  4144. * returns the state of the discussion checkbox
  4145. *
  4146. * @name TopNav.getOpenDiscussion
  4147. * @function
  4148. * @return {bool}
  4149. */
  4150. me.getOpenDiscussion = function () {
  4151. return openDiscussion ? !!openDiscussion.checked : false;
  4152. };
  4153. /**
  4154. * returns the entered password
  4155. *
  4156. * @name TopNav.getPassword
  4157. * @function
  4158. * @return {string}
  4159. */
  4160. me.getPassword = function () {
  4161. // when password is disabled passwordInput.value will return undefined
  4162. return passwordInput && passwordInput.value || '';
  4163. };
  4164. /**
  4165. * returns the element where custom attachments can be placed
  4166. *
  4167. * Used by AttachmentViewer when an attachment is cloned here.
  4168. *
  4169. * @name TopNav.getCustomAttachment
  4170. * @function
  4171. * @return {HTMLElement}
  4172. */
  4173. me.getCustomAttachment = function () {
  4174. return customAttachment;
  4175. };
  4176. /**
  4177. * Set a function to call when the retry button is clicked.
  4178. *
  4179. * @name TopNav.setRetryCallback
  4180. * @function
  4181. * @param {function} callback
  4182. */
  4183. me.setRetryCallback = function (callback) {
  4184. retryButtonCallback = callback;
  4185. };
  4186. /**
  4187. * Highlight file upload
  4188. *
  4189. * @name TopNav.highlightFileupload
  4190. * @function
  4191. */
  4192. me.highlightFileupload = function () {
  4193. // visually indicate file uploaded
  4194. const attachDropdownToggle = attach && attach.querySelector('.dropdown-toggle');
  4195. if (attachDropdownToggle && attachDropdownToggle.getAttribute('aria-expanded') === 'false') {
  4196. if (Helper.isBootstrap5()) {
  4197. new bootstrap.Dropdown(attachDropdownToggle).toggle();
  4198. } else {
  4199. attachDropdownToggle.click();
  4200. }
  4201. }
  4202. fileWrap.classList.add('highlight');
  4203. setTimeout(function () {
  4204. fileWrap.classList.remove('highlight');
  4205. }, 300);
  4206. }
  4207. /**
  4208. * set the format on bootstrap templates in dropdown programmatically
  4209. *
  4210. * @name TopNav.setFormat
  4211. * @function
  4212. */
  4213. me.setFormat = function (format) {
  4214. if (Helper.isBootstrap5()) {
  4215. const select = formatter.querySelector('select');
  4216. if (select) {
  4217. select.value = format;
  4218. }
  4219. } else {
  4220. const formatLink = formatter.parentElement.querySelector(`a[data-format="${format}"]`);
  4221. if (formatLink) {
  4222. formatLink.click();
  4223. }
  4224. }
  4225. }
  4226. /**
  4227. * returns if attachment dropdown is readonly, not editable
  4228. *
  4229. * @name TopNav.isAttachmentReadonly
  4230. * @function
  4231. * @return {bool}
  4232. */
  4233. me.isAttachmentReadonly = function () {
  4234. return !createButtonsDisplayed || (attach && attach.classList.contains('hidden'));
  4235. }
  4236. /**
  4237. * init navigation manager
  4238. *
  4239. * preloads DOM elements
  4240. *
  4241. * @name TopNav.init
  4242. * @function
  4243. */
  4244. /**
  4245. * bind all navigation event listeners
  4246. *
  4247. * @name TopNav.bindEvents
  4248. * @private
  4249. * @function
  4250. */
  4251. function bindEvents() {
  4252. const languageDropdown = document.getElementById('language');
  4253. if (languageDropdown) {
  4254. languageDropdown.querySelectorAll('ul.dropdown-menu li a').forEach(link => {
  4255. link.addEventListener('click', setLanguage);
  4256. });
  4257. }
  4258. const templateDropdown = document.getElementById('template');
  4259. if (templateDropdown) {
  4260. templateDropdown.querySelectorAll('ul.dropdown-menu li a').forEach(link => {
  4261. link.addEventListener('click', setTemplate);
  4262. });
  4263. }
  4264. // bind events
  4265. if (burnAfterReading) {
  4266. burnAfterReading.addEventListener('change', changeBurnAfterReading);
  4267. }
  4268. if (openDiscussionOption) {
  4269. openDiscussionOption.addEventListener('change', changeOpenDiscussion);
  4270. }
  4271. if (newButton) {
  4272. newButton.addEventListener('click', clickNewPaste);
  4273. }
  4274. if (sendButton) {
  4275. sendButton.addEventListener('click', PasteEncrypter.sendPaste);
  4276. }
  4277. if (cloneButton) {
  4278. cloneButton.addEventListener('click', Controller.clonePaste);
  4279. }
  4280. if (rawTextButton) {
  4281. rawTextButton.addEventListener('click', rawText);
  4282. }
  4283. if (downloadTextButton) {
  4284. downloadTextButton.addEventListener('click', downloadText);
  4285. }
  4286. if (retryButton) {
  4287. retryButton.addEventListener('click', clickRetryButton);
  4288. }
  4289. if (fileRemoveButton) {
  4290. fileRemoveButton.addEventListener('click', removeAttachment);
  4291. }
  4292. if (qrCodeLink) {
  4293. qrCodeLink.addEventListener('click', displayQrCode);
  4294. }
  4295. if (Helper.isBootstrap5()) {
  4296. const pasteExpirationSelect = document.getElementById('pasteExpiration');
  4297. if (pasteExpirationSelect) {
  4298. pasteExpirationSelect.addEventListener('change', function () {
  4299. pasteExpiration = Model.getExpirationDefault();
  4300. });
  4301. }
  4302. const pasteFormatterSelect = document.getElementById('pasteFormatter');
  4303. if (pasteFormatterSelect) {
  4304. pasteFormatterSelect.addEventListener('change', function () {
  4305. PasteViewer.setFormat(Model.getFormatDefault());
  4306. });
  4307. }
  4308. } else {
  4309. // bootstrap template drop downs
  4310. if (expiration) {
  4311. expiration.parentElement.querySelectorAll('ul.dropdown-menu li a').forEach(link => {
  4312. link.addEventListener('click', updateExpiration);
  4313. });
  4314. }
  4315. if (formatter) {
  4316. formatter.parentElement.querySelectorAll('ul.dropdown-menu li a').forEach(link => {
  4317. link.addEventListener('click', updateFormat);
  4318. });
  4319. }
  4320. // page drop downs
  4321. const pasteExpirationSelect = document.getElementById('pasteExpiration');
  4322. if (pasteExpirationSelect) {
  4323. pasteExpirationSelect.addEventListener('change', function () {
  4324. pasteExpiration = Model.getExpirationDefault();
  4325. });
  4326. }
  4327. const pasteFormatterSelect = document.getElementById('pasteFormatter');
  4328. if (pasteFormatterSelect) {
  4329. pasteFormatterSelect.addEventListener('change', function () {
  4330. PasteViewer.setFormat(Model.getFormatDefault());
  4331. });
  4332. }
  4333. }
  4334. }
  4335. me.init = function () {
  4336. attach = document.getElementById('attach');
  4337. burnAfterReading = document.getElementById('burnafterreading');
  4338. burnAfterReadingOption = document.getElementById('burnafterreadingoption');
  4339. cloneButton = document.getElementById('clonebutton');
  4340. customAttachment = document.getElementById('customattachment');
  4341. expiration = document.getElementById('expiration');
  4342. fileRemoveButton = document.getElementById('fileremovebutton');
  4343. fileWrap = document.getElementById('filewrap');
  4344. formatter = document.getElementById('formatter');
  4345. newButton = document.getElementById('newbutton');
  4346. openDiscussion = document.getElementById('opendiscussion');
  4347. openDiscussionOption = document.getElementById('opendiscussionoption');
  4348. password = document.getElementById('password');
  4349. passwordInput = document.getElementById('passwordinput');
  4350. rawTextButton = document.getElementById('rawtextbutton');
  4351. downloadTextButton = document.getElementById('downloadtextbutton');
  4352. retryButton = document.getElementById('retrybutton');
  4353. sendButton = document.getElementById('sendbutton');
  4354. qrCodeLink = document.getElementById('qrcodelink');
  4355. emailLink = document.getElementById('emaillink');
  4356. bindEvents();
  4357. // initiate default state of checkboxes
  4358. changeBurnAfterReading();
  4359. changeOpenDiscussion();
  4360. // get default values from template or fall back to set value
  4361. burnAfterReadingDefault = me.getBurnAfterReading();
  4362. openDiscussionDefault = me.getOpenDiscussion();
  4363. pasteExpiration = Model.getExpirationDefault();
  4364. createButtonsDisplayed = false;
  4365. viewButtonsDisplayed = false;
  4366. };
  4367. return me;
  4368. })(window, document);
  4369. /**
  4370. * Responsible for AJAX requests, transparently handles encryption…
  4371. *
  4372. * @name ServerInteraction
  4373. * @class
  4374. */
  4375. const ServerInteraction = (function () {
  4376. const me = {};
  4377. let successFunc = null,
  4378. failureFunc = null,
  4379. symmetricKey = null,
  4380. url,
  4381. data,
  4382. password;
  4383. /**
  4384. * public variable ('constant') for errors to prevent magic numbers
  4385. *
  4386. * @name ServerInteraction.error
  4387. * @readonly
  4388. * @enum {Object}
  4389. */
  4390. me.error = {
  4391. okay: 0,
  4392. custom: 1,
  4393. unknown: 2,
  4394. serverError: 3
  4395. };
  4396. /**
  4397. * ajaxHeaders to send in AJAX requests
  4398. *
  4399. * @name ServerInteraction.ajaxHeaders
  4400. * @private
  4401. * @readonly
  4402. * @enum {Object}
  4403. */
  4404. const ajaxHeaders = {
  4405. 'X-Requested-With': 'JSONHttpRequest',
  4406. 'Content-Type': 'application/json'
  4407. };
  4408. /**
  4409. * called after successful upload
  4410. *
  4411. * @name ServerInteraction.success
  4412. * @private
  4413. * @function
  4414. * @param {int} status
  4415. * @param {int} result - optional
  4416. */
  4417. function success(status, result) {
  4418. if (successFunc !== null) {
  4419. // add useful data to result
  4420. result.encryptionKey = symmetricKey;
  4421. successFunc(status, result);
  4422. }
  4423. }
  4424. /**
  4425. * called after a upload failure
  4426. *
  4427. * @name ServerInteraction.fail
  4428. * @private
  4429. * @function
  4430. * @param {int} status - internal code
  4431. * @param {int} result - original error code
  4432. */
  4433. function fail(status, result) {
  4434. if (failureFunc !== null) {
  4435. failureFunc(status, result);
  4436. }
  4437. }
  4438. /**
  4439. * actually uploads the data
  4440. *
  4441. * @name ServerInteraction.run
  4442. * @function
  4443. */
  4444. me.run = function () {
  4445. let isPost = Object.keys(data).length > 0,
  4446. options = {
  4447. method: isPost ? 'POST' : 'GET',
  4448. headers: ajaxHeaders
  4449. };
  4450. if (isPost) {
  4451. options.body = JSON.stringify(data);
  4452. }
  4453. fetch(url, options)
  4454. .then(response => {
  4455. if (!response.ok) {
  4456. throw response;
  4457. }
  4458. return response.json();
  4459. })
  4460. .then(result => {
  4461. if (result.status === 0) {
  4462. success(0, result);
  4463. } else if (result.status === 1) {
  4464. fail(1, result);
  4465. } else {
  4466. fail(2, result);
  4467. }
  4468. })
  4469. .catch(error => {
  4470. console.error(error);
  4471. fail(3, error);
  4472. });
  4473. };
  4474. /**
  4475. * return currently set data, used in unit testing
  4476. *
  4477. * @name ServerInteraction.getData
  4478. * @function
  4479. */
  4480. me.getData = function () {
  4481. return data;
  4482. };
  4483. /**
  4484. * set success function
  4485. *
  4486. * @name ServerInteraction.setUrl
  4487. * @function
  4488. * @param {function} newUrl
  4489. */
  4490. me.setUrl = function (newUrl) {
  4491. url = newUrl;
  4492. };
  4493. /**
  4494. * sets the password to use (first value) and optionally also the
  4495. * encryption key (not recommended, it is automatically generated).
  4496. *
  4497. * Note: Call this after prepare() as prepare() resets these values.
  4498. *
  4499. * @name ServerInteraction.setCryptValues
  4500. * @function
  4501. * @param {string} newPassword
  4502. * @param {string} newKey - optional
  4503. */
  4504. me.setCryptParameters = function (newPassword, newKey) {
  4505. password = newPassword;
  4506. if (typeof newKey !== 'undefined') {
  4507. symmetricKey = newKey;
  4508. }
  4509. };
  4510. /**
  4511. * set success function
  4512. *
  4513. * @name ServerInteraction.setSuccess
  4514. * @function
  4515. * @param {function} func
  4516. */
  4517. me.setSuccess = function (func) {
  4518. successFunc = func;
  4519. };
  4520. /**
  4521. * set failure function
  4522. *
  4523. * @name ServerInteraction.setFailure
  4524. * @function
  4525. * @param {function} func
  4526. */
  4527. me.setFailure = function (func) {
  4528. failureFunc = func;
  4529. };
  4530. /**
  4531. * prepares a new upload
  4532. *
  4533. * Call this when doing a new upload to reset any data from potential
  4534. * previous uploads. Must be called before any other method of this
  4535. * module.
  4536. *
  4537. * @name ServerInteraction.prepare
  4538. * @function
  4539. * @return {object}
  4540. */
  4541. me.prepare = function () {
  4542. // entropy should already be checked!
  4543. // reset password
  4544. password = '';
  4545. // reset key, so it a new one is generated when it is used
  4546. symmetricKey = null;
  4547. // reset data
  4548. successFunc = null;
  4549. failureFunc = null;
  4550. url = Helper.baseUri();
  4551. data = {};
  4552. };
  4553. /**
  4554. * encrypts and sets the data
  4555. *
  4556. * @name ServerInteraction.setCipherMessage
  4557. * @async
  4558. * @function
  4559. * @param {object} cipherMessage
  4560. */
  4561. me.setCipherMessage = async function (cipherMessage) {
  4562. if (
  4563. symmetricKey === null ||
  4564. (typeof symmetricKey === 'string' && symmetricKey === '')
  4565. ) {
  4566. symmetricKey = CryptTool.getSymmetricKey();
  4567. }
  4568. if (!data.hasOwnProperty('adata')) {
  4569. data['adata'] = [];
  4570. }
  4571. let cipherResult = await CryptTool.cipher(symmetricKey, password, JSON.stringify(cipherMessage), data['adata']);
  4572. data['v'] = 2;
  4573. data['ct'] = cipherResult[0];
  4574. data['adata'] = cipherResult[1];
  4575. };
  4576. /**
  4577. * set the additional metadata to send unencrypted
  4578. *
  4579. * @name ServerInteraction.setUnencryptedData
  4580. * @function
  4581. * @param {string} index
  4582. * @param {mixed} element
  4583. */
  4584. me.setUnencryptedData = function (index, element) {
  4585. data[index] = element;
  4586. };
  4587. /**
  4588. * Helper, which parses shows a general error message based on the result of the ServerInteraction
  4589. *
  4590. * @name ServerInteraction.parseUploadError
  4591. * @function
  4592. * @param {int} status
  4593. * @param {object} data
  4594. * @param {string} doThisThing - a human description of the action, which was tried
  4595. * @return {array}
  4596. */
  4597. me.parseUploadError = function (status, data, doThisThing) {
  4598. let errorArray;
  4599. switch (status) {
  4600. case me.error.custom:
  4601. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  4602. break;
  4603. case me.error.unknown:
  4604. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  4605. break;
  4606. case me.error.serverError:
  4607. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  4608. break;
  4609. default:
  4610. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  4611. break;
  4612. }
  4613. return errorArray;
  4614. };
  4615. return me;
  4616. })();
  4617. /**
  4618. * (controller) Responsible for encrypting document and sending it to server.
  4619. *
  4620. * Does upload, encryption is done transparently by ServerInteraction.
  4621. *
  4622. * @name PasteEncrypter
  4623. * @class
  4624. */
  4625. const PasteEncrypter = (function () {
  4626. const me = {};
  4627. /**
  4628. * called after successful document upload
  4629. *
  4630. * @name PasteEncrypter.showCreatedPaste
  4631. * @private
  4632. * @function
  4633. * @param {int} status
  4634. * @param {object} data
  4635. */
  4636. function showCreatedPaste(status, data) {
  4637. Alert.hideLoading();
  4638. Alert.hideMessages();
  4639. // show notification
  4640. const baseUri = Helper.baseUri() + '?',
  4641. url = baseUri + data.id + (TopNav.getBurnAfterReading() ? loadConfirmPrefix : '#') + CryptTool.base58encode(data.encryptionKey),
  4642. deleteUrl = baseUri + 'pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  4643. PasteStatus.createPasteNotification(url, deleteUrl);
  4644. // show new URL in browser bar
  4645. history.pushState({ type: 'newpaste' }, document.title, url);
  4646. TopNav.showViewButtons();
  4647. CopyToClipboard.setUrl(url);
  4648. CopyToClipboard.showKeyboardShortcutHint();
  4649. // this cannot be grouped with showViewButtons due to remaining time calculation
  4650. TopNav.showEmailButton();
  4651. TopNav.hideRawButton();
  4652. TopNav.hideDownloadButton();
  4653. Editor.hide();
  4654. PasteStatus.checkAutoShorten();
  4655. // parse and show text
  4656. // (preparation already done in me.sendPaste())
  4657. PasteViewer.run();
  4658. }
  4659. /**
  4660. * called after successful comment upload
  4661. *
  4662. * @name PasteEncrypter.showUploadedComment
  4663. * @private
  4664. * @function
  4665. * @param {int} status
  4666. * @param {object} data
  4667. */
  4668. function showUploadedComment(status, data) {
  4669. // show success message
  4670. Alert.showStatus('Comment posted.');
  4671. // reload document
  4672. Controller.refreshPaste(function () {
  4673. // highlight sent comment
  4674. DiscussionViewer.highlightComment(data.id, true);
  4675. // reset error handler
  4676. Alert.setCustomHandler(null);
  4677. });
  4678. }
  4679. /**
  4680. * send a reply in a discussion
  4681. *
  4682. * @name PasteEncrypter.sendComment
  4683. * @async
  4684. * @function
  4685. */
  4686. me.sendComment = async function () {
  4687. // get data
  4688. const plainText = DiscussionViewer.getReplyMessage();
  4689. // do not send if there is no data
  4690. if (plainText.length === 0) {
  4691. return;
  4692. }
  4693. let nickname = DiscussionViewer.getReplyNickname(),
  4694. parentid = DiscussionViewer.getReplyCommentId();
  4695. Alert.hideMessages();
  4696. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  4697. // UI loading state
  4698. TopNav.hideAllButtons();
  4699. Alert.showLoading('Sending comment…', 'cloud-upload');
  4700. // prepare server interaction
  4701. ServerInteraction.prepare();
  4702. ServerInteraction.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  4703. // set success/fail functions
  4704. ServerInteraction.setSuccess(showUploadedComment);
  4705. ServerInteraction.setFailure(function (status, data) {
  4706. // revert loading status…
  4707. Alert.hideLoading();
  4708. TopNav.showViewButtons();
  4709. // …show error message…
  4710. Alert.showError(
  4711. ServerInteraction.parseUploadError(status, data, 'post comment')
  4712. );
  4713. // …and reset error handler
  4714. Alert.setCustomHandler(null);
  4715. });
  4716. // fill it with unencrypted params
  4717. ServerInteraction.setUnencryptedData('pasteid', Model.getPasteId());
  4718. if (typeof parentid === 'undefined') {
  4719. // if parent id is not set, this is the top-most comment, so use
  4720. // document id as parent, as the root element of the discussion tree
  4721. ServerInteraction.setUnencryptedData('parentid', Model.getPasteId());
  4722. } else {
  4723. ServerInteraction.setUnencryptedData('parentid', parentid);
  4724. }
  4725. // prepare cypher message
  4726. let cipherMessage = {
  4727. 'comment': plainText
  4728. };
  4729. if (nickname.length > 0) {
  4730. cipherMessage['nickname'] = nickname;
  4731. }
  4732. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4733. ServerInteraction.run();
  4734. };
  4735. /**
  4736. * sends a new document to server
  4737. *
  4738. * @name PasteEncrypter.sendPaste
  4739. * @async
  4740. * @function
  4741. */
  4742. me.sendPaste = async function () {
  4743. // hide previous (error) messages
  4744. Controller.hideStatusMessages();
  4745. // UI loading state
  4746. TopNav.hideAllButtons();
  4747. Alert.showLoading('Sending document…', 'cloud-upload');
  4748. TopNav.collapseBar();
  4749. // get data
  4750. const plainText = Editor.getText(),
  4751. format = PasteViewer.getFormat(),
  4752. // the methods may return different values if no files are attached (null, undefined or false)
  4753. files = TopNav.getFileList() || AttachmentViewer.getFiles() || AttachmentViewer.hasAttachmentData();
  4754. // do not send if there is no data
  4755. if (plainText.length === 0 && !files) {
  4756. // revert loading status…
  4757. Alert.hideLoading();
  4758. TopNav.showCreateButtons();
  4759. return;
  4760. }
  4761. // prepare server interaction
  4762. ServerInteraction.prepare();
  4763. ServerInteraction.setCryptParameters(TopNav.getPassword());
  4764. // set success/fail functions
  4765. ServerInteraction.setSuccess(showCreatedPaste);
  4766. ServerInteraction.setFailure(function (status, data) {
  4767. // revert loading status…
  4768. Alert.hideLoading();
  4769. TopNav.showCreateButtons();
  4770. // show error message
  4771. Alert.showError(
  4772. ServerInteraction.parseUploadError(status, data, 'create document')
  4773. );
  4774. });
  4775. // fill it with unencrypted submitted options
  4776. ServerInteraction.setUnencryptedData('adata', [
  4777. null, format,
  4778. TopNav.getOpenDiscussion() ? 1 : 0,
  4779. TopNav.getBurnAfterReading() ? 1 : 0
  4780. ]);
  4781. ServerInteraction.setUnencryptedData('meta', { 'expire': TopNav.getExpiration() });
  4782. // prepare PasteViewer for later preview
  4783. PasteViewer.setText(plainText);
  4784. PasteViewer.setFormat(format);
  4785. // prepare cypher message
  4786. let attachmentsData = AttachmentViewer.getAttachmentsData(),
  4787. cipherMessage = {
  4788. 'paste': plainText
  4789. };
  4790. if (attachmentsData.length) {
  4791. cipherMessage['attachment'] = attachmentsData;
  4792. cipherMessage['attachment_name'] = AttachmentViewer.getFiles().map(fileInfo => fileInfo.name);
  4793. } else if (AttachmentViewer.hasAttachment()) {
  4794. // fall back to cloned part
  4795. let attachments = AttachmentViewer.getAttachments();
  4796. cipherMessage['attachment'] = attachments.map(attachment => attachment[0]);
  4797. cipherMessage['attachment_name'] = attachments.map(attachment => attachment[1]);
  4798. cipherMessage['attachment'] = await Promise.all(cipherMessage['attachment'].map(async (attachment, i) => {
  4799. // we need to retrieve data from blob if browser already parsed it in memory
  4800. if (typeof attachment === 'string' && attachment.startsWith('blob:')) {
  4801. Alert.showStatus(
  4802. [
  4803. 'Retrieving cloned file \'%s\' from memory...',
  4804. cipherMessage['attachment_name'][i]
  4805. ],
  4806. 'copy'
  4807. );
  4808. try {
  4809. const response = await fetch(attachment, {
  4810. method: 'GET',
  4811. credentials: 'omit',
  4812. signal: AbortSignal.timeout(10000)
  4813. });
  4814. if (!response.ok) {
  4815. throw new Error('HTTP ' + response.status);
  4816. }
  4817. const blobData = await response.blob();
  4818. if (blobData instanceof window.Blob) {
  4819. const fileReading = new Promise(function (resolve, reject) {
  4820. const fileReader = new FileReader();
  4821. fileReader.onload = function (event) {
  4822. resolve(event.target.result);
  4823. };
  4824. fileReader.onerror = function (error) {
  4825. reject(error);
  4826. }
  4827. fileReader.readAsDataURL(blobData);
  4828. });
  4829. return await fileReading;
  4830. } else {
  4831. const error = 'Cannot process attachment data.';
  4832. Alert.showError(error);
  4833. throw new TypeError(error);
  4834. }
  4835. } catch (error) {
  4836. Alert.showError('Cannot retrieve attachment.');
  4837. throw error;
  4838. }
  4839. }
  4840. }));
  4841. }
  4842. // encrypt message
  4843. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4844. // send data
  4845. ServerInteraction.run();
  4846. };
  4847. return me;
  4848. })();
  4849. /**
  4850. * (controller) Responsible for decrypting cipherdata and passing data to view.
  4851. *
  4852. * Only decryption, no download.
  4853. *
  4854. * @name PasteDecrypter
  4855. * @class
  4856. */
  4857. const PasteDecrypter = (function () {
  4858. const me = {};
  4859. /**
  4860. * decrypt data or prompts for password in case of failure
  4861. *
  4862. * @name PasteDecrypter.decryptOrPromptPassword
  4863. * @private
  4864. * @async
  4865. * @function
  4866. * @param {string} key
  4867. * @param {string} password - optional, may be an empty string
  4868. * @param {string} cipherdata
  4869. * @throws {string}
  4870. * @return {Promise<false|string>} false, when unsuccessful or string (decrypted data)
  4871. */
  4872. async function decryptOrPromptPassword(key, password, cipherdata) {
  4873. // try decryption without password
  4874. const plaindata = await CryptTool.decipher(key, password, cipherdata);
  4875. // if it fails, request password
  4876. if (plaindata.length === 0 && password.length === 0) {
  4877. // show prompt
  4878. Prompt.requestPassword();
  4879. // Thus, we cannot do anything yet, we need to wait for the user
  4880. // input.
  4881. return false;
  4882. }
  4883. // if all tries failed, we can only return an error
  4884. if (plaindata.length === 0) {
  4885. return false;
  4886. }
  4887. return plaindata;
  4888. }
  4889. /**
  4890. * decrypt the actual document text
  4891. *
  4892. * @name PasteDecrypter.decryptPaste
  4893. * @private
  4894. * @async
  4895. * @function
  4896. * @param {Paste} paste - document data in object form
  4897. * @param {string} key
  4898. * @param {string} password
  4899. * @throws {string}
  4900. * @return {Promise}
  4901. */
  4902. async function decryptPaste(paste, key, password) {
  4903. const pastePlain = await decryptOrPromptPassword(
  4904. key, password,
  4905. paste.getCipherData()
  4906. );
  4907. if (pastePlain === false) {
  4908. if (password.length === 0) {
  4909. throw 'waiting on user to provide a password';
  4910. } else {
  4911. Alert.hideLoading();
  4912. // reset password, so it can be re-entered
  4913. Prompt.reset();
  4914. TopNav.showRetryButton();
  4915. throw 'Could not decrypt data. Did you enter a wrong password? Retry with the button at the top.';
  4916. }
  4917. }
  4918. const pasteMessage = JSON.parse(pastePlain);
  4919. if (pasteMessage.hasOwnProperty('attachment') && pasteMessage.hasOwnProperty('attachment_name')) {
  4920. if (Array.isArray(pasteMessage.attachment) && Array.isArray(pasteMessage.attachment_name)) {
  4921. pasteMessage.attachment.forEach((attachment, key) => {
  4922. const attachment_name = pasteMessage.attachment_name[key];
  4923. AttachmentViewer.setAttachment(attachment, attachment_name);
  4924. });
  4925. } else {
  4926. // Continue to process attachment parameters as strings to ensure backward compatibility
  4927. AttachmentViewer.setAttachment(pasteMessage.attachment, pasteMessage.attachment_name);
  4928. }
  4929. AttachmentViewer.showAttachment();
  4930. }
  4931. PasteViewer.setFormat(paste.getFormat());
  4932. PasteViewer.setText(pasteMessage.paste);
  4933. PasteViewer.run();
  4934. }
  4935. /**
  4936. * decrypts all comments and shows them
  4937. *
  4938. * @name PasteDecrypter.decryptComments
  4939. * @private
  4940. * @async
  4941. * @function
  4942. * @param {Paste} paste - document data in object form
  4943. * @param {string} key
  4944. * @param {string} password
  4945. * @return {Promise}
  4946. */
  4947. async function decryptComments(paste, key, password) {
  4948. // remove potential previous discussion
  4949. DiscussionViewer.prepareNewDiscussion();
  4950. const commentDecryptionPromises = [];
  4951. // iterate over comments
  4952. for (let i = 0; i < paste.comments.length; ++i) {
  4953. const comment = new Comment(paste.comments[i]),
  4954. commentPromise = CryptTool.decipher(key, password, comment.getCipherData());
  4955. paste.comments[i] = comment;
  4956. commentDecryptionPromises.push(
  4957. commentPromise.then(function (commentJson) {
  4958. const commentMessage = JSON.parse(commentJson);
  4959. return [
  4960. commentMessage.comment || '',
  4961. commentMessage.nickname || ''
  4962. ];
  4963. })
  4964. );
  4965. }
  4966. return Promise.all(commentDecryptionPromises).then(function (plaintexts) {
  4967. for (let i = 0; i < paste.comments.length; ++i) {
  4968. if (plaintexts[i][0].length === 0) {
  4969. continue;
  4970. }
  4971. DiscussionViewer.addComment(
  4972. paste.comments[i],
  4973. plaintexts[i][0],
  4974. plaintexts[i][1]
  4975. );
  4976. }
  4977. document.addEventListener(I18n.languageLoadedEvent, function () {
  4978. const commentContainer = document.getElementById('commentcontainer');
  4979. if (!commentContainer) {
  4980. return;
  4981. }
  4982. commentContainer.querySelectorAll('img.vizhash')
  4983. .forEach(img => img.setAttribute('title', I18n._('Avatar generated from IP address')));
  4984. });
  4985. });
  4986. }
  4987. /**
  4988. * show decrypted text in the display area, including discussion (if open)
  4989. *
  4990. * @name PasteDecrypter.run
  4991. * @function
  4992. * @param {Paste} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  4993. */
  4994. me.run = function (paste) {
  4995. Alert.hideMessages();
  4996. Alert.setCustomHandler(null);
  4997. Alert.showLoading('Decrypting document…', 'cloud-download');
  4998. if (typeof paste === 'undefined' || paste.type === 'click') {
  4999. // get cipher data and wait until it is available
  5000. Model.getPasteData(me.run);
  5001. return;
  5002. }
  5003. let key = Model.getPasteKey(),
  5004. password = Prompt.getPassword(),
  5005. decryptionPromises = [];
  5006. TopNav.setRetryCallback(function () {
  5007. TopNav.hideRetryButton();
  5008. me.run(paste);
  5009. });
  5010. // Clear attachments to prevent duplicates
  5011. AttachmentViewer.removeAttachment();
  5012. // decrypt paste & attachments
  5013. decryptionPromises.push(decryptPaste(paste, key, password));
  5014. // if the discussion is opened on this document, display it
  5015. if (paste.isDiscussionEnabled()) {
  5016. decryptionPromises.push(decryptComments(paste, key, password));
  5017. }
  5018. // shows the remaining time (until) deletion
  5019. PasteStatus.showRemainingTime(paste);
  5020. CopyToClipboard.showKeyboardShortcutHint();
  5021. Promise.all(decryptionPromises)
  5022. .then(() => {
  5023. Alert.hideLoading();
  5024. TopNav.showViewButtons();
  5025. // discourage cloning (it cannot really be prevented)
  5026. if (paste.isBurnAfterReadingEnabled()) {
  5027. TopNav.hideBurnAfterReadingButtons();
  5028. } else {
  5029. // we have to pass in remaining_time here
  5030. TopNav.showEmailButton(
  5031. paste.getTimeToLive(),
  5032. paste.isBurnAfterReadingEnabled()
  5033. );
  5034. }
  5035. // only offer adding comments, after document was successfully decrypted
  5036. if (paste.isDiscussionEnabled()) {
  5037. DiscussionViewer.finishDiscussion();
  5038. }
  5039. })
  5040. .catch((err) => {
  5041. // wait for the user to type in the password,
  5042. // then PasteDecrypter.run will be called again
  5043. Alert.showError(err);
  5044. });
  5045. };
  5046. return me;
  5047. })();
  5048. /**
  5049. *
  5050. * @name CopyToClipboard
  5051. * @class
  5052. */
  5053. const CopyToClipboard = (function () {
  5054. const me = {};
  5055. let copyButton,
  5056. copyLinkButton,
  5057. shortcutHint,
  5058. url;
  5059. /**
  5060. * Handle copy to clipboard button click
  5061. *
  5062. * @name CopyToClipboard.handleCopyButtonClick
  5063. * @private
  5064. * @function
  5065. */
  5066. function handleCopyButtonClick() {
  5067. if (!copyButton) return;
  5068. copyButton.addEventListener('click', function () {
  5069. const text = PasteViewer.getText();
  5070. saveToClipboard(text);
  5071. showAlertMessage('Document copied to clipboard');
  5072. });
  5073. }
  5074. /**
  5075. * Handle copy link to clipboard button click
  5076. *
  5077. * @name CopyToClipboard.handleCopyLinkButtonClick
  5078. * @private
  5079. * @function
  5080. */
  5081. function handleCopyLinkButtonClick() {
  5082. if (!copyLinkButton) return;
  5083. copyLinkButton.addEventListener('click', function () {
  5084. saveToClipboard(url);
  5085. showAlertMessage('Link copied to clipboard');
  5086. });
  5087. }
  5088. /**
  5089. * Handle CTRL+C/CMD+C keyboard shortcut
  5090. *
  5091. * @name CopyToClipboard.handleKeyboardShortcut
  5092. * @private
  5093. * @function
  5094. */
  5095. function handleKeyboardShortcut() {
  5096. document.addEventListener('copy', function () {
  5097. if (!isUserSelectedTextToCopy()) {
  5098. const text = PasteViewer.getText();
  5099. saveToClipboard(text);
  5100. showAlertMessage('Document copied to clipboard');
  5101. }
  5102. });
  5103. }
  5104. /**
  5105. * Check if user selected some text on the page to copy it
  5106. *
  5107. * @name CopyToClipboard.isUserSelectedTextToCopy
  5108. * @private
  5109. * @function
  5110. * @returns {boolean}
  5111. */
  5112. function isUserSelectedTextToCopy() {
  5113. let text = '';
  5114. if (window.getSelection) {
  5115. text = window.getSelection().toString();
  5116. } else if (document.selection && document.selection.type !== 'Control') {
  5117. text = document.selection.createRange().text;
  5118. }
  5119. return text.length > 0;
  5120. }
  5121. /**
  5122. * Save text to the clipboard
  5123. *
  5124. * @name CopyToClipboard.saveToClipboard
  5125. * @private
  5126. * @param {string} text
  5127. * @function
  5128. */
  5129. function saveToClipboard(text) {
  5130. navigator.clipboard.writeText(text);
  5131. }
  5132. /**
  5133. * Show alert message after text copy
  5134. *
  5135. * @name CopyToClipboard.showAlertMessage
  5136. * @private
  5137. * @param {string} message
  5138. * @function
  5139. */
  5140. function showAlertMessage(message) {
  5141. Alert.showStatus(message);
  5142. }
  5143. /**
  5144. * Show keyboard shortcut hint
  5145. *
  5146. * @name CopyToClipboard.showKeyboardShortcutHint
  5147. * @function
  5148. */
  5149. me.showKeyboardShortcutHint = function () {
  5150. shortcutHint.classList.remove('hidden');
  5151. };
  5152. /**
  5153. * Hide keyboard shortcut hint
  5154. *
  5155. * @name CopyToClipboard.showKeyboardShortcutHint
  5156. * @function
  5157. */
  5158. me.hideKeyboardShortcutHint = function () {
  5159. shortcutHint.classList.add('hidden');
  5160. };
  5161. /**
  5162. * Set document url
  5163. *
  5164. * @name CopyToClipboard.setUrl
  5165. * @param {string} newUrl
  5166. * @function
  5167. */
  5168. me.setUrl = function (newUrl) {
  5169. url = newUrl;
  5170. };
  5171. /**
  5172. * Initialize
  5173. *
  5174. * @name CopyToClipboard.init
  5175. * @function
  5176. */
  5177. me.init = function () {
  5178. copyButton = document.getElementById('copyShortcutHintBtn');
  5179. copyLinkButton = document.getElementById('copyLink');
  5180. shortcutHint = document.getElementById('copyShortcutHint');
  5181. handleCopyButtonClick();
  5182. handleCopyLinkButtonClick();
  5183. handleKeyboardShortcut();
  5184. };
  5185. return me;
  5186. })();
  5187. /**
  5188. *
  5189. * @name PasswordPeek
  5190. * @class
  5191. */
  5192. const PasswordPeek = (function () {
  5193. const me = {};
  5194. /**
  5195. * Switch between visible and hidden password
  5196. *
  5197. * @name PasswordPeek.handleRevealButtonClick
  5198. * @private
  5199. * @function
  5200. */
  5201. function handleRevealButtonClick() {
  5202. const element = this;
  5203. const inputGroup = element.closest('.input-group');
  5204. const passwordInput = inputGroup ? inputGroup.querySelector('.input-password') : null;
  5205. if (!passwordInput) {
  5206. return;
  5207. }
  5208. const isHidden = passwordInput.getAttribute('type') === 'password';
  5209. passwordInput.setAttribute('type', isHidden ? 'text' : 'password');
  5210. const tooltip = I18n._(isHidden ? 'Hide password' : 'Show password');
  5211. element.setAttribute('title', tooltip);
  5212. element.setAttribute('aria-label', tooltip);
  5213. // handle bootstrap 5 icons: eye & eye-slash
  5214. const buttonSvg = element.querySelector('use');
  5215. if (buttonSvg) {
  5216. const iconHref = buttonSvg.getAttribute('href');
  5217. if (iconHref) {
  5218. buttonSvg.setAttribute('href', isHidden ? `${iconHref}-slash` : iconHref.substring(0, iconHref.length - 6));
  5219. }
  5220. return;
  5221. }
  5222. // handle bootstrap 3 icons: eye-open & eye-close
  5223. const buttonSpan = element.querySelector('span');
  5224. if (buttonSpan) {
  5225. if (isHidden) {
  5226. buttonSpan.classList.add('glyphicon-eye-close');
  5227. buttonSpan.classList.remove('glyphicon-eye-open');
  5228. } else {
  5229. buttonSpan.classList.add('glyphicon-eye-open');
  5230. buttonSpan.classList.remove('glyphicon-eye-close');
  5231. }
  5232. }
  5233. }
  5234. /**
  5235. * Initialize
  5236. *
  5237. * @name PasswordPeek.init
  5238. * @function
  5239. */
  5240. me.init = function () {
  5241. const revealButton = document.querySelector('.toggle-password');
  5242. if (!revealButton) {
  5243. return;
  5244. }
  5245. revealButton.addEventListener('click', handleRevealButtonClick);
  5246. };
  5247. return me;
  5248. })();
  5249. /**
  5250. * (controller) main PrivateBin logic
  5251. *
  5252. * @name Controller
  5253. * @param {object} window
  5254. * @param {object} document
  5255. * @class
  5256. */
  5257. const Controller = (function (window, document) {
  5258. const me = {};
  5259. /**
  5260. * hides all status messages no matter which module showed them
  5261. *
  5262. * @name Controller.hideStatusMessages
  5263. * @function
  5264. */
  5265. me.hideStatusMessages = function () {
  5266. PasteStatus.hideMessages();
  5267. Alert.hideMessages();
  5268. CopyToClipboard.hideKeyboardShortcutHint();
  5269. };
  5270. /**
  5271. * creates a new document
  5272. *
  5273. * @name Controller.newPaste
  5274. * @function
  5275. */
  5276. me.newPaste = function () {
  5277. // Important: This *must not* run Alert.hideMessages() as previous
  5278. // errors from viewing a document should be shown.
  5279. TopNav.hideAllButtons();
  5280. Alert.showLoading('Preparing new document…', 'time');
  5281. PasteStatus.hideMessages();
  5282. PasteViewer.hide();
  5283. Editor.resetInput();
  5284. Editor.show();
  5285. Editor.focusInput();
  5286. AttachmentViewer.removeAttachment();
  5287. TopNav.resetInput();
  5288. // reset format
  5289. PasteViewer.setFormat('plaintext');
  5290. TopNav.setFormat('plaintext');
  5291. TopNav.showCreateButtons();
  5292. // newPaste could be called when user is on document clone editing view
  5293. TopNav.hideCustomAttachment();
  5294. AttachmentViewer.clearDragAndDrop();
  5295. AttachmentViewer.removeAttachmentData();
  5296. Alert.hideLoading();
  5297. // only push new state if we are coming from a different one
  5298. if (Helper.baseUri() !== window.location) {
  5299. history.pushState({ type: 'create' }, document.title, Helper.baseUri());
  5300. }
  5301. // clear discussion
  5302. DiscussionViewer.prepareNewDiscussion();
  5303. };
  5304. /**
  5305. * shows the loaded document
  5306. *
  5307. * @name Controller.showPaste
  5308. * @function
  5309. */
  5310. me.showPaste = function () {
  5311. try {
  5312. Model.getPasteKey();
  5313. } catch (err) {
  5314. console.error(err);
  5315. 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?)');
  5316. return;
  5317. }
  5318. // check if we should request loading confirmation
  5319. if (window.location.hash.startsWith(loadConfirmPrefix)) {
  5320. Prompt.requestLoadConfirmation();
  5321. return;
  5322. }
  5323. // show proper elements on screen
  5324. PasteDecrypter.run();
  5325. };
  5326. /**
  5327. * refreshes the loaded document to show potential new data
  5328. *
  5329. * @name Controller.refreshPaste
  5330. * @function
  5331. * @param {function} callback
  5332. */
  5333. me.refreshPaste = function (callback) {
  5334. // save window position to restore it later
  5335. const orgPosition = window.scrollY;
  5336. Model.getPasteData(function (data) {
  5337. ServerInteraction.prepare();
  5338. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + Model.getPasteId());
  5339. ServerInteraction.setFailure(function (status, data) {
  5340. // revert loading status…
  5341. Alert.hideLoading();
  5342. TopNav.showViewButtons();
  5343. // show error message
  5344. Alert.showError(
  5345. ServerInteraction.parseUploadError(status, data, 'refresh display')
  5346. );
  5347. });
  5348. ServerInteraction.setSuccess(function (status, data) {
  5349. PasteDecrypter.run(new Paste(data));
  5350. // NOTE: callback needs to be called (with setTimeout) after a JS
  5351. // rendering cycle, as otherwise it would be called before the new content
  5352. // is actually rendered, which would cause problems when trying to e.g.
  5353. // highlight a comment right after refreshing the document, as the comment would not be in the DOM at that time.
  5354. // For scrolling, more timeout is used.
  5355. setTimeout(() => {
  5356. // restore position instantly (as the process should be instantly)
  5357. window.scrollTo({
  5358. top: orgPosition,
  5359. behavior: 'instant'
  5360. });
  5361. callback();
  5362. }, 10);
  5363. });
  5364. ServerInteraction.run();
  5365. }, false); // this false is important as it circumvents the cache
  5366. };
  5367. /**
  5368. * clone the current document
  5369. *
  5370. * @name Controller.clonePaste
  5371. * @function
  5372. */
  5373. me.clonePaste = function () {
  5374. TopNav.collapseBar();
  5375. TopNav.hideAllButtons();
  5376. // hide messages from previous document
  5377. me.hideStatusMessages();
  5378. // erase the id and the key in url
  5379. history.pushState({ type: 'clone' }, document.title, Helper.baseUri());
  5380. if (AttachmentViewer.hasAttachment()) {
  5381. const attachments = AttachmentViewer.getAttachments();
  5382. attachments.forEach(attachment => {
  5383. AttachmentViewer.moveAttachmentTo(
  5384. TopNav.getCustomAttachment(),
  5385. attachment,
  5386. 'Cloned: \'%s\''
  5387. );
  5388. });
  5389. TopNav.hideFileSelector();
  5390. AttachmentViewer.hideAttachment();
  5391. // NOTE: it also looks nice without removing the attachment
  5392. // but for a consistent display we remove it…
  5393. AttachmentViewer.hideAttachmentPreview();
  5394. TopNav.showCustomAttachment();
  5395. // show another status messages to make the user aware that the
  5396. // files were cloned too!
  5397. Alert.showStatus(
  5398. [
  5399. 'The cloned file \'%s\' was attached to this document.',
  5400. attachments.map(attachment => attachment[1]).join(', ')
  5401. ],
  5402. 'copy'
  5403. );
  5404. }
  5405. Editor.setText(PasteViewer.getText());
  5406. // also clone the format
  5407. TopNav.setFormat(PasteViewer.getFormat());
  5408. PasteViewer.hide();
  5409. Editor.show();
  5410. TopNav.showCreateButtons();
  5411. // clear discussion
  5412. DiscussionViewer.prepareNewDiscussion();
  5413. };
  5414. /**
  5415. * try initializing zlib or display a warning if it fails,
  5416. * extracted from main init to allow unit testing
  5417. *
  5418. * @name Controller.initZlib
  5419. * @function
  5420. */
  5421. me.initZlib = function () {
  5422. z = zlib.catch(function () {
  5423. if (document.body.dataset.compression !== 'none') {
  5424. Alert.showWarning('Your browser doesn\'t support WebAssembly, used for zlib compression. You can create uncompressed documents, but can\'t read compressed ones.');
  5425. }
  5426. });
  5427. };
  5428. /**
  5429. * application start
  5430. *
  5431. * @name Controller.init
  5432. * @function
  5433. */
  5434. me.init = function () {
  5435. // first load translations
  5436. I18n.loadTranslations();
  5437. // Add a hook to make all links open a new window
  5438. DOMPurify.addHook('afterSanitizeAttributes', function (node) {
  5439. // set all elements owning target to target=_blank
  5440. if ('target' in node && node.id !== 'pasteurl') {
  5441. node.setAttribute('target', '_blank');
  5442. }
  5443. // set non-HTML/MathML links to xlink:show=new
  5444. if (!node.hasAttribute('target')
  5445. && (node.hasAttribute('xlink:href')
  5446. || node.hasAttribute('href'))) {
  5447. node.setAttribute('xlink:show', 'new');
  5448. }
  5449. if ('rel' in node) {
  5450. node.setAttribute('rel', 'nofollow noopener noreferrer');
  5451. }
  5452. });
  5453. // initialize other modules/"classes"
  5454. Alert.init();
  5455. Model.init();
  5456. AttachmentViewer.init();
  5457. DiscussionViewer.init();
  5458. Editor.init();
  5459. PasteStatus.init();
  5460. PasteViewer.init();
  5461. Prompt.init();
  5462. TopNav.init();
  5463. UiHelper.init();
  5464. CopyToClipboard.init();
  5465. PasswordPeek.init();
  5466. // check for legacy browsers before going any further
  5467. if (!Legacy.Check.getInit()) {
  5468. // Legacy check didn't complete, wait and try again
  5469. setTimeout(init, 500);
  5470. return;
  5471. }
  5472. if (!Legacy.Check.getStatus()) {
  5473. // something major is wrong, stop right away
  5474. return;
  5475. }
  5476. me.initZlib();
  5477. // if delete token is passed (i.e. document has been deleted by this
  5478. // access), add an event listener for the 'new' document button in the alert
  5479. if (Model.hasDeleteToken()) {
  5480. const newFromAlert = document.getElementById('new-from-alert');
  5481. if (newFromAlert) {
  5482. newFromAlert.addEventListener('click', function () {
  5483. UiHelper.reloadHome();
  5484. });
  5485. }
  5486. return;
  5487. }
  5488. // check whether existing document needs to be shown
  5489. try {
  5490. Model.getPasteId();
  5491. } catch (e) {
  5492. // otherwise create a new document
  5493. return me.newPaste();
  5494. }
  5495. // always reload on back button to invalidate cache (protect burn after read document)
  5496. window.addEventListener('popstate', () => {
  5497. window.location.reload();
  5498. });
  5499. // display an existing document
  5500. return me.showPaste();
  5501. };
  5502. return me;
  5503. })(window, document);
  5504. return {
  5505. Helper: Helper,
  5506. I18n: I18n,
  5507. CryptTool: CryptTool,
  5508. Model: Model,
  5509. UiHelper: UiHelper,
  5510. Alert: Alert,
  5511. PasteStatus: PasteStatus,
  5512. Prompt: Prompt,
  5513. Editor: Editor,
  5514. PasteViewer: PasteViewer,
  5515. AttachmentViewer: AttachmentViewer,
  5516. DiscussionViewer: DiscussionViewer,
  5517. TopNav: TopNav,
  5518. ServerInteraction: ServerInteraction,
  5519. PasteEncrypter: PasteEncrypter,
  5520. PasteDecrypter: PasteDecrypter,
  5521. PasswordPeek: PasswordPeek,
  5522. CopyToClipboard: CopyToClipboard,
  5523. Controller: Controller
  5524. };
  5525. })();
  5526. // main application start, called when DOM is fully loaded
  5527. // skip auto-initialization in test environments (Node.js)
  5528. if (typeof module === 'undefined' || !module.exports) {
  5529. window.addEventListener('DOMContentLoaded', function () {
  5530. // run main controller
  5531. window.PrivateBin.Controller.init();
  5532. });
  5533. }