zerobin.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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.
  519. if (comments[0].meta.expire_date)
  520. {
  521. var expiration = helper.secondsToHuman(comments[0].meta.remaining_time),
  522. expirationLabel = [
  523. 'This document will expire in %d ' + expiration[1] + '.',
  524. 'This document will expire in %d ' + expiration[1] + 's.'
  525. ];
  526. this.remainingTime.removeClass('foryoureyesonly')
  527. .text(i18n._(expirationLabel, expiration[0]))
  528. .removeClass('hidden');
  529. }
  530. if (comments[0].meta.burnafterreading)
  531. {
  532. $.get(this.scriptLocation() + '?pasteid=' + this.pasteID() + '&deletetoken=burnafterreading', 'json')
  533. .fail(function() {
  534. zerobin.showError(i18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  535. });
  536. this.remainingTime.addClass('foryoureyesonly')
  537. .text(i18n._('FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.'))
  538. .removeClass('hidden');
  539. // Discourage cloning (as it can't really be prevented).
  540. this.cloneButton.addClass('hidden');
  541. }
  542. // If the discussion is opened on this paste, display it.
  543. if (comments[0].meta.opendiscussion)
  544. {
  545. this.comments.html('');
  546. // iterate over comments
  547. for (var i = 1; i < comments.length; i++)
  548. {
  549. var place = this.comments;
  550. var comment=comments[i];
  551. var cleartext = '[' + i18n._('Could not decrypt comment; Wrong key?') + ']';
  552. try
  553. {
  554. cleartext = filter.decipher(key, password, comment.data);
  555. }
  556. catch(err)
  557. {}
  558. // If parent comment exists, display below (CSS will automatically shift it right.)
  559. var cname = '#comment_' + comment.meta.parentid;
  560. // If the element exists in page
  561. if ($(cname).length)
  562. {
  563. place = $(cname);
  564. }
  565. var divComment = $('<article><div class="comment" id="comment_' + comment.meta.commentid+'">'
  566. + '<div class="commentmeta"><span class="nickname"></span><span class="commentdate"></span></div><div class="commentdata"></div>'
  567. + '<button class="btn btn-default btn-sm">' + i18n._('Reply') + '</button>'
  568. + '</div></article>');
  569. divComment.find('button').click({commentid: comment.meta.commentid}, $.proxy(this.openReply, this));
  570. helper.setElementText(divComment.find('div.commentdata'), cleartext);
  571. // Convert URLs to clickable links in comment.
  572. helper.urls2links(divComment.find('div.commentdata'));
  573. // Try to get optional nickname:
  574. var nick = filter.decipher(key, password, comment.meta.nickname);
  575. if (nick.length > 0)
  576. {
  577. divComment.find('span.nickname').text(nick);
  578. }
  579. else
  580. {
  581. divComment.find('span.nickname').html('<i>' + i18n._('Anonymous') + '</i>');
  582. }
  583. divComment.find('span.commentdate')
  584. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  585. .attr('title', 'CommentID: ' + comment.meta.commentid);
  586. // If an avatar is available, display it.
  587. if (comment.meta.vizhash)
  588. {
  589. divComment.find('span.nickname')
  590. .before(
  591. '<img src="' + comment.meta.vizhash + '" class="vizhash" title="' +
  592. i18n._('Anonymous avatar (Vizhash of the IP address)') + '" /> '
  593. );
  594. }
  595. place.append(divComment);
  596. }
  597. var divComment = $(
  598. '<div class="comment"><button class="btn btn-default btn-sm">' +
  599. i18n._('Add comment') + '</button></div>'
  600. );
  601. divComment.find('button').click({commentid: this.pasteID()}, $.proxy(this.openReply, this));
  602. this.comments.append(divComment);
  603. this.discussion.removeClass('hidden');
  604. }
  605. },
  606. /**
  607. * Open the comment entry when clicking the "Reply" button of a comment.
  608. *
  609. * @param Event event
  610. */
  611. openReply: function(event)
  612. {
  613. event.preventDefault();
  614. var source = $(event.target),
  615. commentid = event.data.commentid,
  616. hint = i18n._('Optional nickname...');
  617. // Remove any other reply area.
  618. $('div.reply').remove();
  619. var reply = $(
  620. '<div class="reply">' +
  621. '<input type="text" id="nickname" class="form-control" title="' + hint + '" placeholder="' + hint + '" />' +
  622. '<textarea id="replymessage" class="replymessage form-control" cols="80" rows="7"></textarea>' +
  623. '<br /><button id="replybutton" class="btn btn-default btn-sm">' + i18n._('Post comment') + '</button>' +
  624. '<div id="replystatus"> </div>' +
  625. '</div>'
  626. );
  627. reply.find('button').click({parentid: commentid}, $.proxy(this.sendComment, this));
  628. source.after(reply);
  629. $('#replymessage').focus();
  630. },
  631. /**
  632. * Send a reply in a discussion.
  633. *
  634. * @param Event event
  635. */
  636. sendComment: function(event)
  637. {
  638. event.preventDefault();
  639. this.errorMessage.addClass('hidden');
  640. // Do not send if no data.
  641. var replyMessage = $('#replymessage');
  642. if (replyMessage.val().length == 0) return;
  643. this.showStatus(i18n._('Sending comment...'), true);
  644. var parentid = event.data.parentid;
  645. var cipherdata = filter.cipher(this.pageKey(), this.passwordInput.val(), replyMessage.val());
  646. var ciphernickname = '';
  647. var nick = $('#nickname').val();
  648. if (nick != '')
  649. {
  650. ciphernickname = filter.cipher(this.pageKey(), this.passwordInput.val(), nick);
  651. }
  652. var data_to_send = {
  653. data: cipherdata,
  654. parentid: parentid,
  655. pasteid: this.pasteID(),
  656. nickname: ciphernickname
  657. };
  658. $.post(this.scriptLocation(), data_to_send, function(data)
  659. {
  660. if (data.status == 0)
  661. {
  662. zerobin.showStatus(i18n._('Comment posted.'), false);
  663. $.get(zerobin.scriptLocation() + '?' + zerobin.pasteID() + '&json', function(data)
  664. {
  665. if (data.status == 0)
  666. {
  667. zerobin.displayMessages(zerobin.pageKey(), data.messages);
  668. }
  669. else if (data.status == 1)
  670. {
  671. zerobin.showError(i18n._('Could not refresh display: %s', data.message));
  672. }
  673. else
  674. {
  675. zerobin.showError(i18n._('Could not refresh display: %s', i18n._('unknown status')));
  676. }
  677. }, 'json')
  678. .fail(function() {
  679. zerobin.showError(i18n._('Could not refresh display: %s', i18n._('server error or not responding')));
  680. });
  681. }
  682. else if (data.status == 1)
  683. {
  684. zerobin.showError(i18n._('Could not post comment: %s', data.message));
  685. }
  686. else
  687. {
  688. zerobin.showError(i18n._('Could not post comment: %s', i18n._('unknown status')));
  689. }
  690. }, 'json')
  691. .fail(function() {
  692. zerobin.showError(i18n._('Could not post comment: %s', i18n._('server error or not responding')));
  693. });
  694. },
  695. /**
  696. * Send a new paste to server
  697. *
  698. * @param Event event
  699. */
  700. sendData: function(event)
  701. {
  702. event.preventDefault();
  703. // Do not send if no data.
  704. if (this.message.val().length == 0) return;
  705. // If sjcl has not collected enough entropy yet, display a message.
  706. if (!sjcl.random.isReady())
  707. {
  708. this.showStatus(i18n._('Sending paste (Please move your mouse for more entropy)...'), true);
  709. sjcl.random.addEventListener('seeded', function() {
  710. this.sendData(event);
  711. });
  712. return;
  713. }
  714. $('.navbar-toggle').click();
  715. this.password.addClass('hidden');
  716. this.showStatus(i18n._('Sending paste...'), true);
  717. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  718. var cipherdata = filter.cipher(randomkey, this.passwordInput.val(), this.message.val());
  719. var data_to_send = {
  720. data: cipherdata,
  721. expire: $('#pasteExpiration').val(),
  722. burnafterreading: this.burnAfterReading.is(':checked') ? 1 : 0,
  723. opendiscussion: this.openDiscussion.is(':checked') ? 1 : 0
  724. };
  725. $.post(this.scriptLocation(), data_to_send, function(data)
  726. {
  727. if (data.status == 0) {
  728. zerobin.stateExistingPaste();
  729. var url = zerobin.scriptLocation() + '?' + data.id + '#' + randomkey;
  730. var deleteUrl = zerobin.scriptLocation() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  731. zerobin.showStatus('', false);
  732. zerobin.errorMessage.addClass('hidden');
  733. $('#pastelink').html(i18n._('Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>', url, url));
  734. $('#deletelink').html('<a href="' + deleteUrl + '">' + i18n._('Delete data') + '</a>');
  735. zerobin.pasteResult.removeClass('hidden');
  736. // We pre-select the link so that the user only has to [Ctrl]+[c] the link.
  737. helper.selectText('pasteurl');
  738. helper.setElementText(zerobin.clearText, zerobin.message.val());
  739. helper.setElementText(zerobin.prettyPrint, zerobin.message.val());
  740. // Convert URLs to clickable links.
  741. helper.urls2links(zerobin.clearText);
  742. helper.urls2links(zerobin.prettyPrint);
  743. zerobin.showStatus('', false);
  744. if (typeof prettyPrint == 'function') prettyPrint();
  745. }
  746. else if (data.status==1)
  747. {
  748. zerobin.showError(i18n._('Could not create paste: %s', data.message));
  749. }
  750. else
  751. {
  752. zerobin.showError(i18n._('Could not create paste: %s', i18n._('unknown status')));
  753. }
  754. }, 'json')
  755. .fail(function() {
  756. zerobin.showError(i18n._('Could not create paste: %s', i18n._('server error or not responding')));
  757. });
  758. },
  759. /**
  760. * Put the screen in "New paste" mode.
  761. */
  762. stateNewPaste: function()
  763. {
  764. this.message.text('');
  765. this.cloneButton.addClass('hidden');
  766. this.rawTextButton.addClass('hidden');
  767. this.remainingTime.addClass('hidden');
  768. this.pasteResult.addClass('hidden');
  769. this.clearText.addClass('hidden');
  770. this.discussion.addClass('hidden');
  771. this.prettyMessage.addClass('hidden');
  772. this.sendButton.removeClass('hidden');
  773. this.expiration.removeClass('hidden');
  774. this.burnAfterReadingOption.removeClass('hidden');
  775. this.openDisc.removeClass('hidden');
  776. this.newButton.removeClass('hidden');
  777. this.password.removeClass('hidden');
  778. this.message.removeClass('hidden');
  779. this.message.focus();
  780. },
  781. /**
  782. * Put the screen in "Existing paste" mode.
  783. */
  784. stateExistingPaste: function()
  785. {
  786. this.sendButton.addClass('hidden');
  787. // No "clone" for IE<10.
  788. if ($('#oldienotice').is(":visible"))
  789. {
  790. this.cloneButton.addClass('hidden');
  791. }
  792. else
  793. {
  794. this.cloneButton.removeClass('hidden');
  795. }
  796. this.rawTextButton.removeClass('hidden');
  797. this.expiration.addClass('hidden');
  798. this.burnAfterReadingOption.addClass('hidden');
  799. this.openDisc.addClass('hidden');
  800. this.newButton.removeClass('hidden');
  801. this.pasteResult.addClass('hidden');
  802. this.message.addClass('hidden');
  803. this.clearText.addClass('hidden');
  804. this.prettyMessage.removeClass('hidden');
  805. },
  806. /**
  807. * If "burn after reading" is checked, disable discussion.
  808. */
  809. changeBurnAfterReading: function()
  810. {
  811. if (this.burnAfterReading.is(':checked') )
  812. {
  813. this.openDisc.addClass('buttondisabled');
  814. this.openDiscussion.attr({checked: false, disabled: true});
  815. }
  816. else
  817. {
  818. this.openDisc.removeClass('buttondisabled');
  819. this.openDiscussion.removeAttr('disabled');
  820. }
  821. },
  822. /**
  823. * Reload the page
  824. *
  825. * @param Event event
  826. */
  827. reloadPage: function(event)
  828. {
  829. event.preventDefault();
  830. window.location.href = this.scriptLocation();
  831. },
  832. /**
  833. * Return raw text
  834. *
  835. * @param Event event
  836. */
  837. rawText: function(event)
  838. {
  839. event.preventDefault();
  840. var paste = this.clearText.html();
  841. var newDoc = document.open('text/html', 'replace');
  842. newDoc.write('<pre>' + paste + '</pre>');
  843. newDoc.close();
  844. },
  845. /**
  846. * Clone the current paste.
  847. *
  848. * @param Event event
  849. */
  850. clonePaste: function(event)
  851. {
  852. event.preventDefault();
  853. this.stateNewPaste();
  854. // Erase the id and the key in url
  855. history.replaceState(document.title, document.title, this.scriptLocation());
  856. this.showStatus('', false);
  857. this.message.text(this.clearText.text());
  858. $('.navbar-toggle').click();
  859. },
  860. /**
  861. * Create a new paste.
  862. */
  863. newPaste: function()
  864. {
  865. this.stateNewPaste();
  866. this.showStatus('', false);
  867. this.message.text('');
  868. $('.navbar-toggle').click();
  869. },
  870. /**
  871. * Display an error message
  872. * (We use the same function for paste and reply to comments)
  873. *
  874. * @param string message : text to display
  875. */
  876. showError: function(message)
  877. {
  878. if (this.status.length)
  879. {
  880. this.status.addClass('errorMessage').text(message);
  881. }
  882. else
  883. {
  884. this.errorMessage.removeClass('hidden');
  885. var content = this.errorMessage.contents();
  886. content[content.length - 1].nodeValue = ' ' + message;
  887. }
  888. this.replyStatus.addClass('errorMessage').text(message);
  889. },
  890. /**
  891. * Display a status message
  892. * (We use the same function for paste and reply to comments)
  893. *
  894. * @param string message : text to display
  895. * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
  896. */
  897. showStatus: function(message, spin)
  898. {
  899. this.replyStatus.removeClass('errorMessage').text(message);
  900. if (!message)
  901. {
  902. this.status.html(' ');
  903. return;
  904. }
  905. if (message == '')
  906. {
  907. this.status.html(' ');
  908. return;
  909. }
  910. this.status.removeClass('errorMessage').text(message);
  911. if (spin)
  912. {
  913. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0 4px 0 0;" />';
  914. this.status.prepend(img);
  915. this.replyStatus.prepend(img);
  916. }
  917. },
  918. /**
  919. * bind events to DOM elements
  920. */
  921. bindEvents: function()
  922. {
  923. this.burnAfterReading.change($.proxy(this.changeBurnAfterReading, this));
  924. this.sendButton.click($.proxy(this.sendData, this));
  925. this.cloneButton.click($.proxy(this.clonePaste, this));
  926. this.rawTextButton.click($.proxy(this.rawText, this));
  927. $('.reloadlink').click($.proxy(this.reloadPage, this));
  928. },
  929. /**
  930. * main application
  931. */
  932. init: function()
  933. {
  934. // hide "no javascript" message
  935. $('#noscript').hide();
  936. // preload jQuery wrapped DOM elements and bind events
  937. this.burnAfterReading = $('#burnafterreading');
  938. this.burnAfterReadingOption = $('#burnafterreadingoption');
  939. this.cipherData = $('#cipherdata');
  940. this.clearText = $('#cleartext');
  941. this.cloneButton = $('#clonebutton');
  942. this.comments = $('#comments');
  943. this.discussion = $('#discussion');
  944. this.errorMessage = $('#errormessage');
  945. this.expiration = $('#expiration');
  946. this.message = $('#message');
  947. this.newButton = $('#newbutton');
  948. this.openDisc = $('#opendisc');
  949. this.openDiscussion = $('#opendiscussion');
  950. this.password = $('#password');
  951. this.passwordInput = $('#passwordinput');
  952. this.pasteResult = $('#pasteresult');
  953. this.prettyMessage = $('#prettymessage');
  954. this.prettyPrint = $('#prettyprint');
  955. this.rawTextButton = $('#rawtextbutton');
  956. this.remainingTime = $('#remainingtime');
  957. this.replyStatus = $('#replystatus');
  958. this.sendButton = $('#sendbutton');
  959. this.status = $('#status');
  960. this.bindEvents();
  961. // Display status returned by php code if any (eg. Paste was properly deleted.)
  962. if (this.status.text().length > 0)
  963. {
  964. this.showStatus(this.status.text(), false);
  965. return;
  966. }
  967. // Keep line height even if content empty.
  968. this.status.html(' ');
  969. // Display an existing paste
  970. if (this.cipherData.text().length > 1)
  971. {
  972. // Missing decryption key in URL?
  973. if (window.location.hash.length == 0)
  974. {
  975. 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?)'));
  976. return;
  977. }
  978. // List of messages to display.
  979. var messages = $.parseJSON(this.cipherData.text());
  980. // Show proper elements on screen.
  981. this.stateExistingPaste();
  982. this.displayMessages(this.pageKey(), messages);
  983. }
  984. // Display error message from php code.
  985. else if (this.errorMessage.text().length > 1)
  986. {
  987. this.showError(this.errorMessage.text());
  988. }
  989. // Create a new paste.
  990. else
  991. {
  992. this.newPaste();
  993. }
  994. }
  995. }
  996. /**
  997. * main application start, called when DOM is fully loaded
  998. * runs zerobin when translations were loaded
  999. */
  1000. i18n.loadTranslations($.proxy(zerobin.init, zerobin));
  1001. });