privatebin.js 186 KB

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