privatebin.js 58 KB

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