privatebin.js 202 KB

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