privatebin.js 67 KB

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