privatebin.js 190 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060
  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. const fileInfo = document.createTextNode(` (${fileName}, ${fileSize})`);
  2725. template[0].appendChild(fileInfo);
  2726. }
  2727. // sanitize SVG preview
  2728. // prevents executing embedded scripts when CSP is not set and user
  2729. // right-clicks/long-taps and opens the SVG in a new tab - prevented
  2730. // in the preview by use of an img tag, which disables scripts, too
  2731. if (mimeType.match(/^image\/.*svg/i)) {
  2732. const sanitizedData = DOMPurify.sanitize(
  2733. decodedData,
  2734. purifySvgConfig
  2735. );
  2736. blobUrl = getBlobUrl(sanitizedData, mimeType);
  2737. }
  2738. template.removeClass('hidden');
  2739. $attachment.append(template);
  2740. me.handleBlobAttachmentPreview($attachmentPreview, blobUrl, mimeType);
  2741. };
  2742. /**
  2743. * displays the attachment
  2744. *
  2745. * @name AttachmentViewer.showAttachment
  2746. * @function
  2747. */
  2748. me.showAttachment = function()
  2749. {
  2750. // skip, if attachments got disabled
  2751. if (!$attachment || !$attachmentPreview) return;
  2752. $attachment.removeClass('hidden');
  2753. if (me.hasAttachmentPreview()) {
  2754. $attachmentPreview.removeClass('hidden');
  2755. }
  2756. };
  2757. /**
  2758. * removes the attachment
  2759. *
  2760. * This automatically hides the attachment containers too, to
  2761. * prevent an inconsistent display.
  2762. *
  2763. * @name AttachmentViewer.removeAttachment
  2764. * @function
  2765. */
  2766. me.removeAttachment = function()
  2767. {
  2768. if (!$attachment.length) {
  2769. return;
  2770. }
  2771. me.hideAttachment();
  2772. me.hideAttachmentPreview();
  2773. $attachment.html('');
  2774. $attachmentPreview.html('');
  2775. $dragAndDropFileNames.html('');
  2776. AttachmentViewer.removeAttachmentData();
  2777. };
  2778. /**
  2779. * removes the attachment data
  2780. *
  2781. * This removes the data, which would be uploaded otherwise.
  2782. *
  2783. * @name AttachmentViewer.removeAttachmentData
  2784. * @function
  2785. */
  2786. me.removeAttachmentData = function()
  2787. {
  2788. files = undefined;
  2789. attachmentsData = [];
  2790. };
  2791. /**
  2792. * Cleares the drag & drop data.
  2793. *
  2794. * @name AttachmentViewer.clearDragAndDrop
  2795. * @function
  2796. */
  2797. me.clearDragAndDrop = function()
  2798. {
  2799. $dragAndDropFileNames.html('');
  2800. };
  2801. /**
  2802. * Print file names added via drag & drop
  2803. *
  2804. * @name AttachmentViewer.printDragAndDropFileNames
  2805. * @private
  2806. * @function
  2807. * @param {string[]} fileNames
  2808. */
  2809. function printDragAndDropFileNames(fileNames) {
  2810. $dragAndDropFileNames.empty();
  2811. fileNames.forEach(fileName => {
  2812. const name = document.createTextNode(fileName);
  2813. $dragAndDropFileNames[0].appendChild(name);
  2814. $dragAndDropFileNames[0].appendChild(document.createElement('br'));
  2815. });
  2816. }
  2817. /**
  2818. * hides the attachment
  2819. *
  2820. * This will not hide the preview (see AttachmentViewer.hideAttachmentPreview
  2821. * for that) nor will it hide the attachment link if it was moved somewhere
  2822. * else (see AttachmentViewer.moveAttachmentTo).
  2823. *
  2824. * @name AttachmentViewer.hideAttachment
  2825. * @function
  2826. */
  2827. me.hideAttachment = function()
  2828. {
  2829. $attachment.addClass('hidden');
  2830. };
  2831. /**
  2832. * hides the attachment preview
  2833. *
  2834. * @name AttachmentViewer.hideAttachmentPreview
  2835. * @function
  2836. */
  2837. me.hideAttachmentPreview = function()
  2838. {
  2839. if ($attachmentPreview) {
  2840. $attachmentPreview.addClass('hidden');
  2841. }
  2842. };
  2843. /**
  2844. * checks if has any attachment preview
  2845. *
  2846. * @name AttachmentViewer.hasAttachmentPreview
  2847. * @function
  2848. * @return {JQuery}
  2849. */
  2850. me.hasAttachmentPreview = function()
  2851. {
  2852. return $attachmentPreview.children().length > 0;
  2853. }
  2854. /**
  2855. * checks if there is an attachment displayed
  2856. *
  2857. * @name AttachmentViewer.hasAttachment
  2858. * @function
  2859. */
  2860. me.hasAttachment = function()
  2861. {
  2862. if (!$attachment.length) {
  2863. return false;
  2864. }
  2865. return [...$attachment.children()].length > 0;
  2866. };
  2867. /**
  2868. * checks if there is attachment data (for preview!) available
  2869. *
  2870. * It returns true, when there is data that needs to be encrypted.
  2871. *
  2872. * @name AttachmentViewer.hasAttachmentData
  2873. * @function
  2874. */
  2875. me.hasAttachmentData = function()
  2876. {
  2877. if ($attachment.length) {
  2878. return true;
  2879. }
  2880. return false;
  2881. };
  2882. /**
  2883. * return the attachments
  2884. *
  2885. * @name AttachmentViewer.getAttachments
  2886. * @function
  2887. * @returns {array}
  2888. */
  2889. me.getAttachments = function()
  2890. {
  2891. return [...$attachment.find('a')].map(link => (
  2892. [
  2893. $(link).prop('href'),
  2894. $(link).prop('download')
  2895. ]
  2896. ));
  2897. };
  2898. /**
  2899. * Get attachment mime type
  2900. *
  2901. * @name AttachmentViewer.getAttachmentMimeType
  2902. * @function
  2903. * @param {string} attachmentData - Base64 string
  2904. */
  2905. me.getAttachmentMimeType = function(attachmentData)
  2906. {
  2907. // position in data URI string of where mimeType ends
  2908. const mimeTypeEnd = attachmentData.indexOf(';');
  2909. // extract mimeType
  2910. return attachmentData.substring(5, mimeTypeEnd);
  2911. }
  2912. /**
  2913. * moves the attachment link to another element
  2914. *
  2915. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  2916. *
  2917. * @name AttachmentViewer.moveAttachmentTo
  2918. * @function
  2919. * @param {jQuery} $element - the wrapper/container element where this should be moved to
  2920. * @param {array} attachment - attachment data
  2921. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  2922. */
  2923. me.moveAttachmentTo = function($element, attachment, label)
  2924. {
  2925. const attachmentLink = $(document.createElement('a'))
  2926. .addClass('alert-link')
  2927. .prop('href', attachment[0])
  2928. .prop('download', attachment[1]);
  2929. // move elemement to new place
  2930. attachmentLink.appendTo($element);
  2931. // update text - ensuring no HTML is inserted into the text node
  2932. I18n._(attachmentLink, label, attachment[1]);
  2933. };
  2934. /**
  2935. * read files data as data URL using the FileReader API
  2936. *
  2937. * @name AttachmentViewer.readFileData
  2938. * @private
  2939. * @function
  2940. * @param {FileList[]} loadedFiles (optional) loaded files array
  2941. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsDataURL()}
  2942. */
  2943. function readFileData(loadedFiles) {
  2944. // Clear old cache
  2945. me.removeAttachmentData();
  2946. if (typeof FileReader === 'undefined') {
  2947. // revert loading status…
  2948. me.hideAttachment();
  2949. me.hideAttachmentPreview();
  2950. Alert.showWarning('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2951. return;
  2952. }
  2953. if (loadedFiles === undefined) {
  2954. loadedFiles = [...$fileInput[0].files];
  2955. me.clearDragAndDrop();
  2956. } else {
  2957. const fileNames = loadedFiles.map((loadedFile => loadedFile.name));
  2958. printDragAndDropFileNames(fileNames);
  2959. }
  2960. if (typeof loadedFiles !== 'undefined') {
  2961. files = loadedFiles;
  2962. loadedFiles.forEach((loadedFile, index) => {
  2963. const fileReader = new FileReader();
  2964. fileReader.onload = function (event) {
  2965. const dataURL = event.target.result;
  2966. if (dataURL) {
  2967. attachmentsData[index] = dataURL;
  2968. }
  2969. if (Editor.isPreview()) {
  2970. me.handleAttachmentPreview($attachmentPreview, dataURL);
  2971. $attachmentPreview.removeClass('hidden');
  2972. }
  2973. TopNav.highlightFileupload();
  2974. };
  2975. fileReader.readAsDataURL(loadedFile);
  2976. });
  2977. } else {
  2978. me.removeAttachmentData();
  2979. }
  2980. }
  2981. /**
  2982. * handle the preview of files decoded to blob that can either be an image, video, audio or pdf element
  2983. *
  2984. * @name AttachmentViewer.handleBlobAttachmentPreview
  2985. * @function
  2986. * @argument {jQuery} $targetElement element where the preview should be appended
  2987. * @argument {string} file as a blob URL
  2988. * @argument {string} mime type
  2989. */
  2990. me.handleBlobAttachmentPreview = function ($targetElement, blobUrl, mimeType) {
  2991. const alreadyIncludesCurrentAttachment = $targetElement.find(`[src='${blobUrl}']`).length > 0;
  2992. if (blobUrl && !alreadyIncludesCurrentAttachment) {
  2993. if (mimeType.toLowerCase().startsWith('image/')) {
  2994. const image = document.createElement('img');
  2995. image.setAttribute('src', blobUrl);
  2996. image.setAttribute('class', 'img-thumbnail');
  2997. $targetElement[0].appendChild(image);
  2998. } else if (mimeType.toLowerCase().startsWith('video/')) {
  2999. const video = document.createElement('video');
  3000. video.setAttribute('controls', 'true');
  3001. video.setAttribute('autoplay', 'true');
  3002. video.setAttribute('class', 'img-thumbnail');
  3003. const source = document.createElement('source');
  3004. source.setAttribute('type', mimeType);
  3005. source.setAttribute('src', blobUrl);
  3006. video.appendChild(source);
  3007. $targetElement[0].appendChild(video);
  3008. } else if (mimeType.toLowerCase().startsWith('audio/')) {
  3009. const audio = document.createElement('audio');
  3010. audio.setAttribute('controls', 'true');
  3011. audio.setAttribute('autoplay', 'true');
  3012. const source = document.createElement('source');
  3013. source.setAttribute('type', mimeType);
  3014. source.setAttribute('src', blobUrl);
  3015. audio.appendChild(source);
  3016. $targetElement[0].appendChild(audio);
  3017. } else if (mimeType.toLowerCase().endsWith('/pdf')) {
  3018. const embed = document.createElement('embed');
  3019. embed.setAttribute('src', blobUrl);
  3020. embed.setAttribute('type', 'application/pdf');
  3021. embed.setAttribute('class', 'pdfPreview');
  3022. // Fallback for browsers, that don't support the vh unit
  3023. embed.style.height = window.innerHeight + 'px';
  3024. $targetElement[0].appendChild(embed);
  3025. }
  3026. }
  3027. };
  3028. /**
  3029. * attaches the file attachment drag & drop handler to the page
  3030. *
  3031. * @name AttachmentViewer.addDragDropHandler
  3032. * @private
  3033. * @function
  3034. */
  3035. function addDragDropHandler() {
  3036. if (typeof $fileInput === 'undefined' || $fileInput.length === 0) {
  3037. return;
  3038. }
  3039. const handleDragEnterOrOver = function(event) {
  3040. event.stopPropagation();
  3041. event.preventDefault();
  3042. return false;
  3043. };
  3044. const handleDrop = function(event) {
  3045. const evt = event.originalEvent;
  3046. evt.stopPropagation();
  3047. evt.preventDefault();
  3048. if (TopNav.isAttachmentReadonly()) {
  3049. return false;
  3050. }
  3051. if ($fileInput) {
  3052. const files = [...evt.dataTransfer.files];
  3053. //Clear the file input:
  3054. $fileInput.wrap('<form>').closest('form').get(0).reset();
  3055. $fileInput.unwrap();
  3056. //Only works in Chrome:
  3057. //fileInput[0].files = e.dataTransfer.files;
  3058. readFileData(files);
  3059. }
  3060. };
  3061. $(document).draghover().on({
  3062. 'draghoverstart': function(e) {
  3063. if (TopNav.isAttachmentReadonly()) {
  3064. e.stopPropagation();
  3065. e.preventDefault();
  3066. return false;
  3067. }
  3068. // show dropzone to indicate drop support
  3069. $dropzone.removeClass('hidden');
  3070. },
  3071. 'draghoverend': function() {
  3072. $dropzone.addClass('hidden');
  3073. }
  3074. });
  3075. $(document).on('drop', handleDrop);
  3076. $(document).on('dragenter dragover', handleDragEnterOrOver);
  3077. $fileInput.on('change', function () {
  3078. readFileData();
  3079. });
  3080. }
  3081. /**
  3082. * attaches the clipboard attachment handler to the page
  3083. *
  3084. * @name AttachmentViewer.addClipboardEventHandler
  3085. * @private
  3086. * @function
  3087. */
  3088. function addClipboardEventHandler() {
  3089. $('#message').on('paste', function (event) {
  3090. const items = (event.clipboardData || event.originalEvent.clipboardData).items;
  3091. const files = [...items]
  3092. .filter(item => item.kind === 'file')
  3093. .map(item => item.getAsFile());
  3094. if (TopNav.isAttachmentReadonly()) {
  3095. event.stopPropagation();
  3096. event.preventDefault();
  3097. return false;
  3098. }
  3099. readFileData(files);
  3100. });
  3101. }
  3102. /**
  3103. * getter for attachment data
  3104. *
  3105. * @name AttachmentViewer.getAttachmentsData
  3106. * @function
  3107. * @return {string[]}
  3108. */
  3109. me.getAttachmentsData = function () {
  3110. return attachmentsData;
  3111. };
  3112. /**
  3113. * getter for attachment preview
  3114. *
  3115. * @name AttachmentViewer.getAttachmentPreview
  3116. * @function
  3117. * @return {jQuery}
  3118. */
  3119. me.getAttachmentPreview = function () {
  3120. return $attachmentPreview;
  3121. };
  3122. /**
  3123. * getter for files data, returns the file list
  3124. *
  3125. * @name AttachmentViewer.getFiles
  3126. * @function
  3127. * @return {FileList[]}
  3128. */
  3129. me.getFiles = function () {
  3130. return files;
  3131. };
  3132. /**
  3133. * initiate
  3134. *
  3135. * preloads jQuery elements
  3136. *
  3137. * @name AttachmentViewer.init
  3138. * @function
  3139. */
  3140. me.init = function()
  3141. {
  3142. $attachment = $('#attachment');
  3143. $dragAndDropFileNames = $('#dragAndDropFileName');
  3144. $dropzone = $('#dropzone');
  3145. if($attachment.length) {
  3146. $attachmentPreview = $('#attachmentPreview');
  3147. $fileInput = $('#file');
  3148. addDragDropHandler();
  3149. addClipboardEventHandler();
  3150. }
  3151. }
  3152. return me;
  3153. })();
  3154. /**
  3155. * (view) Shows discussion thread and handles replies
  3156. *
  3157. * @name DiscussionViewer
  3158. * @class
  3159. */
  3160. const DiscussionViewer = (function () {
  3161. const me = {};
  3162. let $commentTail,
  3163. $discussion,
  3164. $reply,
  3165. $replyMessage,
  3166. $replyNickname,
  3167. $replyStatus,
  3168. $commentContainer,
  3169. replyCommentId;
  3170. /**
  3171. * initializes the templates
  3172. *
  3173. * @name DiscussionViewer.initTemplates
  3174. * @private
  3175. * @function
  3176. */
  3177. function initTemplates()
  3178. {
  3179. $reply = Model.getTemplate('reply');
  3180. $replyMessage = $reply.find('#replymessage');
  3181. $replyNickname = $reply.find('#nickname');
  3182. $replyStatus = $reply.find('#replystatus');
  3183. // cache jQuery elements
  3184. $commentTail = Model.getTemplate('commenttail');
  3185. }
  3186. /**
  3187. * open the comment entry when clicking the "Reply" button of a comment
  3188. *
  3189. * @name DiscussionViewer.openReply
  3190. * @private
  3191. * @function
  3192. * @param {Event} event
  3193. */
  3194. function openReply(event)
  3195. {
  3196. const $source = $(event.target);
  3197. // show all reply buttons
  3198. $commentContainer.find('button').removeClass('hidden');
  3199. // hide the current reply button
  3200. $source.addClass('hidden');
  3201. // clear input
  3202. $replyMessage.val('');
  3203. $replyNickname.val('');
  3204. // get comment id from source element
  3205. replyCommentId = $source.parent().prop('id').split('_')[1];
  3206. // move to correct position
  3207. $source.after($reply);
  3208. // show
  3209. $reply.removeClass('hidden');
  3210. $replyMessage.focus();
  3211. event.preventDefault();
  3212. }
  3213. /**
  3214. * custom handler for displaying notifications in own status message area
  3215. *
  3216. * @name DiscussionViewer.handleNotification
  3217. * @function
  3218. * @param {string} alertType
  3219. * @return {bool|jQuery}
  3220. */
  3221. me.handleNotification = function(alertType)
  3222. {
  3223. // ignore loading messages
  3224. if (alertType === 'loading') {
  3225. return false;
  3226. }
  3227. if (alertType === 'danger') {
  3228. $replyStatus.removeClass('alert-info');
  3229. $replyStatus.addClass('alert-danger');
  3230. $replyStatus.find(':first').removeClass('glyphicon-alert');
  3231. $replyStatus.find(':first').addClass('glyphicon-info-sign');
  3232. } else {
  3233. $replyStatus.removeClass('alert-danger');
  3234. $replyStatus.addClass('alert-info');
  3235. $replyStatus.find(':first').removeClass('glyphicon-info-sign');
  3236. $replyStatus.find(':first').addClass('glyphicon-alert');
  3237. }
  3238. return $replyStatus;
  3239. };
  3240. /**
  3241. * adds another comment
  3242. *
  3243. * @name DiscussionViewer.addComment
  3244. * @function
  3245. * @param {Comment} comment
  3246. * @param {string} commentText
  3247. * @param {string} nickname
  3248. */
  3249. me.addComment = function(comment, commentText, nickname)
  3250. {
  3251. if (commentText === '') {
  3252. commentText = 'comment decryption failed';
  3253. }
  3254. // create new comment based on template
  3255. const $commentEntry = Model.getTemplate('comment');
  3256. $commentEntry.prop('id', 'comment_' + comment.id);
  3257. const $commentEntryData = $commentEntry.find('div.commentdata');
  3258. // set & parse text
  3259. $commentEntryData.text(commentText);
  3260. Helper.urls2links($commentEntryData);
  3261. // set nickname
  3262. if (nickname.length > 0) {
  3263. $commentEntry.find('span.nickname').text(nickname);
  3264. } else {
  3265. const anonCommenter = document.createElement('em');
  3266. anonCommenter.textContent = I18n._('Anonymous');
  3267. $commentEntry.find('span.nickname')[0].innerHTML = '';
  3268. $commentEntry.find('span.nickname')[0].appendChild(anonCommenter);
  3269. }
  3270. // set date
  3271. const created = comment.getCreated();
  3272. const commentDate = created === 0 ? '' : ' (' + (new Date(created * 1000).toLocaleString()) + ')';
  3273. $commentEntry.find('span.commentdate')
  3274. .text(commentDate)
  3275. .attr('title', 'CommentID: ' + comment.id);
  3276. // if an avatar is available, display it
  3277. const icon = comment.getIcon();
  3278. if (icon) {
  3279. const image = document.createElement('img');
  3280. image.setAttribute('src', icon);
  3281. image.setAttribute('class', 'vizhash');
  3282. $commentEntry.find('span.nickname').prepend(' ').prepend(image);
  3283. }
  3284. // starting point (default value/fallback)
  3285. let $place = $commentContainer;
  3286. // if parent comment exists
  3287. const $parentComment = $('#comment_' + comment.parentid);
  3288. if ($parentComment.length) {
  3289. // use parent as position for new comment, so it is shifted
  3290. // to the right
  3291. $place = $parentComment;
  3292. }
  3293. // finally append comment
  3294. $place.append($commentEntry);
  3295. };
  3296. /**
  3297. * finishes the discussion area after last comment
  3298. *
  3299. * @name DiscussionViewer.finishDiscussion
  3300. * @function
  3301. */
  3302. me.finishDiscussion = function()
  3303. {
  3304. // add 'add new comment' area
  3305. $commentContainer.append($commentTail);
  3306. // show discussions
  3307. $discussion.removeClass('hidden');
  3308. };
  3309. /**
  3310. * removes the old discussion and prepares everything for creating a new
  3311. * one.
  3312. *
  3313. * @name DiscussionViewer.prepareNewDiscussion
  3314. * @function
  3315. */
  3316. me.prepareNewDiscussion = function()
  3317. {
  3318. $commentContainer.html('');
  3319. $discussion.addClass('hidden');
  3320. // (re-)init templates
  3321. initTemplates();
  3322. };
  3323. /**
  3324. * returns the users message from the reply form
  3325. *
  3326. * @name DiscussionViewer.getReplyMessage
  3327. * @function
  3328. * @return {String}
  3329. */
  3330. me.getReplyMessage = function()
  3331. {
  3332. return $replyMessage.val();
  3333. };
  3334. /**
  3335. * returns the users nickname (if any) from the reply form
  3336. *
  3337. * @name DiscussionViewer.getReplyNickname
  3338. * @function
  3339. * @return {String}
  3340. */
  3341. me.getReplyNickname = function()
  3342. {
  3343. return $replyNickname.val();
  3344. };
  3345. /**
  3346. * returns the id of the parent comment the user is replying to
  3347. *
  3348. * @name DiscussionViewer.getReplyCommentId
  3349. * @function
  3350. * @return {int|undefined}
  3351. */
  3352. me.getReplyCommentId = function()
  3353. {
  3354. return replyCommentId;
  3355. };
  3356. /**
  3357. * highlights a specific comment and scrolls to it if necessary
  3358. *
  3359. * @name DiscussionViewer.highlightComment
  3360. * @function
  3361. * @param {string} commentId
  3362. * @param {bool} fadeOut - whether to fade out the comment
  3363. */
  3364. me.highlightComment = function(commentId, fadeOut)
  3365. {
  3366. const $comment = $('#comment_' + commentId);
  3367. // in case comment does not exist, cancel
  3368. if ($comment.length === 0) {
  3369. return;
  3370. }
  3371. $comment.addClass('highlight');
  3372. const highlightComment = function () {
  3373. if (fadeOut === true) {
  3374. setTimeout(function () {
  3375. $comment.removeClass('highlight');
  3376. }, 300);
  3377. }
  3378. };
  3379. if (UiHelper.isVisible($comment)) {
  3380. return highlightComment();
  3381. }
  3382. UiHelper.scrollTo($comment, 100, 'swing', highlightComment);
  3383. };
  3384. /**
  3385. * initiate
  3386. *
  3387. * preloads jQuery elements
  3388. *
  3389. * @name DiscussionViewer.init
  3390. * @function
  3391. */
  3392. me.init = function()
  3393. {
  3394. // bind events to templates (so they are later cloned)
  3395. $('#commenttailtemplate, #commenttemplate').find('button').on('click', openReply);
  3396. $('#replytemplate').find('button').on('click', PasteEncrypter.sendComment);
  3397. $commentContainer = $('#commentcontainer');
  3398. $discussion = $('#discussion');
  3399. };
  3400. return me;
  3401. })();
  3402. /**
  3403. * Manage top (navigation) bar
  3404. *
  3405. * @name TopNav
  3406. * @param {object} window
  3407. * @param {object} document
  3408. * @class
  3409. */
  3410. const TopNav = (function (window, document) {
  3411. const me = {};
  3412. let createButtonsDisplayed = false,
  3413. viewButtonsDisplayed = false,
  3414. burnAfterReadingDefault = false,
  3415. openDiscussionDefault = false,
  3416. $attach,
  3417. $burnAfterReading,
  3418. $burnAfterReadingOption,
  3419. $cloneButton,
  3420. $customAttachment,
  3421. $expiration,
  3422. $fileRemoveButton,
  3423. $fileWrap,
  3424. $formatter,
  3425. $newButton,
  3426. $openDiscussion,
  3427. $openDiscussionOption,
  3428. $password,
  3429. $passwordInput,
  3430. $rawTextButton,
  3431. $downloadTextButton,
  3432. $qrCodeLink,
  3433. $emailLink,
  3434. $sendButton,
  3435. $retryButton,
  3436. pasteExpiration = null,
  3437. retryButtonCallback;
  3438. /**
  3439. * set the expiration on bootstrap templates in dropdown
  3440. *
  3441. * @name TopNav.updateExpiration
  3442. * @private
  3443. * @function
  3444. * @param {Event} event
  3445. */
  3446. function updateExpiration(event)
  3447. {
  3448. // get selected option
  3449. const target = $(event.target);
  3450. // update dropdown display and save new expiration time
  3451. $('#pasteExpirationDisplay').text(target.text());
  3452. pasteExpiration = target.data('expiration');
  3453. event.preventDefault();
  3454. }
  3455. /**
  3456. * set the format on bootstrap templates in dropdown from user interaction
  3457. *
  3458. * @name TopNav.updateFormat
  3459. * @private
  3460. * @function
  3461. * @param {Event} event
  3462. */
  3463. function updateFormat(event)
  3464. {
  3465. // get selected option
  3466. const $target = $(event.target);
  3467. // update dropdown display and save new format
  3468. const newFormat = $target.data('format');
  3469. $('#pasteFormatterDisplay').text($target.text());
  3470. PasteViewer.setFormat(newFormat);
  3471. event.preventDefault();
  3472. }
  3473. /**
  3474. * when "burn after reading" is checked, disable discussion
  3475. *
  3476. * @name TopNav.changeBurnAfterReading
  3477. * @private
  3478. * @function
  3479. */
  3480. function changeBurnAfterReading()
  3481. {
  3482. if (me.getBurnAfterReading()) {
  3483. $openDiscussionOption.addClass('buttondisabled');
  3484. $openDiscussion.prop('checked', false);
  3485. // if button is actually disabled, force-enable it and uncheck other button
  3486. $burnAfterReadingOption.removeClass('buttondisabled');
  3487. } else {
  3488. $openDiscussionOption.removeClass('buttondisabled');
  3489. }
  3490. }
  3491. /**
  3492. * when discussion is checked, disable "burn after reading"
  3493. *
  3494. * @name TopNav.changeOpenDiscussion
  3495. * @private
  3496. * @function
  3497. */
  3498. function changeOpenDiscussion()
  3499. {
  3500. if (me.getOpenDiscussion()) {
  3501. $burnAfterReadingOption.addClass('buttondisabled');
  3502. $burnAfterReading.prop('checked', false);
  3503. // if button is actually disabled, force-enable it and uncheck other button
  3504. $openDiscussionOption.removeClass('buttondisabled');
  3505. } else {
  3506. $burnAfterReadingOption.removeClass('buttondisabled');
  3507. }
  3508. }
  3509. /**
  3510. * Clear the password input in the top navigation
  3511. *
  3512. * @name TopNav.clearPasswordInput
  3513. * @function
  3514. */
  3515. function clearPasswordInput()
  3516. {
  3517. $passwordInput.val('');
  3518. }
  3519. /**
  3520. * Clear the attachment input in the top navigation.
  3521. *
  3522. * @name TopNav.clearAttachmentInput
  3523. * @function
  3524. */
  3525. function clearAttachmentInput()
  3526. {
  3527. // hide UI for selected files
  3528. // our up-to-date jQuery can handle it :)
  3529. $fileWrap.find('input').val('');
  3530. }
  3531. /**
  3532. * return raw text
  3533. *
  3534. * @name TopNav.rawText
  3535. * @private
  3536. * @function
  3537. */
  3538. function rawText()
  3539. {
  3540. TopNav.hideAllButtons();
  3541. Alert.showLoading('Showing raw text…', 'time');
  3542. let paste = PasteViewer.getText();
  3543. // push a new state to allow back navigation with browser back button
  3544. history.pushState(
  3545. {type: 'raw'},
  3546. document.title,
  3547. // recreate document URL
  3548. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  3549. CryptTool.base58encode(Model.getPasteKey())
  3550. );
  3551. // we use text/html instead of text/plain to avoid a bug when
  3552. // reloading the raw text view (it reverts to type text/html)
  3553. const $head = $('head').children().not('noscript, script, link[type="text/css"]'),
  3554. newDoc = document.open('text/html', 'replace');
  3555. newDoc.write('<!DOCTYPE html><html><head>');
  3556. for (let i = 0; i < $head.length; ++i) {
  3557. newDoc.write($head[i].outerHTML);
  3558. }
  3559. newDoc.write(
  3560. '</head><body><pre>' +
  3561. DOMPurify.sanitize(
  3562. Helper.htmlEntities(paste),
  3563. purifyHtmlConfig
  3564. ) +
  3565. '</pre></body></html>'
  3566. );
  3567. newDoc.close();
  3568. }
  3569. /**
  3570. * download text
  3571. *
  3572. * @name TopNav.downloadText
  3573. * @private
  3574. * @function
  3575. */
  3576. function downloadText()
  3577. {
  3578. const fileFormat = PasteViewer.getFormat() === 'markdown' ? '.md' : '.txt';
  3579. const filename = 'document-' + Model.getPasteId() + fileFormat;
  3580. const text = PasteViewer.getText();
  3581. const element = document.createElement('a');
  3582. element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  3583. element.setAttribute('download', filename);
  3584. element.style.display = 'none';
  3585. document.body.appendChild(element);
  3586. element.click();
  3587. document.body.removeChild(element);
  3588. }
  3589. /**
  3590. * saves the language in a cookie and reloads the page
  3591. *
  3592. * @name TopNav.setLanguage
  3593. * @private
  3594. * @function
  3595. * @param {Event} event
  3596. */
  3597. function setLanguage(event)
  3598. {
  3599. let lang = $(event.target).data('lang') || event.target.value;
  3600. document.cookie = 'lang=' + lang + '; SameSite=Lax; Secure';
  3601. window.location.reload();
  3602. event.preventDefault();
  3603. }
  3604. /**
  3605. * save the template in a cookie and reloads the page
  3606. *
  3607. * @name TopNav.setTemplate
  3608. * @private
  3609. * @function
  3610. * @param {Event} event
  3611. */
  3612. function setTemplate(event)
  3613. {
  3614. let template = $(event.target).data('template') || event.target.value;
  3615. document.cookie = 'template=' + template + '; SameSite=Lax; Secure';
  3616. window.location.reload();
  3617. event.preventDefault();
  3618. }
  3619. /**
  3620. * hides all messages and creates a new document
  3621. *
  3622. * @name TopNav.clickNewPaste
  3623. * @private
  3624. * @function
  3625. */
  3626. function clickNewPaste()
  3627. {
  3628. Controller.hideStatusMessages();
  3629. Controller.newPaste();
  3630. }
  3631. /**
  3632. * retrys some callback registered before
  3633. *
  3634. * @name TopNav.clickRetryButton
  3635. * @private
  3636. * @function
  3637. * @param {Event} event
  3638. */
  3639. function clickRetryButton(event)
  3640. {
  3641. retryButtonCallback(event);
  3642. }
  3643. /**
  3644. * removes the existing attachment
  3645. *
  3646. * @name TopNav.removeAttachment
  3647. * @private
  3648. * @function
  3649. * @param {Event} event
  3650. */
  3651. function removeAttachment(event)
  3652. {
  3653. // if custom attachment is used, remove it first
  3654. if (!$customAttachment.hasClass('hidden')) {
  3655. AttachmentViewer.removeAttachment();
  3656. $customAttachment.addClass('hidden');
  3657. $fileWrap.removeClass('hidden');
  3658. }
  3659. // in any case, remove saved attachment data
  3660. AttachmentViewer.removeAttachmentData();
  3661. clearAttachmentInput();
  3662. AttachmentViewer.clearDragAndDrop();
  3663. // pevent '#' from appearing in the URL
  3664. event.preventDefault();
  3665. }
  3666. /**
  3667. * Shows the QR code of the current document (URL).
  3668. *
  3669. * @name TopNav.displayQrCode
  3670. * @private
  3671. * @function
  3672. */
  3673. function displayQrCode()
  3674. {
  3675. const qrCanvas = kjua({
  3676. render: 'canvas',
  3677. text: window.location.href
  3678. });
  3679. $('#qrcode-display').html(qrCanvas);
  3680. }
  3681. /**
  3682. * Template Email body.
  3683. *
  3684. * @name TopNav.templateEmailBody
  3685. * @private
  3686. * @param {string} expirationDateString
  3687. * @param {bool} isBurnafterreading
  3688. */
  3689. function templateEmailBody(expirationDateString, isBurnafterreading)
  3690. {
  3691. const EOL = '\n';
  3692. const BULLET = ' - ';
  3693. let emailBody = '';
  3694. if (expirationDateString !== null || isBurnafterreading) {
  3695. emailBody += I18n._('Notice:');
  3696. emailBody += EOL;
  3697. if (expirationDateString !== null) {
  3698. emailBody += EOL;
  3699. emailBody += BULLET;
  3700. // avoid DOMPurify mess with forward slash in expirationDateString
  3701. emailBody += Helper.sprintf(
  3702. I18n._(
  3703. 'This link will expire after %s.',
  3704. '%s'
  3705. ),
  3706. expirationDateString
  3707. );
  3708. }
  3709. if (isBurnafterreading) {
  3710. emailBody += EOL;
  3711. emailBody += BULLET;
  3712. emailBody += I18n._(
  3713. 'This link can only be accessed once, do not use back or refresh button in your browser.'
  3714. );
  3715. }
  3716. emailBody += EOL;
  3717. emailBody += EOL;
  3718. }
  3719. emailBody += I18n._('Link:');
  3720. emailBody += EOL;
  3721. emailBody += $('#pasteurl').attr('href') || window.location.href; // href is tried first as it might have been shortened
  3722. return emailBody;
  3723. }
  3724. /**
  3725. * Trigger Email send.
  3726. *
  3727. * @name TopNav.triggerEmailSend
  3728. * @private
  3729. * @param {string} emailBody
  3730. */
  3731. function triggerEmailSend(emailBody)
  3732. {
  3733. window.open(
  3734. `mailto:?body=${encodeURIComponent(emailBody)}`,
  3735. '_self',
  3736. 'noopener, noreferrer'
  3737. );
  3738. }
  3739. /**
  3740. * Send Email with current document (URL).
  3741. *
  3742. * @name TopNav.sendEmail
  3743. * @private
  3744. * @function
  3745. * @param {Date|null} expirationDate date of expiration
  3746. * @param {bool} isBurnafterreading whether it is burn after reading
  3747. */
  3748. function sendEmail(expirationDate, isBurnafterreading)
  3749. {
  3750. const expirationDateRoundedToSecond = new Date(expirationDate);
  3751. // round down at least 30 seconds to make up for the delay of request
  3752. expirationDateRoundedToSecond.setUTCSeconds(
  3753. expirationDateRoundedToSecond.getUTCSeconds() - 30
  3754. );
  3755. expirationDateRoundedToSecond.setUTCSeconds(0);
  3756. const $emailconfirmmodal = $('#emailconfirmmodal');
  3757. if (expirationDate !== null) {
  3758. const $emailconfirmTimezoneCurrent = $emailconfirmmodal.find('#emailconfirm-timezone-current');
  3759. const $emailconfirmTimezoneUtc = $emailconfirmmodal.find('#emailconfirm-timezone-utc');
  3760. let localeConfiguration = { dateStyle: 'long', timeStyle: 'long' };
  3761. const bootstrap5EmailConfirmModal = typeof bootstrap !== 'undefined' && bootstrap.Tooltip.VERSION ?
  3762. new bootstrap.Modal($emailconfirmmodal[0]) : null;
  3763. function sendEmailAndHideModal() {
  3764. const emailBody = templateEmailBody(
  3765. // we don't use Date.prototype.toUTCString() because we would like to avoid GMT
  3766. expirationDateRoundedToSecond.toLocaleString(
  3767. [], localeConfiguration
  3768. ), isBurnafterreading
  3769. );
  3770. if (bootstrap5EmailConfirmModal) {
  3771. bootstrap5EmailConfirmModal.hide();
  3772. } else {
  3773. $emailconfirmmodal.modal('hide');
  3774. }
  3775. triggerEmailSend(emailBody);
  3776. }
  3777. $emailconfirmTimezoneCurrent.off('click.sendEmailCurrentTimezone');
  3778. $emailconfirmTimezoneCurrent.on('click.sendEmailCurrentTimezone', sendEmailAndHideModal);
  3779. $emailconfirmTimezoneUtc.off('click.sendEmailUtcTimezone');
  3780. $emailconfirmTimezoneUtc.on('click.sendEmailUtcTimezone', () => {
  3781. localeConfiguration.timeZone = 'UTC';
  3782. sendEmailAndHideModal();
  3783. });
  3784. if (bootstrap5EmailConfirmModal) {
  3785. bootstrap5EmailConfirmModal.show();
  3786. } else {
  3787. $emailconfirmmodal.modal('show');
  3788. }
  3789. } else {
  3790. triggerEmailSend(templateEmailBody(null, isBurnafterreading));
  3791. }
  3792. }
  3793. /**
  3794. * Shows all navigation elements for viewing an existing document
  3795. *
  3796. * @name TopNav.showViewButtons
  3797. * @function
  3798. */
  3799. me.showViewButtons = function()
  3800. {
  3801. if (viewButtonsDisplayed) {
  3802. return;
  3803. }
  3804. $newButton.removeClass('hidden');
  3805. $cloneButton.removeClass('hidden');
  3806. $rawTextButton.removeClass('hidden');
  3807. $downloadTextButton.removeClass('hidden');
  3808. $qrCodeLink.removeClass('hidden');
  3809. viewButtonsDisplayed = true;
  3810. };
  3811. /**
  3812. * Hides all navigation elements for viewing an existing document
  3813. *
  3814. * @name TopNav.hideViewButtons
  3815. * @function
  3816. */
  3817. me.hideViewButtons = function()
  3818. {
  3819. if (!viewButtonsDisplayed) {
  3820. return;
  3821. }
  3822. $cloneButton.addClass('hidden');
  3823. $newButton.addClass('hidden');
  3824. $rawTextButton.addClass('hidden');
  3825. $downloadTextButton.addClass('hidden');
  3826. $qrCodeLink.addClass('hidden');
  3827. me.hideEmailButton();
  3828. viewButtonsDisplayed = false;
  3829. };
  3830. /**
  3831. * Hides all elements belonging to existing documents
  3832. *
  3833. * @name TopNav.hideAllButtons
  3834. * @function
  3835. */
  3836. me.hideAllButtons = function()
  3837. {
  3838. me.hideViewButtons();
  3839. me.hideCreateButtons();
  3840. };
  3841. /**
  3842. * shows all elements needed when creating a new document
  3843. *
  3844. * @name TopNav.showCreateButtons
  3845. * @function
  3846. */
  3847. me.showCreateButtons = function()
  3848. {
  3849. if (createButtonsDisplayed) {
  3850. return;
  3851. }
  3852. $attach.removeClass('hidden');
  3853. $burnAfterReadingOption.removeClass('hidden');
  3854. $expiration.removeClass('hidden');
  3855. $formatter.removeClass('hidden');
  3856. $newButton.removeClass('hidden');
  3857. $openDiscussionOption.removeClass('hidden');
  3858. $password.removeClass('hidden');
  3859. $sendButton.removeClass('hidden');
  3860. createButtonsDisplayed = true;
  3861. };
  3862. /**
  3863. * shows all elements needed when creating a new document
  3864. *
  3865. * @name TopNav.hideCreateButtons
  3866. * @function
  3867. */
  3868. me.hideCreateButtons = function()
  3869. {
  3870. if (!createButtonsDisplayed) {
  3871. return;
  3872. }
  3873. $newButton.addClass('hidden');
  3874. $sendButton.addClass('hidden');
  3875. $expiration.addClass('hidden');
  3876. $formatter.addClass('hidden');
  3877. $burnAfterReadingOption.addClass('hidden');
  3878. $openDiscussionOption.addClass('hidden');
  3879. $password.addClass('hidden');
  3880. $attach.addClass('hidden');
  3881. createButtonsDisplayed = false;
  3882. };
  3883. /**
  3884. * only shows the "new document" button
  3885. *
  3886. * @name TopNav.showNewPasteButton
  3887. * @function
  3888. */
  3889. me.showNewPasteButton = function()
  3890. {
  3891. $newButton.removeClass('hidden');
  3892. };
  3893. /**
  3894. * only shows the "retry" button
  3895. *
  3896. * @name TopNav.showRetryButton
  3897. * @function
  3898. */
  3899. me.showRetryButton = function()
  3900. {
  3901. $retryButton.removeClass('hidden');
  3902. }
  3903. /**
  3904. * hides the "retry" button
  3905. *
  3906. * @name TopNav.hideRetryButton
  3907. * @function
  3908. */
  3909. me.hideRetryButton = function()
  3910. {
  3911. $retryButton.addClass('hidden');
  3912. }
  3913. /**
  3914. * show the "email" button
  3915. *
  3916. * @name TopNav.showEmailbutton
  3917. * @function
  3918. * @param {int|undefined} optionalRemainingTimeInSeconds
  3919. */
  3920. me.showEmailButton = function(optionalRemainingTimeInSeconds)
  3921. {
  3922. try {
  3923. // we cache expiration date in closure to avoid inaccurate expiration datetime
  3924. const expirationDate = Helper.calculateExpirationDate(
  3925. new Date(),
  3926. typeof optionalRemainingTimeInSeconds === 'number' ? optionalRemainingTimeInSeconds : TopNav.getExpiration()
  3927. );
  3928. const isBurnafterreading = TopNav.getBurnAfterReading();
  3929. $emailLink.removeClass('hidden');
  3930. $emailLink.off('click.sendEmail');
  3931. $emailLink.on('click.sendEmail', () => {
  3932. sendEmail(expirationDate, isBurnafterreading);
  3933. });
  3934. } catch (error) {
  3935. console.error(error);
  3936. Alert.showError('Cannot calculate expiration date.');
  3937. }
  3938. }
  3939. /**
  3940. * hide the "email" button
  3941. *
  3942. * @name TopNav.hideEmailButton
  3943. * @function
  3944. */
  3945. me.hideEmailButton = function()
  3946. {
  3947. $emailLink.addClass('hidden');
  3948. $emailLink.off('click.sendEmail');
  3949. }
  3950. /**
  3951. * only hides the clone button
  3952. *
  3953. * @name TopNav.hideCloneButton
  3954. * @function
  3955. */
  3956. me.hideCloneButton = function()
  3957. {
  3958. $cloneButton.addClass('hidden');
  3959. };
  3960. /**
  3961. * only hides the raw text button
  3962. *
  3963. * @name TopNav.hideRawButton
  3964. * @function
  3965. */
  3966. me.hideRawButton = function()
  3967. {
  3968. $rawTextButton.addClass('hidden');
  3969. };
  3970. /**
  3971. * only hides the download text button
  3972. *
  3973. * @name TopNav.hideRawButton
  3974. * @function
  3975. */
  3976. me.hideDownloadButton = function()
  3977. {
  3978. $downloadTextButton.addClass('hidden');
  3979. };
  3980. /**
  3981. * only hides the qr code button
  3982. *
  3983. * @name TopNav.hideQrCodeButton
  3984. * @function
  3985. */
  3986. me.hideQrCodeButton = function()
  3987. {
  3988. $qrCodeLink.addClass('hidden');
  3989. }
  3990. /**
  3991. * hide irrelevant buttons when viewing burn after reading document
  3992. *
  3993. * @name TopNav.hideBurnAfterReadingButtons
  3994. * @function
  3995. */
  3996. me.hideBurnAfterReadingButtons = function()
  3997. {
  3998. me.hideCloneButton();
  3999. me.hideQrCodeButton();
  4000. me.hideEmailButton();
  4001. }
  4002. /**
  4003. * hides the file selector in attachment
  4004. *
  4005. * @name TopNav.hideFileSelector
  4006. * @function
  4007. */
  4008. me.hideFileSelector = function()
  4009. {
  4010. $fileWrap.addClass('hidden');
  4011. };
  4012. /**
  4013. * shows the custom attachment
  4014. *
  4015. * @name TopNav.showCustomAttachment
  4016. * @function
  4017. */
  4018. me.showCustomAttachment = function()
  4019. {
  4020. $customAttachment.removeClass('hidden');
  4021. };
  4022. /**
  4023. * hides the custom attachment
  4024. *
  4025. * @name TopNav.hideCustomAttachment
  4026. * @function
  4027. */
  4028. me.hideCustomAttachment = function()
  4029. {
  4030. $customAttachment.addClass('hidden');
  4031. $fileWrap.removeClass('hidden');
  4032. };
  4033. /**
  4034. * collapses the navigation bar, only if expanded
  4035. *
  4036. * @name TopNav.collapseBar
  4037. * @function
  4038. */
  4039. me.collapseBar = function()
  4040. {
  4041. if ($('#navbar').attr('aria-expanded') === 'true') {
  4042. $('.navbar-toggle').click();
  4043. }
  4044. };
  4045. /**
  4046. * Reset the top navigation back to it's default values.
  4047. *
  4048. * @name TopNav.resetInput
  4049. * @function
  4050. */
  4051. me.resetInput = function()
  4052. {
  4053. clearAttachmentInput();
  4054. clearPasswordInput();
  4055. $burnAfterReading.prop('checked', burnAfterReadingDefault);
  4056. $openDiscussion.prop('checked', openDiscussionDefault);
  4057. if (openDiscussionDefault || !burnAfterReadingDefault) $openDiscussionOption.removeClass('buttondisabled');
  4058. if (burnAfterReadingDefault || !openDiscussionDefault) $burnAfterReadingOption.removeClass('buttondisabled');
  4059. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  4060. $('#pasteExpiration>option').each(function() {
  4061. const $this = $(this);
  4062. if ($this.val() === pasteExpiration) {
  4063. $('#pasteExpirationDisplay').text($this.text());
  4064. }
  4065. });
  4066. };
  4067. /**
  4068. * returns the currently set expiration time
  4069. *
  4070. * @name TopNav.getExpiration
  4071. * @function
  4072. * @return {int}
  4073. */
  4074. me.getExpiration = function()
  4075. {
  4076. return pasteExpiration;
  4077. };
  4078. /**
  4079. * returns the currently selected file(s)
  4080. *
  4081. * @name TopNav.getFileList
  4082. * @function
  4083. * @return {FileList|null}
  4084. */
  4085. me.getFileList = function()
  4086. {
  4087. const $file = $('#file');
  4088. // if no file given, return null
  4089. if (!$file.length || !$file[0].files.length) {
  4090. return null;
  4091. }
  4092. // ensure the selected file is still accessible
  4093. if (!($file[0].files && $file[0].files[0])) {
  4094. return null;
  4095. }
  4096. return $file[0].files;
  4097. };
  4098. /**
  4099. * returns the state of the burn after reading checkbox
  4100. *
  4101. * @name TopNav.getBurnAfterReading
  4102. * @function
  4103. * @return {bool}
  4104. */
  4105. me.getBurnAfterReading = function()
  4106. {
  4107. return $burnAfterReading.prop('checked');
  4108. };
  4109. /**
  4110. * returns the state of the discussion checkbox
  4111. *
  4112. * @name TopNav.getOpenDiscussion
  4113. * @function
  4114. * @return {bool}
  4115. */
  4116. me.getOpenDiscussion = function()
  4117. {
  4118. return $openDiscussion.prop('checked');
  4119. };
  4120. /**
  4121. * returns the entered password
  4122. *
  4123. * @name TopNav.getPassword
  4124. * @function
  4125. * @return {string}
  4126. */
  4127. me.getPassword = function()
  4128. {
  4129. // when password is disabled $passwordInput.val() will return undefined
  4130. return $passwordInput.val() || '';
  4131. };
  4132. /**
  4133. * returns the element where custom attachments can be placed
  4134. *
  4135. * Used by AttachmentViewer when an attachment is cloned here.
  4136. *
  4137. * @name TopNav.getCustomAttachment
  4138. * @function
  4139. * @return {jQuery}
  4140. */
  4141. me.getCustomAttachment = function()
  4142. {
  4143. return $customAttachment;
  4144. };
  4145. /**
  4146. * Set a function to call when the retry button is clicked.
  4147. *
  4148. * @name TopNav.setRetryCallback
  4149. * @function
  4150. * @param {function} callback
  4151. */
  4152. me.setRetryCallback = function(callback)
  4153. {
  4154. retryButtonCallback = callback;
  4155. }
  4156. /**
  4157. * Highlight file upload
  4158. *
  4159. * @name TopNav.highlightFileupload
  4160. * @function
  4161. */
  4162. me.highlightFileupload = function()
  4163. {
  4164. // visually indicate file uploaded
  4165. const $attachDropdownToggle = $attach.children('.dropdown-toggle');
  4166. if ($attachDropdownToggle.attr('aria-expanded') === 'false') {
  4167. if (Helper.isBootstrap5()) {
  4168. new bootstrap.Dropdown($attachDropdownToggle).toggle();
  4169. } else {
  4170. $attachDropdownToggle.click();
  4171. }
  4172. }
  4173. $fileWrap.addClass('highlight');
  4174. setTimeout(function () {
  4175. $fileWrap.removeClass('highlight');
  4176. }, 300);
  4177. }
  4178. /**
  4179. * set the format on bootstrap templates in dropdown programmatically
  4180. *
  4181. * @name TopNav.setFormat
  4182. * @function
  4183. */
  4184. me.setFormat = function(format)
  4185. {
  4186. $formatter.parent().find(`a[data-format="${format}"]`).click();
  4187. }
  4188. /**
  4189. * returns if attachment dropdown is readonly, not editable
  4190. *
  4191. * @name TopNav.isAttachmentReadonly
  4192. * @function
  4193. * @return {bool}
  4194. */
  4195. me.isAttachmentReadonly = function()
  4196. {
  4197. return !createButtonsDisplayed || $attach.hasClass('hidden');
  4198. }
  4199. /**
  4200. * init navigation manager
  4201. *
  4202. * preloads jQuery elements
  4203. *
  4204. * @name TopNav.init
  4205. * @function
  4206. */
  4207. me.init = function()
  4208. {
  4209. $attach = $('#attach');
  4210. $burnAfterReading = $('#burnafterreading');
  4211. $burnAfterReadingOption = $('#burnafterreadingoption');
  4212. $cloneButton = $('#clonebutton');
  4213. $customAttachment = $('#customattachment');
  4214. $expiration = $('#expiration');
  4215. $fileRemoveButton = $('#fileremovebutton');
  4216. $fileWrap = $('#filewrap');
  4217. $formatter = $('#formatter');
  4218. $newButton = $('#newbutton');
  4219. $openDiscussion = $('#opendiscussion');
  4220. $openDiscussionOption = $('#opendiscussionoption');
  4221. $password = $('#password');
  4222. $passwordInput = $('#passwordinput');
  4223. $rawTextButton = $('#rawtextbutton');
  4224. $downloadTextButton = $('#downloadtextbutton');
  4225. $retryButton = $('#retrybutton');
  4226. $sendButton = $('#sendbutton');
  4227. $qrCodeLink = $('#qrcodelink');
  4228. $emailLink = $('#emaillink');
  4229. // bootstrap template drop down
  4230. $('#language ul.dropdown-menu li a').click(setLanguage);
  4231. // bootstrap template drop down
  4232. $('#template ul.dropdown-menu li a').click(setTemplate);
  4233. // bind events
  4234. $burnAfterReading.change(changeBurnAfterReading);
  4235. $openDiscussionOption.change(changeOpenDiscussion);
  4236. $newButton.click(clickNewPaste);
  4237. $sendButton.click(PasteEncrypter.sendPaste);
  4238. $cloneButton.click(Controller.clonePaste);
  4239. $rawTextButton.click(rawText);
  4240. $downloadTextButton.click(downloadText);
  4241. $retryButton.click(clickRetryButton);
  4242. $fileRemoveButton.click(removeAttachment);
  4243. $qrCodeLink.click(displayQrCode);
  4244. // bootstrap template drop downs
  4245. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  4246. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  4247. // bootstrap5 & page drop downs
  4248. $('#pasteExpiration').on('change', function() {
  4249. pasteExpiration = Model.getExpirationDefault();
  4250. });
  4251. $('#pasteFormatter').on('change', function() {
  4252. PasteViewer.setFormat(Model.getFormatDefault());
  4253. });
  4254. // initiate default state of checkboxes
  4255. changeBurnAfterReading();
  4256. changeOpenDiscussion();
  4257. // get default values from template or fall back to set value
  4258. burnAfterReadingDefault = me.getBurnAfterReading();
  4259. openDiscussionDefault = me.getOpenDiscussion();
  4260. pasteExpiration = Model.getExpirationDefault();
  4261. createButtonsDisplayed = false;
  4262. viewButtonsDisplayed = false;
  4263. };
  4264. return me;
  4265. })(window, document);
  4266. /**
  4267. * Responsible for AJAX requests, transparently handles encryption…
  4268. *
  4269. * @name ServerInteraction
  4270. * @class
  4271. */
  4272. const ServerInteraction = (function () {
  4273. const me = {};
  4274. let successFunc = null,
  4275. failureFunc = null,
  4276. symmetricKey = null,
  4277. url,
  4278. data,
  4279. password;
  4280. /**
  4281. * public variable ('constant') for errors to prevent magic numbers
  4282. *
  4283. * @name ServerInteraction.error
  4284. * @readonly
  4285. * @enum {Object}
  4286. */
  4287. me.error = {
  4288. okay: 0,
  4289. custom: 1,
  4290. unknown: 2,
  4291. serverError: 3
  4292. };
  4293. /**
  4294. * ajaxHeaders to send in AJAX requests
  4295. *
  4296. * @name ServerInteraction.ajaxHeaders
  4297. * @private
  4298. * @readonly
  4299. * @enum {Object}
  4300. */
  4301. const ajaxHeaders = {
  4302. 'X-Requested-With': 'JSONHttpRequest',
  4303. 'Content-Type': 'application/json'
  4304. };
  4305. /**
  4306. * called after successful upload
  4307. *
  4308. * @name ServerInteraction.success
  4309. * @private
  4310. * @function
  4311. * @param {int} status
  4312. * @param {int} result - optional
  4313. */
  4314. function success(status, result)
  4315. {
  4316. if (successFunc !== null) {
  4317. // add useful data to result
  4318. result.encryptionKey = symmetricKey;
  4319. successFunc(status, result);
  4320. }
  4321. }
  4322. /**
  4323. * called after a upload failure
  4324. *
  4325. * @name ServerInteraction.fail
  4326. * @private
  4327. * @function
  4328. * @param {int} status - internal code
  4329. * @param {int} result - original error code
  4330. */
  4331. function fail(status, result)
  4332. {
  4333. if (failureFunc !== null) {
  4334. failureFunc(status, result);
  4335. }
  4336. }
  4337. /**
  4338. * actually uploads the data
  4339. *
  4340. * @name ServerInteraction.run
  4341. * @function
  4342. */
  4343. me.run = function()
  4344. {
  4345. let isPost = Object.keys(data).length > 0,
  4346. ajaxParams = {
  4347. type: isPost ? 'POST' : 'GET',
  4348. url: url,
  4349. headers: ajaxHeaders,
  4350. dataType: 'json',
  4351. success: function(result) {
  4352. if (result.status === 0) {
  4353. success(0, result);
  4354. } else if (result.status === 1) {
  4355. fail(1, result);
  4356. } else {
  4357. fail(2, result);
  4358. }
  4359. }
  4360. };
  4361. if (isPost) {
  4362. ajaxParams.data = JSON.stringify(data);
  4363. }
  4364. $.ajax(ajaxParams).fail(function(jqXHR, textStatus, errorThrown) {
  4365. console.error(textStatus, errorThrown);
  4366. fail(3, jqXHR);
  4367. });
  4368. };
  4369. /**
  4370. * return currently set data, used in unit testing
  4371. *
  4372. * @name ServerInteraction.getData
  4373. * @function
  4374. */
  4375. me.getData = function()
  4376. {
  4377. return data;
  4378. };
  4379. /**
  4380. * set success function
  4381. *
  4382. * @name ServerInteraction.setUrl
  4383. * @function
  4384. * @param {function} newUrl
  4385. */
  4386. me.setUrl = function(newUrl)
  4387. {
  4388. url = newUrl;
  4389. };
  4390. /**
  4391. * sets the password to use (first value) and optionally also the
  4392. * encryption key (not recommended, it is automatically generated).
  4393. *
  4394. * Note: Call this after prepare() as prepare() resets these values.
  4395. *
  4396. * @name ServerInteraction.setCryptValues
  4397. * @function
  4398. * @param {string} newPassword
  4399. * @param {string} newKey - optional
  4400. */
  4401. me.setCryptParameters = function(newPassword, newKey)
  4402. {
  4403. password = newPassword;
  4404. if (typeof newKey !== 'undefined') {
  4405. symmetricKey = newKey;
  4406. }
  4407. };
  4408. /**
  4409. * set success function
  4410. *
  4411. * @name ServerInteraction.setSuccess
  4412. * @function
  4413. * @param {function} func
  4414. */
  4415. me.setSuccess = function(func)
  4416. {
  4417. successFunc = func;
  4418. };
  4419. /**
  4420. * set failure function
  4421. *
  4422. * @name ServerInteraction.setFailure
  4423. * @function
  4424. * @param {function} func
  4425. */
  4426. me.setFailure = function(func)
  4427. {
  4428. failureFunc = func;
  4429. };
  4430. /**
  4431. * prepares a new upload
  4432. *
  4433. * Call this when doing a new upload to reset any data from potential
  4434. * previous uploads. Must be called before any other method of this
  4435. * module.
  4436. *
  4437. * @name ServerInteraction.prepare
  4438. * @function
  4439. * @return {object}
  4440. */
  4441. me.prepare = function()
  4442. {
  4443. // entropy should already be checked!
  4444. // reset password
  4445. password = '';
  4446. // reset key, so it a new one is generated when it is used
  4447. symmetricKey = null;
  4448. // reset data
  4449. successFunc = null;
  4450. failureFunc = null;
  4451. url = Helper.baseUri();
  4452. data = {};
  4453. };
  4454. /**
  4455. * encrypts and sets the data
  4456. *
  4457. * @name ServerInteraction.setCipherMessage
  4458. * @async
  4459. * @function
  4460. * @param {object} cipherMessage
  4461. */
  4462. me.setCipherMessage = async function(cipherMessage)
  4463. {
  4464. if (
  4465. symmetricKey === null ||
  4466. (typeof symmetricKey === 'string' && symmetricKey === '')
  4467. ) {
  4468. symmetricKey = CryptTool.getSymmetricKey();
  4469. }
  4470. if (!data.hasOwnProperty('adata')) {
  4471. data['adata'] = [];
  4472. }
  4473. let cipherResult = await CryptTool.cipher(symmetricKey, password, JSON.stringify(cipherMessage), data['adata']);
  4474. data['v'] = 2;
  4475. data['ct'] = cipherResult[0];
  4476. data['adata'] = cipherResult[1];
  4477. };
  4478. /**
  4479. * set the additional metadata to send unencrypted
  4480. *
  4481. * @name ServerInteraction.setUnencryptedData
  4482. * @function
  4483. * @param {string} index
  4484. * @param {mixed} element
  4485. */
  4486. me.setUnencryptedData = function(index, element)
  4487. {
  4488. data[index] = element;
  4489. };
  4490. /**
  4491. * Helper, which parses shows a general error message based on the result of the ServerInteraction
  4492. *
  4493. * @name ServerInteraction.parseUploadError
  4494. * @function
  4495. * @param {int} status
  4496. * @param {object} data
  4497. * @param {string} doThisThing - a human description of the action, which was tried
  4498. * @return {array}
  4499. */
  4500. me.parseUploadError = function(status, data, doThisThing) {
  4501. let errorArray;
  4502. switch (status) {
  4503. case me.error.custom:
  4504. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  4505. break;
  4506. case me.error.unknown:
  4507. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  4508. break;
  4509. case me.error.serverError:
  4510. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  4511. break;
  4512. default:
  4513. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  4514. break;
  4515. }
  4516. return errorArray;
  4517. };
  4518. return me;
  4519. })();
  4520. /**
  4521. * (controller) Responsible for encrypting document and sending it to server.
  4522. *
  4523. * Does upload, encryption is done transparently by ServerInteraction.
  4524. *
  4525. * @name PasteEncrypter
  4526. * @class
  4527. */
  4528. const PasteEncrypter = (function () {
  4529. const me = {};
  4530. /**
  4531. * called after successful document upload
  4532. *
  4533. * @name PasteEncrypter.showCreatedPaste
  4534. * @private
  4535. * @function
  4536. * @param {int} status
  4537. * @param {object} data
  4538. */
  4539. function showCreatedPaste(status, data) {
  4540. Alert.hideLoading();
  4541. Alert.hideMessages();
  4542. // show notification
  4543. const baseUri = Helper.baseUri() + '?',
  4544. url = baseUri + data.id + (TopNav.getBurnAfterReading() ? loadConfirmPrefix : '#') + CryptTool.base58encode(data.encryptionKey),
  4545. deleteUrl = baseUri + 'pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  4546. PasteStatus.createPasteNotification(url, deleteUrl);
  4547. // show new URL in browser bar
  4548. history.pushState({type: 'newpaste'}, document.title, url);
  4549. TopNav.showViewButtons();
  4550. CopyToClipboard.setUrl(url);
  4551. CopyToClipboard.showKeyboardShortcutHint();
  4552. // this cannot be grouped with showViewButtons due to remaining time calculation
  4553. TopNav.showEmailButton();
  4554. TopNav.hideRawButton();
  4555. TopNav.hideDownloadButton();
  4556. Editor.hide();
  4557. PasteStatus.checkAutoShorten();
  4558. // parse and show text
  4559. // (preparation already done in me.sendPaste())
  4560. PasteViewer.run();
  4561. }
  4562. /**
  4563. * called after successful comment upload
  4564. *
  4565. * @name PasteEncrypter.showUploadedComment
  4566. * @private
  4567. * @function
  4568. * @param {int} status
  4569. * @param {object} data
  4570. */
  4571. function showUploadedComment(status, data) {
  4572. // show success message
  4573. Alert.showStatus('Comment posted.');
  4574. // reload document
  4575. Controller.refreshPaste(function () {
  4576. // highlight sent comment
  4577. DiscussionViewer.highlightComment(data.id, true);
  4578. // reset error handler
  4579. Alert.setCustomHandler(null);
  4580. });
  4581. }
  4582. /**
  4583. * send a reply in a discussion
  4584. *
  4585. * @name PasteEncrypter.sendComment
  4586. * @async
  4587. * @function
  4588. */
  4589. me.sendComment = async function()
  4590. {
  4591. Alert.hideMessages();
  4592. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  4593. // UI loading state
  4594. TopNav.hideAllButtons();
  4595. Alert.showLoading('Sending comment…', 'cloud-upload');
  4596. // get data
  4597. const plainText = DiscussionViewer.getReplyMessage(),
  4598. nickname = DiscussionViewer.getReplyNickname(),
  4599. parentid = DiscussionViewer.getReplyCommentId();
  4600. // do not send if there is no data
  4601. if (plainText.length === 0) {
  4602. // revert loading status…
  4603. Alert.hideLoading();
  4604. Alert.setCustomHandler(null);
  4605. TopNav.showViewButtons();
  4606. return;
  4607. }
  4608. // prepare server interaction
  4609. ServerInteraction.prepare();
  4610. ServerInteraction.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  4611. // set success/fail functions
  4612. ServerInteraction.setSuccess(showUploadedComment);
  4613. ServerInteraction.setFailure(function (status, data) {
  4614. // revert loading status…
  4615. Alert.hideLoading();
  4616. TopNav.showViewButtons();
  4617. // …show error message…
  4618. Alert.showError(
  4619. ServerInteraction.parseUploadError(status, data, 'post comment')
  4620. );
  4621. // …and reset error handler
  4622. Alert.setCustomHandler(null);
  4623. });
  4624. // fill it with unencrypted params
  4625. ServerInteraction.setUnencryptedData('pasteid', Model.getPasteId());
  4626. if (typeof parentid === 'undefined') {
  4627. // if parent id is not set, this is the top-most comment, so use
  4628. // document id as parent, as the root element of the discussion tree
  4629. ServerInteraction.setUnencryptedData('parentid', Model.getPasteId());
  4630. } else {
  4631. ServerInteraction.setUnencryptedData('parentid', parentid);
  4632. }
  4633. // prepare cypher message
  4634. let cipherMessage = {
  4635. 'comment': plainText
  4636. };
  4637. if (nickname.length > 0) {
  4638. cipherMessage['nickname'] = nickname;
  4639. }
  4640. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4641. ServerInteraction.run();
  4642. };
  4643. /**
  4644. * sends a new document to server
  4645. *
  4646. * @name PasteEncrypter.sendPaste
  4647. * @async
  4648. * @function
  4649. */
  4650. me.sendPaste = async function()
  4651. {
  4652. // hide previous (error) messages
  4653. Controller.hideStatusMessages();
  4654. // UI loading state
  4655. TopNav.hideAllButtons();
  4656. Alert.showLoading('Sending document…', 'cloud-upload');
  4657. TopNav.collapseBar();
  4658. // get data
  4659. const plainText = Editor.getText(),
  4660. format = PasteViewer.getFormat(),
  4661. // the methods may return different values if no files are attached (null, undefined or false)
  4662. files = TopNav.getFileList() || AttachmentViewer.getFiles() || AttachmentViewer.hasAttachment();
  4663. // do not send if there is no data
  4664. if (plainText.length === 0 && !files) {
  4665. // revert loading status…
  4666. Alert.hideLoading();
  4667. TopNav.showCreateButtons();
  4668. return;
  4669. }
  4670. // prepare server interaction
  4671. ServerInteraction.prepare();
  4672. ServerInteraction.setCryptParameters(TopNav.getPassword());
  4673. // set success/fail functions
  4674. ServerInteraction.setSuccess(showCreatedPaste);
  4675. ServerInteraction.setFailure(function (status, data) {
  4676. // revert loading status…
  4677. Alert.hideLoading();
  4678. TopNav.showCreateButtons();
  4679. // show error message
  4680. Alert.showError(
  4681. ServerInteraction.parseUploadError(status, data, 'create document')
  4682. );
  4683. });
  4684. // fill it with unencrypted submitted options
  4685. ServerInteraction.setUnencryptedData('adata', [
  4686. null, format,
  4687. TopNav.getOpenDiscussion() ? 1 : 0,
  4688. TopNav.getBurnAfterReading() ? 1 : 0
  4689. ]);
  4690. ServerInteraction.setUnencryptedData('meta', {'expire': TopNav.getExpiration()});
  4691. // prepare PasteViewer for later preview
  4692. PasteViewer.setText(plainText);
  4693. PasteViewer.setFormat(format);
  4694. // prepare cypher message
  4695. let attachmentsData = AttachmentViewer.getAttachmentsData(),
  4696. cipherMessage = {
  4697. 'paste': plainText
  4698. };
  4699. if (attachmentsData.length) {
  4700. cipherMessage['attachment'] = attachmentsData;
  4701. cipherMessage['attachment_name'] = AttachmentViewer.getFiles().map((fileInfo => fileInfo.name));
  4702. } else if (AttachmentViewer.hasAttachment()) {
  4703. // fall back to cloned part
  4704. let attachments = AttachmentViewer.getAttachments();
  4705. cipherMessage['attachment'] = attachments.map(attachment => attachment[0]);
  4706. cipherMessage['attachment_name'] = attachments.map(attachment => attachment[1]);
  4707. cipherMessage['attachment'] = await Promise.all(cipherMessage['attachment'].map(async (attachment, i) => {
  4708. // we need to retrieve data from blob if browser already parsed it in memory
  4709. if (typeof attachment === 'string' && attachment.startsWith('blob:')) {
  4710. Alert.showStatus(
  4711. [
  4712. 'Retrieving cloned file \'%s\' from memory...',
  4713. cipherMessage['attachment_name'][i]
  4714. ],
  4715. 'copy'
  4716. );
  4717. try {
  4718. const blobData = await $.ajax({
  4719. type: 'GET',
  4720. url: attachment,
  4721. processData: false,
  4722. timeout: 10000,
  4723. dataType: 'binary',
  4724. xhrFields: {
  4725. withCredentials: false,
  4726. responseType: 'blob'
  4727. }
  4728. });
  4729. if (blobData instanceof window.Blob) {
  4730. const fileReading = new Promise(function(resolve, reject) {
  4731. const fileReader = new FileReader();
  4732. fileReader.onload = function (event) {
  4733. resolve(event.target.result);
  4734. };
  4735. fileReader.onerror = function (error) {
  4736. reject(error);
  4737. }
  4738. fileReader.readAsDataURL(blobData);
  4739. });
  4740. return await fileReading;
  4741. } else {
  4742. const error = 'Cannot process attachment data.';
  4743. Alert.showError(error);
  4744. throw new TypeError(error);
  4745. }
  4746. } catch (error) {
  4747. Alert.showError('Cannot retrieve attachment.');
  4748. throw error;
  4749. }
  4750. }
  4751. }));
  4752. }
  4753. // encrypt message
  4754. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4755. // send data
  4756. ServerInteraction.run();
  4757. };
  4758. return me;
  4759. })();
  4760. /**
  4761. * (controller) Responsible for decrypting cipherdata and passing data to view.
  4762. *
  4763. * Only decryption, no download.
  4764. *
  4765. * @name PasteDecrypter
  4766. * @class
  4767. */
  4768. const PasteDecrypter = (function () {
  4769. const me = {};
  4770. /**
  4771. * decrypt data or prompts for password in case of failure
  4772. *
  4773. * @name PasteDecrypter.decryptOrPromptPassword
  4774. * @private
  4775. * @async
  4776. * @function
  4777. * @param {string} key
  4778. * @param {string} password - optional, may be an empty string
  4779. * @param {string} cipherdata
  4780. * @throws {string}
  4781. * @return {false|string} false, when unsuccessful or string (decrypted data)
  4782. */
  4783. async function decryptOrPromptPassword(key, password, cipherdata)
  4784. {
  4785. // try decryption without password
  4786. const plaindata = await CryptTool.decipher(key, password, cipherdata);
  4787. // if it fails, request password
  4788. if (plaindata.length === 0 && password.length === 0) {
  4789. // show prompt
  4790. Prompt.requestPassword();
  4791. // Thus, we cannot do anything yet, we need to wait for the user
  4792. // input.
  4793. return false;
  4794. }
  4795. // if all tries failed, we can only return an error
  4796. if (plaindata.length === 0) {
  4797. return false;
  4798. }
  4799. return plaindata;
  4800. }
  4801. /**
  4802. * decrypt the actual document text
  4803. *
  4804. * @name PasteDecrypter.decryptPaste
  4805. * @private
  4806. * @async
  4807. * @function
  4808. * @param {Paste} paste - document data in object form
  4809. * @param {string} key
  4810. * @param {string} password
  4811. * @throws {string}
  4812. * @return {Promise}
  4813. */
  4814. async function decryptPaste(paste, key, password)
  4815. {
  4816. const pastePlain = await decryptOrPromptPassword(
  4817. key, password,
  4818. paste.getCipherData()
  4819. );
  4820. if (pastePlain === false) {
  4821. if (password.length === 0) {
  4822. throw 'waiting on user to provide a password';
  4823. } else {
  4824. Alert.hideLoading();
  4825. // reset password, so it can be re-entered
  4826. Prompt.reset();
  4827. TopNav.showRetryButton();
  4828. throw 'Could not decrypt data. Did you enter a wrong password? Retry with the button at the top.';
  4829. }
  4830. }
  4831. const pasteMessage = JSON.parse(pastePlain);
  4832. if (pasteMessage.hasOwnProperty('attachment') && pasteMessage.hasOwnProperty('attachment_name')) {
  4833. if (Array.isArray(pasteMessage.attachment) && Array.isArray(pasteMessage.attachment_name)) {
  4834. pasteMessage.attachment.forEach((attachment, key) => {
  4835. const attachment_name = pasteMessage.attachment_name[key];
  4836. AttachmentViewer.setAttachment(attachment, attachment_name);
  4837. });
  4838. } else {
  4839. // Continue to process attachment parameters as strings to ensure backward compatibility
  4840. AttachmentViewer.setAttachment(pasteMessage.attachment, pasteMessage.attachment_name);
  4841. }
  4842. AttachmentViewer.showAttachment();
  4843. }
  4844. PasteViewer.setFormat(paste.getFormat());
  4845. PasteViewer.setText(pasteMessage.paste);
  4846. PasteViewer.run();
  4847. }
  4848. /**
  4849. * decrypts all comments and shows them
  4850. *
  4851. * @name PasteDecrypter.decryptComments
  4852. * @private
  4853. * @async
  4854. * @function
  4855. * @param {Paste} paste - document data in object form
  4856. * @param {string} key
  4857. * @param {string} password
  4858. * @return {Promise}
  4859. */
  4860. async function decryptComments(paste, key, password)
  4861. {
  4862. // remove potential previous discussion
  4863. DiscussionViewer.prepareNewDiscussion();
  4864. const commentDecryptionPromises = [];
  4865. // iterate over comments
  4866. for (let i = 0; i < paste.comments.length; ++i) {
  4867. const comment = new Comment(paste.comments[i]),
  4868. commentPromise = CryptTool.decipher(key, password, comment.getCipherData());
  4869. paste.comments[i] = comment;
  4870. commentDecryptionPromises.push(
  4871. commentPromise.then(function (commentJson) {
  4872. const commentMessage = JSON.parse(commentJson);
  4873. return [
  4874. commentMessage.comment || '',
  4875. commentMessage.nickname || ''
  4876. ];
  4877. })
  4878. );
  4879. }
  4880. return Promise.all(commentDecryptionPromises).then(function (plaintexts) {
  4881. for (let i = 0; i < paste.comments.length; ++i) {
  4882. if (plaintexts[i][0].length === 0) {
  4883. continue;
  4884. }
  4885. DiscussionViewer.addComment(
  4886. paste.comments[i],
  4887. plaintexts[i][0],
  4888. plaintexts[i][1]
  4889. );
  4890. }
  4891. $(document).on('languageLoaded', function () {
  4892. $('#commentcontainer').find('img.vizhash')
  4893. .prop('title', I18n._('Avatar generated from IP address'));
  4894. });
  4895. });
  4896. }
  4897. /**
  4898. * show decrypted text in the display area, including discussion (if open)
  4899. *
  4900. * @name PasteDecrypter.run
  4901. * @function
  4902. * @param {Paste} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  4903. */
  4904. me.run = function(paste)
  4905. {
  4906. Alert.hideMessages();
  4907. Alert.setCustomHandler(null);
  4908. Alert.showLoading('Decrypting document…', 'cloud-download');
  4909. if (typeof paste === 'undefined' || paste.type === 'click') {
  4910. // get cipher data and wait until it is available
  4911. Model.getPasteData(me.run);
  4912. return;
  4913. }
  4914. let key = Model.getPasteKey(),
  4915. password = Prompt.getPassword(),
  4916. decryptionPromises = [];
  4917. TopNav.setRetryCallback(function () {
  4918. TopNav.hideRetryButton();
  4919. me.run(paste);
  4920. });
  4921. // Clear attachments to prevent duplicates
  4922. AttachmentViewer.removeAttachment();
  4923. // decrypt paste & attachments
  4924. decryptionPromises.push(decryptPaste(paste, key, password));
  4925. // if the discussion is opened on this document, display it
  4926. if (paste.isDiscussionEnabled()) {
  4927. decryptionPromises.push(decryptComments(paste, key, password));
  4928. }
  4929. // shows the remaining time (until) deletion
  4930. PasteStatus.showRemainingTime(paste);
  4931. CopyToClipboard.showKeyboardShortcutHint();
  4932. Promise.all(decryptionPromises)
  4933. .then(() => {
  4934. Alert.hideLoading();
  4935. TopNav.showViewButtons();
  4936. // discourage cloning (it cannot really be prevented)
  4937. if (paste.isBurnAfterReadingEnabled()) {
  4938. TopNav.hideBurnAfterReadingButtons();
  4939. } else {
  4940. // we have to pass in remaining_time here
  4941. TopNav.showEmailButton(paste.getTimeToLive());
  4942. }
  4943. // only offer adding comments, after document was successfully decrypted
  4944. if (paste.isDiscussionEnabled()) {
  4945. DiscussionViewer.finishDiscussion();
  4946. }
  4947. })
  4948. .catch((err) => {
  4949. // wait for the user to type in the password,
  4950. // then PasteDecrypter.run will be called again
  4951. Alert.showError(err);
  4952. });
  4953. };
  4954. return me;
  4955. })();
  4956. /**
  4957. *
  4958. * @name CopyToClipboard
  4959. * @class
  4960. */
  4961. const CopyToClipboard = (function () {
  4962. const me = {};
  4963. let copyButton,
  4964. copyLinkButton,
  4965. copyIcon,
  4966. successIcon,
  4967. shortcutHint,
  4968. url;
  4969. /**
  4970. * Handle copy to clipboard button click
  4971. *
  4972. * @name CopyToClipboard.handleCopyButtonClick
  4973. * @private
  4974. * @function
  4975. */
  4976. function handleCopyButtonClick() {
  4977. $(copyButton).click(function() {
  4978. const text = PasteViewer.getText();
  4979. saveToClipboard(text);
  4980. toggleSuccessIcon();
  4981. showAlertMessage('Document copied to clipboard');
  4982. });
  4983. }
  4984. /**
  4985. * Handle copy link to clipboard button click
  4986. *
  4987. * @name CopyToClipboard.handleCopyLinkButtonClick
  4988. * @private
  4989. * @function
  4990. */
  4991. function handleCopyLinkButtonClick() {
  4992. $(copyLinkButton).click(function () {
  4993. saveToClipboard(url);
  4994. showAlertMessage('Link copied to clipboard');
  4995. });
  4996. }
  4997. /**
  4998. * Handle CTRL+C/CMD+C keyboard shortcut
  4999. *
  5000. * @name CopyToClipboard.handleKeyboardShortcut
  5001. * @private
  5002. * @function
  5003. */
  5004. function handleKeyboardShortcut() {
  5005. $(document).bind('copy', function () {
  5006. if (!isUserSelectedTextToCopy()) {
  5007. const text = PasteViewer.getText();
  5008. saveToClipboard(text);
  5009. showAlertMessage('Document copied to clipboard');
  5010. }
  5011. });
  5012. }
  5013. /**
  5014. * Check if user selected some text on the page to copy it
  5015. *
  5016. * @name CopyToClipboard.isUserSelectedTextToCopy
  5017. * @private
  5018. * @function
  5019. * @returns {boolean}
  5020. */
  5021. function isUserSelectedTextToCopy() {
  5022. let text = '';
  5023. if (window.getSelection) {
  5024. text = window.getSelection().toString();
  5025. } else if (document.selection && document.selection.type !== 'Control') {
  5026. text = document.selection.createRange().text;
  5027. }
  5028. return text.length > 0;
  5029. }
  5030. /**
  5031. * Save text to the clipboard
  5032. *
  5033. * @name CopyToClipboard.saveToClipboard
  5034. * @private
  5035. * @param {string} text
  5036. * @function
  5037. */
  5038. function saveToClipboard(text) {
  5039. navigator.clipboard.writeText(text);
  5040. }
  5041. /**
  5042. * Show alert message after text copy
  5043. *
  5044. * @name CopyToClipboard.showAlertMessage
  5045. * @private
  5046. * @param {string} message
  5047. * @function
  5048. */
  5049. function showAlertMessage(message) {
  5050. Alert.showStatus(message);
  5051. }
  5052. /**
  5053. * Toogle success icon after copy
  5054. *
  5055. * @name CopyToClipboard.toggleSuccessIcon
  5056. * @private
  5057. * @function
  5058. */
  5059. function toggleSuccessIcon() {
  5060. $(copyIcon).css('display', 'none');
  5061. $(successIcon).css('display', 'block');
  5062. setTimeout(function() {
  5063. $(copyIcon).css('display', 'block');
  5064. $(successIcon).css('display', 'none');
  5065. }, 1000);
  5066. }
  5067. /**
  5068. * Show keyboard shortcut hint
  5069. *
  5070. * @name CopyToClipboard.showKeyboardShortcutHint
  5071. * @function
  5072. */
  5073. me.showKeyboardShortcutHint = function () {
  5074. I18n._(
  5075. shortcutHint,
  5076. '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>'
  5077. );
  5078. };
  5079. /**
  5080. * Hide keyboard shortcut hint
  5081. *
  5082. * @name CopyToClipboard.showKeyboardShortcutHint
  5083. * @function
  5084. */
  5085. me.hideKeyboardShortcutHint = function () {
  5086. $(shortcutHint).html('');
  5087. };
  5088. /**
  5089. * Set document url
  5090. *
  5091. * @name CopyToClipboard.setUrl
  5092. * @param {string} newUrl
  5093. * @function
  5094. */
  5095. me.setUrl = function (newUrl) {
  5096. url = newUrl;
  5097. };
  5098. /**
  5099. * Initialize
  5100. *
  5101. * @name CopyToClipboard.init
  5102. * @function
  5103. */
  5104. me.init = function() {
  5105. copyButton = $('#prettyMessageCopyBtn');
  5106. copyLinkButton = $('#copyLink');
  5107. copyIcon = $('#copyIcon');
  5108. successIcon = $('#copySuccessIcon');
  5109. shortcutHint = $('#copyShortcutHintText');
  5110. handleCopyButtonClick();
  5111. handleCopyLinkButtonClick();
  5112. handleKeyboardShortcut();
  5113. };
  5114. return me;
  5115. })();
  5116. /**
  5117. *
  5118. * @name PasswordPeek
  5119. * @class
  5120. */
  5121. const PasswordPeek = (function () {
  5122. const me = {};
  5123. /**
  5124. * Switch between visible and hidden password
  5125. *
  5126. * @name PasswordPeek.handleRevealButtonClick
  5127. * @private
  5128. * @function
  5129. */
  5130. function handleRevealButtonClick() {
  5131. const element = $(this);
  5132. const passwordInput = element.siblings('.input-password');
  5133. const isHidden = passwordInput.attr('type') === 'password';
  5134. passwordInput.attr('type', isHidden ? 'text' : 'password');
  5135. const tooltip = I18n._(isHidden ? 'Hide password' : 'Show password');
  5136. element.attr('title', tooltip);
  5137. element.attr('aria-label', tooltip);
  5138. // handle bootstrap 5 icons: eye & eye-slash
  5139. const buttonSvg = element.find('use');
  5140. if (buttonSvg.length) {
  5141. const iconHref = buttonSvg.attr('href');
  5142. if (isHidden) {
  5143. buttonSvg.attr('href', iconHref + '-slash');
  5144. } else {
  5145. buttonSvg.attr('href', iconHref.substring(0, iconHref.length - 6));
  5146. }
  5147. return;
  5148. }
  5149. // handle bootstrap 3 icons: eye-open & eye-close
  5150. const buttonSpan = element.find('span');
  5151. if (buttonSpan.length) {
  5152. if (isHidden) {
  5153. buttonSpan.addClass('glyphicon-eye-close');
  5154. buttonSpan.removeClass('glyphicon-eye-open');
  5155. } else {
  5156. buttonSpan.addClass('glyphicon-eye-open');
  5157. buttonSpan.removeClass('glyphicon-eye-close');
  5158. }
  5159. }
  5160. }
  5161. /**
  5162. * Initialize
  5163. *
  5164. * @name PasswordPeek.init
  5165. * @function
  5166. */
  5167. me.init = function() {
  5168. const revealButton = $('.toggle-password');
  5169. revealButton.click(handleRevealButtonClick);
  5170. };
  5171. return me;
  5172. })();
  5173. /**
  5174. * (controller) main PrivateBin logic
  5175. *
  5176. * @name Controller
  5177. * @param {object} window
  5178. * @param {object} document
  5179. * @class
  5180. */
  5181. const Controller = (function (window, document) {
  5182. const me = {};
  5183. /**
  5184. * hides all status messages no matter which module showed them
  5185. *
  5186. * @name Controller.hideStatusMessages
  5187. * @function
  5188. */
  5189. me.hideStatusMessages = function()
  5190. {
  5191. PasteStatus.hideMessages();
  5192. Alert.hideMessages();
  5193. CopyToClipboard.hideKeyboardShortcutHint();
  5194. };
  5195. /**
  5196. * creates a new document
  5197. *
  5198. * @name Controller.newPaste
  5199. * @function
  5200. */
  5201. me.newPaste = function()
  5202. {
  5203. // Important: This *must not* run Alert.hideMessages() as previous
  5204. // errors from viewing a document should be shown.
  5205. TopNav.hideAllButtons();
  5206. Alert.showLoading('Preparing new document…', 'time');
  5207. PasteStatus.hideMessages();
  5208. PasteViewer.hide();
  5209. Editor.resetInput();
  5210. Editor.show();
  5211. Editor.focusInput();
  5212. AttachmentViewer.removeAttachment();
  5213. TopNav.resetInput();
  5214. TopNav.showCreateButtons();
  5215. // newPaste could be called when user is on document clone editing view
  5216. TopNav.hideCustomAttachment();
  5217. AttachmentViewer.clearDragAndDrop();
  5218. AttachmentViewer.removeAttachmentData();
  5219. Alert.hideLoading();
  5220. // only push new state if we are coming from a different one
  5221. if (Helper.baseUri() !== window.location) {
  5222. history.pushState({type: 'create'}, document.title, Helper.baseUri());
  5223. }
  5224. // clear discussion
  5225. DiscussionViewer.prepareNewDiscussion();
  5226. };
  5227. /**
  5228. * shows the loaded document
  5229. *
  5230. * @name Controller.showPaste
  5231. * @function
  5232. */
  5233. me.showPaste = function()
  5234. {
  5235. try {
  5236. Model.getPasteKey();
  5237. } catch (err) {
  5238. console.error(err);
  5239. 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?)');
  5240. return;
  5241. }
  5242. // check if we should request loading confirmation
  5243. if(window.location.hash.startsWith(loadConfirmPrefix)) {
  5244. Prompt.requestLoadConfirmation();
  5245. return;
  5246. }
  5247. // show proper elements on screen
  5248. PasteDecrypter.run();
  5249. };
  5250. /**
  5251. * refreshes the loaded document to show potential new data
  5252. *
  5253. * @name Controller.refreshPaste
  5254. * @function
  5255. * @param {function} callback
  5256. */
  5257. me.refreshPaste = function(callback)
  5258. {
  5259. // save window position to restore it later
  5260. const orgPosition = $(window).scrollTop();
  5261. Model.getPasteData(function (data) {
  5262. ServerInteraction.prepare();
  5263. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + Model.getPasteId());
  5264. ServerInteraction.setFailure(function (status, data) {
  5265. // revert loading status…
  5266. Alert.hideLoading();
  5267. TopNav.showViewButtons();
  5268. // show error message
  5269. Alert.showError(
  5270. ServerInteraction.parseUploadError(status, data, 'refresh display')
  5271. );
  5272. });
  5273. ServerInteraction.setSuccess(function (status, data) {
  5274. PasteDecrypter.run(new Paste(data));
  5275. // restore position
  5276. window.scrollTo(0, orgPosition);
  5277. // NOTE: could create problems as callback may be called
  5278. // asyncronously if PasteDecrypter e.g. needs to wait for a
  5279. // password being entered
  5280. callback();
  5281. });
  5282. ServerInteraction.run();
  5283. }, false); // this false is important as it circumvents the cache
  5284. }
  5285. /**
  5286. * clone the current document
  5287. *
  5288. * @name Controller.clonePaste
  5289. * @function
  5290. */
  5291. me.clonePaste = function()
  5292. {
  5293. TopNav.collapseBar();
  5294. TopNav.hideAllButtons();
  5295. // hide messages from previous document
  5296. me.hideStatusMessages();
  5297. // erase the id and the key in url
  5298. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  5299. if (AttachmentViewer.hasAttachment()) {
  5300. const attachments = AttachmentViewer.getAttachments();
  5301. attachments.forEach(attachment => {
  5302. AttachmentViewer.moveAttachmentTo(
  5303. TopNav.getCustomAttachment(),
  5304. attachment,
  5305. 'Cloned: \'%s\''
  5306. );
  5307. });
  5308. TopNav.hideFileSelector();
  5309. AttachmentViewer.hideAttachment();
  5310. // NOTE: it also looks nice without removing the attachment
  5311. // but for a consistent display we remove it…
  5312. AttachmentViewer.hideAttachmentPreview();
  5313. TopNav.showCustomAttachment();
  5314. // show another status messages to make the user aware that the
  5315. // files were cloned too!
  5316. Alert.showStatus(
  5317. [
  5318. 'The cloned file \'%s\' was attached to this document.',
  5319. attachments.map(attachment => attachment[1]).join(', ')
  5320. ],
  5321. 'copy'
  5322. );
  5323. }
  5324. Editor.setText(PasteViewer.getText());
  5325. // also clone the format
  5326. TopNav.setFormat(PasteViewer.getFormat());
  5327. PasteViewer.hide();
  5328. Editor.show();
  5329. TopNav.showCreateButtons();
  5330. // clear discussion
  5331. DiscussionViewer.prepareNewDiscussion();
  5332. };
  5333. /**
  5334. * try initializing zlib or display a warning if it fails,
  5335. * extracted from main init to allow unit testing
  5336. *
  5337. * @name Controller.initZ
  5338. * @function
  5339. */
  5340. me.initZ = function()
  5341. {
  5342. z = zlib.catch(function () {
  5343. if ($('body').data('compression') !== 'none') {
  5344. Alert.showWarning('Your browser doesn\'t support WebAssembly, used for zlib compression. You can create uncompressed documents, but can\'t read compressed ones.');
  5345. }
  5346. });
  5347. }
  5348. /**
  5349. * application start
  5350. *
  5351. * @name Controller.init
  5352. * @function
  5353. */
  5354. me.init = function()
  5355. {
  5356. // first load translations
  5357. I18n.loadTranslations();
  5358. // Add a hook to make all links open a new window
  5359. DOMPurify.addHook('afterSanitizeAttributes', function(node) {
  5360. // set all elements owning target to target=_blank
  5361. if ('target' in node && node.id !== 'pasteurl') {
  5362. node.setAttribute('target', '_blank');
  5363. }
  5364. // set non-HTML/MathML links to xlink:show=new
  5365. if (!node.hasAttribute('target')
  5366. && (node.hasAttribute('xlink:href')
  5367. || node.hasAttribute('href'))) {
  5368. node.setAttribute('xlink:show', 'new');
  5369. }
  5370. if ('rel' in node) {
  5371. node.setAttribute('rel', 'nofollow noopener noreferrer');
  5372. }
  5373. });
  5374. // center all modals
  5375. $('.modal').on('show.bs.modal', function(e) {
  5376. $(e.target).css({
  5377. display: 'flex'
  5378. });
  5379. });
  5380. // initialize other modules/"classes"
  5381. Alert.init();
  5382. Model.init();
  5383. AttachmentViewer.init();
  5384. DiscussionViewer.init();
  5385. Editor.init();
  5386. PasteStatus.init();
  5387. PasteViewer.init();
  5388. Prompt.init();
  5389. TopNav.init();
  5390. UiHelper.init();
  5391. CopyToClipboard.init();
  5392. PasswordPeek.init();
  5393. // check for legacy browsers before going any further
  5394. if (!Legacy.Check.getInit()) {
  5395. // Legacy check didn't complete, wait and try again
  5396. setTimeout(init, 500);
  5397. return;
  5398. }
  5399. if (!Legacy.Check.getStatus()) {
  5400. // something major is wrong, stop right away
  5401. return;
  5402. }
  5403. me.initZ();
  5404. // if delete token is passed (i.e. document has been deleted by this
  5405. // access), add an event listener for the 'new' document button in the alert
  5406. if (Model.hasDeleteToken()) {
  5407. $('#new-from-alert').on('click', function () {
  5408. UiHelper.reloadHome();
  5409. });
  5410. return;
  5411. }
  5412. // check whether existing document needs to be shown
  5413. try {
  5414. Model.getPasteId();
  5415. } catch (e) {
  5416. // otherwise create a new document
  5417. return me.newPaste();
  5418. }
  5419. // always reload on back button to invalidate cache (protect burn after read document)
  5420. window.addEventListener('popstate', () => {
  5421. window.location.reload();
  5422. });
  5423. // display an existing document
  5424. return me.showPaste();
  5425. }
  5426. return me;
  5427. })(window, document);
  5428. return {
  5429. Helper: Helper,
  5430. I18n: I18n,
  5431. CryptTool: CryptTool,
  5432. Model: Model,
  5433. UiHelper: UiHelper,
  5434. Alert: Alert,
  5435. PasteStatus: PasteStatus,
  5436. Prompt: Prompt,
  5437. Editor: Editor,
  5438. PasteViewer: PasteViewer,
  5439. AttachmentViewer: AttachmentViewer,
  5440. DiscussionViewer: DiscussionViewer,
  5441. TopNav: TopNav,
  5442. ServerInteraction: ServerInteraction,
  5443. PasteEncrypter: PasteEncrypter,
  5444. PasteDecrypter: PasteDecrypter,
  5445. PasswordPeek: PasswordPeek,
  5446. CopyToClipboard: CopyToClipboard,
  5447. Controller: Controller
  5448. };
  5449. })(jQuery);