privatebin.js 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  1. /**
  2. * PrivateBin
  3. *
  4. * a zero-knowledge paste bin
  5. *
  6. * @link https://github.com/PrivateBin/PrivateBin
  7. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  8. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  9. * @version 1.1
  10. */
  11. 'use strict';
  12. /** global: Base64 */
  13. /** global: FileReader */
  14. /** global: RawDeflate */
  15. /** global: history */
  16. /** global: navigator */
  17. /** global: prettyPrint */
  18. /** global: prettyPrintOne */
  19. /** global: showdown */
  20. /** global: sjcl */
  21. // Immediately start random number generator collector.
  22. sjcl.random.startCollectors();
  23. $(function() {
  24. /**
  25. * static helper methods
  26. */
  27. var helper = {
  28. /**
  29. * Converts a duration (in seconds) into human friendly approximation.
  30. *
  31. * @param int seconds
  32. * @return array
  33. */
  34. secondsToHuman: function(seconds)
  35. {
  36. var v;
  37. if (seconds < 60)
  38. {
  39. v = Math.floor(seconds);
  40. return [v, 'second'];
  41. }
  42. if (seconds < 60 * 60)
  43. {
  44. v = Math.floor(seconds / 60);
  45. return [v, 'minute'];
  46. }
  47. if (seconds < 60 * 60 * 24)
  48. {
  49. v = Math.floor(seconds / (60 * 60));
  50. return [v, 'hour'];
  51. }
  52. // If less than 2 months, display in days:
  53. if (seconds < 60 * 60 * 24 * 60)
  54. {
  55. v = Math.floor(seconds / (60 * 60 * 24));
  56. return [v, 'day'];
  57. }
  58. v = Math.floor(seconds / (60 * 60 * 24 * 30));
  59. return [v, 'month'];
  60. },
  61. /**
  62. * Converts an associative array to an encoded string
  63. * for appending to the anchor.
  64. *
  65. * @param object associative_array Object to be serialized
  66. * @return string
  67. */
  68. hashToParameterString: function(associativeArray)
  69. {
  70. var parameterString = '';
  71. for (var key in associativeArray)
  72. {
  73. if(parameterString === '')
  74. {
  75. parameterString = encodeURIComponent(key);
  76. parameterString += '=' + encodeURIComponent(associativeArray[key]);
  77. }
  78. else
  79. {
  80. parameterString += '&' + encodeURIComponent(key);
  81. parameterString += '=' + encodeURIComponent(associativeArray[key]);
  82. }
  83. }
  84. // padding for URL shorteners
  85. parameterString += '&p=p';
  86. return parameterString;
  87. },
  88. /**
  89. * Converts a string to an associative array.
  90. *
  91. * @param string parameter_string String containing parameters
  92. * @return object
  93. */
  94. parameterStringToHash: function(parameterString)
  95. {
  96. var parameterHash = {};
  97. var parameterArray = parameterString.split('&');
  98. for (var i = 0; i < parameterArray.length; i++)
  99. {
  100. var pair = parameterArray[i].split('=');
  101. var key = decodeURIComponent(pair[0]);
  102. var value = decodeURIComponent(pair[1]);
  103. parameterHash[key] = value;
  104. }
  105. return parameterHash;
  106. },
  107. /**
  108. * Get an associative array of the parameters found in the anchor
  109. *
  110. * @return object
  111. */
  112. getParameterHash: function()
  113. {
  114. var hashIndex = window.location.href.indexOf('#');
  115. if (hashIndex >= 0)
  116. {
  117. return this.parameterStringToHash(window.location.href.substring(hashIndex + 1));
  118. }
  119. else
  120. {
  121. return {};
  122. }
  123. },
  124. /**
  125. * Text range selection.
  126. * From: https://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: https://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')
  230. {
  231. args = arguments[0];
  232. }
  233. var string = args[0],
  234. i = 1;
  235. return string.replace(/%((%)|s|d)/g, function (m) {
  236. // m is the matched format, e.g. %s, %d
  237. var val;
  238. if (m[2]) {
  239. val = m[2];
  240. } else {
  241. val = args[i];
  242. // A switch statement so that the formatter can be extended.
  243. switch (m)
  244. {
  245. case '%d':
  246. val = parseFloat(val);
  247. if (isNaN(val)) {
  248. val = 0;
  249. }
  250. break;
  251. default:
  252. // Default is %s
  253. }
  254. ++i;
  255. }
  256. return val;
  257. });
  258. },
  259. /**
  260. * get value of cookie, if it was set, empty string otherwise
  261. * From: http://www.w3schools.com/js/js_cookies.asp
  262. *
  263. * @param string cname
  264. * @return string
  265. */
  266. getCookie: function(cname) {
  267. var name = cname + '=';
  268. var ca = document.cookie.split(';');
  269. for (var i = 0; i < ca.length; ++i) {
  270. var c = ca[i];
  271. while (c.charAt(0) === ' ') c = c.substring(1);
  272. if (c.indexOf(name) === 0)
  273. {
  274. return c.substring(name.length, c.length);
  275. }
  276. }
  277. return '';
  278. },
  279. /**
  280. * Convert all applicable characters to HTML entities.
  281. * From: https://github.com/janl/mustache.js/blob/master/mustache.js#L60
  282. * Also: https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into_HTML_Element_Content
  283. *
  284. * @param string str
  285. * @return string escaped HTML
  286. */
  287. htmlEntities: function(str) {
  288. return String(str).replace(
  289. /[&<>"'`=\/]/g, function(s) {
  290. return helper.entityMap[s];
  291. });
  292. },
  293. /**
  294. * character to HTML entity lookup table
  295. */
  296. entityMap: {
  297. '&': '&amp;',
  298. '<': '&lt;',
  299. '>': '&gt;',
  300. '"': '&quot;',
  301. "'": '&#39;',
  302. '/': '&#x2F;',
  303. '`': '&#x60;',
  304. '=': '&#x3D;'
  305. }
  306. };
  307. /**
  308. * internationalization methods
  309. */
  310. var i18n = {
  311. /**
  312. * supported languages, minus the built in 'en'
  313. */
  314. supportedLanguages: ['de', 'es', 'fr', 'it', 'pl', 'ru', 'sl', 'zh'],
  315. /**
  316. * translate a string, alias for translate()
  317. *
  318. * @param string $messageId
  319. * @param mixed args one or multiple parameters injected into placeholders
  320. * @return string
  321. */
  322. _: function()
  323. {
  324. return this.translate(arguments);
  325. },
  326. /**
  327. * translate a string
  328. *
  329. * @param string $messageId
  330. * @param mixed args one or multiple parameters injected into placeholders
  331. * @return string
  332. */
  333. translate: function()
  334. {
  335. var args = arguments, messageId;
  336. if (typeof arguments[0] === 'object')
  337. {
  338. args = arguments[0];
  339. }
  340. var usesPlurals = $.isArray(args[0]);
  341. if (usesPlurals)
  342. {
  343. // use the first plural form as messageId, otherwise the singular
  344. messageId = (args[0].length > 1 ? args[0][1] : args[0][0]);
  345. }
  346. else
  347. {
  348. messageId = args[0];
  349. }
  350. if (messageId.length === 0)
  351. {
  352. return messageId;
  353. }
  354. if (!this.translations.hasOwnProperty(messageId))
  355. {
  356. if (this.language !== 'en')
  357. {
  358. console.debug(
  359. 'Missing ' + this.language + ' translation for: ' + messageId
  360. );
  361. }
  362. this.translations[messageId] = args[0];
  363. }
  364. if (usesPlurals && $.isArray(this.translations[messageId]))
  365. {
  366. var n = parseInt(args[1] || 1, 10),
  367. key = this.getPluralForm(n),
  368. maxKey = this.translations[messageId].length - 1;
  369. if (key > maxKey)
  370. {
  371. key = maxKey;
  372. }
  373. args[0] = this.translations[messageId][key];
  374. args[1] = n;
  375. }
  376. else
  377. {
  378. args[0] = this.translations[messageId];
  379. }
  380. return helper.sprintf(args);
  381. },
  382. /**
  383. * per language functions to use to determine the plural form
  384. * From: http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html
  385. *
  386. * @param int number
  387. * @return int array key
  388. */
  389. getPluralForm: function(n) {
  390. switch (this.language)
  391. {
  392. case 'fr':
  393. case 'zh':
  394. return (n > 1 ? 1 : 0);
  395. case 'pl':
  396. return (n === 1 ? 0 : (n%10 >= 2 && n %10 <=4 && (n%100 < 10 || n%100 >= 20) ? 1 : 2));
  397. case 'ru':
  398. return (n % 10 === 1 && n % 100 !== 11 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2));
  399. // en, de
  400. default:
  401. return (n !== 1 ? 1 : 0);
  402. }
  403. },
  404. /**
  405. * load translations into cache, then execute callback function
  406. *
  407. * @param function callback
  408. */
  409. loadTranslations: function(callback)
  410. {
  411. var selectedLang = helper.getCookie('lang');
  412. var language = selectedLang.length > 0 ? selectedLang : (navigator.language || navigator.userLanguage).substring(0, 2);
  413. // note that 'en' is built in, so no translation is necessary
  414. if (this.supportedLanguages.indexOf(language) === -1)
  415. {
  416. callback();
  417. }
  418. else
  419. {
  420. $.getJSON('i18n/' + language + '.json', function(data) {
  421. i18n.language = language;
  422. i18n.translations = data;
  423. callback();
  424. });
  425. }
  426. },
  427. /**
  428. * built in language
  429. */
  430. language: 'en',
  431. /**
  432. * translation cache
  433. */
  434. translations: {}
  435. };
  436. /**
  437. * filter methods
  438. */
  439. var filter = {
  440. /**
  441. * Compress a message (deflate compression). Returns base64 encoded data.
  442. *
  443. * @param string message
  444. * @return base64 string data
  445. */
  446. compress: function(message)
  447. {
  448. return Base64.toBase64( RawDeflate.deflate( Base64.utob(message) ) );
  449. },
  450. /**
  451. * Decompress a message compressed with compress().
  452. *
  453. * @param base64 string data
  454. * @return string message
  455. */
  456. decompress: function(data)
  457. {
  458. return Base64.btou( RawDeflate.inflate( Base64.fromBase64(data) ) );
  459. },
  460. /**
  461. * Compress, then encrypt message with key.
  462. *
  463. * @param string key
  464. * @param string password
  465. * @param string message
  466. * @return encrypted string data
  467. */
  468. cipher: function(key, password, message)
  469. {
  470. // Galois Counter Mode, keysize 256 bit, authentication tag 128 bit
  471. var options = {mode: 'gcm', ks: 256, ts: 128};
  472. if ((password || '').trim().length === 0)
  473. {
  474. return sjcl.encrypt(key, this.compress(message), options);
  475. }
  476. return sjcl.encrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), this.compress(message), options);
  477. },
  478. /**
  479. * Decrypt message with key, then decompress.
  480. *
  481. * @param string key
  482. * @param string password
  483. * @param encrypted string data
  484. * @return string readable message
  485. */
  486. decipher: function(key, password, data)
  487. {
  488. if (data !== undefined)
  489. {
  490. try
  491. {
  492. return this.decompress(sjcl.decrypt(key, data));
  493. }
  494. catch(err)
  495. {
  496. try
  497. {
  498. return this.decompress(sjcl.decrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), data));
  499. }
  500. catch(e)
  501. {}
  502. }
  503. }
  504. return '';
  505. }
  506. };
  507. var privatebin = {
  508. /**
  509. * headers to send in AJAX requests
  510. */
  511. headers: {'X-Requested-With': 'JSONHttpRequest'},
  512. /**
  513. * URL shortners create address
  514. */
  515. shortenerUrl: '',
  516. /**
  517. * URL of newly created paste
  518. */
  519. createdPasteUrl: '',
  520. /**
  521. * Get the current script location (without search or hash part of the URL).
  522. * eg. http://server.com/zero/?aaaa#bbbb --> http://server.com/zero/
  523. *
  524. * @return string current script location
  525. */
  526. scriptLocation: function()
  527. {
  528. var scriptLocation = window.location.href.substring(0,window.location.href.length
  529. - window.location.search.length - window.location.hash.length),
  530. hashIndex = scriptLocation.indexOf('#');
  531. if (hashIndex !== -1)
  532. {
  533. scriptLocation = scriptLocation.substring(0, hashIndex);
  534. }
  535. return scriptLocation;
  536. },
  537. /**
  538. * Get the pastes unique identifier from the URL
  539. * eg. http://server.com/zero/?c05354954c49a487#c05354954c49a487 returns c05354954c49a487
  540. *
  541. * @return string unique identifier
  542. */
  543. pasteID: function()
  544. {
  545. return window.location.search.substring(1);
  546. },
  547. /**
  548. * Return the deciphering key stored in anchor part of the URL
  549. *
  550. * @return string key
  551. */
  552. pageKey: function()
  553. {
  554. // Some web 2.0 services and redirectors add data AFTER the anchor
  555. // (such as &utm_source=...). We will strip any additional data.
  556. var key = window.location.hash.substring(1), // Get key
  557. i = key.indexOf('=');
  558. // First, strip everything after the equal sign (=) which signals end of base64 string.
  559. if (i > -1)
  560. {
  561. key = key.substring(0, i + 1);
  562. }
  563. // If the equal sign was not present, some parameters may remain:
  564. i = key.indexOf('&');
  565. if (i > -1)
  566. {
  567. key = key.substring(0, i);
  568. }
  569. // Then add trailing equal sign if it's missing
  570. if (key.charAt(key.length - 1) !== '=')
  571. {
  572. key += '=';
  573. }
  574. return key;
  575. },
  576. /**
  577. * ask the user for the password and set it
  578. */
  579. requestPassword: function()
  580. {
  581. if (this.passwordModal.length === 0) {
  582. var password = prompt(i18n._('Please enter the password for this paste:'), '');
  583. if (password === null)
  584. {
  585. throw 'password prompt canceled';
  586. }
  587. if (password.length === 0)
  588. {
  589. this.requestPassword();
  590. } else {
  591. this.passwordInput.val(password);
  592. this.displayMessages();
  593. }
  594. } else {
  595. this.passwordModal.modal();
  596. }
  597. },
  598. /**
  599. * use given format on paste, defaults to plain text
  600. *
  601. * @param string format
  602. * @param string text
  603. */
  604. formatPaste: function(format, text)
  605. {
  606. helper.setElementText(this.clearText, text);
  607. helper.setElementText(this.prettyPrint, text);
  608. switch (format || 'plaintext')
  609. {
  610. case 'markdown':
  611. if (typeof showdown === 'object')
  612. {
  613. showdown.setOption('strikethrough', true);
  614. showdown.setOption('tables', true);
  615. showdown.setOption('tablesHeaderId', true);
  616. var converter = new showdown.Converter();
  617. this.clearText.html(
  618. converter.makeHtml(text)
  619. );
  620. // add table classes from bootstrap css
  621. this.clearText.find('table').addClass('table-condensed table-bordered');
  622. this.clearText.removeClass('hidden');
  623. }
  624. this.prettyMessage.addClass('hidden');
  625. break;
  626. case 'syntaxhighlighting':
  627. if (typeof prettyPrintOne === 'function')
  628. {
  629. if (typeof prettyPrint === 'function')
  630. {
  631. prettyPrint();
  632. }
  633. this.prettyPrint.html(
  634. prettyPrintOne(
  635. helper.htmlEntities(text), null, true
  636. )
  637. );
  638. }
  639. // fall through, as the rest is the same
  640. default:
  641. // Convert URLs to clickable links.
  642. helper.urls2links(this.clearText);
  643. helper.urls2links(this.prettyPrint);
  644. this.clearText.addClass('hidden');
  645. if (format === 'plaintext')
  646. {
  647. this.prettyPrint.css('white-space', 'pre-wrap');
  648. this.prettyPrint.css('word-break', 'normal');
  649. this.prettyPrint.removeClass('prettyprint');
  650. }
  651. this.prettyMessage.removeClass('hidden');
  652. }
  653. },
  654. /**
  655. * Show decrypted text in the display area, including discussion (if open)
  656. *
  657. * @param object paste (optional) object including comments to display (items = array with keys ('data','meta')
  658. */
  659. displayMessages: function(paste)
  660. {
  661. paste = paste || $.parseJSON(this.cipherData.text());
  662. var key = this.pageKey();
  663. var password = this.passwordInput.val();
  664. if (!this.prettyPrint.hasClass('prettyprinted')) {
  665. // Try to decrypt the paste.
  666. try
  667. {
  668. if (paste.attachment)
  669. {
  670. var attachment = filter.decipher(key, password, paste.attachment);
  671. if (attachment.length === 0)
  672. {
  673. if (password.length === 0)
  674. {
  675. this.requestPassword();
  676. return;
  677. }
  678. attachment = filter.decipher(key, password, paste.attachment);
  679. }
  680. if (attachment.length === 0)
  681. {
  682. throw 'failed to decipher attachment';
  683. }
  684. if (paste.attachmentname)
  685. {
  686. var attachmentname = filter.decipher(key, password, paste.attachmentname);
  687. if (attachmentname.length > 0)
  688. {
  689. this.attachmentLink.attr('download', attachmentname);
  690. }
  691. }
  692. this.attachmentLink.attr('href', attachment);
  693. this.attachment.removeClass('hidden');
  694. // if the attachment is an image, display it
  695. var imagePrefix = 'data:image/';
  696. if (attachment.substring(0, imagePrefix.length) === imagePrefix)
  697. {
  698. this.image.html(
  699. $(document.createElement('img'))
  700. .attr('src', attachment)
  701. .attr('class', 'img-thumbnail')
  702. );
  703. this.image.removeClass('hidden');
  704. }
  705. }
  706. var cleartext = filter.decipher(key, password, paste.data);
  707. if (cleartext.length === 0 && password.length === 0 && !paste.attachment)
  708. {
  709. this.requestPassword();
  710. return;
  711. }
  712. if (cleartext.length === 0 && !paste.attachment)
  713. {
  714. throw 'failed to decipher message';
  715. }
  716. this.passwordInput.val(password);
  717. if (cleartext.length > 0)
  718. {
  719. $('#pasteFormatter').val(paste.meta.formatter);
  720. this.formatPaste(paste.meta.formatter, cleartext);
  721. }
  722. }
  723. catch(err)
  724. {
  725. this.clearText.addClass('hidden');
  726. this.prettyMessage.addClass('hidden');
  727. this.cloneButton.addClass('hidden');
  728. this.showError(i18n._('Could not decrypt data (Wrong key?)'));
  729. return;
  730. }
  731. }
  732. // Display paste expiration / for your eyes only.
  733. if (paste.meta.expire_date)
  734. {
  735. var expiration = helper.secondsToHuman(paste.meta.remaining_time),
  736. expirationLabel = [
  737. 'This document will expire in %d ' + expiration[1] + '.',
  738. 'This document will expire in %d ' + expiration[1] + 's.'
  739. ];
  740. helper.setMessage(this.remainingTime, i18n._(expirationLabel, expiration[0]));
  741. this.remainingTime.removeClass('foryoureyesonly')
  742. .removeClass('hidden');
  743. }
  744. if (paste.meta.burnafterreading)
  745. {
  746. // unfortunately many web servers don't support DELETE (and PUT) out of the box
  747. $.ajax({
  748. type: 'POST',
  749. url: this.scriptLocation() + '?' + this.pasteID(),
  750. data: {deletetoken: 'burnafterreading'},
  751. dataType: 'json',
  752. headers: this.headers
  753. })
  754. .fail(function() {
  755. privatebin.showError(i18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  756. });
  757. helper.setMessage(this.remainingTime, i18n._(
  758. 'FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.'
  759. ));
  760. this.remainingTime.addClass('foryoureyesonly')
  761. .removeClass('hidden');
  762. // Discourage cloning (as it can't really be prevented).
  763. this.cloneButton.addClass('hidden');
  764. }
  765. // If the discussion is opened on this paste, display it.
  766. if (paste.meta.opendiscussion)
  767. {
  768. this.comments.html('');
  769. // iterate over comments
  770. for (var i = 0; i < paste.comments.length; ++i)
  771. {
  772. var place = this.comments;
  773. var comment = paste.comments[i];
  774. var commenttext = filter.decipher(key, password, comment.data);
  775. // If parent comment exists, display below (CSS will automatically shift it right.)
  776. var cname = '#comment_' + comment.parentid;
  777. // If the element exists in page
  778. if ($(cname).length)
  779. {
  780. place = $(cname);
  781. }
  782. var divComment = $('<article><div class="comment" id="comment_' + comment.id + '">'
  783. + '<div class="commentmeta"><span class="nickname"></span><span class="commentdate"></span></div><div class="commentdata"></div>'
  784. + '<button class="btn btn-default btn-sm">' + i18n._('Reply') + '</button>'
  785. + '</div></article>');
  786. divComment.find('button').click({commentid: comment.id}, $.proxy(this.openReply, this));
  787. helper.setElementText(divComment.find('div.commentdata'), commenttext);
  788. // Convert URLs to clickable links in comment.
  789. helper.urls2links(divComment.find('div.commentdata'));
  790. // Try to get optional nickname:
  791. var nick = filter.decipher(key, password, comment.meta.nickname);
  792. if (nick.length > 0)
  793. {
  794. divComment.find('span.nickname').text(nick);
  795. }
  796. else
  797. {
  798. divComment.find('span.nickname').html('<i>' + i18n._('Anonymous') + '</i>');
  799. }
  800. divComment.find('span.commentdate')
  801. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  802. .attr('title', 'CommentID: ' + comment.id);
  803. // If an avatar is available, display it.
  804. if (comment.meta.vizhash)
  805. {
  806. divComment.find('span.nickname')
  807. .before(
  808. '<img src="' + comment.meta.vizhash + '" class="vizhash" title="' +
  809. i18n._('Anonymous avatar (Vizhash of the IP address)') + '" /> '
  810. );
  811. }
  812. place.append(divComment);
  813. }
  814. var divComment = $(
  815. '<div class="comment"><button class="btn btn-default btn-sm">' +
  816. i18n._('Add comment') + '</button></div>'
  817. );
  818. divComment.find('button').click({commentid: this.pasteID()}, $.proxy(this.openReply, this));
  819. this.comments.append(divComment);
  820. this.discussion.removeClass('hidden');
  821. }
  822. },
  823. /**
  824. * Open the comment entry when clicking the "Reply" button of a comment.
  825. *
  826. * @param Event event
  827. */
  828. openReply: function(event)
  829. {
  830. event.preventDefault();
  831. var source = $(event.target),
  832. commentid = event.data.commentid,
  833. hint = i18n._('Optional nickname...');
  834. // Remove any other reply area.
  835. $('div.reply').remove();
  836. var reply = $(
  837. '<div class="reply">' +
  838. '<input type="text" id="nickname" class="form-control" title="' + hint + '" placeholder="' + hint + '" />' +
  839. '<textarea id="replymessage" class="replymessage form-control" cols="80" rows="7"></textarea>' +
  840. '<br /><div id="replystatus"></div><button id="replybutton" class="btn btn-default btn-sm">' +
  841. i18n._('Post comment') + '</button></div>'
  842. );
  843. reply.find('button').click({parentid: commentid}, $.proxy(this.sendComment, this));
  844. source.after(reply);
  845. this.replyStatus = $('#replystatus');
  846. $('#replymessage').focus();
  847. },
  848. /**
  849. * Send a reply in a discussion.
  850. *
  851. * @param Event event
  852. */
  853. sendComment: function(event)
  854. {
  855. event.preventDefault();
  856. this.errorMessage.addClass('hidden');
  857. // Do not send if no data.
  858. var replyMessage = $('#replymessage');
  859. if (replyMessage.val().length === 0)
  860. {
  861. return;
  862. }
  863. this.showStatus(i18n._('Sending comment...'), true);
  864. var parentid = event.data.parentid;
  865. var cipherdata = filter.cipher(this.pageKey(), this.passwordInput.val(), replyMessage.val());
  866. var ciphernickname = '';
  867. var nick = $('#nickname').val();
  868. if (nick !== '')
  869. {
  870. ciphernickname = filter.cipher(this.pageKey(), this.passwordInput.val(), nick);
  871. }
  872. var data_to_send = {
  873. data: cipherdata,
  874. parentid: parentid,
  875. pasteid: this.pasteID(),
  876. nickname: ciphernickname
  877. };
  878. $.ajax({
  879. type: 'POST',
  880. url: this.scriptLocation(),
  881. data: data_to_send,
  882. dataType: 'json',
  883. headers: this.headers,
  884. success: function(data)
  885. {
  886. if (data.status === 0)
  887. {
  888. privatebin.showStatus(i18n._('Comment posted.'), false);
  889. $.ajax({
  890. type: 'GET',
  891. url: privatebin.scriptLocation() + '?' + privatebin.pasteID(),
  892. dataType: 'json',
  893. headers: privatebin.headers,
  894. success: function(data)
  895. {
  896. if (data.status === 0)
  897. {
  898. privatebin.displayMessages(data);
  899. }
  900. else if (data.status === 1)
  901. {
  902. privatebin.showError(i18n._('Could not refresh display: %s', data.message));
  903. }
  904. else
  905. {
  906. privatebin.showError(i18n._('Could not refresh display: %s', i18n._('unknown status')));
  907. }
  908. }
  909. })
  910. .fail(function() {
  911. privatebin.showError(i18n._('Could not refresh display: %s', i18n._('server error or not responding')));
  912. });
  913. }
  914. else if (data.status === 1)
  915. {
  916. privatebin.showError(i18n._('Could not post comment: %s', data.message));
  917. }
  918. else
  919. {
  920. privatebin.showError(i18n._('Could not post comment: %s', i18n._('unknown status')));
  921. }
  922. }
  923. })
  924. .fail(function() {
  925. privatebin.showError(i18n._('Could not post comment: %s', i18n._('server error or not responding')));
  926. });
  927. },
  928. /**
  929. * Send a new paste to server
  930. *
  931. * @param Event event
  932. */
  933. sendData: function(event)
  934. {
  935. event.preventDefault();
  936. var file = document.getElementById('file'),
  937. files = (file && file.files) ? file.files : null; // FileList object
  938. // Do not send if no data.
  939. if (this.message.val().length === 0 && !(files && files[0]))
  940. {
  941. return;
  942. }
  943. // If sjcl has not collected enough entropy yet, display a message.
  944. if (!sjcl.random.isReady())
  945. {
  946. this.showStatus(i18n._('Sending paste (Please move your mouse for more entropy)...'), true);
  947. sjcl.random.addEventListener('seeded', function() {
  948. this.sendData(event);
  949. });
  950. return;
  951. }
  952. $('.navbar-toggle').click();
  953. this.password.addClass('hidden');
  954. this.showStatus(i18n._('Sending paste...'), true);
  955. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  956. var password = this.passwordInput.val();
  957. if(files && files[0])
  958. {
  959. if(typeof FileReader === undefined)
  960. {
  961. this.showError(i18n._('Your browser does not support uploading encrypted files. Please use a newer browser.'));
  962. return;
  963. }
  964. var reader = new FileReader();
  965. // Closure to capture the file information.
  966. reader.onload = (function(theFile)
  967. {
  968. return function(e) {
  969. privatebin.sendDataContinue(
  970. randomkey,
  971. filter.cipher(randomkey, password, e.target.result),
  972. filter.cipher(randomkey, password, theFile.name)
  973. );
  974. };
  975. })(files[0]);
  976. reader.readAsDataURL(files[0]);
  977. }
  978. else if(this.attachmentLink.attr('href'))
  979. {
  980. this.sendDataContinue(
  981. randomkey,
  982. filter.cipher(randomkey, password, this.attachmentLink.attr('href')),
  983. this.attachmentLink.attr('download')
  984. );
  985. }
  986. else
  987. {
  988. this.sendDataContinue(randomkey, '', '');
  989. }
  990. },
  991. /**
  992. * Send a new paste to server, step 2
  993. *
  994. * @param string randomkey
  995. * @param encrypted string cipherdata_attachment
  996. * @param encrypted string cipherdata_attachment_name
  997. */
  998. sendDataContinue: function(randomkey, cipherdata_attachment, cipherdata_attachment_name)
  999. {
  1000. var cipherdata = filter.cipher(randomkey, this.passwordInput.val(), this.message.val());
  1001. var data_to_send = {
  1002. data: cipherdata,
  1003. expire: $('#pasteExpiration').val(),
  1004. formatter: $('#pasteFormatter').val(),
  1005. burnafterreading: this.burnAfterReading.is(':checked') ? 1 : 0,
  1006. opendiscussion: this.openDiscussion.is(':checked') ? 1 : 0
  1007. };
  1008. if (cipherdata_attachment.length > 0)
  1009. {
  1010. data_to_send.attachment = cipherdata_attachment;
  1011. if (cipherdata_attachment_name.length > 0)
  1012. {
  1013. data_to_send.attachmentname = cipherdata_attachment_name;
  1014. }
  1015. }
  1016. $.ajax({
  1017. type: 'POST',
  1018. url: this.scriptLocation(),
  1019. data: data_to_send,
  1020. dataType: 'json',
  1021. headers: this.headers,
  1022. success: function(data)
  1023. {
  1024. if (data.status === 0) {
  1025. privatebin.stateExistingPaste();
  1026. var url = privatebin.scriptLocation() + '?' + data.id + '#' + randomkey;
  1027. var deleteUrl = privatebin.scriptLocation() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  1028. privatebin.showStatus('', false);
  1029. privatebin.errorMessage.addClass('hidden');
  1030. $('#pastelink').html(
  1031. i18n._(
  1032. 'Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>',
  1033. url, url
  1034. ) + privatebin.shortenUrl(url)
  1035. );
  1036. var shortenButton = $('#shortenbutton');
  1037. if (shortenButton) {
  1038. shortenButton.click($.proxy(privatebin.sendToShortener, privatebin));
  1039. }
  1040. $('#deletelink').html('<a href="' + deleteUrl + '">' + i18n._('Delete data') + '</a>');
  1041. privatebin.pasteResult.removeClass('hidden');
  1042. // We pre-select the link so that the user only has to [Ctrl]+[c] the link.
  1043. helper.selectText('pasteurl');
  1044. privatebin.showStatus('', false);
  1045. privatebin.formatPaste(data_to_send.formatter, privatebin.message.val());
  1046. }
  1047. else if (data.status === 1)
  1048. {
  1049. privatebin.showError(i18n._('Could not create paste: %s', data.message));
  1050. }
  1051. else
  1052. {
  1053. privatebin.showError(i18n._('Could not create paste: %s', i18n._('unknown status')));
  1054. }
  1055. }
  1056. })
  1057. .fail(function()
  1058. {
  1059. privatebin.showError(i18n._('Could not create paste: %s', i18n._('server error or not responding')));
  1060. });
  1061. },
  1062. /**
  1063. * Check if a URL shortener was defined and create HTML containing a link to it.
  1064. *
  1065. * @param string url
  1066. * @return string html
  1067. */
  1068. shortenUrl: function(url)
  1069. {
  1070. var shortenerHtml = $('#shortenbutton');
  1071. if (shortenerHtml) {
  1072. this.shortenerUrl = shortenerHtml.data('shortener');
  1073. this.createdPasteUrl = url;
  1074. return ' ' + $('<div />').append(shortenerHtml.clone()).html();
  1075. }
  1076. return '';
  1077. },
  1078. /**
  1079. * Put the screen in "New paste" mode.
  1080. */
  1081. stateNewPaste: function()
  1082. {
  1083. this.message.text('');
  1084. this.attachment.addClass('hidden');
  1085. this.cloneButton.addClass('hidden');
  1086. this.rawTextButton.addClass('hidden');
  1087. this.remainingTime.addClass('hidden');
  1088. this.pasteResult.addClass('hidden');
  1089. this.clearText.addClass('hidden');
  1090. this.discussion.addClass('hidden');
  1091. this.prettyMessage.addClass('hidden');
  1092. this.sendButton.removeClass('hidden');
  1093. this.expiration.removeClass('hidden');
  1094. this.formatter.removeClass('hidden');
  1095. this.burnAfterReadingOption.removeClass('hidden');
  1096. this.openDisc.removeClass('hidden');
  1097. this.newButton.removeClass('hidden');
  1098. this.password.removeClass('hidden');
  1099. this.attach.removeClass('hidden');
  1100. this.message.removeClass('hidden');
  1101. this.preview.removeClass('hidden');
  1102. this.message.focus();
  1103. },
  1104. /**
  1105. * Put the screen in "Existing paste" mode.
  1106. *
  1107. * @param boolean preview (optional) tell if the preview tabs should be displayed, defaults to false.
  1108. */
  1109. stateExistingPaste: function(preview)
  1110. {
  1111. preview = preview || false;
  1112. if (!preview)
  1113. {
  1114. // No "clone" for IE<10.
  1115. if ($('#oldienotice').is(":visible"))
  1116. {
  1117. this.cloneButton.addClass('hidden');
  1118. }
  1119. else
  1120. {
  1121. this.cloneButton.removeClass('hidden');
  1122. }
  1123. this.rawTextButton.removeClass('hidden');
  1124. this.sendButton.addClass('hidden');
  1125. this.attach.addClass('hidden');
  1126. this.expiration.addClass('hidden');
  1127. this.formatter.addClass('hidden');
  1128. this.burnAfterReadingOption.addClass('hidden');
  1129. this.openDisc.addClass('hidden');
  1130. this.newButton.removeClass('hidden');
  1131. this.preview.addClass('hidden');
  1132. }
  1133. this.pasteResult.addClass('hidden');
  1134. this.message.addClass('hidden');
  1135. this.clearText.addClass('hidden');
  1136. this.prettyMessage.addClass('hidden');
  1137. },
  1138. /**
  1139. * If "burn after reading" is checked, disable discussion.
  1140. */
  1141. changeBurnAfterReading: function()
  1142. {
  1143. if (this.burnAfterReading.is(':checked') )
  1144. {
  1145. this.openDisc.addClass('buttondisabled');
  1146. this.openDiscussion.attr({checked: false, disabled: true});
  1147. }
  1148. else
  1149. {
  1150. this.openDisc.removeClass('buttondisabled');
  1151. this.openDiscussion.removeAttr('disabled');
  1152. }
  1153. },
  1154. /**
  1155. * If discussion is checked, disable "burn after reading".
  1156. */
  1157. changeOpenDisc: function()
  1158. {
  1159. if (this.openDiscussion.is(':checked') )
  1160. {
  1161. this.burnAfterReadingOption.addClass('buttondisabled');
  1162. this.burnAfterReading.attr({checked: false, disabled: true});
  1163. }
  1164. else
  1165. {
  1166. this.burnAfterReadingOption.removeClass('buttondisabled');
  1167. this.burnAfterReading.removeAttr('disabled');
  1168. }
  1169. },
  1170. /**
  1171. * Forward to URL shortener.
  1172. *
  1173. * @param Event event
  1174. */
  1175. sendToShortener: function(event)
  1176. {
  1177. event.preventDefault();
  1178. window.location.href = this.shortenerUrl + encodeURIComponent(this.createdPasteUrl);
  1179. },
  1180. /**
  1181. * Reload the page.
  1182. *
  1183. * @param Event event
  1184. */
  1185. reloadPage: function(event)
  1186. {
  1187. event.preventDefault();
  1188. window.location.href = this.scriptLocation();
  1189. },
  1190. /**
  1191. * Return raw text.
  1192. *
  1193. * @param Event event
  1194. */
  1195. rawText: function(event)
  1196. {
  1197. event.preventDefault();
  1198. var paste = $('#pasteFormatter').val() === 'markdown' ?
  1199. this.prettyPrint.text() : this.clearText.text();
  1200. history.pushState(
  1201. null, document.title, this.scriptLocation() + '?' +
  1202. this.pasteID() + '#' + this.pageKey()
  1203. );
  1204. // we use text/html instead of text/plain to avoid a bug when
  1205. // reloading the raw text view (it reverts to type text/html)
  1206. var newDoc = document.open('text/html', 'replace');
  1207. newDoc.write('<pre>' + helper.htmlEntities(paste) + '</pre>');
  1208. newDoc.close();
  1209. },
  1210. /**
  1211. * Clone the current paste.
  1212. *
  1213. * @param Event event
  1214. */
  1215. clonePaste: function(event)
  1216. {
  1217. event.preventDefault();
  1218. this.stateNewPaste();
  1219. // Erase the id and the key in url
  1220. history.replaceState(null, document.title, this.scriptLocation());
  1221. this.showStatus('', false);
  1222. if (this.attachmentLink.attr('href'))
  1223. {
  1224. this.clonedFile.removeClass('hidden');
  1225. this.fileWrap.addClass('hidden');
  1226. }
  1227. this.message.text(
  1228. $('#pasteFormatter').val() === 'markdown' ?
  1229. this.prettyPrint.text() : this.clearText.text()
  1230. );
  1231. $('.navbar-toggle').click();
  1232. },
  1233. /**
  1234. * Set the expiration on bootstrap templates.
  1235. *
  1236. * @param Event event
  1237. */
  1238. setExpiration: function(event)
  1239. {
  1240. event.preventDefault();
  1241. var target = $(event.target);
  1242. $('#pasteExpiration').val(target.data('expiration'));
  1243. $('#pasteExpirationDisplay').text(target.text());
  1244. },
  1245. /**
  1246. * Set the format on bootstrap templates.
  1247. *
  1248. * @param Event event
  1249. */
  1250. setFormat: function(event)
  1251. {
  1252. event.preventDefault();
  1253. var target = $(event.target);
  1254. $('#pasteFormatter').val(target.data('format'));
  1255. $('#pasteFormatterDisplay').text(target.text());
  1256. if (this.messagePreview.parent().hasClass('active')) {
  1257. this.viewPreview(event);
  1258. }
  1259. },
  1260. /**
  1261. * Set the language on bootstrap templates.
  1262. *
  1263. * Sets the language cookie and reloads the page.
  1264. *
  1265. * @param Event event
  1266. */
  1267. setLanguage: function(event)
  1268. {
  1269. document.cookie = 'lang=' + $(event.target).data('lang');
  1270. this.reloadPage(event);
  1271. },
  1272. /**
  1273. * Support input of tab character.
  1274. *
  1275. * @param Event event
  1276. */
  1277. supportTabs: function(event)
  1278. {
  1279. var keyCode = event.keyCode || event.which;
  1280. // tab was pressed
  1281. if (keyCode === 9)
  1282. {
  1283. // prevent the textarea to lose focus
  1284. event.preventDefault();
  1285. // get caret position & selection
  1286. var val = this.value,
  1287. start = this.selectionStart,
  1288. end = this.selectionEnd;
  1289. // set textarea value to: text before caret + tab + text after caret
  1290. this.value = val.substring(0, start) + '\t' + val.substring(end);
  1291. // put caret at right position again
  1292. this.selectionStart = this.selectionEnd = start + 1;
  1293. }
  1294. },
  1295. /**
  1296. * View the editor tab.
  1297. *
  1298. * @param Event event
  1299. */
  1300. viewEditor: function(event)
  1301. {
  1302. event.preventDefault();
  1303. this.messagePreview.parent().removeClass('active');
  1304. this.messageEdit.parent().addClass('active');
  1305. this.message.focus();
  1306. this.stateNewPaste();
  1307. },
  1308. /**
  1309. * View the preview tab.
  1310. *
  1311. * @param Event event
  1312. */
  1313. viewPreview: function(event)
  1314. {
  1315. event.preventDefault();
  1316. this.messageEdit.parent().removeClass('active');
  1317. this.messagePreview.parent().addClass('active');
  1318. this.message.focus();
  1319. this.stateExistingPaste(true);
  1320. this.formatPaste($('#pasteFormatter').val(), this.message.val());
  1321. },
  1322. /**
  1323. * Create a new paste.
  1324. */
  1325. newPaste: function()
  1326. {
  1327. this.stateNewPaste();
  1328. this.showStatus('', false);
  1329. this.message.text('');
  1330. this.changeBurnAfterReading();
  1331. this.changeOpenDisc();
  1332. },
  1333. /**
  1334. * Removes an attachment.
  1335. */
  1336. removeAttachment: function()
  1337. {
  1338. this.clonedFile.addClass('hidden');
  1339. // removes the saved decrypted file data
  1340. this.attachmentLink.attr('href', '');
  1341. // the only way to deselect the file is to recreate the input
  1342. this.fileWrap.html(this.fileWrap.html());
  1343. this.fileWrap.removeClass('hidden');
  1344. },
  1345. /**
  1346. * Focus on the modal password dialog.
  1347. */
  1348. focusPasswordModal: function()
  1349. {
  1350. this.passwordDecrypt.focus();
  1351. },
  1352. /**
  1353. * Decrypt using the password from the modal dialog.
  1354. */
  1355. decryptPasswordModal: function()
  1356. {
  1357. this.passwordInput.val(this.passwordDecrypt.val());
  1358. this.displayMessages();
  1359. },
  1360. /**
  1361. * Submit a password in the modal dialog.
  1362. *
  1363. * @param Event event
  1364. */
  1365. submitPasswordModal: function(event)
  1366. {
  1367. event.preventDefault();
  1368. this.passwordModal.modal('hide');
  1369. },
  1370. /**
  1371. * Display an error message
  1372. * (We use the same function for paste and reply to comments)
  1373. *
  1374. * @param string message : text to display
  1375. */
  1376. showError: function(message)
  1377. {
  1378. if (this.status.length)
  1379. {
  1380. this.status.addClass('errorMessage').text(message);
  1381. }
  1382. else
  1383. {
  1384. this.errorMessage.removeClass('hidden');
  1385. helper.setMessage(this.errorMessage, message);
  1386. }
  1387. if (typeof this.replyStatus !== 'undefined') {
  1388. this.replyStatus.addClass('errorMessage');
  1389. this.replyStatus.addClass(this.errorMessage.attr('class'));
  1390. if (this.status.length)
  1391. {
  1392. this.replyStatus.html(this.status.html());
  1393. }
  1394. else
  1395. {
  1396. this.replyStatus.html(this.errorMessage.html());
  1397. }
  1398. }
  1399. },
  1400. /**
  1401. * Display a status message
  1402. * (We use the same function for paste and reply to comments)
  1403. *
  1404. * @param string message : text to display
  1405. * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
  1406. */
  1407. showStatus: function(message, spin)
  1408. {
  1409. if (typeof this.replyStatus !== 'undefined') {
  1410. this.replyStatus.removeClass('errorMessage').text(message);
  1411. }
  1412. if (!message)
  1413. {
  1414. this.status.html(' ');
  1415. return;
  1416. }
  1417. if (message === '')
  1418. {
  1419. this.status.html(' ');
  1420. return;
  1421. }
  1422. this.status.removeClass('errorMessage').text(message);
  1423. if (spin)
  1424. {
  1425. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0 4px 0 0;" />';
  1426. this.status.prepend(img);
  1427. if (typeof this.replyStatus !== 'undefined') {
  1428. this.replyStatus.prepend(img);
  1429. }
  1430. }
  1431. },
  1432. /**
  1433. * bind events to DOM elements
  1434. */
  1435. bindEvents: function()
  1436. {
  1437. this.burnAfterReading.change($.proxy(this.changeBurnAfterReading, this));
  1438. this.openDisc.change($.proxy(this.changeOpenDisc, this));
  1439. this.sendButton.click($.proxy(this.sendData, this));
  1440. this.cloneButton.click($.proxy(this.clonePaste, this));
  1441. this.rawTextButton.click($.proxy(this.rawText, this));
  1442. this.fileRemoveButton.click($.proxy(this.removeAttachment, this));
  1443. $('.reloadlink').click($.proxy(this.reloadPage, this));
  1444. this.message.keydown(this.supportTabs);
  1445. this.messageEdit.click($.proxy(this.viewEditor, this));
  1446. this.messagePreview.click($.proxy(this.viewPreview, this));
  1447. // bootstrap template drop downs
  1448. $('ul.dropdown-menu li a', $('#expiration').parent()).click($.proxy(this.setExpiration, this));
  1449. $('ul.dropdown-menu li a', $('#formatter').parent()).click($.proxy(this.setFormat, this));
  1450. $('#language ul.dropdown-menu li a').click($.proxy(this.setLanguage, this));
  1451. // page template drop down
  1452. $('#language select option').click($.proxy(this.setLanguage, this));
  1453. // handle modal password request on decryption
  1454. this.passwordModal.on('shown.bs.modal', $.proxy(this.focusPasswordModal, this));
  1455. this.passwordModal.on('hidden.bs.modal', $.proxy(this.decryptPasswordModal, this));
  1456. this.passwordForm.submit($.proxy(this.submitPasswordModal, this));
  1457. },
  1458. /**
  1459. * main application
  1460. */
  1461. init: function()
  1462. {
  1463. // hide "no javascript" message
  1464. $('#noscript').hide();
  1465. // preload jQuery wrapped DOM elements and bind events
  1466. this.attach = $('#attach');
  1467. this.attachment = $('#attachment');
  1468. this.attachmentLink = $('#attachment a');
  1469. this.burnAfterReading = $('#burnafterreading');
  1470. this.burnAfterReadingOption = $('#burnafterreadingoption');
  1471. this.cipherData = $('#cipherdata');
  1472. this.clearText = $('#cleartext');
  1473. this.cloneButton = $('#clonebutton');
  1474. this.clonedFile = $('#clonedfile');
  1475. this.comments = $('#comments');
  1476. this.discussion = $('#discussion');
  1477. this.errorMessage = $('#errormessage');
  1478. this.expiration = $('#expiration');
  1479. this.fileRemoveButton = $('#fileremovebutton');
  1480. this.fileWrap = $('#filewrap');
  1481. this.formatter = $('#formatter');
  1482. this.image = $('#image');
  1483. this.message = $('#message');
  1484. this.messageEdit = $('#messageedit');
  1485. this.messagePreview = $('#messagepreview');
  1486. this.newButton = $('#newbutton');
  1487. this.openDisc = $('#opendisc');
  1488. this.openDiscussion = $('#opendiscussion');
  1489. this.password = $('#password');
  1490. this.passwordInput = $('#passwordinput');
  1491. this.passwordModal = $('#passwordmodal');
  1492. this.passwordForm = $('#passwordform');
  1493. this.passwordDecrypt = $('#passworddecrypt');
  1494. this.pasteResult = $('#pasteresult');
  1495. this.prettyMessage = $('#prettymessage');
  1496. this.prettyPrint = $('#prettyprint');
  1497. this.preview = $('#preview');
  1498. this.rawTextButton = $('#rawtextbutton');
  1499. this.remainingTime = $('#remainingtime');
  1500. this.sendButton = $('#sendbutton');
  1501. this.status = $('#status');
  1502. this.bindEvents();
  1503. // Display status returned by php code if any (eg. Paste was properly deleted.)
  1504. if (this.status.text().length > 0)
  1505. {
  1506. this.showStatus(this.status.text(), false);
  1507. return;
  1508. }
  1509. // Keep line height even if content empty.
  1510. this.status.html(' ');
  1511. // Display an existing paste
  1512. if (this.cipherData.text().length > 1)
  1513. {
  1514. // Missing decryption key in URL?
  1515. if (window.location.hash.length === 0)
  1516. {
  1517. 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?)'));
  1518. return;
  1519. }
  1520. // Show proper elements on screen.
  1521. this.stateExistingPaste();
  1522. this.displayMessages();
  1523. }
  1524. // Display error message from php code.
  1525. else if (this.errorMessage.text().length > 1)
  1526. {
  1527. this.showError(this.errorMessage.text());
  1528. }
  1529. // Create a new paste.
  1530. else
  1531. {
  1532. this.newPaste();
  1533. }
  1534. }
  1535. }
  1536. /**
  1537. * main application start, called when DOM is fully loaded
  1538. * runs privatebin when translations were loaded
  1539. */
  1540. i18n.loadTranslations($.proxy(privatebin.init, privatebin));
  1541. });