privatebin.js 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764
  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.1
  10. * @name PrivateBin
  11. * @namespace
  12. */
  13. 'use strict';
  14. /** global: Base64 */
  15. /** global: FileReader */
  16. /** global: RawDeflate */
  17. /** global: history */
  18. /** global: navigator */
  19. /** global: prettyPrint */
  20. /** global: prettyPrintOne */
  21. /** global: showdown */
  22. /** global: sjcl */
  23. // Immediately start random number generator collector.
  24. sjcl.random.startCollectors();
  25. jQuery.PrivateBin = function($, sjcl, Base64, RawDeflate) {
  26. /**
  27. * static helper methods
  28. *
  29. * @name helper
  30. * @class
  31. */
  32. var helper = {
  33. /**
  34. * converts a duration (in seconds) into human friendly approximation
  35. *
  36. * @name helper.secondsToHuman
  37. * @function
  38. * @param {number} seconds
  39. * @return {Array}
  40. */
  41. secondsToHuman: function(seconds)
  42. {
  43. var v;
  44. if (seconds < 60)
  45. {
  46. v = Math.floor(seconds);
  47. return [v, 'second'];
  48. }
  49. if (seconds < 60 * 60)
  50. {
  51. v = Math.floor(seconds / 60);
  52. return [v, 'minute'];
  53. }
  54. if (seconds < 60 * 60 * 24)
  55. {
  56. v = Math.floor(seconds / (60 * 60));
  57. return [v, 'hour'];
  58. }
  59. // If less than 2 months, display in days:
  60. if (seconds < 60 * 60 * 24 * 60)
  61. {
  62. v = Math.floor(seconds / (60 * 60 * 24));
  63. return [v, 'day'];
  64. }
  65. v = Math.floor(seconds / (60 * 60 * 24 * 30));
  66. return [v, 'month'];
  67. },
  68. /**
  69. * text range selection
  70. *
  71. * @see {@link https://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse}
  72. * @name helper.selectText
  73. * @function
  74. * @param {string} element - Indentifier of the element to select (id="")
  75. */
  76. selectText: function(element)
  77. {
  78. var doc = document,
  79. text = doc.getElementById(element),
  80. range,
  81. selection;
  82. // MS
  83. if (doc.body.createTextRange)
  84. {
  85. range = doc.body.createTextRange();
  86. range.moveToElementText(text);
  87. range.select();
  88. }
  89. // all others
  90. else if (window.getSelection)
  91. {
  92. selection = window.getSelection();
  93. range = doc.createRange();
  94. range.selectNodeContents(text);
  95. selection.removeAllRanges();
  96. selection.addRange(range);
  97. }
  98. },
  99. /**
  100. * set text of a DOM element (required for IE),
  101. * this is equivalent to element.text(text)
  102. *
  103. * @name helper.setElementText
  104. * @function
  105. * @param {Object} element - a DOM element
  106. * @param {string} text - the text to enter
  107. */
  108. setElementText: function(element, text)
  109. {
  110. // For IE<10: Doesn't support white-space:pre-wrap; so we have to do this...
  111. if ($('#oldienotice').is(':visible')) {
  112. var html = this.htmlEntities(text).replace(/\n/ig, '\r\n<br>');
  113. element.html('<pre>' + html + '</pre>');
  114. }
  115. // for other (sane) browsers:
  116. else
  117. {
  118. element.text(text);
  119. }
  120. },
  121. /**
  122. * replace last child of element with message
  123. *
  124. * @name helper.setMessage
  125. * @function
  126. * @param {Object} element - a jQuery wrapped DOM element
  127. * @param {string} message - the message to append
  128. */
  129. setMessage: function(element, message)
  130. {
  131. var content = element.contents();
  132. if (content.length > 0)
  133. {
  134. content[content.length - 1].nodeValue = ' ' + message;
  135. }
  136. else
  137. {
  138. this.setElementText(element, message);
  139. }
  140. },
  141. /**
  142. * convert URLs to clickable links.
  143. * URLs to handle:
  144. * <pre>
  145. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  146. * http://example.com:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  147. * http://user:example.com@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  148. * </pre>
  149. *
  150. * @name helper.urls2links
  151. * @function
  152. * @param {Object} element - a jQuery DOM element
  153. */
  154. urls2links: function(element)
  155. {
  156. var markup = '<a href="$1" rel="nofollow">$1</a>';
  157. element.html(
  158. element.html().replace(
  159. /((http|https|ftp):\/\/[\w?=&.\/-;#@~%+-]+(?![\w\s?&.\/;#~%"=-]*>))/ig,
  160. markup
  161. )
  162. );
  163. element.html(
  164. element.html().replace(
  165. /((magnet):[\w?=&.\/-;#@~%+-]+)/ig,
  166. markup
  167. )
  168. );
  169. },
  170. /**
  171. * minimal sprintf emulation for %s and %d formats
  172. *
  173. * @see {@link https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914}
  174. * @name helper.sprintf
  175. * @function
  176. * @param {string} format
  177. * @param {...*} args - one or multiple parameters injected into format string
  178. * @return {string}
  179. */
  180. sprintf: function()
  181. {
  182. var args = arguments;
  183. if (typeof arguments[0] === 'object')
  184. {
  185. args = arguments[0];
  186. }
  187. var format = args[0],
  188. i = 1;
  189. return format.replace(/%((%)|s|d)/g, function (m) {
  190. // m is the matched format, e.g. %s, %d
  191. var val;
  192. if (m[2]) {
  193. val = m[2];
  194. } else {
  195. val = args[i];
  196. // A switch statement so that the formatter can be extended.
  197. switch (m)
  198. {
  199. case '%d':
  200. val = parseFloat(val);
  201. if (isNaN(val)) {
  202. val = 0;
  203. }
  204. break;
  205. default:
  206. // Default is %s
  207. }
  208. ++i;
  209. }
  210. return val;
  211. });
  212. },
  213. /**
  214. * get value of cookie, if it was set, empty string otherwise
  215. *
  216. * @see {@link http://www.w3schools.com/js/js_cookies.asp}
  217. * @name helper.getCookie
  218. * @function
  219. * @param {string} cname
  220. * @return {string}
  221. */
  222. getCookie: function(cname) {
  223. var name = cname + '=',
  224. ca = document.cookie.split(';');
  225. for (var i = 0; i < ca.length; ++i) {
  226. var c = ca[i];
  227. while (c.charAt(0) === ' ')
  228. {
  229. c = c.substring(1);
  230. }
  231. if (c.indexOf(name) === 0)
  232. {
  233. return c.substring(name.length, c.length);
  234. }
  235. }
  236. return '';
  237. },
  238. /**
  239. * get the current script location (without search or hash part of the URL),
  240. * eg. http://example.com/path/?aaaa#bbbb --> http://example.com/path/
  241. *
  242. * @name helper.scriptLocation
  243. * @function
  244. * @return {string} current script location
  245. */
  246. scriptLocation: function()
  247. {
  248. var scriptLocation = window.location.href.substring(
  249. 0,
  250. window.location.href.length - window.location.search.length - window.location.hash.length
  251. ), hashIndex = scriptLocation.indexOf('#');
  252. if (hashIndex !== -1)
  253. {
  254. scriptLocation = scriptLocation.substring(0, hashIndex);
  255. }
  256. return scriptLocation;
  257. },
  258. /**
  259. * get the pastes unique identifier from the URL,
  260. * eg. http://example.com/path/?c05354954c49a487#c05354954c49a487 returns c05354954c49a487
  261. *
  262. * @name helper.pasteId
  263. * @function
  264. * @return {string} unique identifier
  265. */
  266. pasteId: function()
  267. {
  268. return window.location.search.substring(1);
  269. },
  270. /**
  271. * return the deciphering key stored in anchor part of the URL
  272. *
  273. * @name helper.pageKey
  274. * @function
  275. * @return {string} key
  276. */
  277. pageKey: function()
  278. {
  279. // Some web 2.0 services and redirectors add data AFTER the anchor
  280. // (such as &utm_source=...). We will strip any additional data.
  281. var key = window.location.hash.substring(1), // Get key
  282. i = key.indexOf('=');
  283. // First, strip everything after the equal sign (=) which signals end of base64 string.
  284. if (i > -1)
  285. {
  286. key = key.substring(0, i + 1);
  287. }
  288. // If the equal sign was not present, some parameters may remain:
  289. i = key.indexOf('&');
  290. if (i > -1)
  291. {
  292. key = key.substring(0, i);
  293. }
  294. // Then add trailing equal sign if it's missing
  295. if (key.charAt(key.length - 1) !== '=')
  296. {
  297. key += '=';
  298. }
  299. return key;
  300. },
  301. /**
  302. * convert all applicable characters to HTML entities
  303. *
  304. * @see {@link https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into_HTML_Element_Content}
  305. * @name helper.htmlEntities
  306. * @function
  307. * @param {string} str
  308. * @return {string} escaped HTML
  309. */
  310. htmlEntities: function(str) {
  311. return String(str).replace(
  312. /[&<>"'`=\/]/g, function(s) {
  313. return helper.entityMap[s];
  314. });
  315. },
  316. /**
  317. * character to HTML entity lookup table
  318. *
  319. * @see {@link https://github.com/janl/mustache.js/blob/master/mustache.js#L60}
  320. * @name helper.entityMap
  321. * @enum {Object}
  322. * @readonly
  323. */
  324. entityMap: {
  325. '&': '&amp;',
  326. '<': '&lt;',
  327. '>': '&gt;',
  328. '"': '&quot;',
  329. "'": '&#39;',
  330. '/': '&#x2F;',
  331. '`': '&#x60;',
  332. '=': '&#x3D;'
  333. }
  334. };
  335. /**
  336. * internationalization methods
  337. *
  338. * @name i18n
  339. * @class
  340. */
  341. var i18n = {
  342. /**
  343. * supported languages, minus the built in 'en'
  344. *
  345. * @name i18n.supportedLanguages
  346. * @prop {string[]}
  347. * @readonly
  348. */
  349. supportedLanguages: ['de', 'es', 'fr', 'it', 'no', 'pl', 'oc', 'ru', 'sl', 'zh'],
  350. /**
  351. * translate a string, alias for i18n.translate()
  352. *
  353. * @name i18n._
  354. * @function
  355. * @param {string} messageId
  356. * @param {...*} args - one or multiple parameters injected into placeholders
  357. * @return {string}
  358. */
  359. _: function()
  360. {
  361. return this.translate(arguments);
  362. },
  363. /**
  364. * translate a string
  365. *
  366. * @name i18n.translate
  367. * @function
  368. * @param {string} messageId
  369. * @param {...*} args - one or multiple parameters injected into placeholders
  370. * @return {string}
  371. */
  372. translate: function()
  373. {
  374. var args = arguments, messageId;
  375. if (typeof arguments[0] === 'object')
  376. {
  377. args = arguments[0];
  378. }
  379. var usesPlurals = $.isArray(args[0]);
  380. if (usesPlurals)
  381. {
  382. // use the first plural form as messageId, otherwise the singular
  383. messageId = (args[0].length > 1 ? args[0][1] : args[0][0]);
  384. }
  385. else
  386. {
  387. messageId = args[0];
  388. }
  389. if (messageId.length === 0)
  390. {
  391. return messageId;
  392. }
  393. if (!this.translations.hasOwnProperty(messageId))
  394. {
  395. if (this.language !== 'en')
  396. {
  397. console.debug(
  398. 'Missing ' + this.language + ' translation for: ' + messageId
  399. );
  400. }
  401. this.translations[messageId] = args[0];
  402. }
  403. if (usesPlurals && $.isArray(this.translations[messageId]))
  404. {
  405. var n = parseInt(args[1] || 1, 10),
  406. key = this.getPluralForm(n),
  407. maxKey = this.translations[messageId].length - 1;
  408. if (key > maxKey)
  409. {
  410. key = maxKey;
  411. }
  412. args[0] = this.translations[messageId][key];
  413. args[1] = n;
  414. }
  415. else
  416. {
  417. args[0] = this.translations[messageId];
  418. }
  419. return helper.sprintf(args);
  420. },
  421. /**
  422. * per language functions to use to determine the plural form
  423. *
  424. * @see {@link http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html}
  425. * @name i18n.getPluralForm
  426. * @function
  427. * @param {number} n
  428. * @return {number} array key
  429. */
  430. getPluralForm: function(n) {
  431. switch (this.language)
  432. {
  433. case 'fr':
  434. case 'oc':
  435. case 'zh':
  436. return (n > 1 ? 1 : 0);
  437. case 'pl':
  438. return (n === 1 ? 0 : (n % 10 >= 2 && n %10 <=4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2));
  439. case 'ru':
  440. return (n % 10 === 1 && n % 100 !== 11 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2));
  441. case 'sl':
  442. return (n % 100 === 1 ? 1 : (n % 100 === 2 ? 2 : (n % 100 === 3 || n % 100 === 4 ? 3 : 0)));
  443. // de, en, es, it, no
  444. default:
  445. return (n !== 1 ? 1 : 0);
  446. }
  447. },
  448. /**
  449. * load translations into cache, then trigger controller initialization
  450. *
  451. * @name i18n.loadTranslations
  452. * @function
  453. */
  454. loadTranslations: function()
  455. {
  456. var language = helper.getCookie('lang');
  457. if (language.length === 0)
  458. {
  459. language = (navigator.language || navigator.userLanguage).substring(0, 2);
  460. }
  461. // note that 'en' is built in, so no translation is necessary
  462. if (i18n.supportedLanguages.indexOf(language) === -1)
  463. {
  464. controller.init();
  465. }
  466. else
  467. {
  468. $.getJSON('i18n/' + language + '.json', function(data) {
  469. i18n.language = language;
  470. i18n.translations = data;
  471. controller.init();
  472. });
  473. }
  474. },
  475. /**
  476. * built in language
  477. *
  478. * @name i18n.language
  479. * @prop {string}
  480. */
  481. language: 'en',
  482. /**
  483. * translation cache
  484. *
  485. * @name i18n.translations
  486. * @enum {Object}
  487. */
  488. translations: {}
  489. };
  490. /**
  491. * filter methods
  492. *
  493. * @name filter
  494. * @class
  495. */
  496. var filter = {
  497. /**
  498. * compress a message (deflate compression), returns base64 encoded data
  499. *
  500. * @name filter.compress
  501. * @function
  502. * @param {string} message
  503. * @return {string} base64 data
  504. */
  505. compress: function(message)
  506. {
  507. return Base64.toBase64( RawDeflate.deflate( Base64.utob(message) ) );
  508. },
  509. /**
  510. * decompress a message compressed with filter.compress()
  511. *
  512. * @name filter.decompress
  513. * @function
  514. * @param {string} data - base64 data
  515. * @return {string} message
  516. */
  517. decompress: function(data)
  518. {
  519. return Base64.btou( RawDeflate.inflate( Base64.fromBase64(data) ) );
  520. },
  521. /**
  522. * compress, then encrypt message with given key and password
  523. *
  524. * @name filter.cipher
  525. * @function
  526. * @param {string} key
  527. * @param {string} password
  528. * @param {string} message
  529. * @return {string} data - JSON with encrypted data
  530. */
  531. cipher: function(key, password, message)
  532. {
  533. // Galois Counter Mode, keysize 256 bit, authentication tag 128 bit
  534. var options = {mode: 'gcm', ks: 256, ts: 128};
  535. if ((password || '').trim().length === 0)
  536. {
  537. return sjcl.encrypt(key, this.compress(message), options);
  538. }
  539. return sjcl.encrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), this.compress(message), options);
  540. },
  541. /**
  542. * decrypt message with key, then decompress
  543. *
  544. * @name filter.decipher
  545. * @function
  546. * @param {string} key
  547. * @param {string} password
  548. * @param {string} data - JSON with encrypted data
  549. * @return {string} decrypted message
  550. */
  551. decipher: function(key, password, data)
  552. {
  553. if (data !== undefined)
  554. {
  555. try
  556. {
  557. return this.decompress(sjcl.decrypt(key, data));
  558. }
  559. catch(err)
  560. {
  561. try
  562. {
  563. return this.decompress(sjcl.decrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), data));
  564. }
  565. catch(e)
  566. {}
  567. }
  568. }
  569. return '';
  570. }
  571. };
  572. /**
  573. * PrivateBin logic
  574. *
  575. * @name controller
  576. * @class
  577. */
  578. var controller = {
  579. /**
  580. * headers to send in AJAX requests
  581. *
  582. * @name controller.headers
  583. * @enum {Object}
  584. */
  585. headers: {'X-Requested-With': 'JSONHttpRequest'},
  586. /**
  587. * URL shortners create address
  588. *
  589. * @name controller.shortenerUrl
  590. * @prop {string}
  591. */
  592. shortenerUrl: '',
  593. /**
  594. * URL of newly created paste
  595. *
  596. * @name controller.createdPasteUrl
  597. * @prop {string}
  598. */
  599. createdPasteUrl: '',
  600. /**
  601. * ask the user for the password and set it
  602. *
  603. * @name controller.requestPassword
  604. * @function
  605. */
  606. requestPassword: function()
  607. {
  608. if (this.passwordModal.length === 0) {
  609. var password = prompt(i18n._('Please enter the password for this paste:'), '');
  610. if (password === null)
  611. {
  612. throw 'password prompt canceled';
  613. }
  614. if (password.length === 0)
  615. {
  616. this.requestPassword();
  617. } else {
  618. this.passwordInput.val(password);
  619. this.displayMessages();
  620. }
  621. } else {
  622. this.passwordModal.modal();
  623. }
  624. },
  625. /**
  626. * use given format on paste, defaults to plain text
  627. *
  628. * @name controller.formatPaste
  629. * @function
  630. * @param {string} format
  631. * @param {string} text
  632. */
  633. formatPaste: function(format, text)
  634. {
  635. helper.setElementText(this.clearText, text);
  636. helper.setElementText(this.prettyPrint, text);
  637. switch (format || 'plaintext')
  638. {
  639. case 'markdown':
  640. if (typeof showdown === 'object')
  641. {
  642. var converter = new showdown.Converter({
  643. strikethrough: true,
  644. tables: true,
  645. tablesHeaderId: true
  646. });
  647. this.clearText.html(
  648. converter.makeHtml(text)
  649. );
  650. // add table classes from bootstrap css
  651. this.clearText.find('table').addClass('table-condensed table-bordered');
  652. this.clearText.removeClass('hidden');
  653. }
  654. this.prettyMessage.addClass('hidden');
  655. break;
  656. case 'syntaxhighlighting':
  657. if (typeof prettyPrintOne === 'function')
  658. {
  659. if (typeof prettyPrint === 'function')
  660. {
  661. prettyPrint();
  662. }
  663. this.prettyPrint.html(
  664. prettyPrintOne(
  665. helper.htmlEntities(text), null, true
  666. )
  667. );
  668. }
  669. // fall through, as the rest is the same
  670. default:
  671. // convert URLs to clickable links
  672. helper.urls2links(this.clearText);
  673. helper.urls2links(this.prettyPrint);
  674. this.clearText.addClass('hidden');
  675. if (format === 'plaintext')
  676. {
  677. this.prettyPrint.css('white-space', 'pre-wrap');
  678. this.prettyPrint.css('word-break', 'normal');
  679. this.prettyPrint.removeClass('prettyprint');
  680. }
  681. this.prettyMessage.removeClass('hidden');
  682. }
  683. },
  684. /**
  685. * show decrypted text in the display area, including discussion (if open)
  686. *
  687. * @name controller.displayMessages
  688. * @function
  689. * @param {Object} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  690. */
  691. displayMessages: function(paste)
  692. {
  693. paste = paste || $.parseJSON(this.cipherData.text());
  694. var key = helper.pageKey(),
  695. password = this.passwordInput.val();
  696. if (!this.prettyPrint.hasClass('prettyprinted')) {
  697. // Try to decrypt the paste.
  698. try
  699. {
  700. if (paste.attachment)
  701. {
  702. var attachment = filter.decipher(key, password, paste.attachment);
  703. if (attachment.length === 0)
  704. {
  705. if (password.length === 0)
  706. {
  707. this.requestPassword();
  708. return;
  709. }
  710. attachment = filter.decipher(key, password, paste.attachment);
  711. }
  712. if (attachment.length === 0)
  713. {
  714. throw 'failed to decipher attachment';
  715. }
  716. if (paste.attachmentname)
  717. {
  718. var attachmentname = filter.decipher(key, password, paste.attachmentname);
  719. if (attachmentname.length > 0)
  720. {
  721. this.attachmentLink.attr('download', attachmentname);
  722. }
  723. }
  724. this.attachmentLink.attr('href', attachment);
  725. this.attachment.removeClass('hidden');
  726. // if the attachment is an image, display it
  727. var imagePrefix = 'data:image/';
  728. if (attachment.substring(0, imagePrefix.length) === imagePrefix)
  729. {
  730. this.image.html(
  731. $(document.createElement('img'))
  732. .attr('src', attachment)
  733. .attr('class', 'img-thumbnail')
  734. );
  735. this.image.removeClass('hidden');
  736. }
  737. }
  738. var cleartext = filter.decipher(key, password, paste.data);
  739. if (cleartext.length === 0 && password.length === 0 && !paste.attachment)
  740. {
  741. this.requestPassword();
  742. return;
  743. }
  744. if (cleartext.length === 0 && !paste.attachment)
  745. {
  746. throw 'failed to decipher message';
  747. }
  748. this.passwordInput.val(password);
  749. if (cleartext.length > 0)
  750. {
  751. $('#pasteFormatter').val(paste.meta.formatter);
  752. this.formatPaste(paste.meta.formatter, cleartext);
  753. }
  754. }
  755. catch(err)
  756. {
  757. this.clearText.addClass('hidden');
  758. this.prettyMessage.addClass('hidden');
  759. this.cloneButton.addClass('hidden');
  760. this.showError(i18n._('Could not decrypt data (Wrong key?)'));
  761. return;
  762. }
  763. }
  764. // display paste expiration / for your eyes only
  765. if (paste.meta.expire_date)
  766. {
  767. var expiration = helper.secondsToHuman(paste.meta.remaining_time),
  768. expirationLabel = [
  769. 'This document will expire in %d ' + expiration[1] + '.',
  770. 'This document will expire in %d ' + expiration[1] + 's.'
  771. ];
  772. helper.setMessage(this.remainingTime, i18n._(expirationLabel, expiration[0]));
  773. this.remainingTime.removeClass('foryoureyesonly')
  774. .removeClass('hidden');
  775. }
  776. if (paste.meta.burnafterreading)
  777. {
  778. // unfortunately many web servers don't support DELETE (and PUT) out of the box
  779. $.ajax({
  780. type: 'POST',
  781. url: helper.scriptLocation() + '?' + helper.pasteId(),
  782. data: {deletetoken: 'burnafterreading'},
  783. dataType: 'json',
  784. headers: this.headers
  785. })
  786. .fail(function() {
  787. controller.showError(i18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  788. });
  789. helper.setMessage(this.remainingTime, i18n._(
  790. 'FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.'
  791. ));
  792. this.remainingTime.addClass('foryoureyesonly')
  793. .removeClass('hidden');
  794. // discourage cloning (as it can't really be prevented)
  795. this.cloneButton.addClass('hidden');
  796. }
  797. // if the discussion is opened on this paste, display it
  798. if (paste.meta.opendiscussion)
  799. {
  800. this.comments.html('');
  801. // iterate over comments
  802. for (var i = 0; i < paste.comments.length; ++i)
  803. {
  804. var place = this.comments,
  805. comment = paste.comments[i],
  806. commenttext = filter.decipher(key, password, comment.data),
  807. // if parent comment exists, display below (CSS will automatically shift it to the right)
  808. cname = '#comment_' + comment.parentid,
  809. divComment = $('<article><div class="comment" id="comment_' + comment.id
  810. + '"><div class="commentmeta"><span class="nickname"></span>'
  811. + '<span class="commentdate"></span></div>'
  812. + '<div class="commentdata"></div>'
  813. + '<button class="btn btn-default btn-sm">'
  814. + i18n._('Reply') + '</button></div></article>'),
  815. divCommentData = divComment.find('div.commentdata');
  816. // if the element exists in page
  817. if ($(cname).length)
  818. {
  819. place = $(cname);
  820. }
  821. divComment.find('button').click({commentid: comment.id}, $.proxy(this.openReply, this));
  822. helper.setElementText(divCommentData, commenttext);
  823. helper.urls2links(divCommentData);
  824. // try to get optional nickname
  825. var nick = filter.decipher(key, password, comment.meta.nickname);
  826. if (nick.length > 0)
  827. {
  828. divComment.find('span.nickname').text(nick);
  829. }
  830. else
  831. {
  832. divComment.find('span.nickname').html('<i>' + i18n._('Anonymous') + '</i>');
  833. }
  834. divComment.find('span.commentdate')
  835. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  836. .attr('title', 'CommentID: ' + comment.id);
  837. // if an avatar is available, display it
  838. if (comment.meta.vizhash)
  839. {
  840. divComment.find('span.nickname')
  841. .before(
  842. '<img src="' + comment.meta.vizhash + '" class="vizhash" title="' +
  843. i18n._('Anonymous avatar (Vizhash of the IP address)') + '" /> '
  844. );
  845. }
  846. place.append(divComment);
  847. }
  848. var divComment = $(
  849. '<div class="comment"><button class="btn btn-default btn-sm">' +
  850. i18n._('Add comment') + '</button></div>'
  851. );
  852. divComment.find('button').click({commentid: helper.pasteId()}, $.proxy(this.openReply, this));
  853. this.comments.append(divComment);
  854. this.discussion.removeClass('hidden');
  855. }
  856. },
  857. /**
  858. * open the comment entry when clicking the "Reply" button of a comment
  859. *
  860. * @name controller.openReply
  861. * @function
  862. * @param {Event} event
  863. */
  864. openReply: function(event)
  865. {
  866. event.preventDefault();
  867. // remove any other reply area
  868. $('div.reply').remove();
  869. var source = $(event.target),
  870. commentid = event.data.commentid,
  871. hint = i18n._('Optional nickname...'),
  872. reply = $(
  873. '<div class="reply"><input type="text" id="nickname" ' +
  874. 'class="form-control" title="' + hint + '" placeholder="' +
  875. hint + '" /><textarea id="replymessage" class="replymessage ' +
  876. 'form-control" cols="80" rows="7"></textarea><br />' +
  877. '<div id="replystatus"></div><button id="replybutton" ' +
  878. 'class="btn btn-default btn-sm">' + i18n._('Post comment') +
  879. '</button></div>'
  880. );
  881. reply.find('button').click(
  882. {parentid: commentid},
  883. $.proxy(this.sendComment, this)
  884. );
  885. source.after(reply);
  886. this.replyStatus = $('#replystatus');
  887. $('#replymessage').focus();
  888. },
  889. /**
  890. * send a reply in a discussion
  891. *
  892. * @name controller.sendComment
  893. * @function
  894. * @param {Event} event
  895. */
  896. sendComment: function(event)
  897. {
  898. event.preventDefault();
  899. this.errorMessage.addClass('hidden');
  900. // do not send if no data
  901. var replyMessage = $('#replymessage');
  902. if (replyMessage.val().length === 0)
  903. {
  904. return;
  905. }
  906. this.showStatus(i18n._('Sending comment...'), true);
  907. var parentid = event.data.parentid,
  908. key = helper.pageKey(),
  909. cipherdata = filter.cipher(key, this.passwordInput.val(), replyMessage.val()),
  910. ciphernickname = '',
  911. nick = $('#nickname').val();
  912. if (nick.length > 0)
  913. {
  914. ciphernickname = filter.cipher(key, this.passwordInput.val(), nick);
  915. }
  916. var data_to_send = {
  917. data: cipherdata,
  918. parentid: parentid,
  919. pasteid: helper.pasteId(),
  920. nickname: ciphernickname
  921. };
  922. $.ajax({
  923. type: 'POST',
  924. url: helper.scriptLocation(),
  925. data: data_to_send,
  926. dataType: 'json',
  927. headers: this.headers,
  928. success: function(data)
  929. {
  930. if (data.status === 0)
  931. {
  932. controller.showStatus(i18n._('Comment posted.'));
  933. $.ajax({
  934. type: 'GET',
  935. url: helper.scriptLocation() + '?' + helper.pasteId(),
  936. dataType: 'json',
  937. headers: controller.headers,
  938. success: function(data)
  939. {
  940. if (data.status === 0)
  941. {
  942. controller.displayMessages(data);
  943. }
  944. else if (data.status === 1)
  945. {
  946. controller.showError(i18n._('Could not refresh display: %s', data.message));
  947. }
  948. else
  949. {
  950. controller.showError(i18n._('Could not refresh display: %s', i18n._('unknown status')));
  951. }
  952. }
  953. })
  954. .fail(function() {
  955. controller.showError(i18n._('Could not refresh display: %s', i18n._('server error or not responding')));
  956. });
  957. }
  958. else if (data.status === 1)
  959. {
  960. controller.showError(i18n._('Could not post comment: %s', data.message));
  961. }
  962. else
  963. {
  964. controller.showError(i18n._('Could not post comment: %s', i18n._('unknown status')));
  965. }
  966. }
  967. })
  968. .fail(function() {
  969. controller.showError(i18n._('Could not post comment: %s', i18n._('server error or not responding')));
  970. });
  971. },
  972. /**
  973. * send a new paste to server
  974. *
  975. * @name controller.sendData
  976. * @function
  977. * @param {Event} event
  978. */
  979. sendData: function(event)
  980. {
  981. event.preventDefault();
  982. var file = document.getElementById('file'),
  983. files = (file && file.files) ? file.files : null; // FileList object
  984. // do not send if no data.
  985. if (this.message.val().length === 0 && !(files && files[0]))
  986. {
  987. return;
  988. }
  989. // if sjcl has not collected enough entropy yet, display a message
  990. if (!sjcl.random.isReady())
  991. {
  992. this.showStatus(i18n._('Sending paste (Please move your mouse for more entropy)...'), true);
  993. sjcl.random.addEventListener('seeded', function() {
  994. this.sendData(event);
  995. });
  996. return;
  997. }
  998. $('.navbar-toggle').click();
  999. this.password.addClass('hidden');
  1000. this.showStatus(i18n._('Sending paste...'), true);
  1001. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0),
  1002. password = this.passwordInput.val();
  1003. if(files && files[0])
  1004. {
  1005. if(typeof FileReader === undefined)
  1006. {
  1007. this.showError(i18n._('Your browser does not support uploading encrypted files. Please use a newer browser.'));
  1008. return;
  1009. }
  1010. var reader = new FileReader();
  1011. // closure to capture the file information
  1012. reader.onload = (function(theFile)
  1013. {
  1014. return function(e) {
  1015. controller.sendDataContinue(
  1016. randomkey,
  1017. filter.cipher(randomkey, password, e.target.result),
  1018. filter.cipher(randomkey, password, theFile.name)
  1019. );
  1020. };
  1021. })(files[0]);
  1022. reader.readAsDataURL(files[0]);
  1023. }
  1024. else if(this.attachmentLink.attr('href'))
  1025. {
  1026. this.sendDataContinue(
  1027. randomkey,
  1028. filter.cipher(randomkey, password, this.attachmentLink.attr('href')),
  1029. this.attachmentLink.attr('download')
  1030. );
  1031. }
  1032. else
  1033. {
  1034. this.sendDataContinue(randomkey, '', '');
  1035. }
  1036. },
  1037. /**
  1038. * send a new paste to server, step 2
  1039. *
  1040. * @name controller.sendDataContinue
  1041. * @function
  1042. * @param {string} randomkey
  1043. * @param {string} cipherdata_attachment
  1044. * @param {string} cipherdata_attachment_name
  1045. */
  1046. sendDataContinue: function(randomkey, cipherdata_attachment, cipherdata_attachment_name)
  1047. {
  1048. var cipherdata = filter.cipher(randomkey, this.passwordInput.val(), this.message.val()),
  1049. data_to_send = {
  1050. data: cipherdata,
  1051. expire: $('#pasteExpiration').val(),
  1052. formatter: $('#pasteFormatter').val(),
  1053. burnafterreading: this.burnAfterReading.is(':checked') ? 1 : 0,
  1054. opendiscussion: this.openDiscussion.is(':checked') ? 1 : 0
  1055. };
  1056. if (cipherdata_attachment.length > 0)
  1057. {
  1058. data_to_send.attachment = cipherdata_attachment;
  1059. if (cipherdata_attachment_name.length > 0)
  1060. {
  1061. data_to_send.attachmentname = cipherdata_attachment_name;
  1062. }
  1063. }
  1064. $.ajax({
  1065. type: 'POST',
  1066. url: helper.scriptLocation(),
  1067. data: data_to_send,
  1068. dataType: 'json',
  1069. headers: this.headers,
  1070. success: function(data)
  1071. {
  1072. if (data.status === 0) {
  1073. controller.stateExistingPaste();
  1074. var url = helper.scriptLocation() + '?' + data.id + '#' + randomkey,
  1075. deleteUrl = helper.scriptLocation() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  1076. controller.showStatus('');
  1077. controller.errorMessage.addClass('hidden');
  1078. history.pushState({type: 'newpaste'}, '', url);
  1079. $('#pastelink').html(
  1080. i18n._(
  1081. 'Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>',
  1082. url, url
  1083. ) + controller.shortenUrl(url)
  1084. );
  1085. var shortenButton = $('#shortenbutton');
  1086. if (shortenButton) {
  1087. shortenButton.click($.proxy(controller.sendToShortener, controller));
  1088. }
  1089. $('#deletelink').html('<a href="' + deleteUrl + '">' + i18n._('Delete data') + '</a>');
  1090. controller.pasteResult.removeClass('hidden');
  1091. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1092. helper.selectText('pasteurl');
  1093. controller.showStatus('');
  1094. controller.formatPaste(data_to_send.formatter, controller.message.val());
  1095. }
  1096. else if (data.status === 1)
  1097. {
  1098. controller.showError(i18n._('Could not create paste: %s', data.message));
  1099. }
  1100. else
  1101. {
  1102. controller.showError(i18n._('Could not create paste: %s', i18n._('unknown status')));
  1103. }
  1104. }
  1105. })
  1106. .fail(function()
  1107. {
  1108. controller.showError(i18n._('Could not create paste: %s', i18n._('server error or not responding')));
  1109. });
  1110. },
  1111. /**
  1112. * check if a URL shortener was defined and create HTML containing a link to it
  1113. *
  1114. * @name controller.shortenUrl
  1115. * @function
  1116. * @param {string} url
  1117. * @return {string} html
  1118. */
  1119. shortenUrl: function(url)
  1120. {
  1121. var shortenerHtml = $('#shortenbutton');
  1122. if (shortenerHtml) {
  1123. this.shortenerUrl = shortenerHtml.data('shortener');
  1124. this.createdPasteUrl = url;
  1125. return ' ' + $('<div />').append(shortenerHtml.clone()).html();
  1126. }
  1127. return '';
  1128. },
  1129. /**
  1130. * put the screen in "New paste" mode
  1131. *
  1132. * @name controller.stateNewPaste
  1133. * @function
  1134. */
  1135. stateNewPaste: function()
  1136. {
  1137. this.message.text('');
  1138. this.attachment.addClass('hidden');
  1139. this.cloneButton.addClass('hidden');
  1140. this.rawTextButton.addClass('hidden');
  1141. this.remainingTime.addClass('hidden');
  1142. this.pasteResult.addClass('hidden');
  1143. this.clearText.addClass('hidden');
  1144. this.discussion.addClass('hidden');
  1145. this.prettyMessage.addClass('hidden');
  1146. this.sendButton.removeClass('hidden');
  1147. this.expiration.removeClass('hidden');
  1148. this.formatter.removeClass('hidden');
  1149. this.burnAfterReadingOption.removeClass('hidden');
  1150. this.openDisc.removeClass('hidden');
  1151. this.newButton.removeClass('hidden');
  1152. this.password.removeClass('hidden');
  1153. this.attach.removeClass('hidden');
  1154. this.message.removeClass('hidden');
  1155. this.preview.removeClass('hidden');
  1156. this.message.focus();
  1157. },
  1158. /**
  1159. * put the screen in "Existing paste" mode
  1160. *
  1161. * @name controller.stateExistingPaste
  1162. * @function
  1163. * @param {boolean} [preview=false] - (optional) tell if the preview tabs should be displayed, defaults to false
  1164. */
  1165. stateExistingPaste: function(preview)
  1166. {
  1167. preview = preview || false;
  1168. if (!preview)
  1169. {
  1170. // no "clone" for IE<10.
  1171. if ($('#oldienotice').is(":visible"))
  1172. {
  1173. this.cloneButton.addClass('hidden');
  1174. }
  1175. else
  1176. {
  1177. this.cloneButton.removeClass('hidden');
  1178. }
  1179. this.rawTextButton.removeClass('hidden');
  1180. this.sendButton.addClass('hidden');
  1181. this.attach.addClass('hidden');
  1182. this.expiration.addClass('hidden');
  1183. this.formatter.addClass('hidden');
  1184. this.burnAfterReadingOption.addClass('hidden');
  1185. this.openDisc.addClass('hidden');
  1186. this.newButton.removeClass('hidden');
  1187. this.preview.addClass('hidden');
  1188. }
  1189. this.pasteResult.addClass('hidden');
  1190. this.message.addClass('hidden');
  1191. this.clearText.addClass('hidden');
  1192. this.prettyMessage.addClass('hidden');
  1193. },
  1194. /**
  1195. * when "burn after reading" is checked, disable discussion
  1196. *
  1197. * @name controller.changeBurnAfterReading
  1198. * @function
  1199. */
  1200. changeBurnAfterReading: function()
  1201. {
  1202. if (this.burnAfterReading.is(':checked') )
  1203. {
  1204. this.openDisc.addClass('buttondisabled');
  1205. this.openDiscussion.attr({checked: false, disabled: true});
  1206. }
  1207. else
  1208. {
  1209. this.openDisc.removeClass('buttondisabled');
  1210. this.openDiscussion.removeAttr('disabled');
  1211. }
  1212. },
  1213. /**
  1214. * when discussion is checked, disable "burn after reading"
  1215. *
  1216. * @name controller.changeOpenDisc
  1217. * @function
  1218. */
  1219. changeOpenDisc: function()
  1220. {
  1221. if (this.openDiscussion.is(':checked') )
  1222. {
  1223. this.burnAfterReadingOption.addClass('buttondisabled');
  1224. this.burnAfterReading.attr({checked: false, disabled: true});
  1225. }
  1226. else
  1227. {
  1228. this.burnAfterReadingOption.removeClass('buttondisabled');
  1229. this.burnAfterReading.removeAttr('disabled');
  1230. }
  1231. },
  1232. /**
  1233. * forward to URL shortener
  1234. *
  1235. * @name controller.sendToShortener
  1236. * @function
  1237. * @param {Event} event
  1238. */
  1239. sendToShortener: function(event)
  1240. {
  1241. event.preventDefault();
  1242. window.location.href = this.shortenerUrl + encodeURIComponent(this.createdPasteUrl);
  1243. },
  1244. /**
  1245. * reload the page
  1246. *
  1247. * @name controller.reloadPage
  1248. * @function
  1249. * @param {Event} event
  1250. */
  1251. reloadPage: function(event)
  1252. {
  1253. event.preventDefault();
  1254. window.location.href = helper.scriptLocation();
  1255. },
  1256. /**
  1257. * return raw text
  1258. *
  1259. * @name controller.rawText
  1260. * @function
  1261. * @param {Event} event
  1262. */
  1263. rawText: function(event)
  1264. {
  1265. event.preventDefault();
  1266. var paste = $('#pasteFormatter').val() === 'markdown' ?
  1267. this.prettyPrint.text() : this.clearText.text();
  1268. history.pushState(
  1269. null, document.title, helper.scriptLocation() + '?' +
  1270. helper.pasteId() + '#' + helper.pageKey()
  1271. );
  1272. // we use text/html instead of text/plain to avoid a bug when
  1273. // reloading the raw text view (it reverts to type text/html)
  1274. var newDoc = document.open('text/html', 'replace');
  1275. newDoc.write('<pre>' + helper.htmlEntities(paste) + '</pre>');
  1276. newDoc.close();
  1277. },
  1278. /**
  1279. * clone the current paste
  1280. *
  1281. * @name controller.clonePaste
  1282. * @function
  1283. * @param {Event} event
  1284. */
  1285. clonePaste: function(event)
  1286. {
  1287. event.preventDefault();
  1288. this.stateNewPaste();
  1289. // erase the id and the key in url
  1290. history.replaceState(null, document.title, helper.scriptLocation());
  1291. this.showStatus('');
  1292. if (this.attachmentLink.attr('href'))
  1293. {
  1294. this.clonedFile.removeClass('hidden');
  1295. this.fileWrap.addClass('hidden');
  1296. }
  1297. this.message.text(
  1298. $('#pasteFormatter').val() === 'markdown' ?
  1299. this.prettyPrint.text() : this.clearText.text()
  1300. );
  1301. $('.navbar-toggle').click();
  1302. },
  1303. /**
  1304. * set the expiration on bootstrap templates
  1305. *
  1306. * @name controller.setExpiration
  1307. * @function
  1308. * @param {Event} event
  1309. */
  1310. setExpiration: function(event)
  1311. {
  1312. event.preventDefault();
  1313. var target = $(event.target);
  1314. $('#pasteExpiration').val(target.data('expiration'));
  1315. $('#pasteExpirationDisplay').text(target.text());
  1316. },
  1317. /**
  1318. * set the format on bootstrap templates
  1319. *
  1320. * @name controller.setFormat
  1321. * @function
  1322. * @param {Event} event
  1323. */
  1324. setFormat: function(event)
  1325. {
  1326. event.preventDefault();
  1327. var target = $(event.target);
  1328. $('#pasteFormatter').val(target.data('format'));
  1329. $('#pasteFormatterDisplay').text(target.text());
  1330. if (this.messagePreview.parent().hasClass('active')) {
  1331. this.viewPreview(event);
  1332. }
  1333. },
  1334. /**
  1335. * set the language in a cookie and reload the page
  1336. *
  1337. * @name controller.setLanguage
  1338. * @function
  1339. * @param {Event} event
  1340. */
  1341. setLanguage: function(event)
  1342. {
  1343. document.cookie = 'lang=' + $(event.target).data('lang');
  1344. this.reloadPage(event);
  1345. },
  1346. /**
  1347. * support input of tab character
  1348. *
  1349. * @name controller.supportTabs
  1350. * @function
  1351. * @param {Event} event
  1352. */
  1353. supportTabs: function(event)
  1354. {
  1355. var keyCode = event.keyCode || event.which;
  1356. // tab was pressed
  1357. if (keyCode === 9)
  1358. {
  1359. // prevent the textarea to lose focus
  1360. event.preventDefault();
  1361. // get caret position & selection
  1362. var val = this.value,
  1363. start = this.selectionStart,
  1364. end = this.selectionEnd;
  1365. // set textarea value to: text before caret + tab + text after caret
  1366. this.value = val.substring(0, start) + '\t' + val.substring(end);
  1367. // put caret at right position again
  1368. this.selectionStart = this.selectionEnd = start + 1;
  1369. }
  1370. },
  1371. /**
  1372. * view the editor tab
  1373. *
  1374. * @name controller.viewEditor
  1375. * @function
  1376. * @param {Event} event
  1377. */
  1378. viewEditor: function(event)
  1379. {
  1380. event.preventDefault();
  1381. this.messagePreview.parent().removeClass('active');
  1382. this.messageEdit.parent().addClass('active');
  1383. this.message.focus();
  1384. this.stateNewPaste();
  1385. },
  1386. /**
  1387. * view the preview tab
  1388. *
  1389. * @name controller.viewPreview
  1390. * @function
  1391. * @param {Event} event
  1392. */
  1393. viewPreview: function(event)
  1394. {
  1395. event.preventDefault();
  1396. this.messageEdit.parent().removeClass('active');
  1397. this.messagePreview.parent().addClass('active');
  1398. this.message.focus();
  1399. this.stateExistingPaste(true);
  1400. this.formatPaste($('#pasteFormatter').val(), this.message.val());
  1401. },
  1402. /**
  1403. * handle history (pop) state changes
  1404. *
  1405. * currently this does only handle redirects to the home page.
  1406. *
  1407. * @name controller.historyChange
  1408. * @function
  1409. * @param {Event} event
  1410. */
  1411. historyChange: function(event)
  1412. {
  1413. var currentLocation = helper.scriptLocation();
  1414. if (event.originalEvent.state === null && // no state object passed
  1415. event.originalEvent.target.location.href === currentLocation && // target location is home page
  1416. window.location.href === currentLocation // and we are not already on the home page
  1417. ) {
  1418. // redirect to home page
  1419. window.location.href = currentLocation;
  1420. }
  1421. },
  1422. /**
  1423. * create a new paste
  1424. *
  1425. * @name controller.newPaste
  1426. * @function
  1427. */
  1428. newPaste: function()
  1429. {
  1430. this.stateNewPaste();
  1431. this.showStatus('');
  1432. this.message.text('');
  1433. this.changeBurnAfterReading();
  1434. this.changeOpenDisc();
  1435. },
  1436. /**
  1437. * removes an attachment
  1438. *
  1439. * @name controller.removeAttachment
  1440. * @function
  1441. */
  1442. removeAttachment: function()
  1443. {
  1444. this.clonedFile.addClass('hidden');
  1445. // removes the saved decrypted file data
  1446. this.attachmentLink.attr('href', '');
  1447. // the only way to deselect the file is to recreate the input
  1448. this.fileWrap.html(this.fileWrap.html());
  1449. this.fileWrap.removeClass('hidden');
  1450. },
  1451. /**
  1452. * decrypt using the password from the modal dialog
  1453. *
  1454. * @name controller.decryptPasswordModal
  1455. * @function
  1456. */
  1457. decryptPasswordModal: function()
  1458. {
  1459. this.passwordInput.val(this.passwordDecrypt.val());
  1460. this.displayMessages();
  1461. },
  1462. /**
  1463. * submit a password in the modal dialog
  1464. *
  1465. * @name controller.submitPasswordModal
  1466. * @function
  1467. * @param {Event} event
  1468. */
  1469. submitPasswordModal: function(event)
  1470. {
  1471. event.preventDefault();
  1472. this.passwordModal.modal('hide');
  1473. },
  1474. /**
  1475. * display an error message,
  1476. * we use the same function for paste and reply to comments
  1477. *
  1478. * @name controller.showError
  1479. * @function
  1480. * @param {string} message - text to display
  1481. */
  1482. showError: function(message)
  1483. {
  1484. if (this.status.length)
  1485. {
  1486. this.status.addClass('errorMessage').text(message);
  1487. }
  1488. else
  1489. {
  1490. this.errorMessage.removeClass('hidden');
  1491. helper.setMessage(this.errorMessage, message);
  1492. }
  1493. if (typeof this.replyStatus !== 'undefined') {
  1494. this.replyStatus.addClass('errorMessage');
  1495. this.replyStatus.addClass(this.errorMessage.attr('class'));
  1496. if (this.status.length)
  1497. {
  1498. this.replyStatus.html(this.status.html());
  1499. }
  1500. else
  1501. {
  1502. this.replyStatus.html(this.errorMessage.html());
  1503. }
  1504. }
  1505. },
  1506. /**
  1507. * display a status message,
  1508. * we use the same function for paste and reply to comments
  1509. *
  1510. * @name controller.showStatus
  1511. * @function
  1512. * @param {string} message - text to display
  1513. * @param {boolean} [spin=false] - (optional) tell if the "spinning" animation should be displayed, defaults to false
  1514. */
  1515. showStatus: function(message, spin)
  1516. {
  1517. if (spin || false)
  1518. {
  1519. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0 4px 0 0;" />';
  1520. this.status.prepend(img);
  1521. if (typeof this.replyStatus !== 'undefined') {
  1522. this.replyStatus.prepend(img);
  1523. }
  1524. }
  1525. if (typeof this.replyStatus !== 'undefined') {
  1526. this.replyStatus.removeClass('errorMessage').text(message);
  1527. }
  1528. if (!message)
  1529. {
  1530. this.status.html(' ');
  1531. return;
  1532. }
  1533. if (message === '')
  1534. {
  1535. this.status.html(' ');
  1536. return;
  1537. }
  1538. this.status.removeClass('errorMessage').text(message);
  1539. },
  1540. /**
  1541. * bind events to DOM elements
  1542. *
  1543. * @name controller.bindEvents
  1544. * @function
  1545. */
  1546. bindEvents: function()
  1547. {
  1548. this.burnAfterReading.change($.proxy(this.changeBurnAfterReading, this));
  1549. this.openDisc.change($.proxy(this.changeOpenDisc, this));
  1550. this.sendButton.click($.proxy(this.sendData, this));
  1551. this.cloneButton.click($.proxy(this.clonePaste, this));
  1552. this.rawTextButton.click($.proxy(this.rawText, this));
  1553. this.fileRemoveButton.click($.proxy(this.removeAttachment, this));
  1554. $('.reloadlink').click($.proxy(this.reloadPage, this));
  1555. this.message.keydown(this.supportTabs);
  1556. this.messageEdit.click($.proxy(this.viewEditor, this));
  1557. this.messagePreview.click($.proxy(this.viewPreview, this));
  1558. // bootstrap template drop downs
  1559. $('ul.dropdown-menu li a', $('#expiration').parent()).click($.proxy(this.setExpiration, this));
  1560. $('ul.dropdown-menu li a', $('#formatter').parent()).click($.proxy(this.setFormat, this));
  1561. $('#language ul.dropdown-menu li a').click($.proxy(this.setLanguage, this));
  1562. // page template drop down
  1563. $('#language select option').click($.proxy(this.setLanguage, this));
  1564. // handle modal password request on decryption
  1565. this.passwordModal.on('shown.bs.modal', $.proxy(this.passwordDecrypt.focus, this));
  1566. this.passwordModal.on('hidden.bs.modal', $.proxy(this.decryptPasswordModal, this));
  1567. this.passwordForm.submit($.proxy(this.submitPasswordModal, this));
  1568. $(window).on('popstate', $.proxy(this.historyChange, this));
  1569. },
  1570. /**
  1571. * main application
  1572. *
  1573. * @name controller.init
  1574. * @function
  1575. */
  1576. init: function()
  1577. {
  1578. // hide "no javascript" message
  1579. $('#noscript').hide();
  1580. // preload jQuery wrapped DOM elements and bind events
  1581. this.attach = $('#attach');
  1582. this.attachment = $('#attachment');
  1583. this.attachmentLink = $('#attachment a');
  1584. this.burnAfterReading = $('#burnafterreading');
  1585. this.burnAfterReadingOption = $('#burnafterreadingoption');
  1586. this.cipherData = $('#cipherdata');
  1587. this.clearText = $('#cleartext');
  1588. this.cloneButton = $('#clonebutton');
  1589. this.clonedFile = $('#clonedfile');
  1590. this.comments = $('#comments');
  1591. this.discussion = $('#discussion');
  1592. this.errorMessage = $('#errormessage');
  1593. this.expiration = $('#expiration');
  1594. this.fileRemoveButton = $('#fileremovebutton');
  1595. this.fileWrap = $('#filewrap');
  1596. this.formatter = $('#formatter');
  1597. this.image = $('#image');
  1598. this.message = $('#message');
  1599. this.messageEdit = $('#messageedit');
  1600. this.messagePreview = $('#messagepreview');
  1601. this.newButton = $('#newbutton');
  1602. this.openDisc = $('#opendisc');
  1603. this.openDiscussion = $('#opendiscussion');
  1604. this.password = $('#password');
  1605. this.passwordInput = $('#passwordinput');
  1606. this.passwordModal = $('#passwordmodal');
  1607. this.passwordForm = $('#passwordform');
  1608. this.passwordDecrypt = $('#passworddecrypt');
  1609. this.pasteResult = $('#pasteresult');
  1610. this.prettyMessage = $('#prettymessage');
  1611. this.prettyPrint = $('#prettyprint');
  1612. this.preview = $('#preview');
  1613. this.rawTextButton = $('#rawtextbutton');
  1614. this.remainingTime = $('#remainingtime');
  1615. this.sendButton = $('#sendbutton');
  1616. this.status = $('#status');
  1617. this.bindEvents();
  1618. // display status returned by php code, if any (eg. paste was properly deleted)
  1619. if (this.status.text().length > 0)
  1620. {
  1621. this.showStatus(this.status.text());
  1622. return;
  1623. }
  1624. // keep line height even if content empty
  1625. this.status.html(' ');
  1626. // display an existing paste
  1627. if (this.cipherData.text().length > 1)
  1628. {
  1629. // missing decryption key in URL?
  1630. if (window.location.hash.length === 0)
  1631. {
  1632. this.showError(i18n._('Cannot decrypt paste: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL?)'));
  1633. return;
  1634. }
  1635. // show proper elements on screen
  1636. this.stateExistingPaste();
  1637. this.displayMessages();
  1638. }
  1639. // display error message from php code
  1640. else if (this.errorMessage.text().length > 1)
  1641. {
  1642. this.showError(this.errorMessage.text());
  1643. }
  1644. // create a new paste
  1645. else
  1646. {
  1647. this.newPaste();
  1648. }
  1649. }
  1650. }
  1651. /**
  1652. * main application start, called when DOM is fully loaded and
  1653. * runs controller initalization after translations are loaded
  1654. */
  1655. $(i18n.loadTranslations);
  1656. return {
  1657. helper: helper,
  1658. i18n: i18n,
  1659. filter: filter,
  1660. controller: controller
  1661. };
  1662. }(jQuery, sjcl, Base64, RawDeflate);