zerobin.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /**
  2. * ZeroBin 0.15
  3. *
  4. * @link http://sebsauvage.net/wiki/doku.php?id=php:zerobin
  5. * @author sebsauvage
  6. */
  7. // Immediately start random number generator collector.
  8. sjcl.random.startCollectors();
  9. /**
  10. * Converts a duration (in seconds) into human readable format.
  11. *
  12. * @param int seconds
  13. * @return string
  14. */
  15. function secondsToHuman(seconds)
  16. {
  17. if (seconds<60) { var v=Math.floor(seconds); return v+' second'+((v>1)?'s':''); }
  18. if (seconds<60*60) { var v=Math.floor(seconds/60); return v+' minute'+((v>1)?'s':''); }
  19. if (seconds<60*60*24) { var v=Math.floor(seconds/(60*60)); return v+' hour'+((v>1)?'s':''); }
  20. // If less than 2 months, display in days:
  21. if (seconds<60*60*24*60) { var v=Math.floor(seconds/(60*60*24)); return v+' day'+((v>1)?'s':''); }
  22. var v=Math.floor(seconds/(60*60*24*30)); return v+' month'+((v>1)?'s':'');
  23. }
  24. /**
  25. * Compress a message (deflate compression). Returns base64 encoded data.
  26. *
  27. * @param string message
  28. * @return base64 string data
  29. */
  30. function compress(message) {
  31. return Base64.toBase64( RawDeflate.deflate( Base64.utob(message) ) );
  32. }
  33. /**
  34. * Decompress a message compressed with compress().
  35. */
  36. function decompress(data) {
  37. return Base64.btou( RawDeflate.inflate( Base64.fromBase64(data) ) );
  38. }
  39. /**
  40. * Compress, then encrypt message with key.
  41. *
  42. * @param string key
  43. * @param string message
  44. * @return encrypted string data
  45. */
  46. function zeroCipher(key, message) {
  47. return sjcl.encrypt(key,compress(message));
  48. }
  49. /**
  50. * Decrypt message with key, then decompress.
  51. *
  52. * @param key
  53. * @param encrypted string data
  54. * @return string readable message
  55. */
  56. function zeroDecipher(key, data) {
  57. return decompress(sjcl.decrypt(key,data));
  58. }
  59. /**
  60. * @return the current script location (without search or hash part of the URL).
  61. * eg. http://server.com/zero/?aaaa#bbbb --> http://server.com/zero/
  62. */
  63. function scriptLocation() {
  64. return window.location.href.substring(0,window.location.href.length
  65. -window.location.search.length -window.location.hash.length);
  66. }
  67. /**
  68. * @return the paste unique identifier from the URL
  69. * eg. 'c05354954c49a487'
  70. */
  71. function pasteID() {
  72. return window.location.search.substring(1);
  73. }
  74. /**
  75. * Set text of a DOM element (required for IE)
  76. * This is equivalent to element.text(text)
  77. * @param object element : a DOM element.
  78. * @param string text : the text to enter.
  79. */
  80. function setElementText(element, text) {
  81. // For IE<10.
  82. if ($('div#oldienotice').is(":visible")) {
  83. // IE<10 do not support white-space:pre-wrap; so we have to do this BIG UGLY STINKING THING.
  84. element.text(text.replace(/\n/ig,'{BIG_UGLY_STINKING_THING__OH_GOD_I_HATE_IE}'));
  85. element.html(element.text().replace(/{BIG_UGLY_STINKING_THING__OH_GOD_I_HATE_IE}/ig,"\r\n<br>"));
  86. }
  87. // for other (sane) browsers:
  88. else {
  89. element.text(text);
  90. }
  91. }
  92. /**
  93. * Show decrypted text in the display area, including discussion (if open)
  94. *
  95. * @param string key : decryption key
  96. * @param array comments : Array of messages to display (items = array with keys ('data','meta')
  97. */
  98. function displayMessages(key, comments) {
  99. try { // Try to decrypt the paste.
  100. var cleartext = zeroDecipher(key, comments[0].data);
  101. } catch(err) {
  102. $('div#cleartext').hide();
  103. $('button#clonebutton').hide();
  104. showError('Could not decrypt data (Wrong key ?)');
  105. return;
  106. }
  107. setElementText($('div#cleartext'), cleartext);
  108. urls2links($('div#cleartext')); // Convert URLs to clickable links.
  109. // Display paste expiration.
  110. if (comments[0].meta.expire_date) $('div#remainingtime').removeClass('foryoureyesonly').text('This document will expire in '+secondsToHuman(comments[0].meta.remaining_time)+'.').show();
  111. if (comments[0].meta.burnafterreading) {
  112. $('div#remainingtime').addClass('foryoureyesonly').text('FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.').show();
  113. $('button#clonebutton').hide(); // Discourage cloning (as it can't really be prevented).
  114. }
  115. // If the discussion is opened on this paste, display it.
  116. if (comments[0].meta.opendiscussion) {
  117. $('div#comments').html('');
  118. // For each comment.
  119. for (var i = 1; i < comments.length; i++) {
  120. var comment=comments[i];
  121. var cleartext="[Could not decrypt comment ; Wrong key ?]";
  122. try {
  123. cleartext = zeroDecipher(key, comment.data);
  124. } catch(err) { }
  125. var place = $('div#comments');
  126. // If parent comment exists, display below (CSS will automatically shift it right.)
  127. var cname = 'div#comment_'+comment.meta.parentid
  128. // If the element exists in page
  129. if ($(cname).length) {
  130. place = $(cname);
  131. }
  132. var divComment = $('<div class="comment" id="comment_' + comment.meta.commentid+'">'
  133. + '<div class="commentmeta"><span class="nickname"></span><span class="commentdate"></span></div><div class="commentdata"></div>'
  134. + '<button onclick="open_reply($(this),\'' + comment.meta.commentid + '\');return false;">Reply</button>'
  135. + '</div>');
  136. setElementText(divComment.find('div.commentdata'), cleartext);
  137. // Convert URLs to clickable links in comment.
  138. urls2links(divComment.find('div.commentdata'));
  139. divComment.find('span.nickname').html('<i>(Anonymous)</i>');
  140. // Try to get optional nickname:
  141. try {
  142. divComment.find('span.nickname').text(zeroDecipher(key, comment.meta.nickname));
  143. } catch(err) { }
  144. divComment.find('span.commentdate').text(' ('+(new Date(comment.meta.postdate*1000).toUTCString())+')').attr('title','CommentID: ' + comment.meta.commentid);
  145. // If an avatar is available, display it.
  146. if (comment.meta.vizhash) {
  147. divComment.find('span.nickname').before('<img src="' + comment.meta.vizhash + '" class="vizhash" title="Anonymous avatar (Vizhash of the IP address)" />');
  148. }
  149. place.append(divComment);
  150. }
  151. $('div#comments').append('<div class="comment"><button onclick="open_reply($(this),\'' + pasteID() + '\');return false;">Add comment</button></div>');
  152. $('div#discussion').show();
  153. }
  154. }
  155. /**
  156. * Open the comment entry when clicking the "Reply" button of a comment.
  157. * @param object source : element which emitted the event.
  158. * @param string commentid = identifier of the comment we want to reply to.
  159. */
  160. function open_reply(source, commentid) {
  161. $('div.reply').remove(); // Remove any other reply area.
  162. source.after('<div class="reply">'
  163. + '<input type="text" id="nickname" title="Optional nickname..." value="Optional nickname..." />'
  164. + '<textarea id="replymessage" class="replymessage" cols="80" rows="7"></textarea>'
  165. + '<br><button id="replybutton" onclick="send_comment(\'' + commentid + '\');return false;">Post comment</button>'
  166. + '<div id="replystatus">&nbsp;</div>'
  167. + '</div>');
  168. $('input#nickname').focus(function() {
  169. $(this).css('color', '#000');
  170. if ($(this).val() == $(this).attr('title')) {
  171. $(this).val('');
  172. }
  173. });
  174. $('textarea#replymessage').focus();
  175. }
  176. /**
  177. * Send a reply in a discussion.
  178. * @param string parentid : the comment identifier we want to send a reply to.
  179. */
  180. function send_comment(parentid) {
  181. // Do not send if no data.
  182. if ($('textarea#replymessage').val().length==0) {
  183. return;
  184. }
  185. showStatus('Sending comment...', spin=true);
  186. var cipherdata = zeroCipher(pageKey(), $('textarea#replymessage').val());
  187. var ciphernickname = '';
  188. var nick=$('input#nickname').val();
  189. if (nick != '' && nick != 'Optional nickname...') {
  190. ciphernickname = ciphernickname = zeroCipher(pageKey(), nick);
  191. }
  192. var data_to_send = { data:cipherdata,
  193. parentid: parentid,
  194. pasteid: pasteID(),
  195. nickname: ciphernickname
  196. };
  197. $
  198. .post(scriptLocation(), data_to_send, 'json')
  199. .error(function() {
  200. showError('Comment could not be sent (serveur error or not responding).');
  201. })
  202. .success(function(data) {
  203. if (data.status == 0) {
  204. showStatus('Comment posted.');
  205. location.reload();
  206. }
  207. else if (data.status==1) {
  208. showError('Could not post comment: '+data.message);
  209. }
  210. else {
  211. showError('Could not post comment.');
  212. }
  213. });
  214. }
  215. /**
  216. * Send a new paste to server
  217. */
  218. function send_data() {
  219. // Do not send if no data.
  220. if ($('textarea#message').val().length == 0) {
  221. return;
  222. }
  223. showStatus('Sending paste...', spin=true);
  224. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  225. var cipherdata = zeroCipher(randomkey, $('textarea#message').val());
  226. var data_to_send = { data: cipherdata,
  227. expire: $('select#pasteExpiration').val(),
  228. opendiscussion: $('input#opendiscussion').is(':checked') ? 1 : 0
  229. };
  230. $
  231. .post(scriptLocation(), data_to_send, 'json')
  232. .error(function() {
  233. showError('Data could not be sent (serveur error or not responding).');
  234. })
  235. .success(function(data) {
  236. if (data.status == 0) {
  237. stateExistingPaste();
  238. var url = scriptLocation() + "?" + data.id + '#' + randomkey;
  239. showStatus('');
  240. $('div#pastelink').html('Your paste is <a href="' + url + '">' + url + '</a>');
  241. $('div#pastelink')
  242. .append('&nbsp;&nbsp;<button id="shortenbutton" onclick="document.location=\'' + shortenUrl(url) + '\'"><img src="lib/icon_shorten.png" width="13" height="15" />Shorten URL</button>')
  243. .show();
  244. setElementText($('div#cleartext'), $('textarea#message').val());
  245. urls2links($('div#cleartext'));
  246. showStatus('');
  247. }
  248. else if (data.status==1) {
  249. showError('Could not create paste: '+data.message);
  250. }
  251. else {
  252. showError('Could not create paste.');
  253. }
  254. });
  255. }
  256. /**
  257. * Put the screen in "New paste" mode.
  258. */
  259. function stateNewPaste() {
  260. $('#sendbutton').show();
  261. $('#clonebutton').hide();
  262. $('div#expiration').show();
  263. $('div#remainingtime').hide();
  264. $('div#language').hide(); // $('#language').show();
  265. $('input#password').hide(); //$('#password').show();
  266. $('div#opendisc').show();
  267. $('#newbutton').show();
  268. $('div#pastelink').hide();
  269. $('textarea#message').text('');
  270. $('textarea#message').show();
  271. $('div#cleartext').hide();
  272. $('div#message').focus();
  273. $('div#discussion').hide();
  274. }
  275. /**
  276. * Put the screen in "Existing paste" mode.
  277. */
  278. function stateExistingPaste() {
  279. $('#sendbutton').hide();
  280. // No "clone" for IE<10.
  281. if (!$('div#oldienotice').is(":visible")) {
  282. $('button#clonebutton').show();
  283. }
  284. /**
  285. * @FIXME
  286. */
  287. $('#clonebutton').show();
  288. $('div#expiration').hide();
  289. $('div#language').hide();
  290. $('input#password').hide();
  291. $('div#opendisc').hide();
  292. $('#newbutton').show();
  293. $('div#pastelink').hide();
  294. $('textarea#message').hide();
  295. $('div#cleartext').show();
  296. }
  297. /**
  298. * Clone the current paste.
  299. */
  300. function clonePaste() {
  301. stateNewPaste();
  302. showStatus('');
  303. $('textarea#message').text($('div#cleartext').text());
  304. }
  305. /**
  306. * Create a new paste.
  307. */
  308. function newPaste() {
  309. stateNewPaste();
  310. showStatus('');
  311. $('textarea#message').text('');
  312. }
  313. /**
  314. * Display an error message
  315. * (We use the same function for paste and reply to comments)
  316. */
  317. function showError(message) {
  318. $('div#status').addClass('errorMessage').text(message);
  319. $('div#replystatus').addClass('errorMessage').text(message);
  320. }
  321. /**
  322. * Display status
  323. * (We use the same function for paste and reply to comments)
  324. *
  325. * @param string message : text to display
  326. * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
  327. */
  328. function showStatus(message, spin) {
  329. $('div#replystatus').removeClass('errorMessage');
  330. $('div#replystatus').text(message);
  331. if (!message) {
  332. $('div#status').html('&nbsp');
  333. return;
  334. }
  335. if (message == '') {
  336. $('div#status').html('&nbsp');
  337. return;
  338. }
  339. $('div#status').removeClass('errorMessage');
  340. $('div#status').text(message);
  341. if (spin) {
  342. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0px 4px 0px 0px;" />';
  343. $('div#status').prepend(img);
  344. $('div#replystatus').prepend(img);
  345. }
  346. }
  347. /**
  348. * Generate link to URL shortener.
  349. */
  350. function shortenUrl(url) {
  351. return 'http://snipurl.com/site/snip?link=' + encodeURIComponent(url);
  352. }
  353. /**
  354. * Convert URLs to clickable links.
  355. * URLs to handle:
  356. * <code>
  357. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  358. * http://localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  359. * http://user:password@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  360. * </code>
  361. *
  362. * @param object element : a jQuery DOM element.
  363. * @FIXME: add ppa & apt links.
  364. */
  365. function urls2links(element) {
  366. var re = /((http|https|ftp):\/\/[\w?=&.\/-;#@~%+-]+(?![\w\s?&.\/;#~%"=-]*>))/ig;
  367. element.html(element.html().replace(re,'<a href="$1" rel="nofollow">$1</a>'));
  368. var re = /((magnet):[\w?=&.\/-;#@~%+-]+)/ig;
  369. element.html(element.html().replace(re,'<a href="$1">$1</a>'));
  370. }
  371. /**
  372. * Return the deciphering key stored in anchor part of the URL
  373. */
  374. function pageKey() {
  375. var key = window.location.hash.substring(1); // Get key
  376. // Some stupid web 2.0 services and redirectors add data AFTER the anchor
  377. // (such as &utm_source=...).
  378. // We will strip any additional data.
  379. // First, strip everything after the equal sign (=) which signals end of base64 string.
  380. i = key.indexOf('='); if (i>-1) { key = key.substring(0,i+1); }
  381. // If the equal sign was not present, some parameters may remain:
  382. i = key.indexOf('&'); if (i>-1) { key = key.substring(0,i); }
  383. // Then add trailing equal sign if it's missing
  384. if (key.charAt(key.length-1)!=='=') key+='=';
  385. return key;
  386. }
  387. $(function() {
  388. $('select#pasteExpiration').change(function() {
  389. if ($(this).val() == 'burn') {
  390. $('div#opendisc').addClass('buttondisabled');
  391. $('input#opendiscussion').attr('disabled',true);
  392. }
  393. else {
  394. $('div#opendisc').removeClass('buttondisabled');
  395. $('input#opendiscussion').removeAttr('disabled');
  396. }
  397. });
  398. // Display an existing paste
  399. if ($('div#cipherdata').text().length > 1) {
  400. // Missing decryption key in URL ?
  401. if (window.location.hash.length == 0) {
  402. showError('Cannot decrypt paste: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL ?)');
  403. return;
  404. }
  405. // List of messages to display
  406. var messages = jQuery.parseJSON($('div#cipherdata').text());
  407. // Show proper elements on screen.
  408. stateExistingPaste();
  409. displayMessages(pageKey(), messages);
  410. }
  411. // Display error message from php code.
  412. else if ($('div#errormessage').text().length>1) {
  413. showError($('div#errormessage').text());
  414. }
  415. // Create a new paste.
  416. else {
  417. newPaste();
  418. }
  419. });