privatebin.js 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  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 0.22
  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', '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. if ((password || '').trim().length === 0)
  468. {
  469. return sjcl.encrypt(key, this.compress(message), {mode : 'gcm'});
  470. }
  471. return sjcl.encrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), this.compress(message), {mode : 'gcm'});
  472. },
  473. /**
  474. * Decrypt message with key, then decompress.
  475. *
  476. * @param string key
  477. * @param string password
  478. * @param encrypted string data
  479. * @return string readable message
  480. */
  481. decipher: function(key, password, data)
  482. {
  483. if (data !== undefined)
  484. {
  485. try
  486. {
  487. return this.decompress(sjcl.decrypt(key, data));
  488. }
  489. catch(err)
  490. {
  491. try
  492. {
  493. return this.decompress(sjcl.decrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), data));
  494. }
  495. catch(e)
  496. {}
  497. }
  498. }
  499. return '';
  500. }
  501. };
  502. var privatebin = {
  503. /**
  504. * headers to send in AJAX requests
  505. */
  506. headers: {'X-Requested-With': 'JSONHttpRequest'},
  507. /**
  508. * Get the current script location (without search or hash part of the URL).
  509. * eg. http://server.com/zero/?aaaa#bbbb --> http://server.com/zero/
  510. *
  511. * @return string current script location
  512. */
  513. scriptLocation: function()
  514. {
  515. var scriptLocation = window.location.href.substring(0,window.location.href.length
  516. - window.location.search.length - window.location.hash.length),
  517. hashIndex = scriptLocation.indexOf('#');
  518. if (hashIndex !== -1)
  519. {
  520. scriptLocation = scriptLocation.substring(0, hashIndex);
  521. }
  522. return scriptLocation;
  523. },
  524. /**
  525. * Get the pastes unique identifier from the URL
  526. * eg. http://server.com/zero/?c05354954c49a487#c05354954c49a487 returns c05354954c49a487
  527. *
  528. * @return string unique identifier
  529. */
  530. pasteID: function()
  531. {
  532. return window.location.search.substring(1);
  533. },
  534. /**
  535. * Return the deciphering key stored in anchor part of the URL
  536. *
  537. * @return string key
  538. */
  539. pageKey: function()
  540. {
  541. // Some web 2.0 services and redirectors add data AFTER the anchor
  542. // (such as &utm_source=...). We will strip any additional data.
  543. var key = window.location.hash.substring(1), // Get key
  544. i = key.indexOf('=');
  545. // First, strip everything after the equal sign (=) which signals end of base64 string.
  546. if (i > -1)
  547. {
  548. key = key.substring(0, i + 1);
  549. }
  550. // If the equal sign was not present, some parameters may remain:
  551. i = key.indexOf('&');
  552. if (i > -1)
  553. {
  554. key = key.substring(0, i);
  555. }
  556. // Then add trailing equal sign if it's missing
  557. if (key.charAt(key.length - 1) !== '=')
  558. {
  559. key += '=';
  560. }
  561. return key;
  562. },
  563. /**
  564. * ask the user for the password and return it
  565. *
  566. * @throws error when dialog canceled
  567. * @return string password
  568. */
  569. requestPassword: function()
  570. {
  571. var password = prompt(i18n._('Please enter the password for this paste:'), '');
  572. if (password === null)
  573. {
  574. throw 'password prompt canceled';
  575. }
  576. if (password.length === 0)
  577. {
  578. return this.requestPassword();
  579. }
  580. return password;
  581. },
  582. /**
  583. * use given format on paste, defaults to plain text
  584. *
  585. * @param string format
  586. * @param string text
  587. */
  588. formatPaste: function(format, text)
  589. {
  590. helper.setElementText(this.clearText, text);
  591. helper.setElementText(this.prettyPrint, text);
  592. switch (format || 'plaintext')
  593. {
  594. case 'markdown':
  595. if (typeof showdown === 'object')
  596. {
  597. showdown.setOption('strikethrough', true);
  598. showdown.setOption('tables', true);
  599. showdown.setOption('tablesHeaderId', true);
  600. var converter = new showdown.Converter();
  601. this.clearText.html(
  602. converter.makeHtml(text)
  603. );
  604. this.clearText.removeClass('hidden');
  605. }
  606. this.prettyMessage.addClass('hidden');
  607. break;
  608. case 'syntaxhighlighting':
  609. if (typeof prettyPrintOne === 'function')
  610. {
  611. if (typeof prettyPrint === 'function')
  612. {
  613. prettyPrint();
  614. }
  615. this.prettyPrint.html(
  616. prettyPrintOne(
  617. helper.htmlEntities(text), null, true
  618. )
  619. );
  620. }
  621. // fall through, as the rest is the same
  622. default:
  623. // Convert URLs to clickable links.
  624. helper.urls2links(this.clearText);
  625. helper.urls2links(this.prettyPrint);
  626. this.clearText.addClass('hidden');
  627. if (format === 'plaintext')
  628. {
  629. this.prettyPrint.css('white-space', 'pre-wrap');
  630. this.prettyPrint.css('word-break', 'normal');
  631. this.prettyPrint.removeClass('prettyprint');
  632. }
  633. this.prettyMessage.removeClass('hidden');
  634. }
  635. },
  636. /**
  637. * Show decrypted text in the display area, including discussion (if open)
  638. *
  639. * @param string key : decryption key
  640. * @param object paste : paste object including comments to display (items = array with keys ('data','meta')
  641. */
  642. displayMessages: function(key, paste)
  643. {
  644. // Try to decrypt the paste.
  645. var password = this.passwordInput.val();
  646. if (!this.prettyPrint.hasClass('prettyprinted')) {
  647. try
  648. {
  649. if (paste.attachment)
  650. {
  651. var attachment = filter.decipher(key, password, paste.attachment);
  652. if (attachment.length === 0)
  653. {
  654. if (password.length === 0)
  655. {
  656. password = this.requestPassword();
  657. }
  658. attachment = filter.decipher(key, password, paste.attachment);
  659. }
  660. if (attachment.length === 0)
  661. {
  662. throw 'failed to decipher attachment';
  663. }
  664. if (paste.attachmentname)
  665. {
  666. var attachmentname = filter.decipher(key, password, paste.attachmentname);
  667. if (attachmentname.length > 0)
  668. {
  669. this.attachmentLink.attr('download', attachmentname);
  670. }
  671. }
  672. this.attachmentLink.attr('href', attachment);
  673. this.attachment.removeClass('hidden');
  674. // if the attachment is an image, display it
  675. var imagePrefix = 'data:image/';
  676. if (attachment.substring(0, imagePrefix.length) === imagePrefix)
  677. {
  678. this.image.html(
  679. $(document.createElement('img'))
  680. .attr('src', attachment)
  681. .attr('class', 'img-thumbnail')
  682. );
  683. this.image.removeClass('hidden');
  684. }
  685. }
  686. var cleartext = filter.decipher(key, password, paste.data);
  687. if (cleartext.length === 0 && password.length === 0 && !paste.attachment)
  688. {
  689. password = this.requestPassword();
  690. cleartext = filter.decipher(key, password, paste.data);
  691. }
  692. if (cleartext.length === 0 && !paste.attachment)
  693. {
  694. throw 'failed to decipher message';
  695. }
  696. this.passwordInput.val(password);
  697. if (cleartext.length > 0)
  698. {
  699. this.formatPaste(paste.meta.formatter, cleartext);
  700. }
  701. }
  702. catch(err)
  703. {
  704. this.clearText.addClass('hidden');
  705. this.prettyMessage.addClass('hidden');
  706. this.cloneButton.addClass('hidden');
  707. this.showError(i18n._('Could not decrypt data (Wrong key?)'));
  708. return;
  709. }
  710. }
  711. // Display paste expiration / for your eyes only.
  712. if (paste.meta.expire_date)
  713. {
  714. var expiration = helper.secondsToHuman(paste.meta.remaining_time),
  715. expirationLabel = [
  716. 'This document will expire in %d ' + expiration[1] + '.',
  717. 'This document will expire in %d ' + expiration[1] + 's.'
  718. ];
  719. helper.setMessage(this.remainingTime, i18n._(expirationLabel, expiration[0]));
  720. this.remainingTime.removeClass('foryoureyesonly')
  721. .removeClass('hidden');
  722. }
  723. if (paste.meta.burnafterreading)
  724. {
  725. // unfortunately many web servers don't support DELETE (and PUT) out of the box
  726. $.ajax({
  727. type: 'POST',
  728. url: this.scriptLocation() + '?' + this.pasteID(),
  729. data: {deletetoken: 'burnafterreading'},
  730. dataType: 'json',
  731. headers: this.headers
  732. })
  733. .fail(function() {
  734. privatebin.showError(i18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  735. });
  736. helper.setMessage(this.remainingTime, i18n._(
  737. 'FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.'
  738. ));
  739. this.remainingTime.addClass('foryoureyesonly')
  740. .removeClass('hidden');
  741. // Discourage cloning (as it can't really be prevented).
  742. this.cloneButton.addClass('hidden');
  743. }
  744. // If the discussion is opened on this paste, display it.
  745. if (paste.meta.opendiscussion)
  746. {
  747. this.comments.html('');
  748. // iterate over comments
  749. for (var i = 0; i < paste.comments.length; ++i)
  750. {
  751. var place = this.comments;
  752. var comment = paste.comments[i];
  753. var commenttext = filter.decipher(key, password, comment.data);
  754. // If parent comment exists, display below (CSS will automatically shift it right.)
  755. var cname = '#comment_' + comment.parentid;
  756. // If the element exists in page
  757. if ($(cname).length)
  758. {
  759. place = $(cname);
  760. }
  761. var divComment = $('<article><div class="comment" id="comment_' + comment.id + '">'
  762. + '<div class="commentmeta"><span class="nickname"></span><span class="commentdate"></span></div><div class="commentdata"></div>'
  763. + '<button class="btn btn-default btn-sm">' + i18n._('Reply') + '</button>'
  764. + '</div></article>');
  765. divComment.find('button').click({commentid: comment.id}, $.proxy(this.openReply, this));
  766. helper.setElementText(divComment.find('div.commentdata'), commenttext);
  767. // Convert URLs to clickable links in comment.
  768. helper.urls2links(divComment.find('div.commentdata'));
  769. // Try to get optional nickname:
  770. var nick = filter.decipher(key, password, comment.meta.nickname);
  771. if (nick.length > 0)
  772. {
  773. divComment.find('span.nickname').text(nick);
  774. }
  775. else
  776. {
  777. divComment.find('span.nickname').html('<i>' + i18n._('Anonymous') + '</i>');
  778. }
  779. divComment.find('span.commentdate')
  780. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  781. .attr('title', 'CommentID: ' + comment.id);
  782. // If an avatar is available, display it.
  783. if (comment.meta.vizhash)
  784. {
  785. divComment.find('span.nickname')
  786. .before(
  787. '<img src="' + comment.meta.vizhash + '" class="vizhash" title="' +
  788. i18n._('Anonymous avatar (Vizhash of the IP address)') + '" /> '
  789. );
  790. }
  791. place.append(divComment);
  792. }
  793. var divComment = $(
  794. '<div class="comment"><button class="btn btn-default btn-sm">' +
  795. i18n._('Add comment') + '</button></div>'
  796. );
  797. divComment.find('button').click({commentid: this.pasteID()}, $.proxy(this.openReply, this));
  798. this.comments.append(divComment);
  799. this.discussion.removeClass('hidden');
  800. }
  801. },
  802. /**
  803. * Open the comment entry when clicking the "Reply" button of a comment.
  804. *
  805. * @param Event event
  806. */
  807. openReply: function(event)
  808. {
  809. event.preventDefault();
  810. var source = $(event.target),
  811. commentid = event.data.commentid,
  812. hint = i18n._('Optional nickname...');
  813. // Remove any other reply area.
  814. $('div.reply').remove();
  815. var reply = $(
  816. '<div class="reply">' +
  817. '<input type="text" id="nickname" class="form-control" title="' + hint + '" placeholder="' + hint + '" />' +
  818. '<textarea id="replymessage" class="replymessage form-control" cols="80" rows="7"></textarea>' +
  819. '<br /><button id="replybutton" class="btn btn-default btn-sm">' + i18n._('Post comment') + '</button>' +
  820. '<div id="replystatus"> </div>' +
  821. '</div>'
  822. );
  823. reply.find('button').click({parentid: commentid}, $.proxy(this.sendComment, this));
  824. source.after(reply);
  825. $('#replymessage').focus();
  826. },
  827. /**
  828. * Send a reply in a discussion.
  829. *
  830. * @param Event event
  831. */
  832. sendComment: function(event)
  833. {
  834. event.preventDefault();
  835. this.errorMessage.addClass('hidden');
  836. // Do not send if no data.
  837. var replyMessage = $('#replymessage');
  838. if (replyMessage.val().length === 0)
  839. {
  840. return;
  841. }
  842. this.showStatus(i18n._('Sending comment...'), true);
  843. var parentid = event.data.parentid;
  844. var cipherdata = filter.cipher(this.pageKey(), this.passwordInput.val(), replyMessage.val());
  845. var ciphernickname = '';
  846. var nick = $('#nickname').val();
  847. if (nick !== '')
  848. {
  849. ciphernickname = filter.cipher(this.pageKey(), this.passwordInput.val(), nick);
  850. }
  851. var data_to_send = {
  852. data: cipherdata,
  853. parentid: parentid,
  854. pasteid: this.pasteID(),
  855. nickname: ciphernickname
  856. };
  857. $.ajax({
  858. type: 'POST',
  859. url: this.scriptLocation(),
  860. data: data_to_send,
  861. dataType: 'json',
  862. headers: this.headers,
  863. success: function(data)
  864. {
  865. if (data.status === 0)
  866. {
  867. privatebin.showStatus(i18n._('Comment posted.'), false);
  868. $.ajax({
  869. type: 'GET',
  870. url: privatebin.scriptLocation() + '?' + privatebin.pasteID(),
  871. dataType: 'json',
  872. headers: privatebin.headers,
  873. success: function(data)
  874. {
  875. if (data.status === 0)
  876. {
  877. privatebin.displayMessages(privatebin.pageKey(), data);
  878. }
  879. else if (data.status === 1)
  880. {
  881. privatebin.showError(i18n._('Could not refresh display: %s', data.message));
  882. }
  883. else
  884. {
  885. privatebin.showError(i18n._('Could not refresh display: %s', i18n._('unknown status')));
  886. }
  887. }
  888. })
  889. .fail(function() {
  890. privatebin.showError(i18n._('Could not refresh display: %s', i18n._('server error or not responding')));
  891. });
  892. }
  893. else if (data.status === 1)
  894. {
  895. privatebin.showError(i18n._('Could not post comment: %s', data.message));
  896. }
  897. else
  898. {
  899. privatebin.showError(i18n._('Could not post comment: %s', i18n._('unknown status')));
  900. }
  901. }
  902. })
  903. .fail(function() {
  904. privatebin.showError(i18n._('Could not post comment: %s', i18n._('server error or not responding')));
  905. });
  906. },
  907. /**
  908. * Send a new paste to server
  909. *
  910. * @param Event event
  911. */
  912. sendData: function(event)
  913. {
  914. event.preventDefault();
  915. var file = document.getElementById('file'),
  916. files = (file && file.files) ? file.files : null; // FileList object
  917. // Do not send if no data.
  918. if (this.message.val().length === 0 && !(files && files[0]))
  919. {
  920. return;
  921. }
  922. // If sjcl has not collected enough entropy yet, display a message.
  923. if (!sjcl.random.isReady())
  924. {
  925. this.showStatus(i18n._('Sending paste (Please move your mouse for more entropy)...'), true);
  926. sjcl.random.addEventListener('seeded', function() {
  927. this.sendData(event);
  928. });
  929. return;
  930. }
  931. $('.navbar-toggle').click();
  932. this.password.addClass('hidden');
  933. this.showStatus(i18n._('Sending paste...'), true);
  934. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  935. var password = this.passwordInput.val();
  936. if(files && files[0])
  937. {
  938. if(typeof FileReader === undefined)
  939. {
  940. this.showError(i18n._('Your browser does not support uploading encrypted files. Please use a newer browser.'));
  941. return;
  942. }
  943. var reader = new FileReader();
  944. // Closure to capture the file information.
  945. reader.onload = (function(theFile)
  946. {
  947. return function(e) {
  948. privatebin.sendDataContinue(
  949. randomkey,
  950. filter.cipher(randomkey, password, e.target.result),
  951. filter.cipher(randomkey, password, theFile.name)
  952. );
  953. };
  954. })(files[0]);
  955. reader.readAsDataURL(files[0]);
  956. }
  957. else if(this.attachmentLink.attr('href'))
  958. {
  959. this.sendDataContinue(
  960. randomkey,
  961. filter.cipher(randomkey, password, this.attachmentLink.attr('href')),
  962. this.attachmentLink.attr('download')
  963. );
  964. }
  965. else
  966. {
  967. this.sendDataContinue(randomkey, '', '');
  968. }
  969. },
  970. /**
  971. * Send a new paste to server, step 2
  972. *
  973. * @param string randomkey
  974. * @param encrypted string cipherdata_attachment
  975. * @param encrypted string cipherdata_attachment_name
  976. */
  977. sendDataContinue: function(randomkey, cipherdata_attachment, cipherdata_attachment_name)
  978. {
  979. var cipherdata = filter.cipher(randomkey, this.passwordInput.val(), this.message.val());
  980. var data_to_send = {
  981. data: cipherdata,
  982. expire: $('#pasteExpiration').val(),
  983. formatter: $('#pasteFormatter').val(),
  984. burnafterreading: this.burnAfterReading.is(':checked') ? 1 : 0,
  985. opendiscussion: this.openDiscussion.is(':checked') ? 1 : 0
  986. };
  987. if (cipherdata_attachment.length > 0)
  988. {
  989. data_to_send.attachment = cipherdata_attachment;
  990. if (cipherdata_attachment_name.length > 0)
  991. {
  992. data_to_send.attachmentname = cipherdata_attachment_name;
  993. }
  994. }
  995. $.ajax({
  996. type: 'POST',
  997. url: this.scriptLocation(),
  998. data: data_to_send,
  999. dataType: 'json',
  1000. headers: this.headers,
  1001. success: function(data)
  1002. {
  1003. if (data.status === 0) {
  1004. privatebin.stateExistingPaste();
  1005. var url = privatebin.scriptLocation() + '?' + data.id + '#' + randomkey;
  1006. var deleteUrl = privatebin.scriptLocation() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  1007. privatebin.showStatus('', false);
  1008. privatebin.errorMessage.addClass('hidden');
  1009. $('#pastelink').html(
  1010. i18n._(
  1011. 'Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>',
  1012. url, url
  1013. ) + privatebin.shortenUrl(url)
  1014. );
  1015. $('#deletelink').html('<a href="' + deleteUrl + '">' + i18n._('Delete data') + '</a>');
  1016. privatebin.pasteResult.removeClass('hidden');
  1017. // We pre-select the link so that the user only has to [Ctrl]+[c] the link.
  1018. helper.selectText('pasteurl');
  1019. privatebin.showStatus('', false);
  1020. privatebin.formatPaste(data_to_send.formatter, privatebin.message.val());
  1021. }
  1022. else if (data.status === 1)
  1023. {
  1024. privatebin.showError(i18n._('Could not create paste: %s', data.message));
  1025. }
  1026. else
  1027. {
  1028. privatebin.showError(i18n._('Could not create paste: %s', i18n._('unknown status')));
  1029. }
  1030. }
  1031. })
  1032. .fail(function()
  1033. {
  1034. privatebin.showError(i18n._('Could not create paste: %s', i18n._('server error or not responding')));
  1035. });
  1036. },
  1037. /**
  1038. * Check if a URL shortener was defined and create HTML containing a link to it.
  1039. *
  1040. * @param string url
  1041. * @return string html
  1042. */
  1043. shortenUrl: function(url)
  1044. {
  1045. var shortenerHtml = $('#shortenbutton');
  1046. if (shortenerHtml) {
  1047. var shortener = shortenerHtml.data('shortener');
  1048. shortenerHtml.attr(
  1049. 'onclick',
  1050. "window.location.href = '" + shortener + encodeURIComponent(url) + "';"
  1051. );
  1052. return ' ' + $('<div />').append(shortenerHtml.clone()).html();
  1053. }
  1054. return '';
  1055. },
  1056. /**
  1057. * Put the screen in "New paste" mode.
  1058. */
  1059. stateNewPaste: function()
  1060. {
  1061. this.message.text('');
  1062. this.attachment.addClass('hidden');
  1063. this.cloneButton.addClass('hidden');
  1064. this.rawTextButton.addClass('hidden');
  1065. this.remainingTime.addClass('hidden');
  1066. this.pasteResult.addClass('hidden');
  1067. this.clearText.addClass('hidden');
  1068. this.discussion.addClass('hidden');
  1069. this.prettyMessage.addClass('hidden');
  1070. this.sendButton.removeClass('hidden');
  1071. this.expiration.removeClass('hidden');
  1072. this.formatter.removeClass('hidden');
  1073. this.burnAfterReadingOption.removeClass('hidden');
  1074. this.openDisc.removeClass('hidden');
  1075. this.newButton.removeClass('hidden');
  1076. this.password.removeClass('hidden');
  1077. this.attach.removeClass('hidden');
  1078. this.message.removeClass('hidden');
  1079. this.preview.removeClass('hidden');
  1080. this.message.focus();
  1081. },
  1082. /**
  1083. * Put the screen in "Existing paste" mode.
  1084. *
  1085. * @param boolean preview (optional) : tell if the preview tabs should be displayed, defaults to false.
  1086. */
  1087. stateExistingPaste: function(preview)
  1088. {
  1089. preview = preview || false;
  1090. if (!preview)
  1091. {
  1092. // No "clone" for IE<10.
  1093. if ($('#oldienotice').is(":visible"))
  1094. {
  1095. this.cloneButton.addClass('hidden');
  1096. }
  1097. else
  1098. {
  1099. this.cloneButton.removeClass('hidden');
  1100. }
  1101. this.rawTextButton.removeClass('hidden');
  1102. this.sendButton.addClass('hidden');
  1103. this.attach.addClass('hidden');
  1104. this.expiration.addClass('hidden');
  1105. this.formatter.addClass('hidden');
  1106. this.burnAfterReadingOption.addClass('hidden');
  1107. this.openDisc.addClass('hidden');
  1108. this.newButton.removeClass('hidden');
  1109. this.preview.addClass('hidden');
  1110. }
  1111. this.pasteResult.addClass('hidden');
  1112. this.message.addClass('hidden');
  1113. this.clearText.addClass('hidden');
  1114. this.prettyMessage.addClass('hidden');
  1115. },
  1116. /**
  1117. * If "burn after reading" is checked, disable discussion.
  1118. */
  1119. changeBurnAfterReading: function()
  1120. {
  1121. if (this.burnAfterReading.is(':checked') )
  1122. {
  1123. this.openDisc.addClass('buttondisabled');
  1124. this.openDiscussion.attr({checked: false, disabled: true});
  1125. }
  1126. else
  1127. {
  1128. this.openDisc.removeClass('buttondisabled');
  1129. this.openDiscussion.removeAttr('disabled');
  1130. }
  1131. },
  1132. /**
  1133. * Reload the page.
  1134. *
  1135. * @param Event event
  1136. */
  1137. reloadPage: function(event)
  1138. {
  1139. event.preventDefault();
  1140. window.location.href = this.scriptLocation();
  1141. },
  1142. /**
  1143. * Return raw text.
  1144. *
  1145. * @param Event event
  1146. */
  1147. rawText: function(event)
  1148. {
  1149. event.preventDefault();
  1150. var paste = this.clearText.html();
  1151. var newDoc = document.open('text/html', 'replace');
  1152. newDoc.write('<pre>' + paste + '</pre>');
  1153. newDoc.close();
  1154. },
  1155. /**
  1156. * Clone the current paste.
  1157. *
  1158. * @param Event event
  1159. */
  1160. clonePaste: function(event)
  1161. {
  1162. event.preventDefault();
  1163. this.stateNewPaste();
  1164. // Erase the id and the key in url
  1165. history.replaceState(document.title, document.title, this.scriptLocation());
  1166. this.showStatus('', false);
  1167. if (this.attachmentLink.attr('href'))
  1168. {
  1169. this.clonedFile.removeClass('hidden');
  1170. this.fileWrap.addClass('hidden');
  1171. }
  1172. this.message.text(this.clearText.text());
  1173. $('.navbar-toggle').click();
  1174. },
  1175. /**
  1176. * Support input of tab character.
  1177. *
  1178. * @param Event event
  1179. */
  1180. supportTabs: function(event)
  1181. {
  1182. var keyCode = event.keyCode || event.which;
  1183. // tab was pressed
  1184. if (keyCode === 9)
  1185. {
  1186. // prevent the textarea to lose focus
  1187. event.preventDefault();
  1188. // get caret position & selection
  1189. var val = this.value,
  1190. start = this.selectionStart,
  1191. end = this.selectionEnd;
  1192. // set textarea value to: text before caret + tab + text after caret
  1193. this.value = val.substring(0, start) + '\t' + val.substring(end);
  1194. // put caret at right position again
  1195. this.selectionStart = this.selectionEnd = start + 1;
  1196. }
  1197. },
  1198. /**
  1199. * View the editor tab.
  1200. *
  1201. * @param Event event
  1202. */
  1203. viewEditor: function(event)
  1204. {
  1205. event.preventDefault();
  1206. this.messagePreview.parent().removeClass('active');
  1207. this.messageEdit.parent().addClass('active');
  1208. this.message.focus();
  1209. this.stateNewPaste();
  1210. },
  1211. /**
  1212. * View the preview tab.
  1213. *
  1214. * @param Event event
  1215. */
  1216. viewPreview: function(event)
  1217. {
  1218. event.preventDefault();
  1219. this.messageEdit.parent().removeClass('active');
  1220. this.messagePreview.parent().addClass('active');
  1221. this.message.focus();
  1222. this.stateExistingPaste(true);
  1223. this.formatPaste($('#pasteFormatter').val(), this.message.val());
  1224. },
  1225. /**
  1226. * Create a new paste.
  1227. */
  1228. newPaste: function()
  1229. {
  1230. this.stateNewPaste();
  1231. this.showStatus('', false);
  1232. this.message.text('');
  1233. },
  1234. /**
  1235. * Removes an attachment.
  1236. */
  1237. removeAttachment: function()
  1238. {
  1239. this.clonedFile.addClass('hidden');
  1240. // removes the saved decrypted file data
  1241. this.attachmentLink.attr('href', '');
  1242. // the only way to deselect the file is to recreate the input
  1243. this.fileWrap.html(this.fileWrap.html());
  1244. this.fileWrap.removeClass('hidden');
  1245. },
  1246. /**
  1247. * Display an error message
  1248. * (We use the same function for paste and reply to comments)
  1249. *
  1250. * @param string message : text to display
  1251. */
  1252. showError: function(message)
  1253. {
  1254. if (this.status.length)
  1255. {
  1256. this.status.addClass('errorMessage').text(message);
  1257. }
  1258. else
  1259. {
  1260. this.errorMessage.removeClass('hidden');
  1261. helper.setMessage(this.errorMessage, message);
  1262. }
  1263. this.replyStatus.addClass('errorMessage').text(message);
  1264. },
  1265. /**
  1266. * Display a status message
  1267. * (We use the same function for paste and reply to comments)
  1268. *
  1269. * @param string message : text to display
  1270. * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
  1271. */
  1272. showStatus: function(message, spin)
  1273. {
  1274. this.replyStatus.removeClass('errorMessage').text(message);
  1275. if (!message)
  1276. {
  1277. this.status.html(' ');
  1278. return;
  1279. }
  1280. if (message === '')
  1281. {
  1282. this.status.html(' ');
  1283. return;
  1284. }
  1285. this.status.removeClass('errorMessage').text(message);
  1286. if (spin)
  1287. {
  1288. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0 4px 0 0;" />';
  1289. this.status.prepend(img);
  1290. this.replyStatus.prepend(img);
  1291. }
  1292. },
  1293. /**
  1294. * bind events to DOM elements
  1295. */
  1296. bindEvents: function()
  1297. {
  1298. this.burnAfterReading.change($.proxy(this.changeBurnAfterReading, this));
  1299. this.sendButton.click($.proxy(this.sendData, this));
  1300. this.cloneButton.click($.proxy(this.clonePaste, this));
  1301. this.rawTextButton.click($.proxy(this.rawText, this));
  1302. this.fileRemoveButton.click($.proxy(this.removeAttachment, this));
  1303. $('.reloadlink').click($.proxy(this.reloadPage, this));
  1304. this.message.keydown(this.supportTabs);
  1305. this.messageEdit.click($.proxy(this.viewEditor, this));
  1306. this.messagePreview.click($.proxy(this.viewPreview, this));
  1307. },
  1308. /**
  1309. * main application
  1310. */
  1311. init: function()
  1312. {
  1313. // hide "no javascript" message
  1314. $('#noscript').hide();
  1315. // preload jQuery wrapped DOM elements and bind events
  1316. this.attach = $('#attach');
  1317. this.attachment = $('#attachment');
  1318. this.attachmentLink = $('#attachment a');
  1319. this.burnAfterReading = $('#burnafterreading');
  1320. this.burnAfterReadingOption = $('#burnafterreadingoption');
  1321. this.cipherData = $('#cipherdata');
  1322. this.clearText = $('#cleartext');
  1323. this.cloneButton = $('#clonebutton');
  1324. this.clonedFile = $('#clonedfile');
  1325. this.comments = $('#comments');
  1326. this.discussion = $('#discussion');
  1327. this.errorMessage = $('#errormessage');
  1328. this.expiration = $('#expiration');
  1329. this.fileRemoveButton = $('#fileremovebutton');
  1330. this.fileWrap = $('#filewrap');
  1331. this.formatter = $('#formatter');
  1332. this.image = $('#image');
  1333. this.message = $('#message');
  1334. this.messageEdit = $('#messageedit');
  1335. this.messagePreview = $('#messagepreview');
  1336. this.newButton = $('#newbutton');
  1337. this.openDisc = $('#opendisc');
  1338. this.openDiscussion = $('#opendiscussion');
  1339. this.password = $('#password');
  1340. this.passwordInput = $('#passwordinput');
  1341. this.pasteResult = $('#pasteresult');
  1342. this.prettyMessage = $('#prettymessage');
  1343. this.prettyPrint = $('#prettyprint');
  1344. this.preview = $('#preview');
  1345. this.rawTextButton = $('#rawtextbutton');
  1346. this.remainingTime = $('#remainingtime');
  1347. this.replyStatus = $('#replystatus');
  1348. this.sendButton = $('#sendbutton');
  1349. this.status = $('#status');
  1350. this.bindEvents();
  1351. // Display status returned by php code if any (eg. Paste was properly deleted.)
  1352. if (this.status.text().length > 0)
  1353. {
  1354. this.showStatus(this.status.text(), false);
  1355. return;
  1356. }
  1357. // Keep line height even if content empty.
  1358. this.status.html(' ');
  1359. // Display an existing paste
  1360. if (this.cipherData.text().length > 1)
  1361. {
  1362. // Missing decryption key in URL?
  1363. if (window.location.hash.length === 0)
  1364. {
  1365. 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?)'));
  1366. return;
  1367. }
  1368. // List of messages to display.
  1369. var data = $.parseJSON(this.cipherData.text());
  1370. // Show proper elements on screen.
  1371. this.stateExistingPaste();
  1372. this.displayMessages(this.pageKey(), data);
  1373. }
  1374. // Display error message from php code.
  1375. else if (this.errorMessage.text().length > 1)
  1376. {
  1377. this.showError(this.errorMessage.text());
  1378. }
  1379. // Create a new paste.
  1380. else
  1381. {
  1382. this.newPaste();
  1383. }
  1384. }
  1385. }
  1386. /**
  1387. * main application start, called when DOM is fully loaded
  1388. * runs privatebin when translations were loaded
  1389. */
  1390. i18n.loadTranslations($.proxy(privatebin.init, privatebin));
  1391. });