zerobin.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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. this.showStatus(i18n._('Sending paste...'), true);
  715. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  716. var cipherdata = filter.cipher(randomkey, this.passwordInput.val(), this.message.val());
  717. var data_to_send = {
  718. data: cipherdata,
  719. expire: $('#pasteExpiration').val(),
  720. burnafterreading: this.burnAfterReading.is(':checked') ? 1 : 0,
  721. opendiscussion: this.openDiscussion.is(':checked') ? 1 : 0
  722. };
  723. $.post(this.scriptLocation(), data_to_send, function(data)
  724. {
  725. if (data.status == 0) {
  726. zerobin.stateExistingPaste();
  727. var url = zerobin.scriptLocation() + '?' + data.id + '#' + randomkey;
  728. var deleteUrl = zerobin.scriptLocation() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  729. zerobin.showStatus('', false);
  730. zerobin.errorMessage.addClass('hidden');
  731. $('#pastelink').html(i18n._('Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>', url, url));
  732. $('#deletelink').html('<a href="' + deleteUrl + '">' + i18n._('Delete data') + '</a>');
  733. zerobin.pasteResult.removeClass('hidden');
  734. // We pre-select the link so that the user only has to [Ctrl]+[c] the link.
  735. helper.selectText('pasteurl');
  736. helper.setElementText(zerobin.clearText, zerobin.message.val());
  737. helper.setElementText(zerobin.prettyPrint, zerobin.message.val());
  738. // Convert URLs to clickable links.
  739. helper.urls2links(zerobin.clearText);
  740. helper.urls2links(zerobin.prettyPrint);
  741. zerobin.showStatus('', false);
  742. if (typeof prettyPrint == 'function') prettyPrint();
  743. }
  744. else if (data.status==1)
  745. {
  746. zerobin.showError(i18n._('Could not create paste: %s', data.message));
  747. }
  748. else
  749. {
  750. zerobin.showError(i18n._('Could not create paste: %s', i18n._('unknown status')));
  751. }
  752. }, 'json')
  753. .fail(function() {
  754. zerobin.showError(i18n._('Could not create paste: %s', i18n._('server error or not responding')));
  755. });
  756. },
  757. /**
  758. * Put the screen in "New paste" mode.
  759. */
  760. stateNewPaste: function()
  761. {
  762. this.message.text('');
  763. this.cloneButton.addClass('hidden');
  764. this.rawTextButton.addClass('hidden');
  765. this.remainingTime.addClass('hidden');
  766. this.pasteResult.addClass('hidden');
  767. this.clearText.addClass('hidden');
  768. this.discussion.addClass('hidden');
  769. this.prettyMessage.addClass('hidden');
  770. this.sendButton.removeClass('hidden');
  771. this.expiration.removeClass('hidden');
  772. this.burnAfterReadingOption.removeClass('hidden');
  773. this.openDisc.removeClass('hidden');
  774. this.newButton.removeClass('hidden');
  775. this.password.removeClass('hidden');
  776. this.message.removeClass('hidden');
  777. this.message.focus();
  778. },
  779. /**
  780. * Put the screen in "Existing paste" mode.
  781. */
  782. stateExistingPaste: function()
  783. {
  784. this.sendButton.addClass('hidden');
  785. // No "clone" for IE<10.
  786. if ($('#oldienotice').is(":visible"))
  787. {
  788. this.cloneButton.addClass('hidden');
  789. }
  790. else
  791. {
  792. this.cloneButton.removeClass('hidden');
  793. }
  794. this.rawTextButton.removeClass('hidden');
  795. this.expiration.addClass('hidden');
  796. this.burnAfterReadingOption.addClass('hidden');
  797. this.openDisc.addClass('hidden');
  798. this.newButton.removeClass('hidden');
  799. this.pasteResult.addClass('hidden');
  800. this.message.addClass('hidden');
  801. this.clearText.addClass('hidden');
  802. this.prettyMessage.removeClass('hidden');
  803. },
  804. /**
  805. * If "burn after reading" is checked, disable discussion.
  806. */
  807. changeBurnAfterReading: function()
  808. {
  809. if (this.burnAfterReading.is(':checked') )
  810. {
  811. this.openDisc.addClass('buttondisabled');
  812. this.openDiscussion.attr({checked: false, disabled: true});
  813. }
  814. else
  815. {
  816. this.openDisc.removeClass('buttondisabled');
  817. this.openDiscussion.removeAttr('disabled');
  818. }
  819. },
  820. /**
  821. * Reload the page
  822. *
  823. * @param Event event
  824. */
  825. reloadPage: function(event)
  826. {
  827. event.preventDefault();
  828. window.location.href = this.scriptLocation();
  829. },
  830. /**
  831. * Return raw text
  832. *
  833. * @param Event event
  834. */
  835. rawText: function(event)
  836. {
  837. event.preventDefault();
  838. var paste = this.clearText.html();
  839. var newDoc = document.open('text/html', 'replace');
  840. newDoc.write('<pre>' + paste + '</pre>');
  841. newDoc.close();
  842. },
  843. /**
  844. * Clone the current paste.
  845. *
  846. * @param Event event
  847. */
  848. clonePaste: function(event)
  849. {
  850. event.preventDefault();
  851. this.stateNewPaste();
  852. // Erase the id and the key in url
  853. history.replaceState(document.title, document.title, this.scriptLocation());
  854. this.showStatus('', false);
  855. this.message.text(this.clearText.text());
  856. },
  857. /**
  858. * Create a new paste.
  859. */
  860. newPaste: function()
  861. {
  862. this.stateNewPaste();
  863. this.showStatus('', false);
  864. this.message.text('');
  865. },
  866. /**
  867. * Display an error message
  868. * (We use the same function for paste and reply to comments)
  869. *
  870. * @param string message : text to display
  871. */
  872. showError: function(message)
  873. {
  874. if (this.status.length)
  875. {
  876. this.status.addClass('errorMessage').text(message);
  877. }
  878. else
  879. {
  880. this.errorMessage.removeClass('hidden');
  881. var content = this.errorMessage.contents();
  882. content[content.length - 1].nodeValue = ' ' + message;
  883. }
  884. this.replyStatus.addClass('errorMessage').text(message);
  885. },
  886. /**
  887. * Display a status message
  888. * (We use the same function for paste and reply to comments)
  889. *
  890. * @param string message : text to display
  891. * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
  892. */
  893. showStatus: function(message, spin)
  894. {
  895. this.replyStatus.removeClass('errorMessage').text(message);
  896. if (!message)
  897. {
  898. this.status.html(' ');
  899. return;
  900. }
  901. if (message == '')
  902. {
  903. this.status.html(' ');
  904. return;
  905. }
  906. this.status.removeClass('errorMessage').text(message);
  907. if (spin)
  908. {
  909. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0 4px 0 0;" />';
  910. this.status.prepend(img);
  911. this.replyStatus.prepend(img);
  912. }
  913. },
  914. /**
  915. * bind events to DOM elements
  916. */
  917. bindEvents: function()
  918. {
  919. this.burnAfterReading.change($.proxy(this.changeBurnAfterReading, this));
  920. this.sendButton.click($.proxy(this.sendData, this));
  921. this.cloneButton.click($.proxy(this.clonePaste, this));
  922. this.rawTextButton.click($.proxy(this.rawText, this));
  923. $('.reloadlink').click($.proxy(this.reloadPage, this));
  924. },
  925. /**
  926. * main application
  927. */
  928. init: function()
  929. {
  930. // hide "no javascript" message
  931. $('#noscript').hide();
  932. // preload jQuery wrapped DOM elements and bind events
  933. this.burnAfterReading = $('#burnafterreading');
  934. this.burnAfterReadingOption = $('#burnafterreadingoption');
  935. this.cipherData = $('#cipherdata');
  936. this.clearText = $('#cleartext');
  937. this.cloneButton = $('#clonebutton');
  938. this.comments = $('#comments');
  939. this.discussion = $('#discussion');
  940. this.errorMessage = $('#errormessage');
  941. this.expiration = $('#expiration');
  942. this.message = $('#message');
  943. this.newButton = $('#newbutton');
  944. this.openDisc = $('#opendisc');
  945. this.openDiscussion = $('#opendiscussion');
  946. this.password = $('#password');
  947. this.passwordInput = $('#passwordinput');
  948. this.pasteResult = $('#pasteresult');
  949. this.prettyMessage = $('#prettymessage');
  950. this.prettyPrint = $('#prettyprint');
  951. this.rawTextButton = $('#rawtextbutton');
  952. this.remainingTime = $('#remainingtime');
  953. this.replyStatus = $('#replystatus');
  954. this.sendButton = $('#sendbutton');
  955. this.status = $('#status');
  956. this.bindEvents();
  957. // Display status returned by php code if any (eg. Paste was properly deleted.)
  958. if (this.status.text().length > 0)
  959. {
  960. this.showStatus(this.status.text(), false);
  961. return;
  962. }
  963. // Keep line height even if content empty.
  964. this.status.html(' ');
  965. // Display an existing paste
  966. if (this.cipherData.text().length > 1)
  967. {
  968. // Missing decryption key in URL?
  969. if (window.location.hash.length == 0)
  970. {
  971. 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?)'));
  972. return;
  973. }
  974. // List of messages to display.
  975. var messages = $.parseJSON(this.cipherData.text());
  976. // Show proper elements on screen.
  977. this.stateExistingPaste();
  978. this.displayMessages(this.pageKey(), messages);
  979. }
  980. // Display error message from php code.
  981. else if (this.errorMessage.text().length > 1)
  982. {
  983. this.showError(this.errorMessage.text());
  984. }
  985. // Create a new paste.
  986. else
  987. {
  988. this.newPaste();
  989. }
  990. }
  991. }
  992. /**
  993. * main application start, called when DOM is fully loaded
  994. * runs zerobin when translations were loaded
  995. */
  996. i18n.loadTranslations($.proxy(zerobin.init, zerobin));
  997. });