privatebin.js 57 KB

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