zerobin.js 44 KB

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