privatebin.js 206 KB

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