zerobin.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. $('div#prettymessage').hide();
  104. $('button#clonebutton').hide();
  105. showError('Could not decrypt data (Wrong key ?)');
  106. return;
  107. }
  108. setElementText($('div#cleartext'), cleartext);
  109. setElementText($('pre#prettyprint'), cleartext);
  110. urls2links($('div#cleartext')); // Convert URLs to clickable links.
  111. prettyPrint();
  112. // Display paste expiration.
  113. if (comments[0].meta.expire_date) $('div#remainingtime').removeClass('foryoureyesonly').text('This document will expire in '+secondsToHuman(comments[0].meta.remaining_time)+'.').show();
  114. if (comments[0].meta.burnafterreading) {
  115. $('div#remainingtime').addClass('foryoureyesonly').text('FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.').show();
  116. $('button#clonebutton').hide(); // Discourage cloning (as it can't really be prevented).
  117. }
  118. // If the discussion is opened on this paste, display it.
  119. if (comments[0].meta.opendiscussion) {
  120. $('div#comments').html('');
  121. // For each comment.
  122. for (var i = 1; i < comments.length; i++) {
  123. var comment=comments[i];
  124. var cleartext="[Could not decrypt comment ; Wrong key ?]";
  125. try {
  126. cleartext = zeroDecipher(key, comment.data);
  127. } catch(err) { }
  128. var place = $('div#comments');
  129. // If parent comment exists, display below (CSS will automatically shift it right.)
  130. var cname = 'div#comment_'+comment.meta.parentid
  131. // If the element exists in page
  132. if ($(cname).length) {
  133. place = $(cname);
  134. }
  135. var divComment = $('<div class="comment" id="comment_' + comment.meta.commentid+'">'
  136. + '<div class="commentmeta"><span class="nickname"></span><span class="commentdate"></span></div><div class="commentdata"></div>'
  137. + '<button onclick="open_reply($(this),\'' + comment.meta.commentid + '\');return false;">Reply</button>'
  138. + '</div>');
  139. setElementText(divComment.find('div.commentdata'), cleartext);
  140. // Convert URLs to clickable links in comment.
  141. urls2links(divComment.find('div.commentdata'));
  142. divComment.find('span.nickname').html('<i>(Anonymous)</i>');
  143. // Try to get optional nickname:
  144. try {
  145. divComment.find('span.nickname').text(zeroDecipher(key, comment.meta.nickname));
  146. } catch(err) { }
  147. divComment.find('span.commentdate').text(' ('+(new Date(comment.meta.postdate*1000).toUTCString())+')').attr('title','CommentID: ' + comment.meta.commentid);
  148. // If an avatar is available, display it.
  149. if (comment.meta.vizhash) {
  150. divComment.find('span.nickname').before('<img src="' + comment.meta.vizhash + '" class="vizhash" title="Anonymous avatar (Vizhash of the IP address)" />');
  151. }
  152. place.append(divComment);
  153. }
  154. $('div#comments').append('<div class="comment"><button onclick="open_reply($(this),\'' + pasteID() + '\');return false;">Add comment</button></div>');
  155. $('div#discussion').show();
  156. }
  157. }
  158. /**
  159. * Open the comment entry when clicking the "Reply" button of a comment.
  160. * @param object source : element which emitted the event.
  161. * @param string commentid = identifier of the comment we want to reply to.
  162. */
  163. function open_reply(source, commentid) {
  164. $('div.reply').remove(); // Remove any other reply area.
  165. source.after('<div class="reply">'
  166. + '<input type="text" id="nickname" title="Optional nickname..." value="Optional nickname..." />'
  167. + '<textarea id="replymessage" class="replymessage" cols="80" rows="7"></textarea>'
  168. + '<br><button id="replybutton" onclick="send_comment(\'' + commentid + '\');return false;">Post comment</button>'
  169. + '<div id="replystatus">&nbsp;</div>'
  170. + '</div>');
  171. $('input#nickname').focus(function() {
  172. $(this).css('color', '#000');
  173. if ($(this).val() == $(this).attr('title')) {
  174. $(this).val('');
  175. }
  176. });
  177. $('textarea#replymessage').focus();
  178. }
  179. /**
  180. * Send a reply in a discussion.
  181. * @param string parentid : the comment identifier we want to send a reply to.
  182. */
  183. function send_comment(parentid) {
  184. // Do not send if no data.
  185. if ($('textarea#replymessage').val().length==0) {
  186. return;
  187. }
  188. showStatus('Sending comment...', spin=true);
  189. var cipherdata = zeroCipher(pageKey(), $('textarea#replymessage').val());
  190. var ciphernickname = '';
  191. var nick=$('input#nickname').val();
  192. if (nick != '' && nick != 'Optional nickname...') {
  193. ciphernickname = zeroCipher(pageKey(), nick);
  194. }
  195. var data_to_send = { data:cipherdata,
  196. parentid: parentid,
  197. pasteid: pasteID(),
  198. nickname: ciphernickname
  199. };
  200. $.post(scriptLocation(), data_to_send, 'json')
  201. .error(function() {
  202. showError('Comment could not be sent (serveur error or not responding).');
  203. })
  204. .success(function(data) {
  205. if (data.status == 0) {
  206. showStatus('Comment posted.');
  207. location.reload();
  208. }
  209. else if (data.status==1) {
  210. showError('Could not post comment: '+data.message);
  211. }
  212. else {
  213. showError('Could not post comment.');
  214. }
  215. });
  216. }
  217. /**
  218. * Send a new paste to server
  219. */
  220. function send_data() {
  221. // Do not send if no data.
  222. if ($('textarea#message').val().length == 0) {
  223. return;
  224. }
  225. showStatus('Sending paste...', spin=true);
  226. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  227. var cipherdata = zeroCipher(randomkey, $('textarea#message').val());
  228. var data_to_send = { data: cipherdata,
  229. expire: $('select#pasteExpiration').val(),
  230. opendiscussion: $('input#opendiscussion').is(':checked') ? 1 : 0
  231. };
  232. $.post(scriptLocation(), data_to_send, 'json')
  233. .error(function() {
  234. showError('Data could not be sent (serveur error or not responding).');
  235. })
  236. .success(function(data) {
  237. if (data.status == 0) {
  238. stateExistingPaste();
  239. var url = scriptLocation() + "?" + data.id + '#' + randomkey;
  240. showStatus('');
  241. $('div#pastelink').html('Your paste is <a href="' + url + '">' + url + '</a>').show();
  242. setElementText($('div#cleartext'), $('textarea#message').val());
  243. setElementText($('pre#prettyprint'), $('textarea#message').val());
  244. urls2links($('div#cleartext'));
  245. showStatus('');
  246. prettyPrint();
  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. $('button#sendbutton').show();
  261. $('button#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. $('button#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. $('div#prettymessage').hide();
  275. }
  276. /**
  277. * Put the screen in "Existing paste" mode.
  278. */
  279. function stateExistingPaste() {
  280. $('button#sendbutton').hide();
  281. // No "clone" for IE<10.
  282. if ($('div#oldienotice').is(":visible")) {
  283. $('button#clonebutton').hide();
  284. }
  285. else {
  286. $('button#clonebutton').show();
  287. }
  288. $('div#expiration').hide();
  289. $('div#language').hide();
  290. $('input#password').hide();
  291. $('div#opendisc').hide();
  292. $('button#newbutton').show();
  293. $('div#pastelink').hide();
  294. $('textarea#message').hide();
  295. $('div#cleartext').hide();
  296. $('div#prettymessage').show();
  297. }
  298. /**
  299. * Clone the current paste.
  300. */
  301. function clonePaste() {
  302. stateNewPaste();
  303. showStatus('');
  304. $('textarea#message').text($('div#cleartext').text());
  305. }
  306. /**
  307. * Create a new paste.
  308. */
  309. function newPaste() {
  310. stateNewPaste();
  311. showStatus('');
  312. $('textarea#message').text('');
  313. }
  314. /**
  315. * Display an error message
  316. * (We use the same function for paste and reply to comments)
  317. */
  318. function showError(message) {
  319. $('div#status').addClass('errorMessage').text(message);
  320. $('div#replystatus').addClass('errorMessage').text(message);
  321. }
  322. /**
  323. * Display status
  324. * (We use the same function for paste and reply to comments)
  325. *
  326. * @param string message : text to display
  327. * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
  328. */
  329. function showStatus(message, spin) {
  330. $('div#replystatus').removeClass('errorMessage');
  331. $('div#replystatus').text(message);
  332. if (!message) {
  333. $('div#status').html('&nbsp');
  334. return;
  335. }
  336. if (message == '') {
  337. $('div#status').html('&nbsp');
  338. return;
  339. }
  340. $('div#status').removeClass('errorMessage');
  341. $('div#status').text(message);
  342. if (spin) {
  343. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0px 4px 0px 0px;" />';
  344. $('div#status').prepend(img);
  345. $('div#replystatus').prepend(img);
  346. }
  347. }
  348. /**
  349. * Convert URLs to clickable links.
  350. * URLs to handle:
  351. * <code>
  352. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  353. * http://localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  354. * http://user:password@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  355. * </code>
  356. *
  357. * @param object element : a jQuery DOM element.
  358. * @FIXME: add ppa & apt links.
  359. */
  360. function urls2links(element) {
  361. var re = /((http|https|ftp):\/\/[\w?=&.\/-;#@~%+-]+(?![\w\s?&.\/;#~%"=-]*>))/ig;
  362. element.html(element.html().replace(re,'<a href="$1" rel="nofollow">$1</a>'));
  363. var re = /((magnet):[\w?=&.\/-;#@~%+-]+)/ig;
  364. element.html(element.html().replace(re,'<a href="$1">$1</a>'));
  365. }
  366. /**
  367. * Return the deciphering key stored in anchor part of the URL
  368. */
  369. function pageKey() {
  370. var key = window.location.hash.substring(1); // Get key
  371. // Some stupid web 2.0 services and redirectors add data AFTER the anchor
  372. // (such as &utm_source=...).
  373. // We will strip any additional data.
  374. // First, strip everything after the equal sign (=) which signals end of base64 string.
  375. i = key.indexOf('='); if (i>-1) { key = key.substring(0,i+1); }
  376. // If the equal sign was not present, some parameters may remain:
  377. i = key.indexOf('&'); if (i>-1) { key = key.substring(0,i); }
  378. // Then add trailing equal sign if it's missing
  379. if (key.charAt(key.length-1)!=='=') key+='=';
  380. return key;
  381. }
  382. $(function() {
  383. $('select#pasteExpiration').change(function() {
  384. if ($(this).val() == 'burn') {
  385. $('div#opendisc').addClass('buttondisabled');
  386. $('input#opendiscussion').attr('disabled',true);
  387. }
  388. else {
  389. $('div#opendisc').removeClass('buttondisabled');
  390. $('input#opendiscussion').removeAttr('disabled');
  391. }
  392. });
  393. // Display an existing paste
  394. if ($('div#cipherdata').text().length > 1) {
  395. // Missing decryption key in URL ?
  396. if (window.location.hash.length == 0) {
  397. showError('Cannot decrypt paste: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL ?)');
  398. return;
  399. }
  400. // List of messages to display
  401. var messages = jQuery.parseJSON($('div#cipherdata').text());
  402. // Show proper elements on screen.
  403. stateExistingPaste();
  404. displayMessages(pageKey(), messages);
  405. }
  406. // Display error message from php code.
  407. else if ($('div#errormessage').text().length>1) {
  408. showError($('div#errormessage').text());
  409. }
  410. // Create a new paste.
  411. else {
  412. newPaste();
  413. }
  414. });