privatebin.js 65 KB

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