fileinput.js 164 KB

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