privatebin.js 58 KB

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