privatebin.js 58 KB

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