privatebin.js 208 KB

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