privatebin.js 178 KB

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