privatebin.js 190 KB

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