zerobin.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 = zeroCipher(pageKey(), nick);
  191. }
  192. var data_to_send = { data:cipherdata,
  193. parentid: parentid,
  194. pasteid: pasteID(),
  195. nickname: ciphernickname
  196. };
  197. $.post(scriptLocation(), data_to_send, 'json')
  198. .error(function() {
  199. showError('Comment could not be sent (serveur error or not responding).');
  200. })
  201. .success(function(data) {
  202. if (data.status == 0) {
  203. showStatus('Comment posted.');
  204. location.reload();
  205. }
  206. else if (data.status==1) {
  207. showError('Could not post comment: '+data.message);
  208. }
  209. else {
  210. showError('Could not post comment.');
  211. }
  212. });
  213. }
  214. /**
  215. * Send a new paste to server
  216. */
  217. function send_data() {
  218. // Do not send if no data.
  219. if ($('textarea#message').val().length == 0) {
  220. return;
  221. }
  222. showStatus('Sending paste...', spin=true);
  223. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  224. var cipherdata = zeroCipher(randomkey, $('textarea#message').val());
  225. var data_to_send = { data: cipherdata,
  226. expire: $('select#pasteExpiration').val(),
  227. opendiscussion: $('input#opendiscussion').is(':checked') ? 1 : 0
  228. };
  229. $.post(scriptLocation(), data_to_send, 'json')
  230. .error(function() {
  231. showError('Data could not be sent (serveur error or not responding).');
  232. })
  233. .success(function(data) {
  234. if (data.status == 0) {
  235. stateExistingPaste();
  236. var url = scriptLocation() + "?" + data.id + '#' + randomkey;
  237. showStatus('');
  238. $('div#pastelink').html('Your paste is <a href="' + url + '">' + url + '</a>');
  239. $('div#pastelink')
  240. .append('&nbsp;&nbsp;<button id="shortenbutton" onclick="document.location=\'' + shortenUrl(url) + '\'"><img src="img/icon_shorten.png" width="13" height="15" />Shorten URL</button>')
  241. .show();
  242. setElementText($('div#cleartext'), $('textarea#message').val());
  243. urls2links($('div#cleartext'));
  244. showStatus('');
  245. }
  246. else if (data.status==1) {
  247. showError('Could not create paste: '+data.message);
  248. }
  249. else {
  250. showError('Could not create paste.');
  251. }
  252. });
  253. }
  254. /**
  255. * Put the screen in "New paste" mode.
  256. */
  257. function stateNewPaste() {
  258. $('button#sendbutton').show();
  259. $('button#clonebutton').hide();
  260. $('div#expiration').show();
  261. $('div#remainingtime').hide();
  262. $('div#language').hide(); // $('#language').show();
  263. $('input#password').hide(); //$('#password').show();
  264. $('div#opendisc').show();
  265. $('button#newbutton').show();
  266. $('div#pastelink').hide();
  267. $('textarea#message').text('');
  268. $('textarea#message').show();
  269. $('div#cleartext').hide();
  270. $('div#message').focus();
  271. $('div#discussion').hide();
  272. }
  273. /**
  274. * Put the screen in "Existing paste" mode.
  275. */
  276. function stateExistingPaste() {
  277. $('button#sendbutton').hide();
  278. // No "clone" for IE<10.
  279. if ($('div#oldienotice').is(":visible")) {
  280. $('button#clonebutton').hide();
  281. }
  282. else {
  283. $('button#clonebutton').show();
  284. }
  285. $('div#expiration').hide();
  286. $('div#language').hide();
  287. $('input#password').hide();
  288. $('div#opendisc').hide();
  289. $('button#newbutton').show();
  290. $('div#pastelink').hide();
  291. $('textarea#message').hide();
  292. $('div#cleartext').show();
  293. }
  294. /**
  295. * Clone the current paste.
  296. */
  297. function clonePaste() {
  298. stateNewPaste();
  299. showStatus('');
  300. $('textarea#message').text($('div#cleartext').text());
  301. }
  302. /**
  303. * Create a new paste.
  304. */
  305. function newPaste() {
  306. stateNewPaste();
  307. showStatus('');
  308. $('textarea#message').text('');
  309. }
  310. /**
  311. * Display an error message
  312. * (We use the same function for paste and reply to comments)
  313. */
  314. function showError(message) {
  315. $('div#status').addClass('errorMessage').text(message);
  316. $('div#replystatus').addClass('errorMessage').text(message);
  317. }
  318. /**
  319. * Display status
  320. * (We use the same function for paste and reply to comments)
  321. *
  322. * @param string message : text to display
  323. * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
  324. */
  325. function showStatus(message, spin) {
  326. $('div#replystatus').removeClass('errorMessage');
  327. $('div#replystatus').text(message);
  328. if (!message) {
  329. $('div#status').html('&nbsp');
  330. return;
  331. }
  332. if (message == '') {
  333. $('div#status').html('&nbsp');
  334. return;
  335. }
  336. $('div#status').removeClass('errorMessage');
  337. $('div#status').text(message);
  338. if (spin) {
  339. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0px 4px 0px 0px;" />';
  340. $('div#status').prepend(img);
  341. $('div#replystatus').prepend(img);
  342. }
  343. }
  344. /**
  345. * Generate link to URL shortener.
  346. */
  347. function shortenUrl(url) {
  348. return 'http://snipurl.com/site/snip?link=' + encodeURIComponent(url);
  349. }
  350. /**
  351. * Convert URLs to clickable links.
  352. * URLs to handle:
  353. * <code>
  354. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  355. * http://localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  356. * http://user:password@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  357. * </code>
  358. *
  359. * @param object element : a jQuery DOM element.
  360. * @FIXME: add ppa & apt links.
  361. */
  362. function urls2links(element) {
  363. var re = /((http|https|ftp):\/\/[\w?=&.\/-;#@~%+-]+(?![\w\s?&.\/;#~%"=-]*>))/ig;
  364. element.html(element.html().replace(re,'<a href="$1" rel="nofollow">$1</a>'));
  365. var re = /((magnet):[\w?=&.\/-;#@~%+-]+)/ig;
  366. element.html(element.html().replace(re,'<a href="$1">$1</a>'));
  367. }
  368. /**
  369. * Return the deciphering key stored in anchor part of the URL
  370. */
  371. function pageKey() {
  372. var key = window.location.hash.substring(1); // Get key
  373. // Some stupid web 2.0 services and redirectors add data AFTER the anchor
  374. // (such as &utm_source=...).
  375. // We will strip any additional data.
  376. // First, strip everything after the equal sign (=) which signals end of base64 string.
  377. i = key.indexOf('='); if (i>-1) { key = key.substring(0,i+1); }
  378. // If the equal sign was not present, some parameters may remain:
  379. i = key.indexOf('&'); if (i>-1) { key = key.substring(0,i); }
  380. // Then add trailing equal sign if it's missing
  381. if (key.charAt(key.length-1)!=='=') key+='=';
  382. return key;
  383. }
  384. $(function() {
  385. $('select#pasteExpiration').change(function() {
  386. if ($(this).val() == 'burn') {
  387. $('div#opendisc').addClass('buttondisabled');
  388. $('input#opendiscussion').attr('disabled',true);
  389. }
  390. else {
  391. $('div#opendisc').removeClass('buttondisabled');
  392. $('input#opendiscussion').removeAttr('disabled');
  393. }
  394. });
  395. // Display an existing paste
  396. if ($('div#cipherdata').text().length > 1) {
  397. // Missing decryption key in URL ?
  398. if (window.location.hash.length == 0) {
  399. showError('Cannot decrypt paste: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL ?)');
  400. return;
  401. }
  402. // List of messages to display
  403. var messages = jQuery.parseJSON($('div#cipherdata').text());
  404. // Show proper elements on screen.
  405. stateExistingPaste();
  406. displayMessages(pageKey(), messages);
  407. }
  408. // Display error message from php code.
  409. else if ($('div#errormessage').text().length>1) {
  410. showError($('div#errormessage').text());
  411. }
  412. // Create a new paste.
  413. else {
  414. newPaste();
  415. }
  416. });