privatebin.js 151 KB

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