privatebin.js 165 KB

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