privatebin.js 147 KB

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