privatebin.js 57 KB

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