privatebin.js 207 KB

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