privatebin.js 57 KB

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