zerobin.js 48 KB

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