privatebin.js 62 KB

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