privatebin.js 191 KB

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