fileinput.js 163 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523
  1. /*!
  2. * bootstrap-fileinput v4.3.9
  3. * http://plugins.krajee.com/file-input
  4. *
  5. * Author: Kartik Visweswaran
  6. * Copyright: 2014 - 2017, Kartik Visweswaran, Krajee.com
  7. *
  8. * Licensed under the BSD 3-Clause
  9. * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md
  10. */
  11. (function (factory) {
  12. "use strict";
  13. //noinspection JSUnresolvedVariable
  14. if (typeof define === 'function' && define.amd) { // jshint ignore:line
  15. // AMD. Register as an anonymous module.
  16. define(['jquery'], factory); // jshint ignore:line
  17. } else { // noinspection JSUnresolvedVariable
  18. if (typeof module === 'object' && module.exports) { // jshint ignore:line
  19. // Node/CommonJS
  20. // noinspection JSUnresolvedVariable
  21. module.exports = factory(require('jquery')); // jshint ignore:line
  22. } else {
  23. // Browser globals
  24. factory(window.jQuery);
  25. }
  26. }
  27. }(function ($) {
  28. "use strict";
  29. $.fn.fileinputLocales = {};
  30. $.fn.fileinputThemes = {};
  31. var $h, FileInput;
  32. // fileinput helper object for all global variables and internal helper methods
  33. //noinspection JSUnresolvedVariable
  34. $h = {
  35. NAMESPACE: '.fileinput',
  36. FRAMES: '.kv-preview-thumb',
  37. SORT_CSS: 'file-sortable',
  38. STYLE_SETTING: 'style="width:{width};height:{height};"',
  39. OBJECT_PARAMS: '<param name="controller" value="true" />\n' +
  40. '<param name="allowFullScreen" value="true" />\n' +
  41. '<param name="allowScriptAccess" value="always" />\n' +
  42. '<param name="autoPlay" value="false" />\n' +
  43. '<param name="autoStart" value="false" />\n' +
  44. '<param name="quality" value="high" />\n',
  45. DEFAULT_PREVIEW: '<div class="file-preview-other">\n' +
  46. '<span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
  47. '</div>',
  48. MODAL_ID: 'kvFileinputModal',
  49. MODAL_EVENTS: ['show', 'shown', 'hide', 'hidden', 'loaded'],
  50. objUrl: window.URL || window.webkitURL,
  51. compare: function (input, str, exact) {
  52. return input !== undefined && (exact ? input === str : input.match(str));
  53. },
  54. isIE: function (ver) {
  55. // check for IE versions < 11
  56. if (navigator.appName !== 'Microsoft Internet Explorer') {
  57. return false;
  58. }
  59. if (ver === 10) {
  60. return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  61. }
  62. var div = document.createElement("div"), status;
  63. div.innerHTML = "<!--[if IE " + ver + "]> <i></i> <![endif]-->";
  64. status = div.getElementsByTagName("i").length;
  65. document.body.appendChild(div);
  66. div.parentNode.removeChild(div);
  67. return status;
  68. },
  69. handler: function ($el, event, callback, skipReset, skipNS) {
  70. if (!$el || !$el.length) {
  71. return;
  72. }
  73. var ev = skipNS ? event : event.split(' ').join($h.NAMESPACE + ' ') + $h.NAMESPACE;
  74. if (!skipReset) {
  75. $el.off(ev);
  76. }
  77. $el.on(ev, callback);
  78. },
  79. initModal: function ($modal) {
  80. var $body = $('body');
  81. if ($body.length) {
  82. $modal.appendTo($body);
  83. }
  84. },
  85. isEmpty: function (value, trim) {
  86. return value === undefined || value === null || value.length === 0 || (trim && $.trim(value) === '');
  87. },
  88. isArray: function (a) {
  89. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  90. },
  91. ifSet: function (needle, haystack, def) {
  92. def = def || '';
  93. return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def;
  94. },
  95. getNum: function (num, def) {
  96. def = def || 0;
  97. if (typeof num === "number") {
  98. return num;
  99. }
  100. if (typeof num === "string") {
  101. num = parseFloat(num);
  102. }
  103. return isNaN(num) ? def : num;
  104. },
  105. hasFileAPISupport: function () {
  106. return !!(window.File && window.FileReader);
  107. },
  108. hasDragDropSupport: function () {
  109. var div = document.createElement('div');
  110. /** @namespace div.draggable */
  111. /** @namespace div.ondragstart */
  112. /** @namespace div.ondrop */
  113. return !$h.isIE(9) && (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined));
  114. },
  115. hasFileUploadSupport: function () {
  116. return $h.hasFileAPISupport() && window.FormData;
  117. },
  118. addCss: function ($el, css) {
  119. $el.removeClass(css).addClass(css);
  120. },
  121. getElement: function (options, param, value) {
  122. return ($h.isEmpty(options) || $h.isEmpty(options[param])) ? value : $(options[param]);
  123. },
  124. uniqId: function () {
  125. return Math.round(new Date().getTime() + (Math.random() * 100));
  126. },
  127. htmlEncode: function (str) {
  128. return str.replace(/&/g, '&amp;')
  129. .replace(/</g, '&lt;')
  130. .replace(/>/g, '&gt;')
  131. .replace(/"/g, '&quot;')
  132. .replace(/'/g, '&apos;');
  133. },
  134. replaceTags: function (str, tags) {
  135. var out = str;
  136. if (!tags) {
  137. return out;
  138. }
  139. $.each(tags, function (key, value) {
  140. if (typeof value === "function") {
  141. value = value();
  142. }
  143. out = out.split(key).join(value);
  144. });
  145. return out;
  146. },
  147. cleanMemory: function ($thumb) {
  148. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  149. /** @namespace $h.objUrl.revokeObjectURL */
  150. $h.objUrl.revokeObjectURL(data);
  151. },
  152. findFileName: function (filePath) {
  153. var sepIndex = filePath.lastIndexOf('/');
  154. if (sepIndex === -1) {
  155. sepIndex = filePath.lastIndexOf('\\');
  156. }
  157. return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop();
  158. },
  159. checkFullScreen: function () {
  160. //noinspection JSUnresolvedVariable
  161. return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ||
  162. document.msFullscreenElement;
  163. },
  164. toggleFullScreen: function (maximize) {
  165. var doc = document, de = doc.documentElement;
  166. if (de && maximize && !$h.checkFullScreen()) {
  167. /** @namespace document.requestFullscreen */
  168. /** @namespace document.msRequestFullscreen */
  169. /** @namespace document.mozRequestFullScreen */
  170. /** @namespace document.webkitRequestFullscreen */
  171. /** @namespace Element.ALLOW_KEYBOARD_INPUT */
  172. if (de.requestFullscreen) {
  173. de.requestFullscreen();
  174. } else if (de.msRequestFullscreen) {
  175. de.msRequestFullscreen();
  176. } else if (de.mozRequestFullScreen) {
  177. de.mozRequestFullScreen();
  178. } else if (de.webkitRequestFullscreen) {
  179. de.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
  180. }
  181. } else {
  182. /** @namespace document.exitFullscreen */
  183. /** @namespace document.msExitFullscreen */
  184. /** @namespace document.mozCancelFullScreen */
  185. /** @namespace document.webkitExitFullscreen */
  186. if (doc.exitFullscreen) {
  187. doc.exitFullscreen();
  188. } else if (doc.msExitFullscreen) {
  189. doc.msExitFullscreen();
  190. } else if (doc.mozCancelFullScreen) {
  191. doc.mozCancelFullScreen();
  192. } else if (doc.webkitExitFullscreen) {
  193. doc.webkitExitFullscreen();
  194. }
  195. }
  196. },
  197. moveArray: function (arr, oldIndex, newIndex) {
  198. if (newIndex >= arr.length) {
  199. var k = newIndex - arr.length;
  200. while ((k--) + 1) {
  201. arr.push(undefined);
  202. }
  203. }
  204. arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
  205. return arr;
  206. },
  207. cleanZoomCache: function ($el) {
  208. var $cache = $el.closest('.kv-zoom-cache-theme');
  209. if (!$cache.length) {
  210. $cache = $el.closest('.kv-zoom-cache');
  211. }
  212. $cache.remove();
  213. }
  214. };
  215. FileInput = function (element, options) {
  216. var self = this;
  217. self.$element = $(element);
  218. if (!self._validate()) {
  219. return;
  220. }
  221. self.isPreviewable = $h.hasFileAPISupport();
  222. self.isIE9 = $h.isIE(9);
  223. self.isIE10 = $h.isIE(10);
  224. if (self.isPreviewable || self.isIE9) {
  225. self._init(options);
  226. self._listen();
  227. } else {
  228. self.$element.removeClass('file-loading');
  229. }
  230. };
  231. FileInput.prototype = {
  232. constructor: FileInput,
  233. _init: function (options) {
  234. var self = this, $el = self.$element, t;
  235. self.options = options;
  236. $.each(options, function (key, value) {
  237. switch (key) {
  238. case 'minFileCount':
  239. case 'maxFileCount':
  240. case 'maxFileSize':
  241. self[key] = $h.getNum(value);
  242. break;
  243. default:
  244. self[key] = value;
  245. break;
  246. }
  247. });
  248. self.$form = $el.closest('form');
  249. self._initTemplateDefaults();
  250. self.fileInputCleared = false;
  251. self.fileBatchCompleted = true;
  252. if (!self.isPreviewable) {
  253. self.showPreview = false;
  254. }
  255. self.uploadFileAttr = !$h.isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  256. self.reader = null;
  257. self.formdata = {};
  258. self.clearStack();
  259. self.uploadCount = 0;
  260. self.uploadStatus = {};
  261. self.uploadLog = [];
  262. self.uploadAsyncCount = 0;
  263. self.loadedImages = [];
  264. self.totalImagesCount = 0;
  265. self.ajaxRequests = [];
  266. self.isError = false;
  267. self.ajaxAborted = false;
  268. self.cancelling = false;
  269. t = self._getLayoutTemplate('progress');
  270. self.progressTemplate = t.replace('{class}', self.progressClass);
  271. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  272. self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass);
  273. self.dropZoneEnabled = $h.hasDragDropSupport() && self.dropZoneEnabled;
  274. self.isDisabled = $el.attr('disabled') || $el.attr('readonly');
  275. self.isUploadable = $h.hasFileUploadSupport() && !$h.isEmpty(self.uploadUrl);
  276. self.isClickable = self.browseOnZoneClick && self.showPreview &&
  277. (self.isUploadable && self.dropZoneEnabled || !$h.isEmpty(self.defaultPreviewContent));
  278. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self._slugDefault;
  279. self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2');
  280. self.captionTemplate = self._getLayoutTemplate('caption');
  281. self.previewGenericTemplate = self._getPreviewTemplate('generic');
  282. if (self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
  283. self.imageCanvas = document.createElement('canvas');
  284. self.imageCanvasContext = self.imageCanvas.getContext('2d');
  285. }
  286. if ($h.isEmpty($el.attr('id'))) {
  287. $el.attr('id', $h.uniqId());
  288. }
  289. if (self.$container === undefined) {
  290. self.$container = self._createContainer();
  291. } else {
  292. self._refreshContainer();
  293. }
  294. self.$dropZone = self.$container.find('.file-drop-zone');
  295. self.$progress = self.$container.find('.kv-upload-progress');
  296. self.$btnUpload = self.$container.find('.fileinput-upload');
  297. self.$captionContainer = $h.getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  298. self.$caption = $h.getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  299. self.$previewContainer = $h.getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  300. self.$preview = $h.getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  301. self.$previewStatus = $h.getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  302. self.$errorContainer = $h.getElement(options, 'elErrorContainer',
  303. self.$previewContainer.find('.kv-fileinput-error'));
  304. if (!$h.isEmpty(self.msgErrorClass)) {
  305. $h.addCss(self.$errorContainer, self.msgErrorClass);
  306. }
  307. self.$errorContainer.hide();
  308. self.previewInitId = "preview-" + $h.uniqId();
  309. self._initPreviewCache();
  310. self._initPreview(true);
  311. self._initPreviewActions();
  312. self._setFileDropZoneTitle();
  313. $el.removeClass('file-loading');
  314. if ($el.attr('disabled')) {
  315. self.disable();
  316. }
  317. self._initZoom();
  318. },
  319. _initTemplateDefaults: function () {
  320. var self = this, tMain1, tMain2, tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse,
  321. tModalMain, tModal, tProgress, tSize, tFooter, tActions, tActionDelete, tActionUpload, tActionZoom,
  322. tActionDrag, tTagBef, tTagBef1, tTagBef2, tTagAft, tGeneric, tHtml, tImage, tText, tVideo, tAudio,
  323. tFlash, tObject, tPdf, tOther, tZoomCache;
  324. tMain1 = '{preview}\n' +
  325. '<div class="kv-upload-progress hide"></div>\n' +
  326. '<div class="input-group {class}">\n' +
  327. ' {caption}\n' +
  328. ' <div class="input-group-btn">\n' +
  329. ' {remove}\n' +
  330. ' {cancel}\n' +
  331. ' {upload}\n' +
  332. ' {browse}\n' +
  333. ' </div>\n' +
  334. '</div>';
  335. tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n';
  336. tPreview = '<div class="file-preview {class}">\n' +
  337. ' {close}' +
  338. ' <div class="{dropClass}">\n' +
  339. ' <div class="file-preview-thumbnails">\n' +
  340. ' </div>\n' +
  341. ' <div class="clearfix"></div>' +
  342. ' <div class="file-preview-status text-center text-success"></div>\n' +
  343. ' <div class="kv-fileinput-error"></div>\n' +
  344. ' </div>\n' +
  345. '</div>';
  346. tClose = '<div class="close fileinput-remove">&times;</div>\n';
  347. tFileIcon = '<i class="glyphicon glyphicon-file kv-caption-icon"></i>';
  348. tCaption = '<div tabindex="500" class="form-control file-caption {class}">\n' +
  349. ' <div class="file-caption-name"></div>\n' +
  350. '</div>\n';
  351. //noinspection HtmlUnknownAttribute
  352. tBtnDefault = '<button type="{type}" tabindex="500" title="{title}" class="{css}" ' +
  353. '{status}>{icon} {label}</button>';
  354. //noinspection HtmlUnknownAttribute
  355. tBtnLink = '<a href="{href}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</a>';
  356. //noinspection HtmlUnknownAttribute
  357. tBtnBrowse = '<div tabindex="500" class="{css}" {status}>{icon} {label}</div>';
  358. tModalMain = '<div id="' + $h.MODAL_ID + '" class="file-zoom-dialog modal fade" ' +
  359. 'tabindex="-1" aria-labelledby="' + $h.MODAL_ID + 'Label"></div>';
  360. tModal = '<div class="modal-dialog modal-lg" role="document">\n' +
  361. ' <div class="modal-content">\n' +
  362. ' <div class="modal-header">\n' +
  363. ' <div class="kv-zoom-actions pull-right">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
  364. ' <h3 class="modal-title">{heading} <small><span class="kv-zoom-title"></span></small></h3>\n' +
  365. ' </div>\n' +
  366. ' <div class="modal-body">\n' +
  367. ' <div class="floating-buttons"></div>\n' +
  368. ' <div class="kv-zoom-body file-zoom-content"></div>\n' + '{prev} {next}\n' +
  369. ' </div>\n' +
  370. ' </div>\n' +
  371. '</div>\n';
  372. tProgress = '<div class="progress">\n' +
  373. ' <div class="{class}" role="progressbar"' +
  374. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  375. ' {percent}%\n' +
  376. ' </div>\n' +
  377. '</div>';
  378. tSize = ' <samp>({sizeText})</samp>';
  379. tFooter = '<div class="file-thumbnail-footer">\n' +
  380. ' <div class="file-footer-caption" title="{caption}">{caption}<br>{size}</div>\n' +
  381. ' {progress} {actions}\n' +
  382. '</div>';
  383. tActions = '<div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>\n' +
  384. '{drag}\n' +
  385. '<div class="file-actions">\n' +
  386. ' <div class="file-footer-buttons">\n' +
  387. ' {upload} {delete} {zoom} {other}' +
  388. ' </div>\n' +
  389. ' <div class="clearfix"></div>\n' +
  390. '</div>';
  391. //noinspection HtmlUnknownAttribute
  392. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  393. 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n';
  394. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  395. '{uploadIcon}</button>';
  396. tActionZoom = '<button type="button" class="kv-file-zoom {zoomClass}" ' +
  397. 'title="{zoomTitle}">{zoomIcon}</button>';
  398. tActionDrag = '<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>';
  399. tTagBef = '<div class="file-preview-frame {frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  400. ' data-template="{template}"';
  401. tTagBef1 = tTagBef + '><div class="kv-file-content">\n';
  402. tTagBef2 = tTagBef + ' title="{caption}"><div class="kv-file-content">\n';
  403. tTagAft = '</div>{footer}\n</div>\n';
  404. tGeneric = '{content}\n';
  405. tHtml = '<div class="kv-preview-data file-preview-html" title="{caption}" ' + $h.STYLE_SETTING +
  406. '>{data}</div>\n';
  407. tImage = '<img src="{data}" class="file-preview-image kv-preview-data" title="{caption}" alt="{caption}" ' +
  408. $h.STYLE_SETTING + '>\n';
  409. tText = '<textarea class="kv-preview-data file-preview-text" title="{caption}" readonly ' +
  410. $h.STYLE_SETTING + '>{data}</textarea>\n';
  411. tVideo = '<video class="kv-preview-data file-preview-video" width="{width}" ' +
  412. 'height="{height}" controls>\n' + '<source src="{data}" type="{type}">\n' + $h.DEFAULT_PREVIEW +
  413. '\n</video>\n';
  414. tAudio = '<div class="file-preview-audio"><audio class="kv-preview-data" controls>\n<source src="{data}" ' +
  415. 'type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</audio></div>\n';
  416. tFlash = '<object class="kv-preview-data file-object" type="application/x-shockwave-flash" ' +
  417. 'width="{width}" height="{height}" data="{data}">\n' + $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW +
  418. '\n</object>\n';
  419. tObject = '<object class="kv-preview-data file-object" data="{data}" type="{type}" ' +
  420. 'width="{width}" height="{height}">\n' + '<param name="movie" value="{caption}" />\n' +
  421. $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW + '\n</object>\n';
  422. tPdf = '<embed class="kv-preview-data" src="{data}" ' +
  423. 'width="{width}" height="{height}" type="application/pdf">\n';
  424. tOther = '<div class="kv-preview-data file-preview-other-frame">\n' + $h.DEFAULT_PREVIEW + '\n</div>\n';
  425. tZoomCache = '<div class="kv-zoom-cache" style="display:none">{zoomContent}</div>';
  426. self.defaults = {
  427. layoutTemplates: {
  428. main1: tMain1,
  429. main2: tMain2,
  430. preview: tPreview,
  431. close: tClose,
  432. fileIcon: tFileIcon,
  433. caption: tCaption,
  434. modalMain: tModalMain,
  435. modal: tModal,
  436. progress: tProgress,
  437. size: tSize,
  438. footer: tFooter,
  439. actions: tActions,
  440. actionDelete: tActionDelete,
  441. actionUpload: tActionUpload,
  442. actionZoom: tActionZoom,
  443. actionDrag: tActionDrag,
  444. btnDefault: tBtnDefault,
  445. btnLink: tBtnLink,
  446. btnBrowse: tBtnBrowse,
  447. zoomCache: tZoomCache
  448. },
  449. previewMarkupTags: {
  450. tagBefore1: tTagBef1,
  451. tagBefore2: tTagBef2,
  452. tagAfter: tTagAft
  453. },
  454. previewContentTemplates: {
  455. generic: tGeneric,
  456. html: tHtml,
  457. image: tImage,
  458. text: tText,
  459. video: tVideo,
  460. audio: tAudio,
  461. flash: tFlash,
  462. object: tObject,
  463. pdf: tPdf,
  464. other: tOther
  465. },
  466. allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'],
  467. previewTemplates: {},
  468. previewSettings: {
  469. image: {width: "auto", height: "160px"},
  470. html: {width: "213px", height: "160px"},
  471. text: {width: "213px", height: "160px"},
  472. video: {width: "213px", height: "160px"},
  473. audio: {width: "213px", height: "80px"},
  474. flash: {width: "213px", height: "160px"},
  475. object: {width: "160px", height: "auto"},
  476. pdf: {width: "160px", height: "160px"},
  477. other: {width: "160px", height: "160px"}
  478. },
  479. previewZoomSettings: {
  480. image: {width: "auto", height: "auto", 'max-width': "100%", 'max-height': "100%"},
  481. html: {width: "100%", height: "100%", 'min-height': "480px"},
  482. text: {width: "100%", height: "100%", 'min-height': "480px"},
  483. video: {width: "auto", height: "100%", 'max-width': "100%"},
  484. audio: {width: "100%", height: "30px"},
  485. flash: {width: "auto", height: "480px"},
  486. object: {width: "auto", height: "100%", 'min-height': "480px"},
  487. pdf: {width: "100%", height: "100%", 'min-height': "480px"},
  488. other: {width: "auto", height: "100%", 'min-height': "480px"}
  489. },
  490. fileTypeSettings: {
  491. image: function (vType, vName) {
  492. return $h.compare(vType, 'image.*') || $h.compare(vName, /\.(gif|png|jpe?g)$/i);
  493. },
  494. html: function (vType, vName) {
  495. return $h.compare(vType, 'text/html') || $h.compare(vName, /\.(htm|html)$/i);
  496. },
  497. text: function (vType, vName) {
  498. return $h.compare(vType, 'text.*') || $h.compare(vName, /\.(xml|javascript)$/i) ||
  499. $h.compare(vName, /\.(txt|md|csv|nfo|ini|json|php|js|css)$/i);
  500. },
  501. video: function (vType, vName) {
  502. return $h.compare(vType, 'video.*') && ($h.compare(vType, /(ogg|mp4|mp?g|mov|webm|3gp)$/i) ||
  503. $h.compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i));
  504. },
  505. audio: function (vType, vName) {
  506. return $h.compare(vType, 'audio.*') && ($h.compare(vName, /(ogg|mp3|mp?g|wav)$/i) ||
  507. $h.compare(vName, /\.(og?|mp3|mp?g|wav)$/i));
  508. },
  509. flash: function (vType, vName) {
  510. return $h.compare(vType, 'application/x-shockwave-flash', true) || $h.compare(vName, /\.(swf)$/i);
  511. },
  512. pdf: function (vType, vName) {
  513. return $h.compare(vType, 'application/pdf', true) || $h.compare(vName, /\.(pdf)$/i);
  514. },
  515. object: function () {
  516. return true;
  517. },
  518. other: function () {
  519. return true;
  520. }
  521. },
  522. fileActionSettings: {
  523. showRemove: true,
  524. showUpload: true,
  525. showZoom: true,
  526. showDrag: true,
  527. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  528. removeClass: 'btn btn-xs btn-default',
  529. removeTitle: 'Remove file',
  530. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  531. uploadClass: 'btn btn-xs btn-default',
  532. uploadTitle: 'Upload file',
  533. zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>',
  534. zoomClass: 'btn btn-xs btn-default',
  535. zoomTitle: 'View Details',
  536. dragIcon: '<i class="glyphicon glyphicon-menu-hamburger"></i>',
  537. dragClass: 'text-info',
  538. dragTitle: 'Move / Rearrange',
  539. dragSettings: {},
  540. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  541. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
  542. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  543. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  544. indicatorNewTitle: 'Not uploaded yet',
  545. indicatorSuccessTitle: 'Uploaded',
  546. indicatorErrorTitle: 'Upload Error',
  547. indicatorLoadingTitle: 'Uploading ...'
  548. }
  549. };
  550. $.each(self.defaults, function (key, setting) {
  551. if (key === 'allowedPreviewTypes') {
  552. if (self.allowedPreviewTypes === undefined) {
  553. self.allowedPreviewTypes = setting;
  554. }
  555. return;
  556. }
  557. self[key] = $.extend(true, {}, setting, self[key]);
  558. });
  559. self._initPreviewTemplates();
  560. },
  561. _initPreviewTemplates: function () {
  562. var self = this, cfg = self.defaults, tags = self.previewMarkupTags, tagBef, tagAft = tags.tagAfter;
  563. $.each(cfg.previewContentTemplates, function (key, value) {
  564. if ($h.isEmpty(self.previewTemplates[key])) {
  565. tagBef = tags.tagBefore2;
  566. if (key === 'generic' || key === 'image' || key === 'html' || key === 'text') {
  567. tagBef = tags.tagBefore1;
  568. }
  569. self.previewTemplates[key] = tagBef + value + tagAft;
  570. }
  571. });
  572. },
  573. _initPreviewCache: function () {
  574. var self = this;
  575. self.previewCache = {
  576. data: {},
  577. init: function () {
  578. var content = self.initialPreview;
  579. if (content.length > 0 && !$h.isArray(content)) {
  580. content = content.split(self.initialPreviewDelimiter);
  581. }
  582. self.previewCache.data = {
  583. content: content,
  584. config: self.initialPreviewConfig,
  585. tags: self.initialPreviewThumbTags
  586. };
  587. },
  588. fetch: function () {
  589. return self.previewCache.data.content.filter(function (n) {
  590. return n !== null;
  591. });
  592. },
  593. count: function (all) {
  594. return !!self.previewCache.data && !!self.previewCache.data.content ?
  595. (all ? self.previewCache.data.content.length : self.previewCache.fetch().length) : 0;
  596. },
  597. get: function (i, isDisabled) {
  598. var ind = 'init_' + i, data = self.previewCache.data, config = data.config[i],
  599. content = data.content[i], previewId = self.previewInitId + '-' + ind, out, $tmp, cat, ftr,
  600. fname, ftype, frameClass, asData = $h.ifSet('previewAsData', config, self.initialPreviewAsData),
  601. parseTemplate = function (cat, dat, fn, ft, id, ftr, ind, fc, t) {
  602. fc = ' file-preview-initial ' + $h.SORT_CSS + (fc ? ' ' + fc : '');
  603. return self._generatePreviewTemplate(cat, dat, fn, ft, id, false, null, fc, ftr, ind, t);
  604. };
  605. if (!content) {
  606. return '';
  607. }
  608. isDisabled = isDisabled === undefined ? true : isDisabled;
  609. cat = $h.ifSet('type', config, self.initialPreviewFileType || 'generic');
  610. fname = $h.ifSet('filename', config, $h.ifSet('caption', config));
  611. ftype = $h.ifSet('filetype', config, cat);
  612. ftr = self.previewCache.footer(i, isDisabled, (config && config.size || null));
  613. frameClass = $h.ifSet('frameClass', config);
  614. if (asData) {
  615. out = parseTemplate(cat, content, fname, ftype, previewId, ftr, ind, frameClass);
  616. } else {
  617. out = parseTemplate('generic', content, fname, ftype, previewId, ftr, ind, frameClass, cat)
  618. .replace(/\{content}/g, data.content[i]);
  619. }
  620. if (data.tags.length && data.tags[i]) {
  621. out = $h.replaceTags(out, data.tags[i]);
  622. }
  623. /** @namespace config.frameAttr */
  624. if (!$h.isEmpty(config) && !$h.isEmpty(config.frameAttr)) {
  625. $tmp = $(document.createElement('div')).html(out);
  626. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  627. out = $tmp.html();
  628. $tmp.remove();
  629. }
  630. return out;
  631. },
  632. add: function (content, config, tags, append) {
  633. var data = self.previewCache.data, index;
  634. if (!$h.isArray(content)) {
  635. content = content.split(self.initialPreviewDelimiter);
  636. }
  637. if (append) {
  638. index = data.content.push(content) - 1;
  639. data.config[index] = config;
  640. data.tags[index] = tags;
  641. } else {
  642. index = content.length - 1;
  643. data.content = content;
  644. data.config = config;
  645. data.tags = tags;
  646. }
  647. self.previewCache.data = data;
  648. return index;
  649. },
  650. set: function (content, config, tags, append) {
  651. var data = self.previewCache.data, i, chk;
  652. if (!content || !content.length) {
  653. return;
  654. }
  655. if (!$h.isArray(content)) {
  656. content = content.split(self.initialPreviewDelimiter);
  657. }
  658. chk = content.filter(function (n) {
  659. return n !== null;
  660. });
  661. if (!chk.length) {
  662. return;
  663. }
  664. if (data.content === undefined) {
  665. data.content = [];
  666. }
  667. if (data.config === undefined) {
  668. data.config = [];
  669. }
  670. if (data.tags === undefined) {
  671. data.tags = [];
  672. }
  673. if (append) {
  674. for (i = 0; i < content.length; i++) {
  675. if (content[i]) {
  676. data.content.push(content[i]);
  677. }
  678. }
  679. for (i = 0; i < config.length; i++) {
  680. if (config[i]) {
  681. data.config.push(config[i]);
  682. }
  683. }
  684. for (i = 0; i < tags.length; i++) {
  685. if (tags[i]) {
  686. data.tags.push(tags[i]);
  687. }
  688. }
  689. } else {
  690. data.content = content;
  691. data.config = config;
  692. data.tags = tags;
  693. }
  694. self.previewCache.data = data;
  695. },
  696. unset: function (index) {
  697. var chk = self.previewCache.count();
  698. if (!chk) {
  699. return;
  700. }
  701. if (chk === 1) {
  702. self.previewCache.data.content = [];
  703. self.previewCache.data.config = [];
  704. self.previewCache.data.tags = [];
  705. self.initialPreview = [];
  706. self.initialPreviewConfig = [];
  707. self.initialPreviewThumbTags = [];
  708. return;
  709. }
  710. self.previewCache.data.content[index] = null;
  711. self.previewCache.data.config[index] = null;
  712. self.previewCache.data.tags[index] = null;
  713. },
  714. out: function () {
  715. var html = '', caption, len = self.previewCache.count(true), i;
  716. if (len === 0) {
  717. return {content: '', caption: ''};
  718. }
  719. for (i = 0; i < len; i++) {
  720. html += self.previewCache.get(i);
  721. }
  722. caption = self._getMsgSelected(self.previewCache.count());
  723. return {content: html, caption: caption};
  724. },
  725. footer: function (i, isDisabled, size) {
  726. var data = self.previewCache.data;
  727. if (!data || !data.config || data.config.length === 0 || $h.isEmpty(data.config[i])) {
  728. return '';
  729. }
  730. isDisabled = isDisabled === undefined ? true : isDisabled;
  731. var config = data.config[i], caption = $h.ifSet('caption', config), actions = '',
  732. width = $h.ifSet('width', config, 'auto'), url = $h.ifSet('url', config, false),
  733. key = $h.ifSet('key', config, null), fs = self.fileActionSettings,
  734. showDel = $h.ifSet('showDelete', config, true), showZoom = $h.ifSet('showZoom', config, fs.showZoom),
  735. showDrag = $h.ifSet('showDrag', config, fs.showDrag), disabled = (url === false) && isDisabled;
  736. if (self.initialPreviewShowDelete) {
  737. actions = self._renderFileActions(false, showDel, showZoom, showDrag, disabled, url, key, true);
  738. }
  739. return self._getLayoutTemplate('footer').replace(/\{progress}/g, self._renderThumbProgress())
  740. .replace(/\{actions}/g, actions).replace(/\{caption}/g, caption)
  741. .replace(/\{size}/g, self._getSize(size)).replace(/\{width}/g, width)
  742. .replace(/\{indicator}/g, '').replace(/\{indicatorTitle}/g, '');
  743. }
  744. };
  745. self.previewCache.init();
  746. },
  747. _log: function (msg) {
  748. var self = this, id = self.$element.attr('id');
  749. if (id) {
  750. msg = '"' + id + '": ' + msg;
  751. }
  752. if (typeof window.console.log !== "undefined") {
  753. window.console.log(msg);
  754. } else {
  755. window.alert(msg);
  756. }
  757. },
  758. _validate: function () {
  759. var self = this, status = self.$element.attr('type') === 'file';
  760. if (!status) {
  761. self._log('The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.');
  762. }
  763. return status;
  764. },
  765. _errorsExist: function () {
  766. var self = this, $err;
  767. if (self.$errorContainer.find('li').length) {
  768. return true;
  769. }
  770. $err = $(document.createElement('div')).html(self.$errorContainer.html());
  771. $err.find('span.kv-error-close').remove();
  772. $err.find('ul').remove();
  773. return $.trim($err.text()).length ? true : false;
  774. },
  775. _errorHandler: function (evt, caption) {
  776. var self = this, err = evt.target.error;
  777. /** @namespace err.NOT_FOUND_ERR */
  778. /** @namespace err.SECURITY_ERR */
  779. /** @namespace err.NOT_READABLE_ERR */
  780. if (err.code === err.NOT_FOUND_ERR) {
  781. self._showError(self.msgFileNotFound.replace('{name}', caption));
  782. } else if (err.code === err.SECURITY_ERR) {
  783. self._showError(self.msgFileSecured.replace('{name}', caption));
  784. } else if (err.code === err.NOT_READABLE_ERR) {
  785. self._showError(self.msgFileNotReadable.replace('{name}', caption));
  786. } else if (err.code === err.ABORT_ERR) {
  787. self._showError(self.msgFilePreviewAborted.replace('{name}', caption));
  788. } else {
  789. self._showError(self.msgFilePreviewError.replace('{name}', caption));
  790. }
  791. },
  792. _addError: function (msg) {
  793. var self = this, $error = self.$errorContainer;
  794. if (msg && $error.length) {
  795. $error.html(self.errorCloseButton + msg);
  796. $h.handler($error.find('.kv-error-close'), 'click', function () {
  797. $error.fadeOut('slow');
  798. });
  799. }
  800. },
  801. _resetErrors: function (fade) {
  802. var self = this, $error = self.$errorContainer;
  803. self.isError = false;
  804. self.$container.removeClass('has-error');
  805. $error.html('');
  806. if (fade) {
  807. $error.fadeOut('slow');
  808. } else {
  809. $error.hide();
  810. }
  811. },
  812. _showFolderError: function (folders) {
  813. var self = this, $error = self.$errorContainer, msg;
  814. if (!folders) {
  815. return;
  816. }
  817. msg = self.msgFoldersNotAllowed.replace(/\{n}/g, folders);
  818. self._addError(msg);
  819. $h.addCss(self.$container, 'has-error');
  820. $error.fadeIn(800);
  821. self._raise('filefoldererror', [folders, msg]);
  822. },
  823. _showUploadError: function (msg, params, event) {
  824. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', e = params && params.id ?
  825. '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  826. if ($error.find('ul').length === 0) {
  827. self._addError('<ul>' + e + '</ul>');
  828. } else {
  829. $error.find('ul').append(e);
  830. }
  831. $error.fadeIn(800);
  832. self._raise(ev, [params, msg]);
  833. self.$container.removeClass('file-input-new');
  834. $h.addCss(self.$container, 'has-error');
  835. return true;
  836. },
  837. _showError: function (msg, params, event) {
  838. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  839. params = params || {};
  840. params.reader = self.reader;
  841. self._addError(msg);
  842. $error.fadeIn(800);
  843. self._raise(ev, [params, msg]);
  844. if (!self.isUploadable) {
  845. self._clearFileInput();
  846. }
  847. self.$container.removeClass('file-input-new');
  848. $h.addCss(self.$container, 'has-error');
  849. self.$btnUpload.attr('disabled', true);
  850. return true;
  851. },
  852. _noFilesError: function (params) {
  853. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  854. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  855. $error = self.$errorContainer;
  856. self._addError(msg);
  857. self.isError = true;
  858. self._updateFileDetails(0);
  859. $error.fadeIn(800);
  860. self._raise('fileerror', [params, msg]);
  861. self._clearFileInput();
  862. $h.addCss(self.$container, 'has-error');
  863. },
  864. _parseError: function (operation, jqXHR, errorThrown, fileName) {
  865. /** @namespace jqXHR.responseJSON */
  866. var self = this, errMsg = $.trim(errorThrown + ''), dot = errMsg.slice(-1) === '.' ? '' : '.',
  867. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  868. jqXHR.responseJSON.error : jqXHR.responseText;
  869. if (self.cancelling && self.msgUploadAborted) {
  870. errMsg = self.msgUploadAborted;
  871. }
  872. if (self.showAjaxErrorDetails && text) {
  873. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  874. text = text.length > 0 ? '<pre>' + text + '</pre>' : '';
  875. errMsg += dot + text;
  876. } else {
  877. errMsg += dot;
  878. }
  879. if (errMsg === dot) {
  880. errMsg = self.msgAjaxError.replace('{operation}', operation);
  881. }
  882. self.cancelling = false;
  883. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  884. },
  885. _parseFileType: function (file) {
  886. var self = this, isValid, vType, cat, i, types = self.allowedPreviewTypes;
  887. for (i = 0; i < types.length; i++) {
  888. cat = types[i];
  889. isValid = self.fileTypeSettings[cat];
  890. vType = isValid(file.type, file.name) ? cat : '';
  891. if (!$h.isEmpty(vType)) {
  892. return vType;
  893. }
  894. }
  895. return 'other';
  896. },
  897. _getPreviewIcon: function (fname) {
  898. var self = this, ext, out = null;
  899. if (fname && fname.indexOf('.') > -1) {
  900. ext = fname.split('.').pop();
  901. if (self.previewFileIconSettings && self.previewFileIconSettings[ext]) {
  902. out = self.previewFileIconSettings[ext];
  903. }
  904. if (self.previewFileExtSettings) {
  905. $.each(self.previewFileExtSettings, function (key, func) {
  906. if (self.previewFileIconSettings[key] && func(ext)) {
  907. out = self.previewFileIconSettings[key];
  908. //noinspection UnnecessaryReturnStatementJS
  909. return;
  910. }
  911. });
  912. }
  913. }
  914. return out;
  915. },
  916. _parseFilePreviewIcon: function (content, fname) {
  917. var self = this, icn = self._getPreviewIcon(fname) || self.previewFileIcon;
  918. if (content.indexOf('{previewFileIcon}') > -1) {
  919. content = content.replace(/\{previewFileIconClass}/g, self.previewFileIconClass).replace(
  920. /\{previewFileIcon}/g, icn);
  921. }
  922. return content;
  923. },
  924. _raise: function (event, params) {
  925. var self = this, e = $.Event(event);
  926. if (params !== undefined) {
  927. self.$element.trigger(e, params);
  928. } else {
  929. self.$element.trigger(e);
  930. }
  931. if (e.isDefaultPrevented() || e.result === false) {
  932. return false;
  933. }
  934. switch (event) {
  935. // ignore these events
  936. case 'filebatchuploadcomplete':
  937. case 'filebatchuploadsuccess':
  938. case 'fileuploaded':
  939. case 'fileclear':
  940. case 'filecleared':
  941. case 'filereset':
  942. case 'fileerror':
  943. case 'filefoldererror':
  944. case 'fileuploaderror':
  945. case 'filebatchuploaderror':
  946. case 'filedeleteerror':
  947. case 'filecustomerror':
  948. case 'filesuccessremove':
  949. break;
  950. // receive data response via `filecustomerror` event`
  951. default:
  952. self.ajaxAborted = e.result;
  953. break;
  954. }
  955. return true;
  956. },
  957. _listenFullScreen: function (isFullScreen) {
  958. var self = this, $modal = self.$modal, $btnFull, $btnBord;
  959. if (!$modal || !$modal.length) {
  960. return;
  961. }
  962. $btnFull = $modal && $modal.find('.btn-fullscreen');
  963. $btnBord = $modal && $modal.find('.btn-borderless');
  964. if (!$btnFull.length || !$btnBord.length) {
  965. return;
  966. }
  967. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  968. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  969. if (isFullScreen) {
  970. $btnFull.addClass('active').attr('aria-pressed', 'true');
  971. } else {
  972. $btnBord.addClass('active').attr('aria-pressed', 'true');
  973. }
  974. if ($modal.hasClass('file-zoom-fullscreen')) {
  975. self._maximizeZoomDialog();
  976. } else {
  977. if (isFullScreen) {
  978. self._maximizeZoomDialog();
  979. } else {
  980. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  981. }
  982. }
  983. },
  984. _listen: function () {
  985. var self = this, $el = self.$element, $form = self.$form, $cont = self.$container;
  986. $h.handler($el, 'change', $.proxy(self._change, self));
  987. if (self.showBrowse) {
  988. $h.handler(self.$btnFile, 'click', $.proxy(self._browse, self));
  989. }
  990. $h.handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  991. $h.handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  992. self._initDragDrop();
  993. $h.handler($form, 'reset', $.proxy(self.reset, self), true);
  994. if (!self.isUploadable) {
  995. $h.handler($form, 'submit', $.proxy(self._submitForm, self), true);
  996. }
  997. $h.handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
  998. $h.handler($(window), 'resize', function () {
  999. self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight);
  1000. }, true);
  1001. $h.handler($(document), 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange',
  1002. function () {
  1003. self._listenFullScreen($h.checkFullScreen());
  1004. }, true);
  1005. self._initClickable();
  1006. },
  1007. _initClickable: function () {
  1008. var self = this, $zone;
  1009. if (!self.isClickable) {
  1010. return;
  1011. }
  1012. $zone = self.isUploadable ? self.$dropZone : self.$preview.find('.file-default-preview');
  1013. $h.addCss($zone, 'clickable');
  1014. $zone.attr('tabindex', -1);
  1015. $h.handler($zone, 'click', function (e) {
  1016. var $tar = $(e.target);
  1017. if (!$tar.parents('.file-preview-thumbnails').length || $tar.parents('.file-default-preview').length) {
  1018. self.$element.trigger('click');
  1019. $zone.blur();
  1020. }
  1021. });
  1022. },
  1023. _initDragDrop: function () {
  1024. var self = this, $zone = self.$dropZone;
  1025. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  1026. $h.handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
  1027. $h.handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
  1028. $h.handler($zone, 'drop', $.proxy(self._zoneDrop, self));
  1029. $h.handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
  1030. }
  1031. },
  1032. _zoneDragDropInit: function (e) {
  1033. e.stopPropagation();
  1034. e.preventDefault();
  1035. },
  1036. _zoneDragEnter: function (e) {
  1037. var self = this, hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1;
  1038. self._zoneDragDropInit(e);
  1039. if (self.isDisabled || !hasFiles) {
  1040. e.originalEvent.dataTransfer.effectAllowed = 'none';
  1041. e.originalEvent.dataTransfer.dropEffect = 'none';
  1042. return;
  1043. }
  1044. $h.addCss(self.$dropZone, 'file-highlighted');
  1045. },
  1046. _zoneDragLeave: function (e) {
  1047. var self = this;
  1048. self._zoneDragDropInit(e);
  1049. if (self.isDisabled) {
  1050. return;
  1051. }
  1052. self.$dropZone.removeClass('file-highlighted');
  1053. },
  1054. _zoneDrop: function (e) {
  1055. var self = this;
  1056. e.preventDefault();
  1057. /** @namespace e.originalEvent.dataTransfer */
  1058. if (self.isDisabled || $h.isEmpty(e.originalEvent.dataTransfer.files)) {
  1059. return;
  1060. }
  1061. self._change(e, 'dragdrop');
  1062. self.$dropZone.removeClass('file-highlighted');
  1063. },
  1064. _uploadClick: function (e) {
  1065. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  1066. isEnabled = !$btn.hasClass('disabled') && $h.isEmpty($btn.attr('disabled'));
  1067. if (e && e.isDefaultPrevented()) {
  1068. return;
  1069. }
  1070. if (!self.isUploadable) {
  1071. if (isEnabled && $btn.attr('type') !== 'submit') {
  1072. $form = $btn.closest('form');
  1073. // downgrade to normal form submit if possible
  1074. if ($form.length) {
  1075. $form.trigger('submit');
  1076. }
  1077. e.preventDefault();
  1078. }
  1079. return;
  1080. }
  1081. e.preventDefault();
  1082. if (isEnabled) {
  1083. self.upload();
  1084. }
  1085. },
  1086. _submitForm: function () {
  1087. var self = this, $el = self.$element, files = $el.get(0).files;
  1088. if (files && self.minFileCount > 0 && self._getFileCount(files.length) < self.minFileCount) {
  1089. self._noFilesError({});
  1090. return false;
  1091. }
  1092. return !self._abort({});
  1093. },
  1094. _clearPreview: function () {
  1095. var self = this, $p = self.$preview,
  1096. $thumbs = self.showUploadedThumbs ? $p.find($h.FRAMES + ':not(.file-preview-success)') : $p.find($h.FRAMES);
  1097. $thumbs.each(function () {
  1098. var $thumb = $(this);
  1099. $thumb.remove();
  1100. $h.cleanZoomCache($p.find('#zoom-' + $thumb.attr('id')));
  1101. });
  1102. if (!self.$preview.find($h.FRAMES).length || !self.showPreview) {
  1103. self._resetUpload();
  1104. }
  1105. self._validateDefaultPreview();
  1106. },
  1107. _initSortable: function () {
  1108. var self = this, $el = self.$preview, settings, selector = '.' + $h.SORT_CSS;
  1109. if (!window.KvSortable || $el.find(selector).length === 0) {
  1110. return;
  1111. }
  1112. //noinspection JSUnusedGlobalSymbols
  1113. settings = {
  1114. handle: '.drag-handle-init',
  1115. dataIdAttr: 'data-preview-id',
  1116. draggable: selector,
  1117. onSort: function (e) {
  1118. var oldIndex = e.oldIndex, newIndex = e.newIndex, key, $frame;
  1119. self.initialPreview = $h.moveArray(self.initialPreview, oldIndex, newIndex);
  1120. self.initialPreviewConfig = $h.moveArray(self.initialPreviewConfig, oldIndex, newIndex);
  1121. self.previewCache.init();
  1122. for (var i = 0; i < self.initialPreviewConfig.length; i++) {
  1123. if (self.initialPreviewConfig[i] !== null) {
  1124. key = self.initialPreviewConfig[i].key;
  1125. $frame = $(".kv-file-remove[data-key='" + key + "']").closest($h.FRAMES);
  1126. $frame.attr('data-fileindex', 'init_' + i).data('fileindex', 'init_' + i);
  1127. }
  1128. }
  1129. self._raise('filesorted', {
  1130. previewId: $(e.item).attr('id'),
  1131. 'oldIndex': oldIndex,
  1132. 'newIndex': newIndex,
  1133. stack: self.initialPreviewConfig
  1134. });
  1135. }
  1136. };
  1137. if ($el.data('kvsortable')) {
  1138. $el.kvsortable('destroy');
  1139. }
  1140. $.extend(true, settings, self.fileActionSettings.dragSettings);
  1141. $el.kvsortable(settings);
  1142. },
  1143. _initPreview: function (isInit) {
  1144. var self = this, cap = self.initialCaption || '', out;
  1145. if (!self.previewCache.count()) {
  1146. self._clearPreview();
  1147. if (isInit) {
  1148. self._setCaption(cap);
  1149. } else {
  1150. self._initCaption();
  1151. }
  1152. return;
  1153. }
  1154. out = self.previewCache.out();
  1155. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  1156. self.$preview.html(out.content);
  1157. self._setInitThumbAttr();
  1158. self._setCaption(cap);
  1159. self._initSortable();
  1160. if (!$h.isEmpty(out.content)) {
  1161. self.$container.removeClass('file-input-new');
  1162. }
  1163. },
  1164. _getZoomButton: function (type) {
  1165. var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type],
  1166. title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ',
  1167. params = title + (type === 'close' ? ' data-dismiss="modal" aria-hidden="true"' : '');
  1168. if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') {
  1169. params += ' data-toggle="button" aria-pressed="false" autocomplete="off"';
  1170. }
  1171. return '<button type="button" class="' + css + ' btn-' + type + '"' + params + '>' + label + '</button>';
  1172. },
  1173. _getModalContent: function () {
  1174. var self = this;
  1175. return self._getLayoutTemplate('modal')
  1176. .replace(/\{heading}/g, self.msgZoomModalHeading)
  1177. .replace(/\{prev}/g, self._getZoomButton('prev'))
  1178. .replace(/\{next}/g, self._getZoomButton('next'))
  1179. .replace(/\{toggleheader}/g, self._getZoomButton('toggleheader'))
  1180. .replace(/\{fullscreen}/g, self._getZoomButton('fullscreen'))
  1181. .replace(/\{borderless}/g, self._getZoomButton('borderless'))
  1182. .replace(/\{close}/g, self._getZoomButton('close'));
  1183. },
  1184. _listenModalEvent: function (event) {
  1185. var self = this, $modal = self.$modal, getParams = function (e) {
  1186. return {
  1187. sourceEvent: e,
  1188. previewId: $modal.data('previewId'),
  1189. modal: $modal
  1190. };
  1191. };
  1192. $modal.on(event + '.bs.modal', function (e) {
  1193. var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
  1194. self._raise('filezoom' + event, getParams(e));
  1195. if (event === 'shown') {
  1196. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1197. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1198. if ($modal.hasClass('file-zoom-fullscreen')) {
  1199. self._maximizeZoomDialog();
  1200. if ($h.checkFullScreen()) {
  1201. $btnFull.addClass('active').attr('aria-pressed', 'true');
  1202. } else {
  1203. $btnBord.addClass('active').attr('aria-pressed', 'true');
  1204. }
  1205. }
  1206. }
  1207. });
  1208. },
  1209. _initZoom: function () {
  1210. var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID;
  1211. if (!self.showPreview) {
  1212. return;
  1213. }
  1214. self.$modal = $(modalId);
  1215. if (!self.$modal || !self.$modal.length) {
  1216. $dialog = $(document.createElement('div')).html(modalMain).insertAfter(self.$container);
  1217. self.$modal = $('#' + $h.MODAL_ID).insertBefore($dialog);
  1218. $dialog.remove();
  1219. }
  1220. $h.initModal(self.$modal);
  1221. self.$modal.html(self._getModalContent());
  1222. $.each($h.MODAL_EVENTS, function (event) {
  1223. self._listenModalEvent(event);
  1224. });
  1225. },
  1226. _initZoomButtons: function () {
  1227. var self = this, previewId = self.$modal.data('previewId') || '', $first, $last, $preview = self.$preview,
  1228. thumbs = $preview.find($h.FRAMES).toArray(), len = thumbs.length,
  1229. $prev = self.$modal.find('.btn-prev'), $next = self.$modal.find('.btn-next');
  1230. if (thumbs.length < 2) {
  1231. $prev.hide();
  1232. $next.hide();
  1233. return;
  1234. } else {
  1235. $prev.show();
  1236. $next.show();
  1237. }
  1238. if (!len) {
  1239. return;
  1240. }
  1241. $first = $(thumbs[0]);
  1242. $last = $(thumbs[len - 1]);
  1243. $prev.removeAttr('disabled');
  1244. $next.removeAttr('disabled');
  1245. if ($first.length && $first.attr('id') === previewId) {
  1246. $prev.attr('disabled', true);
  1247. }
  1248. if ($last.length && $last.attr('id') === previewId) {
  1249. $next.attr('disabled', true);
  1250. }
  1251. },
  1252. _maximizeZoomDialog: function () {
  1253. var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
  1254. $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'),
  1255. h = $(window).height(), diff = 0;
  1256. $modal.addClass('file-zoom-fullscreen');
  1257. if ($head && $head.length) {
  1258. h -= $head.outerHeight(true);
  1259. }
  1260. if ($foot && $foot.length) {
  1261. h -= $foot.outerHeight(true);
  1262. }
  1263. if ($body && $body.length) {
  1264. diff = $body.outerHeight(true) - $body.height();
  1265. h -= diff;
  1266. }
  1267. $modal.find('.kv-zoom-body').height(h);
  1268. },
  1269. _resizeZoomDialog: function (fullScreen) {
  1270. var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'),
  1271. $btnBord = $modal.find('.btn-borderless');
  1272. if ($modal.hasClass('file-zoom-fullscreen')) {
  1273. $h.toggleFullScreen(false);
  1274. if (!fullScreen) {
  1275. if (!$btnFull.hasClass('active')) {
  1276. $modal.removeClass('file-zoom-fullscreen');
  1277. self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
  1278. } else {
  1279. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1280. }
  1281. } else {
  1282. if (!$btnFull.hasClass('active')) {
  1283. $modal.removeClass('file-zoom-fullscreen');
  1284. self._resizeZoomDialog(true);
  1285. if ($btnBord.hasClass('active')) {
  1286. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1287. }
  1288. }
  1289. }
  1290. } else {
  1291. if (!fullScreen) {
  1292. self._maximizeZoomDialog();
  1293. return;
  1294. }
  1295. $h.toggleFullScreen(true);
  1296. }
  1297. $modal.focus();
  1298. },
  1299. _setZoomContent: function ($frame, animate) {
  1300. var self = this, $content, tmplt, body, title, $body, $dataEl, config, pid = $frame.attr('id'),
  1301. $modal = self.$modal, $prev = $modal.find('.btn-prev'), $next = $modal.find('.btn-next'), $tmp,
  1302. $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'), cap, size,
  1303. $btnTogh = $modal.find('.btn-toggleheader'), $zoomPreview = self.$preview.find('#zoom-' + pid);
  1304. tmplt = $zoomPreview.attr('data-template') || 'generic';
  1305. $content = $zoomPreview.find('.kv-file-content');
  1306. body = $content.length ? $content.html() : '';
  1307. cap = $frame.data('caption') || '';
  1308. size = $frame.data('size') || '';
  1309. title = cap + ' ' + size;
  1310. $modal.find('.kv-zoom-title').html(title);
  1311. $body = $modal.find('.kv-zoom-body');
  1312. $modal.removeClass('kv-single-content');
  1313. if (animate) {
  1314. $tmp = $body.clone().insertAfter($body);
  1315. $body.html(body).hide();
  1316. $tmp.fadeOut('fast', function () {
  1317. $body.fadeIn('fast');
  1318. $tmp.remove();
  1319. });
  1320. } else {
  1321. $body.html(body);
  1322. }
  1323. config = self.previewZoomSettings[tmplt];
  1324. if (config) {
  1325. $dataEl = $body.find('.kv-preview-data');
  1326. $h.addCss($dataEl, 'file-zoom-detail');
  1327. $.each(config, function (key, value) {
  1328. $dataEl.css(key, value);
  1329. if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
  1330. $dataEl.removeAttr(key);
  1331. }
  1332. });
  1333. }
  1334. $modal.data('previewId', pid);
  1335. $h.handler($prev, 'click', function () {
  1336. self._zoomSlideShow('prev', pid);
  1337. });
  1338. $h.handler($next, 'click', function () {
  1339. self._zoomSlideShow('next', pid);
  1340. });
  1341. $h.handler($btnFull, 'click', function () {
  1342. self._resizeZoomDialog(true);
  1343. });
  1344. $h.handler($btnBord, 'click', function () {
  1345. self._resizeZoomDialog(false);
  1346. });
  1347. $h.handler($btnTogh, 'click', function () {
  1348. var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'),
  1349. ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
  1350. var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
  1351. if ($modal.hasClass('file-zoom-fullscreen')) {
  1352. h = $body.outerHeight(true);
  1353. if (!height) {
  1354. h = h - $header.outerHeight(true);
  1355. }
  1356. }
  1357. $body.css('height', height ? h + height : h);
  1358. };
  1359. if ($header.is(':visible')) {
  1360. ht = $header.outerHeight(true);
  1361. $header.slideUp('slow', function () {
  1362. $actions.find('.btn').appendTo($floatBar);
  1363. resize(ht);
  1364. });
  1365. } else {
  1366. $floatBar.find('.btn').appendTo($actions);
  1367. $header.slideDown('slow', function () {
  1368. resize();
  1369. });
  1370. }
  1371. $modal.focus();
  1372. });
  1373. $h.handler($modal, 'keydown', function (e) {
  1374. var key = e.which || e.keyCode;
  1375. if (key === 37 && !$prev.attr('disabled')) {
  1376. self._zoomSlideShow('prev', pid);
  1377. }
  1378. if (key === 39 && !$next.attr('disabled')) {
  1379. self._zoomSlideShow('next', pid);
  1380. }
  1381. });
  1382. },
  1383. _zoomPreview: function ($btn) {
  1384. var self = this, $frame, $modal = self.$modal;
  1385. if (!$btn.length) {
  1386. throw 'Cannot zoom to detailed preview!';
  1387. }
  1388. $h.initModal($modal);
  1389. $modal.html(self._getModalContent());
  1390. $frame = $btn.closest($h.FRAMES);
  1391. self._setZoomContent($frame);
  1392. $modal.modal('show');
  1393. self._initZoomButtons();
  1394. },
  1395. _zoomSlideShow: function (dir, previewId) {
  1396. var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i,
  1397. thumbs = self.$preview.find($h.FRAMES).toArray(), len = thumbs.length, out;
  1398. if ($btn.attr('disabled')) {
  1399. return;
  1400. }
  1401. for (i = 0; i < len; i++) {
  1402. if ($(thumbs[i]).attr('id') === previewId) {
  1403. out = dir === 'prev' ? i - 1 : i + 1;
  1404. break;
  1405. }
  1406. }
  1407. if (out < 0 || out >= len || !thumbs[out]) {
  1408. return;
  1409. }
  1410. $targFrame = $(thumbs[out]);
  1411. if ($targFrame.length) {
  1412. self._setZoomContent($targFrame, true);
  1413. }
  1414. self._initZoomButtons();
  1415. self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
  1416. },
  1417. _initZoomButton: function () {
  1418. var self = this;
  1419. self.$preview.find('.kv-file-zoom').each(function () {
  1420. var $el = $(this);
  1421. $h.handler($el, 'click', function () {
  1422. self._zoomPreview($el);
  1423. });
  1424. });
  1425. },
  1426. _initPreviewActions: function () {
  1427. var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {},
  1428. btnRemove = $h.FRAMES + ' .kv-file-remove',
  1429. resetProgress = function () {
  1430. var hasFiles = self.isUploadable ? self.previewCache.count() : self.$element.get(0).files.length;
  1431. if ($preview.find(btnRemove).length === 0 && !hasFiles) {
  1432. self.reset();
  1433. self.initialCaption = '';
  1434. }
  1435. };
  1436. self._initZoomButton();
  1437. $preview.find(btnRemove).each(function () {
  1438. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key');
  1439. if ($h.isEmpty(vUrl) || vKey === undefined) {
  1440. return;
  1441. }
  1442. var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data,
  1443. settings, params, index = $frame.data('fileindex'), config, extraData;
  1444. index = parseInt(index.replace('init_', ''));
  1445. config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index];
  1446. extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra;
  1447. if (typeof extraData === "function") {
  1448. extraData = extraData();
  1449. }
  1450. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  1451. settings = $.extend(true, {}, {
  1452. url: vUrl,
  1453. type: 'POST',
  1454. dataType: 'json',
  1455. data: $.extend(true, {}, {key: vKey}, extraData),
  1456. beforeSend: function (jqXHR) {
  1457. self.ajaxAborted = false;
  1458. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  1459. if (self.ajaxAborted) {
  1460. jqXHR.abort();
  1461. } else {
  1462. $h.addCss($frame, 'file-uploading');
  1463. $h.addCss($el, 'disabled');
  1464. }
  1465. },
  1466. success: function (data, textStatus, jqXHR) {
  1467. var n, cap;
  1468. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  1469. self.previewCache.init();
  1470. index = parseInt(($frame.data('fileindex')).replace('init_', ''));
  1471. self.previewCache.unset(index);
  1472. n = self.previewCache.count();
  1473. cap = n > 0 ? self._getMsgSelected(n) : '';
  1474. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  1475. self._setCaption(cap);
  1476. } else {
  1477. params.jqXHR = jqXHR;
  1478. params.response = data;
  1479. self._showError(data.error, params, 'filedeleteerror');
  1480. $frame.removeClass('file-uploading');
  1481. $el.removeClass('disabled');
  1482. resetProgress();
  1483. return;
  1484. }
  1485. $frame.removeClass('file-uploading').addClass('file-deleted');
  1486. $frame.fadeOut('slow', function () {
  1487. $h.cleanZoomCache($preview.find('#zoom-' + $frame.attr('id')));
  1488. self._clearObjects($frame);
  1489. $frame.remove();
  1490. resetProgress();
  1491. if (!n && self.getFileStack().length === 0) {
  1492. self._setCaption('');
  1493. self.reset();
  1494. }
  1495. });
  1496. },
  1497. error: function (jqXHR, textStatus, errorThrown) {
  1498. var op = self.ajaxOperations.deleteThumb, errMsg = self._parseError(op, jqXHR, errorThrown);
  1499. params.jqXHR = jqXHR;
  1500. params.response = {};
  1501. self._showError(errMsg, params, 'filedeleteerror');
  1502. $frame.removeClass('file-uploading');
  1503. resetProgress();
  1504. }
  1505. }, self.ajaxDeleteSettings);
  1506. $h.handler($el, 'click', function () {
  1507. if (!self._validateMinCount()) {
  1508. return false;
  1509. }
  1510. $.ajax(settings);
  1511. });
  1512. });
  1513. },
  1514. _clearObjects: function ($el) {
  1515. $el.find('video audio').each(function () {
  1516. this.pause();
  1517. $(this).remove();
  1518. });
  1519. $el.find('img object div').each(function () {
  1520. $(this).remove();
  1521. });
  1522. },
  1523. _clearFileInput: function () {
  1524. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1525. self.fileInputCleared = true;
  1526. if ($h.isEmpty($el.val())) {
  1527. return;
  1528. }
  1529. // Fix for IE ver < 11, that does not clear file inputs. Requires a sequence of steps to prevent IE
  1530. // crashing but still allow clearing of the file input.
  1531. if (self.isIE9 || self.isIE10) {
  1532. $srcFrm = $el.closest('form');
  1533. $tmpFrm = $(document.createElement('form'));
  1534. $tmpEl = $(document.createElement('div'));
  1535. $el.before($tmpEl);
  1536. if ($srcFrm.length) {
  1537. $srcFrm.after($tmpFrm);
  1538. } else {
  1539. $tmpEl.after($tmpFrm);
  1540. }
  1541. $tmpFrm.append($el).trigger('reset');
  1542. $tmpEl.before($el).remove();
  1543. $tmpFrm.remove();
  1544. } else { // normal input clear behavior for other sane browsers
  1545. $el.val('');
  1546. }
  1547. },
  1548. _resetUpload: function () {
  1549. var self = this;
  1550. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1551. self.uploadCount = 0;
  1552. self.uploadStatus = {};
  1553. self.uploadLog = [];
  1554. self.uploadAsyncCount = 0;
  1555. self.loadedImages = [];
  1556. self.totalImagesCount = 0;
  1557. self.$btnUpload.removeAttr('disabled');
  1558. self._setProgress(0);
  1559. $h.addCss(self.$progress, 'hide');
  1560. self._resetErrors(false);
  1561. self.ajaxAborted = false;
  1562. self.ajaxRequests = [];
  1563. self._resetCanvas();
  1564. self.cacheInitialPreview = {};
  1565. },
  1566. _resetCanvas: function () {
  1567. var self = this;
  1568. if (self.canvas && self.imageCanvasContext) {
  1569. self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
  1570. }
  1571. },
  1572. _hasInitialPreview: function () {
  1573. var self = this;
  1574. return !self.overwriteInitial && self.previewCache.count();
  1575. },
  1576. _resetPreview: function () {
  1577. var self = this, out, cap;
  1578. if (self.previewCache.count()) {
  1579. out = self.previewCache.out();
  1580. self.$preview.html(out.content);
  1581. self._setInitThumbAttr();
  1582. cap = self.initialCaption ? self.initialCaption : out.caption;
  1583. self._setCaption(cap);
  1584. } else {
  1585. self._clearPreview();
  1586. self._initCaption();
  1587. }
  1588. if (self.showPreview) {
  1589. self._initZoom();
  1590. self._initSortable();
  1591. }
  1592. },
  1593. _clearDefaultPreview: function () {
  1594. var self = this;
  1595. self.$preview.find('.file-default-preview').remove();
  1596. },
  1597. _validateDefaultPreview: function () {
  1598. var self = this;
  1599. if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) {
  1600. return;
  1601. }
  1602. self.$preview.html('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  1603. self.$container.removeClass('file-input-new');
  1604. self._initClickable();
  1605. },
  1606. _resetPreviewThumbs: function (isAjax) {
  1607. var self = this, out;
  1608. if (isAjax) {
  1609. self._clearPreview();
  1610. self.clearStack();
  1611. return;
  1612. }
  1613. if (self._hasInitialPreview()) {
  1614. out = self.previewCache.out();
  1615. self.$preview.html(out.content);
  1616. self._setInitThumbAttr();
  1617. self._setCaption(out.caption);
  1618. self._initPreviewActions();
  1619. } else {
  1620. self._clearPreview();
  1621. }
  1622. },
  1623. _getLayoutTemplate: function (t) {
  1624. var self = this, template = self.layoutTemplates[t];
  1625. if ($h.isEmpty(self.customLayoutTags)) {
  1626. return template;
  1627. }
  1628. return $h.replaceTags(template, self.customLayoutTags);
  1629. },
  1630. _getPreviewTemplate: function (t) {
  1631. var self = this, template = self.previewTemplates[t];
  1632. if ($h.isEmpty(self.customPreviewTags)) {
  1633. return template;
  1634. }
  1635. return $h.replaceTags(template, self.customPreviewTags);
  1636. },
  1637. _getOutData: function (jqXHR, responseData, filesData) {
  1638. var self = this;
  1639. jqXHR = jqXHR || {};
  1640. responseData = responseData || {};
  1641. filesData = filesData || self.filestack.slice(0) || {};
  1642. return {
  1643. form: self.formdata,
  1644. files: filesData,
  1645. filenames: self.filenames,
  1646. filescount: self.getFilesCount(),
  1647. extra: self._getExtraData(),
  1648. response: responseData,
  1649. reader: self.reader,
  1650. jqXHR: jqXHR
  1651. };
  1652. },
  1653. _getMsgSelected: function (n) {
  1654. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  1655. return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected;
  1656. },
  1657. _getThumbs: function (css) {
  1658. css = css || '';
  1659. return this.$preview.find($h.FRAMES + ':not(.file-preview-initial)' + css);
  1660. },
  1661. _getExtraData: function (previewId, index) {
  1662. var self = this, data = self.uploadExtraData;
  1663. if (typeof self.uploadExtraData === "function") {
  1664. data = self.uploadExtraData(previewId, index);
  1665. }
  1666. return data;
  1667. },
  1668. _initXhr: function (xhrobj, previewId, fileCount) {
  1669. var self = this;
  1670. if (xhrobj.upload) {
  1671. xhrobj.upload.addEventListener('progress', function (event) {
  1672. var pct = 0, total = event.total, position = event.loaded || event.position;
  1673. /** @namespace event.lengthComputable */
  1674. if (event.lengthComputable) {
  1675. pct = Math.floor(position / total * 100);
  1676. }
  1677. if (previewId) {
  1678. self._setAsyncUploadStatus(previewId, pct, fileCount);
  1679. } else {
  1680. self._setProgress(pct);
  1681. }
  1682. }, false);
  1683. }
  1684. return xhrobj;
  1685. },
  1686. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  1687. var self = this, settings;
  1688. if (!self._raise('filepreajax', [previewId, index])) {
  1689. return;
  1690. }
  1691. self._uploadExtra(previewId, index);
  1692. settings = $.extend(true, {}, {
  1693. xhr: function () {
  1694. var xhrobj = $.ajaxSettings.xhr();
  1695. return self._initXhr(xhrobj, previewId, self.getFileStack().length);
  1696. },
  1697. url: self.uploadUrl,
  1698. type: 'POST',
  1699. dataType: 'json',
  1700. data: self.formdata,
  1701. cache: false,
  1702. processData: false,
  1703. contentType: false,
  1704. beforeSend: fnBefore,
  1705. success: fnSuccess,
  1706. complete: fnComplete,
  1707. error: fnError
  1708. }, self.ajaxSettings);
  1709. self.ajaxRequests.push($.ajax(settings));
  1710. },
  1711. _initUploadSuccess: function (out, $thumb, allFiles) {
  1712. var self = this, append, data, index, $div, $newCache, content, config, tags, i,
  1713. mergeArray = function (prop, content) {
  1714. if (!(self[prop] instanceof Array)) {
  1715. self[prop] = [];
  1716. }
  1717. if (content && content.length) {
  1718. self[prop] = self[prop].concat(content);
  1719. }
  1720. };
  1721. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  1722. return;
  1723. }
  1724. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1725. self.hasInitData = true;
  1726. content = out.initialPreview || [];
  1727. config = out.initialPreviewConfig || [];
  1728. tags = out.initialPreviewThumbTags || [];
  1729. append = out.append === undefined || out.append ? true : false;
  1730. if (content.length > 0 && !$h.isArray(content)) {
  1731. content = content.split(self.initialPreviewDelimiter);
  1732. }
  1733. self.overwriteInitial = false;
  1734. mergeArray('initialPreview', content);
  1735. mergeArray('initialPreviewConfig', config);
  1736. mergeArray('initialPreviewThumbTags', tags);
  1737. if ($thumb !== undefined) {
  1738. if (!allFiles) {
  1739. index = self.previewCache.add(content, config[0], tags[0], append);
  1740. data = self.previewCache.get(index, false);
  1741. $div = $(document.createElement('div')).html(data).hide().insertAfter($thumb);
  1742. $newCache = $div.find('.kv-zoom-cache');
  1743. if ($newCache && $newCache.length) {
  1744. $newCache.insertAfter($thumb);
  1745. }
  1746. $thumb.fadeOut('slow', function () {
  1747. var $newThumb = $div.find('.file-preview-frame');
  1748. if ($newThumb && $newThumb.length) {
  1749. $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');
  1750. }
  1751. self._initPreviewActions();
  1752. self._clearFileInput();
  1753. $h.cleanZoomCache(self.$preview.find('#zoom-' + $thumb.attr('id')));
  1754. $thumb.remove();
  1755. $div.remove();
  1756. self._initSortable();
  1757. });
  1758. } else {
  1759. i = $thumb.attr('data-fileindex');
  1760. self.uploadCache.content[i] = content[0];
  1761. self.uploadCache.config[i] = config[0] || [];
  1762. self.uploadCache.tags[i] = tags[0] || [];
  1763. self.uploadCache.append = append;
  1764. }
  1765. } else {
  1766. self.previewCache.set(content, config, tags, append);
  1767. self._initPreview();
  1768. self._initPreviewActions();
  1769. }
  1770. }
  1771. },
  1772. _initSuccessThumbs: function () {
  1773. var self = this;
  1774. if (!self.showPreview) {
  1775. return;
  1776. }
  1777. self._getThumbs($h.FRAMES + ' .file-preview-success').each(function () {
  1778. var $thumb = $(this), $preview = self.$preview, $remove = $thumb.find('.kv-file-remove');
  1779. $remove.removeAttr('disabled');
  1780. $h.handler($remove, 'click', function () {
  1781. var id = $thumb.attr('id'), out = self._raise('filesuccessremove', [id, $thumb.data('fileindex')]);
  1782. $h.cleanMemory($thumb);
  1783. if (out === false) {
  1784. return;
  1785. }
  1786. $thumb.fadeOut('slow', function () {
  1787. $h.cleanZoomCache($preview.find('#zoom-' + id));
  1788. $thumb.remove();
  1789. if (!$preview.find($h.FRAMES).length) {
  1790. self.reset();
  1791. }
  1792. });
  1793. });
  1794. });
  1795. },
  1796. _checkAsyncComplete: function () {
  1797. var self = this, previewId, i;
  1798. for (i = 0; i < self.filestack.length; i++) {
  1799. if (self.filestack[i]) {
  1800. previewId = self.previewInitId + "-" + i;
  1801. if ($.inArray(previewId, self.uploadLog) === -1) {
  1802. return false;
  1803. }
  1804. }
  1805. }
  1806. return (self.uploadAsyncCount === self.uploadLog.length);
  1807. },
  1808. _uploadExtra: function (previewId, index) {
  1809. var self = this, data = self._getExtraData(previewId, index);
  1810. if (data.length === 0) {
  1811. return;
  1812. }
  1813. $.each(data, function (key, value) {
  1814. self.formdata.append(key, value);
  1815. });
  1816. },
  1817. _uploadSingle: function (i, files, allFiles) {
  1818. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1819. previewId = self.previewInitId + "-" + i, $thumb, chkComplete, $btnUpload, $btnDelete,
  1820. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1821. $prog = $('#' + previewId).find('.file-thumb-progress'),
  1822. fnBefore, fnSuccess, fnComplete, fnError, updateUploadLog, params = {id: previewId, index: i};
  1823. self.formdata = formdata;
  1824. if (self.showPreview) {
  1825. $thumb = $('#' + previewId + ':not(.file-preview-initial)');
  1826. $btnUpload = $thumb.find('.kv-file-upload');
  1827. $btnDelete = $thumb.find('.kv-file-remove');
  1828. $prog.removeClass('hide');
  1829. }
  1830. if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self._abort(params)) {
  1831. return;
  1832. }
  1833. updateUploadLog = function (i, previewId) {
  1834. self.updateStack(i, undefined);
  1835. self.uploadLog.push(previewId);
  1836. if (self._checkAsyncComplete()) {
  1837. self.fileBatchCompleted = true;
  1838. }
  1839. };
  1840. chkComplete = function () {
  1841. var u = self.uploadCache, $initThumbs, i, j, len, data = self.cacheInitialPreview;
  1842. if (!self.fileBatchCompleted) {
  1843. return;
  1844. }
  1845. setTimeout(function () {
  1846. if (self.showPreview) {
  1847. self.previewCache.set(u.content, u.config, u.tags, u.append);
  1848. len = data && data.content ? data.content.length : 0;
  1849. if (len) {
  1850. for (i = 0; i < u.content.length; i++) {
  1851. j = i + len;
  1852. data.content[j] = u.content[i];
  1853. if (data.config.length) {
  1854. data.config[j] = u.config[i];
  1855. }
  1856. if (data.tags.length) {
  1857. data.tags[j] = u.tags[i];
  1858. }
  1859. }
  1860. self.initialPreview = data.content;
  1861. self.initialPreviewConfig = data.config;
  1862. self.initialPreviewThumbTags = data.tags;
  1863. } else {
  1864. self.initialPreview = u.content;
  1865. self.initialPreviewConfig = u.config;
  1866. self.initialPreviewThumbTags = u.tags;
  1867. }
  1868. self.cacheInitialPreview = {};
  1869. if (self.hasInitData) {
  1870. self._initPreview();
  1871. self._initPreviewActions();
  1872. }
  1873. }
  1874. self.unlock();
  1875. self._clearFileInput();
  1876. $initThumbs = self.$preview.find('.file-preview-initial');
  1877. if (self.uploadAsync && $initThumbs.length) {
  1878. $h.addCss($initThumbs, $h.SORT_CSS);
  1879. self._initSortable();
  1880. }
  1881. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1882. self.uploadCount = 0;
  1883. self.uploadStatus = {};
  1884. self.uploadLog = [];
  1885. self._setProgress(101);
  1886. }, 100);
  1887. };
  1888. fnBefore = function (jqXHR) {
  1889. outData = self._getOutData(jqXHR);
  1890. self.fileBatchCompleted = false;
  1891. if (self.showPreview) {
  1892. if (!$thumb.hasClass('file-preview-success')) {
  1893. self._setThumbStatus($thumb, 'Loading');
  1894. $h.addCss($thumb, 'file-uploading');
  1895. }
  1896. $btnUpload.attr('disabled', true);
  1897. $btnDelete.attr('disabled', true);
  1898. }
  1899. if (!allFiles) {
  1900. self.lock();
  1901. }
  1902. self._raise('filepreupload', [outData, previewId, i]);
  1903. $.extend(true, params, outData);
  1904. if (self._abort(params)) {
  1905. jqXHR.abort();
  1906. self._setProgressCancelled();
  1907. }
  1908. };
  1909. fnSuccess = function (data, textStatus, jqXHR) {
  1910. var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
  1911. outData = self._getOutData(jqXHR, data);
  1912. $.extend(true, params, outData);
  1913. setTimeout(function () {
  1914. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  1915. if (self.showPreview) {
  1916. self._setThumbStatus($thumb, 'Success');
  1917. $btnUpload.hide();
  1918. self._initUploadSuccess(data, $thumb, allFiles);
  1919. self._setProgress(101, $prog);
  1920. }
  1921. self._raise('fileuploaded', [outData, pid, i]);
  1922. if (!allFiles) {
  1923. self.updateStack(i, undefined);
  1924. } else {
  1925. updateUploadLog(i, pid);
  1926. }
  1927. } else {
  1928. self._showUploadError(data.error, params);
  1929. self._setPreviewError($thumb, i);
  1930. if (allFiles) {
  1931. updateUploadLog(i, pid);
  1932. }
  1933. }
  1934. }, 100);
  1935. };
  1936. fnComplete = function () {
  1937. setTimeout(function () {
  1938. if (self.showPreview) {
  1939. $btnUpload.removeAttr('disabled');
  1940. $btnDelete.removeAttr('disabled');
  1941. $thumb.removeClass('file-uploading');
  1942. }
  1943. if (!allFiles) {
  1944. self.unlock(false);
  1945. self._clearFileInput();
  1946. } else {
  1947. chkComplete();
  1948. }
  1949. self._initSuccessThumbs();
  1950. }, 100);
  1951. };
  1952. fnError = function (jqXHR, textStatus, errorThrown) {
  1953. var op = self.ajaxOperations.uploadThumb,
  1954. errMsg = self._parseError(op, jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1955. setTimeout(function () {
  1956. if (allFiles) {
  1957. updateUploadLog(i, previewId);
  1958. }
  1959. self.uploadStatus[previewId] = 100;
  1960. self._setPreviewError($thumb, i);
  1961. $.extend(true, params, self._getOutData(jqXHR));
  1962. self._setProgress(101, $prog, self.msgAjaxProgressError.replace('{operation}', op));
  1963. self._showUploadError(errMsg, params);
  1964. }, 100);
  1965. };
  1966. formdata.append(self.uploadFileAttr, files[i], self.filenames[i]);
  1967. formdata.append('file_id', i);
  1968. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  1969. },
  1970. _uploadBatch: function () {
  1971. var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError,
  1972. fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1973. setAllUploaded;
  1974. self.formdata = new FormData();
  1975. if (total === 0 || !hasPostData || self._abort(params)) {
  1976. return;
  1977. }
  1978. setAllUploaded = function () {
  1979. $.each(files, function (key) {
  1980. self.updateStack(key, undefined);
  1981. });
  1982. self._clearFileInput();
  1983. };
  1984. fnBefore = function (jqXHR) {
  1985. self.lock();
  1986. var outData = self._getOutData(jqXHR);
  1987. if (self.showPreview) {
  1988. self._getThumbs().each(function () {
  1989. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1990. $btnDelete = $thumb.find('.kv-file-remove');
  1991. if (!$thumb.hasClass('file-preview-success')) {
  1992. self._setThumbStatus($thumb, 'Loading');
  1993. $h.addCss($thumb, 'file-uploading');
  1994. }
  1995. $btnUpload.attr('disabled', true);
  1996. $btnDelete.attr('disabled', true);
  1997. });
  1998. }
  1999. self._raise('filebatchpreupload', [outData]);
  2000. if (self._abort(outData)) {
  2001. jqXHR.abort();
  2002. self._setProgressCancelled();
  2003. }
  2004. };
  2005. fnSuccess = function (data, textStatus, jqXHR) {
  2006. /** @namespace data.errorkeys */
  2007. var outData = self._getOutData(jqXHR, data), $thumbs = self._getThumbs(':not(.file-preview-error)'), key = 0,
  2008. keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys;
  2009. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2010. self._raise('filebatchuploadsuccess', [outData]);
  2011. setAllUploaded();
  2012. if (self.showPreview) {
  2013. $thumbs.each(function () {
  2014. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  2015. $thumb.find('.kv-file-upload').hide();
  2016. self._setThumbStatus($thumb, 'Success');
  2017. $thumb.removeClass('file-uploading');
  2018. $btnUpload.removeAttr('disabled');
  2019. });
  2020. self._initUploadSuccess(data);
  2021. } else {
  2022. self.reset();
  2023. }
  2024. self._setProgress(101);
  2025. } else {
  2026. if (self.showPreview) {
  2027. $thumbs.each(function () {
  2028. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  2029. $btnUpload = $thumb.find('.kv-file-upload');
  2030. $thumb.removeClass('file-uploading');
  2031. $btnUpload.removeAttr('disabled');
  2032. $btnDelete.removeAttr('disabled');
  2033. if (keys.length === 0) {
  2034. self._setPreviewError($thumb);
  2035. return;
  2036. }
  2037. if ($.inArray(key, keys) !== -1) {
  2038. self._setPreviewError($thumb);
  2039. } else {
  2040. $thumb.find('.kv-file-upload').hide();
  2041. self._setThumbStatus($thumb, 'Success');
  2042. self.updateStack(key, undefined);
  2043. }
  2044. key++;
  2045. });
  2046. self._initUploadSuccess(data);
  2047. }
  2048. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  2049. }
  2050. };
  2051. fnComplete = function () {
  2052. self.unlock();
  2053. self._initSuccessThumbs();
  2054. self._clearFileInput();
  2055. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2056. };
  2057. fnError = function (jqXHR, textStatus, errorThrown) {
  2058. var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadBatch,
  2059. errMsg = self._parseError(op, jqXHR, errorThrown);
  2060. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2061. self.uploadFileCount = total - 1;
  2062. if (!self.showPreview) {
  2063. return;
  2064. }
  2065. self._getThumbs().each(function () {
  2066. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  2067. $thumb.removeClass('file-uploading');
  2068. if (self.filestack[key] !== undefined) {
  2069. self._setPreviewError($thumb);
  2070. }
  2071. });
  2072. self._getThumbs().removeClass('file-uploading');
  2073. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  2074. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  2075. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  2076. };
  2077. $.each(files, function (key, data) {
  2078. if (!$h.isEmpty(files[key])) {
  2079. self.formdata.append(self.uploadFileAttr, data, self.filenames[key]);
  2080. }
  2081. });
  2082. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2083. },
  2084. _uploadExtraOnly: function () {
  2085. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  2086. self.formdata = new FormData();
  2087. if (self._abort(params)) {
  2088. return;
  2089. }
  2090. fnBefore = function (jqXHR) {
  2091. self.lock();
  2092. var outData = self._getOutData(jqXHR);
  2093. self._raise('filebatchpreupload', [outData]);
  2094. self._setProgress(50);
  2095. params.data = outData;
  2096. params.xhr = jqXHR;
  2097. if (self._abort(params)) {
  2098. jqXHR.abort();
  2099. self._setProgressCancelled();
  2100. }
  2101. };
  2102. fnSuccess = function (data, textStatus, jqXHR) {
  2103. var outData = self._getOutData(jqXHR, data);
  2104. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2105. self._raise('filebatchuploadsuccess', [outData]);
  2106. self._clearFileInput();
  2107. self._initUploadSuccess(data);
  2108. self._setProgress(101);
  2109. } else {
  2110. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  2111. }
  2112. };
  2113. fnComplete = function () {
  2114. self.unlock();
  2115. self._clearFileInput();
  2116. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2117. };
  2118. fnError = function (jqXHR, textStatus, errorThrown) {
  2119. var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadExtra,
  2120. errMsg = self._parseError(op, jqXHR, errorThrown);
  2121. params.data = outData;
  2122. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2123. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  2124. };
  2125. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2126. },
  2127. _initFileActions: function () {
  2128. var self = this, $preview = self.$preview;
  2129. if (!self.showPreview) {
  2130. return;
  2131. }
  2132. self._initZoomButton();
  2133. $preview.find($h.FRAMES + ' .kv-file-remove').each(function () {
  2134. var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'),
  2135. ind = $frame.attr('data-fileindex'), n, cap, status;
  2136. $h.handler($el, 'click', function () {
  2137. status = self._raise('filepreremove', [id, ind]);
  2138. if (status === false || !self._validateMinCount()) {
  2139. return false;
  2140. }
  2141. hasError = $frame.hasClass('file-preview-error');
  2142. $h.cleanMemory($frame);
  2143. $frame.fadeOut('slow', function () {
  2144. $h.cleanZoomCache($preview.find('#zoom-' + id));
  2145. self.updateStack(ind, undefined);
  2146. self._clearObjects($frame);
  2147. $frame.remove();
  2148. if (id && hasError) {
  2149. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () {
  2150. $(this).remove();
  2151. if (!self._errorsExist()) {
  2152. self._resetErrors();
  2153. }
  2154. });
  2155. }
  2156. self._clearFileInput();
  2157. var filestack = self.getFileStack(true), chk = self.previewCache.count(),
  2158. len = filestack.length,
  2159. hasThumb = self.showPreview && $preview.find($h.FRAMES).length;
  2160. if (len === 0 && chk === 0 && !hasThumb) {
  2161. self.reset();
  2162. } else {
  2163. n = chk + len;
  2164. cap = n > 1 ? self._getMsgSelected(n) : (filestack[0] ? self._getFileNames()[0] : '');
  2165. self._setCaption(cap);
  2166. }
  2167. self._raise('fileremoved', [id, ind]);
  2168. });
  2169. });
  2170. });
  2171. self.$preview.find($h.FRAMES + ' .kv-file-upload').each(function () {
  2172. var $el = $(this);
  2173. $h.handler($el, 'click', function () {
  2174. var $frame = $el.closest($h.FRAMES), ind = $frame.attr('data-fileindex');
  2175. if (!$frame.hasClass('file-preview-error')) {
  2176. self._uploadSingle(ind, self.filestack, false);
  2177. }
  2178. });
  2179. });
  2180. },
  2181. _hideFileIcon: function () {
  2182. if (this.overwriteInitial) {
  2183. this.$captionContainer.find('.kv-caption-icon').hide();
  2184. }
  2185. },
  2186. _showFileIcon: function () {
  2187. this.$captionContainer.find('.kv-caption-icon').show();
  2188. },
  2189. _getSize: function (bytes) {
  2190. var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, sizes, out;
  2191. if (!$.isNumeric(bytes) || !$.isNumeric(size)) {
  2192. return '';
  2193. }
  2194. if (typeof func === 'function') {
  2195. out = func(size);
  2196. } else {
  2197. i = Math.floor(Math.log(size) / Math.log(1024));
  2198. sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  2199. out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
  2200. }
  2201. return self._getLayoutTemplate('size').replace('{sizeText}', out);
  2202. },
  2203. _generatePreviewTemplate: function (cat, data, fname, ftype, previewId, isError, size, frameClass, foot, ind, templ) {
  2204. var self = this, caption = self.slug(fname), prevContent, zoomContent = '',
  2205. config = self.previewSettings[cat] || self.defaults.previewSettings[cat],
  2206. w = config && config.width ? config.width : '', h = config && config.height ? config.height : '',
  2207. footer = foot || self._renderFileFooter(caption, size, ($h.isEmpty(w) ? 'auto' : w), isError),
  2208. hasIconSetting = self._getPreviewIcon(fname),
  2209. forcePrevIcon = hasIconSetting && self.preferIconicPreview,
  2210. forceZoomIcon = hasIconSetting && self.preferIconicZoomPreview,
  2211. getContent = function (c, d, zoom, frameCss) {
  2212. var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(c),
  2213. css = (frameClass || '') + ' ' + frameCss;
  2214. if (self.frameClass) {
  2215. css = self.frameClass + ' ' + css;
  2216. }
  2217. if (zoom) {
  2218. css = css.replace(' ' + $h.SORT_CSS, '');
  2219. }
  2220. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  2221. if (c === 'text') {
  2222. d = $h.htmlEncode(d);
  2223. }
  2224. return tmplt.replace(/\{previewId}/g, id).replace(/\{caption}/g, caption)
  2225. .replace(/\{frameClass}/g, css).replace(/\{type}/g, ftype).replace(/\{fileindex}/g, ind)
  2226. .replace(/\{width}/g, w).replace(/\{height}/g, h)
  2227. .replace(/\{footer}/g, footer).replace(/\{data}/g, d).replace(/\{template}/g, templ || cat);
  2228. };
  2229. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  2230. if (self.fileActionSettings.showZoom) {
  2231. zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, 'kv-zoom-thumb');
  2232. }
  2233. zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent);
  2234. prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb');
  2235. return prevContent + zoomContent;
  2236. },
  2237. _previewDefault: function (file, previewId, isDisabled) {
  2238. var self = this, $preview = self.$preview;
  2239. if (!self.showPreview) {
  2240. return;
  2241. }
  2242. var fname = file ? file.name : '', ftype = file ? file.type : '', content, size = file.size,
  2243. caption = self.slug(fname), isError = isDisabled === true && !self.isUploadable,
  2244. data = $h.objUrl.createObjectURL(file);
  2245. self._clearDefaultPreview();
  2246. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, isError, size);
  2247. $preview.append("\n" + content);
  2248. self._setThumbAttr(previewId, caption, size);
  2249. if (isDisabled === true && self.isUploadable) {
  2250. self._setThumbStatus($('#' + previewId), 'Error');
  2251. }
  2252. },
  2253. _previewFile: function (i, file, theFile, previewId, data) {
  2254. if (!this.showPreview) {
  2255. return;
  2256. }
  2257. var self = this, cat = self._parseFileType(file), fname = file ? file.name : '', caption = self.slug(fname),
  2258. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, $preview = self.$preview,
  2259. chkTypes = types && types.indexOf(cat) >= 0, size = file.size,
  2260. iData = (cat === 'text' || cat === 'html' || cat === 'image') ? theFile.target.result : data, content,
  2261. chkMimes = mimes && mimes.indexOf(file.type) !== -1;
  2262. /** @namespace window.DOMPurify */
  2263. if (cat === 'html' && self.purifyHtml && window.DOMPurify) {
  2264. iData = window.DOMPurify.sanitize(iData);
  2265. }
  2266. if (chkTypes || chkMimes) {
  2267. content = self._generatePreviewTemplate(cat, iData, fname, file.type, previewId, false, size);
  2268. self._clearDefaultPreview();
  2269. $preview.append("\n" + content);
  2270. self._validateImage(previewId, caption, file.type);
  2271. } else {
  2272. self._previewDefault(file, previewId);
  2273. }
  2274. self._setThumbAttr(previewId, caption, size);
  2275. self._initSortable();
  2276. },
  2277. _setThumbAttr: function (id, caption, size) {
  2278. var self = this, $frame = $('#' + id);
  2279. if ($frame.length) {
  2280. size = size && size > 0 ? self._getSize(size) : '';
  2281. $frame.data({'caption': caption, 'size': size});
  2282. }
  2283. },
  2284. _setInitThumbAttr: function () {
  2285. var self = this, data = self.previewCache.data, len = self.previewCache.count(true), config,
  2286. caption, size, previewId;
  2287. if (len === 0) {
  2288. return;
  2289. }
  2290. for (var i = 0; i < len; i++) {
  2291. config = data.config[i];
  2292. previewId = self.previewInitId + '-' + 'init_' + i;
  2293. caption = $h.ifSet('caption', config, $h.ifSet('filename', config));
  2294. size = $h.ifSet('size', config);
  2295. self._setThumbAttr(previewId, caption, size);
  2296. }
  2297. },
  2298. _slugDefault: function (text) {
  2299. return $h.isEmpty(text) ? '' : String(text).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  2300. },
  2301. _readFiles: function (files) {
  2302. this.reader = new FileReader();
  2303. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  2304. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  2305. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  2306. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  2307. fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
  2308. fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
  2309. maxPreviewSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize),
  2310. canPreview = $preview.length && (!maxPreviewSize || isNaN(maxPreviewSize)),
  2311. throwError = function (msg, file, previewId, index) {
  2312. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2313. p2 = {id: previewId, index: index, file: file, files: files};
  2314. self._previewDefault(file, previewId, true);
  2315. if (self.isUploadable) {
  2316. self.addToStack(undefined);
  2317. setTimeout(function () {
  2318. readFile(index + 1);
  2319. }, 100);
  2320. }
  2321. self._initFileActions();
  2322. if (self.removeFromPreviewOnError) {
  2323. $('#' + previewId).remove();
  2324. }
  2325. return self.isUploadable ? self._showUploadError(msg, p1) : self._showError(msg, p2);
  2326. };
  2327. self.loadedImages = [];
  2328. self.totalImagesCount = 0;
  2329. $.each(files, function (key, file) {
  2330. var func = self.fileTypeSettings.image;
  2331. if (func && func(file.type)) {
  2332. self.totalImagesCount++;
  2333. }
  2334. });
  2335. readFile = function (i) {
  2336. if ($h.isEmpty($el.attr('multiple'))) {
  2337. numFiles = 1;
  2338. }
  2339. if (i >= numFiles) {
  2340. if (self.isUploadable && self.filestack.length > 0) {
  2341. self._raise('filebatchselected', [self.getFileStack()]);
  2342. } else {
  2343. self._raise('filebatchselected', [files]);
  2344. }
  2345. $container.removeClass('file-thumb-loading');
  2346. $status.html('');
  2347. return;
  2348. }
  2349. var node = ctr + i, previewId = previewInitId + "-" + node, isText, isImage, file = files[i], fSizeKB,
  2350. caption = file.name ? self.slug(file.name) : '', fileSize = (file.size || 0) / 1000, j, msg,
  2351. fileExtExpr = '', previewData = $h.objUrl.createObjectURL(file), typ, chk, typ1, typ2,
  2352. fileCount = 0, strTypes = '', func;
  2353. if (typLen > 0) {
  2354. for (j = 0; j < typLen; j++) {
  2355. typ1 = fileTypes[j];
  2356. typ2 = self.msgFileTypes[typ1] || typ1;
  2357. strTypes += j === 0 ? typ2 : ', ' + typ2;
  2358. }
  2359. }
  2360. if (caption === false) {
  2361. readFile(i + 1);
  2362. return;
  2363. }
  2364. if (caption.length === 0) {
  2365. msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode(file.name));
  2366. self.isError = throwError(msg, file, previewId, i);
  2367. return;
  2368. }
  2369. if (!$h.isEmpty(fileExt)) {
  2370. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  2371. }
  2372. fSizeKB = fileSize.toFixed(2);
  2373. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  2374. msg = self.msgSizeTooLarge.replace('{name}', caption).replace('{size}', fSizeKB)
  2375. .replace('{maxSize}', self.maxFileSize);
  2376. self.isError = throwError(msg, file, previewId, i);
  2377. return;
  2378. }
  2379. if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
  2380. msg = self.msgSizeTooSmall.replace('{name}', caption).replace('{size}', fSizeKB)
  2381. .replace('{minSize}', self.minFileSize);
  2382. self.isError = throwError(msg, file, previewId, i);
  2383. return;
  2384. }
  2385. if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
  2386. for (j = 0; j < fileTypes.length; j += 1) {
  2387. typ = fileTypes[j];
  2388. func = settings[typ];
  2389. fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type, file.name) ? 1 : 0);
  2390. }
  2391. if (fileCount === 0) {
  2392. msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes);
  2393. self.isError = throwError(msg, file, previewId, i);
  2394. return;
  2395. }
  2396. }
  2397. if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
  2398. chk = $h.compare(caption, fileExtExpr);
  2399. fileCount += $h.isEmpty(chk) ? 0 : chk.length;
  2400. if (fileCount === 0) {
  2401. msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}', strExt);
  2402. self.isError = throwError(msg, file, previewId, i);
  2403. return;
  2404. }
  2405. }
  2406. if (!self.showPreview) {
  2407. self.addToStack(file);
  2408. setTimeout(function () {
  2409. readFile(i + 1);
  2410. }, 100);
  2411. self._raise('fileloaded', [file, previewId, i, reader]);
  2412. return;
  2413. }
  2414. if (!canPreview && fileSize > maxPreviewSize) {
  2415. self.addToStack(file);
  2416. $container.addClass('file-thumb-loading');
  2417. self._previewDefault(file, previewId);
  2418. self._initFileActions();
  2419. self._updateFileDetails(numFiles);
  2420. readFile(i + 1);
  2421. return;
  2422. }
  2423. if ($preview.length && FileReader !== undefined) {
  2424. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  2425. $container.addClass('file-thumb-loading');
  2426. reader.onerror = function (evt) {
  2427. self._errorHandler(evt, caption);
  2428. };
  2429. reader.onload = function (theFile) {
  2430. self._previewFile(i, file, theFile, previewId, previewData);
  2431. self._initFileActions();
  2432. };
  2433. reader.onloadend = function () {
  2434. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  2435. .replace('{percent}', 50).replace('{name}', caption);
  2436. setTimeout(function () {
  2437. $status.html(msg);
  2438. self._updateFileDetails(numFiles);
  2439. readFile(i + 1);
  2440. }, 100);
  2441. self._raise('fileloaded', [file, previewId, i, reader]);
  2442. };
  2443. reader.onprogress = function (data) {
  2444. if (data.lengthComputable) {
  2445. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  2446. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  2447. .replace('{percent}', progress).replace('{name}', caption);
  2448. setTimeout(function () {
  2449. $status.html(msg);
  2450. }, 100);
  2451. }
  2452. };
  2453. isText = settings.text;
  2454. isImage = settings.image;
  2455. if (isText(file.type, caption)) {
  2456. reader.readAsText(file, self.textEncoding);
  2457. } else {
  2458. if (isImage(file.type, caption)) {
  2459. reader.readAsDataURL(file);
  2460. } else {
  2461. reader.readAsArrayBuffer(file);
  2462. }
  2463. }
  2464. } else {
  2465. self._previewDefault(file, previewId);
  2466. setTimeout(function () {
  2467. readFile(i + 1);
  2468. self._updateFileDetails(numFiles);
  2469. }, 100);
  2470. self._raise('fileloaded', [file, previewId, i, reader]);
  2471. }
  2472. self.addToStack(file);
  2473. };
  2474. readFile(0);
  2475. self._updateFileDetails(numFiles, false);
  2476. },
  2477. _updateFileDetails: function (numFiles) {
  2478. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  2479. name = ($h.isIE(9) && $h.findFileName($el.val())) ||
  2480. ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '',
  2481. label = self.slug(name), n = self.isUploadable ? fileStack.length : numFiles,
  2482. nFiles = self.previewCache.count() + n, log = n > 1 ? self._getMsgSelected(nFiles) : label;
  2483. if (self.isError) {
  2484. self.$previewContainer.removeClass('file-thumb-loading');
  2485. self.$previewStatus.html('');
  2486. self.$captionContainer.find('.kv-caption-icon').hide();
  2487. } else {
  2488. self._showFileIcon();
  2489. }
  2490. self._setCaption(log, self.isError);
  2491. self.$container.removeClass('file-input-new file-input-ajax-new');
  2492. if (arguments.length === 1) {
  2493. self._raise('fileselect', [numFiles, label]);
  2494. }
  2495. if (self.previewCache.count()) {
  2496. self._initPreviewActions();
  2497. }
  2498. },
  2499. _setThumbStatus: function ($thumb, status) {
  2500. var self = this;
  2501. if (!self.showPreview) {
  2502. return;
  2503. }
  2504. var icon = 'indicator' + status, msg = icon + 'Title',
  2505. css = 'file-preview-' + status.toLowerCase(),
  2506. $indicator = $thumb.find('.file-upload-indicator'),
  2507. config = self.fileActionSettings;
  2508. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  2509. if (status === 'Error') {
  2510. $thumb.find('.kv-file-upload').attr('disabled', true);
  2511. }
  2512. if (status === 'Success') {
  2513. $thumb.find('.file-drag-handle').remove();
  2514. $indicator.css('margin-left', 0);
  2515. }
  2516. $indicator.html(config[icon]);
  2517. $indicator.attr('title', config[msg]);
  2518. $thumb.addClass(css);
  2519. },
  2520. _setProgressCancelled: function () {
  2521. var self = this;
  2522. self._setProgress(101, self.$progress, self.msgCancelled);
  2523. },
  2524. _setProgress: function (p, $el, error) {
  2525. var self = this, pct = Math.min(p, 100), template = pct < 100 ? self.progressTemplate :
  2526. (error ? self.progressErrorTemplate : (p <= 100 ? self.progressTemplate : self.progressCompleteTemplate)),
  2527. pctLimit = self.progressUploadThreshold;
  2528. $el = $el || self.$progress;
  2529. if (!$h.isEmpty(template)) {
  2530. if (pctLimit && pct > pctLimit && p <= 100) {
  2531. var out = template.replace('{percent}', pctLimit).replace('{percent}', pctLimit).replace('{percent}%', self.msgUploadThreshold);
  2532. $el.html(out);
  2533. } else {
  2534. $el.html(template.replace(/\{percent}/g, pct));
  2535. }
  2536. if (error) {
  2537. $el.find('[role="progressbar"]').html(error);
  2538. }
  2539. }
  2540. },
  2541. _setFileDropZoneTitle: function () {
  2542. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  2543. if (self.isClickable) {
  2544. strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  2545. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  2546. }
  2547. $zone.find('.' + self.dropZoneTitleClass).remove();
  2548. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  2549. return;
  2550. }
  2551. if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) {
  2552. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  2553. }
  2554. self.$container.removeClass('file-input-new');
  2555. $h.addCss(self.$container, 'file-input-ajax-new');
  2556. },
  2557. _setAsyncUploadStatus: function (previewId, pct, total) {
  2558. var self = this, sum = 0;
  2559. self._setProgress(pct, $('#' + previewId).find('.file-thumb-progress'));
  2560. self.uploadStatus[previewId] = pct;
  2561. $.each(self.uploadStatus, function (key, value) {
  2562. sum += value;
  2563. });
  2564. self._setProgress(Math.floor(sum / total));
  2565. },
  2566. _validateMinCount: function () {
  2567. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  2568. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  2569. self._noFilesError({});
  2570. return false;
  2571. }
  2572. return true;
  2573. },
  2574. _getFileCount: function (fileCount) {
  2575. var self = this, addCount = 0;
  2576. if (self.validateInitialCount && !self.overwriteInitial) {
  2577. addCount = self.previewCache.count();
  2578. fileCount += addCount;
  2579. }
  2580. return fileCount;
  2581. },
  2582. _getFileName: function (file) {
  2583. return file && file.name ? this.slug(file.name) : undefined;
  2584. },
  2585. _getFileNames: function (skipNull) {
  2586. var self = this;
  2587. return self.filenames.filter(function (n) {
  2588. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2589. });
  2590. },
  2591. _setPreviewError: function ($thumb, i, val) {
  2592. var self = this;
  2593. if (i !== undefined) {
  2594. self.updateStack(i, val);
  2595. }
  2596. if (self.removeFromPreviewOnError) {
  2597. $thumb.remove();
  2598. } else {
  2599. self._setThumbStatus($thumb, 'Error');
  2600. }
  2601. },
  2602. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  2603. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  2604. $imgEl, isValid;
  2605. if ($h.isEmpty(limit) || !$img.length) {
  2606. return;
  2607. }
  2608. $imgEl = $img[0];
  2609. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  2610. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  2611. if (isValid) {
  2612. return;
  2613. }
  2614. msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit);
  2615. self._showUploadError(msg, params);
  2616. self._setPreviewError($thumb, i, null);
  2617. },
  2618. _validateImage: function (previewId, fname, ftype) {
  2619. var self = this, $preview = self.$preview, params, w1, w2, $thumb = $preview.find("#" + previewId),
  2620. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img');
  2621. fname = fname || 'Untitled';
  2622. if (!$img.length) {
  2623. return;
  2624. }
  2625. $h.handler($img, 'load', function () {
  2626. w1 = $thumb.width();
  2627. w2 = $preview.width();
  2628. if (w1 > w2) {
  2629. $img.css('width', '100%');
  2630. $thumb.css('width', '97%');
  2631. }
  2632. params = {ind: i, id: previewId};
  2633. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  2634. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  2635. if (!self.resizeImage) {
  2636. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  2637. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  2638. }
  2639. self._raise('fileimageloaded', [previewId]);
  2640. self.loadedImages.push({ind: i, img: $img, thumb: $thumb, pid: previewId, typ: ftype});
  2641. self._validateAllImages();
  2642. });
  2643. },
  2644. _validateAllImages: function () {
  2645. var self = this, i, counter = {val: 0}, numImgs = self.loadedImages.length;
  2646. if (numImgs !== self.totalImagesCount) {
  2647. return;
  2648. }
  2649. self._raise('fileimagesloaded');
  2650. if (!self.resizeImage) {
  2651. return;
  2652. }
  2653. for (i = 0; i < self.loadedImages.length; i++) {
  2654. self._getResizedImage(self.loadedImages[i], counter, numImgs);
  2655. }
  2656. },
  2657. _getResizedImage: function (config, counter, numImgs) {
  2658. var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight,
  2659. ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  2660. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas,
  2661. context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
  2662. thumb = config.thumb, throwError, msg;
  2663. throwError = function (msg, params, ev) {
  2664. if (self.isUploadable) {
  2665. self._showUploadError(msg, params, ev);
  2666. } else {
  2667. self._showError(msg, params, ev);
  2668. }
  2669. self._setPreviewError(thumb, ind);
  2670. };
  2671. if (!self.filestack[ind] || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  2672. if (isValidImage && self.filestack[ind]) {
  2673. self._raise('fileimageresized', [pid, ind]);
  2674. }
  2675. counter.val++;
  2676. if (counter.val === numImgs) {
  2677. self._raise('fileimagesresized');
  2678. }
  2679. if (!isValidImage) {
  2680. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  2681. return;
  2682. }
  2683. }
  2684. type = type || self.resizeDefaultImageType;
  2685. chkWidth = width > maxWidth;
  2686. chkHeight = height > maxHeight;
  2687. if (self.resizePreference === 'width') {
  2688. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  2689. } else {
  2690. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  2691. }
  2692. self._resetCanvas();
  2693. width *= ratio;
  2694. height *= ratio;
  2695. canvas.width = width;
  2696. canvas.height = height;
  2697. try {
  2698. context.drawImage(img, 0, 0, width, height);
  2699. canvas.toBlob(function (blob) {
  2700. self.filestack[ind] = blob;
  2701. self._raise('fileimageresized', [pid, ind]);
  2702. counter.val++;
  2703. if (counter.val === numImgs) {
  2704. self._raise('fileimagesresized', [undefined, undefined]);
  2705. }
  2706. if (!(blob instanceof Blob)) {
  2707. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  2708. }
  2709. }, type, self.resizeQuality);
  2710. }
  2711. catch (err) {
  2712. counter.val++;
  2713. if (counter.val === numImgs) {
  2714. self._raise('fileimagesresized', [undefined, undefined]);
  2715. }
  2716. msg = self.msgImageResizeException.replace('{errors}', err.message);
  2717. throwError(msg, {id: pid, 'index': ind}, 'fileimageresizeexception');
  2718. }
  2719. },
  2720. _initBrowse: function ($container) {
  2721. var self = this;
  2722. if (self.showBrowse) {
  2723. self.$btnFile = $container.find('.btn-file');
  2724. self.$btnFile.append(self.$element);
  2725. } else {
  2726. self.$element.hide();
  2727. }
  2728. },
  2729. _initCaption: function () {
  2730. var self = this, cap = self.initialCaption || '';
  2731. if (self.overwriteInitial || $h.isEmpty(cap)) {
  2732. self.$caption.html('');
  2733. return false;
  2734. }
  2735. self._setCaption(cap);
  2736. return true;
  2737. },
  2738. _setCaption: function (content, isError) {
  2739. var self = this, title, out, n, cap, stack = self.getFileStack();
  2740. if (!self.$caption.length) {
  2741. return;
  2742. }
  2743. if (isError) {
  2744. title = $('<div>' + self.msgValidationError + '</div>').text();
  2745. n = stack.length;
  2746. if (n) {
  2747. cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n);
  2748. } else {
  2749. cap = self._getMsgSelected(self.msgNo);
  2750. }
  2751. out = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon +
  2752. ($h.isEmpty(content) ? cap : content) + '</span>';
  2753. } else {
  2754. if ($h.isEmpty(content)) {
  2755. return;
  2756. }
  2757. title = $('<div>' + content + '</div>').text();
  2758. out = self._getLayoutTemplate('fileIcon') + title;
  2759. }
  2760. self.$caption.html(out);
  2761. self.$caption.attr('title', title);
  2762. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  2763. },
  2764. _createContainer: function () {
  2765. var self = this, $container = $(document.createElement("div"))
  2766. .attr({"class": 'file-input file-input-new'})
  2767. .html(self._renderMain());
  2768. self.$element.before($container);
  2769. self._initBrowse($container);
  2770. if (self.theme) {
  2771. $container.addClass('theme-' + self.theme);
  2772. }
  2773. return $container;
  2774. },
  2775. _refreshContainer: function () {
  2776. var self = this, $container = self.$container;
  2777. $container.before(self.$element);
  2778. $container.html(self._renderMain());
  2779. self._initBrowse($container);
  2780. },
  2781. _renderMain: function () {
  2782. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : 'file-drop-disabled',
  2783. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  2784. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  2785. .replace(/\{class}/g, self.previewClass)
  2786. .replace(/\{dropClass}/g, dropCss),
  2787. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2788. caption = self.captionTemplate.replace(/\{class}/g, css + ' kv-fileinput-caption');
  2789. return self.mainTemplate.replace(/\{class}/g, self.mainClass +
  2790. (!self.showBrowse && self.showCaption ? ' no-browse' : ''))
  2791. .replace(/\{preview}/g, preview)
  2792. .replace(/\{close}/g, close)
  2793. .replace(/\{caption}/g, caption)
  2794. .replace(/\{upload}/g, self._renderButton('upload'))
  2795. .replace(/\{remove}/g, self._renderButton('remove'))
  2796. .replace(/\{cancel}/g, self._renderButton('cancel'))
  2797. .replace(/\{browse}/g, self._renderButton('browse'));
  2798. },
  2799. _renderButton: function (type) {
  2800. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  2801. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  2802. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  2803. switch (type) {
  2804. case 'remove':
  2805. if (!self.showRemove) {
  2806. return '';
  2807. }
  2808. break;
  2809. case 'cancel':
  2810. if (!self.showCancel) {
  2811. return '';
  2812. }
  2813. css += ' hide';
  2814. break;
  2815. case 'upload':
  2816. if (!self.showUpload) {
  2817. return '';
  2818. }
  2819. if (self.isUploadable && !self.isDisabled) {
  2820. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  2821. } else {
  2822. btnType = 'submit';
  2823. }
  2824. break;
  2825. case 'browse':
  2826. if (!self.showBrowse) {
  2827. return '';
  2828. }
  2829. tmplt = self._getLayoutTemplate('btnBrowse');
  2830. break;
  2831. default:
  2832. return '';
  2833. }
  2834. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  2835. if (!$h.isEmpty(label)) {
  2836. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  2837. }
  2838. return tmplt.replace('{type}', btnType).replace('{css}', css).replace('{title}', title)
  2839. .replace('{status}', status).replace('{icon}', icon).replace('{label}', label);
  2840. },
  2841. _renderThumbProgress: function () {
  2842. return '<div class="file-thumb-progress hide">' + this.progressTemplate.replace(/\{percent}/g,
  2843. '0') + '</div>';
  2844. },
  2845. _renderFileFooter: function (caption, size, width, isError) {
  2846. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  2847. upl = config.showUpload, zoom = config.showZoom, out, template = self._getLayoutTemplate('footer'),
  2848. indicator = isError ? config.indicatorError : config.indicatorNew,
  2849. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle;
  2850. size = self._getSize(size);
  2851. if (self.isUploadable) {
  2852. out = template.replace(/\{actions}/g, self._renderFileActions(upl, rem, zoom, drg, false, false, false))
  2853. .replace(/\{caption}/g, caption).replace(/\{size}/g, size).replace(/\{width}/g, width)
  2854. .replace(/\{progress}/g, self._renderThumbProgress()).replace(/\{indicator}/g, indicator)
  2855. .replace(/\{indicatorTitle}/g, title);
  2856. } else {
  2857. out = template.replace(/\{actions}/g,
  2858. self._renderFileActions(false, false, zoom, drg, false, false, false))
  2859. .replace(/\{caption}/g, caption).replace(/\{size}/g, size).replace(/\{width}/g, width)
  2860. .replace(/\{progress}/g, '').replace(/\{indicator}/g, indicator)
  2861. .replace(/\{indicatorTitle}/g, title);
  2862. }
  2863. out = $h.replaceTags(out, self.previewThumbTags);
  2864. return out;
  2865. },
  2866. _renderFileActions: function (showUpload, showDelete, showZoom, showDrag, disabled, url, key, isInit) {
  2867. if (!showUpload && !showDelete && !showZoom && !showDrag) {
  2868. return '';
  2869. }
  2870. var self = this,
  2871. vUrl = url === false ? '' : ' data-url="' + url + '"',
  2872. vKey = key === false ? '' : ' data-key="' + key + '"',
  2873. btnDelete = '', btnUpload = '', btnZoom = '', btnDrag = '', css,
  2874. template = self._getLayoutTemplate('actions'), config = self.fileActionSettings,
  2875. otherButtons = self.otherActionButtons.replace(/\{dataKey}/g, vKey),
  2876. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  2877. if (showDelete) {
  2878. btnDelete = self._getLayoutTemplate('actionDelete')
  2879. .replace(/\{removeClass}/g, removeClass)
  2880. .replace(/\{removeIcon}/g, config.removeIcon)
  2881. .replace(/\{removeTitle}/g, config.removeTitle)
  2882. .replace(/\{dataUrl}/g, vUrl)
  2883. .replace(/\{dataKey}/g, vKey);
  2884. }
  2885. if (showUpload) {
  2886. btnUpload = self._getLayoutTemplate('actionUpload')
  2887. .replace(/\{uploadClass}/g, config.uploadClass)
  2888. .replace(/\{uploadIcon}/g, config.uploadIcon)
  2889. .replace(/\{uploadTitle}/g, config.uploadTitle);
  2890. }
  2891. if (showZoom) {
  2892. btnZoom = self._getLayoutTemplate('actionZoom')
  2893. .replace(/\{zoomClass}/g, config.zoomClass)
  2894. .replace(/\{zoomIcon}/g, config.zoomIcon)
  2895. .replace(/\{zoomTitle}/g, config.zoomTitle);
  2896. }
  2897. if (showDrag && isInit) {
  2898. css = 'drag-handle-init ' + config.dragClass;
  2899. btnDrag = self._getLayoutTemplate('actionDrag').replace(/\{dragClass}/g, css)
  2900. .replace(/\{dragTitle}/g, config.dragTitle)
  2901. .replace(/\{dragIcon}/g, config.dragIcon);
  2902. }
  2903. return template.replace(/\{delete}/g, btnDelete)
  2904. .replace(/\{upload}/g, btnUpload)
  2905. .replace(/\{zoom}/g, btnZoom)
  2906. .replace(/\{drag}/g, btnDrag)
  2907. .replace(/\{other}/g, otherButtons);
  2908. },
  2909. _browse: function (e) {
  2910. var self = this;
  2911. self._raise('filebrowse');
  2912. if (e && e.isDefaultPrevented()) {
  2913. return;
  2914. }
  2915. if (self.isError && !self.isUploadable) {
  2916. self.clear();
  2917. }
  2918. self.$captionContainer.focus();
  2919. },
  2920. _change: function (e) {
  2921. var self = this, $el = self.$element;
  2922. if (!self.isUploadable && $h.isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  2923. self.fileInputCleared = false;
  2924. return;
  2925. }
  2926. self.fileInputCleared = false;
  2927. var tfiles, msg, total, isDragDrop = arguments.length > 1, isAjaxUpload = self.isUploadable, i = 0, f, n, len,
  2928. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, ctr = self.filestack.length,
  2929. isSingleUpload = $h.isEmpty($el.attr('multiple')), flagSingle = (isSingleUpload && ctr > 0), folders = 0,
  2930. throwError = function (mesg, file, previewId, index) {
  2931. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2932. p2 = {id: previewId, index: index, file: file, files: files};
  2933. return self.isUploadable ? self._showUploadError(mesg, p1) : self._showError(mesg, p2);
  2934. };
  2935. self.reader = null;
  2936. self._resetUpload();
  2937. self._hideFileIcon();
  2938. if (self.isUploadable) {
  2939. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  2940. }
  2941. if (isDragDrop) {
  2942. tfiles = [];
  2943. while (files[i]) {
  2944. f = files[i];
  2945. if (!f.type && f.size % 4096 === 0) {
  2946. folders++;
  2947. } else {
  2948. tfiles.push(f);
  2949. }
  2950. i++;
  2951. }
  2952. } else {
  2953. if (e.target.files === undefined) {
  2954. tfiles = e.target && e.target.value ? [
  2955. {name: e.target.value.replace(/^.+\\/, '')}
  2956. ] : [];
  2957. } else {
  2958. tfiles = e.target.files;
  2959. }
  2960. }
  2961. if ($h.isEmpty(tfiles) || tfiles.length === 0) {
  2962. if (!isAjaxUpload) {
  2963. self.clear();
  2964. }
  2965. self._showFolderError(folders);
  2966. self._raise('fileselectnone');
  2967. return;
  2968. }
  2969. self._resetErrors();
  2970. len = tfiles.length;
  2971. total = self._getFileCount(self.isUploadable ? (self.getFileStack().length + len) : len);
  2972. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  2973. if (!self.autoReplace || len > self.maxFileCount) {
  2974. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  2975. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  2976. self.isError = throwError(msg, null, null, null);
  2977. self.$captionContainer.find('.kv-caption-icon').hide();
  2978. self._setCaption('', true);
  2979. self.$container.removeClass('file-input-new file-input-ajax-new');
  2980. return;
  2981. }
  2982. if (total > self.maxFileCount) {
  2983. self._resetPreviewThumbs(isAjaxUpload);
  2984. }
  2985. } else {
  2986. if (!isAjaxUpload || flagSingle) {
  2987. self._resetPreviewThumbs(false);
  2988. if (flagSingle) {
  2989. self.clearStack();
  2990. }
  2991. } else {
  2992. if (isAjaxUpload && ctr === 0 && (!self.previewCache.count() || self.overwriteInitial)) {
  2993. self._resetPreviewThumbs(true);
  2994. }
  2995. }
  2996. }
  2997. if (self.isPreviewable) {
  2998. self._readFiles(tfiles);
  2999. } else {
  3000. self._updateFileDetails(1);
  3001. }
  3002. self._showFolderError(folders);
  3003. },
  3004. _abort: function (params) {
  3005. var self = this, data;
  3006. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  3007. data = $.extend(true, {}, self._getOutData(), params);
  3008. data.abortData = self.ajaxAborted.data || {};
  3009. data.abortMessage = self.ajaxAborted.message;
  3010. self.cancel();
  3011. self._setProgress(101, self.$progress, self.msgCancelled);
  3012. self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  3013. return true;
  3014. }
  3015. return false;
  3016. },
  3017. _resetFileStack: function () {
  3018. var self = this, i = 0, newstack = [], newnames = [];
  3019. self._getThumbs().each(function () {
  3020. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  3021. file = self.filestack[ind];
  3022. if (ind === -1) {
  3023. return;
  3024. }
  3025. if (file !== undefined) {
  3026. newstack[i] = file;
  3027. newnames[i] = self._getFileName(file);
  3028. $thumb.attr({
  3029. 'id': self.previewInitId + '-' + i,
  3030. 'data-fileindex': i
  3031. });
  3032. i++;
  3033. } else {
  3034. $thumb.attr({
  3035. 'id': 'uploaded-' + $h.uniqId(),
  3036. 'data-fileindex': '-1'
  3037. });
  3038. }
  3039. });
  3040. self.filestack = newstack;
  3041. self.filenames = newnames;
  3042. },
  3043. clearStack: function () {
  3044. var self = this;
  3045. self.filestack = [];
  3046. self.filenames = [];
  3047. return self.$element;
  3048. },
  3049. updateStack: function (i, file) {
  3050. var self = this;
  3051. self.filestack[i] = file;
  3052. self.filenames[i] = self._getFileName(file);
  3053. return self.$element;
  3054. },
  3055. addToStack: function (file) {
  3056. var self = this;
  3057. self.filestack.push(file);
  3058. self.filenames.push(self._getFileName(file));
  3059. return self.$element;
  3060. },
  3061. getFileStack: function (skipNull) {
  3062. var self = this;
  3063. return self.filestack.filter(function (n) {
  3064. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3065. });
  3066. },
  3067. getFilesCount: function () {
  3068. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  3069. return self._getFileCount(len);
  3070. },
  3071. lock: function () {
  3072. var self = this;
  3073. self._resetErrors();
  3074. self.disable();
  3075. if (self.showRemove) {
  3076. $h.addCss(self.$container.find('.fileinput-remove'), 'hide');
  3077. }
  3078. if (self.showCancel) {
  3079. self.$container.find('.fileinput-cancel').removeClass('hide');
  3080. }
  3081. self._raise('filelock', [self.filestack, self._getExtraData()]);
  3082. return self.$element;
  3083. },
  3084. unlock: function (reset) {
  3085. var self = this;
  3086. if (reset === undefined) {
  3087. reset = true;
  3088. }
  3089. self.enable();
  3090. if (self.showCancel) {
  3091. $h.addCss(self.$container.find('.fileinput-cancel'), 'hide');
  3092. }
  3093. if (self.showRemove) {
  3094. self.$container.find('.fileinput-remove').removeClass('hide');
  3095. }
  3096. if (reset) {
  3097. self._resetFileStack();
  3098. }
  3099. self._raise('fileunlock', [self.filestack, self._getExtraData()]);
  3100. return self.$element;
  3101. },
  3102. cancel: function () {
  3103. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  3104. if (len > 0) {
  3105. for (i = 0; i < len; i += 1) {
  3106. self.cancelling = true;
  3107. xhr[i].abort();
  3108. }
  3109. }
  3110. self._setProgressCancelled();
  3111. self._getThumbs().each(function () {
  3112. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  3113. $thumb.removeClass('file-uploading');
  3114. if (self.filestack[ind] !== undefined) {
  3115. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  3116. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  3117. }
  3118. self.unlock();
  3119. });
  3120. return self.$element;
  3121. },
  3122. clear: function () {
  3123. var self = this, cap;
  3124. if (!self._raise('fileclear')) {
  3125. return;
  3126. }
  3127. self.$btnUpload.removeAttr('disabled');
  3128. self._getThumbs().find('video,audio,img').each(function () {
  3129. $h.cleanMemory($(this));
  3130. });
  3131. self._resetUpload();
  3132. self.clearStack();
  3133. self._clearFileInput();
  3134. self._resetErrors(true);
  3135. if (self._hasInitialPreview()) {
  3136. self._showFileIcon();
  3137. self._resetPreview();
  3138. self._initPreviewActions();
  3139. self.$container.removeClass('file-input-new');
  3140. } else {
  3141. self._getThumbs().each(function () {
  3142. self._clearObjects($(this));
  3143. });
  3144. if (self.isUploadable) {
  3145. self.previewCache.data = {};
  3146. }
  3147. self.$preview.html('');
  3148. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  3149. self.$caption.html(cap);
  3150. self.$caption.attr('title', '');
  3151. $h.addCss(self.$container, 'file-input-new');
  3152. self._validateDefaultPreview();
  3153. }
  3154. if (self.$container.find($h.FRAMES).length === 0) {
  3155. if (!self._initCaption()) {
  3156. self.$captionContainer.find('.kv-caption-icon').hide();
  3157. }
  3158. }
  3159. self._hideFileIcon();
  3160. self._raise('filecleared');
  3161. self.$captionContainer.focus();
  3162. self._setFileDropZoneTitle();
  3163. return self.$element;
  3164. },
  3165. reset: function () {
  3166. var self = this;
  3167. if (!self._raise('filereset')) {
  3168. return;
  3169. }
  3170. self._resetPreview();
  3171. self.$container.find('.fileinput-filename').text('');
  3172. $h.addCss(self.$container, 'file-input-new');
  3173. if (self.$preview.find($h.FRAMES).length || self.isUploadable && self.dropZoneEnabled) {
  3174. self.$container.removeClass('file-input-new');
  3175. }
  3176. self._setFileDropZoneTitle();
  3177. self.clearStack();
  3178. self.formdata = {};
  3179. return self.$element;
  3180. },
  3181. disable: function () {
  3182. var self = this;
  3183. self.isDisabled = true;
  3184. self._raise('filedisabled');
  3185. self.$element.attr('disabled', 'disabled');
  3186. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  3187. self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").attr(
  3188. "disabled",
  3189. true);
  3190. self._initDragDrop();
  3191. return self.$element;
  3192. },
  3193. enable: function () {
  3194. var self = this;
  3195. self.isDisabled = false;
  3196. self._raise('fileenabled');
  3197. self.$element.removeAttr('disabled');
  3198. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  3199. self.$container.find(
  3200. ".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled");
  3201. self._initDragDrop();
  3202. return self.$element;
  3203. },
  3204. upload: function () {
  3205. var self = this, totLen = self.getFileStack().length, params = {}, i, outData, len,
  3206. hasExtraData = !$.isEmptyObject(self._getExtraData());
  3207. if (!self.isUploadable || self.isDisabled) {
  3208. return;
  3209. }
  3210. if (self.minFileCount > 0 && self._getFileCount(totLen) < self.minFileCount) {
  3211. self._noFilesError(params);
  3212. return;
  3213. }
  3214. if (totLen === 0 && !hasExtraData) {
  3215. self._resetUpload();
  3216. self._showUploadError(self.msgUploadEmpty);
  3217. return;
  3218. }
  3219. self._resetUpload();
  3220. self.$progress.removeClass('hide');
  3221. self.uploadCount = 0;
  3222. self.uploadStatus = {};
  3223. self.uploadLog = [];
  3224. self.lock();
  3225. self._setProgress(2);
  3226. if (totLen === 0 && hasExtraData) {
  3227. self._uploadExtraOnly();
  3228. return;
  3229. }
  3230. len = self.filestack.length;
  3231. self.hasInitData = false;
  3232. if (self.uploadAsync) {
  3233. outData = self._getOutData();
  3234. self._raise('filebatchpreupload', [outData]);
  3235. self.fileBatchCompleted = false;
  3236. self.uploadCache = {content: [], config: [], tags: [], append: true};
  3237. self.uploadAsyncCount = self.getFileStack().length;
  3238. for (i = 0; i < len; i++) {
  3239. self.uploadCache.content[i] = null;
  3240. self.uploadCache.config[i] = null;
  3241. self.uploadCache.tags[i] = null;
  3242. }
  3243. self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
  3244. self._initSortable();
  3245. self.cacheInitialPreview = {
  3246. content: self.initialPreview,
  3247. config: self.initialPreviewConfig,
  3248. tags: self.initialPreviewThumbTags
  3249. };
  3250. for (i = 0; i < len; i++) {
  3251. if (self.filestack[i] !== undefined) {
  3252. self._uploadSingle(i, self.filestack, true);
  3253. }
  3254. }
  3255. return;
  3256. }
  3257. self._uploadBatch();
  3258. return self.$element;
  3259. },
  3260. destroy: function () {
  3261. var self = this, $form = self.$form, $cont = self.$container, $el = self.$element;
  3262. if ($form && $form.length) {
  3263. $form.off($h.NAMESPACE);
  3264. }
  3265. $el.insertBefore($cont).off($h.NAMESPACE).removeData();
  3266. $cont.off().remove();
  3267. return $el;
  3268. },
  3269. refresh: function (options) {
  3270. var self = this, $el = self.$element;
  3271. options = options ? $.extend(true, {}, self.options, options) : self.options;
  3272. self.destroy();
  3273. $el.fileinput(options);
  3274. if ($el.val()) {
  3275. $el.trigger('change.fileinput');
  3276. }
  3277. return $el;
  3278. }
  3279. };
  3280. $.fn.fileinput = function (option) {
  3281. if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
  3282. return;
  3283. }
  3284. var args = Array.apply(null, arguments), retvals = [];
  3285. args.shift();
  3286. this.each(function () {
  3287. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  3288. theme = options.theme || self.data('theme'), l = {}, t = {},
  3289. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
  3290. if (!data) {
  3291. if (theme) {
  3292. t = $.fn.fileinputThemes[theme] || {};
  3293. }
  3294. if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
  3295. l = $.fn.fileinputLocales[lang] || {};
  3296. }
  3297. opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data());
  3298. data = new FileInput(this, opt);
  3299. self.data('fileinput', data);
  3300. }
  3301. if (typeof option === 'string') {
  3302. retvals.push(data[option].apply(data, args));
  3303. }
  3304. });
  3305. switch (retvals.length) {
  3306. case 0:
  3307. return this;
  3308. case 1:
  3309. return retvals[0];
  3310. default:
  3311. return retvals;
  3312. }
  3313. };
  3314. $.fn.fileinput.defaults = {
  3315. language: 'en',
  3316. showCaption: true,
  3317. showBrowse: true,
  3318. showPreview: true,
  3319. showRemove: true,
  3320. showUpload: true,
  3321. showCancel: true,
  3322. showClose: true,
  3323. showUploadedThumbs: true,
  3324. browseOnZoneClick: false,
  3325. autoReplace: false,
  3326. previewClass: '',
  3327. captionClass: '',
  3328. frameClass: 'krajee-default',
  3329. mainClass: 'file-caption-main',
  3330. mainTemplate: null,
  3331. purifyHtml: true,
  3332. fileSizeGetter: null,
  3333. initialCaption: '',
  3334. initialPreview: [],
  3335. initialPreviewDelimiter: '*$$*',
  3336. initialPreviewAsData: false,
  3337. initialPreviewFileType: 'image',
  3338. initialPreviewConfig: [],
  3339. initialPreviewThumbTags: [],
  3340. previewThumbTags: {},
  3341. initialPreviewShowDelete: true,
  3342. removeFromPreviewOnError: false,
  3343. deleteUrl: '',
  3344. deleteExtraData: {},
  3345. overwriteInitial: true,
  3346. previewZoomButtonIcons: {
  3347. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  3348. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  3349. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  3350. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  3351. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  3352. close: '<i class="glyphicon glyphicon-remove"></i>'
  3353. },
  3354. previewZoomButtonClasses: {
  3355. prev: 'btn btn-navigate',
  3356. next: 'btn btn-navigate',
  3357. toggleheader: 'btn btn-default btn-header-toggle',
  3358. fullscreen: 'btn btn-default',
  3359. borderless: 'btn btn-default',
  3360. close: 'btn btn-default'
  3361. },
  3362. preferIconicPreview: false,
  3363. preferIconicZoomPreview: false,
  3364. allowedPreviewTypes: undefined,
  3365. allowedPreviewMimeTypes: null,
  3366. allowedFileTypes: null,
  3367. allowedFileExtensions: null,
  3368. defaultPreviewContent: null,
  3369. customLayoutTags: {},
  3370. customPreviewTags: {},
  3371. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  3372. previewFileIconClass: 'file-other-icon',
  3373. previewFileIconSettings: {},
  3374. previewFileExtSettings: {},
  3375. buttonLabelClass: 'hidden-xs',
  3376. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  3377. browseClass: 'btn btn-primary',
  3378. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  3379. removeClass: 'btn btn-default',
  3380. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  3381. cancelClass: 'btn btn-default',
  3382. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  3383. uploadClass: 'btn btn-default',
  3384. uploadUrl: null,
  3385. uploadAsync: true,
  3386. uploadExtraData: {},
  3387. zoomModalHeight: 480,
  3388. minImageWidth: null,
  3389. minImageHeight: null,
  3390. maxImageWidth: null,
  3391. maxImageHeight: null,
  3392. resizeImage: false,
  3393. resizePreference: 'width',
  3394. resizeQuality: 0.92,
  3395. resizeDefaultImageType: 'image/jpeg',
  3396. minFileSize: 0,
  3397. maxFileSize: 0,
  3398. maxFilePreviewSize: 25600, // 25 MB
  3399. minFileCount: 0,
  3400. maxFileCount: 0,
  3401. validateInitialCount: false,
  3402. msgValidationErrorClass: 'text-danger',
  3403. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  3404. msgErrorClass: 'file-error-message',
  3405. progressThumbClass: "progress-bar progress-bar-success progress-bar-striped active",
  3406. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  3407. progressCompleteClass: "progress-bar progress-bar-success",
  3408. progressErrorClass: "progress-bar progress-bar-danger",
  3409. progressUploadThreshold: 99,
  3410. previewFileType: 'image',
  3411. elCaptionContainer: null,
  3412. elCaptionText: null,
  3413. elPreviewContainer: null,
  3414. elPreviewImage: null,
  3415. elPreviewStatus: null,
  3416. elErrorContainer: null,
  3417. errorCloseButton: '<span class="close kv-error-close">&times;</span>',
  3418. slugCallback: null,
  3419. dropZoneEnabled: true,
  3420. dropZoneTitleClass: 'file-drop-zone-title',
  3421. fileActionSettings: {},
  3422. otherActionButtons: '',
  3423. textEncoding: 'UTF-8',
  3424. ajaxSettings: {},
  3425. ajaxDeleteSettings: {},
  3426. showAjaxErrorDetails: true
  3427. };
  3428. $.fn.fileinputLocales.en = {
  3429. fileSingle: 'file',
  3430. filePlural: 'files',
  3431. browseLabel: 'Browse &hellip;',
  3432. removeLabel: 'Remove',
  3433. removeTitle: 'Clear selected files',
  3434. cancelLabel: 'Cancel',
  3435. cancelTitle: 'Abort ongoing upload',
  3436. uploadLabel: 'Upload',
  3437. uploadTitle: 'Upload selected files',
  3438. msgNo: 'No',
  3439. msgNoFilesSelected: 'No files selected',
  3440. msgCancelled: 'Cancelled',
  3441. msgZoomModalHeading: 'Detailed Preview',
  3442. msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  3443. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  3444. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  3445. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  3446. msgFileNotFound: 'File "{name}" not found!',
  3447. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  3448. msgFileNotReadable: 'File "{name}" is not readable.',
  3449. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  3450. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  3451. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  3452. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  3453. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  3454. msgFileTypes: {
  3455. 'image': 'image',
  3456. 'html': 'HTML',
  3457. 'text': 'text',
  3458. 'video': 'video',
  3459. 'audio': 'audio',
  3460. 'flash': 'flash',
  3461. 'pdf': 'PDF',
  3462. 'object': 'object'
  3463. },
  3464. msgUploadAborted: 'The file upload was aborted',
  3465. msgUploadThreshold: 'Processing...',
  3466. msgUploadEmpty: 'No valid data available for upload.',
  3467. msgValidationError: 'Validation Error',
  3468. msgLoading: 'Loading file {index} of {files} &hellip;',
  3469. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  3470. msgSelected: '{n} {files} selected',
  3471. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  3472. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  3473. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  3474. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  3475. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  3476. msgImageResizeError: 'Could not get the image dimensions to resize.',
  3477. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  3478. msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  3479. msgAjaxProgressError: '{operation} failed',
  3480. ajaxOperations: {
  3481. deleteThumb: 'file delete',
  3482. uploadThumb: 'single file upload',
  3483. uploadBatch: 'batch file upload',
  3484. uploadExtra: 'form data upload'
  3485. },
  3486. dropZoneTitle: 'Drag & drop files here &hellip;',
  3487. dropZoneClickTitle: '<br>(or click to select {files})',
  3488. previewZoomButtonTitles: {
  3489. prev: 'View previous file',
  3490. next: 'View next file',
  3491. toggleheader: 'Toggle header',
  3492. fullscreen: 'Toggle full screen',
  3493. borderless: 'Toggle borderless mode',
  3494. close: 'Close detailed preview'
  3495. }
  3496. };
  3497. $.fn.fileinput.Constructor = FileInput;
  3498. /**
  3499. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  3500. */
  3501. $(document).ready(function () {
  3502. var $input = $('input.file[type=file]');
  3503. if ($input.length) {
  3504. $input.fileinput();
  3505. }
  3506. });
  3507. }));