privatebin.js 200 KB

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