privatebin.js 117 KB

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