privatebin.js 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523
  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. /** global: Base64 */
  14. /** global: FileReader */
  15. /** global: RawDeflate */
  16. /** global: history */
  17. /** global: navigator */
  18. /** global: prettyPrint */
  19. /** global: prettyPrintOne */
  20. /** global: showdown */
  21. /** global: sjcl */
  22. // Immediately start random number generator collector.
  23. sjcl.random.startCollectors();
  24. // main application start, called when DOM is fully loaded
  25. jQuery(document).ready(function() {
  26. // run main controller
  27. $.PrivateBin.Controller.init();
  28. });
  29. jQuery.PrivateBin = function($, sjcl, Base64, RawDeflate) {
  30. 'use strict';
  31. /**
  32. * static Helper methods
  33. *
  34. * @param {object} window
  35. * @param {object} document
  36. * @class
  37. */
  38. var Helper = (function (window, document) {
  39. var me = {};
  40. /**
  41. * character to HTML entity lookup table
  42. *
  43. * @see {@link https://github.com/janl/mustache.js/blob/master/mustache.js#L60}
  44. * @private
  45. * @enum {Object}
  46. * @readonly
  47. */
  48. var entityMap = {
  49. '&': '&',
  50. '<': '&lt;',
  51. '>': '&gt;',
  52. '"': '&quot;',
  53. "'": '&#39;',
  54. '/': '&#x2F;',
  55. '`': '&#x60;',
  56. '=': '&#x3D;'
  57. };
  58. /**
  59. * cache for script location
  60. *
  61. * @private
  62. * @enum {string|null}
  63. */
  64. var baseUri = null;
  65. /**
  66. * converts a duration (in seconds) into human friendly approximation
  67. *
  68. * @name Helper.secondsToHuman
  69. * @function
  70. * @param {number} seconds
  71. * @return {Array}
  72. */
  73. me.secondsToHuman = function(seconds)
  74. {
  75. var v;
  76. if (seconds < 60)
  77. {
  78. v = Math.floor(seconds);
  79. return [v, 'second'];
  80. }
  81. if (seconds < 60 * 60)
  82. {
  83. v = Math.floor(seconds / 60);
  84. return [v, 'minute'];
  85. }
  86. if (seconds < 60 * 60 * 24)
  87. {
  88. v = Math.floor(seconds / (60 * 60));
  89. return [v, 'hour'];
  90. }
  91. // If less than 2 months, display in days:
  92. if (seconds < 60 * 60 * 24 * 60)
  93. {
  94. v = Math.floor(seconds / (60 * 60 * 24));
  95. return [v, 'day'];
  96. }
  97. v = Math.floor(seconds / (60 * 60 * 24 * 30));
  98. return [v, 'month'];
  99. };
  100. /**
  101. * checks if a string is valid text (and not onyl whitespace)
  102. *
  103. * @name Helper.isValidText
  104. * @function
  105. * @param {string} string
  106. * @return {bool}
  107. */
  108. me.isValidText = function(string)
  109. {
  110. return (string.length > 0 && $.trim(string) !== '')
  111. };
  112. /**
  113. * text range selection
  114. *
  115. * @see {@link https://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse}
  116. * @name Helper.selectText
  117. * @function
  118. * @param {HTMLElement} element
  119. */
  120. me.selectText = function(element)
  121. {
  122. var range, selection;
  123. // MS
  124. if (document.body.createTextRange) {
  125. range = document.body.createTextRange();
  126. range.moveToElementText(element);
  127. range.select();
  128. } else if (window.getSelection){
  129. selection = window.getSelection();
  130. range = document.createRange();
  131. range.selectNodeContents(element);
  132. selection.removeAllRanges();
  133. selection.addRange(range);
  134. }
  135. };
  136. /**
  137. * set text of a jQuery element (required for IE),
  138. *
  139. * @name Helper.setElementText
  140. * @function
  141. * @param {jQuery} $element - a jQuery element
  142. * @param {string} text - the text to enter
  143. */
  144. me.setElementText = function($element, text)
  145. {
  146. // For IE<10: Doesn't support white-space:pre-wrap; so we have to do this...
  147. if ($('#oldienotice').is(':visible')) {
  148. var html = me.htmlEntities(text).replace(/\n/ig, '\r\n<br>');
  149. $element.html('<pre>' + html + '</pre>');
  150. }
  151. // for other (sane) browsers:
  152. else
  153. {
  154. $element.text(text);
  155. }
  156. };
  157. /**
  158. * convert URLs to clickable links.
  159. * URLs to handle:
  160. * <pre>
  161. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  162. * http://example.com:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  163. * http://user:example.com@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  164. * </pre>
  165. *
  166. * @name Helper.urls2links
  167. * @function
  168. * @param {Object} element - a jQuery DOM element
  169. */
  170. me.urls2links = function($element)
  171. {
  172. var markup = '<a href="$1" rel="nofollow">$1</a>';
  173. $element.html(
  174. $element.html().replace(
  175. /((http|https|ftp):\/\/[\w?=&.\/-;#@~%+-]+(?![\w\s?&.\/;#~%"=-]*>))/ig,
  176. markup
  177. )
  178. );
  179. $element.html(
  180. $element.html().replace(
  181. /((magnet):[\w?=&.\/-;#@~%+-]+)/ig,
  182. markup
  183. )
  184. );
  185. };
  186. /**
  187. * minimal sprintf emulation for %s and %d formats
  188. *
  189. * @see {@link https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914}
  190. * @name Helper.sprintf
  191. * @function
  192. * @param {string} format
  193. * @param {...*} args - one or multiple parameters injected into format string
  194. * @return {string}
  195. */
  196. me.sprintf = function()
  197. {
  198. var args = Array.prototype.slice.call(arguments);
  199. var format = args[0],
  200. i = 1;
  201. return format.replace(/%((%)|s|d)/g, function (m) {
  202. // m is the matched format, e.g. %s, %d
  203. var val;
  204. if (m[2]) {
  205. val = m[2];
  206. } else {
  207. val = args[i];
  208. // A switch statement so that the formatter can be extended.
  209. switch (m)
  210. {
  211. case '%d':
  212. val = parseFloat(val);
  213. if (isNaN(val)) {
  214. val = 0;
  215. }
  216. break;
  217. default:
  218. // Default is %s
  219. }
  220. ++i;
  221. }
  222. return val;
  223. });
  224. };
  225. /**
  226. * get value of cookie, if it was set, empty string otherwise
  227. *
  228. * @see {@link http://www.w3schools.com/js/js_cookies.asp}
  229. * @name Helper.getCookie
  230. * @function
  231. * @param {string} cname
  232. * @return {string}
  233. */
  234. me.getCookie = function(cname) {
  235. var name = cname + '=',
  236. ca = document.cookie.split(';');
  237. for (var i = 0; i < ca.length; ++i) {
  238. var c = ca[i];
  239. while (c.charAt(0) === ' ')
  240. {
  241. c = c.substring(1);
  242. }
  243. if (c.indexOf(name) === 0)
  244. {
  245. return c.substring(name.length, c.length);
  246. }
  247. }
  248. return '';
  249. };
  250. /**
  251. * get the current location (without search or hash part of the URL),
  252. * eg. http://example.com/path/?aaaa#bbbb --> http://example.com/path/
  253. *
  254. * @name Helper.baseUri
  255. * @function
  256. * @return {string}
  257. */
  258. me.baseUri = function()
  259. {
  260. // check for cached version
  261. if (baseUri !== null) {
  262. return baseUri;
  263. }
  264. // get official base uri string, from base tag in head of HTML
  265. baseUri = document.baseURI;
  266. // if base uri contains query string (when no base tag is present),
  267. // it is unwanted
  268. if (baseUri.indexOf('?')) {
  269. // so we built our own baseuri
  270. baseUri = window.location.origin + window.location.pathname;
  271. }
  272. return baseUri;
  273. };
  274. /**
  275. * convert all applicable characters to HTML entities
  276. *
  277. * @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}
  278. * @name Helper.htmlEntities
  279. * @function
  280. * @param {string} str
  281. * @return {string} escaped HTML
  282. */
  283. me.htmlEntities = function(str) {
  284. return String(str).replace(
  285. /[&<>"'`=\/]/g, function(s) {
  286. return entityMap[s];
  287. });
  288. };
  289. return me;
  290. })(window, document);
  291. /**
  292. * internationalization module
  293. *
  294. * @param {object} window
  295. * @param {object} document
  296. * @class
  297. */
  298. var I18n = (function (window, document) {
  299. var me = {};
  300. /**
  301. * const for string of loaded language
  302. *
  303. * @private
  304. * @prop {string}
  305. * @readonly
  306. */
  307. var languageLoadedEvent = 'languageLoaded';
  308. /**
  309. * supported languages, minus the built in 'en'
  310. *
  311. * @private
  312. * @prop {string[]}
  313. * @readonly
  314. */
  315. var supportedLanguages = ['de', 'es', 'fr', 'it', 'no', 'pl', 'oc', 'ru', 'sl', 'zh'];
  316. /**
  317. * built in language
  318. *
  319. * @private
  320. * @prop {string|null}
  321. */
  322. var language = null;
  323. /**
  324. * translation cache
  325. *
  326. * @private
  327. * @enum {Object}
  328. */
  329. var translations = {};
  330. /**
  331. * translate a string, alias for I18n.translate()
  332. *
  333. * for a full description see me.translate
  334. *
  335. * @name I18n._
  336. * @function
  337. * @param {jQuery} $element - optional
  338. * @param {string} messageId
  339. * @param {...*} args - one or multiple parameters injected into placeholders
  340. * @return {string}
  341. */
  342. me._ = function()
  343. {
  344. return me.translate.apply(this, arguments);
  345. };
  346. /**
  347. * translate a string
  348. *
  349. * Optionally pass a jQuery element as the first parameter, to automatically
  350. * let the text of this element be replaced. In case the (asynchronously
  351. * loaded) language is not downloadet yet, this will make sure the string
  352. * is replaced when it is actually loaded.
  353. * So for easy translations passing the jQuery object to apply it to is
  354. * more save, especially when they are loaded in the beginning.
  355. *
  356. * @name I18n.translate
  357. * @function
  358. * @param {jQuery} $element - optional
  359. * @param {string} messageId
  360. * @param {...*} args - one or multiple parameters injected into placeholders
  361. * @return {string}
  362. */
  363. me.translate = function()
  364. {
  365. // convert parameters to array
  366. var args = Array.prototype.slice.call(arguments),
  367. messageId,
  368. $element = null;
  369. // parse arguments
  370. if (args[0] instanceof jQuery) {
  371. // optional jQuery element as first parameter
  372. $element = args[0];
  373. args.shift();
  374. }
  375. // extract messageId from arguments
  376. var usesPlurals = $.isArray(args[0]);
  377. if (usesPlurals) {
  378. // use the first plural form as messageId, otherwise the singular
  379. messageId = (args[0].length > 1 ? args[0][1] : args[0][0]);
  380. } else {
  381. messageId = args[0];
  382. }
  383. if (messageId.length === 0) {
  384. return messageId;
  385. }
  386. // if no translation string cannot be found (in translations object)
  387. if (!translations.hasOwnProperty(messageId)) {
  388. // if language is still loading and we have an elemt assigned
  389. if (language === null && $element !== null) {
  390. // handle the error by attaching the language loaded event
  391. var orgArguments = arguments;
  392. $(document).on(languageLoadedEvent, function () {
  393. // log to show that the previous error could be mitigated
  394. console.log('Fix missing translation of \'' + messageId + '\' with now loaded language ' + language);
  395. // re-execute this function
  396. me.translate.apply(this, orgArguments);
  397. });
  398. // and fall back to English for now until the real language
  399. // file is loaded
  400. }
  401. // for all other langauges than English for which thsi behaviour
  402. // is expected as it is built-in, log error
  403. if (language !== 'en') {
  404. console.error('Missing translation for: \'' + messageId + '\' in language ' + language);
  405. // fallback to English
  406. }
  407. // save English translation (should be the same on both sides)
  408. translations[messageId] = args[0];
  409. }
  410. // lookup plural translation
  411. if (usesPlurals && $.isArray(translations[messageId])) {
  412. var n = parseInt(args[1] || 1, 10),
  413. key = me.getPluralForm(n),
  414. maxKey = translations[messageId].length - 1;
  415. if (key > maxKey) {
  416. key = maxKey;
  417. }
  418. args[0] = translations[messageId][key];
  419. args[1] = n;
  420. } else {
  421. // lookup singular translation
  422. args[0] = translations[messageId];
  423. }
  424. // format string
  425. var output = Helper.sprintf.apply(this, args);
  426. // if $element is given, apply text to element
  427. if ($element !== null) {
  428. $element.text(output);
  429. }
  430. return output;
  431. };
  432. /**
  433. * per language functions to use to determine the plural form
  434. *
  435. * @see {@link http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html}
  436. * @name I18n.getPluralForm
  437. * @function
  438. * @param {int} n
  439. * @return {int} array key
  440. */
  441. me.getPluralForm = function(n) {
  442. switch (language)
  443. {
  444. case 'fr':
  445. case 'oc':
  446. case 'zh':
  447. return (n > 1 ? 1 : 0);
  448. case 'pl':
  449. return (n === 1 ? 0 : (n % 10 >= 2 && n %10 <=4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2));
  450. case 'ru':
  451. return (n % 10 === 1 && n % 100 !== 11 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2));
  452. case 'sl':
  453. return (n % 100 === 1 ? 1 : (n % 100 === 2 ? 2 : (n % 100 === 3 || n % 100 === 4 ? 3 : 0)));
  454. // de, en, es, it, no
  455. default:
  456. return (n !== 1 ? 1 : 0);
  457. }
  458. };
  459. /**
  460. * load translations into cache
  461. *
  462. * @name I18n.loadTranslations
  463. * @function
  464. */
  465. me.loadTranslations = function()
  466. {
  467. var newLanguage = Helper.getCookie('lang');
  468. // auto-select language based on browser settings
  469. if (newLanguage.length === 0) {
  470. newLanguage = (navigator.language || navigator.userLanguage).substring(0, 2);
  471. }
  472. // if language is already used skip update
  473. if (newLanguage === language) {
  474. return;
  475. }
  476. // if language is built-in (English) skip update
  477. if (newLanguage === 'en') {
  478. language = 'en';
  479. return;
  480. }
  481. // if language is not supported, show error
  482. if (supportedLanguages.indexOf(newLanguage) === -1) {
  483. console.error('Language \'%s\' is not supported. Translation failed, fallback to English.', newLanguage);
  484. language = 'en';
  485. return;
  486. }
  487. // load strings from JSON
  488. $.getJSON('i18n/' + newLanguage + '.json', function(data) {
  489. language = newLanguage;
  490. translations = data;
  491. $(document).triggerHandler(languageLoadedEvent);
  492. }).fail(function (data, textStatus, errorMsg) {
  493. console.error('Language \'%s\' could not be loaded (%s: %s). Translation failed, fallback to English.', newLanguage, textStatus, errorMsg);
  494. language = 'en';
  495. });
  496. };
  497. return me;
  498. })(window, document);
  499. /**
  500. * handles everything related to en/decryption
  501. *
  502. * @class
  503. */
  504. var CryptTool = (function () {
  505. var me = {};
  506. /**
  507. * compress a message (deflate compression), returns base64 encoded data
  508. *
  509. * @name cryptToolcompress
  510. * @function
  511. * @private
  512. * @param {string} message
  513. * @return {string} base64 data
  514. */
  515. function compress(message)
  516. {
  517. return Base64.toBase64( RawDeflate.deflate( Base64.utob(message) ) );
  518. }
  519. /**
  520. * decompress a message compressed with cryptToolcompress()
  521. *
  522. * @name cryptTooldecompress
  523. * @function
  524. * @private
  525. * @param {string} data - base64 data
  526. * @return {string} message
  527. */
  528. function decompress(data)
  529. {
  530. return Base64.btou( RawDeflate.inflate( Base64.fromBase64(data) ) );
  531. }
  532. /**
  533. * compress, then encrypt message with given key and password
  534. *
  535. * @name CryptTool.cipher
  536. * @function
  537. * @param {string} key
  538. * @param {string} password
  539. * @param {string} message
  540. * @return {string} data - JSON with encrypted data
  541. */
  542. me.cipher = function(key, password, message)
  543. {
  544. // Galois Counter Mode, keysize 256 bit, authentication tag 128 bit
  545. var options = {
  546. mode: 'gcm',
  547. ks: 256,
  548. ts: 128
  549. };
  550. if ((password || '').trim().length === 0)
  551. {
  552. return sjcl.encrypt(key, compress(message), options);
  553. }
  554. return sjcl.encrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), compress(message), options);
  555. };
  556. /**
  557. * decrypt message with key, then decompress
  558. *
  559. * @name CryptTool.decipher
  560. * @function
  561. * @param {string} key
  562. * @param {string} password
  563. * @param {string} data - JSON with encrypted data
  564. * @return {string} decrypted message
  565. */
  566. me.decipher = function(key, password, data)
  567. {
  568. if (data !== undefined)
  569. {
  570. try
  571. {
  572. return decompress(sjcl.decrypt(key, data));
  573. }
  574. catch(err)
  575. {
  576. try
  577. {
  578. return decompress(sjcl.decrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), data));
  579. }
  580. catch(e)
  581. {
  582. // ignore error, because ????? @TODO
  583. }
  584. }
  585. }
  586. return '';
  587. };
  588. /**
  589. * checks whether the crypt tool is ready.
  590. *
  591. * @name CryptTool.isReady
  592. * @function
  593. * @return {bool}
  594. */
  595. me.isEntropyReady = function()
  596. {
  597. return sjcl.random.isReady();
  598. };
  599. /**
  600. * checks whether the crypt tool is ready.
  601. *
  602. * @name CryptTool.isReady
  603. * @function
  604. * @param {function} func
  605. */
  606. me.addEntropySeedListener = function(func)
  607. {
  608. sjcl.random.addEventListener('seeded', func);
  609. };
  610. /**
  611. * returns a random symmetric key
  612. *
  613. * @name CryptTool.getSymmetricKey
  614. * @function
  615. * @return {string} func
  616. */
  617. me.getSymmetricKey = function(func)
  618. {
  619. return sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  620. };
  621. /**
  622. * initialize crypt tool
  623. *
  624. * @name CryptTool.init
  625. * @function
  626. */
  627. me.init = function()
  628. {
  629. // will fail earlier as sjcl is already passed as a parameter
  630. // if (typeof sjcl !== 'object') {
  631. // Alert.showError(
  632. // I18n._('The library %s is not available.', 'sjcl') +
  633. // I18n._('Messages cannot be decrypted or encrypted.')
  634. // );
  635. // }
  636. };
  637. return me;
  638. })();
  639. /**
  640. * (Model) Data source (aka MVC)
  641. *
  642. * @param {object} window
  643. * @param {object} document
  644. * @class
  645. */
  646. var Model = (function (window, document) {
  647. var me = {};
  648. var $cipherData;
  649. var id = null, symmetricKey = null;
  650. /**
  651. * returns the expiration set in the HTML
  652. *
  653. * @name Model.getExpirationDefault
  654. * @function
  655. * @return string
  656. * @TODO the template can be simplified as #pasteExpiration is no longer modified (only default value)
  657. */
  658. me.getExpirationDefault = function()
  659. {
  660. return $('#pasteExpiration').val();
  661. };
  662. /**
  663. * returns the format set in the HTML
  664. *
  665. * @name Model.getFormatDefault
  666. * @function
  667. * @return string
  668. * @TODO the template can be simplified as #pasteFormatter is no longer modified (only default value)
  669. */
  670. me.getFormatDefault = function()
  671. {
  672. return $('#pasteFormatter').val();
  673. };
  674. /**
  675. * check if cipher data was supplied
  676. *
  677. * @name Model.getCipherData
  678. * @function
  679. * @return boolean
  680. */
  681. me.hasCipherData = function()
  682. {
  683. return (me.getCipherData().length > 0);
  684. };
  685. /**
  686. * returns the cipher data
  687. *
  688. * @name Model.getCipherData
  689. * @function
  690. * @return string
  691. */
  692. me.getCipherData = function()
  693. {
  694. return $cipherData.text();
  695. };
  696. /**
  697. * get the pastes unique identifier from the URL,
  698. * eg. http://example.com/path/?c05354954c49a487#dfdsdgdgdfgdf returns c05354954c49a487
  699. *
  700. * @name Model.getPasteId
  701. * @function
  702. * @return {string} unique identifier
  703. */
  704. me.getPasteId = function()
  705. {
  706. if (id === null) {
  707. id = window.location.search.substring(1);
  708. }
  709. return id;
  710. };
  711. /**
  712. * return the deciphering key stored in anchor part of the URL
  713. *
  714. * @name Model.getPasteKey
  715. * @function
  716. * @return {string} key
  717. */
  718. me.getPasteKey = function()
  719. {
  720. if (symmetricKey === null) {
  721. symmetricKey = window.location.hash.substring(1);
  722. // Some web 2.0 services and redirectors add data AFTER the anchor
  723. // (such as &utm_source=...). We will strip any additional data.
  724. var ampersandPos = symmetricKey.indexOf('&');
  725. if (ampersandPos > -1)
  726. {
  727. symmetricKey = symmetricKey.substring(0, ampersandPos);
  728. }
  729. }
  730. return symmetricKey;
  731. };
  732. /**
  733. * init navigation manager
  734. *
  735. * preloads jQuery elements
  736. *
  737. * @name Model.init
  738. * @function
  739. */
  740. me.init = function()
  741. {
  742. $cipherData = $('#cipherdata');
  743. };
  744. return me;
  745. })(window, document);
  746. /**
  747. * Helper functions for user interface
  748. *
  749. * everything directly UI-related, which fits nowhere else
  750. *
  751. * @param {object} window
  752. * @param {object} document
  753. * @class
  754. */
  755. var UiHelper = (function (window, document) {
  756. var me = {};
  757. /**
  758. * handle history (pop) state changes
  759. *
  760. * currently this does only handle redirects to the home page.
  761. *
  762. * @private
  763. * @function
  764. * @param {Event} event
  765. */
  766. function historyChange(event)
  767. {
  768. var currentLocation = Helper.baseUri();
  769. if (event.originalEvent.state === null && // no state object passed
  770. event.originalEvent.target.location.href === currentLocation && // target location is home page
  771. window.location.href === currentLocation // and we are not already on the home page
  772. ) {
  773. // redirect to home page
  774. window.location.href = currentLocation;
  775. }
  776. };
  777. /**
  778. * reload the page
  779. *
  780. * This takes the user to the PrivateBin homepage.
  781. *
  782. * @name UiHelper.reloadHome
  783. * @function
  784. */
  785. me.reloadHome = function()
  786. {
  787. window.location.href = Helper.baseUri();
  788. };
  789. /**
  790. * initialize
  791. *
  792. * @name UiHelper.init
  793. * @function
  794. */
  795. me.init = function()
  796. {
  797. // update link to home page
  798. $('.reloadlink').prop('href', Helper.baseUri());
  799. $(window).on('popstate', historyChange);
  800. };
  801. return me;
  802. })(window, document);
  803. /**
  804. * Alert/error manager
  805. *
  806. * @param {object} window
  807. * @param {object} document
  808. * @class
  809. */
  810. var Alert = (function (window, document) {
  811. var me = {};
  812. var $errorMessage,
  813. $statusMessage,
  814. $loadingIndicator;
  815. var currentIcon = [
  816. 'glyphicon-time', // loading icon
  817. 'glyphicon-info-sign', // status icon
  818. '', // resevered for warning, not used yet
  819. 'glyphicon-alert' // error icon
  820. ];
  821. /**
  822. * forwards a request to the i18n module and shows the element
  823. *
  824. * @private
  825. * @function
  826. * @param {int} id - id of notification
  827. * @param {jQuery} $element - jQuery object
  828. * @param {string|array} args
  829. * @param {string|null} icon - optional, icon
  830. */
  831. function handleNotification(id, $element, args, icon)
  832. {
  833. // handle icon
  834. if (
  835. typeof icon !== 'undefined' && // if icon is passed
  836. icon !== currentIcon[id] // and it differs from current icon
  837. ) {
  838. var $glyphIcon = $element.find(':first');
  839. // remove (previous) icon
  840. $glyphIcon.removeClass(currentIcon[id]);
  841. // any other thing as a string (e.g. 'null') (only) removes the icon
  842. if (typeof icon === 'string') {
  843. // set new icon
  844. currentIcon[id] = 'glyphicon-' + icon;
  845. $glyphIcon.addClass(currentIcon[id]);
  846. }
  847. }
  848. // show text
  849. if (typeof args !== 'undefined' && args !== null) {
  850. // convert string to array if needed
  851. if (typeof args === 'string') {
  852. args = [args];
  853. }
  854. // add jQuery object to it as first parameter
  855. args.unshift($element.find(':last'));
  856. // pass it to I18n
  857. I18n._.apply(this, args);
  858. }
  859. // show notification
  860. $element.removeClass('hidden');
  861. }
  862. /**
  863. * display a status message
  864. *
  865. * This automatically passes the text to I18n for translation.
  866. *
  867. * @name Alert.showStatus
  868. * @function
  869. * @param {string|array} message string, use an array for %s/%d options
  870. * @param {string|null} icon optional, the icon to show,
  871. * default: leave previous icon
  872. * @param {bool} dismissable optional, whether the notification
  873. * can be dismissed (closed), default: false
  874. * @param {bool|int} autoclose optional, after how many seconds the
  875. * notification should be hidden automatically;
  876. * default: disabled (0); use true for default value
  877. */
  878. me.showStatus = function(message, icon, dismissable, autoclose)
  879. {
  880. console.log('status shown: ', message);
  881. // @TODO: implement dismissable
  882. // @TODO: implement autoclose
  883. handleNotification(1, $statusMessage, message, icon);
  884. };
  885. /**
  886. * display an error message
  887. *
  888. * This automatically passes the text to I18n for translation.
  889. *
  890. * @name Alert.showError
  891. * @function
  892. * @param {string|array} message string, use an array for %s/%d options
  893. * @param {string|null} icon optional, the icon to show, default:
  894. * leave previous icon
  895. * @param {bool} dismissable optional, whether the notification
  896. * can be dismissed (closed), default: false
  897. * @param {bool|int} autoclose optional, after how many seconds the
  898. * notification should be hidden automatically;
  899. * default: disabled (0); use true for default value
  900. */
  901. me.showError = function(message, icon, dismissable, autoclose)
  902. {
  903. console.error('error message shown: ', message);
  904. // @TODO: implement dismissable
  905. // @TODO: implement autoclose
  906. handleNotification(3, $errorMessage, message, icon);
  907. };
  908. /**
  909. * shows a loading message, optionally with a percentage
  910. *
  911. * This automatically passes all texts to the i10s module.
  912. *
  913. * @name Alert.showLoading
  914. * @function
  915. * @param {string|array|null} message optional, use an array for %s/%d options, default: 'Loading…'
  916. * @param {int} percentage optional, default: null
  917. * @param {string|null} icon optional, the icon to show, default: leave previous icon
  918. */
  919. me.showLoading = function(message, percentage, icon)
  920. {
  921. if (typeof message !== 'undefined' && message !== null) {
  922. console.log('status changed: ', message);
  923. }
  924. // default message text
  925. if (typeof message === 'undefined') {
  926. message = 'Loading…';
  927. }
  928. // currently percentage parameter is ignored
  929. // // @TODO handle it here…
  930. handleNotification(0, $loadingIndicator, message, icon);
  931. };
  932. /**
  933. * hides the loading message
  934. *
  935. * @name Alert.hideLoading
  936. * @function
  937. */
  938. me.hideLoading = function()
  939. {
  940. $loadingIndicator.addClass('hidden');
  941. };
  942. /**
  943. * hides any status/error messages
  944. *
  945. * This does not include the loading message.
  946. *
  947. * @name Alert.hideMessages
  948. * @function
  949. */
  950. me.hideMessages = function()
  951. {
  952. $statusMessage.addClass('hidden');
  953. $errorMessage.addClass('hidden');
  954. };
  955. /**
  956. * init status manager
  957. *
  958. * preloads jQuery elements
  959. *
  960. * @name Alert.init
  961. * @function
  962. */
  963. me.init = function()
  964. {
  965. // hide "no javascript" message
  966. $('#noscript').hide();
  967. $errorMessage = $('#errormessage');
  968. $statusMessage = $('#status');
  969. $loadingIndicator = $('#loadingindicator');
  970. // display status returned by php code, if any (e.g. paste was properly deleted)
  971. var serverStatus = $statusMessage.text();
  972. if (Helper.isValidText(serverStatus)) {
  973. me.showStatus();
  974. }
  975. // display error message from php code
  976. var serverError = $errorMessage.text();
  977. if (Helper.isValidText(serverError)) {
  978. Alert.showError();
  979. }
  980. };
  981. return me;
  982. })(window, document);
  983. /**
  984. * handles paste status/result
  985. *
  986. * @param {object} window
  987. * @param {object} document
  988. * @class
  989. */
  990. var PasteStatus = (function (window, document) {
  991. var me = {};
  992. var $pasteSuccess,
  993. $shortenButton,
  994. $pasteUrl,
  995. $remainingTime;
  996. /**
  997. * forward to URL shortener
  998. *
  999. * @private
  1000. * @function
  1001. * @param {Event} event
  1002. */
  1003. function sendToShortener(event)
  1004. {
  1005. window.location.href = $shortenButton.data('shortener')
  1006. + encodeURIComponent($pasteUrl.attr('href'));
  1007. }
  1008. /**
  1009. * Forces opening the paste if the link does not do this automatically.
  1010. *
  1011. * This is necessary as browsers will not reload the page when it is
  1012. * already loaded (which is fake as it is set via history.pushState()).
  1013. *
  1014. * @name Controller.pasteLinkClick
  1015. * @function
  1016. * @param {Event} event
  1017. */
  1018. function pasteLinkClick(event)
  1019. {
  1020. // check if location is (already) shown in URL bar
  1021. if (window.location.href === $pasteUrl.attr('href')) {
  1022. // if so we need to load link by reloading the current site
  1023. window.location.reload(true);
  1024. }
  1025. }
  1026. /**
  1027. * creates a notification after a successfull paste upload
  1028. *
  1029. * @name PasteStatus.createPasteNotification
  1030. * @function
  1031. * @param {string} url
  1032. * @param {string} deleteUrl
  1033. */
  1034. me.createPasteNotification = function(url, deleteUrl)
  1035. {
  1036. $('#pastelink').find(':first').html(
  1037. I18n._(
  1038. 'Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>',
  1039. url, url
  1040. )
  1041. );
  1042. // save newly created element
  1043. $pasteUrl = $('#pasteurl');
  1044. // and add click event
  1045. $pasteUrl.click(pasteLinkClick);
  1046. // shorten button
  1047. $('#deletelink').html('<a href="' + deleteUrl + '">' + I18n._('Delete data') + '</a>');
  1048. // show result
  1049. $pasteSuccess.removeClass('hidden');
  1050. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1051. Helper.selectText($pasteUrl[0]);
  1052. };
  1053. /**
  1054. * shows the remaining time
  1055. *
  1056. * @name PasteStatus.showRemainingTime
  1057. * @function
  1058. * @param {object} pasteMetaData
  1059. */
  1060. me.showRemainingTime = function(pasteMetaData)
  1061. {
  1062. if (pasteMetaData.burnafterreading) {
  1063. // display paste "for your eyes only" if it is deleted
  1064. // actually remove paste, before we claim it is deleted
  1065. Controller.removePaste(Model.getPasteId(), 'burnafterreading');
  1066. I18n._($remainingTime.find(':last'), "FOR YOUR EYES ONLY. Don't close this window, this message can't be displayed again.");
  1067. $remainingTime.addClass('foryoureyesonly');
  1068. // discourage cloning (it cannot really be prevented)
  1069. TopNav.hideCloneButton();
  1070. } else if (pasteMetaData.expire_date) {
  1071. // display paste expiration
  1072. var expiration = Helper.secondsToHuman(pasteMetaData.remaining_time),
  1073. expirationLabel = [
  1074. 'This document will expire in %d ' + expiration[1] + '.',
  1075. 'This document will expire in %d ' + expiration[1] + 's.'
  1076. ];
  1077. I18n._($remainingTime.find(':last'), expirationLabel, expiration[0]);
  1078. $remainingTime.removeClass('foryoureyesonly')
  1079. } else {
  1080. // never expires
  1081. return;
  1082. }
  1083. // in the end, display notification
  1084. $remainingTime.removeClass('hidden');
  1085. };
  1086. /**
  1087. * hides the remaining time and successful upload notification
  1088. *
  1089. * @name PasteStatus.hideRemainingTime
  1090. * @function
  1091. */
  1092. me.hideMessages = function()
  1093. {
  1094. $remainingTime.addClass('hidden');
  1095. $pasteSuccess.addClass('hidden');
  1096. };
  1097. /**
  1098. * init status manager
  1099. *
  1100. * preloads jQuery elements
  1101. *
  1102. * @name Alert.init
  1103. * @function
  1104. */
  1105. me.init = function()
  1106. {
  1107. $shortenButton = $('#shortenbutton');
  1108. $pasteSuccess = $('#pasteSuccess');
  1109. // $pasteUrl is saved in me.createPasteNotification() after creation
  1110. $remainingTime = $('#remainingtime');
  1111. // bind elements
  1112. $shortenButton.click(sendToShortener);
  1113. };
  1114. return me;
  1115. })(window, document);
  1116. /**
  1117. * password prompt
  1118. *
  1119. * @param {object} window
  1120. * @param {object} document
  1121. * @class
  1122. */
  1123. var Prompt = (function (window, document) {
  1124. var me = {};
  1125. var $passwordModel,
  1126. $passwordForm,
  1127. $passwordDecrypt;
  1128. var password = '',
  1129. passwordCallback = null;
  1130. /**
  1131. * ask the user for the password and set it
  1132. *
  1133. * the callback set via setPasswordCallback is executed
  1134. *
  1135. * @name Prompt.requestPassword()
  1136. * @function
  1137. */
  1138. me.requestPassword = function()
  1139. {
  1140. // show new bootstrap method
  1141. $passwordModel.Model({
  1142. backdrop: 'static',
  1143. keyboard: false
  1144. });
  1145. if ($passwordModel.length === 0) {
  1146. // old method for page template
  1147. var newPassword = prompt(I18n._('Please enter the password for this paste:'), '');
  1148. if (newPassword === null) {
  1149. throw 'password prompt canceled';
  1150. }
  1151. if (password.length === 0) {
  1152. // recursive…
  1153. return me.requestPassword();
  1154. }
  1155. password = newPassword;
  1156. if (passwordCallback !== null) {
  1157. passwordCallback();
  1158. }
  1159. return;
  1160. }
  1161. };
  1162. /**
  1163. * getthe cached password
  1164. *
  1165. * If you do not get a password with this function
  1166. * (returns an empty string), use requestPassword.
  1167. *
  1168. * @name Prompt.getPassword
  1169. * @function
  1170. * @return {string}
  1171. */
  1172. me.getPassword = function()
  1173. {
  1174. return password;
  1175. };
  1176. /**
  1177. * setsthe callback called when password is entered
  1178. *
  1179. * @name Prompt.setPasswordCallback
  1180. * @function
  1181. * @param {functions} setPasswordCallback
  1182. */
  1183. me.setPasswordCallback = function(callback)
  1184. {
  1185. passwordCallback = callback;
  1186. };
  1187. /**
  1188. * submit a password in the Model dialog
  1189. *
  1190. * @private
  1191. * @function
  1192. * @param {Event} event
  1193. */
  1194. function submitPasswordModel(event)
  1195. {
  1196. // get input
  1197. password = $passwordDecrypt.val();
  1198. // hide Model
  1199. $passwordModel.Model('hide');
  1200. if (passwordCallback !== null) {
  1201. passwordCallback();
  1202. }
  1203. event.preventDefault();
  1204. }
  1205. /**
  1206. * init status manager
  1207. *
  1208. * preloads jQuery elements
  1209. *
  1210. * @name Controller.init
  1211. * @function
  1212. */
  1213. me.init = function()
  1214. {
  1215. $passwordModel = $('#passwordModel');
  1216. $passwordForm = $('#passwordform');
  1217. $passwordDecrypt = $('#passworddecrypt');
  1218. // bind events
  1219. // focus password input when it is shown
  1220. $passwordModel.on('shown.bs.Model', function () {
  1221. $passwordDecrypt.focus();
  1222. });
  1223. // handle Model password submission
  1224. $passwordForm.submit(submitPasswordModel);
  1225. };
  1226. return me;
  1227. })(window, document);
  1228. /**
  1229. * Manage paste/message input, and preview tab
  1230. *
  1231. * Note that the actual preview is handled by PasteViewer.
  1232. *
  1233. * @param {object} window
  1234. * @param {object} document
  1235. * @class
  1236. */
  1237. var Editor = (function (window, document) {
  1238. var me = {};
  1239. var $message,
  1240. $messageEdit,
  1241. $messagePreview,
  1242. $editorTabs;
  1243. var isPreview = false;
  1244. /**
  1245. * support input of tab character
  1246. *
  1247. * @name Editor.supportTabs
  1248. * @function
  1249. * @param {Event} event
  1250. * @this $message (but not used, so it is jQuery-free, possibly faster)
  1251. */
  1252. function supportTabs(event)
  1253. {
  1254. var keyCode = event.keyCode || event.which;
  1255. // tab was pressed
  1256. if (keyCode === 9) {
  1257. // get caret position & selection
  1258. var val = this.value,
  1259. start = this.selectionStart,
  1260. end = this.selectionEnd;
  1261. // set textarea value to: text before caret + tab + text after caret
  1262. this.value = val.substring(0, start) + '\t' + val.substring(end);
  1263. // put caret at right position again
  1264. this.selectionStart = this.selectionEnd = start + 1;
  1265. // prevent the textarea to lose focus
  1266. event.preventDefault();
  1267. }
  1268. }
  1269. /**
  1270. * view the Editor tab
  1271. *
  1272. * @name Editor.viewEditor
  1273. * @function
  1274. * @param {Event} event - optional
  1275. */
  1276. function viewEditor(event)
  1277. {
  1278. // toggle buttons
  1279. $messageEdit.addClass('active');
  1280. $messagePreview.removeClass('active');
  1281. PasteViewer.hide();
  1282. // reshow input
  1283. $message.removeClass('hidden');
  1284. me.focusInput();
  1285. // finish
  1286. isPreview = false;
  1287. // prevent jumping of page to top
  1288. if (typeof event !== 'undefined') {
  1289. event.preventDefault();
  1290. }
  1291. }
  1292. /**
  1293. * view the preview tab
  1294. *
  1295. * @name Editor.viewPreview
  1296. * @function
  1297. * @param {Event} event
  1298. */
  1299. function viewPreview(event)
  1300. {
  1301. // toggle buttons
  1302. $messageEdit.removeClass('active');
  1303. $messagePreview.addClass('active');
  1304. // hide input as now preview is shown
  1305. $message.addClass('hidden');
  1306. // show preview
  1307. $('#errormessage').find(':last')
  1308. PasteViewer.setText($message.val());
  1309. PasteViewer.run();
  1310. // finish
  1311. isPreview = true;
  1312. // prevent jumping of page to top
  1313. if (typeof event !== 'undefined') {
  1314. event.preventDefault();
  1315. }
  1316. }
  1317. /**
  1318. * get the state of the preview
  1319. *
  1320. * @name Editor.isPreview
  1321. * @function
  1322. */
  1323. me.isPreview = function()
  1324. {
  1325. return isPreview;
  1326. }
  1327. /**
  1328. * reset the Editor view
  1329. *
  1330. * @name Editor.resetInput
  1331. * @function
  1332. */
  1333. me.resetInput = function()
  1334. {
  1335. // go back to input
  1336. if (isPreview) {
  1337. viewEditor();
  1338. }
  1339. // clear content
  1340. $message.val('');
  1341. };
  1342. /**
  1343. * shows the Editor
  1344. *
  1345. * @name Editor.show
  1346. * @function
  1347. */
  1348. me.show = function()
  1349. {
  1350. $message.removeClass('hidden');
  1351. $editorTabs.removeClass('hidden');
  1352. };
  1353. /**
  1354. * hides the Editor
  1355. *
  1356. * @name Editor.reset
  1357. * @function
  1358. */
  1359. me.hide = function()
  1360. {
  1361. $message.addClass('hidden');
  1362. $editorTabs.addClass('hidden');
  1363. };
  1364. /**
  1365. * focuses the message input
  1366. *
  1367. * @name Editor.focusInput
  1368. * @function
  1369. */
  1370. me.focusInput = function()
  1371. {
  1372. $message.focus();
  1373. };
  1374. /**
  1375. * sets a new text
  1376. *
  1377. * @name Editor.setText
  1378. * @function
  1379. * @param {string} newText
  1380. */
  1381. me.setText = function(newText)
  1382. {
  1383. $message.val(newText);
  1384. };
  1385. /**
  1386. * returns the current text
  1387. *
  1388. * @name Editor.getText
  1389. * @function
  1390. * @return {string}
  1391. */
  1392. me.getText = function()
  1393. {
  1394. return $message.val()
  1395. };
  1396. /**
  1397. * init status manager
  1398. *
  1399. * preloads jQuery elements
  1400. *
  1401. * @name Editor.init
  1402. * @function
  1403. */
  1404. me.init = function()
  1405. {
  1406. $message = $('#message');
  1407. $editorTabs = $('#editorTabs');
  1408. // bind events
  1409. $message.keydown(supportTabs);
  1410. // bind click events to tab switchers (a), but save parent of them
  1411. // (li)
  1412. $messageEdit = $('#messageedit').click(viewEditor).parent();
  1413. $messagePreview = $('#messagepreview').click(viewPreview).parent();
  1414. };
  1415. return me;
  1416. })(window, document);
  1417. /**
  1418. * (view) Parse and show paste.
  1419. *
  1420. * @param {object} window
  1421. * @param {object} document
  1422. * @class
  1423. */
  1424. var PasteViewer = (function (window, document) {
  1425. var me = {};
  1426. var $plainText,
  1427. $placeholder,
  1428. $prettyMessage,
  1429. $prettyPrint;
  1430. var text,
  1431. format = 'plaintext',
  1432. isDisplayed = false,
  1433. isChanged = true; // by default true as nothing was parsed yet
  1434. /**
  1435. * apply the set format on paste and displays it
  1436. *
  1437. * @private
  1438. * @function
  1439. */
  1440. function parsePaste()
  1441. {
  1442. // skip parsing if no text is given
  1443. if (text === '') {
  1444. return;
  1445. }
  1446. // set text
  1447. Helper.setElementText($plainText, text);
  1448. Helper.setElementText($prettyPrint, text);
  1449. switch (format) {
  1450. case 'markdown':
  1451. var converter = new showdown.Converter({
  1452. strikethrough: true,
  1453. tables: true,
  1454. tablesHeaderId: true
  1455. });
  1456. $plainText.html(
  1457. converter.makeHtml(text)
  1458. );
  1459. // add table classes from bootstrap css
  1460. $plainText.find('table').addClass('table-condensed table-bordered');
  1461. break;
  1462. case 'syntaxhighlighting':
  1463. // @TODO is this really needed or is "one" enough?
  1464. if (typeof prettyPrint === 'function')
  1465. {
  1466. prettyPrint();
  1467. }
  1468. $prettyPrint.html(
  1469. prettyPrintOne(
  1470. Helper.htmlEntities(text), null, true
  1471. )
  1472. );
  1473. // fall through, as the rest is the same
  1474. default: // = 'plaintext'
  1475. // convert URLs to clickable links
  1476. Helper.urls2links($plainText);
  1477. Helper.urls2links($prettyPrint);
  1478. $prettyPrint.css('white-space', 'pre-wrap');
  1479. $prettyPrint.css('word-break', 'normal');
  1480. $prettyPrint.removeClass('prettyprint');
  1481. }
  1482. }
  1483. /**
  1484. * displays the paste
  1485. *
  1486. * @private
  1487. * @function
  1488. */
  1489. function showPaste()
  1490. {
  1491. // instead of "nothing" better display a placeholder
  1492. if (text === '') {
  1493. $placeholder.removeClass('hidden')
  1494. return;
  1495. }
  1496. // otherwise hide the placeholder
  1497. $placeholder.addClass('hidden')
  1498. switch (format) {
  1499. case 'markdown':
  1500. $plainText.removeClass('hidden');
  1501. $prettyMessage.addClass('hidden');
  1502. break;
  1503. default:
  1504. $plainText.addClass('hidden');
  1505. $prettyMessage.removeClass('hidden');
  1506. break;
  1507. }
  1508. }
  1509. /**
  1510. * sets the format in which the text is shown
  1511. *
  1512. * @name PasteViewer.setFormat
  1513. * @function
  1514. * @param {string} newFormat the the new format
  1515. */
  1516. me.setFormat = function(newFormat)
  1517. {
  1518. // skip if there is no update
  1519. if (format === newFormat) {
  1520. return;
  1521. }
  1522. // needs to update display too, if from or to Markdown is switched
  1523. if (format === 'markdown' || newFormat === 'markdown') {
  1524. isDisplayed = false;
  1525. }
  1526. format = newFormat;
  1527. isChanged = true;
  1528. };
  1529. /**
  1530. * returns the current format
  1531. *
  1532. * @name PasteViewer.setFormat
  1533. * @function
  1534. * @return {string}
  1535. */
  1536. me.getFormat = function()
  1537. {
  1538. return format;
  1539. };
  1540. /**
  1541. * returns whether the current view is pretty printed
  1542. *
  1543. * @name PasteViewer.isPrettyPrinted
  1544. * @function
  1545. * @return {bool}
  1546. */
  1547. me.isPrettyPrinted = function()
  1548. {
  1549. return $prettyPrint.hasClass('prettyprinted');
  1550. };
  1551. /**
  1552. * sets the text to show
  1553. *
  1554. * @name PasteViewer.setText
  1555. * @function
  1556. * @param {string} newText the text to show
  1557. */
  1558. me.setText = function(newText)
  1559. {
  1560. if (text !== newText) {
  1561. text = newText;
  1562. isChanged = true;
  1563. }
  1564. };
  1565. /**
  1566. * gets the current cached text
  1567. *
  1568. * @name PasteViewer.getText
  1569. * @function
  1570. * @return {string}
  1571. */
  1572. me.getText = function(newText)
  1573. {
  1574. return text;
  1575. };
  1576. /**
  1577. * show/update the parsed text (preview)
  1578. *
  1579. * @name PasteViewer.run
  1580. * @function
  1581. */
  1582. me.run = function()
  1583. {
  1584. if (isChanged) {
  1585. parsePaste();
  1586. isChanged = false;
  1587. }
  1588. if (!isDisplayed) {
  1589. showPaste();
  1590. isDisplayed = true;
  1591. }
  1592. };
  1593. /**
  1594. * hide parsed text (preview)
  1595. *
  1596. * @name PasteViewer.hide
  1597. * @function
  1598. */
  1599. me.hide = function()
  1600. {
  1601. if (!isDisplayed) {
  1602. console.warn('PasteViewer was called to hide the parsed view, but it is already hidden.');
  1603. }
  1604. $plainText.addClass('hidden');
  1605. $prettyMessage.addClass('hidden');
  1606. $placeholder.addClass('hidden');
  1607. isDisplayed = false;
  1608. };
  1609. /**
  1610. * init status manager
  1611. *
  1612. * preloads jQuery elements
  1613. *
  1614. * @name Editor.init
  1615. * @function
  1616. */
  1617. me.init = function()
  1618. {
  1619. $plainText = $('#plaintext');
  1620. $placeholder = $('#placeholder');
  1621. $prettyMessage = $('#prettymessage');
  1622. $prettyPrint = $('#prettyprint');
  1623. // check requirements
  1624. if (typeof prettyPrintOne !== 'function') {
  1625. Alert.showError([
  1626. 'The library %s is not available. This may cause display errors.',
  1627. 'pretty print'
  1628. ]);
  1629. }
  1630. if (typeof showdown !== 'object') {
  1631. Alert.showError([
  1632. 'The library %s is not available. This may cause display errors.',
  1633. 'showdown'
  1634. ]);
  1635. }
  1636. // get default option from template/HTML or fall back to set value
  1637. format = Model.getFormatDefault() || format;
  1638. };
  1639. return me;
  1640. })(window, document);
  1641. /**
  1642. * (view) Show attachment and preview if possible
  1643. *
  1644. * @param {object} window
  1645. * @param {object} document
  1646. * @class
  1647. */
  1648. var AttachmentViewer = (function (window, document) {
  1649. var me = {};
  1650. var $attachment,
  1651. $attachmentLink,
  1652. $attachmentPreview;
  1653. var attachmentChanged = false,
  1654. attachmentHasPreview = false;
  1655. /**
  1656. * sets the attachment but does not yet show it
  1657. *
  1658. * @name AttachmentViewer.setAttachment
  1659. * @function
  1660. * @param {string} attachmentData - base64-encoded data of file
  1661. * @param {string} fileName - optional, file name
  1662. */
  1663. me.setAttachment = function(attachmentData, fileName)
  1664. {
  1665. var imagePrefix = 'data:image/';
  1666. $attachmentLink.attr('href', attachmentData);
  1667. if (typeof fileName !== 'undefined') {
  1668. $attachmentLink.attr('download', fileName);
  1669. }
  1670. // if the attachment is an image, display it
  1671. if (attachmentData.substring(0, imagePrefix.length) === imagePrefix) {
  1672. $attachmentPreview.html(
  1673. $(document.createElement('img'))
  1674. .attr('src', attachmentData)
  1675. .attr('class', 'img-thumbnail')
  1676. );
  1677. attachmentHasPreview = true;
  1678. }
  1679. attachmentChanged = true;
  1680. };
  1681. /**
  1682. * displays the attachment
  1683. *
  1684. * @name AttachmentViewer.showAttachment
  1685. * @function
  1686. */
  1687. me.showAttachment = function()
  1688. {
  1689. $attachment.removeClass('hidden');
  1690. if (attachmentHasPreview) {
  1691. $attachmentPreview.removeClass('hidden');
  1692. }
  1693. }
  1694. /**
  1695. * removes the attachment
  1696. *
  1697. * This automatically hides the attachment containers to, to
  1698. * prevent an inconsistent display.
  1699. *
  1700. * @name AttachmentViewer.removeAttachment
  1701. * @function
  1702. */
  1703. me.removeAttachment = function()
  1704. {
  1705. me.hideAttachment();
  1706. me.hideAttachmentPreview();
  1707. $attachmentLink.prop('href', '');
  1708. $attachmentLink.prop('download', '');
  1709. $attachmentPreview.html('');
  1710. }
  1711. /**
  1712. * hides the attachment
  1713. *
  1714. * This will not hide the preview {@see me.hideAttachmentPreview}
  1715. * nor will it hide the attachment link if it was moved somewhere
  1716. * else {@see moveAttachmentTo}.
  1717. *
  1718. * @name AttachmentViewer.hideAttachment
  1719. * @function
  1720. */
  1721. me.hideAttachment = function()
  1722. {
  1723. $attachment.addClass('hidden');
  1724. }
  1725. /**
  1726. * hides the attachment preview
  1727. *
  1728. * @name AttachmentViewer.hideAttachmentPreview
  1729. * @function
  1730. */
  1731. me.hideAttachmentPreview = function()
  1732. {
  1733. $attachmentPreview.addClass('hidden');
  1734. }
  1735. /**
  1736. * checks if there is an attachment
  1737. *
  1738. * @name AttachmentViewer.hasAttachment
  1739. * @function
  1740. */
  1741. me.hasAttachment = function()
  1742. {
  1743. return ($attachmentLink.prop('href') !== '')
  1744. };
  1745. /**
  1746. * return the attachment
  1747. *
  1748. * @name AttachmentViewer.getAttachment
  1749. * @function
  1750. * @returns {array}
  1751. */
  1752. me.getAttachment = function()
  1753. {
  1754. return [
  1755. $attachmentLink.prop('href'),
  1756. $attachmentLink.prop('download')
  1757. ];
  1758. };
  1759. /**
  1760. * moves the attachment link to another element
  1761. *
  1762. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  1763. *
  1764. * @name AttachmentViewer.setClonedAttachment
  1765. * @function
  1766. * @param {jQuery} $element - the wrapper/container element where this should be moved to
  1767. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  1768. */
  1769. me.moveAttachmentTo = function($element, label)
  1770. {
  1771. // move elemement to new place
  1772. $attachmentLink.appendTo($element);
  1773. // update text
  1774. I18n._($attachmentLink, label, $attachmentLink.attr('download'));
  1775. };
  1776. /**
  1777. * initiate
  1778. *
  1779. * preloads jQuery elements
  1780. *
  1781. * @name AttachmentViewer.init
  1782. * @function
  1783. */
  1784. me.init = function()
  1785. {
  1786. $attachmentPreview = $('#attachmentPreview');
  1787. $attachment = $('#attachment');
  1788. $attachmentLink = $('#attachment a');
  1789. };
  1790. return me;
  1791. })(window, document);
  1792. /**
  1793. * (view) Shows discussion thread and handles replies
  1794. *
  1795. * @param {object} window
  1796. * @param {object} document
  1797. * @class
  1798. */
  1799. var DiscussionViewer = (function (window, document) {
  1800. var me = {};
  1801. var $comments,
  1802. $discussion;
  1803. /**
  1804. * display a status message for replying to comments
  1805. *
  1806. * @name DiscussionViewer.showStatus
  1807. * @function
  1808. * @param {string} message - text to display
  1809. * @param {boolean} [spin=false] - (optional) tell if the "spinning" animation should be displayed, defaults to false
  1810. */
  1811. me.showReplyStatus = function(message, spin)
  1812. {
  1813. if (spin || false) {
  1814. $replyalert.find('.spinner').removeClass('hidden')
  1815. }
  1816. $replyalert.text(message);
  1817. };
  1818. /**
  1819. * display an error message
  1820. *
  1821. * @name DiscussionViewer.showReplyError
  1822. * @function
  1823. * @param {string} message - text to display
  1824. */
  1825. me.showReplyError = function(message)
  1826. {
  1827. $replyalert.addClass('Alert-danger');
  1828. $replyalert.addClass($errorMessage.attr('class')); // @TODO ????
  1829. $replyalert.text(message);
  1830. };
  1831. /**
  1832. * open the comment entry when clicking the "Reply" button of a comment
  1833. *
  1834. * @name DiscussionViewer.openReply
  1835. * @function
  1836. * @param {Event} event
  1837. */
  1838. me.openReply = function(event)
  1839. {
  1840. event.preventDefault();
  1841. // remove any other reply area
  1842. $('div.reply').remove();
  1843. var source = $(event.target),
  1844. commentid = event.data.commentid,
  1845. hint = I18n._('Optional nickname...'),
  1846. $reply = $('#replytemplate');
  1847. $reply.find('button').click(
  1848. {parentid: commentid},
  1849. me.sendComment
  1850. );
  1851. source.after($reply);
  1852. $replyStatus = $('#replystatus'); // when ID --> put into HTML
  1853. $('#replymessage').focus();
  1854. };
  1855. /**
  1856. * initiate
  1857. *
  1858. * preloads jQuery elements
  1859. *
  1860. * @name DiscussionViewer.init
  1861. * @function
  1862. */
  1863. me.init = function()
  1864. {
  1865. $comments = $('#comments');
  1866. $discussion = $('#discussion');
  1867. // $replyStatus in openReply()
  1868. };
  1869. return me;
  1870. })(window, document);
  1871. /**
  1872. * Manage top (navigation) bar
  1873. *
  1874. * @param {object} window
  1875. * @param {object} document
  1876. * @class
  1877. */
  1878. var TopNav = (function (window, document) {
  1879. var me = {};
  1880. var createButtonsDisplayed = false;
  1881. var viewButtonsDisplayed = false;
  1882. var $attach,
  1883. $burnAfterReading,
  1884. $burnAfterReadingOption,
  1885. $cloneButton,
  1886. $customAttachment,
  1887. $expiration,
  1888. $fileRemoveButton,
  1889. $formatter,
  1890. $newButton,
  1891. $openDiscussionOption,
  1892. $openDiscussion,
  1893. $password,
  1894. $passwordInput,
  1895. $rawTextButton,
  1896. $sendButton,
  1897. $fileWrap;
  1898. var pasteExpiration = '1week';
  1899. /**
  1900. * set the expiration on bootstrap templates in dropdown
  1901. *
  1902. * @name TopNav.updateExpiration
  1903. * @function
  1904. * @param {Event} event
  1905. */
  1906. function updateExpiration(event)
  1907. {
  1908. // get selected option
  1909. var target = $(event.target);
  1910. // update dropdown display and save new expiration time
  1911. $('#pasteExpirationDisplay').text(target.text());
  1912. pasteExpiration = target.data('expiration');
  1913. event.preventDefault();
  1914. }
  1915. /**
  1916. * set the format on bootstrap templates in dropdown
  1917. *
  1918. * @name TopNav.updateFormat
  1919. * @function
  1920. * @param {Event} event
  1921. */
  1922. function updateFormat(event)
  1923. {
  1924. // get selected option
  1925. var $target = $(event.target);
  1926. // update dropdown display and save new format
  1927. var newFormat = $target.data('format');
  1928. $('#pasteFormatterDisplay').text($target.text());
  1929. PasteViewer.setFormat(newFormat);
  1930. // update preview
  1931. if (Editor.isPreview()) {
  1932. PasteViewer.run();
  1933. }
  1934. event.preventDefault();
  1935. }
  1936. /**
  1937. * when "burn after reading" is checked, disable discussion
  1938. *
  1939. * @name TopNav.changeBurnAfterReading
  1940. * @function
  1941. */
  1942. function changeBurnAfterReading()
  1943. {
  1944. if ($burnAfterReading.is(':checked')) {
  1945. $openDiscussionOption.addClass('buttondisabled');
  1946. $openDiscussion.prop('checked', false);
  1947. // if button is actually disabled, force-enable it and uncheck other button
  1948. $burnAfterReadingOption.removeClass('buttondisabled');
  1949. } else {
  1950. $openDiscussionOption.removeClass('buttondisabled');
  1951. }
  1952. }
  1953. /**
  1954. * when discussion is checked, disable "burn after reading"
  1955. *
  1956. * @name TopNav.changeOpenDiscussion
  1957. * @function
  1958. */
  1959. function changeOpenDiscussion()
  1960. {
  1961. if ($openDiscussion.is(':checked')) {
  1962. $burnAfterReadingOption.addClass('buttondisabled');
  1963. $burnAfterReading.prop('checked', false);
  1964. // if button is actually disabled, force-enable it and uncheck other button
  1965. $openDiscussionOption.removeClass('buttondisabled');
  1966. } else {
  1967. $burnAfterReadingOption.removeClass('buttondisabled');
  1968. }
  1969. }
  1970. /**
  1971. * return raw text
  1972. *
  1973. * @name TopNav.rawText
  1974. * @function
  1975. * @param {Event} event
  1976. */
  1977. function rawText(event)
  1978. {
  1979. var paste = PasteViewer.getText();
  1980. // push a new state to allow back navigation with browser back button
  1981. history.pushState(
  1982. {type: 'raw'},
  1983. document.title,
  1984. // recreate paste URL
  1985. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  1986. Model.getPasteKey()
  1987. );
  1988. // we use text/html instead of text/plain to avoid a bug when
  1989. // reloading the raw text view (it reverts to type text/html)
  1990. var newDoc = document.open('text/html', 'replace');
  1991. newDoc.write('<pre>' + Helper.htmlEntities(paste) + '</pre>');
  1992. newDoc.close();
  1993. event.preventDefault();
  1994. }
  1995. /**
  1996. * saves the language in a cookie and reloads the page
  1997. *
  1998. * @name TopNav.setLanguage
  1999. * @function
  2000. * @param {Event} event
  2001. */
  2002. function setLanguage(event)
  2003. {
  2004. document.cookie = 'lang=' + $(event.target).data('lang');
  2005. UiHelper.reloadHome();
  2006. }
  2007. /**
  2008. * hides all messages and creates a new paste
  2009. *
  2010. * @private
  2011. * @function
  2012. * @param {Event} event
  2013. */
  2014. function clickNewPaste(event)
  2015. {
  2016. Controller.hideStatusMessages();
  2017. Controller.newPaste();
  2018. }
  2019. /**
  2020. * removes the existing attachment
  2021. *
  2022. * @private
  2023. * @function
  2024. * @param {Event} event
  2025. */
  2026. function removeAttachment(event)
  2027. {
  2028. // if custom attachment is used, remove it first
  2029. if (!$customAttachment.hasClass('hidden')) {
  2030. AttachmentViewer.removeAttachment();
  2031. $customAttachment.addClass('hidden');
  2032. $fileWrap.removeClass('hidden');
  2033. }
  2034. // our up-to-date jQuery can handle it :)
  2035. $fileWrap.find('input').val('');
  2036. // pevent '#' from appearing in the URL
  2037. event.preventDefault();
  2038. }
  2039. /**
  2040. * Loads the default options for creating a paste.
  2041. *
  2042. * @name TopNav.loadDefaults
  2043. * @function
  2044. */
  2045. me.loadDefaults = function()
  2046. {
  2047. // @TODO
  2048. };
  2049. /**
  2050. * Shows all elements belonging to viwing an existing pastes
  2051. *
  2052. * @name TopNav.hideAllElem
  2053. * @function
  2054. */
  2055. me.showViewButtons = function()
  2056. {
  2057. if (viewButtonsDisplayed) {
  2058. console.log('showViewButtons: view buttons are already displayed');
  2059. return;
  2060. }
  2061. $cloneButton.removeClass('hidden');
  2062. $rawTextButton.removeClass('hidden');
  2063. viewButtonsDisplayed = true;
  2064. };
  2065. /**
  2066. * Hides all elements belonging to existing pastes
  2067. *
  2068. * @name TopNav.hideAllElem
  2069. * @function
  2070. */
  2071. me.hideViewButtons = function()
  2072. {
  2073. if (!viewButtonsDisplayed) {
  2074. console.log('hideViewButtons: view buttons are already hidden');
  2075. return;
  2076. }
  2077. $newButton.removeClass('hidden');
  2078. $cloneButton.addClass('hidden');
  2079. $rawTextButton.addClass('hidden');
  2080. viewButtonsDisplayed = false;
  2081. };
  2082. /**
  2083. * shows all elements needed when creating a new paste
  2084. *
  2085. * @name TopNav.setLanguage
  2086. * @function
  2087. */
  2088. me.showCreateButtons = function()
  2089. {
  2090. if (createButtonsDisplayed) {
  2091. console.log('showCreateButtons: create buttons are already displayed');
  2092. return;
  2093. }
  2094. $sendButton.removeClass('hidden');
  2095. $expiration.removeClass('hidden');
  2096. $formatter.removeClass('hidden');
  2097. $burnAfterReadingOption.removeClass('hidden');
  2098. $openDiscussionOption.removeClass('hidden');
  2099. $newButton.removeClass('hidden');
  2100. $password.removeClass('hidden');
  2101. $attach.removeClass('hidden');
  2102. createButtonsDisplayed = true;
  2103. };
  2104. /**
  2105. * shows all elements needed when creating a new paste
  2106. *
  2107. * @name TopNav.setLanguage
  2108. * @function
  2109. */
  2110. me.hideCreateButtons = function()
  2111. {
  2112. if (!createButtonsDisplayed) {
  2113. console.log('hideCreateButtons: create buttons are already hidden');
  2114. return;
  2115. }
  2116. $newButton.addClass('hidden');
  2117. $sendButton.addClass('hidden');
  2118. $expiration.addClass('hidden');
  2119. $formatter.addClass('hidden');
  2120. $burnAfterReadingOption.addClass('hidden');
  2121. $openDiscussionOption.addClass('hidden');
  2122. $password.addClass('hidden');
  2123. $attach.addClass('hidden');
  2124. createButtonsDisplayed = false;
  2125. };
  2126. /**
  2127. * only shows the "new paste" button
  2128. *
  2129. * @name TopNav.setLanguage
  2130. * @function
  2131. */
  2132. me.showNewPasteButton = function()
  2133. {
  2134. $newButton.removeClass('hidden');
  2135. };
  2136. /**
  2137. * only hides the clone button
  2138. *
  2139. * @name TopNav.hideCloneButton
  2140. * @function
  2141. */
  2142. me.hideCloneButton = function()
  2143. {
  2144. $cloneButton.addClass('hidden');
  2145. };
  2146. /**
  2147. * only hides the raw text button
  2148. *
  2149. * @name TopNav.hideRawButton
  2150. * @function
  2151. */
  2152. me.hideRawButton = function()
  2153. {
  2154. $rawTextButton.addClass('hidden');
  2155. };
  2156. /**
  2157. * hides the file selector in attachment
  2158. *
  2159. * @name TopNav.hideFileSelector
  2160. * @function
  2161. */
  2162. me.hideFileSelector = function()
  2163. {
  2164. $fileWrap.addClass('hidden');
  2165. };
  2166. /**
  2167. * shows the custom attachment
  2168. *
  2169. * @name TopNav.showCustomAttachment
  2170. * @function
  2171. */
  2172. me.showCustomAttachment = function()
  2173. {
  2174. $customAttachment.removeClass('hidden');
  2175. };
  2176. /**
  2177. * collapses the navigation bar if nedded
  2178. *
  2179. * @name TopNav.collapseBar
  2180. * @function
  2181. */
  2182. me.collapseBar = function()
  2183. {
  2184. var $bar = $('.navbar-toggle');
  2185. // check if bar is expanded
  2186. if ($bar.hasClass('collapse in')) {
  2187. // if so, toggle it
  2188. $bar.click();
  2189. }
  2190. };
  2191. /**
  2192. * returns the currently set expiration time
  2193. *
  2194. * @name TopNav.getExpiration
  2195. * @function
  2196. * @return {int}
  2197. */
  2198. me.getExpiration = function()
  2199. {
  2200. return pasteExpiration;
  2201. };
  2202. /**
  2203. * returns the currently selected file(s)
  2204. *
  2205. * @name TopNav.getFileList
  2206. * @function
  2207. * @return {FileList|null}
  2208. */
  2209. me.getFileList = function()
  2210. {
  2211. var $file = $('#file');
  2212. // if no file given, return null
  2213. if (!$file.length || !$file[0].files.length) {
  2214. return null;
  2215. }
  2216. // @TODO is this really necessary
  2217. if (!($file[0].files && $file[0].files[0])) {
  2218. return null;
  2219. }
  2220. return $file[0].files;
  2221. };
  2222. /**
  2223. * returns the state of the burn after reading checkbox
  2224. *
  2225. * @name TopNav.getExpiration
  2226. * @function
  2227. * @return {bool}
  2228. */
  2229. me.getBurnAfterReading = function()
  2230. {
  2231. return $burnAfterReading.is(':checked');
  2232. };
  2233. /**
  2234. * returns the state of the discussion checkbox
  2235. *
  2236. * @name TopNav.getOpenDiscussion
  2237. * @function
  2238. * @return {bool}
  2239. */
  2240. me.getOpenDiscussion = function()
  2241. {
  2242. return $openDiscussion.is(':checked');
  2243. };
  2244. /**
  2245. * returns the entered password
  2246. *
  2247. * @name TopNav.getPassword
  2248. * @function
  2249. * @return {string}
  2250. */
  2251. me.getPassword = function()
  2252. {
  2253. return $passwordInput.val();
  2254. };
  2255. /**
  2256. * returns the element where custom attachments can be placed
  2257. *
  2258. * Used by AttachmentViewer when an attachment is cloned here.
  2259. *
  2260. * @name TopNav.getCustomAttachment
  2261. * @function
  2262. * @return {jQuery}
  2263. */
  2264. me.getCustomAttachment = function()
  2265. {
  2266. return $customAttachment;
  2267. };
  2268. /**
  2269. * init navigation manager
  2270. *
  2271. * preloads jQuery elements
  2272. *
  2273. * @name TopNav.init
  2274. * @function
  2275. */
  2276. me.init = function()
  2277. {
  2278. $attach = $('#attach');
  2279. $burnAfterReading = $('#burnafterreading');
  2280. $burnAfterReadingOption = $('#burnafterreadingoption');
  2281. $cloneButton = $('#clonebutton');
  2282. $customAttachment = $('#customattachment');
  2283. $expiration = $('#expiration');
  2284. $fileRemoveButton = $('#fileremovebutton');
  2285. $formatter = $('#formatter');
  2286. $newButton = $('#newbutton');
  2287. $openDiscussionOption = $('#opendiscussionoption');
  2288. $openDiscussion = $('#opendiscussion');
  2289. $password = $('#password');
  2290. $passwordInput = $('#passwordinput');
  2291. $rawTextButton = $('#rawtextbutton');
  2292. $sendButton = $('#sendbutton');
  2293. $fileWrap = $('#filewrap');
  2294. // bootstrap template drop down
  2295. $('#language ul.dropdown-menu li a').click(me.setLanguage);
  2296. // page template drop down
  2297. $('#language select option').click(me.setLanguage);
  2298. // bind events
  2299. $burnAfterReading.change(changeBurnAfterReading);
  2300. $openDiscussionOption.change(changeOpenDiscussion);
  2301. $newButton.click(clickNewPaste);
  2302. $sendButton.click(PasteEncrypter.submitPaste);
  2303. $cloneButton.click(Controller.clonePaste);
  2304. $rawTextButton.click(rawText);
  2305. $fileRemoveButton.click(removeAttachment);
  2306. // bootstrap template drop downs
  2307. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  2308. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  2309. // initiate default state of checkboxes
  2310. changeBurnAfterReading();
  2311. changeOpenDiscussion();
  2312. // get default value from template or fall back to set value
  2313. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  2314. me.loadDefaults();
  2315. };
  2316. return me;
  2317. })(window, document);
  2318. /**
  2319. * Responsible for AJAX requests, transparently handles encryption…
  2320. *
  2321. * @class
  2322. */
  2323. var Uploader = (function () {
  2324. var me = {};
  2325. var successFunc = null,
  2326. failureFunc = null,
  2327. url,
  2328. data,
  2329. randomKey,
  2330. password;
  2331. /**
  2332. * public variable ('constant') for errors to prevent magic numbers
  2333. *
  2334. * @readonly
  2335. * @enum {Object}
  2336. */
  2337. me.error = {
  2338. okay: 0,
  2339. custom: 1,
  2340. unknown: 2,
  2341. serverError: 3
  2342. };
  2343. /**
  2344. * ajaxHeaders to send in AJAX requests
  2345. *
  2346. * @private
  2347. * @readonly
  2348. * @enum {Object}
  2349. */
  2350. var ajaxHeaders = {'X-Requested-With': 'JSONHttpRequest'};
  2351. /**
  2352. * called after successful upload
  2353. *
  2354. * @function
  2355. * @param {int} status
  2356. * @param {int} data - optional
  2357. */
  2358. function success(status, result)
  2359. {
  2360. // add useful data to result
  2361. result.encryptionKey = randomKey;
  2362. result.requestData = data;
  2363. if (successFunc !== null) {
  2364. successFunc(status, result);
  2365. }
  2366. }
  2367. /**
  2368. * called after a upload failure
  2369. *
  2370. * @name Uploader.submitPasteUpload
  2371. * @function
  2372. * @param {int} status - internal code
  2373. * @param {int} data - original error code
  2374. */
  2375. function fail(status, result)
  2376. {
  2377. if (failureFunc !== null) {
  2378. failureFunc(status, result);
  2379. }
  2380. }
  2381. /**
  2382. * actually uploads the data
  2383. *
  2384. * @name Uploader.run
  2385. * @function
  2386. */
  2387. me.run = function()
  2388. {
  2389. $.ajax({
  2390. type: 'POST',
  2391. url: url,
  2392. data: data,
  2393. dataType: 'json',
  2394. headers: ajaxHeaders,
  2395. success: function(result) {
  2396. if (result.status === 0) {
  2397. success(0, result);
  2398. } else if (result.status === 1) {
  2399. fail(1, result);
  2400. } else {
  2401. fail(2, result);
  2402. }
  2403. }
  2404. })
  2405. .fail(function(jqXHR, textStatus, errorThrown) {
  2406. console.error(textStatus, errorThrown);
  2407. fail(3, jqXHR);
  2408. });
  2409. };
  2410. /**
  2411. * set success function
  2412. *
  2413. * @name Uploader.setSuccess
  2414. * @function
  2415. * @param {function} func
  2416. */
  2417. me.setUrl = function(newUrl)
  2418. {
  2419. url = newUrl;
  2420. };
  2421. /**
  2422. * set success function
  2423. *
  2424. * @name Uploader.setSuccess
  2425. * @function
  2426. * @param {function} func
  2427. */
  2428. me.setSuccess = function(func)
  2429. {
  2430. successFunc = func;
  2431. };
  2432. /**
  2433. * set failure function
  2434. *
  2435. * @name Uploader.setSuccess
  2436. * @function
  2437. * @param {function} func
  2438. */
  2439. me.setFailure = function(func)
  2440. {
  2441. failureFunc = func;
  2442. };
  2443. /**
  2444. * prepares a new upload
  2445. *
  2446. * @name Uploader.prepare
  2447. * @function
  2448. * @param {string} newPassword
  2449. * @return {object}
  2450. */
  2451. me.prepare = function(newPassword)
  2452. {
  2453. // set password
  2454. password = newPassword;
  2455. // entropy should already be checked!
  2456. // generate a new random key
  2457. randomKey = CryptTool.getSymmetricKey();
  2458. // reset data
  2459. successFunc = null;
  2460. failureFunc = null;
  2461. url = Helper.baseUri()
  2462. data = {};
  2463. };
  2464. /**
  2465. * encrypts and sets the data
  2466. *
  2467. * @name Uploader.setData
  2468. * @function
  2469. * @param {string} index
  2470. * @param {mixed} element
  2471. */
  2472. me.setData = function(index, element)
  2473. {
  2474. data[index] = CryptTool.cipher(randomKey, password, element);
  2475. };
  2476. /**
  2477. * set the additional metadata to send unencrypted
  2478. *
  2479. * @name Uploader.setUnencryptedData
  2480. * @function
  2481. * @param {string} index
  2482. * @param {mixed} element
  2483. */
  2484. me.setUnencryptedData = function(index, element)
  2485. {
  2486. data[index] = element;
  2487. };
  2488. /**
  2489. * set the additional metadata to send unencrypted passed at once
  2490. *
  2491. * @name Uploader.setUnencryptedData
  2492. * @function
  2493. * @param {object} newData
  2494. */
  2495. me.setUnencryptedBulkData = function(newData)
  2496. {
  2497. $.extend(data, newData);
  2498. };
  2499. /**
  2500. * init Uploader
  2501. *
  2502. * @name Uploader.init
  2503. * @function
  2504. */
  2505. me.init = function()
  2506. {
  2507. // nothing yet
  2508. };
  2509. return me;
  2510. })();
  2511. /**
  2512. * (controller) Responsible for encrypting paste and sending it to server.
  2513. *
  2514. * @name state
  2515. * @class
  2516. */
  2517. var PasteEncrypter = (function () {
  2518. var me = {};
  2519. var requirementsChecked = false;
  2520. /**
  2521. * checks whether there is a suitable amount of entrophy
  2522. *
  2523. * @private
  2524. * @function
  2525. * @param {function} retryCallback - the callback to execute to retry the upload
  2526. * @return {bool}
  2527. */
  2528. function checkRequirements(retryCallback) {
  2529. // skip double requirement checks
  2530. if (requirementsChecked === true) {
  2531. return true;
  2532. }
  2533. if (!CryptTool.isEntropyReady()) {
  2534. // display a message and wait
  2535. Alert.showStatus('Please move your mouse for more entropy…');
  2536. CryptTool.addEntropySeedListener(retryCallback);
  2537. return false;
  2538. }
  2539. requirementsChecked = true;
  2540. return true;
  2541. }
  2542. /**
  2543. * called after successful upload
  2544. *
  2545. * @private
  2546. * @function
  2547. * @param {int} status
  2548. * @param {int} data
  2549. */
  2550. function showCreatedPaste(status, data) {
  2551. Alert.hideLoading();
  2552. var url = Helper.baseUri() + '?' + data.id + '#' + data.encryptionKey,
  2553. deleteUrl = Helper.baseUri() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  2554. Alert.hideMessages();
  2555. // show notification
  2556. PasteStatus.createPasteNotification(url, deleteUrl)
  2557. // show new URL in browser bar
  2558. history.pushState({type: 'newpaste'}, document.title, url);
  2559. TopNav.showViewButtons();
  2560. TopNav.hideRawButton();
  2561. Editor.hide();
  2562. // parse and show text
  2563. // (preparation already done in me.submitPaste())
  2564. PasteViewer.run();
  2565. }
  2566. /**
  2567. * adds attachments to the Uploader
  2568. *
  2569. * @private
  2570. * @function
  2571. * @param {File|null|undefined} file - optional, falls back to cloned attachment
  2572. * @param {function} callback - excuted when action is successful
  2573. */
  2574. function encryptAttachments(file, callback) {
  2575. if (typeof file !== 'undefined' && file !== null) {
  2576. // check file reader requirements for upload
  2577. if (typeof FileReader === 'undefined') {
  2578. Alert.showError('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2579. // cancels process as it does not execute callback
  2580. return;
  2581. }
  2582. var reader = new FileReader();
  2583. // closure to capture the file information
  2584. reader.onload = function(event) {
  2585. Uploader.setData('attachment', event.target.result);
  2586. Uploader.setData('attachmentname', file.name);
  2587. // run callback
  2588. return callback();
  2589. };
  2590. // actually read first file
  2591. reader.readAsDataURL(file);
  2592. } else if (AttachmentViewer.hasAttachment()) {
  2593. // fall back to cloned part
  2594. var attachment = AttachmentViewer.getAttachment();
  2595. Uploader.setData('attachment', attachment[0]);
  2596. Uploader.setData('attachmentname', attachment[1]);
  2597. return callback();
  2598. } else {
  2599. // if there are no attachments, this is of course still successful
  2600. return callback();
  2601. }
  2602. }
  2603. /**
  2604. * send a reply in a discussion
  2605. *
  2606. * @name PasteEncrypter.sendComment
  2607. * @function
  2608. * @param {Event} event
  2609. * @TODO WIP
  2610. */
  2611. me.sendComment = function(event)
  2612. {
  2613. event.preventDefault();
  2614. $errorMessage.addClass('hidden');
  2615. // do not send if no data
  2616. var replyMessage = $('#replymessage');
  2617. if (replyMessage.val().length === 0)
  2618. {
  2619. return;
  2620. }
  2621. me.showStatus(I18n._('Sending comment...'), true);
  2622. var parentid = event.data.parentid,
  2623. key = Model.getPasteKey(),
  2624. cipherdata = CryptTool.cipher(key, $passwordInput.val(), replyMessage.val()),
  2625. ciphernickname = '',
  2626. nick = $('#nickname').val();
  2627. if (nick.length > 0)
  2628. {
  2629. ciphernickname = CryptTool.cipher(key, $passwordInput.val(), nick);
  2630. }
  2631. var dataToSend = {
  2632. data: cipherdata,
  2633. parentid: parentid,
  2634. pasteid: Model.getPasteId(),
  2635. nickname: ciphernickname
  2636. };
  2637. $.ajax({
  2638. type: 'POST',
  2639. url: Helper.baseUri(),
  2640. data: dataToSend,
  2641. dataType: 'json',
  2642. headers: ajaxHeaders,
  2643. success: function(data) {
  2644. if (data.status === 0)
  2645. {
  2646. status.showStatus(I18n._('Comment posted.'));
  2647. $.ajax({
  2648. type: 'GET',
  2649. url: Helper.baseUri() + '?' + Model.getPasteId(),
  2650. dataType: 'json',
  2651. headers: ajaxHeaders,
  2652. success: function(data) {
  2653. if (data.status === 0)
  2654. {
  2655. me.displayMessages(data);
  2656. }
  2657. else if (data.status === 1)
  2658. {
  2659. Alert.showError(['Could not refresh display: %s', data.message]);
  2660. }
  2661. else
  2662. {
  2663. Alert.showError(['Could not refresh display: %s', I18n._('unknown status')]);
  2664. }
  2665. }
  2666. })
  2667. .fail(function() {
  2668. Alert.showError(['Could not refresh display: %s', I18n._('server error or not responding')]);
  2669. });
  2670. }
  2671. else if (data.status === 1)
  2672. {
  2673. Alert.showError(['Could not post comment: %s', data.message]);
  2674. }
  2675. else
  2676. {
  2677. Alert.showError(['Could not post comment: %s', I18n._('unknown status')]);
  2678. }
  2679. }
  2680. })
  2681. .fail(function() {
  2682. Alert.showError(['Could not post comment: %s', I18n._('server error or not responding')]);
  2683. });
  2684. };
  2685. /**
  2686. * sends a new paste to server
  2687. *
  2688. * @name PasteEncrypter.submitPaste
  2689. * @function
  2690. */
  2691. me.submitPaste = function()
  2692. {
  2693. // hide previous (error) messages
  2694. Alert.hideMessages();
  2695. // UI loading state
  2696. TopNav.hideCreateButtons();
  2697. Alert.showLoading('Sending paste…', 0, 'cloud-upload');
  2698. TopNav.collapseBar();
  2699. // get data
  2700. var plainText = Editor.getText(),
  2701. format = PasteViewer.getFormat(),
  2702. files = TopNav.getFileList();
  2703. // do not send if there is no data
  2704. if (plainText.length === 0 && files === null) {
  2705. // revert loading status…
  2706. Alert.hideLoading();
  2707. TopNav.showCreateButtons();
  2708. return;
  2709. }
  2710. Alert.showLoading(null, 10);
  2711. // check entropy
  2712. if (!checkRequirements(function () {
  2713. me.submitPaste();
  2714. })) {
  2715. return; // to prevent multiple executions
  2716. }
  2717. // prepare Uploader
  2718. Uploader.prepare(TopNav.getPassword());
  2719. // set success/fail functions
  2720. Uploader.setSuccess(showCreatedPaste);
  2721. Uploader.setFailure(function (status, data) {
  2722. // revert loading status…
  2723. Alert.hideLoading();
  2724. TopNav.showCreateButtons();
  2725. // show error message
  2726. switch (status) {
  2727. case Uploader.error['custom']:
  2728. Alert.showError(['Could not create paste: %s', data.message]);
  2729. break;
  2730. case Uploader.error['unknown']:
  2731. Alert.showError(['Could not create paste: %s', I18n._('unknown status')]);
  2732. break;
  2733. case Uploader.error['serverError']:
  2734. Alert.showError(['Could not create paste: %s', I18n._('server error or not responding')]);
  2735. break;
  2736. default:
  2737. Alert.showError(['Could not create paste: %s', I18n._('unknown error')]);
  2738. break;
  2739. }
  2740. });
  2741. // fill it with unencrypted submitted options
  2742. Uploader.setUnencryptedBulkData({
  2743. expire: TopNav.getExpiration(),
  2744. formatter: format,
  2745. burnafterreading: TopNav.getBurnAfterReading() ? 1 : 0,
  2746. opendiscussion: TopNav.getOpenDiscussion() ? 1 : 0
  2747. });
  2748. // prepare PasteViewer for later preview
  2749. PasteViewer.setText(plainText);
  2750. PasteViewer.setFormat(format);
  2751. // encrypt cipher data
  2752. Uploader.setData('data', plainText);
  2753. // encrypt attachments
  2754. encryptAttachments(
  2755. files === null ? null : files[0],
  2756. function () {
  2757. // send data
  2758. Uploader.run();
  2759. }
  2760. );
  2761. };
  2762. /**
  2763. * initialize
  2764. *
  2765. * @name PasteEncrypter.init
  2766. * @function
  2767. */
  2768. me.init = function()
  2769. {
  2770. // nothing yet
  2771. };
  2772. return me;
  2773. })();
  2774. /**
  2775. * (controller) Responsible for decrypting cipherdata and passing data to view.
  2776. *
  2777. * @name state
  2778. * @class
  2779. */
  2780. var PasteDecrypter = (function () {
  2781. var me = {};
  2782. /**
  2783. * decrypt the actual paste text
  2784. *
  2785. * @private
  2786. * @function
  2787. * @param {object} paste - paste data in object form
  2788. * @param {string} key
  2789. * @param {string} password
  2790. * @return {bool} - whether action was successful
  2791. */
  2792. function decryptPaste(paste, key, password)
  2793. {
  2794. // try decryption without password
  2795. var plaintext = CryptTool.decipher(key, password, paste.data);
  2796. // if it fails, request password
  2797. if (plaintext.length === 0 && password.length === 0) {
  2798. // get password
  2799. try {
  2800. console.log('bef');
  2801. password = Prompt.getPassword();
  2802. console.log('pass');
  2803. } catch (e) {
  2804. console.error(e);
  2805. return false;
  2806. }
  2807. // if password is there, re-try
  2808. if (password.length !== 0) {
  2809. // recursive
  2810. // note: an infinite loop is prevented as the previous if
  2811. // clause checks whether a password is already set and ignores
  2812. // error with password being passed
  2813. return decryptPaste(paste, key, password);
  2814. }
  2815. // trigger password request
  2816. Prompt.requestPassword();
  2817. // the callback (via setPasswordCallback()) should have been set
  2818. // by parent function
  2819. return false;
  2820. }
  2821. // if all tries failed, we can only throw an error
  2822. if (plaintext.length === 0) {
  2823. throw 'failed to decipher message';
  2824. }
  2825. // on success show paste
  2826. PasteViewer.setFormat(paste.meta.formatter);
  2827. PasteViewer.setText(plaintext);
  2828. // trigger to show the text (attachment loaded afterwards)
  2829. PasteViewer.run();
  2830. return true;
  2831. }
  2832. /**
  2833. * decrypts any attachment
  2834. *
  2835. * @private
  2836. * @function
  2837. * @param {object} paste - paste data in object form
  2838. * @param {string} key
  2839. * @param {string} password
  2840. * @return {bool} - whether action was successful
  2841. */
  2842. function decryptAttachment(paste, key, password)
  2843. {
  2844. // decrypt attachment
  2845. var attachment = CryptTool.decipher(key, password, paste.attachment);
  2846. if (attachment.length === 0) {
  2847. throw 'failed to decipher attachment';
  2848. }
  2849. // decrypt attachment name
  2850. var attachmentName;
  2851. if (paste.attachmentname) {
  2852. attachmentName = attachmentName = CryptTool.decipher(key, password, paste.attachmentname);
  2853. if (attachmentName.length === 0) {
  2854. // @TODO considering the buggy cloning (?, see other todo comment) this might affect previous pastes
  2855. throw 'failed to decipher attachment name';
  2856. }
  2857. }
  2858. AttachmentViewer.setAttachment(attachment, attachmentName);
  2859. AttachmentViewer.showAttachment();
  2860. }
  2861. /**
  2862. * show decrypted text in the display area, including discussion (if open)
  2863. *
  2864. * @name PasteDecrypter.run
  2865. * @function
  2866. * @param {Object} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  2867. */
  2868. me.run = function(paste)
  2869. {
  2870. Alert.showLoading('Decrypting paste…', 0, 'cloud-download'); // @TODO icon maybe rotation-lock, but needs full Glyphicons
  2871. if (typeof paste === 'undefined') {
  2872. paste = $.parseJSON(Model.getCipherData());
  2873. }
  2874. var key = Model.getPasteKey(),
  2875. password = Prompt.getPassword();
  2876. if (PasteViewer.isPrettyPrinted()) {
  2877. console.error('Too pretty! (don\'t know why this check)'); //@TODO
  2878. return;
  2879. }
  2880. // try to decrypt the paste
  2881. try {
  2882. Prompt.setPasswordCallback(function () {
  2883. me.run(paste);
  2884. });
  2885. // try to decrypt paste and if it fails (because the password is
  2886. // missing) return to let JS continue and wait for user
  2887. if (!decryptPaste(paste, key, password)) {
  2888. return;
  2889. }
  2890. // decrypt attachments
  2891. if (paste.attachment) {
  2892. decryptAttachment(paste, key, password);
  2893. }
  2894. } catch(err) {
  2895. Alert.hideLoading();
  2896. // log and show error
  2897. console.error(err);
  2898. Alert.showError('Could not decrypt data (Wrong key?)'); // @TODO error is not translated
  2899. // still go on to potentially show potentially partially decrypted data
  2900. }
  2901. // shows the remaining time (until) deletion
  2902. PasteStatus.showRemainingTime(paste.meta);
  2903. // if the discussion is opened on this paste, display it
  2904. // @TODO BELOW
  2905. if (paste.meta.opendiscussion) {
  2906. $comments.html('');
  2907. var $divComment;
  2908. // iterate over comments
  2909. for (var i = 0; i < paste.comments.length; ++i)
  2910. {
  2911. var $place = $comments,
  2912. comment = paste.comments[i],
  2913. commentText = CryptTool.decipher(key, password, comment.data),
  2914. $parentComment = $('#comment_' + comment.parentid);
  2915. $divComment = $('<article><div class="comment" id="comment_' + comment.id
  2916. + '"><div class="commentmeta"><span class="nickname"></span>'
  2917. + '<span class="commentdate"></span></div>'
  2918. + '<div class="commentdata"></div>'
  2919. + '<button class="btn btn-default btn-sm">'
  2920. + I18n._('Reply') + '</button></div></article>');
  2921. var $divCommentData = $divComment.find('div.commentdata');
  2922. // if parent comment exists
  2923. if ($parentComment.length)
  2924. {
  2925. // shift comment to the right
  2926. $place = $parentComment;
  2927. }
  2928. $divComment.find('button').click({commentid: comment.id}, me.openReply);
  2929. Helper.setElementText($divCommentData, commentText);
  2930. Helper.urls2links($divCommentData);
  2931. // try to get optional nickname
  2932. var nick = CryptTool.decipher(key, password, comment.meta.nickname);
  2933. if (nick.length > 0)
  2934. {
  2935. $divComment.find('span.nickname').text(nick);
  2936. }
  2937. else
  2938. {
  2939. divComment.find('span.nickname').html('<i>' + I18n._('Anonymous') + '</i>');
  2940. }
  2941. $divComment.find('span.commentdate')
  2942. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  2943. .attr('title', 'CommentID: ' + comment.id);
  2944. // if an avatar is available, display it
  2945. if (comment.meta.vizhash)
  2946. {
  2947. $divComment.find('span.nickname')
  2948. .before(
  2949. '<img src="' + comment.meta.vizhash + '" class="vizhash" title="' +
  2950. I18n._('Anonymous avatar (Vizhash of the IP address)') + '" /> '
  2951. );
  2952. }
  2953. $place.append($divComment);
  2954. }
  2955. // add 'add new comment' area
  2956. $divComment = $(
  2957. '<div class="comment"><button class="btn btn-default btn-sm">' +
  2958. I18n._('Add comment') + '</button></div>'
  2959. );
  2960. $divComment.find('button').click({commentid: Model.getPasteId()}, me.openReply);
  2961. $comments.append($divComment);
  2962. $discussion.removeClass('hidden');
  2963. }
  2964. Alert.hideLoading();
  2965. TopNav.showViewButtons();
  2966. };
  2967. /**
  2968. * initialize
  2969. *
  2970. * @name PasteDecrypter.init
  2971. * @function
  2972. */
  2973. me.init = function()
  2974. {
  2975. // nothing yet
  2976. };
  2977. return me;
  2978. })();
  2979. /**
  2980. * (controller) main PrivateBin logic
  2981. *
  2982. * @param {object} window
  2983. * @param {object} document
  2984. * @class
  2985. */
  2986. var Controller = (function (window, document) {
  2987. var me = {};
  2988. /**
  2989. * hides all status messages no matter which module showed them
  2990. *
  2991. * @name Controller.hideStatusMessages
  2992. * @function
  2993. */
  2994. me.hideStatusMessages = function()
  2995. {
  2996. PasteStatus.hideMessages();
  2997. Alert.hideMessages();
  2998. };
  2999. /**
  3000. * creates a new paste
  3001. *
  3002. * @name Controller.newPaste
  3003. * @function
  3004. */
  3005. me.newPaste = function()
  3006. {
  3007. TopNav.hideViewButtons();
  3008. Alert.showLoading('Preparing new paste…', 0, 'time');
  3009. PasteViewer.hide();
  3010. Editor.resetInput();
  3011. Editor.show();
  3012. Editor.focusInput();
  3013. TopNav.loadDefaults();
  3014. TopNav.showCreateButtons();
  3015. Alert.hideLoading();
  3016. };
  3017. /**
  3018. * clone the current paste
  3019. *
  3020. * @name Controller.clonePaste
  3021. * @function
  3022. * @param {Event} event
  3023. */
  3024. me.clonePaste = function(event)
  3025. {
  3026. TopNav.collapseBar();
  3027. TopNav.hideViewButtons();
  3028. Alert.showLoading('Cloning paste…', 0, 'transfer');
  3029. // hide messages from previous paste
  3030. me.hideStatusMessages();
  3031. // erase the id and the key in url
  3032. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  3033. if (AttachmentViewer.hasAttachment()) {
  3034. AttachmentViewer.moveAttachmentTo(
  3035. TopNav.getCustomAttachment(),
  3036. 'Cloned: \'%s\''
  3037. );
  3038. TopNav.hideFileSelector();
  3039. AttachmentViewer.hideAttachment();
  3040. // NOTE: it also looks nice without removing the attachment
  3041. // but for a consistent display we remove it…
  3042. AttachmentViewer.hideAttachmentPreview();
  3043. TopNav.showCustomAttachment();
  3044. // show another status message to make the user aware that the
  3045. // file was cloned too!
  3046. Alert.showStatus(
  3047. [
  3048. 'The cloned file \'%s\' was attached to this paste.',
  3049. AttachmentViewer.getAttachment()[1]
  3050. ], 'copy', true, true);
  3051. }
  3052. Editor.setText(PasteViewer.getText())
  3053. PasteViewer.hide();
  3054. Editor.show();
  3055. Alert.hideLoading();
  3056. TopNav.showCreateButtons();
  3057. };
  3058. /**
  3059. * removes a saved paste
  3060. *
  3061. * @name Controller.removePaste
  3062. * @function
  3063. * @param {string} pasteId
  3064. * @param {string} deleteToken
  3065. */
  3066. me.removePaste = function(pasteId, deleteToken) {
  3067. // unfortunately many web servers don't support DELETE (and PUT) out of the box
  3068. // so we use a POST request
  3069. Uploader.prepare();
  3070. Uploader.setUrl(Helper.baseUri() + '?' + pasteId);
  3071. Uploader.setUnencryptedData('deletetoken', deleteToken);
  3072. Uploader.setFailure(function () {
  3073. Controller.showError(I18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  3074. })
  3075. Uploader.run();
  3076. };
  3077. /**
  3078. * application start
  3079. *
  3080. * @name Controller.init
  3081. * @function
  3082. */
  3083. me.init = function()
  3084. {
  3085. // first load translations
  3086. I18n.loadTranslations();
  3087. // initialize other modules/"classes"
  3088. Alert.init();
  3089. Uploader.init();
  3090. Model.init();
  3091. CryptTool.init();
  3092. UiHelper.init();
  3093. TopNav.init();
  3094. Editor.init();
  3095. PasteStatus.init();
  3096. PasteViewer.init();
  3097. AttachmentViewer.init();
  3098. DiscussionViewer.init();
  3099. PasteEncrypter.init();
  3100. PasteDecrypter.init();
  3101. Prompt.init();
  3102. // display an existing paste
  3103. if (Model.hasCipherData()) {
  3104. // missing decryption key in URL?
  3105. if (window.location.hash.length === 0) {
  3106. Alert.showError('Cannot decrypt paste: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL?)');
  3107. return;
  3108. }
  3109. // show proper elements on screen
  3110. PasteDecrypter.run();
  3111. return;
  3112. }
  3113. // otherwise create a new paste
  3114. me.newPaste();
  3115. };
  3116. return me;
  3117. })(window, document);
  3118. return {
  3119. Helper: Helper,
  3120. I18n: I18n,
  3121. CryptTool: CryptTool,
  3122. TopNav: TopNav,
  3123. Alert: Alert,
  3124. Uploader: Uploader,
  3125. Controller: Controller
  3126. };
  3127. }(jQuery, sjcl, Base64, RawDeflate);