privatebin.js 167 KB

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