privatebin.js 194 KB

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