privatebin.js 174 KB

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