privatebin.js 190 KB

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