privatebin.js 190 KB

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