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