1
0

privatebin.js 204 KB

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