privatebin.js 60 KB

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