zerobin.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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>').show();
  239. setElementText($('div#cleartext'), $('textarea#message').val());
  240. urls2links($('div#cleartext'));
  241. showStatus('');
  242. }
  243. else if (data.status==1) {
  244. showError('Could not create paste: '+data.message);
  245. }
  246. else {
  247. showError('Could not create paste.');
  248. }
  249. });
  250. }
  251. /**
  252. * Put the screen in "New paste" mode.
  253. */
  254. function stateNewPaste() {
  255. $('button#sendbutton').show();
  256. $('button#clonebutton').hide();
  257. $('div#expiration').show();
  258. $('div#remainingtime').hide();
  259. $('div#language').hide(); // $('#language').show();
  260. $('input#password').hide(); //$('#password').show();
  261. $('div#opendisc').show();
  262. $('button#newbutton').show();
  263. $('div#pastelink').hide();
  264. $('textarea#message').text('');
  265. $('textarea#message').show();
  266. $('div#cleartext').hide();
  267. $('div#message').focus();
  268. $('div#discussion').hide();
  269. }
  270. /**
  271. * Put the screen in "Existing paste" mode.
  272. */
  273. function stateExistingPaste() {
  274. $('button#sendbutton').hide();
  275. // No "clone" for IE<10.
  276. if ($('div#oldienotice').is(":visible")) {
  277. $('button#clonebutton').hide();
  278. }
  279. else {
  280. $('button#clonebutton').show();
  281. }
  282. $('div#expiration').hide();
  283. $('div#language').hide();
  284. $('input#password').hide();
  285. $('div#opendisc').hide();
  286. $('button#newbutton').show();
  287. $('div#pastelink').hide();
  288. $('textarea#message').hide();
  289. $('div#cleartext').show();
  290. }
  291. /**
  292. * Clone the current paste.
  293. */
  294. function clonePaste() {
  295. stateNewPaste();
  296. showStatus('');
  297. $('textarea#message').text($('div#cleartext').text());
  298. }
  299. /**
  300. * Create a new paste.
  301. */
  302. function newPaste() {
  303. stateNewPaste();
  304. showStatus('');
  305. $('textarea#message').text('');
  306. }
  307. /**
  308. * Display an error message
  309. * (We use the same function for paste and reply to comments)
  310. */
  311. function showError(message) {
  312. $('div#status').addClass('errorMessage').text(message);
  313. $('div#replystatus').addClass('errorMessage').text(message);
  314. }
  315. /**
  316. * Display status
  317. * (We use the same function for paste and reply to comments)
  318. *
  319. * @param string message : text to display
  320. * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
  321. */
  322. function showStatus(message, spin) {
  323. $('div#replystatus').removeClass('errorMessage');
  324. $('div#replystatus').text(message);
  325. if (!message) {
  326. $('div#status').html('&nbsp');
  327. return;
  328. }
  329. if (message == '') {
  330. $('div#status').html('&nbsp');
  331. return;
  332. }
  333. $('div#status').removeClass('errorMessage');
  334. $('div#status').text(message);
  335. if (spin) {
  336. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0px 4px 0px 0px;" />';
  337. $('div#status').prepend(img);
  338. $('div#replystatus').prepend(img);
  339. }
  340. }
  341. /**
  342. * Convert URLs to clickable links.
  343. * URLs to handle:
  344. * <code>
  345. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  346. * http://localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  347. * http://user:password@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  348. * </code>
  349. *
  350. * @param object element : a jQuery DOM element.
  351. * @FIXME: add ppa & apt links.
  352. */
  353. function urls2links(element) {
  354. var re = /((http|https|ftp):\/\/[\w?=&.\/-;#@~%+-]+(?![\w\s?&.\/;#~%"=-]*>))/ig;
  355. element.html(element.html().replace(re,'<a href="$1" rel="nofollow">$1</a>'));
  356. var re = /((magnet):[\w?=&.\/-;#@~%+-]+)/ig;
  357. element.html(element.html().replace(re,'<a href="$1">$1</a>'));
  358. }
  359. /**
  360. * Return the deciphering key stored in anchor part of the URL
  361. */
  362. function pageKey() {
  363. var key = window.location.hash.substring(1); // Get key
  364. // Some stupid web 2.0 services and redirectors add data AFTER the anchor
  365. // (such as &utm_source=...).
  366. // We will strip any additional data.
  367. // First, strip everything after the equal sign (=) which signals end of base64 string.
  368. i = key.indexOf('='); if (i>-1) { key = key.substring(0,i+1); }
  369. // If the equal sign was not present, some parameters may remain:
  370. i = key.indexOf('&'); if (i>-1) { key = key.substring(0,i); }
  371. // Then add trailing equal sign if it's missing
  372. if (key.charAt(key.length-1)!=='=') key+='=';
  373. return key;
  374. }
  375. $(function() {
  376. $('select#pasteExpiration').change(function() {
  377. if ($(this).val() == 'burn') {
  378. $('div#opendisc').addClass('buttondisabled');
  379. $('input#opendiscussion').attr('disabled',true);
  380. }
  381. else {
  382. $('div#opendisc').removeClass('buttondisabled');
  383. $('input#opendiscussion').removeAttr('disabled');
  384. }
  385. });
  386. // Display an existing paste
  387. if ($('div#cipherdata').text().length > 1) {
  388. // Missing decryption key in URL ?
  389. if (window.location.hash.length == 0) {
  390. showError('Cannot decrypt paste: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL ?)');
  391. return;
  392. }
  393. // List of messages to display
  394. var messages = jQuery.parseJSON($('div#cipherdata').text());
  395. // Show proper elements on screen.
  396. stateExistingPaste();
  397. displayMessages(pageKey(), messages);
  398. }
  399. // Display error message from php code.
  400. else if ($('div#errormessage').text().length>1) {
  401. showError($('div#errormessage').text());
  402. }
  403. // Create a new paste.
  404. else {
  405. newPaste();
  406. }
  407. });