privatebin.js 174 KB

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