zerobin.js 51 KB

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