privatebin.js 189 KB

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