privatebin.js 199 KB

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