privatebin.js 119 KB

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