1
0

privatebin.js 166 KB

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