zerobin.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. /**
  2. * ZeroBin
  3. *
  4. * a zero-knowledge paste bin
  5. *
  6. * @link http://sebsauvage.net/wiki/doku.php?id=php:zerobin
  7. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  8. * @license http://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  9. * @version 0.21.1
  10. */
  11. 'use strict';
  12. // Immediately start random number generator collector.
  13. sjcl.random.startCollectors();
  14. $(function() {
  15. /**
  16. * static helper methods
  17. */
  18. var helper = {
  19. /**
  20. * Converts a duration (in seconds) into human friendly approximation.
  21. *
  22. * @param int seconds
  23. * @return array
  24. */
  25. secondsToHuman: function(seconds)
  26. {
  27. if (seconds < 60)
  28. {
  29. var v = Math.floor(seconds);
  30. return [v, 'second'];
  31. }
  32. if (seconds < 60 * 60)
  33. {
  34. var v = Math.floor(seconds / 60);
  35. return [v, 'minute'];
  36. }
  37. if (seconds < 60 * 60 * 24)
  38. {
  39. var v = Math.floor(seconds / (60 * 60));
  40. return [v, 'hour'];
  41. }
  42. // If less than 2 months, display in days:
  43. if (seconds < 60 * 60 * 24 * 60)
  44. {
  45. var v = Math.floor(seconds / (60 * 60 * 24));
  46. return [v, 'day'];
  47. }
  48. var v = Math.floor(seconds / (60 * 60 * 24 * 30));
  49. return [v, 'month'];
  50. },
  51. /**
  52. * Converts an associative array to an encoded string
  53. * for appending to the anchor.
  54. *
  55. * @param object associative_array Object to be serialized
  56. * @return string
  57. */
  58. hashToParameterString: function(associativeArray)
  59. {
  60. var parameterString = '';
  61. for (key in associativeArray)
  62. {
  63. if(parameterString === '')
  64. {
  65. parameterString = encodeURIComponent(key);
  66. parameterString += '=' + encodeURIComponent(associativeArray[key]);
  67. }
  68. else
  69. {
  70. parameterString += '&' + encodeURIComponent(key);
  71. parameterString += '=' + encodeURIComponent(associativeArray[key]);
  72. }
  73. }
  74. // padding for URL shorteners
  75. parameterString += '&p=p';
  76. return parameterString;
  77. },
  78. /**
  79. * Converts a string to an associative array.
  80. *
  81. * @param string parameter_string String containing parameters
  82. * @return object
  83. */
  84. parameterStringToHash: function(parameterString)
  85. {
  86. var parameterHash = {};
  87. var parameterArray = parameterString.split('&');
  88. for (var i = 0; i < parameterArray.length; i++)
  89. {
  90. var pair = parameterArray[i].split('=');
  91. var key = decodeURIComponent(pair[0]);
  92. var value = decodeURIComponent(pair[1]);
  93. parameterHash[key] = value;
  94. }
  95. return parameterHash;
  96. },
  97. /**
  98. * Get an associative array of the parameters found in the anchor
  99. *
  100. * @return object
  101. */
  102. getParameterHash: function()
  103. {
  104. var hashIndex = window.location.href.indexOf('#');
  105. if (hashIndex >= 0)
  106. {
  107. return this.parameterStringToHash(window.location.href.substring(hashIndex + 1));
  108. }
  109. else
  110. {
  111. return {};
  112. }
  113. },
  114. /**
  115. * Convert all applicable characters to HTML entities
  116. *
  117. * @param string str
  118. * @return string encoded string
  119. */
  120. htmlEntities: function(str)
  121. {
  122. return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  123. },
  124. /**
  125. * Text range selection.
  126. * From: http://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse
  127. *
  128. * @param string element : Indentifier of the element to select (id="").
  129. */
  130. selectText: function(element)
  131. {
  132. var doc = document,
  133. text = doc.getElementById(element),
  134. range,
  135. selection;
  136. // MS
  137. if (doc.body.createTextRange)
  138. {
  139. range = doc.body.createTextRange();
  140. range.moveToElementText(text);
  141. range.select();
  142. }
  143. // all others
  144. else if (window.getSelection)
  145. {
  146. selection = window.getSelection();
  147. range = doc.createRange();
  148. range.selectNodeContents(text);
  149. selection.removeAllRanges();
  150. selection.addRange(range);
  151. }
  152. },
  153. /**
  154. * Set text of a DOM element (required for IE)
  155. * This is equivalent to element.text(text)
  156. *
  157. * @param object element : a DOM element.
  158. * @param string text : the text to enter.
  159. */
  160. setElementText: function(element, text)
  161. {
  162. // For IE<10: Doesn't support white-space:pre-wrap; so we have to do this...
  163. if ($('#oldienotice').is(':visible')) {
  164. var html = this.htmlEntities(text).replace(/\n/ig,'\r\n<br>');
  165. element.html('<pre>'+html+'</pre>');
  166. }
  167. // for other (sane) browsers:
  168. else
  169. {
  170. element.text(text);
  171. }
  172. },
  173. /**
  174. * replace last child of element with message
  175. *
  176. * @param object element : a jQuery wrapped DOM element.
  177. * @param string message : the message to append.
  178. */
  179. setMessage: function(element, message)
  180. {
  181. var content = element.contents();
  182. if (content.length > 0)
  183. {
  184. content[content.length - 1].nodeValue = ' ' + message;
  185. }
  186. else
  187. {
  188. this.setElementText(element, message);
  189. }
  190. },
  191. /**
  192. * Convert URLs to clickable links.
  193. * URLs to handle:
  194. * <code>
  195. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  196. * http://localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  197. * http://user:password@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  198. * </code>
  199. *
  200. * @param object element : a jQuery DOM element.
  201. */
  202. urls2links: function(element)
  203. {
  204. var markup = '<a href="$1" rel="nofollow">$1</a>';
  205. element.html(
  206. element.html().replace(
  207. /((http|https|ftp):\/\/[\w?=&.\/-;#@~%+-]+(?![\w\s?&.\/;#~%"=-]*>))/ig,
  208. markup
  209. )
  210. );
  211. element.html(
  212. element.html().replace(
  213. /((magnet):[\w?=&.\/-;#@~%+-]+)/ig,
  214. markup
  215. )
  216. );
  217. },
  218. /**
  219. * minimal sprintf emulation for %s and %d formats
  220. * From: http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914
  221. *
  222. * @param string format
  223. * @param mixed args one or multiple parameters injected into format string
  224. * @return string
  225. */
  226. sprintf: function()
  227. {
  228. var args = arguments;
  229. if (typeof arguments[0] == 'object') args = arguments[0];
  230. var string = args[0],
  231. i = 1;
  232. return string.replace(/%((%)|s|d)/g, function (m) {
  233. // m is the matched format, e.g. %s, %d
  234. var val = null;
  235. if (m[2]) {
  236. val = m[2];
  237. } else {
  238. val = args[i];
  239. // A switch statement so that the formatter can be extended.
  240. switch (m)
  241. {
  242. case '%d':
  243. val = parseFloat(val);
  244. if (isNaN(val)) {
  245. val = 0;
  246. }
  247. break;
  248. // Default is %s
  249. }
  250. ++i;
  251. }
  252. return val;
  253. });
  254. },
  255. /**
  256. * get value of cookie, if it was set, empty string otherwise
  257. * From: http://www.w3schools.com/js/js_cookies.asp
  258. *
  259. * @param string cname
  260. * @return string
  261. */
  262. getCookie: function(cname) {
  263. var name = cname + '=';
  264. var ca = document.cookie.split(';');
  265. for(var i = 0; i < ca.length; ++i) {
  266. var c = ca[i];
  267. while (c.charAt(0) == ' ') c = c.substring(1);
  268. if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
  269. }
  270. return '';
  271. }
  272. };
  273. /**
  274. * internationalization methods
  275. */
  276. var i18n = {
  277. /**
  278. * supported languages, minus the built in 'en'
  279. */
  280. supportedLanguages: ['de', 'fr', 'pl'],
  281. /**
  282. * translate a string, alias for translate()
  283. *
  284. * @param string $messageId
  285. * @param mixed args one or multiple parameters injected into placeholders
  286. * @return string
  287. */
  288. _: function()
  289. {
  290. return this.translate(arguments);
  291. },
  292. /**
  293. * translate a string
  294. *
  295. * @param string $messageId
  296. * @param mixed args one or multiple parameters injected into placeholders
  297. * @return string
  298. */
  299. translate: function()
  300. {
  301. var args = arguments, messageId, usesPlurals;
  302. if (typeof arguments[0] == 'object') args = arguments[0];
  303. if (usesPlurals = $.isArray(args[0]))
  304. {
  305. // use the first plural form as messageId, otherwise the singular
  306. messageId = (args[0].length > 1 ? args[0][1] : args[0][0]);
  307. }
  308. else
  309. {
  310. messageId = args[0];
  311. }
  312. if (messageId.length == 0) return messageId;
  313. if (!this.translations.hasOwnProperty(messageId))
  314. {
  315. if (this.language != 'en') console.debug(
  316. 'Missing translation for: ' + messageId
  317. );
  318. this.translations[messageId] = args[0];
  319. }
  320. if (usesPlurals && $.isArray(this.translations[messageId]))
  321. {
  322. var n = parseInt(args[1] || 1),
  323. key = this.getPluralForm(n),
  324. maxKey = this.translations[messageId].length - 1;
  325. if (key > maxKey) key = maxKey;
  326. args[0] = this.translations[messageId][key];
  327. args[1] = n;
  328. }
  329. else
  330. {
  331. args[0] = this.translations[messageId];
  332. }
  333. return helper.sprintf(args);
  334. },
  335. /**
  336. * per language functions to use to determine the plural form
  337. * From: http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html
  338. *
  339. * @param int number
  340. * @return int array key
  341. */
  342. getPluralForm: function(n) {
  343. switch (this.language)
  344. {
  345. case 'fr':
  346. return (n > 1 ? 1 : 0);
  347. case 'pl':
  348. return (n == 1 ? 0 : n%10 >= 2 && n %10 <=4 && (n%100 < 10 || n%100 >= 20) ? 1 : 2);
  349. // en, de
  350. default:
  351. return (n != 1 ? 1 : 0);
  352. }
  353. },
  354. /**
  355. * load translations into cache, then execute callback function
  356. *
  357. * @param function callback
  358. */
  359. loadTranslations: function(callback)
  360. {
  361. var selectedLang = helper.getCookie('lang');
  362. var language = selectedLang.length > 0 ? selectedLang : (navigator.language || navigator.userLanguage).substring(0, 2);
  363. // note that 'en' is built in, so no translation is necessary
  364. if (this.supportedLanguages.indexOf(language) == -1)
  365. {
  366. callback();
  367. }
  368. else
  369. {
  370. $.getJSON('i18n/' + language + '.json', function(data) {
  371. i18n.language = language;
  372. i18n.translations = data;
  373. callback();
  374. });
  375. }
  376. },
  377. /**
  378. * built in language
  379. */
  380. language: 'en',
  381. /**
  382. * translation cache
  383. */
  384. translations: {}
  385. }
  386. /**
  387. * filter methods
  388. */
  389. var filter = {
  390. /**
  391. * Compress a message (deflate compression). Returns base64 encoded data.
  392. *
  393. * @param string message
  394. * @return base64 string data
  395. */
  396. compress: function(message)
  397. {
  398. return Base64.toBase64( RawDeflate.deflate( Base64.utob(message) ) );
  399. },
  400. /**
  401. * Decompress a message compressed with compress().
  402. *
  403. * @param base64 string data
  404. * @return string message
  405. */
  406. decompress: function(data)
  407. {
  408. return Base64.btou( RawDeflate.inflate( Base64.fromBase64(data) ) );
  409. },
  410. /**
  411. * Compress, then encrypt message with key.
  412. *
  413. * @param string key
  414. * @param string password
  415. * @param string message
  416. * @return encrypted string data
  417. */
  418. cipher: function(key, password, message)
  419. {
  420. password = password.trim();
  421. if (password.length == 0)
  422. {
  423. return sjcl.encrypt(key, this.compress(message));
  424. }
  425. return sjcl.encrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), this.compress(message));
  426. },
  427. /**
  428. * Decrypt message with key, then decompress.
  429. *
  430. * @param string key
  431. * @param string password
  432. * @param encrypted string data
  433. * @return string readable message
  434. */
  435. decipher: function(key, password, data)
  436. {
  437. if (data != undefined)
  438. {
  439. try
  440. {
  441. return this.decompress(sjcl.decrypt(key, data));
  442. }
  443. catch(err)
  444. {
  445. try
  446. {
  447. return this.decompress(sjcl.decrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), data));
  448. }
  449. catch(err)
  450. {}
  451. }
  452. }
  453. return '';
  454. }
  455. };
  456. var zerobin = {
  457. /**
  458. * Get the current script location (without search or hash part of the URL).
  459. * eg. http://server.com/zero/?aaaa#bbbb --> http://server.com/zero/
  460. *
  461. * @return string current script location
  462. */
  463. scriptLocation: function()
  464. {
  465. var scriptLocation = window.location.href.substring(0,window.location.href.length
  466. - window.location.search.length - window.location.hash.length),
  467. hashIndex = scriptLocation.indexOf('#');
  468. if (hashIndex !== -1)
  469. {
  470. scriptLocation = scriptLocation.substring(0, hashIndex);
  471. }
  472. return scriptLocation;
  473. },
  474. /**
  475. * Get the pastes unique identifier from the URL
  476. * eg. http://server.com/zero/?c05354954c49a487#xxx --> c05354954c49a487
  477. *
  478. * @return string unique identifier
  479. */
  480. pasteID: function()
  481. {
  482. return window.location.search.substring(1);
  483. },
  484. /**
  485. * Return the deciphering key stored in anchor part of the URL
  486. *
  487. * @return string key
  488. */
  489. pageKey: function()
  490. {
  491. // Some web 2.0 services and redirectors add data AFTER the anchor
  492. // (such as &utm_source=...). We will strip any additional data.
  493. var key = window.location.hash.substring(1), // Get key
  494. i = key.indexOf('=');
  495. // First, strip everything after the equal sign (=) which signals end of base64 string.
  496. if (i > -1) key = key.substring(0, i + 1);
  497. // If the equal sign was not present, some parameters may remain:
  498. i = key.indexOf('&');
  499. if (i > -1) key = key.substring(0, i);
  500. // Then add trailing equal sign if it's missing
  501. if (key.charAt(key.length - 1) !== '=') key += '=';
  502. return key;
  503. },
  504. /**
  505. * ask the user for the password and return it
  506. *
  507. * @throws error when dialog canceled
  508. * @return string password
  509. */
  510. requestPassword: function()
  511. {
  512. var password = prompt(i18n._('Please enter the password for this paste:'), '');
  513. if (password == null) throw 'password prompt canceled';
  514. if (password.length == 0) return this.requestPassword();
  515. return password;
  516. },
  517. /**
  518. * use given format on paste, defaults to plain text
  519. *
  520. * @param string format
  521. */
  522. formatPaste: function(format)
  523. {
  524. switch (format || 'plaintext')
  525. {
  526. case 'markdown':
  527. if (typeof Showdown == 'object')
  528. {
  529. var converter = new Showdown.converter();
  530. this.clearText.html(
  531. converter.makeHtml(this.clearText.html())
  532. );
  533. this.clearText.removeClass('hidden');
  534. }
  535. this.prettyMessage.addClass('hidden');
  536. break;
  537. case 'syntaxhighlighting':
  538. if (typeof prettyPrint == 'function') prettyPrint();
  539. default:
  540. // Convert URLs to clickable links.
  541. helper.urls2links(this.clearText);
  542. helper.urls2links(this.prettyPrint);
  543. this.clearText.addClass('hidden');
  544. this.prettyMessage.removeClass('hidden');
  545. }
  546. if (format == 'plaintext') this.prettyPrint.removeClass('prettyprint');
  547. },
  548. /**
  549. * Show decrypted text in the display area, including discussion (if open)
  550. *
  551. * @param string key : decryption key
  552. * @param array comments : Array of messages to display (items = array with keys ('data','meta')
  553. */
  554. displayMessages: function(key, comments)
  555. {
  556. // Try to decrypt the paste.
  557. var password = this.passwordInput.val();
  558. if (!this.prettyPrint.hasClass('prettyprinted')) {
  559. try
  560. {
  561. if (comments[0].attachment)
  562. {
  563. var attachment = filter.decipher(key, password, comments[0].attachment);
  564. if (attachment.length == 0)
  565. {
  566. if (password.length == 0) password = this.requestPassword();
  567. attachment = filter.decipher(key, password, comments[0].attachment);
  568. }
  569. if (attachment.length == 0) throw 'failed to decipher attachment';
  570. if (comments[0].attachmentname)
  571. {
  572. var attachmentname = filter.decipher(key, password, comments[0].attachmentname);
  573. if (attachmentname.length > 0) this.attachmentLink.attr('download', attachmentname);
  574. }
  575. this.attachmentLink.attr('href', attachment);
  576. this.attachment.removeClass('hidden');
  577. // if the attachment is an image, display it
  578. var imagePrefix = 'data:image/';
  579. if (attachment.substring(0, imagePrefix.length) == imagePrefix)
  580. {
  581. this.image.html(
  582. $(document.createElement('img'))
  583. .attr('src', attachment)
  584. .attr('class', 'img-thumbnail')
  585. );
  586. this.image.removeClass('hidden');
  587. }
  588. }
  589. var cleartext = filter.decipher(key, password, comments[0].data);
  590. if (cleartext.length == 0 && password.length == 0 && !comments[0].attachment)
  591. {
  592. password = this.requestPassword();
  593. cleartext = filter.decipher(key, password, comments[0].data);
  594. }
  595. if (cleartext.length == 0 && !comments[0].attachment) throw 'failed to decipher message';
  596. this.passwordInput.val(password);
  597. if (cleartext.length > 0)
  598. {
  599. helper.setElementText(this.clearText, cleartext);
  600. helper.setElementText(this.prettyPrint, cleartext);
  601. this.formatPaste(comments[0].meta.formatter);
  602. }
  603. }
  604. catch(err)
  605. {
  606. this.clearText.addClass('hidden');
  607. this.prettyMessage.addClass('hidden');
  608. this.cloneButton.addClass('hidden');
  609. this.showError(i18n._('Could not decrypt data (Wrong key?)'));
  610. return;
  611. }
  612. }
  613. // Display paste expiration / for your eyes only.
  614. if (comments[0].meta.expire_date)
  615. {
  616. var expiration = helper.secondsToHuman(comments[0].meta.remaining_time),
  617. expirationLabel = [
  618. 'This document will expire in %d ' + expiration[1] + '.',
  619. 'This document will expire in %d ' + expiration[1] + 's.'
  620. ];
  621. helper.setMessage(this.remainingTime, i18n._(expirationLabel, expiration[0]));
  622. this.remainingTime.removeClass('foryoureyesonly')
  623. .removeClass('hidden');
  624. }
  625. if (comments[0].meta.burnafterreading)
  626. {
  627. $.get(this.scriptLocation() + '?pasteid=' + this.pasteID() + '&deletetoken=burnafterreading', 'json')
  628. .fail(function() {
  629. zerobin.showError(i18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  630. });
  631. helper.setMessage(this.remainingTime, i18n._(
  632. 'FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.'
  633. ));
  634. this.remainingTime.addClass('foryoureyesonly')
  635. .removeClass('hidden');
  636. // Discourage cloning (as it can't really be prevented).
  637. this.cloneButton.addClass('hidden');
  638. }
  639. // If the discussion is opened on this paste, display it.
  640. if (comments[0].meta.opendiscussion)
  641. {
  642. this.comments.html('');
  643. // iterate over comments
  644. for (var i = 1; i < comments.length; i++)
  645. {
  646. var place = this.comments;
  647. var comment=comments[i];
  648. var cleartext = '[' + i18n._('Could not decrypt comment; Wrong key?') + ']';
  649. try
  650. {
  651. cleartext = filter.decipher(key, password, comment.data);
  652. }
  653. catch(err)
  654. {}
  655. // If parent comment exists, display below (CSS will automatically shift it right.)
  656. var cname = '#comment_' + comment.meta.parentid;
  657. // If the element exists in page
  658. if ($(cname).length)
  659. {
  660. place = $(cname);
  661. }
  662. var divComment = $('<article><div class="comment" id="comment_' + comment.meta.commentid+'">'
  663. + '<div class="commentmeta"><span class="nickname"></span><span class="commentdate"></span></div><div class="commentdata"></div>'
  664. + '<button class="btn btn-default btn-sm">' + i18n._('Reply') + '</button>'
  665. + '</div></article>');
  666. divComment.find('button').click({commentid: comment.meta.commentid}, $.proxy(this.openReply, this));
  667. helper.setElementText(divComment.find('div.commentdata'), cleartext);
  668. // Convert URLs to clickable links in comment.
  669. helper.urls2links(divComment.find('div.commentdata'));
  670. // Try to get optional nickname:
  671. var nick = filter.decipher(key, password, comment.meta.nickname);
  672. if (nick.length > 0)
  673. {
  674. divComment.find('span.nickname').text(nick);
  675. }
  676. else
  677. {
  678. divComment.find('span.nickname').html('<i>' + i18n._('Anonymous') + '</i>');
  679. }
  680. divComment.find('span.commentdate')
  681. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  682. .attr('title', 'CommentID: ' + comment.meta.commentid);
  683. // If an avatar is available, display it.
  684. if (comment.meta.vizhash)
  685. {
  686. divComment.find('span.nickname')
  687. .before(
  688. '<img src="' + comment.meta.vizhash + '" class="vizhash" title="' +
  689. i18n._('Anonymous avatar (Vizhash of the IP address)') + '" /> '
  690. );
  691. }
  692. place.append(divComment);
  693. }
  694. var divComment = $(
  695. '<div class="comment"><button class="btn btn-default btn-sm">' +
  696. i18n._('Add comment') + '</button></div>'
  697. );
  698. divComment.find('button').click({commentid: this.pasteID()}, $.proxy(this.openReply, this));
  699. this.comments.append(divComment);
  700. this.discussion.removeClass('hidden');
  701. }
  702. },
  703. /**
  704. * Open the comment entry when clicking the "Reply" button of a comment.
  705. *
  706. * @param Event event
  707. */
  708. openReply: function(event)
  709. {
  710. event.preventDefault();
  711. var source = $(event.target),
  712. commentid = event.data.commentid,
  713. hint = i18n._('Optional nickname...');
  714. // Remove any other reply area.
  715. $('div.reply').remove();
  716. var reply = $(
  717. '<div class="reply">' +
  718. '<input type="text" id="nickname" class="form-control" title="' + hint + '" placeholder="' + hint + '" />' +
  719. '<textarea id="replymessage" class="replymessage form-control" cols="80" rows="7"></textarea>' +
  720. '<br /><button id="replybutton" class="btn btn-default btn-sm">' + i18n._('Post comment') + '</button>' +
  721. '<div id="replystatus"> </div>' +
  722. '</div>'
  723. );
  724. reply.find('button').click({parentid: commentid}, $.proxy(this.sendComment, this));
  725. source.after(reply);
  726. $('#replymessage').focus();
  727. },
  728. /**
  729. * Send a reply in a discussion.
  730. *
  731. * @param Event event
  732. */
  733. sendComment: function(event)
  734. {
  735. event.preventDefault();
  736. this.errorMessage.addClass('hidden');
  737. // Do not send if no data.
  738. var replyMessage = $('#replymessage');
  739. if (replyMessage.val().length == 0) return;
  740. this.showStatus(i18n._('Sending comment...'), true);
  741. var parentid = event.data.parentid;
  742. var cipherdata = filter.cipher(this.pageKey(), this.passwordInput.val(), replyMessage.val());
  743. var ciphernickname = '';
  744. var nick = $('#nickname').val();
  745. if (nick != '')
  746. {
  747. ciphernickname = filter.cipher(this.pageKey(), this.passwordInput.val(), nick);
  748. }
  749. var data_to_send = {
  750. data: cipherdata,
  751. parentid: parentid,
  752. pasteid: this.pasteID(),
  753. nickname: ciphernickname
  754. };
  755. $.post(this.scriptLocation(), data_to_send, function(data)
  756. {
  757. if (data.status == 0)
  758. {
  759. zerobin.showStatus(i18n._('Comment posted.'), false);
  760. $.get(zerobin.scriptLocation() + '?' + zerobin.pasteID() + '&json', function(data)
  761. {
  762. if (data.status == 0)
  763. {
  764. zerobin.displayMessages(zerobin.pageKey(), data.messages);
  765. }
  766. else if (data.status == 1)
  767. {
  768. zerobin.showError(i18n._('Could not refresh display: %s', data.message));
  769. }
  770. else
  771. {
  772. zerobin.showError(i18n._('Could not refresh display: %s', i18n._('unknown status')));
  773. }
  774. }, 'json')
  775. .fail(function() {
  776. zerobin.showError(i18n._('Could not refresh display: %s', i18n._('server error or not responding')));
  777. });
  778. }
  779. else if (data.status == 1)
  780. {
  781. zerobin.showError(i18n._('Could not post comment: %s', data.message));
  782. }
  783. else
  784. {
  785. zerobin.showError(i18n._('Could not post comment: %s', i18n._('unknown status')));
  786. }
  787. }, 'json')
  788. .fail(function() {
  789. zerobin.showError(i18n._('Could not post comment: %s', i18n._('server error or not responding')));
  790. });
  791. },
  792. /**
  793. * Send a new paste to server
  794. *
  795. * @param Event event
  796. */
  797. sendData: function(event)
  798. {
  799. event.preventDefault();
  800. var file = document.getElementById('file'),
  801. files = (file && file.files) ? file.files : null; // FileList object
  802. // Do not send if no data.
  803. if (this.message.val().length == 0 && !(files && files[0])) return;
  804. // If sjcl has not collected enough entropy yet, display a message.
  805. if (!sjcl.random.isReady())
  806. {
  807. this.showStatus(i18n._('Sending paste (Please move your mouse for more entropy)...'), true);
  808. sjcl.random.addEventListener('seeded', function() {
  809. this.sendData(event);
  810. });
  811. return;
  812. }
  813. $('.navbar-toggle').click();
  814. this.password.addClass('hidden');
  815. this.showStatus(i18n._('Sending paste...'), true);
  816. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  817. var cipherdata_attachment;
  818. var password = this.passwordInput.val();
  819. if(files && files[0])
  820. {
  821. if(typeof FileReader === undefined)
  822. {
  823. this.showError(i18n._('Your browser does not support uploading encrypted files. Please use a newer browser.'));
  824. return;
  825. }
  826. var reader = new FileReader();
  827. // Closure to capture the file information.
  828. reader.onload = (function(theFile)
  829. {
  830. return function(e) {
  831. zerobin.sendDataContinue(
  832. randomkey,
  833. filter.cipher(randomkey, password, e.target.result),
  834. filter.cipher(randomkey, password, theFile.name)
  835. );
  836. }
  837. })(files[0]);
  838. reader.readAsDataURL(files[0]);
  839. }
  840. else if(this.attachmentLink.attr('href'))
  841. {
  842. this.sendDataContinue(
  843. randomkey,
  844. filter.cipher(randomkey, password, this.attachmentLink.attr('href')),
  845. this.attachmentLink.attr('download')
  846. );
  847. }
  848. else
  849. {
  850. this.sendDataContinue(randomkey, '', '');
  851. }
  852. },
  853. /**
  854. * Send a new paste to server, step 2
  855. *
  856. * @param Event event
  857. */
  858. sendDataContinue: function(randomkey, cipherdata_attachment, cipherdata_attachment_name)
  859. {
  860. var cipherdata = filter.cipher(randomkey, this.passwordInput.val(), this.message.val());
  861. var data_to_send = {
  862. data: cipherdata,
  863. expire: $('#pasteExpiration').val(),
  864. formatter: $('#pasteFormatter').val(),
  865. burnafterreading: this.burnAfterReading.is(':checked') ? 1 : 0,
  866. opendiscussion: this.openDiscussion.is(':checked') ? 1 : 0
  867. };
  868. if (cipherdata_attachment.length > 0)
  869. {
  870. data_to_send.attachment = cipherdata_attachment;
  871. if (cipherdata_attachment_name.length > 0)
  872. {
  873. data_to_send.attachmentname = cipherdata_attachment_name;
  874. }
  875. }
  876. $.post(this.scriptLocation(), data_to_send, function(data)
  877. {
  878. if (data.status == 0) {
  879. zerobin.stateExistingPaste();
  880. var url = zerobin.scriptLocation() + '?' + data.id + '#' + randomkey;
  881. var deleteUrl = zerobin.scriptLocation() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  882. zerobin.showStatus('', false);
  883. zerobin.errorMessage.addClass('hidden');
  884. $('#pastelink').html(i18n._('Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>', url, url));
  885. $('#deletelink').html('<a href="' + deleteUrl + '">' + i18n._('Delete data') + '</a>');
  886. zerobin.pasteResult.removeClass('hidden');
  887. // We pre-select the link so that the user only has to [Ctrl]+[c] the link.
  888. helper.selectText('pasteurl');
  889. zerobin.showStatus('', false);
  890. helper.setElementText(zerobin.clearText, zerobin.message.val());
  891. helper.setElementText(zerobin.prettyPrint, zerobin.message.val());
  892. zerobin.formatPaste(data_to_send.formatter);
  893. }
  894. else if (data.status==1)
  895. {
  896. zerobin.showError(i18n._('Could not create paste: %s', data.message));
  897. }
  898. else
  899. {
  900. zerobin.showError(i18n._('Could not create paste: %s', i18n._('unknown status')));
  901. }
  902. }, 'json')
  903. .fail(function() {
  904. zerobin.showError(i18n._('Could not create paste: %s', i18n._('server error or not responding')));
  905. });
  906. },
  907. /**
  908. * Put the screen in "New paste" mode.
  909. */
  910. stateNewPaste: function()
  911. {
  912. this.message.text('');
  913. this.attachment.addClass('hidden');
  914. this.cloneButton.addClass('hidden');
  915. this.rawTextButton.addClass('hidden');
  916. this.remainingTime.addClass('hidden');
  917. this.pasteResult.addClass('hidden');
  918. this.clearText.addClass('hidden');
  919. this.discussion.addClass('hidden');
  920. this.prettyMessage.addClass('hidden');
  921. this.sendButton.removeClass('hidden');
  922. this.expiration.removeClass('hidden');
  923. this.formatter.removeClass('hidden');
  924. this.burnAfterReadingOption.removeClass('hidden');
  925. this.openDisc.removeClass('hidden');
  926. this.newButton.removeClass('hidden');
  927. this.password.removeClass('hidden');
  928. this.attach.removeClass('hidden');
  929. this.message.removeClass('hidden');
  930. this.message.focus();
  931. },
  932. /**
  933. * Put the screen in "Existing paste" mode.
  934. */
  935. stateExistingPaste: function()
  936. {
  937. this.sendButton.addClass('hidden');
  938. // No "clone" for IE<10.
  939. if ($('#oldienotice').is(":visible"))
  940. {
  941. this.cloneButton.addClass('hidden');
  942. }
  943. else
  944. {
  945. this.cloneButton.removeClass('hidden');
  946. }
  947. this.rawTextButton.removeClass('hidden');
  948. this.attach.addClass('hidden');
  949. this.expiration.addClass('hidden');
  950. this.formatter.addClass('hidden');
  951. this.burnAfterReadingOption.addClass('hidden');
  952. this.openDisc.addClass('hidden');
  953. this.newButton.removeClass('hidden');
  954. this.pasteResult.addClass('hidden');
  955. this.message.addClass('hidden');
  956. this.clearText.addClass('hidden');
  957. this.prettyMessage.addClass('hidden');
  958. },
  959. /**
  960. * If "burn after reading" is checked, disable discussion.
  961. */
  962. changeBurnAfterReading: function()
  963. {
  964. if (this.burnAfterReading.is(':checked') )
  965. {
  966. this.openDisc.addClass('buttondisabled');
  967. this.openDiscussion.attr({checked: false, disabled: true});
  968. }
  969. else
  970. {
  971. this.openDisc.removeClass('buttondisabled');
  972. this.openDiscussion.removeAttr('disabled');
  973. }
  974. },
  975. /**
  976. * Reload the page
  977. *
  978. * @param Event event
  979. */
  980. reloadPage: function(event)
  981. {
  982. event.preventDefault();
  983. window.location.href = this.scriptLocation();
  984. },
  985. /**
  986. * Return raw text
  987. *
  988. * @param Event event
  989. */
  990. rawText: function(event)
  991. {
  992. event.preventDefault();
  993. var paste = this.clearText.html();
  994. var newDoc = document.open('text/html', 'replace');
  995. newDoc.write('<pre>' + paste + '</pre>');
  996. newDoc.close();
  997. },
  998. /**
  999. * Clone the current paste.
  1000. *
  1001. * @param Event event
  1002. */
  1003. clonePaste: function(event)
  1004. {
  1005. event.preventDefault();
  1006. this.stateNewPaste();
  1007. // Erase the id and the key in url
  1008. history.replaceState(document.title, document.title, this.scriptLocation());
  1009. this.showStatus('', false);
  1010. if (this.attachmentLink.attr('href'))
  1011. {
  1012. this.clonedFile.removeClass('hidden');
  1013. this.fileWrap.addClass('hidden');
  1014. }
  1015. this.message.text(this.clearText.text());
  1016. $('.navbar-toggle').click();
  1017. },
  1018. /**
  1019. * Create a new paste.
  1020. */
  1021. newPaste: function()
  1022. {
  1023. this.stateNewPaste();
  1024. this.showStatus('', false);
  1025. this.message.text('');
  1026. },
  1027. /**
  1028. * Removes an attachment.
  1029. */
  1030. removeAttachment: function()
  1031. {
  1032. this.clonedFile.addClass('hidden');
  1033. // removes the saved decrypted file data
  1034. this.attachmentLink.attr('href', '');
  1035. // the only way to deselect the file is to recreate the input
  1036. this.fileWrap.html(this.fileWrap.html());
  1037. this.fileWrap.removeClass('hidden');
  1038. },
  1039. /**
  1040. * Display an error message
  1041. * (We use the same function for paste and reply to comments)
  1042. *
  1043. * @param string message : text to display
  1044. */
  1045. showError: function(message)
  1046. {
  1047. if (this.status.length)
  1048. {
  1049. this.status.addClass('errorMessage').text(message);
  1050. }
  1051. else
  1052. {
  1053. this.errorMessage.removeClass('hidden');
  1054. helper.setMessage(this.errorMessage, message);
  1055. }
  1056. this.replyStatus.addClass('errorMessage').text(message);
  1057. },
  1058. /**
  1059. * Display a status message
  1060. * (We use the same function for paste and reply to comments)
  1061. *
  1062. * @param string message : text to display
  1063. * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
  1064. */
  1065. showStatus: function(message, spin)
  1066. {
  1067. this.replyStatus.removeClass('errorMessage').text(message);
  1068. if (!message)
  1069. {
  1070. this.status.html(' ');
  1071. return;
  1072. }
  1073. if (message == '')
  1074. {
  1075. this.status.html(' ');
  1076. return;
  1077. }
  1078. this.status.removeClass('errorMessage').text(message);
  1079. if (spin)
  1080. {
  1081. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0 4px 0 0;" />';
  1082. this.status.prepend(img);
  1083. this.replyStatus.prepend(img);
  1084. }
  1085. },
  1086. /**
  1087. * bind events to DOM elements
  1088. */
  1089. bindEvents: function()
  1090. {
  1091. this.burnAfterReading.change($.proxy(this.changeBurnAfterReading, this));
  1092. this.sendButton.click($.proxy(this.sendData, this));
  1093. this.cloneButton.click($.proxy(this.clonePaste, this));
  1094. this.rawTextButton.click($.proxy(this.rawText, this));
  1095. this.fileRemoveButton.click($.proxy(this.removeAttachment, this));
  1096. $('.reloadlink').click($.proxy(this.reloadPage, this));
  1097. },
  1098. /**
  1099. * main application
  1100. */
  1101. init: function()
  1102. {
  1103. // hide "no javascript" message
  1104. $('#noscript').hide();
  1105. // preload jQuery wrapped DOM elements and bind events
  1106. this.attach = $('#attach');
  1107. this.attachment = $('#attachment');
  1108. this.attachmentLink = $('#attachment a');
  1109. this.burnAfterReading = $('#burnafterreading');
  1110. this.burnAfterReadingOption = $('#burnafterreadingoption');
  1111. this.cipherData = $('#cipherdata');
  1112. this.clearText = $('#cleartext');
  1113. this.cloneButton = $('#clonebutton');
  1114. this.clonedFile = $('#clonedfile');
  1115. this.comments = $('#comments');
  1116. this.discussion = $('#discussion');
  1117. this.errorMessage = $('#errormessage');
  1118. this.expiration = $('#expiration');
  1119. this.fileRemoveButton = $('#fileremovebutton');
  1120. this.fileWrap = $('#filewrap');
  1121. this.formatter = $('#formatter');
  1122. this.image = $('#image');
  1123. this.message = $('#message');
  1124. this.newButton = $('#newbutton');
  1125. this.openDisc = $('#opendisc');
  1126. this.openDiscussion = $('#opendiscussion');
  1127. this.password = $('#password');
  1128. this.passwordInput = $('#passwordinput');
  1129. this.pasteResult = $('#pasteresult');
  1130. this.prettyMessage = $('#prettymessage');
  1131. this.prettyPrint = $('#prettyprint');
  1132. this.rawTextButton = $('#rawtextbutton');
  1133. this.remainingTime = $('#remainingtime');
  1134. this.replyStatus = $('#replystatus');
  1135. this.sendButton = $('#sendbutton');
  1136. this.status = $('#status');
  1137. this.bindEvents();
  1138. // Display status returned by php code if any (eg. Paste was properly deleted.)
  1139. if (this.status.text().length > 0)
  1140. {
  1141. this.showStatus(this.status.text(), false);
  1142. return;
  1143. }
  1144. // Keep line height even if content empty.
  1145. this.status.html(' ');
  1146. // Display an existing paste
  1147. if (this.cipherData.text().length > 1)
  1148. {
  1149. // Missing decryption key in URL?
  1150. if (window.location.hash.length == 0)
  1151. {
  1152. 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?)'));
  1153. return;
  1154. }
  1155. // List of messages to display.
  1156. var messages = $.parseJSON(this.cipherData.text());
  1157. // Show proper elements on screen.
  1158. this.stateExistingPaste();
  1159. this.displayMessages(this.pageKey(), messages);
  1160. }
  1161. // Display error message from php code.
  1162. else if (this.errorMessage.text().length > 1)
  1163. {
  1164. this.showError(this.errorMessage.text());
  1165. }
  1166. // Create a new paste.
  1167. else
  1168. {
  1169. this.newPaste();
  1170. }
  1171. }
  1172. }
  1173. /**
  1174. * main application start, called when DOM is fully loaded
  1175. * runs zerobin when translations were loaded
  1176. */
  1177. i18n.loadTranslations($.proxy(zerobin.init, zerobin));
  1178. });