privatebin.js 61 KB

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