privatebin.js 191 KB

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