privatebin.js 174 KB

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