privatebin.js 203 KB

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