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. // global Base64, DOMPurify, FileReader, baseX, bootstrap, history, navigator, prettyPrint, prettyPrintOne, showdown, kjua
  13. jQuery.fn.draghover = function() {
  14. 'use strict';
  15. return this.each(function() {
  16. let collection = $(),
  17. self = $(this);
  18. self.on('dragenter', function(e) {
  19. if (collection.length === 0) {
  20. self.trigger('draghoverstart');
  21. }
  22. collection = collection.add(e.target);
  23. });
  24. self.on('dragleave drop', function(e) {
  25. collection = collection.not(e.target);
  26. if (collection.length === 0) {
  27. self.trigger('draghoverend');
  28. }
  29. });
  30. });
  31. };
  32. // main application start, called when DOM is fully loaded
  33. jQuery(document).ready(function() {
  34. 'use strict';
  35. // run main controller
  36. $.PrivateBin.Controller.init();
  37. });
  38. jQuery.PrivateBin = (function($) {
  39. 'use strict';
  40. /**
  41. * zlib library interface
  42. *
  43. * @private
  44. */
  45. let z;
  46. /**
  47. * DOMpurify settings for HTML content
  48. *
  49. * @private
  50. */
  51. const purifyHtmlConfig = {
  52. ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|magnet):)/i,
  53. USE_PROFILES: {
  54. html: true
  55. }
  56. };
  57. /**
  58. * DOMpurify settings for SVG content
  59. *
  60. * @private
  61. */
  62. const purifySvgConfig = {
  63. USE_PROFILES: {
  64. svg: true,
  65. svgFilters: true
  66. }
  67. };
  68. /**
  69. * URL fragment prefix requiring load confirmation
  70. *
  71. * @private
  72. */
  73. const loadConfirmPrefix = '#-';
  74. /**
  75. * CryptoData class
  76. *
  77. * bundles helper functions used in both document and comment formats
  78. *
  79. * @name CryptoData
  80. * @class
  81. */
  82. function CryptoData(data) {
  83. // store all keys in the default locations for drop-in replacement
  84. for (let key in data) {
  85. this[key] = data[key];
  86. }
  87. /**
  88. * gets the cipher data (cipher text + adata)
  89. *
  90. * @name CryptoData.getCipherData
  91. * @function
  92. * @return {Array}
  93. */
  94. this.getCipherData = function()
  95. {
  96. return [this.ct, this.adata];
  97. }
  98. }
  99. /**
  100. * Paste class
  101. *
  102. * bundles helper functions around the document formats
  103. *
  104. * @name Paste
  105. * @class
  106. */
  107. function Paste(data) {
  108. // inherit constructor and methods of CryptoData
  109. CryptoData.call(this, data);
  110. /**
  111. * gets the used formatter
  112. *
  113. * @name Paste.getFormat
  114. * @function
  115. * @return {string}
  116. */
  117. this.getFormat = function()
  118. {
  119. return this.adata[1];
  120. }
  121. /**
  122. * gets the remaining seconds before the document expires
  123. *
  124. * returns 0 if there is no expiration
  125. *
  126. * @name Paste.getTimeToLive
  127. * @function
  128. * @return {string}
  129. */
  130. this.getTimeToLive = function()
  131. {
  132. return this.meta.time_to_live || 0;
  133. }
  134. /**
  135. * is burn-after-reading enabled
  136. *
  137. * @name Paste.isBurnAfterReadingEnabled
  138. * @function
  139. * @return {bool}
  140. */
  141. this.isBurnAfterReadingEnabled = function()
  142. {
  143. return this.adata[3];
  144. }
  145. /**
  146. * are discussions enabled
  147. *
  148. * @name Paste.isDiscussionEnabled
  149. * @function
  150. * @return {bool}
  151. */
  152. this.isDiscussionEnabled = function()
  153. {
  154. return this.adata[2];
  155. }
  156. }
  157. /**
  158. * Comment class
  159. *
  160. * bundles helper functions around the comment formats
  161. *
  162. * @name Comment
  163. * @class
  164. */
  165. function Comment(data) {
  166. // inherit constructor and methods of CryptoData
  167. CryptoData.call(this, data);
  168. /**
  169. * gets the UNIX timestamp of the comment creation
  170. *
  171. * @name Comment.getCreated
  172. * @function
  173. * @return {int}
  174. */
  175. this.getCreated = function()
  176. {
  177. return this.meta['created'] || 0;
  178. }
  179. /**
  180. * gets the icon of the comment submitter
  181. *
  182. * @name Comment.getIcon
  183. * @function
  184. * @return {string}
  185. */
  186. this.getIcon = function()
  187. {
  188. return this.meta['icon'] || '';
  189. }
  190. }
  191. /**
  192. * static Helper methods
  193. *
  194. * @name Helper
  195. * @class
  196. */
  197. const Helper = (function () {
  198. const me = {};
  199. /**
  200. * character to HTML entity lookup table
  201. *
  202. * @see {@link https://github.com/janl/mustache.js/blob/master/mustache.js#L60}
  203. * @name Helper.entityMap
  204. * @private
  205. * @enum {Object}
  206. * @readonly
  207. */
  208. const entityMap = {
  209. '&': '&',
  210. '<': '&lt;',
  211. '>': '&gt;',
  212. '"': '&quot;',
  213. '\'': '&#39;',
  214. '/': '&#x2F;',
  215. '`': '&#x60;',
  216. '=': '&#x3D;'
  217. };
  218. /**
  219. * number of seconds in a minute
  220. *
  221. * @name Helper.minute
  222. * @private
  223. * @enum {number}
  224. * @readonly
  225. */
  226. const minute = 60;
  227. /**
  228. * number of seconds in an hour
  229. *
  230. * = 60 * 60 seconds
  231. *
  232. * @name Helper.minute
  233. * @private
  234. * @enum {number}
  235. * @readonly
  236. */
  237. const hour = 3600;
  238. /**
  239. * number of seconds in a day
  240. *
  241. * = 60 * 60 * 24 seconds
  242. *
  243. * @name Helper.day
  244. * @private
  245. * @enum {number}
  246. * @readonly
  247. */
  248. const day = 86400;
  249. /**
  250. * number of seconds in a week
  251. *
  252. * = 60 * 60 * 24 * 7 seconds
  253. *
  254. * @name Helper.week
  255. * @private
  256. * @enum {number}
  257. * @readonly
  258. */
  259. const week = 604800;
  260. /**
  261. * number of seconds in a month (30 days, an approximation)
  262. *
  263. * = 60 * 60 * 24 * 30 seconds
  264. *
  265. * @name Helper.month
  266. * @private
  267. * @enum {number}
  268. * @readonly
  269. */
  270. const month = 2592000;
  271. /**
  272. * number of seconds in a non-leap year
  273. *
  274. * = 60 * 60 * 24 * 365 seconds
  275. *
  276. * @name Helper.year
  277. * @private
  278. * @enum {number}
  279. * @readonly
  280. */
  281. const year = 31536000;
  282. /**
  283. * cache for script location
  284. *
  285. * @name Helper.baseUri
  286. * @private
  287. * @enum {string|null}
  288. */
  289. let baseUri = null;
  290. /**
  291. * converts a duration (in seconds) into human friendly approximation
  292. *
  293. * @name Helper.secondsToHuman
  294. * @function
  295. * @param {number} seconds
  296. * @return {Array}
  297. */
  298. me.secondsToHuman = function(seconds)
  299. {
  300. let v;
  301. if (seconds < minute)
  302. {
  303. v = Math.floor(seconds);
  304. return [v, 'second'];
  305. }
  306. if (seconds < hour)
  307. {
  308. v = Math.floor(seconds / minute);
  309. return [v, 'minute'];
  310. }
  311. if (seconds < day)
  312. {
  313. v = Math.floor(seconds / hour);
  314. return [v, 'hour'];
  315. }
  316. // If less than 2 months, display in days:
  317. if (seconds < (2 * month))
  318. {
  319. v = Math.floor(seconds / day);
  320. return [v, 'day'];
  321. }
  322. v = Math.floor(seconds / month);
  323. return [v, 'month'];
  324. };
  325. /**
  326. * converts a duration string into seconds
  327. *
  328. * The string is expected to be optional digits, followed by a time.
  329. * Supported times are: min, hour, day, month, year, never
  330. * Examples: 5min, 13hour, never
  331. *
  332. * @name Helper.durationToSeconds
  333. * @function
  334. * @param {String} duration
  335. * @return {number}
  336. */
  337. me.durationToSeconds = function(duration)
  338. {
  339. let pieces = duration.split(/(\D+)/),
  340. factor = pieces[0] || 0,
  341. timespan = pieces[1] || pieces[0];
  342. switch (timespan)
  343. {
  344. case 'min':
  345. return factor * minute;
  346. case 'hour':
  347. return factor * hour;
  348. case 'day':
  349. return factor * day;
  350. case 'week':
  351. return factor * week;
  352. case 'month':
  353. return factor * month;
  354. case 'year':
  355. return factor * year;
  356. case 'never':
  357. return 0;
  358. default:
  359. return factor;
  360. }
  361. };
  362. /**
  363. * text range selection
  364. *
  365. * @see {@link https://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse}
  366. * @name Helper.selectText
  367. * @function
  368. * @param {HTMLElement} element
  369. */
  370. me.selectText = function(element)
  371. {
  372. let range, selection;
  373. // MS
  374. if (document.body.createTextRange) {
  375. range = document.body.createTextRange();
  376. range.moveToElementText(element);
  377. range.select();
  378. } else if (window.getSelection) {
  379. selection = window.getSelection();
  380. range = document.createRange();
  381. range.selectNodeContents(element);
  382. selection.removeAllRanges();
  383. selection.addRange(range);
  384. }
  385. };
  386. /**
  387. * convert URLs to clickable links in the provided element.
  388. *
  389. * URLs to handle:
  390. * <pre>
  391. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  392. * https://example.com:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  393. * http://user:example.com@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  394. * </pre>
  395. *
  396. * @name Helper.urls2links
  397. * @function
  398. * @param {HTMLElement} element
  399. */
  400. me.urls2links = function(element)
  401. {
  402. element.html(
  403. DOMPurify.sanitize(
  404. element.html().replace(
  405. /(((https?|ftp):\/\/[\w?!=&.\/-;#@~%+*-]+(?![\w\s?!&.\/;#~%"=-]>))|((magnet):[\w?=&.\/-;#@~%+*-]+))/ig,
  406. '<a href="$1" rel="nofollow noopener noreferrer">$1</a>'
  407. ),
  408. purifyHtmlConfig
  409. )
  410. );
  411. };
  412. /**
  413. * minimal sprintf emulation for %s and %d formats
  414. *
  415. * Note that this function needs the parameters in the same order as the
  416. * format strings appear in the string, contrary to the original.
  417. *
  418. * @see {@link https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914}
  419. * @name Helper.sprintf
  420. * @function
  421. * @param {string} format
  422. * @param {...*} args - one or multiple parameters injected into format string
  423. * @return {string}
  424. */
  425. me.sprintf = function()
  426. {
  427. const args = Array.prototype.slice.call(arguments);
  428. let format = args[0],
  429. i = 1;
  430. return format.replace(/%(s|d)/g, function (m) {
  431. let val = args[i];
  432. if (m === '%d') {
  433. val = parseFloat(val);
  434. if (isNaN(val)) {
  435. val = 0;
  436. }
  437. }
  438. ++i;
  439. return val;
  440. });
  441. };
  442. /**
  443. * get value of cookie, if it was set, empty string otherwise
  444. *
  445. * @see {@link http://www.w3schools.com/js/js_cookies.asp}
  446. * @name Helper.getCookie
  447. * @function
  448. * @param {string} cname - may not be empty
  449. * @return {string}
  450. */
  451. me.getCookie = function(cname) {
  452. const name = cname + '=',
  453. ca = document.cookie.split(';');
  454. for (let i = 0; i < ca.length; ++i) {
  455. let c = ca[i];
  456. while (c.charAt(0) === ' ')
  457. {
  458. c = c.substring(1);
  459. }
  460. if (c.indexOf(name) === 0)
  461. {
  462. return c.substring(name.length, c.length);
  463. }
  464. }
  465. return '';
  466. };
  467. /**
  468. * get the current location (without search or hash part of the URL),
  469. * eg. https://example.com/path/?aaaa#bbbb --> https://example.com/path/
  470. *
  471. * @name Helper.baseUri
  472. * @function
  473. * @return {string}
  474. */
  475. me.baseUri = function()
  476. {
  477. // check for cached version
  478. if (baseUri !== null) {
  479. return baseUri;
  480. }
  481. baseUri = window.location.origin + window.location.pathname;
  482. return baseUri;
  483. };
  484. /**
  485. * wrap an object into a Paste, used for mocking in the unit tests
  486. *
  487. * @name Helper.PasteFactory
  488. * @function
  489. * @param {object} data
  490. * @return {Paste}
  491. */
  492. me.PasteFactory = function(data)
  493. {
  494. return new Paste(data);
  495. };
  496. /**
  497. * wrap an object into a Comment, used for mocking in the unit tests
  498. *
  499. * @name Helper.CommentFactory
  500. * @function
  501. * @param {object} data
  502. * @return {Comment}
  503. */
  504. me.CommentFactory = function(data)
  505. {
  506. return new Comment(data);
  507. };
  508. /**
  509. * convert all applicable characters to HTML entities
  510. *
  511. * @see {@link https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html}
  512. * @name Helper.htmlEntities
  513. * @function
  514. * @param {string} str
  515. * @return {string} escaped HTML
  516. */
  517. me.htmlEntities = function(str) {
  518. return String(str).replace(
  519. /[&<>"'`=\/]/g, function(s) {
  520. return entityMap[s];
  521. }
  522. );
  523. }
  524. /**
  525. * calculate expiration date given initial date and expiration period
  526. *
  527. * @name Helper.calculateExpirationDate
  528. * @function
  529. * @param {Date} initialDate - may not be empty
  530. * @param {string|number} expirationDisplayStringOrSecondsToExpire - may not be empty
  531. * @return {Date}
  532. */
  533. me.calculateExpirationDate = function(initialDate, expirationDisplayStringOrSecondsToExpire) {
  534. let expirationDate = new Date(initialDate),
  535. secondsToExpiration = expirationDisplayStringOrSecondsToExpire;
  536. if (typeof expirationDisplayStringOrSecondsToExpire === 'string') {
  537. secondsToExpiration = me.durationToSeconds(expirationDisplayStringOrSecondsToExpire);
  538. }
  539. if (typeof secondsToExpiration !== 'number') {
  540. throw new Error('Cannot calculate expiration date.');
  541. }
  542. if (secondsToExpiration === 0) {
  543. return null;
  544. }
  545. expirationDate = expirationDate.setUTCSeconds(expirationDate.getUTCSeconds() + secondsToExpiration);
  546. return expirationDate;
  547. };
  548. /**
  549. * Convert Bytes to kB/MB/GB/TB/PB/EB/ZB/YB
  550. *
  551. * @name Helper.formatBytes
  552. * @function
  553. *
  554. * @param {number} bytes
  555. * @return {string}
  556. */
  557. me.formatBytes = function (bytes)
  558. {
  559. let result = '';
  560. const kilobyte = 1000;
  561. const decimalPoint = 2;
  562. const sizes = [
  563. I18n._('B'), I18n._('kB'), I18n._('MB'), I18n._('GB'), I18n._('TB'),
  564. I18n._('PB'), I18n._('EB'), I18n._('ZB'), I18n._('YB')
  565. ];
  566. const index = Math.floor(Math.log(bytes) / Math.log(kilobyte));
  567. if (bytes > 0) {
  568. result = parseFloat((bytes / Math.pow(kilobyte, index)).toFixed(decimalPoint)) + ' ' + sizes[index];
  569. } else {
  570. result = `0 ${I18n._('B')}`;
  571. }
  572. return result;
  573. }
  574. /**
  575. * resets state, used for unit testing
  576. *
  577. * @name Helper.reset
  578. * @function
  579. */
  580. me.reset = function()
  581. {
  582. baseUri = null;
  583. };
  584. /**
  585. * check if bootstrap5 object detected
  586. *
  587. * @name Helper.isBootstrap5
  588. * @returns {Boolean}
  589. */
  590. me.isBootstrap5 = function ()
  591. {
  592. return typeof bootstrap !== 'undefined';
  593. };
  594. return me;
  595. })();
  596. /**
  597. * internationalization module
  598. *
  599. * @name I18n
  600. * @class
  601. */
  602. const I18n = (function () {
  603. const me = {};
  604. /**
  605. * const for string of loaded language
  606. *
  607. * @name I18n.languageLoadedEvent
  608. * @private
  609. * @prop {string}
  610. * @readonly
  611. */
  612. const languageLoadedEvent = 'languageLoaded';
  613. /**
  614. * supported languages, minus the built in 'en'
  615. *
  616. * @name I18n.supportedLanguages
  617. * @private
  618. * @prop {string[]}
  619. * @readonly
  620. */
  621. 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'];
  622. /**
  623. * built in language
  624. *
  625. * @name I18n.language
  626. * @private
  627. * @prop {string|null}
  628. */
  629. let language = null;
  630. /**
  631. * translation cache
  632. *
  633. * @name I18n.translations
  634. * @private
  635. * @enum {Object}
  636. */
  637. let translations = {};
  638. /**
  639. * translate a string, alias for I18n.translate
  640. *
  641. * @name I18n._
  642. * @function
  643. * @param {jQuery} $element - optional
  644. * @param {string} messageId
  645. * @param {...*} args - one or multiple parameters injected into placeholders
  646. * @return {string}
  647. */
  648. me._ = function()
  649. {
  650. return me.translate.apply(this, arguments);
  651. };
  652. /**
  653. * translate a string
  654. *
  655. * Optionally pass a jQuery element as the first parameter, to automatically
  656. * let the text of this element be replaced. In case the (asynchronously
  657. * loaded) language is not downloaded yet, this will make sure the string
  658. * is replaced when it eventually gets loaded. Using this is both simpler
  659. * and more secure, as it avoids potential XSS when inserting text.
  660. * The next parameter is the message ID, matching the ones found in
  661. * the translation files under the i18n directory.
  662. * Any additional parameters will get inserted into the message ID in
  663. * place of %s (strings) or %d (digits), applying the appropriate plural
  664. * in case of digits. See also Helper.sprintf().
  665. *
  666. * @name I18n.translate
  667. * @function
  668. * @param {jQuery} $element - optional
  669. * @param {string} messageId
  670. * @param {...*} args - one or multiple parameters injected into placeholders
  671. * @return {string}
  672. */
  673. me.translate = function()
  674. {
  675. // convert parameters to array
  676. let args = Array.prototype.slice.call(arguments),
  677. messageId,
  678. $element = null;
  679. // parse arguments
  680. if (args[0] instanceof jQuery) {
  681. // optional jQuery element as first parameter
  682. $element = args[0];
  683. args.shift();
  684. }
  685. // extract messageId from arguments
  686. let usesPlurals = $.isArray(args[0]);
  687. if (usesPlurals) {
  688. // use the first plural form as messageId, otherwise the singular
  689. messageId = args[0].length > 1 ? args[0][1] : args[0][0];
  690. } else {
  691. messageId = args[0];
  692. }
  693. if (messageId.length === 0) {
  694. return messageId;
  695. }
  696. // if no translation string cannot be found (in translations object)
  697. if (!translations.hasOwnProperty(messageId) || language === null) {
  698. // if language is still loading and we have an elemt assigned
  699. if (language === null && $element !== null) {
  700. // handle the error by attaching the language loaded event
  701. let orgArguments = arguments;
  702. $(document).on(languageLoadedEvent, function () {
  703. // re-execute this function
  704. me.translate.apply(this, orgArguments);
  705. });
  706. // and fall back to English for now until the real language
  707. // file is loaded
  708. }
  709. // for all other languages than English for which this behaviour
  710. // is expected as it is built-in, log error
  711. if (language !== null && language !== 'en') {
  712. console.error('Missing translation for: \'' + messageId + '\' in language ' + language);
  713. // fallback to English
  714. }
  715. // save English translation (should be the same on both sides)
  716. translations[messageId] = args[0];
  717. }
  718. // lookup plural translation
  719. if (usesPlurals && $.isArray(translations[messageId])) {
  720. let n = parseInt(args[1] || 1, 10),
  721. key = me.getPluralForm(n),
  722. maxKey = translations[messageId].length - 1;
  723. if (key > maxKey) {
  724. key = maxKey;
  725. }
  726. args[0] = translations[messageId][key];
  727. args[1] = n;
  728. } else {
  729. // lookup singular translation
  730. args[0] = translations[messageId];
  731. }
  732. // messageID may contain HTML, but should be from a trusted source (code or translation JSON files)
  733. let containsHtml = isStringContainsHtml(args[0]);
  734. // prevent double encoding, when we insert into a text node
  735. if (containsHtml || $element === null) {
  736. for (let i = 0; i < args.length; ++i) {
  737. // parameters (i > 0) may never contain HTML as they may come from untrusted parties
  738. if ((containsHtml ? i > 1 : i > 0) || !containsHtml) {
  739. args[i] = Helper.htmlEntities(args[i]);
  740. }
  741. }
  742. }
  743. // format string
  744. let output = Helper.sprintf.apply(this, args);
  745. if (containsHtml) {
  746. // only allow tags/attributes we actually use in translations
  747. output = DOMPurify.sanitize(
  748. output, {
  749. ALLOWED_TAGS: ['a', 'i', 'span', 'kbd'],
  750. ALLOWED_ATTR: ['href', 'id']
  751. }
  752. );
  753. }
  754. // if $element is given, insert translation
  755. if ($element !== null) {
  756. if (containsHtml) {
  757. $element.html(output);
  758. } else {
  759. // text node takes care of entity encoding
  760. $element.text(output);
  761. }
  762. return '';
  763. }
  764. return output;
  765. };
  766. /**
  767. * get currently loaded language
  768. *
  769. * @name I18n.getLanguage
  770. * @function
  771. * @return {string}
  772. */
  773. me.getLanguage = function()
  774. {
  775. return language;
  776. };
  777. /**
  778. * per language functions to use to determine the plural form
  779. *
  780. * @see {@link https://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html}
  781. * @name I18n.getPluralForm
  782. * @function
  783. * @param {int} n
  784. * @return {int} array key
  785. */
  786. me.getPluralForm = function(n) {
  787. switch (language)
  788. {
  789. case 'ar':
  790. return n === 0 ? 0 : (n === 1 ? 1 : (n === 2 ? 2 : (n % 100 >= 3 && n % 100 <= 10 ? 3 : (n % 100 >= 11 ? 4 : 5))));
  791. case 'cs':
  792. case 'sk':
  793. return n === 1 ? 0 : (n >= 2 && n <= 4 ? 1 : 2);
  794. case 'co':
  795. case 'fr':
  796. case 'oc':
  797. case 'tr':
  798. case 'zh':
  799. return n > 1 ? 1 : 0;
  800. case 'he':
  801. return n === 1 ? 0 : (n === 2 ? 1 : ((n < 0 || n > 10) && (n % 10 === 0) ? 2 : 3));
  802. case 'id':
  803. case 'ja':
  804. case 'jbo':
  805. case 'th':
  806. return 0;
  807. case 'lt':
  808. return n % 10 === 1 && n % 100 !== 11 ? 0 : ((n % 10 >= 2 && n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  809. case 'pl':
  810. return n === 1 ? 0 : (n % 10 >= 2 && n %10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  811. case 'ro':
  812. return n === 1 ? 0 : ((n === 0 || (n % 100 > 0 && n % 100 < 20)) ? 1 : 2);
  813. case 'ru':
  814. case 'uk':
  815. return n % 10 === 1 && n % 100 !== 11 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  816. case 'sl':
  817. return n % 100 === 1 ? 1 : (n % 100 === 2 ? 2 : (n % 100 === 3 || n % 100 === 4 ? 3 : 0));
  818. // bg, ca, de, el, en, es, et, fi, hu, it, nl, no, pt
  819. default:
  820. return n !== 1 ? 1 : 0;
  821. }
  822. };
  823. /**
  824. * load translations into cache
  825. *
  826. * @name I18n.loadTranslations
  827. * @function
  828. */
  829. me.loadTranslations = function()
  830. {
  831. let newLanguage = Helper.getCookie('lang');
  832. // auto-select language based on browser settings
  833. if (newLanguage.length === 0) {
  834. newLanguage = (navigator.language || navigator.userLanguage || 'en');
  835. if (newLanguage.indexOf('-') > 0) {
  836. newLanguage = newLanguage.split('-')[0];
  837. }
  838. }
  839. // if language is already used skip update
  840. if (newLanguage === language) {
  841. return;
  842. }
  843. // if language is built-in (English) skip update
  844. if (newLanguage === 'en') {
  845. language = 'en';
  846. return;
  847. }
  848. // if language is not supported, show error
  849. if (supportedLanguages.indexOf(newLanguage) === -1) {
  850. console.error('Language \'%s\' is not supported. Translation failed, fallback to English.', newLanguage);
  851. language = 'en';
  852. return;
  853. }
  854. // load strings from JSON
  855. const cacheBreaker = document.querySelector('script[src^="js/privatebin.js"]').getAttribute('src').split('.js')[1] || '';
  856. $.getJSON('i18n/' + newLanguage + '.json' + cacheBreaker, function(data) {
  857. language = newLanguage;
  858. translations = data;
  859. $(document).triggerHandler(languageLoadedEvent);
  860. }).fail(function (data, textStatus, errorMsg) {
  861. console.error('Language \'%s\' could not be loaded (%s: %s). Translation failed, fallback to English.', newLanguage, textStatus, errorMsg);
  862. language = 'en';
  863. });
  864. };
  865. /**
  866. * resets state, used for unit testing
  867. *
  868. * @name I18n.reset
  869. * @function
  870. */
  871. me.reset = function(mockLanguage, mockTranslations)
  872. {
  873. language = mockLanguage || null;
  874. translations = mockTranslations || {};
  875. };
  876. /**
  877. * Check if string contains valid HTML code
  878. *
  879. * @name I18n.isStringContainsHtml
  880. * @function
  881. * @private
  882. * @param {string} messageId
  883. * @returns {boolean}
  884. */
  885. function isStringContainsHtml(messageId) {
  886. // An integer which specifies the type of the node. An Element node like <p> or <div>.
  887. const elementNodeType = 1;
  888. const div = document.createElement('div');
  889. div.innerHTML = messageId;
  890. return Array.from(div.childNodes).some(node => node.nodeType === elementNodeType);
  891. }
  892. return me;
  893. })();
  894. /**
  895. * handles everything related to en/decryption
  896. *
  897. * @name CryptTool
  898. * @class
  899. */
  900. const CryptTool = (function () {
  901. const me = {};
  902. /**
  903. * base58 encoder & decoder
  904. *
  905. * @private
  906. */
  907. const base58 = new baseX('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
  908. /**
  909. * convert UTF-8 string stored in a DOMString to a standard UTF-16 DOMString
  910. *
  911. * Iterates over the bytes of the message, converting them all hexadecimal
  912. * percent encoded representations, then URI decodes them all
  913. *
  914. * @name CryptTool.utf8To16
  915. * @function
  916. * @private
  917. * @param {string} message UTF-8 string
  918. * @return {string} UTF-16 string
  919. */
  920. function utf8To16(message)
  921. {
  922. return decodeURIComponent(
  923. message.split('').map(
  924. function(character)
  925. {
  926. return '%' + ('00' + character.charCodeAt(0).toString(16)).slice(-2);
  927. }
  928. ).join('')
  929. );
  930. }
  931. /**
  932. * convert DOMString (UTF-16) to a UTF-8 string stored in a DOMString
  933. *
  934. * URI encodes the message, then finds the percent encoded characters
  935. * and transforms these hexadecimal representation back into bytes
  936. *
  937. * @name CryptTool.utf16To8
  938. * @function
  939. * @private
  940. * @param {string} message UTF-16 string
  941. * @return {string} UTF-8 string
  942. */
  943. function utf16To8(message)
  944. {
  945. return encodeURIComponent(message).replace(
  946. /%([0-9A-F]{2})/g,
  947. function (match, hexCharacter)
  948. {
  949. return String.fromCharCode('0x' + hexCharacter);
  950. }
  951. );
  952. }
  953. /**
  954. * convert ArrayBuffer into a UTF-8 string
  955. *
  956. * Iterates over the bytes of the array, catenating them into a string
  957. *
  958. * @name CryptTool.arraybufferToString
  959. * @function
  960. * @private
  961. * @param {ArrayBuffer} messageArray
  962. * @return {string} message
  963. */
  964. function arraybufferToString(messageArray)
  965. {
  966. const array = new Uint8Array(messageArray);
  967. let message = '',
  968. i = 0;
  969. while(i < array.length) {
  970. message += String.fromCharCode(array[i++]);
  971. }
  972. return message;
  973. }
  974. /**
  975. * convert UTF-8 string into a Uint8Array
  976. *
  977. * Iterates over the bytes of the message, writing them to the array
  978. *
  979. * @name CryptTool.stringToArraybuffer
  980. * @function
  981. * @private
  982. * @param {string} message UTF-8 string
  983. * @return {Uint8Array} array
  984. */
  985. function stringToArraybuffer(message)
  986. {
  987. const messageArray = new Uint8Array(message.length);
  988. for (let i = 0; i < message.length; ++i) {
  989. messageArray[i] = message.charCodeAt(i);
  990. }
  991. return messageArray;
  992. }
  993. /**
  994. * compress a string (deflate compression), returns buffer
  995. *
  996. * @name CryptTool.compress
  997. * @async
  998. * @function
  999. * @private
  1000. * @param {string} message
  1001. * @param {string} mode
  1002. * @param {object} zlib
  1003. * @throws {string}
  1004. * @return {ArrayBuffer} data
  1005. */
  1006. async function compress(message, mode, zlib)
  1007. {
  1008. message = stringToArraybuffer(
  1009. utf16To8(message)
  1010. );
  1011. if (mode === 'zlib') {
  1012. if (typeof zlib === 'undefined') {
  1013. throw 'Error compressing document, due to missing WebAssembly support.'
  1014. }
  1015. return zlib.deflate(message).buffer;
  1016. }
  1017. return message;
  1018. }
  1019. /**
  1020. * decompress potentially base64 encoded, deflate compressed buffer, returns string
  1021. *
  1022. * @name CryptTool.decompress
  1023. * @async
  1024. * @function
  1025. * @private
  1026. * @param {ArrayBuffer} data
  1027. * @param {string} mode
  1028. * @param {object} zlib
  1029. * @throws {string}
  1030. * @return {string} message
  1031. */
  1032. async function decompress(data, mode, zlib)
  1033. {
  1034. if (mode === 'zlib') {
  1035. if (typeof zlib === 'undefined') {
  1036. throw 'Error decompressing document, your browser does not support WebAssembly. Please use another browser to view this document.'
  1037. }
  1038. data = zlib.inflate(
  1039. new Uint8Array(data)
  1040. ).buffer;
  1041. }
  1042. return utf8To16(
  1043. arraybufferToString(data)
  1044. );
  1045. }
  1046. /**
  1047. * returns specified number of random bytes
  1048. *
  1049. * @name CryptTool.getRandomBytes
  1050. * @function
  1051. * @private
  1052. * @param {int} length number of random bytes to fetch
  1053. * @throws {string}
  1054. * @return {string} random bytes
  1055. */
  1056. function getRandomBytes(length)
  1057. {
  1058. let bytes = '';
  1059. const byteArray = new Uint8Array(length);
  1060. window.crypto.getRandomValues(byteArray);
  1061. for (let i = 0; i < length; ++i) {
  1062. bytes += String.fromCharCode(byteArray[i]);
  1063. }
  1064. return bytes;
  1065. }
  1066. /**
  1067. * derive cryptographic key from key string and password
  1068. *
  1069. * @name CryptTool.deriveKey
  1070. * @async
  1071. * @function
  1072. * @private
  1073. * @param {string} key
  1074. * @param {string} password
  1075. * @param {array} spec cryptographic specification
  1076. * @return {CryptoKey} derived key
  1077. */
  1078. async function deriveKey(key, password, spec)
  1079. {
  1080. let keyArray = stringToArraybuffer(key);
  1081. if (password.length > 0) {
  1082. let passwordArray = stringToArraybuffer(password),
  1083. newKeyArray = new Uint8Array(keyArray.length + passwordArray.length);
  1084. newKeyArray.set(keyArray, 0);
  1085. newKeyArray.set(passwordArray, keyArray.length);
  1086. keyArray = newKeyArray;
  1087. }
  1088. // import raw key
  1089. const importedKey = await window.crypto.subtle.importKey(
  1090. 'raw', // only 'raw' is allowed
  1091. keyArray,
  1092. {name: 'PBKDF2'}, // we use PBKDF2 for key derivation
  1093. false, // the key may not be exported
  1094. ['deriveKey'] // we may only use it for key derivation
  1095. ).catch(Alert.showError);
  1096. // derive a stronger key for use with AES
  1097. return window.crypto.subtle.deriveKey(
  1098. {
  1099. name: 'PBKDF2', // we use PBKDF2 for key derivation
  1100. salt: stringToArraybuffer(spec[1]), // salt used in HMAC
  1101. iterations: spec[2], // amount of iterations to apply
  1102. hash: {name: 'SHA-256'} // can be "SHA-1", "SHA-256", "SHA-384" or "SHA-512"
  1103. },
  1104. importedKey,
  1105. {
  1106. name: 'AES-' + spec[6].toUpperCase(), // can be any supported AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH" or "HMAC")
  1107. length: spec[3] // can be 128, 192 or 256
  1108. },
  1109. false, // the key may not be exported
  1110. ['encrypt', 'decrypt'] // we may only use it for en- and decryption
  1111. ).catch(Alert.showError);
  1112. }
  1113. /**
  1114. * gets crypto settings from specification and authenticated data
  1115. *
  1116. * @name CryptTool.cryptoSettings
  1117. * @function
  1118. * @private
  1119. * @param {string} adata authenticated data
  1120. * @param {array} spec cryptographic specification
  1121. * @return {object} crypto settings
  1122. */
  1123. function cryptoSettings(adata, spec)
  1124. {
  1125. return {
  1126. name: 'AES-' + spec[6].toUpperCase(), // can be any supported AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH" or "HMAC")
  1127. iv: stringToArraybuffer(spec[0]), // the initialization vector you used to encrypt
  1128. additionalData: stringToArraybuffer(adata), // the addtional data you used during encryption (if any)
  1129. tagLength: spec[4] // the length of the tag you used to encrypt (if any)
  1130. };
  1131. }
  1132. /**
  1133. * compress, then encrypt message with given key and password
  1134. *
  1135. * @name CryptTool.cipher
  1136. * @async
  1137. * @function
  1138. * @param {string} key
  1139. * @param {string} password
  1140. * @param {string} message
  1141. * @param {array} adata
  1142. * @return {array} encrypted message in base64 encoding & adata containing encryption spec
  1143. */
  1144. me.cipher = async function(key, password, message, adata)
  1145. {
  1146. let zlib = (await z);
  1147. // AES in Galois Counter Mode, keysize 256 bit,
  1148. // authentication tag 128 bit, 10000 iterations in key derivation
  1149. const compression = (
  1150. typeof zlib === 'undefined' ?
  1151. 'none' : // client lacks support for WASM
  1152. ($('body').data('compression') || 'zlib')
  1153. ),
  1154. spec = [
  1155. getRandomBytes(16), // initialization vector
  1156. getRandomBytes(8), // salt
  1157. 100000, // iterations
  1158. 256, // key size
  1159. 128, // tag size
  1160. 'aes', // algorithm
  1161. 'gcm', // algorithm mode
  1162. compression // compression
  1163. ], encodedSpec = [];
  1164. for (let i = 0; i < spec.length; ++i) {
  1165. encodedSpec[i] = i < 2 ? btoa(spec[i]) : spec[i];
  1166. }
  1167. if (adata.length === 0) {
  1168. // comment
  1169. adata = encodedSpec;
  1170. } else if (adata[0] === null) {
  1171. // paste
  1172. adata[0] = encodedSpec;
  1173. }
  1174. // finally, encrypt message
  1175. return [
  1176. btoa(
  1177. arraybufferToString(
  1178. await window.crypto.subtle.encrypt(
  1179. cryptoSettings(JSON.stringify(adata), spec),
  1180. await deriveKey(key, password, spec),
  1181. await compress(message, compression, zlib)
  1182. ).catch(Alert.showError)
  1183. )
  1184. ),
  1185. adata
  1186. ];
  1187. };
  1188. /**
  1189. * decrypt message with key, then decompress
  1190. *
  1191. * @name CryptTool.decipher
  1192. * @async
  1193. * @function
  1194. * @param {string} key
  1195. * @param {string} password
  1196. * @param {string|object} data encrypted message
  1197. * @return {string} decrypted message, empty if decryption failed
  1198. */
  1199. me.decipher = async function(key, password, data)
  1200. {
  1201. let adataString, spec, cipherMessage, plaintext;
  1202. let zlib = (await z);
  1203. if (data instanceof Array) {
  1204. // version 2
  1205. adataString = JSON.stringify(data[1]);
  1206. // clone the array instead of passing the reference
  1207. spec = (data[1][0] instanceof Array ? data[1][0] : data[1]).slice();
  1208. cipherMessage = data[0];
  1209. } else {
  1210. throw 'unsupported message format';
  1211. }
  1212. spec[0] = atob(spec[0]);
  1213. spec[1] = atob(spec[1]);
  1214. if (spec[7] === 'zlib') {
  1215. if (typeof zlib === 'undefined') {
  1216. throw 'Error decompressing document, your browser does not support WebAssembly. Please use another browser to view this document.'
  1217. }
  1218. }
  1219. try {
  1220. plaintext = await window.crypto.subtle.decrypt(
  1221. cryptoSettings(adataString, spec),
  1222. await deriveKey(key, password, spec),
  1223. stringToArraybuffer(
  1224. atob(cipherMessage)
  1225. )
  1226. );
  1227. } catch(err) {
  1228. console.error(err);
  1229. return '';
  1230. }
  1231. try {
  1232. return await decompress(plaintext, spec[7], zlib);
  1233. } catch(err) {
  1234. Alert.showError(err);
  1235. return err;
  1236. }
  1237. };
  1238. /**
  1239. * returns a random symmetric key
  1240. *
  1241. * generates 256 bit long keys (8 Bits * 32) for AES with 256 bit long blocks
  1242. *
  1243. * @name CryptTool.getSymmetricKey
  1244. * @function
  1245. * @throws {string}
  1246. * @return {string} raw bytes
  1247. */
  1248. me.getSymmetricKey = function()
  1249. {
  1250. return getRandomBytes(32);
  1251. };
  1252. /**
  1253. * base58 encode a DOMString (UTF-16)
  1254. *
  1255. * @name CryptTool.base58encode
  1256. * @function
  1257. * @param {string} input
  1258. * @return {string} output
  1259. */
  1260. me.base58encode = function(input)
  1261. {
  1262. return base58.encode(
  1263. stringToArraybuffer(input)
  1264. );
  1265. }
  1266. /**
  1267. * base58 decode a DOMString (UTF-16)
  1268. *
  1269. * @name CryptTool.base58decode
  1270. * @function
  1271. * @param {string} input
  1272. * @return {string} output
  1273. */
  1274. me.base58decode = function(input)
  1275. {
  1276. return arraybufferToString(
  1277. base58.decode(input)
  1278. );
  1279. }
  1280. return me;
  1281. })();
  1282. /**
  1283. * (Model) Data source (aka MVC)
  1284. *
  1285. * @name Model
  1286. * @class
  1287. */
  1288. const Model = (function () {
  1289. const me = {};
  1290. let id = null,
  1291. pasteData = null,
  1292. symmetricKey = null,
  1293. $templates;
  1294. /**
  1295. * returns the expiration set in the HTML
  1296. *
  1297. * @name Model.getExpirationDefault
  1298. * @function
  1299. * @return string
  1300. */
  1301. me.getExpirationDefault = function()
  1302. {
  1303. return $('#pasteExpiration').val();
  1304. };
  1305. /**
  1306. * returns the format set in the HTML
  1307. *
  1308. * @name Model.getFormatDefault
  1309. * @function
  1310. * @return string
  1311. */
  1312. me.getFormatDefault = function()
  1313. {
  1314. return $('#pasteFormatter').val();
  1315. };
  1316. /**
  1317. * returns the document data (including the cipher data)
  1318. *
  1319. * @name Model.getPasteData
  1320. * @function
  1321. * @param {function} callback (optional) Called when data is available
  1322. * @param {function} useCache (optional) Whether to use the cache or
  1323. * force a data reload. Default: true
  1324. * @return string
  1325. */
  1326. me.getPasteData = function(callback, useCache)
  1327. {
  1328. // use cache if possible/allowed
  1329. if (useCache !== false && pasteData !== null) {
  1330. //execute callback
  1331. if (typeof callback === 'function') {
  1332. return callback(pasteData);
  1333. }
  1334. // alternatively just using inline
  1335. return pasteData;
  1336. }
  1337. // reload data
  1338. ServerInteraction.prepare();
  1339. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + me.getPasteId());
  1340. ServerInteraction.setFailure(function (status, data) {
  1341. // revert loading status…
  1342. Alert.hideLoading();
  1343. TopNav.showViewButtons();
  1344. // show error message
  1345. Alert.showError(ServerInteraction.parseUploadError(status, data, 'get document data'));
  1346. });
  1347. ServerInteraction.setSuccess(function (status, data) {
  1348. pasteData = new Paste(data);
  1349. if (typeof callback === 'function') {
  1350. return callback(pasteData);
  1351. }
  1352. });
  1353. ServerInteraction.run();
  1354. };
  1355. /**
  1356. * get the documents unique identifier from the URL,
  1357. * eg. https://example.com/path/?c05354954c49a487#dfdsdgdgdfgdf returns c05354954c49a487
  1358. *
  1359. * @name Model.getPasteId
  1360. * @function
  1361. * @return {string} unique identifier
  1362. * @throws {string}
  1363. */
  1364. me.getPasteId = function()
  1365. {
  1366. const idRegEx = /^[a-z0-9]{16}$/;
  1367. // return cached value
  1368. if (id !== null) {
  1369. return id;
  1370. }
  1371. // do use URL interface, if possible
  1372. const url = new URL(window.location);
  1373. for (const param of url.searchParams) {
  1374. const key = param[0];
  1375. const value = param[1];
  1376. if (value === '' && idRegEx.test(key)) {
  1377. // safe, as the whole regex is matched
  1378. id = key;
  1379. return key;
  1380. }
  1381. }
  1382. if (id === null) {
  1383. throw 'no document id given';
  1384. }
  1385. return id;
  1386. }
  1387. /**
  1388. * returns true, when the URL has a delete token and the current call was used for deleting a document.
  1389. *
  1390. * @name Model.hasDeleteToken
  1391. * @function
  1392. * @return {bool}
  1393. */
  1394. me.hasDeleteToken = function()
  1395. {
  1396. return window.location.search.indexOf('deletetoken') !== -1;
  1397. }
  1398. /**
  1399. * return the deciphering key stored in anchor part of the URL
  1400. *
  1401. * @name Model.getPasteKey
  1402. * @function
  1403. * @return {string|null} key
  1404. * @throws {string}
  1405. */
  1406. me.getPasteKey = function()
  1407. {
  1408. if (symmetricKey === null) {
  1409. let startPos = 1;
  1410. if(window.location.hash.startsWith(loadConfirmPrefix)) {
  1411. startPos = loadConfirmPrefix.length;
  1412. }
  1413. let newKey = window.location.hash.substring(startPos);
  1414. // Some web 2.0 services and redirectors add data AFTER the anchor
  1415. // (such as &utm_source=...). We will strip any additional data.
  1416. let ampersandPos = newKey.indexOf('&');
  1417. if (ampersandPos > -1)
  1418. {
  1419. newKey = newKey.substring(0, ampersandPos);
  1420. }
  1421. if (newKey === '') {
  1422. throw 'no encryption key given';
  1423. }
  1424. // version 2 uses base58, version 1 uses base64 without decoding
  1425. try {
  1426. // base58 encode strips NULL bytes at the beginning of the
  1427. // string, so we re-add them if necessary
  1428. symmetricKey = CryptTool.base58decode(newKey).padStart(32, '\u0000');
  1429. } catch(e) {
  1430. throw 'encryption key of unsupported format given or incomplete, mangled URL';
  1431. }
  1432. }
  1433. return symmetricKey;
  1434. };
  1435. /**
  1436. * returns a jQuery copy of the HTML template
  1437. *
  1438. * @name Model.getTemplate
  1439. * @function
  1440. * @param {string} name - the name of the template
  1441. * @return {jQuery}
  1442. */
  1443. me.getTemplate = function(name)
  1444. {
  1445. // find template
  1446. let $element = $templates.find('#' + name + 'template').clone(true);
  1447. // change ID to avoid collisions (one ID should really be unique)
  1448. return $element.prop('id', name);
  1449. };
  1450. /**
  1451. * resets state, used for unit testing
  1452. *
  1453. * @name Model.reset
  1454. * @function
  1455. */
  1456. me.reset = function()
  1457. {
  1458. pasteData = $templates = id = symmetricKey = null;
  1459. };
  1460. /**
  1461. * init navigation manager
  1462. *
  1463. * preloads jQuery elements
  1464. *
  1465. * @name Model.init
  1466. * @function
  1467. */
  1468. me.init = function()
  1469. {
  1470. $templates = $('#templates');
  1471. };
  1472. return me;
  1473. })();
  1474. /**
  1475. * Helper functions for user interface
  1476. *
  1477. * everything directly UI-related, which fits nowhere else
  1478. *
  1479. * @name UiHelper
  1480. * @class
  1481. */
  1482. const UiHelper = (function () {
  1483. const me = {};
  1484. /**
  1485. * handle history (pop) state changes
  1486. *
  1487. * currently this does only handle redirects to the home page.
  1488. *
  1489. * @name UiHelper.historyChange
  1490. * @private
  1491. * @function
  1492. * @param {Event} event
  1493. */
  1494. function historyChange(event)
  1495. {
  1496. let currentLocation = Helper.baseUri();
  1497. if (event.originalEvent.state === null && // no state object passed
  1498. event.target.location.href === currentLocation && // target location is home page
  1499. window.location.href === currentLocation // and we are not already on the home page
  1500. ) {
  1501. // redirect to home page
  1502. window.location.href = currentLocation;
  1503. }
  1504. }
  1505. /**
  1506. * reload the page
  1507. *
  1508. * This takes the user to the PrivateBin homepage.
  1509. *
  1510. * @name UiHelper.reloadHome
  1511. * @function
  1512. */
  1513. me.reloadHome = function()
  1514. {
  1515. window.location.href = Helper.baseUri();
  1516. };
  1517. /**
  1518. * checks whether the element is currently visible in the viewport (so
  1519. * the user can actually see it)
  1520. *
  1521. * @see {@link https://stackoverflow.com/a/40658647}
  1522. * @name UiHelper.isVisible
  1523. * @function
  1524. * @param {jQuery} $element The link hash to move to.
  1525. */
  1526. me.isVisible = function($element)
  1527. {
  1528. let elementTop = $element.offset().top,
  1529. viewportTop = $(window).scrollTop(),
  1530. viewportBottom = viewportTop + $(window).height();
  1531. return elementTop > viewportTop && elementTop < viewportBottom;
  1532. };
  1533. /**
  1534. * scrolls to a specific element
  1535. *
  1536. * @see {@link https://stackoverflow.com/questions/4198041/jquery-smooth-scroll-to-an-anchor#answer-12714767}
  1537. * @name UiHelper.scrollTo
  1538. * @function
  1539. * @param {jQuery} $element The link hash to move to.
  1540. * @param {(number|string)} animationDuration passed to jQuery .animate, when set to 0 the animation is skipped
  1541. * @param {string} animationEffect passed to jQuery .animate
  1542. * @param {function} finishedCallback function to call after animation finished
  1543. */
  1544. me.scrollTo = function($element, animationDuration, animationEffect, finishedCallback)
  1545. {
  1546. let $body = $('html, body'),
  1547. margin = 50,
  1548. callbackCalled = false,
  1549. dest = 0;
  1550. // calculate destination place
  1551. // if it would scroll out of the screen at the bottom only scroll it as
  1552. // far as the screen can go
  1553. if ($element.offset().top > $(document).height() - $(window).height()) {
  1554. dest = $(document).height() - $(window).height();
  1555. } else {
  1556. dest = $element.offset().top - margin;
  1557. }
  1558. // skip animation if duration is set to 0
  1559. if (animationDuration === 0) {
  1560. window.scrollTo(0, dest);
  1561. } else {
  1562. // stop previous animation
  1563. $body.stop();
  1564. // scroll to destination
  1565. $body.animate({
  1566. scrollTop: dest
  1567. }, animationDuration, animationEffect);
  1568. }
  1569. // as we have finished we can enable scrolling again
  1570. $body.queue(function (next) {
  1571. if (!callbackCalled) {
  1572. // call user function if needed
  1573. if (typeof finishedCallback !== 'undefined') {
  1574. finishedCallback();
  1575. }
  1576. // prevent calling this function twice
  1577. callbackCalled = true;
  1578. }
  1579. next();
  1580. });
  1581. };
  1582. /**
  1583. * trigger a history (pop) state change
  1584. *
  1585. * used to test the UiHelper.historyChange private function
  1586. *
  1587. * @name UiHelper.mockHistoryChange
  1588. * @function
  1589. * @param {string} state (optional) state to mock
  1590. */
  1591. me.mockHistoryChange = function(state)
  1592. {
  1593. if (typeof state === 'undefined') {
  1594. state = null;
  1595. }
  1596. historyChange($.Event('popstate', {originalEvent: new PopStateEvent('popstate', {state: state}), target: window}));
  1597. };
  1598. /**
  1599. * initialize
  1600. *
  1601. * @name UiHelper.init
  1602. * @function
  1603. */
  1604. me.init = function()
  1605. {
  1606. // update link to home page
  1607. $('.reloadlink').prop('href', Helper.baseUri());
  1608. $(window).on('popstate', historyChange);
  1609. };
  1610. return me;
  1611. })();
  1612. /**
  1613. * Alert/error manager
  1614. *
  1615. * @name Alert
  1616. * @class
  1617. */
  1618. const Alert = (function () {
  1619. const me = {};
  1620. let $errorMessage,
  1621. $loadingIndicator,
  1622. $statusMessage,
  1623. $remainingTime,
  1624. currentIcon,
  1625. customHandler;
  1626. const alertType = [
  1627. 'loading', // not in bootstrap CSS, but using a plausible value here
  1628. 'info', // status icon
  1629. 'warning', // warning icon
  1630. 'danger' // error icon
  1631. ];
  1632. /**
  1633. * forwards a request to the i18n module and shows the element
  1634. *
  1635. * @name Alert.handleNotification
  1636. * @private
  1637. * @function
  1638. * @param {int} id - id of notification
  1639. * @param {jQuery} $element - jQuery object
  1640. * @param {string|array} args
  1641. * @param {string|null} icon - optional, icon
  1642. */
  1643. function handleNotification(id, $element, args, icon)
  1644. {
  1645. // basic parsing/conversion of parameters
  1646. if (typeof icon === 'undefined') {
  1647. icon = null;
  1648. }
  1649. if (typeof args === 'undefined') {
  1650. args = null;
  1651. } else if (typeof args === 'string') {
  1652. // convert string to array if needed
  1653. args = [args];
  1654. } else if (args instanceof Error) {
  1655. // extract message into array if needed
  1656. args = [args.message];
  1657. }
  1658. // pass to custom handler if defined
  1659. if (typeof customHandler === 'function') {
  1660. let handlerResult = customHandler(alertType[id], $element, args, icon);
  1661. if (handlerResult === true) {
  1662. // if it returns true, skip own handler
  1663. return;
  1664. }
  1665. if (handlerResult instanceof jQuery) {
  1666. // continue processing with new element
  1667. $element = handlerResult;
  1668. icon = null; // icons not supported in this case
  1669. }
  1670. }
  1671. let $translationTarget = $element;
  1672. // handle icon, if template uses one
  1673. const $glyphIcon = $element.find(':first');
  1674. if ($glyphIcon.length) {
  1675. // if there is an icon, we need to provide an inner element
  1676. // to translate the message into, instead of the parent
  1677. $translationTarget = $('<span>');
  1678. $element.html(' ').prepend($glyphIcon).append($translationTarget);
  1679. if (icon !== null && // icon was passed
  1680. icon !== currentIcon[id] // and it differs from current icon
  1681. ) {
  1682. // remove (previous) icon
  1683. $glyphIcon.removeClass(currentIcon[id]);
  1684. // any other thing as a string (e.g. 'null') (only) removes the icon
  1685. if (typeof icon === 'string') {
  1686. // set new icon
  1687. currentIcon[id] = 'glyphicon-' + icon;
  1688. $glyphIcon.addClass(currentIcon[id]);
  1689. }
  1690. }
  1691. }
  1692. // show text
  1693. if (args !== null) {
  1694. // add jQuery object to it as first parameter
  1695. args.unshift($translationTarget);
  1696. // pass it to I18n
  1697. I18n._.apply(this, args);
  1698. }
  1699. // show notification
  1700. $element.removeClass('hidden');
  1701. }
  1702. /**
  1703. * display a status message
  1704. *
  1705. * This automatically passes the text to I18n for translation.
  1706. *
  1707. * @name Alert.showStatus
  1708. * @function
  1709. * @param {string|array} message string, use an array for %s/%d options
  1710. * @param {string|null} icon optional, the icon to show,
  1711. * default: leave previous icon
  1712. */
  1713. me.showStatus = function(message, icon)
  1714. {
  1715. handleNotification(1, $statusMessage, message, icon);
  1716. };
  1717. /**
  1718. * display a warning message
  1719. *
  1720. * This automatically passes the text to I18n for translation.
  1721. *
  1722. * @name Alert.showWarning
  1723. * @function
  1724. * @param {string|array} message string, use an array for %s/%d options
  1725. * @param {string|null} icon optional, the icon to show, default:
  1726. * leave previous icon
  1727. */
  1728. me.showWarning = function(message, icon)
  1729. {
  1730. $errorMessage.find(':first')
  1731. .removeClass(currentIcon[3])
  1732. .addClass(currentIcon[2]);
  1733. handleNotification(2, $errorMessage, message, icon);
  1734. };
  1735. /**
  1736. * display an error message
  1737. *
  1738. * This automatically passes the text to I18n for translation.
  1739. *
  1740. * @name Alert.showError
  1741. * @function
  1742. * @param {string|array} message string, use an array for %s/%d options
  1743. * @param {string|null} icon optional, the icon to show, default:
  1744. * leave previous icon
  1745. */
  1746. me.showError = function(message, icon)
  1747. {
  1748. handleNotification(3, $errorMessage, message, icon);
  1749. };
  1750. /**
  1751. * display remaining message
  1752. *
  1753. * This automatically passes the text to I18n for translation.
  1754. *
  1755. * @name Alert.showRemaining
  1756. * @function
  1757. * @param {string|array} message string, use an array for %s/%d options
  1758. */
  1759. me.showRemaining = function(message)
  1760. {
  1761. handleNotification(1, $remainingTime, message);
  1762. };
  1763. /**
  1764. * shows a loading message, optionally with a percentage
  1765. *
  1766. * This automatically passes all texts to the i10s module.
  1767. *
  1768. * @name Alert.showLoading
  1769. * @function
  1770. * @param {string|array|null} message optional, use an array for %s/%d options, default: 'Loading…'
  1771. * @param {string|null} icon optional, the icon to show, default: leave previous icon
  1772. */
  1773. me.showLoading = function(message, icon)
  1774. {
  1775. // default message text
  1776. if (typeof message === 'undefined') {
  1777. message = 'Loading…';
  1778. }
  1779. handleNotification(0, $loadingIndicator, message, icon);
  1780. // show loading status (cursor)
  1781. $('body').addClass('loading');
  1782. };
  1783. /**
  1784. * hides the loading message
  1785. *
  1786. * @name Alert.hideLoading
  1787. * @function
  1788. */
  1789. me.hideLoading = function()
  1790. {
  1791. $loadingIndicator.addClass('hidden');
  1792. // hide loading cursor
  1793. $('body').removeClass('loading');
  1794. };
  1795. /**
  1796. * hides any status/error messages
  1797. *
  1798. * This does not include the loading message.
  1799. *
  1800. * @name Alert.hideMessages
  1801. * @function
  1802. */
  1803. me.hideMessages = function()
  1804. {
  1805. $statusMessage.addClass('hidden');
  1806. $errorMessage.addClass('hidden');
  1807. };
  1808. /**
  1809. * set a custom handler, which gets all notifications.
  1810. *
  1811. * This handler gets the following arguments:
  1812. * alertType (see array), $element, args, icon
  1813. * If it returns true, the own processing will be stopped so the message
  1814. * will not be displayed. Otherwise it will continue.
  1815. * As an aditional feature it can return q jQuery element, which will
  1816. * then be used to add the message there. Icons are not supported in
  1817. * that case and will be ignored.
  1818. * Pass 'null' to reset/delete the custom handler.
  1819. * Note that there is no notification when a message is supposed to get
  1820. * hidden.
  1821. *
  1822. * @name Alert.setCustomHandler
  1823. * @function
  1824. * @param {function|null} newHandler
  1825. */
  1826. me.setCustomHandler = function(newHandler)
  1827. {
  1828. customHandler = newHandler;
  1829. };
  1830. /**
  1831. * init status manager
  1832. *
  1833. * preloads jQuery elements
  1834. *
  1835. * @name Alert.init
  1836. * @function
  1837. */
  1838. me.init = function()
  1839. {
  1840. // hide "no javascript" error message
  1841. $('#noscript').hide();
  1842. // not a reset, but first set of the elements
  1843. $errorMessage = $('#errormessage');
  1844. $loadingIndicator = $('#loadingindicator');
  1845. $statusMessage = $('#status');
  1846. $remainingTime = $('#remainingtime');
  1847. currentIcon = [
  1848. 'glyphicon-time', // loading icon
  1849. 'glyphicon-info-sign', // status icon
  1850. 'glyphicon-warning-sign', // warning icon
  1851. 'glyphicon-alert' // error icon
  1852. ];
  1853. };
  1854. return me;
  1855. })();
  1856. /**
  1857. * handles paste status/result
  1858. *
  1859. * @name PasteStatus
  1860. * @class
  1861. */
  1862. const PasteStatus = (function () {
  1863. const me = {};
  1864. let $pasteSuccess,
  1865. $pasteUrl,
  1866. $remainingTime,
  1867. $shortenButton;
  1868. /**
  1869. * forward to URL shortener
  1870. *
  1871. * @name PasteStatus.sendToShortener
  1872. * @private
  1873. * @function
  1874. */
  1875. function sendToShortener()
  1876. {
  1877. if ($shortenButton.hasClass('buttondisabled')) {
  1878. return;
  1879. }
  1880. $.ajax({
  1881. type: 'GET',
  1882. url: `${$shortenButton.data('shortener')}${encodeURIComponent($pasteUrl.attr('href'))}`,
  1883. headers: {'Accept': 'text/html, application/xhtml+xml, application/xml, application/json'},
  1884. processData: false,
  1885. timeout: 10000,
  1886. xhrFields: {
  1887. withCredentials: false
  1888. },
  1889. success: PasteStatus.extractUrl
  1890. })
  1891. .fail(function(data, textStatus, errorThrown) {
  1892. console.error(textStatus, errorThrown);
  1893. // we don't know why it failed, could be CORS of the external
  1894. // server not setup properly, in which case we follow old
  1895. // behavior to open it in new tab
  1896. window.open(
  1897. `${$shortenButton.data('shortener')}${encodeURIComponent($pasteUrl.attr('href'))}`,
  1898. '_blank',
  1899. 'noopener, noreferrer'
  1900. );
  1901. });
  1902. }
  1903. /**
  1904. * Forces opening the document if the link does not do this automatically.
  1905. *
  1906. * This is necessary as browsers will not reload the page when it is
  1907. * already loaded (which is fake as it is set via history.pushState()).
  1908. *
  1909. * @name PasteStatus.pasteLinkClick
  1910. * @function
  1911. */
  1912. function pasteLinkClick()
  1913. {
  1914. // check if location is (already) shown in URL bar
  1915. if (window.location.href === $pasteUrl.attr('href')) {
  1916. // if so we need to load link by reloading the current site
  1917. window.location.reload(true);
  1918. }
  1919. }
  1920. /**
  1921. * creates a notification after a successful document upload
  1922. *
  1923. * @name PasteStatus.createPasteNotification
  1924. * @function
  1925. * @param {string} url
  1926. * @param {string} deleteUrl
  1927. */
  1928. me.createPasteNotification = function(url, deleteUrl)
  1929. {
  1930. I18n._(
  1931. $('#pastelink'),
  1932. 'Your document is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit <kbd>Ctrl</kbd>+<kbd>c</kbd> to copy)</span>',
  1933. url, url
  1934. );
  1935. // save newly created element
  1936. $pasteUrl = $('#pasteurl');
  1937. // and add click event
  1938. $pasteUrl.click(pasteLinkClick);
  1939. // delete link
  1940. $('#deletelink').attr('href', deleteUrl);
  1941. I18n._($('#deletelink span').not('.glyphicon').first(), 'Delete data');
  1942. // enable shortener button
  1943. $shortenButton.removeClass('buttondisabled');
  1944. // show result
  1945. $pasteSuccess.removeClass('hidden');
  1946. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1947. Helper.selectText($pasteUrl[0]);
  1948. };
  1949. /**
  1950. * Checks if auto-shortening is enabled and sends the link to the shortener if it is.
  1951. *
  1952. * @name PasteStatus.checkAutoShorten
  1953. * @function
  1954. */
  1955. me.checkAutoShorten = function() {
  1956. // check if auto-shortening is enabled
  1957. if ($shortenButton.data('autoshorten') === true) {
  1958. // if so, we send the link to the shortener
  1959. // we do not remove the button, in case shortener fails
  1960. sendToShortener();
  1961. }
  1962. }
  1963. /**
  1964. * extracts URLs from given string
  1965. *
  1966. * if at least one is found, it disables the shortener button and
  1967. * replaces the document URL
  1968. *
  1969. * @name PasteStatus.extractUrl
  1970. * @function
  1971. * @param {string} response
  1972. */
  1973. me.extractUrl = function(response)
  1974. {
  1975. if (typeof response === 'object') {
  1976. response = JSON.stringify(response);
  1977. }
  1978. if (typeof response === 'string' && response.length > 0) {
  1979. const shortUrlMatcher = /https?:\/\/[^\s"<]+/g; // JSON API will have URL in quotes, XML in tags
  1980. const shortUrl = (response.match(shortUrlMatcher) || []).filter(function(urlRegExMatch) {
  1981. if (typeof URL.canParse === 'function') {
  1982. return URL.canParse(urlRegExMatch);
  1983. }
  1984. // polyfill for older browsers (< 120) & node (< 19.9 & < 18.17)
  1985. try {
  1986. return !!new URL(urlRegExMatch);
  1987. } catch (error) {
  1988. return false;
  1989. }
  1990. }).sort(function(a, b) {
  1991. return a.length - b.length; // shortest first
  1992. })[0];
  1993. if (typeof shortUrl === 'string' && shortUrl.length > 0) {
  1994. // we disable the button to avoid calling shortener again
  1995. $shortenButton.addClass('buttondisabled');
  1996. // update link
  1997. $pasteUrl.text(shortUrl);
  1998. $pasteUrl.prop('href', shortUrl);
  1999. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  2000. Helper.selectText($pasteUrl[0]);
  2001. CopyToClipboard.setUrl(shortUrl);
  2002. return;
  2003. }
  2004. }
  2005. Alert.showError('Cannot parse response from URL shortener.');
  2006. };
  2007. /**
  2008. * shows the remaining time
  2009. *
  2010. * @name PasteStatus.showRemainingTime
  2011. * @function
  2012. * @param {Paste} paste
  2013. */
  2014. me.showRemainingTime = function(paste)
  2015. {
  2016. if (paste.isBurnAfterReadingEnabled()) {
  2017. // display document "for your eyes only" if it is deleted
  2018. // the document has been deleted when the JSON with the ciphertext
  2019. // has been downloaded
  2020. Alert.showRemaining('FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.');
  2021. $remainingTime.addClass('foryoureyesonly');
  2022. } else if (paste.getTimeToLive() > 0) {
  2023. // display document expiration
  2024. let expiration = Helper.secondsToHuman(paste.getTimeToLive()),
  2025. expirationLabel = [
  2026. 'This document will expire in %d ' + expiration[1] + '.',
  2027. 'This document will expire in %d ' + expiration[1] + 's.'
  2028. ];
  2029. Alert.showRemaining([expirationLabel, expiration[0]]);
  2030. $remainingTime.removeClass('foryoureyesonly');
  2031. } else {
  2032. // never expires
  2033. return;
  2034. }
  2035. // in the end, display notification
  2036. $remainingTime.removeClass('hidden');
  2037. };
  2038. /**
  2039. * hides the remaining time and successful upload notification
  2040. *
  2041. * @name PasteStatus.hideMessages
  2042. * @function
  2043. */
  2044. me.hideMessages = function()
  2045. {
  2046. $remainingTime.addClass('hidden');
  2047. $pasteSuccess.addClass('hidden');
  2048. };
  2049. /**
  2050. * init status manager
  2051. *
  2052. * preloads jQuery elements
  2053. *
  2054. * @name PasteStatus.init
  2055. * @function
  2056. */
  2057. me.init = function()
  2058. {
  2059. $pasteSuccess = $('#pastesuccess');
  2060. // $pasteUrl is saved in me.createPasteNotification() after creation
  2061. $remainingTime = $('#remainingtime');
  2062. $shortenButton = $('#shortenbutton');
  2063. // bind elements
  2064. $shortenButton.click(sendToShortener);
  2065. };
  2066. return me;
  2067. })();
  2068. /**
  2069. * password prompt
  2070. *
  2071. * @name Prompt
  2072. * @class
  2073. */
  2074. const Prompt = (function () {
  2075. const me = {};
  2076. let $passwordDecrypt,
  2077. $passwordModal,
  2078. bootstrap5PasswordModal = null,
  2079. password = '';
  2080. /**
  2081. * submit a password in the modal dialog
  2082. *
  2083. * @name Prompt.submitPasswordModal
  2084. * @private
  2085. * @function
  2086. * @param {Event} event
  2087. */
  2088. function submitPasswordModal(event)
  2089. {
  2090. event.preventDefault();
  2091. // get input
  2092. password = $passwordDecrypt.val();
  2093. // hide modal
  2094. if (bootstrap5PasswordModal) {
  2095. bootstrap5PasswordModal.hide();
  2096. } else {
  2097. $passwordModal.modal('hide');
  2098. }
  2099. PasteDecrypter.run();
  2100. }
  2101. /**
  2102. * Request users confirmation to load possibly burn after reading document
  2103. *
  2104. * @name Prompt.requestLoadConfirmation
  2105. * @function
  2106. */
  2107. me.requestLoadConfirmation = function()
  2108. {
  2109. const $loadconfirmmodal = $('#loadconfirmmodal');
  2110. const $loadconfirmOpenNow = $loadconfirmmodal.find('#loadconfirm-open-now');
  2111. $loadconfirmOpenNow.off('click.loadPaste');
  2112. $loadconfirmOpenNow.on('click.loadPaste', PasteDecrypter.run);
  2113. const $loadconfirmClose = $loadconfirmmodal.find('.close');
  2114. $loadconfirmClose.off('click.close');
  2115. $loadconfirmClose.on('click.close', Controller.newPaste);
  2116. if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip.VERSION) {
  2117. (new bootstrap.Modal($loadconfirmmodal[0])).show();
  2118. } else {
  2119. $loadconfirmmodal.modal('show');
  2120. }
  2121. }
  2122. /**
  2123. * ask the user for the password and set it
  2124. *
  2125. * @name Prompt.requestPassword
  2126. * @function
  2127. */
  2128. me.requestPassword = function()
  2129. {
  2130. // show new bootstrap method (if available)
  2131. if ($passwordModal.length !== 0) {
  2132. if (bootstrap5PasswordModal) {
  2133. bootstrap5PasswordModal.show();
  2134. } else {
  2135. $passwordModal.modal('show');
  2136. }
  2137. return;
  2138. }
  2139. PasteDecrypter.run();
  2140. };
  2141. /**
  2142. * get the cached password
  2143. *
  2144. * If you do not get a password with this function
  2145. * (returns an empty string), use requestPassword.
  2146. *
  2147. * @name Prompt.getPassword
  2148. * @function
  2149. * @return {string}
  2150. */
  2151. me.getPassword = function()
  2152. {
  2153. return password;
  2154. };
  2155. /**
  2156. * resets the password to an empty string
  2157. *
  2158. * @name Prompt.reset
  2159. * @function
  2160. */
  2161. me.reset = function()
  2162. {
  2163. // reset internal
  2164. password = '';
  2165. // and also reset UI
  2166. $passwordDecrypt.val('');
  2167. };
  2168. /**
  2169. * init status manager
  2170. *
  2171. * preloads jQuery elements
  2172. *
  2173. * @name Prompt.init
  2174. * @function
  2175. */
  2176. me.init = function()
  2177. {
  2178. $passwordDecrypt = $('#passworddecrypt');
  2179. $passwordModal = $('#passwordmodal');
  2180. // bind events - handle Model password submission
  2181. if ($passwordModal.length !== 0) {
  2182. $('#passwordform').submit(submitPasswordModal);
  2183. const disableClosingConfig = {
  2184. backdrop: 'static',
  2185. keyboard: false,
  2186. show: false
  2187. };
  2188. if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip.VERSION) {
  2189. bootstrap5PasswordModal = new bootstrap.Modal($passwordModal[0], disableClosingConfig);
  2190. } else {
  2191. $passwordModal.modal(disableClosingConfig);
  2192. }
  2193. $passwordModal.on('shown.bs.modal', () => {
  2194. $passwordDecrypt.focus();
  2195. });
  2196. }
  2197. };
  2198. return me;
  2199. })();
  2200. /**
  2201. * Manage paste/message input, and preview tab
  2202. *
  2203. * Note that the actual preview is handled by PasteViewer.
  2204. *
  2205. * @name Editor
  2206. * @class
  2207. */
  2208. const Editor = (function () {
  2209. const me = {};
  2210. let $editorTabs,
  2211. $messageEdit,
  2212. $messageEditParent,
  2213. $messagePreview,
  2214. $messagePreviewParent,
  2215. $messageTab,
  2216. $messageTabParent,
  2217. $message,
  2218. isPreview = false,
  2219. isTabSupported = true;
  2220. /**
  2221. * support input of tab character
  2222. *
  2223. * @name Editor.supportTabs
  2224. * @function
  2225. * @param {Event} event
  2226. * @this $message (but not used, so it is jQuery-free, possibly faster)
  2227. */
  2228. function supportTabs(event)
  2229. {
  2230. // support disabling tab support using [Esc] and [Ctrl]+[m]
  2231. if (event.key === 'Escape' || (event.ctrlKey && event.key === 'm')) {
  2232. toggleTabSupport();
  2233. $messageTab[0].checked = isTabSupported;
  2234. event.preventDefault();
  2235. }
  2236. else if (isTabSupported && event.key === 'Tab') {
  2237. // get caret position & selection
  2238. const val = this.value,
  2239. start = this.selectionStart,
  2240. end = this.selectionEnd;
  2241. // set textarea value to: text before caret + tab + text after caret
  2242. this.value = val.substring(0, start) + '\t' + val.substring(end);
  2243. // put caret at right position again
  2244. this.selectionStart = this.selectionEnd = start + 1;
  2245. // prevent the textarea to lose focus
  2246. event.preventDefault();
  2247. }
  2248. }
  2249. /**
  2250. * toggle tab support in message textarea
  2251. *
  2252. * @name Editor.toggleTabSupport
  2253. * @private
  2254. * @function
  2255. */
  2256. function toggleTabSupport()
  2257. {
  2258. isTabSupported = !isTabSupported;
  2259. }
  2260. /**
  2261. * view the Editor tab
  2262. *
  2263. * @name Editor.viewEditor
  2264. * @function
  2265. * @param {Event} event - optional
  2266. */
  2267. function viewEditor(event)
  2268. {
  2269. // toggle buttons
  2270. $messageEdit.addClass('active');
  2271. $messageEditParent.addClass('active');
  2272. $messagePreview.removeClass('active');
  2273. $messagePreviewParent.removeClass('active');
  2274. $messageEdit.attr('aria-selected','true');
  2275. $messagePreview.attr('aria-selected','false');
  2276. PasteViewer.hide();
  2277. // reshow input
  2278. $message.removeClass('hidden');
  2279. $messageTabParent.removeClass('hidden');
  2280. me.focusInput();
  2281. // finish
  2282. isPreview = false;
  2283. // prevent jumping of page to top
  2284. if (typeof event !== 'undefined') {
  2285. event.preventDefault();
  2286. }
  2287. }
  2288. /**
  2289. * view the preview tab
  2290. *
  2291. * @name Editor.viewPreview
  2292. * @function
  2293. * @param {Event} event
  2294. */
  2295. function viewPreview(event)
  2296. {
  2297. // toggle buttons
  2298. $messageEdit.removeClass('active');
  2299. $messageEditParent.removeClass('active');
  2300. $messagePreview.addClass('active');
  2301. $messagePreviewParent.addClass('active');
  2302. $messageEdit.attr('aria-selected','false');
  2303. $messagePreview.attr('aria-selected','true');
  2304. // hide input as now preview is shown
  2305. $message.addClass('hidden');
  2306. $messageTabParent.addClass('hidden');
  2307. // show preview
  2308. PasteViewer.setText($message.val());
  2309. if (AttachmentViewer.hasAttachmentData()) {
  2310. const attachmentsData = AttachmentViewer.getAttachmentsData();
  2311. attachmentsData.forEach(attachmentData => {
  2312. const mimeType = AttachmentViewer.getAttachmentMimeType(attachmentData);
  2313. AttachmentViewer.handleBlobAttachmentPreview(
  2314. AttachmentViewer.getAttachmentPreview(),
  2315. attachmentData, mimeType
  2316. );
  2317. });
  2318. AttachmentViewer.showAttachment();
  2319. }
  2320. PasteViewer.run();
  2321. // finish
  2322. isPreview = true;
  2323. // prevent jumping of page to top
  2324. if (typeof event !== 'undefined') {
  2325. event.preventDefault();
  2326. }
  2327. }
  2328. /**
  2329. * get the state of the preview
  2330. *
  2331. * @name Editor.isPreview
  2332. * @function
  2333. */
  2334. me.isPreview = function()
  2335. {
  2336. return isPreview;
  2337. };
  2338. /**
  2339. * reset the Editor view
  2340. *
  2341. * @name Editor.resetInput
  2342. * @function
  2343. */
  2344. me.resetInput = function()
  2345. {
  2346. // go back to input
  2347. if (isPreview) {
  2348. viewEditor();
  2349. }
  2350. // clear content
  2351. $message.val('');
  2352. };
  2353. /**
  2354. * shows the Editor
  2355. *
  2356. * @name Editor.show
  2357. * @function
  2358. */
  2359. me.show = function()
  2360. {
  2361. $message.removeClass('hidden');
  2362. $messageTabParent.removeClass('hidden');
  2363. $editorTabs.removeClass('hidden');
  2364. };
  2365. /**
  2366. * hides the Editor
  2367. *
  2368. * @name Editor.hide
  2369. * @function
  2370. */
  2371. me.hide = function()
  2372. {
  2373. $message.addClass('hidden');
  2374. $messageTabParent.addClass('hidden');
  2375. $editorTabs.addClass('hidden');
  2376. };
  2377. /**
  2378. * focuses the message input
  2379. *
  2380. * @name Editor.focusInput
  2381. * @function
  2382. */
  2383. me.focusInput = function()
  2384. {
  2385. $message.focus();
  2386. };
  2387. /**
  2388. * sets a new text
  2389. *
  2390. * @name Editor.setText
  2391. * @function
  2392. * @param {string} newText
  2393. */
  2394. me.setText = function(newText)
  2395. {
  2396. $message.val(newText);
  2397. };
  2398. /**
  2399. * returns the current text
  2400. *
  2401. * @name Editor.getText
  2402. * @function
  2403. * @return {string}
  2404. */
  2405. me.getText = function()
  2406. {
  2407. return $message.val();
  2408. };
  2409. /**
  2410. * init editor
  2411. *
  2412. * preloads jQuery elements
  2413. *
  2414. * @name Editor.init
  2415. * @function
  2416. */
  2417. me.init = function()
  2418. {
  2419. $editorTabs = $('#editorTabs');
  2420. $message = $('#message');
  2421. $messageTab = $('#messagetab');
  2422. $messageTabParent = $messageTab.parent();
  2423. // bind events
  2424. $message.keydown(supportTabs);
  2425. $messageTab.change(toggleTabSupport);
  2426. // bind click events to tab switchers (a), and save parents (li)
  2427. $messageEdit = $('#messageedit').click(viewEditor);
  2428. $messageEditParent = $messageEdit.parent();
  2429. $messagePreview = $('#messagepreview').click(viewPreview);
  2430. $messagePreviewParent = $messagePreview.parent();
  2431. };
  2432. return me;
  2433. })();
  2434. /**
  2435. * (view) Parse and show document.
  2436. *
  2437. * @name PasteViewer
  2438. * @class
  2439. */
  2440. const PasteViewer = (function () {
  2441. const me = {};
  2442. let $messageTabParent,
  2443. $placeholder,
  2444. $prettyMessage,
  2445. $prettyPrint,
  2446. $plainText,
  2447. text,
  2448. format = 'plaintext',
  2449. isDisplayed = false,
  2450. isChanged = true; // by default true as nothing was parsed yet
  2451. /**
  2452. * apply the set format on paste and displays it
  2453. *
  2454. * @name PasteViewer.parsePaste
  2455. * @private
  2456. * @function
  2457. */
  2458. function parsePaste()
  2459. {
  2460. // skip parsing if no text is given
  2461. if (text === '') {
  2462. return;
  2463. }
  2464. if (format === 'markdown') {
  2465. const converter = new showdown.Converter({
  2466. strikethrough: true,
  2467. tables: true,
  2468. tablesHeaderId: true,
  2469. simplifiedAutoLink: true,
  2470. excludeTrailingPunctuationFromURLs: true
  2471. });
  2472. // let showdown convert the HTML and sanitize HTML *afterwards*!
  2473. $plainText.html(
  2474. DOMPurify.sanitize(
  2475. converter.makeHtml(text),
  2476. purifyHtmlConfig
  2477. )
  2478. );
  2479. // add table classes from bootstrap css
  2480. $plainText.find('table').addClass('table-condensed table-bordered');
  2481. } else {
  2482. if (format === 'syntaxhighlighting') {
  2483. // yes, this is really needed to initialize the environment
  2484. if (typeof prettyPrint === 'function')
  2485. {
  2486. prettyPrint();
  2487. }
  2488. $prettyPrint.html(
  2489. prettyPrintOne(
  2490. Helper.htmlEntities(text), null, true
  2491. )
  2492. );
  2493. } else {
  2494. // = 'plaintext'
  2495. $prettyPrint.text(text);
  2496. }
  2497. Helper.urls2links($prettyPrint);
  2498. $prettyPrint.css('white-space', 'pre-wrap');
  2499. $prettyPrint.css('word-break', 'normal');
  2500. $prettyPrint.removeClass('prettyprint');
  2501. }
  2502. }
  2503. /**
  2504. * displays the document
  2505. *
  2506. * @name PasteViewer.showPaste
  2507. * @private
  2508. * @function
  2509. */
  2510. function showPaste()
  2511. {
  2512. // instead of "nothing" better display a placeholder
  2513. if (text === '') {
  2514. $placeholder.removeClass('hidden');
  2515. return;
  2516. }
  2517. // otherwise hide the placeholder
  2518. $placeholder.addClass('hidden');
  2519. $messageTabParent.addClass('hidden');
  2520. if (format === 'markdown') {
  2521. $plainText.removeClass('hidden');
  2522. $prettyMessage.addClass('hidden');
  2523. } else {
  2524. $plainText.addClass('hidden');
  2525. $prettyMessage.removeClass('hidden');
  2526. }
  2527. }
  2528. /**
  2529. * sets the format in which the text is shown
  2530. *
  2531. * @name PasteViewer.setFormat
  2532. * @function
  2533. * @param {string} newFormat the new format
  2534. */
  2535. me.setFormat = function(newFormat)
  2536. {
  2537. // skip if there is no update
  2538. if (format === newFormat) {
  2539. return;
  2540. }
  2541. // needs to update display too, if we switch from or to Markdown
  2542. if (format === 'markdown' || newFormat === 'markdown') {
  2543. isDisplayed = false;
  2544. }
  2545. format = newFormat;
  2546. isChanged = true;
  2547. // update preview
  2548. if (Editor.isPreview()) {
  2549. PasteViewer.run();
  2550. }
  2551. };
  2552. /**
  2553. * returns the current format
  2554. *
  2555. * @name PasteViewer.getFormat
  2556. * @function
  2557. * @return {string}
  2558. */
  2559. me.getFormat = function()
  2560. {
  2561. return format;
  2562. };
  2563. /**
  2564. * returns whether the current view is pretty printed
  2565. *
  2566. * @name PasteViewer.isPrettyPrinted
  2567. * @function
  2568. * @return {bool}
  2569. */
  2570. me.isPrettyPrinted = function()
  2571. {
  2572. return $prettyPrint.hasClass('prettyprinted');
  2573. };
  2574. /**
  2575. * sets the text to show
  2576. *
  2577. * @name PasteViewer.setText
  2578. * @function
  2579. * @param {string} newText the text to show
  2580. */
  2581. me.setText = function(newText)
  2582. {
  2583. if (text !== newText) {
  2584. text = newText;
  2585. isChanged = true;
  2586. }
  2587. };
  2588. /**
  2589. * gets the current cached text
  2590. *
  2591. * @name PasteViewer.getText
  2592. * @function
  2593. * @return {string}
  2594. */
  2595. me.getText = function()
  2596. {
  2597. return text;
  2598. };
  2599. /**
  2600. * show/update the parsed text (preview)
  2601. *
  2602. * @name PasteViewer.run
  2603. * @function
  2604. */
  2605. me.run = function()
  2606. {
  2607. if (isChanged) {
  2608. parsePaste();
  2609. isChanged = false;
  2610. }
  2611. if (!isDisplayed) {
  2612. showPaste();
  2613. isDisplayed = true;
  2614. }
  2615. };
  2616. /**
  2617. * hide parsed text (preview)
  2618. *
  2619. * @name PasteViewer.hide
  2620. * @function
  2621. */
  2622. me.hide = function()
  2623. {
  2624. if (!isDisplayed) {
  2625. return;
  2626. }
  2627. $plainText.addClass('hidden');
  2628. $prettyMessage.addClass('hidden');
  2629. $placeholder.addClass('hidden');
  2630. AttachmentViewer.hideAttachmentPreview();
  2631. isDisplayed = false;
  2632. };
  2633. /**
  2634. * init status manager
  2635. *
  2636. * preloads jQuery elements
  2637. *
  2638. * @name PasteViewer.init
  2639. * @function
  2640. */
  2641. me.init = function()
  2642. {
  2643. $messageTabParent = $('#messagetab').parent();
  2644. $placeholder = $('#placeholder');
  2645. $plainText = $('#plaintext');
  2646. $prettyMessage = $('#prettymessage');
  2647. $prettyPrint = $('#prettyprint');
  2648. // get default option from template/HTML or fall back to set value
  2649. format = Model.getFormatDefault() || format;
  2650. text = '';
  2651. isDisplayed = false;
  2652. isChanged = true;
  2653. };
  2654. return me;
  2655. })();
  2656. /**
  2657. * (view) Show attachment and preview if possible
  2658. *
  2659. * @name AttachmentViewer
  2660. * @class
  2661. */
  2662. const AttachmentViewer = (function () {
  2663. const me = {};
  2664. let $attachmentPreview,
  2665. $attachment,
  2666. attachmentsData = [],
  2667. files,
  2668. $fileInput,
  2669. $dragAndDropFileNames,
  2670. $dropzone;
  2671. /**
  2672. * get blob URL from string data and mime type
  2673. *
  2674. * @name AttachmentViewer.getBlobUrl
  2675. * @private
  2676. * @function
  2677. * @param {string} data - raw data of attachment
  2678. * @param {string} data - mime type of attachment
  2679. * @return {string} objectURL
  2680. */
  2681. function getBlobUrl(data, mimeType)
  2682. {
  2683. // Transform into a Blob
  2684. const buf = new Uint8Array(data.length);
  2685. for (let i = 0; i < data.length; ++i) {
  2686. buf[i] = data.charCodeAt(i);
  2687. }
  2688. const blob = new window.Blob(
  2689. [buf],
  2690. {
  2691. type: mimeType
  2692. }
  2693. );
  2694. // Get blob URL
  2695. return window.URL.createObjectURL(blob);
  2696. }
  2697. /**
  2698. * sets the attachment but does not yet show it
  2699. *
  2700. * @name AttachmentViewer.setAttachment
  2701. * @function
  2702. * @param {string} attachmentData - base64-encoded data of file
  2703. * @param {string} fileName - optional, file name
  2704. */
  2705. me.setAttachment = function(attachmentData, fileName)
  2706. {
  2707. // skip, if attachments got disabled
  2708. if (!$attachment || !$attachmentPreview) return;
  2709. // data URI format: data:[<mimeType>][;base64],<data>
  2710. const template = Model.getTemplate('attachment');
  2711. const attachmentLink = template.find('a');
  2712. // position in data URI string of where data begins
  2713. const base64Start = attachmentData.indexOf(',') + 1;
  2714. const mimeType = me.getAttachmentMimeType(attachmentData);
  2715. // extract data and convert to binary
  2716. const rawData = attachmentData.substring(base64Start);
  2717. const decodedData = rawData.length > 0 ? atob(rawData) : '';
  2718. let blobUrl = getBlobUrl(decodedData, mimeType);
  2719. attachmentLink.attr('href', blobUrl);
  2720. if (typeof fileName !== 'undefined') {
  2721. attachmentLink.attr('download', fileName);
  2722. const fileSize = Helper.formatBytes(decodedData.length);
  2723. template.append(`(${fileName}, ${fileSize})`);
  2724. }
  2725. // sanitize SVG preview
  2726. // prevents executing embedded scripts when CSP is not set and user
  2727. // right-clicks/long-taps and opens the SVG in a new tab - prevented
  2728. // in the preview by use of an img tag, which disables scripts, too
  2729. if (mimeType.match(/^image\/.*svg/i)) {
  2730. const sanitizedData = DOMPurify.sanitize(
  2731. decodedData,
  2732. purifySvgConfig
  2733. );
  2734. blobUrl = getBlobUrl(sanitizedData, mimeType);
  2735. }
  2736. template.removeClass('hidden');
  2737. $attachment.append(template);
  2738. me.handleBlobAttachmentPreview($attachmentPreview, blobUrl, mimeType);
  2739. };
  2740. /**
  2741. * displays the attachment
  2742. *
  2743. * @name AttachmentViewer.showAttachment
  2744. * @function
  2745. */
  2746. me.showAttachment = function()
  2747. {
  2748. // skip, if attachments got disabled
  2749. if (!$attachment || !$attachmentPreview) return;
  2750. $attachment.removeClass('hidden');
  2751. if (me.hasAttachmentPreview()) {
  2752. $attachmentPreview.removeClass('hidden');
  2753. }
  2754. };
  2755. /**
  2756. * removes the attachment
  2757. *
  2758. * This automatically hides the attachment containers too, to
  2759. * prevent an inconsistent display.
  2760. *
  2761. * @name AttachmentViewer.removeAttachment
  2762. * @function
  2763. */
  2764. me.removeAttachment = function()
  2765. {
  2766. if (!$attachment.length) {
  2767. return;
  2768. }
  2769. me.hideAttachment();
  2770. me.hideAttachmentPreview();
  2771. $attachment.html('');
  2772. $attachmentPreview.html('');
  2773. $dragAndDropFileNames.html('');
  2774. AttachmentViewer.removeAttachmentData();
  2775. };
  2776. /**
  2777. * removes the attachment data
  2778. *
  2779. * This removes the data, which would be uploaded otherwise.
  2780. *
  2781. * @name AttachmentViewer.removeAttachmentData
  2782. * @function
  2783. */
  2784. me.removeAttachmentData = function()
  2785. {
  2786. files = undefined;
  2787. attachmentsData = [];
  2788. };
  2789. /**
  2790. * Cleares the drag & drop data.
  2791. *
  2792. * @name AttachmentViewer.clearDragAndDrop
  2793. * @function
  2794. */
  2795. me.clearDragAndDrop = function()
  2796. {
  2797. $dragAndDropFileNames.html('');
  2798. };
  2799. /**
  2800. * Print file names added via drag & drop
  2801. *
  2802. * @name AttachmentViewer.printDragAndDropFileNames
  2803. * @private
  2804. * @function
  2805. * @param {array} fileNames
  2806. */
  2807. function printDragAndDropFileNames(fileNames) {
  2808. $dragAndDropFileNames.html(fileNames.join("<br>"));
  2809. }
  2810. /**
  2811. * hides the attachment
  2812. *
  2813. * This will not hide the preview (see AttachmentViewer.hideAttachmentPreview
  2814. * for that) nor will it hide the attachment link if it was moved somewhere
  2815. * else (see AttachmentViewer.moveAttachmentTo).
  2816. *
  2817. * @name AttachmentViewer.hideAttachment
  2818. * @function
  2819. */
  2820. me.hideAttachment = function()
  2821. {
  2822. $attachment.addClass('hidden');
  2823. };
  2824. /**
  2825. * hides the attachment preview
  2826. *
  2827. * @name AttachmentViewer.hideAttachmentPreview
  2828. * @function
  2829. */
  2830. me.hideAttachmentPreview = function()
  2831. {
  2832. if ($attachmentPreview) {
  2833. $attachmentPreview.addClass('hidden');
  2834. }
  2835. };
  2836. /**
  2837. * checks if has any attachment preview
  2838. *
  2839. * @name AttachmentViewer.hasAttachmentPreview
  2840. * @function
  2841. * @return {JQuery}
  2842. */
  2843. me.hasAttachmentPreview = function()
  2844. {
  2845. return $attachmentPreview.children().length > 0;
  2846. }
  2847. /**
  2848. * checks if there is an attachment displayed
  2849. *
  2850. * @name AttachmentViewer.hasAttachment
  2851. * @function
  2852. */
  2853. me.hasAttachment = function()
  2854. {
  2855. if (!$attachment.length) {
  2856. return false;
  2857. }
  2858. return [...$attachment.children()].length > 0;
  2859. };
  2860. /**
  2861. * checks if there is attachment data (for preview!) available
  2862. *
  2863. * It returns true, when there is data that needs to be encrypted.
  2864. *
  2865. * @name AttachmentViewer.hasAttachmentData
  2866. * @function
  2867. */
  2868. me.hasAttachmentData = function()
  2869. {
  2870. if ($attachment.length) {
  2871. return true;
  2872. }
  2873. return false;
  2874. };
  2875. /**
  2876. * return the attachments
  2877. *
  2878. * @name AttachmentViewer.getAttachments
  2879. * @function
  2880. * @returns {array}
  2881. */
  2882. me.getAttachments = function()
  2883. {
  2884. return [...$attachment.find('a')].map(link => (
  2885. [
  2886. $(link).prop('href'),
  2887. $(link).prop('download')
  2888. ]
  2889. ));
  2890. };
  2891. /**
  2892. * Get attachment mime type
  2893. *
  2894. * @name AttachmentViewer.getAttachmentMimeType
  2895. * @function
  2896. * @param {string} attachmentData - Base64 string
  2897. */
  2898. me.getAttachmentMimeType = function(attachmentData)
  2899. {
  2900. // position in data URI string of where mimeType ends
  2901. const mimeTypeEnd = attachmentData.indexOf(';');
  2902. // extract mimeType
  2903. return attachmentData.substring(5, mimeTypeEnd);
  2904. }
  2905. /**
  2906. * moves the attachment link to another element
  2907. *
  2908. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  2909. *
  2910. * @name AttachmentViewer.moveAttachmentTo
  2911. * @function
  2912. * @param {jQuery} $element - the wrapper/container element where this should be moved to
  2913. * @param {array} attachment - attachment data
  2914. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  2915. */
  2916. me.moveAttachmentTo = function($element, attachment, label)
  2917. {
  2918. const attachmentLink = $(document.createElement('a'))
  2919. .addClass('alert-link')
  2920. .prop('href', attachment[0])
  2921. .prop('download', attachment[1]);
  2922. // move elemement to new place
  2923. attachmentLink.appendTo($element);
  2924. // update text - ensuring no HTML is inserted into the text node
  2925. I18n._(attachmentLink, label, attachment[1]);
  2926. };
  2927. /**
  2928. * read files data as data URL using the FileReader API
  2929. *
  2930. * @name AttachmentViewer.readFileData
  2931. * @private
  2932. * @function
  2933. * @param {FileList[]} loadedFiles (optional) loaded files array
  2934. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsDataURL()}
  2935. */
  2936. function readFileData(loadedFiles) {
  2937. // Clear old cache
  2938. me.removeAttachmentData();
  2939. if (typeof FileReader === 'undefined') {
  2940. // revert loading status…
  2941. me.hideAttachment();
  2942. me.hideAttachmentPreview();
  2943. Alert.showWarning('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2944. return;
  2945. }
  2946. if (loadedFiles === undefined) {
  2947. loadedFiles = [...$fileInput[0].files];
  2948. me.clearDragAndDrop();
  2949. } else {
  2950. const fileNames = loadedFiles.map((loadedFile => loadedFile.name));
  2951. printDragAndDropFileNames(fileNames);
  2952. }
  2953. if (typeof loadedFiles !== 'undefined') {
  2954. files = loadedFiles;
  2955. loadedFiles.forEach((loadedFile, index) => {
  2956. const fileReader = new FileReader();
  2957. fileReader.onload = function (event) {
  2958. const dataURL = event.target.result;
  2959. if (dataURL) {
  2960. attachmentsData[index] = dataURL;
  2961. }
  2962. if (Editor.isPreview()) {
  2963. me.handleAttachmentPreview($attachmentPreview, dataURL);
  2964. $attachmentPreview.removeClass('hidden');
  2965. }
  2966. TopNav.highlightFileupload();
  2967. };
  2968. fileReader.readAsDataURL(loadedFile);
  2969. });
  2970. } else {
  2971. me.removeAttachmentData();
  2972. }
  2973. }
  2974. /**
  2975. * handle the preview of files decoded to blob that can either be an image, video, audio or pdf element
  2976. *
  2977. * @name AttachmentViewer.handleBlobAttachmentPreview
  2978. * @function
  2979. * @argument {jQuery} $targetElement element where the preview should be appended
  2980. * @argument {string} file as a blob URL
  2981. * @argument {string} mime type
  2982. */
  2983. me.handleBlobAttachmentPreview = function ($targetElement, blobUrl, mimeType) {
  2984. const alreadyIncludesCurrentAttachment = $targetElement.find(`[src='${blobUrl}']`).length > 0;
  2985. if (blobUrl && !alreadyIncludesCurrentAttachment) {
  2986. if (mimeType.match(/^image\//i)) {
  2987. $targetElement.append(
  2988. $(document.createElement('img'))
  2989. .attr('src', blobUrl)
  2990. .attr('class', 'img-thumbnail')
  2991. );
  2992. } else if (mimeType.match(/^video\//i)) {
  2993. $targetElement.append(
  2994. $(document.createElement('video'))
  2995. .attr('controls', 'true')
  2996. .attr('autoplay', 'true')
  2997. .attr('class', 'img-thumbnail')
  2998. .append($(document.createElement('source'))
  2999. .attr('type', mimeType)
  3000. .attr('src', blobUrl))
  3001. );
  3002. } else if (mimeType.match(/^audio\//i)) {
  3003. $targetElement.append(
  3004. $(document.createElement('audio'))
  3005. .attr('controls', 'true')
  3006. .attr('autoplay', 'true')
  3007. .append($(document.createElement('source'))
  3008. .attr('type', mimeType)
  3009. .attr('src', blobUrl))
  3010. );
  3011. } else if (mimeType.match(/\/pdf/i)) {
  3012. // Fallback for browsers, that don't support the vh unit
  3013. const clientHeight = $(window).height();
  3014. $targetElement.append(
  3015. $(document.createElement('embed'))
  3016. .attr('src', blobUrl)
  3017. .attr('type', 'application/pdf')
  3018. .attr('class', 'pdfPreview')
  3019. .css('height', clientHeight)
  3020. );
  3021. }
  3022. }
  3023. };
  3024. /**
  3025. * attaches the file attachment drag & drop handler to the page
  3026. *
  3027. * @name AttachmentViewer.addDragDropHandler
  3028. * @private
  3029. * @function
  3030. */
  3031. function addDragDropHandler() {
  3032. if (typeof $fileInput === 'undefined' || $fileInput.length === 0) {
  3033. return;
  3034. }
  3035. const handleDragEnterOrOver = function(event) {
  3036. event.stopPropagation();
  3037. event.preventDefault();
  3038. return false;
  3039. };
  3040. const handleDrop = function(event) {
  3041. const evt = event.originalEvent;
  3042. evt.stopPropagation();
  3043. evt.preventDefault();
  3044. if (TopNav.isAttachmentReadonly()) {
  3045. return false;
  3046. }
  3047. if ($fileInput) {
  3048. const files = [...evt.dataTransfer.files];
  3049. //Clear the file input:
  3050. $fileInput.wrap('<form>').closest('form').get(0).reset();
  3051. $fileInput.unwrap();
  3052. //Only works in Chrome:
  3053. //fileInput[0].files = e.dataTransfer.files;
  3054. readFileData(files);
  3055. }
  3056. };
  3057. $(document).draghover().on({
  3058. 'draghoverstart': function(e) {
  3059. if (TopNav.isAttachmentReadonly()) {
  3060. e.stopPropagation();
  3061. e.preventDefault();
  3062. return false;
  3063. }
  3064. // show dropzone to indicate drop support
  3065. $dropzone.removeClass('hidden');
  3066. },
  3067. 'draghoverend': function() {
  3068. $dropzone.addClass('hidden');
  3069. }
  3070. });
  3071. $(document).on('drop', handleDrop);
  3072. $(document).on('dragenter dragover', handleDragEnterOrOver);
  3073. $fileInput.on('change', function () {
  3074. readFileData();
  3075. });
  3076. }
  3077. /**
  3078. * attaches the clipboard attachment handler to the page
  3079. *
  3080. * @name AttachmentViewer.addClipboardEventHandler
  3081. * @private
  3082. * @function
  3083. */
  3084. function addClipboardEventHandler() {
  3085. $('#message').on('paste', function (event) {
  3086. const items = (event.clipboardData || event.originalEvent.clipboardData).items;
  3087. const files = [...items]
  3088. .filter(item => item.kind === 'file')
  3089. .map(item => item.getAsFile());
  3090. if (TopNav.isAttachmentReadonly()) {
  3091. event.stopPropagation();
  3092. event.preventDefault();
  3093. return false;
  3094. }
  3095. readFileData(files);
  3096. });
  3097. }
  3098. /**
  3099. * getter for attachment data
  3100. *
  3101. * @name AttachmentViewer.getAttachmentsData
  3102. * @function
  3103. * @return {string[]}
  3104. */
  3105. me.getAttachmentsData = function () {
  3106. return attachmentsData;
  3107. };
  3108. /**
  3109. * getter for attachment preview
  3110. *
  3111. * @name AttachmentViewer.getAttachmentPreview
  3112. * @function
  3113. * @return {jQuery}
  3114. */
  3115. me.getAttachmentPreview = function () {
  3116. return $attachmentPreview;
  3117. };
  3118. /**
  3119. * getter for files data, returns the file list
  3120. *
  3121. * @name AttachmentViewer.getFiles
  3122. * @function
  3123. * @return {FileList[]}
  3124. */
  3125. me.getFiles = function () {
  3126. return files;
  3127. };
  3128. /**
  3129. * initiate
  3130. *
  3131. * preloads jQuery elements
  3132. *
  3133. * @name AttachmentViewer.init
  3134. * @function
  3135. */
  3136. me.init = function()
  3137. {
  3138. $attachment = $('#attachment');
  3139. $dragAndDropFileNames = $('#dragAndDropFileName');
  3140. $dropzone = $('#dropzone');
  3141. if($attachment.length) {
  3142. $attachmentPreview = $('#attachmentPreview');
  3143. $fileInput = $('#file');
  3144. addDragDropHandler();
  3145. addClipboardEventHandler();
  3146. }
  3147. }
  3148. return me;
  3149. })();
  3150. /**
  3151. * (view) Shows discussion thread and handles replies
  3152. *
  3153. * @name DiscussionViewer
  3154. * @class
  3155. */
  3156. const DiscussionViewer = (function () {
  3157. const me = {};
  3158. let $commentTail,
  3159. $discussion,
  3160. $reply,
  3161. $replyMessage,
  3162. $replyNickname,
  3163. $replyStatus,
  3164. $commentContainer,
  3165. replyCommentId;
  3166. /**
  3167. * initializes the templates
  3168. *
  3169. * @name DiscussionViewer.initTemplates
  3170. * @private
  3171. * @function
  3172. */
  3173. function initTemplates()
  3174. {
  3175. $reply = Model.getTemplate('reply');
  3176. $replyMessage = $reply.find('#replymessage');
  3177. $replyNickname = $reply.find('#nickname');
  3178. $replyStatus = $reply.find('#replystatus');
  3179. // cache jQuery elements
  3180. $commentTail = Model.getTemplate('commenttail');
  3181. }
  3182. /**
  3183. * open the comment entry when clicking the "Reply" button of a comment
  3184. *
  3185. * @name DiscussionViewer.openReply
  3186. * @private
  3187. * @function
  3188. * @param {Event} event
  3189. */
  3190. function openReply(event)
  3191. {
  3192. const $source = $(event.target);
  3193. // show all reply buttons
  3194. $commentContainer.find('button').removeClass('hidden');
  3195. // hide the current reply button
  3196. $source.addClass('hidden');
  3197. // clear input
  3198. $replyMessage.val('');
  3199. $replyNickname.val('');
  3200. // get comment id from source element
  3201. replyCommentId = $source.parent().prop('id').split('_')[1];
  3202. // move to correct position
  3203. $source.after($reply);
  3204. // show
  3205. $reply.removeClass('hidden');
  3206. $replyMessage.focus();
  3207. event.preventDefault();
  3208. }
  3209. /**
  3210. * custom handler for displaying notifications in own status message area
  3211. *
  3212. * @name DiscussionViewer.handleNotification
  3213. * @function
  3214. * @param {string} alertType
  3215. * @return {bool|jQuery}
  3216. */
  3217. me.handleNotification = function(alertType)
  3218. {
  3219. // ignore loading messages
  3220. if (alertType === 'loading') {
  3221. return false;
  3222. }
  3223. if (alertType === 'danger') {
  3224. $replyStatus.removeClass('alert-info');
  3225. $replyStatus.addClass('alert-danger');
  3226. $replyStatus.find(':first').removeClass('glyphicon-alert');
  3227. $replyStatus.find(':first').addClass('glyphicon-info-sign');
  3228. } else {
  3229. $replyStatus.removeClass('alert-danger');
  3230. $replyStatus.addClass('alert-info');
  3231. $replyStatus.find(':first').removeClass('glyphicon-info-sign');
  3232. $replyStatus.find(':first').addClass('glyphicon-alert');
  3233. }
  3234. return $replyStatus;
  3235. };
  3236. /**
  3237. * adds another comment
  3238. *
  3239. * @name DiscussionViewer.addComment
  3240. * @function
  3241. * @param {Comment} comment
  3242. * @param {string} commentText
  3243. * @param {string} nickname
  3244. */
  3245. me.addComment = function(comment, commentText, nickname)
  3246. {
  3247. if (commentText === '') {
  3248. commentText = 'comment decryption failed';
  3249. }
  3250. // create new comment based on template
  3251. const $commentEntry = Model.getTemplate('comment');
  3252. $commentEntry.prop('id', 'comment_' + comment.id);
  3253. const $commentEntryData = $commentEntry.find('div.commentdata');
  3254. // set & parse text
  3255. $commentEntryData.text(commentText);
  3256. Helper.urls2links($commentEntryData);
  3257. // set nickname
  3258. if (nickname.length > 0) {
  3259. $commentEntry.find('span.nickname').text(nickname);
  3260. } else {
  3261. $commentEntry.find('span.nickname').html('<i></i>');
  3262. I18n._($commentEntry.find('span.nickname i'), 'Anonymous');
  3263. }
  3264. // set date
  3265. const created = comment.getCreated();
  3266. const commentDate = created == 0 ? '' : ' (' + (new Date(created * 1000).toLocaleString()) + ')';
  3267. $commentEntry.find('span.commentdate')
  3268. .text(commentDate)
  3269. .attr('title', 'CommentID: ' + comment.id);
  3270. // if an avatar is available, display it
  3271. const icon = comment.getIcon();
  3272. if (icon) {
  3273. $commentEntry.find('span.nickname')
  3274. .before(
  3275. '<img src="' + icon + '" class="vizhash" /> '
  3276. );
  3277. $(document).on('languageLoaded', function () {
  3278. $commentEntry.find('img.vizhash')
  3279. .prop('title', I18n._('Avatar generated from IP address'));
  3280. });
  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. });
  4889. }
  4890. /**
  4891. * show decrypted text in the display area, including discussion (if open)
  4892. *
  4893. * @name PasteDecrypter.run
  4894. * @function
  4895. * @param {Paste} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  4896. */
  4897. me.run = function(paste)
  4898. {
  4899. Alert.hideMessages();
  4900. Alert.setCustomHandler(null);
  4901. Alert.showLoading('Decrypting document…', 'cloud-download');
  4902. if (typeof paste === 'undefined' || paste.type === 'click') {
  4903. // get cipher data and wait until it is available
  4904. Model.getPasteData(me.run);
  4905. return;
  4906. }
  4907. let key = Model.getPasteKey(),
  4908. password = Prompt.getPassword(),
  4909. decryptionPromises = [];
  4910. TopNav.setRetryCallback(function () {
  4911. TopNav.hideRetryButton();
  4912. me.run(paste);
  4913. });
  4914. // Clear attachments to prevent duplicates
  4915. AttachmentViewer.removeAttachment();
  4916. // decrypt paste & attachments
  4917. decryptionPromises.push(decryptPaste(paste, key, password));
  4918. // if the discussion is opened on this document, display it
  4919. if (paste.isDiscussionEnabled()) {
  4920. decryptionPromises.push(decryptComments(paste, key, password));
  4921. }
  4922. // shows the remaining time (until) deletion
  4923. PasteStatus.showRemainingTime(paste);
  4924. CopyToClipboard.showKeyboardShortcutHint();
  4925. Promise.all(decryptionPromises)
  4926. .then(() => {
  4927. Alert.hideLoading();
  4928. TopNav.showViewButtons();
  4929. // discourage cloning (it cannot really be prevented)
  4930. if (paste.isBurnAfterReadingEnabled()) {
  4931. TopNav.hideBurnAfterReadingButtons();
  4932. } else {
  4933. // we have to pass in remaining_time here
  4934. TopNav.showEmailButton(paste.getTimeToLive());
  4935. }
  4936. // only offer adding comments, after document was successfully decrypted
  4937. if (paste.isDiscussionEnabled()) {
  4938. DiscussionViewer.finishDiscussion();
  4939. }
  4940. })
  4941. .catch((err) => {
  4942. // wait for the user to type in the password,
  4943. // then PasteDecrypter.run will be called again
  4944. Alert.showError(err);
  4945. });
  4946. };
  4947. return me;
  4948. })();
  4949. /**
  4950. *
  4951. * @name CopyToClipboard
  4952. * @class
  4953. */
  4954. const CopyToClipboard = (function () {
  4955. const me = {};
  4956. let copyButton,
  4957. copyLinkButton,
  4958. copyIcon,
  4959. successIcon,
  4960. shortcutHint,
  4961. url;
  4962. /**
  4963. * Handle copy to clipboard button click
  4964. *
  4965. * @name CopyToClipboard.handleCopyButtonClick
  4966. * @private
  4967. * @function
  4968. */
  4969. function handleCopyButtonClick() {
  4970. $(copyButton).click(function() {
  4971. const text = PasteViewer.getText();
  4972. saveToClipboard(text);
  4973. toggleSuccessIcon();
  4974. showAlertMessage('Document copied to clipboard');
  4975. });
  4976. };
  4977. /**
  4978. * Handle copy link to clipboard button click
  4979. *
  4980. * @name CopyToClipboard.handleCopyLinkButtonClick
  4981. * @private
  4982. * @function
  4983. */
  4984. function handleCopyLinkButtonClick() {
  4985. $(copyLinkButton).click(function () {
  4986. saveToClipboard(url);
  4987. showAlertMessage('Link copied to clipboard');
  4988. });
  4989. }
  4990. /**
  4991. * Handle CTRL+C/CMD+C keyboard shortcut
  4992. *
  4993. * @name CopyToClipboard.handleKeyboardShortcut
  4994. * @private
  4995. * @function
  4996. */
  4997. function handleKeyboardShortcut() {
  4998. $(document).bind('copy', function () {
  4999. if (!isUserSelectedTextToCopy()) {
  5000. const text = PasteViewer.getText();
  5001. saveToClipboard(text);
  5002. showAlertMessage('Document copied to clipboard');
  5003. }
  5004. });
  5005. };
  5006. /**
  5007. * Check if user selected some text on the page to copy it
  5008. *
  5009. * @name CopyToClipboard.isUserSelectedTextToCopy
  5010. * @private
  5011. * @function
  5012. * @returns {boolean}
  5013. */
  5014. function isUserSelectedTextToCopy() {
  5015. let text = '';
  5016. if (window.getSelection) {
  5017. text = window.getSelection().toString();
  5018. } else if (document.selection && document.selection.type != 'Control') {
  5019. text = document.selection.createRange().text;
  5020. }
  5021. return text.length > 0;
  5022. };
  5023. /**
  5024. * Save text to the clipboard
  5025. *
  5026. * @name CopyToClipboard.saveToClipboard
  5027. * @private
  5028. * @param {string} text
  5029. * @function
  5030. */
  5031. function saveToClipboard(text) {
  5032. navigator.clipboard.writeText(text);
  5033. };
  5034. /**
  5035. * Show alert message after text copy
  5036. *
  5037. * @name CopyToClipboard.showAlertMessage
  5038. * @private
  5039. * @param {string} message
  5040. * @function
  5041. */
  5042. function showAlertMessage(message) {
  5043. Alert.showStatus(message);
  5044. };
  5045. /**
  5046. * Toogle success icon after copy
  5047. *
  5048. * @name CopyToClipboard.toggleSuccessIcon
  5049. * @private
  5050. * @function
  5051. */
  5052. function toggleSuccessIcon() {
  5053. $(copyIcon).css('display', 'none');
  5054. $(successIcon).css('display', 'block');
  5055. setTimeout(function() {
  5056. $(copyIcon).css('display', 'block');
  5057. $(successIcon).css('display', 'none');
  5058. }, 1000);
  5059. };
  5060. /**
  5061. * Show keyboard shortcut hint
  5062. *
  5063. * @name CopyToClipboard.showKeyboardShortcutHint
  5064. * @function
  5065. */
  5066. me.showKeyboardShortcutHint = function () {
  5067. I18n._(
  5068. shortcutHint,
  5069. '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>'
  5070. );
  5071. };
  5072. /**
  5073. * Hide keyboard shortcut hint
  5074. *
  5075. * @name CopyToClipboard.showKeyboardShortcutHint
  5076. * @function
  5077. */
  5078. me.hideKeyboardShortcutHint = function () {
  5079. $(shortcutHint).html('');
  5080. };
  5081. /**
  5082. * Set document url
  5083. *
  5084. * @name CopyToClipboard.setUrl
  5085. * @param {string} newUrl
  5086. * @function
  5087. */
  5088. me.setUrl = function (newUrl) {
  5089. url = newUrl;
  5090. };
  5091. /**
  5092. * Initialize
  5093. *
  5094. * @name CopyToClipboard.init
  5095. * @function
  5096. */
  5097. me.init = function() {
  5098. copyButton = $('#prettyMessageCopyBtn');
  5099. copyLinkButton = $('#copyLink');
  5100. copyIcon = $('#copyIcon');
  5101. successIcon = $('#copySuccessIcon');
  5102. shortcutHint = $('#copyShortcutHintText');
  5103. handleCopyButtonClick();
  5104. handleCopyLinkButtonClick();
  5105. handleKeyboardShortcut();
  5106. };
  5107. return me;
  5108. })();
  5109. /**
  5110. *
  5111. * @name PasswordPeek
  5112. * @class
  5113. */
  5114. const PasswordPeek = (function () {
  5115. const me = {};
  5116. /**
  5117. * Switch between visible and hidden password
  5118. *
  5119. * @name PasswordPeek.handleRevealButtonClick
  5120. * @private
  5121. * @function
  5122. */
  5123. function handleRevealButtonClick() {
  5124. const element = $(this);
  5125. const passwordInput = element.siblings('.input-password');
  5126. const isHidden = passwordInput.attr('type') === 'password';
  5127. passwordInput.attr('type', isHidden ? 'text' : 'password');
  5128. const tooltip = I18n._(isHidden ? 'Hide password' : 'Show password');
  5129. element.attr('title', tooltip);
  5130. element.attr('aria-label', tooltip);
  5131. // handle bootstrap 5 icons: eye & eye-slash
  5132. const buttonSvg = element.find('use');
  5133. if (buttonSvg.length) {
  5134. const iconHref = buttonSvg.attr('href');
  5135. if (isHidden) {
  5136. buttonSvg.attr('href', iconHref + '-slash');
  5137. } else {
  5138. buttonSvg.attr('href', iconHref.substring(0, iconHref.length - 6));
  5139. }
  5140. return;
  5141. }
  5142. // handle bootstrap 3 icons: eye-open & eye-close
  5143. const buttonSpan = element.find('span');
  5144. if (buttonSpan.length) {
  5145. if (isHidden) {
  5146. buttonSpan.addClass('glyphicon-eye-close');
  5147. buttonSpan.removeClass('glyphicon-eye-open');
  5148. } else {
  5149. buttonSpan.addClass('glyphicon-eye-open');
  5150. buttonSpan.removeClass('glyphicon-eye-close');
  5151. }
  5152. }
  5153. }
  5154. /**
  5155. * Initialize
  5156. *
  5157. * @name PasswordPeek.init
  5158. * @function
  5159. */
  5160. me.init = function() {
  5161. const revealButton = $('.toggle-password');
  5162. revealButton.click(handleRevealButtonClick);
  5163. };
  5164. return me;
  5165. })();
  5166. /**
  5167. * (controller) main PrivateBin logic
  5168. *
  5169. * @name Controller
  5170. * @param {object} window
  5171. * @param {object} document
  5172. * @class
  5173. */
  5174. const Controller = (function (window, document) {
  5175. const me = {};
  5176. /**
  5177. * hides all status messages no matter which module showed them
  5178. *
  5179. * @name Controller.hideStatusMessages
  5180. * @function
  5181. */
  5182. me.hideStatusMessages = function()
  5183. {
  5184. PasteStatus.hideMessages();
  5185. Alert.hideMessages();
  5186. CopyToClipboard.hideKeyboardShortcutHint();
  5187. };
  5188. /**
  5189. * creates a new document
  5190. *
  5191. * @name Controller.newPaste
  5192. * @function
  5193. */
  5194. me.newPaste = function()
  5195. {
  5196. // Important: This *must not* run Alert.hideMessages() as previous
  5197. // errors from viewing a document should be shown.
  5198. TopNav.hideAllButtons();
  5199. Alert.showLoading('Preparing new document…', 'time');
  5200. PasteStatus.hideMessages();
  5201. PasteViewer.hide();
  5202. Editor.resetInput();
  5203. Editor.show();
  5204. Editor.focusInput();
  5205. AttachmentViewer.removeAttachment();
  5206. TopNav.resetInput();
  5207. TopNav.showCreateButtons();
  5208. // newPaste could be called when user is on document clone editing view
  5209. TopNav.hideCustomAttachment();
  5210. AttachmentViewer.clearDragAndDrop();
  5211. AttachmentViewer.removeAttachmentData();
  5212. Alert.hideLoading();
  5213. // only push new state if we are coming from a different one
  5214. if (Helper.baseUri() != window.location) {
  5215. history.pushState({type: 'create'}, document.title, Helper.baseUri());
  5216. }
  5217. // clear discussion
  5218. DiscussionViewer.prepareNewDiscussion();
  5219. };
  5220. /**
  5221. * shows the loaded document
  5222. *
  5223. * @name Controller.showPaste
  5224. * @function
  5225. */
  5226. me.showPaste = function()
  5227. {
  5228. try {
  5229. Model.getPasteKey();
  5230. } catch (err) {
  5231. console.error(err);
  5232. 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?)');
  5233. return;
  5234. }
  5235. // check if we should request loading confirmation
  5236. if(window.location.hash.startsWith(loadConfirmPrefix)) {
  5237. Prompt.requestLoadConfirmation();
  5238. return;
  5239. }
  5240. // show proper elements on screen
  5241. PasteDecrypter.run();
  5242. };
  5243. /**
  5244. * refreshes the loaded document to show potential new data
  5245. *
  5246. * @name Controller.refreshPaste
  5247. * @function
  5248. * @param {function} callback
  5249. */
  5250. me.refreshPaste = function(callback)
  5251. {
  5252. // save window position to restore it later
  5253. const orgPosition = $(window).scrollTop();
  5254. Model.getPasteData(function (data) {
  5255. ServerInteraction.prepare();
  5256. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + Model.getPasteId());
  5257. ServerInteraction.setFailure(function (status, data) {
  5258. // revert loading status…
  5259. Alert.hideLoading();
  5260. TopNav.showViewButtons();
  5261. // show error message
  5262. Alert.showError(
  5263. ServerInteraction.parseUploadError(status, data, 'refresh display')
  5264. );
  5265. });
  5266. ServerInteraction.setSuccess(function (status, data) {
  5267. PasteDecrypter.run(new Paste(data));
  5268. // restore position
  5269. window.scrollTo(0, orgPosition);
  5270. // NOTE: could create problems as callback may be called
  5271. // asyncronously if PasteDecrypter e.g. needs to wait for a
  5272. // password being entered
  5273. callback();
  5274. });
  5275. ServerInteraction.run();
  5276. }, false); // this false is important as it circumvents the cache
  5277. }
  5278. /**
  5279. * clone the current document
  5280. *
  5281. * @name Controller.clonePaste
  5282. * @function
  5283. */
  5284. me.clonePaste = function()
  5285. {
  5286. TopNav.collapseBar();
  5287. TopNav.hideAllButtons();
  5288. // hide messages from previous document
  5289. me.hideStatusMessages();
  5290. // erase the id and the key in url
  5291. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  5292. if (AttachmentViewer.hasAttachment()) {
  5293. const attachments = AttachmentViewer.getAttachments();
  5294. attachments.forEach(attachment => {
  5295. AttachmentViewer.moveAttachmentTo(
  5296. TopNav.getCustomAttachment(),
  5297. attachment,
  5298. 'Cloned: \'%s\''
  5299. );
  5300. });
  5301. TopNav.hideFileSelector();
  5302. AttachmentViewer.hideAttachment();
  5303. // NOTE: it also looks nice without removing the attachment
  5304. // but for a consistent display we remove it…
  5305. AttachmentViewer.hideAttachmentPreview();
  5306. TopNav.showCustomAttachment();
  5307. // show another status messages to make the user aware that the
  5308. // files were cloned too!
  5309. Alert.showStatus(
  5310. [
  5311. 'The cloned file \'%s\' was attached to this document.',
  5312. attachments.map(attachment => attachment[1]).join(', '),
  5313. ],
  5314. 'copy'
  5315. );
  5316. }
  5317. Editor.setText(PasteViewer.getText());
  5318. // also clone the format
  5319. TopNav.setFormat(PasteViewer.getFormat());
  5320. PasteViewer.hide();
  5321. Editor.show();
  5322. TopNav.showCreateButtons();
  5323. // clear discussion
  5324. DiscussionViewer.prepareNewDiscussion();
  5325. };
  5326. /**
  5327. * try initializing zlib or display a warning if it fails,
  5328. * extracted from main init to allow unit testing
  5329. *
  5330. * @name Controller.initZ
  5331. * @function
  5332. */
  5333. me.initZ = function()
  5334. {
  5335. z = zlib.catch(function () {
  5336. if ($('body').data('compression') !== 'none') {
  5337. Alert.showWarning('Your browser doesn\'t support WebAssembly, used for zlib compression. You can create uncompressed documents, but can\'t read compressed ones.');
  5338. }
  5339. });
  5340. }
  5341. /**
  5342. * application start
  5343. *
  5344. * @name Controller.init
  5345. * @function
  5346. */
  5347. me.init = function()
  5348. {
  5349. // first load translations
  5350. I18n.loadTranslations();
  5351. // Add a hook to make all links open a new window
  5352. DOMPurify.addHook('afterSanitizeAttributes', function(node) {
  5353. // set all elements owning target to target=_blank
  5354. if ('target' in node && node.id !== 'pasteurl') {
  5355. node.setAttribute('target', '_blank');
  5356. }
  5357. // set non-HTML/MathML links to xlink:show=new
  5358. if (!node.hasAttribute('target')
  5359. && (node.hasAttribute('xlink:href')
  5360. || node.hasAttribute('href'))) {
  5361. node.setAttribute('xlink:show', 'new');
  5362. }
  5363. if ('rel' in node) {
  5364. node.setAttribute('rel', 'nofollow noopener noreferrer');
  5365. }
  5366. });
  5367. // center all modals
  5368. $('.modal').on('show.bs.modal', function(e) {
  5369. $(e.target).css({
  5370. display: 'flex'
  5371. });
  5372. });
  5373. // initialize other modules/"classes"
  5374. Alert.init();
  5375. Model.init();
  5376. AttachmentViewer.init();
  5377. DiscussionViewer.init();
  5378. Editor.init();
  5379. PasteStatus.init();
  5380. PasteViewer.init();
  5381. Prompt.init();
  5382. TopNav.init();
  5383. UiHelper.init();
  5384. CopyToClipboard.init();
  5385. PasswordPeek.init();
  5386. // check for legacy browsers before going any further
  5387. if (!Legacy.Check.getInit()) {
  5388. // Legacy check didn't complete, wait and try again
  5389. setTimeout(init, 500);
  5390. return;
  5391. }
  5392. if (!Legacy.Check.getStatus()) {
  5393. // something major is wrong, stop right away
  5394. return;
  5395. }
  5396. me.initZ();
  5397. // if delete token is passed (i.e. document has been deleted by this
  5398. // access), add an event listener for the 'new' document button in the alert
  5399. if (Model.hasDeleteToken()) {
  5400. $("#new-from-alert").on("click", function () {
  5401. UiHelper.reloadHome();
  5402. });
  5403. return;
  5404. }
  5405. // check whether existing document needs to be shown
  5406. try {
  5407. Model.getPasteId();
  5408. } catch (e) {
  5409. // otherwise create a new document
  5410. return me.newPaste();
  5411. }
  5412. // always reload on back button to invalidate cache (protect burn after read document)
  5413. window.addEventListener('popstate', () => {
  5414. window.location.reload();
  5415. });
  5416. // display an existing document
  5417. return me.showPaste();
  5418. }
  5419. return me;
  5420. })(window, document);
  5421. return {
  5422. Helper: Helper,
  5423. I18n: I18n,
  5424. CryptTool: CryptTool,
  5425. Model: Model,
  5426. UiHelper: UiHelper,
  5427. Alert: Alert,
  5428. PasteStatus: PasteStatus,
  5429. Prompt: Prompt,
  5430. Editor: Editor,
  5431. PasteViewer: PasteViewer,
  5432. AttachmentViewer: AttachmentViewer,
  5433. DiscussionViewer: DiscussionViewer,
  5434. TopNav: TopNav,
  5435. ServerInteraction: ServerInteraction,
  5436. PasteEncrypter: PasteEncrypter,
  5437. PasteDecrypter: PasteDecrypter,
  5438. PasswordPeek: PasswordPeek,
  5439. CopyToClipboard: CopyToClipboard,
  5440. Controller: Controller
  5441. };
  5442. })(jQuery);