privatebin.js 192 KB

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