privatebin.js 207 KB

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