fileinput.js 163 KB

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