privatebin.js 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994
  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. * @class
  1877. */
  1878. var DiscussionViewer = (function () {
  1879. var me = {};
  1880. var $commentTail,
  1881. $discussion,
  1882. $reply,
  1883. $replyMessage,
  1884. $replyNickname,
  1885. $replyStatus,
  1886. $commentContainer;
  1887. var replyCommentId;
  1888. /**
  1889. * initializes the templates
  1890. *
  1891. * @name DiscussionViewer.initTemplates
  1892. * @private
  1893. * @function
  1894. */
  1895. function initTemplates()
  1896. {
  1897. $reply = Model.getTemplate('reply');
  1898. $replyMessage = $reply.find('#replymessage');
  1899. $replyNickname = $reply.find('#nickname');
  1900. $replyStatus = $reply.find('#replystatus');
  1901. // cache jQuery elements
  1902. $commentTail = Model.getTemplate('commenttail');
  1903. }
  1904. /**
  1905. * open the comment entry when clicking the "Reply" button of a comment
  1906. *
  1907. * @name DiscussionViewer.openReply
  1908. * @private
  1909. * @function
  1910. * @param {Event} event
  1911. */
  1912. function openReply(event)
  1913. {
  1914. var $source = $(event.target);
  1915. // clear input
  1916. $replyMessage.val('');
  1917. $replyNickname.val('');
  1918. // get comment id from source element
  1919. replyCommentId = $source.parent().prop('id').split('_')[1];
  1920. // move to correct position
  1921. $source.after($reply);
  1922. // show
  1923. $reply.removeClass('hidden');
  1924. $replyMessage.focus();
  1925. event.preventDefault();
  1926. }
  1927. /**
  1928. * custom handler for displaying notifications in own status message area
  1929. *
  1930. * @name DiscussionViewer.handleNotification
  1931. * @function
  1932. * @param {string} alertType
  1933. * @param {jQuery} $element
  1934. * @param {string|array} args
  1935. * @param {string|null} icon
  1936. * @return {bool|jQuery}
  1937. */
  1938. me.handleNotification = function(alertType, $element, args, icon)
  1939. {
  1940. // ignore loading messages
  1941. if (alertType === 'loading') {
  1942. return false;
  1943. }
  1944. if (alertType === 'danger') {
  1945. $replyStatus.removeClass('alert-info');
  1946. $replyStatus.addClass('alert-danger');
  1947. $replyStatus.find(':first').removeClass('glyphicon-alert');
  1948. $replyStatus.find(':first').addClass('glyphicon-info-sign');
  1949. } else {
  1950. $replyStatus.removeClass('alert-danger');
  1951. $replyStatus.addClass('alert-info');
  1952. $replyStatus.find(':first').removeClass('glyphicon-info-sign');
  1953. $replyStatus.find(':first').addClass('glyphicon-alert');
  1954. }
  1955. return $replyStatus;
  1956. }
  1957. /**
  1958. * adds another comment
  1959. *
  1960. * @name DiscussionViewer.addComment
  1961. * @function
  1962. * @param {object} comment
  1963. * @param {string} commentText
  1964. * @param {jQuery} $place - optional, tries to find the best position otherwise
  1965. */
  1966. me.addComment = function(comment, commentText, nickname, $place)
  1967. {
  1968. if (typeof $place === 'undefined') {
  1969. // starting point (default value/fallback)
  1970. $place = $commentContainer;
  1971. // if parent comment exists
  1972. var $parentComment = $('#comment_' + comment.parentid);
  1973. if ($parentComment.length) {
  1974. // use parent as position for noew comment, so it shifted
  1975. // to the right
  1976. $place = $parentComment;
  1977. }
  1978. }
  1979. if (commentText === '') {
  1980. commentText = 'comment decryption failed';
  1981. }
  1982. // create new comment based on template
  1983. var $commentEntry = Model.getTemplate('comment');
  1984. $commentEntry.prop('id', 'comment_' + comment.id);
  1985. var $commentEntryData = $commentEntry.find('div.commentdata');
  1986. // set & parse text
  1987. $commentEntryData.html(
  1988. DOMPurify.sanitize(
  1989. Helper.urls2links(commentText),
  1990. {SAFE_FOR_JQUERY: true}
  1991. )
  1992. );
  1993. // set nickname
  1994. if (nickname.length > 0) {
  1995. $commentEntry.find('span.nickname').text(nickname);
  1996. } else {
  1997. $commentEntry.find('span.nickname').html('<i></i>');
  1998. I18n._($commentEntry.find('span.nickname i'), 'Anonymous');
  1999. }
  2000. // set date
  2001. $commentEntry.find('span.commentdate')
  2002. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  2003. .attr('title', 'CommentID: ' + comment.id);
  2004. // if an avatar is available, display it
  2005. if (comment.meta.vizhash) {
  2006. $commentEntry.find('span.nickname')
  2007. .before(
  2008. '<img src="' + comment.meta.vizhash + '" class="vizhash" /> '
  2009. );
  2010. $(document).on('languageLoaded', function () {
  2011. $commentEntry.find('img.vizhash')
  2012. .prop('title', I18n._('Avatar generated from IP address'));
  2013. });
  2014. }
  2015. // finally append comment
  2016. $place.append($commentEntry);
  2017. }
  2018. /**
  2019. * finishes the discussion area after last comment
  2020. *
  2021. * @name DiscussionViewer.finishDiscussion
  2022. * @function
  2023. */
  2024. me.finishDiscussion = function()
  2025. {
  2026. // add 'add new comment' area
  2027. $commentContainer.append($commentTail);
  2028. // show discussions
  2029. $discussion.removeClass('hidden');
  2030. }
  2031. /**
  2032. * shows the discussion area
  2033. *
  2034. * @name DiscussionViewer.showDiscussion
  2035. * @function
  2036. */
  2037. me.showDiscussion = function()
  2038. {
  2039. $discussion.removeClass('hidden');
  2040. }
  2041. /**
  2042. * removes the old discussion and prepares everything for creating a new
  2043. * one.
  2044. *
  2045. * @name DiscussionViewer.prepareNewDiscussion
  2046. * @function
  2047. */
  2048. me.prepareNewDiscussion = function()
  2049. {
  2050. $commentContainer.html('');
  2051. $discussion.addClass('hidden');
  2052. // (re-)init templates
  2053. initTemplates();
  2054. }
  2055. /**
  2056. * returns the users message from the reply form
  2057. *
  2058. * @name DiscussionViewer.getReplyMessage
  2059. * @function
  2060. * @return {String}
  2061. */
  2062. me.getReplyMessage = function()
  2063. {
  2064. return $replyMessage.val();
  2065. }
  2066. /**
  2067. * returns the users nickname (if any) from the reply form
  2068. *
  2069. * @name DiscussionViewer.getReplyNickname
  2070. * @function
  2071. * @return {String}
  2072. */
  2073. me.getReplyNickname = function()
  2074. {
  2075. return $replyNickname.val();
  2076. }
  2077. /**
  2078. * returns the id of the parent comment the user is replying to
  2079. *
  2080. * @name DiscussionViewer.getReplyCommentId
  2081. * @function
  2082. * @return {int|undefined}
  2083. */
  2084. me.getReplyCommentId = function()
  2085. {
  2086. return replyCommentId;
  2087. }
  2088. /**
  2089. * highlights a specific comment and scrolls to it if necessary
  2090. *
  2091. * @name DiscussionViewer.highlightComment
  2092. * @function
  2093. * @param {string} commentId
  2094. * @param {bool} fadeOut - whether to fade out the comment
  2095. */
  2096. me.highlightComment = function(commentId, fadeOut)
  2097. {
  2098. var $comment = $('#comment_' + commentId);
  2099. // in case comment does not exist, cancel
  2100. if ($comment.length === 0) {
  2101. return;
  2102. }
  2103. var highlightComment = function () {
  2104. $comment.addClass('highlight');
  2105. if (fadeOut === true) {
  2106. setTimeout(function () {
  2107. $comment.removeClass('highlight');
  2108. }, 300);
  2109. }
  2110. }
  2111. if (UiHelper.isVisible($comment)) {
  2112. return highlightComment();
  2113. }
  2114. UiHelper.scrollTo($comment, 100, 'swing', highlightComment);
  2115. }
  2116. /**
  2117. * initiate
  2118. *
  2119. * preloads jQuery elements
  2120. *
  2121. * @name DiscussionViewer.init
  2122. * @function
  2123. */
  2124. me.init = function()
  2125. {
  2126. // bind events to templates (so they are later cloned)
  2127. $('#commenttailtemplate, #commenttemplate').find('button').on('click', openReply);
  2128. $('#replytemplate').find('button').on('click', PasteEncrypter.sendComment);
  2129. $commentContainer = $('#commentcontainer');
  2130. $discussion = $('#discussion');
  2131. }
  2132. return me;
  2133. })();
  2134. /**
  2135. * Manage top (navigation) bar
  2136. *
  2137. * @name TopNav
  2138. * @param {object} window
  2139. * @param {object} document
  2140. * @class
  2141. */
  2142. var TopNav = (function (window, document) {
  2143. var me = {};
  2144. var createButtonsDisplayed = false;
  2145. var viewButtonsDisplayed = false;
  2146. var $attach,
  2147. $burnAfterReading,
  2148. $burnAfterReadingOption,
  2149. $cloneButton,
  2150. $customAttachment,
  2151. $expiration,
  2152. $fileRemoveButton,
  2153. $fileWrap,
  2154. $formatter,
  2155. $newButton,
  2156. $openDiscussion,
  2157. $openDiscussionOption,
  2158. $password,
  2159. $passwordInput,
  2160. $rawTextButton,
  2161. $sendButton;
  2162. var pasteExpiration = '1week';
  2163. /**
  2164. * set the expiration on bootstrap templates in dropdown
  2165. *
  2166. * @name TopNav.updateExpiration
  2167. * @private
  2168. * @function
  2169. * @param {Event} event
  2170. */
  2171. function updateExpiration(event)
  2172. {
  2173. // get selected option
  2174. var target = $(event.target);
  2175. // update dropdown display and save new expiration time
  2176. $('#pasteExpirationDisplay').text(target.text());
  2177. pasteExpiration = target.data('expiration');
  2178. event.preventDefault();
  2179. }
  2180. /**
  2181. * set the format on bootstrap templates in dropdown
  2182. *
  2183. * @name TopNav.updateFormat
  2184. * @private
  2185. * @function
  2186. * @param {Event} event
  2187. */
  2188. function updateFormat(event)
  2189. {
  2190. // get selected option
  2191. var $target = $(event.target);
  2192. // update dropdown display and save new format
  2193. var newFormat = $target.data('format');
  2194. $('#pasteFormatterDisplay').text($target.text());
  2195. PasteViewer.setFormat(newFormat);
  2196. // update preview
  2197. if (Editor.isPreview()) {
  2198. PasteViewer.run();
  2199. }
  2200. event.preventDefault();
  2201. }
  2202. /**
  2203. * when "burn after reading" is checked, disable discussion
  2204. *
  2205. * @name TopNav.changeBurnAfterReading
  2206. * @private
  2207. * @function
  2208. */
  2209. function changeBurnAfterReading()
  2210. {
  2211. if ($burnAfterReading.is(':checked')) {
  2212. $openDiscussionOption.addClass('buttondisabled');
  2213. $openDiscussion.prop('checked', false);
  2214. // if button is actually disabled, force-enable it and uncheck other button
  2215. $burnAfterReadingOption.removeClass('buttondisabled');
  2216. } else {
  2217. $openDiscussionOption.removeClass('buttondisabled');
  2218. }
  2219. }
  2220. /**
  2221. * when discussion is checked, disable "burn after reading"
  2222. *
  2223. * @name TopNav.changeOpenDiscussion
  2224. * @private
  2225. * @function
  2226. */
  2227. function changeOpenDiscussion()
  2228. {
  2229. if ($openDiscussion.is(':checked')) {
  2230. $burnAfterReadingOption.addClass('buttondisabled');
  2231. $burnAfterReading.prop('checked', false);
  2232. // if button is actually disabled, force-enable it and uncheck other button
  2233. $openDiscussionOption.removeClass('buttondisabled');
  2234. } else {
  2235. $burnAfterReadingOption.removeClass('buttondisabled');
  2236. }
  2237. }
  2238. /**
  2239. * return raw text
  2240. *
  2241. * @name TopNav.rawText
  2242. * @private
  2243. * @function
  2244. * @param {Event} event
  2245. */
  2246. function rawText(event)
  2247. {
  2248. TopNav.hideAllButtons();
  2249. Alert.showLoading('Showing raw text…', 0, 'time');
  2250. var paste = PasteViewer.getText();
  2251. // push a new state to allow back navigation with browser back button
  2252. history.pushState(
  2253. {type: 'raw'},
  2254. document.title,
  2255. // recreate paste URL
  2256. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  2257. Model.getPasteKey()
  2258. );
  2259. // we use text/html instead of text/plain to avoid a bug when
  2260. // reloading the raw text view (it reverts to type text/html)
  2261. var $head = $('head').children().not('noscript, script, link[type="text/css"]');
  2262. var newDoc = document.open('text/html', 'replace');
  2263. newDoc.write('<!DOCTYPE html><html><head>');
  2264. for (var i = 0; i < $head.length; i++) {
  2265. newDoc.write($head[i].outerHTML);
  2266. }
  2267. newDoc.write('</head><body><pre>' + DOMPurify.sanitize(paste, {SAFE_FOR_JQUERY: true}) + '</pre></body></html>');
  2268. newDoc.close();
  2269. }
  2270. /**
  2271. * saves the language in a cookie and reloads the page
  2272. *
  2273. * @name TopNav.setLanguage
  2274. * @private
  2275. * @function
  2276. * @param {Event} event
  2277. */
  2278. function setLanguage(event)
  2279. {
  2280. document.cookie = 'lang=' + $(event.target).data('lang');
  2281. UiHelper.reloadHome();
  2282. }
  2283. /**
  2284. * hides all messages and creates a new paste
  2285. *
  2286. * @name TopNav.clickNewPaste
  2287. * @private
  2288. * @function
  2289. * @param {Event} event
  2290. */
  2291. function clickNewPaste(event)
  2292. {
  2293. Controller.hideStatusMessages();
  2294. Controller.newPaste();
  2295. }
  2296. /**
  2297. * removes the existing attachment
  2298. *
  2299. * @name TopNav.removeAttachment
  2300. * @private
  2301. * @function
  2302. * @param {Event} event
  2303. */
  2304. function removeAttachment(event)
  2305. {
  2306. // if custom attachment is used, remove it first
  2307. if (!$customAttachment.hasClass('hidden')) {
  2308. AttachmentViewer.removeAttachment();
  2309. $customAttachment.addClass('hidden');
  2310. $fileWrap.removeClass('hidden');
  2311. }
  2312. // our up-to-date jQuery can handle it :)
  2313. $fileWrap.find('input').val('');
  2314. // pevent '#' from appearing in the URL
  2315. event.preventDefault();
  2316. }
  2317. /**
  2318. * Shows all elements belonging to viwing an existing pastes
  2319. *
  2320. * @name TopNav.showViewButtons
  2321. * @function
  2322. */
  2323. me.showViewButtons = function()
  2324. {
  2325. if (viewButtonsDisplayed) {
  2326. console.warn('showViewButtons: view buttons are already displayed');
  2327. return;
  2328. }
  2329. $newButton.removeClass('hidden');
  2330. $cloneButton.removeClass('hidden');
  2331. $rawTextButton.removeClass('hidden');
  2332. viewButtonsDisplayed = true;
  2333. }
  2334. /**
  2335. * Hides all elements belonging to existing pastes
  2336. *
  2337. * @name TopNav.hideViewButtons
  2338. * @function
  2339. */
  2340. me.hideViewButtons = function()
  2341. {
  2342. if (!viewButtonsDisplayed) {
  2343. console.warn('hideViewButtons: view buttons are already hidden');
  2344. return;
  2345. }
  2346. $newButton.addClass('hidden');
  2347. $cloneButton.addClass('hidden');
  2348. $rawTextButton.addClass('hidden');
  2349. viewButtonsDisplayed = false;
  2350. }
  2351. /**
  2352. * Hides all elements belonging to existing pastes
  2353. *
  2354. * @name TopNav.hideAllButtons
  2355. * @function
  2356. */
  2357. me.hideAllButtons = function()
  2358. {
  2359. me.hideViewButtons();
  2360. me.hideCreateButtons();
  2361. }
  2362. /**
  2363. * shows all elements needed when creating a new paste
  2364. *
  2365. * @name TopNav.showCreateButtons
  2366. * @function
  2367. */
  2368. me.showCreateButtons = function()
  2369. {
  2370. if (createButtonsDisplayed) {
  2371. console.warn('showCreateButtons: create buttons are already displayed');
  2372. return;
  2373. }
  2374. $sendButton.removeClass('hidden');
  2375. $expiration.removeClass('hidden');
  2376. $formatter.removeClass('hidden');
  2377. $burnAfterReadingOption.removeClass('hidden');
  2378. $openDiscussionOption.removeClass('hidden');
  2379. $newButton.removeClass('hidden');
  2380. $password.removeClass('hidden');
  2381. $attach.removeClass('hidden');
  2382. createButtonsDisplayed = true;
  2383. }
  2384. /**
  2385. * shows all elements needed when creating a new paste
  2386. *
  2387. * @name TopNav.hideCreateButtons
  2388. * @function
  2389. */
  2390. me.hideCreateButtons = function()
  2391. {
  2392. if (!createButtonsDisplayed) {
  2393. console.warn('hideCreateButtons: create buttons are already hidden');
  2394. return;
  2395. }
  2396. $newButton.addClass('hidden');
  2397. $sendButton.addClass('hidden');
  2398. $expiration.addClass('hidden');
  2399. $formatter.addClass('hidden');
  2400. $burnAfterReadingOption.addClass('hidden');
  2401. $openDiscussionOption.addClass('hidden');
  2402. $password.addClass('hidden');
  2403. $attach.addClass('hidden');
  2404. createButtonsDisplayed = false;
  2405. }
  2406. /**
  2407. * only shows the "new paste" button
  2408. *
  2409. * @name TopNav.showNewPasteButton
  2410. * @function
  2411. */
  2412. me.showNewPasteButton = function()
  2413. {
  2414. $newButton.removeClass('hidden');
  2415. }
  2416. /**
  2417. * only hides the clone button
  2418. *
  2419. * @name TopNav.hideCloneButton
  2420. * @function
  2421. */
  2422. me.hideCloneButton = function()
  2423. {
  2424. $cloneButton.addClass('hidden');
  2425. }
  2426. /**
  2427. * only hides the raw text button
  2428. *
  2429. * @name TopNav.hideRawButton
  2430. * @function
  2431. */
  2432. me.hideRawButton = function()
  2433. {
  2434. $rawTextButton.addClass('hidden');
  2435. }
  2436. /**
  2437. * hides the file selector in attachment
  2438. *
  2439. * @name TopNav.hideFileSelector
  2440. * @function
  2441. */
  2442. me.hideFileSelector = function()
  2443. {
  2444. $fileWrap.addClass('hidden');
  2445. }
  2446. /**
  2447. * shows the custom attachment
  2448. *
  2449. * @name TopNav.showCustomAttachment
  2450. * @function
  2451. */
  2452. me.showCustomAttachment = function()
  2453. {
  2454. $customAttachment.removeClass('hidden');
  2455. }
  2456. /**
  2457. * collapses the navigation bar if nedded
  2458. *
  2459. * @name TopNav.collapseBar
  2460. * @function
  2461. */
  2462. me.collapseBar = function()
  2463. {
  2464. var $bar = $('.navbar-toggle');
  2465. // check if bar is expanded
  2466. if ($bar.hasClass('collapse in')) {
  2467. // if so, toggle it
  2468. $bar.click();
  2469. }
  2470. }
  2471. /**
  2472. * returns the currently set expiration time
  2473. *
  2474. * @name TopNav.getExpiration
  2475. * @function
  2476. * @return {int}
  2477. */
  2478. me.getExpiration = function()
  2479. {
  2480. return pasteExpiration;
  2481. }
  2482. /**
  2483. * returns the currently selected file(s)
  2484. *
  2485. * @name TopNav.getFileList
  2486. * @function
  2487. * @return {FileList|null}
  2488. */
  2489. me.getFileList = function()
  2490. {
  2491. var $file = $('#file');
  2492. // if no file given, return null
  2493. if (!$file.length || !$file[0].files.length) {
  2494. return null;
  2495. }
  2496. // @TODO is this really necessary
  2497. if (!($file[0].files && $file[0].files[0])) {
  2498. return null;
  2499. }
  2500. return $file[0].files;
  2501. }
  2502. /**
  2503. * returns the state of the burn after reading checkbox
  2504. *
  2505. * @name TopNav.getExpiration
  2506. * @function
  2507. * @return {bool}
  2508. */
  2509. me.getBurnAfterReading = function()
  2510. {
  2511. return $burnAfterReading.is(':checked');
  2512. }
  2513. /**
  2514. * returns the state of the discussion checkbox
  2515. *
  2516. * @name TopNav.getOpenDiscussion
  2517. * @function
  2518. * @return {bool}
  2519. */
  2520. me.getOpenDiscussion = function()
  2521. {
  2522. return $openDiscussion.is(':checked');
  2523. }
  2524. /**
  2525. * returns the entered password
  2526. *
  2527. * @name TopNav.getPassword
  2528. * @function
  2529. * @return {string}
  2530. */
  2531. me.getPassword = function()
  2532. {
  2533. return $passwordInput.val();
  2534. }
  2535. /**
  2536. * returns the element where custom attachments can be placed
  2537. *
  2538. * Used by AttachmentViewer when an attachment is cloned here.
  2539. *
  2540. * @name TopNav.getCustomAttachment
  2541. * @function
  2542. * @return {jQuery}
  2543. */
  2544. me.getCustomAttachment = function()
  2545. {
  2546. return $customAttachment;
  2547. }
  2548. /**
  2549. * init navigation manager
  2550. *
  2551. * preloads jQuery elements
  2552. *
  2553. * @name TopNav.init
  2554. * @function
  2555. */
  2556. me.init = function()
  2557. {
  2558. $attach = $('#attach');
  2559. $burnAfterReading = $('#burnafterreading');
  2560. $burnAfterReadingOption = $('#burnafterreadingoption');
  2561. $cloneButton = $('#clonebutton');
  2562. $customAttachment = $('#customattachment');
  2563. $expiration = $('#expiration');
  2564. $fileRemoveButton = $('#fileremovebutton');
  2565. $fileWrap = $('#filewrap');
  2566. $formatter = $('#formatter');
  2567. $newButton = $('#newbutton');
  2568. $openDiscussion = $('#opendiscussion');
  2569. $openDiscussionOption = $('#opendiscussionoption');
  2570. $password = $('#password');
  2571. $passwordInput = $('#passwordinput');
  2572. $rawTextButton = $('#rawtextbutton');
  2573. $sendButton = $('#sendbutton');
  2574. // bootstrap template drop down
  2575. $('#language ul.dropdown-menu li a').click(setLanguage);
  2576. // page template drop down
  2577. $('#language select option').click(setLanguage);
  2578. // bind events
  2579. $burnAfterReading.change(changeBurnAfterReading);
  2580. $openDiscussionOption.change(changeOpenDiscussion);
  2581. $newButton.click(clickNewPaste);
  2582. $sendButton.click(PasteEncrypter.sendPaste);
  2583. $cloneButton.click(Controller.clonePaste);
  2584. $rawTextButton.click(rawText);
  2585. $fileRemoveButton.click(removeAttachment);
  2586. // bootstrap template drop downs
  2587. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  2588. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  2589. // initiate default state of checkboxes
  2590. changeBurnAfterReading();
  2591. changeOpenDiscussion();
  2592. // get default value from template or fall back to set value
  2593. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  2594. }
  2595. return me;
  2596. })(window, document);
  2597. /**
  2598. * Responsible for AJAX requests, transparently handles encryption…
  2599. *
  2600. * @name Uploader
  2601. * @class
  2602. */
  2603. var Uploader = (function () {
  2604. var me = {};
  2605. var successFunc = null,
  2606. failureFunc = null,
  2607. url,
  2608. data,
  2609. symmetricKey,
  2610. password;
  2611. /**
  2612. * public variable ('constant') for errors to prevent magic numbers
  2613. *
  2614. * @name Uploader.error
  2615. * @readonly
  2616. * @enum {Object}
  2617. */
  2618. me.error = {
  2619. okay: 0,
  2620. custom: 1,
  2621. unknown: 2,
  2622. serverError: 3
  2623. };
  2624. /**
  2625. * ajaxHeaders to send in AJAX requests
  2626. *
  2627. * @name Uploader.ajaxHeaders
  2628. * @private
  2629. * @readonly
  2630. * @enum {Object}
  2631. */
  2632. var ajaxHeaders = {'X-Requested-With': 'JSONHttpRequest'};
  2633. /**
  2634. * called after successful upload
  2635. *
  2636. * @name Uploader.checkCryptParameters
  2637. * @private
  2638. * @function
  2639. * @throws {string}
  2640. */
  2641. function checkCryptParameters()
  2642. {
  2643. // workaround for this nasty 'bug' in ECMAScript
  2644. // see https://stackoverflow.com/questions/18808226/why-is-typeof-null-object
  2645. var typeOfKey = typeof symmetricKey;
  2646. if (symmetricKey === null) {
  2647. typeOfKey = 'null';
  2648. }
  2649. // in case of missing preparation, throw error
  2650. switch (typeOfKey) {
  2651. case 'string':
  2652. // already set, all right
  2653. return;
  2654. case 'null':
  2655. // needs to be generated auto-generate
  2656. symmetricKey = CryptTool.getSymmetricKey();
  2657. break;
  2658. default:
  2659. console.error('current invalid symmetricKey:', symmetricKey);
  2660. throw 'symmetricKey is invalid, probably the module was not prepared';
  2661. }
  2662. // password is optional
  2663. }
  2664. /**
  2665. * called after successful upload
  2666. *
  2667. * @name Uploader.success
  2668. * @private
  2669. * @function
  2670. * @param {int} status
  2671. * @param {int} result - optional
  2672. */
  2673. function success(status, result)
  2674. {
  2675. // add useful data to result
  2676. result.encryptionKey = symmetricKey;
  2677. result.requestData = data;
  2678. if (successFunc !== null) {
  2679. successFunc(status, result);
  2680. }
  2681. }
  2682. /**
  2683. * called after a upload failure
  2684. *
  2685. * @name Uploader.fail
  2686. * @private
  2687. * @function
  2688. * @param {int} status - internal code
  2689. * @param {int} result - original error code
  2690. */
  2691. function fail(status, result)
  2692. {
  2693. if (failureFunc !== null) {
  2694. failureFunc(status, result);
  2695. }
  2696. }
  2697. /**
  2698. * actually uploads the data
  2699. *
  2700. * @name Uploader.run
  2701. * @function
  2702. */
  2703. me.run = function()
  2704. {
  2705. $.ajax({
  2706. type: 'POST',
  2707. url: url,
  2708. data: data,
  2709. dataType: 'json',
  2710. headers: ajaxHeaders,
  2711. success: function(result) {
  2712. if (result.status === 0) {
  2713. success(0, result);
  2714. } else if (result.status === 1) {
  2715. fail(1, result);
  2716. } else {
  2717. fail(2, result);
  2718. }
  2719. }
  2720. })
  2721. .fail(function(jqXHR, textStatus, errorThrown) {
  2722. console.error(textStatus, errorThrown);
  2723. fail(3, jqXHR);
  2724. });
  2725. }
  2726. /**
  2727. * set success function
  2728. *
  2729. * @name Uploader.setUrl
  2730. * @function
  2731. * @param {function} newUrl
  2732. */
  2733. me.setUrl = function(newUrl)
  2734. {
  2735. url = newUrl;
  2736. }
  2737. /**
  2738. * sets the password to use (first value) and optionally also the
  2739. * encryption key (not recommend, it is automatically generated).
  2740. *
  2741. * Note: Call this after prepare() as prepare() resets these values.
  2742. *
  2743. * @name Uploader.setCryptValues
  2744. * @function
  2745. * @param {string} newPassword
  2746. * @param {string} newKey - optional
  2747. */
  2748. me.setCryptParameters = function(newPassword, newKey)
  2749. {
  2750. password = newPassword;
  2751. if (typeof newKey !== 'undefined') {
  2752. symmetricKey = newKey;
  2753. }
  2754. }
  2755. /**
  2756. * set success function
  2757. *
  2758. * @name Uploader.setSuccess
  2759. * @function
  2760. * @param {function} func
  2761. */
  2762. me.setSuccess = function(func)
  2763. {
  2764. successFunc = func;
  2765. }
  2766. /**
  2767. * set failure function
  2768. *
  2769. * @name Uploader.setFailure
  2770. * @function
  2771. * @param {function} func
  2772. */
  2773. me.setFailure = function(func)
  2774. {
  2775. failureFunc = func;
  2776. }
  2777. /**
  2778. * prepares a new upload
  2779. *
  2780. * Call this when doing a new upload to reset any data from potential
  2781. * previous uploads. Must be called before any other method of this
  2782. * module.
  2783. *
  2784. * @name Uploader.prepare
  2785. * @function
  2786. * @return {object}
  2787. */
  2788. me.prepare = function()
  2789. {
  2790. // entropy should already be checked!
  2791. // reset password
  2792. password = '';
  2793. // reset key, so it a new one is generated when it is used
  2794. symmetricKey = null;
  2795. // reset data
  2796. successFunc = null;
  2797. failureFunc = null;
  2798. url = Helper.baseUri();
  2799. data = {};
  2800. }
  2801. /**
  2802. * encrypts and sets the data
  2803. *
  2804. * @name Uploader.setData
  2805. * @function
  2806. * @param {string} index
  2807. * @param {mixed} element
  2808. */
  2809. me.setData = function(index, element)
  2810. {
  2811. checkCryptParameters();
  2812. data[index] = CryptTool.cipher(symmetricKey, password, element);
  2813. }
  2814. /**
  2815. * set the additional metadata to send unencrypted
  2816. *
  2817. * @name Uploader.setUnencryptedData
  2818. * @function
  2819. * @param {string} index
  2820. * @param {mixed} element
  2821. */
  2822. me.setUnencryptedData = function(index, element)
  2823. {
  2824. data[index] = element;
  2825. }
  2826. /**
  2827. * set the additional metadata to send unencrypted passed at once
  2828. *
  2829. * @name Uploader.setUnencryptedData
  2830. * @function
  2831. * @param {object} newData
  2832. */
  2833. me.setUnencryptedBulkData = function(newData)
  2834. {
  2835. $.extend(data, newData);
  2836. }
  2837. /**
  2838. * Helper, which parses shows a general error message based on the result of the Uploader
  2839. *
  2840. * @name Uploader.parseUploadError
  2841. * @function
  2842. * @param {int} status
  2843. * @param {object} data
  2844. * @param {string} doThisThing - a human description of the action, which was tried
  2845. * @return {array}
  2846. */
  2847. me.parseUploadError = function(status, data, doThisThing) {
  2848. var errorArray;
  2849. switch (status) {
  2850. case me.error['custom']:
  2851. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  2852. break;
  2853. case me.error['unknown']:
  2854. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  2855. break;
  2856. case me.error['serverError']:
  2857. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  2858. break;
  2859. default:
  2860. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  2861. break;
  2862. }
  2863. return errorArray;
  2864. }
  2865. /**
  2866. * init Uploader
  2867. *
  2868. * @name Uploader.init
  2869. * @function
  2870. */
  2871. me.init = function()
  2872. {
  2873. // nothing yet
  2874. }
  2875. return me;
  2876. })();
  2877. /**
  2878. * (controller) Responsible for encrypting paste and sending it to server.
  2879. *
  2880. * Does upload, encryption is done transparently by Uploader.
  2881. *
  2882. * @name PasteEncrypter
  2883. * @class
  2884. */
  2885. var PasteEncrypter = (function () {
  2886. var me = {};
  2887. var requirementsChecked = false;
  2888. /**
  2889. * checks whether there is a suitable amount of entrophy
  2890. *
  2891. * @name PasteEncrypter.checkRequirements
  2892. * @private
  2893. * @function
  2894. * @param {function} retryCallback - the callback to execute to retry the upload
  2895. * @return {bool}
  2896. */
  2897. function checkRequirements(retryCallback) {
  2898. // skip double requirement checks
  2899. if (requirementsChecked === true) {
  2900. return true;
  2901. }
  2902. if (!CryptTool.isEntropyReady()) {
  2903. // display a message and wait
  2904. Alert.showStatus('Please move your mouse for more entropy…');
  2905. CryptTool.addEntropySeedListener(retryCallback);
  2906. return false;
  2907. }
  2908. requirementsChecked = true;
  2909. return true;
  2910. }
  2911. /**
  2912. * called after successful paste upload
  2913. *
  2914. * @name PasteEncrypter.showCreatedPaste
  2915. * @private
  2916. * @function
  2917. * @param {int} status
  2918. * @param {object} data
  2919. */
  2920. function showCreatedPaste(status, data) {
  2921. Alert.hideLoading();
  2922. var url = Helper.baseUri() + '?' + data.id + '#' + data.encryptionKey,
  2923. deleteUrl = Helper.baseUri() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  2924. Alert.hideMessages();
  2925. // show notification
  2926. PasteStatus.createPasteNotification(url, deleteUrl)
  2927. // show new URL in browser bar
  2928. history.pushState({type: 'newpaste'}, document.title, url);
  2929. TopNav.showViewButtons();
  2930. TopNav.hideRawButton();
  2931. Editor.hide();
  2932. // parse and show text
  2933. // (preparation already done in me.sendPaste())
  2934. PasteViewer.run();
  2935. }
  2936. /**
  2937. * called after successful comment upload
  2938. *
  2939. * @name PasteEncrypter.showUploadedComment
  2940. * @private
  2941. * @function
  2942. * @param {int} status
  2943. * @param {object} data
  2944. */
  2945. function showUploadedComment(status, data) {
  2946. // show success message
  2947. // Alert.showStatus('Comment posted.');
  2948. // reload paste
  2949. Controller.refreshPaste(function () {
  2950. // highlight sent comment
  2951. DiscussionViewer.highlightComment(data.id, true);
  2952. // reset error handler
  2953. Alert.setCustomHandler(null);
  2954. });
  2955. }
  2956. /**
  2957. * adds attachments to the Uploader
  2958. *
  2959. * @name PasteEncrypter.encryptAttachments
  2960. * @private
  2961. * @function
  2962. * @param {File|null|undefined} file - optional, falls back to cloned attachment
  2963. * @param {function} callback - excuted when action is successful
  2964. */
  2965. function encryptAttachments(file, callback) {
  2966. if (typeof file !== 'undefined' && file !== null) {
  2967. // check file reader requirements for upload
  2968. if (typeof FileReader === 'undefined') {
  2969. Alert.showError('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2970. // cancels process as it does not execute callback
  2971. return;
  2972. }
  2973. var reader = new FileReader();
  2974. // closure to capture the file information
  2975. reader.onload = function(event) {
  2976. Uploader.setData('attachment', event.target.result);
  2977. Uploader.setData('attachmentname', file.name);
  2978. // run callback
  2979. return callback();
  2980. }
  2981. // actually read first file
  2982. reader.readAsDataURL(file);
  2983. } else if (AttachmentViewer.hasAttachment()) {
  2984. // fall back to cloned part
  2985. var attachment = AttachmentViewer.getAttachment();
  2986. Uploader.setData('attachment', attachment[0]);
  2987. Uploader.setData('attachmentname', attachment[1]);
  2988. return callback();
  2989. } else {
  2990. // if there are no attachments, this is of course still successful
  2991. return callback();
  2992. }
  2993. }
  2994. /**
  2995. * send a reply in a discussion
  2996. *
  2997. * @name PasteEncrypter.sendComment
  2998. * @function
  2999. */
  3000. me.sendComment = function()
  3001. {
  3002. Alert.hideMessages();
  3003. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  3004. // UI loading state
  3005. TopNav.hideAllButtons();
  3006. Alert.showLoading('Sending comment…', 0, 'cloud-upload');
  3007. // get data
  3008. var plainText = DiscussionViewer.getReplyMessage(),
  3009. nickname = DiscussionViewer.getReplyNickname(),
  3010. parentid = DiscussionViewer.getReplyCommentId();
  3011. // do not send if there is no data
  3012. if (plainText.length === 0) {
  3013. // revert loading status…
  3014. Alert.hideLoading();
  3015. Alert.setCustomHandler(null);
  3016. TopNav.showViewButtons();
  3017. return;
  3018. }
  3019. // check entropy
  3020. if (!checkRequirements(function () {
  3021. me.sendComment();
  3022. })) {
  3023. return; // to prevent multiple executions
  3024. }
  3025. Alert.showLoading(null, 10);
  3026. // prepare Uploader
  3027. Uploader.prepare();
  3028. Uploader.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  3029. // set success/fail functions
  3030. Uploader.setSuccess(showUploadedComment);
  3031. Uploader.setFailure(function (status, data) {
  3032. // revert loading status…
  3033. Alert.hideLoading();
  3034. TopNav.showViewButtons();
  3035. // show error message
  3036. Alert.showError(Uploader.parseUploadError(status, data, 'post comment'));
  3037. // reset error handler
  3038. Alert.setCustomHandler(null);
  3039. });
  3040. // fill it with unencrypted params
  3041. Uploader.setUnencryptedData('pasteid', Model.getPasteId());
  3042. if (typeof parentid === 'undefined') {
  3043. // if parent id is not set, this is the top-most comment, so use
  3044. // paste id as parent @TODO is this really good?
  3045. Uploader.setUnencryptedData('parentid', Model.getPasteId());
  3046. } else {
  3047. Uploader.setUnencryptedData('parentid', parentid);
  3048. }
  3049. // encrypt data
  3050. Uploader.setData('data', plainText);
  3051. if (nickname.length > 0) {
  3052. Uploader.setData('nickname', nickname);
  3053. }
  3054. Uploader.run();
  3055. }
  3056. /**
  3057. * sends a new paste to server
  3058. *
  3059. * @name PasteEncrypter.sendPaste
  3060. * @function
  3061. */
  3062. me.sendPaste = function()
  3063. {
  3064. // hide previous (error) messages
  3065. Controller.hideStatusMessages();
  3066. // UI loading state
  3067. TopNav.hideAllButtons();
  3068. Alert.showLoading('Sending paste…', 0, 'cloud-upload');
  3069. TopNav.collapseBar();
  3070. // get data
  3071. var plainText = Editor.getText(),
  3072. format = PasteViewer.getFormat(),
  3073. files = TopNav.getFileList();
  3074. // do not send if there is no data
  3075. if (plainText.length === 0 && files === null) {
  3076. // revert loading status…
  3077. Alert.hideLoading();
  3078. TopNav.showCreateButtons();
  3079. return;
  3080. }
  3081. Alert.showLoading(null, 10);
  3082. // check entropy
  3083. if (!checkRequirements(function () {
  3084. me.sendPaste();
  3085. })) {
  3086. return; // to prevent multiple executions
  3087. }
  3088. // prepare Uploader
  3089. Uploader.prepare();
  3090. Uploader.setCryptParameters(TopNav.getPassword());
  3091. // set success/fail functions
  3092. Uploader.setSuccess(showCreatedPaste);
  3093. Uploader.setFailure(function (status, data) {
  3094. // revert loading status…
  3095. Alert.hideLoading();
  3096. TopNav.showCreateButtons();
  3097. // show error message
  3098. Alert.showError(Uploader.parseUploadError(status, data, 'create paste'));
  3099. });
  3100. // fill it with unencrypted submitted options
  3101. Uploader.setUnencryptedBulkData({
  3102. expire: TopNav.getExpiration(),
  3103. formatter: format,
  3104. burnafterreading: TopNav.getBurnAfterReading() ? 1 : 0,
  3105. opendiscussion: TopNav.getOpenDiscussion() ? 1 : 0
  3106. });
  3107. // prepare PasteViewer for later preview
  3108. PasteViewer.setText(plainText);
  3109. PasteViewer.setFormat(format);
  3110. // encrypt cipher data
  3111. Uploader.setData('data', plainText);
  3112. // encrypt attachments
  3113. encryptAttachments(
  3114. files === null ? null : files[0],
  3115. function () {
  3116. // send data
  3117. Uploader.run();
  3118. }
  3119. );
  3120. }
  3121. /**
  3122. * initialize
  3123. *
  3124. * @name PasteEncrypter.init
  3125. * @function
  3126. */
  3127. me.init = function()
  3128. {
  3129. // nothing yet
  3130. }
  3131. return me;
  3132. })();
  3133. /**
  3134. * (controller) Responsible for decrypting cipherdata and passing data to view.
  3135. *
  3136. * Only decryption, no download.
  3137. *
  3138. * @name PasteDecrypter
  3139. * @class
  3140. */
  3141. var PasteDecrypter = (function () {
  3142. var me = {};
  3143. /**
  3144. * decrypt data or prompts for password in cvase of failure
  3145. *
  3146. * @name PasteDecrypter.decryptOrPromptPassword
  3147. * @private
  3148. * @function
  3149. * @param {string} key
  3150. * @param {string} password - optional, may be an empty string
  3151. * @param {string} cipherdata
  3152. * @throws {string}
  3153. * @return {false|string} false, when unsuccessful or string (decrypted data)
  3154. */
  3155. function decryptOrPromptPassword(key, password, cipherdata)
  3156. {
  3157. // try decryption without password
  3158. var plaindata = CryptTool.decipher(key, password, cipherdata);
  3159. // if it fails, request password
  3160. if (plaindata.length === 0 && password.length === 0) {
  3161. // try to get cached password first
  3162. password = Prompt.getPassword();
  3163. // if password is there, re-try
  3164. if (password.length === 0) {
  3165. password = Prompt.requestPassword();
  3166. }
  3167. // recursive
  3168. // note: an infinite loop is prevented as the previous if
  3169. // clause checks whether a password is already set and ignores
  3170. // errors when a password has been passed
  3171. return decryptOrPromptPassword.apply(key, password, cipherdata);
  3172. }
  3173. // if all tries failed, we can only return an error
  3174. if (plaindata.length === 0) {
  3175. throw 'failed to decipher data';
  3176. }
  3177. return plaindata;
  3178. }
  3179. /**
  3180. * decrypt the actual paste text
  3181. *
  3182. * @name PasteDecrypter.decryptOrPromptPassword
  3183. * @private
  3184. * @function
  3185. * @param {object} paste - paste data in object form
  3186. * @param {string} key
  3187. * @param {string} password
  3188. * @param {bool} ignoreError - ignore decryption errors iof set to true
  3189. * @return {bool} whether action was successful
  3190. * @throws {string}
  3191. */
  3192. function decryptPaste(paste, key, password, ignoreError)
  3193. {
  3194. var plaintext
  3195. if (ignoreError === true) {
  3196. plaintext = CryptTool.decipher(key, password, paste.data);
  3197. } else {
  3198. try {
  3199. plaintext = decryptOrPromptPassword(key, password, paste.data);
  3200. } catch (err) {
  3201. throw 'failed to decipher paste text: ' + err
  3202. }
  3203. if (plaintext === false) {
  3204. return false;
  3205. }
  3206. }
  3207. // on success show paste
  3208. PasteViewer.setFormat(paste.meta.formatter);
  3209. PasteViewer.setText(plaintext);
  3210. // trigger to show the text (attachment loaded afterwards)
  3211. PasteViewer.run();
  3212. return true;
  3213. }
  3214. /**
  3215. * decrypts any attachment
  3216. *
  3217. * @name PasteDecrypter.decryptAttachment
  3218. * @private
  3219. * @function
  3220. * @param {object} paste - paste data in object form
  3221. * @param {string} key
  3222. * @param {string} password
  3223. * @return {bool} whether action was successful
  3224. * @throws {string}
  3225. */
  3226. function decryptAttachment(paste, key, password)
  3227. {
  3228. // decrypt attachment
  3229. try {
  3230. var attachment = decryptOrPromptPassword(key, password, paste.attachment);
  3231. } catch (err) {
  3232. throw 'failed to decipher attachment: ' + err
  3233. }
  3234. if (attachment === false) {
  3235. return false;
  3236. }
  3237. // decrypt attachment name
  3238. var attachmentName;
  3239. if (paste.attachmentname) {
  3240. try {
  3241. attachmentName = decryptOrPromptPassword(key, password, paste.attachmentname);
  3242. } catch (err) {
  3243. throw 'failed to decipher attachment name: ' + err
  3244. }
  3245. if (attachmentName === false) {
  3246. return false;
  3247. }
  3248. }
  3249. AttachmentViewer.setAttachment(attachment, attachmentName);
  3250. AttachmentViewer.showAttachment();
  3251. return true;
  3252. }
  3253. /**
  3254. * decrypts all comments and shows them
  3255. *
  3256. * @name PasteDecrypter.decryptComments
  3257. * @private
  3258. * @function
  3259. * @param {object} paste - paste data in object form
  3260. * @param {string} key
  3261. * @param {string} password
  3262. * @return {bool} whether action was successful
  3263. */
  3264. function decryptComments(paste, key, password)
  3265. {
  3266. // remove potentially previous discussion
  3267. DiscussionViewer.prepareNewDiscussion();
  3268. // iterate over comments
  3269. for (var i = 0; i < paste.comments.length; ++i) {
  3270. var comment = paste.comments[i];
  3271. DiscussionViewer.addComment(
  3272. comment,
  3273. CryptTool.decipher(key, password, comment.data),
  3274. CryptTool.decipher(key, password, comment.meta.nickname)
  3275. );
  3276. }
  3277. DiscussionViewer.finishDiscussion();
  3278. DiscussionViewer.showDiscussion();
  3279. return true;
  3280. }
  3281. /**
  3282. * show decrypted text in the display area, including discussion (if open)
  3283. *
  3284. * @name PasteDecrypter.run
  3285. * @function
  3286. * @param {Object} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  3287. */
  3288. me.run = function(paste)
  3289. {
  3290. Alert.hideMessages();
  3291. Alert.showLoading('Decrypting paste…', 0, 'cloud-download'); // @TODO icon maybe rotation-lock, but needs full Glyphicons
  3292. if (typeof paste === 'undefined') {
  3293. paste = $.parseJSON(Model.getCipherData());
  3294. }
  3295. var key = Model.getPasteKey(),
  3296. password = Prompt.getPassword();
  3297. if (PasteViewer.isPrettyPrinted()) {
  3298. console.error('Too pretty! (don\'t know why this check)'); //@TODO
  3299. return;
  3300. }
  3301. // try to decrypt the paste
  3302. try {
  3303. // decrypt attachments
  3304. if (paste.attachment) {
  3305. // try to decrypt paste and if it fails (because the password is
  3306. // missing) return to let JS continue and wait for user
  3307. if (!decryptAttachment(paste, key, password)) {
  3308. return;
  3309. }
  3310. // ignore empty paste, as this is allowed when pasting attachments
  3311. decryptPaste(paste, key, password, true);
  3312. } else {
  3313. decryptPaste(paste, key, password);
  3314. }
  3315. // shows the remaining time (until) deletion
  3316. PasteStatus.showRemainingTime(paste.meta);
  3317. // if the discussion is opened on this paste, display it
  3318. if (paste.meta.opendiscussion) {
  3319. decryptComments(paste, key, password);
  3320. }
  3321. Alert.hideLoading();
  3322. TopNav.showViewButtons();
  3323. } catch(err) {
  3324. Alert.hideLoading();
  3325. // log and show error
  3326. console.error(err);
  3327. Alert.showError('Could not decrypt data (Wrong key?)');
  3328. }
  3329. }
  3330. /**
  3331. * initialize
  3332. *
  3333. * @name PasteDecrypter.init
  3334. * @function
  3335. */
  3336. me.init = function()
  3337. {
  3338. // nothing yet
  3339. }
  3340. return me;
  3341. })();
  3342. /**
  3343. * (controller) main PrivateBin logic
  3344. *
  3345. * @name Controller
  3346. * @param {object} window
  3347. * @param {object} document
  3348. * @class
  3349. */
  3350. var Controller = (function (window, document) {
  3351. var me = {};
  3352. /**
  3353. * hides all status messages no matter which module showed them
  3354. *
  3355. * @name Controller.hideStatusMessages
  3356. * @function
  3357. */
  3358. me.hideStatusMessages = function()
  3359. {
  3360. PasteStatus.hideMessages();
  3361. Alert.hideMessages();
  3362. }
  3363. /**
  3364. * creates a new paste
  3365. *
  3366. * @name Controller.newPaste
  3367. * @function
  3368. */
  3369. me.newPaste = function()
  3370. {
  3371. // Important: This *must not* run Alert.hideMessages() as previous
  3372. // errors from viewing a paste should be shown.
  3373. TopNav.hideAllButtons();
  3374. Alert.showLoading('Preparing new paste…', 0, 'time');
  3375. PasteStatus.hideMessages();
  3376. PasteViewer.hide();
  3377. Editor.resetInput();
  3378. Editor.show();
  3379. Editor.focusInput();
  3380. TopNav.showCreateButtons();
  3381. Alert.hideLoading();
  3382. }
  3383. /**
  3384. * shows the loaded paste
  3385. *
  3386. * @name Controller.showPaste
  3387. * @function
  3388. */
  3389. me.showPaste = function()
  3390. {
  3391. try {
  3392. Model.getPasteId();
  3393. Model.getPasteKey();
  3394. } catch (err) {
  3395. console.error(err);
  3396. // missing decryption key (or paste ID) in URL?
  3397. if (window.location.hash.length === 0) {
  3398. 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?)');
  3399. // @TODO adjust error message as it is less specific now, probably include thrown exception for a detailed error
  3400. return;
  3401. }
  3402. }
  3403. // show proper elements on screen
  3404. PasteDecrypter.run();
  3405. }
  3406. /**
  3407. * refreshes the loaded paste to show potential new data
  3408. *
  3409. * @name Controller.refreshPaste
  3410. * @function
  3411. * @param {function} callback
  3412. */
  3413. me.refreshPaste = function(callback)
  3414. {
  3415. // save window position to restore it later
  3416. var orgPosition = $(window).scrollTop();
  3417. Uploader.prepare();
  3418. Uploader.setUrl(Helper.baseUri() + '?' + Model.getPasteId());
  3419. Uploader.setFailure(function (status, data) {
  3420. // revert loading status…
  3421. Alert.hideLoading();
  3422. TopNav.showViewButtons();
  3423. // show error message
  3424. Alert.showError(Uploader.parseUploadError(status, data, 'refresh display'));
  3425. })
  3426. Uploader.setSuccess(function (status, data) {
  3427. PasteDecrypter.run(data);
  3428. // restore position
  3429. window.scrollTo(0, orgPosition);
  3430. callback();
  3431. })
  3432. Uploader.run();
  3433. }
  3434. /**
  3435. * clone the current paste
  3436. *
  3437. * @name Controller.clonePaste
  3438. * @function
  3439. * @param {Event} event
  3440. */
  3441. me.clonePaste = function(event)
  3442. {
  3443. TopNav.collapseBar();
  3444. TopNav.hideAllButtons();
  3445. Alert.showLoading('Cloning paste…', 0, 'transfer');
  3446. // hide messages from previous paste
  3447. me.hideStatusMessages();
  3448. // erase the id and the key in url
  3449. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  3450. if (AttachmentViewer.hasAttachment()) {
  3451. AttachmentViewer.moveAttachmentTo(
  3452. TopNav.getCustomAttachment(),
  3453. 'Cloned: \'%s\''
  3454. );
  3455. TopNav.hideFileSelector();
  3456. AttachmentViewer.hideAttachment();
  3457. // NOTE: it also looks nice without removing the attachment
  3458. // but for a consistent display we remove it…
  3459. AttachmentViewer.hideAttachmentPreview();
  3460. TopNav.showCustomAttachment();
  3461. // show another status message to make the user aware that the
  3462. // file was cloned too!
  3463. Alert.showStatus(
  3464. [
  3465. 'The cloned file \'%s\' was attached to this paste.',
  3466. AttachmentViewer.getAttachment()[1]
  3467. ], 'copy', true, true);
  3468. }
  3469. Editor.setText(PasteViewer.getText())
  3470. PasteViewer.hide();
  3471. Editor.show();
  3472. Alert.hideLoading();
  3473. TopNav.showCreateButtons();
  3474. }
  3475. /**
  3476. * removes a saved paste
  3477. *
  3478. * @name Controller.removePaste
  3479. * @function
  3480. * @param {string} pasteId
  3481. * @param {string} deleteToken
  3482. */
  3483. me.removePaste = function(pasteId, deleteToken) {
  3484. // unfortunately many web servers don't support DELETE (and PUT) out of the box
  3485. // so we use a POST request
  3486. Uploader.prepare();
  3487. Uploader.setUrl(Helper.baseUri() + '?' + pasteId);
  3488. Uploader.setUnencryptedData('deletetoken', deleteToken);
  3489. Uploader.setFailure(function () {
  3490. Alert.showError(I18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  3491. })
  3492. Uploader.run();
  3493. }
  3494. /**
  3495. * application start
  3496. *
  3497. * @name Controller.init
  3498. * @function
  3499. */
  3500. me.init = function()
  3501. {
  3502. // first load translations
  3503. I18n.loadTranslations();
  3504. // initialize other modules/"classes"
  3505. Alert.init();
  3506. Model.init();
  3507. AttachmentViewer.init();
  3508. DiscussionViewer.init();
  3509. Editor.init();
  3510. PasteDecrypter.init();
  3511. PasteEncrypter.init();
  3512. PasteStatus.init();
  3513. PasteViewer.init();
  3514. Prompt.init();
  3515. TopNav.init();
  3516. UiHelper.init();
  3517. Uploader.init();
  3518. // display an existing paste
  3519. if (Model.hasCipherData()) {
  3520. return me.showPaste();
  3521. }
  3522. // otherwise create a new paste
  3523. me.newPaste();
  3524. }
  3525. return me;
  3526. })(window, document);
  3527. return {
  3528. Helper: Helper,
  3529. I18n: I18n,
  3530. CryptTool: CryptTool,
  3531. Model: Model,
  3532. UiHelper: UiHelper,
  3533. Alert: Alert,
  3534. PasteStatus: PasteStatus,
  3535. Prompt: Prompt,
  3536. Editor: Editor,
  3537. PasteViewer: PasteViewer,
  3538. AttachmentViewer: AttachmentViewer,
  3539. DiscussionViewer: DiscussionViewer,
  3540. TopNav: TopNav,
  3541. Uploader: Uploader,
  3542. PasteEncrypter: PasteEncrypter,
  3543. PasteDecrypter: PasteDecrypter,
  3544. Controller: Controller
  3545. };
  3546. }(jQuery, sjcl, Base64, RawDeflate);