zerobin.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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.20
  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. * Convert URLs to clickable links.
  175. * URLs to handle:
  176. * <code>
  177. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  178. * http://localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  179. * http://user:password@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  180. * </code>
  181. *
  182. * @param object element : a jQuery DOM element.
  183. */
  184. urls2links: function(element)
  185. {
  186. var markup = '<a href="$1" rel="nofollow">$1</a>';
  187. element.html(
  188. element.html().replace(
  189. /((http|https|ftp):\/\/[\w?=&.\/-;#@~%+-]+(?![\w\s?&.\/;#~%"=-]*>))/ig,
  190. markup
  191. )
  192. );
  193. element.html(
  194. element.html().replace(
  195. /((magnet):[\w?=&.\/-;#@~%+-]+)/ig,
  196. markup
  197. )
  198. );
  199. },
  200. /**
  201. * minimal sprintf emulation for %s and %d formats
  202. * From: http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914
  203. *
  204. * @param string format
  205. * @param mixed args one or multiple parameters injected into format string
  206. * @return string
  207. */
  208. sprintf: function()
  209. {
  210. var args = arguments;
  211. if (typeof arguments[0] == 'object') args = arguments[0];
  212. var string = args[0],
  213. i = 1;
  214. return string.replace(/%((%)|s|d)/g, function (m) {
  215. // m is the matched format, e.g. %s, %d
  216. var val = null;
  217. if (m[2]) {
  218. val = m[2];
  219. } else {
  220. val = args[i];
  221. // A switch statement so that the formatter can be extended.
  222. switch (m)
  223. {
  224. case '%d':
  225. val = parseFloat(val);
  226. if (isNaN(val)) {
  227. val = 0;
  228. }
  229. break;
  230. // Default is %s
  231. }
  232. ++i;
  233. }
  234. return val;
  235. });
  236. }
  237. };
  238. /**
  239. * internationalization methods
  240. */
  241. var i18n = {
  242. /**
  243. * supported languages, minus the built in 'en'
  244. */
  245. supportedLanguages: ['de', 'fr', 'pl'],
  246. /**
  247. * translate a string, alias for translate()
  248. *
  249. * @param string $messageId
  250. * @param mixed args one or multiple parameters injected into placeholders
  251. * @return string
  252. */
  253. _: function()
  254. {
  255. return this.translate(arguments);
  256. },
  257. /**
  258. * translate a string
  259. *
  260. * @param string $messageId
  261. * @param mixed args one or multiple parameters injected into placeholders
  262. * @return string
  263. */
  264. translate: function()
  265. {
  266. var args = arguments, messageId, usesPlurals;
  267. if (typeof arguments[0] == 'object') args = arguments[0];
  268. if (usesPlurals = $.isArray(args[0]))
  269. {
  270. // use the first plural form as messageId, otherwise the singular
  271. messageId = (args[0].length > 1 ? args[0][1] : args[0][0]);
  272. }
  273. else
  274. {
  275. messageId = args[0];
  276. }
  277. if (messageId.length == 0) return messageId;
  278. if (!this.translations.hasOwnProperty(messageId))
  279. {
  280. if (this.language != 'en') console.debug(
  281. 'Missing translation for: ' + messageId
  282. );
  283. this.translations[messageId] = args[0];
  284. }
  285. if (usesPlurals && $.isArray(this.translations[messageId]))
  286. {
  287. var n = parseInt(args[1] || 1),
  288. key = this.getPluralForm(n),
  289. maxKey = this.translations[messageId].length - 1;
  290. if (key > maxKey) key = maxKey;
  291. args[0] = this.translations[messageId][key];
  292. args[1] = n;
  293. }
  294. else
  295. {
  296. args[0] = this.translations[messageId];
  297. }
  298. return helper.sprintf(args);
  299. },
  300. /**
  301. * per language functions to use to determine the plural form
  302. * From: http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html
  303. *
  304. * @param int number
  305. * @return int array key
  306. */
  307. getPluralForm: function(n) {
  308. switch (this.language)
  309. {
  310. case 'fr':
  311. return (n > 1 ? 1 : 0);
  312. case 'pl':
  313. return (n == 1 ? 0 : n%10 >= 2 && n %10 <=4 && (n%100 < 10 || n%100 >= 20) ? 1 : 2);
  314. // en, de
  315. default:
  316. return (n != 1 ? 1 : 0);
  317. }
  318. },
  319. /**
  320. * load translations into cache, then execute callback function
  321. *
  322. * @param function callback
  323. */
  324. loadTranslations: function(callback)
  325. {
  326. var language = (navigator.language || navigator.userLanguage).substring(0, 2);
  327. // note that 'en' is built in, so no translation is necessary
  328. if (this.supportedLanguages.indexOf(language) == -1)
  329. {
  330. callback();
  331. }
  332. else
  333. {
  334. $.getJSON('i18n/' + language + '.json', function(data) {
  335. i18n.language = language;
  336. i18n.translations = data;
  337. callback();
  338. });
  339. }
  340. },
  341. /**
  342. * built in language
  343. */
  344. language: 'en',
  345. /**
  346. * translation cache
  347. */
  348. translations: {}
  349. }
  350. /**
  351. * filter methods
  352. */
  353. var filter = {
  354. /**
  355. * Compress a message (deflate compression). Returns base64 encoded data.
  356. *
  357. * @param string message
  358. * @return base64 string data
  359. */
  360. compress: function(message)
  361. {
  362. return Base64.toBase64( RawDeflate.deflate( Base64.utob(message) ) );
  363. },
  364. /**
  365. * Decompress a message compressed with compress().
  366. *
  367. * @param base64 string data
  368. * @return string message
  369. */
  370. decompress: function(data)
  371. {
  372. return Base64.btou( RawDeflate.inflate( Base64.fromBase64(data) ) );
  373. },
  374. /**
  375. * Compress, then encrypt message with key.
  376. *
  377. * @param string key
  378. * @param string password
  379. * @param string message
  380. * @return encrypted string data
  381. */
  382. cipher: function(key, password, message)
  383. {
  384. password = password.trim();
  385. if (password.length == 0)
  386. {
  387. return sjcl.encrypt(key, this.compress(message));
  388. }
  389. return sjcl.encrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), this.compress(message));
  390. },
  391. /**
  392. * Decrypt message with key, then decompress.
  393. *
  394. * @param string key
  395. * @param string password
  396. * @param encrypted string data
  397. * @return string readable message
  398. */
  399. decipher: function(key, password, data)
  400. {
  401. if (data != undefined)
  402. {
  403. try
  404. {
  405. return this.decompress(sjcl.decrypt(key, data));
  406. }
  407. catch(err)
  408. {
  409. try
  410. {
  411. return this.decompress(sjcl.decrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), data));
  412. }
  413. catch(err)
  414. {}
  415. }
  416. }
  417. return '';
  418. }
  419. };
  420. var zerobin = {
  421. /**
  422. * Get the current script location (without search or hash part of the URL).
  423. * eg. http://server.com/zero/?aaaa#bbbb --> http://server.com/zero/
  424. *
  425. * @return string current script location
  426. */
  427. scriptLocation: function()
  428. {
  429. var scriptLocation = window.location.href.substring(0,window.location.href.length
  430. - window.location.search.length - window.location.hash.length),
  431. hashIndex = scriptLocation.indexOf('#');
  432. if (hashIndex !== -1)
  433. {
  434. scriptLocation = scriptLocation.substring(0, hashIndex);
  435. }
  436. return scriptLocation;
  437. },
  438. /**
  439. * Get the pastes unique identifier from the URL
  440. * eg. http://server.com/zero/?c05354954c49a487#xxx --> c05354954c49a487
  441. *
  442. * @return string unique identifier
  443. */
  444. pasteID: function()
  445. {
  446. return window.location.search.substring(1);
  447. },
  448. /**
  449. * Return the deciphering key stored in anchor part of the URL
  450. *
  451. * @return string key
  452. */
  453. pageKey: function()
  454. {
  455. // Some web 2.0 services and redirectors add data AFTER the anchor
  456. // (such as &utm_source=...). We will strip any additional data.
  457. var key = window.location.hash.substring(1), // Get key
  458. i = key.indexOf('=');
  459. // First, strip everything after the equal sign (=) which signals end of base64 string.
  460. if (i > -1) key = key.substring(0, i + 1);
  461. // If the equal sign was not present, some parameters may remain:
  462. i = key.indexOf('&');
  463. if (i > -1) key = key.substring(0, i);
  464. // Then add trailing equal sign if it's missing
  465. if (key.charAt(key.length - 1) !== '=') key += '=';
  466. return key;
  467. },
  468. /**
  469. * ask the user for the password and return it
  470. *
  471. * @throws error when dialog canceled
  472. * @return string password
  473. */
  474. requestPassword: function()
  475. {
  476. var password = prompt(i18n._('Please enter the password for this paste:'), '');
  477. if (password == null) throw 'password prompt canceled';
  478. if (password.length == 0) return this.requestPassword();
  479. return password;
  480. },
  481. /**
  482. * Show decrypted text in the display area, including discussion (if open)
  483. *
  484. * @param string key : decryption key
  485. * @param array comments : Array of messages to display (items = array with keys ('data','meta')
  486. */
  487. displayMessages: function(key, comments)
  488. {
  489. // Try to decrypt the paste.
  490. var password = this.passwordInput.val();
  491. if (!this.prettyPrint.hasClass('prettyprinted')) {
  492. try
  493. {
  494. var cleartext = filter.decipher(key, password, comments[0].data);
  495. if (cleartext.length == 0)
  496. {
  497. if (password.length == 0) password = this.requestPassword();
  498. cleartext = filter.decipher(key, password, comments[0].data);
  499. }
  500. if (cleartext.length == 0) throw 'failed to decipher message';
  501. this.passwordInput.val(password);
  502. helper.setElementText(this.clearText, cleartext);
  503. helper.setElementText(this.prettyPrint, cleartext);
  504. // Convert URLs to clickable links.
  505. helper.urls2links(this.clearText);
  506. helper.urls2links(this.prettyPrint);
  507. if (typeof prettyPrint == 'function') prettyPrint();
  508. }
  509. catch(err)
  510. {
  511. this.clearText.addClass('hidden');
  512. this.prettyMessage.addClass('hidden');
  513. this.cloneButton.addClass('hidden');
  514. this.showError(i18n._('Could not decrypt data (Wrong key?)'));
  515. return;
  516. }
  517. }
  518. // Display paste expiration / for your eyes only.
  519. var content = this.remainingTime.contents();
  520. if (comments[0].meta.expire_date)
  521. {
  522. var expiration = helper.secondsToHuman(comments[0].meta.remaining_time),
  523. expirationLabel = [
  524. 'This document will expire in %d ' + expiration[1] + '.',
  525. 'This document will expire in %d ' + expiration[1] + 's.'
  526. ];
  527. content[content.length - 1].nodeValue = ' ' + i18n._(expirationLabel, expiration[0]);
  528. this.remainingTime.removeClass('foryoureyesonly')
  529. .removeClass('hidden');
  530. }
  531. if (comments[0].meta.burnafterreading)
  532. {
  533. $.get(this.scriptLocation() + '?pasteid=' + this.pasteID() + '&deletetoken=burnafterreading', 'json')
  534. .fail(function() {
  535. zerobin.showError(i18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  536. });
  537. content[content.length - 1].nodeValue = ' ' + i18n._(
  538. 'FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.'
  539. );
  540. this.remainingTime.addClass('foryoureyesonly')
  541. .removeClass('hidden');
  542. // Discourage cloning (as it can't really be prevented).
  543. this.cloneButton.addClass('hidden');
  544. }
  545. // If the discussion is opened on this paste, display it.
  546. if (comments[0].meta.opendiscussion)
  547. {
  548. this.comments.html('');
  549. // iterate over comments
  550. for (var i = 1; i < comments.length; i++)
  551. {
  552. var place = this.comments;
  553. var comment=comments[i];
  554. var cleartext = '[' + i18n._('Could not decrypt comment; Wrong key?') + ']';
  555. try
  556. {
  557. cleartext = filter.decipher(key, password, comment.data);
  558. }
  559. catch(err)
  560. {}
  561. // If parent comment exists, display below (CSS will automatically shift it right.)
  562. var cname = '#comment_' + comment.meta.parentid;
  563. // If the element exists in page
  564. if ($(cname).length)
  565. {
  566. place = $(cname);
  567. }
  568. var divComment = $('<article><div class="comment" id="comment_' + comment.meta.commentid+'">'
  569. + '<div class="commentmeta"><span class="nickname"></span><span class="commentdate"></span></div><div class="commentdata"></div>'
  570. + '<button class="btn btn-default btn-sm">' + i18n._('Reply') + '</button>'
  571. + '</div></article>');
  572. divComment.find('button').click({commentid: comment.meta.commentid}, $.proxy(this.openReply, this));
  573. helper.setElementText(divComment.find('div.commentdata'), cleartext);
  574. // Convert URLs to clickable links in comment.
  575. helper.urls2links(divComment.find('div.commentdata'));
  576. // Try to get optional nickname:
  577. var nick = filter.decipher(key, password, comment.meta.nickname);
  578. if (nick.length > 0)
  579. {
  580. divComment.find('span.nickname').text(nick);
  581. }
  582. else
  583. {
  584. divComment.find('span.nickname').html('<i>' + i18n._('Anonymous') + '</i>');
  585. }
  586. divComment.find('span.commentdate')
  587. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  588. .attr('title', 'CommentID: ' + comment.meta.commentid);
  589. // If an avatar is available, display it.
  590. if (comment.meta.vizhash)
  591. {
  592. divComment.find('span.nickname')
  593. .before(
  594. '<img src="' + comment.meta.vizhash + '" class="vizhash" title="' +
  595. i18n._('Anonymous avatar (Vizhash of the IP address)') + '" /> '
  596. );
  597. }
  598. place.append(divComment);
  599. }
  600. var divComment = $(
  601. '<div class="comment"><button class="btn btn-default btn-sm">' +
  602. i18n._('Add comment') + '</button></div>'
  603. );
  604. divComment.find('button').click({commentid: this.pasteID()}, $.proxy(this.openReply, this));
  605. this.comments.append(divComment);
  606. this.discussion.removeClass('hidden');
  607. }
  608. },
  609. /**
  610. * Open the comment entry when clicking the "Reply" button of a comment.
  611. *
  612. * @param Event event
  613. */
  614. openReply: function(event)
  615. {
  616. event.preventDefault();
  617. var source = $(event.target),
  618. commentid = event.data.commentid,
  619. hint = i18n._('Optional nickname...');
  620. // Remove any other reply area.
  621. $('div.reply').remove();
  622. var reply = $(
  623. '<div class="reply">' +
  624. '<input type="text" id="nickname" class="form-control" title="' + hint + '" placeholder="' + hint + '" />' +
  625. '<textarea id="replymessage" class="replymessage form-control" cols="80" rows="7"></textarea>' +
  626. '<br /><button id="replybutton" class="btn btn-default btn-sm">' + i18n._('Post comment') + '</button>' +
  627. '<div id="replystatus"> </div>' +
  628. '</div>'
  629. );
  630. reply.find('button').click({parentid: commentid}, $.proxy(this.sendComment, this));
  631. source.after(reply);
  632. $('#replymessage').focus();
  633. },
  634. /**
  635. * Send a reply in a discussion.
  636. *
  637. * @param Event event
  638. */
  639. sendComment: function(event)
  640. {
  641. event.preventDefault();
  642. this.errorMessage.addClass('hidden');
  643. // Do not send if no data.
  644. var replyMessage = $('#replymessage');
  645. if (replyMessage.val().length == 0) return;
  646. this.showStatus(i18n._('Sending comment...'), true);
  647. var parentid = event.data.parentid;
  648. var cipherdata = filter.cipher(this.pageKey(), this.passwordInput.val(), replyMessage.val());
  649. var ciphernickname = '';
  650. var nick = $('#nickname').val();
  651. if (nick != '')
  652. {
  653. ciphernickname = filter.cipher(this.pageKey(), this.passwordInput.val(), nick);
  654. }
  655. var data_to_send = {
  656. data: cipherdata,
  657. parentid: parentid,
  658. pasteid: this.pasteID(),
  659. nickname: ciphernickname
  660. };
  661. $.post(this.scriptLocation(), data_to_send, function(data)
  662. {
  663. if (data.status == 0)
  664. {
  665. zerobin.showStatus(i18n._('Comment posted.'), false);
  666. $.get(zerobin.scriptLocation() + '?' + zerobin.pasteID() + '&json', function(data)
  667. {
  668. if (data.status == 0)
  669. {
  670. zerobin.displayMessages(zerobin.pageKey(), data.messages);
  671. }
  672. else if (data.status == 1)
  673. {
  674. zerobin.showError(i18n._('Could not refresh display: %s', data.message));
  675. }
  676. else
  677. {
  678. zerobin.showError(i18n._('Could not refresh display: %s', i18n._('unknown status')));
  679. }
  680. }, 'json')
  681. .fail(function() {
  682. zerobin.showError(i18n._('Could not refresh display: %s', i18n._('server error or not responding')));
  683. });
  684. }
  685. else if (data.status == 1)
  686. {
  687. zerobin.showError(i18n._('Could not post comment: %s', data.message));
  688. }
  689. else
  690. {
  691. zerobin.showError(i18n._('Could not post comment: %s', i18n._('unknown status')));
  692. }
  693. }, 'json')
  694. .fail(function() {
  695. zerobin.showError(i18n._('Could not post comment: %s', i18n._('server error or not responding')));
  696. });
  697. },
  698. /**
  699. * Send a new paste to server
  700. *
  701. * @param Event event
  702. */
  703. sendData: function(event)
  704. {
  705. event.preventDefault();
  706. // Do not send if no data.
  707. if (this.message.val().length == 0) return;
  708. // If sjcl has not collected enough entropy yet, display a message.
  709. if (!sjcl.random.isReady())
  710. {
  711. this.showStatus(i18n._('Sending paste (Please move your mouse for more entropy)...'), true);
  712. sjcl.random.addEventListener('seeded', function() {
  713. this.sendData(event);
  714. });
  715. return;
  716. }
  717. $('.navbar-toggle').click();
  718. this.password.addClass('hidden');
  719. this.showStatus(i18n._('Sending paste...'), true);
  720. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  721. var cipherdata = filter.cipher(randomkey, this.passwordInput.val(), this.message.val());
  722. var data_to_send = {
  723. data: cipherdata,
  724. expire: $('#pasteExpiration').val(),
  725. burnafterreading: this.burnAfterReading.is(':checked') ? 1 : 0,
  726. opendiscussion: this.openDiscussion.is(':checked') ? 1 : 0
  727. };
  728. $.post(this.scriptLocation(), data_to_send, function(data)
  729. {
  730. if (data.status == 0) {
  731. zerobin.stateExistingPaste();
  732. var url = zerobin.scriptLocation() + '?' + data.id + '#' + randomkey;
  733. var deleteUrl = zerobin.scriptLocation() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  734. zerobin.showStatus('', false);
  735. zerobin.errorMessage.addClass('hidden');
  736. $('#pastelink').html(i18n._('Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>', url, url));
  737. $('#deletelink').html('<a href="' + deleteUrl + '">' + i18n._('Delete data') + '</a>');
  738. zerobin.pasteResult.removeClass('hidden');
  739. // We pre-select the link so that the user only has to [Ctrl]+[c] the link.
  740. helper.selectText('pasteurl');
  741. helper.setElementText(zerobin.clearText, zerobin.message.val());
  742. helper.setElementText(zerobin.prettyPrint, zerobin.message.val());
  743. // Convert URLs to clickable links.
  744. helper.urls2links(zerobin.clearText);
  745. helper.urls2links(zerobin.prettyPrint);
  746. zerobin.showStatus('', false);
  747. if (typeof prettyPrint == 'function') prettyPrint();
  748. }
  749. else if (data.status==1)
  750. {
  751. zerobin.showError(i18n._('Could not create paste: %s', data.message));
  752. }
  753. else
  754. {
  755. zerobin.showError(i18n._('Could not create paste: %s', i18n._('unknown status')));
  756. }
  757. }, 'json')
  758. .fail(function() {
  759. zerobin.showError(i18n._('Could not create paste: %s', i18n._('server error or not responding')));
  760. });
  761. },
  762. /**
  763. * Put the screen in "New paste" mode.
  764. */
  765. stateNewPaste: function()
  766. {
  767. this.message.text('');
  768. this.cloneButton.addClass('hidden');
  769. this.rawTextButton.addClass('hidden');
  770. this.remainingTime.addClass('hidden');
  771. this.pasteResult.addClass('hidden');
  772. this.clearText.addClass('hidden');
  773. this.discussion.addClass('hidden');
  774. this.prettyMessage.addClass('hidden');
  775. this.sendButton.removeClass('hidden');
  776. this.expiration.removeClass('hidden');
  777. this.burnAfterReadingOption.removeClass('hidden');
  778. this.openDisc.removeClass('hidden');
  779. this.newButton.removeClass('hidden');
  780. this.password.removeClass('hidden');
  781. this.message.removeClass('hidden');
  782. this.message.focus();
  783. },
  784. /**
  785. * Put the screen in "Existing paste" mode.
  786. */
  787. stateExistingPaste: function()
  788. {
  789. this.sendButton.addClass('hidden');
  790. // No "clone" for IE<10.
  791. if ($('#oldienotice').is(":visible"))
  792. {
  793. this.cloneButton.addClass('hidden');
  794. }
  795. else
  796. {
  797. this.cloneButton.removeClass('hidden');
  798. }
  799. this.rawTextButton.removeClass('hidden');
  800. this.expiration.addClass('hidden');
  801. this.burnAfterReadingOption.addClass('hidden');
  802. this.openDisc.addClass('hidden');
  803. this.newButton.removeClass('hidden');
  804. this.pasteResult.addClass('hidden');
  805. this.message.addClass('hidden');
  806. this.clearText.addClass('hidden');
  807. this.prettyMessage.removeClass('hidden');
  808. },
  809. /**
  810. * If "burn after reading" is checked, disable discussion.
  811. */
  812. changeBurnAfterReading: function()
  813. {
  814. if (this.burnAfterReading.is(':checked') )
  815. {
  816. this.openDisc.addClass('buttondisabled');
  817. this.openDiscussion.attr({checked: false, disabled: true});
  818. }
  819. else
  820. {
  821. this.openDisc.removeClass('buttondisabled');
  822. this.openDiscussion.removeAttr('disabled');
  823. }
  824. },
  825. /**
  826. * Reload the page
  827. *
  828. * @param Event event
  829. */
  830. reloadPage: function(event)
  831. {
  832. event.preventDefault();
  833. window.location.href = this.scriptLocation();
  834. },
  835. /**
  836. * Return raw text
  837. *
  838. * @param Event event
  839. */
  840. rawText: function(event)
  841. {
  842. event.preventDefault();
  843. var paste = this.clearText.html();
  844. var newDoc = document.open('text/html', 'replace');
  845. newDoc.write('<pre>' + paste + '</pre>');
  846. newDoc.close();
  847. },
  848. /**
  849. * Clone the current paste.
  850. *
  851. * @param Event event
  852. */
  853. clonePaste: function(event)
  854. {
  855. event.preventDefault();
  856. this.stateNewPaste();
  857. // Erase the id and the key in url
  858. history.replaceState(document.title, document.title, this.scriptLocation());
  859. this.showStatus('', false);
  860. this.message.text(this.clearText.text());
  861. $('.navbar-toggle').click();
  862. },
  863. /**
  864. * Create a new paste.
  865. */
  866. newPaste: function()
  867. {
  868. this.stateNewPaste();
  869. this.showStatus('', false);
  870. this.message.text('');
  871. $('.navbar-toggle').click();
  872. },
  873. /**
  874. * Display an error message
  875. * (We use the same function for paste and reply to comments)
  876. *
  877. * @param string message : text to display
  878. */
  879. showError: function(message)
  880. {
  881. if (this.status.length)
  882. {
  883. this.status.addClass('errorMessage').text(message);
  884. }
  885. else
  886. {
  887. this.errorMessage.removeClass('hidden');
  888. var content = this.errorMessage.contents();
  889. content[content.length - 1].nodeValue = ' ' + message;
  890. }
  891. this.replyStatus.addClass('errorMessage').text(message);
  892. },
  893. /**
  894. * Display a status message
  895. * (We use the same function for paste and reply to comments)
  896. *
  897. * @param string message : text to display
  898. * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
  899. */
  900. showStatus: function(message, spin)
  901. {
  902. this.replyStatus.removeClass('errorMessage').text(message);
  903. if (!message)
  904. {
  905. this.status.html(' ');
  906. return;
  907. }
  908. if (message == '')
  909. {
  910. this.status.html(' ');
  911. return;
  912. }
  913. this.status.removeClass('errorMessage').text(message);
  914. if (spin)
  915. {
  916. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0 4px 0 0;" />';
  917. this.status.prepend(img);
  918. this.replyStatus.prepend(img);
  919. }
  920. },
  921. /**
  922. * bind events to DOM elements
  923. */
  924. bindEvents: function()
  925. {
  926. this.burnAfterReading.change($.proxy(this.changeBurnAfterReading, this));
  927. this.sendButton.click($.proxy(this.sendData, this));
  928. this.cloneButton.click($.proxy(this.clonePaste, this));
  929. this.rawTextButton.click($.proxy(this.rawText, this));
  930. $('.reloadlink').click($.proxy(this.reloadPage, this));
  931. },
  932. /**
  933. * main application
  934. */
  935. init: function()
  936. {
  937. // hide "no javascript" message
  938. $('#noscript').hide();
  939. // preload jQuery wrapped DOM elements and bind events
  940. this.burnAfterReading = $('#burnafterreading');
  941. this.burnAfterReadingOption = $('#burnafterreadingoption');
  942. this.cipherData = $('#cipherdata');
  943. this.clearText = $('#cleartext');
  944. this.cloneButton = $('#clonebutton');
  945. this.comments = $('#comments');
  946. this.discussion = $('#discussion');
  947. this.errorMessage = $('#errormessage');
  948. this.expiration = $('#expiration');
  949. this.message = $('#message');
  950. this.newButton = $('#newbutton');
  951. this.openDisc = $('#opendisc');
  952. this.openDiscussion = $('#opendiscussion');
  953. this.password = $('#password');
  954. this.passwordInput = $('#passwordinput');
  955. this.pasteResult = $('#pasteresult');
  956. this.prettyMessage = $('#prettymessage');
  957. this.prettyPrint = $('#prettyprint');
  958. this.rawTextButton = $('#rawtextbutton');
  959. this.remainingTime = $('#remainingtime');
  960. this.replyStatus = $('#replystatus');
  961. this.sendButton = $('#sendbutton');
  962. this.status = $('#status');
  963. this.bindEvents();
  964. // Display status returned by php code if any (eg. Paste was properly deleted.)
  965. if (this.status.text().length > 0)
  966. {
  967. this.showStatus(this.status.text(), false);
  968. return;
  969. }
  970. // Keep line height even if content empty.
  971. this.status.html(' ');
  972. // Display an existing paste
  973. if (this.cipherData.text().length > 1)
  974. {
  975. // Missing decryption key in URL?
  976. if (window.location.hash.length == 0)
  977. {
  978. 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?)'));
  979. return;
  980. }
  981. // List of messages to display.
  982. var messages = $.parseJSON(this.cipherData.text());
  983. // Show proper elements on screen.
  984. this.stateExistingPaste();
  985. this.displayMessages(this.pageKey(), messages);
  986. }
  987. // Display error message from php code.
  988. else if (this.errorMessage.text().length > 1)
  989. {
  990. this.showError(this.errorMessage.text());
  991. }
  992. // Create a new paste.
  993. else
  994. {
  995. this.newPaste();
  996. }
  997. }
  998. }
  999. /**
  1000. * main application start, called when DOM is fully loaded
  1001. * runs zerobin when translations were loaded
  1002. */
  1003. i18n.loadTranslations($.proxy(zerobin.init, zerobin));
  1004. });