privatebin.js 187 KB

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