zerobin.js 49 KB

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