1
0

privatebin.js 204 KB

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