privatebin.js 183 KB

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