privatebin.js 63 KB

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