zerobin.js 48 KB

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