privatebin.js 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821
  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', '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
  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.clearText.addClass('hidden');
  747. this.prettyMessage.addClass('hidden');
  748. this.cloneButton.addClass('hidden');
  749. this.showError(i18n._('Could not decrypt data (Wrong key?)'));
  750. return;
  751. }
  752. }
  753. // display paste expiration / for your eyes only
  754. if (paste.meta.expire_date)
  755. {
  756. var expiration = helper.secondsToHuman(paste.meta.remaining_time),
  757. expirationLabel = [
  758. 'This document will expire in %d ' + expiration[1] + '.',
  759. 'This document will expire in %d ' + expiration[1] + 's.'
  760. ];
  761. helper.setMessage(this.remainingTime, i18n._(expirationLabel, expiration[0]));
  762. this.remainingTime.removeClass('foryoureyesonly')
  763. .removeClass('hidden');
  764. }
  765. if (paste.meta.burnafterreading)
  766. {
  767. // unfortunately many web servers don't support DELETE (and PUT) out of the box
  768. $.ajax({
  769. type: 'POST',
  770. url: helper.scriptLocation() + '?' + helper.pasteId(),
  771. data: {deletetoken: 'burnafterreading'},
  772. dataType: 'json',
  773. headers: this.headers
  774. })
  775. .fail(function() {
  776. controller.showError(i18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  777. });
  778. helper.setMessage(this.remainingTime, i18n._(
  779. 'FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.'
  780. ));
  781. this.remainingTime.addClass('foryoureyesonly')
  782. .removeClass('hidden');
  783. // discourage cloning (as it can't really be prevented)
  784. this.cloneButton.addClass('hidden');
  785. }
  786. // if the discussion is opened on this paste, display it
  787. if (paste.meta.opendiscussion)
  788. {
  789. this.comments.html('');
  790. // iterate over comments
  791. for (var i = 0; i < paste.comments.length; ++i)
  792. {
  793. var place = this.comments,
  794. comment = paste.comments[i],
  795. commenttext = filter.decipher(key, password, comment.data),
  796. // if parent comment exists, display below (CSS will automatically shift it to the right)
  797. cname = '#comment_' + comment.parentid,
  798. divComment = $('<article><div class="comment" id="comment_' + comment.id
  799. + '"><div class="commentmeta"><span class="nickname"></span>'
  800. + '<span class="commentdate"></span></div>'
  801. + '<div class="commentdata"></div>'
  802. + '<button class="btn btn-default btn-sm">'
  803. + i18n._('Reply') + '</button></div></article>'),
  804. divCommentData = divComment.find('div.commentdata');
  805. // if the element exists in page
  806. if ($(cname).length)
  807. {
  808. place = $(cname);
  809. }
  810. divComment.find('button').click({commentid: comment.id}, $.proxy(this.openReply, this));
  811. helper.setElementText(divCommentData, commenttext);
  812. helper.urls2links(divCommentData);
  813. // try to get optional nickname
  814. var nick = filter.decipher(key, password, comment.meta.nickname);
  815. if (nick.length > 0)
  816. {
  817. divComment.find('span.nickname').text(nick);
  818. }
  819. else
  820. {
  821. divComment.find('span.nickname').html('<i>' + i18n._('Anonymous') + '</i>');
  822. }
  823. divComment.find('span.commentdate')
  824. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  825. .attr('title', 'CommentID: ' + comment.id);
  826. // if an avatar is available, display it
  827. if (comment.meta.vizhash)
  828. {
  829. divComment.find('span.nickname')
  830. .before(
  831. '<img src="' + comment.meta.vizhash + '" class="vizhash" title="' +
  832. i18n._('Anonymous avatar (Vizhash of the IP address)') + '" /> '
  833. );
  834. }
  835. place.append(divComment);
  836. }
  837. var divComment = $(
  838. '<div class="comment"><button class="btn btn-default btn-sm">' +
  839. i18n._('Add comment') + '</button></div>'
  840. );
  841. divComment.find('button').click({commentid: helper.pasteId()}, $.proxy(this.openReply, this));
  842. this.comments.append(divComment);
  843. this.discussion.removeClass('hidden');
  844. }
  845. },
  846. /**
  847. * open the comment entry when clicking the "Reply" button of a comment
  848. *
  849. * @name controller.openReply
  850. * @function
  851. * @param {Event} event
  852. */
  853. openReply: function(event)
  854. {
  855. event.preventDefault();
  856. // remove any other reply area
  857. $('div.reply').remove();
  858. var source = $(event.target),
  859. commentid = event.data.commentid,
  860. hint = i18n._('Optional nickname...'),
  861. reply = $(
  862. '<div class="reply"><input type="text" id="nickname" ' +
  863. 'class="form-control" title="' + hint + '" placeholder="' +
  864. hint + '" /><textarea id="replymessage" class="replymessage ' +
  865. 'form-control" cols="80" rows="7"></textarea><br />' +
  866. '<div id="replystatus"></div><button id="replybutton" ' +
  867. 'class="btn btn-default btn-sm">' + i18n._('Post comment') +
  868. '</button></div>'
  869. );
  870. reply.find('button').click(
  871. {parentid: commentid},
  872. $.proxy(this.sendComment, this)
  873. );
  874. source.after(reply);
  875. this.replyStatus = $('#replystatus');
  876. $('#replymessage').focus();
  877. },
  878. /**
  879. * send a reply in a discussion
  880. *
  881. * @name controller.sendComment
  882. * @function
  883. * @param {Event} event
  884. */
  885. sendComment: function(event)
  886. {
  887. event.preventDefault();
  888. this.errorMessage.addClass('hidden');
  889. // do not send if no data
  890. var replyMessage = $('#replymessage');
  891. if (replyMessage.val().length === 0)
  892. {
  893. return;
  894. }
  895. this.showStatus(i18n._('Sending comment...'), true);
  896. var parentid = event.data.parentid,
  897. key = helper.pageKey(),
  898. cipherdata = filter.cipher(key, this.passwordInput.val(), replyMessage.val()),
  899. ciphernickname = '',
  900. nick = $('#nickname').val();
  901. if (nick.length > 0)
  902. {
  903. ciphernickname = filter.cipher(key, this.passwordInput.val(), nick);
  904. }
  905. var data_to_send = {
  906. data: cipherdata,
  907. parentid: parentid,
  908. pasteid: helper.pasteId(),
  909. nickname: ciphernickname
  910. };
  911. $.ajax({
  912. type: 'POST',
  913. url: helper.scriptLocation(),
  914. data: data_to_send,
  915. dataType: 'json',
  916. headers: this.headers,
  917. success: function(data)
  918. {
  919. if (data.status === 0)
  920. {
  921. controller.showStatus(i18n._('Comment posted.'));
  922. $.ajax({
  923. type: 'GET',
  924. url: helper.scriptLocation() + '?' + helper.pasteId(),
  925. dataType: 'json',
  926. headers: controller.headers,
  927. success: function(data)
  928. {
  929. if (data.status === 0)
  930. {
  931. controller.displayMessages(data);
  932. }
  933. else if (data.status === 1)
  934. {
  935. controller.showError(i18n._('Could not refresh display: %s', data.message));
  936. }
  937. else
  938. {
  939. controller.showError(i18n._('Could not refresh display: %s', i18n._('unknown status')));
  940. }
  941. }
  942. })
  943. .fail(function() {
  944. controller.showError(i18n._('Could not refresh display: %s', i18n._('server error or not responding')));
  945. });
  946. }
  947. else if (data.status === 1)
  948. {
  949. controller.showError(i18n._('Could not post comment: %s', data.message));
  950. }
  951. else
  952. {
  953. controller.showError(i18n._('Could not post comment: %s', i18n._('unknown status')));
  954. }
  955. }
  956. })
  957. .fail(function() {
  958. controller.showError(i18n._('Could not post comment: %s', i18n._('server error or not responding')));
  959. });
  960. },
  961. /**
  962. * send a new paste to server
  963. *
  964. * @name controller.sendData
  965. * @function
  966. * @param {Event} event
  967. */
  968. sendData: function(event)
  969. {
  970. event.preventDefault();
  971. var file = document.getElementById('file'),
  972. files = (file && file.files) ? file.files : null; // FileList object
  973. // do not send if no data.
  974. if (this.message.val().length === 0 && !(files && files[0]))
  975. {
  976. return;
  977. }
  978. // if sjcl has not collected enough entropy yet, display a message
  979. if (!sjcl.random.isReady())
  980. {
  981. this.showStatus(i18n._('Sending paste (Please move your mouse for more entropy)...'), true);
  982. sjcl.random.addEventListener('seeded', function() {
  983. this.sendData(event);
  984. });
  985. return;
  986. }
  987. $('.navbar-toggle').click();
  988. this.password.addClass('hidden');
  989. this.showStatus(i18n._('Sending paste...'), true);
  990. this.stateSubmittingPaste();
  991. var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0),
  992. password = this.passwordInput.val();
  993. if(files && files[0])
  994. {
  995. if(typeof FileReader === undefined)
  996. {
  997. // revert loading status…
  998. this.stateNewPaste();
  999. this.showError(i18n._('Your browser does not support uploading encrypted files. Please use a newer browser.'));
  1000. return;
  1001. }
  1002. var reader = new FileReader();
  1003. // closure to capture the file information
  1004. reader.onload = (function(theFile)
  1005. {
  1006. return function(e) {
  1007. controller.sendDataContinue(
  1008. randomkey,
  1009. filter.cipher(randomkey, password, e.target.result),
  1010. filter.cipher(randomkey, password, theFile.name)
  1011. );
  1012. };
  1013. })(files[0]);
  1014. reader.readAsDataURL(files[0]);
  1015. }
  1016. else if(this.attachmentLink.attr('href'))
  1017. {
  1018. this.sendDataContinue(
  1019. randomkey,
  1020. filter.cipher(randomkey, password, this.attachmentLink.attr('href')),
  1021. this.attachmentLink.attr('download')
  1022. );
  1023. }
  1024. else
  1025. {
  1026. this.sendDataContinue(randomkey, '', '');
  1027. }
  1028. },
  1029. /**
  1030. * send a new paste to server, step 2
  1031. *
  1032. * @name controller.sendDataContinue
  1033. * @function
  1034. * @param {string} randomkey
  1035. * @param {string} cipherdata_attachment
  1036. * @param {string} cipherdata_attachment_name
  1037. */
  1038. sendDataContinue: function(randomkey, cipherdata_attachment, cipherdata_attachment_name)
  1039. {
  1040. var cipherdata = filter.cipher(randomkey, this.passwordInput.val(), this.message.val()),
  1041. data_to_send = {
  1042. data: cipherdata,
  1043. expire: $('#pasteExpiration').val(),
  1044. formatter: $('#pasteFormatter').val(),
  1045. burnafterreading: this.burnAfterReading.is(':checked') ? 1 : 0,
  1046. opendiscussion: this.openDiscussion.is(':checked') ? 1 : 0
  1047. };
  1048. if (cipherdata_attachment.length > 0)
  1049. {
  1050. data_to_send.attachment = cipherdata_attachment;
  1051. if (cipherdata_attachment_name.length > 0)
  1052. {
  1053. data_to_send.attachmentname = cipherdata_attachment_name;
  1054. }
  1055. }
  1056. $.ajax({
  1057. type: 'POST',
  1058. url: helper.scriptLocation(),
  1059. data: data_to_send,
  1060. dataType: 'json',
  1061. headers: this.headers,
  1062. success: function(data)
  1063. {
  1064. if (data.status === 0) {
  1065. controller.stateExistingPaste();
  1066. var url = helper.scriptLocation() + '?' + data.id + '#' + randomkey,
  1067. deleteUrl = helper.scriptLocation() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  1068. controller.showStatus('');
  1069. controller.errorMessage.addClass('hidden');
  1070. // show new URL in browser bar
  1071. history.pushState({type: 'newpaste'}, document.title, url);
  1072. $('#pastelink').html(
  1073. i18n._(
  1074. 'Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>',
  1075. url, url
  1076. ) + controller.shortenUrl(url)
  1077. );
  1078. // save newly created element
  1079. controller.pasteUrl = $('#pasteurl');
  1080. // and add click event
  1081. controller.pasteUrl.click($.proxy(controller.pasteLinkClick, controller));
  1082. var shortenButton = $('#shortenbutton');
  1083. if (shortenButton) {
  1084. shortenButton.click($.proxy(controller.sendToShortener, controller));
  1085. }
  1086. $('#deletelink').html('<a href="' + deleteUrl + '">' + i18n._('Delete data') + '</a>');
  1087. controller.pasteResult.removeClass('hidden');
  1088. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1089. helper.selectText('pasteurl');
  1090. controller.showStatus('');
  1091. controller.formatPaste(data_to_send.formatter, controller.message.val());
  1092. }
  1093. else if (data.status === 1)
  1094. {
  1095. // revert loading status…
  1096. controller.stateNewPaste();
  1097. controller.showError(i18n._('Could not create paste: %s', data.message));
  1098. }
  1099. else
  1100. {
  1101. // revert loading status…
  1102. controller.stateNewPaste();
  1103. controller.showError(i18n._('Could not create paste: %s', i18n._('unknown status')));
  1104. }
  1105. }
  1106. })
  1107. .fail(function()
  1108. {
  1109. // revert loading status…
  1110. this.stateNewPaste();
  1111. controller.showError(i18n._('Could not create paste: %s', i18n._('server error or not responding')));
  1112. });
  1113. },
  1114. /**
  1115. * check if a URL shortener was defined and create HTML containing a link to it
  1116. *
  1117. * @name controller.shortenUrl
  1118. * @function
  1119. * @param {string} url
  1120. * @return {string} html
  1121. */
  1122. shortenUrl: function(url)
  1123. {
  1124. var shortenerHtml = $('#shortenbutton');
  1125. if (shortenerHtml) {
  1126. this.shortenerUrl = shortenerHtml.data('shortener');
  1127. this.createdPasteUrl = url;
  1128. return ' ' + $('<div />').append(shortenerHtml.clone()).html();
  1129. }
  1130. return '';
  1131. },
  1132. /**
  1133. * put the screen in "New paste" mode
  1134. *
  1135. * @name controller.stateNewPaste
  1136. * @function
  1137. */
  1138. stateNewPaste: function()
  1139. {
  1140. this.message.text('');
  1141. this.attachment.addClass('hidden');
  1142. this.cloneButton.addClass('hidden');
  1143. this.rawTextButton.addClass('hidden');
  1144. this.remainingTime.addClass('hidden');
  1145. this.pasteResult.addClass('hidden');
  1146. this.clearText.addClass('hidden');
  1147. this.discussion.addClass('hidden');
  1148. this.prettyMessage.addClass('hidden');
  1149. this.loadingIndicator.addClass('hidden');
  1150. this.sendButton.removeClass('hidden');
  1151. this.expiration.removeClass('hidden');
  1152. this.formatter.removeClass('hidden');
  1153. this.burnAfterReadingOption.removeClass('hidden');
  1154. this.openDisc.removeClass('hidden');
  1155. this.newButton.removeClass('hidden');
  1156. this.password.removeClass('hidden');
  1157. this.attach.removeClass('hidden');
  1158. this.message.removeClass('hidden');
  1159. this.preview.removeClass('hidden');
  1160. this.message.focus();
  1161. },
  1162. /**
  1163. * put the screen in mode after submitting a paste
  1164. *
  1165. * @name controller.stateSubmittingPaste
  1166. * @function
  1167. */
  1168. stateSubmittingPaste: function()
  1169. {
  1170. this.message.text('');
  1171. this.attachment.addClass('hidden');
  1172. this.cloneButton.addClass('hidden');
  1173. this.rawTextButton.addClass('hidden');
  1174. this.remainingTime.addClass('hidden');
  1175. this.pasteResult.addClass('hidden');
  1176. this.clearText.addClass('hidden');
  1177. this.discussion.addClass('hidden');
  1178. this.prettyMessage.addClass('hidden');
  1179. this.sendButton.addClass('hidden');
  1180. this.expiration.addClass('hidden');
  1181. this.formatter.addClass('hidden');
  1182. this.burnAfterReadingOption.addClass('hidden');
  1183. this.openDisc.addClass('hidden');
  1184. this.newButton.addClass('hidden');
  1185. this.password.addClass('hidden');
  1186. this.attach.addClass('hidden');
  1187. this.message.addClass('hidden');
  1188. this.preview.addClass('hidden');
  1189. this.loadingIndicator.removeClass('hidden');
  1190. },
  1191. /**
  1192. * put the screen in "Existing paste" mode
  1193. *
  1194. * @name controller.stateExistingPaste
  1195. * @function
  1196. * @param {boolean} [preview=false] - (optional) tell if the preview tabs should be displayed, defaults to false
  1197. */
  1198. stateExistingPaste: function(preview)
  1199. {
  1200. preview = preview || false;
  1201. if (!preview)
  1202. {
  1203. // no "clone" for IE<10.
  1204. if ($('#oldienotice').is(":visible"))
  1205. {
  1206. this.cloneButton.addClass('hidden');
  1207. }
  1208. else
  1209. {
  1210. this.cloneButton.removeClass('hidden');
  1211. }
  1212. this.rawTextButton.removeClass('hidden');
  1213. this.sendButton.addClass('hidden');
  1214. this.attach.addClass('hidden');
  1215. this.expiration.addClass('hidden');
  1216. this.formatter.addClass('hidden');
  1217. this.burnAfterReadingOption.addClass('hidden');
  1218. this.openDisc.addClass('hidden');
  1219. this.newButton.removeClass('hidden');
  1220. this.preview.addClass('hidden');
  1221. }
  1222. this.pasteResult.addClass('hidden');
  1223. this.message.addClass('hidden');
  1224. this.clearText.addClass('hidden');
  1225. this.prettyMessage.addClass('hidden');
  1226. this.loadingIndicator.addClass('hidden');
  1227. },
  1228. /**
  1229. * when "burn after reading" is checked, disable discussion
  1230. *
  1231. * @name controller.changeBurnAfterReading
  1232. * @function
  1233. */
  1234. changeBurnAfterReading: function()
  1235. {
  1236. if (this.burnAfterReading.is(':checked') )
  1237. {
  1238. this.openDisc.addClass('buttondisabled');
  1239. this.openDiscussion.attr({checked: false, disabled: true});
  1240. }
  1241. else
  1242. {
  1243. this.openDisc.removeClass('buttondisabled');
  1244. this.openDiscussion.removeAttr('disabled');
  1245. }
  1246. },
  1247. /**
  1248. * when discussion is checked, disable "burn after reading"
  1249. *
  1250. * @name controller.changeOpenDisc
  1251. * @function
  1252. */
  1253. changeOpenDisc: function()
  1254. {
  1255. if (this.openDiscussion.is(':checked') )
  1256. {
  1257. this.burnAfterReadingOption.addClass('buttondisabled');
  1258. this.burnAfterReading.attr({checked: false, disabled: true});
  1259. }
  1260. else
  1261. {
  1262. this.burnAfterReadingOption.removeClass('buttondisabled');
  1263. this.burnAfterReading.removeAttr('disabled');
  1264. }
  1265. },
  1266. /**
  1267. * forward to URL shortener
  1268. *
  1269. * @name controller.sendToShortener
  1270. * @function
  1271. * @param {Event} event
  1272. */
  1273. sendToShortener: function(event)
  1274. {
  1275. event.preventDefault();
  1276. window.location.href = this.shortenerUrl + encodeURIComponent(this.createdPasteUrl);
  1277. },
  1278. /**
  1279. * reload the page
  1280. *
  1281. * @name controller.reloadPage
  1282. * @function
  1283. * @param {Event} event
  1284. */
  1285. reloadPage: function(event)
  1286. {
  1287. event.preventDefault();
  1288. window.location.href = helper.scriptLocation();
  1289. },
  1290. /**
  1291. * return raw text
  1292. *
  1293. * @name controller.rawText
  1294. * @function
  1295. * @param {Event} event
  1296. */
  1297. rawText: function(event)
  1298. {
  1299. event.preventDefault();
  1300. var paste = $('#pasteFormatter').val() === 'markdown' ?
  1301. this.prettyPrint.text() : this.clearText.text();
  1302. history.pushState(
  1303. null, document.title, helper.scriptLocation() + '?' +
  1304. helper.pasteId() + '#' + helper.pageKey()
  1305. );
  1306. // we use text/html instead of text/plain to avoid a bug when
  1307. // reloading the raw text view (it reverts to type text/html)
  1308. var newDoc = document.open('text/html', 'replace');
  1309. newDoc.write('<pre>' + helper.htmlEntities(paste) + '</pre>');
  1310. newDoc.close();
  1311. },
  1312. /**
  1313. * clone the current paste
  1314. *
  1315. * @name controller.clonePaste
  1316. * @function
  1317. * @param {Event} event
  1318. */
  1319. clonePaste: function(event)
  1320. {
  1321. event.preventDefault();
  1322. this.stateNewPaste();
  1323. // erase the id and the key in url
  1324. history.replaceState(null, document.title, helper.scriptLocation());
  1325. this.showStatus('');
  1326. if (this.attachmentLink.attr('href'))
  1327. {
  1328. this.clonedFile.removeClass('hidden');
  1329. this.fileWrap.addClass('hidden');
  1330. }
  1331. this.message.text(
  1332. $('#pasteFormatter').val() === 'markdown' ?
  1333. this.prettyPrint.text() : this.clearText.text()
  1334. );
  1335. $('.navbar-toggle').click();
  1336. },
  1337. /**
  1338. * set the expiration on bootstrap templates
  1339. *
  1340. * @name controller.setExpiration
  1341. * @function
  1342. * @param {Event} event
  1343. */
  1344. setExpiration: function(event)
  1345. {
  1346. event.preventDefault();
  1347. var target = $(event.target);
  1348. $('#pasteExpiration').val(target.data('expiration'));
  1349. $('#pasteExpirationDisplay').text(target.text());
  1350. },
  1351. /**
  1352. * set the format on bootstrap templates
  1353. *
  1354. * @name controller.setFormat
  1355. * @function
  1356. * @param {Event} event
  1357. */
  1358. setFormat: function(event)
  1359. {
  1360. event.preventDefault();
  1361. var target = $(event.target);
  1362. $('#pasteFormatter').val(target.data('format'));
  1363. $('#pasteFormatterDisplay').text(target.text());
  1364. if (this.messagePreview.parent().hasClass('active')) {
  1365. this.viewPreview(event);
  1366. }
  1367. },
  1368. /**
  1369. * set the language in a cookie and reload the page
  1370. *
  1371. * @name controller.setLanguage
  1372. * @function
  1373. * @param {Event} event
  1374. */
  1375. setLanguage: function(event)
  1376. {
  1377. document.cookie = 'lang=' + $(event.target).data('lang');
  1378. this.reloadPage(event);
  1379. },
  1380. /**
  1381. * support input of tab character
  1382. *
  1383. * @name controller.supportTabs
  1384. * @function
  1385. * @param {Event} event
  1386. */
  1387. supportTabs: function(event)
  1388. {
  1389. var keyCode = event.keyCode || event.which;
  1390. // tab was pressed
  1391. if (keyCode === 9)
  1392. {
  1393. // prevent the textarea to lose focus
  1394. event.preventDefault();
  1395. // get caret position & selection
  1396. var val = this.value,
  1397. start = this.selectionStart,
  1398. end = this.selectionEnd;
  1399. // set textarea value to: text before caret + tab + text after caret
  1400. this.value = val.substring(0, start) + '\t' + val.substring(end);
  1401. // put caret at right position again
  1402. this.selectionStart = this.selectionEnd = start + 1;
  1403. }
  1404. },
  1405. /**
  1406. * view the editor tab
  1407. *
  1408. * @name controller.viewEditor
  1409. * @function
  1410. * @param {Event} event
  1411. */
  1412. viewEditor: function(event)
  1413. {
  1414. event.preventDefault();
  1415. this.messagePreview.parent().removeClass('active');
  1416. this.messageEdit.parent().addClass('active');
  1417. this.message.focus();
  1418. this.stateNewPaste();
  1419. },
  1420. /**
  1421. * view the preview tab
  1422. *
  1423. * @name controller.viewPreview
  1424. * @function
  1425. * @param {Event} event
  1426. */
  1427. viewPreview: function(event)
  1428. {
  1429. event.preventDefault();
  1430. this.messageEdit.parent().removeClass('active');
  1431. this.messagePreview.parent().addClass('active');
  1432. this.message.focus();
  1433. this.stateExistingPaste(true);
  1434. this.formatPaste($('#pasteFormatter').val(), this.message.val());
  1435. },
  1436. /**
  1437. * handle history (pop) state changes
  1438. *
  1439. * currently this does only handle redirects to the home page.
  1440. *
  1441. * @name controller.historyChange
  1442. * @function
  1443. * @param {Event} event
  1444. */
  1445. historyChange: function(event)
  1446. {
  1447. var currentLocation = helper.scriptLocation();
  1448. if (event.originalEvent.state === null && // no state object passed
  1449. event.originalEvent.target.location.href === currentLocation && // target location is home page
  1450. window.location.href === currentLocation // and we are not already on the home page
  1451. ) {
  1452. // redirect to home page
  1453. window.location.href = currentLocation;
  1454. }
  1455. },
  1456. /**
  1457. * Forces opening the paste if the link does not do this automatically.
  1458. *
  1459. * This is necessary as browsers will not reload the page when it is
  1460. * already loaded (which is fake as it is set via history.pushState()).
  1461. *
  1462. * @name controller.pasteLinkClick
  1463. * @function
  1464. * @param {Event} event
  1465. */
  1466. pasteLinkClick: function(event)
  1467. {
  1468. // check if location is (already) shown in URL bar
  1469. if (window.location.href === this.pasteUrl.attr('href')) {
  1470. // if so we need to load link by reloading the site
  1471. this.reloadPage(event);
  1472. }
  1473. },
  1474. /**
  1475. * create a new paste
  1476. *
  1477. * @name controller.newPaste
  1478. * @function
  1479. */
  1480. newPaste: function()
  1481. {
  1482. this.stateNewPaste();
  1483. this.showStatus('');
  1484. this.message.text('');
  1485. this.changeBurnAfterReading();
  1486. this.changeOpenDisc();
  1487. },
  1488. /**
  1489. * removes an attachment
  1490. *
  1491. * @name controller.removeAttachment
  1492. * @function
  1493. */
  1494. removeAttachment: function()
  1495. {
  1496. this.clonedFile.addClass('hidden');
  1497. // removes the saved decrypted file data
  1498. this.attachmentLink.attr('href', '');
  1499. // the only way to deselect the file is to recreate the input
  1500. this.fileWrap.html(this.fileWrap.html());
  1501. this.fileWrap.removeClass('hidden');
  1502. },
  1503. /**
  1504. * decrypt using the password from the modal dialog
  1505. *
  1506. * @name controller.decryptPasswordModal
  1507. * @function
  1508. */
  1509. decryptPasswordModal: function()
  1510. {
  1511. this.passwordInput.val(this.passwordDecrypt.val());
  1512. this.displayMessages();
  1513. },
  1514. /**
  1515. * submit a password in the modal dialog
  1516. *
  1517. * @name controller.submitPasswordModal
  1518. * @function
  1519. * @param {Event} event
  1520. */
  1521. submitPasswordModal: function(event)
  1522. {
  1523. event.preventDefault();
  1524. this.passwordModal.modal('hide');
  1525. },
  1526. /**
  1527. * display an error message,
  1528. * we use the same function for paste and reply to comments
  1529. *
  1530. * @name controller.showError
  1531. * @function
  1532. * @param {string} message - text to display
  1533. */
  1534. showError: function(message)
  1535. {
  1536. if (this.status.length)
  1537. {
  1538. this.status.addClass('errorMessage').text(message);
  1539. }
  1540. else
  1541. {
  1542. this.errorMessage.removeClass('hidden');
  1543. helper.setMessage(this.errorMessage, message);
  1544. }
  1545. if (typeof this.replyStatus !== 'undefined') {
  1546. this.replyStatus.addClass('errorMessage');
  1547. this.replyStatus.addClass(this.errorMessage.attr('class'));
  1548. if (this.status.length)
  1549. {
  1550. this.replyStatus.html(this.status.html());
  1551. }
  1552. else
  1553. {
  1554. this.replyStatus.html(this.errorMessage.html());
  1555. }
  1556. }
  1557. },
  1558. /**
  1559. * display a status message,
  1560. * we use the same function for paste and reply to comments
  1561. *
  1562. * @name controller.showStatus
  1563. * @function
  1564. * @param {string} message - text to display
  1565. * @param {boolean} [spin=false] - (optional) tell if the "spinning" animation should be displayed, defaults to false
  1566. */
  1567. showStatus: function(message, spin)
  1568. {
  1569. if (spin || false)
  1570. {
  1571. var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0 4px 0 0;" />';
  1572. this.status.prepend(img);
  1573. if (typeof this.replyStatus !== 'undefined') {
  1574. this.replyStatus.prepend(img);
  1575. }
  1576. }
  1577. if (typeof this.replyStatus !== 'undefined') {
  1578. this.replyStatus.removeClass('errorMessage').text(message);
  1579. }
  1580. if (!message)
  1581. {
  1582. this.status.html(' ');
  1583. return;
  1584. }
  1585. if (message === '')
  1586. {
  1587. this.status.html(' ');
  1588. return;
  1589. }
  1590. this.status.removeClass('errorMessage').text(message);
  1591. },
  1592. /**
  1593. * bind events to DOM elements
  1594. *
  1595. * @name controller.bindEvents
  1596. * @function
  1597. */
  1598. bindEvents: function()
  1599. {
  1600. this.burnAfterReading.change($.proxy(this.changeBurnAfterReading, this));
  1601. this.openDisc.change($.proxy(this.changeOpenDisc, this));
  1602. this.sendButton.click($.proxy(this.sendData, this));
  1603. this.cloneButton.click($.proxy(this.clonePaste, this));
  1604. this.rawTextButton.click($.proxy(this.rawText, this));
  1605. this.fileRemoveButton.click($.proxy(this.removeAttachment, this));
  1606. $('.reloadlink').click($.proxy(this.reloadPage, this));
  1607. this.message.keydown(this.supportTabs);
  1608. this.messageEdit.click($.proxy(this.viewEditor, this));
  1609. this.messagePreview.click($.proxy(this.viewPreview, this));
  1610. // bootstrap template drop downs
  1611. $('ul.dropdown-menu li a', $('#expiration').parent()).click($.proxy(this.setExpiration, this));
  1612. $('ul.dropdown-menu li a', $('#formatter').parent()).click($.proxy(this.setFormat, this));
  1613. $('#language ul.dropdown-menu li a').click($.proxy(this.setLanguage, this));
  1614. // page template drop down
  1615. $('#language select option').click($.proxy(this.setLanguage, this));
  1616. // handle modal password request on decryption
  1617. this.passwordModal.on('shown.bs.modal', $.proxy(this.passwordDecrypt.focus, this));
  1618. this.passwordModal.on('hidden.bs.modal', $.proxy(this.decryptPasswordModal, this));
  1619. this.passwordForm.submit($.proxy(this.submitPasswordModal, this));
  1620. $(window).on('popstate', $.proxy(this.historyChange, this));
  1621. },
  1622. /**
  1623. * main application
  1624. *
  1625. * @name controller.init
  1626. * @function
  1627. */
  1628. init: function()
  1629. {
  1630. // hide "no javascript" message
  1631. $('#noscript').hide();
  1632. // preload jQuery wrapped DOM elements and bind events
  1633. this.attach = $('#attach');
  1634. this.attachment = $('#attachment');
  1635. this.attachmentLink = $('#attachment a');
  1636. this.burnAfterReading = $('#burnafterreading');
  1637. this.burnAfterReadingOption = $('#burnafterreadingoption');
  1638. this.cipherData = $('#cipherdata');
  1639. this.clearText = $('#cleartext');
  1640. this.cloneButton = $('#clonebutton');
  1641. this.clonedFile = $('#clonedfile');
  1642. this.comments = $('#comments');
  1643. this.discussion = $('#discussion');
  1644. this.errorMessage = $('#errormessage');
  1645. this.expiration = $('#expiration');
  1646. this.fileRemoveButton = $('#fileremovebutton');
  1647. this.fileWrap = $('#filewrap');
  1648. this.formatter = $('#formatter');
  1649. this.image = $('#image');
  1650. this.loadingIndicator = $('#loadingindicator');
  1651. this.message = $('#message');
  1652. this.messageEdit = $('#messageedit');
  1653. this.messagePreview = $('#messagepreview');
  1654. this.newButton = $('#newbutton');
  1655. this.openDisc = $('#opendisc');
  1656. this.openDiscussion = $('#opendiscussion');
  1657. this.password = $('#password');
  1658. this.passwordInput = $('#passwordinput');
  1659. this.passwordModal = $('#passwordmodal');
  1660. this.passwordForm = $('#passwordform');
  1661. this.passwordDecrypt = $('#passworddecrypt');
  1662. this.pasteResult = $('#pasteresult');
  1663. // this.pasteUrl is saved in sendDataContinue() if/after it is
  1664. // actually created
  1665. this.prettyMessage = $('#prettymessage');
  1666. this.prettyPrint = $('#prettyprint');
  1667. this.preview = $('#preview');
  1668. this.rawTextButton = $('#rawtextbutton');
  1669. this.remainingTime = $('#remainingtime');
  1670. this.sendButton = $('#sendbutton');
  1671. this.status = $('#status');
  1672. this.bindEvents();
  1673. // display status returned by php code, if any (eg. paste was properly deleted)
  1674. if (this.status.text().length > 0)
  1675. {
  1676. this.showStatus(this.status.text());
  1677. return;
  1678. }
  1679. // keep line height even if content empty
  1680. this.status.html(' ');
  1681. // display an existing paste
  1682. if (this.cipherData.text().length > 1)
  1683. {
  1684. // missing decryption key in URL?
  1685. if (window.location.hash.length === 0)
  1686. {
  1687. 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?)'));
  1688. return;
  1689. }
  1690. // show proper elements on screen
  1691. this.stateExistingPaste();
  1692. this.displayMessages();
  1693. }
  1694. // display error message from php code
  1695. else if (this.errorMessage.text().length > 1)
  1696. {
  1697. this.showError(this.errorMessage.text());
  1698. }
  1699. // create a new paste
  1700. else
  1701. {
  1702. this.newPaste();
  1703. }
  1704. }
  1705. }
  1706. /**
  1707. * main application start, called when DOM is fully loaded and
  1708. * runs controller initalization after translations are loaded
  1709. */
  1710. $(i18n.loadTranslations);
  1711. return {
  1712. helper: helper,
  1713. i18n: i18n,
  1714. filter: filter,
  1715. controller: controller
  1716. };
  1717. }(jQuery, sjcl, Base64, RawDeflate);