privatebin.js 65 KB

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