zerobin.js 38 KB

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