privatebin.js 192 KB

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