fileinput.js 164 KB

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