privatebin.js 60 KB

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