privatebin.js 71 KB

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