privatebin.js 120 KB

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