privatebin.js 164 KB

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