privatebin.js 62 KB

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