privatebin.js 191 KB

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