privatebin.js 189 KB

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