zerobin.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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. // if the attachment is an image, display it
  560. var imagePrefix = 'data:image/';
  561. if (attachment.substring(0, imagePrefix.length) == imagePrefix)
  562. {
  563. this.image.html(
  564. $(document.createElement('img'))
  565. .attr('src', attachment)
  566. .attr('class', 'img-thumbnail')
  567. );
  568. this.image.removeClass('hidden');
  569. }
  570. }
  571. var cleartext = filter.decipher(key, password, comments[0].data);
  572. if (cleartext.length == 0 && password.length == 0 && !comments[0].attachment)
  573. {
  574. password = this.requestPassword();
  575. cleartext = filter.decipher(key, password, comments[0].data);
  576. }
  577. if (cleartext.length == 0 && !comments[0].attachment) throw 'failed to decipher message';
  578. this.passwordInput.val(password);
  579. if (cleartext.length > 0)
  580. {
  581. helper.setElementText(this.clearText, cleartext);
  582. helper.setElementText(this.prettyPrint, cleartext);
  583. this.formatPaste(comments[0].meta.formatter);
  584. }
  585. }
  586. catch(err)
  587. {
  588. this.clearText.addClass('hidden');
  589. this.prettyMessage.addClass('hidden');
  590. this.cloneButton.addClass('hidden');
  591. this.showError(i18n._('Could not decrypt data (Wrong key?)'));
  592. return;
  593. }
  594. }
  595. // Display paste expiration / for your eyes only.
  596. if (comments[0].meta.expire_date)
  597. {
  598. var expiration = helper.secondsToHuman(comments[0].meta.remaining_time),
  599. expirationLabel = [
  600. 'This document will expire in %d ' + expiration[1] + '.',
  601. 'This document will expire in %d ' + expiration[1] + 's.'
  602. ];
  603. helper.setMessage(this.remainingTime, i18n._(expirationLabel, expiration[0]));
  604. this.remainingTime.removeClass('foryoureyesonly')
  605. .removeClass('hidden');
  606. }
  607. if (comments[0].meta.burnafterreading)
  608. {
  609. $.get(this.scriptLocation() + '?pasteid=' + this.pasteID() + '&deletetoken=burnafterreading', 'json')
  610. .fail(function() {
  611. zerobin.showError(i18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  612. });
  613. helper.setMessage(this.remainingTime, i18n._(
  614. 'FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.'
  615. ));
  616. this.remainingTime.addClass('foryoureyesonly')
  617. .removeClass('hidden');
  618. // Discourage cloning (as it can't really be prevented).
  619. this.cloneButton.addClass('hidden');
  620. }
  621. // If the discussion is opened on this paste, display it.
  622. if (comments[0].meta.opendiscussion)
  623. {
  624. this.comments.html('');
  625. // iterate over comments
  626. for (var i = 1; i < comments.length; i++)
  627. {
  628. var place = this.comments;
  629. var comment=comments[i];
  630. var cleartext = '[' + i18n._('Could not decrypt comment; Wrong key?') + ']';
  631. try
  632. {
  633. cleartext = filter.decipher(key, password, comment.data);
  634. }
  635. catch(err)
  636. {}
  637. // If parent comment exists, display below (CSS will automatically shift it right.)
  638. var cname = '#comment_' + comment.meta.parentid;
  639. // If the element exists in page
  640. if ($(cname).length)
  641. {
  642. place = $(cname);
  643. }
  644. var divComment = $('<article><div class="comment" id="comment_' + comment.meta.commentid+'">'
  645. + '<div class="commentmeta"><span class="nickname"></span><span class="commentdate"></span></div><div class="commentdata"></div>'
  646. + '<button class="btn btn-default btn-sm">' + i18n._('Reply') + '</button>'
  647. + '</div></article>');
  648. divComment.find('button').click({commentid: comment.meta.commentid}, $.proxy(this.openReply, this));
  649. helper.setElementText(divComment.find('div.commentdata'), cleartext);
  650. // Convert URLs to clickable links in comment.
  651. helper.urls2links(divComment.find('div.commentdata'));
  652. // Try to get optional nickname:
  653. var nick = filter.decipher(key, password, comment.meta.nickname);
  654. if (nick.length > 0)
  655. {
  656. divComment.find('span.nickname').text(nick);
  657. }
  658. else
  659. {
  660. divComment.find('span.nickname').html('<i>' + i18n._('Anonymous') + '</i>');
  661. }
  662. divComment.find('span.commentdate')
  663. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  664. .attr('title', 'CommentID: ' + comment.meta.commentid);
  665. // If an avatar is available, display it.
  666. if (comment.meta.vizhash)
  667. {
  668. divComment.find('span.nickname')
  669. .before(
  670. '<img src="' + comment.meta.vizhash + '" class="vizhash" title="' +
  671. i18n._('Anonymous avatar (Vizhash of the IP address)') + '" /> '
  672. );
  673. }
  674. place.append(divComment);
  675. }
  676. var divComment = $(
  677. '<div class="comment"><button class="btn btn-default btn-sm">' +
  678. i18n._('Add comment') + '</button></div>'
  679. );
  680. divComment.find('button').click({commentid: this.pasteID()}, $.proxy(this.openReply, this));
  681. this.comments.append(divComment);
  682. this.discussion.removeClass('hidden');
  683. }
  684. },
  685. /**
  686. * Open the comment entry when clicking the "Reply" button of a comment.
  687. *
  688. * @param Event event
  689. */
  690. openReply: function(event)
  691. {
  692. event.preventDefault();
  693. var source = $(event.target),
  694. commentid = event.data.commentid,
  695. hint = i18n._('Optional nickname...');
  696. // Remove any other reply area.
  697. $('div.reply').remove();
  698. var reply = $(
  699. '<div class="reply">' +
  700. '<input type="text" id="nickname" class="form-control" title="' + hint + '" placeholder="' + hint + '" />' +
  701. '<textarea id="replymessage" class="replymessage form-control" cols="80" rows="7"></textarea>' +
  702. '<br /><button id="replybutton" class="btn btn-default btn-sm">' + i18n._('Post comment') + '</button>' +
  703. '<div id="replystatus"> </div>' +
  704. '</div>'
  705. );
  706. reply.find('button').click({parentid: commentid}, $.proxy(this.sendComment, this));
  707. source.after(reply);
  708. $('#replymessage').focus();
  709. },
  710. /**
  711. * Send a reply in a discussion.
  712. *
  713. * @param Event event
  714. */
  715. sendComment: function(event)
  716. {
  717. event.preventDefault();
  718. this.errorMessage.addClass('hidden');
  719. // Do not send if no data.
  720. var replyMessage = $('#replymessage');
  721. if (replyMessage.val().length == 0) return;
  722. this.showStatus(i18n._('Sending comment...'), true);
  723. var parentid = event.data.parentid;
  724. var cipherdata = filter.cipher(this.pageKey(), this.passwordInput.val(), replyMessage.val());
  725. var ciphernickname = '';
  726. var nick = $('#nickname').val();
  727. if (nick != '')
  728. {
  729. ciphernickname = filter.cipher(this.pageKey(), this.passwordInput.val(), nick);
  730. }
  731. var data_to_send = {
  732. data: cipherdata,
  733. parentid: parentid,
  734. pasteid: this.pasteID(),
  735. nickname: ciphernickname
  736. };
  737. $.post(this.scriptLocation(), data_to_send, function(data)
  738. {
  739. if (data.status == 0)
  740. {
  741. zerobin.showStatus(i18n._('Comment posted.'), false);
  742. $.get(zerobin.scriptLocation() + '?' + zerobin.pasteID() + '&json', function(data)
  743. {
  744. if (data.status == 0)
  745. {
  746. zerobin.displayMessages(zerobin.pageKey(), data.messages);
  747. }
  748. else if (data.status == 1)
  749. {
  750. zerobin.showError(i18n._('Could not refresh display: %s', data.message));
  751. }
  752. else
  753. {
  754. zerobin.showError(i18n._('Could not refresh display: %s', i18n._('unknown status')));
  755. }
  756. }, 'json')
  757. .fail(function() {
  758. zerobin.showError(i18n._('Could not refresh display: %s', i18n._('server error or not responding')));
  759. });
  760. }
  761. else if (data.status == 1)
  762. {
  763. zerobin.showError(i18n._('Could not post comment: %s', data.message));
  764. }
  765. else
  766. {
  767. zerobin.showError(i18n._('Could not post comment: %s', i18n._('unknown status')));
  768. }
  769. }, 'json')
  770. .fail(function() {
  771. zerobin.showError(i18n._('Could not post comment: %s', i18n._('server error or not responding')));
  772. });
  773. },
  774. /**
  775. * Send a new paste to server
  776. *
  777. * @param Event event
  778. */
  779. sendData: function(event)
  780. {
  781. event.preventDefault();
  782. var files = document.getElementById('file').files; // FileList object
  783. // Do not send if no data.
  784. if (this.message.val().length == 0 && !(files && files[0])) return;
  785. // If sjcl has not collected enough entropy yet, display a message.
  786. if (!sjcl.random.isReady())
  787. {
  788. this.showStatus(i18n._('Sending paste (Please move your mouse for more entropy)...'), true);
  789. sjcl.random.addEventListener('seeded', function() {
  790. this.sendData(event);
  791. });
  792. return;
  793. }
  794. $('.navbar-toggle').click();
  795. this.password.addClass('hidden');
  796. this.showStatus(i18n._('Sending paste...'), true);
  797. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  798. var cipherdata_attachment;
  799. var password = this.passwordInput.val();
  800. if(files && files[0])
  801. {
  802. if(typeof FileReader === undefined)
  803. {
  804. this.showError(i18n._('Your browser does not support uploading encrypted files. Please use a newer browser.'));
  805. return;
  806. }
  807. var reader = new FileReader();
  808. // Closure to capture the file information.
  809. reader.onload = (function(theFile)
  810. {
  811. return function(e) {
  812. zerobin.sendDataContinue(
  813. randomkey,
  814. filter.cipher(randomkey, password, e.target.result),
  815. filter.cipher(randomkey, password, theFile.name)
  816. );
  817. }
  818. })(files[0]);
  819. reader.readAsDataURL(files[0]);
  820. }
  821. else if(this.attachmentLink.attr('href'))
  822. {
  823. this.sendDataContinue(
  824. randomkey,
  825. filter.cipher(randomkey, password, this.attachmentLink.attr('href')),
  826. this.attachmentLink.attr('download')
  827. );
  828. }
  829. else
  830. {
  831. this.sendDataContinue(randomkey, '', '');
  832. }
  833. },
  834. /**
  835. * Send a new paste to server, step 2
  836. *
  837. * @param Event event
  838. */
  839. sendDataContinue: function(randomkey, cipherdata_attachment, cipherdata_attachment_name)
  840. {
  841. var cipherdata = filter.cipher(randomkey, this.passwordInput.val(), this.message.val());
  842. var data_to_send = {
  843. data: cipherdata,
  844. expire: $('#pasteExpiration').val(),
  845. formatter: $('#pasteFormatter').val(),
  846. burnafterreading: this.burnAfterReading.is(':checked') ? 1 : 0,
  847. opendiscussion: this.openDiscussion.is(':checked') ? 1 : 0
  848. };
  849. if (cipherdata_attachment.length > 0)
  850. {
  851. data_to_send.attachment = cipherdata_attachment;
  852. if (cipherdata_attachment_name.length > 0)
  853. {
  854. data_to_send.attachmentname = cipherdata_attachment_name;
  855. }
  856. }
  857. $.post(this.scriptLocation(), data_to_send, function(data)
  858. {
  859. if (data.status == 0) {
  860. zerobin.stateExistingPaste();
  861. var url = zerobin.scriptLocation() + '?' + data.id + '#' + randomkey;
  862. var deleteUrl = zerobin.scriptLocation() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  863. zerobin.showStatus('', false);
  864. zerobin.errorMessage.addClass('hidden');
  865. $('#pastelink').html(i18n._('Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>', url, url));
  866. $('#deletelink').html('<a href="' + deleteUrl + '">' + i18n._('Delete data') + '</a>');
  867. zerobin.pasteResult.removeClass('hidden');
  868. // We pre-select the link so that the user only has to [Ctrl]+[c] the link.
  869. helper.selectText('pasteurl');
  870. zerobin.showStatus('', false);
  871. helper.setElementText(zerobin.clearText, zerobin.message.val());
  872. helper.setElementText(zerobin.prettyPrint, zerobin.message.val());
  873. zerobin.formatPaste(data_to_send.formatter);
  874. }
  875. else if (data.status==1)
  876. {
  877. zerobin.showError(i18n._('Could not create paste: %s', data.message));
  878. }
  879. else
  880. {
  881. zerobin.showError(i18n._('Could not create paste: %s', i18n._('unknown status')));
  882. }
  883. }, 'json')
  884. .fail(function() {
  885. zerobin.showError(i18n._('Could not create paste: %s', i18n._('server error or not responding')));
  886. });
  887. },
  888. /**
  889. * Put the screen in "New paste" mode.
  890. */
  891. stateNewPaste: function()
  892. {
  893. this.message.text('');
  894. this.attachment.addClass('hidden');
  895. this.cloneButton.addClass('hidden');
  896. this.rawTextButton.addClass('hidden');
  897. this.remainingTime.addClass('hidden');
  898. this.pasteResult.addClass('hidden');
  899. this.clearText.addClass('hidden');
  900. this.discussion.addClass('hidden');
  901. this.prettyMessage.addClass('hidden');
  902. this.sendButton.removeClass('hidden');
  903. this.expiration.removeClass('hidden');
  904. this.formatter.removeClass('hidden');
  905. this.burnAfterReadingOption.removeClass('hidden');
  906. this.openDisc.removeClass('hidden');
  907. this.newButton.removeClass('hidden');
  908. this.password.removeClass('hidden');
  909. this.attach.removeClass('hidden');
  910. this.message.removeClass('hidden');
  911. this.message.focus();
  912. },
  913. /**
  914. * Put the screen in "Existing paste" mode.
  915. */
  916. stateExistingPaste: function()
  917. {
  918. this.sendButton.addClass('hidden');
  919. // No "clone" for IE<10.
  920. if ($('#oldienotice').is(":visible"))
  921. {
  922. this.cloneButton.addClass('hidden');
  923. }
  924. else
  925. {
  926. this.cloneButton.removeClass('hidden');
  927. }
  928. this.rawTextButton.removeClass('hidden');
  929. this.attach.addClass('hidden');
  930. this.expiration.addClass('hidden');
  931. this.formatter.addClass('hidden');
  932. this.burnAfterReadingOption.addClass('hidden');
  933. this.openDisc.addClass('hidden');
  934. this.newButton.removeClass('hidden');
  935. this.pasteResult.addClass('hidden');
  936. this.message.addClass('hidden');
  937. this.clearText.addClass('hidden');
  938. this.prettyMessage.addClass('hidden');
  939. },
  940. /**
  941. * If "burn after reading" is checked, disable discussion.
  942. */
  943. changeBurnAfterReading: function()
  944. {
  945. if (this.burnAfterReading.is(':checked') )
  946. {
  947. this.openDisc.addClass('buttondisabled');
  948. this.openDiscussion.attr({checked: false, disabled: true});
  949. }
  950. else
  951. {
  952. this.openDisc.removeClass('buttondisabled');
  953. this.openDiscussion.removeAttr('disabled');
  954. }
  955. },
  956. /**
  957. * Reload the page
  958. *
  959. * @param Event event
  960. */
  961. reloadPage: function(event)
  962. {
  963. event.preventDefault();
  964. window.location.href = this.scriptLocation();
  965. },
  966. /**
  967. * Return raw text
  968. *
  969. * @param Event event
  970. */
  971. rawText: function(event)
  972. {
  973. event.preventDefault();
  974. var paste = this.clearText.html();
  975. var newDoc = document.open('text/html', 'replace');
  976. newDoc.write('<pre>' + paste + '</pre>');
  977. newDoc.close();
  978. },
  979. /**
  980. * Clone the current paste.
  981. *
  982. * @param Event event
  983. */
  984. clonePaste: function(event)
  985. {
  986. event.preventDefault();
  987. this.stateNewPaste();
  988. // Erase the id and the key in url
  989. history.replaceState(document.title, document.title, this.scriptLocation());
  990. this.showStatus('', false);
  991. if (this.attachmentLink.attr('href'))
  992. {
  993. this.clonedFile.removeClass('hidden');
  994. this.fileWrap.addClass('hidden');
  995. }
  996. this.message.text(this.clearText.text());
  997. $('.navbar-toggle').click();
  998. },
  999. /**
  1000. * Create a new paste.
  1001. */
  1002. newPaste: function()
  1003. {
  1004. this.stateNewPaste();
  1005. this.showStatus('', false);
  1006. this.message.text('');
  1007. $('.navbar-toggle').click();
  1008. },
  1009. /**
  1010. * Removes an attachment.
  1011. */
  1012. removeAttachment: function()
  1013. {
  1014. this.clonedFile.addClass('hidden');
  1015. // removes the saved decrypted file data
  1016. this.attachmentLink.attr('href', '');
  1017. // the only way to deselect the file is to recreate the input
  1018. this.fileWrap.html(this.fileWrap.html());
  1019. this.fileWrap.removeClass('hidden');
  1020. },
  1021. /**
  1022. * Display an error message
  1023. * (We use the same function for paste and reply to comments)
  1024. *
  1025. * @param string message : text to display
  1026. */
  1027. showError: function(message)
  1028. {
  1029. if (this.status.length)
  1030. {
  1031. this.status.addClass('errorMessage').text(message);
  1032. }
  1033. else
  1034. {
  1035. this.errorMessage.removeClass('hidden');
  1036. helper.setMessage(this.errorMessage, message);
  1037. }
  1038. this.replyStatus.addClass('errorMessage').text(message);
  1039. },
  1040. /**
  1041. * Display a status message
  1042. * (We use the same function for paste and reply to comments)
  1043. *
  1044. * @param string message : text to display
  1045. * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
  1046. */
  1047. showStatus: function(message, spin)
  1048. {
  1049. this.replyStatus.removeClass('errorMessage').text(message);
  1050. if (!message)
  1051. {
  1052. this.status.html(' ');
  1053. return;
  1054. }
  1055. if (message == '')
  1056. {
  1057. this.status.html(' ');
  1058. return;
  1059. }
  1060. this.status.removeClass('errorMessage').text(message);
  1061. if (spin)
  1062. {
  1063. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0 4px 0 0;" />';
  1064. this.status.prepend(img);
  1065. this.replyStatus.prepend(img);
  1066. }
  1067. },
  1068. /**
  1069. * bind events to DOM elements
  1070. */
  1071. bindEvents: function()
  1072. {
  1073. this.burnAfterReading.change($.proxy(this.changeBurnAfterReading, this));
  1074. this.sendButton.click($.proxy(this.sendData, this));
  1075. this.cloneButton.click($.proxy(this.clonePaste, this));
  1076. this.rawTextButton.click($.proxy(this.rawText, this));
  1077. this.fileRemoveButton.click($.proxy(this.removeAttachment, this));
  1078. $('.reloadlink').click($.proxy(this.reloadPage, this));
  1079. },
  1080. /**
  1081. * main application
  1082. */
  1083. init: function()
  1084. {
  1085. // hide "no javascript" message
  1086. $('#noscript').hide();
  1087. // preload jQuery wrapped DOM elements and bind events
  1088. this.attach = $('#attach');
  1089. this.attachment = $('#attachment');
  1090. this.attachmentLink = $('#attachment a');
  1091. this.burnAfterReading = $('#burnafterreading');
  1092. this.burnAfterReadingOption = $('#burnafterreadingoption');
  1093. this.cipherData = $('#cipherdata');
  1094. this.clearText = $('#cleartext');
  1095. this.cloneButton = $('#clonebutton');
  1096. this.clonedFile = $('#clonedfile');
  1097. this.comments = $('#comments');
  1098. this.discussion = $('#discussion');
  1099. this.errorMessage = $('#errormessage');
  1100. this.expiration = $('#expiration');
  1101. this.fileRemoveButton = $('#fileremovebutton');
  1102. this.fileWrap = $('#filewrap');
  1103. this.formatter = $('#formatter');
  1104. this.image = $('#image');
  1105. this.message = $('#message');
  1106. this.newButton = $('#newbutton');
  1107. this.openDisc = $('#opendisc');
  1108. this.openDiscussion = $('#opendiscussion');
  1109. this.password = $('#password');
  1110. this.passwordInput = $('#passwordinput');
  1111. this.pasteResult = $('#pasteresult');
  1112. this.prettyMessage = $('#prettymessage');
  1113. this.prettyPrint = $('#prettyprint');
  1114. this.rawTextButton = $('#rawtextbutton');
  1115. this.remainingTime = $('#remainingtime');
  1116. this.replyStatus = $('#replystatus');
  1117. this.sendButton = $('#sendbutton');
  1118. this.status = $('#status');
  1119. this.bindEvents();
  1120. // Display status returned by php code if any (eg. Paste was properly deleted.)
  1121. if (this.status.text().length > 0)
  1122. {
  1123. this.showStatus(this.status.text(), false);
  1124. return;
  1125. }
  1126. // Keep line height even if content empty.
  1127. this.status.html(' ');
  1128. // Display an existing paste
  1129. if (this.cipherData.text().length > 1)
  1130. {
  1131. // Missing decryption key in URL?
  1132. if (window.location.hash.length == 0)
  1133. {
  1134. 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?)'));
  1135. return;
  1136. }
  1137. // List of messages to display.
  1138. var messages = $.parseJSON(this.cipherData.text());
  1139. // Show proper elements on screen.
  1140. this.stateExistingPaste();
  1141. this.displayMessages(this.pageKey(), messages);
  1142. }
  1143. // Display error message from php code.
  1144. else if (this.errorMessage.text().length > 1)
  1145. {
  1146. this.showError(this.errorMessage.text());
  1147. }
  1148. // Create a new paste.
  1149. else
  1150. {
  1151. this.newPaste();
  1152. }
  1153. }
  1154. }
  1155. /**
  1156. * main application start, called when DOM is fully loaded
  1157. * runs zerobin when translations were loaded
  1158. */
  1159. i18n.loadTranslations($.proxy(zerobin.init, zerobin));
  1160. });