privatebin.js 175 KB

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