privatebin.js 205 KB

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