privatebin.js 154 KB

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