From 4142a733b8d5bfb2c72a75eba5fe9a37269bf74b Mon Sep 17 00:00:00 2001 From: RuoYi Date: Sun, 8 Aug 2021 16:48:42 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8D=87=E7=BA=A7bootstrap-fileinput=E5=88=B0?= =?UTF-8?q?=E6=9C=80=E6=96=B0=E7=89=88=E6=9C=AC5.2.3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/common/CommonController.java | 17 +- .../libs/bootstrap-fileinput/fileinput.css | 222 +- .../libs/bootstrap-fileinput/fileinput.js | 12542 ++++++++-------- .../bootstrap-fileinput/fileinput.min.css | 7 +- .../libs/bootstrap-fileinput/fileinput.min.js | 489 +- .../resources/templates/demo/form/upload.html | 7 +- .../src/main/resources/templates/include.html | 4 +- .../ruoyi/common/core/domain/FileInfo.java | 61 - .../com/ruoyi/common/utils/StringUtils.java | 16 + 9 files changed, 7077 insertions(+), 6288 deletions(-) delete mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/core/domain/FileInfo.java diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java index 4cef79e2..f6485960 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java @@ -1,6 +1,5 @@ package com.ruoyi.web.controller.common; -import java.util.LinkedList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -17,7 +16,6 @@ import com.ruoyi.common.config.RuoYiConfig; import com.ruoyi.common.config.ServerConfig; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.domain.FileInfo; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.file.FileUploadUtils; import com.ruoyi.common.utils.file.FileUtils; @@ -35,6 +33,8 @@ public class CommonController @Autowired private ServerConfig serverConfig; + private static final String FILE_DELIMETER = ","; + /** * 通用下载请求 * @@ -101,17 +101,22 @@ public class CommonController { try { - // 上传文件路径 + // 上传文件路径 String filePath = RuoYiConfig.getUploadPath(); - List fileInfos = new LinkedList(); + String fileNames = ""; + String urls = ""; for (MultipartFile file : files) { // 上传并返回新文件名称 String fileName = FileUploadUtils.upload(filePath, file); String url = serverConfig.getUrl() + fileName; - fileInfos.add(new FileInfo(fileName, url)); + fileNames += fileName + FILE_DELIMETER; + urls += url + FILE_DELIMETER; } - return AjaxResult.success(fileInfos); + AjaxResult ajax = AjaxResult.success(); + ajax.put("fileNames", StringUtils.lastStringDel(fileNames, FILE_DELIMETER)); + ajax.put("urls", StringUtils.lastStringDel(urls, FILE_DELIMETER)); + return ajax; } catch (Exception e) { diff --git a/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.css b/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.css index 05878a34..e5e48de7 100644 --- a/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.css +++ b/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.css @@ -1,16 +1,18 @@ /*! - * bootstrap-fileinput v5.1.3 + * bootstrap-fileinput v5.2.3 * http://plugins.krajee.com/file-input * * Krajee default styling for bootstrap-fileinput. * * Author: Kartik Visweswaran - * Copyright: 2014 - 2020, Kartik Visweswaran, Krajee.com + * Copyright: 2014 - 2021, Kartik Visweswaran, Krajee.com * * Licensed under the BSD-3-Clause * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md */ -.file-loading input[type=file], input[type=file].file-loading { + +.file-loading input[type=file], +input[type=file].file-loading { width: 0; height: 0; } @@ -29,11 +31,31 @@ box-shadow: none; } -.kv-hidden, .file-caption-icon, .file-zoom-dialog .modal-header:before, .file-zoom-dialog .modal-header:after, .file-input-new .file-preview, .file-input-new .close, .file-input-new .glyphicon-file, .file-input-new .fileinput-remove-button, .file-input-new .fileinput-upload-button, .file-input-new .no-browse .input-group-btn, .file-input-ajax-new .fileinput-remove-button, .file-input-ajax-new .fileinput-upload-button, .file-input-ajax-new .no-browse .input-group-btn, .hide-content .kv-file-content, .is-locked .fileinput-upload-button, .is-locked .fileinput-remove-button { +.kv-hidden, +.file-caption-icon, +.file-zoom-dialog .modal-header:before, +.file-zoom-dialog .modal-header:after, +.file-input-new .file-preview, +.file-input-new .close, +.file-input-new .glyphicon-file, +.file-input-new .fileinput-remove-button, +.file-input-new .fileinput-upload-button, +.file-input-new .no-browse .input-group-btn, +.file-input-ajax-new .fileinput-remove-button, +.file-input-ajax-new .fileinput-upload-button, +.file-input-ajax-new .no-browse .input-group-btn, +.hide-content .kv-file-content, +.is-locked .fileinput-upload-button, +.is-locked .fileinput-remove-button { display: none; } -.btn-file input[type=file], .file-caption-icon, .file-preview .fileinput-remove, .krajee-default .file-thumb-progress, .file-zoom-dialog .btn-navigate, .file-zoom-dialog .floating-buttons { +.btn-file input[type=file], +.file-caption-icon, +.file-preview .fileinput-remove, +.krajee-default .file-thumb-progress, +.file-zoom-dialog .btn-navigate, +.file-zoom-dialog .floating-buttons { position: absolute; } @@ -41,35 +63,50 @@ line-height: inherit; } -.file-input, .file-loading:before, .btn-file, .file-caption, .file-preview, .krajee-default.file-preview-frame, .krajee-default .file-thumbnail-footer, .file-zoom-dialog .modal-dialog { +.file-input, +.file-loading:before, +.btn-file, +.file-caption, +.file-preview, +.krajee-default.file-preview-frame, +.krajee-default .file-thumbnail-footer, +.file-zoom-dialog .modal-dialog { position: relative; } -.file-error-message pre, .file-error-message ul, .krajee-default .file-actions, .krajee-default .file-other-error { +.file-error-message pre, +.file-error-message ul, +.krajee-default .file-actions, +.krajee-default .file-other-error { text-align: left; } -.file-error-message pre, .file-error-message ul { +.file-error-message pre, +.file-error-message ul { margin: 0; } -.krajee-default .file-drag-handle, .krajee-default .file-upload-indicator { +.krajee-default .file-drag-handle, +.krajee-default .file-upload-indicator { float: left; margin-top: 10px; width: 16px; height: 16px; } -.file-thumb-progress .progress, .file-thumb-progress .progress-bar { +.file-thumb-progress .progress, +.file-thumb-progress .progress-bar { font-family: Verdana, Helvetica, sans-serif; font-size: 0.7rem; } -.krajee-default .file-thumb-progress .progress, .kv-upload-progress .progress { +.krajee-default .file-thumb-progress .progress, +.kv-upload-progress .progress { background-color: #ccc; } -.krajee-default .file-caption-info, .krajee-default .file-size-info { +.krajee-default .file-caption-info, +.krajee-default .file-size-info { display: block; white-space: nowrap; overflow: hidden; @@ -79,17 +116,23 @@ margin: auto; } -.file-zoom-content > .file-object.type-video, .file-zoom-content > .file-object.type-flash, .file-zoom-content > .file-object.type-image { +.file-zoom-content > .file-object.type-video, +.file-zoom-content > .file-object.type-flash, +.file-zoom-content > .file-object.type-image { max-width: 100%; max-height: 100%; width: auto; } -.file-zoom-content > .file-object.type-video, .file-zoom-content > .file-object.type-flash { +.file-zoom-content > .file-object.type-video, +.file-zoom-content > .file-object.type-flash { height: 100%; } -.file-zoom-content > .file-object.type-pdf, .file-zoom-content > .file-object.type-html, .file-zoom-content > .file-object.type-text, .file-zoom-content > .file-object.type-default { +.file-zoom-content > .file-object.type-pdf, +.file-zoom-content > .file-object.type-html, +.file-zoom-content > .file-object.type-text, +.file-zoom-content > .file-object.type-default { width: 100%; } @@ -131,26 +174,44 @@ height: 100%; } -.file-caption .file-caption-name { - width: 100%; - margin: 0; - padding: 0; - box-shadow: none; - border: none; - background: none; - outline: none; -} - .file-caption.icon-visible .file-caption-icon { display: inline-block; } .file-caption.icon-visible .file-caption-name { - padding-left: 15px; + padding-left: 1.875rem; +} + +.file-caption.icon-visible > .input-group-lg .file-caption-name { + padding-left: 2.1rem; +} + +.file-caption.icon-visible > .input-group-sm .file-caption-name { + padding-left: 1.5rem; +} + +.file-caption-name:not(.file-caption-disabled) { + background-color: transparent; +} + +.file-caption-name.file-processing { + font-style: italic; + border-color: #bbb; + opacity: 0.5; } .file-caption-icon { - left: 8px; + padding: 0.5rem; + left: 4px; +} + +.input-group-lg .file-caption-icon { + font-size: 1.25rem; +} + +.input-group-sm .file-caption-icon { + font-size: 0.875rem; + padding: 0.25rem; } .file-error-message { @@ -200,10 +261,10 @@ .file-preview-image { font: 40px Impact, Charcoal, sans-serif; color: #008000; - width:auto; - height:auto; - max-width:100%; - max-height:100%; + width: auto; + height: auto; + max-width: 100%; + max-height: 100%; } .krajee-default.file-preview-frame { @@ -319,7 +380,9 @@ font-family: Verdana, Helvetica, sans-serif; } + /*noinspection CssOverwrittenProperties*/ + .file-zoom-dialog .file-other-icon { font-size: 22em; font-size: 50vmin; @@ -336,21 +399,18 @@ } .file-zoom-dialog .btn-navigate { + margin: 0 0.1rem; padding: 0; - margin: -60px 0 0; - font-size: 60px; - background: transparent; - text-decoration: none; - outline: none; - opacity: 0.7; + font-size: 1.2rem; + width: 2.4rem; + height: 2.4rem; top: 50%; - color: #1c94c4; + border-radius: 50%; + text-align:center; } -.file-zoom-dialog .btn-navigate:not([disabled]):hover { - outline: none; - box-shadow: none; - opacity: 0.6; +.btn-navigate * { + width: auto; } .file-zoom-dialog .floating-buttons { @@ -358,27 +418,59 @@ right: 10px; } -.file-zoom-dialog .btn-navigate[disabled] { - opacity: 0.3; +.file-zoom-dialog .btn-kv-prev { + left: 0; } -.file-zoom-dialog .btn-prev { - left: 1px; +.file-zoom-dialog .btn-kv-next { + right: 0; } -.file-zoom-dialog .btn-next { - right: 1px; -} - -.file-zoom-dialog .kv-zoom-title { - font-weight: 300; - color: #999; +.file-zoom-dialog .kv-zoom-caption { max-width: 50%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.file-zoom-dialog .kv-zoom-header { + padding: 0.5rem; +} + +.file-zoom-dialog .kv-zoom-body { + padding: 0.25rem 0.5rem 0.25rem 0; +} + +.file-zoom-dialog .kv-zoom-description { + position: absolute; + opacity: 0.8; + font-size: 0.8rem; + background-color: #1a1a1a; + padding: 1rem; + text-align: center; + border-radius: 0.5rem; + color: #fff; + left: 15%; + right: 15%; + bottom: 15%; +} + +.file-zoom-dialog .kv-desc-hide { + float: right; + color: #fff; + padding: 0 0.1rem; + background: none; + border: none; +} + +.file-zoom-dialog .kv-desc-hide:hover { + opacity: 0.7; +} + +.file-zoom-dialog .kv-desc-hide:focus { + opacity: 0.9; +} + .file-input-new .no-browse .form-control { border-top-right-radius: 4px; border-bottom-right-radius: 4px; @@ -389,8 +481,9 @@ border-bottom-right-radius: 4px; } -.file-caption-main { +.file-caption { width: 100%; + position: relative; } .file-thumb-loading { @@ -422,7 +515,7 @@ .file-drop-zone-title { color: #aaa; font-size: 1.6em; - text-align:center; + text-align: center; padding: 85px 10px; cursor: default; } @@ -448,7 +541,7 @@ min-height: 100vh; } -.file-zoom-fullscreen .modal-body { +.file-zoom-fullscreen .kv-zoom-body { overflow-y: auto; } @@ -467,9 +560,23 @@ .file-zoom-content { text-align: center; + white-space: nowrap; min-height: 300px; } +.file-zoom-content:hover { + background: transparent; +} + +.file-zoom-content > * { + display: inline-block; + vertical-align: middle; +} + +.file-zoom-content .kv-spacer { + height: 100%; +} + .file-zoom-content .file-preview-image { max-height: 100%; } @@ -544,7 +651,8 @@ opacity: 1; } -.file-grabbing, .file-grabbing * { +.file-grabbing, +.file-grabbing * { cursor: not-allowed !important; } diff --git a/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.js b/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.js index d7555492..35f0d48f 100644 --- a/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.js +++ b/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.js @@ -1,6150 +1,6392 @@ -/*! - * bootstrap-fileinput v5.1.3 - * http://plugins.krajee.com/file-input - * - * Author: Kartik Visweswaran - * Copyright: 2014 - 2020, Kartik Visweswaran, Krajee.com - * - * Licensed under the BSD-3-Clause - * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md - */ -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - define(['jquery'], factory); - } else { - if (typeof module === 'object' && module.exports) { - //noinspection NpmUsedModulesInstalled - module.exports = factory(require('jquery')); - } else { - factory(window.jQuery); - } - } -}(function ($) { - 'use strict'; - - $.fn.fileinputLocales = {}; - $.fn.fileinputThemes = {}; - - String.prototype.setTokens = function (replacePairs) { - var str = this.toString(), key, re; - for (key in replacePairs) { - if (replacePairs.hasOwnProperty(key)) { - re = new RegExp('\{' + key + '\}', 'g'); - str = str.replace(re, replacePairs[key]); - } - } - return str; - }; - - if (!Array.prototype.flatMap) { // polyfill flatMap - Array.prototype.flatMap = function (lambda) { - return [].concat(this.map(lambda)); - }; - } - - var $h, FileInput; - - // fileinput helper object for all global variables and internal helper methods - $h = { - FRAMES: '.kv-preview-thumb', - SORT_CSS: 'file-sortable', - INIT_FLAG: 'init-', - OBJECT_PARAMS: '\n' + - '\n' + - '\n' + - '\n' + - '\n' + - '\n', - DEFAULT_PREVIEW: '
\n' + - '{previewFileIcon}\n' + - '
', - MODAL_ID: 'kvFileinputModal', - MODAL_EVENTS: ['show', 'shown', 'hide', 'hidden', 'loaded'], - logMessages: { - ajaxError: '{status}: {error}. Error Details: {text}.', - badDroppedFiles: 'Error scanning dropped files!', - badExifParser: 'Error loading the piexif.js library. {details}', - badInputType: 'The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.', - exifWarning: 'To avoid this warning, either set "autoOrientImage" to "false" OR ensure you have loaded ' + - 'the "piexif.js" library correctly on your page before the "fileinput.js" script.', - invalidChunkSize: 'Invalid upload chunk size: "{chunkSize}". Resumable uploads are disabled.', - invalidThumb: 'Invalid thumb frame with id: "{id}".', - noResumableSupport: 'The browser does not support resumable or chunk uploads.', - noUploadUrl: 'The "uploadUrl" is not set. Ajax uploads and resumable uploads have been disabled.', - retryStatus: 'Retrying upload for chunk # {chunk} for {filename}... retry # {retry}.', - chunkQueueError: 'Could not push task to ajax pool for chunk index # {index}.', - resumableMaxRetriesReached: 'Maximum resumable ajax retries ({n}) reached.', - resumableRetryError: 'Could not retry the resumable request (try # {n})... aborting.', - resumableAborting: 'Aborting / cancelling the resumable request.' - - }, - objUrl: window.URL || window.webkitURL, - now: function () { - return new Date().getTime(); - }, - round: function (num) { - num = parseFloat(num); - return isNaN(num) ? 0 : Math.floor(Math.round(num)); - }, - getArray: function (obj) { - var i, arr = [], len = obj && obj.length || 0; - for (i = 0; i < len; i++) { - arr.push(obj[i]); - } - return arr; - }, - getFileRelativePath: function (file) { - /** @namespace file.relativePath */ - /** @namespace file.webkitRelativePath */ - return String(file.newPath || file.relativePath || file.webkitRelativePath || $h.getFileName(file) || null); - - }, - getFileId: function (file, generateFileId) { - var relativePath = $h.getFileRelativePath(file); - if (typeof generateFileId === 'function') { - return generateFileId(file); - } - if (!file) { - return null; - } - if (!relativePath) { - return null; - } - return (file.size + '_' + encodeURIComponent(relativePath).replace(/%/g, '_')); - }, - getFrameSelector: function (id, selector) { - selector = selector || ''; - return '[id="' + id + '"]' + selector; - }, - getZoomSelector: function (id, selector) { - return $h.getFrameSelector('zoom-' + id, selector); - }, - getFrameElement: function ($element, id, selector) { - return $element.find($h.getFrameSelector(id, selector)); - }, - getZoomElement: function ($element, id, selector) { - return $element.find($h.getZoomSelector(id, selector)); - }, - getElapsed: function (seconds) { - var delta = seconds, out = '', result = {}, structure = { - year: 31536000, - month: 2592000, - week: 604800, // uncomment row to ignore - day: 86400, // feel free to add your own row - hour: 3600, - minute: 60, - second: 1 - }; - $h.getObjectKeys(structure).forEach(function (key) { - result[key] = Math.floor(delta / structure[key]); - delta -= result[key] * structure[key]; - }); - $.each(result, function (key, value) { - if (value > 0) { - out += (out ? ' ' : '') + value + key.substring(0, 1); - } - }); - return out; - }, - debounce: function (func, delay) { - var inDebounce; - return function () { - var args = arguments, context = this; - clearTimeout(inDebounce); - inDebounce = setTimeout(function () { - func.apply(context, args); - }, delay); - }; - }, - stopEvent: function (e) { - e.stopPropagation(); - e.preventDefault(); - }, - getFileName: function (file) { - /** @namespace file.fileName */ - return file ? (file.fileName || file.name || '') : ''; // some confusion in different versions of Firefox - }, - createObjectURL: function (data) { - if ($h.objUrl && $h.objUrl.createObjectURL && data) { - return $h.objUrl.createObjectURL(data); - } - return ''; - }, - revokeObjectURL: function (data) { - if ($h.objUrl && $h.objUrl.revokeObjectURL && data) { - $h.objUrl.revokeObjectURL(data); - } - }, - compare: function (input, str, exact) { - return input !== undefined && (exact ? input === str : input.match(str)); - }, - isIE: function (ver) { - var div, status; - // check for IE versions < 11 - if (navigator.appName !== 'Microsoft Internet Explorer') { - return false; - } - if (ver === 10) { - return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent); - } - div = document.createElement('div'); - div.innerHTML = ''; - status = div.getElementsByTagName('i').length; - document.body.appendChild(div); - div.parentNode.removeChild(div); - return status; - }, - canOrientImage: function ($el) { - var $img = $(document.createElement('img')).css({width: '1px', height: '1px'}).insertAfter($el), - flag = $img.css('image-orientation'); - $img.remove(); - return !!flag; - }, - canAssignFilesToInput: function () { - var input = document.createElement('input'); - try { - input.type = 'file'; - input.files = null; - return true; - } catch (err) { - return false; - } - }, - getDragDropFolders: function (items) { - var i, item, len = items ? items.length : 0, folders = 0; - if (len > 0 && items[0].webkitGetAsEntry()) { - for (i = 0; i < len; i++) { - item = items[i].webkitGetAsEntry(); - if (item && item.isDirectory) { - folders++; - } - } - } - return folders; - }, - initModal: function ($modal) { - var $body = $('body'); - if ($body.length) { - $modal.appendTo($body); - } - }, - isFunction: function (v) { - return typeof v === 'function'; - }, - isEmpty: function (value, trim) { - return value === undefined || value === null || (!$h.isFunction( - value) && (value.length === 0 || (trim && $.trim(value) === ''))); - }, - isArray: function (a) { - return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]'; - }, - ifSet: function (needle, haystack, def) { - def = def || ''; - return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def; - }, - cleanArray: function (arr) { - if (!(arr instanceof Array)) { - arr = []; - } - return arr.filter(function (e) { - return (e !== undefined && e !== null); - }); - }, - spliceArray: function (arr, index, reverseOrder) { - var i, j = 0, out = [], newArr; - if (!(arr instanceof Array)) { - return []; - } - newArr = $.extend(true, [], arr); - if (reverseOrder) { - newArr.reverse(); - } - for (i = 0; i < newArr.length; i++) { - if (i !== index) { - out[j] = newArr[i]; - j++; - } - } - if (reverseOrder) { - out.reverse(); - } - return out; - }, - getNum: function (num, def) { - def = def || 0; - if (typeof num === 'number') { - return num; - } - if (typeof num === 'string') { - num = parseFloat(num); - } - return isNaN(num) ? def : num; - }, - hasFileAPISupport: function () { - return !!(window.File && window.FileReader); - }, - hasDragDropSupport: function () { - var div = document.createElement('div'); - /** @namespace div.draggable */ - /** @namespace div.ondragstart */ - /** @namespace div.ondrop */ - return !$h.isIE(9) && - (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined)); - }, - hasFileUploadSupport: function () { - return $h.hasFileAPISupport() && window.FormData; - }, - hasBlobSupport: function () { - try { - return !!window.Blob && Boolean(new Blob()); - } catch (e) { - return false; - } - }, - hasArrayBufferViewSupport: function () { - try { - return new Blob([new Uint8Array(100)]).size === 100; - } catch (e) { - return false; - } - }, - hasResumableUploadSupport: function () { - /** @namespace Blob.prototype.webkitSlice */ - /** @namespace Blob.prototype.mozSlice */ - return $h.hasFileUploadSupport() && $h.hasBlobSupport() && $h.hasArrayBufferViewSupport() && - (!!Blob.prototype.webkitSlice || !!Blob.prototype.mozSlice || !!Blob.prototype.slice || false); - }, - dataURI2Blob: function (dataURI) { - var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || - window.MSBlobBuilder, canBlob = $h.hasBlobSupport(), byteStr, arrayBuffer, intArray, i, mimeStr, bb, - canProceed = (canBlob || BlobBuilder) && window.atob && window.ArrayBuffer && window.Uint8Array; - if (!canProceed) { - return null; - } - if (dataURI.split(',')[0].indexOf('base64') >= 0) { - byteStr = atob(dataURI.split(',')[1]); - } else { - byteStr = decodeURIComponent(dataURI.split(',')[1]); - } - arrayBuffer = new ArrayBuffer(byteStr.length); - intArray = new Uint8Array(arrayBuffer); - for (i = 0; i < byteStr.length; i += 1) { - intArray[i] = byteStr.charCodeAt(i); - } - mimeStr = dataURI.split(',')[0].split(':')[1].split(';')[0]; - if (canBlob) { - return new Blob([$h.hasArrayBufferViewSupport() ? intArray : arrayBuffer], {type: mimeStr}); - } - bb = new BlobBuilder(); - bb.append(arrayBuffer); - return bb.getBlob(mimeStr); - }, - arrayBuffer2String: function (buffer) { - if (window.TextDecoder) { - return new TextDecoder('utf-8').decode(buffer); - } - var array = Array.prototype.slice.apply(new Uint8Array(buffer)), out = '', i = 0, len, c, char2, char3; - len = array.length; - while (i < len) { - c = array[i++]; - switch (c >> 4) { // jshint ignore:line - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - // 0xxxxxxx - out += String.fromCharCode(c); - break; - case 12: - case 13: - // 110x xxxx 10xx xxxx - char2 = array[i++]; - out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); // jshint ignore:line - break; - case 14: - // 1110 xxxx 10xx xxxx 10xx xxxx - char2 = array[i++]; - char3 = array[i++]; - out += String.fromCharCode(((c & 0x0F) << 12) | // jshint ignore:line - ((char2 & 0x3F) << 6) | // jshint ignore:line - ((char3 & 0x3F) << 0)); // jshint ignore:line - break; - } - } - return out; - }, - isHtml: function (str) { - var a = document.createElement('div'); - a.innerHTML = str; - for (var c = a.childNodes, i = c.length; i--;) { - if (c[i].nodeType === 1) { - return true; - } - } - return false; - }, - isSvg: function (str) { - return str.match(/^\s*<\?xml/i) && (str.match(/' + str + '')); - }, - uniqId: function () { - return (new Date().getTime() + Math.floor(Math.random() * Math.pow(10, 15))).toString(36); - }, - cspBuffer: { - CSP_ATTRIB: 'data-csp-01928735', // a randomly named temporary attribute to store the CSP elem id - domElementsStyles: {}, - stash: function (htmlString) { - var self = this, outerDom = $.parseHTML('
' + htmlString + '
'), $el = $(outerDom); - $el.find('[style]').each(function (key, elem) { - var $elem = $(elem), styleString = $elem.attr('style'), id = $h.uniqId(), styles = {}; - if (styleString && styleString.length) { - if (styleString.indexOf(';') === -1) { - styleString += ';'; - } - styleString.slice(0, styleString.length - 1).split(';').map(function (str) { - str = str.split(':'); - if (str[0]) { - styles[str[0]] = str[1] ? str[1] : ''; - } - }); - self.domElementsStyles[id] = styles; - $elem.removeAttr('style').attr(self.CSP_ATTRIB, id); - } - }); - $el.filter('*').removeAttr('style'); // make sure all style attr are removed - var values = Object.values ? Object.values(outerDom) : Object.keys(outerDom).map(function (itm) { - return outerDom[itm]; - }); - return values.flatMap(function (elem) { - return elem.innerHTML; - }).join(''); - }, - apply: function (domElement) { - var self = this, $el = $(domElement); - $el.find('[' + self.CSP_ATTRIB + ']').each(function (key, elem) { - var $elem = $(elem), id = $elem.attr(self.CSP_ATTRIB), styles = self.domElementsStyles[id]; - if (styles) { - $elem.css(styles); - } - $elem.removeAttr(self.CSP_ATTRIB); - }); - self.domElementsStyles = {}; - } - }, - setHtml: function ($elem, htmlString) { - var buf = $h.cspBuffer; - $elem.html(buf.stash(htmlString)); - buf.apply($elem); - return $elem; - }, - htmlEncode: function (str, undefVal) { - if (str === undefined) { - return undefVal || null; - } - return str.replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); - }, - replaceTags: function (str, tags) { - var out = str; - if (!tags) { - return out; - } - $.each(tags, function (key, value) { - if (typeof value === 'function') { - value = value(); - } - out = out.split(key).join(value); - }); - return out; - }, - cleanMemory: function ($thumb) { - var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src'); - $h.revokeObjectURL(data); - }, - findFileName: function (filePath) { - var sepIndex = filePath.lastIndexOf('/'); - if (sepIndex === -1) { - sepIndex = filePath.lastIndexOf('\\'); - } - return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop(); - }, - checkFullScreen: function () { - return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || - document.msFullscreenElement; - }, - toggleFullScreen: function (maximize) { - var doc = document, de = doc.documentElement, isFullScreen = $h.checkFullScreen(); - if (de && maximize && !isFullScreen) { - if (de.requestFullscreen) { - de.requestFullscreen(); - } else { - if (de.msRequestFullscreen) { - de.msRequestFullscreen(); - } else { - if (de.mozRequestFullScreen) { - de.mozRequestFullScreen(); - } else { - if (de.webkitRequestFullscreen) { - de.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); - } - } - } - } - } else { - if (isFullScreen) { - if (doc.exitFullscreen) { - doc.exitFullscreen(); - } else { - if (doc.msExitFullscreen) { - doc.msExitFullscreen(); - } else { - if (doc.mozCancelFullScreen) { - doc.mozCancelFullScreen(); - } else { - if (doc.webkitExitFullscreen) { - doc.webkitExitFullscreen(); - } - } - } - } - } - } - }, - moveArray: function (arr, oldIndex, newIndex, reverseOrder) { - var newArr = $.extend(true, [], arr); - if (reverseOrder) { - newArr.reverse(); - } - if (newIndex >= newArr.length) { - var k = newIndex - newArr.length; - while ((k--) + 1) { - newArr.push(undefined); - } - } - newArr.splice(newIndex, 0, newArr.splice(oldIndex, 1)[0]); - if (reverseOrder) { - newArr.reverse(); - } - return newArr; - }, - closeButton: function (css) { - css = css ? 'close ' + css : 'close'; - return ''; - }, - getRotation: function (value) { - switch (value) { - case 2: - return 'rotateY(180deg)'; - case 3: - return 'rotate(180deg)'; - case 4: - return 'rotate(180deg) rotateY(180deg)'; - case 5: - return 'rotate(270deg) rotateY(180deg)'; - case 6: - return 'rotate(90deg)'; - case 7: - return 'rotate(90deg) rotateY(180deg)'; - case 8: - return 'rotate(270deg)'; - default: - return ''; - } - }, - setTransform: function (el, val) { - if (!el) { - return; - } - el.style.transform = val; - el.style.webkitTransform = val; - el.style['-moz-transform'] = val; - el.style['-ms-transform'] = val; - el.style['-o-transform'] = val; - }, - getObjectKeys: function (obj) { - var keys = []; - if (obj) { - $.each(obj, function (key) { - keys.push(key); - }); - } - return keys; - }, - getObjectSize: function (obj) { - return $h.getObjectKeys(obj).length; - }, - /** - * Small dependency injection for the task manager - * https://gist.github.com/fearphage/4341799 - */ - whenAll: function (array) { - var s = [].slice, resolveValues = arguments.length === 1 && $h.isArray(array) ? array : s.call(arguments), - deferred = $.Deferred(), i, failed = 0, value, length = resolveValues.length, - remaining = length, rejectContexts, rejectValues, resolveContexts, updateFunc; - rejectContexts = rejectValues = resolveContexts = Array(length); - updateFunc = function (index, contexts, values) { - return function () { - if (values !== resolveValues) { - failed++; - } - deferred.notifyWith(contexts[index] = this, values[index] = s.call(arguments)); - if (!(--remaining)) { - deferred[(!failed ? 'resolve' : 'reject') + 'With'](contexts, values); - } - }; - }; - for (i = 0; i < length; i++) { - if ((value = resolveValues[i]) && $.isFunction(value.promise)) { - value.promise() - .done(updateFunc(i, resolveContexts, resolveValues)) - .fail(updateFunc(i, rejectContexts, rejectValues)); - } else { - deferred.notifyWith(this, value); - --remaining; - } - } - if (!remaining) { - deferred.resolveWith(resolveContexts, resolveValues); - } - return deferred.promise(); - } - }; - FileInput = function (element, options) { - var self = this; - self.$element = $(element); - self.$parent = self.$element.parent(); - if (!self._validate()) { - return; - } - self.isPreviewable = $h.hasFileAPISupport(); - self.isIE9 = $h.isIE(9); - self.isIE10 = $h.isIE(10); - if (self.isPreviewable || self.isIE9) { - self._init(options); - self._listen(); - } - self.$element.removeClass('file-loading'); - }; - - FileInput.prototype = { - constructor: FileInput, - _cleanup: function () { - var self = this; - self.reader = null; - self.clearFileStack(); - self.fileBatchCompleted = true; - self.isError = false; - self.isDuplicateError = false; - self.isPersistentError = false; - self.cancelling = false; - self.paused = false; - self.lastProgress = 0; - self._initAjax(); - }, - _isAborted: function () { - var self = this; - return self.cancelling || self.paused; - }, - _initAjax: function () { - var self = this, tm = self.taskManager = { - pool: {}, - addPool: function (id) { - return (tm.pool[id] = new tm.TasksPool(id)); - }, - getPool: function (id) { - return tm.pool[id]; - }, - addTask: function (id, logic) { // add standalone task directly from task manager - return new tm.Task(id, logic); - }, - TasksPool: function (id) { - var tp = this; - tp.id = id; - tp.cancelled = false; - tp.cancelledDeferrer = $.Deferred(); - tp.tasks = {}; - tp.addTask = function (id, logic) { - return (tp.tasks[id] = new tm.Task(id, logic)); - }; - tp.size = function () { - return $h.getObjectSize(tp.tasks); - }; - tp.run = function (maxThreads) { - var i = 0, failed = false, task, tasksList = $h.getObjectKeys(tp.tasks).map(function (key) { - return tp.tasks[key]; - }), tasksDone = [], deferred = $.Deferred(), enqueue, callback; - - if (tp.cancelled) { - tp.cancelledDeferrer.resolve(); - return deferred.reject(); - } - // if run all at once - if (!maxThreads) { - var tasksDeferredList = $h.getObjectKeys(tp.tasks).map(function (key) { - return tp.tasks[key].deferred; - }); - // when all are done - $h.whenAll(tasksDeferredList).done(function () { - var argv = $h.getArray(arguments); - if (!tp.cancelled) { - deferred.resolve.apply(null, argv); - tp.cancelledDeferrer.reject(); - } else { - deferred.reject.apply(null, argv); - tp.cancelledDeferrer.resolve(); - } - }).fail(function () { - var argv = $h.getArray(arguments); - deferred.reject.apply(null, argv); - if (!tp.cancelled) { - tp.cancelledDeferrer.reject(); - } else { - tp.cancelledDeferrer.resolve(); - } - }); - // run all tasks - $.each(tp.tasks, function (id) { - task = tp.tasks[id]; - task.run(); - }); - return deferred; - } - enqueue = function (task) { - $.when(task.deferred) - .fail(function () { - failed = true; - callback.apply(null, arguments); - }) - .always(callback); - }; - callback = function () { - var argv = $h.getArray(arguments); - // notify a task just ended - deferred.notify(argv); - tasksDone.push(argv); - if (tp.cancelled) { - deferred.reject.apply(null, tasksDone); - tp.cancelledDeferrer.resolve(); - return; - } - if (tasksDone.length === tp.size()) { - if (failed) { - deferred.reject.apply(null, tasksDone); - } else { - deferred.resolve.apply(null, tasksDone); - } - } - // if there are any tasks remaining - if (tasksList.length) { - task = tasksList.shift(); - enqueue(task); - task.run(); - } - }; - // run the first "maxThreads" tasks - while (tasksList.length && i++ < maxThreads) { - task = tasksList.shift(); - enqueue(task); - task.run(); - } - return deferred; - }; - tp.cancel = function () { - tp.cancelled = true; - return tp.cancelledDeferrer; - }; - }, - Task: function (id, logic) { - var tk = this; - tk.id = id; - tk.deferred = $.Deferred(); - tk.logic = logic; - tk.context = null; - tk.run = function () { - var argv = $h.getArray(arguments); - argv.unshift(tk.deferred); // add deferrer as first argument - logic.apply(tk.context, argv); // run task - return tk.deferred; // return deferrer - }; - tk.runWithContext = function (context) { - tk.context = context; - return tk.run(); - }; - } - }; - self.ajaxQueue = []; - self.ajaxRequests = []; - self.ajaxAborted = false; - }, - _init: function (options, refreshMode) { - var self = this, f, $el = self.$element, $cont, t, tmp; - self.options = options; - self.canOrientImage = $h.canOrientImage($el); - $.each(options, function (key, value) { - switch (key) { - case 'minFileCount': - case 'maxFileCount': - case 'maxTotalFileCount': - case 'minFileSize': - case 'maxFileSize': - case 'maxFilePreviewSize': - case 'resizeImageQuality': - case 'resizeIfSizeMoreThan': - case 'progressUploadThreshold': - case 'initialPreviewCount': - case 'zoomModalHeight': - case 'minImageHeight': - case 'maxImageHeight': - case 'minImageWidth': - case 'maxImageWidth': - self[key] = $h.getNum(value); - break; - default: - self[key] = value; - break; - } - }); - if (self.maxTotalFileCount > 0 && self.maxTotalFileCount < self.maxFileCount) { - self.maxTotalFileCount = self.maxFileCount; - } - if (self.rtl) { // swap buttons for rtl - tmp = self.previewZoomButtonIcons.prev; - self.previewZoomButtonIcons.prev = self.previewZoomButtonIcons.next; - self.previewZoomButtonIcons.next = tmp; - } - // validate chunk threads to not exceed maxAjaxThreads - if (!isNaN(self.maxAjaxThreads) && self.maxAjaxThreads < self.resumableUploadOptions.maxThreads) { - self.resumableUploadOptions.maxThreads = self.maxAjaxThreads; - } - self._initFileManager(); - if (typeof self.autoOrientImage === 'function') { - self.autoOrientImage = self.autoOrientImage(); - } - if (typeof self.autoOrientImageInitial === 'function') { - self.autoOrientImageInitial = self.autoOrientImageInitial(); - } - if (!refreshMode) { - self._cleanup(); - } - self.duplicateErrors = []; - self.$form = $el.closest('form'); - self._initTemplateDefaults(); - self.uploadFileAttr = !$h.isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data'; - t = self._getLayoutTemplate('progress'); - self.progressTemplate = t.replace('{class}', self.progressClass); - self.progressInfoTemplate = t.replace('{class}', self.progressInfoClass); - self.progressPauseTemplate = t.replace('{class}', self.progressPauseClass); - self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass); - self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass); - self.isDisabled = $el.attr('disabled') || $el.attr('readonly'); - if (self.isDisabled) { - $el.attr('disabled', true); - } - self.isClickable = self.browseOnZoneClick && self.showPreview && - (self.dropZoneEnabled || !$h.isEmpty(self.defaultPreviewContent)); - self.isAjaxUpload = $h.hasFileUploadSupport() && !$h.isEmpty(self.uploadUrl); - self.dropZoneEnabled = $h.hasDragDropSupport() && self.dropZoneEnabled; - if (!self.isAjaxUpload) { - self.dropZoneEnabled = self.dropZoneEnabled && $h.canAssignFilesToInput(); - } - self.slug = typeof options.slugCallback === 'function' ? options.slugCallback : self._slugDefault; - self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2'); - self.captionTemplate = self._getLayoutTemplate('caption'); - self.previewGenericTemplate = self._getPreviewTemplate('generic'); - if (!self.imageCanvas && self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) { - self.imageCanvas = document.createElement('canvas'); - self.imageCanvasContext = self.imageCanvas.getContext('2d'); - } - if ($h.isEmpty($el.attr('id'))) { - $el.attr('id', $h.uniqId()); - } - self.namespace = '.fileinput_' + $el.attr('id').replace(/-/g, '_'); - if (self.$container === undefined) { - self.$container = self._createContainer(); - } else { - self._refreshContainer(); - } - $cont = self.$container; - self.$dropZone = $cont.find('.file-drop-zone'); - self.$progress = $cont.find('.kv-upload-progress'); - self.$btnUpload = $cont.find('.fileinput-upload'); - self.$captionContainer = $h.getElement(options, 'elCaptionContainer', $cont.find('.file-caption')); - self.$caption = $h.getElement(options, 'elCaptionText', $cont.find('.file-caption-name')); - if (!$h.isEmpty(self.msgPlaceholder)) { - f = $el.attr('multiple') ? self.filePlural : self.fileSingle; - self.$caption.attr('placeholder', self.msgPlaceholder.replace('{files}', f)); - } - self.$captionIcon = self.$captionContainer.find('.file-caption-icon'); - self.$previewContainer = $h.getElement(options, 'elPreviewContainer', $cont.find('.file-preview')); - self.$preview = $h.getElement(options, 'elPreviewImage', $cont.find('.file-preview-thumbnails')); - self.$previewStatus = $h.getElement(options, 'elPreviewStatus', $cont.find('.file-preview-status')); - self.$errorContainer = $h.getElement(options, 'elErrorContainer', - self.$previewContainer.find('.kv-fileinput-error')); - self._validateDisabled(); - if (!$h.isEmpty(self.msgErrorClass)) { - $h.addCss(self.$errorContainer, self.msgErrorClass); - } - if (!refreshMode) { - self._resetErrors(); - self.$errorContainer.hide(); - self.previewInitId = 'thumb-' + $el.attr('id'); - self._initPreviewCache(); - self._initPreview(true); - self._initPreviewActions(); - if (self.$parent.hasClass('file-loading')) { - self.$container.insertBefore(self.$parent); - self.$parent.remove(); - } - } else { - if (!self._errorsExist()) { - self.$errorContainer.hide(); - } - } - self._setFileDropZoneTitle(); - if ($el.attr('disabled')) { - self.disable(); - } - self._initZoom(); - if (self.hideThumbnailContent) { - $h.addCss(self.$preview, 'hide-content'); - } - }, - _initFileManager: function () { - var self = this; - self.uploadStartTime = $h.now(); - self.fileManager = { - stack: {}, - filesProcessed: [], - errors: [], - loadedImages: {}, - totalImages: 0, - totalFiles: null, - totalSize: null, - uploadedSize: 0, - stats: {}, - initStats: function (id) { - var data = {started: $h.now()}; - if (id) { - self.fileManager.stats[id] = data; - } else { - self.fileManager.stats = data; - } - }, - getUploadStats: function (id, loaded, total) { - var fm = self.fileManager, - started = id ? fm.stats[id] && fm.stats[id].started || $h.now() : self.uploadStartTime; - var elapsed = ($h.now() - started) / 1000, - speeds = ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s', 'PB/s', 'EB/s', 'ZB/s', 'YB/s'], - bps = elapsed ? loaded / elapsed : 0, bitrate = self._getSize(bps, speeds), - pendingBytes = total - loaded, - out = { - fileId: id, - started: started, - elapsed: elapsed, - loaded: loaded, - total: total, - bps: bps, - bitrate: bitrate, - pendingBytes: pendingBytes - }; - if (id) { - fm.stats[id] = out; - } else { - fm.stats = out; - } - return out; - }, - exists: function (id) { - return $.inArray(id, self.fileManager.getIdList()) !== -1; - }, - count: function () { - return self.fileManager.getIdList().length; - }, - total: function () { - var fm = self.fileManager; - if (!fm.totalFiles) { - fm.totalFiles = fm.count(); - } - return fm.totalFiles; - }, - getTotalSize: function () { - var fm = self.fileManager; - if (fm.totalSize) { - return fm.totalSize; - } - fm.totalSize = 0; - $.each(self.fileManager.stack, function (id, f) { - var size = parseFloat(f.size); - fm.totalSize += isNaN(size) ? 0 : size; - }); - return fm.totalSize; - }, - add: function (file, id) { - if (!id) { - id = self.fileManager.getId(file); - } - if (!id) { - return; - } - self.fileManager.stack[id] = { - file: file, - name: $h.getFileName(file), - relativePath: $h.getFileRelativePath(file), - size: file.size, - nameFmt: self._getFileName(file, ''), - sizeFmt: self._getSize(file.size) - }; - }, - remove: function ($thumb) { - var id = $thumb.attr('data-fileid'); - if (id) { - self.fileManager.removeFile(id); - } - }, - removeFile: function (id) { - delete self.fileManager.stack[id]; - delete self.fileManager.loadedImages[id]; - }, - move: function (idFrom, idTo) { - var result = {}, stack = self.fileManager.stack; - if (!idFrom && !idTo || idFrom === idTo) { - return; - } - $.each(stack, function (k, v) { - if (k !== idFrom) { - result[k] = v; - } - if (k === idTo) { - result[idFrom] = stack[idFrom]; - } - }); - self.fileManager.stack = result; - }, - list: function () { - var files = []; - $.each(self.fileManager.stack, function (k, v) { - if (v && v.file) { - files.push(v.file); - } - }); - return files; - }, - isPending: function (id) { - return $.inArray(id, self.fileManager.filesProcessed) === -1 && self.fileManager.exists(id); - }, - isProcessed: function () { - var filesProcessed = true, fm = self.fileManager; - $.each(fm.stack, function (id) { - if (fm.isPending(id)) { - filesProcessed = false; - } - }); - return filesProcessed; - }, - clear: function () { - var fm = self.fileManager; - self.isDuplicateError = false; - self.isPersistentError = false; - fm.totalFiles = null; - fm.totalSize = null; - fm.uploadedSize = 0; - fm.stack = {}; - fm.errors = []; - fm.filesProcessed = []; - fm.stats = {}; - fm.clearImages(); - }, - clearImages: function () { - self.fileManager.loadedImages = {}; - self.fileManager.totalImages = 0; - }, - addImage: function (id, config) { - self.fileManager.loadedImages[id] = config; - }, - removeImage: function (id) { - delete self.fileManager.loadedImages[id]; - }, - getImageIdList: function () { - return $h.getObjectKeys(self.fileManager.loadedImages); - }, - getImageCount: function () { - return self.fileManager.getImageIdList().length; - }, - getId: function (file) { - return self._getFileId(file); - }, - getIndex: function (id) { - return self.fileManager.getIdList().indexOf(id); - }, - getThumb: function (id) { - var $thumb = null; - self._getThumbs().each(function () { - var $t = $(this); - if ($t.attr('data-fileid') === id) { - $thumb = $t; - } - }); - return $thumb; - }, - getThumbIndex: function ($thumb) { - var id = $thumb.attr('data-fileid'); - return self.fileManager.getIndex(id); - }, - getIdList: function () { - return $h.getObjectKeys(self.fileManager.stack); - }, - getFile: function (id) { - return self.fileManager.stack[id] || null; - }, - getFileName: function (id, fmt) { - var file = self.fileManager.getFile(id); - if (!file) { - return ''; - } - return fmt ? (file.nameFmt || '') : file.name || ''; - }, - getFirstFile: function () { - var ids = self.fileManager.getIdList(), id = ids && ids.length ? ids[0] : null; - return self.fileManager.getFile(id); - }, - setFile: function (id, file) { - if (self.fileManager.getFile(id)) { - self.fileManager.stack[id].file = file; - } else { - self.fileManager.add(file, id); - } - }, - setProcessed: function (id) { - self.fileManager.filesProcessed.push(id); - }, - getProgress: function () { - var total = self.fileManager.total(), filesProcessed = self.fileManager.filesProcessed.length; - if (!total) { - return 0; - } - return Math.ceil(filesProcessed / total * 100); - - }, - setProgress: function (id, pct) { - var f = self.fileManager.getFile(id); - if (!isNaN(pct) && f) { - f.progress = pct; - } - } - }; - }, - _setUploadData: function (fd, config) { - var self = this; - $.each(config, function (key, value) { - var param = self.uploadParamNames[key] || key; - if ($h.isArray(value)) { - fd.append(param, value[0], value[1]); - } else { - fd.append(param, value); - } - }); - }, - _initResumableUpload: function () { - var self = this, opts = self.resumableUploadOptions, logs = $h.logMessages, rm, fm = self.fileManager; - if (!self.enableResumableUpload) { - return; - } - if (opts.fallback !== false && typeof opts.fallback !== 'function') { - opts.fallback = function (s) { - s._log(logs.noResumableSupport); - s.enableResumableUpload = false; - }; - } - if (!$h.hasResumableUploadSupport() && opts.fallback !== false) { - opts.fallback(self); - return; - } - if (!self.uploadUrl && self.enableResumableUpload) { - self._log(logs.noUploadUrl); - self.enableResumableUpload = false; - return; - - } - opts.chunkSize = parseFloat(opts.chunkSize); - if (opts.chunkSize <= 0 || isNaN(opts.chunkSize)) { - self._log(logs.invalidChunkSize, {chunkSize: opts.chunkSize}); - self.enableResumableUpload = false; - return; - } - rm = self.resumableManager = { - init: function (id, f, index) { - rm.logs = []; - rm.stack = []; - rm.error = ''; - rm.id = id; - rm.file = f.file; - rm.fileName = f.name; - rm.fileIndex = index; - rm.completed = false; - rm.lastProgress = 0; - if (self.showPreview) { - rm.$thumb = fm.getThumb(id) || null; - rm.$progress = rm.$btnDelete = null; - if (rm.$thumb && rm.$thumb.length) { - rm.$progress = rm.$thumb.find('.file-thumb-progress'); - rm.$btnDelete = rm.$thumb.find('.kv-file-remove'); - } - } - rm.chunkSize = opts.chunkSize * 1024; - rm.chunkCount = rm.getTotalChunks(); - }, - setAjaxError: function (jqXHR, textStatus, errorThrown, isTest) { - if (jqXHR.responseJSON && jqXHR.responseJSON.error) { - errorThrown = jqXHR.responseJSON.error.toString(); - } - if (!isTest) { - rm.error = errorThrown; - } - if (opts.showErrorLog) { - self._log(logs.ajaxError, { - status: jqXHR.status, - error: errorThrown, - text: jqXHR.responseText || '' - }); - } - }, - reset: function () { - rm.stack = []; - rm.chunksProcessed = {}; - }, - setProcessed: function (status) { - var id = rm.id, msg, $thumb = rm.$thumb, $prog = rm.$progress, hasThumb = $thumb && $thumb.length, - params = {id: hasThumb ? $thumb.attr('id') : '', index: fm.getIndex(id), fileId: id}; - rm.completed = true; - rm.lastProgress = 0; - if (hasThumb) { - $thumb.removeClass('file-uploading'); - } - if (status === 'success') { - fm.uploadedSize += rm.file.size; - if (self.showPreview) { - self._setProgress(101, $prog); - self._setThumbStatus($thumb, 'Success'); - self._initUploadSuccess(rm.chunksProcessed[id].data, $thumb); - } - fm.removeFile(id); - delete rm.chunksProcessed[id]; - self._raise('fileuploaded', [params.id, params.index, params.fileId]); - if (fm.isProcessed()) { - self._setProgress(101); - } - } else { - if (status !== 'cancel') { - if (self.showPreview) { - self._setThumbStatus($thumb, 'Error'); - self._setPreviewError($thumb, true); - self._setProgress(101, $prog, self.msgProgressError); - self._setProgress(101, self.$progress, self.msgProgressError); - self.cancelling = true; - } - if (!self.$errorContainer.find('li[data-file-id="' + params.fileId + '"]').length) { - msg = self.msgResumableUploadRetriesExceeded.setTokens({ - file: rm.fileName, - max: opts.maxRetries, - error: rm.error - }); - self._showFileError(msg, params); - } - } - } - if (fm.isProcessed()) { - rm.reset(); - } - }, - check: function () { - var status = true; - $.each(rm.logs, function (index, value) { - if (!value) { - status = false; - return false; - } - }); - }, - processedResumables: function () { - var logs = rm.logs, i, count = 0; - if (!logs || !logs.length) { - return 0; - } - for (i = 0; i < logs.length; i++) { - if (logs[i] === true) { - count++; - } - } - return count; - }, - getUploadedSize: function () { - var size = rm.processedResumables() * rm.chunkSize; - return size > rm.file.size ? rm.file.size : size; - }, - getTotalChunks: function () { - var chunkSize = parseFloat(rm.chunkSize); - if (!isNaN(chunkSize) && chunkSize > 0) { - return Math.ceil(rm.file.size / chunkSize); - } - return 0; - }, - getProgress: function () { - var chunksProcessed = rm.processedResumables(), total = rm.chunkCount; - if (total === 0) { - return 0; - } - return Math.ceil(chunksProcessed / total * 100); - }, - checkAborted: function (intervalId) { - if (self._isAborted()) { - clearInterval(intervalId); - self.unlock(); - } - }, - upload: function () { - var ids = fm.getIdList(), flag = 'new', intervalId; - intervalId = setInterval(function () { - var id; - rm.checkAborted(intervalId); - if (flag === 'new') { - self.lock(); - flag = 'processing'; - id = ids.shift(); - fm.initStats(id); - if (fm.stack[id]) { - rm.init(id, fm.stack[id], fm.getIndex(id)); - rm.processUpload(); - } - } - if (!fm.isPending(id) && rm.completed) { - flag = 'new'; - } - if (fm.isProcessed()) { - var $initThumbs = self.$preview.find('.file-preview-initial'); - if ($initThumbs.length) { - $h.addCss($initThumbs, $h.SORT_CSS); - self._initSortable(); - } - clearInterval(intervalId); - self._clearFileInput(); - self.unlock(); - setTimeout(function () { - var data = self.previewCache.data; - if (data) { - self.initialPreview = data.content; - self.initialPreviewConfig = data.config; - self.initialPreviewThumbTags = data.tags; - } - self._raise('filebatchuploadcomplete', [ - self.initialPreview, - self.initialPreviewConfig, - self.initialPreviewThumbTags, - self._getExtraData() - ]); - }, self.processDelay); - } - }, self.processDelay); - }, - uploadResumable: function () { - var i, pool, tm = self.taskManager, total = rm.chunkCount; - pool = tm.addPool(rm.id); - for (i = 0; i < total; i++) { - rm.logs[i] = !!(rm.chunksProcessed[rm.id] && rm.chunksProcessed[rm.id][i]); - if (!rm.logs[i]) { - rm.pushAjax(i, 0); - } - } - pool.run(opts.maxThreads) - .done(function () { - rm.setProcessed('success'); - }) - .fail(function () { - rm.setProcessed(pool.cancelled ? 'cancel' : 'error'); - }); - }, - processUpload: function () { - var fd, f, id = rm.id, fnBefore, fnSuccess, fnError, fnComplete, outData; - if (!opts.testUrl) { - rm.uploadResumable(); - return; - } - fd = new FormData(); - f = fm.stack[id]; - self._setUploadData(fd, { - fileId: id, - fileName: f.fileName, - fileSize: f.size, - fileRelativePath: f.relativePath, - chunkSize: rm.chunkSize, - chunkCount: rm.chunkCount - }); - fnBefore = function (jqXHR) { - outData = self._getOutData(fd, jqXHR); - self._raise('filetestbeforesend', [id, fm, rm, outData]); - }; - fnSuccess = function (data, textStatus, jqXHR) { - outData = self._getOutData(fd, jqXHR, data); - var pNames = self.uploadParamNames, chunksUploaded = pNames.chunksUploaded || 'chunksUploaded', - params = [id, fm, rm, outData]; - if (!data[chunksUploaded] || !$h.isArray(data[chunksUploaded])) { - self._raise('filetesterror', params); - } else { - if (!rm.chunksProcessed[id]) { - rm.chunksProcessed[id] = {}; - } - $.each(data[chunksUploaded], function (key, index) { - rm.logs[index] = true; - rm.chunksProcessed[id][index] = true; - }); - rm.chunksProcessed[id].data = data; - self._raise('filetestsuccess', params); - } - rm.uploadResumable(); - }; - fnError = function (jqXHR, textStatus, errorThrown) { - outData = self._getOutData(fd, jqXHR); - self._raise('filetestajaxerror', [id, fm, rm, outData]); - rm.setAjaxError(jqXHR, textStatus, errorThrown, true); - rm.uploadResumable(); - }; - fnComplete = function () { - self._raise('filetestcomplete', [id, fm, rm, self._getOutData(fd)]); - }; - self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, fd, id, rm.fileIndex, opts.testUrl); - }, - pushAjax: function (index, retry) { - var tm = self.taskManager, pool = tm.getPool(rm.id); - pool.addTask(pool.size() + 1, function (deferrer) { - // use fifo chunk stack - var arr = rm.stack.shift(), index; - index = arr[0]; - if (!rm.chunksProcessed[rm.id] || !rm.chunksProcessed[rm.id][index]) { - rm.sendAjax(index, arr[1], deferrer); - } else { - self._log(logs.chunkQueueError, {index: index}); - } - }); - rm.stack.push([index, retry]); - }, - sendAjax: function (index, retry, deferrer) { - var f, chunkSize = rm.chunkSize, id = rm.id, file = rm.file, $thumb = rm.$thumb, - msgs = $h.logMessages, $btnDelete = rm.$btnDelete, logError = function (msg, tokens) { - if (tokens) { - msg = msg.setTokens(tokens); - } - msg = 'Error processing resumable ajax request. ' + msg; - self._log(msg); - deferrer.reject(msg); - }; - if (rm.chunksProcessed[id] && rm.chunksProcessed[id][index]) { - return; - } - if (retry > opts.maxRetries) { - logError(msgs.resumableMaxRetriesReached, {n: opts.maxRetries}); - rm.setProcessed('error'); - return; - } - var fd, outData, fnBefore, fnSuccess, fnError, fnComplete, slice = file.slice ? 'slice' : - (file.mozSlice ? 'mozSlice' : (file.webkitSlice ? 'webkitSlice' : 'slice')), - blob = file[slice](chunkSize * index, chunkSize * (index + 1)); - fd = new FormData(); - f = fm.stack[id]; - self._setUploadData(fd, { - chunkCount: rm.chunkCount, - chunkIndex: index, - chunkSize: chunkSize, - chunkSizeStart: chunkSize * index, - fileBlob: [blob, rm.fileName], - fileId: id, - fileName: rm.fileName, - fileRelativePath: f.relativePath, - fileSize: file.size, - retryCount: retry - }); - if (rm.$progress && rm.$progress.length) { - rm.$progress.show(); - } - fnBefore = function (jqXHR) { - outData = self._getOutData(fd, jqXHR); - if (self.showPreview) { - if (!$thumb.hasClass('file-preview-success')) { - self._setThumbStatus($thumb, 'Loading'); - $h.addCss($thumb, 'file-uploading'); - } - $btnDelete.attr('disabled', true); - } - self._raise('filechunkbeforesend', [id, index, retry, fm, rm, outData]); - }; - fnSuccess = function (data, textStatus, jqXHR) { - if (self._isAborted()) { - logError(msgs.resumableAborting); - return; - } - outData = self._getOutData(fd, jqXHR, data); - var paramNames = self.uploadParamNames, chunkIndex = paramNames.chunkIndex || 'chunkIndex', - params = [id, index, retry, fm, rm, outData]; - if (data.error) { - if (opts.showErrorLog) { - self._log(logs.retryStatus, { - retry: retry + 1, - filename: rm.fileName, - chunk: index - }); - } - rm.pushAjax(index, retry + 1); - rm.error = data.error; - self._raise('filechunkerror', params); - } else { - rm.logs[data[chunkIndex]] = true; - if (!rm.chunksProcessed[id]) { - rm.chunksProcessed[id] = {}; - } - rm.chunksProcessed[id][data[chunkIndex]] = true; - rm.chunksProcessed[id].data = data; - deferrer.resolve.call(null, data); - self._raise('filechunksuccess', params); - rm.check(); - } - }; - fnError = function (jqXHR, textStatus, errorThrown) { - if (self._isAborted()) { - logError(msgs.resumableAborting); - return; - } - outData = self._getOutData(fd, jqXHR); - rm.setAjaxError(jqXHR, textStatus, errorThrown); - self._raise('filechunkajaxerror', [id, index, retry, fm, rm, outData]); - rm.pushAjax(index, retry + 1); // push another task - logError(msgs.resumableRetryError, {n: retry - 1}); // resolve the current task - }; - fnComplete = function () { - if (!self._isAborted()) { - self._raise('filechunkcomplete', [id, index, retry, fm, rm, self._getOutData(fd)]); - } - }; - self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, fd, id, rm.fileIndex); - } - }; - rm.reset(); - }, - _initTemplateDefaults: function () { - var self = this, tMain1, tMain2, tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse, - tModalMain, tModal, tProgress, tSize, tFooter, tActions, tActionDelete, tActionUpload, tActionDownload, - tActionZoom, tActionDrag, tIndicator, tTagBef, tTagBef1, tTagBef2, tTagAft, tGeneric, tHtml, tImage, - tText, tOffice, tGdocs, tVideo, tAudio, tFlash, tObject, tPdf, tOther, tStyle, tZoomCache, vDefaultDim, - tStats, tModalLabel, renderObject = function (type, mime) { - return '\n' + $h.DEFAULT_PREVIEW + '\n\n'; - }; - tMain1 = '{preview}\n' + - '
\n' + - '
\n' + - ' {caption}\n' + - '
\n' + - ' {remove}\n' + - ' {cancel}\n' + - ' {pause}\n' + - ' {upload}\n' + - ' {browse}\n' + - '
\n' + - '
'; - tMain2 = '{preview}\n
\n
\n' + - '{remove}\n{cancel}\n{upload}\n{browse}\n'; - tPreview = '
\n' + - ' {close}' + - '
\n' + - '
\n' + - '
\n' + - '
\n' + - '
\n' + - '
\n' + - '
'; - tClose = $h.closeButton('fileinput-remove'); - tFileIcon = ''; - // noinspection HtmlUnknownAttribute - tCaption = '
\n' + - ' \n' + - ' \n' + - '
'; - //noinspection HtmlUnknownAttribute - tBtnDefault = ''; - //noinspection HtmlUnknownTarget,HtmlUnknownAttribute - tBtnLink = '{icon} {label}'; - //noinspection HtmlUnknownAttribute - tBtnBrowse = '
{icon} {label}
'; - tModalLabel = $h.MODAL_ID + 'Label'; - tModalMain = ''; - tModal = '\n'; - tProgress = '
\n' + - '
\n' + - ' {status}\n' + - '
\n' + - '
{stats}'; - tStats = '
' + - '{pendingTime} ' + - '{uploadSpeed}' + - '
'; - tSize = ' ({sizeText})'; - tFooter = ''; - tActions = '
\n' + - ' \n' + - '
\n' + - '{drag}\n' + - '
'; - //noinspection HtmlUnknownAttribute - tActionDelete = '\n'; - tActionUpload = ''; - tActionDownload = '{downloadIcon}'; - tActionZoom = ''; - tActionDrag = '{dragIcon}'; - tIndicator = '
{indicator}
'; - tTagBef = '
\n'; - tTagBef2 = tTagBef + ' title="{caption}">
\n'; - tTagAft = '
{footer}\n{zoomCache}
\n'; - tGeneric = '{content}\n'; - tStyle = ' {style}'; - tHtml = renderObject('html', 'text/html'); - tText = renderObject('text', 'text/plain;charset=UTF-8'); - tPdf = renderObject('pdf', 'application/pdf'); - tImage = '{alt}\n'; - tOffice = ''; - tGdocs = ''; - tVideo = '\n'; - tAudio = '\n'; - tFlash = '\n'; - tObject = '\n' + '\n' + - $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW + '\n\n'; - tOther = '
\n' + $h.DEFAULT_PREVIEW + '\n
\n'; - tZoomCache = '
{zoomContent}
'; - vDefaultDim = {width: '100%', height: '100%', 'min-height': '480px'}; - if (self._isPdfRendered()) { - tPdf = self.pdfRendererTemplate.replace('{renderer}', self._encodeURI(self.pdfRendererUrl)); - } - self.defaults = { - layoutTemplates: { - main1: tMain1, - main2: tMain2, - preview: tPreview, - close: tClose, - fileIcon: tFileIcon, - caption: tCaption, - modalMain: tModalMain, - modal: tModal, - progress: tProgress, - stats: tStats, - size: tSize, - footer: tFooter, - indicator: tIndicator, - actions: tActions, - actionDelete: tActionDelete, - actionUpload: tActionUpload, - actionDownload: tActionDownload, - actionZoom: tActionZoom, - actionDrag: tActionDrag, - btnDefault: tBtnDefault, - btnLink: tBtnLink, - btnBrowse: tBtnBrowse, - zoomCache: tZoomCache - }, - previewMarkupTags: { - tagBefore1: tTagBef1, - tagBefore2: tTagBef2, - tagAfter: tTagAft - }, - previewContentTemplates: { - generic: tGeneric, - html: tHtml, - image: tImage, - text: tText, - office: tOffice, - gdocs: tGdocs, - video: tVideo, - audio: tAudio, - flash: tFlash, - object: tObject, - pdf: tPdf, - other: tOther - }, - allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'], - previewTemplates: {}, - previewSettings: { - image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'}, - html: {width: '213px', height: '160px'}, - text: {width: '213px', height: '160px'}, - office: {width: '213px', height: '160px'}, - gdocs: {width: '213px', height: '160px'}, - video: {width: '213px', height: '160px'}, - audio: {width: '100%', height: '30px'}, - flash: {width: '213px', height: '160px'}, - object: {width: '213px', height: '160px'}, - pdf: {width: '100%', height: '160px', 'position': 'relative'}, - other: {width: '213px', height: '160px'} - }, - previewSettingsSmall: { - image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'}, - html: {width: '100%', height: '160px'}, - text: {width: '100%', height: '160px'}, - office: {width: '100%', height: '160px'}, - gdocs: {width: '100%', height: '160px'}, - video: {width: '100%', height: 'auto'}, - audio: {width: '100%', height: '30px'}, - flash: {width: '100%', height: 'auto'}, - object: {width: '100%', height: 'auto'}, - pdf: {width: '100%', height: '160px'}, - other: {width: '100%', height: '160px'} - }, - previewZoomSettings: { - image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'}, - html: vDefaultDim, - text: vDefaultDim, - office: {width: '100%', height: '100%', 'max-width': '100%', 'min-height': '480px'}, - gdocs: {width: '100%', height: '100%', 'max-width': '100%', 'min-height': '480px'}, - video: {width: 'auto', height: '100%', 'max-width': '100%'}, - audio: {width: '100%', height: '30px'}, - flash: {width: 'auto', height: '480px'}, - object: {width: 'auto', height: '100%', 'max-width': '100%', 'min-height': '480px'}, - pdf: vDefaultDim, - other: {width: 'auto', height: '100%', 'min-height': '480px'} - }, - mimeTypeAliases: { - 'video/quicktime': 'video/mp4' - }, - fileTypeSettings: { - image: function (vType, vName) { - return ($h.compare(vType, 'image.*') && !$h.compare(vType, /(tiff?|wmf)$/i) || - $h.compare(vName, /\.(gif|png|jpe?g)$/i)); - }, - html: function (vType, vName) { - return $h.compare(vType, 'text/html') || $h.compare(vName, /\.(htm|html)$/i); - }, - office: function (vType, vName) { - return $h.compare(vType, /(word|excel|powerpoint|office)$/i) || - $h.compare(vName, /\.(docx?|xlsx?|pptx?|pps|potx?)$/i); - }, - gdocs: function (vType, vName) { - return $h.compare(vType, /(word|excel|powerpoint|office|iwork-pages|tiff?)$/i) || - $h.compare(vName, - /\.(docx?|xlsx?|pptx?|pps|potx?|rtf|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i); - }, - text: function (vType, vName) { - return $h.compare(vType, 'text.*') || $h.compare(vName, /\.(xml|javascript)$/i) || - $h.compare(vName, /\.(txt|md|nfo|ini|json|php|js|css)$/i); - }, - video: function (vType, vName) { - return $h.compare(vType, 'video.*') && ($h.compare(vType, /(ogg|mp4|mp?g|mov|webm|3gp)$/i) || - $h.compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i)); - }, - audio: function (vType, vName) { - return $h.compare(vType, 'audio.*') && ($h.compare(vName, /(ogg|mp3|mp?g|wav)$/i) || - $h.compare(vName, /\.(og?|mp3|mp?g|wav)$/i)); - }, - flash: function (vType, vName) { - return $h.compare(vType, 'application/x-shockwave-flash', true) || $h.compare(vName, - /\.(swf)$/i); - }, - pdf: function (vType, vName) { - return $h.compare(vType, 'application/pdf', true) || $h.compare(vName, /\.(pdf)$/i); - }, - object: function () { - return true; - }, - other: function () { - return true; - } - }, - fileActionSettings: { - showRemove: true, - showUpload: true, - showDownload: true, - showZoom: true, - showDrag: true, - removeIcon: '', - removeClass: 'btn btn-sm btn-kv btn-default btn-outline-secondary', - removeErrorClass: 'btn btn-sm btn-kv btn-danger', - removeTitle: 'Remove file', - uploadIcon: '', - uploadClass: 'btn btn-sm btn-kv btn-default btn-outline-secondary', - uploadTitle: 'Upload file', - uploadRetryIcon: '', - uploadRetryTitle: 'Retry upload', - downloadIcon: '', - downloadClass: 'btn btn-sm btn-kv btn-default btn-outline-secondary', - downloadTitle: 'Download file', - zoomIcon: '', - zoomClass: 'btn btn-sm btn-kv btn-default btn-outline-secondary', - zoomTitle: 'View Details', - dragIcon: '', - dragClass: 'text-info', - dragTitle: 'Move / Rearrange', - dragSettings: {}, - indicatorNew: '', - indicatorSuccess: '', - indicatorError: '', - indicatorLoading: '', - indicatorPaused: '', - indicatorNewTitle: 'Not uploaded yet', - indicatorSuccessTitle: 'Uploaded', - indicatorErrorTitle: 'Upload Error', - indicatorLoadingTitle: 'Uploading …', - indicatorPausedTitle: 'Upload Paused' - } - }; - $.each(self.defaults, function (key, setting) { - if (key === 'allowedPreviewTypes') { - if (self.allowedPreviewTypes === undefined) { - self.allowedPreviewTypes = setting; - } - return; - } - self[key] = $.extend(true, {}, setting, self[key]); - }); - self._initPreviewTemplates(); - }, - _initPreviewTemplates: function () { - var self = this, tags = self.previewMarkupTags, tagBef, tagAft = tags.tagAfter; - $.each(self.previewContentTemplates, function (key, value) { - if ($h.isEmpty(self.previewTemplates[key])) { - tagBef = tags.tagBefore2; - if (key === 'generic' || key === 'image') { - tagBef = tags.tagBefore1; - } - if (self._isPdfRendered() && key === 'pdf') { - tagBef = tagBef.replace('kv-file-content', 'kv-file-content kv-pdf-rendered'); - } - self.previewTemplates[key] = tagBef + value + tagAft; - } - }); - }, - _initPreviewCache: function () { - var self = this; - self.previewCache = { - data: {}, - init: function () { - var content = self.initialPreview; - if (content.length > 0 && !$h.isArray(content)) { - content = content.split(self.initialPreviewDelimiter); - } - self.previewCache.data = { - content: content, - config: self.initialPreviewConfig, - tags: self.initialPreviewThumbTags - }; - }, - count: function (skipNull) { - if (!self.previewCache.data || !self.previewCache.data.content) { - return 0; - } - if (skipNull) { - var chk = self.previewCache.data.content.filter(function (n) { - return n !== null; - }); - return chk.length; - } - return self.previewCache.data.content.length; - }, - get: function (i, isDisabled) { - var ind = $h.INIT_FLAG + i, data = self.previewCache.data, config = data.config[i], - content = data.content[i], out, $tmp, cat, ftr, - fname, ftype, frameClass, asData = $h.ifSet('previewAsData', config, self.initialPreviewAsData), - a = config ? {title: config.title || null, alt: config.alt || null} : {title: null, alt: null}, - parseTemplate = function (cat, dat, fname, ftype, ftr, ind, fclass, t) { - var fc = ' file-preview-initial ' + $h.SORT_CSS + (fclass ? ' ' + fclass : ''), - id = self.previewInitId + '-' + ind, - fileId = config && config.fileId || id; - /** @namespace config.zoomData */ - return self._generatePreviewTemplate(cat, dat, fname, ftype, id, fileId, false, null, fc, - ftr, ind, t, a, config && config.zoomData || dat); - }; - if (!content || !content.length) { - return ''; - } - isDisabled = isDisabled === undefined ? true : isDisabled; - cat = $h.ifSet('type', config, self.initialPreviewFileType || 'generic'); - fname = $h.ifSet('filename', config, $h.ifSet('caption', config)); - ftype = $h.ifSet('filetype', config, cat); - ftr = self.previewCache.footer(i, isDisabled, (config && config.size || null)); - frameClass = $h.ifSet('frameClass', config); - if (asData) { - out = parseTemplate(cat, content, fname, ftype, ftr, ind, frameClass); - } else { - out = parseTemplate('generic', content, fname, ftype, ftr, ind, frameClass, cat) - .setTokens({'content': data.content[i]}); - } - if (data.tags.length && data.tags[i]) { - out = $h.replaceTags(out, data.tags[i]); - } - /** @namespace config.frameAttr */ - if (!$h.isEmpty(config) && !$h.isEmpty(config.frameAttr)) { - $tmp = $h.createElement(out); - $tmp.find('.file-preview-initial').attr(config.frameAttr); - out = $tmp.html(); - $tmp.remove(); - } - return out; - }, - clean: function (data) { - data.content = $h.cleanArray(data.content); - data.config = $h.cleanArray(data.config); - data.tags = $h.cleanArray(data.tags); - self.previewCache.data = data; - }, - add: function (content, config, tags, append) { - var data = self.previewCache.data, index; - if (!content || !content.length) { - return 0; - } - index = content.length - 1; - if (!$h.isArray(content)) { - content = content.split(self.initialPreviewDelimiter); - } - if (append && data.content) { - index = data.content.push(content[0]) - 1; - data.config[index] = config; - data.tags[index] = tags; - } else { - data.content = content; - data.config = config; - data.tags = tags; - } - self.previewCache.clean(data); - return index; - }, - set: function (content, config, tags, append) { - var data = self.previewCache.data, i, chk; - if (!content || !content.length) { - return; - } - if (!$h.isArray(content)) { - content = content.split(self.initialPreviewDelimiter); - } - chk = content.filter(function (n) { - return n !== null; - }); - if (!chk.length) { - return; - } - if (data.content === undefined) { - data.content = []; - } - if (data.config === undefined) { - data.config = []; - } - if (data.tags === undefined) { - data.tags = []; - } - if (append) { - for (i = 0; i < content.length; i++) { - if (content[i]) { - data.content.push(content[i]); - } - } - for (i = 0; i < config.length; i++) { - if (config[i]) { - data.config.push(config[i]); - } - } - for (i = 0; i < tags.length; i++) { - if (tags[i]) { - data.tags.push(tags[i]); - } - } - } else { - data.content = content; - data.config = config; - data.tags = tags; - } - self.previewCache.clean(data); - }, - unset: function (index) { - var chk = self.previewCache.count(), rev = self.reversePreviewOrder; - if (!chk) { - return; - } - if (chk === 1) { - self.previewCache.data.content = []; - self.previewCache.data.config = []; - self.previewCache.data.tags = []; - self.initialPreview = []; - self.initialPreviewConfig = []; - self.initialPreviewThumbTags = []; - return; - } - self.previewCache.data.content = $h.spliceArray(self.previewCache.data.content, index, rev); - self.previewCache.data.config = $h.spliceArray(self.previewCache.data.config, index, rev); - self.previewCache.data.tags = $h.spliceArray(self.previewCache.data.tags, index, rev); - var data = $.extend(true, {}, self.previewCache.data); - self.previewCache.clean(data); - }, - out: function () { - var html = '', caption, len = self.previewCache.count(), i, content; - if (len === 0) { - return {content: '', caption: ''}; - } - for (i = 0; i < len; i++) { - content = self.previewCache.get(i); - html = self.reversePreviewOrder ? (content + html) : (html + content); - } - caption = self._getMsgSelected(len); - return {content: html, caption: caption}; - }, - footer: function (i, isDisabled, size) { - var data = self.previewCache.data || {}; - if ($h.isEmpty(data.content)) { - return ''; - } - if ($h.isEmpty(data.config) || $h.isEmpty(data.config[i])) { - data.config[i] = {}; - } - isDisabled = isDisabled === undefined ? true : isDisabled; - var config = data.config[i], caption = $h.ifSet('caption', config), a, - width = $h.ifSet('width', config, 'auto'), url = $h.ifSet('url', config, false), - key = $h.ifSet('key', config, null), fileId = $h.ifSet('fileId', config, null), - fs = self.fileActionSettings, initPreviewShowDel = self.initialPreviewShowDelete || false, - downloadInitialUrl = !self.initialPreviewDownloadUrl ? '' : - self.initialPreviewDownloadUrl + '?key=' + key + (fileId ? '&fileId=' + fileId : ''), - dUrl = config.downloadUrl || downloadInitialUrl, - dFil = config.filename || config.caption || '', - initPreviewShowDwl = !!(dUrl), - sDel = $h.ifSet('showRemove', config, initPreviewShowDel), - sDwl = $h.ifSet('showDownload', config, $h.ifSet('showDownload', fs, initPreviewShowDwl)), - sZm = $h.ifSet('showZoom', config, $h.ifSet('showZoom', fs, true)), - sDrg = $h.ifSet('showDrag', config, $h.ifSet('showDrag', fs, true)), - dis = (url === false) && isDisabled; - sDwl = sDwl && config.downloadUrl !== false && !!dUrl; - a = self._renderFileActions(config, false, sDwl, sDel, sZm, sDrg, dis, url, key, true, dUrl, dFil); - return self._getLayoutTemplate('footer').setTokens({ - 'progress': self._renderThumbProgress(), - 'actions': a, - 'caption': caption, - 'size': self._getSize(size), - 'width': width, - 'indicator': '' - }); - } - }; - self.previewCache.init(); - }, - _isPdfRendered: function () { - var self = this, useLib = self.usePdfRenderer, - flag = typeof useLib === 'function' ? useLib() : !!useLib; - return flag && self.pdfRendererUrl; - }, - _handler: function ($el, event, callback) { - var self = this, ns = self.namespace, ev = event.split(' ').join(ns + ' ') + ns; - if (!$el || !$el.length) { - return; - } - $el.off(ev).on(ev, callback); - }, - _encodeURI: function (vUrl) { - var self = this; - return self.encodeUrl ? encodeURI(vUrl) : vUrl; - }, - _log: function (msg, tokens) { - var self = this, id = self.$element.attr('id'); - if (!self.showConsoleLogs) { - return; - } - if (id) { - msg = '"' + id + '": ' + msg; - } - msg = 'bootstrap-fileinput: ' + msg; - if (typeof tokens === 'object') { - msg = msg.setTokens(tokens); - } - if (window.console && typeof window.console.log !== 'undefined') { - window.console.log(msg); - } else { - window.alert(msg); - } - }, - _validate: function () { - var self = this, status = self.$element.attr('type') === 'file'; - if (!status) { - self._log($h.logMessages.badInputType); - } - return status; - }, - _errorsExist: function () { - var self = this, $err, $errList = self.$errorContainer.find('li'); - if ($errList.length) { - return true; - } - $err = $h.createElement(self.$errorContainer.html()); - $err.find('.kv-error-close').remove(); - $err.find('ul').remove(); - return !!$.trim($err.text()).length; - }, - _errorHandler: function (evt, caption) { - var self = this, err = evt.target.error, showError = function (msg) { - self._showError(msg.replace('{name}', caption)); - }; - /** @namespace err.NOT_FOUND_ERR */ - /** @namespace err.SECURITY_ERR */ - /** @namespace err.NOT_READABLE_ERR */ - if (err.code === err.NOT_FOUND_ERR) { - showError(self.msgFileNotFound); - } else { - if (err.code === err.SECURITY_ERR) { - showError(self.msgFileSecured); - } else { - if (err.code === err.NOT_READABLE_ERR) { - showError(self.msgFileNotReadable); - } else { - if (err.code === err.ABORT_ERR) { - showError(self.msgFilePreviewAborted); - } else { - showError(self.msgFilePreviewError); - } - } - } - } - }, - _addError: function (msg) { - var self = this, $error = self.$errorContainer; - if (msg && $error.length) { - $h.setHtml($error, self.errorCloseButton + msg); - self._handler($error.find('.kv-error-close'), 'click', function () { - setTimeout(function () { - if (self.showPreview && !self.getFrames().length) { - self.clear(); - } - $error.fadeOut('slow'); - }, self.processDelay); - }); - } - }, - _setValidationError: function (css) { - var self = this; - css = (css ? css + ' ' : '') + 'has-error'; - self.$container.removeClass(css).addClass('has-error'); - $h.addCss(self.$captionContainer, 'is-invalid'); - }, - _resetErrors: function (fade) { - var self = this, $error = self.$errorContainer; - if (self.isPersistentError) { - return; - } - self.isError = false; - self.$container.removeClass('has-error'); - self.$captionContainer.removeClass('is-invalid'); - $error.html(''); - if (fade) { - $error.fadeOut('slow'); - } else { - $error.hide(); - } - }, - _showFolderError: function (folders) { - var self = this, $error = self.$errorContainer, msg; - if (!folders) { - return; - } - if (!self.isAjaxUpload) { - self._clearFileInput(); - } - msg = self.msgFoldersNotAllowed.replace('{n}', folders); - self._addError(msg); - self._setValidationError(); - $error.fadeIn(self.fadeDelay); - self._raise('filefoldererror', [folders, msg]); - }, - _showFileError: function (msg, params, event) { - var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', - fId = params && params.fileId || '', e = params && params.id ? - '
  • ' + msg + '
  • ' : '
  • ' + msg + '
  • '; - - if ($error.find('ul').length === 0) { - self._addError('
      ' + e + '
    '); - } else { - $error.find('ul').append(e); - } - $error.fadeIn(self.fadeDelay); - self._raise(ev, [params, msg]); - self._setValidationError('file-input-new'); - return true; - }, - _showError: function (msg, params, event) { - var self = this, $error = self.$errorContainer, ev = event || 'fileerror'; - params = params || {}; - params.reader = self.reader; - self._addError(msg); - $error.fadeIn(self.fadeDelay); - self._raise(ev, [params, msg]); - if (!self.isAjaxUpload) { - self._clearFileInput(); - } - self._setValidationError('file-input-new'); - self.$btnUpload.attr('disabled', true); - return true; - }, - _noFilesError: function (params) { - var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle, - msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label), - $error = self.$errorContainer; - msg = '
  • ' + msg + '
  • '; - if ($error.find('ul').length === 0) { - self._addError('
      ' + msg + '
    '); - } else { - $error.find('ul').append(msg); - } - self.isError = true; - self._updateFileDetails(0); - $error.fadeIn(self.fadeDelay); - self._raise('fileerror', [params, msg]); - self._clearFileInput(); - self._setValidationError(); - }, - _parseError: function (operation, jqXHR, errorThrown, fileName) { - /** @namespace jqXHR.responseJSON */ - var self = this, errMsg = $.trim(errorThrown + ''), textPre, errText, text; - errText = jqXHR.responseJSON && jqXHR.responseJSON.error ? jqXHR.responseJSON.error.toString() : ''; - text = errText ? errText : jqXHR.responseText; - if (self.cancelling && self.msgUploadAborted) { - errMsg = self.msgUploadAborted; - } - if (self.showAjaxErrorDetails && text) { - if (errText) { - errMsg = $.trim(errText + ''); - } else { - text = $.trim(text.replace(/\n\s*\n/g, '\n')); - textPre = text.length ? '
    ' + text + '
    ' : ''; - errMsg += errMsg ? textPre : text; - } - } - if (!errMsg) { - errMsg = self.msgAjaxError.replace('{operation}', operation); - } - self.cancelling = false; - return fileName ? '' + fileName + ': ' + errMsg : errMsg; - }, - _parseFileType: function (type, name) { - var self = this, isValid, vType, cat, i, types = self.allowedPreviewTypes || []; - if (type === 'application/text-plain') { - return 'text'; - } - for (i = 0; i < types.length; i++) { - cat = types[i]; - isValid = self.fileTypeSettings[cat]; - vType = isValid(type, name) ? cat : ''; - if (!$h.isEmpty(vType)) { - return vType; - } - } - return 'other'; - }, - _getPreviewIcon: function (fname) { - var self = this, ext, out = null; - if (fname && fname.indexOf('.') > -1) { - ext = fname.split('.').pop(); - if (self.previewFileIconSettings) { - out = self.previewFileIconSettings[ext] || self.previewFileIconSettings[ext.toLowerCase()] || null; - } - if (self.previewFileExtSettings) { - $.each(self.previewFileExtSettings, function (key, func) { - if (self.previewFileIconSettings[key] && func(ext)) { - out = self.previewFileIconSettings[key]; - //noinspection UnnecessaryReturnStatementJS - return; - } - }); - } - } - return out || self.previewFileIcon; - }, - _parseFilePreviewIcon: function (content, fname) { - var self = this, icn = self._getPreviewIcon(fname), out = content; - if (out.indexOf('{previewFileIcon}') > -1) { - out = out.setTokens({'previewFileIconClass': self.previewFileIconClass, 'previewFileIcon': icn}); - } - return out; - }, - _raise: function (event, params) { - var self = this, e = $.Event(event); - if (params !== undefined) { - self.$element.trigger(e, params); - } else { - self.$element.trigger(e); - } - if (e.isDefaultPrevented() || e.result === false) { - return false; - } - switch (event) { - // ignore these events - case 'filebatchuploadcomplete': - case 'filebatchuploadsuccess': - case 'fileuploaded': - case 'fileclear': - case 'filecleared': - case 'filereset': - case 'fileerror': - case 'filefoldererror': - case 'fileuploaderror': - case 'filebatchuploaderror': - case 'filedeleteerror': - case 'filecustomerror': - case 'filesuccessremove': - break; - // receive data response via `filecustomerror` event` - default: - if (!self.ajaxAborted) { - self.ajaxAborted = e.result; - } - break; - } - return true; - }, - _listenFullScreen: function (isFullScreen) { - var self = this, $modal = self.$modal, $btnFull, $btnBord; - if (!$modal || !$modal.length) { - return; - } - $btnFull = $modal && $modal.find('.btn-fullscreen'); - $btnBord = $modal && $modal.find('.btn-borderless'); - if (!$btnFull.length || !$btnBord.length) { - return; - } - $btnFull.removeClass('active').attr('aria-pressed', 'false'); - $btnBord.removeClass('active').attr('aria-pressed', 'false'); - if (isFullScreen) { - $btnFull.addClass('active').attr('aria-pressed', 'true'); - } else { - $btnBord.addClass('active').attr('aria-pressed', 'true'); - } - if ($modal.hasClass('file-zoom-fullscreen')) { - self._maximizeZoomDialog(); - } else { - if (isFullScreen) { - self._maximizeZoomDialog(); - } else { - $btnBord.removeClass('active').attr('aria-pressed', 'false'); - } - } - }, - _listen: function () { - var self = this, $el = self.$element, $form = self.$form, $cont = self.$container, fullScreenEv, $cap, fn; - self._handler($el, 'click', function (e) { - if ($el.hasClass('file-no-browse')) { - if ($el.data('zoneClicked')) { - $el.data('zoneClicked', false); - } else { - e.preventDefault(); - } - } - }); - self._handler($el, 'change', $.proxy(self._change, self)); - if (self.showBrowse) { - self._handler(self.$btnFile, 'click', $.proxy(self._browse, self)); - } - $cap = $cont.find('.file-caption-name'); - fn = function () { - return false; - }; - self._handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self)); - self._handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self)); - self._handler($cont.find('.fileinput-pause'), 'click', $.proxy(self.pause, self)); - self._handler($cap, 'keydown', fn); - self._handler($cap, 'paste', fn); - self._initDragDrop(); - self._handler($form, 'reset', $.proxy(self.clear, self)); - if (!self.isAjaxUpload) { - self._handler($form, 'submit', $.proxy(self._submitForm, self)); - } - self._handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self)); - self._handler($(window), 'resize', function () { - self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight); - }); - fullScreenEv = 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange'; - self._handler($(document), fullScreenEv, function () { - self._listenFullScreen($h.checkFullScreen()); - }); - self._autoFitContent(); - self._initClickable(); - self._refreshPreview(); - }, - _autoFitContent: function () { - var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, - self = this, config = width < 400 ? (self.previewSettingsSmall || self.defaults.previewSettingsSmall) : - (self.previewSettings || self.defaults.previewSettings), sel; - $.each(config, function (cat, settings) { - sel = '.file-preview-frame .file-preview-' + cat; - self.$preview.find(sel + '.kv-preview-data,' + sel + ' .kv-preview-data').css(settings); - }); - }, - _scanDroppedItems: function (item, files, path) { - path = path || ''; - var self = this, i, dirReader, readDir, errorHandler = function (e) { - self._log($h.logMessages.badDroppedFiles); - self._log(e); - }; - if (item.isFile) { - item.file(function (file) { - if (path) { - file.newPath = path + file.name; - } - files.push(file); - }, errorHandler); - } else { - if (item.isDirectory) { - dirReader = item.createReader(); - readDir = function () { - dirReader.readEntries(function (entries) { - if (entries && entries.length > 0) { - for (i = 0; i < entries.length; i++) { - self._scanDroppedItems(entries[i], files, path + item.name + '/'); - } - // recursively call readDir() again, since browser can only handle first 100 entries. - readDir(); - } - return null; - }, errorHandler); - }; - readDir(); - } - } - - }, - _initDragDrop: function () { - var self = this, $zone = self.$dropZone; - if (self.dropZoneEnabled && self.showPreview) { - self._handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self)); - self._handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self)); - self._handler($zone, 'drop', $.proxy(self._zoneDrop, self)); - self._handler($(document), 'dragenter dragover drop', self._zoneDragDropInit); - } - }, - _zoneDragDropInit: function (e) { - e.stopPropagation(); - e.preventDefault(); - }, - _zoneDragEnter: function (e) { - var self = this, dt = e.originalEvent.dataTransfer, hasFiles = $.inArray('Files', dt.types) > -1; - self._zoneDragDropInit(e); - if (self.isDisabled || !hasFiles) { - dt.effectAllowed = 'none'; - dt.dropEffect = 'none'; - return; - } - dt.dropEffect = 'copy'; - if (self._raise('fileDragEnter', {'sourceEvent': e, 'files': dt.types.Files})) { - $h.addCss(self.$dropZone, 'file-highlighted'); - } - }, - _zoneDragLeave: function (e) { - var self = this; - self._zoneDragDropInit(e); - if (self.isDisabled) { - return; - } - if (self._raise('fileDragLeave', {'sourceEvent': e})) { - self.$dropZone.removeClass('file-highlighted'); - } - - }, - _zoneDrop: function (e) { - /** @namespace e.originalEvent.dataTransfer */ - var self = this, i, $el = self.$element, dt = e.originalEvent.dataTransfer, - files = dt.files, items = dt.items, folders = $h.getDragDropFolders(items), - processFiles = function () { - if (!self.isAjaxUpload) { - self.changeTriggered = true; - $el.get(0).files = files; - setTimeout(function () { - self.changeTriggered = false; - $el.trigger('change' + self.namespace); - }, self.processDelay); - } else { - self._change(e, files); - } - self.$dropZone.removeClass('file-highlighted'); - }; - e.preventDefault(); - if (self.isDisabled || $h.isEmpty(files)) { - return; - } - if (!self._raise('fileDragDrop', {'sourceEvent': e, 'files': files})) { - return; - } - if (folders > 0) { - if (!self.isAjaxUpload) { - self._showFolderError(folders); - return; - } - files = []; - for (i = 0; i < items.length; i++) { - var item = items[i].webkitGetAsEntry(); - if (item) { - self._scanDroppedItems(item, files); - } - } - setTimeout(function () { - processFiles(); - }, 500); - } else { - processFiles(); - } - }, - _uploadClick: function (e) { - var self = this, $btn = self.$container.find('.fileinput-upload'), $form, - isEnabled = !$btn.hasClass('disabled') && $h.isEmpty($btn.attr('disabled')); - if (e && e.isDefaultPrevented()) { - return; - } - if (!self.isAjaxUpload) { - if (isEnabled && $btn.attr('type') !== 'submit') { - $form = $btn.closest('form'); - // downgrade to normal form submit if possible - if ($form.length) { - $form.trigger('submit'); - } - e.preventDefault(); - } - return; - } - e.preventDefault(); - if (isEnabled) { - self.upload(); - } - }, - _submitForm: function () { - var self = this; - return self._isFileSelectionValid() && !self._abort({}); - }, - _clearPreview: function () { - var self = this, - $thumbs = self.showUploadedThumbs ? self.getFrames(':not(.file-preview-success)') : self.getFrames(); - $thumbs.each(function () { - var $thumb = $(this); - $thumb.remove(); - }); - if (!self.getFrames().length || !self.showPreview) { - self._resetUpload(); - } - self._validateDefaultPreview(); - }, - _initSortable: function () { - var self = this, $el = self.$preview, settings, selector = '.' + $h.SORT_CSS, $cont, $body = $('body'), - $html = $('html'), rev = self.reversePreviewOrder, Sortable = window.Sortable, beginGrab, endGrab; - if (!Sortable || $el.find(selector).length === 0) { - return; - } - $cont = $body.length ? $body : ($html.length ? $html : self.$container); - beginGrab = function () { - $cont.addClass('file-grabbing'); - }; - endGrab = function () { - $cont.removeClass('file-grabbing'); - }; - settings = { - handle: '.drag-handle-init', - dataIdAttr: 'data-fileid', - animation: 600, - draggable: selector, - scroll: false, - forceFallback: true, - onChoose: beginGrab, - onStart: beginGrab, - onUnchoose: endGrab, - onEnd: endGrab, - onSort: function (e) { - var oldIndex = e.oldIndex, newIndex = e.newIndex, i = 0, len = self.initialPreviewConfig.length, - exceedsLast = len > 0 && newIndex >= len, $item = $(e.item), $first; - if (exceedsLast) { - newIndex = len - 1; - } - self.initialPreview = $h.moveArray(self.initialPreview, oldIndex, newIndex, rev); - self.initialPreviewConfig = $h.moveArray(self.initialPreviewConfig, oldIndex, newIndex, rev); - self.previewCache.init(); - self.getFrames('.file-preview-initial').each(function () { - $(this).attr('data-fileindex', $h.INIT_FLAG + i); - i++; - }); - if (exceedsLast) { - $first = self.getFrames(':not(.file-preview-initial):first'); - if ($first.length) { - $item.slideUp(function () { - $item.insertBefore($first).slideDown(); - }); - } - } - self._raise('filesorted', { - previewId: $item.attr('id'), - 'oldIndex': oldIndex, - 'newIndex': newIndex, - stack: self.initialPreviewConfig - }); - }, - }; - $.extend(true, settings, self.fileActionSettings.dragSettings); - if (self.sortable) { - self.sortable.destroy(); - } - self.sortable = Sortable.create($el[0], settings); - }, - _setPreviewContent: function (content) { - var self = this; - $h.setHtml(self.$preview, content); - self._autoFitContent(); - }, - _initPreviewImageOrientations: function () { - var self = this, i = 0, canOrientImage = self.canOrientImage; - if (!self.autoOrientImageInitial && !canOrientImage) { - return; - } - self.getFrames('.file-preview-initial').each(function () { - var $thumb = $(this), $img, $zoomImg, id, config = self.initialPreviewConfig[i]; - /** @namespace config.exif */ - if (config && config.exif && config.exif.Orientation) { - id = $thumb.attr('id'); - $img = $thumb.find('>.kv-file-content img'); - $zoomImg = self._getZoom(id, ' >.kv-file-content img'); - if (canOrientImage) { - $img.css('image-orientation', (self.autoOrientImageInitial ? 'from-image' : 'none')); - } else { - self.setImageOrientation($img, $zoomImg, config.exif.Orientation, $thumb); - } - } - i++; - }); - }, - _initPreview: function (isInit) { - var self = this, cap = self.initialCaption || '', out; - if (!self.previewCache.count(true)) { - self._clearPreview(); - if (isInit) { - self._setCaption(cap); - } else { - self._initCaption(); - } - return; - } - out = self.previewCache.out(); - cap = isInit && self.initialCaption ? self.initialCaption : out.caption; - self._setPreviewContent(out.content); - self._setInitThumbAttr(); - self._setCaption(cap); - self._initSortable(); - if (!$h.isEmpty(out.content)) { - self.$container.removeClass('file-input-new'); - } - self._initPreviewImageOrientations(); - }, - _getZoomButton: function (type) { - var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type], - title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ', - params = title + (type === 'close' ? ' data-dismiss="modal" aria-hidden="true"' : ''); - if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') { - params += ' data-toggle="button" aria-pressed="false" autocomplete="off"'; - } - return ''; - }, - _getModalContent: function () { - var self = this; - return self._getLayoutTemplate('modal').setTokens({ - 'rtl': self.rtl ? ' kv-rtl' : '', - 'zoomFrameClass': self.frameClass, - 'heading': self.msgZoomModalHeading, - 'prev': self._getZoomButton('prev'), - 'next': self._getZoomButton('next'), - 'toggleheader': self._getZoomButton('toggleheader'), - 'fullscreen': self._getZoomButton('fullscreen'), - 'borderless': self._getZoomButton('borderless'), - 'close': self._getZoomButton('close') - }); - }, - _listenModalEvent: function (event) { - var self = this, $modal = self.$modal, getParams = function (e) { - return { - sourceEvent: e, - previewId: $modal.data('previewId'), - modal: $modal - }; - }; - $modal.on(event + '.bs.modal', function (e) { - var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'); - if ($modal.data('fileinputPluginId') === self.$element.attr('id')) { - self._raise('filezoom' + event, getParams(e)); - } - if (event === 'shown') { - $btnBord.removeClass('active').attr('aria-pressed', 'false'); - $btnFull.removeClass('active').attr('aria-pressed', 'false'); - if ($modal.hasClass('file-zoom-fullscreen')) { - self._maximizeZoomDialog(); - if ($h.checkFullScreen()) { - $btnFull.addClass('active').attr('aria-pressed', 'true'); - } else { - $btnBord.addClass('active').attr('aria-pressed', 'true'); - } - } - } - }); - }, - _initZoom: function () { - var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID; - if (!self.showPreview) { - return; - } - self.$modal = $(modalId); - if (!self.$modal || !self.$modal.length) { - $dialog = $h.createElement($h.cspBuffer.stash(modalMain)).insertAfter(self.$container); - self.$modal = $(modalId).insertBefore($dialog); - $h.cspBuffer.apply(self.$modal); - $dialog.remove(); - } - $h.initModal(self.$modal); - self.$modal.html($h.cspBuffer.stash(self._getModalContent())); - $h.cspBuffer.apply(self.$modal); - $.each($h.MODAL_EVENTS, function (key, event) { - self._listenModalEvent(event); - }); - }, - _initZoomButtons: function () { - var self = this, previewId = self.$modal.data('previewId') || '', $first, $last, - thumbs = self.getFrames().toArray(), len = thumbs.length, $prev = self.$modal.find('.btn-prev'), - $next = self.$modal.find('.btn-next'); - if (thumbs.length < 2) { - $prev.hide(); - $next.hide(); - return; - } else { - $prev.show(); - $next.show(); - } - if (!len) { - return; - } - $first = $(thumbs[0]); - $last = $(thumbs[len - 1]); - $prev.removeAttr('disabled'); - $next.removeAttr('disabled'); - if ($first.length && $first.attr('id') === previewId) { - $prev.attr('disabled', true); - } - if ($last.length && $last.attr('id') === previewId) { - $next.attr('disabled', true); - } - }, - _maximizeZoomDialog: function () { - var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'), - $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'), - h = $(window).height(), diff = 0; - $modal.addClass('file-zoom-fullscreen'); - if ($head && $head.length) { - h -= $head.outerHeight(true); - } - if ($foot && $foot.length) { - h -= $foot.outerHeight(true); - } - if ($body && $body.length) { - diff = $body.outerHeight(true) - $body.height(); - h -= diff; - } - $modal.find('.kv-zoom-body').height(h); - }, - _resizeZoomDialog: function (fullScreen) { - var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'), - $btnBord = $modal.find('.btn-borderless'); - if ($modal.hasClass('file-zoom-fullscreen')) { - $h.toggleFullScreen(false); - if (!fullScreen) { - if (!$btnFull.hasClass('active')) { - $modal.removeClass('file-zoom-fullscreen'); - self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight); - } else { - $btnFull.removeClass('active').attr('aria-pressed', 'false'); - } - } else { - if (!$btnFull.hasClass('active')) { - $modal.removeClass('file-zoom-fullscreen'); - self._resizeZoomDialog(true); - if ($btnBord.hasClass('active')) { - $btnBord.removeClass('active').attr('aria-pressed', 'false'); - } - } - } - } else { - if (!fullScreen) { - self._maximizeZoomDialog(); - return; - } - $h.toggleFullScreen(true); - } - $modal.focus(); - }, - _setZoomContent: function ($frame, animate) { - var self = this, $content, tmplt, body, title, $body, $dataEl, config, previewId = $frame.attr('id'), - $zoomPreview = self._getZoom(previewId), $modal = self.$modal, $tmp, - $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'), cap, size, - $btnTogh = $modal.find('.btn-toggleheader'); - tmplt = $zoomPreview.attr('data-template') || 'generic'; - $content = $zoomPreview.find('.kv-file-content'); - body = $content.length ? $content.html() : ''; - cap = $frame.data('caption') || ''; - size = $frame.data('size') || ''; - title = cap + ' ' + size; - $modal.find('.kv-zoom-title').attr('title', $('
    ').html(title).text()).html(title); - $body = $modal.find('.kv-zoom-body'); - $modal.removeClass('kv-single-content'); - if (animate) { - $tmp = $body.addClass('file-thumb-loading').clone().insertAfter($body); - $h.setHtml($body, body).hide(); - $tmp.fadeOut('fast', function () { - $body.fadeIn('fast', function () { - $body.removeClass('file-thumb-loading'); - }); - $tmp.remove(); - }); - } else { - $h.setHtml($body, body); - } - config = self.previewZoomSettings[tmplt]; - if (config) { - $dataEl = $body.find('.kv-preview-data'); - $h.addCss($dataEl, 'file-zoom-detail'); - $.each(config, function (key, value) { - $dataEl.css(key, value); - if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) { - $dataEl.removeAttr(key); - } - }); - } - $modal.data('previewId', previewId); - self._handler($modal.find('.btn-prev'), 'click', function () { - self._zoomSlideShow('prev', previewId); - }); - self._handler($modal.find('.btn-next'), 'click', function () { - self._zoomSlideShow('next', previewId); - }); - self._handler($btnFull, 'click', function () { - self._resizeZoomDialog(true); - }); - self._handler($btnBord, 'click', function () { - self._resizeZoomDialog(false); - }); - self._handler($btnTogh, 'click', function () { - var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'), - ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) { - var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight; - if ($modal.hasClass('file-zoom-fullscreen')) { - h = $body.outerHeight(true); - if (!height) { - h = h - $header.outerHeight(true); - } - } - $body.css('height', height ? h + height : h); - }; - if ($header.is(':visible')) { - ht = $header.outerHeight(true); - $header.slideUp('slow', function () { - $actions.find('.btn').appendTo($floatBar); - resize(ht); - }); - } else { - $floatBar.find('.btn').appendTo($actions); - $header.slideDown('slow', function () { - resize(); - }); - } - $modal.focus(); - }); - self._handler($modal, 'keydown', function (e) { - var key = e.which || e.keyCode, $prev = $(this).find('.btn-prev'), $next = $(this).find('.btn-next'), - vId = $(this).data('previewId'), vPrevKey = self.rtl ? 39 : 37, vNextKey = self.rtl ? 37 : 39; - if (key === vPrevKey && $prev.length && !$prev.attr('disabled')) { - self._zoomSlideShow('prev', vId); - } - if (key === vNextKey && $next.length && !$next.attr('disabled')) { - self._zoomSlideShow('next', vId); - } - }); - }, - _showModal: function ($frame) { - var self = this, $modal = self.$modal; - if (!$frame || !$frame.length) { - return; - } - $h.initModal($modal); - $h.setHtml($modal, self._getModalContent()); - self._setZoomContent($frame); - $modal.data('fileinputPluginId', self.$element.attr('id')); - $modal.modal('show'); - self._initZoomButtons(); - }, - _zoomPreview: function ($btn) { - var self = this, $frame; - if (!$btn.length) { - throw 'Cannot zoom to detailed preview!'; - } - $frame = $btn.closest($h.FRAMES); - self._showModal($frame); - }, - _zoomSlideShow: function (dir, previewId) { - var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i, $thumb, - thumbsData = self.getFrames().toArray(), thumbs = [], len = thumbsData.length, out; - if ($btn.attr('disabled')) { - return; - } - for (i = 0; i < len; i++) { - $thumb = $(thumbsData[i]); - if ($thumb && $thumb.length && $thumb.find('.kv-file-zoom:visible').length) { - thumbs.push(thumbsData[i]); - } - } - len = thumbs.length; - for (i = 0; i < len; i++) { - if ($(thumbs[i]).attr('id') === previewId) { - out = dir === 'prev' ? i - 1 : i + 1; - break; - } - } - if (out < 0 || out >= len || !thumbs[out]) { - return; - } - $targFrame = $(thumbs[out]); - if ($targFrame.length) { - self._setZoomContent($targFrame, true); - } - self._initZoomButtons(); - self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal}); - }, - _initZoomButton: function () { - var self = this; - self.$preview.find('.kv-file-zoom').each(function () { - var $el = $(this); - self._handler($el, 'click', function () { - self._zoomPreview($el); - }); - }); - }, - _inputFileCount: function () { - return this.$element[0].files.length; - }, - _refreshPreview: function () { - var self = this, files; - if ((!self._inputFileCount() && !self.isAjaxUpload) || !self.showPreview || !self.isPreviewable) { - return; - } - if (self.isAjaxUpload) { - if (self.fileManager.count() > 0) { - files = $.extend(true, {}, self.fileManager.stack); - self.fileManager.clear(); - self._clearFileInput(); - } else { - files = self.$element[0].files; - } - } else { - files = self.$element[0].files; - } - if (files && files.length) { - self.readFiles(files); - self._setFileDropZoneTitle(); - } - }, - _clearObjects: function ($el) { - $el.find('video audio').each(function () { - this.pause(); - $(this).remove(); - }); - $el.find('img object div').each(function () { - $(this).remove(); - }); - }, - _clearFileInput: function () { - var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl; - if (!self._inputFileCount()) { - return; - } - $srcFrm = $el.closest('form'); - $tmpFrm = $(document.createElement('form')); - $tmpEl = $(document.createElement('div')); - $el.before($tmpEl); - if ($srcFrm.length) { - $srcFrm.after($tmpFrm); - } else { - $tmpEl.after($tmpFrm); - } - $tmpFrm.append($el).trigger('reset'); - $tmpEl.before($el).remove(); - $tmpFrm.remove(); - }, - _resetUpload: function () { - var self = this; - self.uploadStartTime = $h.now(); - self.uploadCache = []; - self.$btnUpload.removeAttr('disabled'); - self._setProgress(0); - self._hideProgress(); - self._resetErrors(false); - self._initAjax(); - self.fileManager.clearImages(); - self._resetCanvas(); - if (self.overwriteInitial) { - self.initialPreview = []; - self.initialPreviewConfig = []; - self.initialPreviewThumbTags = []; - self.previewCache.data = { - content: [], - config: [], - tags: [] - }; - } - }, - _resetCanvas: function () { - var self = this; - if (self.canvas && self.imageCanvasContext) { - self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height); - } - }, - _hasInitialPreview: function () { - var self = this; - return !self.overwriteInitial && self.previewCache.count(true); - }, - _resetPreview: function () { - var self = this, out, cap, $div, hasSuc = self.showUploadedThumbs, hasErr = !self.removeFromPreviewOnError, - includeProcessed = (hasSuc || hasErr) && self.isDuplicateError; - if (self.previewCache.count(true)) { - out = self.previewCache.out(); - if (includeProcessed) { - $div = $h.createElement('').insertAfter(self.$container); - self.getFrames().each(function () { - var $thumb = $(this); - if ((hasSuc && $thumb.hasClass('file-preview-success')) || - (hasErr && $thumb.hasClass('file-preview-error'))) { - $div.append($thumb); - } - }); - } - self._setPreviewContent(out.content); - self._setInitThumbAttr(); - cap = self.initialCaption ? self.initialCaption : out.caption; - self._setCaption(cap); - if (includeProcessed) { - $div.contents().appendTo(self.$preview); - $div.remove(); - } - } else { - self._clearPreview(); - self._initCaption(); - } - if (self.showPreview) { - self._initZoom(); - self._initSortable(); - } - self.isDuplicateError = false; - }, - _clearDefaultPreview: function () { - var self = this; - self.$preview.find('.file-default-preview').remove(); - }, - _validateDefaultPreview: function () { - var self = this; - if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) { - return; - } - self._setPreviewContent('
    ' + self.defaultPreviewContent + '
    '); - self.$container.removeClass('file-input-new'); - self._initClickable(); - }, - _resetPreviewThumbs: function (isAjax) { - var self = this, out; - if (isAjax) { - self._clearPreview(); - self.clearFileStack(); - return; - } - if (self._hasInitialPreview()) { - out = self.previewCache.out(); - self._setPreviewContent(out.content); - self._setInitThumbAttr(); - self._setCaption(out.caption); - self._initPreviewActions(); - } else { - self._clearPreview(); - } - }, - _getLayoutTemplate: function (t) { - var self = this, template = self.layoutTemplates[t]; - if ($h.isEmpty(self.customLayoutTags)) { - return template; - } - return $h.replaceTags(template, self.customLayoutTags); - }, - _getPreviewTemplate: function (t) { - var self = this, templates = self.previewTemplates, template = templates[t] || templates.other; - if ($h.isEmpty(self.customPreviewTags)) { - return template; - } - return $h.replaceTags(template, self.customPreviewTags); - }, - _getOutData: function (formdata, jqXHR, responseData, filesData) { - var self = this; - jqXHR = jqXHR || {}; - responseData = responseData || {}; - filesData = filesData || self.fileManager.list(); - return { - formdata: formdata, - files: filesData, - filenames: self.filenames, - filescount: self.getFilesCount(), - extra: self._getExtraData(), - response: responseData, - reader: self.reader, - jqXHR: jqXHR - }; - }, - _getMsgSelected: function (n) { - var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural; - return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected; - }, - _getFrame: function (id, skipWarning) { - var self = this, $frame = $h.getFrameElement(self.$preview, id); - if (self.showPreview && !skipWarning && !$frame.length) { - self._log($h.logMessages.invalidThumb, {id: id}); - } - return $frame; - }, - _getZoom: function (id, selector) { - var self = this, $frame = $h.getZoomElement(self.$preview, id, selector); - if (self.showPreview && !$frame.length) { - self._log($h.logMessages.invalidThumb, {id: id}); - } - return $frame; - }, - _getThumbs: function (css) { - css = css || ''; - return this.getFrames(':not(.file-preview-initial)' + css); - }, - _getThumbId: function (fileId) { - var self = this; - return self.previewInitId + '-' + fileId; - }, - _getExtraData: function (fileId, index) { - var self = this, data = self.uploadExtraData; - if (typeof self.uploadExtraData === 'function') { - data = self.uploadExtraData(fileId, index); - } - return data; - }, - _initXhr: function (xhrobj, fileId) { - var self = this, fm = self.fileManager, func = function (event) { - var pct = 0, total = event.total, loaded = event.loaded || event.position, - stats = fm.getUploadStats(fileId, loaded, total); - /** @namespace event.lengthComputable */ - if (event.lengthComputable && !self.enableResumableUpload) { - pct = $h.round(loaded / total * 100); - } - if (fileId) { - self._setFileUploadStats(fileId, pct, stats); - } else { - self._setProgress(pct, null, null, self._getStats(stats)); - } - self._raise('fileajaxprogress', [stats]); - }; - if (xhrobj.upload) { - if (self.progressDelay) { - func = $h.debounce(func, self.progressDelay); - } - xhrobj.upload.addEventListener('progress', func, false); - } - return xhrobj; - }, - _initAjaxSettings: function () { - var self = this; - self._ajaxSettings = $.extend(true, {}, self.ajaxSettings); - self._ajaxDeleteSettings = $.extend(true, {}, self.ajaxDeleteSettings); - }, - _mergeAjaxCallback: function (funcName, srcFunc, type) { - var self = this, settings = self._ajaxSettings, flag = self.mergeAjaxCallbacks, targFunc; - if (type === 'delete') { - settings = self._ajaxDeleteSettings; - flag = self.mergeAjaxDeleteCallbacks; - } - targFunc = settings[funcName]; - if (flag && typeof targFunc === 'function') { - if (flag === 'before') { - settings[funcName] = function () { - targFunc.apply(this, arguments); - srcFunc.apply(this, arguments); - }; - } else { - settings[funcName] = function () { - srcFunc.apply(this, arguments); - targFunc.apply(this, arguments); - }; - } - } else { - settings[funcName] = srcFunc; - } - }, - _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, formdata, fileId, index, vUrl) { - var self = this, settings, defaults, data, ajaxTask; - if (!self._raise('filepreajax', [formdata, fileId, index])) { - return; - } - formdata.append('initialPreview', JSON.stringify(self.initialPreview)); - formdata.append('initialPreviewConfig', JSON.stringify(self.initialPreviewConfig)); - formdata.append('initialPreviewThumbTags', JSON.stringify(self.initialPreviewThumbTags)); - self._initAjaxSettings(); - self._mergeAjaxCallback('beforeSend', fnBefore); - self._mergeAjaxCallback('success', fnSuccess); - self._mergeAjaxCallback('complete', fnComplete); - self._mergeAjaxCallback('error', fnError); - vUrl = vUrl || self.uploadUrlThumb || self.uploadUrl; - if (typeof vUrl === 'function') { - vUrl = vUrl(); - } - data = self._getExtraData(fileId, index) || {}; - if (typeof data === 'object') { - $.each(data, function (key, value) { - formdata.append(key, value); - }); - } - defaults = { - xhr: function () { - var xhrobj = $.ajaxSettings.xhr(); - return self._initXhr(xhrobj, fileId); - }, - url: self._encodeURI(vUrl), - type: 'POST', - dataType: 'json', - data: formdata, - cache: false, - processData: false, - contentType: false - }; - settings = $.extend(true, {}, defaults, self._ajaxSettings); - ajaxTask = self.taskManager.addTask(fileId + '-' + index, function () { - var self = this.self, config, xhr; - config = self.ajaxQueue.shift(); - xhr = $.ajax(config); - self.ajaxRequests.push(xhr); - }); - self.ajaxQueue.push(settings); - ajaxTask.runWithContext({self: self}); - }, - _mergeArray: function (prop, content) { - var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content); - self[prop] = arr1.concat(arr2); - }, - _initUploadSuccess: function (out, $thumb, allFiles) { - var self = this, append, data, index, $div, $newCache, content, config, tags, id, i; - if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) { - self._resetCaption(); - return; - } - if (out.initialPreview !== undefined && out.initialPreview.length > 0) { - self.hasInitData = true; - content = out.initialPreview || []; - config = out.initialPreviewConfig || []; - tags = out.initialPreviewThumbTags || []; - append = out.append === undefined || out.append; - if (content.length > 0 && !$h.isArray(content)) { - content = content.split(self.initialPreviewDelimiter); - } - if (content.length) { - self._mergeArray('initialPreview', content); - self._mergeArray('initialPreviewConfig', config); - self._mergeArray('initialPreviewThumbTags', tags); - } - if ($thumb !== undefined) { - if (!allFiles) { - index = self.previewCache.add(content[0], config[0], tags[0], append); - data = self.previewCache.get(index, false); - $div = $h.createElement(data).hide().appendTo($thumb); - $newCache = $div.find('.kv-zoom-cache'); - if ($newCache && $newCache.length) { - $newCache.appendTo($thumb); - } - $thumb.fadeOut('slow', function () { - var $newThumb = $div.find('.file-preview-frame'); - if ($newThumb && $newThumb.length) { - $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block'); - } - self._initPreviewActions(); - self._clearFileInput(); - $thumb.remove(); - $div.remove(); - self._initSortable(); - }); - } else { - id = $thumb.attr('id'); - i = self._getUploadCacheIndex(id); - if (i !== null) { - self.uploadCache[i] = { - id: id, - content: content[0], - config: config[0] || [], - tags: tags[0] || [], - append: append - }; - } - } - } else { - self.previewCache.set(content, config, tags, append); - self._initPreview(); - self._initPreviewActions(); - } - } - self._resetCaption(); - }, - _getUploadCacheIndex: function (id) { - var self = this, i, len = self.uploadCache.length, config; - for (i = 0; i < len; i++) { - config = self.uploadCache[i]; - if (config.id === id) { - return i; - } - } - return null; - }, - _initSuccessThumbs: function () { - var self = this; - if (!self.showPreview) { - return; - } - self._getThumbs($h.FRAMES + '.file-preview-success').each(function () { - var $thumb = $(this), $remove = $thumb.find('.kv-file-remove'); - $remove.removeAttr('disabled'); - self._handler($remove, 'click', function () { - var id = $thumb.attr('id'), - out = self._raise('filesuccessremove', [id, $thumb.attr('data-fileindex')]); - $h.cleanMemory($thumb); - if (out === false) { - return; - } - $thumb.fadeOut('slow', function () { - $thumb.remove(); - if (!self.getFrames().length) { - self.reset(); - } - }); - }); - }); - }, - _updateInitialPreview: function () { - var self = this, u = self.uploadCache; - if (self.showPreview) { - $.each(u, function (key, setting) { - self.previewCache.add(setting.content, setting.config, setting.tags, setting.append); - }); - if (self.hasInitData) { - self._initPreview(); - self._initPreviewActions(); - } - } - }, - _uploadSingle: function (i, id, isBatch) { - var self = this, fm = self.fileManager, count = fm.count(), formdata = new FormData(), outData, - previewId = self._getThumbId(id), $thumb, chkComplete, $btnUpload, $btnDelete, - hasPostData = count > 0 || !$.isEmptyObject(self.uploadExtraData), uploadFailed, $prog, fnBefore, - errMsg, fnSuccess, fnComplete, fnError, updateUploadLog, op = self.ajaxOperations.uploadThumb, - fileObj = fm.getFile(id), params = {id: previewId, index: i, fileId: id}, - fileName = self.fileManager.getFileName(id, true); - if (self.enableResumableUpload) { // not enabled for resumable uploads - return; - } - if (self.showPreview) { - $thumb = self.fileManager.getThumb(id); - $prog = $thumb.find('.file-thumb-progress'); - $btnUpload = $thumb.find('.kv-file-upload'); - $btnDelete = $thumb.find('.kv-file-remove'); - $prog.show(); - } - if (count === 0 || !hasPostData || (self.showPreview && $btnUpload && $btnUpload.hasClass('disabled')) || - self._abort(params)) { - return; - } - updateUploadLog = function () { - if (!uploadFailed) { - fm.removeFile(id); - } else { - fm.errors.push(id); - } - fm.setProcessed(id); - if (fm.isProcessed()) { - self.fileBatchCompleted = true; - chkComplete(); - } - }; - chkComplete = function () { - var $initThumbs; - if (!self.fileBatchCompleted) { - return; - } - setTimeout(function () { - var triggerReset = fm.count() === 0, errCount = fm.errors.length; - self._updateInitialPreview(); - self.unlock(triggerReset); - if (triggerReset) { - self._clearFileInput(); - } - $initThumbs = self.$preview.find('.file-preview-initial'); - if (self.uploadAsync && $initThumbs.length) { - $h.addCss($initThumbs, $h.SORT_CSS); - self._initSortable(); - } - self._raise('filebatchuploadcomplete', [fm.stack, self._getExtraData()]); - if (!self.retryErrorUploads || errCount === 0) { - fm.clear(); - } - self._setProgress(101); - self.ajaxAborted = false; - }, self.processDelay); - }; - fnBefore = function (jqXHR) { - outData = self._getOutData(formdata, jqXHR); - fm.initStats(id); - self.fileBatchCompleted = false; - if (!isBatch) { - self.ajaxAborted = false; - } - if (self.showPreview) { - if (!$thumb.hasClass('file-preview-success')) { - self._setThumbStatus($thumb, 'Loading'); - $h.addCss($thumb, 'file-uploading'); - } - $btnUpload.attr('disabled', true); - $btnDelete.attr('disabled', true); - } - if (!isBatch) { - self.lock(); - } - if (fm.errors.indexOf(id) !== -1) { - delete fm.errors[id]; - } - self._raise('filepreupload', [outData, previewId, i]); - $.extend(true, params, outData); - if (self._abort(params)) { - jqXHR.abort(); - if (!isBatch) { - self._setThumbStatus($thumb, 'New'); - $thumb.removeClass('file-uploading'); - $btnUpload.removeAttr('disabled'); - $btnDelete.removeAttr('disabled'); - self.unlock(); - } - self._setProgressCancelled(); - } - }; - fnSuccess = function (data, textStatus, jqXHR) { - var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId; - outData = self._getOutData(formdata, jqXHR, data); - $.extend(true, params, outData); - setTimeout(function () { - if ($h.isEmpty(data) || $h.isEmpty(data.error)) { - if (self.showPreview) { - self._setThumbStatus($thumb, 'Success'); - $btnUpload.hide(); - self._initUploadSuccess(data, $thumb, isBatch); - self._setProgress(101, $prog); - } - self._raise('fileuploaded', [outData, pid, i]); - if (!isBatch) { - self.fileManager.remove($thumb); - } else { - updateUploadLog(); - } - } else { - uploadFailed = true; - errMsg = self._parseError(op, jqXHR, self.msgUploadError, self.fileManager.getFileName(id)); - self._showFileError(errMsg, params); - self._setPreviewError($thumb, true); - if (!self.retryErrorUploads) { - $btnUpload.hide(); - } - if (isBatch) { - updateUploadLog(); - } - self._setProgress(101, self._getFrame(pid).find('.file-thumb-progress'), - self.msgUploadError); - } - }, self.processDelay); - }; - fnComplete = function () { - if (self.showPreview) { - $btnUpload.removeAttr('disabled'); - $btnDelete.removeAttr('disabled'); - $thumb.removeClass('file-uploading'); - } - if (!isBatch) { - self.unlock(false); - self._clearFileInput(); - } else { - chkComplete(); - } - self._initSuccessThumbs(); - }; - fnError = function (jqXHR, textStatus, errorThrown) { - errMsg = self._parseError(op, jqXHR, errorThrown, self.fileManager.getFileName(id)); - uploadFailed = true; - setTimeout(function () { - var $prog; - if (isBatch) { - updateUploadLog(); - } - self.fileManager.setProgress(id, 100); - self._setPreviewError($thumb, true); - if (!self.retryErrorUploads) { - $btnUpload.hide(); - } - $.extend(true, params, self._getOutData(formdata, jqXHR)); - self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op)); - $prog = self.showPreview && $thumb ? $thumb.find('.file-thumb-progress') : ''; - self._setProgress(101, $prog, self.msgUploadError); - self._showFileError(errMsg, params); - }, self.processDelay); - }; - self._setFileData(formdata, fileObj.file, fileName, id); - self._setUploadData(formdata, {fileId: id}); - self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata, id, i); - }, - _setFileData: function (formdata, file, fileName, fileId) { - var self = this, preProcess = self.preProcessUpload; - if (preProcess && typeof preProcess === 'function') { - formdata.append(self.uploadFileAttr, preProcess(fileId, file)); - } else { - formdata.append(self.uploadFileAttr, file, fileName); - } - }, - _uploadBatch: function () { - var self = this, fm = self.fileManager, total = fm.total(), params = {}, fnBefore, fnSuccess, fnError, - fnComplete, hasPostData = total > 0 || !$.isEmptyObject(self.uploadExtraData), errMsg, - setAllUploaded, formdata = new FormData(), op = self.ajaxOperations.uploadBatch; - if (total === 0 || !hasPostData || self._abort(params)) { - return; - } - setAllUploaded = function () { - self.fileManager.clear(); - self._clearFileInput(); - }; - fnBefore = function (jqXHR) { - self.lock(); - fm.initStats(); - var outData = self._getOutData(formdata, jqXHR); - self.ajaxAborted = false; - if (self.showPreview) { - self._getThumbs().each(function () { - var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), - $btnDelete = $thumb.find('.kv-file-remove'); - if (!$thumb.hasClass('file-preview-success')) { - self._setThumbStatus($thumb, 'Loading'); - $h.addCss($thumb, 'file-uploading'); - } - $btnUpload.attr('disabled', true); - $btnDelete.attr('disabled', true); - }); - } - self._raise('filebatchpreupload', [outData]); - if (self._abort(outData)) { - jqXHR.abort(); - self._getThumbs().each(function () { - var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), - $btnDelete = $thumb.find('.kv-file-remove'); - if ($thumb.hasClass('file-preview-loading')) { - self._setThumbStatus($thumb, 'New'); - $thumb.removeClass('file-uploading'); - } - $btnUpload.removeAttr('disabled'); - $btnDelete.removeAttr('disabled'); - }); - self._setProgressCancelled(); - } - }; - fnSuccess = function (data, textStatus, jqXHR) { - /** @namespace data.errorkeys */ - var outData = self._getOutData(formdata, jqXHR, data), key = 0, - $thumbs = self._getThumbs(':not(.file-preview-success)'), - keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys; - - if ($h.isEmpty(data) || $h.isEmpty(data.error)) { - self._raise('filebatchuploadsuccess', [outData]); - setAllUploaded(); - if (self.showPreview) { - $thumbs.each(function () { - var $thumb = $(this); - self._setThumbStatus($thumb, 'Success'); - $thumb.removeClass('file-uploading'); - $thumb.find('.kv-file-upload').hide().removeAttr('disabled'); - }); - self._initUploadSuccess(data); - } else { - self.reset(); - } - self._setProgress(101); - } else { - if (self.showPreview) { - $thumbs.each(function () { - var $thumb = $(this); - $thumb.removeClass('file-uploading'); - $thumb.find('.kv-file-upload').removeAttr('disabled'); - $thumb.find('.kv-file-remove').removeAttr('disabled'); - if (keys.length === 0 || $.inArray(key, keys) !== -1) { - self._setPreviewError($thumb, true); - if (!self.retryErrorUploads) { - $thumb.find('.kv-file-upload').hide(); - self.fileManager.remove($thumb); - } - } else { - $thumb.find('.kv-file-upload').hide(); - self._setThumbStatus($thumb, 'Success'); - self.fileManager.remove($thumb); - } - if (!$thumb.hasClass('file-preview-error') || self.retryErrorUploads) { - key++; - } - }); - self._initUploadSuccess(data); - } - errMsg = self._parseError(op, jqXHR, self.msgUploadError); - self._showFileError(errMsg, outData, 'filebatchuploaderror'); - self._setProgress(101, self.$progress, self.msgUploadError); - } - }; - fnComplete = function () { - self.unlock(); - self._initSuccessThumbs(); - self._clearFileInput(); - self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]); - }; - fnError = function (jqXHR, textStatus, errorThrown) { - var outData = self._getOutData(formdata, jqXHR); - errMsg = self._parseError(op, jqXHR, errorThrown); - self._showFileError(errMsg, outData, 'filebatchuploaderror'); - self.uploadFileCount = total - 1; - if (!self.showPreview) { - return; - } - self._getThumbs().each(function () { - var $thumb = $(this); - $thumb.removeClass('file-uploading'); - if (self.fileManager.getFile($thumb.attr('data-fileid'))) { - self._setPreviewError($thumb); - } - }); - self._getThumbs().removeClass('file-uploading'); - self._getThumbs(' .kv-file-upload').removeAttr('disabled'); - self._getThumbs(' .kv-file-delete').removeAttr('disabled'); - self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op)); - }; - var ctr = 0; - $.each(self.fileManager.stack, function (key, data) { - if (!$h.isEmpty(data.file)) { - self._setFileData(formdata, data.file, (data.nameFmt || ('untitled_' + ctr)), key); - } - ctr++; - }); - self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata); - }, - _uploadExtraOnly: function () { - var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError, formdata = new FormData(), errMsg, - op = self.ajaxOperations.uploadExtra; - if (self._abort(params)) { - return; - } - fnBefore = function (jqXHR) { - self.lock(); - var outData = self._getOutData(formdata, jqXHR); - self._raise('filebatchpreupload', [outData]); - self._setProgress(50); - params.data = outData; - params.xhr = jqXHR; - if (self._abort(params)) { - jqXHR.abort(); - self._setProgressCancelled(); - } - }; - fnSuccess = function (data, textStatus, jqXHR) { - var outData = self._getOutData(formdata, jqXHR, data); - if ($h.isEmpty(data) || $h.isEmpty(data.error)) { - self._raise('filebatchuploadsuccess', [outData]); - self._clearFileInput(); - self._initUploadSuccess(data); - self._setProgress(101); - } else { - errMsg = self._parseError(op, jqXHR, self.msgUploadError); - self._showFileError(errMsg, outData, 'filebatchuploaderror'); - } - }; - fnComplete = function () { - self.unlock(); - self._clearFileInput(); - self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]); - }; - fnError = function (jqXHR, textStatus, errorThrown) { - var outData = self._getOutData(formdata, jqXHR); - errMsg = self._parseError(op, jqXHR, errorThrown); - params.data = outData; - self._showFileError(errMsg, outData, 'filebatchuploaderror'); - self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op)); - }; - self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata); - }, - _deleteFileIndex: function ($frame) { - var self = this, ind = $frame.attr('data-fileindex'), rev = self.reversePreviewOrder; - if (ind.substring(0, 5) === $h.INIT_FLAG) { - ind = parseInt(ind.replace($h.INIT_FLAG, '')); - self.initialPreview = $h.spliceArray(self.initialPreview, ind, rev); - self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind, rev); - self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind, rev); - self.getFrames().each(function () { - var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex'); - if (nInd.substring(0, 5) === $h.INIT_FLAG) { - nInd = parseInt(nInd.replace($h.INIT_FLAG, '')); - if (nInd > ind) { - nInd--; - $nFrame.attr('data-fileindex', $h.INIT_FLAG + nInd); - } - } - }); - } - }, - _resetCaption: function () { - var self = this; - setTimeout(function () { - var cap, n, chk = self.previewCache.count(true), len = self.fileManager.count(), file, - incomplete = ':not(.file-preview-success):not(.file-preview-error)', - hasThumb = self.showPreview && self.getFrames(incomplete).length; - if (len === 0 && chk === 0 && !hasThumb) { - self.reset(); - } else { - n = chk + len; - if (n > 1) { - cap = self._getMsgSelected(n); - } else { - file = self.fileManager.getFirstFile(); - cap = file ? file.nameFmt : '_'; - } - self._setCaption(cap); - } - }, self.processDelay); - }, - _initFileActions: function () { - var self = this; - if (!self.showPreview) { - return; - } - self._initZoomButton(); - self.getFrames(' .kv-file-remove').each(function () { - var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'), - ind = $frame.attr('data-fileindex'), status; - self._handler($el, 'click', function () { - status = self._raise('filepreremove', [id, ind]); - if (status === false || !self._validateMinCount()) { - return false; - } - hasError = $frame.hasClass('file-preview-error'); - $h.cleanMemory($frame); - $frame.fadeOut('slow', function () { - self.fileManager.remove($frame); - self._clearObjects($frame); - $frame.remove(); - if (id && hasError) { - self.$errorContainer.find('li[data-thumb-id="' + id + '"]').fadeOut('fast', function () { - $(this).remove(); - if (!self._errorsExist()) { - self._resetErrors(); - } - }); - } - self._clearFileInput(); - self._resetCaption(); - self._raise('fileremoved', [id, ind]); - }); - }); - }); - self.getFrames(' .kv-file-upload').each(function () { - var $el = $(this); - self._handler($el, 'click', function () { - var $frame = $el.closest($h.FRAMES), fileId = $frame.attr('data-fileid'); - self._hideProgress(); - if ($frame.hasClass('file-preview-error') && !self.retryErrorUploads) { - return; - } - self._uploadSingle(self.fileManager.getIndex(fileId), fileId, false); - }); - }); - }, - _initPreviewActions: function () { - var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {}, - btnRemove = $h.FRAMES + ' .kv-file-remove', settings = self.fileActionSettings, - origClass = settings.removeClass, errClass = settings.removeErrorClass, - resetProgress = function () { - var hasFiles = self.isAjaxUpload ? self.previewCache.count(true) : self._inputFileCount(); - if (!self.getFrames().length && !hasFiles) { - self._setCaption(''); - self.reset(); - self.initialCaption = ''; - } - }; - self._initZoomButton(); - $preview.find(btnRemove).each(function () { - var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), errMsg, fnBefore, - fnSuccess, fnError, op = self.ajaxOperations.deleteThumb; - if ($h.isEmpty(vUrl) || vKey === undefined) { - return; - } - if (typeof vUrl === 'function') { - vUrl = vUrl(); - } - var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data, settings, params, config, - fileName, extraData, index = $frame.attr('data-fileindex'); - index = parseInt(index.replace($h.INIT_FLAG, '')); - config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index]; - extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra; - fileName = config && (config.filename || config.caption) || ''; - if (typeof extraData === 'function') { - extraData = extraData(); - } - params = {id: $el.attr('id'), key: vKey, extra: extraData}; - fnBefore = function (jqXHR) { - self.ajaxAborted = false; - self._raise('filepredelete', [vKey, jqXHR, extraData]); - if (self._abort()) { - jqXHR.abort(); - } else { - $el.removeClass(errClass); - $h.addCss($frame, 'file-uploading'); - $h.addCss($el, 'disabled ' + origClass); - } - }; - fnSuccess = function (data, textStatus, jqXHR) { - var n, cap; - if (!$h.isEmpty(data) && !$h.isEmpty(data.error)) { - params.jqXHR = jqXHR; - params.response = data; - errMsg = self._parseError(op, jqXHR, self.msgDeleteError, fileName); - self._showFileError(errMsg, params, 'filedeleteerror'); - $frame.removeClass('file-uploading'); - $el.removeClass('disabled ' + origClass).addClass(errClass); - resetProgress(); - return; - } - $frame.removeClass('file-uploading').addClass('file-deleted'); - $frame.fadeOut('slow', function () { - index = parseInt(($frame.attr('data-fileindex')).replace($h.INIT_FLAG, '')); - self.previewCache.unset(index); - self._deleteFileIndex($frame); - n = self.previewCache.count(true); - cap = n > 0 ? self._getMsgSelected(n) : ''; - self._setCaption(cap); - self._raise('filedeleted', [vKey, jqXHR, extraData]); - self._clearObjects($frame); - $frame.remove(); - resetProgress(); - }); - }; - fnError = function (jqXHR, textStatus, errorThrown) { - var errMsg = self._parseError(op, jqXHR, errorThrown, fileName); - params.jqXHR = jqXHR; - params.response = {}; - self._showFileError(errMsg, params, 'filedeleteerror'); - $frame.removeClass('file-uploading'); - $el.removeClass('disabled ' + origClass).addClass(errClass); - resetProgress(); - }; - self._initAjaxSettings(); - self._mergeAjaxCallback('beforeSend', fnBefore, 'delete'); - self._mergeAjaxCallback('success', fnSuccess, 'delete'); - self._mergeAjaxCallback('error', fnError, 'delete'); - settings = $.extend(true, {}, { - url: self._encodeURI(vUrl), - type: 'POST', - dataType: 'json', - data: $.extend(true, {}, {key: vKey}, extraData) - }, self._ajaxDeleteSettings); - self._handler($el, 'click', function () { - if (!self._validateMinCount()) { - return false; - } - self.ajaxAborted = false; - self._raise('filebeforedelete', [vKey, extraData]); - if (self.ajaxAborted instanceof Promise) { - self.ajaxAborted.then(function (result) { - if (!result) { - $.ajax(settings); - } - }); - } else { - if (!self.ajaxAborted) { - $.ajax(settings); - } - } - }); - }); - }, - _hideFileIcon: function () { - var self = this; - if (self.overwriteInitial) { - self.$captionContainer.removeClass('icon-visible'); - } - }, - _showFileIcon: function () { - var self = this; - $h.addCss(self.$captionContainer, 'icon-visible'); - }, - _getSize: function (bytes, sizes) { - var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, out; - if (!$.isNumeric(bytes) || !$.isNumeric(size)) { - return ''; - } - if (typeof func === 'function') { - out = func(size); - } else { - if (size === 0) { - out = '0.00 B'; - } else { - i = Math.floor(Math.log(size) / Math.log(1024)); - if (!sizes) { - sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - } - out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i]; - } - } - return self._getLayoutTemplate('size').replace('{sizeText}', out); - }, - _getFileType: function (ftype) { - var self = this; - return self.mimeTypeAliases[ftype] || ftype; - }, - _generatePreviewTemplate: function ( - cat, - data, - fname, - ftype, - previewId, - fileId, - isError, - size, - frameClass, - foot, - ind, - templ, - attrs, - zoomData - ) { - var self = this, caption = self.slug(fname), prevContent, zoomContent = '', styleAttribs = '', - screenW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, - config, title = caption, alt = caption, typeCss = 'type-default', getContent, - footer = foot || self._renderFileFooter(cat, caption, size, 'auto', isError), - forcePrevIcon = self.preferIconicPreview, forceZoomIcon = self.preferIconicZoomPreview, - newCat = forcePrevIcon ? 'other' : cat; - config = screenW < 400 ? (self.previewSettingsSmall[newCat] || self.defaults.previewSettingsSmall[newCat]) : - (self.previewSettings[newCat] || self.defaults.previewSettings[newCat]); - if (config) { - $.each(config, function (key, val) { - styleAttribs += key + ':' + val + ';'; - }); - } - getContent = function (c, d, zoom, frameCss) { - var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(c), - css = (frameClass || '') + ' ' + frameCss; - if (self.frameClass) { - css = self.frameClass + ' ' + css; - } - if (zoom) { - css = css.replace(' ' + $h.SORT_CSS, ''); - } - tmplt = self._parseFilePreviewIcon(tmplt, fname); - if (cat === 'object' && !ftype) { - $.each(self.defaults.fileTypeSettings, function (key, func) { - if (key === 'object' || key === 'other') { - return; - } - if (func(fname, ftype)) { - typeCss = 'type-' + key; - } - }); - } - if (!$h.isEmpty(attrs)) { - if (attrs.title !== undefined && attrs.title !== null) { - title = attrs.title; - } - if (attrs.alt !== undefined && attrs.alt !== null) { - title = attrs.alt; - } - } - return tmplt.setTokens({ - 'previewId': id, - 'caption': caption, - 'title': title, - 'alt': alt, - 'frameClass': css, - 'type': self._getFileType(ftype), - 'fileindex': ind, - 'fileid': fileId || '', - 'typeCss': typeCss, - 'footer': footer, - 'data': d, - 'template': templ || cat, - 'style': styleAttribs ? 'style="' + styleAttribs + '"' : '' - }); - }; - ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1); - if (self.fileActionSettings.showZoom) { - zoomContent = getContent((forceZoomIcon ? 'other' : cat), zoomData ? zoomData : data, true, - 'kv-zoom-thumb'); - } - zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent); - if (typeof self.sanitizeZoomCache === 'function') { - zoomContent = self.sanitizeZoomCache(zoomContent); - } - prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb'); - return prevContent.setTokens({zoomCache: zoomContent}); - }, - _addToPreview: function ($preview, content) { - var self = this, $el; - content = $h.cspBuffer.stash(content); - $el = self.reversePreviewOrder ? $preview.prepend(content) : $preview.append(content); - $h.cspBuffer.apply($preview); - return $el; - }, - _previewDefault: function (file, isDisabled) { - var self = this, $preview = self.$preview; - if (!self.showPreview) { - return; - } - var fname = $h.getFileName(file), ftype = file ? file.type : '', content, size = file.size || 0, - caption = self._getFileName(file, ''), isError = isDisabled === true && !self.isAjaxUpload, - data = $h.createObjectURL(file), fileId = self.fileManager.getId(file), - previewId = self._getThumbId(fileId); - self._clearDefaultPreview(); - content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, fileId, isError, size); - self._addToPreview($preview, content); - self._setThumbAttr(previewId, caption, size); - if (isDisabled === true && self.isAjaxUpload) { - self._setThumbStatus(self._getFrame(previewId), 'Error'); - } - }, - _previewFile: function (i, file, theFile, data, fileInfo) { - if (!this.showPreview) { - return; - } - var self = this, fname = $h.getFileName(file), ftype = fileInfo.type, caption = fileInfo.name, - cat = self._parseFileType(ftype, fname), content, $preview = self.$preview, fsize = file.size || 0, - iData = cat === 'image' ? theFile.target.result : data, - fileId = self.fileManager.getId(file), previewId = self._getThumbId(fileId); - /** @namespace window.DOMPurify */ - content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, fileId, false, fsize); - self._clearDefaultPreview(); - self._addToPreview($preview, content); - var $thumb = self._getFrame(previewId); - self._validateImageOrientation($thumb.find('img'), file, previewId, fileId, caption, ftype, fsize, iData); - self._setThumbAttr(previewId, caption, fsize); - self._initSortable(); - }, - _setThumbAttr: function (id, caption, size) { - var self = this, $frame = self._getFrame(id); - if ($frame.length) { - size = size && size > 0 ? self._getSize(size) : ''; - $frame.data({'caption': caption, 'size': size}); - } - }, - _setInitThumbAttr: function () { - var self = this, data = self.previewCache.data, len = self.previewCache.count(true), config, - caption, size, previewId; - if (len === 0) { - return; - } - for (var i = 0; i < len; i++) { - config = data.config[i]; - previewId = self.previewInitId + '-' + $h.INIT_FLAG + i; - caption = $h.ifSet('caption', config, $h.ifSet('filename', config)); - size = $h.ifSet('size', config); - self._setThumbAttr(previewId, caption, size); - } - }, - _slugDefault: function (text) { - // noinspection RegExpRedundantEscape - return $h.isEmpty(text, true) ? '' : String(text).replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_'); - }, - _updateFileDetails: function (numFiles, skipRaiseEvent) { - var self = this, $el = self.$element, label, n, log, nFiles, file, - name = ($h.isIE(9) && $h.findFileName($el.val())) || ($el[0].files[0] && $el[0].files[0].name); - if (!name && self.fileManager.count() > 0) { - file = self.fileManager.getFirstFile(); - label = file.nameFmt; - } else { - label = name ? self.slug(name) : '_'; - } - n = self.isAjaxUpload ? self.fileManager.count() : numFiles; - nFiles = self.previewCache.count(true) + n; - log = n === 1 ? label : self._getMsgSelected(nFiles); - if (self.isError) { - self.$previewContainer.removeClass('file-thumb-loading'); - self.$previewStatus.html(''); - self.$captionContainer.removeClass('icon-visible'); - } else { - self._showFileIcon(); - } - self._setCaption(log, self.isError); - self.$container.removeClass('file-input-new file-input-ajax-new'); - if (!skipRaiseEvent) { - self._raise('fileselect', [numFiles, label]); - } - if (self.previewCache.count(true)) { - self._initPreviewActions(); - } - }, - _setThumbStatus: function ($thumb, status) { - var self = this; - if (!self.showPreview) { - return; - } - var icon = 'indicator' + status, msg = icon + 'Title', - css = 'file-preview-' + status.toLowerCase(), - $indicator = $thumb.find('.file-upload-indicator'), - config = self.fileActionSettings; - $thumb.removeClass('file-preview-success file-preview-error file-preview-paused file-preview-loading'); - if (status === 'Success') { - $thumb.find('.file-drag-handle').remove(); - } - $h.setHtml($indicator, config[icon]); - $indicator.attr('title', config[msg]); - $thumb.addClass(css); - if (status === 'Error' && !self.retryErrorUploads) { - $thumb.find('.kv-file-upload').attr('disabled', true); - } - }, - _setProgressCancelled: function () { - var self = this; - self._setProgress(101, self.$progress, self.msgCancelled); - }, - _setProgress: function (p, $el, error, stats) { - var self = this; - $el = $el || self.$progress; - if (!$el.length) { - return; - } - var pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold, - t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate, - template = pct < 100 ? self.progressTemplate : - (error ? (self.paused ? self.progressPauseTemplate : self.progressErrorTemplate) : t); - if (p >= 100) { - stats = ''; - } - if (!$h.isEmpty(template)) { - if (pctLimit && pct > pctLimit && p <= 100) { - out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold}); - } else { - out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')}); - } - stats = stats || ''; - out = out.setTokens({stats: stats}); - $h.setHtml($el, out); - if (error) { - $h.setHtml($el.find('[role="progressbar"]'), error); - } - } - }, - _hasFiles: function () { - var el = this.$element[0]; - return !!(el && el.files && el.files.length); - }, - _setFileDropZoneTitle: function () { - var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles; - if (self.isClickable) { - strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural; - title += self.dropZoneClickTitle.replace('{files}', strFiles); - } - $zone.find('.' + self.dropZoneTitleClass).remove(); - if (!self.showPreview || $zone.length === 0 || self.fileManager.count() > 0 || !self.dropZoneEnabled || - self.previewCache.count() > 0 || (!self.isAjaxUpload && self._hasFiles())) { - return; - } - if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) { - $zone.prepend('
    ' + title + '
    '); - } - self.$container.removeClass('file-input-new'); - $h.addCss(self.$container, 'file-input-ajax-new'); - }, - _getStats: function (stats) { - var self = this, pendingTime, t; - if (!self.showUploadStats || !stats || !stats.bitrate) { - return ''; - } - t = self._getLayoutTemplate('stats'); - pendingTime = (!stats.elapsed || !stats.bps) ? self.msgCalculatingTime : - self.msgPendingTime.setTokens({time: $h.getElapsed(Math.ceil(stats.pendingBytes / stats.bps))}); - - return t.setTokens({ - uploadSpeed: stats.bitrate, - pendingTime: pendingTime - }); - }, - _setResumableProgress: function (pct, stats, $thumb) { - var self = this, rm = self.resumableManager, obj = $thumb ? rm : self, - $prog = $thumb ? $thumb.find('.file-thumb-progress') : null; - if (obj.lastProgress === 0) { - obj.lastProgress = pct; - } - if (pct < obj.lastProgress) { - pct = obj.lastProgress; - } - self._setProgress(pct, $prog, null, self._getStats(stats)); - obj.lastProgress = pct; - }, - _toggleResumableProgress: function (template, message) { - var self = this, $progress = self.$progress; - if ($progress && $progress.length) { - $h.setHtml($progress, template.setTokens({ - percent: 101, - status: message, - stats: '' - })); - } - }, - _setFileUploadStats: function (id, pct, stats) { - var self = this, $prog = self.$progress; - if (!self.showPreview && (!$prog || !$prog.length)) { - return; - } - var fm = self.fileManager, rm = self.resumableManager, $thumb = fm.getThumb(id), pctTot, - totUpSize = 0, totSize = fm.getTotalSize(), totStats = $.extend(true, {}, stats); - if (self.enableResumableUpload) { - var loaded = stats.loaded, currUplSize = rm.getUploadedSize(), currTotSize = rm.file.size, totLoaded; - loaded += currUplSize; - totLoaded = fm.uploadedSize + loaded; - pct = $h.round(100 * loaded / currTotSize); - stats.pendingBytes = currTotSize - currUplSize; - self._setResumableProgress(pct, stats, $thumb); - pctTot = Math.floor(100 * totLoaded / totSize); - totStats.pendingBytes = totSize - totLoaded; - self._setResumableProgress(pctTot, totStats); - } else { - fm.setProgress(id, pct); - $prog = $thumb && $thumb.length ? $thumb.find('.file-thumb-progress') : null; - self._setProgress(pct, $prog, null, self._getStats(stats)); - $.each(fm.stats, function (id, cfg) { - totUpSize += cfg.loaded; - }); - totStats.pendingBytes = totSize - totUpSize; - pctTot = $h.round(totUpSize / totSize * 100); - self._setProgress(pctTot, null, null, self._getStats(totStats)); - } - }, - _validateMinCount: function () { - var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount(); - if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) { - self._noFilesError({}); - return false; - } - return true; - }, - _getFileCount: function (fileCount, includeInitial) { - var self = this, addCount = 0; - if (includeInitial === undefined) { - includeInitial = self.validateInitialCount && !self.overwriteInitial; - } - if (includeInitial) { - addCount = self.previewCache.count(true); - fileCount += addCount; - } - return fileCount; - }, - _getFileId: function (file) { - return $h.getFileId(file, this.generateFileId); - }, - _getFileName: function (file, defaultValue) { - var self = this, fileName = $h.getFileName(file); - return fileName ? self.slug(fileName) : defaultValue; - }, - _getFileNames: function (skipNull) { - var self = this; - return self.filenames.filter(function (n) { - return (skipNull ? n !== undefined : n !== undefined && n !== null); - }); - }, - _setPreviewError: function ($thumb, keepFile) { - var self = this, removeFrame = self.removeFromPreviewOnError && !self.retryErrorUploads; - if (!keepFile || removeFrame) { - self.fileManager.remove($thumb); - } - if (!self.showPreview) { - return; - } - if (removeFrame) { - $thumb.remove(); - return; - } else { - self._setThumbStatus($thumb, 'Error'); - } - self._refreshUploadButton($thumb); - }, - _refreshUploadButton: function ($thumb) { - var self = this, $btn = $thumb.find('.kv-file-upload'), cfg = self.fileActionSettings, - icon = cfg.uploadIcon, title = cfg.uploadTitle; - if (!$btn.length) { - return; - } - if (self.retryErrorUploads) { - icon = cfg.uploadRetryIcon; - title = cfg.uploadRetryTitle; - } - $btn.attr('title', title); - $h.setHtml($btn, icon); - }, - _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) { - var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type], - $imgEl, isValid; - if ($h.isEmpty(limit) || !$img.length) { - return; - } - $imgEl = $img[0]; - dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height; - isValid = chk === 'Small' ? dim >= limit : dim <= limit; - if (isValid) { - return; - } - msg = self['msgImage' + type + chk].setTokens({'name': fname, 'size': limit}); - self._showFileError(msg, params); - self._setPreviewError($thumb); - }, - _getExifObj: function (data) { - var self = this, exifObj, error = $h.logMessages.exifWarning; - if (data.slice(0, 23) !== 'data:image/jpeg;base64,' && data.slice(0, 22) !== 'data:image/jpg;base64,') { - exifObj = null; - return; - } - try { - exifObj = window.piexif ? window.piexif.load(data) : null; - } catch (err) { - exifObj = null; - error = err && err.message || ''; - } - if (!exifObj) { - self._log($h.logMessages.badExifParser, {details: error}); - } - return exifObj; - }, - setImageOrientation: function ($img, $zoomImg, value, $thumb) { - var self = this, invalidImg = !$img || !$img.length, invalidZoomImg = !$zoomImg || !$zoomImg.length, $mark, - isHidden = false, $div, zoomOnly = invalidImg && $thumb && $thumb.attr('data-template') === 'image', ev; - if (invalidImg && invalidZoomImg) { - return; - } - ev = 'load.fileinputimageorient'; - if (zoomOnly) { - $img = $zoomImg; - $zoomImg = null; - $img.css(self.previewSettings.image); - $div = $(document.createElement('div')).appendTo($thumb.find('.kv-file-content')); - $mark = $(document.createElement('span')).insertBefore($img); - $img.css('visibility', 'hidden').removeClass('file-zoom-detail').appendTo($div); - } else { - isHidden = !$img.is(':visible'); - } - $img.off(ev).on(ev, function () { - if (isHidden) { - self.$preview.removeClass('hide-content'); - $thumb.find('.kv-file-content').css('visibility', 'hidden'); - } - var img = $img[0], zoomImg = $zoomImg && $zoomImg.length ? $zoomImg[0] : null, - h = img.offsetHeight, w = img.offsetWidth, r = $h.getRotation(value); - if (isHidden) { - $thumb.find('.kv-file-content').css('visibility', 'visible'); - self.$preview.addClass('hide-content'); - } - $img.data('orientation', value); - if (zoomImg) { - $zoomImg.data('orientation', value); - } - if (value < 5) { - $h.setTransform(img, r); - $h.setTransform(zoomImg, r); - return; - } - var offsetAngle = Math.atan(w / h), origFactor = Math.sqrt(Math.pow(h, 2) + Math.pow(w, 2)), - scale = !origFactor ? 1 : (h / Math.cos(Math.PI / 2 + offsetAngle)) / origFactor, - s = ' scale(' + Math.abs(scale) + ')'; - $h.setTransform(img, r + s); - $h.setTransform(zoomImg, r + s); - if (zoomOnly) { - $img.css('visibility', 'visible').insertAfter($mark).addClass('file-zoom-detail'); - $mark.remove(); - $div.remove(); - } - }); - }, - _validateImageOrientation: function ($img, file, previewId, fileId, caption, ftype, fsize, iData) { - var self = this, exifObj, value, autoOrientImage = self.autoOrientImage, selector; - if (self.canOrientImage) { - $img.css('image-orientation', (autoOrientImage ? 'from-image' : 'none')); - return; - } - selector = $h.getZoomSelector(previewId, ' img'); - exifObj = autoOrientImage ? self._getExifObj(iData) : null; - value = exifObj ? exifObj['0th'][piexif.ImageIFD.Orientation] : null; // jshint ignore:line - if (!value) { - self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj); - return; - } - self.setImageOrientation($img, $(selector), value, self._getFrame(previewId)); - self._raise('fileimageoriented', {'$img': $img, 'file': file}); - self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj); - }, - _validateImage: function (previewId, fileId, fname, ftype, fsize, iData, exifObj) { - var self = this, $preview = self.$preview, params, w1, w2, $thumb = self._getFrame(previewId), - i = $thumb.attr('data-fileindex'), $img = $thumb.find('img'); - fname = fname || 'Untitled'; - $img.one('load', function () { - w1 = $thumb.width(); - w2 = $preview.width(); - if (w1 > w2) { - $img.css('width', '100%'); - } - params = {ind: i, id: previewId, fileId: fileId}; - self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params); - self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params); - if (!self.resizeImage) { - self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params); - self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params); - } - self._raise('fileimageloaded', [previewId]); - self.fileManager.addImage(fileId, { - ind: i, - img: $img, - thumb: $thumb, - pid: previewId, - typ: ftype, - siz: fsize, - validated: false, - imgData: iData, - exifObj: exifObj - }); - $thumb.data('exif', exifObj); - self._validateAllImages(); - }).one('error', function () { - self._raise('fileimageloaderror', [previewId]); - }).each(function () { - if (this.complete) { - $(this).trigger('load'); - } else { - if (this.error) { - $(this).trigger('error'); - } - } - }); - }, - _validateAllImages: function () { - var self = this, counter = {val: 0}, numImgs = self.fileManager.getImageCount(), fsize, - minSize = self.resizeIfSizeMoreThan; - if (numImgs !== self.fileManager.totalImages) { - return; - } - self._raise('fileimagesloaded'); - if (!self.resizeImage) { - return; - } - $.each(self.fileManager.loadedImages, function (id, config) { - if (!config.validated) { - fsize = config.siz; - if (fsize && fsize > minSize * 1000) { - self._getResizedImage(id, config, counter, numImgs); - } - config.validated = true; - } - }); - }, - _getResizedImage: function (id, config, counter, numImgs) { - var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob, - ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height, - isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI, - context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind, - $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr, file, params, evParams; - throwError = function (msg, params, ev) { - if (self.isAjaxUpload) { - self._showFileError(msg, params, ev); - } else { - self._showError(msg, params, ev); - } - self._setPreviewError($thumb); - }; - file = self.fileManager.getFile(id); - params = {id: pid, 'index': ind, fileId: id}; - evParams = [id, pid, ind]; - if (!file || !isValidImage || (width <= maxWidth && height <= maxHeight)) { - if (isValidImage && file) { - self._raise('fileimageresized', evParams); - } - counter.val++; - if (counter.val === numImgs) { - self._raise('fileimagesresized'); - } - if (!isValidImage) { - throwError(self.msgImageResizeError, params, 'fileimageresizeerror'); - return; - } - } - type = type || self.resizeDefaultImageType; - chkWidth = width > maxWidth; - chkHeight = height > maxHeight; - if (self.resizePreference === 'width') { - ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1); - } else { - ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1); - } - self._resetCanvas(); - width *= ratio; - height *= ratio; - canvas.width = width; - canvas.height = height; - try { - context.drawImage(img, 0, 0, width, height); - dataURI = canvas.toDataURL(type, self.resizeQuality); - if (exifObj) { - exifStr = window.piexif.dump(exifObj); - dataURI = window.piexif.insert(exifStr, dataURI); - } - blob = $h.dataURI2Blob(dataURI); - self.fileManager.setFile(id, blob); - self._raise('fileimageresized', evParams); - counter.val++; - if (counter.val === numImgs) { - self._raise('fileimagesresized', [undefined, undefined]); - } - if (!(blob instanceof Blob)) { - throwError(self.msgImageResizeError, params, 'fileimageresizeerror'); - } - } catch (err) { - counter.val++; - if (counter.val === numImgs) { - self._raise('fileimagesresized', [undefined, undefined]); - } - msg = self.msgImageResizeException.replace('{errors}', err.message); - throwError(msg, params, 'fileimageresizeexception'); - } - }, - _showProgress: function () { - var self = this; - if (self.$progress && self.$progress.length) { - self.$progress.show(); - } - }, - _hideProgress: function () { - var self = this; - if (self.$progress && self.$progress.length) { - self.$progress.hide(); - } - }, - _initBrowse: function ($container) { - var self = this, $el = self.$element; - if (self.showBrowse) { - self.$btnFile = $container.find('.btn-file').append($el); - } else { - $el.appendTo($container).attr('tabindex', -1); - $h.addCss($el, 'file-no-browse'); - } - }, - _initClickable: function () { - var self = this, $zone, $tmpZone; - if (!self.isClickable) { - return; - } - $zone = self.$dropZone; - if (!self.isAjaxUpload) { - $tmpZone = self.$preview.find('.file-default-preview'); - if ($tmpZone.length) { - $zone = $tmpZone; - } - } - - $h.addCss($zone, 'clickable'); - $zone.attr('tabindex', -1); - self._handler($zone, 'click', function (e) { - var $tar = $(e.target); - if (!$(self.elErrorContainer + ':visible').length && - (!$tar.parents('.file-preview-thumbnails').length || $tar.parents( - '.file-default-preview').length)) { - self.$element.data('zoneClicked', true).trigger('click'); - $zone.blur(); - } - }); - }, - _initCaption: function () { - var self = this, cap = self.initialCaption || ''; - if (self.overwriteInitial || $h.isEmpty(cap)) { - self.$caption.val(''); - return false; - } - self._setCaption(cap); - return true; - }, - _setCaption: function (content, isError) { - var self = this, title, out, icon, n, cap, file; - if (!self.$caption.length) { - return; - } - self.$captionContainer.removeClass('icon-visible'); - if (isError) { - title = $('
    ' + self.msgValidationError + '
    ').text(); - n = self.fileManager.count(); - if (n) { - file = self.fileManager.getFirstFile(); - cap = n === 1 && file ? file.nameFmt : self._getMsgSelected(n); - } else { - cap = self._getMsgSelected(self.msgNo); - } - out = $h.isEmpty(content) ? cap : content; - icon = '' + self.msgValidationErrorIcon + ''; - } else { - if ($h.isEmpty(content)) { - return; - } - title = $('
    ' + content + '
    ').text(); - out = title; - icon = self._getLayoutTemplate('fileIcon'); - } - self.$captionContainer.addClass('icon-visible'); - self.$caption.attr('title', title).val(out); - $h.setHtml(self.$captionIcon, icon); - }, - _createContainer: function () { - var self = this, attribs = {'class': 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')}, - $container = $h.createElement($h.cspBuffer.stash(self._renderMain())); - $h.cspBuffer.apply($container); - $container.insertBefore(self.$element).attr(attribs); - self._initBrowse($container); - if (self.theme) { - $container.addClass('theme-' + self.theme); - } - return $container; - }, - _refreshContainer: function () { - var self = this, $container = self.$container, $el = self.$element; - $el.insertAfter($container); - $h.setHtml($container, self._renderMain()); - self._initBrowse($container); - self._validateDisabled(); - }, - _validateDisabled: function () { - var self = this; - self.$caption.attr({readonly: self.isDisabled}); - }, - _renderMain: function () { - var self = this, - dropCss = self.dropZoneEnabled ? ' file-drop-zone' : 'file-drop-disabled', - close = !self.showClose ? '' : self._getLayoutTemplate('close'), - preview = !self.showPreview ? '' : self._getLayoutTemplate('preview') - .setTokens({'class': self.previewClass, 'dropClass': dropCss}), - css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass, - caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'}); - return self.mainTemplate.setTokens({ - 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''), - 'preview': preview, - 'close': close, - 'caption': caption, - 'upload': self._renderButton('upload'), - 'remove': self._renderButton('remove'), - 'cancel': self._renderButton('cancel'), - 'pause': self._renderButton('pause'), - 'browse': self._renderButton('browse') - }); - - }, - _renderButton: function (type) { - var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'], - title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'], - status = self.isDisabled ? ' disabled' : '', btnType = 'button'; - switch (type) { - case 'remove': - if (!self.showRemove) { - return ''; - } - break; - case 'cancel': - if (!self.showCancel) { - return ''; - } - css += ' kv-hidden'; - break; - case 'pause': - if (!self.showPause) { - return ''; - } - css += ' kv-hidden'; - break; - case 'upload': - if (!self.showUpload) { - return ''; - } - if (self.isAjaxUpload && !self.isDisabled) { - tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl); - } else { - btnType = 'submit'; - } - break; - case 'browse': - if (!self.showBrowse) { - return ''; - } - tmplt = self._getLayoutTemplate('btnBrowse'); - break; - default: - return ''; - } - - css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button'; - if (!$h.isEmpty(label)) { - label = ' ' + label + ''; - } - return tmplt.setTokens({ - 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label - }); - }, - _renderThumbProgress: function () { - var self = this; - return '
    ' + - self.progressInfoTemplate.setTokens({percent: 101, status: self.msgUploadBegin, stats: ''}) + - '
    '; - }, - _renderFileFooter: function (cat, caption, size, width, isError) { - var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag, - upl = config.showUpload, zoom = config.showZoom, out, params, - template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'), - ind = isError ? config.indicatorError : config.indicatorNew, - title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle, - indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title}); - size = self._getSize(size); - params = {type: cat, caption: caption, size: size, width: width, progress: '', indicator: indicator}; - if (self.isAjaxUpload) { - params.progress = self._renderThumbProgress(); - params.actions = self._renderFileActions(params, upl, false, rem, zoom, drg, false, false, false); - } else { - params.actions = self._renderFileActions(params, false, false, false, zoom, drg, false, false, false); - } - out = template.setTokens(params); - out = $h.replaceTags(out, self.previewThumbTags); - return out; - }, - _renderFileActions: function ( - cfg, - showUpl, - showDwn, - showDel, - showZoom, - showDrag, - disabled, - url, - key, - isInit, - dUrl, - dFile - ) { - var self = this; - if (!cfg.type && isInit) { - cfg.type = 'image'; - } - if (self.enableResumableUpload) { - showUpl = false; - } else { - if (typeof showUpl === 'function') { - showUpl = showUpl(cfg); - } - } - if (typeof showDwn === 'function') { - showDwn = showDwn(cfg); - } - if (typeof showDel === 'function') { - showDel = showDel(cfg); - } - if (typeof showZoom === 'function') { - showZoom = showZoom(cfg); - } - if (typeof showDrag === 'function') { - showDrag = showDrag(cfg); - } - if (!showUpl && !showDwn && !showDel && !showZoom && !showDrag) { - return ''; - } - var vUrl = url === false ? '' : ' data-url="' + url + '"', btnZoom = '', btnDrag = '', css, - vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '', - template = self._getLayoutTemplate('actions'), config = self.fileActionSettings, - otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}), - removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass; - if (showDel) { - btnDelete = self._getLayoutTemplate('actionDelete').setTokens({ - 'removeClass': removeClass, - 'removeIcon': config.removeIcon, - 'removeTitle': config.removeTitle, - 'dataUrl': vUrl, - 'dataKey': vKey, - 'key': key - }); - } - if (showUpl) { - btnUpload = self._getLayoutTemplate('actionUpload').setTokens({ - 'uploadClass': config.uploadClass, - 'uploadIcon': config.uploadIcon, - 'uploadTitle': config.uploadTitle - }); - } - if (showDwn) { - btnDownload = self._getLayoutTemplate('actionDownload').setTokens({ - 'downloadClass': config.downloadClass, - 'downloadIcon': config.downloadIcon, - 'downloadTitle': config.downloadTitle, - 'downloadUrl': dUrl || self.initialPreviewDownloadUrl - }); - btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key}); - } - if (showZoom) { - btnZoom = self._getLayoutTemplate('actionZoom').setTokens({ - 'zoomClass': config.zoomClass, - 'zoomIcon': config.zoomIcon, - 'zoomTitle': config.zoomTitle - }); - } - if (showDrag && isInit) { - css = 'drag-handle-init ' + config.dragClass; - btnDrag = self._getLayoutTemplate('actionDrag').setTokens({ - 'dragClass': css, - 'dragTitle': config.dragTitle, - 'dragIcon': config.dragIcon - }); - } - return template.setTokens({ - 'delete': btnDelete, - 'upload': btnUpload, - 'download': btnDownload, - 'zoom': btnZoom, - 'drag': btnDrag, - 'other': otherButtons - }); - }, - _browse: function (e) { - var self = this; - if (e && e.isDefaultPrevented() || !self._raise('filebrowse')) { - return; - } - if (self.isError && !self.isAjaxUpload) { - self.clear(); - } - if (self.focusCaptionOnBrowse) { - self.$captionContainer.focus(); - } - }, - _change: function (e) { - var self = this; - if (self.changeTriggered) { - return; - } - var $el = self.$element, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload, - tfiles, files = isDragDrop ? arguments[1] : $el[0].files, ctr = self.fileManager.count(), - total, initCount, len, isSingleUpl = $h.isEmpty($el.attr('multiple')), - maxCount = !isAjaxUpload && isSingleUpl ? 1 : self.maxFileCount, maxTotCount = self.maxTotalFileCount, - inclAll = maxTotCount > 0 && maxTotCount > maxCount, flagSingle = (isSingleUpl && ctr > 0), - throwError = function (mesg, file, previewId, index) { - var p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files), {id: previewId, index: index}), - p2 = {id: previewId, index: index, file: file, files: files}; - self.isPersistentError = true; - return isAjaxUpload ? self._showFileError(mesg, p1) : self._showError(mesg, p2); - }, - maxCountCheck = function (n, m, all) { - var msg = all ? self.msgTotalFilesTooMany : self.msgFilesTooMany; - msg = msg.replace('{m}', m).replace('{n}', n); - self.isError = throwError(msg, null, null, null); - self.$captionContainer.removeClass('icon-visible'); - self._setCaption('', true); - self.$container.removeClass('file-input-new file-input-ajax-new'); - }; - self.reader = null; - self._resetUpload(); - self._hideFileIcon(); - if (self.dropZoneEnabled) { - self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove(); - } - if (!isAjaxUpload) { - if (e.target && e.target.files === undefined) { - files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : []; - } else { - files = e.target.files || {}; - } - } - tfiles = files; - if ($h.isEmpty(tfiles) || tfiles.length === 0) { - if (!isAjaxUpload) { - self.clear(); - } - self._raise('fileselectnone'); - return; - } - self._resetErrors(); - len = tfiles.length; - initCount = isAjaxUpload ? (self.fileManager.count() + len) : len; - total = self._getFileCount(initCount, inclAll ? false : undefined); - if (maxCount > 0 && total > maxCount) { - if (!self.autoReplace || len > maxCount) { - maxCountCheck((self.autoReplace && len > maxCount ? len : total), maxCount); - return; - } - if (total > maxCount) { - self._resetPreviewThumbs(isAjaxUpload); - } - } else { - if (inclAll) { - total = self._getFileCount(initCount, true); - if (maxTotCount > 0 && total > maxTotCount) { - if (!self.autoReplace || len > maxCount) { - maxCountCheck((self.autoReplace && len > maxTotCount ? len : total), maxTotCount, true); - return; - } - if (total > maxCount) { - self._resetPreviewThumbs(isAjaxUpload); - } - } - } - if (!isAjaxUpload || flagSingle) { - self._resetPreviewThumbs(false); - if (flagSingle) { - self.clearFileStack(); - } - } else { - if (isAjaxUpload && ctr === 0 && (!self.previewCache.count(true) || self.overwriteInitial)) { - self._resetPreviewThumbs(true); - } - } - } - self.readFiles(tfiles); - }, - _abort: function (params) { - var self = this, data; - if (self.ajaxAborted && typeof self.ajaxAborted === 'object' && self.ajaxAborted.message !== undefined) { - data = $.extend(true, {}, self._getOutData(null), params); - data.abortData = self.ajaxAborted.data || {}; - data.abortMessage = self.ajaxAborted.message; - self._setProgress(101, self.$progress, self.msgCancelled); - self._showFileError(self.ajaxAborted.message, data, 'filecustomerror'); - self.cancel(); - return true; - } - return !!self.ajaxAborted; - }, - _resetFileStack: function () { - var self = this, i = 0; - self._getThumbs().each(function () { - var $thumb = $(this), ind = $thumb.attr('data-fileindex'), pid = $thumb.attr('id'); - if (ind === '-1' || ind === -1) { - return; - } - if (!self.fileManager.getFile($thumb.attr('data-fileid'))) { - $thumb.attr({'data-fileindex': i}); - i++; - } else { - $thumb.attr({'data-fileindex': '-1'}); - } - self._getZoom(pid).attr({ - 'data-fileindex': $thumb.attr('data-fileindex') - }); - }); - }, - _isFileSelectionValid: function (cnt) { - var self = this; - cnt = cnt || 0; - if (self.required && !self.getFilesCount()) { - self.$errorContainer.html(''); - self._showFileError(self.msgFileRequired); - return false; - } - if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) { - self._noFilesError({}); - return false; - } - return true; - }, - _canPreview: function (file) { - var self = this; - if (!file || !self.showPreview || !self.$preview || !self.$preview.length) { - return false; - } - var name = file.name || '', type = file.type || '', size = (file.size || 0) / 1000, - cat = self._parseFileType(type, name), allowedTypes, allowedMimes, allowedExts, skipPreview, - types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, - exts = self.allowedPreviewExtensions || [], dTypes = self.disabledPreviewTypes, - dMimes = self.disabledPreviewMimeTypes, dExts = self.disabledPreviewExtensions || [], - maxSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize) || 0, - expAllExt = new RegExp('\\.(' + exts.join('|') + ')$', 'i'), - expDisExt = new RegExp('\\.(' + dExts.join('|') + ')$', 'i'); - allowedTypes = !types || types.indexOf(cat) !== -1; - allowedMimes = !mimes || mimes.indexOf(type) !== -1; - allowedExts = !exts.length || $h.compare(name, expAllExt); - skipPreview = (dTypes && dTypes.indexOf(cat) !== -1) || (dMimes && dMimes.indexOf(type) !== -1) || - (dExts.length && $h.compare(name, expDisExt)) || (maxSize && !isNaN(maxSize) && size > maxSize); - return !skipPreview && (allowedTypes || allowedMimes || allowedExts); - }, - addToStack: function (file, id) { - this.fileManager.add(file, id); - }, - clearFileStack: function () { - var self = this; - self.fileManager.clear(); - self._initResumableUpload(); - if (self.enableResumableUpload) { - if (self.showPause === null) { - self.showPause = true; - } - if (self.showCancel === null) { - self.showCancel = false; - } - } else { - self.showPause = false; - if (self.showCancel === null) { - self.showCancel = true; - } - } - return self.$element; - }, - getFileStack: function () { - return this.fileManager.stack; - }, - getFileList: function () { - return this.fileManager.list(); - }, - getFilesCount: function (includeInitial) { - var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount(); - if (includeInitial) { - len += self.previewCache.count(true); - } - return self._getFileCount(len); - }, - readFiles: function (files) { - this.reader = new FileReader(); - var self = this, reader = self.reader, $container = self.$previewContainer, - $status = self.$previewStatus, msgLoading = self.msgLoading, msgProgress = self.msgProgress, - previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings, - readFile, fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0, - fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '), - throwError = function (msg, file, previewId, index, fileId) { - var $thumb, p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files), - {id: previewId, index: index, fileId: fileId}), - p2 = {id: previewId, index: index, fileId: fileId, file: file, files: files}; - self._previewDefault(file, true); - $thumb = self._getFrame(previewId, true); - if (self.isAjaxUpload) { - setTimeout(function () { - readFile(index + 1); - }, self.processDelay); - } else { - self.unlock(); - numFiles = 0; - } - if (self.removeFromPreviewOnError && $thumb.length) { - $thumb.remove(); - } else { - self._initFileActions(); - $thumb.find('.kv-file-upload').remove(); - } - self.isPersistentError = true; - self.isError = self.isAjaxUpload ? self._showFileError(msg, p1) : self._showError(msg, p2); - self._updateFileDetails(numFiles); - }; - self.fileManager.clearImages(); - $.each(files, function (key, file) { - var func = self.fileTypeSettings.image; - if (func && func(file.type)) { - self.fileManager.totalImages++; - } - }); - readFile = function (i) { - var $error = self.$errorContainer, errors, fm = self.fileManager; - if (i >= numFiles) { - self.unlock(); - if (self.duplicateErrors.length) { - errors = '
  • ' + self.duplicateErrors.join('
  • ') + '
  • '; - if ($error.find('ul').length === 0) { - $h.setHtml($error, self.errorCloseButton + '
      ' + errors + '
    '); - } else { - $error.find('ul').append(errors); - } - $error.fadeIn(self.fadeDelay); - self._handler($error.find('.kv-error-close'), 'click', function () { - $error.fadeOut(self.fadeDelay); - }); - self.duplicateErrors = []; - } - if (self.isAjaxUpload) { - self._raise('filebatchselected', [fm.stack]); - if (fm.count() === 0 && !self.isError) { - self.reset(); - } - } else { - self._raise('filebatchselected', [files]); - } - $container.removeClass('file-thumb-loading'); - $status.html(''); - return; - } - self.lock(true); - var file = files[i], id = self._getFileId(file), previewId = previewInitId + '-' + id, fSizeKB, j, msg, - fnText = settings.text, fnImage = settings.image, fnHtml = settings.html, typ, chk, typ1, typ2, - caption = self._getFileName(file, ''), fileSize = (file && file.size || 0) / 1000, - fileExtExpr = '', previewData = $h.createObjectURL(file), fileCount = 0, - strTypes = '', fileId, canLoad, fileReaderAborted = false, - func, knownTypes = 0, isImage, txtFlag, processFileLoaded = function () { - var msg = msgProgress.setTokens({ - 'index': i + 1, - 'files': numFiles, - 'percent': 50, - 'name': caption - }); - setTimeout(function () { - $status.html(msg); - self._updateFileDetails(numFiles); - readFile(i + 1); - }, self.processDelay); - if (self._raise('fileloaded', [file, previewId, id, i, reader]) && self.isAjaxUpload) { - fm.add(file); - } - }; - if (!file) { - return; - } - fileId = fm.getId(file); - if (typLen > 0) { - for (j = 0; j < typLen; j++) { - typ1 = fileTypes[j]; - typ2 = self.msgFileTypes[typ1] || typ1; - strTypes += j === 0 ? typ2 : ', ' + typ2; - } - } - if (caption === false) { - readFile(i + 1); - return; - } - if (caption.length === 0) { - msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode($h.getFileName(file), '[unknown]')); - throwError(msg, file, previewId, i, fileId); - return; - } - if (!$h.isEmpty(fileExt)) { - fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i'); - } - fSizeKB = fileSize.toFixed(2); - if (self.isAjaxUpload && fm.exists(fileId) || self._getFrame(previewId, true).length) { - var p2 = {id: previewId, index: i, fileId: fileId, file: file, files: files}; - msg = self.msgDuplicateFile.setTokens({name: caption, size: fSizeKB}); - if (self.isAjaxUpload) { - self.duplicateErrors.push(msg); - self.isDuplicateError = true; - self._raise('fileduplicateerror', [file, fileId, caption, fSizeKB, previewId, i]); - readFile(i + 1); - self._updateFileDetails(numFiles); - } else { - self._showError(msg, p2); - self.unlock(); - numFiles = 0; - self._clearFileInput(); - self.reset(); - self._updateFileDetails(numFiles); - } - return; - } - if (self.maxFileSize > 0 && fileSize > self.maxFileSize) { - msg = self.msgSizeTooLarge.setTokens({ - 'name': caption, - 'size': fSizeKB, - 'maxSize': self.maxFileSize - }); - throwError(msg, file, previewId, i, fileId); - return; - } - if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) { - msg = self.msgSizeTooSmall.setTokens({ - 'name': caption, - 'size': fSizeKB, - 'minSize': self.minFileSize - }); - throwError(msg, file, previewId, i, fileId); - return; - } - if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) { - for (j = 0; j < fileTypes.length; j += 1) { - typ = fileTypes[j]; - func = settings[typ]; - fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type, - $h.getFileName(file)) ? 1 : 0); - } - if (fileCount === 0) { - msg = self.msgInvalidFileType.setTokens({name: caption, types: strTypes}); - throwError(msg, file, previewId, i, fileId); - return; - } - } - if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) { - chk = $h.compare(caption, fileExtExpr); - fileCount += $h.isEmpty(chk) ? 0 : chk.length; - if (fileCount === 0) { - msg = self.msgInvalidFileExtension.setTokens({name: caption, extensions: strExt}); - throwError(msg, file, previewId, i, fileId); - return; - } - } - if (!self._canPreview(file)) { - canLoad = self.isAjaxUpload && self._raise('filebeforeload', [file, i, reader]); - if (self.isAjaxUpload && canLoad) { - fm.add(file); - } - if (self.showPreview && canLoad) { - $container.addClass('file-thumb-loading'); - self._previewDefault(file); - self._initFileActions(); - } - setTimeout(function () { - if (canLoad) { - self._updateFileDetails(numFiles); - } - readFile(i + 1); - self._raise('fileloaded', [file, previewId, id, i]); - }, 10); - return; - } - isImage = fnImage(file.type, caption); - $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles)); - $container.addClass('file-thumb-loading'); - reader.onerror = function (evt) { - self._errorHandler(evt, caption); - }; - reader.onload = function (theFile) { - var hex, fileInfo, uint, byte, bytes = [], contents, mime, readImage = function () { - var newReader = new FileReader(); - newReader.onerror = function (theFileNew) { - self._errorHandler(theFileNew, caption); - }; - newReader.onload = function (theFileNew) { - if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) { - fileReaderAborted = true; - self._resetCaption(); - reader.abort(); - $status.html(''); - $container.removeClass('file-thumb-loading'); - self.enable(); - return; - } - self._previewFile(i, file, theFileNew, previewData, fileInfo); - self._initFileActions(); - processFileLoaded(); - }; - newReader.readAsDataURL(file); - }; - fileInfo = {'name': caption, 'type': file.type}; - $.each(settings, function (k, f) { - if (k !== 'object' && k !== 'other' && typeof f === 'function' && f(file.type, caption)) { - knownTypes++; - } - }); - if (knownTypes === 0) { // auto detect mime types from content if no known file types detected - uint = new Uint8Array(theFile.target.result); - for (j = 0; j < uint.length; j++) { - byte = uint[j].toString(16); - bytes.push(byte); - } - hex = bytes.join('').toLowerCase().substring(0, 8); - mime = $h.getMimeType(hex, '', ''); - if ($h.isEmpty(mime)) { // look for ascii text content - contents = $h.arrayBuffer2String(reader.result); - mime = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type); - } - fileInfo = {'name': caption, 'type': mime}; - isImage = fnImage(mime, ''); - if (isImage) { - readImage(txtFlag); - return; - } - } - if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) { - fileReaderAborted = true; - self._resetCaption(); - reader.abort(); - $status.html(''); - $container.removeClass('file-thumb-loading'); - self.enable(); - return; - } - self._previewFile(i, file, theFile, previewData, fileInfo); - self._initFileActions(); - processFileLoaded(); - }; - reader.onprogress = function (data) { - if (data.lengthComputable) { - var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact); - msg = msgProgress.setTokens({ - 'index': i + 1, - 'files': numFiles, - 'percent': progress, - 'name': caption - }); - setTimeout(function () { - if (!fileReaderAborted) { - $status.html(msg); - } - }, self.processDelay); - } - }; - if (isImage) { - reader.readAsDataURL(file); - } else { - reader.readAsArrayBuffer(file); - } - }; - - readFile(0); - self._updateFileDetails(numFiles, true); - }, - lock: function (selectMode) { - var self = this, $container = self.$container; - self._resetErrors(); - self.disable(); - if (!selectMode && self.showCancel) { - $container.find('.fileinput-cancel').show(); - } - if (!selectMode && self.showPause) { - $container.find('.fileinput-pause').show(); - } - self._raise('filelock', [self.fileManager.stack, self._getExtraData()]); - return self.$element; - }, - unlock: function (reset) { - var self = this, $container = self.$container; - if (reset === undefined) { - reset = true; - } - self.enable(); - $container.removeClass('is-locked'); - if (self.showCancel) { - $container.find('.fileinput-cancel').hide(); - } - if (self.showPause) { - $container.find('.fileinput-pause').hide(); - } - if (reset) { - self._resetFileStack(); - } - self._raise('fileunlock', [self.fileManager.stack, self._getExtraData()]); - return self.$element; - }, - resume: function () { - var self = this, flag = false, rm = self.resumableManager; - if (!self.enableResumableUpload) { - return self.$element; - } - if (self.paused) { - self._toggleResumableProgress(self.progressPauseTemplate, self.msgUploadResume); - } else { - flag = true; - } - self.paused = false; - if (flag) { - self._toggleResumableProgress(self.progressInfoTemplate, self.msgUploadBegin); - } - setTimeout(function () { - rm.upload(); - }, self.processDelay); - return self.$element; - }, - pause: function () { - var self = this, rm = self.resumableManager, xhr = self.ajaxRequests, len = xhr.length, i, - pct = rm.getProgress(), actions = self.fileActionSettings, tm = self.taskManager, - pool = tm.getPool(rm.id); - if (!self.enableResumableUpload) { - return self.$element; - } else { - if (pool) { - pool.cancel(); - } - } - self._raise('fileuploadpaused', [self.fileManager, rm]); - if (len > 0) { - for (i = 0; i < len; i += 1) { - self.paused = true; - xhr[i].abort(); - } - } - if (self.showPreview) { - self._getThumbs().each(function () { - var $thumb = $(this), fileId = $thumb.attr('data-fileid'), t = self._getLayoutTemplate('stats'), - stats, $indicator = $thumb.find('.file-upload-indicator'); - $thumb.removeClass('file-uploading'); - if ($indicator.attr('title') === actions.indicatorLoadingTitle) { - self._setThumbStatus($thumb, 'Paused'); - stats = t.setTokens({pendingTime: self.msgPaused, uploadSpeed: ''}); - self.paused = true; - self._setProgress(pct, $thumb.find('.file-thumb-progress'), pct + '%', stats); - } - if (!self.fileManager.getFile(fileId)) { - $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled'); - } - }); - } - self._setProgress(101, self.$progress, self.msgPaused); - return self.$element; - }, - cancel: function () { - var self = this, xhr = self.ajaxRequests, - rm = self.resumableManager, tm = self.taskManager, - pool = rm ? tm.getPool(rm.id) : undefined, len = xhr.length, i; - - if (self.enableResumableUpload && pool) { - pool.cancel().done(function () { - self._setProgressCancelled(); - }); - rm.reset(); - self._raise('fileuploadcancelled', [self.fileManager, rm]); - } else { - self._raise('fileuploadcancelled', [self.fileManager]); - } - self._initAjax(); - if (len > 0) { - for (i = 0; i < len; i += 1) { - self.cancelling = true; - xhr[i].abort(); - } - } - self._getThumbs().each(function () { - var $thumb = $(this), fileId = $thumb.attr('data-fileid'), $prog = $thumb.find('.file-thumb-progress'); - $thumb.removeClass('file-uploading'); - self._setProgress(0, $prog); - $prog.hide(); - if (!self.fileManager.getFile(fileId)) { - $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled'); - $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled'); - } - self.unlock(); - }); - setTimeout(function () { - self._setProgressCancelled(); - }, self.processDelay); - return self.$element; - }, - clear: function () { - var self = this, cap; - if (!self._raise('fileclear')) { - return; - } - self.$btnUpload.removeAttr('disabled'); - self._getThumbs().find('video,audio,img').each(function () { - $h.cleanMemory($(this)); - }); - self._clearFileInput(); - self._resetUpload(); - self.clearFileStack(); - self.isDuplicateError = false; - self.isPersistentError = false; - self._resetErrors(true); - if (self._hasInitialPreview()) { - self._showFileIcon(); - self._resetPreview(); - self._initPreviewActions(); - self.$container.removeClass('file-input-new'); - } else { - self._getThumbs().each(function () { - self._clearObjects($(this)); - }); - if (self.isAjaxUpload) { - self.previewCache.data = {}; - } - self.$preview.html(''); - cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : ''; - self.$caption.attr('title', '').val(cap); - $h.addCss(self.$container, 'file-input-new'); - self._validateDefaultPreview(); - } - if (self.$container.find($h.FRAMES).length === 0) { - if (!self._initCaption()) { - self.$captionContainer.removeClass('icon-visible'); - } - } - self._hideFileIcon(); - if (self.focusCaptionOnClear) { - self.$captionContainer.focus(); - } - self._setFileDropZoneTitle(); - self._raise('filecleared'); - return self.$element; - }, - reset: function () { - var self = this; - if (!self._raise('filereset')) { - return; - } - self.lastProgress = 0; - self._resetPreview(); - self.$container.find('.fileinput-filename').text(''); - $h.addCss(self.$container, 'file-input-new'); - if (self.getFrames().length) { - self.$container.removeClass('file-input-new'); - } - self.clearFileStack(); - self._setFileDropZoneTitle(); - return self.$element; - }, - disable: function () { - var self = this, $container = self.$container; - self.isDisabled = true; - self._raise('filedisabled'); - self.$element.attr('disabled', 'disabled'); - $container.addClass('is-locked'); - $h.addCss($container.find('.btn-file'), 'disabled'); - $container.find('.kv-fileinput-caption').addClass('file-caption-disabled'); - $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button') - .attr('disabled', true); - self._initDragDrop(); - return self.$element; - }, - enable: function () { - var self = this, $container = self.$container; - self.isDisabled = false; - self._raise('fileenabled'); - self.$element.removeAttr('disabled'); - $container.removeClass('is-locked'); - $container.find('.kv-fileinput-caption').removeClass('file-caption-disabled'); - $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button') - .removeAttr('disabled'); - $container.find('.btn-file').removeClass('disabled'); - self._initDragDrop(); - return self.$element; - }, - upload: function () { - var self = this, fm = self.fileManager, totLen = fm.count(), i, outData, - hasExtraData = !$.isEmptyObject(self._getExtraData()); - if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) { - return; - } - self.lastProgress = 0; - self._resetUpload(); - if (totLen === 0 && !hasExtraData) { - self._showFileError(self.msgUploadEmpty); - return; - } - self.cancelling = false; - self._showProgress(); - self.lock(); - if (totLen === 0 && hasExtraData) { - self._setProgress(2); - self._uploadExtraOnly(); - return; - } - if (self.enableResumableUpload) { - return self.resume(); - } - if (self.uploadAsync || self.enableResumableUpload) { - outData = self._getOutData(null); - self._raise('filebatchpreupload', [outData]); - self.fileBatchCompleted = false; - self.uploadCache = []; - $.each(self.getFileStack(), function (id) { - var previewId = self._getThumbId(id); - self.uploadCache.push({id: previewId, content: null, config: null, tags: null, append: true}); - }); - self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS); - self._initSortable(); - } - self._setProgress(2); - self.hasInitData = false; - if (self.uploadAsync) { - i = 0; - $.each(fm.stack, function (id) { - self._uploadSingle(i, id, true); - i++; - }); - return; - } - self._uploadBatch(); - return self.$element; - }, - destroy: function () { - var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace; - $(document).off(ns); - $(window).off(ns); - if ($form && $form.length) { - $form.off(ns); - } - if (self.isAjaxUpload) { - self._clearFileInput(); - } - self._cleanup(); - self._initPreviewCache(); - $el.insertBefore($cont).off(ns).removeData(); - $cont.off().remove(); - return $el; - }, - refresh: function (options) { - var self = this, $el = self.$element; - if (typeof options !== 'object' || $h.isEmpty(options)) { - options = self.options; - } else { - options = $.extend(true, {}, self.options, options); - } - self._init(options, true); - self._listen(); - return $el; - }, - zoom: function (frameId) { - var self = this, $frame = self._getFrame(frameId); - self._showModal($frame); - }, - getExif: function (frameId) { - var self = this, $frame = self._getFrame(frameId); - return $frame && $frame.data('exif') || null; - }, - getFrames: function (cssFilter) { - var self = this, $frames; - cssFilter = cssFilter || ''; - $frames = self.$preview.find($h.FRAMES + cssFilter); - if (self.reversePreviewOrder) { - $frames = $($frames.get().reverse()); - } - return $frames; - }, - getPreview: function () { - var self = this; - return { - content: self.initialPreview, - config: self.initialPreviewConfig, - tags: self.initialPreviewThumbTags - }; - } - }; - - $.fn.fileinput = function (option) { - if (!$h.hasFileAPISupport() && !$h.isIE(9)) { - return; - } - var args = Array.apply(null, arguments), retvals = []; - args.shift(); - this.each(function () { - var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option, - theme = options.theme || self.data('theme'), l = {}, t = {}, - lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt; - if (!data) { - if (theme) { - t = $.fn.fileinputThemes[theme] || {}; - } - if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) { - l = $.fn.fileinputLocales[lang] || {}; - } - opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data()); - data = new FileInput(this, opt); - self.data('fileinput', data); - } - - if (typeof option === 'string') { - retvals.push(data[option].apply(data, args)); - } - }); - switch (retvals.length) { - case 0: - return this; - case 1: - return retvals[0]; - default: - return retvals; - } - }; - - var IFRAME_ATTRIBS = 'class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}'; - - $.fn.fileinput.defaults = { - language: 'zh', - showCaption: true, - showBrowse: true, - showPreview: true, - showRemove: true, - showUpload: true, - showUploadStats: true, - showCancel: null, - showPause: null, - showClose: true, - showUploadedThumbs: true, - showConsoleLogs: false, - browseOnZoneClick: false, - autoReplace: false, - autoOrientImage: function () { // applicable for JPEG images only and non ios safari - var ua = window.navigator.userAgent, webkit = !!ua.match(/WebKit/i), - iOS = !!ua.match(/iP(od|ad|hone)/i), iOSSafari = iOS && webkit && !ua.match(/CriOS/i); - return !iOSSafari; - }, - autoOrientImageInitial: true, - required: false, - rtl: false, - hideThumbnailContent: false, - encodeUrl: true, - focusCaptionOnBrowse: true, - focusCaptionOnClear: true, - generateFileId: null, - previewClass: '', - captionClass: '', - frameClass: 'krajee-default', - mainClass: 'file-caption-main', - mainTemplate: null, - fileSizeGetter: null, - initialCaption: '', - initialPreview: [], - initialPreviewDelimiter: '*$$*', - initialPreviewAsData: false, - initialPreviewFileType: 'image', - initialPreviewConfig: [], - initialPreviewThumbTags: [], - previewThumbTags: {}, - initialPreviewShowDelete: true, - initialPreviewDownloadUrl: '', - removeFromPreviewOnError: false, - deleteUrl: '', - deleteExtraData: {}, - overwriteInitial: true, - sanitizeZoomCache: function (content) { - var $container = $h.createElement(content); - $container.find('input,textarea,select,datalist,form,.file-thumbnail-footer').remove(); - return $container.html(); - }, - previewZoomButtonIcons: { - prev: '', - next: '', - toggleheader: '', - fullscreen: '', - borderless: '', - close: '' - }, - previewZoomButtonClasses: { - prev: 'btn btn-navigate', - next: 'btn btn-navigate', - toggleheader: 'btn btn-sm btn-kv btn-default btn-outline-secondary', - fullscreen: 'btn btn-sm btn-kv btn-default btn-outline-secondary', - borderless: 'btn btn-sm btn-kv btn-default btn-outline-secondary', - close: 'btn btn-sm btn-kv btn-default btn-outline-secondary' - }, - previewTemplates: {}, - previewContentTemplates: {}, - preferIconicPreview: false, - preferIconicZoomPreview: false, - allowedFileTypes: null, - allowedFileExtensions: null, - allowedPreviewTypes: undefined, - allowedPreviewMimeTypes: null, - allowedPreviewExtensions: null, - disabledPreviewTypes: undefined, - disabledPreviewExtensions: ['msi', 'exe', 'com', 'zip', 'rar', 'app', 'vb', 'scr'], - disabledPreviewMimeTypes: null, - defaultPreviewContent: null, - customLayoutTags: {}, - customPreviewTags: {}, - previewFileIcon: '', - previewFileIconClass: 'file-other-icon', - previewFileIconSettings: {}, - previewFileExtSettings: {}, - buttonLabelClass: 'hidden-xs', - browseIcon: ' ', - browseClass: 'btn btn-primary', - removeIcon: '', - removeClass: 'btn btn-default btn-secondary', - cancelIcon: '', - cancelClass: 'btn btn-default btn-secondary', - pauseIcon: '', - pauseClass: 'btn btn-default btn-secondary', - uploadIcon: '', - uploadClass: 'btn btn-default btn-secondary', - uploadUrl: null, - uploadUrlThumb: null, - uploadAsync: true, - uploadParamNames: { - chunkCount: 'chunkCount', - chunkIndex: 'chunkIndex', - chunkSize: 'chunkSize', - chunkSizeStart: 'chunkSizeStart', - chunksUploaded: 'chunksUploaded', - fileBlob: 'fileBlob', - fileId: 'fileId', - fileName: 'fileName', - fileRelativePath: 'fileRelativePath', - fileSize: 'fileSize', - retryCount: 'retryCount' - }, - maxAjaxThreads: 5, - fadeDelay: 800, - processDelay: 100, - queueDelay: 10, // must be lesser than process delay - progressDelay: 0, // must be lesser than process delay - enableResumableUpload: false, - resumableUploadOptions: { - fallback: null, - testUrl: null, // used for checking status of chunks/ files previously / partially uploaded - chunkSize: 2 * 1024, // in KB - maxThreads: 4, - maxRetries: 3, - showErrorLog: true - }, - uploadExtraData: {}, - zoomModalHeight: 480, - minImageWidth: null, - minImageHeight: null, - maxImageWidth: null, - maxImageHeight: null, - resizeImage: false, - resizePreference: 'width', - resizeQuality: 0.92, - resizeDefaultImageType: 'image/jpeg', - resizeIfSizeMoreThan: 0, // in KB - minFileSize: -1, - maxFileSize: 0, - maxFilePreviewSize: 25600, // 25 MB - minFileCount: 0, - maxFileCount: 0, - maxTotalFileCount: 0, - validateInitialCount: false, - msgValidationErrorClass: 'text-danger', - msgValidationErrorIcon: ' ', - msgErrorClass: 'file-error-message', - progressThumbClass: 'progress-bar progress-bar-striped active progress-bar-animated', - progressClass: 'progress-bar bg-success progress-bar-success progress-bar-striped active progress-bar-animated', - progressInfoClass: 'progress-bar bg-info progress-bar-info progress-bar-striped active progress-bar-animated', - progressCompleteClass: 'progress-bar bg-success progress-bar-success', - progressPauseClass: 'progress-bar bg-primary progress-bar-primary progress-bar-striped active progress-bar-animated', - progressErrorClass: 'progress-bar bg-danger progress-bar-danger', - progressUploadThreshold: 99, - previewFileType: 'image', - elCaptionContainer: null, - elCaptionText: null, - elPreviewContainer: null, - elPreviewImage: null, - elPreviewStatus: null, - elErrorContainer: null, - errorCloseButton: $h.closeButton('kv-error-close'), - slugCallback: null, - dropZoneEnabled: true, - dropZoneTitleClass: 'file-drop-zone-title', - fileActionSettings: {}, - otherActionButtons: '', - textEncoding: 'UTF-8', - preProcessUpload: null, - ajaxSettings: {}, - ajaxDeleteSettings: {}, - showAjaxErrorDetails: true, - mergeAjaxCallbacks: false, - mergeAjaxDeleteCallbacks: false, - retryErrorUploads: true, - reversePreviewOrder: false, - usePdfRenderer: function () { - var isIE11 = !!window.MSInputMethodContext && !!document.documentMode; - return !!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i) || isIE11; - }, - pdfRendererUrl: '', - pdfRendererTemplate: '' - }; - - // noinspection HtmlUnknownAttribute - $.fn.fileinputLocales.en = { - fileSingle: 'file', - filePlural: 'files', - browseLabel: 'Browse …', - removeLabel: 'Remove', - removeTitle: 'Clear all unprocessed files', - cancelLabel: 'Cancel', - cancelTitle: 'Abort ongoing upload', - pauseLabel: 'Pause', - pauseTitle: 'Pause ongoing upload', - uploadLabel: 'Upload', - uploadTitle: 'Upload selected files', - msgNo: 'No', - msgNoFilesSelected: 'No files selected', - msgCancelled: 'Cancelled', - msgPaused: 'Paused', - msgPlaceholder: 'Select {files} ...', - msgZoomModalHeading: 'Detailed Preview', - msgFileRequired: 'You must select a file to upload.', - msgSizeTooSmall: 'File "{name}" ({size} KB) is too small and must be larger than {minSize} KB.', - msgSizeTooLarge: 'File "{name}" ({size} KB) exceeds maximum allowed upload size of {maxSize} KB.', - msgFilesTooLess: 'You must select at least {n} {files} to upload.', - msgFilesTooMany: 'Number of files selected for upload ({n}) exceeds maximum allowed limit of {m}.', - msgTotalFilesTooMany: 'You can upload a maximum of {m} files ({n} files detected).', - msgFileNotFound: 'File "{name}" not found!', - msgFileSecured: 'Security restrictions prevent reading the file "{name}".', - msgFileNotReadable: 'File "{name}" is not readable.', - msgFilePreviewAborted: 'File preview aborted for "{name}".', - msgFilePreviewError: 'An error occurred while reading the file "{name}".', - msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".', - msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.', - msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.', - msgFileTypes: { - 'image': 'image', - 'html': 'HTML', - 'text': 'text', - 'video': 'video', - 'audio': 'audio', - 'flash': 'flash', - 'pdf': 'PDF', - 'object': 'object' - }, - msgUploadAborted: 'The file upload was aborted', - msgUploadThreshold: 'Processing …', - msgUploadBegin: 'Initializing …', - msgUploadEnd: 'Done', - msgUploadResume: 'Resuming upload …', - msgUploadEmpty: 'No valid data available for upload.', - msgUploadError: 'Upload Error', - msgDeleteError: 'Delete Error', - msgProgressError: 'Error', - msgValidationError: 'Validation Error', - msgLoading: 'Loading file {index} of {files} …', - msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.', - msgSelected: '{n} {files} selected', - msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.', - msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.', - msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.', - msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.', - msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.', - msgImageResizeError: 'Could not get the image dimensions to resize.', - msgImageResizeException: 'Error while resizing the image.
    {errors}
    ', - msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!', - msgAjaxProgressError: '{operation} failed', - msgDuplicateFile: 'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.', - msgResumableUploadRetriesExceeded: 'Upload aborted beyond {max} retries for file {file}! Error Details:
    {error}
    ', - msgPendingTime: '{time} remaining', - msgCalculatingTime: 'calculating time remaining', - ajaxOperations: { - deleteThumb: 'file delete', - uploadThumb: 'file upload', - uploadBatch: 'batch file upload', - uploadExtra: 'form data upload' - }, - dropZoneTitle: 'Drag & drop files here …', - dropZoneClickTitle: '
    (or click to select {files})', - previewZoomButtonTitles: { - prev: 'View previous file', - next: 'View next file', - toggleheader: 'Toggle header', - fullscreen: 'Toggle full screen', - borderless: 'Toggle borderless mode', - close: 'Close detailed preview' - } - }; - - $.fn.fileinputLocales.zh = { - fileSingle: '文件', - filePlural: '个文件', - browseLabel: '选择 …', - removeLabel: '移除', - removeTitle: '清除选中文件', - cancelLabel: '取消', - cancelTitle: '取消进行中的上传', - pauseLabel: 'Pause', - pauseTitle: 'Pause ongoing upload', - uploadLabel: '上传', - uploadTitle: '上传选中文件', - msgNo: '没有', - msgNoFilesSelected: '未选择文件', - msgPaused: 'Paused', - msgCancelled: '取消', - msgPlaceholder: '选择 {files} ...', - msgZoomModalHeading: '详细预览', - msgFileRequired: '必须选择一个文件上传.', - msgSizeTooSmall: '文件 "{name}" ({size} KB) 必须大于限定大小 {minSize} KB.', - msgSizeTooLarge: '文件 "{name}" ({size} KB) 超过了允许大小 {maxSize} KB.', - msgFilesTooLess: '你必须选择最少 {n} {files} 来上传. ', - msgFilesTooMany: '选择的上传文件个数 ({n}) 超出最大文件的限制个数 {m}.', - msgTotalFilesTooMany: 'You can upload a maximum of {m} files ({n} files detected).', - msgFileNotFound: '文件 "{name}" 未找到!', - msgFileSecured: '安全限制,为了防止读取文件 "{name}".', - msgFileNotReadable: '文件 "{name}" 不可读.', - msgFilePreviewAborted: '取消 "{name}" 的预览.', - msgFilePreviewError: '读取 "{name}" 时出现了一个错误.', - msgInvalidFileName: '文件名 "{name}" 包含非法字符.', - msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.', - msgInvalidFileExtension: '不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.', - msgFileTypes: { - 'image': 'image', - 'html': 'HTML', - 'text': 'text', - 'video': 'video', - 'audio': 'audio', - 'flash': 'flash', - 'pdf': 'PDF', - 'object': 'object' - }, - msgUploadAborted: '该文件上传被中止', - msgUploadThreshold: '处理中 …', - msgUploadBegin: '正在初始化 …', - msgUploadEnd: '完成', - msgUploadResume: 'Resuming upload …', - msgUploadEmpty: '无效的文件上传.', - msgUploadError: 'Upload Error', - msgDeleteError: 'Delete Error', - msgProgressError: '上传出错', - msgValidationError: '验证错误', - msgLoading: '加载第 {index} 文件 共 {files} …', - msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.', - msgSelected: '{n} {files} 选中', - msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.', - msgImageWidthSmall: '图像文件的"{name}"的宽度必须是至少{size}像素.', - msgImageHeightSmall: '图像文件的"{name}"的高度必须至少为{size}像素.', - msgImageWidthLarge: '图像文件"{name}"的宽度不能超过{size}像素.', - msgImageHeightLarge: '图像文件"{name}"的高度不能超过{size}像素.', - msgImageResizeError: '无法获取的图像尺寸调整。', - msgImageResizeException: '调整图像大小时发生错误。
    {errors}
    ', - msgAjaxError: '{operation} 发生错误. 请重试!', - msgAjaxProgressError: '{operation} 失败', - msgDuplicateFile: 'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.', - msgResumableUploadRetriesExceeded: 'Upload aborted beyond {max} retries for file {file}! Error Details:
    {error}
    ', - msgPendingTime: '{time} remaining', - msgCalculatingTime: 'calculating time remaining', - ajaxOperations: { - deleteThumb: '删除文件', - uploadThumb: '上传文件', - uploadBatch: '批量上传', - uploadExtra: '表单数据上传' - }, - dropZoneTitle: '拖拽文件到这里 …
    支持多文件同时上传', - dropZoneClickTitle: '
    (或点击{files}按钮选择文件)', - fileActionSettings: { - removeTitle: '删除文件', - uploadTitle: '上传文件', - downloadTitle: '下载文件', - uploadRetryTitle: '重试', - zoomTitle: '查看详情', - dragTitle: '移动 / 重置', - indicatorNewTitle: '没有上传', - indicatorSuccessTitle: '上传', - indicatorErrorTitle: '上传错误', - indicatorPausedTitle: 'Upload Paused', - indicatorLoadingTitle: '上传 …' - }, - previewZoomButtonTitles: { - prev: '预览上一个文件', - next: '预览下一个文件', - toggleheader: '缩放', - fullscreen: '全屏', - borderless: '无边界模式', - close: '关闭当前预览' - } - }; - - $.fn.fileinput.Constructor = FileInput; - - /** - * Convert automatically file inputs with class 'file' into a bootstrap fileinput control. - */ - $(document).ready(function () { - var $input = $('input.file[type=file]'); - if ($input.length) { - $input.fileinput(); - } - }); -})); \ No newline at end of file +/*! + * bootstrap-fileinput v5.2.3 + * http://plugins.krajee.com/file-input + * + * Author: Kartik Visweswaran + * Copyright: 2014 - 2021, Kartik Visweswaran, Krajee.com + * + * Licensed under the BSD-3-Clause + * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md + */ +(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + define(['jquery'], factory); + } else { + if (typeof module === 'object' && module.exports) { + //noinspection NpmUsedModulesInstalled + module.exports = factory(require('jquery')); + } else { + factory(window.jQuery); + } + } +}(function ($) { + 'use strict'; + $.fn.fileinputLocales = {}; + $.fn.fileinputThemes = {}; + if (!$.fn.fileinputBsVersion) { + $.fn.fileinputBsVersion = (window.Alert && window.Alert.VERSION) || + (window.bootstrap && window.bootstrap.Alert && bootstrap.Alert.VERSION) || '3.x.x'; + } + String.prototype.setTokens = function (replacePairs) { + var str = this.toString(), key, re; + for (key in replacePairs) { + if (replacePairs.hasOwnProperty(key)) { + re = new RegExp('\{' + key + '\}', 'g'); + str = str.replace(re, replacePairs[key]); + } + } + return str; + }; + + if (!Array.prototype.flatMap) { // polyfill flatMap + Array.prototype.flatMap = function (lambda) { + return [].concat(this.map(lambda)); + }; + } + + var $h, FileInput; + + // fileinput helper object for all global variables and internal helper methods + $h = { + FRAMES: '.kv-preview-thumb', + SORT_CSS: 'file-sortable', + INIT_FLAG: 'init-', + OBJECT_PARAMS: '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n', + DEFAULT_PREVIEW: '
    \n' + + '{previewFileIcon}\n' + + '
    ', + MODAL_ID: 'kvFileinputModal', + MODAL_EVENTS: ['show', 'shown', 'hide', 'hidden', 'loaded'], + logMessages: { + ajaxError: '{status}: {error}. Error Details: {text}.', + badDroppedFiles: 'Error scanning dropped files!', + badExifParser: 'Error loading the piexif.js library. {details}', + badInputType: 'The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.', + exifWarning: 'To avoid this warning, either set "autoOrientImage" to "false" OR ensure you have loaded ' + + 'the "piexif.js" library correctly on your page before the "fileinput.js" script.', + invalidChunkSize: 'Invalid upload chunk size: "{chunkSize}". Resumable uploads are disabled.', + invalidThumb: 'Invalid thumb frame with id: "{id}".', + noResumableSupport: 'The browser does not support resumable or chunk uploads.', + noUploadUrl: 'The "uploadUrl" is not set. Ajax uploads and resumable uploads have been disabled.', + retryStatus: 'Retrying upload for chunk # {chunk} for {filename}... retry # {retry}.', + chunkQueueError: 'Could not push task to ajax pool for chunk index # {index}.', + resumableMaxRetriesReached: 'Maximum resumable ajax retries ({n}) reached.', + resumableRetryError: 'Could not retry the resumable request (try # {n})... aborting.', + resumableAborting: 'Aborting / cancelling the resumable request.', + resumableRequestError: 'Error processing resumable request. {msg}' + + }, + objUrl: window.URL || window.webkitURL, + isBs: function (ver) { + var chk = $.trim(($.fn.fileinputBsVersion || '') + ''); + ver = parseInt(ver, 10); + if (!chk) { + return ver === 4; + } + return ver === parseInt(chk.charAt(0), 10); + + }, + defaultButtonCss: function (fill) { + return 'btn-default btn-' + (fill ? '' : 'outline-') + 'secondary'; + }, + now: function () { + return new Date().getTime(); + }, + round: function (num) { + num = parseFloat(num); + return isNaN(num) ? 0 : Math.floor(Math.round(num)); + }, + getArray: function (obj) { + var i, arr = [], len = obj && obj.length || 0; + for (i = 0; i < len; i++) { + arr.push(obj[i]); + } + return arr; + }, + getFileRelativePath: function (file) { + /** @namespace file.relativePath */ + /** @namespace file.webkitRelativePath */ + return String(file.newPath || file.relativePath || file.webkitRelativePath || $h.getFileName(file) || null); + + }, + getFileId: function (file, generateFileId) { + var relativePath = $h.getFileRelativePath(file); + if (typeof generateFileId === 'function') { + return generateFileId(file); + } + if (!file) { + return null; + } + if (!relativePath) { + return null; + } + return (file.size + '_' + encodeURIComponent(relativePath).replace(/%/g, '_')); + }, + getFrameSelector: function (id, selector) { + selector = selector || ''; + return '[id="' + id + '"]' + selector; + }, + getZoomSelector: function (id, selector) { + return $h.getFrameSelector('zoom-' + id, selector); + }, + getFrameElement: function ($element, id, selector) { + return $element.find($h.getFrameSelector(id, selector)); + }, + getZoomElement: function ($element, id, selector) { + return $element.find($h.getZoomSelector(id, selector)); + }, + getElapsed: function (seconds) { + var delta = seconds, out = '', result = {}, structure = { + year: 31536000, + month: 2592000, + week: 604800, // uncomment row to ignore + day: 86400, // feel free to add your own row + hour: 3600, + minute: 60, + second: 1 + }; + $h.getObjectKeys(structure).forEach(function (key) { + result[key] = Math.floor(delta / structure[key]); + delta -= result[key] * structure[key]; + }); + $.each(result, function (key, value) { + if (value > 0) { + out += (out ? ' ' : '') + value + key.substring(0, 1); + } + }); + return out; + }, + debounce: function (func, delay) { + var inDebounce; + return function () { + var args = arguments, context = this; + clearTimeout(inDebounce); + inDebounce = setTimeout(function () { + func.apply(context, args); + }, delay); + }; + }, + stopEvent: function (e) { + e.stopPropagation(); + e.preventDefault(); + }, + getFileName: function (file) { + /** @namespace file.fileName */ + return file ? (file.fileName || file.name || '') : ''; // some confusion in different versions of Firefox + }, + createObjectURL: function (data) { + if ($h.objUrl && $h.objUrl.createObjectURL && data) { + return $h.objUrl.createObjectURL(data); + } + return ''; + }, + revokeObjectURL: function (data) { + if ($h.objUrl && $h.objUrl.revokeObjectURL && data) { + $h.objUrl.revokeObjectURL(data); + } + }, + compare: function (input, str, exact) { + return input !== undefined && (exact ? input === str : input.match(str)); + }, + isIE: function (ver) { + var div, status; + // check for IE versions < 11 + if (navigator.appName !== 'Microsoft Internet Explorer') { + return false; + } + if (ver === 10) { + return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent); + } + div = document.createElement('div'); + div.innerHTML = ''; + status = div.getElementsByTagName('i').length; + document.body.appendChild(div); + div.parentNode.removeChild(div); + return status; + }, + canOrientImage: function ($el) { + var $img = $(document.createElement('img')).css({width: '1px', height: '1px'}).insertAfter($el), + flag = $img.css('image-orientation'); + $img.remove(); + return !!flag; + }, + canAssignFilesToInput: function () { + var input = document.createElement('input'); + try { + input.type = 'file'; + input.files = null; + return true; + } catch (err) { + return false; + } + }, + getDragDropFolders: function (items) { + var i, item, len = items ? items.length : 0, folders = 0; + if (len > 0 && items[0].webkitGetAsEntry()) { + for (i = 0; i < len; i++) { + item = items[i].webkitGetAsEntry(); + if (item && item.isDirectory) { + folders++; + } + } + } + return folders; + }, + initModal: function ($modal) { + var $body = $('body'); + if ($body.length) { + $modal.appendTo($body); + } + }, + isFunction: function (v) { + return typeof v === 'function'; + }, + isEmpty: function (value, trim) { + if (value === undefined || value === null || value === '') { + return true; + } + if ($h.isString(value) && trim) { + return $.trim(value) === ''; + } + if ($h.isArray(value)) { + return value.length === 0; + } + if ($.isPlainObject(value) && $.isEmptyObject(value)) { + return true + } + return false; + }, + isArray: function (a) { + return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]'; + }, + isString: function (a) { + return Object.prototype.toString.call(a) === '[object String]'; + }, + ifSet: function (needle, haystack, def) { + def = def || ''; + return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def; + }, + cleanArray: function (arr) { + if (!(arr instanceof Array)) { + arr = []; + } + return arr.filter(function (e) { + return (e !== undefined && e !== null); + }); + }, + spliceArray: function (arr, index, reverseOrder) { + var i, j = 0, out = [], newArr; + if (!(arr instanceof Array)) { + return []; + } + newArr = $.extend(true, [], arr); + if (reverseOrder) { + newArr.reverse(); + } + for (i = 0; i < newArr.length; i++) { + if (i !== index) { + out[j] = newArr[i]; + j++; + } + } + if (reverseOrder) { + out.reverse(); + } + return out; + }, + getNum: function (num, def) { + def = def || 0; + if (typeof num === 'number') { + return num; + } + if (typeof num === 'string') { + num = parseFloat(num); + } + return isNaN(num) ? def : num; + }, + hasFileAPISupport: function () { + return !!(window.File && window.FileReader); + }, + hasDragDropSupport: function () { + var div = document.createElement('div'); + /** @namespace div.draggable */ + /** @namespace div.ondragstart */ + /** @namespace div.ondrop */ + return !$h.isIE(9) && + (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined)); + }, + hasFileUploadSupport: function () { + return $h.hasFileAPISupport() && window.FormData; + }, + hasBlobSupport: function () { + try { + return !!window.Blob && Boolean(new Blob()); + } catch (e) { + return false; + } + }, + hasArrayBufferViewSupport: function () { + try { + return new Blob([new Uint8Array(100)]).size === 100; + } catch (e) { + return false; + } + }, + hasResumableUploadSupport: function () { + /** @namespace Blob.prototype.webkitSlice */ + /** @namespace Blob.prototype.mozSlice */ + return $h.hasFileUploadSupport() && $h.hasBlobSupport() && $h.hasArrayBufferViewSupport() && + (!!Blob.prototype.webkitSlice || !!Blob.prototype.mozSlice || !!Blob.prototype.slice || false); + }, + dataURI2Blob: function (dataURI) { + var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || + window.MSBlobBuilder, canBlob = $h.hasBlobSupport(), byteStr, arrayBuffer, intArray, i, mimeStr, bb, + canProceed = (canBlob || BlobBuilder) && window.atob && window.ArrayBuffer && window.Uint8Array; + if (!canProceed) { + return null; + } + if (dataURI.split(',')[0].indexOf('base64') >= 0) { + byteStr = atob(dataURI.split(',')[1]); + } else { + byteStr = decodeURIComponent(dataURI.split(',')[1]); + } + arrayBuffer = new ArrayBuffer(byteStr.length); + intArray = new Uint8Array(arrayBuffer); + for (i = 0; i < byteStr.length; i += 1) { + intArray[i] = byteStr.charCodeAt(i); + } + mimeStr = dataURI.split(',')[0].split(':')[1].split(';')[0]; + if (canBlob) { + return new Blob([$h.hasArrayBufferViewSupport() ? intArray : arrayBuffer], {type: mimeStr}); + } + bb = new BlobBuilder(); + bb.append(arrayBuffer); + return bb.getBlob(mimeStr); + }, + arrayBuffer2String: function (buffer) { + if (window.TextDecoder) { + return new TextDecoder('utf-8').decode(buffer); + } + var array = Array.prototype.slice.apply(new Uint8Array(buffer)), out = '', i = 0, len, c, char2, char3; + len = array.length; + while (i < len) { + c = array[i++]; + switch (c >> 4) { // jshint ignore:line + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + // 0xxxxxxx + out += String.fromCharCode(c); + break; + case 12: + case 13: + // 110x xxxx 10xx xxxx + char2 = array[i++]; + out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); // jshint ignore:line + break; + case 14: + // 1110 xxxx 10xx xxxx 10xx xxxx + char2 = array[i++]; + char3 = array[i++]; + out += String.fromCharCode(((c & 0x0F) << 12) | // jshint ignore:line + ((char2 & 0x3F) << 6) | // jshint ignore:line + ((char3 & 0x3F) << 0)); // jshint ignore:line + break; + } + } + return out; + }, + isHtml: function (str) { + var a = document.createElement('div'); + a.innerHTML = str; + for (var c = a.childNodes, i = c.length; i--;) { + if (c[i].nodeType === 1) { + return true; + } + } + return false; + }, + isSvg: function (str) { + return str.match(/^\s*<\?xml/i) && (str.match(/' + str + '')); + }, + uniqId: function () { + return (new Date().getTime() + Math.floor(Math.random() * Math.pow(10, 15))).toString(36); + }, + cspBuffer: { + CSP_ATTRIB: 'data-csp-01928735', // a randomly named temporary attribute to store the CSP elem id + domElementsStyles: {}, + stash: function (htmlString) { + var self = this, outerDom = $.parseHTML('
    ' + htmlString + '
    '), $el = $(outerDom); + $el.find('[style]').each(function (key, elem) { + var $elem = $(elem), styleDeclaration = $elem[0].style, id = $h.uniqId(), styles = {}; + if (styleDeclaration && styleDeclaration.length) { + $(styleDeclaration).each(function () { + styles[this] = styleDeclaration[this]; + }); + self.domElementsStyles[id] = styles; + $elem.removeAttr('style').attr(self.CSP_ATTRIB, id); + } + }); + $el.filter('*').removeAttr('style'); // make sure all style attr are removed + var values = Object.values ? Object.values(outerDom) : Object.keys(outerDom).map(function (itm) { + return outerDom[itm]; + }); + return values.flatMap(function (elem) { + return elem.innerHTML; + }).join(''); + }, + apply: function (domElement) { + var self = this, $el = $(domElement); + $el.find('[' + self.CSP_ATTRIB + ']').each(function (key, elem) { + var $elem = $(elem), id = $elem.attr(self.CSP_ATTRIB), styles = self.domElementsStyles[id]; + if (styles) { + $elem.css(styles); + } + $elem.removeAttr(self.CSP_ATTRIB); + }); + self.domElementsStyles = {}; + } + }, + setHtml: function ($elem, htmlString) { + var buf = $h.cspBuffer; + $elem.html(buf.stash(htmlString)); + buf.apply($elem); + return $elem; + }, + htmlEncode: function (str, undefVal) { + if (str === undefined) { + return undefVal || null; + } + return str.replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + }, + replaceTags: function (str, tags) { + var out = str; + if (!tags) { + return out; + } + $.each(tags, function (key, value) { + if (typeof value === 'function') { + value = value(); + } + out = out.split(key).join(value); + }); + return out; + }, + cleanMemory: function ($thumb) { + var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src'); + $h.revokeObjectURL(data); + }, + findFileName: function (filePath) { + var sepIndex = filePath.lastIndexOf('/'); + if (sepIndex === -1) { + sepIndex = filePath.lastIndexOf('\\'); + } + return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop(); + }, + checkFullScreen: function () { + return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || + document.msFullscreenElement; + }, + toggleFullScreen: function (maximize) { + var doc = document, de = doc.documentElement, isFullScreen = $h.checkFullScreen(); + if (de && maximize && !isFullScreen) { + if (de.requestFullscreen) { + de.requestFullscreen(); + } else { + if (de.msRequestFullscreen) { + de.msRequestFullscreen(); + } else { + if (de.mozRequestFullScreen) { + de.mozRequestFullScreen(); + } else { + if (de.webkitRequestFullscreen) { + de.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); + } + } + } + } + } else { + if (isFullScreen) { + if (doc.exitFullscreen) { + doc.exitFullscreen(); + } else { + if (doc.msExitFullscreen) { + doc.msExitFullscreen(); + } else { + if (doc.mozCancelFullScreen) { + doc.mozCancelFullScreen(); + } else { + if (doc.webkitExitFullscreen) { + doc.webkitExitFullscreen(); + } + } + } + } + } + } + }, + moveArray: function (arr, oldIndex, newIndex, reverseOrder) { + var newArr = $.extend(true, [], arr); + if (reverseOrder) { + newArr.reverse(); + } + if (newIndex >= newArr.length) { + var k = newIndex - newArr.length; + while ((k--) + 1) { + newArr.push(undefined); + } + } + newArr.splice(newIndex, 0, newArr.splice(oldIndex, 1)[0]); + if (reverseOrder) { + newArr.reverse(); + } + return newArr; + }, + closeButton: function (css) { + css = ($h.isBs(5) ? 'btn-close' : 'close') + (css ? ' ' + css : ''); + return ''; + }, + getRotation: function (value) { + switch (value) { + case 2: + return 'rotateY(180deg)'; + case 3: + return 'rotate(180deg)'; + case 4: + return 'rotate(180deg) rotateY(180deg)'; + case 5: + return 'rotate(270deg) rotateY(180deg)'; + case 6: + return 'rotate(90deg)'; + case 7: + return 'rotate(90deg) rotateY(180deg)'; + case 8: + return 'rotate(270deg)'; + default: + return ''; + } + }, + setTransform: function (el, val) { + if (!el) { + return; + } + el.style.transform = val; + el.style.webkitTransform = val; + el.style['-moz-transform'] = val; + el.style['-ms-transform'] = val; + el.style['-o-transform'] = val; + }, + getObjectKeys: function (obj) { + var keys = []; + if (obj) { + $.each(obj, function (key) { + keys.push(key); + }); + } + return keys; + }, + getObjectSize: function (obj) { + return $h.getObjectKeys(obj).length; + }, + /** + * Small dependency injection for the task manager + * https://gist.github.com/fearphage/4341799 + */ + whenAll: function (array) { + var s = [].slice, resolveValues = arguments.length === 1 && $h.isArray(array) ? array : s.call(arguments), + deferred = $.Deferred(), i, failed = 0, value, length = resolveValues.length, + remaining = length, rejectContexts, rejectValues, resolveContexts, updateFunc; + rejectContexts = rejectValues = resolveContexts = Array(length); + updateFunc = function (index, contexts, values) { + return function () { + if (values !== resolveValues) { + failed++; + } + deferred.notifyWith(contexts[index] = this, values[index] = s.call(arguments)); + if (!(--remaining)) { + deferred[(!failed ? 'resolve' : 'reject') + 'With'](contexts, values); + } + }; + }; + for (i = 0; i < length; i++) { + if ((value = resolveValues[i]) && $.isFunction(value.promise)) { + value.promise() + .done(updateFunc(i, resolveContexts, resolveValues)) + .fail(updateFunc(i, rejectContexts, rejectValues)); + } else { + deferred.notifyWith(this, value); + --remaining; + } + } + if (!remaining) { + deferred.resolveWith(resolveContexts, resolveValues); + } + return deferred.promise(); + } + }; + FileInput = function (element, options) { + var self = this; + self.$element = $(element); + self.$parent = self.$element.parent(); + if (!self._validate()) { + return; + } + self.isPreviewable = $h.hasFileAPISupport(); + self.isIE9 = $h.isIE(9); + self.isIE10 = $h.isIE(10); + if (self.isPreviewable || self.isIE9) { + self._init(options); + self._listen(); + } + self.$element.removeClass('file-loading'); + }; + + FileInput.prototype = { + constructor: FileInput, + _cleanup: function () { + var self = this; + self.reader = null; + self.clearFileStack(); + self.fileBatchCompleted = true; + self.isError = false; + self.isDuplicateError = false; + self.isPersistentError = false; + self.cancelling = false; + self.paused = false; + self.lastProgress = 0; + self._initAjax(); + }, + _isAborted: function () { + var self = this; + return self.cancelling || self.paused; + }, + _initAjax: function () { + var self = this, tm = self.taskManager = { + pool: {}, + addPool: function (id) { + return (tm.pool[id] = new tm.TasksPool(id)); + }, + getPool: function (id) { + return tm.pool[id]; + }, + addTask: function (id, logic) { // add standalone task directly from task manager + return new tm.Task(id, logic); + }, + TasksPool: function (id) { + var tp = this; + tp.id = id; + tp.cancelled = false; + tp.cancelledDeferrer = $.Deferred(); + tp.tasks = {}; + tp.addTask = function (id, logic) { + return (tp.tasks[id] = new tm.Task(id, logic)); + }; + tp.size = function () { + return $h.getObjectSize(tp.tasks); + }; + tp.run = function (maxThreads) { + var i = 0, failed = false, task, tasksList = $h.getObjectKeys(tp.tasks).map(function (key) { + return tp.tasks[key]; + }), tasksDone = [], deferred = $.Deferred(), enqueue, callback; + + if (tp.cancelled) { + tp.cancelledDeferrer.resolve(); + return deferred.reject(); + } + // if run all at once + if (!maxThreads) { + var tasksDeferredList = $h.getObjectKeys(tp.tasks).map(function (key) { + return tp.tasks[key].deferred; + }); + // when all are done + $h.whenAll(tasksDeferredList).done(function () { + var argv = $h.getArray(arguments); + if (!tp.cancelled) { + deferred.resolve.apply(null, argv); + tp.cancelledDeferrer.reject(); + } else { + deferred.reject.apply(null, argv); + tp.cancelledDeferrer.resolve(); + } + }).fail(function () { + var argv = $h.getArray(arguments); + deferred.reject.apply(null, argv); + if (!tp.cancelled) { + tp.cancelledDeferrer.reject(); + } else { + tp.cancelledDeferrer.resolve(); + } + }); + // run all tasks + $.each(tp.tasks, function (id) { + task = tp.tasks[id]; + task.run(); + }); + return deferred; + } + enqueue = function (task) { + $.when(task.deferred) + .fail(function () { + failed = true; + callback.apply(null, arguments); + }) + .always(callback); + }; + callback = function () { + var argv = $h.getArray(arguments); + // notify a task just ended + deferred.notify(argv); + tasksDone.push(argv); + if (tp.cancelled) { + deferred.reject.apply(null, tasksDone); + tp.cancelledDeferrer.resolve(); + return; + } + if (tasksDone.length === tp.size()) { + if (failed) { + deferred.reject.apply(null, tasksDone); + } else { + deferred.resolve.apply(null, tasksDone); + } + } + // if there are any tasks remaining + if (tasksList.length) { + task = tasksList.shift(); + enqueue(task); + task.run(); + } + }; + // run the first "maxThreads" tasks + while (tasksList.length && i++ < maxThreads) { + task = tasksList.shift(); + enqueue(task); + task.run(); + } + return deferred; + }; + tp.cancel = function () { + tp.cancelled = true; + return tp.cancelledDeferrer; + }; + }, + Task: function (id, logic) { + var tk = this; + tk.id = id; + tk.deferred = $.Deferred(); + tk.logic = logic; + tk.context = null; + tk.run = function () { + var argv = $h.getArray(arguments); + argv.unshift(tk.deferred); // add deferrer as first argument + logic.apply(tk.context, argv); // run task + return tk.deferred; // return deferrer + }; + tk.runWithContext = function (context) { + tk.context = context; + return tk.run(); + }; + } + }; + self.ajaxQueue = []; + self.ajaxRequests = []; + self.ajaxAborted = false; + }, + _init: function (options, refreshMode) { + var self = this, f, $el = self.$element, $cont, t, tmp; + self.options = options; + self.canOrientImage = $h.canOrientImage($el); + $.each(options, function (key, value) { + switch (key) { + case 'minFileCount': + case 'maxFileCount': + case 'maxTotalFileCount': + case 'minFileSize': + case 'maxFileSize': + case 'maxFilePreviewSize': + case 'resizeQuality': + case 'resizeIfSizeMoreThan': + case 'progressUploadThreshold': + case 'initialPreviewCount': + case 'zoomModalHeight': + case 'minImageHeight': + case 'maxImageHeight': + case 'minImageWidth': + case 'maxImageWidth': + case 'bytesToKB': + self[key] = $h.getNum(value); + break; + default: + self[key] = value; + break; + } + }); + if (!self.bytesToKB || self.bytesToKB <= 0) { + self.bytesToKB = 1024; + } + if (self.errorCloseButton === undefined) { + self.errorCloseButton = $h.closeButton('kv-error-close' + ($h.isBs(5) ? ' float-end' : '')); + } + if (self.maxTotalFileCount > 0 && self.maxTotalFileCount < self.maxFileCount) { + self.maxTotalFileCount = self.maxFileCount; + } + if (self.rtl) { // swap buttons for rtl + tmp = self.previewZoomButtonIcons.prev; + self.previewZoomButtonIcons.prev = self.previewZoomButtonIcons.next; + self.previewZoomButtonIcons.next = tmp; + } + // validate chunk threads to not exceed maxAjaxThreads + if (!isNaN(self.maxAjaxThreads) && self.maxAjaxThreads < self.resumableUploadOptions.maxThreads) { + self.resumableUploadOptions.maxThreads = self.maxAjaxThreads; + } + self._initFileManager(); + if (typeof self.autoOrientImage === 'function') { + self.autoOrientImage = self.autoOrientImage(); + } + if (typeof self.autoOrientImageInitial === 'function') { + self.autoOrientImageInitial = self.autoOrientImageInitial(); + } + if (!refreshMode) { + self._cleanup(); + } + self.duplicateErrors = []; + self.$form = $el.closest('form'); + self._initTemplateDefaults(); + self.uploadFileAttr = !$h.isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data'; + t = self._getLayoutTemplate('progress'); + self.progressTemplate = t.replace('{class}', self.progressClass); + self.progressInfoTemplate = t.replace('{class}', self.progressInfoClass); + self.progressPauseTemplate = t.replace('{class}', self.progressPauseClass); + self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass); + self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass); + self.isDisabled = $el.attr('disabled') || $el.attr('readonly'); + if (self.isDisabled) { + $el.attr('disabled', true); + } + self.isClickable = self.browseOnZoneClick && self.showPreview && + (self.dropZoneEnabled || !$h.isEmpty(self.defaultPreviewContent)); + self.isAjaxUpload = $h.hasFileUploadSupport() && !$h.isEmpty(self.uploadUrl); + self.dropZoneEnabled = $h.hasDragDropSupport() && self.dropZoneEnabled; + if (!self.isAjaxUpload) { + self.dropZoneEnabled = self.dropZoneEnabled && $h.canAssignFilesToInput(); + } + self.slug = typeof options.slugCallback === 'function' ? options.slugCallback : self._slugDefault; + self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2'); + self.captionTemplate = self._getLayoutTemplate('caption'); + self.previewGenericTemplate = self._getPreviewTemplate('generic'); + if (!self.imageCanvas && self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) { + self.imageCanvas = document.createElement('canvas'); + self.imageCanvasContext = self.imageCanvas.getContext('2d'); + } + if ($h.isEmpty($el.attr('id'))) { + $el.attr('id', $h.uniqId()); + } + self.namespace = '.fileinput_' + $el.attr('id').replace(/-/g, '_'); + if (self.$container === undefined) { + self.$container = self._createContainer(); + } else { + self._refreshContainer(); + } + $cont = self.$container; + self.$dropZone = $cont.find('.file-drop-zone'); + self.$progress = $cont.find('.kv-upload-progress'); + self.$btnUpload = $cont.find('.fileinput-upload'); + self.$captionContainer = $h.getElement(options, 'elCaptionContainer', $cont.find('.file-caption')); + self.$caption = $h.getElement(options, 'elCaptionText', $cont.find('.file-caption-name')); + if (!$h.isEmpty(self.msgPlaceholder)) { + f = $el.attr('multiple') ? self.filePlural : self.fileSingle; + self.$caption.attr('placeholder', self.msgPlaceholder.replace('{files}', f)); + } + self.$captionIcon = self.$captionContainer.find('.file-caption-icon'); + self.$previewContainer = $h.getElement(options, 'elPreviewContainer', $cont.find('.file-preview')); + self.$preview = $h.getElement(options, 'elPreviewImage', $cont.find('.file-preview-thumbnails')); + self.$previewStatus = $h.getElement(options, 'elPreviewStatus', $cont.find('.file-preview-status')); + self.$errorContainer = $h.getElement(options, 'elErrorContainer', + self.$previewContainer.find('.kv-fileinput-error')); + self._validateDisabled(); + if (!$h.isEmpty(self.msgErrorClass)) { + $h.addCss(self.$errorContainer, self.msgErrorClass); + } + if (!refreshMode) { + self._resetErrors(); + self.$errorContainer.hide(); + self.previewInitId = 'thumb-' + $el.attr('id'); + self._initPreviewCache(); + self._initPreview(true); + self._initPreviewActions(); + if (self.$parent.hasClass('file-loading')) { + self.$container.insertBefore(self.$parent); + self.$parent.remove(); + } + } else { + if (!self._errorsExist()) { + self.$errorContainer.hide(); + } + } + self._setFileDropZoneTitle(); + if ($el.attr('disabled')) { + self.disable(); + } + self._initZoom(); + if (self.hideThumbnailContent) { + $h.addCss(self.$preview, 'hide-content'); + } + }, + _initFileManager: function () { + var self = this; + self.uploadStartTime = $h.now(); + self.fileManager = { + stack: {}, + filesProcessed: [], + errors: [], + loadedImages: {}, + totalImages: 0, + totalFiles: null, + totalSize: null, + uploadedSize: 0, + stats: {}, + bpsLog: [], + bps: 0, + initStats: function (id) { + var data = {started: $h.now()}; + if (id) { + self.fileManager.stats[id] = data; + } else { + self.fileManager.stats = data; + } + }, + getUploadStats: function (id, loaded, total) { + var fm = self.fileManager, + started = id ? fm.stats[id] && fm.stats[id].started || $h.now() : self.uploadStartTime, + elapsed = ($h.now() - started) / 1000, bps = Math.ceil(elapsed ? loaded / elapsed : 0), + pendingBytes = total - loaded, out, delay = fm.bpsLog.length ? self.bitrateUpdateDelay : 0; + setTimeout(function () { + var i, j = 0, n = 0, len, beg; + fm.bpsLog.push(bps); + fm.bpsLog.sort(function (a, b) { + return a - b; + }); + len = fm.bpsLog.length; + beg = len > 10 ? len - 10 : Math.ceil(len / 2); + for (i = len; i > beg; i--) { + n = parseFloat(fm.bpsLog[i]); + j++; + } + fm.bps = (j > 0 ? n / j : 0) * 64; + }, delay); + out = { + fileId: id, + started: started, + elapsed: elapsed, + loaded: loaded, + total: total, + bps: fm.bps, + bitrate: self._getSize(fm.bps, self.bitRateUnits), + pendingBytes: pendingBytes + }; + if (id) { + fm.stats[id] = out; + } else { + fm.stats = out; + } + return out; + }, + exists: function (id) { + return $.inArray(id, self.fileManager.getIdList()) !== -1; + }, + count: function () { + return self.fileManager.getIdList().length; + }, + total: function () { + var fm = self.fileManager; + if (!fm.totalFiles) { + fm.totalFiles = fm.count(); + } + return fm.totalFiles; + }, + getTotalSize: function () { + var fm = self.fileManager; + if (fm.totalSize) { + return fm.totalSize; + } + fm.totalSize = 0; + $.each(self.getFileStack(), function (id, f) { + var size = parseFloat(f.size); + fm.totalSize += isNaN(size) ? 0 : size; + }); + return fm.totalSize; + }, + add: function (file, id) { + if (!id) { + id = self.fileManager.getId(file); + } + if (!id) { + return; + } + self.fileManager.stack[id] = { + file: file, + name: $h.getFileName(file), + relativePath: $h.getFileRelativePath(file), + size: file.size, + nameFmt: self._getFileName(file, ''), + sizeFmt: self._getSize(file.size) + }; + }, + remove: function ($thumb) { + var id = self._getThumbFileId($thumb); + self.fileManager.removeFile(id); + }, + removeFile: function (id) { + var fm = self.fileManager; + if (!id) { + return; + } + delete fm.stack[id]; + delete fm.loadedImages[id]; + }, + move: function (idFrom, idTo) { + var result = {}, stack = self.fileManager.stack; + if (!idFrom && !idTo || idFrom === idTo) { + return; + } + $.each(stack, function (k, v) { + if (k !== idFrom) { + result[k] = v; + } + if (k === idTo) { + result[idFrom] = stack[idFrom]; + } + }); + self.fileManager.stack = result; + }, + list: function () { + var files = []; + $.each(self.getFileStack(), function (k, v) { + if (v && v.file) { + files.push(v.file); + } + }); + return files; + }, + isPending: function (id) { + return $.inArray(id, self.fileManager.filesProcessed) === -1 && self.fileManager.exists(id); + }, + isProcessed: function () { + var filesProcessed = true, fm = self.fileManager; + $.each(self.getFileStack(), function (id) { + if (fm.isPending(id)) { + filesProcessed = false; + } + }); + return filesProcessed; + }, + clear: function () { + var fm = self.fileManager; + self.isDuplicateError = false; + self.isPersistentError = false; + fm.totalFiles = null; + fm.totalSize = null; + fm.uploadedSize = 0; + fm.stack = {}; + fm.errors = []; + fm.filesProcessed = []; + fm.stats = {}; + fm.bpsLog = []; + fm.bps = 0; + fm.clearImages(); + }, + clearImages: function () { + self.fileManager.loadedImages = {}; + self.fileManager.totalImages = 0; + }, + addImage: function (id, config) { + self.fileManager.loadedImages[id] = config; + }, + removeImage: function (id) { + delete self.fileManager.loadedImages[id]; + }, + getImageIdList: function () { + return $h.getObjectKeys(self.fileManager.loadedImages); + }, + getImageCount: function () { + return self.fileManager.getImageIdList().length; + }, + getId: function (file) { + return self._getFileId(file); + }, + getIndex: function (id) { + return self.fileManager.getIdList().indexOf(id); + }, + getThumb: function (id) { + var $thumb = null; + self._getThumbs().each(function () { + var $t = $(this); + if (self._getThumbFileId($t) === id) { + $thumb = $t; + } + }); + return $thumb; + }, + getThumbIndex: function ($thumb) { + var id = self._getThumbFileId($thumb); + return self.fileManager.getIndex(id); + }, + getIdList: function () { + return $h.getObjectKeys(self.fileManager.stack); + }, + getFile: function (id) { + return self.fileManager.stack[id] || null; + }, + getFileName: function (id, fmt) { + var file = self.fileManager.getFile(id); + if (!file) { + return ''; + } + return fmt ? (file.nameFmt || '') : file.name || ''; + }, + getFirstFile: function () { + var ids = self.fileManager.getIdList(), id = ids && ids.length ? ids[0] : null; + return self.fileManager.getFile(id); + }, + setFile: function (id, file) { + if (self.fileManager.getFile(id)) { + self.fileManager.stack[id].file = file; + } else { + self.fileManager.add(file, id); + } + }, + setProcessed: function (id) { + self.fileManager.filesProcessed.push(id); + }, + getProgress: function () { + var total = self.fileManager.total(), filesProcessed = self.fileManager.filesProcessed.length; + if (!total) { + return 0; + } + return Math.ceil(filesProcessed / total * 100); + + }, + setProgress: function (id, pct) { + var f = self.fileManager.getFile(id); + if (!isNaN(pct) && f) { + f.progress = pct; + } + } + }; + }, + _setUploadData: function (fd, config) { + var self = this; + $.each(config, function (key, value) { + var param = self.uploadParamNames[key] || key; + if ($h.isArray(value)) { + fd.append(param, value[0], value[1]); + } else { + fd.append(param, value); + } + }); + }, + _initResumableUpload: function () { + var self = this, opts = self.resumableUploadOptions, logs = $h.logMessages, rm, fm = self.fileManager; + if (!self.enableResumableUpload) { + return; + } + if (opts.fallback !== false && typeof opts.fallback !== 'function') { + opts.fallback = function (s) { + s._log(logs.noResumableSupport); + s.enableResumableUpload = false; + }; + } + if (!$h.hasResumableUploadSupport() && opts.fallback !== false) { + opts.fallback(self); + return; + } + if (!self.uploadUrl && self.enableResumableUpload) { + self._log(logs.noUploadUrl); + self.enableResumableUpload = false; + return; + + } + opts.chunkSize = parseFloat(opts.chunkSize); + if (opts.chunkSize <= 0 || isNaN(opts.chunkSize)) { + self._log(logs.invalidChunkSize, {chunkSize: opts.chunkSize}); + self.enableResumableUpload = false; + return; + } + rm = self.resumableManager = { + init: function (id, f, index) { + rm.logs = []; + rm.stack = []; + rm.error = ''; + rm.id = id; + rm.file = f.file; + rm.fileName = f.name; + rm.fileIndex = index; + rm.completed = false; + rm.lastProgress = 0; + if (self.showPreview) { + rm.$thumb = fm.getThumb(id) || null; + rm.$progress = rm.$btnDelete = null; + if (rm.$thumb && rm.$thumb.length) { + rm.$progress = rm.$thumb.find('.file-thumb-progress'); + rm.$btnDelete = rm.$thumb.find('.kv-file-remove'); + } + } + rm.chunkSize = opts.chunkSize * self.bytesToKB; + rm.chunkCount = rm.getTotalChunks(); + }, + setAjaxError: function (jqXHR, textStatus, errorThrown, isTest) { + if (jqXHR.responseJSON && jqXHR.responseJSON.error) { + errorThrown = jqXHR.responseJSON.error.toString(); + } + if (!isTest) { + rm.error = errorThrown; + } + if (opts.showErrorLog) { + self._log(logs.ajaxError, { + status: jqXHR.status, + error: errorThrown, + text: jqXHR.responseText || '' + }); + } + }, + reset: function () { + rm.stack = []; + rm.chunksProcessed = {}; + }, + setProcessed: function (status) { + var id = rm.id, msg, $thumb = rm.$thumb, $prog = rm.$progress, hasThumb = $thumb && $thumb.length, + params = {id: hasThumb ? $thumb.attr('id') : '', index: fm.getIndex(id), fileId: id}, tokens, + skipErrorsAndProceed = self.resumableUploadOptions.skipErrorsAndProceed; + rm.completed = true; + rm.lastProgress = 0; + if (hasThumb) { + $thumb.removeClass('file-uploading'); + } + if (status === 'success') { + fm.uploadedSize += rm.file.size; + if (self.showPreview) { + self._setProgress(101, $prog); + self._setThumbStatus($thumb, 'Success'); + self._initUploadSuccess(rm.chunksProcessed[id].data, $thumb); + } + fm.removeFile(id); + delete rm.chunksProcessed[id]; + self._raise('fileuploaded', [params.id, params.index, params.fileId]); + if (fm.isProcessed()) { + self._setProgress(101); + } + } else { + if (status !== 'cancel') { + if (self.showPreview) { + self._setThumbStatus($thumb, 'Error'); + self._setPreviewError($thumb, true); + self._setProgress(101, $prog, self.msgProgressError); + self._setProgress(101, self.$progress, self.msgProgressError); + self.cancelling = !skipErrorsAndProceed; + } + if (!self.$errorContainer.find('li[data-file-id="' + params.fileId + '"]').length) { + tokens = {file: rm.fileName, max: opts.maxRetries, error: rm.error}; + msg = self.msgResumableUploadRetriesExceeded.setTokens(tokens); + $.extend(params, tokens); + self._showFileError(msg, params, 'filemaxretries'); + if (skipErrorsAndProceed) { + fm.removeFile(id); + delete rm.chunksProcessed[id]; + if (fm.isProcessed()) { + self._setProgress(101); + } + } + } + } + } + if (fm.isProcessed()) { + rm.reset(); + } + }, + check: function () { + var status = true; + $.each(rm.logs, function (index, value) { + if (!value) { + status = false; + return false; + } + }); + }, + processedResumables: function () { + var logs = rm.logs, i, count = 0; + if (!logs || !logs.length) { + return 0; + } + for (i = 0; i < logs.length; i++) { + if (logs[i] === true) { + count++; + } + } + return count; + }, + getUploadedSize: function () { + var size = rm.processedResumables() * rm.chunkSize; + return size > rm.file.size ? rm.file.size : size; + }, + getTotalChunks: function () { + var chunkSize = parseFloat(rm.chunkSize); + if (!isNaN(chunkSize) && chunkSize > 0) { + return Math.ceil(rm.file.size / chunkSize); + } + return 0; + }, + getProgress: function () { + var chunksProcessed = rm.processedResumables(), total = rm.chunkCount; + if (total === 0) { + return 0; + } + return Math.ceil(chunksProcessed / total * 100); + }, + checkAborted: function (intervalId) { + if (self._isAborted()) { + clearInterval(intervalId); + self.unlock(); + } + }, + upload: function () { + var ids = fm.getIdList(), flag = 'new', intervalId; + intervalId = setInterval(function () { + var id; + rm.checkAborted(intervalId); + if (flag === 'new') { + self.lock(); + flag = 'processing'; + id = ids.shift(); + fm.initStats(id); + if (fm.stack[id]) { + rm.init(id, fm.stack[id], fm.getIndex(id)); + rm.processUpload(); + } + } + if (!fm.isPending(id) && rm.completed) { + flag = 'new'; + } + if (fm.isProcessed()) { + var $initThumbs = self.$preview.find('.file-preview-initial'); + if ($initThumbs.length) { + $h.addCss($initThumbs, $h.SORT_CSS); + self._initSortable(); + } + clearInterval(intervalId); + self._clearFileInput(); + self.unlock(); + setTimeout(function () { + var data = self.previewCache.data; + if (data) { + self.initialPreview = data.content; + self.initialPreviewConfig = data.config; + self.initialPreviewThumbTags = data.tags; + } + self._raise('filebatchuploadcomplete', [ + self.initialPreview, + self.initialPreviewConfig, + self.initialPreviewThumbTags, + self._getExtraData() + ]); + }, self.processDelay); + } + }, self.processDelay); + }, + uploadResumable: function () { + var i, pool, tm = self.taskManager, total = rm.chunkCount; + pool = tm.addPool(rm.id); + for (i = 0; i < total; i++) { + rm.logs[i] = !!(rm.chunksProcessed[rm.id] && rm.chunksProcessed[rm.id][i]); + if (!rm.logs[i]) { + rm.pushAjax(i, 0); + } + } + pool.run(opts.maxThreads) + .done(function () { + rm.setProcessed('success'); + }) + .fail(function () { + rm.setProcessed(pool.cancelled ? 'cancel' : 'error'); + }); + }, + processUpload: function () { + var fd, f, id = rm.id, fnBefore, fnSuccess, fnError, fnComplete, outData; + if (!opts.testUrl) { + rm.uploadResumable(); + return; + } + fd = new FormData(); + f = fm.stack[id]; + self._setUploadData(fd, { + fileId: id, + fileName: f.fileName, + fileSize: f.size, + fileRelativePath: f.relativePath, + chunkSize: rm.chunkSize, + chunkCount: rm.chunkCount + }); + fnBefore = function (jqXHR) { + outData = self._getOutData(fd, jqXHR); + self._raise('filetestbeforesend', [id, fm, rm, outData]); + }; + fnSuccess = function (data, textStatus, jqXHR) { + outData = self._getOutData(fd, jqXHR, data); + var pNames = self.uploadParamNames, chunksUploaded = pNames.chunksUploaded || 'chunksUploaded', + params = [id, fm, rm, outData]; + if (!data[chunksUploaded] || !$h.isArray(data[chunksUploaded])) { + self._raise('filetesterror', params); + } else { + if (!rm.chunksProcessed[id]) { + rm.chunksProcessed[id] = {}; + } + $.each(data[chunksUploaded], function (key, index) { + rm.logs[index] = true; + rm.chunksProcessed[id][index] = true; + }); + rm.chunksProcessed[id].data = data; + self._raise('filetestsuccess', params); + } + rm.uploadResumable(); + }; + fnError = function (jqXHR, textStatus, errorThrown) { + outData = self._getOutData(fd, jqXHR); + self._raise('filetestajaxerror', [id, fm, rm, outData]); + rm.setAjaxError(jqXHR, textStatus, errorThrown, true); + rm.uploadResumable(); + }; + fnComplete = function () { + self._raise('filetestcomplete', [id, fm, rm, self._getOutData(fd)]); + }; + self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, fd, id, rm.fileIndex, opts.testUrl); + }, + pushAjax: function (index, retry) { + var tm = self.taskManager, pool = tm.getPool(rm.id); + pool.addTask(pool.size() + 1, function (deferrer) { + // use fifo chunk stack + var arr = rm.stack.shift(), index; + index = arr[0]; + if (!rm.chunksProcessed[rm.id] || !rm.chunksProcessed[rm.id][index]) { + rm.sendAjax(index, arr[1], deferrer); + } else { + self._log(logs.chunkQueueError, {index: index}); + } + }); + rm.stack.push([index, retry]); + }, + sendAjax: function (index, retry, deferrer) { + var f, chunkSize = rm.chunkSize, id = rm.id, file = rm.file, $thumb = rm.$thumb, + msgs = $h.logMessages, $btnDelete = rm.$btnDelete, logError = function (msg, tokens) { + if (tokens) { + msg = msg.setTokens(tokens); + } + msg = msgs.resumableRequestError.setTokens({msg: msg}); + self._log(msg); + deferrer.reject(msg); + }; + if (rm.chunksProcessed[id] && rm.chunksProcessed[id][index]) { + return; + } + if (retry > opts.maxRetries) { + logError(msgs.resumableMaxRetriesReached, {n: opts.maxRetries}); + rm.setProcessed('error'); + return; + } + var fd, outData, fnBefore, fnSuccess, fnError, fnComplete, slice = file.slice ? 'slice' : + (file.mozSlice ? 'mozSlice' : (file.webkitSlice ? 'webkitSlice' : 'slice')), + blob = file[slice](chunkSize * index, chunkSize * (index + 1)); + fd = new FormData(); + f = fm.stack[id]; + self._setUploadData(fd, { + chunkCount: rm.chunkCount, + chunkIndex: index, + chunkSize: chunkSize, + chunkSizeStart: chunkSize * index, + fileBlob: [blob, rm.fileName], + fileId: id, + fileName: rm.fileName, + fileRelativePath: f.relativePath, + fileSize: file.size, + retryCount: retry + }); + if (rm.$progress && rm.$progress.length) { + rm.$progress.show(); + } + fnBefore = function (jqXHR) { + outData = self._getOutData(fd, jqXHR); + if (self.showPreview) { + if (!$thumb.hasClass('file-preview-success')) { + self._setThumbStatus($thumb, 'Loading'); + $h.addCss($thumb, 'file-uploading'); + } + $btnDelete.attr('disabled', true); + } + self._raise('filechunkbeforesend', [id, index, retry, fm, rm, outData]); + }; + fnSuccess = function (data, textStatus, jqXHR) { + if (self._isAborted()) { + logError(msgs.resumableAborting); + return; + } + outData = self._getOutData(fd, jqXHR, data); + var paramNames = self.uploadParamNames, chunkIndex = paramNames.chunkIndex || 'chunkIndex', + params = [id, index, retry, fm, rm, outData]; + if (data.error) { + if (opts.showErrorLog) { + self._log(logs.retryStatus, { + retry: retry + 1, + filename: rm.fileName, + chunk: index + }); + } + self._raise('filechunkerror', params); + rm.pushAjax(index, retry + 1); + rm.error = data.error; + logError(data.error); + } else { + rm.logs[data[chunkIndex]] = true; + if (!rm.chunksProcessed[id]) { + rm.chunksProcessed[id] = {}; + } + rm.chunksProcessed[id][data[chunkIndex]] = true; + rm.chunksProcessed[id].data = data; + deferrer.resolve.call(null, data); + self._raise('filechunksuccess', params); + rm.check(); + } + }; + fnError = function (jqXHR, textStatus, errorThrown) { + if (self._isAborted()) { + logError(msgs.resumableAborting); + return; + } + outData = self._getOutData(fd, jqXHR); + rm.setAjaxError(jqXHR, textStatus, errorThrown); + self._raise('filechunkajaxerror', [id, index, retry, fm, rm, outData]); + rm.pushAjax(index, retry + 1); // push another task + logError(msgs.resumableRetryError, {n: retry - 1}); // resolve the current task + }; + fnComplete = function () { + if (!self._isAborted()) { + self._raise('filechunkcomplete', [id, index, retry, fm, rm, self._getOutData(fd)]); + } + }; + self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, fd, id, rm.fileIndex); + } + }; + rm.reset(); + }, + _initTemplateDefaults: function () { + var self = this, tMain1, tMain2, tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse, + tModalMain, tModal, tProgress, tSize, tFooter, tActions, tActionDelete, tActionUpload, tActionDownload, + tActionZoom, tActionDrag, tIndicator, tTagBef, tTagBef1, tTagBef2, tTagAft, tGeneric, tHtml, tImage, + tText, tOffice, tGdocs, tVideo, tAudio, tFlash, tObject, tPdf, tOther, tStyle, tZoomCache, vDefaultDim, + tStats, tModalLabel, tDescClose, renderObject = function (type, mime) { + return '\n' + $h.DEFAULT_PREVIEW + '\n\n'; + }, defBtnCss1 = 'btn btn-sm btn-kv ' + $h.defaultButtonCss(); + tMain1 = '{preview}\n' + + '
    \n' + + '
    \n' + + '
    \n' + + ' {caption}\n\n' + + ($h.isBs(5) ? '' : '
    \n') + + ' {remove}\n' + + ' {cancel}\n' + + ' {pause}\n' + + ' {upload}\n' + + ' {browse}\n' + + ($h.isBs(5) ? '' : '
    \n') + + '
    ' + '
    '; + tMain2 = '{preview}\n
    \n
    \n' + + '{remove}\n{cancel}\n{upload}\n{browse}\n'; + tPreview = '
    \n' + + ' {close}' + + '
    \n' + + '
    \n' + + '
    \n' + + '
    \n' + + '
    \n' + + '
    \n' + + '
    '; + tClose = $h.closeButton('fileinput-remove'); + tFileIcon = ''; + // noinspection HtmlUnknownAttribute + tCaption = '\n'; + //noinspection HtmlUnknownAttribute + tBtnDefault = ''; + //noinspection HtmlUnknownTarget,HtmlUnknownAttribute + tBtnLink = '{icon} {label}'; + //noinspection HtmlUnknownAttribute + tBtnBrowse = '
    {icon} {label}
    '; + tModalLabel = $h.MODAL_ID + 'Label'; + tModalMain = ''; + tModal = '\n'; + tDescClose = ''; + tProgress = '
    \n' + + '
    \n' + + ' {status}\n' + + '
    \n' + + '
    {stats}'; + tStats = '
    ' + + '{pendingTime} ' + + '{uploadSpeed}' + + '
    '; + tSize = ' ({sizeText})'; + tFooter = ''; + tActions = '
    \n' + + ' \n' + + '
    \n' + + '{drag}\n' + + '
    '; + //noinspection HtmlUnknownAttribute + tActionDelete = '\n'; + tActionUpload = ''; + tActionDownload = '{downloadIcon}'; + tActionZoom = ''; + tActionDrag = '{dragIcon}'; + tIndicator = '
    {indicator}
    '; + tTagBef = '
    \n'; + tTagBef2 = tTagBef + ' title="{caption}">
    \n'; + tTagAft = '
    {footer}\n{zoomCache}
    \n'; + tGeneric = '{content}\n'; + tStyle = ' {style}'; + tHtml = renderObject('html', 'text/html'); + tText = renderObject('text', 'text/plain;charset=UTF-8'); + tPdf = renderObject('pdf', 'application/pdf'); + tImage = '{alt}\n'; + tOffice = ''; + tGdocs = ''; + tVideo = '\n'; + tAudio = '\n'; + tFlash = '\n'; + tObject = '\n' + '\n' + + $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW + '\n\n'; + tOther = '
    \n' + $h.DEFAULT_PREVIEW + '\n
    \n'; + tZoomCache = '
    {zoomContent}
    '; + vDefaultDim = {width: '100%', height: '100%', 'min-height': '480px'}; + if (self._isPdfRendered()) { + tPdf = self.pdfRendererTemplate.replace('{renderer}', self._encodeURI(self.pdfRendererUrl)); + } + self.defaults = { + layoutTemplates: { + main1: tMain1, + main2: tMain2, + preview: tPreview, + close: tClose, + fileIcon: tFileIcon, + caption: tCaption, + modalMain: tModalMain, + modal: tModal, + descriptionClose: tDescClose, + progress: tProgress, + stats: tStats, + size: tSize, + footer: tFooter, + indicator: tIndicator, + actions: tActions, + actionDelete: tActionDelete, + actionUpload: tActionUpload, + actionDownload: tActionDownload, + actionZoom: tActionZoom, + actionDrag: tActionDrag, + btnDefault: tBtnDefault, + btnLink: tBtnLink, + btnBrowse: tBtnBrowse, + zoomCache: tZoomCache + }, + previewMarkupTags: { + tagBefore1: tTagBef1, + tagBefore2: tTagBef2, + tagAfter: tTagAft + }, + previewContentTemplates: { + generic: tGeneric, + html: tHtml, + image: tImage, + text: tText, + office: tOffice, + gdocs: tGdocs, + video: tVideo, + audio: tAudio, + flash: tFlash, + object: tObject, + pdf: tPdf, + other: tOther + }, + allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'], + previewTemplates: {}, + previewSettings: { + image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'}, + html: {width: '213px', height: '160px'}, + text: {width: '213px', height: '160px'}, + office: {width: '213px', height: '160px'}, + gdocs: {width: '213px', height: '160px'}, + video: {width: '213px', height: '160px'}, + audio: {width: '100%', height: '30px'}, + flash: {width: '213px', height: '160px'}, + object: {width: '213px', height: '160px'}, + pdf: {width: '100%', height: '160px', 'position': 'relative'}, + other: {width: '213px', height: '160px'} + }, + previewSettingsSmall: { + image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'}, + html: {width: '100%', height: '160px'}, + text: {width: '100%', height: '160px'}, + office: {width: '100%', height: '160px'}, + gdocs: {width: '100%', height: '160px'}, + video: {width: '100%', height: 'auto'}, + audio: {width: '100%', height: '30px'}, + flash: {width: '100%', height: 'auto'}, + object: {width: '100%', height: 'auto'}, + pdf: {width: '100%', height: '160px'}, + other: {width: '100%', height: '160px'} + }, + previewZoomSettings: { + image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'}, + html: vDefaultDim, + text: vDefaultDim, + office: {width: '100%', height: '100%', 'max-width': '100%', 'min-height': '480px'}, + gdocs: {width: '100%', height: '100%', 'max-width': '100%', 'min-height': '480px'}, + video: {width: 'auto', height: '100%', 'max-width': '100%'}, + audio: {width: '100%', height: '30px'}, + flash: {width: 'auto', height: '480px'}, + object: {width: 'auto', height: '100%', 'max-width': '100%', 'min-height': '480px'}, + pdf: vDefaultDim, + other: {width: 'auto', height: '100%', 'min-height': '480px'} + }, + mimeTypeAliases: { + 'video/quicktime': 'video/mp4' + }, + fileTypeSettings: { + image: function (vType, vName) { + return ($h.compare(vType, 'image.*') && !$h.compare(vType, /(tiff?|wmf)$/i) || + $h.compare(vName, /\.(gif|png|jpe?g)$/i)); + }, + html: function (vType, vName) { + return $h.compare(vType, 'text/html') || $h.compare(vName, /\.(htm|html)$/i); + }, + office: function (vType, vName) { + return $h.compare(vType, /(word|excel|powerpoint|office)$/i) || + $h.compare(vName, /\.(docx?|xlsx?|pptx?|pps|potx?)$/i); + }, + gdocs: function (vType, vName) { + return $h.compare(vType, /(word|excel|powerpoint|office|iwork-pages|tiff?)$/i) || + $h.compare(vName, + /\.(docx?|xlsx?|pptx?|pps|potx?|rtf|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i); + }, + text: function (vType, vName) { + return $h.compare(vType, 'text.*') || $h.compare(vName, /\.(xml|javascript)$/i) || + $h.compare(vName, /\.(txt|md|nfo|ini|json|php|js|css)$/i); + }, + video: function (vType, vName) { + return $h.compare(vType, 'video.*') && ($h.compare(vType, /(ogg|mp4|mp?g|mov|webm|3gp)$/i) || + $h.compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i)); + }, + audio: function (vType, vName) { + return $h.compare(vType, 'audio.*') && ($h.compare(vName, /(ogg|mp3|mp?g|wav)$/i) || + $h.compare(vName, /\.(og?|mp3|mp?g|wav)$/i)); + }, + flash: function (vType, vName) { + return $h.compare(vType, 'application/x-shockwave-flash', true) || $h.compare(vName, + /\.(swf)$/i); + }, + pdf: function (vType, vName) { + return $h.compare(vType, 'application/pdf', true) || $h.compare(vName, /\.(pdf)$/i); + }, + object: function () { + return true; + }, + other: function () { + return true; + } + }, + fileActionSettings: { + showRemove: true, + showUpload: true, + showDownload: true, + showZoom: true, + showDrag: true, + removeIcon: '', + removeClass: defBtnCss1, + removeErrorClass: 'btn btn-sm btn-kv btn-danger', + removeTitle: 'Remove file', + uploadIcon: '', + uploadClass: defBtnCss1, + uploadTitle: 'Upload file', + uploadRetryIcon: '', + uploadRetryTitle: 'Retry upload', + downloadIcon: '', + downloadClass: defBtnCss1, + downloadTitle: 'Download file', + zoomIcon: '', + zoomClass: defBtnCss1, + zoomTitle: 'View Details', + dragIcon: '', + dragClass: 'text-primary', + dragTitle: 'Move / Rearrange', + dragSettings: {}, + indicatorNew: '', + indicatorSuccess: '', + indicatorError: '', + indicatorLoading: '', + indicatorPaused: '', + indicatorNewTitle: 'Not uploaded yet', + indicatorSuccessTitle: 'Uploaded', + indicatorErrorTitle: 'Upload Error', + indicatorLoadingTitle: 'Uploading …', + indicatorPausedTitle: 'Upload Paused' + } + }; + $.each(self.defaults, function (key, setting) { + if (key === 'allowedPreviewTypes') { + if (self.allowedPreviewTypes === undefined) { + self.allowedPreviewTypes = setting; + } + return; + } + self[key] = $.extend(true, {}, setting, self[key]); + }); + self._initPreviewTemplates(); + }, + _initPreviewTemplates: function () { + var self = this, tags = self.previewMarkupTags, tagBef, tagAft = tags.tagAfter; + $.each(self.previewContentTemplates, function (key, value) { + if ($h.isEmpty(self.previewTemplates[key])) { + tagBef = tags.tagBefore2; + if (key === 'generic' || key === 'image') { + tagBef = tags.tagBefore1; + } + if (self._isPdfRendered() && key === 'pdf') { + tagBef = tagBef.replace('kv-file-content', 'kv-file-content kv-pdf-rendered'); + } + self.previewTemplates[key] = tagBef + value + tagAft; + } + }); + }, + _initPreviewCache: function () { + var self = this; + self.previewCache = { + data: {}, + init: function () { + var content = self.initialPreview; + if (content.length > 0 && !$h.isArray(content)) { + content = content.split(self.initialPreviewDelimiter); + } + self.previewCache.data = { + content: content, + config: self.initialPreviewConfig, + tags: self.initialPreviewThumbTags + }; + }, + count: function (skipNull) { + if (!self.previewCache.data || !self.previewCache.data.content) { + return 0; + } + if (skipNull) { + var chk = self.previewCache.data.content.filter(function (n) { + return n !== null; + }); + return chk.length; + } + return self.previewCache.data.content.length; + }, + get: function (i, isDisabled) { + var ind = $h.INIT_FLAG + i, data = self.previewCache.data, config = data.config[i], + content = data.content[i], out, $tmp, cat, ftr, + fname, ftype, frameClass, asData = $h.ifSet('previewAsData', config, self.initialPreviewAsData), + a = config ? {title: config.title || null, alt: config.alt || null} : {title: null, alt: null}, + parseTemplate = function (cat, dat, fname, ftype, ftr, ind, fclass, t) { + var fc = ' file-preview-initial ' + $h.SORT_CSS + (fclass ? ' ' + fclass : ''), + id = self.previewInitId + '-' + ind, + fileId = config && config.fileId || id; + /** @namespace config.zoomData */ + return self._generatePreviewTemplate(cat, dat, fname, ftype, id, fileId, false, null, fc, + ftr, ind, t, a, config && config.zoomData || dat); + }; + if (!content || !content.length) { + return ''; + } + isDisabled = isDisabled === undefined ? true : isDisabled; + cat = $h.ifSet('type', config, self.initialPreviewFileType || 'generic'); + fname = $h.ifSet('filename', config, $h.ifSet('caption', config)); + ftype = $h.ifSet('filetype', config, cat); + ftr = self.previewCache.footer(i, isDisabled, (config && config.size || null)); + frameClass = $h.ifSet('frameClass', config); + if (asData) { + out = parseTemplate(cat, content, fname, ftype, ftr, ind, frameClass); + } else { + out = parseTemplate('generic', content, fname, ftype, ftr, ind, frameClass, cat) + .setTokens({'content': data.content[i]}); + } + if (data.tags.length && data.tags[i]) { + out = $h.replaceTags(out, data.tags[i]); + } + /** @namespace config.frameAttr */ + if (!$h.isEmpty(config) && !$h.isEmpty(config.frameAttr)) { + $tmp = $h.createElement(out); + $tmp.find('.file-preview-initial').attr(config.frameAttr); + out = $tmp.html(); + $tmp.remove(); + } + return out; + }, + clean: function (data) { + data.content = $h.cleanArray(data.content); + data.config = $h.cleanArray(data.config); + data.tags = $h.cleanArray(data.tags); + self.previewCache.data = data; + }, + add: function (content, config, tags, append) { + var data = self.previewCache.data, index; + if (!content || !content.length) { + return 0; + } + index = content.length - 1; + if (!$h.isArray(content)) { + content = content.split(self.initialPreviewDelimiter); + } + if (append && data.content) { + index = data.content.push(content[0]) - 1; + data.config[index] = config; + data.tags[index] = tags; + } else { + data.content = content; + data.config = config; + data.tags = tags; + } + self.previewCache.clean(data); + return index; + }, + set: function (content, config, tags, append) { + var data = self.previewCache.data, i, chk; + if (!content || !content.length) { + return; + } + if (!$h.isArray(content)) { + content = content.split(self.initialPreviewDelimiter); + } + chk = content.filter(function (n) { + return n !== null; + }); + if (!chk.length) { + return; + } + if (data.content === undefined) { + data.content = []; + } + if (data.config === undefined) { + data.config = []; + } + if (data.tags === undefined) { + data.tags = []; + } + if (append) { + for (i = 0; i < content.length; i++) { + if (content[i]) { + data.content.push(content[i]); + } + } + for (i = 0; i < config.length; i++) { + if (config[i]) { + data.config.push(config[i]); + } + } + for (i = 0; i < tags.length; i++) { + if (tags[i]) { + data.tags.push(tags[i]); + } + } + } else { + data.content = content; + data.config = config; + data.tags = tags; + } + self.previewCache.clean(data); + }, + unset: function (index) { + var chk = self.previewCache.count(), rev = self.reversePreviewOrder; + if (!chk) { + return; + } + if (chk === 1) { + self.previewCache.data.content = []; + self.previewCache.data.config = []; + self.previewCache.data.tags = []; + self.initialPreview = []; + self.initialPreviewConfig = []; + self.initialPreviewThumbTags = []; + return; + } + self.previewCache.data.content = $h.spliceArray(self.previewCache.data.content, index, rev); + self.previewCache.data.config = $h.spliceArray(self.previewCache.data.config, index, rev); + self.previewCache.data.tags = $h.spliceArray(self.previewCache.data.tags, index, rev); + var data = $.extend(true, {}, self.previewCache.data); + self.previewCache.clean(data); + }, + out: function () { + var html = '', caption, len = self.previewCache.count(), i, content; + if (len === 0) { + return {content: '', caption: ''}; + } + for (i = 0; i < len; i++) { + content = self.previewCache.get(i); + html = self.reversePreviewOrder ? (content + html) : (html + content); + } + caption = self._getMsgSelected(len); + return {content: html, caption: caption}; + }, + footer: function (i, isDisabled, size) { + var data = self.previewCache.data || {}; + if ($h.isEmpty(data.content)) { + return ''; + } + if ($h.isEmpty(data.config) || $h.isEmpty(data.config[i])) { + data.config[i] = {}; + } + isDisabled = isDisabled === undefined ? true : isDisabled; + var config = data.config[i], caption = $h.ifSet('caption', config), a, + width = $h.ifSet('width', config, 'auto'), url = $h.ifSet('url', config, false), + key = $h.ifSet('key', config, null), fileId = $h.ifSet('fileId', config, null), + fs = self.fileActionSettings, initPreviewShowDel = self.initialPreviewShowDelete || false, + downloadInitialUrl = !self.initialPreviewDownloadUrl ? '' : + self.initialPreviewDownloadUrl + '?key=' + key + (fileId ? '&fileId=' + fileId : ''), + dUrl = config.downloadUrl || downloadInitialUrl, + dFil = config.filename || config.caption || '', + initPreviewShowDwl = !!(dUrl), + sDel = $h.ifSet('showRemove', config, initPreviewShowDel), + sDwl = $h.ifSet('showDownload', config, $h.ifSet('showDownload', fs, initPreviewShowDwl)), + sZm = $h.ifSet('showZoom', config, $h.ifSet('showZoom', fs, true)), + sDrg = $h.ifSet('showDrag', config, $h.ifSet('showDrag', fs, true)), + dis = (url === false) && isDisabled; + sDwl = sDwl && config.downloadUrl !== false && !!dUrl; + a = self._renderFileActions(config, false, sDwl, sDel, sZm, sDrg, dis, url, key, true, dUrl, dFil); + return self._getLayoutTemplate('footer').setTokens({ + 'progress': self._renderThumbProgress(), + 'actions': a, + 'caption': caption, + 'size': self._getSize(size), + 'width': width, + 'indicator': '' + }); + } + }; + self.previewCache.init(); + }, + _isPdfRendered: function () { + var self = this, useLib = self.usePdfRenderer, + flag = typeof useLib === 'function' ? useLib() : !!useLib; + return flag && self.pdfRendererUrl; + }, + _handler: function ($el, event, callback) { + var self = this, ns = self.namespace, ev = event.split(' ').join(ns + ' ') + ns; + if (!$el || !$el.length) { + return; + } + $el.off(ev).on(ev, callback); + }, + _encodeURI: function (vUrl) { + var self = this; + return self.encodeUrl ? encodeURI(vUrl) : vUrl; + }, + _log: function (msg, tokens) { + var self = this, id = self.$element.attr('id'); + if (!self.showConsoleLogs) { + return; + } + if (id) { + msg = '"' + id + '": ' + msg; + } + msg = 'bootstrap-fileinput: ' + msg; + if (typeof tokens === 'object') { + msg = msg.setTokens(tokens); + } + if (window.console && typeof window.console.log !== 'undefined') { + window.console.log(msg); + } else { + window.alert(msg); + } + }, + _validate: function () { + var self = this, status = self.$element.attr('type') === 'file'; + if (!status) { + self._log($h.logMessages.badInputType); + } + return status; + }, + _errorsExist: function () { + var self = this, $err, $errList = self.$errorContainer.find('li'); + if ($errList.length) { + return true; + } + $err = $h.createElement(self.$errorContainer.html()); + $err.find('.kv-error-close').remove(); + $err.find('ul').remove(); + return !!$.trim($err.text()).length; + }, + _errorHandler: function (evt, caption) { + var self = this, err = evt.target.error, showError = function (msg) { + self._showError(msg.replace('{name}', caption)); + }; + /** @namespace err.NOT_FOUND_ERR */ + /** @namespace err.SECURITY_ERR */ + /** @namespace err.NOT_READABLE_ERR */ + if (err.code === err.NOT_FOUND_ERR) { + showError(self.msgFileNotFound); + } else { + if (err.code === err.SECURITY_ERR) { + showError(self.msgFileSecured); + } else { + if (err.code === err.NOT_READABLE_ERR) { + showError(self.msgFileNotReadable); + } else { + if (err.code === err.ABORT_ERR) { + showError(self.msgFilePreviewAborted); + } else { + showError(self.msgFilePreviewError); + } + } + } + } + }, + _addError: function (msg) { + var self = this, $error = self.$errorContainer; + if (msg && $error.length) { + $h.setHtml($error, self.errorCloseButton + msg); + self._handler($error.find('.kv-error-close'), 'click', function () { + setTimeout(function () { + if (self.showPreview && !self.getFrames().length) { + self.clear(); + } + $error.fadeOut('slow'); + }, self.processDelay); + }); + } + }, + _setValidationError: function (css) { + var self = this; + css = (css ? css + ' ' : '') + 'has-error'; + self.$container.removeClass(css).addClass('has-error'); + $h.addCss(self.$caption, 'is-invalid'); + }, + _resetErrors: function (fade) { + var self = this, $error = self.$errorContainer, history = self.resumableUploadOptions.retainErrorHistory; + if (self.isPersistentError || (self.enableResumableUpload && history)) { + return; + } + self.isError = false; + self.$container.removeClass('has-error'); + self.$caption.removeClass('is-invalid is-valid file-processing'); + $error.html(''); + if (fade) { + $error.fadeOut('slow'); + } else { + $error.hide(); + } + }, + _showFolderError: function (folders) { + var self = this, $error = self.$errorContainer, msg; + if (!folders) { + return; + } + if (!self.isAjaxUpload) { + self._clearFileInput(); + } + msg = self.msgFoldersNotAllowed.replace('{n}', folders); + self._addError(msg); + self._setValidationError(); + $error.fadeIn(self.fadeDelay); + self._raise('filefoldererror', [folders, msg]); + }, + _showFileError: function (msg, params, event) { + var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', + fId = params && params.fileId || '', e = params && params.id ? + '
  • ' + msg + '
  • ' : '
  • ' + msg + '
  • '; + + if ($error.find('ul').length === 0) { + self._addError('
      ' + e + '
    '); + } else { + $error.find('ul').append(e); + } + $error.fadeIn(self.fadeDelay); + self._raise(ev, [params, msg]); + self._setValidationError('file-input-new'); + return true; + }, + _showError: function (msg, params, event) { + var self = this, $error = self.$errorContainer, ev = event || 'fileerror'; + params = params || {}; + params.reader = self.reader; + self._addError(msg); + $error.fadeIn(self.fadeDelay); + self._raise(ev, [params, msg]); + if (!self.isAjaxUpload) { + self._clearFileInput(); + } + self._setValidationError('file-input-new'); + self.$btnUpload.attr('disabled', true); + return true; + }, + _noFilesError: function (params) { + var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle, + msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label), + $error = self.$errorContainer; + msg = '
  • ' + msg + '
  • '; + if ($error.find('ul').length === 0) { + self._addError('
      ' + msg + '
    '); + } else { + $error.find('ul').append(msg); + } + self.isError = true; + self._updateFileDetails(0); + $error.fadeIn(self.fadeDelay); + self._raise('fileerror', [params, msg]); + self._clearFileInput(); + self._setValidationError(); + }, + _parseError: function (operation, jqXHR, errorThrown, fileName) { + /** @namespace jqXHR.responseJSON */ + var self = this, errMsg = $.trim(errorThrown + ''), textPre, errText, text; + errText = jqXHR.responseJSON && jqXHR.responseJSON.error ? jqXHR.responseJSON.error.toString() : ''; + text = errText ? errText : jqXHR.responseText; + if (self.cancelling && self.msgUploadAborted) { + errMsg = self.msgUploadAborted; + } + if (self.showAjaxErrorDetails && text) { + if (errText) { + errMsg = $.trim(errText + ''); + } else { + text = $.trim(text.replace(/\n\s*\n/g, '\n')); + textPre = text.length ? '
    ' + text + '
    ' : ''; + errMsg += errMsg ? textPre : text; + } + } + if (!errMsg) { + errMsg = self.msgAjaxError.replace('{operation}', operation); + } + self.cancelling = false; + return fileName ? '' + fileName + ': ' + errMsg : errMsg; + }, + _parseFileType: function (type, name) { + var self = this, isValid, vType, cat, i, types = self.allowedPreviewTypes || []; + if (type === 'application/text-plain') { + return 'text'; + } + for (i = 0; i < types.length; i++) { + cat = types[i]; + isValid = self.fileTypeSettings[cat]; + vType = isValid(type, name) ? cat : ''; + if (!$h.isEmpty(vType)) { + return vType; + } + } + return 'other'; + }, + _getPreviewIcon: function (fname) { + var self = this, ext, out = null; + if (fname && fname.indexOf('.') > -1) { + ext = fname.split('.').pop(); + if (self.previewFileIconSettings) { + out = self.previewFileIconSettings[ext] || self.previewFileIconSettings[ext.toLowerCase()] || null; + } + if (self.previewFileExtSettings) { + $.each(self.previewFileExtSettings, function (key, func) { + if (self.previewFileIconSettings[key] && func(ext)) { + out = self.previewFileIconSettings[key]; + //noinspection UnnecessaryReturnStatementJS + return; + } + }); + } + } + return out || self.previewFileIcon; + }, + _parseFilePreviewIcon: function (content, fname) { + var self = this, icn = self._getPreviewIcon(fname), out = content; + if (out.indexOf('{previewFileIcon}') > -1) { + out = out.setTokens({'previewFileIconClass': self.previewFileIconClass, 'previewFileIcon': icn}); + } + return out; + }, + _raise: function (event, params) { + var self = this, e = $.Event(event); + if (params !== undefined) { + self.$element.trigger(e, params); + } else { + self.$element.trigger(e); + } + var out = e.result, isAborted = out === false; + if (e.isDefaultPrevented() || isAborted) { + return false; + } + if (e.type === 'filebatchpreupload' && (out || isAborted)) { + self.ajaxAborted = out; + return false; + } + switch (event) { + // ignore these events + case 'filebatchuploadcomplete': + case 'filebatchuploadsuccess': + case 'fileuploaded': + case 'fileclear': + case 'filecleared': + case 'filereset': + case 'fileerror': + case 'filefoldererror': + case 'fileuploaderror': + case 'filebatchuploaderror': + case 'filedeleteerror': + case 'filecustomerror': + case 'filesuccessremove': + break; + // receive data response via `filecustomerror` event` + default: + if (!self.ajaxAborted) { + self.ajaxAborted = out; + } + break; + } + return true; + }, + _listenFullScreen: function (isFullScreen) { + var self = this, $modal = self.$modal, $btnFull, $btnBord; + if (!$modal || !$modal.length) { + return; + } + $btnFull = $modal && $modal.find('.btn-kv-fullscreen'); + $btnBord = $modal && $modal.find('.btn-kv-borderless'); + if (!$btnFull.length || !$btnBord.length) { + return; + } + $btnFull.removeClass('active').attr('aria-pressed', 'false'); + $btnBord.removeClass('active').attr('aria-pressed', 'false'); + if (isFullScreen) { + $btnFull.addClass('active').attr('aria-pressed', 'true'); + } else { + $btnBord.addClass('active').attr('aria-pressed', 'true'); + } + if ($modal.hasClass('file-zoom-fullscreen')) { + self._maximizeZoomDialog(); + } else { + if (isFullScreen) { + self._maximizeZoomDialog(); + } else { + $btnBord.removeClass('active').attr('aria-pressed', 'false'); + } + } + }, + _listen: function () { + var self = this, $el = self.$element, $form = self.$form, $cont = self.$container, fullScreenEv; + self._handler($el, 'click', function (e) { + self._initFileSelected(); + if ($el.hasClass('file-no-browse')) { + if ($el.data('zoneClicked')) { + $el.data('zoneClicked', false); + } else { + e.preventDefault(); + } + } + }); + self._handler($el, 'change', $.proxy(self._change, self)); + self._handler(self.$caption, 'paste', $.proxy(self.paste, self)); + if (self.showBrowse) { + self._handler(self.$btnFile, 'click', $.proxy(self._browse, self)); + self._handler(self.$btnFile, 'keypress', function (e) { + var keycode = e.keyCode || e.which + if (keycode === 13) { + $el.trigger('click'); + self._browse(e); + } + }); + } + self._handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self)); + self._handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self)); + self._handler($cont.find('.fileinput-pause'), 'click', $.proxy(self.pause, self)); + self._initDragDrop(); + self._handler($form, 'reset', $.proxy(self.clear, self)); + if (!self.isAjaxUpload) { + self._handler($form, 'submit', $.proxy(self._submitForm, self)); + } + self._handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self)); + self._handler($(window), 'resize', function () { + self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight); + }); + fullScreenEv = 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange'; + self._handler($(document), fullScreenEv, function () { + self._listenFullScreen($h.checkFullScreen()); + }); + self.$caption.on('focus', function () { + self.$captionContainer.focus(); + }); + self._autoFitContent(); + self._initClickable(); + self._refreshPreview(); + }, + _autoFitContent: function () { + var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, + self = this, config = width < 400 ? (self.previewSettingsSmall || self.defaults.previewSettingsSmall) : + (self.previewSettings || self.defaults.previewSettings), sel; + $.each(config, function (cat, settings) { + sel = '.file-preview-frame .file-preview-' + cat; + self.$preview.find(sel + '.kv-preview-data,' + sel + ' .kv-preview-data').css(settings); + }); + }, + _scanDroppedItems: function (item, files, path) { + path = path || ''; + var self = this, i, dirReader, readDir, errorHandler = function (e) { + self._log($h.logMessages.badDroppedFiles); + self._log(e); + }; + if (item.isFile) { + item.file(function (file) { + if (path) { + file.newPath = path + file.name; + } + files.push(file); + }, errorHandler); + } else { + if (item.isDirectory) { + dirReader = item.createReader(); + readDir = function () { + dirReader.readEntries(function (entries) { + if (entries && entries.length > 0) { + for (i = 0; i < entries.length; i++) { + self._scanDroppedItems(entries[i], files, path + item.name + '/'); + } + // recursively call readDir() again, since browser can only handle first 100 entries. + readDir(); + } + return null; + }, errorHandler); + }; + readDir(); + } + } + + }, + _initDragDrop: function () { + var self = this, $zone = self.$dropZone; + if (self.dropZoneEnabled && self.showPreview) { + self._handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self)); + self._handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self)); + self._handler($zone, 'drop', $.proxy(self._zoneDrop, self)); + self._handler($(document), 'dragenter dragover drop', self._zoneDragDropInit); + } + }, + _zoneDragDropInit: function (e) { + e.stopPropagation(); + e.preventDefault(); + }, + _zoneDragEnter: function (e) { + var self = this, dt = e.originalEvent.dataTransfer, hasFiles = $.inArray('Files', dt.types) > -1; + self._zoneDragDropInit(e); + if (self.isDisabled || !hasFiles) { + dt.effectAllowed = 'none'; + dt.dropEffect = 'none'; + return; + } + dt.dropEffect = 'copy'; + if (self._raise('fileDragEnter', {'sourceEvent': e, 'files': dt.types.Files})) { + $h.addCss(self.$dropZone, 'file-highlighted'); + } + }, + _zoneDragLeave: function (e) { + var self = this; + self._zoneDragDropInit(e); + if (self.isDisabled) { + return; + } + if (self._raise('fileDragLeave', {'sourceEvent': e})) { + self.$dropZone.removeClass('file-highlighted'); + } + + }, + _dropFiles: function (e, files) { + var self = this, $el = self.$element; + if (!self.isAjaxUpload) { + self.changeTriggered = true; + $el.get(0).files = files; + setTimeout(function () { + self.changeTriggered = false; + $el.trigger('change' + self.namespace); + }, self.processDelay); + } else { + self._change(e, files); + } + self.$dropZone.removeClass('file-highlighted'); + }, + _zoneDrop: function (e) { + /** @namespace e.originalEvent.dataTransfer */ + var self = this, i, $el = self.$element, dt = e.originalEvent.dataTransfer, + files = dt.files, items = dt.items, folders = $h.getDragDropFolders(items); + e.preventDefault(); + if (self.isDisabled || $h.isEmpty(files)) { + return; + } + if (!self._raise('fileDragDrop', {'sourceEvent': e, 'files': files})) { + return; + } + if (folders > 0) { + if (!self.isAjaxUpload) { + self._showFolderError(folders); + return; + } + files = []; + for (i = 0; i < items.length; i++) { + var item = items[i].webkitGetAsEntry(); + if (item) { + self._scanDroppedItems(item, files); + } + } + setTimeout(function () { + self._dropFiles(e, files); + }, 500); + } else { + self._dropFiles(e, files); + } + }, + _uploadClick: function (e) { + var self = this, $btn = self.$container.find('.fileinput-upload'), $form, + isEnabled = !$btn.hasClass('disabled') && $h.isEmpty($btn.attr('disabled')); + if (e && e.isDefaultPrevented()) { + return; + } + if (!self.isAjaxUpload) { + if (isEnabled && $btn.attr('type') !== 'submit') { + $form = $btn.closest('form'); + // downgrade to normal form submit if possible + if ($form.length) { + $form.trigger('submit'); + } + e.preventDefault(); + } + return; + } + e.preventDefault(); + if (isEnabled) { + self.upload(); + } + }, + _submitForm: function () { + var self = this; + return self._isFileSelectionValid() && !self._abort({}); + }, + _clearPreview: function () { + var self = this, + $thumbs = self.showUploadedThumbs ? self.getFrames(':not(.file-preview-success)') : self.getFrames(); + $thumbs.each(function () { + var $thumb = $(this); + $thumb.remove(); + }); + if (!self.getFrames().length || !self.showPreview) { + self._resetUpload(); + } + self._validateDefaultPreview(); + }, + _initSortable: function () { + var self = this, $el = self.$preview, settings, selector = '.' + $h.SORT_CSS, $cont, $body = $('body'), + $html = $('html'), rev = self.reversePreviewOrder, Sortable = window.Sortable, beginGrab, endGrab; + if (!Sortable || $el.find(selector).length === 0) { + return; + } + $cont = $body.length ? $body : ($html.length ? $html : self.$container); + beginGrab = function () { + $cont.addClass('file-grabbing'); + }; + endGrab = function () { + $cont.removeClass('file-grabbing'); + }; + settings = { + handle: '.drag-handle-init', + dataIdAttr: 'data-fileid', + animation: 600, + draggable: selector, + scroll: false, + forceFallback: true, + onChoose: beginGrab, + onStart: beginGrab, + onUnchoose: endGrab, + onEnd: endGrab, + onSort: function (e) { + var oldIndex = e.oldIndex, newIndex = e.newIndex, i = 0, len = self.initialPreviewConfig.length, + exceedsLast = len > 0 && newIndex >= len, $item = $(e.item), $first; + if (exceedsLast) { + newIndex = len - 1; + } + self.initialPreview = $h.moveArray(self.initialPreview, oldIndex, newIndex, rev); + self.initialPreviewConfig = $h.moveArray(self.initialPreviewConfig, oldIndex, newIndex, rev); + self.previewCache.init(); + self.getFrames('.file-preview-initial').each(function () { + $(this).attr('data-fileindex', $h.INIT_FLAG + i); + i++; + }); + if (exceedsLast) { + $first = self.getFrames(':not(.file-preview-initial):first'); + if ($first.length) { + $item.slideUp(function () { + $item.insertBefore($first).slideDown(); + }); + } + } + self._raise('filesorted', { + previewId: $item.attr('id'), + 'oldIndex': oldIndex, + 'newIndex': newIndex, + stack: self.initialPreviewConfig + }); + }, + }; + $.extend(true, settings, self.fileActionSettings.dragSettings); + if (self.sortable) { + self.sortable.destroy(); + } + self.sortable = Sortable.create($el[0], settings); + }, + _setPreviewContent: function (content) { + var self = this; + $h.setHtml(self.$preview, content); + self._autoFitContent(); + }, + _initPreviewImageOrientations: function () { + var self = this, i = 0, canOrientImage = self.canOrientImage; + if (!self.autoOrientImageInitial && !canOrientImage) { + return; + } + self.getFrames('.file-preview-initial').each(function () { + var $thumb = $(this), $img, $zoomImg, id, config = self.initialPreviewConfig[i]; + /** @namespace config.exif */ + if (config && config.exif && config.exif.Orientation) { + id = $thumb.attr('id'); + $img = $thumb.find('>.kv-file-content img'); + $zoomImg = self._getZoom(id, ' >.kv-file-content img'); + if (canOrientImage) { + $img.css('image-orientation', (self.autoOrientImageInitial ? 'from-image' : 'none')); + } else { + self.setImageOrientation($img, $zoomImg, config.exif.Orientation, $thumb); + } + } + i++; + }); + }, + _initPreview: function (isInit) { + var self = this, cap = self.initialCaption || '', out; + if (!self.previewCache.count(true)) { + self._clearPreview(); + if (isInit) { + self._setCaption(cap); + } else { + self._initCaption(); + } + return; + } + out = self.previewCache.out(); + cap = isInit && self.initialCaption ? self.initialCaption : out.caption; + self._setPreviewContent(out.content); + self._setInitThumbAttr(); + self._setCaption(cap); + self._initSortable(); + if (!$h.isEmpty(out.content)) { + self.$container.removeClass('file-input-new'); + } + self._initPreviewImageOrientations(); + }, + _getZoomButton: function (type) { + var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type], + title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ', tag = $h.isBs(5) ? 'bs-' : '', + params = title + (type === 'close' ? ' data-' + tag + 'dismiss="modal" aria-hidden="true"' : ''); + if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') { + params += ' data-toggle="button" aria-pressed="false" autocomplete="off"'; + } + return ''; + }, + _getModalContent: function () { + var self = this; + return self._getLayoutTemplate('modal').setTokens({ + 'rtl': self.rtl ? ' kv-rtl' : '', + 'zoomFrameClass': self.frameClass, + 'prev': self._getZoomButton('prev'), + 'next': self._getZoomButton('next'), + 'toggleheader': self._getZoomButton('toggleheader'), + 'fullscreen': self._getZoomButton('fullscreen'), + 'borderless': self._getZoomButton('borderless'), + 'close': self._getZoomButton('close') + }); + }, + _listenModalEvent: function (event) { + var self = this, $modal = self.$modal, getParams = function (e) { + return { + sourceEvent: e, + previewId: $modal.data('previewId'), + modal: $modal + }; + }; + $modal.on(event + '.bs.modal', function (e) { + if (e.namespace !== 'bs.modal') { + return; + } + var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'); + if ($modal.data('fileinputPluginId') === self.$element.attr('id')) { + self._raise('filezoom' + event, getParams(e)); + } + if (event === 'shown') { + $btnBord.removeClass('active').attr('aria-pressed', 'false'); + $btnFull.removeClass('active').attr('aria-pressed', 'false'); + if ($modal.hasClass('file-zoom-fullscreen')) { + self._maximizeZoomDialog(); + if ($h.checkFullScreen()) { + $btnFull.addClass('active').attr('aria-pressed', 'true'); + } else { + $btnBord.addClass('active').attr('aria-pressed', 'true'); + } + } + } + }); + }, + _initZoom: function () { + var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID; + modalMain = self._setTabIndex('modal', modalMain); + if (!self.showPreview) { + return; + } + self.$modal = $(modalId); + if (!self.$modal || !self.$modal.length) { + $dialog = $h.createElement($h.cspBuffer.stash(modalMain)).insertAfter(self.$container); + self.$modal = $(modalId).insertBefore($dialog); + $h.cspBuffer.apply(self.$modal); + $dialog.remove(); + } + $h.initModal(self.$modal); + self.$modal.html($h.cspBuffer.stash(self._getModalContent())); + $h.cspBuffer.apply(self.$modal); + $.each($h.MODAL_EVENTS, function (key, event) { + self._listenModalEvent(event); + }); + }, + _initZoomButtons: function () { + var self = this, previewId = self.$modal.data('previewId') || '', $first, $last, + thumbs = self.getFrames().toArray(), len = thumbs.length, $prev = self.$modal.find('.btn-kv-prev'), + $next = self.$modal.find('.btn-kv-next'); + if (thumbs.length < 2) { + $prev.hide(); + $next.hide(); + return; + } else { + $prev.show(); + $next.show(); + } + if (!len) { + return; + } + $first = $(thumbs[0]); + $last = $(thumbs[len - 1]); + $prev.removeAttr('disabled'); + $next.removeAttr('disabled'); + if (self.reversePreviewOrder) { + [$prev, $next] = [$next, $prev]; // swap + } + if ($first.length && $first.attr('id') === previewId) { + $prev.attr('disabled', true); + } + if ($last.length && $last.attr('id') === previewId) { + $next.attr('disabled', true); + } + }, + _maximizeZoomDialog: function () { + var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'), + $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.kv-zoom-body'), + h = $(window).height(), diff = 0; + $modal.addClass('file-zoom-fullscreen'); + if ($head && $head.length) { + h -= $head.outerHeight(true); + } + if ($foot && $foot.length) { + h -= $foot.outerHeight(true); + } + if ($body && $body.length) { + diff = $body.outerHeight(true) - $body.height(); + h -= diff; + } + $modal.find('.kv-zoom-body').height(h); + }, + _resizeZoomDialog: function (fullScreen) { + var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-kv-fullscreen'), + $btnBord = $modal.find('.btn-kv-borderless'); + if ($modal.hasClass('file-zoom-fullscreen')) { + $h.toggleFullScreen(false); + if (!fullScreen) { + if (!$btnFull.hasClass('active')) { + $modal.removeClass('file-zoom-fullscreen'); + self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight); + } else { + $btnFull.removeClass('active').attr('aria-pressed', 'false'); + } + } else { + if (!$btnFull.hasClass('active')) { + $modal.removeClass('file-zoom-fullscreen'); + self._resizeZoomDialog(true); + if ($btnBord.hasClass('active')) { + $btnBord.removeClass('active').attr('aria-pressed', 'false'); + } + } + } + } else { + if (!fullScreen) { + self._maximizeZoomDialog(); + return; + } + $h.toggleFullScreen(true); + } + $modal.focus(); + }, + _setZoomContent: function ($frame, navigate) { + var self = this, $content, tmplt, body, title, $body, $dataEl, config, previewId = $frame.attr('id'), + $zoomPreview = self._getZoom(previewId), $modal = self.$modal, $tmp, desc, $desc, + $btnFull = $modal.find('.btn-kv-fullscreen'), $btnBord = $modal.find('.btn-kv-borderless'), cap, size, + $btnTogh = $modal.find('.btn-kv-toggleheader'), dir = navigate === 'prev' ? 'Left' : 'Right', + slideIn = 'slideIn' + dir, slideOut = 'slideOut' + dir, parsed, zoomData = $frame.data('zoom'); + if (zoomData) { + zoomData = decodeURIComponent(zoomData); + parsed = $zoomPreview.html().setTokens({zoomData: zoomData}); + $zoomPreview.html(parsed); + $frame.data('zoom', ''); + $zoomPreview.attr('data-zoom', zoomData); + } + tmplt = $zoomPreview.attr('data-template') || 'generic'; + $content = $zoomPreview.find('.kv-file-content'); + body = $content.length ? '\n' + $content.html() : ''; + cap = $frame.data('caption') || self.msgZoomModalHeading; + size = $frame.data('size') || ''; + desc = $frame.data('description') || ''; + $modal.find('.kv-zoom-caption').attr('title', cap).html(cap); + $modal.find('.kv-zoom-size').html(size); + $desc = $modal.find('.kv-zoom-description').hide(); + if (desc) { + if (self.showDescriptionClose) { + desc = self._getLayoutTemplate('descriptionClose').setTokens({ + closeIcon: self.previewZoomButtonIcons.close + }) + '' + desc; + } + $desc.show().html(desc); + if (self.showDescriptionClose) { + self._handler($modal.find('.kv-desc-hide'), 'click', function () { + $(this).parent().fadeOut('fast', function () { + $modal.focus(); + }); + }); + } + } + $body = $modal.find('.kv-zoom-body'); + $modal.removeClass('kv-single-content'); + if (navigate) { + $tmp = $body.addClass('file-thumb-loading').clone().insertAfter($body); + $h.setHtml($body, body).hide(); + $tmp.fadeOut('fast', function () { + $body.fadeIn('fast', function () { + $body.removeClass('file-thumb-loading'); + }); + $tmp.remove(); + }); + } else { + $h.setHtml($body, body); + } + config = self.previewZoomSettings[tmplt]; + if (config) { + $dataEl = $body.find('.kv-preview-data'); + $h.addCss($dataEl, 'file-zoom-detail'); + $.each(config, function (key, value) { + $dataEl.css(key, value); + if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) { + $dataEl.removeAttr(key); + } + }); + } + $modal.data('previewId', previewId); + self._handler($modal.find('.btn-kv-prev'), 'click', function () { + self._zoomSlideShow('prev', previewId); + }); + self._handler($modal.find('.btn-kv-next'), 'click', function () { + self._zoomSlideShow('next', previewId); + }); + self._handler($btnFull, 'click', function () { + self._resizeZoomDialog(true); + }); + self._handler($btnBord, 'click', function () { + self._resizeZoomDialog(false); + }); + self._handler($btnTogh, 'click', function () { + var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.floating-buttons'), + ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) { + var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight; + if ($modal.hasClass('file-zoom-fullscreen')) { + h = $body.outerHeight(true); + if (!height) { + h = h - $header.outerHeight(true); + } + } + $body.css('height', height ? h + height : h); + }; + if ($header.is(':visible')) { + ht = $header.outerHeight(true); + $header.slideUp('slow', function () { + $actions.find('.btn').appendTo($floatBar); + resize(ht); + }); + } else { + $floatBar.find('.btn').appendTo($actions); + $header.slideDown('slow', function () { + resize(); + }); + } + $modal.focus(); + }); + self._handler($modal, 'keydown', function (e) { + var key = e.which || e.keyCode, delay = self.processDelay + 1, $prev = $(this).find('.btn-kv-prev'), + $next = $(this).find('.btn-kv-next'), vId = $(this).data('previewId'), vPrevKey, vNextKey; + [vPrevKey, vNextKey] = self.rtl ? [39, 37] : [37, 39]; + $.each({prev: [$prev, vPrevKey], next: [$next, vNextKey]}, function (direction, config) { + var $btn = config[0], vKey = config[1]; + if (key === vKey && $btn.length) { + $modal.focus(); + if (!$btn.attr('disabled')) { + $btn.focus(); + self._zoomSlideShow(direction, vId); + setTimeout(function () { + if ($btn.attr('disabled')) { + $modal.focus(); + } + }, delay); + } + } + }); + }); + }, + _showModal: function ($frame) { + var self = this, $modal = self.$modal, bs5Modal; + if (!$frame || !$frame.length) { + return; + } + $h.initModal($modal); + $h.setHtml($modal, self._getModalContent()); + self._setZoomContent($frame); + $modal.data({backdrop: false}); + //$modal.data('fileinputPluginId', self.$element.attr('id')); + $modal.modal('show'); + self._initZoomButtons(); + }, + _zoomPreview: function ($btn) { + var self = this, $frame; + if (!$btn.length) { + throw 'Cannot zoom to detailed preview!'; + } + $frame = $btn.closest($h.FRAMES); + self._showModal($frame); + }, + _zoomSlideShow: function (dir, previewId) { + var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-kv-' + dir), $targFrame, i, $thumb, + thumbsData = self.getFrames().toArray(), thumbs = [], len = thumbsData.length, out; + if (self.reversePreviewOrder) { + dir = dir === 'prev' ? 'next' : 'prev'; + } + if ($btn.attr('disabled')) { + return; + } + for (i = 0; i < len; i++) { + $thumb = $(thumbsData[i]); + if ($thumb && $thumb.length && $thumb.find('.kv-file-zoom:visible').length) { + thumbs.push(thumbsData[i]); + } + } + len = thumbs.length; + for (i = 0; i < len; i++) { + if ($(thumbs[i]).attr('id') === previewId) { + out = dir === 'prev' ? i - 1 : i + 1; + break; + } + } + if (out < 0 || out >= len || !thumbs[out]) { + return; + } + $targFrame = $(thumbs[out]); + if ($targFrame.length) { + self._setZoomContent($targFrame, dir); + } + self._initZoomButtons(); + self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal}); + }, + _initZoomButton: function () { + var self = this; + self.$preview.find('.kv-file-zoom').each(function () { + var $el = $(this); + self._handler($el, 'click', function () { + self._zoomPreview($el); + }); + }); + }, + _inputFileCount: function () { + return this.$element[0].files.length; + }, + _refreshPreview: function () { + var self = this, files; + if ((!self._inputFileCount() && !self.isAjaxUpload) || !self.showPreview || !self.isPreviewable) { + return; + } + if (self.isAjaxUpload) { + if (self.fileManager.count() > 0) { + files = $.extend(true, {}, self.getFileList()); + self.fileManager.clear(); + self._clearFileInput(); + } else { + files = self.$element[0].files; + } + } else { + files = self.$element[0].files; + } + if (files && files.length) { + self.readFiles(files); + self._setFileDropZoneTitle(); + } + }, + _clearObjects: function ($el) { + $el.find('video audio').each(function () { + this.pause(); + $(this).remove(); + }); + $el.find('img object div').each(function () { + $(this).remove(); + }); + }, + _clearFileInput: function () { + var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl; + if (!self._inputFileCount()) { + return; + } + $srcFrm = $el.closest('form'); + $tmpFrm = $(document.createElement('form')); + $tmpEl = $(document.createElement('div')); + $el.before($tmpEl); + if ($srcFrm.length) { + $srcFrm.after($tmpFrm); + } else { + $tmpEl.after($tmpFrm); + } + $tmpFrm.append($el).trigger('reset'); + $tmpEl.before($el).remove(); + $tmpFrm.remove(); + }, + _resetUpload: function () { + var self = this; + self.uploadStartTime = $h.now(); + self.uploadCache = []; + self.$btnUpload.removeAttr('disabled'); + self._setProgress(0); + self._hideProgress(); + self._resetErrors(false); + self._initAjax(); + self.fileManager.clearImages(); + self._resetCanvas(); + if (self.overwriteInitial) { + self.initialPreview = []; + self.initialPreviewConfig = []; + self.initialPreviewThumbTags = []; + self.previewCache.data = { + content: [], + config: [], + tags: [] + }; + } + }, + _resetCanvas: function () { + var self = this; + if (self.imageCanvas && self.imageCanvasContext) { + self.imageCanvasContext.clearRect(0, 0, self.imageCanvas.width, self.imageCanvas.height); + } + }, + _hasInitialPreview: function () { + var self = this; + return !self.overwriteInitial && self.previewCache.count(true); + }, + _resetPreview: function () { + var self = this, out, cap, $div, hasSuc = self.showUploadedThumbs, hasErr = !self.removeFromPreviewOnError, + includeProcessed = (hasSuc || hasErr) && self.isDuplicateError; + if (self.previewCache.count(true)) { + out = self.previewCache.out(); + if (includeProcessed) { + $div = $h.createElement('').insertAfter(self.$container); + self.getFrames().each(function () { + var $thumb = $(this); + if ((hasSuc && $thumb.hasClass('file-preview-success')) || + (hasErr && $thumb.hasClass('file-preview-error'))) { + $div.append($thumb); + } + }); + } + self._setPreviewContent(out.content); + self._setInitThumbAttr(); + cap = self.initialCaption ? self.initialCaption : out.caption; + self._setCaption(cap); + if (includeProcessed) { + $div.contents().appendTo(self.$preview); + $div.remove(); + } + } else { + self._clearPreview(); + self._initCaption(); + } + if (self.showPreview) { + self._initZoom(); + self._initSortable(); + } + self.isDuplicateError = false; + }, + _clearDefaultPreview: function () { + var self = this; + self.$preview.find('.file-default-preview').remove(); + }, + _validateDefaultPreview: function () { + var self = this; + if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) { + return; + } + self._setPreviewContent('
    ' + self.defaultPreviewContent + '
    '); + self.$container.removeClass('file-input-new'); + self._initClickable(); + }, + _resetPreviewThumbs: function (isAjax) { + var self = this, out; + if (isAjax) { + self._clearPreview(); + self.clearFileStack(); + return; + } + if (self._hasInitialPreview()) { + out = self.previewCache.out(); + self._setPreviewContent(out.content); + self._setInitThumbAttr(); + self._setCaption(out.caption); + self._initPreviewActions(); + } else { + self._clearPreview(); + } + }, + _getLayoutTemplate: function (t) { + var self = this, template = self.layoutTemplates[t]; + if ($h.isEmpty(self.customLayoutTags)) { + return template; + } + return $h.replaceTags(template, self.customLayoutTags); + }, + _getPreviewTemplate: function (t) { + var self = this, templates = self.previewTemplates, template = templates[t] || templates.other; + if ($h.isEmpty(self.customPreviewTags)) { + return template; + } + return $h.replaceTags(template, self.customPreviewTags); + }, + _getOutData: function (formdata, jqXHR, responseData, filesData) { + var self = this; + jqXHR = jqXHR || {}; + responseData = responseData || {}; + filesData = filesData || self.fileManager.list(); + return { + formdata: formdata, + files: filesData, + filenames: self.filenames, + filescount: self.getFilesCount(), + extra: self._getExtraData(), + response: responseData, + reader: self.reader, + jqXHR: jqXHR + }; + }, + _getMsgSelected: function (n, processing) { + var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural; + return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : + (processing ? self.msgProcessing : self.msgNoFilesSelected); + }, + _getFrame: function (id, skipWarning) { + var self = this, $frame = $h.getFrameElement(self.$preview, id); + if (self.showPreview && !skipWarning && !$frame.length) { + self._log($h.logMessages.invalidThumb, {id: id}); + } + return $frame; + }, + _getZoom: function (id, selector) { + var self = this, $frame = $h.getZoomElement(self.$preview, id, selector); + if (self.showPreview && !$frame.length) { + self._log($h.logMessages.invalidThumb, {id: id}); + } + return $frame; + }, + _getThumbs: function (css) { + css = css || ''; + return this.getFrames(':not(.file-preview-initial)' + css); + }, + _getThumbId: function (fileId) { + var self = this; + return self.previewInitId + '-' + fileId; + }, + _getExtraData: function (fileId, index) { + var self = this, data = self.uploadExtraData; + if (typeof self.uploadExtraData === 'function') { + data = self.uploadExtraData(fileId, index); + } + return data; + }, + _initXhr: function (xhrobj, fileId) { + var self = this, fm = self.fileManager, func = function (event) { + var pct = 0, total = event.total, loaded = event.loaded || event.position, + stats = fm.getUploadStats(fileId, loaded, total); + /** @namespace event.lengthComputable */ + if (event.lengthComputable && !self.enableResumableUpload) { + pct = $h.round(loaded / total * 100); + } + if (fileId) { + self._setFileUploadStats(fileId, pct, stats); + } else { + self._setProgress(pct, null, null, self._getStats(stats)); + } + self._raise('fileajaxprogress', [stats]); + }; + if (xhrobj.upload) { + if (self.progressDelay) { + func = $h.debounce(func, self.progressDelay); + } + xhrobj.upload.addEventListener('progress', func, false); + } + return xhrobj; + }, + _initAjaxSettings: function () { + var self = this; + self._ajaxSettings = $.extend(true, {}, self.ajaxSettings); + self._ajaxDeleteSettings = $.extend(true, {}, self.ajaxDeleteSettings); + }, + _mergeAjaxCallback: function (funcName, srcFunc, type) { + var self = this, settings = self._ajaxSettings, flag = self.mergeAjaxCallbacks, targFunc; + if (type === 'delete') { + settings = self._ajaxDeleteSettings; + flag = self.mergeAjaxDeleteCallbacks; + } + targFunc = settings[funcName]; + if (flag && typeof targFunc === 'function') { + if (flag === 'before') { + settings[funcName] = function () { + targFunc.apply(this, arguments); + srcFunc.apply(this, arguments); + }; + } else { + settings[funcName] = function () { + srcFunc.apply(this, arguments); + targFunc.apply(this, arguments); + }; + } + } else { + settings[funcName] = srcFunc; + } + }, + _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, formdata, fileId, index, vUrl) { + var self = this, settings, defaults, data, ajaxTask; + if (!self._raise('filepreajax', [formdata, fileId, index])) { + return; + } + formdata.append('initialPreview', JSON.stringify(self.initialPreview)); + formdata.append('initialPreviewConfig', JSON.stringify(self.initialPreviewConfig)); + formdata.append('initialPreviewThumbTags', JSON.stringify(self.initialPreviewThumbTags)); + self._initAjaxSettings(); + self._mergeAjaxCallback('beforeSend', fnBefore); + self._mergeAjaxCallback('success', fnSuccess); + self._mergeAjaxCallback('complete', fnComplete); + self._mergeAjaxCallback('error', fnError); + vUrl = vUrl || self.uploadUrlThumb || self.uploadUrl; + if (typeof vUrl === 'function') { + vUrl = vUrl(); + } + data = self._getExtraData(fileId, index) || {}; + if (typeof data === 'object') { + $.each(data, function (key, value) { + formdata.append(key, value); + }); + } + defaults = { + xhr: function () { + var xhrobj = $.ajaxSettings.xhr(); + return self._initXhr(xhrobj, fileId); + }, + url: self._encodeURI(vUrl), + type: 'POST', + dataType: 'json', + data: formdata, + cache: false, + processData: false, + contentType: false + }; + settings = $.extend(true, {}, defaults, self._ajaxSettings); + ajaxTask = self.taskManager.addTask(fileId + '-' + index, function () { + var self = this.self, config, xhr; + config = self.ajaxQueue.shift(); + xhr = $.ajax(config); + self.ajaxRequests.push(xhr); + }); + self.ajaxQueue.push(settings); + ajaxTask.runWithContext({self: self}); + }, + _mergeArray: function (prop, content) { + var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content); + self[prop] = arr1.concat(arr2); + }, + _initUploadSuccess: function (out, $thumb, allFiles) { + var self = this, append, data, index, $div, content, config, tags, id, i; + if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) { + self._resetCaption(); + return; + } + if (out.initialPreview !== undefined && out.initialPreview.length > 0) { + self.hasInitData = true; + content = out.initialPreview || []; + config = out.initialPreviewConfig || []; + tags = out.initialPreviewThumbTags || []; + append = out.append === undefined || out.append; + if (content.length > 0 && !$h.isArray(content)) { + content = content.split(self.initialPreviewDelimiter); + } + if (content.length) { + self._mergeArray('initialPreview', content); + self._mergeArray('initialPreviewConfig', config); + self._mergeArray('initialPreviewThumbTags', tags); + } + if ($thumb !== undefined) { + if (!allFiles) { + index = self.previewCache.add(content[0], config[0], tags[0], append); + data = self.previewCache.get(index, false); + $div = $h.createElement(data).hide().appendTo($thumb); + $thumb.fadeOut('slow', function () { + var $newThumb = $div.find('> .file-preview-frame'); + if ($newThumb && $newThumb.length) { + $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block'); + } + self._initPreviewActions(); + self._clearFileInput(); + $thumb.remove(); + $div.remove(); + self._initSortable(); + }); + } else { + id = $thumb.attr('id'); + i = self._getUploadCacheIndex(id); + if (i !== null) { + self.uploadCache[i] = { + id: id, + content: content[0], + config: config[0] || [], + tags: tags[0] || [], + append: append + }; + } + } + } else { + self.previewCache.set(content, config, tags, append); + self._initPreview(); + self._initPreviewActions(); + } + } + self._resetCaption(); + }, + _getUploadCacheIndex: function (id) { + var self = this, i, len = self.uploadCache.length, config; + for (i = 0; i < len; i++) { + config = self.uploadCache[i]; + if (config.id === id) { + return i; + } + } + return null; + }, + _initSuccessThumbs: function () { + var self = this; + if (!self.showPreview) { + return; + } + setTimeout(function () { + self._getThumbs($h.FRAMES + '.file-preview-success').each(function () { + var $thumb = $(this), $remove = $thumb.find('.kv-file-remove'); + $remove.removeAttr('disabled'); + self._handler($remove, 'click', function () { + var id = $thumb.attr('id'), + out = self._raise('filesuccessremove', [id, $thumb.attr('data-fileindex')]); + $h.cleanMemory($thumb); + if (out === false) { + return; + } + self.$caption.attr('title', ''); + $thumb.fadeOut('slow', function () { + var fm = self.fileManager; + $thumb.remove(); + if (!self.getFrames().length) { + self.reset(); + } + }); + }); + }); + }, self.processDelay); + }, + _updateInitialPreview: function () { + var self = this, u = self.uploadCache; + if (self.showPreview) { + $.each(u, function (key, setting) { + self.previewCache.add(setting.content, setting.config, setting.tags, setting.append); + }); + if (self.hasInitData) { + self._initPreview(); + self._initPreviewActions(); + } + } + }, + _getThumbFileId: function ($thumb) { + var self = this; + if (self.showPreview && $thumb !== undefined) { + return $thumb.attr('data-fileid'); + } + return null; + }, + _getThumbFile: function ($thumb) { + var self = this, id = self._getThumbFileId($thumb); + return id ? self.fileManager.getFile(id) : null; + }, + _uploadSingle: function (i, id, isBatch) { + var self = this, fm = self.fileManager, count = fm.count(), formdata = new FormData(), outData, + previewId = self._getThumbId(id), $thumb, chkComplete, $btnUpload, $btnDelete, + hasPostData = count > 0 || !$.isEmptyObject(self.uploadExtraData), uploadFailed, $prog, fnBefore, + errMsg, fnSuccess, fnComplete, fnError, updateUploadLog, op = self.ajaxOperations.uploadThumb, + fileObj = fm.getFile(id), params = {id: previewId, index: i, fileId: id}, + fileName = self.fileManager.getFileName(id, true); + if (self.enableResumableUpload) { // not enabled for resumable uploads + return; + } + if (self.showPreview) { + $thumb = fm.getThumb(id); + $prog = $thumb.find('.file-thumb-progress'); + $btnUpload = $thumb.find('.kv-file-upload'); + $btnDelete = $thumb.find('.kv-file-remove'); + $prog.show(); + } + if (count === 0 || !hasPostData || (self.showPreview && $btnUpload && $btnUpload.hasClass('disabled')) || + self._abort(params)) { + return; + } + updateUploadLog = function () { + if (!uploadFailed) { + fm.removeFile(id); + } else { + fm.errors.push(id); + } + fm.setProcessed(id); + if (fm.isProcessed()) { + self.fileBatchCompleted = true; + chkComplete(); + } + }; + chkComplete = function () { + var $initThumbs; + if (!self.fileBatchCompleted) { + return; + } + setTimeout(function () { + var triggerReset = fm.count() === 0, errCount = fm.errors.length; + self._updateInitialPreview(); + self.unlock(triggerReset); + if (triggerReset) { + self._clearFileInput(); + } + $initThumbs = self.$preview.find('.file-preview-initial'); + if (self.uploadAsync && $initThumbs.length) { + $h.addCss($initThumbs, $h.SORT_CSS); + self._initSortable(); + } + self._raise('filebatchuploadcomplete', [fm.stack, self._getExtraData()]); + if (!self.retryErrorUploads || errCount === 0) { + fm.clear(); + } + self._setProgress(101); + self.ajaxAborted = false; + }, self.processDelay); + }; + fnBefore = function (jqXHR) { + outData = self._getOutData(formdata, jqXHR); + fm.initStats(id); + self.fileBatchCompleted = false; + if (!isBatch) { + self.ajaxAborted = false; + } + if (self.showPreview) { + if (!$thumb.hasClass('file-preview-success')) { + self._setThumbStatus($thumb, 'Loading'); + $h.addCss($thumb, 'file-uploading'); + } + $btnUpload.attr('disabled', true); + $btnDelete.attr('disabled', true); + } + if (!isBatch) { + self.lock(); + } + if (fm.errors.indexOf(id) !== -1) { + delete fm.errors[id]; + } + self._raise('filepreupload', [outData, previewId, i, self._getThumbFileId($thumb)]); + $.extend(true, params, outData); + if (self._abort(params)) { + jqXHR.abort(); + if (!isBatch) { + self._setThumbStatus($thumb, 'New'); + $thumb.removeClass('file-uploading'); + $btnUpload.removeAttr('disabled'); + $btnDelete.removeAttr('disabled'); + } + self._setProgressCancelled(); + } + }; + fnSuccess = function (data, textStatus, jqXHR) { + var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId; + outData = self._getOutData(formdata, jqXHR, data); + $.extend(true, params, outData); + setTimeout(function () { + if ($h.isEmpty(data) || $h.isEmpty(data.error)) { + if (self.showPreview) { + self._setThumbStatus($thumb, 'Success'); + $btnUpload.hide(); + self._initUploadSuccess(data, $thumb, isBatch); + self._setProgress(101, $prog); + } + self._raise('fileuploaded', [outData, pid, i, self._getThumbFileId($thumb)]); + if (!isBatch) { + self.fileManager.remove($thumb); + } else { + updateUploadLog(); + } + } else { + uploadFailed = true; + errMsg = self._parseError(op, jqXHR, self.msgUploadError, self.fileManager.getFileName(id)); + self._showFileError(errMsg, params); + self._setPreviewError($thumb, true); + if (!self.retryErrorUploads) { + $btnUpload.hide(); + } + if (isBatch) { + updateUploadLog(); + } + self._setProgress(101, self._getFrame(pid).find('.file-thumb-progress'), + self.msgUploadError); + } + }, self.processDelay); + }; + fnComplete = function () { + if (self.showPreview) { + $btnUpload.removeAttr('disabled'); + $btnDelete.removeAttr('disabled'); + $thumb.removeClass('file-uploading'); + } + if (!isBatch) { + self.unlock(false); + self._clearFileInput(); + } else { + chkComplete(); + } + self._initSuccessThumbs(); + }; + fnError = function (jqXHR, textStatus, errorThrown) { + errMsg = self._parseError(op, jqXHR, errorThrown, self.fileManager.getFileName(id)); + uploadFailed = true; + setTimeout(function () { + var $prog; + if (isBatch) { + updateUploadLog(); + } + self.fileManager.setProgress(id, 100); + self._setPreviewError($thumb, true); + if (!self.retryErrorUploads) { + $btnUpload.hide(); + } + $.extend(true, params, self._getOutData(formdata, jqXHR)); + self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op)); + $prog = self.showPreview && $thumb ? $thumb.find('.file-thumb-progress') : ''; + self._setProgress(101, $prog, self.msgUploadError); + self._showFileError(errMsg, params); + }, self.processDelay); + }; + self._setFileData(formdata, fileObj.file, fileName, id); + self._setUploadData(formdata, {fileId: id}); + self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata, id, i); + }, + _setFileData: function (formdata, file, fileName, fileId) { + var self = this, preProcess = self.preProcessUpload; + if (preProcess && typeof preProcess === 'function') { + formdata.append(self.uploadFileAttr, preProcess(fileId, file)); + } else { + formdata.append(self.uploadFileAttr, file, fileName); + } + }, + _checkBatchPreupload: function (outData, jqXHR) { + var self = this, out = self._raise('filebatchpreupload', [outData]); + if (out) { + return true; + } + self._abort(outData); + if (jqXHR) { + jqXHR.abort(); + } + self._getThumbs().each(function () { + var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), + $btnDelete = $thumb.find('.kv-file-remove'); + if ($thumb.hasClass('file-preview-loading')) { + self._setThumbStatus($thumb, 'New'); + $thumb.removeClass('file-uploading'); + } + $btnUpload.removeAttr('disabled'); + $btnDelete.removeAttr('disabled'); + }); + self._setProgressCancelled(); + return false; + }, + _uploadBatch: function () { + var self = this, fm = self.fileManager, total = fm.total(), params = {}, fnBefore, fnSuccess, fnError, + fnComplete, hasPostData = total > 0 || !$.isEmptyObject(self.uploadExtraData), errMsg, + setAllUploaded, formdata = new FormData(), op = self.ajaxOperations.uploadBatch; + if (total === 0 || !hasPostData || self._abort(params)) { + return; + } + setAllUploaded = function () { + self.fileManager.clear(); + self._clearFileInput(); + }; + fnBefore = function (jqXHR) { + self.lock(); + fm.initStats(); + var outData = self._getOutData(formdata, jqXHR); + self.ajaxAborted = false; + if (self.showPreview) { + self._getThumbs().each(function () { + var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), + $btnDelete = $thumb.find('.kv-file-remove'); + if (!$thumb.hasClass('file-preview-success')) { + self._setThumbStatus($thumb, 'Loading'); + $h.addCss($thumb, 'file-uploading'); + } + $btnUpload.attr('disabled', true); + $btnDelete.attr('disabled', true); + }); + } + self._checkBatchPreupload(outData, jqXHR); + }; + fnSuccess = function (data, textStatus, jqXHR) { + /** @namespace data.errorkeys */ + var outData = self._getOutData(formdata, jqXHR, data), key = 0, + $thumbs = self._getThumbs(':not(.file-preview-success)'), + keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys; + + if ($h.isEmpty(data) || $h.isEmpty(data.error)) { + self._raise('filebatchuploadsuccess', [outData]); + setAllUploaded(); + if (self.showPreview) { + $thumbs.each(function () { + var $thumb = $(this); + self._setThumbStatus($thumb, 'Success'); + $thumb.removeClass('file-uploading'); + $thumb.find('.kv-file-upload').hide().removeAttr('disabled'); + }); + self._initUploadSuccess(data); + } else { + self.reset(); + } + self._setProgress(101); + } else { + if (self.showPreview) { + $thumbs.each(function () { + var $thumb = $(this); + $thumb.removeClass('file-uploading'); + $thumb.find('.kv-file-upload').removeAttr('disabled'); + $thumb.find('.kv-file-remove').removeAttr('disabled'); + if (keys.length === 0 || $.inArray(key, keys) !== -1) { + self._setPreviewError($thumb, true); + if (!self.retryErrorUploads) { + $thumb.find('.kv-file-upload').hide(); + self.fileManager.remove($thumb); + } + } else { + $thumb.find('.kv-file-upload').hide(); + self._setThumbStatus($thumb, 'Success'); + self.fileManager.remove($thumb); + } + if (!$thumb.hasClass('file-preview-error') || self.retryErrorUploads) { + key++; + } + }); + self._initUploadSuccess(data); + } + errMsg = self._parseError(op, jqXHR, self.msgUploadError); + self._showFileError(errMsg, outData, 'filebatchuploaderror'); + self._setProgress(101, self.$progress, self.msgUploadError); + } + }; + fnComplete = function () { + self.unlock(); + self._initSuccessThumbs(); + self._clearFileInput(); + self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]); + }; + fnError = function (jqXHR, textStatus, errorThrown) { + var outData = self._getOutData(formdata, jqXHR); + errMsg = self._parseError(op, jqXHR, errorThrown); + self._showFileError(errMsg, outData, 'filebatchuploaderror'); + self.uploadFileCount = total - 1; + if (!self.showPreview) { + return; + } + self._getThumbs().each(function () { + var $thumb = $(this); + $thumb.removeClass('file-uploading'); + if (self._getThumbFile($thumb)) { + self._setPreviewError($thumb); + } + }); + self._getThumbs().removeClass('file-uploading'); + self._getThumbs(' .kv-file-upload').removeAttr('disabled'); + self._getThumbs(' .kv-file-delete').removeAttr('disabled'); + self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op)); + }; + var ctr = 0; + $.each(self.fileManager.stack, function (key, data) { + if (!$h.isEmpty(data.file)) { + self._setFileData(formdata, data.file, (data.nameFmt || ('untitled_' + ctr)), key); + } + ctr++; + }); + self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata); + }, + _uploadExtraOnly: function () { + var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError, formdata = new FormData(), errMsg, + op = self.ajaxOperations.uploadExtra; + fnBefore = function (jqXHR) { + self.lock(); + var outData = self._getOutData(formdata, jqXHR); + self._setProgress(50); + params.data = outData; + params.xhr = jqXHR; + self._checkBatchPreupload(outData, jqXHR); + }; + fnSuccess = function (data, textStatus, jqXHR) { + var outData = self._getOutData(formdata, jqXHR, data); + if ($h.isEmpty(data) || $h.isEmpty(data.error)) { + self._raise('filebatchuploadsuccess', [outData]); + self._clearFileInput(); + self._initUploadSuccess(data); + self._setProgress(101); + } else { + errMsg = self._parseError(op, jqXHR, self.msgUploadError); + self._showFileError(errMsg, outData, 'filebatchuploaderror'); + } + }; + fnComplete = function () { + self.unlock(); + self._clearFileInput(); + self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]); + }; + fnError = function (jqXHR, textStatus, errorThrown) { + var outData = self._getOutData(formdata, jqXHR); + errMsg = self._parseError(op, jqXHR, errorThrown); + params.data = outData; + self._showFileError(errMsg, outData, 'filebatchuploaderror'); + self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op)); + }; + self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata); + }, + _deleteFileIndex: function ($frame) { + var self = this, ind = $frame.attr('data-fileindex'), rev = self.reversePreviewOrder; + if (ind.substring(0, 5) === $h.INIT_FLAG) { + ind = parseInt(ind.replace($h.INIT_FLAG, '')); + self.initialPreview = $h.spliceArray(self.initialPreview, ind, rev); + self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind, rev); + self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind, rev); + self.getFrames().each(function () { + var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex'); + if (nInd.substring(0, 5) === $h.INIT_FLAG) { + nInd = parseInt(nInd.replace($h.INIT_FLAG, '')); + if (nInd > ind) { + nInd--; + $nFrame.attr('data-fileindex', $h.INIT_FLAG + nInd); + } + } + }); + } + }, + _resetCaption: function () { + var self = this; + setTimeout(function () { + var cap = '', n, chk = self.previewCache.count(true), len = self.fileManager.count(), file, + incomplete = ':not(.file-preview-success):not(.file-preview-error)', cfg, + hasThumb = self.showPreview && self.getFrames(incomplete).length; + if (len === 0 && chk === 0 && !hasThumb) { + self.reset(); + } else { + n = chk + len; + if (n > 1) { + cap = self._getMsgSelected(n); + } else { + if (len === 0) { + cfg = self.initialPreviewConfig[0]; + cap = ''; + if (cfg) { + cap = cfg.caption || cfg.filename || '' + } + if (!cap) { + cap = self._getMsgSelected(n); + } + } else { + file = self.fileManager.getFirstFile(); + cap = file ? file.nameFmt : '_'; + } + } + self._setCaption(cap); + } + }, self.processDelay); + }, + _initFileActions: function () { + var self = this; + if (!self.showPreview) { + return; + } + self._initZoomButton(); + self.getFrames(' .kv-file-remove').each(function () { + var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'), + ind = $frame.attr('data-fileindex'), status, fm = self.fileManager; + self._handler($el, 'click', function () { + status = self._raise('filepreremove', [id, ind]); + if (status === false || !self._validateMinCount()) { + return false; + } + hasError = $frame.hasClass('file-preview-error'); + $h.cleanMemory($frame); + $frame.fadeOut('slow', function () { + self.fileManager.remove($frame); + self._clearObjects($frame); + $frame.remove(); + if (id && hasError) { + self.$errorContainer.find('li[data-thumb-id="' + id + '"]').fadeOut('fast', function () { + $(this).remove(); + if (!self._errorsExist()) { + self._resetErrors(); + } + }); + } + self._clearFileInput(); + self._resetCaption(); + self._raise('fileremoved', [id, ind]); + }); + }); + }); + self.getFrames(' .kv-file-upload').each(function () { + var $el = $(this); + self._handler($el, 'click', function () { + var $frame = $el.closest($h.FRAMES), fileId = self._getThumbFileId($frame); + self._hideProgress(); + if ($frame.hasClass('file-preview-error') && !self.retryErrorUploads) { + return; + } + self._uploadSingle(self.fileManager.getIndex(fileId), fileId, false); + }); + }); + }, + _initPreviewActions: function () { + var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {}, + btnRemove = $h.FRAMES + ' .kv-file-remove', settings = self.fileActionSettings, + origClass = settings.removeClass, errClass = settings.removeErrorClass, + resetProgress = function () { + var hasFiles = self.isAjaxUpload ? self.previewCache.count(true) : self._inputFileCount(); + if (!self.getFrames().length && !hasFiles) { + self._setCaption(''); + self.reset(); + self.initialCaption = ''; + } else { + self._resetCaption(); + } + }; + self._initZoomButton(); + $preview.find(btnRemove).each(function () { + var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), errMsg, fnBefore, + fnSuccess, fnError, op = self.ajaxOperations.deleteThumb; + if ($h.isEmpty(vUrl) || vKey === undefined) { + return; + } + if (typeof vUrl === 'function') { + vUrl = vUrl(); + } + var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data, settings, params, config, + fileName, extraData, index = $frame.attr('data-fileindex'); + index = parseInt(index.replace($h.INIT_FLAG, '')); + config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index]; + extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra; + fileName = config && (config.filename || config.caption) || ''; + if (typeof extraData === 'function') { + extraData = extraData(); + } + params = {id: $el.attr('id'), key: vKey, extra: extraData}; + fnBefore = function (jqXHR) { + self.ajaxAborted = false; + self._raise('filepredelete', [vKey, jqXHR, extraData]); + if (self._abort()) { + jqXHR.abort(); + } else { + $el.removeClass(errClass); + $h.addCss($frame, 'file-uploading'); + $h.addCss($el, 'disabled ' + origClass); + } + }; + fnSuccess = function (data, textStatus, jqXHR) { + var n, cap; + if (!$h.isEmpty(data) && !$h.isEmpty(data.error)) { + params.jqXHR = jqXHR; + params.response = data; + errMsg = self._parseError(op, jqXHR, self.msgDeleteError, fileName); + self._showFileError(errMsg, params, 'filedeleteerror'); + $frame.removeClass('file-uploading'); + $el.removeClass('disabled ' + origClass).addClass(errClass); + resetProgress(); + return; + } + $frame.removeClass('file-uploading').addClass('file-deleted'); + $frame.fadeOut('slow', function () { + index = parseInt(($frame.attr('data-fileindex')).replace($h.INIT_FLAG, '')); + self.previewCache.unset(index); + self._deleteFileIndex($frame); + n = self.previewCache.count(true); + cap = n > 0 ? self._getMsgSelected(n) : ''; + self._setCaption(cap); + self._raise('filedeleted', [vKey, jqXHR, extraData]); + self._clearObjects($frame); + $frame.remove(); + resetProgress(); + }); + }; + fnError = function (jqXHR, textStatus, errorThrown) { + var errMsg = self._parseError(op, jqXHR, errorThrown, fileName); + params.jqXHR = jqXHR; + params.response = {}; + self._showFileError(errMsg, params, 'filedeleteerror'); + $frame.removeClass('file-uploading'); + $el.removeClass('disabled ' + origClass).addClass(errClass); + resetProgress(); + }; + self._initAjaxSettings(); + self._mergeAjaxCallback('beforeSend', fnBefore, 'delete'); + self._mergeAjaxCallback('success', fnSuccess, 'delete'); + self._mergeAjaxCallback('error', fnError, 'delete'); + settings = $.extend(true, {}, { + url: self._encodeURI(vUrl), + type: 'POST', + dataType: 'json', + data: $.extend(true, {}, {key: vKey}, extraData) + }, self._ajaxDeleteSettings); + self._handler($el, 'click', function () { + if (!self._validateMinCount()) { + return false; + } + self.ajaxAborted = false; + self._raise('filebeforedelete', [vKey, extraData]); + if (self.ajaxAborted instanceof Promise) { + self.ajaxAborted.then(function (result) { + if (!result) { + $.ajax(settings); + } + }); + } else { + if (!self.ajaxAborted) { + $.ajax(settings); + } + } + }); + }); + }, + _hideFileIcon: function () { + var self = this; + if (self.overwriteInitial) { + self.$captionContainer.removeClass('icon-visible'); + } + }, + _showFileIcon: function () { + var self = this; + $h.addCss(self.$captionContainer, 'icon-visible'); + }, + _getSize: function (bytes, sizes) { + var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, out; + if (!$.isNumeric(bytes) || !$.isNumeric(size)) { + return ''; + } + if (typeof func === 'function') { + out = func(size); + } else { + if (size === 0) { + out = '0.00 B'; + } else { + if (!sizes) { + sizes = self.sizeUnits; + } + i = Math.floor(Math.log(size) / Math.log(self.bytesToKB)); + out = (size / Math.pow(self.bytesToKB, i)).toFixed(2) + ' ' + sizes[i]; + } + } + return self._getLayoutTemplate('size').replace('{sizeText}', out); + }, + _getFileType: function (ftype) { + var self = this; + return self.mimeTypeAliases[ftype] || ftype; + }, + _generatePreviewTemplate: function ( + cat, + data, + fname, + ftype, + previewId, + fileId, + isError, + size, + frameClass, + foot, + ind, + templ, + attrs, + zoomData + ) { + var self = this, caption = self.slug(fname), prevContent, zoomContent = '', styleAttribs = '', + screenW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, + config, title = caption, alt = caption, typeCss = 'type-default', getContent, + footer = foot || self._renderFileFooter(cat, caption, size, 'auto', isError), + forcePrevIcon = self.preferIconicPreview, forceZoomIcon = self.preferIconicZoomPreview, + newCat = forcePrevIcon ? 'other' : cat; + config = screenW < 400 ? (self.previewSettingsSmall[newCat] || self.defaults.previewSettingsSmall[newCat]) : + (self.previewSettings[newCat] || self.defaults.previewSettings[newCat]); + if (config) { + $.each(config, function (key, val) { + styleAttribs += key + ':' + val + ';'; + }); + } + getContent = function (vCat, vData, zoom, frameCss, vZoomData) { + var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(vCat), + css = (frameClass || '') + ' ' + frameCss, tokens; + if (self.frameClass) { + css = self.frameClass + ' ' + css; + } + if (zoom) { + css = css.replace(' ' + $h.SORT_CSS, ''); + } + tmplt = self._parseFilePreviewIcon(tmplt, fname); + if (cat === 'object' && !ftype) { + $.each(self.defaults.fileTypeSettings, function (key, func) { + if (key === 'object' || key === 'other') { + return; + } + if (func(fname, ftype)) { + typeCss = 'type-' + key; + } + }); + } + if (!$h.isEmpty(attrs)) { + if (attrs.title !== undefined && attrs.title !== null) { + title = attrs.title; + } + if (attrs.alt !== undefined && attrs.alt !== null) { + title = attrs.alt; + } + } + tokens = { + 'previewId': id, + 'caption': caption, + 'title': title, + 'alt': alt, + 'frameClass': css, + 'type': self._getFileType(ftype), + 'fileindex': ind, + 'fileid': fileId || '', + 'typeCss': typeCss, + 'footer': footer, + 'data': zoom && vZoomData ? '{zoomData}' : vData, + 'template': templ || cat, + 'style': styleAttribs ? 'style="' + styleAttribs + '"' : '', + 'zoomData': vZoomData ? encodeURIComponent(vZoomData) : '' + }; + if (zoom) { + tokens.zoomCache = ''; + tokens.zoomData = '{zoomData}'; + } + return tmplt.setTokens(tokens); + }; + ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1); + if (self.fileActionSettings.showZoom) { + zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, 'kv-zoom-thumb', zoomData); + } + zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent); + if (typeof self.sanitizeZoomCache === 'function') { + zoomContent = self.sanitizeZoomCache(zoomContent); + } + prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb', zoomData); + return prevContent.setTokens({zoomCache: zoomContent}); + }, + _addToPreview: function ($preview, content) { + var self = this, $el; + content = $h.cspBuffer.stash(content); + $el = self.reversePreviewOrder ? $preview.prepend(content) : $preview.append(content); + $h.cspBuffer.apply($preview); + return $el; + }, + _previewDefault: function (file, isDisabled) { + var self = this, $preview = self.$preview; + if (!self.showPreview) { + return; + } + var fname = $h.getFileName(file), ftype = file ? file.type : '', content, size = file.size || 0, + caption = self._getFileName(file, ''), isError = isDisabled === true && !self.isAjaxUpload, + data = $h.createObjectURL(file), fileId = self.fileManager.getId(file), + previewId = self._getThumbId(fileId); + self._clearDefaultPreview(); + content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, fileId, isError, size); + self._addToPreview($preview, content); + self._setThumbAttr(previewId, caption, size); + if (isDisabled === true && self.isAjaxUpload) { + self._setThumbStatus(self._getFrame(previewId), 'Error'); + } + }, + _previewFile: function (i, file, theFile, data, fileInfo) { + if (!this.showPreview) { + return; + } + var self = this, fname = $h.getFileName(file), ftype = fileInfo.type, caption = fileInfo.name, + cat = self._parseFileType(ftype, fname), content, $preview = self.$preview, fsize = file.size || 0, + iData = cat === 'image' ? theFile.target.result : data, fm = self.fileManager, + fileId = fm.getId(file), previewId = self._getThumbId(fileId); + /** @namespace window.DOMPurify */ + content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, fileId, false, fsize); + self._clearDefaultPreview(); + self._addToPreview($preview, content); + var $thumb = self._getFrame(previewId); + self._validateImageOrientation($thumb.find('img'), file, previewId, fileId, caption, ftype, fsize, iData); + self._setThumbAttr(previewId, caption, fsize); + self._initSortable(); + }, + _setThumbAttr: function (id, caption, size, description) { + var self = this, $frame = self._getFrame(id); + if ($frame.length) { + size = size && size > 0 ? self._getSize(size) : ''; + $frame.data({'caption': caption, 'size': size, 'description': description || ''}); + } + }, + _setInitThumbAttr: function () { + var self = this, data = self.previewCache.data, len = self.previewCache.count(true), config, + caption, size, description, previewId; + if (len === 0) { + return; + } + for (var i = 0; i < len; i++) { + config = data.config[i]; + previewId = self.previewInitId + '-' + $h.INIT_FLAG + i; + caption = $h.ifSet('caption', config, $h.ifSet('filename', config)); + size = $h.ifSet('size', config); + description = $h.ifSet('description', config); + self._setThumbAttr(previewId, caption, size, description); + } + }, + _slugDefault: function (text) { + // noinspection RegExpRedundantEscape + return $h.isEmpty(text, true) ? '' : String(text).replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_'); + }, + _updateFileDetails: function (numFiles) { + var self = this, $el = self.$element, label, n, log, nFiles, file, + name = ($h.isIE(9) && $h.findFileName($el.val())) || ($el[0].files[0] && $el[0].files[0].name); + if (!name && self.fileManager.count() > 0) { + file = self.fileManager.getFirstFile(); + label = file.nameFmt; + } else { + label = name ? self.slug(name) : '_'; + } + n = self.isAjaxUpload ? self.fileManager.count() : numFiles; + nFiles = self.previewCache.count(true) + n; + log = n === 1 ? label : self._getMsgSelected(nFiles, !self.isAjaxUpload && !self.isError); + if (self.isError) { + self.$previewContainer.removeClass('file-thumb-loading'); + self._initCapStatus(); + self.$previewStatus.html(''); + self.$captionContainer.removeClass('icon-visible'); + } else { + self._showFileIcon(); + } + self._setCaption(log, self.isError); + self.$container.removeClass('file-input-new file-input-ajax-new'); + self._raise('fileselect', [numFiles, label]); + if (self.previewCache.count(true)) { + self._initPreviewActions(); + } + }, + _setThumbStatus: function ($thumb, status) { + var self = this; + if (!self.showPreview) { + return; + } + var icon = 'indicator' + status, msg = icon + 'Title', + css = 'file-preview-' + status.toLowerCase(), + $indicator = $thumb.find('.file-upload-indicator'), + config = self.fileActionSettings; + $thumb.removeClass('file-preview-success file-preview-error file-preview-paused file-preview-loading'); + if (status === 'Success') { + $thumb.find('.file-drag-handle').remove(); + } + $h.setHtml($indicator, config[icon]); + $indicator.attr('title', config[msg]); + $thumb.addClass(css); + if (status === 'Error' && !self.retryErrorUploads) { + $thumb.find('.kv-file-upload').attr('disabled', true); + } + }, + _setProgressCancelled: function () { + var self = this; + self._setProgress(101, self.$progress, self.msgCancelled); + }, + _setProgress: function (p, $el, error, stats) { + var self = this; + $el = $el || self.$progress; + if (!$el.length) { + return; + } + var pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold, + t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate, + template = pct < 100 ? self.progressTemplate : + (error ? (self.paused ? self.progressPauseTemplate : self.progressErrorTemplate) : t); + if (p >= 100) { + stats = ''; + } + if (!$h.isEmpty(template)) { + if (pctLimit && pct > pctLimit && p <= 100) { + out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold}); + } else { + out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')}); + } + stats = stats || ''; + out = out.setTokens({stats: stats}); + $h.setHtml($el, out); + if (error) { + $h.setHtml($el.find('[role="progressbar"]'), error); + } + } + }, + _hasFiles: function () { + var el = this.$element[0]; + return !!(el && el.files && el.files.length); + }, + _setFileDropZoneTitle: function () { + var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles; + if (self.isClickable) { + strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural; + title += self.dropZoneClickTitle.replace('{files}', strFiles); + } + $zone.find('.' + self.dropZoneTitleClass).remove(); + if (!self.showPreview || $zone.length === 0 || self.fileManager.count() > 0 || !self.dropZoneEnabled || + self.previewCache.count() > 0 || (!self.isAjaxUpload && self._hasFiles())) { + return; + } + if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) { + $zone.prepend('
    ' + title + '
    '); + } + self.$container.removeClass('file-input-new'); + $h.addCss(self.$container, 'file-input-ajax-new'); + }, + _getStats: function (stats) { + var self = this, pendingTime, t; + if (!self.showUploadStats || !stats || !stats.bitrate) { + return ''; + } + t = self._getLayoutTemplate('stats'); + pendingTime = (!stats.elapsed || !stats.bps) ? self.msgCalculatingTime : + self.msgPendingTime.setTokens({time: $h.getElapsed(Math.ceil(stats.pendingBytes / stats.bps))}); + + return t.setTokens({ + uploadSpeed: stats.bitrate, + pendingTime: pendingTime + }); + }, + _setResumableProgress: function (pct, stats, $thumb) { + var self = this, rm = self.resumableManager, obj = $thumb ? rm : self, + $prog = $thumb ? $thumb.find('.file-thumb-progress') : null; + if (obj.lastProgress === 0) { + obj.lastProgress = pct; + } + if (pct < obj.lastProgress) { + pct = obj.lastProgress; + } + self._setProgress(pct, $prog, null, self._getStats(stats)); + obj.lastProgress = pct; + }, + _toggleResumableProgress: function (template, message) { + var self = this, $progress = self.$progress; + if ($progress && $progress.length) { + $h.setHtml($progress, template.setTokens({ + percent: 101, + status: message, + stats: '' + })); + } + }, + _setFileUploadStats: function (id, pct, stats) { + var self = this, $prog = self.$progress; + if (!self.showPreview && (!$prog || !$prog.length)) { + return; + } + var fm = self.fileManager, rm = self.resumableManager, $thumb = fm.getThumb(id), pctTot, + totUpSize = 0, totSize = fm.getTotalSize(), totStats = $.extend(true, {}, stats); + if (self.enableResumableUpload) { + var loaded = stats.loaded, currUplSize = rm.getUploadedSize(), currTotSize = rm.file.size, totLoaded; + loaded += currUplSize; + totLoaded = fm.uploadedSize + loaded; + pct = $h.round(100 * loaded / currTotSize); + stats.pendingBytes = currTotSize - currUplSize; + self._setResumableProgress(pct, stats, $thumb); + pctTot = Math.floor(100 * totLoaded / totSize); + totStats.pendingBytes = totSize - totLoaded; + self._setResumableProgress(pctTot, totStats); + } else { + fm.setProgress(id, pct); + $prog = $thumb && $thumb.length ? $thumb.find('.file-thumb-progress') : null; + self._setProgress(pct, $prog, null, self._getStats(stats)); + $.each(fm.stats, function (id, cfg) { + totUpSize += cfg.loaded; + }); + totStats.pendingBytes = totSize - totUpSize; + pctTot = $h.round(totUpSize / totSize * 100); + self._setProgress(pctTot, null, null, self._getStats(totStats)); + } + }, + _validateMinCount: function () { + var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount(); + if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) { + self._noFilesError({}); + return false; + } + return true; + }, + _getFileCount: function (fileCount, includeInitial) { + var self = this, addCount = 0; + if (includeInitial === undefined) { + includeInitial = self.validateInitialCount && !self.overwriteInitial; + } + if (includeInitial) { + addCount = self.previewCache.count(true); + fileCount += addCount; + } + return fileCount; + }, + _getFileId: function (file) { + return $h.getFileId(file, this.generateFileId); + }, + _getFileName: function (file, defaultValue) { + var self = this, fileName = $h.getFileName(file); + return fileName ? self.slug(fileName) : defaultValue; + }, + _getFileNames: function (skipNull) { + var self = this; + return self.filenames.filter(function (n) { + return (skipNull ? n !== undefined : n !== undefined && n !== null); + }); + }, + _setPreviewError: function ($thumb, keepFile) { + var self = this, removeFrame = self.removeFromPreviewOnError && !self.retryErrorUploads; + if (!keepFile || removeFrame) { + self.fileManager.remove($thumb); + } + if (!self.showPreview) { + return; + } + if (removeFrame) { + $thumb.remove(); + return; + } else { + self._setThumbStatus($thumb, 'Error'); + } + self._refreshUploadButton($thumb); + }, + _refreshUploadButton: function ($thumb) { + var self = this, $btn = $thumb.find('.kv-file-upload'), cfg = self.fileActionSettings, + icon = cfg.uploadIcon, title = cfg.uploadTitle; + if (!$btn.length) { + return; + } + if (self.retryErrorUploads) { + icon = cfg.uploadRetryIcon; + title = cfg.uploadRetryTitle; + } + $btn.attr('title', title); + $h.setHtml($btn, icon); + }, + _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) { + var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type], + $imgEl, isValid; + if ($h.isEmpty(limit) || !$img.length) { + return; + } + $imgEl = $img[0]; + dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height; + isValid = chk === 'Small' ? dim >= limit : dim <= limit; + if (isValid) { + return; + } + msg = self['msgImage' + type + chk].setTokens({'name': fname, 'size': limit}); + self._showFileError(msg, params); + self._setPreviewError($thumb); + }, + _getExifObj: function (data) { + var self = this, exifObj, error = $h.logMessages.exifWarning; + if (data.slice(0, 23) !== 'data:image/jpeg;base64,' && data.slice(0, 22) !== 'data:image/jpg;base64,') { + exifObj = null; + return; + } + try { + exifObj = window.piexif ? window.piexif.load(data) : null; + } catch (err) { + exifObj = null; + error = err && err.message || ''; + } + if (!exifObj) { + self._log($h.logMessages.badExifParser, {details: error}); + } + return exifObj; + }, + setImageOrientation: function ($img, $zoomImg, value, $thumb) { + var self = this, invalidImg = !$img || !$img.length, invalidZoomImg = !$zoomImg || !$zoomImg.length, $mark, + isHidden = false, $div, zoomOnly = invalidImg && $thumb && $thumb.attr('data-template') === 'image', ev; + if (invalidImg && invalidZoomImg) { + return; + } + ev = 'load.fileinputimageorient'; + if (zoomOnly) { + $img = $zoomImg; + $zoomImg = null; + $img.css(self.previewSettings.image); + $div = $(document.createElement('div')).appendTo($thumb.find('.kv-file-content')); + $mark = $(document.createElement('span')).insertBefore($img); + $img.css('visibility', 'hidden').removeClass('file-zoom-detail').appendTo($div); + } else { + isHidden = !$img.is(':visible'); + } + $img.off(ev).on(ev, function () { + if (isHidden) { + self.$preview.removeClass('hide-content'); + $thumb.find('.kv-file-content').css('visibility', 'hidden'); + } + var img = $img[0], zoomImg = $zoomImg && $zoomImg.length ? $zoomImg[0] : null, + h = img.offsetHeight, w = img.offsetWidth, r = $h.getRotation(value); + if (isHidden) { + $thumb.find('.kv-file-content').css('visibility', 'visible'); + self.$preview.addClass('hide-content'); + } + $img.data('orientation', value); + if (zoomImg) { + $zoomImg.data('orientation', value); + } + if (value < 5) { + $h.setTransform(img, r); + $h.setTransform(zoomImg, r); + return; + } + var offsetAngle = Math.atan(w / h), origFactor = Math.sqrt(Math.pow(h, 2) + Math.pow(w, 2)), + scale = !origFactor ? 1 : (h / Math.cos(Math.PI / 2 + offsetAngle)) / origFactor, + s = ' scale(' + Math.abs(scale) + ')'; + $h.setTransform(img, r + s); + $h.setTransform(zoomImg, r + s); + if (zoomOnly) { + $img.css('visibility', 'visible').insertAfter($mark).addClass('file-zoom-detail'); + $mark.remove(); + $div.remove(); + } + }); + }, + _validateImageOrientation: function ($img, file, previewId, fileId, caption, ftype, fsize, iData) { + var self = this, exifObj = null, value, autoOrientImage = self.autoOrientImage, selector; + if (self.canOrientImage) { + $img.css('image-orientation', (autoOrientImage ? 'from-image' : 'none')); + self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj); + return; + } + selector = $h.getZoomSelector(previewId, ' img'); + exifObj = autoOrientImage ? self._getExifObj(iData) : null; + value = exifObj ? exifObj['0th'][piexif.ImageIFD.Orientation] : null; // jshint ignore:line + if (!value) { + self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj); + return; + } + self.setImageOrientation($img, $(selector), value, self._getFrame(previewId)); + self._raise('fileimageoriented', {'$img': $img, 'file': file}); + self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj); + }, + _validateImage: function (previewId, fileId, fname, ftype, fsize, iData, exifObj) { + var self = this, $preview = self.$preview, params, w1, w2, $thumb = self._getFrame(previewId), + i = $thumb.attr('data-fileindex'), $img = $thumb.find('img'); + fname = fname || 'Untitled'; + $img.one('load', function () { + w1 = $thumb.width(); + w2 = $preview.width(); + if (w1 > w2) { + $img.css('width', '100%'); + } + params = {ind: i, id: previewId, fileId: fileId}; + self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params); + self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params); + if (!self.resizeImage) { + self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params); + self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params); + } + self._raise('fileimageloaded', [previewId]); + self.fileManager.addImage(fileId, { + ind: i, + img: $img, + thumb: $thumb, + pid: previewId, + typ: ftype, + siz: fsize, + validated: false, + imgData: iData, + exifObj: exifObj + }); + $thumb.data('exif', exifObj); + self._validateAllImages(); + }).one('error', function () { + self._raise('fileimageloaderror', [previewId]); + }); + }, + _validateAllImages: function () { + var self = this, counter = {val: 0}, numImgs = self.fileManager.getImageCount(), fsize, + minSize = self.resizeIfSizeMoreThan; + if (numImgs !== self.fileManager.totalImages) { + return; + } + self._raise('fileimagesloaded'); + if (!self.resizeImage) { + return; + } + $.each(self.fileManager.loadedImages, function (id, config) { + if (!config.validated) { + fsize = config.siz; + if (fsize && fsize > minSize * self.bytesToKB) { + self._getResizedImage(id, config, counter, numImgs); + } + config.validated = true; + } + }); + }, + _getResizedImage: function (id, config, counter, numImgs) { + var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob, + ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height, + isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI, + context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind, + $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr, file, params, evParams; + throwError = function (msg, params, ev) { + if (self.isAjaxUpload) { + self._showFileError(msg, params, ev); + } else { + self._showError(msg, params, ev); + } + self._setPreviewError($thumb); + }; + file = self.fileManager.getFile(id); + params = {id: pid, 'index': ind, fileId: id}; + evParams = [id, pid, ind]; + if (!file || !isValidImage || (width <= maxWidth && height <= maxHeight)) { + if (isValidImage && file) { + self._raise('fileimageresized', evParams); + } + counter.val++; + if (counter.val === numImgs) { + self._raise('fileimagesresized'); + } + if (!isValidImage) { + throwError(self.msgImageResizeError, params, 'fileimageresizeerror'); + return; + } + } + type = type || self.resizeDefaultImageType; + chkWidth = width > maxWidth; + chkHeight = height > maxHeight; + if (self.resizePreference === 'width') { + ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1); + } else { + ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1); + } + self._resetCanvas(); + width *= ratio; + height *= ratio; + canvas.width = width; + canvas.height = height; + try { + context.drawImage(img, 0, 0, width, height); + dataURI = canvas.toDataURL(type, self.resizeQuality); + if (exifObj) { + exifStr = window.piexif.dump(exifObj); + dataURI = window.piexif.insert(exifStr, dataURI); + } + blob = $h.dataURI2Blob(dataURI); + self.fileManager.setFile(id, blob); + self._raise('fileimageresized', evParams); + counter.val++; + if (counter.val === numImgs) { + self._raise('fileimagesresized', [undefined, undefined]); + } + if (!(blob instanceof Blob)) { + throwError(self.msgImageResizeError, params, 'fileimageresizeerror'); + } + } catch (err) { + counter.val++; + if (counter.val === numImgs) { + self._raise('fileimagesresized', [undefined, undefined]); + } + msg = self.msgImageResizeException.replace('{errors}', err.message); + throwError(msg, params, 'fileimageresizeexception'); + } + }, + _showProgress: function () { + var self = this; + if (self.$progress && self.$progress.length) { + self.$progress.show(); + } + }, + _hideProgress: function () { + var self = this; + if (self.$progress && self.$progress.length) { + self.$progress.hide(); + } + }, + _initBrowse: function ($container) { + var self = this, $el = self.$element; + if (self.showBrowse) { + self.$btnFile = $container.find('.btn-file').append($el); + } else { + $el.appendTo($container).attr('tabindex', -1); + $h.addCss($el, 'file-no-browse'); + } + }, + _initClickable: function () { + var self = this, $zone, $tmpZone; + if (!self.isClickable) { + return; + } + $zone = self.$dropZone; + if (!self.isAjaxUpload) { + $tmpZone = self.$preview.find('.file-default-preview'); + if ($tmpZone.length) { + $zone = $tmpZone; + } + } + + $h.addCss($zone, 'clickable'); + $zone.attr('tabindex', -1); + self._handler($zone, 'click', function (e) { + var $tar = $(e.target); + if (!self.$errorContainer.is(':visible') && (!$tar.parents( + '.file-preview-thumbnails').length || $tar.parents( + '.file-default-preview').length)) { + self.$element.data('zoneClicked', true).trigger('click'); + $zone.blur(); + } + }); + }, + _initCaption: function () { + var self = this, cap = self.initialCaption || ''; + if (self.overwriteInitial || $h.isEmpty(cap)) { + self.$caption.val(''); + return false; + } + self._setCaption(cap); + return true; + }, + _setCaption: function (content, isError) { + var self = this, title, out, icon, n, cap, file; + if (!self.$caption.length) { + return; + } + self.$captionContainer.removeClass('icon-visible'); + if (isError) { + title = $('
    ' + self.msgValidationError + '
    ').text(); + n = self.fileManager.count(); + if (n) { + file = self.fileManager.getFirstFile(); + cap = n === 1 && file ? file.nameFmt : self._getMsgSelected(n); + } else { + cap = self._getMsgSelected(self.msgNo); + } + out = $h.isEmpty(content) ? cap : content; + icon = '' + self.msgValidationErrorIcon + ''; + } else { + if ($h.isEmpty(content)) { + self.$caption.attr('title', ''); + return; + } + title = $('
    ' + content + '
    ').text(); + out = title; + icon = self._getLayoutTemplate('fileIcon'); + } + self.$captionContainer.addClass('icon-visible'); + self.$caption.attr('title', title).val(out); + $h.setHtml(self.$captionIcon, icon); + }, + _createContainer: function () { + var self = this, attribs = {'class': 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')}, + $container = $h.createElement($h.cspBuffer.stash(self._renderMain())); + $h.cspBuffer.apply($container); + $container.insertBefore(self.$element).attr(attribs); + self._initBrowse($container); + if (self.theme) { + $container.addClass('theme-' + self.theme); + } + return $container; + }, + _refreshContainer: function () { + var self = this, $container = self.$container, $el = self.$element; + $el.insertAfter($container); + $h.setHtml($container, self._renderMain()); + self._initBrowse($container); + self._validateDisabled(); + }, + _validateDisabled: function () { + var self = this; + self.$caption.attr({readonly: self.isDisabled}); + }, + _setTabIndex: function (type, html) { + var self = this, index = self.tabIndexConfig[type]; + return html.setTokens({ + tabIndexConfig: index === undefined || index === null ? '' : 'tabindex="' + index + '"' + }); + }, + _renderMain: function () { + var self = this, + dropCss = self.dropZoneEnabled ? ' file-drop-zone' : 'file-drop-disabled', + close = !self.showClose ? '' : self._getLayoutTemplate('close'), + preview = !self.showPreview ? '' : self._getLayoutTemplate('preview') + .setTokens({'class': self.previewClass, 'dropClass': dropCss}), + css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass, + caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'}); + caption = self._setTabIndex('caption', caption); + return self.mainTemplate.setTokens({ + 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''), + 'inputGroupClass': self.inputGroupClass, + 'preview': preview, + 'close': close, + 'caption': caption, + 'upload': self._renderButton('upload'), + 'remove': self._renderButton('remove'), + 'cancel': self._renderButton('cancel'), + 'pause': self._renderButton('pause'), + 'browse': self._renderButton('browse') + }); + + }, + _renderButton: function (type) { + var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'], + title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'], + status = self.isDisabled ? ' disabled' : '', btnType = 'button'; + switch (type) { + case 'remove': + if (!self.showRemove) { + return ''; + } + break; + case 'cancel': + if (!self.showCancel) { + return ''; + } + css += ' kv-hidden'; + break; + case 'pause': + if (!self.showPause) { + return ''; + } + css += ' kv-hidden'; + break; + case 'upload': + if (!self.showUpload) { + return ''; + } + if (self.isAjaxUpload && !self.isDisabled) { + tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl); + } else { + btnType = 'submit'; + } + break; + case 'browse': + if (!self.showBrowse) { + return ''; + } + tmplt = self._getLayoutTemplate('btnBrowse'); + break; + default: + return ''; + } + tmplt = self._setTabIndex(type, tmplt); + + css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button'; + if (!$h.isEmpty(label)) { + label = ' ' + label + ''; + } + return tmplt.setTokens({ + 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label + }); + }, + _renderThumbProgress: function () { + var self = this; + return '
    ' + + self.progressInfoTemplate.setTokens({percent: 101, status: self.msgUploadBegin, stats: ''}) + + '
    '; + }, + _renderFileFooter: function (cat, caption, size, width, isError) { + var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag, + upl = config.showUpload, zoom = config.showZoom, out, params, + template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'), + ind = isError ? config.indicatorError : config.indicatorNew, + title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle, + indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title}); + size = self._getSize(size); + params = {type: cat, caption: caption, size: size, width: width, progress: '', indicator: indicator}; + if (self.isAjaxUpload) { + params.progress = self._renderThumbProgress(); + params.actions = self._renderFileActions(params, upl, false, rem, zoom, drg, false, false, false); + } else { + params.actions = self._renderFileActions(params, false, false, false, zoom, drg, false, false, false); + } + out = template.setTokens(params); + out = $h.replaceTags(out, self.previewThumbTags); + return out; + }, + _renderFileActions: function ( + cfg, + showUpl, + showDwn, + showDel, + showZoom, + showDrag, + disabled, + url, + key, + isInit, + dUrl, + dFile + ) { + var self = this; + if (!cfg.type && isInit) { + cfg.type = 'image'; + } + if (self.enableResumableUpload) { + showUpl = false; + } else { + if (typeof showUpl === 'function') { + showUpl = showUpl(cfg); + } + } + if (typeof showDwn === 'function') { + showDwn = showDwn(cfg); + } + if (typeof showDel === 'function') { + showDel = showDel(cfg); + } + if (typeof showZoom === 'function') { + showZoom = showZoom(cfg); + } + if (typeof showDrag === 'function') { + showDrag = showDrag(cfg); + } + if (!showUpl && !showDwn && !showDel && !showZoom && !showDrag) { + return ''; + } + var vUrl = url === false ? '' : ' data-url="' + url + '"', btnZoom = '', btnDrag = '', css, + vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '', + template = self._getLayoutTemplate('actions'), config = self.fileActionSettings, + otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}), + removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass; + if (showDel) { + btnDelete = self._getLayoutTemplate('actionDelete').setTokens({ + 'removeClass': removeClass, + 'removeIcon': config.removeIcon, + 'removeTitle': config.removeTitle, + 'dataUrl': vUrl, + 'dataKey': vKey, + 'key': key + }); + } + if (showUpl) { + btnUpload = self._getLayoutTemplate('actionUpload').setTokens({ + 'uploadClass': config.uploadClass, + 'uploadIcon': config.uploadIcon, + 'uploadTitle': config.uploadTitle + }); + } + if (showDwn) { + btnDownload = self._getLayoutTemplate('actionDownload').setTokens({ + 'downloadClass': config.downloadClass, + 'downloadIcon': config.downloadIcon, + 'downloadTitle': config.downloadTitle, + 'downloadUrl': dUrl || self.initialPreviewDownloadUrl + }); + btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key}); + } + if (showZoom) { + btnZoom = self._getLayoutTemplate('actionZoom').setTokens({ + 'zoomClass': config.zoomClass, + 'zoomIcon': config.zoomIcon, + 'zoomTitle': config.zoomTitle + }); + } + if (showDrag && isInit) { + css = 'drag-handle-init ' + config.dragClass; + btnDrag = self._getLayoutTemplate('actionDrag').setTokens({ + 'dragClass': css, + 'dragTitle': config.dragTitle, + 'dragIcon': config.dragIcon + }); + } + return template.setTokens({ + 'delete': btnDelete, + 'upload': btnUpload, + 'download': btnDownload, + 'zoom': btnZoom, + 'drag': btnDrag, + 'other': otherButtons + }); + }, + _browse: function (e) { + var self = this; + if (e && e.isDefaultPrevented() || !self._raise('filebrowse')) { + return; + } + if (self.isError && !self.isAjaxUpload) { + self.clear(); + } + if (self.focusCaptionOnBrowse) { + self.$captionContainer.focus(); + } + }, + _change: function (e) { + var self = this; + $(document.body).off('focusin.fileinput focusout.fileinput'); + if (self.changeTriggered) { + return; + } + self._setLoading('show'); + var $el = self.$element, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload, + tfiles, files = isDragDrop ? arguments[1] : $el[0].files, ctr = self.fileManager.count(), + total, initCount, len, isSingleUpl = $h.isEmpty($el.attr('multiple')), + maxCount = !isAjaxUpload && isSingleUpl ? 1 : self.maxFileCount, maxTotCount = self.maxTotalFileCount, + inclAll = maxTotCount > 0 && maxTotCount > maxCount, flagSingle = (isSingleUpl && ctr > 0), + throwError = function (mesg, file, previewId, index) { + var p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files), {id: previewId, index: index}), + p2 = {id: previewId, index: index, file: file, files: files}; + self.isPersistentError = true; + self._setLoading('hide'); + return isAjaxUpload ? self._showFileError(mesg, p1) : self._showError(mesg, p2); + }, + maxCountCheck = function (n, m, all) { + var msg = all ? self.msgTotalFilesTooMany : self.msgFilesTooMany; + msg = msg.replace('{m}', m).replace('{n}', n); + self.isError = throwError(msg, null, null, null); + self.$captionContainer.removeClass('icon-visible'); + self._setCaption('', true); + self.$container.removeClass('file-input-new file-input-ajax-new'); + }; + self.reader = null; + self._resetUpload(); + self._hideFileIcon(); + if (self.dropZoneEnabled) { + self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove(); + } + if (!isAjaxUpload) { + if (e.target && e.target.files === undefined) { + files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : []; + } else { + files = e.target.files || {}; + } + } + tfiles = files; + if ($h.isEmpty(tfiles) || tfiles.length === 0) { + if (!isAjaxUpload) { + self.clear(); + } + self._raise('fileselectnone'); + return; + } + self._resetErrors(); + len = tfiles.length; + initCount = isAjaxUpload ? (self.fileManager.count() + len) : len; + total = self._getFileCount(initCount, inclAll ? false : undefined); + if (maxCount > 0 && total > maxCount) { + if (!self.autoReplace || len > maxCount) { + maxCountCheck((self.autoReplace && len > maxCount ? len : total), maxCount); + return; + } + if (total > maxCount) { + self._resetPreviewThumbs(isAjaxUpload); + } + } else { + if (inclAll) { + total = self._getFileCount(initCount, true); + if (maxTotCount > 0 && total > maxTotCount) { + if (!self.autoReplace || len > maxCount) { + maxCountCheck((self.autoReplace && len > maxTotCount ? len : total), maxTotCount, true); + return; + } + if (total > maxCount) { + self._resetPreviewThumbs(isAjaxUpload); + } + } + } + if (!isAjaxUpload || flagSingle) { + self._resetPreviewThumbs(false); + if (flagSingle) { + self.clearFileStack(); + } + } else { + if (isAjaxUpload && ctr === 0 && (!self.previewCache.count(true) || self.overwriteInitial)) { + self._resetPreviewThumbs(true); + } + } + } + self.readFiles(tfiles); + self._setLoading('hide'); + }, + _abort: function (params) { + var self = this, data; + if (self.ajaxAborted && typeof self.ajaxAborted === 'object' && self.ajaxAborted.message !== undefined) { + data = $.extend(true, {}, self._getOutData(null), params); + data.abortData = self.ajaxAborted.data || {}; + data.abortMessage = self.ajaxAborted.message; + self._setProgress(101, self.$progress, self.msgCancelled); + self._showFileError(self.ajaxAborted.message, data, 'filecustomerror'); + self.cancel(); + self.unlock(); + return true; + } + return !!self.ajaxAborted; + }, + _resetFileStack: function () { + var self = this, i = 0; + self._getThumbs().each(function () { + var $thumb = $(this), ind = $thumb.attr('data-fileindex'), pid = $thumb.attr('id'); + if (ind === '-1' || ind === -1) { + return; + } + if (!self._getThumbFile($thumb)) { + $thumb.attr({'data-fileindex': i}); + i++; + } else { + $thumb.attr({'data-fileindex': '-1'}); + } + self._getZoom(pid).attr({ + 'data-fileindex': $thumb.attr('data-fileindex') + }); + }); + }, + _isFileSelectionValid: function (cnt) { + var self = this; + cnt = cnt || 0; + if (self.required && !self.getFilesCount()) { + self.$errorContainer.html(''); + self._showFileError(self.msgFileRequired); + return false; + } + if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) { + self._noFilesError({}); + return false; + } + return true; + }, + _canPreview: function (file) { + var self = this; + if (!file || !self.showPreview || !self.$preview || !self.$preview.length) { + return false; + } + var name = file.name || '', type = file.type || '', size = (file.size || 0) / self.bytesToKB, + cat = self._parseFileType(type, name), allowedTypes, allowedMimes, allowedExts, skipPreview, + types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, + exts = self.allowedPreviewExtensions || [], dTypes = self.disabledPreviewTypes, + dMimes = self.disabledPreviewMimeTypes, dExts = self.disabledPreviewExtensions || [], + maxSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize) || 0, + expAllExt = new RegExp('\\.(' + exts.join('|') + ')$', 'i'), + expDisExt = new RegExp('\\.(' + dExts.join('|') + ')$', 'i'); + allowedTypes = !types || types.indexOf(cat) !== -1; + allowedMimes = !mimes || mimes.indexOf(type) !== -1; + allowedExts = !exts.length || $h.compare(name, expAllExt); + skipPreview = (dTypes && dTypes.indexOf(cat) !== -1) || (dMimes && dMimes.indexOf(type) !== -1) || + (dExts.length && $h.compare(name, expDisExt)) || (maxSize && !isNaN(maxSize) && size > maxSize); + return !skipPreview && (allowedTypes || allowedMimes || allowedExts); + }, + addToStack: function (file, id) { + this.fileManager.add(file, id); + }, + clearFileStack: function () { + var self = this; + self.fileManager.clear(); + self._initResumableUpload(); + if (self.enableResumableUpload) { + if (self.showPause === null) { + self.showPause = true; + } + if (self.showCancel === null) { + self.showCancel = false; + } + } else { + self.showPause = false; + if (self.showCancel === null) { + self.showCancel = true; + } + } + return self.$element; + }, + getFileStack: function () { + return this.fileManager.stack; + }, + getFileList: function () { + return this.fileManager.list(); + }, + getFilesSize: function () { + return this.fileManager.getTotalSize(); + }, + getFilesCount: function (includeInitial) { + var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount(); + if (includeInitial) { + len += self.previewCache.count(true); + } + return self._getFileCount(len); + }, + _initCapStatus: function (status) { + var self = this, $cap = self.$caption; + $cap.removeClass('is-valid file-processing'); + if (!status) { + return; + } + if (status === 'processing') { + $cap.addClass('file-processing'); + } else { + $cap.addClass('is-valid'); + } + }, + _setLoading: function (type) { + var self = this; + self.$previewStatus.html(type === 'hide' ? '' : self.msgProcessing); + self.$container.removeClass('file-thumb-loading'); + self._initCapStatus(type === 'hide' ? '' : 'processing'); + if (type !== 'hide') { + if (self.dropZoneEnabled) { + self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove(); + } + self.$container.addClass('file-thumb-loading'); + } + }, + _initFileSelected: function () { + var self = this, $el = self.$element, $body = $(document.body), ev = 'focusin.fileinput focusout.fileinput'; + if ($body.length) { + $body.off(ev).on('focusout.fileinput', function () { + self._setLoading('show'); + }).on('focusin.fileinput', function () { + setTimeout(function () { + if (!$el.val()) { + self._setLoading('hide'); + self._setFileDropZoneTitle(); + } + $body.off(ev); + }, 2500); + }); + } else { + self._setLoading('hide'); + } + }, + readFiles: function (files) { + this.reader = new FileReader(); + var self = this, reader = self.reader, $container = self.$previewContainer, + $status = self.$previewStatus, msgLoading = self.msgLoading, msgProgress = self.msgProgress, + previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings, + readFile, fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0, + fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '), + throwError = function (msg, file, previewId, index, fileId) { + var $thumb, p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files), + {id: previewId, index: index, fileId: fileId}), + p2 = {id: previewId, index: index, fileId: fileId, file: file, files: files}; + self._previewDefault(file, true); + $thumb = self._getFrame(previewId, true); + self._setLoading('hide'); + if (self.isAjaxUpload) { + setTimeout(function () { + readFile(index + 1); + }, self.processDelay); + } else { + self.unlock(); + numFiles = 0; + } + if (self.removeFromPreviewOnError && $thumb.length) { + $thumb.remove(); + } else { + self._initFileActions(); + $thumb.find('.kv-file-upload').remove(); + } + self.isPersistentError = true; + self.isError = self.isAjaxUpload ? self._showFileError(msg, p1) : self._showError(msg, p2); + self._updateFileDetails(numFiles); + }; + self.fileManager.clearImages(); + $.each(files, function (key, file) { + var func = self.fileTypeSettings.image; + if (func && func(file.type)) { + self.fileManager.totalImages++; + } + }); + readFile = function (i) { + var $error = self.$errorContainer, errors, fm = self.fileManager; + if (i >= numFiles) { + self.unlock(); + if (self.duplicateErrors.length) { + errors = '
  • ' + self.duplicateErrors.join('
  • ') + '
  • '; + if ($error.find('ul').length === 0) { + $h.setHtml($error, self.errorCloseButton + '
      ' + errors + '
    '); + } else { + $error.find('ul').append(errors); + } + $error.fadeIn(self.fadeDelay); + self._handler($error.find('.kv-error-close'), 'click', function () { + $error.fadeOut(self.fadeDelay); + }); + self.duplicateErrors = []; + } + if (self.isAjaxUpload) { + self._raise('filebatchselected', [fm.stack]); + if (fm.count() === 0 && !self.isError) { + self.reset(); + } + } else { + self._raise('filebatchselected', [files]); + } + $container.removeClass('file-thumb-loading'); + self._initCapStatus('valid'); + $status.html(''); + return; + } + self.lock(true); + var file = files[i], id = self._getFileId(file), previewId = previewInitId + '-' + id, fSizeKB, j, msg, + fnImage = settings.image, typ, chk, typ1, typ2, + caption = self._getFileName(file, ''), fileSize = (file && file.size || 0) / self.bytesToKB, + fileExtExpr = '', previewData = $h.createObjectURL(file), fileCount = 0, + strTypes = '', fileId, canLoad, fileReaderAborted = false, + func, knownTypes = 0, isImage, txtFlag, processFileLoaded = function () { + var isImageResized = !!fm.loadedImages[id], msg = msgProgress.setTokens({ + 'index': i + 1, + 'files': numFiles, + 'percent': 50, + 'name': caption + }); + setTimeout(function () { + $status.html(msg); + self._updateFileDetails(numFiles); + readFile(i + 1); + }, self.processDelay); + if (self._raise('fileloaded', [file, previewId, id, i, reader]) && self.isAjaxUpload) { + if (!isImageResized) { + fm.add(file); + } + } else { + if (isImageResized) { + fm.removeFile(id); + } + } + }; + if (!file) { + return; + } + fileId = fm.getId(file); + if (typLen > 0) { + for (j = 0; j < typLen; j++) { + typ1 = fileTypes[j]; + typ2 = self.msgFileTypes[typ1] || typ1; + strTypes += j === 0 ? typ2 : ', ' + typ2; + } + } + if (caption === false) { + readFile(i + 1); + return; + } + if (caption.length === 0) { + msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode($h.getFileName(file), '[unknown]')); + throwError(msg, file, previewId, i, fileId); + return; + } + if (!$h.isEmpty(fileExt)) { + fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i'); + } + fSizeKB = fileSize.toFixed(2); + if (self.isAjaxUpload && fm.exists(fileId) || self._getFrame(previewId, true).length) { + var p2 = {id: previewId, index: i, fileId: fileId, file: file, files: files}; + msg = self.msgDuplicateFile.setTokens({name: caption, size: fSizeKB}); + if (self.isAjaxUpload) { + self.duplicateErrors.push(msg); + self.isDuplicateError = true; + self._raise('fileduplicateerror', [file, fileId, caption, fSizeKB, previewId, i]); + readFile(i + 1); + self._updateFileDetails(numFiles); + } else { + self._showError(msg, p2); + self.unlock(); + numFiles = 0; + self._clearFileInput(); + self.reset(); + self._updateFileDetails(numFiles); + } + return; + } + if (self.maxFileSize > 0 && fileSize > self.maxFileSize) { + msg = self.msgSizeTooLarge.setTokens({ + 'name': caption, + 'size': fSizeKB, + 'maxSize': self.maxFileSize + }); + throwError(msg, file, previewId, i, fileId); + return; + } + if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) { + msg = self.msgSizeTooSmall.setTokens({ + 'name': caption, + 'size': fSizeKB, + 'minSize': self.minFileSize + }); + throwError(msg, file, previewId, i, fileId); + return; + } + if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) { + for (j = 0; j < fileTypes.length; j += 1) { + typ = fileTypes[j]; + func = settings[typ]; + fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type, + $h.getFileName(file)) ? 1 : 0); + } + if (fileCount === 0) { + msg = self.msgInvalidFileType.setTokens({name: caption, types: strTypes}); + throwError(msg, file, previewId, i, fileId); + return; + } + } + if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) { + chk = $h.compare(caption, fileExtExpr); + fileCount += $h.isEmpty(chk) ? 0 : chk.length; + if (fileCount === 0) { + msg = self.msgInvalidFileExtension.setTokens({name: caption, extensions: strExt}); + throwError(msg, file, previewId, i, fileId); + return; + } + } + if (!self._canPreview(file)) { + canLoad = self.isAjaxUpload && self._raise('filebeforeload', [file, i, reader]); + if (self.isAjaxUpload && canLoad) { + fm.add(file); + } + if (self.showPreview && canLoad) { + $container.addClass('file-thumb-loading'); + self._initCapStatus('processing'); + self._previewDefault(file); + self._initFileActions(); + } + setTimeout(function () { + if (canLoad) { + self._updateFileDetails(numFiles); + } + readFile(i + 1); + self._raise('fileloaded', [file, previewId, id, i]); + }, 10); + return; + } + isImage = fnImage(file.type, caption); + $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles)); + $container.addClass('file-thumb-loading'); + self._initCapStatus('processing'); + reader.onerror = function (evt) { + self._errorHandler(evt, caption); + }; + reader.onload = function (theFile) { + var hex, fileInfo, uint, byte, bytes = [], contents, mime, readImage = function () { + var newReader = new FileReader(); + newReader.onerror = function (theFileNew) { + self._errorHandler(theFileNew, caption); + }; + newReader.onload = function (theFileNew) { + if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) { + fileReaderAborted = true; + self._resetCaption(); + reader.abort(); + $status.html(''); + $container.removeClass('file-thumb-loading'); + self._initCapStatus('valid'); + self.enable(); + return; + } + self._previewFile(i, file, theFileNew, previewData, fileInfo); + self._initFileActions(); + processFileLoaded(); + }; + newReader.readAsDataURL(file); + }; + fileInfo = {'name': caption, 'type': file.type}; + $.each(settings, function (k, f) { + if (k !== 'object' && k !== 'other' && typeof f === 'function' && f(file.type, caption)) { + knownTypes++; + } + }); + if (knownTypes === 0) { // auto detect mime types from content if no known file types detected + uint = new Uint8Array(theFile.target.result); + for (j = 0; j < uint.length; j++) { + byte = uint[j].toString(16); + bytes.push(byte); + } + hex = bytes.join('').toLowerCase().substring(0, 8); + mime = $h.getMimeType(hex, '', ''); + if ($h.isEmpty(mime)) { // look for ascii text content + contents = $h.arrayBuffer2String(reader.result); + mime = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type); + } + fileInfo = {'name': caption, 'type': mime}; + isImage = fnImage(mime, ''); + if (isImage) { + readImage(txtFlag); + return; + } + } + if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) { + fileReaderAborted = true; + self._resetCaption(); + reader.abort(); + $status.html(''); + $container.removeClass('file-thumb-loading'); + self._initCapStatus('valid'); + self.enable(); + return; + } + self._previewFile(i, file, theFile, previewData, fileInfo); + self._initFileActions(); + processFileLoaded(); + }; + reader.onprogress = function (data) { + if (data.lengthComputable) { + var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact); + msg = msgProgress.setTokens({ + 'index': i + 1, + 'files': numFiles, + 'percent': progress, + 'name': caption + }); + setTimeout(function () { + if (!fileReaderAborted) { + $status.html(msg); + } + }, self.processDelay); + } + }; + if (isImage) { + reader.readAsDataURL(file); + } else { + reader.readAsArrayBuffer(file); + } + }; + + readFile(0); + self._updateFileDetails(numFiles); + }, + lock: function (selectMode) { + var self = this, $container = self.$container; + self._resetErrors(); + self.disable(); + if (!selectMode && self.showCancel) { + $container.find('.fileinput-cancel').show(); + } + if (!selectMode && self.showPause) { + $container.find('.fileinput-pause').show(); + } + self._initCapStatus('processing'); + self._raise('filelock', [self.fileManager.stack, self._getExtraData()]); + return self.$element; + }, + unlock: function (reset) { + var self = this, $container = self.$container; + if (reset === undefined) { + reset = true; + } + self.enable(); + $container.removeClass('is-locked'); + if (self.showCancel) { + $container.find('.fileinput-cancel').hide(); + } + if (self.showPause) { + $container.find('.fileinput-pause').hide(); + } + if (reset) { + self._resetFileStack(); + } + self._initCapStatus(); + self._raise('fileunlock', [self.fileManager.stack, self._getExtraData()]); + return self.$element; + }, + resume: function () { + var self = this, fm = self.fileManager, flag = false, rm = self.resumableManager; + fm.bpsLog = []; + fm.bps = 0; + if (!self.enableResumableUpload) { + return self.$element; + } + if (self.paused) { + self._toggleResumableProgress(self.progressPauseTemplate, self.msgUploadResume); + } else { + flag = true; + } + self.paused = false; + if (flag) { + self._toggleResumableProgress(self.progressInfoTemplate, self.msgUploadBegin); + } + setTimeout(function () { + rm.upload(); + }, self.processDelay); + return self.$element; + }, + paste: function (e) { + var self = this, ev = e.originalEvent, files = ev.clipboardData && ev.clipboardData.files || null; + if (files) { + self._dropFiles(e, files); + } + return self.$element; + }, + pause: function () { + var self = this, rm = self.resumableManager, xhr = self.ajaxRequests, len = xhr.length, i, + pct = rm.getProgress(), actions = self.fileActionSettings, tm = self.taskManager, + pool = tm.getPool(rm.id); + if (!self.enableResumableUpload) { + return self.$element; + } else { + if (pool) { + pool.cancel(); + } + } + self._raise('fileuploadpaused', [self.fileManager, rm]); + if (len > 0) { + for (i = 0; i < len; i += 1) { + self.paused = true; + xhr[i].abort(); + } + } + if (self.showPreview) { + self._getThumbs().each(function () { + var $thumb = $(this), t = self._getLayoutTemplate('stats'), stats, + $indicator = $thumb.find('.file-upload-indicator'); + $thumb.removeClass('file-uploading'); + if ($indicator.attr('title') === actions.indicatorLoadingTitle) { + self._setThumbStatus($thumb, 'Paused'); + stats = t.setTokens({pendingTime: self.msgPaused, uploadSpeed: ''}); + self.paused = true; + self._setProgress(pct, $thumb.find('.file-thumb-progress'), pct + '%', stats); + } + if (!self._getThumbFile($thumb)) { + $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled'); + } + }); + } + self._setProgress(101, self.$progress, self.msgPaused); + return self.$element; + }, + cancel: function () { + var self = this, xhr = self.ajaxRequests, + rm = self.resumableManager, tm = self.taskManager, + pool = rm ? tm.getPool(rm.id) : undefined, len = xhr.length, i; + + if (self.enableResumableUpload && pool) { + pool.cancel().done(function () { + self._setProgressCancelled(); + }); + rm.reset(); + self._raise('fileuploadcancelled', [self.fileManager, rm]); + } else { + self._raise('fileuploadcancelled', [self.fileManager]); + } + self._initAjax(); + if (len > 0) { + for (i = 0; i < len; i += 1) { + self.cancelling = true; + xhr[i].abort(); + } + } + self._getThumbs().each(function () { + var $thumb = $(this), $prog = $thumb.find('.file-thumb-progress'); + $thumb.removeClass('file-uploading'); + self._setProgress(0, $prog); + $prog.hide(); + if (!self._getThumbFile($thumb)) { + $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled'); + $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled'); + } + self.unlock(); + }); + setTimeout(function () { + self._setProgressCancelled(); + }, self.processDelay); + return self.$element; + }, + clear: function () { + var self = this, cap; + if (!self._raise('fileclear')) { + return; + } + self.$btnUpload.removeAttr('disabled'); + self._getThumbs().find('video,audio,img').each(function () { + $h.cleanMemory($(this)); + }); + self._clearFileInput(); + self._resetUpload(); + self.clearFileStack(); + self.isDuplicateError = false; + self.isPersistentError = false; + self._resetErrors(true); + if (self._hasInitialPreview()) { + self._showFileIcon(); + self._resetPreview(); + self._initPreviewActions(); + self.$container.removeClass('file-input-new'); + } else { + self._getThumbs().each(function () { + self._clearObjects($(this)); + }); + if (self.isAjaxUpload) { + self.previewCache.data = {}; + } + self.$preview.html(''); + cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : ''; + self.$caption.attr('title', '').val(cap); + $h.addCss(self.$container, 'file-input-new'); + self._validateDefaultPreview(); + } + if (self.$container.find($h.FRAMES).length === 0) { + if (!self._initCaption()) { + self.$captionContainer.removeClass('icon-visible'); + } + } + self._hideFileIcon(); + if (self.focusCaptionOnClear) { + self.$captionContainer.focus(); + } + self._setFileDropZoneTitle(); + self._raise('filecleared'); + return self.$element; + }, + reset: function () { + var self = this; + if (!self._raise('filereset')) { + return; + } + self.lastProgress = 0; + self._resetPreview(); + self.$container.find('.fileinput-filename').text(''); + $h.addCss(self.$container, 'file-input-new'); + if (self.getFrames().length) { + self.$container.removeClass('file-input-new'); + } + self.clearFileStack(); + self._setFileDropZoneTitle(); + return self.$element; + }, + disable: function () { + var self = this, $container = self.$container; + self.isDisabled = true; + self._raise('filedisabled'); + self.$element.attr('disabled', 'disabled'); + $container.addClass('is-locked'); + $h.addCss($container.find('.btn-file'), 'disabled'); + $container.find('.kv-fileinput-caption').addClass('file-caption-disabled'); + $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button') + .attr('disabled', true); + self._initDragDrop(); + return self.$element; + }, + enable: function () { + var self = this, $container = self.$container; + self.isDisabled = false; + self._raise('fileenabled'); + self.$element.removeAttr('disabled'); + $container.removeClass('is-locked'); + $container.find('.kv-fileinput-caption').removeClass('file-caption-disabled'); + $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button') + .removeAttr('disabled'); + $container.find('.btn-file').removeClass('disabled'); + self._initDragDrop(); + return self.$element; + }, + upload: function () { + var self = this, fm = self.fileManager, totLen = fm.count(), i, outData, + hasExtraData = !$.isEmptyObject(self._getExtraData()); + fm.bpsLog = []; + fm.bps = 0; + if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) { + return; + } + self.lastProgress = 0; + self._resetUpload(); + if (totLen === 0 && !hasExtraData) { + self._showFileError(self.msgUploadEmpty); + return; + } + self.cancelling = false; + self._showProgress(); + self.lock(); + if (totLen === 0 && hasExtraData) { + self._setProgress(2); + self._uploadExtraOnly(); + return; + } + if (self.enableResumableUpload) { + return self.resume(); + } + if (self.uploadAsync || self.enableResumableUpload) { + outData = self._getOutData(null); + if (!self._checkBatchPreupload(outData)) { + return; + } + self.fileBatchCompleted = false; + self.uploadCache = []; + $.each(self.getFileStack(), function (id) { + var previewId = self._getThumbId(id); + self.uploadCache.push({id: previewId, content: null, config: null, tags: null, append: true}); + }); + self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS); + self._initSortable(); + } + self._setProgress(2); + self.hasInitData = false; + if (self.uploadAsync) { + i = 0; + $.each(self.getFileStack(), function (id) { + self._uploadSingle(i, id, true); + i++; + }); + return; + } + self._uploadBatch(); + return self.$element; + }, + destroy: function () { + var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace; + $(document).off(ns); + $(window).off(ns); + if ($form && $form.length) { + $form.off(ns); + } + if (self.isAjaxUpload) { + self._clearFileInput(); + } + self._cleanup(); + self._initPreviewCache(); + $el.insertBefore($cont).off(ns).removeData(); + $cont.off().remove(); + return $el; + }, + refresh: function (options) { + var self = this, $el = self.$element; + if (typeof options !== 'object' || $h.isEmpty(options)) { + options = self.options; + } else { + options = $.extend(true, {}, self.options, options); + } + self._init(options, true); + self._listen(); + return $el; + }, + zoom: function (frameId) { + var self = this, $frame = self._getFrame(frameId); + self._showModal($frame); + }, + getExif: function (frameId) { + var self = this, $frame = self._getFrame(frameId); + return $frame && $frame.data('exif') || null; + }, + getFrames: function (cssFilter) { + var self = this, $frames; + cssFilter = cssFilter || ''; + $frames = self.$preview.find($h.FRAMES + cssFilter); + if (self.reversePreviewOrder) { + $frames = $($frames.get().reverse()); + } + return $frames; + }, + getPreview: function () { + var self = this; + return { + content: self.initialPreview, + config: self.initialPreviewConfig, + tags: self.initialPreviewThumbTags + }; + } + }; + + $.fn.fileinput = function (option) { + if (!$h.hasFileAPISupport() && !$h.isIE(9)) { + return; + } + var args = Array.apply(null, arguments), retvals = []; + args.shift(); + this.each(function () { + var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option, + theme = options.theme || self.data('theme'), l = {}, t = {}, + lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt; + if (!data) { + if (theme) { + t = $.fn.fileinputThemes[theme] || {}; + } + if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) { + l = $.fn.fileinputLocales[lang] || {}; + } + opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data()); + data = new FileInput(this, opt); + self.data('fileinput', data); + } + + if (typeof option === 'string') { + retvals.push(data[option].apply(data, args)); + } + }); + switch (retvals.length) { + case 0: + return this; + case 1: + return retvals[0]; + default: + return retvals; + } + }; + + var IFRAME_ATTRIBS = 'class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}', + defBtnCss1 = 'btn btn-sm btn-kv ' + $h.defaultButtonCss(), defBtnCss2 = 'btn ' + $h.defaultButtonCss(true); + + $.fn.fileinput.defaults = { + language: 'zh', + bytesToKB: 1024, + showCaption: true, + showBrowse: true, + showPreview: true, + showRemove: true, + showUpload: true, + showUploadStats: true, + showCancel: null, + showPause: null, + showClose: true, + showUploadedThumbs: true, + showConsoleLogs: false, + browseOnZoneClick: false, + autoReplace: false, + showDescriptionClose: true, + autoOrientImage: function () { // applicable for JPEG images only and non ios safari + var ua = window.navigator.userAgent, webkit = !!ua.match(/WebKit/i), + iOS = !!ua.match(/iP(od|ad|hone)/i), iOSSafari = iOS && webkit && !ua.match(/CriOS/i); + return !iOSSafari; + }, + autoOrientImageInitial: true, + required: false, + rtl: false, + hideThumbnailContent: false, + encodeUrl: true, + focusCaptionOnBrowse: true, + focusCaptionOnClear: true, + generateFileId: null, + previewClass: '', + captionClass: '', + frameClass: 'krajee-default', + mainClass: '', + inputGroupClass: '', + mainTemplate: null, + fileSizeGetter: null, + initialCaption: '', + initialPreview: [], + initialPreviewDelimiter: '*$$*', + initialPreviewAsData: false, + initialPreviewFileType: 'image', + initialPreviewConfig: [], + initialPreviewThumbTags: [], + previewThumbTags: {}, + initialPreviewShowDelete: true, + initialPreviewDownloadUrl: '', + removeFromPreviewOnError: false, + deleteUrl: '', + deleteExtraData: {}, + overwriteInitial: true, + sanitizeZoomCache: function (content) { + var $container = $h.createElement(content); + $container.find('input,textarea,select,datalist,form,.file-thumbnail-footer').remove(); + return $container.html(); + }, + previewZoomButtonIcons: { + prev: '', + next: '', + toggleheader: '', + fullscreen: '', + borderless: '', + close: '' + }, + previewZoomButtonClasses: { + prev: 'btn btn-default btn-outline-secondary btn-navigate', + next: 'btn btn-default btn-outline-secondary btn-navigate', + toggleheader: defBtnCss1, + fullscreen: defBtnCss1, + borderless: defBtnCss1, + close: defBtnCss1 + }, + previewTemplates: {}, + previewContentTemplates: {}, + preferIconicPreview: false, + preferIconicZoomPreview: false, + allowedFileTypes: null, + allowedFileExtensions: null, + allowedPreviewTypes: undefined, + allowedPreviewMimeTypes: null, + allowedPreviewExtensions: null, + disabledPreviewTypes: undefined, + disabledPreviewExtensions: ['msi', 'exe', 'com', 'zip', 'rar', 'app', 'vb', 'scr'], + disabledPreviewMimeTypes: null, + defaultPreviewContent: null, + customLayoutTags: {}, + customPreviewTags: {}, + previewFileIcon: '', + previewFileIconClass: 'file-other-icon', + previewFileIconSettings: {}, + previewFileExtSettings: {}, + buttonLabelClass: 'hidden-xs', + browseIcon: ' ', + browseClass: 'btn btn-primary', + removeIcon: '', + removeClass: defBtnCss2, + cancelIcon: '', + cancelClass: defBtnCss2, + pauseIcon: '', + pauseClass: defBtnCss2, + uploadIcon: '', + uploadClass: defBtnCss2, + uploadUrl: null, + uploadUrlThumb: null, + uploadAsync: true, + uploadParamNames: { + chunkCount: 'chunkCount', + chunkIndex: 'chunkIndex', + chunkSize: 'chunkSize', + chunkSizeStart: 'chunkSizeStart', + chunksUploaded: 'chunksUploaded', + fileBlob: 'fileBlob', + fileId: 'fileId', + fileName: 'fileName', + fileRelativePath: 'fileRelativePath', + fileSize: 'fileSize', + retryCount: 'retryCount' + }, + maxAjaxThreads: 5, + fadeDelay: 800, + processDelay: 100, + bitrateUpdateDelay: 500, + queueDelay: 10, // must be lesser than process delay + progressDelay: 0, // must be lesser than process delay + enableResumableUpload: false, + resumableUploadOptions: { + fallback: null, + testUrl: null, // used for checking status of chunks/ files previously / partially uploaded + chunkSize: 2048, // in KB + maxThreads: 4, + maxRetries: 3, + showErrorLog: true, + retainErrorHistory: true, // display complete error history always unless user explicitly resets upload + skipErrorsAndProceed: false // when set to true, files with errors will be skipped and upload will continue with other files + }, + uploadExtraData: {}, + zoomModalHeight: 480, + minImageWidth: null, + minImageHeight: null, + maxImageWidth: null, + maxImageHeight: null, + resizeImage: false, + resizePreference: 'width', + resizeQuality: 0.92, + resizeDefaultImageType: 'image/jpeg', + resizeIfSizeMoreThan: 0, // in KB + minFileSize: -1, + maxFileSize: 0, + maxFilePreviewSize: 25600, // 25 MB + minFileCount: 0, + maxFileCount: 0, + maxTotalFileCount: 0, + validateInitialCount: false, + msgValidationErrorClass: 'text-danger', + msgValidationErrorIcon: ' ', + msgErrorClass: 'file-error-message', + progressThumbClass: 'progress-bar progress-bar-striped active progress-bar-animated', + progressClass: 'progress-bar bg-success progress-bar-success progress-bar-striped active progress-bar-animated', + progressInfoClass: 'progress-bar bg-info progress-bar-info progress-bar-striped active progress-bar-animated', + progressCompleteClass: 'progress-bar bg-success progress-bar-success', + progressPauseClass: 'progress-bar bg-primary progress-bar-primary progress-bar-striped active progress-bar-animated', + progressErrorClass: 'progress-bar bg-danger progress-bar-danger', + progressUploadThreshold: 99, + previewFileType: 'image', + elCaptionContainer: null, + elCaptionText: null, + elPreviewContainer: null, + elPreviewImage: null, + elPreviewStatus: null, + elErrorContainer: null, + errorCloseButton: undefined, + slugCallback: null, + dropZoneEnabled: true, + dropZoneTitleClass: 'file-drop-zone-title', + fileActionSettings: {}, + otherActionButtons: '', + textEncoding: 'UTF-8', + preProcessUpload: null, + ajaxSettings: {}, + ajaxDeleteSettings: {}, + showAjaxErrorDetails: true, + mergeAjaxCallbacks: false, + mergeAjaxDeleteCallbacks: false, + retryErrorUploads: true, + reversePreviewOrder: false, + usePdfRenderer: function () { + var isIE11 = !!window.MSInputMethodContext && !!document.documentMode; + return !!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i) || isIE11; + }, + pdfRendererUrl: '', + pdfRendererTemplate: '', + tabIndexConfig: { + browse: 500, + remove: 500, + upload: 500, + cancel: null, + pause: null, + modal: -1 + } + }; + + // noinspection HtmlUnknownAttribute + $.fn.fileinputLocales.en = { + sizeUnits: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], + bitRateUnits: ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s', 'PB/s', 'EB/s', 'ZB/s', 'YB/s'], + fileSingle: 'file', + filePlural: 'files', + browseLabel: 'Browse …', + removeLabel: 'Remove', + removeTitle: 'Clear all unprocessed files', + cancelLabel: 'Cancel', + cancelTitle: 'Abort ongoing upload', + pauseLabel: 'Pause', + pauseTitle: 'Pause ongoing upload', + uploadLabel: 'Upload', + uploadTitle: 'Upload selected files', + msgNo: 'No', + msgNoFilesSelected: 'No files selected', + msgCancelled: 'Cancelled', + msgPaused: 'Paused', + msgPlaceholder: 'Select {files} ...', + msgZoomModalHeading: 'Detailed Preview', + msgFileRequired: 'You must select a file to upload.', + msgSizeTooSmall: 'File "{name}" ({size} KB) is too small and must be larger than {minSize} KB.', + msgSizeTooLarge: 'File "{name}" ({size} KB) exceeds maximum allowed upload size of {maxSize} KB.', + msgFilesTooLess: 'You must select at least {n} {files} to upload.', + msgFilesTooMany: 'Number of files selected for upload ({n}) exceeds maximum allowed limit of {m}.', + msgTotalFilesTooMany: 'You can upload a maximum of {m} files ({n} files detected).', + msgFileNotFound: 'File "{name}" not found!', + msgFileSecured: 'Security restrictions prevent reading the file "{name}".', + msgFileNotReadable: 'File "{name}" is not readable.', + msgFilePreviewAborted: 'File preview aborted for "{name}".', + msgFilePreviewError: 'An error occurred while reading the file "{name}".', + msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".', + msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.', + msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.', + msgFileTypes: { + 'image': 'image', + 'html': 'HTML', + 'text': 'text', + 'video': 'video', + 'audio': 'audio', + 'flash': 'flash', + 'pdf': 'PDF', + 'object': 'object' + }, + msgUploadAborted: 'The file upload was aborted', + msgUploadThreshold: 'Processing …', + msgUploadBegin: 'Initializing …', + msgUploadEnd: 'Done', + msgUploadResume: 'Resuming upload …', + msgUploadEmpty: 'No valid data available for upload.', + msgUploadError: 'Upload Error', + msgDeleteError: 'Delete Error', + msgProgressError: 'Error', + msgValidationError: 'Validation Error', + msgLoading: 'Loading file {index} of {files} …', + msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.', + msgSelected: '{n} {files} selected', + msgProcessing: 'Processing ...', + msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.', + msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.', + msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.', + msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.', + msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.', + msgImageResizeError: 'Could not get the image dimensions to resize.', + msgImageResizeException: 'Error while resizing the image.
    {errors}
    ', + msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!', + msgAjaxProgressError: '{operation} failed', + msgDuplicateFile: 'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.', + msgResumableUploadRetriesExceeded: 'Upload aborted beyond {max} retries for file {file}! Error Details:
    {error}
    ', + msgPendingTime: '{time} remaining', + msgCalculatingTime: 'calculating time remaining', + ajaxOperations: { + deleteThumb: 'file delete', + uploadThumb: 'file upload', + uploadBatch: 'batch file upload', + uploadExtra: 'form data upload' + }, + dropZoneTitle: 'Drag & drop files here …', + dropZoneClickTitle: '
    (or click to select {files})', + previewZoomButtonTitles: { + prev: 'View previous file', + next: 'View next file', + toggleheader: 'Toggle header', + fullscreen: 'Toggle full screen', + borderless: 'Toggle borderless mode', + close: 'Close detailed preview' + } + }; + + $.fn.fileinputLocales.zh = { + sizeUnits: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], + bitRateUnits: ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s', 'PB/s', 'EB/s', 'ZB/s', 'YB/s'], + fileSingle: '文件', + filePlural: '个文件', + browseLabel: '选择 …', + removeLabel: '移除', + removeTitle: '清除选中文件', + cancelLabel: '取消', + cancelTitle: '取消进行中的上传', + pauseLabel: '暂停', + pauseTitle: '暂停上传', + uploadLabel: '上传', + uploadTitle: '上传选中文件', + msgNo: '没有', + msgNoFilesSelected: '未选择文件', + msgPaused: '已暂停', + msgCancelled: '取消', + msgPlaceholder: '选择 {files} ...', + msgZoomModalHeading: '详细预览', + msgFileRequired: '必须选择一个文件上传.', + msgSizeTooSmall: '文件 "{name}" ({size} KB) 必须大于限定大小 {minSize} KB.', + msgSizeTooLarge: '文件 "{name}" ({size} KB) 超过了允许大小 {maxSize} KB.', + msgFilesTooLess: '你必须选择最少 {n} {files} 来上传. ', + msgFilesTooMany: '选择的上传文件个数 ({n}) 超出最大文件的限制个数 {m}.', + msgTotalFilesTooMany: '你最多可以上传 {m} 个文件 (当前有{n} 个文件).', + msgFileNotFound: '文件 "{name}" 未找到!', + msgFileSecured: '安全限制,为了防止读取文件 "{name}".', + msgFileNotReadable: '文件 "{name}" 不可读.', + msgFilePreviewAborted: '取消 "{name}" 的预览.', + msgFilePreviewError: '读取 "{name}" 时出现了一个错误.', + msgInvalidFileName: '文件名 "{name}" 包含非法字符.', + msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.', + msgInvalidFileExtension: '不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.', + msgFileTypes: { + 'image': 'image', + 'html': 'HTML', + 'text': 'text', + 'video': 'video', + 'audio': 'audio', + 'flash': 'flash', + 'pdf': 'PDF', + 'object': 'object' + }, + msgUploadAborted: '该文件上传被中止', + msgUploadThreshold: '处理中 …', + msgUploadBegin: '正在初始化 …', + msgUploadEnd: '完成', + msgUploadResume: '继续上传 …', + msgUploadEmpty: '无效的文件上传.', + msgUploadError: '上传出错', + msgDeleteError: '删除出错', + msgProgressError: '上传出错', + msgValidationError: '验证错误', + msgLoading: '加载第 {index} 文件 共 {files} …', + msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.', + msgSelected: '{n} {files} 选中', + msgProcessing: '处理中 ...', + msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.', + msgImageWidthSmall: '图像文件的"{name}"的宽度必须是至少{size}像素.', + msgImageHeightSmall: '图像文件的"{name}"的高度必须至少为{size}像素.', + msgImageWidthLarge: '图像文件"{name}"的宽度不能超过{size}像素.', + msgImageHeightLarge: '图像文件"{name}"的高度不能超过{size}像素.', + msgImageResizeError: '无法获取的图像尺寸调整。', + msgImageResizeException: '调整图像大小时发生错误。
    {errors}
    ', + msgAjaxError: '{operation} 发生错误. 请重试!', + msgAjaxProgressError: '{operation} 失败', + msgDuplicateFile: '文件 "{name}",大小 "{size} KB" 已经被选中.忽略相同的文件.', + msgResumableUploadRetriesExceeded: '文件 {file} 上传失败超过 {max} 次重试 ! 错误详情:
    {error}
    ', + msgPendingTime: '{time} 剩余', + msgCalculatingTime: '计算剩余时间', + ajaxOperations: { + deleteThumb: '删除文件', + uploadThumb: '上传文件', + uploadBatch: '批量上传', + uploadExtra: '表单数据上传' + }, + dropZoneTitle: '拖拽文件到这里 …
    支持多文件同时上传', + dropZoneClickTitle: '
    (或点击{files}按钮选择文件)', + fileActionSettings: { + removeTitle: '删除文件', + uploadTitle: '上传文件', + downloadTitle: '下载文件', + uploadRetryTitle: '重试', + zoomTitle: '查看详情', + dragTitle: '移动 / 重置', + indicatorNewTitle: '没有上传', + indicatorSuccessTitle: '上传', + indicatorErrorTitle: '上传错误', + indicatorPausedTitle: '上传已暂停', + indicatorLoadingTitle: '上传 …' + }, + previewZoomButtonTitles: { + prev: '预览上一个文件', + next: '预览下一个文件', + toggleheader: '缩放', + fullscreen: '全屏', + borderless: '无边界模式', + close: '关闭当前预览' + } + }; + + $.fn.fileinput.Constructor = FileInput; + + /** + * Convert automatically file inputs with class 'file' into a bootstrap fileinput control. + */ + $(document).ready(function () { + var $input = $('input.file[type=file]'); + if ($input.length) { + $input.fileinput(); + } + }); +})); diff --git a/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.min.css b/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.min.css index 493ce6a0..e7ee75b2 100644 --- a/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.min.css +++ b/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.min.css @@ -1,13 +1,12 @@ /*! - * bootstrap-fileinput v5.1.3 + * bootstrap-fileinput v5.2.3 * http://plugins.krajee.com/file-input * * Krajee default styling for bootstrap-fileinput. * * Author: Kartik Visweswaran - * Copyright: 2014 - 2020, Kartik Visweswaran, Krajee.com + * Copyright: 2014 - 2021, Kartik Visweswaran, Krajee.com * * Licensed under the BSD-3-Clause * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md - */ -.file-loading input[type=file],input[type=file].file-loading{width:0;height:0}.file-no-browse{position:absolute;left:50%;bottom:20%;width:1px;height:1px;font-size:0;opacity:0;border:0;background:0;outline:0;box-shadow:none}.kv-hidden,.file-caption-icon,.file-zoom-dialog .modal-header:before,.file-zoom-dialog .modal-header:after,.file-input-new .file-preview,.file-input-new .close,.file-input-new .glyphicon-file,.file-input-new .fileinput-remove-button,.file-input-new .fileinput-upload-button,.file-input-new .no-browse .input-group-btn,.file-input-ajax-new .fileinput-remove-button,.file-input-ajax-new .fileinput-upload-button,.file-input-ajax-new .no-browse .input-group-btn,.hide-content .kv-file-content,.is-locked .fileinput-upload-button,.is-locked .fileinput-remove-button{display:none}.btn-file input[type=file],.file-caption-icon,.file-preview .fileinput-remove,.krajee-default .file-thumb-progress,.file-zoom-dialog .btn-navigate,.file-zoom-dialog .floating-buttons{position:absolute}.file-caption-icon .kv-caption-icon{line-height:inherit}.file-input,.file-loading:before,.btn-file,.file-caption,.file-preview,.krajee-default.file-preview-frame,.krajee-default .file-thumbnail-footer,.file-zoom-dialog .modal-dialog{position:relative}.file-error-message pre,.file-error-message ul,.krajee-default .file-actions,.krajee-default .file-other-error{text-align:left}.file-error-message pre,.file-error-message ul{margin:0}.krajee-default .file-drag-handle,.krajee-default .file-upload-indicator{float:left;margin-top:10px;width:16px;height:16px}.file-thumb-progress .progress,.file-thumb-progress .progress-bar{font-family:Verdana,Helvetica,sans-serif;font-size:.7rem}.krajee-default .file-thumb-progress .progress,.kv-upload-progress .progress{background-color:#ccc}.krajee-default .file-caption-info,.krajee-default .file-size-info{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;width:160px;height:15px;margin:auto}.file-zoom-content>.file-object.type-video,.file-zoom-content>.file-object.type-flash,.file-zoom-content>.file-object.type-image{max-width:100%;max-height:100%;width:auto}.file-zoom-content>.file-object.type-video,.file-zoom-content>.file-object.type-flash{height:100%}.file-zoom-content>.file-object.type-pdf,.file-zoom-content>.file-object.type-html,.file-zoom-content>.file-object.type-text,.file-zoom-content>.file-object.type-default{width:100%}.file-loading:before{content:" Loading...";display:inline-block;padding-left:20px;line-height:16px;font-size:13px;font-variant:small-caps;color:#999;background:transparent url(loading.gif) top left no-repeat}.file-object{margin:0 0 -5px 0;padding:0}.btn-file{overflow:hidden}.btn-file input[type=file]{top:0;left:0;min-width:100%;min-height:100%;text-align:right;opacity:0;background:none repeat scroll 0 0 transparent;cursor:inherit;display:block}.btn-file ::-ms-browse{font-size:10000px;width:100%;height:100%}.file-caption .file-caption-name{width:100%;margin:0;padding:0;box-shadow:none;border:0;background:0;outline:0}.file-caption.icon-visible .file-caption-icon{display:inline-block}.file-caption.icon-visible .file-caption-name{padding-left:15px}.file-caption-icon{left:8px}.file-error-message{color:#a94442;background-color:#f2dede;margin:5px;border:1px solid #ebccd1;border-radius:4px;padding:15px}.file-error-message pre{margin:5px 0}.file-caption-disabled{background-color:#eee;cursor:not-allowed;opacity:1}.file-preview{border-radius:5px;border:1px solid #ddd;padding:8px;width:100%;margin-bottom:5px}.file-preview .btn-xs{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.file-preview .fileinput-remove{top:1px;right:1px;line-height:10px}.file-preview .clickable{cursor:pointer}.file-preview-image{font:40px Impact,Charcoal,sans-serif;color:#008000;width:auto;height:auto;max-width:100%;max-height:100%}.krajee-default.file-preview-frame{margin:8px;border:1px solid rgba(0,0,0,0.2);box-shadow:0 0 10px 0 rgba(0,0,0,0.2);padding:6px;float:left;text-align:center}.krajee-default.file-preview-frame .kv-file-content{width:213px;height:160px}.krajee-default .file-preview-other-frame{display:flex;align-items:center;justify-content:center}.krajee-default.file-preview-frame .kv-file-content.kv-pdf-rendered{width:400px}.krajee-default.file-preview-frame[data-template="audio"] .kv-file-content{width:240px;height:55px}.krajee-default.file-preview-frame .file-thumbnail-footer{height:70px}.krajee-default.file-preview-frame:not(.file-preview-error):hover{border:1px solid rgba(0,0,0,0.3);box-shadow:0 0 10px 0 rgba(0,0,0,0.4)}.krajee-default .file-preview-text{color:#428bca;border:1px solid #ddd;outline:0;resize:none}.krajee-default .file-preview-html{border:1px solid #ddd}.krajee-default .file-other-icon{font-size:6em;line-height:1}.krajee-default .file-footer-buttons{float:right}.krajee-default .file-footer-caption{display:block;text-align:center;padding-top:4px;font-size:11px;color:#777;margin-bottom:30px}.file-upload-stats{font-size:10px;text-align:center;width:100%}.kv-upload-progress .file-upload-stats{font-size:12px;margin:-10px 0 5px}.krajee-default .file-preview-error{opacity:.65;box-shadow:none}.krajee-default .file-thumb-progress{top:37px;left:0;right:0}.krajee-default.kvsortable-ghost{background:#e1edf7;border:2px solid #a1abff}.krajee-default .file-preview-other:hover{opacity:.8}.krajee-default .file-preview-frame:not(.file-preview-error) .file-footer-caption:hover{color:#000}.kv-upload-progress .progress{height:20px;margin:10px 0;overflow:hidden}.kv-upload-progress .progress-bar{height:11px;font-family:Verdana,Helvetica,sans-serif}.file-zoom-dialog .file-other-icon{font-size:22em;font-size:50vmin}.file-zoom-dialog .modal-dialog{width:auto}.file-zoom-dialog .modal-header{display:flex;align-items:center;justify-content:space-between}.file-zoom-dialog .btn-navigate{padding:0;margin:-60px 0 0;font-size:60px;background:transparent;text-decoration:none;outline:0;opacity:.7;top:50%;color:#1c94c4}.file-zoom-dialog .btn-navigate:not([disabled]):hover{outline:0;box-shadow:none;opacity:.6}.file-zoom-dialog .floating-buttons{top:5px;right:10px}.file-zoom-dialog .btn-navigate[disabled]{opacity:.3}.file-zoom-dialog .btn-prev{left:1px}.file-zoom-dialog .btn-next{right:1px}.file-zoom-dialog .kv-zoom-title{font-weight:300;color:#999;max-width:50%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.file-input-new .no-browse .form-control{border-top-right-radius:4px;border-bottom-right-radius:4px}.file-input-ajax-new .no-browse .form-control{border-top-right-radius:4px;border-bottom-right-radius:4px}.file-caption-main{width:100%}.file-thumb-loading{background:transparent url(loading.gif) no-repeat scroll center center content-box!important}.file-drop-zone{border:1px dashed #aaa;min-height:260px;border-radius:4px;text-align:center;vertical-align:middle;margin:12px 15px 12px 12px;padding:5px}.file-drop-zone.clickable:hover{border:2px dashed #999}.file-drop-zone.clickable:focus{border:2px solid #5acde2}.file-drop-zone .file-preview-thumbnails{cursor:default}.file-drop-zone-title{color:#aaa;font-size:1.6em;text-align:center;padding:85px 10px;cursor:default}.file-highlighted{border:2px dashed #999!important;background-color:#eee}.file-uploading{background:url(loading-sm.gif) no-repeat center bottom 10px;opacity:.65}.file-zoom-fullscreen .modal-dialog{min-width:100%;margin:0}.file-zoom-fullscreen .modal-content{border-radius:0;box-shadow:none;min-height:100vh}.file-zoom-fullscreen .modal-body{overflow-y:auto}.floating-buttons{z-index:3000}.floating-buttons .btn-kv{margin-left:3px;z-index:3000}.kv-zoom-actions .btn-kv{margin-left:3px}.file-zoom-content{text-align:center;min-height:300px}.file-zoom-content .file-preview-image{max-height:100%}.file-zoom-content .file-preview-video{max-height:100%}.file-zoom-content>.file-object.type-image{height:auto;min-height:inherit}.file-zoom-content>.file-object.type-audio{width:auto;height:30px}@media(min-width:576px){.file-zoom-dialog .modal-dialog{max-width:500px}}@media(min-width:992px){.file-zoom-dialog .modal-lg{max-width:800px}}@media(max-width:767px){.file-preview-thumbnails{display:flex;justify-content:center;align-items:center;flex-direction:column}.file-zoom-dialog .modal-header{flex-direction:column}}@media(max-width:350px){.krajee-default.file-preview-frame:not([data-template="audio"]) .kv-file-content{width:160px}}@media(max-width:420px){.krajee-default.file-preview-frame .kv-file-content.kv-pdf-rendered{width:100%}}.file-loading[dir=rtl]:before{background:transparent url(loading.gif) top right no-repeat;padding-left:0;padding-right:20px}.clickable .file-drop-zone-title{cursor:pointer}.file-sortable .file-drag-handle:hover{opacity:.7}.file-sortable .file-drag-handle{cursor:grab;opacity:1}.file-grabbing,.file-grabbing *{cursor:not-allowed!important}.file-grabbing .file-preview-thumbnails *{cursor:grabbing!important}.file-preview-frame.sortable-chosen{background-color:#d9edf7;border-color:#17a2b8;box-shadow:none!important}.file-preview .kv-zoom-cache{display:none} \ No newline at end of file + */.btn-file input[type=file],.file-caption-icon,.file-no-browse,.file-preview .fileinput-remove,.file-zoom-dialog .btn-navigate,.file-zoom-dialog .floating-buttons,.krajee-default .file-thumb-progress{position:absolute}.file-loading input[type=file],input[type=file].file-loading{width:0;height:0}.file-no-browse{left:50%;bottom:20%;width:1px;height:1px;font-size:0;opacity:0;border:none;background:0 0;outline:0;box-shadow:none}.file-caption-icon,.file-input-ajax-new .fileinput-remove-button,.file-input-ajax-new .fileinput-upload-button,.file-input-ajax-new .no-browse .input-group-btn,.file-input-new .close,.file-input-new .file-preview,.file-input-new .fileinput-remove-button,.file-input-new .fileinput-upload-button,.file-input-new .glyphicon-file,.file-input-new .no-browse .input-group-btn,.file-zoom-dialog .modal-header:after,.file-zoom-dialog .modal-header:before,.hide-content .kv-file-content,.is-locked .fileinput-remove-button,.is-locked .fileinput-upload-button,.kv-hidden{display:none}.file-caption-icon .kv-caption-icon{line-height:inherit}.btn-file,.file-caption,.file-input,.file-loading:before,.file-preview,.file-zoom-dialog .modal-dialog,.krajee-default .file-thumbnail-footer,.krajee-default.file-preview-frame{position:relative}.file-error-message pre,.file-error-message ul,.krajee-default .file-actions,.krajee-default .file-other-error{text-align:left}.file-error-message pre,.file-error-message ul{margin:0}.krajee-default .file-drag-handle,.krajee-default .file-upload-indicator{float:left;margin-top:10px;width:16px;height:16px}.file-thumb-progress .progress,.file-thumb-progress .progress-bar{font-family:Verdana,Helvetica,sans-serif;font-size:.7rem}.krajee-default .file-thumb-progress .progress,.kv-upload-progress .progress{background-color:#ccc}.krajee-default .file-caption-info,.krajee-default .file-size-info{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;width:160px;height:15px;margin:auto}.file-zoom-content>.file-object.type-flash,.file-zoom-content>.file-object.type-image,.file-zoom-content>.file-object.type-video{max-width:100%;max-height:100%;width:auto}.file-zoom-content>.file-object.type-flash,.file-zoom-content>.file-object.type-video{height:100%}.file-zoom-content>.file-object.type-default,.file-zoom-content>.file-object.type-html,.file-zoom-content>.file-object.type-pdf,.file-zoom-content>.file-object.type-text{width:100%}.file-loading:before{content:" Loading...";display:inline-block;padding-left:20px;line-height:16px;font-size:13px;font-variant:small-caps;color:#999;background:url(loading.gif) top left no-repeat}.file-object{margin:0 0 -5px;padding:0}.btn-file{overflow:hidden}.btn-file input[type=file]{top:0;left:0;min-width:100%;min-height:100%;text-align:right;opacity:0;background:none;cursor:inherit;display:block}.btn-file ::-ms-browse{font-size:10000px;width:100%;height:100%}.file-caption.icon-visible .file-caption-icon{display:inline-block}.file-caption.icon-visible .file-caption-name{padding-left:1.875rem}.file-caption.icon-visible>.input-group-lg .file-caption-name{padding-left:2.1rem}.file-caption.icon-visible>.input-group-sm .file-caption-name{padding-left:1.5rem}.file-caption-name:not(.file-caption-disabled){background-color:transparent}.file-caption-name.file-processing{font-style:italic;border-color:#bbb;opacity:.5}.file-caption-icon{padding:.5rem;left:4px}.input-group-lg .file-caption-icon{font-size:1.25rem}.input-group-sm .file-caption-icon{font-size:.875rem;padding:.25rem}.file-error-message{color:#a94442;background-color:#f2dede;margin:5px;border:1px solid #ebccd1;border-radius:4px;padding:15px}.file-error-message pre{margin:5px 0}.file-caption-disabled{background-color:#eee;cursor:not-allowed;opacity:1}.file-preview{border-radius:5px;border:1px solid #ddd;padding:8px;width:100%;margin-bottom:5px}.file-preview .btn-xs{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.file-preview .fileinput-remove{top:1px;right:1px;line-height:10px}.file-preview .clickable{cursor:pointer}.file-preview-image{font:40px Impact,Charcoal,sans-serif;color:green;width:auto;height:auto;max-width:100%;max-height:100%}.krajee-default.file-preview-frame{margin:8px;border:1px solid rgba(0,0,0,.2);box-shadow:0 0 10px 0 rgba(0,0,0,.2);padding:6px;float:left;text-align:center}.krajee-default.file-preview-frame .kv-file-content{width:213px;height:160px}.krajee-default .file-preview-other-frame{display:flex;align-items:center;justify-content:center}.krajee-default.file-preview-frame .kv-file-content.kv-pdf-rendered{width:400px}.krajee-default.file-preview-frame[data-template=audio] .kv-file-content{width:240px;height:55px}.krajee-default.file-preview-frame .file-thumbnail-footer{height:70px}.krajee-default.file-preview-frame:not(.file-preview-error):hover{border:1px solid rgba(0,0,0,.3);box-shadow:0 0 10px 0 rgba(0,0,0,.4)}.krajee-default .file-preview-text{color:#428bca;border:1px solid #ddd;outline:0;resize:none}.krajee-default .file-preview-html{border:1px solid #ddd}.krajee-default .file-other-icon{font-size:6em;line-height:1}.krajee-default .file-footer-buttons{float:right}.krajee-default .file-footer-caption{display:block;text-align:center;padding-top:4px;font-size:11px;color:#777;margin-bottom:30px}.file-upload-stats{font-size:10px;text-align:center;width:100%}.kv-upload-progress .file-upload-stats{font-size:12px;margin:-10px 0 5px}.krajee-default .file-preview-error{opacity:.65;box-shadow:none}.krajee-default .file-thumb-progress{top:37px;left:0;right:0}.krajee-default.kvsortable-ghost{background:#e1edf7;border:2px solid #a1abff}.krajee-default .file-preview-other:hover{opacity:.8}.krajee-default .file-preview-frame:not(.file-preview-error) .file-footer-caption:hover{color:#000}.kv-upload-progress .progress{height:20px;margin:10px 0;overflow:hidden}.kv-upload-progress .progress-bar{height:20px;font-family:Verdana,Helvetica,sans-serif}.file-zoom-dialog .file-other-icon{font-size:22em;font-size:50vmin}.file-zoom-dialog .modal-dialog{width:auto}.file-zoom-dialog .modal-header{display:flex;align-items:center;justify-content:space-between}.file-zoom-dialog .btn-navigate{margin:0 .1rem;padding:0;font-size:1.2rem;width:2.4rem;height:2.4rem;top:50%;border-radius:50%;text-align:center}.btn-navigate *{width:auto}.file-zoom-dialog .floating-buttons{top:5px;right:10px}.file-zoom-dialog .btn-kv-prev{left:0}.file-zoom-dialog .btn-kv-next{right:0}.file-zoom-dialog .kv-zoom-caption{max-width:50%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.file-zoom-dialog .kv-zoom-header{padding:.5rem}.file-zoom-dialog .kv-zoom-body{padding:.25rem .5rem .25rem 0}.file-zoom-dialog .kv-zoom-description{position:absolute;opacity:.8;font-size:.8rem;background-color:#1a1a1a;padding:1rem;text-align:center;border-radius:.5rem;color:#fff;left:15%;right:15%;bottom:15%}.file-zoom-dialog .kv-desc-hide{float:right;color:#fff;padding:0 .1rem;background:0 0;border:none}.file-zoom-dialog .kv-desc-hide:hover{opacity:.7}.file-zoom-dialog .kv-desc-hide:focus{opacity:.9}.file-input-ajax-new .no-browse .form-control,.file-input-new .no-browse .form-control{border-top-right-radius:4px;border-bottom-right-radius:4px}.file-caption{width:100%;position:relative}.file-thumb-loading{background:url(loading.gif) center center no-repeat content-box!important}.file-drop-zone{border:1px dashed #aaa;min-height:260px;border-radius:4px;text-align:center;vertical-align:middle;margin:12px 15px 12px 12px;padding:5px}.file-drop-zone.clickable:hover{border:2px dashed #999}.file-drop-zone.clickable:focus{border:2px solid #5acde2}.file-drop-zone .file-preview-thumbnails{cursor:default}.file-drop-zone-title{color:#aaa;font-size:1.6em;text-align:center;padding:85px 10px;cursor:default}.file-highlighted{border:2px dashed #999!important;background-color:#eee}.file-uploading{background:url(loading-sm.gif) center bottom 10px no-repeat;opacity:.65}.file-zoom-fullscreen .modal-dialog{min-width:100%;margin:0}.file-zoom-fullscreen .modal-content{border-radius:0;box-shadow:none;min-height:100vh}.file-zoom-fullscreen .kv-zoom-body{overflow-y:auto}.floating-buttons{z-index:3000}.floating-buttons .btn-kv{margin-left:3px;z-index:3000}.kv-zoom-actions .btn-kv{margin-left:3px}.file-zoom-content{text-align:center;white-space:nowrap;min-height:300px}.file-zoom-content:hover{background:0 0}.file-zoom-content>*{display:inline-block;vertical-align:middle}.file-zoom-content .kv-spacer{height:100%}.file-zoom-content .file-preview-image,.file-zoom-content .file-preview-video{max-height:100%}.file-zoom-content>.file-object.type-image{height:auto;min-height:inherit}.file-zoom-content>.file-object.type-audio{width:auto;height:30px}@media (min-width:576px){.file-zoom-dialog .modal-dialog{max-width:500px}}@media (min-width:992px){.file-zoom-dialog .modal-lg{max-width:800px}}@media (max-width:767px){.file-preview-thumbnails{display:flex;justify-content:center;align-items:center;flex-direction:column}.file-zoom-dialog .modal-header{flex-direction:column}}@media (max-width:350px){.krajee-default.file-preview-frame:not([data-template=audio]) .kv-file-content{width:160px}}@media (max-width:420px){.krajee-default.file-preview-frame .kv-file-content.kv-pdf-rendered{width:100%}}.file-loading[dir=rtl]:before{background:url(loading.gif) top right no-repeat;padding-left:0;padding-right:20px}.clickable .file-drop-zone-title{cursor:pointer}.file-sortable .file-drag-handle:hover{opacity:.7}.file-sortable .file-drag-handle{cursor:grab;opacity:1}.file-grabbing,.file-grabbing *{cursor:not-allowed!important}.file-grabbing .file-preview-thumbnails *{cursor:grabbing!important}.file-preview-frame.sortable-chosen{background-color:#d9edf7;border-color:#17a2b8;box-shadow:none!important}.file-preview .kv-zoom-cache{display:none} \ No newline at end of file diff --git a/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.min.js b/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.min.js index 763f17c2..517009a0 100644 --- a/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.min.js +++ b/ruoyi-admin/src/main/resources/static/ajax/libs/bootstrap-fileinput/fileinput.min.js @@ -1,11 +1,494 @@ /*! - * bootstrap-fileinput v5.1.3 + * bootstrap-fileinput v5.2.3 * http://plugins.krajee.com/file-input * * Author: Kartik Visweswaran - * Copyright: 2014 - 2020, Kartik Visweswaran, Krajee.com + * Copyright: 2014 - 2021, Kartik Visweswaran, Krajee.com * * Licensed under the BSD-3-Clause * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md */ -!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof module&&module.exports?module.exports=e(require("jquery")):e(window.jQuery)}(function(e){e.fn.fileinputLocales={},e.fn.fileinputThemes={},String.prototype.setTokens=function(e){var t,i,a=""+this;for(t in e){e.hasOwnProperty(t)&&(i=RegExp("{"+t+"}","g"),a=a.replace(i,e[t]))}return a},Array.prototype.flatMap||(Array.prototype.flatMap=function(e){return[].concat(this.map(e))});var t,i;t={FRAMES:".kv-preview-thumb",SORT_CSS:"file-sortable",INIT_FLAG:"init-",OBJECT_PARAMS:'\n\n\n\n\n\n',DEFAULT_PREVIEW:'
    \n{previewFileIcon}\n
    ',MODAL_ID:"kvFileinputModal",MODAL_EVENTS:["show","shown","hide","hidden","loaded"],logMessages:{ajaxError:"{status}: {error}. Error Details: {text}.",badDroppedFiles:"Error scanning dropped files!",badExifParser:"Error loading the piexif.js library. {details}",badInputType:'The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.',exifWarning:'To avoid this warning, either set "autoOrientImage" to "false" OR ensure you have loaded the "piexif.js" library correctly on your page before the "fileinput.js" script.',invalidChunkSize:'Invalid upload chunk size: "{chunkSize}". Resumable uploads are disabled.',invalidThumb:'Invalid thumb frame with id: "{id}".',noResumableSupport:"The browser does not support resumable or chunk uploads.",noUploadUrl:'The "uploadUrl" is not set. Ajax uploads and resumable uploads have been disabled.',retryStatus:"Retrying upload for chunk # {chunk} for {filename}... retry # {retry}.",chunkQueueError:"Could not push task to ajax pool for chunk index # {index}.",resumableMaxRetriesReached:"Maximum resumable ajax retries ({n}) reached.",resumableRetryError:"Could not retry the resumable request (try # {n})... aborting.",resumableAborting:"Aborting / cancelling the resumable request."},objUrl:window.URL||window.webkitURL,now:function(){return(new Date).getTime()},round:function(e){return e=parseFloat(e),isNaN(e)?0:Math.floor(Math.round(e))},getArray:function(e){var t,i=[],a=e&&e.length||0;for(t=0;a>t;t++){i.push(e[t])}return i},getFileRelativePath:function(e){return(e.newPath||e.relativePath||e.webkitRelativePath||t.getFileName(e)||null)+""},getFileId:function(e,i){var a=t.getFileRelativePath(e);return"function"==typeof i?i(e):e&&a?e.size+"_"+encodeURIComponent(a).replace(/%/g,"_"):null},getFrameSelector:function(e,t){return t=t||"",'[id="'+e+'"]'+t},getZoomSelector:function(e,i){return t.getFrameSelector("zoom-"+e,i)},getFrameElement:function(e,i,a){return e.find(t.getFrameSelector(i,a))},getZoomElement:function(e,i,a){return e.find(t.getZoomSelector(i,a))},getElapsed:function(i){var a=i,r="",n={},o={year:31536000,month:2592000,week:604800,day:86400,hour:3600,minute:60,second:1};return t.getObjectKeys(o).forEach(function(e){n[e]=Math.floor(a/o[e]),a-=n[e]*o[e]}),e.each(n,function(e,t){t>0&&(r+=(r?" ":"")+t+e.substring(0,1))}),r},debounce:function(e,t){var i;return function(){var a=arguments,r=this;clearTimeout(i),i=setTimeout(function(){e.apply(r,a)},t)}},stopEvent:function(e){e.stopPropagation(),e.preventDefault()},getFileName:function(e){return e?e.fileName||e.name||"":""},createObjectURL:function(e){return t.objUrl&&t.objUrl.createObjectURL&&e?t.objUrl.createObjectURL(e):""},revokeObjectURL:function(e){t.objUrl&&t.objUrl.revokeObjectURL&&e&&t.objUrl.revokeObjectURL(e)},compare:function(e,t,i){return void 0!==e&&(i?e===t:e.match(t))},isIE:function(e){var t,i;return"Microsoft Internet Explorer"!==navigator.appName?!1:10===e?RegExp("msie\\s"+e,"i").test(navigator.userAgent):(t=document.createElement("div"),t.innerHTML="",i=t.getElementsByTagName("i").length,document.body.appendChild(t),t.parentNode.removeChild(t),i)},canOrientImage:function(t){var i=e(document.createElement("img")).css({width:"1px",height:"1px"}).insertAfter(t),a=i.css("image-orientation");return i.remove(),!!a},canAssignFilesToInput:function(){var e=document.createElement("input");try{return e.type="file",e.files=null,!0}catch(t){return !1}},getDragDropFolders:function(e){var t,i,a=e?e.length:0,r=0;if(a>0&&e[0].webkitGetAsEntry()){for(t=0;a>t;t++){i=e[t].webkitGetAsEntry(),i&&i.isDirectory&&r++}}return r},initModal:function(t){var i=e("body");i.length&&t.appendTo(i)},isFunction:function(e){return"function"==typeof e},isEmpty:function(i,a){return void 0===i||null===i||!t.isFunction(i)&&(0===i.length||a&&""===e.trim(i))},isArray:function(e){return Array.isArray(e)||"[object Array]"===Object.prototype.toString.call(e)},ifSet:function(e,t,i){return i=i||"",t&&"object"==typeof t&&e in t?t[e]:i},cleanArray:function(e){return e instanceof Array||(e=[]),e.filter(function(e){return void 0!==e&&null!==e})},spliceArray:function(t,i,a){var r,n,o=0,l=[];if(!(t instanceof Array)){return[]}for(n=e.extend(!0,[],t),a&&n.reverse(),r=0;r=0?atob(e.split(",")[1]):decodeURIComponent(e.split(",")[1]),a=new ArrayBuffer(i.length),r=new Uint8Array(a),n=0;nl;){switch(i=n[l++],i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:a=n[l++],o+=String.fromCharCode((31&i)<<6|63&a);break;case 14:a=n[l++],r=n[l++],o+=String.fromCharCode((15&i)<<12|(63&a)<<6|(63&r)<<0)}}return o},isHtml:function(e){var t=document.createElement("div");t.innerHTML=e;for(var i=t.childNodes,a=i.length;a--;){if(1===i[a].nodeType){return !0}}return !1},isSvg:function(e){return e.match(/^\s*<\?xml/i)&&(e.match(/"+t+""))},uniqId:function(){return((new Date).getTime()+Math.floor(Math.random()*Math.pow(10,15))).toString(36)},cspBuffer:{CSP_ATTRIB:"data-csp-01928735",domElementsStyles:{},stash:function(i){var a=this,r=e.parseHTML("
    "+i+"
    "),n=e(r);n.find("[style]").each(function(i,r){var n=e(r),o=n.attr("style"),l=t.uniqId(),s={};o&&o.length&&(-1===o.indexOf(";")&&(o+=";"),o.slice(0,o.length-1).split(";").map(function(e){e=e.split(":"),e[0]&&(s[e[0]]=e[1]?e[1]:"")}),a.domElementsStyles[l]=s,n.removeAttr("style").attr(a.CSP_ATTRIB,l))}),n.filter("*").removeAttr("style");var o=Object.values?Object.values(r):Object.keys(r).map(function(e){return r[e]});return o.flatMap(function(e){return e.innerHTML}).join("")},apply:function(t){var i=this,a=e(t);a.find("["+i.CSP_ATTRIB+"]").each(function(t,a){var r=e(a),n=r.attr(i.CSP_ATTRIB),o=i.domElementsStyles[n];o&&r.css(o),r.removeAttr(i.CSP_ATTRIB)}),i.domElementsStyles={}}},setHtml:function(e,i){var a=t.cspBuffer;return e.html(a.stash(i)),a.apply(e),e},htmlEncode:function(e,t){return void 0===e?t||null:e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")},replaceTags:function(t,i){var a=t;return i?(e.each(i,function(e,t){"function"==typeof t&&(t=t()),a=a.split(e).join(t)}),a):a},cleanMemory:function(e){var i=e.is("img")?e.attr("src"):e.find("source").attr("src");t.revokeObjectURL(i)},findFileName:function(e){var t=e.lastIndexOf("/");return -1===t&&(t=e.lastIndexOf("\\")),e.split(e.substring(t,t+1)).pop()},checkFullScreen:function(){return document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement},toggleFullScreen:function(e){var i=document,a=i.documentElement,r=t.checkFullScreen();a&&e&&!r?a.requestFullscreen?a.requestFullscreen():a.msRequestFullscreen?a.msRequestFullscreen():a.mozRequestFullScreen?a.mozRequestFullScreen():a.webkitRequestFullscreen&&a.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT):r&&(i.exitFullscreen?i.exitFullscreen():i.msExitFullscreen?i.msExitFullscreen():i.mozCancelFullScreen?i.mozCancelFullScreen():i.webkitExitFullscreen&&i.webkitExitFullscreen())},moveArray:function(t,i,a,r){var n=e.extend(!0,[],t);if(r&&n.reverse(),a>=n.length){for(var o=a-n.length;o--+1;){n.push(void 0)}}return n.splice(a,0,n.splice(i,1)[0]),r&&n.reverse(),n},closeButton:function(e){return e=e?"close "+e:"close",''},getRotation:function(e){switch(e){case 2:return"rotateY(180deg)";case 3:return"rotate(180deg)";case 4:return"rotate(180deg) rotateY(180deg)";case 5:return"rotate(270deg) rotateY(180deg)";case 6:return"rotate(90deg)";case 7:return"rotate(90deg) rotateY(180deg)";case 8:return"rotate(270deg)";default:return""}},setTransform:function(e,t){e&&(e.style.transform=t,e.style.webkitTransform=t,e.style["-moz-transform"]=t,e.style["-ms-transform"]=t,e.style["-o-transform"]=t)},getObjectKeys:function(t){var i=[];return t&&e.each(t,function(e){i.push(e)}),i},getObjectSize:function(e){return t.getObjectKeys(e).length},whenAll:function(i){var a,r,n,o,l,s,d=[].slice,c=1===arguments.length&&t.isArray(i)?i:d.call(arguments),u=e.Deferred(),p=0,f=c.length,g=f;for(n=o=l=Array(f),s=function(e,t,i){return function(){i!==c&&p++,u.notifyWith(t[e]=this,i[e]=d.call(arguments)),--g||u[(p?"reject":"resolve")+"With"](t,i)}},a=0;f>a;a++){(r=c[a])&&e.isFunction(r.promise)?r.promise().done(s(a,l,c)).fail(s(a,n,o)):(u.notifyWith(this,r),--g)}return g||u.resolveWith(l,c),u.promise()}},i=function(i,a){var r=this;r.$element=e(i),r.$parent=r.$element.parent(),r._validate()&&(r.isPreviewable=t.hasFileAPISupport(),r.isIE9=t.isIE(9),r.isIE10=t.isIE(10),(r.isPreviewable||r.isIE9)&&(r._init(a),r._listen()),r.$element.removeClass("file-loading"))},i.prototype={constructor:i,_cleanup:function(){var e=this;e.reader=null,e.clearFileStack(),e.fileBatchCompleted=!0,e.isError=!1,e.isDuplicateError=!1,e.isPersistentError=!1,e.cancelling=!1,e.paused=!1,e.lastProgress=0,e._initAjax()},_isAborted:function(){var e=this;return e.cancelling||e.paused},_initAjax:function(){var i=this,a=i.taskManager={pool:{},addPool:function(e){return a.pool[e]=new a.TasksPool(e)},getPool:function(e){return a.pool[e]},addTask:function(e,t){return new a.Task(e,t)},TasksPool:function(i){var r=this;r.id=i,r.cancelled=!1,r.cancelledDeferrer=e.Deferred(),r.tasks={},r.addTask=function(e,t){return r.tasks[e]=new a.Task(e,t)},r.size=function(){return t.getObjectSize(r.tasks)},r.run=function(i){var a,n,o,l=0,s=!1,d=t.getObjectKeys(r.tasks).map(function(e){return r.tasks[e]}),c=[],u=e.Deferred();if(r.cancelled){return r.cancelledDeferrer.resolve(),u.reject()}if(!i){var p=t.getObjectKeys(r.tasks).map(function(e){return r.tasks[e].deferred});return t.whenAll(p).done(function(){var e=t.getArray(arguments);r.cancelled?(u.reject.apply(null,e),r.cancelledDeferrer.resolve()):(u.resolve.apply(null,e),r.cancelledDeferrer.reject())}).fail(function(){var e=t.getArray(arguments);u.reject.apply(null,e),r.cancelled?r.cancelledDeferrer.resolve():r.cancelledDeferrer.reject()}),e.each(r.tasks,function(e){a=r.tasks[e],a.run()}),u}for(n=function(t){e.when(t.deferred).fail(function(){s=!0,o.apply(null,arguments)}).always(o)},o=function(){var e=t.getArray(arguments);return u.notify(e),c.push(e),r.cancelled?(u.reject.apply(null,c),void r.cancelledDeferrer.resolve()):(c.length===r.size()&&(s?u.reject.apply(null,c):u.resolve.apply(null,c)),void (d.length&&(a=d.shift(),n(a),a.run())))};d.length&&l++0&&s.maxTotalFileCounti.file.size?i.file.size:e},getTotalChunks:function(){var e=parseFloat(i.chunkSize);return !isNaN(e)&&e>0?Math.ceil(i.file.size/e):0},getProgress:function(){var e=i.processedResumables(),t=i.chunkCount;return 0===t?0:Math.ceil(e/t*100)},checkAborted:function(e){a._isAborted()&&(clearInterval(e),a.unlock())},upload:function(){var e,r=o.getIdList(),n="new";e=setInterval(function(){var l;if(i.checkAborted(e),"new"===n&&(a.lock(),n="processing",l=r.shift(),o.initStats(l),o.stack[l]&&(i.init(l,o.stack[l],o.getIndex(l)),i.processUpload())),!o.isPending(l)&&i.completed&&(n="new"),o.isProcessed()){var s=a.$preview.find(".file-preview-initial");s.length&&(t.addCss(s,t.SORT_CSS),a._initSortable()),clearInterval(e),a._clearFileInput(),a.unlock(),setTimeout(function(){var e=a.previewCache.data;e&&(a.initialPreview=e.content,a.initialPreviewConfig=e.config,a.initialPreviewThumbTags=e.tags),a._raise("filebatchuploadcomplete",[a.initialPreview,a.initialPreviewConfig,a.initialPreviewThumbTags,a._getExtraData()])},a.processDelay)}},a.processDelay)},uploadResumable:function(){var e,t,n=a.taskManager,o=i.chunkCount;for(t=n.addPool(i.id),e=0;o>e;e++){i.logs[e]=!(!i.chunksProcessed[i.id]||!i.chunksProcessed[i.id][e]),i.logs[e]||i.pushAjax(e,0)}t.run(r.maxThreads).done(function(){i.setProcessed("success")}).fail(function(){i.setProcessed(t.cancelled?"cancel":"error")})},processUpload:function(){var n,l,s,d,c,u,p,f=i.id;return r.testUrl?(n=new FormData,l=o.stack[f],a._setUploadData(n,{fileId:f,fileName:l.fileName,fileSize:l.size,fileRelativePath:l.relativePath,chunkSize:i.chunkSize,chunkCount:i.chunkCount}),s=function(e){p=a._getOutData(n,e),a._raise("filetestbeforesend",[f,o,i,p])},d=function(r,l,s){p=a._getOutData(n,s,r);var d=a.uploadParamNames,c=d.chunksUploaded||"chunksUploaded",u=[f,o,i,p];r[c]&&t.isArray(r[c])?(i.chunksProcessed[f]||(i.chunksProcessed[f]={}),e.each(r[c],function(e,t){i.logs[t]=!0,i.chunksProcessed[f][t]=!0}),i.chunksProcessed[f].data=r,a._raise("filetestsuccess",u)):a._raise("filetesterror",u),i.uploadResumable()},c=function(e,t,r){p=a._getOutData(n,e),a._raise("filetestajaxerror",[f,o,i,p]),i.setAjaxError(e,t,r,!0),i.uploadResumable()},u=function(){a._raise("filetestcomplete",[f,o,i,a._getOutData(n)])},void a._ajaxSubmit(s,d,u,c,n,f,i.fileIndex,r.testUrl)):void i.uploadResumable()},pushAjax:function(e,t){var r=a.taskManager,o=r.getPool(i.id);o.addTask(o.size()+1,function(e){var t,r=i.stack.shift();t=r[0],i.chunksProcessed[i.id]&&i.chunksProcessed[i.id][t]?a._log(n.chunkQueueError,{index:t}):i.sendAjax(t,r[1],e)}),i.stack.push([e,t])},sendAjax:function(e,l,s){var d,c=i.chunkSize,u=i.id,p=i.file,f=i.$thumb,g=t.logMessages,m=i.$btnDelete,h=function(e,t){t&&(e=e.setTokens(t)),e="Error processing resumable ajax request. "+e,a._log(e),s.reject(e)};if(!i.chunksProcessed[u]||!i.chunksProcessed[u][e]){if(l>r.maxRetries){return h(g.resumableMaxRetriesReached,{n:r.maxRetries}),void i.setProcessed("error")}var v,w,b,_,C,y,x=p.slice?"slice":p.mozSlice?"mozSlice":p.webkitSlice?"webkitSlice":"slice",T=p[x](c*e,c*(e+1));v=new FormData,d=o.stack[u],a._setUploadData(v,{chunkCount:i.chunkCount,chunkIndex:e,chunkSize:c,chunkSizeStart:c*e,fileBlob:[T,i.fileName],fileId:u,fileName:i.fileName,fileRelativePath:d.relativePath,fileSize:p.size,retryCount:l}),i.$progress&&i.$progress.length&&i.$progress.show(),b=function(r){w=a._getOutData(v,r),a.showPreview&&(f.hasClass("file-preview-success")||(a._setThumbStatus(f,"Loading"),t.addCss(f,"file-uploading")),m.attr("disabled",!0)),a._raise("filechunkbeforesend",[u,e,l,o,i,w])},_=function(t,d,c){if(a._isAborted()){return void h(g.resumableAborting)}w=a._getOutData(v,c,t);var p=a.uploadParamNames,f=p.chunkIndex||"chunkIndex",m=[u,e,l,o,i,w];t.error?(r.showErrorLog&&a._log(n.retryStatus,{retry:l+1,filename:i.fileName,chunk:e}),i.pushAjax(e,l+1),i.error=t.error,a._raise("filechunkerror",m)):(i.logs[t[f]]=!0,i.chunksProcessed[u]||(i.chunksProcessed[u]={}),i.chunksProcessed[u][t[f]]=!0,i.chunksProcessed[u].data=t,s.resolve.call(null,t),a._raise("filechunksuccess",m),i.check())},C=function(t,r,n){return a._isAborted()?void h(g.resumableAborting):(w=a._getOutData(v,t),i.setAjaxError(t,r,n),a._raise("filechunkajaxerror",[u,e,l,o,i,w]),i.pushAjax(e,l+1),void h(g.resumableRetryError,{n:l-1}))},y=function(){a._isAborted()||a._raise("filechunkcomplete",[u,e,l,o,i,a._getOutData(v)])},a._ajaxSubmit(b,_,y,C,v,u,i.fileIndex)}}},i.reset()}},_initTemplateDefaults:function(){var i,a,r,n,o,l,s,d,c,u,p,f,g,m,h,v,w,b,_,C,y,x,T,P,F,E,k,S,I,A,D,z,j,U,M,$,R,O,B,L,N,Z,H=this,W=function(e,i){return'\n"+t.DEFAULT_PREVIEW+"\n\n"};i='{preview}\n
    \n
    \n {caption}\n
    \n {remove}\n {cancel}\n {pause}\n {upload}\n {browse}\n
    \n
    ',a='{preview}\n
    \n
    \n{remove}\n{cancel}\n{upload}\n{browse}\n',r='
    \n {close}
    \n
    \n
    \n
    \n
    \n
    \n
    ',o=t.closeButton("fileinput-remove"),n='',l='
    \n \n \n
    ',s='',d='{icon} {label}',c='
    {icon} {label}
    ',Z=t.MODAL_ID+"Label",u='',p='\n',f='
    \n
    \n {status}\n
    \n
    {stats}',N='
    {pendingTime} {uploadSpeed}
    ',g=" ({sizeText})",m='',h='
    \n \n
    \n{drag}\n
    ',v='\n',w='',b='{downloadIcon}',_='',C='{dragIcon}',y='
    {indicator}
    ',x='
    \n',P=x+' title="{caption}">
    \n',F="
    {footer}\n{zoomCache}
    \n",E="{content}\n",O=" {style}",k=W("html","text/html"),I=W("text","text/plain;charset=UTF-8"),$=W("pdf","application/pdf"),S='{alt}\n",A='",D='",z='\n",j='\n",U='\n",M='\n\n'+t.OBJECT_PARAMS+" "+t.DEFAULT_PREVIEW+"\n\n",R='
    \n"+t.DEFAULT_PREVIEW+"\n
    \n",B='
    {zoomContent}
    ',L={width:"100%",height:"100%","min-height":"480px"},H._isPdfRendered()&&($=H.pdfRendererTemplate.replace("{renderer}",H._encodeURI(H.pdfRendererUrl))),H.defaults={layoutTemplates:{main1:i,main2:a,preview:r,close:o,fileIcon:n,caption:l,modalMain:u,modal:p,progress:f,stats:N,size:g,footer:m,indicator:y,actions:h,actionDelete:v,actionUpload:w,actionDownload:b,actionZoom:_,actionDrag:C,btnDefault:s,btnLink:d,btnBrowse:c,zoomCache:B},previewMarkupTags:{tagBefore1:T,tagBefore2:P,tagAfter:F},previewContentTemplates:{generic:E,html:k,image:S,text:I,office:A,gdocs:D,video:z,audio:j,flash:U,object:M,pdf:$,other:R},allowedPreviewTypes:["image","html","text","video","audio","flash","pdf","object"],previewTemplates:{},previewSettings:{image:{width:"auto",height:"auto","max-width":"100%","max-height":"100%"},html:{width:"213px",height:"160px"},text:{width:"213px",height:"160px"},office:{width:"213px",height:"160px"},gdocs:{width:"213px",height:"160px"},video:{width:"213px",height:"160px"},audio:{width:"100%",height:"30px"},flash:{width:"213px",height:"160px"},object:{width:"213px",height:"160px"},pdf:{width:"100%",height:"160px",position:"relative"},other:{width:"213px",height:"160px"}},previewSettingsSmall:{image:{width:"auto",height:"auto","max-width":"100%","max-height":"100%"},html:{width:"100%",height:"160px"},text:{width:"100%",height:"160px"},office:{width:"100%",height:"160px"},gdocs:{width:"100%",height:"160px"},video:{width:"100%",height:"auto"},audio:{width:"100%",height:"30px"},flash:{width:"100%",height:"auto"},object:{width:"100%",height:"auto"},pdf:{width:"100%",height:"160px"},other:{width:"100%",height:"160px"}},previewZoomSettings:{image:{width:"auto",height:"auto","max-width":"100%","max-height":"100%"},html:L,text:L,office:{width:"100%",height:"100%","max-width":"100%","min-height":"480px"},gdocs:{width:"100%",height:"100%","max-width":"100%","min-height":"480px"},video:{width:"auto",height:"100%","max-width":"100%"},audio:{width:"100%",height:"30px"},flash:{width:"auto",height:"480px"},object:{width:"auto",height:"100%","max-width":"100%","min-height":"480px"},pdf:L,other:{width:"auto",height:"100%","min-height":"480px"}},mimeTypeAliases:{"video/quicktime":"video/mp4"},fileTypeSettings:{image:function(e,i){return t.compare(e,"image.*")&&!t.compare(e,/(tiff?|wmf)$/i)||t.compare(i,/\.(gif|png|jpe?g)$/i)},html:function(e,i){return t.compare(e,"text/html")||t.compare(i,/\.(htm|html)$/i)},office:function(e,i){return t.compare(e,/(word|excel|powerpoint|office)$/i)||t.compare(i,/\.(docx?|xlsx?|pptx?|pps|potx?)$/i)},gdocs:function(e,i){return t.compare(e,/(word|excel|powerpoint|office|iwork-pages|tiff?)$/i)||t.compare(i,/\.(docx?|xlsx?|pptx?|pps|potx?|rtf|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i)},text:function(e,i){return t.compare(e,"text.*")||t.compare(i,/\.(xml|javascript)$/i)||t.compare(i,/\.(txt|md|nfo|ini|json|php|js|css)$/i)},video:function(e,i){return t.compare(e,"video.*")&&(t.compare(e,/(ogg|mp4|mp?g|mov|webm|3gp)$/i)||t.compare(i,/\.(og?|mp4|webm|mp?g|mov|3gp)$/i))},audio:function(e,i){return t.compare(e,"audio.*")&&(t.compare(i,/(ogg|mp3|mp?g|wav)$/i)||t.compare(i,/\.(og?|mp3|mp?g|wav)$/i))},flash:function(e,i){return t.compare(e,"application/x-shockwave-flash",!0)||t.compare(i,/\.(swf)$/i)},pdf:function(e,i){return t.compare(e,"application/pdf",!0)||t.compare(i,/\.(pdf)$/i)},object:function(){return !0},other:function(){return !0}},fileActionSettings:{showRemove:!0,showUpload:!0,showDownload:!0,showZoom:!0,showDrag:!0,removeIcon:'',removeClass:"btn btn-sm btn-kv btn-default btn-outline-secondary",removeErrorClass:"btn btn-sm btn-kv btn-danger",removeTitle:"Remove file",uploadIcon:'',uploadClass:"btn btn-sm btn-kv btn-default btn-outline-secondary",uploadTitle:"Upload file",uploadRetryIcon:'',uploadRetryTitle:"Retry upload",downloadIcon:'',downloadClass:"btn btn-sm btn-kv btn-default btn-outline-secondary",downloadTitle:"Download file",zoomIcon:'',zoomClass:"btn btn-sm btn-kv btn-default btn-outline-secondary",zoomTitle:"View Details",dragIcon:'',dragClass:"text-info",dragTitle:"Move / Rearrange",dragSettings:{},indicatorNew:'',indicatorSuccess:'',indicatorError:'',indicatorLoading:'',indicatorPaused:'',indicatorNewTitle:"Not uploaded yet",indicatorSuccessTitle:"Uploaded",indicatorErrorTitle:"Upload Error",indicatorLoadingTitle:"Uploading …",indicatorPausedTitle:"Upload Paused"}},e.each(H.defaults,function(t,i){return"allowedPreviewTypes"===t?void (void 0===H.allowedPreviewTypes&&(H.allowedPreviewTypes=i)):void (H[t]=e.extend(!0,{},i,H[t]))}),H._initPreviewTemplates()},_initPreviewTemplates:function(){var i,a=this,r=a.previewMarkupTags,n=r.tagAfter;e.each(a.previewContentTemplates,function(e,o){t.isEmpty(a.previewTemplates[e])&&(i=r.tagBefore2,("generic"===e||"image"===e)&&(i=r.tagBefore1),a._isPdfRendered()&&"pdf"===e&&(i=i.replace("kv-file-content","kv-file-content kv-pdf-rendered")),a.previewTemplates[e]=i+o+n)})},_initPreviewCache:function(){var i=this;i.previewCache={data:{},init:function(){var e=i.initialPreview;e.length>0&&!t.isArray(e)&&(e=e.split(i.initialPreviewDelimiter)),i.previewCache.data={content:e,config:i.initialPreviewConfig,tags:i.initialPreviewThumbTags}},count:function(e){if(!i.previewCache.data||!i.previewCache.data.content){return 0}if(e){var t=i.previewCache.data.content.filter(function(e){return null!==e});return t.length}return i.previewCache.data.content.length},get:function(e,a){var r,n,o,l,s,d,c,u=t.INIT_FLAG+e,p=i.previewCache.data,f=p.config[e],g=p.content[e],m=t.ifSet("previewAsData",f,i.initialPreviewAsData),h=f?{title:f.title||null,alt:f.alt||null}:{title:null,alt:null},v=function(e,a,r,n,o,l,s,d){var c=" file-preview-initial "+t.SORT_CSS+(s?" "+s:""),u=i.previewInitId+"-"+l,p=f&&f.fileId||u;return i._generatePreviewTemplate(e,a,r,n,u,p,!1,null,c,o,l,d,h,f&&f.zoomData||a)};return g&&g.length?(a=void 0===a?!0:a,o=t.ifSet("type",f,i.initialPreviewFileType||"generic"),s=t.ifSet("filename",f,t.ifSet("caption",f)),d=t.ifSet("filetype",f,o),l=i.previewCache.footer(e,a,f&&f.size||null),c=t.ifSet("frameClass",f),r=m?v(o,g,s,d,l,u,c):v("generic",g,s,d,l,u,c,o).setTokens({content:p.content[e]}),p.tags.length&&p.tags[e]&&(r=t.replaceTags(r,p.tags[e])),t.isEmpty(f)||t.isEmpty(f.frameAttr)||(n=t.createElement(r),n.find(".file-preview-initial").attr(f.frameAttr),r=n.html(),n.remove()),r):""},clean:function(e){e.content=t.cleanArray(e.content),e.config=t.cleanArray(e.config),e.tags=t.cleanArray(e.tags),i.previewCache.data=e},add:function(e,a,r,n){var o,l=i.previewCache.data;return e&&e.length?(o=e.length-1,t.isArray(e)||(e=e.split(i.initialPreviewDelimiter)),n&&l.content?(o=l.content.push(e[0])-1,l.config[o]=a,l.tags[o]=r):(l.content=e,l.config=a,l.tags=r),i.previewCache.clean(l),o):0},set:function(e,a,r,n){var o,l,s=i.previewCache.data;if(e&&e.length&&(t.isArray(e)||(e=e.split(i.initialPreviewDelimiter)),l=e.filter(function(e){return null!==e}),l.length)){if(void 0===s.content&&(s.content=[]),void 0===s.config&&(s.config=[]),void 0===s.tags&&(s.tags=[]),n){for(o=0;ot;t++){a=i.previewCache.get(t),r=i.reversePreviewOrder?a+r:r+a}return e=i._getMsgSelected(n),{content:r,caption:e}},footer:function(e,a,r){var n=i.previewCache.data||{};if(t.isEmpty(n.content)){return""}(t.isEmpty(n.config)||t.isEmpty(n.config[e]))&&(n.config[e]={}),a=void 0===a?!0:a;var o,l=n.config[e],s=t.ifSet("caption",l),d=t.ifSet("width",l,"auto"),c=t.ifSet("url",l,!1),u=t.ifSet("key",l,null),p=t.ifSet("fileId",l,null),f=i.fileActionSettings,g=i.initialPreviewShowDelete||!1,m=i.initialPreviewDownloadUrl?i.initialPreviewDownloadUrl+"?key="+u+(p?"&fileId="+p:""):"",h=l.downloadUrl||m,v=l.filename||l.caption||"",w=!!h,b=t.ifSet("showRemove",l,g),_=t.ifSet("showDownload",l,t.ifSet("showDownload",f,w)),C=t.ifSet("showZoom",l,t.ifSet("showZoom",f,!0)),y=t.ifSet("showDrag",l,t.ifSet("showDrag",f,!0)),x=c===!1&&a;return _=_&&l.downloadUrl!==!1&&!!h,o=i._renderFileActions(l,!1,_,b,C,y,x,c,u,!0,h,v),i._getLayoutTemplate("footer").setTokens({progress:i._renderThumbProgress(),actions:o,caption:s,size:i._getSize(r),width:d,indicator:""})}},i.previewCache.init()},_isPdfRendered:function(){var e=this,t=e.usePdfRenderer,i="function"==typeof t?t():!!t;return i&&e.pdfRendererUrl},_handler:function(e,t,i){var a=this,r=a.namespace,n=t.split(" ").join(r+" ")+r;e&&e.length&&e.off(n).on(n,i)},_encodeURI:function(e){var t=this;return t.encodeUrl?encodeURI(e):e},_log:function(e,t){var i=this,a=i.$element.attr("id");i.showConsoleLogs&&(a&&(e='"'+a+'": '+e),e="bootstrap-fileinput: "+e,"object"==typeof t&&(e=e.setTokens(t)),window.console&&void 0!==window.console.log?window.console.log(e):window.alert(e))},_validate:function(){var e=this,i="file"===e.$element.attr("type");return i||e._log(t.logMessages.badInputType),i},_errorsExist:function(){var i,a=this,r=a.$errorContainer.find("li");return r.length?!0:(i=t.createElement(a.$errorContainer.html()),i.find(".kv-error-close").remove(),i.find("ul").remove(),!!e.trim(i.text()).length)},_errorHandler:function(e,t){var i=this,a=e.target.error,r=function(e){i._showError(e.replace("{name}",t))};r(a.code===a.NOT_FOUND_ERR?i.msgFileNotFound:a.code===a.SECURITY_ERR?i.msgFileSecured:a.code===a.NOT_READABLE_ERR?i.msgFileNotReadable:a.code===a.ABORT_ERR?i.msgFilePreviewAborted:i.msgFilePreviewError)},_addError:function(e){var i=this,a=i.$errorContainer;e&&a.length&&(t.setHtml(a,i.errorCloseButton+e),i._handler(a.find(".kv-error-close"),"click",function(){setTimeout(function(){i.showPreview&&!i.getFrames().length&&i.clear(),a.fadeOut("slow")},i.processDelay)}))},_setValidationError:function(e){var i=this;e=(e?e+" ":"")+"has-error",i.$container.removeClass(e).addClass("has-error"),t.addCss(i.$captionContainer,"is-invalid")},_resetErrors:function(e){var t=this,i=t.$errorContainer;t.isPersistentError||(t.isError=!1,t.$container.removeClass("has-error"),t.$captionContainer.removeClass("is-invalid"),i.html(""),e?i.fadeOut("slow"):i.hide())},_showFolderError:function(e){var t,i=this,a=i.$errorContainer;e&&(i.isAjaxUpload||i._clearFileInput(),t=i.msgFoldersNotAllowed.replace("{n}",e),i._addError(t),i._setValidationError(),a.fadeIn(i.fadeDelay),i._raise("filefoldererror",[e,t]))},_showFileError:function(e,t,i){var a=this,r=a.$errorContainer,n=i||"fileuploaderror",o=t&&t.fileId||"",l=t&&t.id?'
  • '+e+"
  • ":"
  • "+e+"
  • ";return 0===r.find("ul").length?a._addError("
      "+l+"
    "):r.find("ul").append(l),r.fadeIn(a.fadeDelay),a._raise(n,[t,e]),a._setValidationError("file-input-new"),!0},_showError:function(e,t,i){var a=this,r=a.$errorContainer,n=i||"fileerror";return t=t||{},t.reader=a.reader,a._addError(e),r.fadeIn(a.fadeDelay),a._raise(n,[t,e]),a.isAjaxUpload||a._clearFileInput(),a._setValidationError("file-input-new"),a.$btnUpload.attr("disabled",!0),!0},_noFilesError:function(e){var t=this,i=t.minFileCount>1?t.filePlural:t.fileSingle,a=t.msgFilesTooLess.replace("{n}",t.minFileCount).replace("{files}",i),r=t.$errorContainer;a="
  • "+a+"
  • ",0===r.find("ul").length?t._addError("
      "+a+"
    "):r.find("ul").append(a),t.isError=!0,t._updateFileDetails(0),r.fadeIn(t.fadeDelay),t._raise("fileerror",[e,a]),t._clearFileInput(),t._setValidationError()},_parseError:function(t,i,a,r){var n,o,l,s=this,d=e.trim(a+"");return o=i.responseJSON&&i.responseJSON.error?""+i.responseJSON.error:"",l=o?o:i.responseText,s.cancelling&&s.msgUploadAborted&&(d=s.msgUploadAborted),s.showAjaxErrorDetails&&l&&(o?d=e.trim(o+""):(l=e.trim(l.replace(/\n\s*\n/g,"\n")),n=l.length?"
    "+l+"
    ":"",d+=d?n:l)),d||(d=s.msgAjaxError.replace("{operation}",t)),s.cancelling=!1,r?""+r+": "+d:d},_parseFileType:function(e,i){var a,r,n,o,l=this,s=l.allowedPreviewTypes||[];if("application/text-plain"===e){return"text"}for(o=0;o-1&&(i=t.split(".").pop(),a.previewFileIconSettings&&(r=a.previewFileIconSettings[i]||a.previewFileIconSettings[i.toLowerCase()]||null),a.previewFileExtSettings&&e.each(a.previewFileExtSettings,function(e,t){return a.previewFileIconSettings[e]&&t(i)?void (r=a.previewFileIconSettings[e]):void 0})),r||a.previewFileIcon},_parseFilePreviewIcon:function(e,t){var i=this,a=i._getPreviewIcon(t),r=e;return r.indexOf("{previewFileIcon}")>-1&&(r=r.setTokens({previewFileIconClass:i.previewFileIconClass,previewFileIcon:a})),r},_raise:function(t,i){var a=this,r=e.Event(t);if(void 0!==i?a.$element.trigger(r,i):a.$element.trigger(r),r.isDefaultPrevented()||r.result===!1){return !1}switch(t){case"filebatchuploadcomplete":case"filebatchuploadsuccess":case"fileuploaded":case"fileclear":case"filecleared":case"filereset":case"fileerror":case"filefoldererror":case"fileuploaderror":case"filebatchuploaderror":case"filedeleteerror":case"filecustomerror":case"filesuccessremove":break;default:a.ajaxAborted||(a.ajaxAborted=r.result)}return !0},_listenFullScreen:function(e){var t,i,a=this,r=a.$modal;r&&r.length&&(t=r&&r.find(".btn-fullscreen"),i=r&&r.find(".btn-borderless"),t.length&&i.length&&(t.removeClass("active").attr("aria-pressed","false"),i.removeClass("active").attr("aria-pressed","false"),e?t.addClass("active").attr("aria-pressed","true"):i.addClass("active").attr("aria-pressed","true"),r.hasClass("file-zoom-fullscreen")?a._maximizeZoomDialog():e?a._maximizeZoomDialog():i.removeClass("active").attr("aria-pressed","false")))},_listen:function(){var i,a,r,n=this,o=n.$element,l=n.$form,s=n.$container;n._handler(o,"click",function(e){o.hasClass("file-no-browse")&&(o.data("zoneClicked")?o.data("zoneClicked",!1):e.preventDefault())}),n._handler(o,"change",e.proxy(n._change,n)),n.showBrowse&&n._handler(n.$btnFile,"click",e.proxy(n._browse,n)),a=s.find(".file-caption-name"),r=function(){return !1},n._handler(s.find(".fileinput-remove:not([disabled])"),"click",e.proxy(n.clear,n)),n._handler(s.find(".fileinput-cancel"),"click",e.proxy(n.cancel,n)),n._handler(s.find(".fileinput-pause"),"click",e.proxy(n.pause,n)),n._handler(a,"keydown",r),n._handler(a,"paste",r),n._initDragDrop(),n._handler(l,"reset",e.proxy(n.clear,n)),n.isAjaxUpload||n._handler(l,"submit",e.proxy(n._submitForm,n)),n._handler(n.$container.find(".fileinput-upload"),"click",e.proxy(n._uploadClick,n)),n._handler(e(window),"resize",function(){n._listenFullScreen(screen.width===window.innerWidth&&screen.height===window.innerHeight)}),i="webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange",n._handler(e(document),i,function(){n._listenFullScreen(t.checkFullScreen())}),n._autoFitContent(),n._initClickable(),n._refreshPreview()},_autoFitContent:function(){var t,i=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,a=this,r=400>i?a.previewSettingsSmall||a.defaults.previewSettingsSmall:a.previewSettings||a.defaults.previewSettings;e.each(r,function(e,i){t=".file-preview-frame .file-preview-"+e,a.$preview.find(t+".kv-preview-data,"+t+" .kv-preview-data").css(i)})},_scanDroppedItems:function(e,i,a){a=a||"";var r,n,o,l=this,s=function(e){l._log(t.logMessages.badDroppedFiles),l._log(e)};e.isFile?e.file(function(e){a&&(e.newPath=a+e.name),i.push(e)},s):e.isDirectory&&(n=e.createReader(),(o=function(){n.readEntries(function(t){if(t&&t.length>0){for(r=0;r-1;return a._zoneDragDropInit(i),a.isDisabled||!n?(r.effectAllowed="none",void (r.dropEffect="none")):(r.dropEffect="copy",void (a._raise("fileDragEnter",{sourceEvent:i,files:r.types.Files})&&t.addCss(a.$dropZone,"file-highlighted")))},_zoneDragLeave:function(e){var t=this;t._zoneDragDropInit(e),t.isDisabled||t._raise("fileDragLeave",{sourceEvent:e})&&t.$dropZone.removeClass("file-highlighted")},_zoneDrop:function(e){var i,a=this,r=a.$element,n=e.originalEvent.dataTransfer,o=n.files,l=n.items,s=t.getDragDropFolders(l),d=function(){a.isAjaxUpload?a._change(e,o):(a.changeTriggered=!0,r.get(0).files=o,setTimeout(function(){a.changeTriggered=!1,r.trigger("change"+a.namespace)},a.processDelay)),a.$dropZone.removeClass("file-highlighted")};if(e.preventDefault(),!a.isDisabled&&!t.isEmpty(o)&&a._raise("fileDragDrop",{sourceEvent:e,files:o})){if(s>0){if(!a.isAjaxUpload){return void a._showFolderError(s)}for(o=[],i=0;i0&&n>=s,c=e(i.item);d&&(n=s-1),o.initialPreview=t.moveArray(o.initialPreview,r,n,u),o.initialPreviewConfig=t.moveArray(o.initialPreviewConfig,r,n,u),o.previewCache.init(),o.getFrames(".file-preview-initial").each(function(){e(this).attr("data-fileindex",t.INIT_FLAG+l),l++}),d&&(a=o.getFrames(":not(.file-preview-initial):first"),a.length&&c.slideUp(function(){c.insertBefore(a).slideDown()})),o._raise("filesorted",{previewId:c.attr("id"),oldIndex:r,newIndex:n,stack:o.initialPreviewConfig})}},e.extend(!0,i,o.fileActionSettings.dragSettings),o.sortable&&o.sortable.destroy(),o.sortable=p.create(l[0],i))},_setPreviewContent:function(e){var i=this;t.setHtml(i.$preview,e),i._autoFitContent()},_initPreviewImageOrientations:function(){var t=this,i=0,a=t.canOrientImage;(t.autoOrientImageInitial||a)&&t.getFrames(".file-preview-initial").each(function(){var r,n,o,l=e(this),s=t.initialPreviewConfig[i];s&&s.exif&&s.exif.Orientation&&(o=l.attr("id"),r=l.find(">.kv-file-content img"),n=t._getZoom(o," >.kv-file-content img"),a?r.css("image-orientation",t.autoOrientImageInitial?"from-image":"none"):t.setImageOrientation(r,n,s.exif.Orientation,l)),i++})},_initPreview:function(e){var i,a=this,r=a.initialCaption||"";return a.previewCache.count(!0)?(i=a.previewCache.out(),r=e&&a.initialCaption?a.initialCaption:i.caption,a._setPreviewContent(i.content),a._setInitThumbAttr(),a._setCaption(r),a._initSortable(),t.isEmpty(i.content)||a.$container.removeClass("file-input-new"),void a._initPreviewImageOrientations()):(a._clearPreview(),void (e?a._setCaption(r):a._initCaption()))},_getZoomButton:function(e){var t=this,i=t.previewZoomButtonIcons[e],a=t.previewZoomButtonClasses[e],r=' title="'+(t.previewZoomButtonTitles[e]||"")+'" ',n=r+("close"===e?' data-dismiss="modal" aria-hidden="true"':"");return("fullscreen"===e||"borderless"===e||"toggleheader"===e)&&(n+=' data-toggle="button" aria-pressed="false" autocomplete="off"'),'"},_getModalContent:function(){var e=this;return e._getLayoutTemplate("modal").setTokens({rtl:e.rtl?" kv-rtl":"",zoomFrameClass:e.frameClass,heading:e.msgZoomModalHeading,prev:e._getZoomButton("prev"),next:e._getZoomButton("next"),toggleheader:e._getZoomButton("toggleheader"),fullscreen:e._getZoomButton("fullscreen"),borderless:e._getZoomButton("borderless"),close:e._getZoomButton("close")})},_listenModalEvent:function(e){var i=this,a=i.$modal,r=function(e){return{sourceEvent:e,previewId:a.data("previewId"),modal:a}};a.on(e+".bs.modal",function(n){var o=a.find(".btn-fullscreen"),l=a.find(".btn-borderless");a.data("fileinputPluginId")===i.$element.attr("id")&&i._raise("filezoom"+e,r(n)),"shown"===e&&(l.removeClass("active").attr("aria-pressed","false"),o.removeClass("active").attr("aria-pressed","false"),a.hasClass("file-zoom-fullscreen")&&(i._maximizeZoomDialog(),t.checkFullScreen()?o.addClass("active").attr("aria-pressed","true"):l.addClass("active").attr("aria-pressed","true")))})},_initZoom:function(){var i,a=this,r=a._getLayoutTemplate("modalMain"),n="#"+t.MODAL_ID;a.showPreview&&(a.$modal=e(n),a.$modal&&a.$modal.length||(i=t.createElement(t.cspBuffer.stash(r)).insertAfter(a.$container),a.$modal=e(n).insertBefore(i),t.cspBuffer.apply(a.$modal),i.remove()),t.initModal(a.$modal),a.$modal.html(t.cspBuffer.stash(a._getModalContent())),t.cspBuffer.apply(a.$modal),e.each(t.MODAL_EVENTS,function(e,t){a._listenModalEvent(t)}))},_initZoomButtons:function(){var t,i,a=this,r=a.$modal.data("previewId")||"",n=a.getFrames().toArray(),o=n.length,l=a.$modal.find(".btn-prev"),s=a.$modal.find(".btn-next");return n.length<2?(l.hide(),void s.hide()):(l.show(),s.show(),void (o&&(t=e(n[0]),i=e(n[o-1]),l.removeAttr("disabled"),s.removeAttr("disabled"),t.length&&t.attr("id")===r&&l.attr("disabled",!0),i.length&&i.attr("id")===r&&s.attr("disabled",!0))))},_maximizeZoomDialog:function(){var t=this,i=t.$modal,a=i.find(".modal-header:visible"),r=i.find(".modal-footer:visible"),n=i.find(".modal-body"),o=e(window).height(),l=0;i.addClass("file-zoom-fullscreen"),a&&a.length&&(o-=a.outerHeight(!0)),r&&r.length&&(o-=r.outerHeight(!0)),n&&n.length&&(l=n.outerHeight(!0)-n.height(),o-=l),i.find(".kv-zoom-body").height(o)},_resizeZoomDialog:function(e){var i=this,a=i.$modal,r=a.find(".btn-fullscreen"),n=a.find(".btn-borderless");if(a.hasClass("file-zoom-fullscreen")){t.toggleFullScreen(!1),e?r.hasClass("active")||(a.removeClass("file-zoom-fullscreen"),i._resizeZoomDialog(!0),n.hasClass("active")&&n.removeClass("active").attr("aria-pressed","false")):r.hasClass("active")?r.removeClass("active").attr("aria-pressed","false"):(a.removeClass("file-zoom-fullscreen"),i.$modal.find(".kv-zoom-body").css("height",i.zoomModalHeight))}else{if(!e){return void i._maximizeZoomDialog()}t.toggleFullScreen(!0)}a.focus()},_setZoomContent:function(i,a){var r,n,o,l,s,d,c,u,p,f,g=this,m=i.attr("id"),h=g._getZoom(m),v=g.$modal,w=v.find(".btn-fullscreen"),b=v.find(".btn-borderless"),_=v.find(".btn-toggleheader");n=h.attr("data-template")||"generic",r=h.find(".kv-file-content"),o=r.length?r.html():"",p=i.data("caption")||"",f=i.data("size")||"",l=p+" "+f,v.find(".kv-zoom-title").attr("title",e("
    ").html(l).text()).html(l),s=v.find(".kv-zoom-body"),v.removeClass("kv-single-content"),a?(u=s.addClass("file-thumb-loading").clone().insertAfter(s),t.setHtml(s,o).hide(),u.fadeOut("fast",function(){s.fadeIn("fast",function(){s.removeClass("file-thumb-loading")}),u.remove()})):t.setHtml(s,o),c=g.previewZoomSettings[n],c&&(d=s.find(".kv-preview-data"),t.addCss(d,"file-zoom-detail"),e.each(c,function(e,t){d.css(e,t),(d.attr("width")&&"width"===e||d.attr("height")&&"height"===e)&&d.removeAttr(e)})),v.data("previewId",m),g._handler(v.find(".btn-prev"),"click",function(){g._zoomSlideShow("prev",m)}),g._handler(v.find(".btn-next"),"click",function(){g._zoomSlideShow("next",m)}),g._handler(w,"click",function(){g._resizeZoomDialog(!0)}),g._handler(b,"click",function(){g._resizeZoomDialog(!1)}),g._handler(_,"click",function(){var e,t=v.find(".modal-header"),i=v.find(".modal-body .floating-buttons"),a=t.find(".kv-zoom-actions"),r=function(e){var i=g.$modal.find(".kv-zoom-body"),a=g.zoomModalHeight;v.hasClass("file-zoom-fullscreen")&&(a=i.outerHeight(!0),e||(a-=t.outerHeight(!0))),i.css("height",e?a+e:a)};t.is(":visible")?(e=t.outerHeight(!0),t.slideUp("slow",function(){a.find(".btn").appendTo(i),r(e)})):(i.find(".btn").appendTo(a),t.slideDown("slow",function(){r()})),v.focus()}),g._handler(v,"keydown",function(t){var i=t.which||t.keyCode,a=e(this).find(".btn-prev"),r=e(this).find(".btn-next"),n=e(this).data("previewId"),o=g.rtl?39:37,l=g.rtl?37:39;i===o&&a.length&&!a.attr("disabled")&&g._zoomSlideShow("prev",n),i===l&&r.length&&!r.attr("disabled")&&g._zoomSlideShow("next",n)})},_showModal:function(e){var i=this,a=i.$modal;e&&e.length&&(t.initModal(a),t.setHtml(a,i._getModalContent()),i._setZoomContent(e),a.data("fileinputPluginId",i.$element.attr("id")),a.modal("show"),i._initZoomButtons())},_zoomPreview:function(e){var i,a=this;if(!e.length){throw"Cannot zoom to detailed preview!"}i=e.closest(t.FRAMES),a._showModal(i)},_zoomSlideShow:function(t,i){var a,r,n,o,l=this,s=l.$modal.find(".kv-zoom-actions .btn-"+t),d=l.getFrames().toArray(),c=[],u=d.length;if(!s.attr("disabled")){for(r=0;u>r;r++){n=e(d[r]),n&&n.length&&n.find(".kv-file-zoom:visible").length&&c.push(d[r])}for(u=c.length,r=0;u>r;r++){if(e(c[r]).attr("id")===i){o="prev"===t?r-1:r+1;break}}0>o||o>=u||!c[o]||(a=e(c[o]),a.length&&l._setZoomContent(a,!0),l._initZoomButtons(),l._raise("filezoom"+t,{previewId:i,modal:l.$modal}))}},_initZoomButton:function(){var t=this;t.$preview.find(".kv-file-zoom").each(function(){var i=e(this);t._handler(i,"click",function(){t._zoomPreview(i)})})},_inputFileCount:function(){return this.$element[0].files.length},_refreshPreview:function(){var t,i=this;(i._inputFileCount()||i.isAjaxUpload)&&i.showPreview&&i.isPreviewable&&(i.isAjaxUpload&&i.fileManager.count()>0?(t=e.extend(!0,{},i.fileManager.stack),i.fileManager.clear(),i._clearFileInput()):t=i.$element[0].files,t&&t.length&&(i.readFiles(t),i._setFileDropZoneTitle()))},_clearObjects:function(t){t.find("video audio").each(function(){this.pause(),e(this).remove()}),t.find("img object div").each(function(){e(this).remove()})},_clearFileInput:function(){var t,i,a,r=this,n=r.$element;r._inputFileCount()&&(t=n.closest("form"),i=e(document.createElement("form")),a=e(document.createElement("div")),n.before(a),t.length?t.after(i):a.after(i),i.append(n).trigger("reset"),a.before(n).remove(),i.remove())},_resetUpload:function(){var e=this;e.uploadStartTime=t.now(),e.uploadCache=[],e.$btnUpload.removeAttr("disabled"),e._setProgress(0),e._hideProgress(),e._resetErrors(!1),e._initAjax(),e.fileManager.clearImages(),e._resetCanvas(),e.overwriteInitial&&(e.initialPreview=[],e.initialPreviewConfig=[],e.initialPreviewThumbTags=[],e.previewCache.data={content:[],config:[],tags:[]})},_resetCanvas:function(){var e=this;e.canvas&&e.imageCanvasContext&&e.imageCanvasContext.clearRect(0,0,e.canvas.width,e.canvas.height)},_hasInitialPreview:function(){var e=this;return !e.overwriteInitial&&e.previewCache.count(!0)},_resetPreview:function(){var i,a,r,n=this,o=n.showUploadedThumbs,l=!n.removeFromPreviewOnError,s=(o||l)&&n.isDuplicateError;n.previewCache.count(!0)?(i=n.previewCache.out(),s&&(r=t.createElement("").insertAfter(n.$container),n.getFrames().each(function(){var t=e(this);(o&&t.hasClass("file-preview-success")||l&&t.hasClass("file-preview-error"))&&r.append(t)})),n._setPreviewContent(i.content),n._setInitThumbAttr(),a=n.initialCaption?n.initialCaption:i.caption,n._setCaption(a),s&&(r.contents().appendTo(n.$preview),r.remove())):(n._clearPreview(),n._initCaption()),n.showPreview&&(n._initZoom(),n._initSortable()),n.isDuplicateError=!1},_clearDefaultPreview:function(){var e=this;e.$preview.find(".file-default-preview").remove()},_validateDefaultPreview:function(){var e=this;e.showPreview&&!t.isEmpty(e.defaultPreviewContent)&&(e._setPreviewContent('
    '+e.defaultPreviewContent+"
    "),e.$container.removeClass("file-input-new"),e._initClickable())},_resetPreviewThumbs:function(e){var t,i=this;return e?(i._clearPreview(),void i.clearFileStack()):void (i._hasInitialPreview()?(t=i.previewCache.out(),i._setPreviewContent(t.content),i._setInitThumbAttr(),i._setCaption(t.caption),i._initPreviewActions()):i._clearPreview())},_getLayoutTemplate:function(e){var i=this,a=i.layoutTemplates[e];return t.isEmpty(i.customLayoutTags)?a:t.replaceTags(a,i.customLayoutTags)},_getPreviewTemplate:function(e){var i=this,a=i.previewTemplates,r=a[e]||a.other;return t.isEmpty(i.customPreviewTags)?r:t.replaceTags(r,i.customPreviewTags)},_getOutData:function(e,t,i,a){var r=this;return t=t||{},i=i||{},a=a||r.fileManager.list(),{formdata:e,files:a,filenames:r.filenames,filescount:r.getFilesCount(),extra:r._getExtraData(),response:i,reader:r.reader,jqXHR:t}},_getMsgSelected:function(e){var t=this,i=1===e?t.fileSingle:t.filePlural;return e>0?t.msgSelected.replace("{n}",e).replace("{files}",i):t.msgNoFilesSelected},_getFrame:function(e,i){var a=this,r=t.getFrameElement(a.$preview,e);return !a.showPreview||i||r.length||a._log(t.logMessages.invalidThumb,{id:e}),r},_getZoom:function(e,i){var a=this,r=t.getZoomElement(a.$preview,e,i);return a.showPreview&&!r.length&&a._log(t.logMessages.invalidThumb,{id:e}),r},_getThumbs:function(e){return e=e||"",this.getFrames(":not(.file-preview-initial)"+e)},_getThumbId:function(e){var t=this;return t.previewInitId+"-"+e},_getExtraData:function(e,t){var i=this,a=i.uploadExtraData;return"function"==typeof i.uploadExtraData&&(a=i.uploadExtraData(e,t)),a},_initXhr:function(e,i){var a=this,r=a.fileManager,n=function(e){var n=0,o=e.total,l=e.loaded||e.position,s=r.getUploadStats(i,l,o);e.lengthComputable&&!a.enableResumableUpload&&(n=t.round(l/o*100)),i?a._setFileUploadStats(i,n,s):a._setProgress(n,null,null,a._getStats(s)),a._raise("fileajaxprogress",[s])};return e.upload&&(a.progressDelay&&(n=t.debounce(n,a.progressDelay)),e.upload.addEventListener("progress",n,!1)),e},_initAjaxSettings:function(){var t=this;t._ajaxSettings=e.extend(!0,{},t.ajaxSettings),t._ajaxDeleteSettings=e.extend(!0,{},t.ajaxDeleteSettings)},_mergeAjaxCallback:function(e,t,i){var a,r=this,n=r._ajaxSettings,o=r.mergeAjaxCallbacks;"delete"===i&&(n=r._ajaxDeleteSettings,o=r.mergeAjaxDeleteCallbacks),a=n[e],o&&"function"==typeof a?"before"===o?n[e]=function(){a.apply(this,arguments),t.apply(this,arguments)}:n[e]=function(){t.apply(this,arguments),a.apply(this,arguments)}:n[e]=t},_ajaxSubmit:function(t,i,a,r,n,o,l,s){var d,c,u,p,f=this;f._raise("filepreajax",[n,o,l])&&(n.append("initialPreview",JSON.stringify(f.initialPreview)),n.append("initialPreviewConfig",JSON.stringify(f.initialPreviewConfig)),n.append("initialPreviewThumbTags",JSON.stringify(f.initialPreviewThumbTags)),f._initAjaxSettings(),f._mergeAjaxCallback("beforeSend",t),f._mergeAjaxCallback("success",i),f._mergeAjaxCallback("complete",a),f._mergeAjaxCallback("error",r),s=s||f.uploadUrlThumb||f.uploadUrl,"function"==typeof s&&(s=s()),u=f._getExtraData(o,l)||{},"object"==typeof u&&e.each(u,function(e,t){n.append(e,t)}),c={xhr:function(){var t=e.ajaxSettings.xhr();return f._initXhr(t,o)},url:f._encodeURI(s),type:"POST",dataType:"json",data:n,cache:!1,processData:!1,contentType:!1},d=e.extend(!0,{},c,f._ajaxSettings),p=f.taskManager.addTask(o+"-"+l,function(){var t,i,a=this.self;t=a.ajaxQueue.shift(),i=e.ajax(t),a.ajaxRequests.push(i)}),f.ajaxQueue.push(d),p.runWithContext({self:f}))},_mergeArray:function(e,i){var a=this,r=t.cleanArray(a[e]),n=t.cleanArray(i);a[e]=r.concat(n)},_initUploadSuccess:function(i,a,r){var n,o,l,s,d,c,u,p,f,g,m=this;return !m.showPreview||"object"!=typeof i||e.isEmptyObject(i)?void m._resetCaption():(void 0!==i.initialPreview&&i.initialPreview.length>0&&(m.hasInitData=!0,c=i.initialPreview||[],u=i.initialPreviewConfig||[],p=i.initialPreviewThumbTags||[],n=void 0===i.append||i.append,c.length>0&&!t.isArray(c)&&(c=c.split(m.initialPreviewDelimiter)),c.length&&(m._mergeArray("initialPreview",c),m._mergeArray("initialPreviewConfig",u),m._mergeArray("initialPreviewThumbTags",p)),void 0!==a?r?(f=a.attr("id"),g=m._getUploadCacheIndex(f),null!==g&&(m.uploadCache[g]={id:f,content:c[0],config:u[0]||[],tags:p[0]||[],append:n})):(l=m.previewCache.add(c[0],u[0],p[0],n),o=m.previewCache.get(l,!1),s=t.createElement(o).hide().appendTo(a),d=s.find(".kv-zoom-cache"),d&&d.length&&d.appendTo(a),a.fadeOut("slow",function(){var e=s.find(".file-preview-frame");e&&e.length&&e.insertBefore(a).fadeIn("slow").css("display:inline-block"),m._initPreviewActions(),m._clearFileInput(),a.remove(),s.remove(),m._initSortable()})):(m.previewCache.set(c,u,p,n),m._initPreview(),m._initPreviewActions())),void m._resetCaption())},_getUploadCacheIndex:function(e){var t,i,a=this,r=a.uploadCache.length;for(t=0;r>t;t++){if(i=a.uploadCache[t],i.id===e){return t}}return null},_initSuccessThumbs:function(){var i=this;i.showPreview&&i._getThumbs(t.FRAMES+".file-preview-success").each(function(){var a=e(this),r=a.find(".kv-file-remove");r.removeAttr("disabled"),i._handler(r,"click",function(){var e=a.attr("id"),r=i._raise("filesuccessremove",[e,a.attr("data-fileindex")]);t.cleanMemory(a),r!==!1&&a.fadeOut("slow",function(){a.remove(),i.getFrames().length||i.reset()})})})},_updateInitialPreview:function(){var t=this,i=t.uploadCache;t.showPreview&&(e.each(i,function(e,i){t.previewCache.add(i.content,i.config,i.tags,i.append)}),t.hasInitData&&(t._initPreview(),t._initPreviewActions()))},_uploadSingle:function(i,a,r){var n,o,l,s,d,c,u,p,f,g,m,h,v,w=this,b=w.fileManager,_=b.count(),C=new FormData,y=w._getThumbId(a),x=_>0||!e.isEmptyObject(w.uploadExtraData),T=w.ajaxOperations.uploadThumb,P=b.getFile(a),F={id:y,index:i,fileId:a},E=w.fileManager.getFileName(a,!0);w.enableResumableUpload||(w.showPreview&&(o=w.fileManager.getThumb(a),u=o.find(".file-thumb-progress"),s=o.find(".kv-file-upload"),d=o.find(".kv-file-remove"),u.show()),0===_||!x||w.showPreview&&s&&s.hasClass("disabled")||w._abort(F)||(v=function(){c?b.errors.push(a):b.removeFile(a),b.setProcessed(a),b.isProcessed()&&(w.fileBatchCompleted=!0,l())},l=function(){var e;w.fileBatchCompleted&&setTimeout(function(){var i=0===b.count(),a=b.errors.length;w._updateInitialPreview(),w.unlock(i),i&&w._clearFileInput(),e=w.$preview.find(".file-preview-initial"),w.uploadAsync&&e.length&&(t.addCss(e,t.SORT_CSS),w._initSortable()),w._raise("filebatchuploadcomplete",[b.stack,w._getExtraData()]),w.retryErrorUploads&&0!==a||b.clear(),w._setProgress(101),w.ajaxAborted=!1},w.processDelay)},p=function(l){n=w._getOutData(C,l),b.initStats(a),w.fileBatchCompleted=!1,r||(w.ajaxAborted=!1),w.showPreview&&(o.hasClass("file-preview-success")||(w._setThumbStatus(o,"Loading"),t.addCss(o,"file-uploading")),s.attr("disabled",!0),d.attr("disabled",!0)),r||w.lock(),-1!==b.errors.indexOf(a)&&delete b.errors[a],w._raise("filepreupload",[n,y,i]),e.extend(!0,F,n),w._abort(F)&&(l.abort(),r||(w._setThumbStatus(o,"New"),o.removeClass("file-uploading"),s.removeAttr("disabled"),d.removeAttr("disabled"),w.unlock()),w._setProgressCancelled())},g=function(l,d,p){var g=w.showPreview&&o.attr("id")?o.attr("id"):y;n=w._getOutData(C,p,l),e.extend(!0,F,n),setTimeout(function(){t.isEmpty(l)||t.isEmpty(l.error)?(w.showPreview&&(w._setThumbStatus(o,"Success"),s.hide(),w._initUploadSuccess(l,o,r),w._setProgress(101,u)),w._raise("fileuploaded",[n,g,i]),r?v():w.fileManager.remove(o)):(c=!0,f=w._parseError(T,p,w.msgUploadError,w.fileManager.getFileName(a)),w._showFileError(f,F),w._setPreviewError(o,!0),w.retryErrorUploads||s.hide(),r&&v(),w._setProgress(101,w._getFrame(g).find(".file-thumb-progress"),w.msgUploadError))},w.processDelay)},m=function(){w.showPreview&&(s.removeAttr("disabled"),d.removeAttr("disabled"),o.removeClass("file-uploading")),r?l():(w.unlock(!1),w._clearFileInput()),w._initSuccessThumbs()},h=function(t,i,n){f=w._parseError(T,t,n,w.fileManager.getFileName(a)),c=!0,setTimeout(function(){var i;r&&v(),w.fileManager.setProgress(a,100),w._setPreviewError(o,!0),w.retryErrorUploads||s.hide(),e.extend(!0,F,w._getOutData(C,t)),w._setProgress(101,w.$progress,w.msgAjaxProgressError.replace("{operation}",T)),i=w.showPreview&&o?o.find(".file-thumb-progress"):"",w._setProgress(101,i,w.msgUploadError),w._showFileError(f,F)},w.processDelay)},w._setFileData(C,P.file,E,a),w._setUploadData(C,{fileId:a}),w._ajaxSubmit(p,g,m,h,C,a,i)))},_setFileData:function(e,t,i,a){var r=this,n=r.preProcessUpload;n&&"function"==typeof n?e.append(r.uploadFileAttr,n(a,t)):e.append(r.uploadFileAttr,t,i)},_uploadBatch:function(){var i,a,r,n,o,l,s=this,d=s.fileManager,c=d.total(),u={},p=c>0||!e.isEmptyObject(s.uploadExtraData),f=new FormData,g=s.ajaxOperations.uploadBatch;if(0!==c&&p&&!s._abort(u)){l=function(){s.fileManager.clear(),s._clearFileInput()},i=function(i){s.lock(),d.initStats();var a=s._getOutData(f,i);s.ajaxAborted=!1,s.showPreview&&s._getThumbs().each(function(){var i=e(this),a=i.find(".kv-file-upload"),r=i.find(".kv-file-remove");i.hasClass("file-preview-success")||(s._setThumbStatus(i,"Loading"),t.addCss(i,"file-uploading")),a.attr("disabled",!0),r.attr("disabled",!0)}),s._raise("filebatchpreupload",[a]),s._abort(a)&&(i.abort(),s._getThumbs().each(function(){var t=e(this),i=t.find(".kv-file-upload"),a=t.find(".kv-file-remove");t.hasClass("file-preview-loading")&&(s._setThumbStatus(t,"New"),t.removeClass("file-uploading")),i.removeAttr("disabled"),a.removeAttr("disabled")}),s._setProgressCancelled())},a=function(i,a,r){var n=s._getOutData(f,r,i),d=0,c=s._getThumbs(":not(.file-preview-success)"),u=t.isEmpty(i)||t.isEmpty(i.errorkeys)?[]:i.errorkeys;t.isEmpty(i)||t.isEmpty(i.error)?(s._raise("filebatchuploadsuccess",[n]),l(),s.showPreview?(c.each(function(){var t=e(this);s._setThumbStatus(t,"Success"),t.removeClass("file-uploading"),t.find(".kv-file-upload").hide().removeAttr("disabled")}),s._initUploadSuccess(i)):s.reset(),s._setProgress(101)):(s.showPreview&&(c.each(function(){var t=e(this);t.removeClass("file-uploading"),t.find(".kv-file-upload").removeAttr("disabled"),t.find(".kv-file-remove").removeAttr("disabled"),0===u.length||-1!==e.inArray(d,u)?(s._setPreviewError(t,!0),s.retryErrorUploads||(t.find(".kv-file-upload").hide(),s.fileManager.remove(t))):(t.find(".kv-file-upload").hide(),s._setThumbStatus(t,"Success"),s.fileManager.remove(t)),(!t.hasClass("file-preview-error")||s.retryErrorUploads)&&d++}),s._initUploadSuccess(i)),o=s._parseError(g,r,s.msgUploadError),s._showFileError(o,n,"filebatchuploaderror"),s._setProgress(101,s.$progress,s.msgUploadError))},n=function(){s.unlock(),s._initSuccessThumbs(),s._clearFileInput(),s._raise("filebatchuploadcomplete",[s.fileManager.stack,s._getExtraData()])},r=function(t,i,a){var r=s._getOutData(f,t);o=s._parseError(g,t,a),s._showFileError(o,r,"filebatchuploaderror"),s.uploadFileCount=c-1,s.showPreview&&(s._getThumbs().each(function(){var t=e(this);t.removeClass("file-uploading"),s.fileManager.getFile(t.attr("data-fileid"))&&s._setPreviewError(t)}),s._getThumbs().removeClass("file-uploading"),s._getThumbs(" .kv-file-upload").removeAttr("disabled"),s._getThumbs(" .kv-file-delete").removeAttr("disabled"),s._setProgress(101,s.$progress,s.msgAjaxProgressError.replace("{operation}",g)))};var m=0;e.each(s.fileManager.stack,function(e,i){t.isEmpty(i.file)||s._setFileData(f,i.file,i.nameFmt||"untitled_"+m,e),m++}),s._ajaxSubmit(i,a,n,r,f)}},_uploadExtraOnly:function(){var e,i,a,r,n,o=this,l={},s=new FormData,d=o.ajaxOperations.uploadExtra;o._abort(l)||(e=function(e){o.lock();var t=o._getOutData(s,e);o._raise("filebatchpreupload",[t]),o._setProgress(50),l.data=t,l.xhr=e,o._abort(l)&&(e.abort(),o._setProgressCancelled())},i=function(e,i,a){var r=o._getOutData(s,a,e);t.isEmpty(e)||t.isEmpty(e.error)?(o._raise("filebatchuploadsuccess",[r]),o._clearFileInput(),o._initUploadSuccess(e),o._setProgress(101)):(n=o._parseError(d,a,o.msgUploadError),o._showFileError(n,r,"filebatchuploaderror"))},a=function(){o.unlock(),o._clearFileInput(),o._raise("filebatchuploadcomplete",[o.fileManager.stack,o._getExtraData()])},r=function(e,t,i){var a=o._getOutData(s,e);n=o._parseError(d,e,i),l.data=a,o._showFileError(n,a,"filebatchuploaderror"),o._setProgress(101,o.$progress,o.msgAjaxProgressError.replace("{operation}",d))},o._ajaxSubmit(e,i,a,r,s))},_deleteFileIndex:function(i){var a=this,r=i.attr("data-fileindex"),n=a.reversePreviewOrder;r.substring(0,5)===t.INIT_FLAG&&(r=parseInt(r.replace(t.INIT_FLAG,"")),a.initialPreview=t.spliceArray(a.initialPreview,r,n),a.initialPreviewConfig=t.spliceArray(a.initialPreviewConfig,r,n),a.initialPreviewThumbTags=t.spliceArray(a.initialPreviewThumbTags,r,n),a.getFrames().each(function(){var i=e(this),a=i.attr("data-fileindex");a.substring(0,5)===t.INIT_FLAG&&(a=parseInt(a.replace(t.INIT_FLAG,"")),a>r&&(a--,i.attr("data-fileindex",t.INIT_FLAG+a)))}))},_resetCaption:function(){var e=this;setTimeout(function(){var t,i,a,r=e.previewCache.count(!0),n=e.fileManager.count(),o=":not(.file-preview-success):not(.file-preview-error)",l=e.showPreview&&e.getFrames(o).length;0!==n||0!==r||l?(i=r+n,i>1?t=e._getMsgSelected(i):(a=e.fileManager.getFirstFile(),t=a?a.nameFmt:"_"),e._setCaption(t)):e.reset()},e.processDelay)},_initFileActions:function(){var i=this;i.showPreview&&(i._initZoomButton(),i.getFrames(" .kv-file-remove").each(function(){var a,r,n=e(this),o=n.closest(t.FRAMES),l=o.attr("id"),s=o.attr("data-fileindex");i._handler(n,"click",function(){return r=i._raise("filepreremove",[l,s]),r!==!1&&i._validateMinCount()?(a=o.hasClass("file-preview-error"),t.cleanMemory(o),void o.fadeOut("slow",function(){i.fileManager.remove(o),i._clearObjects(o),o.remove(),l&&a&&i.$errorContainer.find('li[data-thumb-id="'+l+'"]').fadeOut("fast",function(){e(this).remove(),i._errorsExist()||i._resetErrors()}),i._clearFileInput(),i._resetCaption(),i._raise("fileremoved",[l,s])})):!1})}),i.getFrames(" .kv-file-upload").each(function(){var a=e(this);i._handler(a,"click",function(){var e=a.closest(t.FRAMES),r=e.attr("data-fileid");i._hideProgress(),(!e.hasClass("file-preview-error")||i.retryErrorUploads)&&i._uploadSingle(i.fileManager.getIndex(r),r,!1)})}))},_initPreviewActions:function(){var i=this,a=i.$preview,r=i.deleteExtraData||{},n=t.FRAMES+" .kv-file-remove",o=i.fileActionSettings,l=o.removeClass,s=o.removeErrorClass,d=function(){var e=i.isAjaxUpload?i.previewCache.count(!0):i._inputFileCount();i.getFrames().length||e||(i._setCaption(""),i.reset(),i.initialCaption="")};i._initZoomButton(),a.find(n).each(function(){var a,n,o,c,u=e(this),p=u.data("url")||i.deleteUrl,f=u.data("key"),g=i.ajaxOperations.deleteThumb;if(!t.isEmpty(p)&&void 0!==f){"function"==typeof p&&(p=p());var m,h,v,w,b,_=u.closest(t.FRAMES),C=i.previewCache.data,y=_.attr("data-fileindex");y=parseInt(y.replace(t.INIT_FLAG,"")),v=t.isEmpty(C.config)&&t.isEmpty(C.config[y])?null:C.config[y],b=t.isEmpty(v)||t.isEmpty(v.extra)?r:v.extra,w=v&&(v.filename||v.caption)||"","function"==typeof b&&(b=b()),h={id:u.attr("id"),key:f,extra:b},n=function(e){i.ajaxAborted=!1,i._raise("filepredelete",[f,e,b]),i._abort()?e.abort():(u.removeClass(s),t.addCss(_,"file-uploading"),t.addCss(u,"disabled "+l))},o=function(e,r,n){var o,c;return t.isEmpty(e)||t.isEmpty(e.error)?(_.removeClass("file-uploading").addClass("file-deleted"),void _.fadeOut("slow",function(){y=parseInt(_.attr("data-fileindex").replace(t.INIT_FLAG,"")),i.previewCache.unset(y),i._deleteFileIndex(_),o=i.previewCache.count(!0),c=o>0?i._getMsgSelected(o):"",i._setCaption(c),i._raise("filedeleted",[f,n,b]),i._clearObjects(_),_.remove(),d()})):(h.jqXHR=n,h.response=e,a=i._parseError(g,n,i.msgDeleteError,w),i._showFileError(a,h,"filedeleteerror"),_.removeClass("file-uploading"),u.removeClass("disabled "+l).addClass(s),void d())},c=function(e,t,a){var r=i._parseError(g,e,a,w);h.jqXHR=e,h.response={},i._showFileError(r,h,"filedeleteerror"),_.removeClass("file-uploading"),u.removeClass("disabled "+l).addClass(s),d()},i._initAjaxSettings(),i._mergeAjaxCallback("beforeSend",n,"delete"),i._mergeAjaxCallback("success",o,"delete"),i._mergeAjaxCallback("error",c,"delete"),m=e.extend(!0,{},{url:i._encodeURI(p),type:"POST",dataType:"json",data:e.extend(!0,{},{key:f},b)},i._ajaxDeleteSettings),i._handler(u,"click",function(){return i._validateMinCount()?(i.ajaxAborted=!1,i._raise("filebeforedelete",[f,b]),void (i.ajaxAborted instanceof Promise?i.ajaxAborted.then(function(t){t||e.ajax(m)}):i.ajaxAborted||e.ajax(m))):!1})}})},_hideFileIcon:function(){var e=this;e.overwriteInitial&&e.$captionContainer.removeClass("icon-visible")},_showFileIcon:function(){var e=this;t.addCss(e.$captionContainer,"icon-visible")},_getSize:function(t,i){var a,r,n=this,o=parseFloat(t),l=n.fileSizeGetter;return e.isNumeric(t)&&e.isNumeric(o)?("function"==typeof l?r=l(o):0===o?r="0.00 B":(a=Math.floor(Math.log(o)/Math.log(1024)),i||(i=["B","KB","MB","GB","TB","PB","EB","ZB","YB"]),r=1*(o/Math.pow(1024,a)).toFixed(2)+" "+i[a]),n._getLayoutTemplate("size").replace("{sizeText}",r)):""},_getFileType:function(e){var t=this;return t.mimeTypeAliases[e]||e},_generatePreviewTemplate:function(i,a,r,n,o,l,s,d,c,u,p,f,g,m){var h,v,w,b=this,_=b.slug(r),C="",y="",x=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,T=_,P=_,F="type-default",E=u||b._renderFileFooter(i,_,d,"auto",s),k=b.preferIconicPreview,S=b.preferIconicZoomPreview,I=k?"other":i;return v=400>x?b.previewSettingsSmall[I]||b.defaults.previewSettingsSmall[I]:b.previewSettings[I]||b.defaults.previewSettings[I],v&&e.each(v,function(e,t){y+=e+":"+t+";"}),w=function(a,s,d,u){var m=d?"zoom-"+o:o,h=b._getPreviewTemplate(a),v=(c||"")+" "+u;return b.frameClass&&(v=b.frameClass+" "+v),d&&(v=v.replace(" "+t.SORT_CSS,"")),h=b._parseFilePreviewIcon(h,r),"object"!==i||n||e.each(b.defaults.fileTypeSettings,function(e,t){"object"!==e&&"other"!==e&&t(r,n)&&(F="type-"+e)}),t.isEmpty(g)||(void 0!==g.title&&null!==g.title&&(T=g.title),void 0!==g.alt&&null!==g.alt&&(T=g.alt)),h.setTokens({previewId:m,caption:_,title:T,alt:P,frameClass:v,type:b._getFileType(n),fileindex:p,fileid:l||"",typeCss:F,footer:E,data:s,template:f||i,style:y?'style="'+y+'"':""})},p=p||o.slice(o.lastIndexOf("-")+1),b.fileActionSettings.showZoom&&(C=w(S?"other":i,m?m:a,!0,"kv-zoom-thumb")),C="\n"+b._getLayoutTemplate("zoomCache").replace("{zoomContent}",C),"function"==typeof b.sanitizeZoomCache&&(C=b.sanitizeZoomCache(C)),h=w(k?"other":i,a,!1,"kv-preview-thumb"),h.setTokens({zoomCache:C})},_addToPreview:function(e,i){var a,r=this;return i=t.cspBuffer.stash(i),a=r.reversePreviewOrder?e.prepend(i):e.append(i),t.cspBuffer.apply(e),a},_previewDefault:function(e,i){var a=this,r=a.$preview;if(a.showPreview){var n,o=t.getFileName(e),l=e?e.type:"",s=e.size||0,d=a._getFileName(e,""),c=i===!0&&!a.isAjaxUpload,u=t.createObjectURL(e),p=a.fileManager.getId(e),f=a._getThumbId(p);a._clearDefaultPreview(),n=a._generatePreviewTemplate("other",u,o,l,f,p,c,s),a._addToPreview(r,n),a._setThumbAttr(f,d,s),i===!0&&a.isAjaxUpload&&a._setThumbStatus(a._getFrame(f),"Error")}},_previewFile:function(e,i,a,r,n){if(this.showPreview){var o,l=this,s=t.getFileName(i),d=n.type,c=n.name,u=l._parseFileType(d,s),p=l.$preview,f=i.size||0,g="image"===u?a.target.result:r,m=l.fileManager.getId(i),h=l._getThumbId(m);o=l._generatePreviewTemplate(u,g,s,d,h,m,!1,f),l._clearDefaultPreview(),l._addToPreview(p,o);var v=l._getFrame(h);l._validateImageOrientation(v.find("img"),i,h,m,c,d,f,g),l._setThumbAttr(h,c,f),l._initSortable()}},_setThumbAttr:function(e,t,i){var a=this,r=a._getFrame(e);r.length&&(i=i&&i>0?a._getSize(i):"",r.data({caption:t,size:i}))},_setInitThumbAttr:function(){var e,i,a,r,n=this,o=n.previewCache.data,l=n.previewCache.count(!0);if(0!==l){for(var s=0;l>s;s++){e=o.config[s],r=n.previewInitId+"-"+t.INIT_FLAG+s,i=t.ifSet("caption",e,t.ifSet("filename",e)),a=t.ifSet("size",e),n._setThumbAttr(r,i,a)}}},_slugDefault:function(e){return t.isEmpty(e,!0)?"":(e+"").replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g,"_")},_updateFileDetails:function(e,i){var a,r,n,o,l,s=this,d=s.$element,c=t.isIE(9)&&t.findFileName(d.val())||d[0].files[0]&&d[0].files[0].name;!c&&s.fileManager.count()>0?(l=s.fileManager.getFirstFile(),a=l.nameFmt):a=c?s.slug(c):"_",r=s.isAjaxUpload?s.fileManager.count():e,o=s.previewCache.count(!0)+r,n=1===r?a:s._getMsgSelected(o),s.isError?(s.$previewContainer.removeClass("file-thumb-loading"),s.$previewStatus.html(""),s.$captionContainer.removeClass("icon-visible")):s._showFileIcon(),s._setCaption(n,s.isError),s.$container.removeClass("file-input-new file-input-ajax-new"),i||s._raise("fileselect",[e,a]),s.previewCache.count(!0)&&s._initPreviewActions()},_setThumbStatus:function(e,i){var a=this;if(a.showPreview){var r="indicator"+i,n=r+"Title",o="file-preview-"+i.toLowerCase(),l=e.find(".file-upload-indicator"),s=a.fileActionSettings;e.removeClass("file-preview-success file-preview-error file-preview-paused file-preview-loading"),"Success"===i&&e.find(".file-drag-handle").remove(),t.setHtml(l,s[r]),l.attr("title",s[n]),e.addClass(o),"Error"!==i||a.retryErrorUploads||e.find(".kv-file-upload").attr("disabled",!0)}},_setProgressCancelled:function(){var e=this;e._setProgress(101,e.$progress,e.msgCancelled)},_setProgress:function(e,i,a,r){var n=this;if(i=i||n.$progress,i.length){var o,l=Math.min(e,100),s=n.progressUploadThreshold,d=100>=e?n.progressTemplate:n.progressCompleteTemplate,c=100>l?n.progressTemplate:a?n.paused?n.progressPauseTemplate:n.progressErrorTemplate:d;e>=100&&(r=""),t.isEmpty(c)||(o=s&&l>s&&100>=e?c.setTokens({percent:s,status:n.msgUploadThreshold}):c.setTokens({percent:l,status:e>100?n.msgUploadEnd:l+"%"}),r=r||"",o=o.setTokens({stats:r}),t.setHtml(i,o),a&&t.setHtml(i.find('[role="progressbar"]'),a))}},_hasFiles:function(){var e=this.$element[0];return !!(e&&e.files&&e.files.length)},_setFileDropZoneTitle:function(){var e,i=this,a=i.$container.find(".file-drop-zone"),r=i.dropZoneTitle;i.isClickable&&(e=t.isEmpty(i.$element.attr("multiple"))?i.fileSingle:i.filePlural,r+=i.dropZoneClickTitle.replace("{files}",e)),a.find("."+i.dropZoneTitleClass).remove(),!i.showPreview||0===a.length||i.fileManager.count()>0||!i.dropZoneEnabled||i.previewCache.count()>0||!i.isAjaxUpload&&i._hasFiles()||(0===a.find(t.FRAMES).length&&t.isEmpty(i.defaultPreviewContent)&&a.prepend('
    '+r+"
    "),i.$container.removeClass("file-input-new"),t.addCss(i.$container,"file-input-ajax-new"))},_getStats:function(e){var i,a,r=this;return r.showUploadStats&&e&&e.bitrate?(a=r._getLayoutTemplate("stats"),i=e.elapsed&&e.bps?r.msgPendingTime.setTokens({time:t.getElapsed(Math.ceil(e.pendingBytes/e.bps))}):r.msgCalculatingTime,a.setTokens({uploadSpeed:e.bitrate,pendingTime:i})):""},_setResumableProgress:function(e,t,i){var a=this,r=a.resumableManager,n=i?r:a,o=i?i.find(".file-thumb-progress"):null;0===n.lastProgress&&(n.lastProgress=e),e0&&e._getFileCount(t-1)=g:g>=d,u||(s=p["msgImage"+o+i].setTokens({name:n,size:g}),p._showFileError(s,l),p._setPreviewError(r)))},_getExifObj:function(e){var i,a=this,r=t.logMessages.exifWarning;if("data:image/jpeg;base64,"!==e.slice(0,23)&&"data:image/jpg;base64,"!==e.slice(0,22)){return void (i=null)}try{i=window.piexif?window.piexif.load(e):null}catch(n){i=null,r=n&&n.message||""}return i||a._log(t.logMessages.badExifParser,{details:r}),i},setImageOrientation:function(i,a,r,n){var o,l,s,d=this,c=!i||!i.length,u=!a||!a.length,p=!1,f=c&&n&&"image"===n.attr("data-template");c&&u||(s="load.fileinputimageorient",f?(i=a,a=null,i.css(d.previewSettings.image),l=e(document.createElement("div")).appendTo(n.find(".kv-file-content")),o=e(document.createElement("span")).insertBefore(i),i.css("visibility","hidden").removeClass("file-zoom-detail").appendTo(l)):p=!i.is(":visible"),i.off(s).on(s,function(){p&&(d.$preview.removeClass("hide-content"),n.find(".kv-file-content").css("visibility","hidden"));var e=i[0],s=a&&a.length?a[0]:null,c=e.offsetHeight,u=e.offsetWidth,g=t.getRotation(r);if(p&&(n.find(".kv-file-content").css("visibility","visible"),d.$preview.addClass("hide-content")),i.data("orientation",r),s&&a.data("orientation",r),5>r){return t.setTransform(e,g),void t.setTransform(s,g)}var m=Math.atan(u/c),h=Math.sqrt(Math.pow(c,2)+Math.pow(u,2)),v=h?c/Math.cos(Math.PI/2+m)/h:1,w=" scale("+Math.abs(v)+")";t.setTransform(e,g+w),t.setTransform(s,g+w),f&&(i.css("visibility","visible").insertAfter(o).addClass("file-zoom-detail"),o.remove(),l.remove())}))},_validateImageOrientation:function(i,a,r,n,o,l,s,d){var c,u,p,f=this,g=f.autoOrientImage;return f.canOrientImage?void i.css("image-orientation",g?"from-image":"none"):(p=t.getZoomSelector(r," img"),c=g?f._getExifObj(d):null,(u=c?c["0th"][piexif.ImageIFD.Orientation]:null)?(f.setImageOrientation(i,e(p),u,f._getFrame(r)),f._raise("fileimageoriented",{$img:i,file:a}),void f._validateImage(r,n,o,l,s,d,c)):void f._validateImage(r,n,o,l,s,d,c))},_validateImage:function(t,i,a,r,n,o,l){var s,d,c,u=this,p=u.$preview,f=u._getFrame(t),g=f.attr("data-fileindex"),m=f.find("img");a=a||"Untitled",m.one("load",function(){d=f.width(),c=p.width(),d>c&&m.css("width","100%"),s={ind:g,id:t,fileId:i},u._checkDimensions(g,"Small",m,f,a,"Width",s),u._checkDimensions(g,"Small",m,f,a,"Height",s),u.resizeImage||(u._checkDimensions(g,"Large",m,f,a,"Width",s),u._checkDimensions(g,"Large",m,f,a,"Height",s)),u._raise("fileimageloaded",[t]),u.fileManager.addImage(i,{ind:g,img:m,thumb:f,pid:t,typ:r,siz:n,validated:!1,imgData:o,exifObj:l}),f.data("exif",l),u._validateAllImages()}).one("error",function(){u._raise("fileimageloaderror",[t])}).each(function(){this.complete?e(this).trigger("load"):this.error&&e(this).trigger("error")})},_validateAllImages:function(){var t,i=this,a={val:0},r=i.fileManager.getImageCount(),n=i.resizeIfSizeMoreThan;r===i.fileManager.totalImages&&(i._raise("fileimagesloaded"),i.resizeImage&&e.each(i.fileManager.loadedImages,function(e,o){o.validated||(t=o.siz,t&&t>1000*n&&i._getResizedImage(e,o,a,r),o.validated=!0)}))},_getResizedImage:function(i,a,r,n){var o,l,s,d,c,u,p,f,g,m,h=this,v=e(a.img)[0],w=v.naturalWidth,b=v.naturalHeight,_=1,C=h.maxImageWidth||w,y=h.maxImageHeight||b,x=!(!w||!b),T=h.imageCanvas,P=h.imageCanvasContext,F=a.typ,E=a.pid,k=a.ind,S=a.thumb,I=a.exifObj;if(c=function(e,t,i){h.isAjaxUpload?h._showFileError(e,t,i):h._showError(e,t,i),h._setPreviewError(S)},f=h.fileManager.getFile(i),g={id:E,index:k,fileId:i},m=[i,E,k],(!f||!x||C>=w&&y>=b)&&(x&&f&&h._raise("fileimageresized",m),r.val++,r.val===n&&h._raise("fileimagesresized"),!x)){return void c(h.msgImageResizeError,g,"fileimageresizeerror")}F=F||h.resizeDefaultImageType,l=w>C,s=b>y,_="width"===h.resizePreference?l?C/w:s?y/b:1:s?y/b:l?C/w:1,h._resetCanvas(),w*=_,b*=_,T.width=w,T.height=b;try{P.drawImage(v,0,0,w,b),d=T.toDataURL(F,h.resizeQuality),I&&(p=window.piexif.dump(I),d=window.piexif.insert(p,d)),o=t.dataURI2Blob(d),h.fileManager.setFile(i,o),h._raise("fileimageresized",m),r.val++,r.val===n&&h._raise("fileimagesresized",[void 0,void 0]),o instanceof Blob||c(h.msgImageResizeError,g,"fileimageresizeerror")}catch(A){r.val++,r.val===n&&h._raise("fileimagesresized",[void 0,void 0]),u=h.msgImageResizeException.replace("{errors}",A.message),c(u,g,"fileimageresizeexception")}},_showProgress:function(){var e=this;e.$progress&&e.$progress.length&&e.$progress.show()},_hideProgress:function(){var e=this;e.$progress&&e.$progress.length&&e.$progress.hide()},_initBrowse:function(e){var i=this,a=i.$element;i.showBrowse?i.$btnFile=e.find(".btn-file").append(a):(a.appendTo(e).attr("tabindex",-1),t.addCss(a,"file-no-browse"))},_initClickable:function(){var i,a,r=this;r.isClickable&&(i=r.$dropZone,r.isAjaxUpload||(a=r.$preview.find(".file-default-preview"),a.length&&(i=a)),t.addCss(i,"clickable"),i.attr("tabindex",-1),r._handler(i,"click",function(t){var a=e(t.target);e(r.elErrorContainer+":visible").length||a.parents(".file-preview-thumbnails").length&&!a.parents(".file-default-preview").length||(r.$element.data("zoneClicked",!0).trigger("click"),i.blur())}))},_initCaption:function(){var e=this,i=e.initialCaption||"";return e.overwriteInitial||t.isEmpty(i)?(e.$caption.val(""),!1):(e._setCaption(i),!0)},_setCaption:function(i,a){var r,n,o,l,s,d,c=this;if(c.$caption.length){if(c.$captionContainer.removeClass("icon-visible"),a){r=e("
    "+c.msgValidationError+"
    ").text(),l=c.fileManager.count(),l?(d=c.fileManager.getFirstFile(),s=1===l&&d?d.nameFmt:c._getMsgSelected(l)):s=c._getMsgSelected(c.msgNo),n=t.isEmpty(i)?s:i,o=''+c.msgValidationErrorIcon+""}else{if(t.isEmpty(i)){return}r=e("
    "+i+"
    ").text(),n=r,o=c._getLayoutTemplate("fileIcon")}c.$captionContainer.addClass("icon-visible"),c.$caption.attr("title",r).val(n),t.setHtml(c.$captionIcon,o)}},_createContainer:function(){var e=this,i={"class":"file-input file-input-new"+(e.rtl?" kv-rtl":"")},a=t.createElement(t.cspBuffer.stash(e._renderMain()));return t.cspBuffer.apply(a),a.insertBefore(e.$element).attr(i),e._initBrowse(a),e.theme&&a.addClass("theme-"+e.theme),a},_refreshContainer:function(){var e=this,i=e.$container,a=e.$element;a.insertAfter(i),t.setHtml(i,e._renderMain()),e._initBrowse(i),e._validateDisabled()},_validateDisabled:function(){var e=this;e.$caption.attr({readonly:e.isDisabled})},_renderMain:function(){var e=this,t=e.dropZoneEnabled?" file-drop-zone":"file-drop-disabled",i=e.showClose?e._getLayoutTemplate("close"):"",a=e.showPreview?e._getLayoutTemplate("preview").setTokens({"class":e.previewClass,dropClass:t}):"",r=e.isDisabled?e.captionClass+" file-caption-disabled":e.captionClass,n=e.captionTemplate.setTokens({"class":r+" kv-fileinput-caption"});return e.mainTemplate.setTokens({"class":e.mainClass+(!e.showBrowse&&e.showCaption?" no-browse":""),preview:a,close:i,caption:n,upload:e._renderButton("upload"),remove:e._renderButton("remove"),cancel:e._renderButton("cancel"),pause:e._renderButton("pause"),browse:e._renderButton("browse")})},_renderButton:function(e){var i=this,a=i._getLayoutTemplate("btnDefault"),r=i[e+"Class"],n=i[e+"Title"],o=i[e+"Icon"],l=i[e+"Label"],s=i.isDisabled?" disabled":"",d="button";switch(e){case"remove":if(!i.showRemove){return""}break;case"cancel":if(!i.showCancel){return""}r+=" kv-hidden";break;case"pause":if(!i.showPause){return""}r+=" kv-hidden";break;case"upload":if(!i.showUpload){return""}i.isAjaxUpload&&!i.isDisabled?a=i._getLayoutTemplate("btnLink").replace("{href}",i.uploadUrl):d="submit";break;case"browse":if(!i.showBrowse){return""}a=i._getLayoutTemplate("btnBrowse");break;default:return""}return r+="browse"===e?" btn-file":" fileinput-"+e+" fileinput-"+e+"-button",t.isEmpty(l)||(l=' '+l+""),a.setTokens({type:d,css:r,title:n,status:s,icon:o,label:l})},_renderThumbProgress:function(){var e=this;return'
    '+e.progressInfoTemplate.setTokens({percent:101,status:e.msgUploadBegin,stats:""})+"
    "},_renderFileFooter:function(e,i,a,r,n){var o,l,s=this,d=s.fileActionSettings,c=d.showRemove,u=d.showDrag,p=d.showUpload,f=d.showZoom,g=s._getLayoutTemplate("footer"),m=s._getLayoutTemplate("indicator"),h=n?d.indicatorError:d.indicatorNew,v=n?d.indicatorErrorTitle:d.indicatorNewTitle,w=m.setTokens({indicator:h,indicatorTitle:v});return a=s._getSize(a),l={type:e,caption:i,size:a,width:r,progress:"",indicator:w},s.isAjaxUpload?(l.progress=s._renderThumbProgress(),l.actions=s._renderFileActions(l,p,!1,c,f,u,!1,!1,!1)):l.actions=s._renderFileActions(l,!1,!1,!1,f,u,!1,!1,!1),o=g.setTokens(l),o=t.replaceTags(o,s.previewThumbTags)},_renderFileActions:function(e,t,i,a,r,n,o,l,s,d,c,u){var p=this;if(!e.type&&d&&(e.type="image"),p.enableResumableUpload?t=!1:"function"==typeof t&&(t=t(e)),"function"==typeof i&&(i=i(e)),"function"==typeof a&&(a=a(e)),"function"==typeof r&&(r=r(e)),"function"==typeof n&&(n=n(e)),!(t||i||a||r||n)){return""}var f,g=l===!1?"":' data-url="'+l+'"',m="",h="",v=s===!1?"":' data-key="'+s+'"',w="",b="",_="",C=p._getLayoutTemplate("actions"),y=p.fileActionSettings,x=p.otherActionButtons.setTokens({dataKey:v,key:s}),T=o?y.removeClass+" disabled":y.removeClass;return a&&(w=p._getLayoutTemplate("actionDelete").setTokens({removeClass:T,removeIcon:y.removeIcon,removeTitle:y.removeTitle,dataUrl:g,dataKey:v,key:s})),t&&(b=p._getLayoutTemplate("actionUpload").setTokens({uploadClass:y.uploadClass,uploadIcon:y.uploadIcon,uploadTitle:y.uploadTitle})),i&&(_=p._getLayoutTemplate("actionDownload").setTokens({downloadClass:y.downloadClass,downloadIcon:y.downloadIcon,downloadTitle:y.downloadTitle,downloadUrl:c||p.initialPreviewDownloadUrl}),_=_.setTokens({filename:u,key:s})),r&&(m=p._getLayoutTemplate("actionZoom").setTokens({zoomClass:y.zoomClass,zoomIcon:y.zoomIcon,zoomTitle:y.zoomTitle})),n&&d&&(f="drag-handle-init "+y.dragClass,h=p._getLayoutTemplate("actionDrag").setTokens({dragClass:f,dragTitle:y.dragTitle,dragIcon:y.dragIcon})),C.setTokens({"delete":w,upload:b,download:_,zoom:m,drag:h,other:x})},_browse:function(e){var t=this;e&&e.isDefaultPrevented()||!t._raise("filebrowse")||(t.isError&&!t.isAjaxUpload&&t.clear(),t.focusCaptionOnBrowse&&t.$captionContainer.focus())},_change:function(i){var a=this;if(!a.changeTriggered){var r,n,o,l,s=a.$element,d=arguments.length>1,c=a.isAjaxUpload,u=d?arguments[1]:s[0].files,p=a.fileManager.count(),f=t.isEmpty(s.attr("multiple")),g=!c&&f?1:a.maxFileCount,m=a.maxTotalFileCount,h=m>0&&m>g,v=f&&p>0,w=function(t,i,r,n){var o=e.extend(!0,{},a._getOutData(null,{},{},u),{id:r,index:n}),l={id:r,index:n,file:i,files:u};return a.isPersistentError=!0,c?a._showFileError(t,o):a._showError(t,l)},b=function(e,t,i){var r=i?a.msgTotalFilesTooMany:a.msgFilesTooMany;r=r.replace("{m}",t).replace("{n}",e),a.isError=w(r,null,null,null),a.$captionContainer.removeClass("icon-visible"),a._setCaption("",!0),a.$container.removeClass("file-input-new file-input-ajax-new")};if(a.reader=null,a._resetUpload(),a._hideFileIcon(),a.dropZoneEnabled&&a.$container.find(".file-drop-zone ."+a.dropZoneTitleClass).remove(),c||(u=i.target&&void 0===i.target.files?i.target.value?[{name:i.target.value.replace(/^.+\\/,"")}]:[]:i.target.files||{}),r=u,t.isEmpty(r)||0===r.length){return c||a.clear(),void a._raise("fileselectnone")}if(a._resetErrors(),l=r.length,o=c?a.fileManager.count()+l:l,n=a._getFileCount(o,h?!1:void 0),g>0&&n>g){if(!a.autoReplace||l>g){return void b(a.autoReplace&&l>g?l:n,g)}n>g&&a._resetPreviewThumbs(c)}else{if(h&&(n=a._getFileCount(o,!0),m>0&&n>m)){if(!a.autoReplace||l>g){return void b(a.autoReplace&&l>m?l:n,m,!0)}n>g&&a._resetPreviewThumbs(c)}!c||v?(a._resetPreviewThumbs(!1),v&&a.clearFileStack()):!c||0!==p||a.previewCache.count(!0)&&!a.overwriteInitial||a._resetPreviewThumbs(!0)}a.readFiles(r)}},_abort:function(t){var i,a=this;return a.ajaxAborted&&"object"==typeof a.ajaxAborted&&void 0!==a.ajaxAborted.message?(i=e.extend(!0,{},a._getOutData(null),t),i.abortData=a.ajaxAborted.data||{},i.abortMessage=a.ajaxAborted.message,a._setProgress(101,a.$progress,a.msgCancelled),a._showFileError(a.ajaxAborted.message,i,"filecustomerror"),a.cancel(),!0):!!a.ajaxAborted},_resetFileStack:function(){var t=this,i=0;t._getThumbs().each(function(){var a=e(this),r=a.attr("data-fileindex"),n=a.attr("id");"-1"!==r&&-1!==r&&(t.fileManager.getFile(a.attr("data-fileid"))?a.attr({"data-fileindex":"-1"}):(a.attr({"data-fileindex":i}),i++),t._getZoom(n).attr({"data-fileindex":a.attr("data-fileindex")}))})},_isFileSelectionValid:function(e){var t=this;return e=e||0,t.required&&!t.getFilesCount()?(t.$errorContainer.html(""),t._showFileError(t.msgFileRequired),!1):t.minFileCount>0&&t._getFileCount(e)v,!o&&(a||r||n)},addToStack:function(e,t){this.fileManager.add(e,t)},clearFileStack:function(){var e=this;return e.fileManager.clear(),e._initResumableUpload(),e.enableResumableUpload?(null===e.showPause&&(e.showPause=!0),null===e.showCancel&&(e.showCancel=!1)):(e.showPause=!1,null===e.showCancel&&(e.showCancel=!0)),e.$element},getFileStack:function(){return this.fileManager.stack},getFileList:function(){return this.fileManager.list()},getFilesCount:function(e){var t=this,i=t.isAjaxUpload?t.fileManager.count():t._inputFileCount();return e&&(i+=t.previewCache.count(!0)),t._getFileCount(i)},readFiles:function(i){this.reader=new FileReader;var a,r=this,n=r.reader,o=r.$previewContainer,l=r.$previewStatus,s=r.msgLoading,d=r.msgProgress,c=r.previewInitId,u=i.length,p=r.fileTypeSettings,f=r.allowedFileTypes,g=f?f.length:0,m=r.allowedFileExtensions,h=t.isEmpty(m)?"":m.join(", "),v=function(t,n,o,l,s){var d,c=e.extend(!0,{},r._getOutData(null,{},{},i),{id:o,index:l,fileId:s}),p={id:o,index:l,fileId:s,file:n,files:i};r._previewDefault(n,!0),d=r._getFrame(o,!0),r.isAjaxUpload?setTimeout(function(){a(l+1)},r.processDelay):(r.unlock(),u=0),r.removeFromPreviewOnError&&d.length?d.remove():(r._initFileActions(),d.find(".kv-file-upload").remove()),r.isPersistentError=!0,r.isError=r.isAjaxUpload?r._showFileError(t,c):r._showError(t,p),r._updateFileDetails(u)};r.fileManager.clearImages(),e.each(i,function(e,t){var i=r.fileTypeSettings.image;i&&i(t.type)&&r.fileManager.totalImages++}),a=function(w){var b,_=r.$errorContainer,C=r.fileManager;if(w>=u){return r.unlock(),r.duplicateErrors.length&&(b="
  • "+r.duplicateErrors.join("
  • ")+"
  • ",0===_.find("ul").length?t.setHtml(_,r.errorCloseButton+"
      "+b+"
    "):_.find("ul").append(b),_.fadeIn(r.fadeDelay),r._handler(_.find(".kv-error-close"),"click",function(){_.fadeOut(r.fadeDelay)}),r.duplicateErrors=[]),r.isAjaxUpload?(r._raise("filebatchselected",[C.stack]),0!==C.count()||r.isError||r.reset()):r._raise("filebatchselected",[i]),o.removeClass("file-thumb-loading"),void l.html("")}r.lock(!0);var y,x,T,P,F,E,k,S,I,A,D,z,j=i[w],U=r._getFileId(j),M=c+"-"+U,$=(p.text,p.image),R=(p.html,r._getFileName(j,"")),O=(j&&j.size||0)/1000,B="",L=t.createObjectURL(j),N=0,Z="",H=!1,W=0,q=function(){var e=d.setTokens({index:w+1,files:u,percent:50,name:R});setTimeout(function(){l.html(e),r._updateFileDetails(u),a(w+1)},r.processDelay),r._raise("fileloaded",[j,M,U,w,n])&&r.isAjaxUpload&&C.add(j)};if(j){if(S=C.getId(j),g>0){for(x=0;g>x;x++){E=f[x],k=r.msgFileTypes[E]||E,Z+=0===x?k:", "+k}}if(R===!1){return void a(w+1)}if(0===R.length){return T=r.msgInvalidFileName.replace("{name}",t.htmlEncode(t.getFileName(j),"[unknown]")),void v(T,j,M,w,S)}if(t.isEmpty(m)||(B=RegExp("\\.("+m.join("|")+")$","i")),y=O.toFixed(2),r.isAjaxUpload&&C.exists(S)||r._getFrame(M,!0).length){var V={id:M,index:w,fileId:S,file:j,files:i};return T=r.msgDuplicateFile.setTokens({name:R,size:y}),void (r.isAjaxUpload?(r.duplicateErrors.push(T),r.isDuplicateError=!0,r._raise("fileduplicateerror",[j,S,R,y,M,w]),a(w+1),r._updateFileDetails(u)):(r._showError(T,V),r.unlock(),u=0,r._clearFileInput(),r.reset(),r._updateFileDetails(u)))}if(r.maxFileSize>0&&O>r.maxFileSize){return T=r.msgSizeTooLarge.setTokens({name:R,size:y,maxSize:r.maxFileSize}),void v(T,j,M,w,S)}if(null!==r.minFileSize&&O<=t.getNum(r.minFileSize)){return T=r.msgSizeTooSmall.setTokens({name:R,size:y,minSize:r.minFileSize}),void v(T,j,M,w,S)}if(!t.isEmpty(f)&&t.isArray(f)){for(x=0;x0){for(t=0;n>t;t+=1){i.paused=!0,r[t].abort()}}return i.showPreview&&i._getThumbs().each(function(){var t,a=e(this),r=a.attr("data-fileid"),n=i._getLayoutTemplate("stats"),s=a.find(".file-upload-indicator");a.removeClass("file-uploading"),s.attr("title")===l.indicatorLoadingTitle&&(i._setThumbStatus(a,"Paused"),t=n.setTokens({pendingTime:i.msgPaused,uploadSpeed:""}),i.paused=!0,i._setProgress(o,a.find(".file-thumb-progress"),o+"%",t)),i.fileManager.getFile(r)||a.find(".kv-file-remove").removeClass("disabled").removeAttr("disabled")}),i._setProgress(101,i.$progress,i.msgPaused),i.$element},cancel:function(){var t,i=this,a=i.ajaxRequests,r=i.resumableManager,n=i.taskManager,o=r?n.getPool(r.id):void 0,l=a.length;if(i.enableResumableUpload&&o?(o.cancel().done(function(){i._setProgressCancelled()}),r.reset(),i._raise("fileuploadcancelled",[i.fileManager,r])):i._raise("fileuploadcancelled",[i.fileManager]),i._initAjax(),l>0){for(t=0;l>t;t+=1){i.cancelling=!0,a[t].abort()}}return i._getThumbs().each(function(){var t=e(this),a=t.attr("data-fileid"),r=t.find(".file-thumb-progress");t.removeClass("file-uploading"),i._setProgress(0,r),r.hide(),i.fileManager.getFile(a)||(t.find(".kv-file-upload").removeClass("disabled").removeAttr("disabled"),t.find(".kv-file-remove").removeClass("disabled").removeAttr("disabled")),i.unlock()}),setTimeout(function(){i._setProgressCancelled()},i.processDelay),i.$element},clear:function(){var i,a=this;if(a._raise("fileclear")){return a.$btnUpload.removeAttr("disabled"),a._getThumbs().find("video,audio,img").each(function(){t.cleanMemory(e(this))}),a._clearFileInput(),a._resetUpload(),a.clearFileStack(),a.isDuplicateError=!1,a.isPersistentError=!1,a._resetErrors(!0),a._hasInitialPreview()?(a._showFileIcon(),a._resetPreview(),a._initPreviewActions(),a.$container.removeClass("file-input-new")):(a._getThumbs().each(function(){a._clearObjects(e(this))}),a.isAjaxUpload&&(a.previewCache.data={}),a.$preview.html(""),i=!a.overwriteInitial&&a.initialCaption.length>0?a.initialCaption:"",a.$caption.attr("title","").val(i),t.addCss(a.$container,"file-input-new"),a._validateDefaultPreview()),0===a.$container.find(t.FRAMES).length&&(a._initCaption()||a.$captionContainer.removeClass("icon-visible")),a._hideFileIcon(),a.focusCaptionOnClear&&a.$captionContainer.focus(),a._setFileDropZoneTitle(),a._raise("filecleared"),a.$element}},reset:function(){var e=this;if(e._raise("filereset")){return e.lastProgress=0,e._resetPreview(),e.$container.find(".fileinput-filename").text(""),t.addCss(e.$container,"file-input-new"),e.getFrames().length&&e.$container.removeClass("file-input-new"),e.clearFileStack(),e._setFileDropZoneTitle(),e.$element}},disable:function(){var e=this,i=e.$container;return e.isDisabled=!0,e._raise("filedisabled"),e.$element.attr("disabled","disabled"),i.addClass("is-locked"),t.addCss(i.find(".btn-file"),"disabled"),i.find(".kv-fileinput-caption").addClass("file-caption-disabled"),i.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button").attr("disabled",!0),e._initDragDrop(),e.$element},enable:function(){var e=this,t=e.$container;return e.isDisabled=!1,e._raise("fileenabled"),e.$element.removeAttr("disabled"),t.removeClass("is-locked"),t.find(".kv-fileinput-caption").removeClass("file-caption-disabled"),t.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled"),t.find(".btn-file").removeClass("disabled"),e._initDragDrop(),e.$element},upload:function(){var i,a,r=this,n=r.fileManager,o=n.count(),l=!e.isEmptyObject(r._getExtraData());if(r.isAjaxUpload&&!r.isDisabled&&r._isFileSelectionValid(o)){return r.lastProgress=0,r._resetUpload(),0!==o||l?(r.cancelling=!1,r._showProgress(),r.lock(),0===o&&l?(r._setProgress(2),void r._uploadExtraOnly()):r.enableResumableUpload?r.resume():((r.uploadAsync||r.enableResumableUpload)&&(a=r._getOutData(null),r._raise("filebatchpreupload",[a]),r.fileBatchCompleted=!1,r.uploadCache=[],e.each(r.getFileStack(),function(e){var t=r._getThumbId(e);r.uploadCache.push({id:t,content:null,config:null,tags:null,append:!0})}),r.$preview.find(".file-preview-initial").removeClass(t.SORT_CSS),r._initSortable()),r._setProgress(2),r.hasInitData=!1,r.uploadAsync?(i=0,void e.each(n.stack,function(e){r._uploadSingle(i,e,!0),i++})):(r._uploadBatch(),r.$element))):void r._showFileError(r.msgUploadEmpty)}},destroy:function(){var t=this,i=t.$form,a=t.$container,r=t.$element,n=t.namespace;return e(document).off(n),e(window).off(n),i&&i.length&&i.off(n),t.isAjaxUpload&&t._clearFileInput(),t._cleanup(),t._initPreviewCache(),r.insertBefore(a).off(n).removeData(),a.off().remove(),r},refresh:function(i){var a=this,r=a.$element;return i="object"!=typeof i||t.isEmpty(i)?a.options:e.extend(!0,{},a.options,i),a._init(i,!0),a._listen(),r},zoom:function(e){var t=this,i=t._getFrame(e);t._showModal(i)},getExif:function(e){var t=this,i=t._getFrame(e);return i&&i.data("exif")||null},getFrames:function(i){var a,r=this;return i=i||"",a=r.$preview.find(t.FRAMES+i),r.reversePreviewOrder&&(a=e(a.get().reverse())),a},getPreview:function(){var e=this;return{content:e.initialPreview,config:e.initialPreviewConfig,tags:e.initialPreviewThumbTags}}},e.fn.fileinput=function(a){if(t.hasFileAPISupport()||t.isIE(9)){var r=Array.apply(null,arguments),n=[];switch(r.shift(),this.each(function(){var o,l=e(this),s=l.data("fileinput"),d="object"==typeof a&&a,c=d.theme||l.data("theme"),u={},p={},f=d.language||l.data("language")||e.fn.fileinput.defaults.language||"en";s||(c&&(p=e.fn.fileinputThemes[c]||{}),"en"===f||t.isEmpty(e.fn.fileinputLocales[f])||(u=e.fn.fileinputLocales[f]||{}),o=e.extend(!0,{},e.fn.fileinput.defaults,p,e.fn.fileinputLocales.en,u,d,l.data()),s=new i(this,o),l.data("fileinput",s)),"string"==typeof a&&n.push(s[a].apply(s,r))}),n.length){case 0:return this;case 1:return n[0];default:return n}}};var a='class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}';e.fn.fileinput.defaults={language:"zh",showCaption:!0,showBrowse:!0,showPreview:!0,showRemove:!0,showUpload:!0,showUploadStats:!0,showCancel:null,showPause:null,showClose:!0,showUploadedThumbs:!0,showConsoleLogs:!1,browseOnZoneClick:!1,autoReplace:!1,autoOrientImage:function(){var e=window.navigator.userAgent,t=!!e.match(/WebKit/i),i=!!e.match(/iP(od|ad|hone)/i),a=i&&t&&!e.match(/CriOS/i);return !a},autoOrientImageInitial:!0,required:!1,rtl:!1,hideThumbnailContent:!1,encodeUrl:!0,focusCaptionOnBrowse:!0,focusCaptionOnClear:!0,generateFileId:null,previewClass:"",captionClass:"",frameClass:"krajee-default",mainClass:"file-caption-main",mainTemplate:null,fileSizeGetter:null,initialCaption:"",initialPreview:[],initialPreviewDelimiter:"*$$*",initialPreviewAsData:!1,initialPreviewFileType:"image",initialPreviewConfig:[],initialPreviewThumbTags:[],previewThumbTags:{},initialPreviewShowDelete:!0,initialPreviewDownloadUrl:"",removeFromPreviewOnError:!1,deleteUrl:"",deleteExtraData:{},overwriteInitial:!0,sanitizeZoomCache:function(e){var i=t.createElement(e);return i.find("input,textarea,select,datalist,form,.file-thumbnail-footer").remove(),i.html()},previewZoomButtonIcons:{prev:'',next:'',toggleheader:'',fullscreen:'',borderless:'',close:''},previewZoomButtonClasses:{prev:"btn btn-navigate",next:"btn btn-navigate",toggleheader:"btn btn-sm btn-kv btn-default btn-outline-secondary",fullscreen:"btn btn-sm btn-kv btn-default btn-outline-secondary",borderless:"btn btn-sm btn-kv btn-default btn-outline-secondary",close:"btn btn-sm btn-kv btn-default btn-outline-secondary"},previewTemplates:{},previewContentTemplates:{},preferIconicPreview:!1,preferIconicZoomPreview:!1,allowedFileTypes:null,allowedFileExtensions:null,allowedPreviewTypes:void 0,allowedPreviewMimeTypes:null,allowedPreviewExtensions:null,disabledPreviewTypes:void 0,disabledPreviewExtensions:["msi","exe","com","zip","rar","app","vb","scr"],disabledPreviewMimeTypes:null,defaultPreviewContent:null,customLayoutTags:{},customPreviewTags:{},previewFileIcon:'',previewFileIconClass:"file-other-icon",previewFileIconSettings:{},previewFileExtSettings:{},buttonLabelClass:"hidden-xs",browseIcon:' ',browseClass:"btn btn-primary",removeIcon:'',removeClass:"btn btn-default btn-secondary",cancelIcon:'',cancelClass:"btn btn-default btn-secondary",pauseIcon:'',pauseClass:"btn btn-default btn-secondary",uploadIcon:'',uploadClass:"btn btn-default btn-secondary",uploadUrl:null,uploadUrlThumb:null,uploadAsync:!0,uploadParamNames:{chunkCount:"chunkCount",chunkIndex:"chunkIndex",chunkSize:"chunkSize",chunkSizeStart:"chunkSizeStart",chunksUploaded:"chunksUploaded",fileBlob:"fileBlob",fileId:"fileId",fileName:"fileName",fileRelativePath:"fileRelativePath",fileSize:"fileSize",retryCount:"retryCount"},maxAjaxThreads:5,fadeDelay:800,processDelay:100,queueDelay:10,progressDelay:0,enableResumableUpload:!1,resumableUploadOptions:{fallback:null,testUrl:null,chunkSize:2048,maxThreads:4,maxRetries:3,showErrorLog:!0},uploadExtraData:{},zoomModalHeight:480,minImageWidth:null,minImageHeight:null,maxImageWidth:null,maxImageHeight:null,resizeImage:!1,resizePreference:"width",resizeQuality:0.92,resizeDefaultImageType:"image/jpeg",resizeIfSizeMoreThan:0,minFileSize:-1,maxFileSize:0,maxFilePreviewSize:25600,minFileCount:0,maxFileCount:0,maxTotalFileCount:0,validateInitialCount:!1,msgValidationErrorClass:"text-danger",msgValidationErrorIcon:' ',msgErrorClass:"file-error-message",progressThumbClass:"progress-bar progress-bar-striped active progress-bar-animated",progressClass:"progress-bar bg-success progress-bar-success progress-bar-striped active progress-bar-animated",progressInfoClass:"progress-bar bg-info progress-bar-info progress-bar-striped active progress-bar-animated",progressCompleteClass:"progress-bar bg-success progress-bar-success",progressPauseClass:"progress-bar bg-primary progress-bar-primary progress-bar-striped active progress-bar-animated",progressErrorClass:"progress-bar bg-danger progress-bar-danger",progressUploadThreshold:99,previewFileType:"image",elCaptionContainer:null,elCaptionText:null,elPreviewContainer:null,elPreviewImage:null,elPreviewStatus:null,elErrorContainer:null,errorCloseButton:t.closeButton("kv-error-close"),slugCallback:null,dropZoneEnabled:!0,dropZoneTitleClass:"file-drop-zone-title",fileActionSettings:{},otherActionButtons:"",textEncoding:"UTF-8",preProcessUpload:null,ajaxSettings:{},ajaxDeleteSettings:{},showAjaxErrorDetails:!0,mergeAjaxCallbacks:!1,mergeAjaxDeleteCallbacks:!1,retryErrorUploads:!0,reversePreviewOrder:!1,usePdfRenderer:function(){var e=!!window.MSInputMethodContext&&!!document.documentMode;return !!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i)||e},pdfRendererUrl:"",pdfRendererTemplate:""},e.fn.fileinputLocales.en={fileSingle:"file",filePlural:"files",browseLabel:"Browse …",removeLabel:"Remove",removeTitle:"Clear all unprocessed files",cancelLabel:"Cancel",cancelTitle:"Abort ongoing upload",pauseLabel:"Pause",pauseTitle:"Pause ongoing upload",uploadLabel:"Upload",uploadTitle:"Upload selected files",msgNo:"No",msgNoFilesSelected:"No files selected",msgCancelled:"Cancelled",msgPaused:"Paused",msgPlaceholder:"Select {files} ...",msgZoomModalHeading:"Detailed Preview",msgFileRequired:"You must select a file to upload.",msgSizeTooSmall:'File "{name}" ({size} KB) is too small and must be larger than {minSize} KB.',msgSizeTooLarge:'File "{name}" ({size} KB) exceeds maximum allowed upload size of {maxSize} KB.',msgFilesTooLess:"You must select at least {n} {files} to upload.",msgFilesTooMany:"Number of files selected for upload ({n}) exceeds maximum allowed limit of {m}.",msgTotalFilesTooMany:"You can upload a maximum of {m} files ({n} files detected).",msgFileNotFound:'File "{name}" not found!',msgFileSecured:'Security restrictions prevent reading the file "{name}".',msgFileNotReadable:'File "{name}" is not readable.',msgFilePreviewAborted:'File preview aborted for "{name}".',msgFilePreviewError:'An error occurred while reading the file "{name}".',msgInvalidFileName:'Invalid or unsupported characters in file name "{name}".',msgInvalidFileType:'Invalid type for file "{name}". Only "{types}" files are supported.',msgInvalidFileExtension:'Invalid extension for file "{name}". Only "{extensions}" files are supported.',msgFileTypes:{image:"image",html:"HTML",text:"text",video:"video",audio:"audio",flash:"flash",pdf:"PDF",object:"object"},msgUploadAborted:"The file upload was aborted",msgUploadThreshold:"Processing …",msgUploadBegin:"Initializing …",msgUploadEnd:"Done",msgUploadResume:"Resuming upload …",msgUploadEmpty:"No valid data available for upload.",msgUploadError:"Upload Error",msgDeleteError:"Delete Error",msgProgressError:"Error",msgValidationError:"Validation Error",msgLoading:"Loading file {index} of {files} …",msgProgress:"Loading file {index} of {files} - {name} - {percent}% completed.",msgSelected:"{n} {files} selected",msgFoldersNotAllowed:"Drag & drop files only! {n} folder(s) dropped were skipped.",msgImageWidthSmall:'Width of image file "{name}" must be at least {size} px.',msgImageHeightSmall:'Height of image file "{name}" must be at least {size} px.',msgImageWidthLarge:'Width of image file "{name}" cannot exceed {size} px.',msgImageHeightLarge:'Height of image file "{name}" cannot exceed {size} px.',msgImageResizeError:"Could not get the image dimensions to resize.",msgImageResizeException:"Error while resizing the image.
    {errors}
    ",msgAjaxError:"Something went wrong with the {operation} operation. Please try again later!",msgAjaxProgressError:"{operation} failed",msgDuplicateFile:'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',msgResumableUploadRetriesExceeded:"Upload aborted beyond {max} retries for file {file}! Error Details:
    {error}
    ",msgPendingTime:"{time} remaining",msgCalculatingTime:"calculating time remaining",ajaxOperations:{deleteThumb:"file delete",uploadThumb:"file upload",uploadBatch:"batch file upload",uploadExtra:"form data upload"},dropZoneTitle:"Drag & drop files here …",dropZoneClickTitle:"
    (or click to select {files})",previewZoomButtonTitles:{prev:"View previous file",next:"View next file",toggleheader:"Toggle header",fullscreen:"Toggle full screen",borderless:"Toggle borderless mode",close:"Close detailed preview"}},e.fn.fileinputLocales.zh={fileSingle:"文件",filePlural:"个文件",browseLabel:"选择 …",removeLabel:"移除",removeTitle:"清除选中文件",cancelLabel:"取消",cancelTitle:"取消进行中的上传",pauseLabel:"Pause",pauseTitle:"Pause ongoing upload",uploadLabel:"上传",uploadTitle:"上传选中文件",msgNo:"没有",msgNoFilesSelected:"未选择文件",msgPaused:"Paused",msgCancelled:"取消",msgPlaceholder:"选择 {files} ...",msgZoomModalHeading:"详细预览",msgFileRequired:"必须选择一个文件上传.",msgSizeTooSmall:'文件 "{name}" ({size} KB) 必须大于限定大小 {minSize} KB.',msgSizeTooLarge:'文件 "{name}" ({size} KB) 超过了允许大小 {maxSize} KB.',msgFilesTooLess:"你必须选择最少 {n} {files} 来上传. ",msgFilesTooMany:"选择的上传文件个数 ({n}) 超出最大文件的限制个数 {m}.",msgTotalFilesTooMany:"You can upload a maximum of {m} files ({n} files detected).",msgFileNotFound:'文件 "{name}" 未找到!',msgFileSecured:'安全限制,为了防止读取文件 "{name}".',msgFileNotReadable:'文件 "{name}" 不可读.',msgFilePreviewAborted:'取消 "{name}" 的预览.',msgFilePreviewError:'读取 "{name}" 时出现了一个错误.',msgInvalidFileName:'文件名 "{name}" 包含非法字符.',msgInvalidFileType:'不正确的类型 "{name}". 只支持 "{types}" 类型的文件.',msgInvalidFileExtension:'不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.',msgFileTypes:{image:"image",html:"HTML",text:"text",video:"video",audio:"audio",flash:"flash",pdf:"PDF",object:"object"},msgUploadAborted:"该文件上传被中止",msgUploadThreshold:"处理中 …",msgUploadBegin:"正在初始化 …",msgUploadEnd:"完成",msgUploadResume:"Resuming upload …",msgUploadEmpty:"无效的文件上传.",msgUploadError:"Upload Error",msgDeleteError:"Delete Error",msgProgressError:"上传出错",msgValidationError:"验证错误",msgLoading:"加载第 {index} 文件 共 {files} …",msgProgress:"加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.",msgSelected:"{n} {files} 选中",msgFoldersNotAllowed:"只支持拖拽文件! 跳过 {n} 拖拽的文件夹.",msgImageWidthSmall:'图像文件的"{name}"的宽度必须是至少{size}像素.',msgImageHeightSmall:'图像文件的"{name}"的高度必须至少为{size}像素.',msgImageWidthLarge:'图像文件"{name}"的宽度不能超过{size}像素.',msgImageHeightLarge:'图像文件"{name}"的高度不能超过{size}像素.',msgImageResizeError:"无法获取的图像尺寸调整。",msgImageResizeException:"调整图像大小时发生错误。
    {errors}
    ",msgAjaxError:"{operation} 发生错误. 请重试!",msgAjaxProgressError:"{operation} 失败",msgDuplicateFile:'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',msgResumableUploadRetriesExceeded:"Upload aborted beyond {max} retries for file {file}! Error Details:
    {error}
    ",msgPendingTime:"{time} remaining",msgCalculatingTime:"calculating time remaining",ajaxOperations:{deleteThumb:"删除文件",uploadThumb:"上传文件",uploadBatch:"批量上传",uploadExtra:"表单数据上传"},dropZoneTitle:"拖拽文件到这里 …
    支持多文件同时上传",dropZoneClickTitle:"
    (或点击{files}按钮选择文件)",fileActionSettings:{removeTitle:"删除文件",uploadTitle:"上传文件",downloadTitle:"下载文件",uploadRetryTitle:"重试",zoomTitle:"查看详情",dragTitle:"移动 / 重置",indicatorNewTitle:"没有上传",indicatorSuccessTitle:"上传",indicatorErrorTitle:"上传错误",indicatorPausedTitle:"Upload Paused",indicatorLoadingTitle:"上传 …"},previewZoomButtonTitles:{prev:"预览上一个文件",next:"预览下一个文件",toggleheader:"缩放",fullscreen:"全屏",borderless:"无边界模式",close:"关闭当前预览"}},e.fn.fileinput.Constructor=i,e(document).ready(function(){var t=e("input.file[type=file]");t.length&&t.fileinput()})}); \ No newline at end of file +!function(e){"use strict" +"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof module&&module.exports?module.exports=e(require("jquery")):e(window.jQuery)}(function(e){"use strict" +e.fn.fileinputLocales={},e.fn.fileinputThemes={},e.fn.fileinputBsVersion||(e.fn.fileinputBsVersion=window.Alert&&window.Alert.VERSION||window.bootstrap&&window.bootstrap.Alert&&bootstrap.Alert.VERSION||"3.x.x"),String.prototype.setTokens=function(e){var t,i,a=""+this +for(t in e)e.hasOwnProperty(t)&&(i=RegExp("{"+t+"}","g"),a=a.replace(i,e[t])) +return a},Array.prototype.flatMap||(Array.prototype.flatMap=function(e){return[].concat(this.map(e))}) +var t,i +t={FRAMES:".kv-preview-thumb",SORT_CSS:"file-sortable",INIT_FLAG:"init-",OBJECT_PARAMS:'\n\n\n\n\n\n',DEFAULT_PREVIEW:'
    \n{previewFileIcon}\n
    ',MODAL_ID:"kvFileinputModal",MODAL_EVENTS:["show","shown","hide","hidden","loaded"],logMessages:{ajaxError:"{status}: {error}. Error Details: {text}.",badDroppedFiles:"Error scanning dropped files!",badExifParser:"Error loading the piexif.js library. {details}",badInputType:'The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.',exifWarning:'To avoid this warning, either set "autoOrientImage" to "false" OR ensure you have loaded the "piexif.js" library correctly on your page before the "fileinput.js" script.',invalidChunkSize:'Invalid upload chunk size: "{chunkSize}". Resumable uploads are disabled.',invalidThumb:'Invalid thumb frame with id: "{id}".',noResumableSupport:"The browser does not support resumable or chunk uploads.",noUploadUrl:'The "uploadUrl" is not set. Ajax uploads and resumable uploads have been disabled.',retryStatus:"Retrying upload for chunk # {chunk} for {filename}... retry # {retry}.",chunkQueueError:"Could not push task to ajax pool for chunk index # {index}.",resumableMaxRetriesReached:"Maximum resumable ajax retries ({n}) reached.",resumableRetryError:"Could not retry the resumable request (try # {n})... aborting.",resumableAborting:"Aborting / cancelling the resumable request.",resumableRequestError:"Error processing resumable request. {msg}"},objUrl:window.URL||window.webkitURL,isBs:function(t){var i=e.trim((e.fn.fileinputBsVersion||"")+"") +return t=parseInt(t,10),i?t===parseInt(i.charAt(0),10):4===t},defaultButtonCss:function(e){return"btn-default btn-"+(e?"":"outline-")+"secondary"},now:function(){return(new Date).getTime()},round:function(e){return e=parseFloat(e),isNaN(e)?0:Math.floor(Math.round(e))},getArray:function(e){var t,i=[],a=e&&e.length||0 +for(t=0;a>t;t++)i.push(e[t]) +return i},getFileRelativePath:function(e){return(e.newPath||e.relativePath||e.webkitRelativePath||t.getFileName(e)||null)+""},getFileId:function(e,i){var a=t.getFileRelativePath(e) +return"function"==typeof i?i(e):e&&a?e.size+"_"+encodeURIComponent(a).replace(/%/g,"_"):null},getFrameSelector:function(e,t){return t=t||"",'[id="'+e+'"]'+t},getZoomSelector:function(e,i){return t.getFrameSelector("zoom-"+e,i)},getFrameElement:function(e,i,a){return e.find(t.getFrameSelector(i,a))},getZoomElement:function(e,i,a){return e.find(t.getZoomSelector(i,a))},getElapsed:function(i){var a=i,r="",n={},o={year:31536e3,month:2592e3,week:604800,day:86400,hour:3600,minute:60,second:1} +return t.getObjectKeys(o).forEach(function(e){n[e]=Math.floor(a/o[e]),a-=n[e]*o[e]}),e.each(n,function(e,t){t>0&&(r+=(r?" ":"")+t+e.substring(0,1))}),r},debounce:function(e,t){var i +return function(){var a=arguments,r=this +clearTimeout(i),i=setTimeout(function(){e.apply(r,a)},t)}},stopEvent:function(e){e.stopPropagation(),e.preventDefault()},getFileName:function(e){return e?e.fileName||e.name||"":""},createObjectURL:function(e){return t.objUrl&&t.objUrl.createObjectURL&&e?t.objUrl.createObjectURL(e):""},revokeObjectURL:function(e){t.objUrl&&t.objUrl.revokeObjectURL&&e&&t.objUrl.revokeObjectURL(e)},compare:function(e,t,i){return void 0!==e&&(i?e===t:e.match(t))},isIE:function(e){var t,i +return"Microsoft Internet Explorer"!==navigator.appName?!1:10===e?RegExp("msie\\s"+e,"i").test(navigator.userAgent):(t=document.createElement("div"),t.innerHTML="",i=t.getElementsByTagName("i").length,document.body.appendChild(t),t.parentNode.removeChild(t),i)},canOrientImage:function(t){var i=e(document.createElement("img")).css({width:"1px",height:"1px"}).insertAfter(t),a=i.css("image-orientation") +return i.remove(),!!a},canAssignFilesToInput:function(){var e=document.createElement("input") +try{return e.type="file",e.files=null,!0}catch(t){return!1}},getDragDropFolders:function(e){var t,i,a=e?e.length:0,r=0 +if(a>0&&e[0].webkitGetAsEntry())for(t=0;a>t;t++)i=e[t].webkitGetAsEntry(),i&&i.isDirectory&&r++ +return r},initModal:function(t){var i=e("body") +i.length&&t.appendTo(i)},isFunction:function(e){return"function"==typeof e},isEmpty:function(i,a){return void 0===i||null===i||""===i?!0:t.isString(i)&&a?""===e.trim(i):t.isArray(i)?0===i.length:e.isPlainObject(i)&&e.isEmptyObject(i)?!0:!1},isArray:function(e){return Array.isArray(e)||"[object Array]"===Object.prototype.toString.call(e)},isString:function(e){return"[object String]"===Object.prototype.toString.call(e)},ifSet:function(e,t,i){return i=i||"",t&&"object"==typeof t&&e in t?t[e]:i},cleanArray:function(e){return e instanceof Array||(e=[]),e.filter(function(e){return void 0!==e&&null!==e})},spliceArray:function(t,i,a){var r,n,o=0,s=[] +if(!(t instanceof Array))return[] +for(n=e.extend(!0,[],t),a&&n.reverse(),r=0;r=0?atob(e.split(",")[1]):decodeURIComponent(e.split(",")[1]),a=new ArrayBuffer(i.length),r=new Uint8Array(a),n=0;ns;)switch(i=n[s++],i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i) +break +case 12:case 13:a=n[s++],o+=String.fromCharCode((31&i)<<6|63&a) +break +case 14:a=n[s++],r=n[s++],o+=String.fromCharCode((15&i)<<12|(63&a)<<6|(63&r)<<0)}return o},isHtml:function(e){var t=document.createElement("div") +t.innerHTML=e +for(var i=t.childNodes,a=i.length;a--;)if(1===i[a].nodeType)return!0 +return!1},isSvg:function(e){return e.match(/^\s*<\?xml/i)&&(e.match(/"+t+""))},uniqId:function(){return((new Date).getTime()+Math.floor(Math.random()*Math.pow(10,15))).toString(36)},cspBuffer:{CSP_ATTRIB:"data-csp-01928735",domElementsStyles:{},stash:function(i){var a=this,r=e.parseHTML("
    "+i+"
    "),n=e(r) +n.find("[style]").each(function(i,r){var n=e(r),o=n[0].style,s=t.uniqId(),l={} +o&&o.length&&(e(o).each(function(){l[this]=o[this]}),a.domElementsStyles[s]=l,n.removeAttr("style").attr(a.CSP_ATTRIB,s))}),n.filter("*").removeAttr("style") +var o=Object.values?Object.values(r):Object.keys(r).map(function(e){return r[e]}) +return o.flatMap(function(e){return e.innerHTML}).join("")},apply:function(t){var i=this,a=e(t) +a.find("["+i.CSP_ATTRIB+"]").each(function(t,a){var r=e(a),n=r.attr(i.CSP_ATTRIB),o=i.domElementsStyles[n] +o&&r.css(o),r.removeAttr(i.CSP_ATTRIB)}),i.domElementsStyles={}}},setHtml:function(e,i){var a=t.cspBuffer +return e.html(a.stash(i)),a.apply(e),e},htmlEncode:function(e,t){return void 0===e?t||null:e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")},replaceTags:function(t,i){var a=t +return i?(e.each(i,function(e,t){"function"==typeof t&&(t=t()),a=a.split(e).join(t)}),a):a},cleanMemory:function(e){var i=e.is("img")?e.attr("src"):e.find("source").attr("src") +t.revokeObjectURL(i)},findFileName:function(e){var t=e.lastIndexOf("/") +return-1===t&&(t=e.lastIndexOf("\\")),e.split(e.substring(t,t+1)).pop()},checkFullScreen:function(){return document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement},toggleFullScreen:function(e){var i=document,a=i.documentElement,r=t.checkFullScreen() +a&&e&&!r?a.requestFullscreen?a.requestFullscreen():a.msRequestFullscreen?a.msRequestFullscreen():a.mozRequestFullScreen?a.mozRequestFullScreen():a.webkitRequestFullscreen&&a.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT):r&&(i.exitFullscreen?i.exitFullscreen():i.msExitFullscreen?i.msExitFullscreen():i.mozCancelFullScreen?i.mozCancelFullScreen():i.webkitExitFullscreen&&i.webkitExitFullscreen())},moveArray:function(t,i,a,r){var n=e.extend(!0,[],t) +if(r&&n.reverse(),a>=n.length)for(var o=a-n.length;o--+1;)n.push(void 0) +return n.splice(a,0,n.splice(i,1)[0]),r&&n.reverse(),n},closeButton:function(e){return e=(t.isBs(5)?"btn-close":"close")+(e?" "+e:""),'"},getRotation:function(e){switch(e){case 2:return"rotateY(180deg)" +case 3:return"rotate(180deg)" +case 4:return"rotate(180deg) rotateY(180deg)" +case 5:return"rotate(270deg) rotateY(180deg)" +case 6:return"rotate(90deg)" +case 7:return"rotate(90deg) rotateY(180deg)" +case 8:return"rotate(270deg)" +default:return""}},setTransform:function(e,t){e&&(e.style.transform=t,e.style.webkitTransform=t,e.style["-moz-transform"]=t,e.style["-ms-transform"]=t,e.style["-o-transform"]=t)},getObjectKeys:function(t){var i=[] +return t&&e.each(t,function(e){i.push(e)}),i},getObjectSize:function(e){return t.getObjectKeys(e).length},whenAll:function(i){var a,r,n,o,s,l,d=[].slice,c=1===arguments.length&&t.isArray(i)?i:d.call(arguments),u=e.Deferred(),p=0,f=c.length,g=f +for(n=o=s=Array(f),l=function(e,t,i){return function(){i!==c&&p++,u.notifyWith(t[e]=this,i[e]=d.call(arguments)),--g||u[(p?"reject":"resolve")+"With"](t,i)}},a=0;f>a;a++)(r=c[a])&&e.isFunction(r.promise)?r.promise().done(l(a,s,c)).fail(l(a,n,o)):(u.notifyWith(this,r),--g) +return g||u.resolveWith(s,c),u.promise()}},i=function(i,a){var r=this +r.$element=e(i),r.$parent=r.$element.parent(),r._validate()&&(r.isPreviewable=t.hasFileAPISupport(),r.isIE9=t.isIE(9),r.isIE10=t.isIE(10),(r.isPreviewable||r.isIE9)&&(r._init(a),r._listen()),r.$element.removeClass("file-loading"))},i.prototype={constructor:i,_cleanup:function(){var e=this +e.reader=null,e.clearFileStack(),e.fileBatchCompleted=!0,e.isError=!1,e.isDuplicateError=!1,e.isPersistentError=!1,e.cancelling=!1,e.paused=!1,e.lastProgress=0,e._initAjax()},_isAborted:function(){var e=this +return e.cancelling||e.paused},_initAjax:function(){var i=this,a=i.taskManager={pool:{},addPool:function(e){return a.pool[e]=new a.TasksPool(e)},getPool:function(e){return a.pool[e]},addTask:function(e,t){return new a.Task(e,t)},TasksPool:function(i){var r=this +r.id=i,r.cancelled=!1,r.cancelledDeferrer=e.Deferred(),r.tasks={},r.addTask=function(e,t){return r.tasks[e]=new a.Task(e,t)},r.size=function(){return t.getObjectSize(r.tasks)},r.run=function(i){var a,n,o,s=0,l=!1,d=t.getObjectKeys(r.tasks).map(function(e){return r.tasks[e]}),c=[],u=e.Deferred() +if(r.cancelled)return r.cancelledDeferrer.resolve(),u.reject() +if(!i){var p=t.getObjectKeys(r.tasks).map(function(e){return r.tasks[e].deferred}) +return t.whenAll(p).done(function(){var e=t.getArray(arguments) +r.cancelled?(u.reject.apply(null,e),r.cancelledDeferrer.resolve()):(u.resolve.apply(null,e),r.cancelledDeferrer.reject())}).fail(function(){var e=t.getArray(arguments) +u.reject.apply(null,e),r.cancelled?r.cancelledDeferrer.resolve():r.cancelledDeferrer.reject()}),e.each(r.tasks,function(e){a=r.tasks[e],a.run()}),u}for(n=function(t){e.when(t.deferred).fail(function(){l=!0,o.apply(null,arguments)}).always(o)},o=function(){var e=t.getArray(arguments) +return u.notify(e),c.push(e),r.cancelled?(u.reject.apply(null,c),void r.cancelledDeferrer.resolve()):(c.length===r.size()&&(l?u.reject.apply(null,c):u.resolve.apply(null,c)),void(d.length&&(a=d.shift(),n(a),a.run())))};d.length&&s++0&&l.maxTotalFileCount10?t-10:Math.ceil(t/2),e=t;e>i;e--)r=parseFloat(o.bpsLog[e]),a++ +o.bps=64*(a>0?r/a:0)},u),n={fileId:e,started:s,elapsed:l,loaded:a,total:r,bps:o.bps,bitrate:i._getSize(o.bps,i.bitRateUnits),pendingBytes:c},e?o.stats[e]=n:o.stats=n,n},exists:function(t){return-1!==e.inArray(t,i.fileManager.getIdList())},count:function(){return i.fileManager.getIdList().length},total:function(){var e=i.fileManager +return e.totalFiles||(e.totalFiles=e.count()),e.totalFiles},getTotalSize:function(){var t=i.fileManager +return t.totalSize?t.totalSize:(t.totalSize=0,e.each(i.getFileStack(),function(e,i){var a=parseFloat(i.size) +t.totalSize+=isNaN(a)?0:a}),t.totalSize)},add:function(e,a){a||(a=i.fileManager.getId(e)),a&&(i.fileManager.stack[a]={file:e,name:t.getFileName(e),relativePath:t.getFileRelativePath(e),size:e.size,nameFmt:i._getFileName(e,""),sizeFmt:i._getSize(e.size)})},remove:function(e){var t=i._getThumbFileId(e) +i.fileManager.removeFile(t)},removeFile:function(e){var t=i.fileManager +e&&(delete t.stack[e],delete t.loadedImages[e])},move:function(t,a){var r={},n=i.fileManager.stack;(t||a)&&t!==a&&(e.each(n,function(e,i){e!==t&&(r[e]=i),e===a&&(r[t]=n[t])}),i.fileManager.stack=r)},list:function(){var t=[] +return e.each(i.getFileStack(),function(e,i){i&&i.file&&t.push(i.file)}),t},isPending:function(t){return-1===e.inArray(t,i.fileManager.filesProcessed)&&i.fileManager.exists(t)},isProcessed:function(){var t=!0,a=i.fileManager +return e.each(i.getFileStack(),function(e){a.isPending(e)&&(t=!1)}),t},clear:function(){var e=i.fileManager +i.isDuplicateError=!1,i.isPersistentError=!1,e.totalFiles=null,e.totalSize=null,e.uploadedSize=0,e.stack={},e.errors=[],e.filesProcessed=[],e.stats={},e.bpsLog=[],e.bps=0,e.clearImages()},clearImages:function(){i.fileManager.loadedImages={},i.fileManager.totalImages=0},addImage:function(e,t){i.fileManager.loadedImages[e]=t},removeImage:function(e){delete i.fileManager.loadedImages[e]},getImageIdList:function(){return t.getObjectKeys(i.fileManager.loadedImages)},getImageCount:function(){return i.fileManager.getImageIdList().length},getId:function(e){return i._getFileId(e)},getIndex:function(e){return i.fileManager.getIdList().indexOf(e)},getThumb:function(t){var a=null +return i._getThumbs().each(function(){var r=e(this) +i._getThumbFileId(r)===t&&(a=r)}),a},getThumbIndex:function(e){var t=i._getThumbFileId(e) +return i.fileManager.getIndex(t)},getIdList:function(){return t.getObjectKeys(i.fileManager.stack)},getFile:function(e){return i.fileManager.stack[e]||null},getFileName:function(e,t){var a=i.fileManager.getFile(e) +return a?t?a.nameFmt||"":a.name||"":""},getFirstFile:function(){var e=i.fileManager.getIdList(),t=e&&e.length?e[0]:null +return i.fileManager.getFile(t)},setFile:function(e,t){i.fileManager.getFile(e)?i.fileManager.stack[e].file=t:i.fileManager.add(t,e)},setProcessed:function(e){i.fileManager.filesProcessed.push(e)},getProgress:function(){var e=i.fileManager.total(),t=i.fileManager.filesProcessed.length +return e?Math.ceil(t/e*100):0},setProgress:function(e,t){var a=i.fileManager.getFile(e) +!isNaN(t)&&a&&(a.progress=t)}}},_setUploadData:function(i,a){var r=this +e.each(a,function(e,a){var n=r.uploadParamNames[e]||e +t.isArray(a)?i.append(n,a[0],a[1]):i.append(n,a)})},_initResumableUpload:function(){var i,a=this,r=a.resumableUploadOptions,n=t.logMessages,o=a.fileManager +if(a.enableResumableUpload){if(r.fallback!==!1&&"function"!=typeof r.fallback&&(r.fallback=function(e){e._log(n.noResumableSupport),e.enableResumableUpload=!1}),!t.hasResumableUploadSupport()&&r.fallback!==!1)return void r.fallback(a) +if(!a.uploadUrl&&a.enableResumableUpload)return a._log(n.noUploadUrl),void(a.enableResumableUpload=!1) +if(r.chunkSize=parseFloat(r.chunkSize),r.chunkSize<=0||isNaN(r.chunkSize))return a._log(n.invalidChunkSize,{chunkSize:r.chunkSize}),void(a.enableResumableUpload=!1) +i=a.resumableManager={init:function(e,t,n){i.logs=[],i.stack=[],i.error="",i.id=e,i.file=t.file,i.fileName=t.name,i.fileIndex=n,i.completed=!1,i.lastProgress=0,a.showPreview&&(i.$thumb=o.getThumb(e)||null,i.$progress=i.$btnDelete=null,i.$thumb&&i.$thumb.length&&(i.$progress=i.$thumb.find(".file-thumb-progress"),i.$btnDelete=i.$thumb.find(".kv-file-remove"))),i.chunkSize=r.chunkSize*a.bytesToKB,i.chunkCount=i.getTotalChunks()},setAjaxError:function(e,t,o,s){e.responseJSON&&e.responseJSON.error&&(o=""+e.responseJSON.error),s||(i.error=o),r.showErrorLog&&a._log(n.ajaxError,{status:e.status,error:o,text:e.responseText||""})},reset:function(){i.stack=[],i.chunksProcessed={}},setProcessed:function(t){var n,s,l=i.id,d=i.$thumb,c=i.$progress,u=d&&d.length,p={id:u?d.attr("id"):"",index:o.getIndex(l),fileId:l},f=a.resumableUploadOptions.skipErrorsAndProceed +i.completed=!0,i.lastProgress=0,u&&d.removeClass("file-uploading"),"success"===t?(o.uploadedSize+=i.file.size,a.showPreview&&(a._setProgress(101,c),a._setThumbStatus(d,"Success"),a._initUploadSuccess(i.chunksProcessed[l].data,d)),o.removeFile(l),delete i.chunksProcessed[l],a._raise("fileuploaded",[p.id,p.index,p.fileId]),o.isProcessed()&&a._setProgress(101)):"cancel"!==t&&(a.showPreview&&(a._setThumbStatus(d,"Error"),a._setPreviewError(d,!0),a._setProgress(101,c,a.msgProgressError),a._setProgress(101,a.$progress,a.msgProgressError),a.cancelling=!f),a.$errorContainer.find('li[data-file-id="'+p.fileId+'"]').length||(s={file:i.fileName,max:r.maxRetries,error:i.error},n=a.msgResumableUploadRetriesExceeded.setTokens(s),e.extend(p,s),a._showFileError(n,p,"filemaxretries"),f&&(o.removeFile(l),delete i.chunksProcessed[l],o.isProcessed()&&a._setProgress(101)))),o.isProcessed()&&i.reset()},check:function(){var t=!0 +e.each(i.logs,function(e,i){return i?void 0:(t=!1,!1)})},processedResumables:function(){var e,t=i.logs,a=0 +if(!t||!t.length)return 0 +for(e=0;ei.file.size?i.file.size:e},getTotalChunks:function(){var e=parseFloat(i.chunkSize) +return!isNaN(e)&&e>0?Math.ceil(i.file.size/e):0},getProgress:function(){var e=i.processedResumables(),t=i.chunkCount +return 0===t?0:Math.ceil(e/t*100)},checkAborted:function(e){a._isAborted()&&(clearInterval(e),a.unlock())},upload:function(){var e,r=o.getIdList(),n="new" +e=setInterval(function(){var s +if(i.checkAborted(e),"new"===n&&(a.lock(),n="processing",s=r.shift(),o.initStats(s),o.stack[s]&&(i.init(s,o.stack[s],o.getIndex(s)),i.processUpload())),!o.isPending(s)&&i.completed&&(n="new"),o.isProcessed()){var l=a.$preview.find(".file-preview-initial") +l.length&&(t.addCss(l,t.SORT_CSS),a._initSortable()),clearInterval(e),a._clearFileInput(),a.unlock(),setTimeout(function(){var e=a.previewCache.data +e&&(a.initialPreview=e.content,a.initialPreviewConfig=e.config,a.initialPreviewThumbTags=e.tags),a._raise("filebatchuploadcomplete",[a.initialPreview,a.initialPreviewConfig,a.initialPreviewThumbTags,a._getExtraData()])},a.processDelay)}},a.processDelay)},uploadResumable:function(){var e,t,n=a.taskManager,o=i.chunkCount +for(t=n.addPool(i.id),e=0;o>e;e++)i.logs[e]=!(!i.chunksProcessed[i.id]||!i.chunksProcessed[i.id][e]),i.logs[e]||i.pushAjax(e,0) +t.run(r.maxThreads).done(function(){i.setProcessed("success")}).fail(function(){i.setProcessed(t.cancelled?"cancel":"error")})},processUpload:function(){var n,s,l,d,c,u,p,f=i.id +return r.testUrl?(n=new FormData,s=o.stack[f],a._setUploadData(n,{fileId:f,fileName:s.fileName,fileSize:s.size,fileRelativePath:s.relativePath,chunkSize:i.chunkSize,chunkCount:i.chunkCount}),l=function(e){p=a._getOutData(n,e),a._raise("filetestbeforesend",[f,o,i,p])},d=function(r,s,l){p=a._getOutData(n,l,r) +var d=a.uploadParamNames,c=d.chunksUploaded||"chunksUploaded",u=[f,o,i,p] +r[c]&&t.isArray(r[c])?(i.chunksProcessed[f]||(i.chunksProcessed[f]={}),e.each(r[c],function(e,t){i.logs[t]=!0,i.chunksProcessed[f][t]=!0}),i.chunksProcessed[f].data=r,a._raise("filetestsuccess",u)):a._raise("filetesterror",u),i.uploadResumable()},c=function(e,t,r){p=a._getOutData(n,e),a._raise("filetestajaxerror",[f,o,i,p]),i.setAjaxError(e,t,r,!0),i.uploadResumable()},u=function(){a._raise("filetestcomplete",[f,o,i,a._getOutData(n)])},void a._ajaxSubmit(l,d,u,c,n,f,i.fileIndex,r.testUrl)):void i.uploadResumable()},pushAjax:function(e,t){var r=a.taskManager,o=r.getPool(i.id) +o.addTask(o.size()+1,function(e){var t,r=i.stack.shift() +t=r[0],i.chunksProcessed[i.id]&&i.chunksProcessed[i.id][t]?a._log(n.chunkQueueError,{index:t}):i.sendAjax(t,r[1],e)}),i.stack.push([e,t])},sendAjax:function(e,s,l){var d,c=i.chunkSize,u=i.id,p=i.file,f=i.$thumb,g=t.logMessages,m=i.$btnDelete,h=function(e,t){t&&(e=e.setTokens(t)),e=g.resumableRequestError.setTokens({msg:e}),a._log(e),l.reject(e)} +if(!i.chunksProcessed[u]||!i.chunksProcessed[u][e]){if(s>r.maxRetries)return h(g.resumableMaxRetriesReached,{n:r.maxRetries}),void i.setProcessed("error") +var v,w,b,_,C,y,x=p.slice?"slice":p.mozSlice?"mozSlice":p.webkitSlice?"webkitSlice":"slice",T=p[x](c*e,c*(e+1)) +v=new FormData,d=o.stack[u],a._setUploadData(v,{chunkCount:i.chunkCount,chunkIndex:e,chunkSize:c,chunkSizeStart:c*e,fileBlob:[T,i.fileName],fileId:u,fileName:i.fileName,fileRelativePath:d.relativePath,fileSize:p.size,retryCount:s}),i.$progress&&i.$progress.length&&i.$progress.show(),b=function(r){w=a._getOutData(v,r),a.showPreview&&(f.hasClass("file-preview-success")||(a._setThumbStatus(f,"Loading"),t.addCss(f,"file-uploading")),m.attr("disabled",!0)),a._raise("filechunkbeforesend",[u,e,s,o,i,w])},_=function(t,d,c){if(a._isAborted())return void h(g.resumableAborting) +w=a._getOutData(v,c,t) +var p=a.uploadParamNames,f=p.chunkIndex||"chunkIndex",m=[u,e,s,o,i,w] +t.error?(r.showErrorLog&&a._log(n.retryStatus,{retry:s+1,filename:i.fileName,chunk:e}),a._raise("filechunkerror",m),i.pushAjax(e,s+1),i.error=t.error,h(t.error)):(i.logs[t[f]]=!0,i.chunksProcessed[u]||(i.chunksProcessed[u]={}),i.chunksProcessed[u][t[f]]=!0,i.chunksProcessed[u].data=t,l.resolve.call(null,t),a._raise("filechunksuccess",m),i.check())},C=function(t,r,n){return a._isAborted()?void h(g.resumableAborting):(w=a._getOutData(v,t),i.setAjaxError(t,r,n),a._raise("filechunkajaxerror",[u,e,s,o,i,w]),i.pushAjax(e,s+1),void h(g.resumableRetryError,{n:s-1}))},y=function(){a._isAborted()||a._raise("filechunkcomplete",[u,e,s,o,i,a._getOutData(v)])},a._ajaxSubmit(b,_,y,C,v,u,i.fileIndex)}}},i.reset()}},_initTemplateDefaults:function(){var i,a,r,n,o,s,l,d,c,u,p,f,g,m,h,v,w,b,_,C,y,x,T,P,F,k,E,S,I,A,z,D,U,j,$,M,B,R,O,L,N,Z,H,W=this,K=function(e,i){return'\n"+t.DEFAULT_PREVIEW+"\n\n"},q="btn btn-sm btn-kv "+t.defaultButtonCss() +i='{preview}\n
    \n
    \n
    \n {caption}\n\n'+(t.isBs(5)?"":'
    \n')+" {remove}\n {cancel}\n {pause}\n {upload}\n {browse}\n"+(t.isBs(5)?"":"
    \n")+"
    ",a='{preview}\n
    \n
    \n{remove}\n{cancel}\n{upload}\n{browse}\n',r='
    \n {close}
    \n
    \n
    \n
    \n
    \n
    \n
    ',o=t.closeButton("fileinput-remove"),n='',s='\n',l='',d='{icon} {label}',c='
    {icon} {label}
    ',Z=t.MODAL_ID+"Label",u='',p='\n',H='',f='
    \n
    \n {status}\n
    \n
    {stats}',N='
    {pendingTime} {uploadSpeed}
    ',g=" ({sizeText})",m='',h='
    \n \n
    \n{drag}\n
    ',v='\n',w='',b='{downloadIcon}',_='',C='{dragIcon}',y='
    {indicator}
    ',x='
    \n',P=x+' title="{caption}">
    \n',F="
    {footer}\n{zoomCache}
    \n",k="{content}\n",R=" {style}",E=K("html","text/html"),I=K("text","text/plain;charset=UTF-8"),M=K("pdf","application/pdf"),S='{alt}\n",A='",z='",D='\n",U='\n",j='\n",$='\n\n'+t.OBJECT_PARAMS+" "+t.DEFAULT_PREVIEW+"\n\n",B='
    \n"+t.DEFAULT_PREVIEW+"\n
    \n",O='
    {zoomContent}
    ',L={width:"100%",height:"100%","min-height":"480px"},W._isPdfRendered()&&(M=W.pdfRendererTemplate.replace("{renderer}",W._encodeURI(W.pdfRendererUrl))),W.defaults={layoutTemplates:{main1:i,main2:a,preview:r,close:o,fileIcon:n,caption:s,modalMain:u,modal:p,descriptionClose:H,progress:f,stats:N,size:g,footer:m,indicator:y,actions:h,actionDelete:v,actionUpload:w,actionDownload:b,actionZoom:_,actionDrag:C,btnDefault:l,btnLink:d,btnBrowse:c,zoomCache:O},previewMarkupTags:{tagBefore1:T,tagBefore2:P,tagAfter:F},previewContentTemplates:{generic:k,html:E,image:S,text:I,office:A,gdocs:z,video:D,audio:U,flash:j,object:$,pdf:M,other:B},allowedPreviewTypes:["image","html","text","video","audio","flash","pdf","object"],previewTemplates:{},previewSettings:{image:{width:"auto",height:"auto","max-width":"100%","max-height":"100%"},html:{width:"213px",height:"160px"},text:{width:"213px",height:"160px"},office:{width:"213px",height:"160px"},gdocs:{width:"213px",height:"160px"},video:{width:"213px",height:"160px"},audio:{width:"100%",height:"30px"},flash:{width:"213px",height:"160px"},object:{width:"213px",height:"160px"},pdf:{width:"100%",height:"160px",position:"relative"},other:{width:"213px",height:"160px"}},previewSettingsSmall:{image:{width:"auto",height:"auto","max-width":"100%","max-height":"100%"},html:{width:"100%",height:"160px"},text:{width:"100%",height:"160px"},office:{width:"100%",height:"160px"},gdocs:{width:"100%",height:"160px"},video:{width:"100%",height:"auto"},audio:{width:"100%",height:"30px"},flash:{width:"100%",height:"auto"},object:{width:"100%",height:"auto"},pdf:{width:"100%",height:"160px"},other:{width:"100%",height:"160px"}},previewZoomSettings:{image:{width:"auto",height:"auto","max-width":"100%","max-height":"100%"},html:L,text:L,office:{width:"100%",height:"100%","max-width":"100%","min-height":"480px"},gdocs:{width:"100%",height:"100%","max-width":"100%","min-height":"480px"},video:{width:"auto",height:"100%","max-width":"100%"},audio:{width:"100%",height:"30px"},flash:{width:"auto",height:"480px"},object:{width:"auto",height:"100%","max-width":"100%","min-height":"480px"},pdf:L,other:{width:"auto",height:"100%","min-height":"480px"}},mimeTypeAliases:{"video/quicktime":"video/mp4"},fileTypeSettings:{image:function(e,i){return t.compare(e,"image.*")&&!t.compare(e,/(tiff?|wmf)$/i)||t.compare(i,/\.(gif|png|jpe?g)$/i)},html:function(e,i){return t.compare(e,"text/html")||t.compare(i,/\.(htm|html)$/i)},office:function(e,i){return t.compare(e,/(word|excel|powerpoint|office)$/i)||t.compare(i,/\.(docx?|xlsx?|pptx?|pps|potx?)$/i)},gdocs:function(e,i){return t.compare(e,/(word|excel|powerpoint|office|iwork-pages|tiff?)$/i)||t.compare(i,/\.(docx?|xlsx?|pptx?|pps|potx?|rtf|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i)},text:function(e,i){return t.compare(e,"text.*")||t.compare(i,/\.(xml|javascript)$/i)||t.compare(i,/\.(txt|md|nfo|ini|json|php|js|css)$/i)},video:function(e,i){return t.compare(e,"video.*")&&(t.compare(e,/(ogg|mp4|mp?g|mov|webm|3gp)$/i)||t.compare(i,/\.(og?|mp4|webm|mp?g|mov|3gp)$/i))},audio:function(e,i){return t.compare(e,"audio.*")&&(t.compare(i,/(ogg|mp3|mp?g|wav)$/i)||t.compare(i,/\.(og?|mp3|mp?g|wav)$/i))},flash:function(e,i){return t.compare(e,"application/x-shockwave-flash",!0)||t.compare(i,/\.(swf)$/i)},pdf:function(e,i){return t.compare(e,"application/pdf",!0)||t.compare(i,/\.(pdf)$/i)},object:function(){return!0},other:function(){return!0}},fileActionSettings:{showRemove:!0,showUpload:!0,showDownload:!0,showZoom:!0,showDrag:!0,removeIcon:'',removeClass:q,removeErrorClass:"btn btn-sm btn-kv btn-danger",removeTitle:"Remove file",uploadIcon:'',uploadClass:q,uploadTitle:"Upload file",uploadRetryIcon:'',uploadRetryTitle:"Retry upload",downloadIcon:'',downloadClass:q,downloadTitle:"Download file",zoomIcon:'',zoomClass:q,zoomTitle:"View Details",dragIcon:'',dragClass:"text-primary",dragTitle:"Move / Rearrange",dragSettings:{},indicatorNew:'',indicatorSuccess:'',indicatorError:'',indicatorLoading:'',indicatorPaused:'',indicatorNewTitle:"Not uploaded yet",indicatorSuccessTitle:"Uploaded",indicatorErrorTitle:"Upload Error",indicatorLoadingTitle:"Uploading …",indicatorPausedTitle:"Upload Paused"}},e.each(W.defaults,function(t,i){return"allowedPreviewTypes"===t?void(void 0===W.allowedPreviewTypes&&(W.allowedPreviewTypes=i)):void(W[t]=e.extend(!0,{},i,W[t]))}),W._initPreviewTemplates()},_initPreviewTemplates:function(){var i,a=this,r=a.previewMarkupTags,n=r.tagAfter +e.each(a.previewContentTemplates,function(e,o){t.isEmpty(a.previewTemplates[e])&&(i=r.tagBefore2,("generic"===e||"image"===e)&&(i=r.tagBefore1),a._isPdfRendered()&&"pdf"===e&&(i=i.replace("kv-file-content","kv-file-content kv-pdf-rendered")),a.previewTemplates[e]=i+o+n)})},_initPreviewCache:function(){var i=this +i.previewCache={data:{},init:function(){var e=i.initialPreview +e.length>0&&!t.isArray(e)&&(e=e.split(i.initialPreviewDelimiter)),i.previewCache.data={content:e,config:i.initialPreviewConfig,tags:i.initialPreviewThumbTags}},count:function(e){if(!i.previewCache.data||!i.previewCache.data.content)return 0 +if(e){var t=i.previewCache.data.content.filter(function(e){return null!==e}) +return t.length}return i.previewCache.data.content.length},get:function(e,a){var r,n,o,s,l,d,c,u=t.INIT_FLAG+e,p=i.previewCache.data,f=p.config[e],g=p.content[e],m=t.ifSet("previewAsData",f,i.initialPreviewAsData),h=f?{title:f.title||null,alt:f.alt||null}:{title:null,alt:null},v=function(e,a,r,n,o,s,l,d){var c=" file-preview-initial "+t.SORT_CSS+(l?" "+l:""),u=i.previewInitId+"-"+s,p=f&&f.fileId||u +return i._generatePreviewTemplate(e,a,r,n,u,p,!1,null,c,o,s,d,h,f&&f.zoomData||a)} +return g&&g.length?(a=void 0===a?!0:a,o=t.ifSet("type",f,i.initialPreviewFileType||"generic"),l=t.ifSet("filename",f,t.ifSet("caption",f)),d=t.ifSet("filetype",f,o),s=i.previewCache.footer(e,a,f&&f.size||null),c=t.ifSet("frameClass",f),r=m?v(o,g,l,d,s,u,c):v("generic",g,l,d,s,u,c,o).setTokens({content:p.content[e]}),p.tags.length&&p.tags[e]&&(r=t.replaceTags(r,p.tags[e])),t.isEmpty(f)||t.isEmpty(f.frameAttr)||(n=t.createElement(r),n.find(".file-preview-initial").attr(f.frameAttr),r=n.html(),n.remove()),r):""},clean:function(e){e.content=t.cleanArray(e.content),e.config=t.cleanArray(e.config),e.tags=t.cleanArray(e.tags),i.previewCache.data=e},add:function(e,a,r,n){var o,s=i.previewCache.data +return e&&e.length?(o=e.length-1,t.isArray(e)||(e=e.split(i.initialPreviewDelimiter)),n&&s.content?(o=s.content.push(e[0])-1,s.config[o]=a,s.tags[o]=r):(s.content=e,s.config=a,s.tags=r),i.previewCache.clean(s),o):0},set:function(e,a,r,n){var o,s,l=i.previewCache.data +if(e&&e.length&&(t.isArray(e)||(e=e.split(i.initialPreviewDelimiter)),s=e.filter(function(e){return null!==e}),s.length)){if(void 0===l.content&&(l.content=[]),void 0===l.config&&(l.config=[]),void 0===l.tags&&(l.tags=[]),n){for(o=0;ot;t++)a=i.previewCache.get(t),r=i.reversePreviewOrder?a+r:r+a +return e=i._getMsgSelected(n),{content:r,caption:e}},footer:function(e,a,r){var n=i.previewCache.data||{} +if(t.isEmpty(n.content))return"";(t.isEmpty(n.config)||t.isEmpty(n.config[e]))&&(n.config[e]={}),a=void 0===a?!0:a +var o,s=n.config[e],l=t.ifSet("caption",s),d=t.ifSet("width",s,"auto"),c=t.ifSet("url",s,!1),u=t.ifSet("key",s,null),p=t.ifSet("fileId",s,null),f=i.fileActionSettings,g=i.initialPreviewShowDelete||!1,m=i.initialPreviewDownloadUrl?i.initialPreviewDownloadUrl+"?key="+u+(p?"&fileId="+p:""):"",h=s.downloadUrl||m,v=s.filename||s.caption||"",w=!!h,b=t.ifSet("showRemove",s,g),_=t.ifSet("showDownload",s,t.ifSet("showDownload",f,w)),C=t.ifSet("showZoom",s,t.ifSet("showZoom",f,!0)),y=t.ifSet("showDrag",s,t.ifSet("showDrag",f,!0)),x=c===!1&&a +return _=_&&s.downloadUrl!==!1&&!!h,o=i._renderFileActions(s,!1,_,b,C,y,x,c,u,!0,h,v),i._getLayoutTemplate("footer").setTokens({progress:i._renderThumbProgress(),actions:o,caption:l,size:i._getSize(r),width:d,indicator:""})}},i.previewCache.init()},_isPdfRendered:function(){var e=this,t=e.usePdfRenderer,i="function"==typeof t?t():!!t +return i&&e.pdfRendererUrl},_handler:function(e,t,i){var a=this,r=a.namespace,n=t.split(" ").join(r+" ")+r +e&&e.length&&e.off(n).on(n,i)},_encodeURI:function(e){var t=this +return t.encodeUrl?encodeURI(e):e},_log:function(e,t){var i=this,a=i.$element.attr("id") +i.showConsoleLogs&&(a&&(e='"'+a+'": '+e),e="bootstrap-fileinput: "+e,"object"==typeof t&&(e=e.setTokens(t)),window.console&&void 0!==window.console.log?window.console.log(e):window.alert(e))},_validate:function(){var e=this,i="file"===e.$element.attr("type") +return i||e._log(t.logMessages.badInputType),i},_errorsExist:function(){var i,a=this,r=a.$errorContainer.find("li") +return r.length?!0:(i=t.createElement(a.$errorContainer.html()),i.find(".kv-error-close").remove(),i.find("ul").remove(),!!e.trim(i.text()).length)},_errorHandler:function(e,t){var i=this,a=e.target.error,r=function(e){i._showError(e.replace("{name}",t))} +r(a.code===a.NOT_FOUND_ERR?i.msgFileNotFound:a.code===a.SECURITY_ERR?i.msgFileSecured:a.code===a.NOT_READABLE_ERR?i.msgFileNotReadable:a.code===a.ABORT_ERR?i.msgFilePreviewAborted:i.msgFilePreviewError)},_addError:function(e){var i=this,a=i.$errorContainer +e&&a.length&&(t.setHtml(a,i.errorCloseButton+e),i._handler(a.find(".kv-error-close"),"click",function(){setTimeout(function(){i.showPreview&&!i.getFrames().length&&i.clear(),a.fadeOut("slow")},i.processDelay)}))},_setValidationError:function(e){var i=this +e=(e?e+" ":"")+"has-error",i.$container.removeClass(e).addClass("has-error"),t.addCss(i.$caption,"is-invalid")},_resetErrors:function(e){var t=this,i=t.$errorContainer,a=t.resumableUploadOptions.retainErrorHistory +t.isPersistentError||t.enableResumableUpload&&a||(t.isError=!1,t.$container.removeClass("has-error"),t.$caption.removeClass("is-invalid is-valid file-processing"),i.html(""),e?i.fadeOut("slow"):i.hide())},_showFolderError:function(e){var t,i=this,a=i.$errorContainer +e&&(i.isAjaxUpload||i._clearFileInput(),t=i.msgFoldersNotAllowed.replace("{n}",e),i._addError(t),i._setValidationError(),a.fadeIn(i.fadeDelay),i._raise("filefoldererror",[e,t]))},_showFileError:function(e,t,i){var a=this,r=a.$errorContainer,n=i||"fileuploaderror",o=t&&t.fileId||"",s=t&&t.id?'
  • '+e+"
  • ":"
  • "+e+"
  • " +return 0===r.find("ul").length?a._addError("
      "+s+"
    "):r.find("ul").append(s),r.fadeIn(a.fadeDelay),a._raise(n,[t,e]),a._setValidationError("file-input-new"),!0},_showError:function(e,t,i){var a=this,r=a.$errorContainer,n=i||"fileerror" +return t=t||{},t.reader=a.reader,a._addError(e),r.fadeIn(a.fadeDelay),a._raise(n,[t,e]),a.isAjaxUpload||a._clearFileInput(),a._setValidationError("file-input-new"),a.$btnUpload.attr("disabled",!0),!0},_noFilesError:function(e){var t=this,i=t.minFileCount>1?t.filePlural:t.fileSingle,a=t.msgFilesTooLess.replace("{n}",t.minFileCount).replace("{files}",i),r=t.$errorContainer +a="
  • "+a+"
  • ",0===r.find("ul").length?t._addError("
      "+a+"
    "):r.find("ul").append(a),t.isError=!0,t._updateFileDetails(0),r.fadeIn(t.fadeDelay),t._raise("fileerror",[e,a]),t._clearFileInput(),t._setValidationError()},_parseError:function(t,i,a,r){var n,o,s,l=this,d=e.trim(a+"") +return o=i.responseJSON&&i.responseJSON.error?""+i.responseJSON.error:"",s=o?o:i.responseText,l.cancelling&&l.msgUploadAborted&&(d=l.msgUploadAborted),l.showAjaxErrorDetails&&s&&(o?d=e.trim(o+""):(s=e.trim(s.replace(/\n\s*\n/g,"\n")),n=s.length?"
    "+s+"
    ":"",d+=d?n:s)),d||(d=l.msgAjaxError.replace("{operation}",t)),l.cancelling=!1,r?""+r+": "+d:d},_parseFileType:function(e,i){var a,r,n,o,s=this,l=s.allowedPreviewTypes||[] +if("application/text-plain"===e)return"text" +for(o=0;o-1&&(i=t.split(".").pop(),a.previewFileIconSettings&&(r=a.previewFileIconSettings[i]||a.previewFileIconSettings[i.toLowerCase()]||null),a.previewFileExtSettings&&e.each(a.previewFileExtSettings,function(e,t){return a.previewFileIconSettings[e]&&t(i)?void(r=a.previewFileIconSettings[e]):void 0})),r||a.previewFileIcon},_parseFilePreviewIcon:function(e,t){var i=this,a=i._getPreviewIcon(t),r=e +return r.indexOf("{previewFileIcon}")>-1&&(r=r.setTokens({previewFileIconClass:i.previewFileIconClass,previewFileIcon:a})),r},_raise:function(t,i){var a=this,r=e.Event(t) +void 0!==i?a.$element.trigger(r,i):a.$element.trigger(r) +var n=r.result,o=n===!1 +if(r.isDefaultPrevented()||o)return!1 +if("filebatchpreupload"===r.type&&(n||o))return a.ajaxAborted=n,!1 +switch(t){case"filebatchuploadcomplete":case"filebatchuploadsuccess":case"fileuploaded":case"fileclear":case"filecleared":case"filereset":case"fileerror":case"filefoldererror":case"fileuploaderror":case"filebatchuploaderror":case"filedeleteerror":case"filecustomerror":case"filesuccessremove":break +default:a.ajaxAborted||(a.ajaxAborted=n)}return!0},_listenFullScreen:function(e){var t,i,a=this,r=a.$modal +r&&r.length&&(t=r&&r.find(".btn-kv-fullscreen"),i=r&&r.find(".btn-kv-borderless"),t.length&&i.length&&(t.removeClass("active").attr("aria-pressed","false"),i.removeClass("active").attr("aria-pressed","false"),e?t.addClass("active").attr("aria-pressed","true"):i.addClass("active").attr("aria-pressed","true"),r.hasClass("file-zoom-fullscreen")?a._maximizeZoomDialog():e?a._maximizeZoomDialog():i.removeClass("active").attr("aria-pressed","false")))},_listen:function(){var i,a=this,r=a.$element,n=a.$form,o=a.$container +a._handler(r,"click",function(e){a._initFileSelected(),r.hasClass("file-no-browse")&&(r.data("zoneClicked")?r.data("zoneClicked",!1):e.preventDefault())}),a._handler(r,"change",e.proxy(a._change,a)),a._handler(a.$caption,"paste",e.proxy(a.paste,a)),a.showBrowse&&(a._handler(a.$btnFile,"click",e.proxy(a._browse,a)),a._handler(a.$btnFile,"keypress",function(e){var t=e.keyCode||e.which +13===t&&(r.trigger("click"),a._browse(e))})),a._handler(o.find(".fileinput-remove:not([disabled])"),"click",e.proxy(a.clear,a)),a._handler(o.find(".fileinput-cancel"),"click",e.proxy(a.cancel,a)),a._handler(o.find(".fileinput-pause"),"click",e.proxy(a.pause,a)),a._initDragDrop(),a._handler(n,"reset",e.proxy(a.clear,a)),a.isAjaxUpload||a._handler(n,"submit",e.proxy(a._submitForm,a)),a._handler(a.$container.find(".fileinput-upload"),"click",e.proxy(a._uploadClick,a)),a._handler(e(window),"resize",function(){a._listenFullScreen(screen.width===window.innerWidth&&screen.height===window.innerHeight)}),i="webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange",a._handler(e(document),i,function(){a._listenFullScreen(t.checkFullScreen())}),a.$caption.on("focus",function(){a.$captionContainer.focus()}),a._autoFitContent(),a._initClickable(),a._refreshPreview()},_autoFitContent:function(){var t,i=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,a=this,r=400>i?a.previewSettingsSmall||a.defaults.previewSettingsSmall:a.previewSettings||a.defaults.previewSettings +e.each(r,function(e,i){t=".file-preview-frame .file-preview-"+e,a.$preview.find(t+".kv-preview-data,"+t+" .kv-preview-data").css(i)})},_scanDroppedItems:function(e,i,a){a=a||"" +var r,n,o,s=this,l=function(e){s._log(t.logMessages.badDroppedFiles),s._log(e)} +e.isFile?e.file(function(e){a&&(e.newPath=a+e.name),i.push(e)},l):e.isDirectory&&(n=e.createReader(),(o=function(){n.readEntries(function(t){if(t&&t.length>0){for(r=0;r-1 +return a._zoneDragDropInit(i),a.isDisabled||!n?(r.effectAllowed="none",void(r.dropEffect="none")):(r.dropEffect="copy",void(a._raise("fileDragEnter",{sourceEvent:i,files:r.types.Files})&&t.addCss(a.$dropZone,"file-highlighted")))},_zoneDragLeave:function(e){var t=this +t._zoneDragDropInit(e),t.isDisabled||t._raise("fileDragLeave",{sourceEvent:e})&&t.$dropZone.removeClass("file-highlighted")},_dropFiles:function(e,t){var i=this,a=i.$element +i.isAjaxUpload?i._change(e,t):(i.changeTriggered=!0,a.get(0).files=t,setTimeout(function(){i.changeTriggered=!1,a.trigger("change"+i.namespace)},i.processDelay)),i.$dropZone.removeClass("file-highlighted")},_zoneDrop:function(e){var i,a=this,r=(a.$element,e.originalEvent.dataTransfer),n=r.files,o=r.items,s=t.getDragDropFolders(o) +if(e.preventDefault(),!a.isDisabled&&!t.isEmpty(n)&&a._raise("fileDragDrop",{sourceEvent:e,files:n}))if(s>0){if(!a.isAjaxUpload)return void a._showFolderError(s) +for(n=[],i=0;i0&&n>=l,c=e(i.item) +d&&(n=l-1),o.initialPreview=t.moveArray(o.initialPreview,r,n,u),o.initialPreviewConfig=t.moveArray(o.initialPreviewConfig,r,n,u),o.previewCache.init(),o.getFrames(".file-preview-initial").each(function(){e(this).attr("data-fileindex",t.INIT_FLAG+s),s++}),d&&(a=o.getFrames(":not(.file-preview-initial):first"),a.length&&c.slideUp(function(){c.insertBefore(a).slideDown()})),o._raise("filesorted",{previewId:c.attr("id"),oldIndex:r,newIndex:n,stack:o.initialPreviewConfig})}},e.extend(!0,i,o.fileActionSettings.dragSettings),o.sortable&&o.sortable.destroy(),o.sortable=p.create(s[0],i))},_setPreviewContent:function(e){var i=this +t.setHtml(i.$preview,e),i._autoFitContent()},_initPreviewImageOrientations:function(){var t=this,i=0,a=t.canOrientImage;(t.autoOrientImageInitial||a)&&t.getFrames(".file-preview-initial").each(function(){var r,n,o,s=e(this),l=t.initialPreviewConfig[i] +l&&l.exif&&l.exif.Orientation&&(o=s.attr("id"),r=s.find(">.kv-file-content img"),n=t._getZoom(o," >.kv-file-content img"),a?r.css("image-orientation",t.autoOrientImageInitial?"from-image":"none"):t.setImageOrientation(r,n,l.exif.Orientation,s)),i++})},_initPreview:function(e){var i,a=this,r=a.initialCaption||"" +return a.previewCache.count(!0)?(i=a.previewCache.out(),r=e&&a.initialCaption?a.initialCaption:i.caption,a._setPreviewContent(i.content),a._setInitThumbAttr(),a._setCaption(r),a._initSortable(),t.isEmpty(i.content)||a.$container.removeClass("file-input-new"),void a._initPreviewImageOrientations()):(a._clearPreview(),void(e?a._setCaption(r):a._initCaption()))},_getZoomButton:function(e){var i=this,a=i.previewZoomButtonIcons[e],r=i.previewZoomButtonClasses[e],n=' title="'+(i.previewZoomButtonTitles[e]||"")+'" ',o=t.isBs(5)?"bs-":"",s=n+("close"===e?" data-"+o+'dismiss="modal" aria-hidden="true"':"") +return("fullscreen"===e||"borderless"===e||"toggleheader"===e)&&(s+=' data-toggle="button" aria-pressed="false" autocomplete="off"'),'"},_getModalContent:function(){var e=this +return e._getLayoutTemplate("modal").setTokens({rtl:e.rtl?" kv-rtl":"",zoomFrameClass:e.frameClass,prev:e._getZoomButton("prev"),next:e._getZoomButton("next"),toggleheader:e._getZoomButton("toggleheader"),fullscreen:e._getZoomButton("fullscreen"),borderless:e._getZoomButton("borderless"),close:e._getZoomButton("close")})},_listenModalEvent:function(e){var i=this,a=i.$modal,r=function(e){return{sourceEvent:e,previewId:a.data("previewId"),modal:a}} +a.on(e+".bs.modal",function(n){if("bs.modal"===n.namespace){var o=a.find(".btn-fullscreen"),s=a.find(".btn-borderless") +a.data("fileinputPluginId")===i.$element.attr("id")&&i._raise("filezoom"+e,r(n)),"shown"===e&&(s.removeClass("active").attr("aria-pressed","false"),o.removeClass("active").attr("aria-pressed","false"),a.hasClass("file-zoom-fullscreen")&&(i._maximizeZoomDialog(),t.checkFullScreen()?o.addClass("active").attr("aria-pressed","true"):s.addClass("active").attr("aria-pressed","true")))}})},_initZoom:function(){var i,a=this,r=a._getLayoutTemplate("modalMain"),n="#"+t.MODAL_ID +r=a._setTabIndex("modal",r),a.showPreview&&(a.$modal=e(n),a.$modal&&a.$modal.length||(i=t.createElement(t.cspBuffer.stash(r)).insertAfter(a.$container),a.$modal=e(n).insertBefore(i),t.cspBuffer.apply(a.$modal),i.remove()),t.initModal(a.$modal),a.$modal.html(t.cspBuffer.stash(a._getModalContent())),t.cspBuffer.apply(a.$modal),e.each(t.MODAL_EVENTS,function(e,t){a._listenModalEvent(t)}))},_initZoomButtons:function(){var t,i,a=this,r=a.$modal.data("previewId")||"",n=a.getFrames().toArray(),o=n.length,s=a.$modal.find(".btn-kv-prev"),l=a.$modal.find(".btn-kv-next") +return n.length<2?(s.hide(),void l.hide()):(s.show(),l.show(),void(o&&(t=e(n[0]),i=e(n[o-1]),s.removeAttr("disabled"),l.removeAttr("disabled"),a.reversePreviewOrder&&([s,l]=[l,s]),t.length&&t.attr("id")===r&&s.attr("disabled",!0),i.length&&i.attr("id")===r&&l.attr("disabled",!0))))},_maximizeZoomDialog:function(){var t=this,i=t.$modal,a=i.find(".modal-header:visible"),r=i.find(".modal-footer:visible"),n=i.find(".kv-zoom-body"),o=e(window).height(),s=0 +i.addClass("file-zoom-fullscreen"),a&&a.length&&(o-=a.outerHeight(!0)),r&&r.length&&(o-=r.outerHeight(!0)),n&&n.length&&(s=n.outerHeight(!0)-n.height(),o-=s),i.find(".kv-zoom-body").height(o)},_resizeZoomDialog:function(e){var i=this,a=i.$modal,r=a.find(".btn-kv-fullscreen"),n=a.find(".btn-kv-borderless") +if(a.hasClass("file-zoom-fullscreen"))t.toggleFullScreen(!1),e?r.hasClass("active")||(a.removeClass("file-zoom-fullscreen"),i._resizeZoomDialog(!0),n.hasClass("active")&&n.removeClass("active").attr("aria-pressed","false")):r.hasClass("active")?r.removeClass("active").attr("aria-pressed","false"):(a.removeClass("file-zoom-fullscreen"),i.$modal.find(".kv-zoom-body").css("height",i.zoomModalHeight)) +else{if(!e)return void i._maximizeZoomDialog() +t.toggleFullScreen(!0)}a.focus()},_setZoomContent:function(i,a){var r,n,o,s,l,d,c,u,p,f,g,m,h=this,v=i.attr("id"),w=h._getZoom(v),b=h.$modal,_=b.find(".btn-kv-fullscreen"),C=b.find(".btn-kv-borderless"),y=b.find(".btn-kv-toggleheader"),x=i.data("zoom") +x&&(x=decodeURIComponent(x),m=w.html().setTokens({zoomData:x}),w.html(m),i.data("zoom",""),w.attr("data-zoom",x)),n=w.attr("data-template")||"generic",r=w.find(".kv-file-content"),o=r.length?'\n'+r.html():"",f=i.data("caption")||h.msgZoomModalHeading,g=i.data("size")||"",u=i.data("description")||"",b.find(".kv-zoom-caption").attr("title",f).html(f),b.find(".kv-zoom-size").html(g),p=b.find(".kv-zoom-description").hide(),u&&(h.showDescriptionClose&&(u=h._getLayoutTemplate("descriptionClose").setTokens({closeIcon:h.previewZoomButtonIcons.close})+""+u),p.show().html(u),h.showDescriptionClose&&h._handler(b.find(".kv-desc-hide"),"click",function(){e(this).parent().fadeOut("fast",function(){b.focus()})})),s=b.find(".kv-zoom-body"),b.removeClass("kv-single-content"),a?(c=s.addClass("file-thumb-loading").clone().insertAfter(s),t.setHtml(s,o).hide(),c.fadeOut("fast",function(){s.fadeIn("fast",function(){s.removeClass("file-thumb-loading")}),c.remove()})):t.setHtml(s,o),d=h.previewZoomSettings[n],d&&(l=s.find(".kv-preview-data"),t.addCss(l,"file-zoom-detail"),e.each(d,function(e,t){l.css(e,t),(l.attr("width")&&"width"===e||l.attr("height")&&"height"===e)&&l.removeAttr(e)})),b.data("previewId",v),h._handler(b.find(".btn-kv-prev"),"click",function(){h._zoomSlideShow("prev",v)}),h._handler(b.find(".btn-kv-next"),"click",function(){h._zoomSlideShow("next",v)}),h._handler(_,"click",function(){h._resizeZoomDialog(!0)}),h._handler(C,"click",function(){h._resizeZoomDialog(!1)}),h._handler(y,"click",function(){var e,t=b.find(".modal-header"),i=b.find(".floating-buttons"),a=t.find(".kv-zoom-actions"),r=function(e){var i=h.$modal.find(".kv-zoom-body"),a=h.zoomModalHeight +b.hasClass("file-zoom-fullscreen")&&(a=i.outerHeight(!0),e||(a-=t.outerHeight(!0))),i.css("height",e?a+e:a)} +t.is(":visible")?(e=t.outerHeight(!0),t.slideUp("slow",function(){a.find(".btn").appendTo(i),r(e)})):(i.find(".btn").appendTo(a),t.slideDown("slow",function(){r()})),b.focus()}),h._handler(b,"keydown",function(t){var i,a,r=t.which||t.keyCode,n=h.processDelay+1,o=e(this).find(".btn-kv-prev"),s=e(this).find(".btn-kv-next"),l=e(this).data("previewId");[i,a]=h.rtl?[39,37]:[37,39],e.each({prev:[o,i],next:[s,a]},function(e,t){var i=t[0],a=t[1] +r===a&&i.length&&(b.focus(),i.attr("disabled")||(i.focus(),h._zoomSlideShow(e,l),setTimeout(function(){i.attr("disabled")&&b.focus()},n)))})})},_showModal:function(e){var i=this,a=i.$modal +e&&e.length&&(t.initModal(a),t.setHtml(a,i._getModalContent()),i._setZoomContent(e),a.data({backdrop:!1}),a.modal("show"),i._initZoomButtons())},_zoomPreview:function(e){var i,a=this +if(!e.length)throw"Cannot zoom to detailed preview!" +i=e.closest(t.FRAMES),a._showModal(i)},_zoomSlideShow:function(t,i){var a,r,n,o,s=this,l=s.$modal.find(".kv-zoom-actions .btn-kv-"+t),d=s.getFrames().toArray(),c=[],u=d.length +if(s.reversePreviewOrder&&(t="prev"===t?"next":"prev"),!l.attr("disabled")){for(r=0;u>r;r++)n=e(d[r]),n&&n.length&&n.find(".kv-file-zoom:visible").length&&c.push(d[r]) +for(u=c.length,r=0;u>r;r++)if(e(c[r]).attr("id")===i){o="prev"===t?r-1:r+1 +break}0>o||o>=u||!c[o]||(a=e(c[o]),a.length&&s._setZoomContent(a,t),s._initZoomButtons(),s._raise("filezoom"+t,{previewId:i,modal:s.$modal}))}},_initZoomButton:function(){var t=this +t.$preview.find(".kv-file-zoom").each(function(){var i=e(this) +t._handler(i,"click",function(){t._zoomPreview(i)})})},_inputFileCount:function(){return this.$element[0].files.length},_refreshPreview:function(){var t,i=this;(i._inputFileCount()||i.isAjaxUpload)&&i.showPreview&&i.isPreviewable&&(i.isAjaxUpload&&i.fileManager.count()>0?(t=e.extend(!0,{},i.getFileList()),i.fileManager.clear(),i._clearFileInput()):t=i.$element[0].files,t&&t.length&&(i.readFiles(t),i._setFileDropZoneTitle()))},_clearObjects:function(t){t.find("video audio").each(function(){this.pause(),e(this).remove()}),t.find("img object div").each(function(){e(this).remove()})},_clearFileInput:function(){var t,i,a,r=this,n=r.$element +r._inputFileCount()&&(t=n.closest("form"),i=e(document.createElement("form")),a=e(document.createElement("div")),n.before(a),t.length?t.after(i):a.after(i),i.append(n).trigger("reset"),a.before(n).remove(),i.remove())},_resetUpload:function(){var e=this +e.uploadStartTime=t.now(),e.uploadCache=[],e.$btnUpload.removeAttr("disabled"),e._setProgress(0),e._hideProgress(),e._resetErrors(!1),e._initAjax(),e.fileManager.clearImages(),e._resetCanvas(),e.overwriteInitial&&(e.initialPreview=[],e.initialPreviewConfig=[],e.initialPreviewThumbTags=[],e.previewCache.data={content:[],config:[],tags:[]})},_resetCanvas:function(){var e=this +e.imageCanvas&&e.imageCanvasContext&&e.imageCanvasContext.clearRect(0,0,e.imageCanvas.width,e.imageCanvas.height)},_hasInitialPreview:function(){var e=this +return!e.overwriteInitial&&e.previewCache.count(!0)},_resetPreview:function(){var i,a,r,n=this,o=n.showUploadedThumbs,s=!n.removeFromPreviewOnError,l=(o||s)&&n.isDuplicateError +n.previewCache.count(!0)?(i=n.previewCache.out(),l&&(r=t.createElement("").insertAfter(n.$container),n.getFrames().each(function(){var t=e(this);(o&&t.hasClass("file-preview-success")||s&&t.hasClass("file-preview-error"))&&r.append(t)})),n._setPreviewContent(i.content),n._setInitThumbAttr(),a=n.initialCaption?n.initialCaption:i.caption,n._setCaption(a),l&&(r.contents().appendTo(n.$preview),r.remove())):(n._clearPreview(),n._initCaption()),n.showPreview&&(n._initZoom(),n._initSortable()),n.isDuplicateError=!1},_clearDefaultPreview:function(){var e=this +e.$preview.find(".file-default-preview").remove()},_validateDefaultPreview:function(){var e=this +e.showPreview&&!t.isEmpty(e.defaultPreviewContent)&&(e._setPreviewContent('
    '+e.defaultPreviewContent+"
    "),e.$container.removeClass("file-input-new"),e._initClickable())},_resetPreviewThumbs:function(e){var t,i=this +return e?(i._clearPreview(),void i.clearFileStack()):void(i._hasInitialPreview()?(t=i.previewCache.out(),i._setPreviewContent(t.content),i._setInitThumbAttr(),i._setCaption(t.caption),i._initPreviewActions()):i._clearPreview())},_getLayoutTemplate:function(e){var i=this,a=i.layoutTemplates[e] +return t.isEmpty(i.customLayoutTags)?a:t.replaceTags(a,i.customLayoutTags)},_getPreviewTemplate:function(e){var i=this,a=i.previewTemplates,r=a[e]||a.other +return t.isEmpty(i.customPreviewTags)?r:t.replaceTags(r,i.customPreviewTags)},_getOutData:function(e,t,i,a){var r=this +return t=t||{},i=i||{},a=a||r.fileManager.list(),{formdata:e,files:a,filenames:r.filenames,filescount:r.getFilesCount(),extra:r._getExtraData(),response:i,reader:r.reader,jqXHR:t}},_getMsgSelected:function(e,t){var i=this,a=1===e?i.fileSingle:i.filePlural +return e>0?i.msgSelected.replace("{n}",e).replace("{files}",a):t?i.msgProcessing:i.msgNoFilesSelected},_getFrame:function(e,i){var a=this,r=t.getFrameElement(a.$preview,e) +return!a.showPreview||i||r.length||a._log(t.logMessages.invalidThumb,{id:e}),r},_getZoom:function(e,i){var a=this,r=t.getZoomElement(a.$preview,e,i) +return a.showPreview&&!r.length&&a._log(t.logMessages.invalidThumb,{id:e}),r},_getThumbs:function(e){return e=e||"",this.getFrames(":not(.file-preview-initial)"+e)},_getThumbId:function(e){var t=this +return t.previewInitId+"-"+e},_getExtraData:function(e,t){var i=this,a=i.uploadExtraData +return"function"==typeof i.uploadExtraData&&(a=i.uploadExtraData(e,t)),a},_initXhr:function(e,i){var a=this,r=a.fileManager,n=function(e){var n=0,o=e.total,s=e.loaded||e.position,l=r.getUploadStats(i,s,o) +e.lengthComputable&&!a.enableResumableUpload&&(n=t.round(s/o*100)),i?a._setFileUploadStats(i,n,l):a._setProgress(n,null,null,a._getStats(l)),a._raise("fileajaxprogress",[l])} +return e.upload&&(a.progressDelay&&(n=t.debounce(n,a.progressDelay)),e.upload.addEventListener("progress",n,!1)),e},_initAjaxSettings:function(){var t=this +t._ajaxSettings=e.extend(!0,{},t.ajaxSettings),t._ajaxDeleteSettings=e.extend(!0,{},t.ajaxDeleteSettings)},_mergeAjaxCallback:function(e,t,i){var a,r=this,n=r._ajaxSettings,o=r.mergeAjaxCallbacks +"delete"===i&&(n=r._ajaxDeleteSettings,o=r.mergeAjaxDeleteCallbacks),a=n[e],o&&"function"==typeof a?"before"===o?n[e]=function(){a.apply(this,arguments),t.apply(this,arguments)}:n[e]=function(){t.apply(this,arguments),a.apply(this,arguments)}:n[e]=t},_ajaxSubmit:function(t,i,a,r,n,o,s,l){var d,c,u,p,f=this +f._raise("filepreajax",[n,o,s])&&(n.append("initialPreview",JSON.stringify(f.initialPreview)),n.append("initialPreviewConfig",JSON.stringify(f.initialPreviewConfig)),n.append("initialPreviewThumbTags",JSON.stringify(f.initialPreviewThumbTags)),f._initAjaxSettings(),f._mergeAjaxCallback("beforeSend",t),f._mergeAjaxCallback("success",i),f._mergeAjaxCallback("complete",a),f._mergeAjaxCallback("error",r),l=l||f.uploadUrlThumb||f.uploadUrl,"function"==typeof l&&(l=l()),u=f._getExtraData(o,s)||{},"object"==typeof u&&e.each(u,function(e,t){n.append(e,t)}),c={xhr:function(){var t=e.ajaxSettings.xhr() +return f._initXhr(t,o)},url:f._encodeURI(l),type:"POST",dataType:"json",data:n,cache:!1,processData:!1,contentType:!1},d=e.extend(!0,{},c,f._ajaxSettings),p=f.taskManager.addTask(o+"-"+s,function(){var t,i,a=this.self +t=a.ajaxQueue.shift(),i=e.ajax(t),a.ajaxRequests.push(i)}),f.ajaxQueue.push(d),p.runWithContext({self:f}))},_mergeArray:function(e,i){var a=this,r=t.cleanArray(a[e]),n=t.cleanArray(i) +a[e]=r.concat(n)},_initUploadSuccess:function(i,a,r){var n,o,s,l,d,c,u,p,f,g=this +return!g.showPreview||"object"!=typeof i||e.isEmptyObject(i)?void g._resetCaption():(void 0!==i.initialPreview&&i.initialPreview.length>0&&(g.hasInitData=!0,d=i.initialPreview||[],c=i.initialPreviewConfig||[],u=i.initialPreviewThumbTags||[],n=void 0===i.append||i.append,d.length>0&&!t.isArray(d)&&(d=d.split(g.initialPreviewDelimiter)),d.length&&(g._mergeArray("initialPreview",d),g._mergeArray("initialPreviewConfig",c),g._mergeArray("initialPreviewThumbTags",u)),void 0!==a?r?(p=a.attr("id"),f=g._getUploadCacheIndex(p),null!==f&&(g.uploadCache[f]={id:p,content:d[0],config:c[0]||[],tags:u[0]||[],append:n})):(s=g.previewCache.add(d[0],c[0],u[0],n),o=g.previewCache.get(s,!1),l=t.createElement(o).hide().appendTo(a),a.fadeOut("slow",function(){var e=l.find("> .file-preview-frame") +e&&e.length&&e.insertBefore(a).fadeIn("slow").css("display:inline-block"),g._initPreviewActions(),g._clearFileInput(),a.remove(),l.remove(),g._initSortable()})):(g.previewCache.set(d,c,u,n),g._initPreview(),g._initPreviewActions())),void g._resetCaption())},_getUploadCacheIndex:function(e){var t,i,a=this,r=a.uploadCache.length +for(t=0;r>t;t++)if(i=a.uploadCache[t],i.id===e)return t +return null},_initSuccessThumbs:function(){var i=this +i.showPreview&&setTimeout(function(){i._getThumbs(t.FRAMES+".file-preview-success").each(function(){var a=e(this),r=a.find(".kv-file-remove") +r.removeAttr("disabled"),i._handler(r,"click",function(){var e=a.attr("id"),r=i._raise("filesuccessremove",[e,a.attr("data-fileindex")]) +t.cleanMemory(a),r!==!1&&(i.$caption.attr("title",""),a.fadeOut("slow",function(){i.fileManager +a.remove(),i.getFrames().length||i.reset()}))})})},i.processDelay)},_updateInitialPreview:function(){var t=this,i=t.uploadCache +t.showPreview&&(e.each(i,function(e,i){t.previewCache.add(i.content,i.config,i.tags,i.append)}),t.hasInitData&&(t._initPreview(),t._initPreviewActions()))},_getThumbFileId:function(e){var t=this +return t.showPreview&&void 0!==e?e.attr("data-fileid"):null},_getThumbFile:function(e){var t=this,i=t._getThumbFileId(e) +return i?t.fileManager.getFile(i):null},_uploadSingle:function(i,a,r){var n,o,s,l,d,c,u,p,f,g,m,h,v,w=this,b=w.fileManager,_=b.count(),C=new FormData,y=w._getThumbId(a),x=_>0||!e.isEmptyObject(w.uploadExtraData),T=w.ajaxOperations.uploadThumb,P=b.getFile(a),F={id:y,index:i,fileId:a},k=w.fileManager.getFileName(a,!0) +w.enableResumableUpload||(w.showPreview&&(o=b.getThumb(a),u=o.find(".file-thumb-progress"),l=o.find(".kv-file-upload"),d=o.find(".kv-file-remove"),u.show()),0===_||!x||w.showPreview&&l&&l.hasClass("disabled")||w._abort(F)||(v=function(){c?b.errors.push(a):b.removeFile(a),b.setProcessed(a),b.isProcessed()&&(w.fileBatchCompleted=!0,s())},s=function(){var e +w.fileBatchCompleted&&setTimeout(function(){var i=0===b.count(),a=b.errors.length +w._updateInitialPreview(),w.unlock(i),i&&w._clearFileInput(),e=w.$preview.find(".file-preview-initial"),w.uploadAsync&&e.length&&(t.addCss(e,t.SORT_CSS),w._initSortable()),w._raise("filebatchuploadcomplete",[b.stack,w._getExtraData()]),w.retryErrorUploads&&0!==a||b.clear(),w._setProgress(101),w.ajaxAborted=!1},w.processDelay)},p=function(s){n=w._getOutData(C,s),b.initStats(a),w.fileBatchCompleted=!1,r||(w.ajaxAborted=!1),w.showPreview&&(o.hasClass("file-preview-success")||(w._setThumbStatus(o,"Loading"),t.addCss(o,"file-uploading")),l.attr("disabled",!0),d.attr("disabled",!0)),r||w.lock(),-1!==b.errors.indexOf(a)&&delete b.errors[a],w._raise("filepreupload",[n,y,i,w._getThumbFileId(o)]),e.extend(!0,F,n),w._abort(F)&&(s.abort(),r||(w._setThumbStatus(o,"New"),o.removeClass("file-uploading"),l.removeAttr("disabled"),d.removeAttr("disabled")),w._setProgressCancelled())},g=function(s,d,p){var g=w.showPreview&&o.attr("id")?o.attr("id"):y +n=w._getOutData(C,p,s),e.extend(!0,F,n),setTimeout(function(){t.isEmpty(s)||t.isEmpty(s.error)?(w.showPreview&&(w._setThumbStatus(o,"Success"),l.hide(),w._initUploadSuccess(s,o,r),w._setProgress(101,u)),w._raise("fileuploaded",[n,g,i,w._getThumbFileId(o)]),r?v():w.fileManager.remove(o)):(c=!0,f=w._parseError(T,p,w.msgUploadError,w.fileManager.getFileName(a)),w._showFileError(f,F),w._setPreviewError(o,!0),w.retryErrorUploads||l.hide(),r&&v(),w._setProgress(101,w._getFrame(g).find(".file-thumb-progress"),w.msgUploadError))},w.processDelay)},m=function(){w.showPreview&&(l.removeAttr("disabled"),d.removeAttr("disabled"),o.removeClass("file-uploading")),r?s():(w.unlock(!1),w._clearFileInput()),w._initSuccessThumbs()},h=function(t,i,n){f=w._parseError(T,t,n,w.fileManager.getFileName(a)),c=!0,setTimeout(function(){var i +r&&v(),w.fileManager.setProgress(a,100),w._setPreviewError(o,!0),w.retryErrorUploads||l.hide(),e.extend(!0,F,w._getOutData(C,t)),w._setProgress(101,w.$progress,w.msgAjaxProgressError.replace("{operation}",T)),i=w.showPreview&&o?o.find(".file-thumb-progress"):"",w._setProgress(101,i,w.msgUploadError),w._showFileError(f,F)},w.processDelay)},w._setFileData(C,P.file,k,a),w._setUploadData(C,{fileId:a}),w._ajaxSubmit(p,g,m,h,C,a,i)))},_setFileData:function(e,t,i,a){var r=this,n=r.preProcessUpload +n&&"function"==typeof n?e.append(r.uploadFileAttr,n(a,t)):e.append(r.uploadFileAttr,t,i)},_checkBatchPreupload:function(t,i){var a=this,r=a._raise("filebatchpreupload",[t]) +return r?!0:(a._abort(t),i&&i.abort(),a._getThumbs().each(function(){var t=e(this),i=t.find(".kv-file-upload"),r=t.find(".kv-file-remove") +t.hasClass("file-preview-loading")&&(a._setThumbStatus(t,"New"),t.removeClass("file-uploading")),i.removeAttr("disabled"),r.removeAttr("disabled")}),a._setProgressCancelled(),!1)},_uploadBatch:function(){var i,a,r,n,o,s,l=this,d=l.fileManager,c=d.total(),u={},p=c>0||!e.isEmptyObject(l.uploadExtraData),f=new FormData,g=l.ajaxOperations.uploadBatch +if(0!==c&&p&&!l._abort(u)){s=function(){l.fileManager.clear(),l._clearFileInput()},i=function(i){l.lock(),d.initStats() +var a=l._getOutData(f,i) +l.ajaxAborted=!1,l.showPreview&&l._getThumbs().each(function(){var i=e(this),a=i.find(".kv-file-upload"),r=i.find(".kv-file-remove") +i.hasClass("file-preview-success")||(l._setThumbStatus(i,"Loading"),t.addCss(i,"file-uploading")),a.attr("disabled",!0),r.attr("disabled",!0)}),l._checkBatchPreupload(a,i)},a=function(i,a,r){var n=l._getOutData(f,r,i),d=0,c=l._getThumbs(":not(.file-preview-success)"),u=t.isEmpty(i)||t.isEmpty(i.errorkeys)?[]:i.errorkeys +t.isEmpty(i)||t.isEmpty(i.error)?(l._raise("filebatchuploadsuccess",[n]),s(),l.showPreview?(c.each(function(){var t=e(this) +l._setThumbStatus(t,"Success"),t.removeClass("file-uploading"),t.find(".kv-file-upload").hide().removeAttr("disabled")}),l._initUploadSuccess(i)):l.reset(),l._setProgress(101)):(l.showPreview&&(c.each(function(){var t=e(this) +t.removeClass("file-uploading"),t.find(".kv-file-upload").removeAttr("disabled"),t.find(".kv-file-remove").removeAttr("disabled"),0===u.length||-1!==e.inArray(d,u)?(l._setPreviewError(t,!0),l.retryErrorUploads||(t.find(".kv-file-upload").hide(),l.fileManager.remove(t))):(t.find(".kv-file-upload").hide(),l._setThumbStatus(t,"Success"),l.fileManager.remove(t)),(!t.hasClass("file-preview-error")||l.retryErrorUploads)&&d++}),l._initUploadSuccess(i)),o=l._parseError(g,r,l.msgUploadError),l._showFileError(o,n,"filebatchuploaderror"),l._setProgress(101,l.$progress,l.msgUploadError))},n=function(){l.unlock(),l._initSuccessThumbs(),l._clearFileInput(),l._raise("filebatchuploadcomplete",[l.fileManager.stack,l._getExtraData()])},r=function(t,i,a){var r=l._getOutData(f,t) +o=l._parseError(g,t,a),l._showFileError(o,r,"filebatchuploaderror"),l.uploadFileCount=c-1,l.showPreview&&(l._getThumbs().each(function(){var t=e(this) +t.removeClass("file-uploading"),l._getThumbFile(t)&&l._setPreviewError(t)}),l._getThumbs().removeClass("file-uploading"),l._getThumbs(" .kv-file-upload").removeAttr("disabled"),l._getThumbs(" .kv-file-delete").removeAttr("disabled"),l._setProgress(101,l.$progress,l.msgAjaxProgressError.replace("{operation}",g)))} +var m=0 +e.each(l.fileManager.stack,function(e,i){t.isEmpty(i.file)||l._setFileData(f,i.file,i.nameFmt||"untitled_"+m,e),m++}),l._ajaxSubmit(i,a,n,r,f)}},_uploadExtraOnly:function(){var e,i,a,r,n,o=this,s={},l=new FormData,d=o.ajaxOperations.uploadExtra +e=function(e){o.lock() +var t=o._getOutData(l,e) +o._setProgress(50),s.data=t,s.xhr=e,o._checkBatchPreupload(t,e)},i=function(e,i,a){var r=o._getOutData(l,a,e) +t.isEmpty(e)||t.isEmpty(e.error)?(o._raise("filebatchuploadsuccess",[r]),o._clearFileInput(),o._initUploadSuccess(e),o._setProgress(101)):(n=o._parseError(d,a,o.msgUploadError),o._showFileError(n,r,"filebatchuploaderror"))},a=function(){o.unlock(),o._clearFileInput(),o._raise("filebatchuploadcomplete",[o.fileManager.stack,o._getExtraData()])},r=function(e,t,i){var a=o._getOutData(l,e) +n=o._parseError(d,e,i),s.data=a,o._showFileError(n,a,"filebatchuploaderror"),o._setProgress(101,o.$progress,o.msgAjaxProgressError.replace("{operation}",d))},o._ajaxSubmit(e,i,a,r,l)},_deleteFileIndex:function(i){var a=this,r=i.attr("data-fileindex"),n=a.reversePreviewOrder +r.substring(0,5)===t.INIT_FLAG&&(r=parseInt(r.replace(t.INIT_FLAG,"")),a.initialPreview=t.spliceArray(a.initialPreview,r,n),a.initialPreviewConfig=t.spliceArray(a.initialPreviewConfig,r,n),a.initialPreviewThumbTags=t.spliceArray(a.initialPreviewThumbTags,r,n),a.getFrames().each(function(){var i=e(this),a=i.attr("data-fileindex") +a.substring(0,5)===t.INIT_FLAG&&(a=parseInt(a.replace(t.INIT_FLAG,"")),a>r&&(a--,i.attr("data-fileindex",t.INIT_FLAG+a)))}))},_resetCaption:function(){var e=this +setTimeout(function(){var t,i,a,r="",n=e.previewCache.count(!0),o=e.fileManager.count(),s=":not(.file-preview-success):not(.file-preview-error)",l=e.showPreview&&e.getFrames(s).length +0!==o||0!==n||l?(t=n+o,t>1?r=e._getMsgSelected(t):0===o?(a=e.initialPreviewConfig[0],r="",a&&(r=a.caption||a.filename||""),r||(r=e._getMsgSelected(t))):(i=e.fileManager.getFirstFile(),r=i?i.nameFmt:"_"),e._setCaption(r)):e.reset()},e.processDelay)},_initFileActions:function(){var i=this +i.showPreview&&(i._initZoomButton(),i.getFrames(" .kv-file-remove").each(function(){var a,r,n=e(this),o=n.closest(t.FRAMES),s=o.attr("id"),l=o.attr("data-fileindex") +i.fileManager +i._handler(n,"click",function(){return r=i._raise("filepreremove",[s,l]),r!==!1&&i._validateMinCount()?(a=o.hasClass("file-preview-error"),t.cleanMemory(o),void o.fadeOut("slow",function(){i.fileManager.remove(o),i._clearObjects(o),o.remove(),s&&a&&i.$errorContainer.find('li[data-thumb-id="'+s+'"]').fadeOut("fast",function(){e(this).remove(),i._errorsExist()||i._resetErrors()}),i._clearFileInput(),i._resetCaption(),i._raise("fileremoved",[s,l])})):!1})}),i.getFrames(" .kv-file-upload").each(function(){var a=e(this) +i._handler(a,"click",function(){var e=a.closest(t.FRAMES),r=i._getThumbFileId(e) +i._hideProgress(),(!e.hasClass("file-preview-error")||i.retryErrorUploads)&&i._uploadSingle(i.fileManager.getIndex(r),r,!1)})}))},_initPreviewActions:function(){var i=this,a=i.$preview,r=i.deleteExtraData||{},n=t.FRAMES+" .kv-file-remove",o=i.fileActionSettings,s=o.removeClass,l=o.removeErrorClass,d=function(){var e=i.isAjaxUpload?i.previewCache.count(!0):i._inputFileCount() +i.getFrames().length||e?i._resetCaption():(i._setCaption(""),i.reset(),i.initialCaption="")} +i._initZoomButton(),a.find(n).each(function(){var a,n,o,c,u=e(this),p=u.data("url")||i.deleteUrl,f=u.data("key"),g=i.ajaxOperations.deleteThumb +if(!t.isEmpty(p)&&void 0!==f){"function"==typeof p&&(p=p()) +var m,h,v,w,b,_=u.closest(t.FRAMES),C=i.previewCache.data,y=_.attr("data-fileindex") +y=parseInt(y.replace(t.INIT_FLAG,"")),v=t.isEmpty(C.config)&&t.isEmpty(C.config[y])?null:C.config[y],b=t.isEmpty(v)||t.isEmpty(v.extra)?r:v.extra,w=v&&(v.filename||v.caption)||"","function"==typeof b&&(b=b()),h={id:u.attr("id"),key:f,extra:b},n=function(e){i.ajaxAborted=!1,i._raise("filepredelete",[f,e,b]),i._abort()?e.abort():(u.removeClass(l),t.addCss(_,"file-uploading"),t.addCss(u,"disabled "+s))},o=function(e,r,n){var o,c +return t.isEmpty(e)||t.isEmpty(e.error)?(_.removeClass("file-uploading").addClass("file-deleted"),void _.fadeOut("slow",function(){y=parseInt(_.attr("data-fileindex").replace(t.INIT_FLAG,"")),i.previewCache.unset(y),i._deleteFileIndex(_),o=i.previewCache.count(!0),c=o>0?i._getMsgSelected(o):"",i._setCaption(c),i._raise("filedeleted",[f,n,b]),i._clearObjects(_),_.remove(),d()})):(h.jqXHR=n,h.response=e,a=i._parseError(g,n,i.msgDeleteError,w),i._showFileError(a,h,"filedeleteerror"),_.removeClass("file-uploading"),u.removeClass("disabled "+s).addClass(l),void d())},c=function(e,t,a){var r=i._parseError(g,e,a,w) +h.jqXHR=e,h.response={},i._showFileError(r,h,"filedeleteerror"),_.removeClass("file-uploading"),u.removeClass("disabled "+s).addClass(l),d()},i._initAjaxSettings(),i._mergeAjaxCallback("beforeSend",n,"delete"),i._mergeAjaxCallback("success",o,"delete"),i._mergeAjaxCallback("error",c,"delete"),m=e.extend(!0,{},{url:i._encodeURI(p),type:"POST",dataType:"json",data:e.extend(!0,{},{key:f},b)},i._ajaxDeleteSettings),i._handler(u,"click",function(){return i._validateMinCount()?(i.ajaxAborted=!1,i._raise("filebeforedelete",[f,b]),void(i.ajaxAborted instanceof Promise?i.ajaxAborted.then(function(t){t||e.ajax(m)}):i.ajaxAborted||e.ajax(m))):!1})}})},_hideFileIcon:function(){var e=this +e.overwriteInitial&&e.$captionContainer.removeClass("icon-visible")},_showFileIcon:function(){var e=this +t.addCss(e.$captionContainer,"icon-visible")},_getSize:function(t,i){var a,r,n=this,o=parseFloat(t),s=n.fileSizeGetter +return e.isNumeric(t)&&e.isNumeric(o)?("function"==typeof s?r=s(o):0===o?r="0.00 B":(i||(i=n.sizeUnits),a=Math.floor(Math.log(o)/Math.log(n.bytesToKB)),r=(o/Math.pow(n.bytesToKB,a)).toFixed(2)+" "+i[a]),n._getLayoutTemplate("size").replace("{sizeText}",r)):""},_getFileType:function(e){var t=this +return t.mimeTypeAliases[e]||e},_generatePreviewTemplate:function(i,a,r,n,o,s,l,d,c,u,p,f,g,m){var h,v,w,b=this,_=b.slug(r),C="",y="",x=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,T=_,P=_,F="type-default",k=u||b._renderFileFooter(i,_,d,"auto",l),E=b.preferIconicPreview,S=b.preferIconicZoomPreview,I=E?"other":i +return v=400>x?b.previewSettingsSmall[I]||b.defaults.previewSettingsSmall[I]:b.previewSettings[I]||b.defaults.previewSettings[I],v&&e.each(v,function(e,t){y+=e+":"+t+";"}),w=function(a,l,d,u,m){var h,v=d?"zoom-"+o:o,w=b._getPreviewTemplate(a),C=(c||"")+" "+u +return b.frameClass&&(C=b.frameClass+" "+C),d&&(C=C.replace(" "+t.SORT_CSS,"")),w=b._parseFilePreviewIcon(w,r),"object"!==i||n||e.each(b.defaults.fileTypeSettings,function(e,t){"object"!==e&&"other"!==e&&t(r,n)&&(F="type-"+e)}),t.isEmpty(g)||(void 0!==g.title&&null!==g.title&&(T=g.title),void 0!==g.alt&&null!==g.alt&&(T=g.alt)),h={previewId:v,caption:_,title:T,alt:P,frameClass:C,type:b._getFileType(n),fileindex:p,fileid:s||"",typeCss:F,footer:k,data:d&&m?"{zoomData}":l,template:f||i,style:y?'style="'+y+'"':"",zoomData:m?encodeURIComponent(m):""},d&&(h.zoomCache="",h.zoomData="{zoomData}"),w.setTokens(h)},p=p||o.slice(o.lastIndexOf("-")+1),b.fileActionSettings.showZoom&&(C=w(S?"other":i,a,!0,"kv-zoom-thumb",m)),C="\n"+b._getLayoutTemplate("zoomCache").replace("{zoomContent}",C),"function"==typeof b.sanitizeZoomCache&&(C=b.sanitizeZoomCache(C)),h=w(E?"other":i,a,!1,"kv-preview-thumb",m),h.setTokens({zoomCache:C})},_addToPreview:function(e,i){var a,r=this +return i=t.cspBuffer.stash(i),a=r.reversePreviewOrder?e.prepend(i):e.append(i),t.cspBuffer.apply(e),a},_previewDefault:function(e,i){var a=this,r=a.$preview +if(a.showPreview){var n,o=t.getFileName(e),s=e?e.type:"",l=e.size||0,d=a._getFileName(e,""),c=i===!0&&!a.isAjaxUpload,u=t.createObjectURL(e),p=a.fileManager.getId(e),f=a._getThumbId(p) +a._clearDefaultPreview(),n=a._generatePreviewTemplate("other",u,o,s,f,p,c,l),a._addToPreview(r,n),a._setThumbAttr(f,d,l),i===!0&&a.isAjaxUpload&&a._setThumbStatus(a._getFrame(f),"Error")}},_previewFile:function(e,i,a,r,n){if(this.showPreview){var o,s=this,l=t.getFileName(i),d=n.type,c=n.name,u=s._parseFileType(d,l),p=s.$preview,f=i.size||0,g="image"===u?a.target.result:r,m=s.fileManager,h=m.getId(i),v=s._getThumbId(h) +o=s._generatePreviewTemplate(u,g,l,d,v,h,!1,f),s._clearDefaultPreview(),s._addToPreview(p,o) +var w=s._getFrame(v) +s._validateImageOrientation(w.find("img"),i,v,h,c,d,f,g),s._setThumbAttr(v,c,f),s._initSortable()}},_setThumbAttr:function(e,t,i,a){var r=this,n=r._getFrame(e) +n.length&&(i=i&&i>0?r._getSize(i):"",n.data({caption:t,size:i,description:a||""}))},_setInitThumbAttr:function(){var e,i,a,r,n,o=this,s=o.previewCache.data,l=o.previewCache.count(!0) +if(0!==l)for(var d=0;l>d;d++)e=s.config[d],n=o.previewInitId+"-"+t.INIT_FLAG+d,i=t.ifSet("caption",e,t.ifSet("filename",e)),a=t.ifSet("size",e),r=t.ifSet("description",e),o._setThumbAttr(n,i,a,r)},_slugDefault:function(e){return t.isEmpty(e,!0)?"":(e+"").replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g,"_")},_updateFileDetails:function(e){var i,a,r,n,o,s=this,l=s.$element,d=t.isIE(9)&&t.findFileName(l.val())||l[0].files[0]&&l[0].files[0].name +!d&&s.fileManager.count()>0?(o=s.fileManager.getFirstFile(),i=o.nameFmt):i=d?s.slug(d):"_",a=s.isAjaxUpload?s.fileManager.count():e,n=s.previewCache.count(!0)+a,r=1===a?i:s._getMsgSelected(n,!s.isAjaxUpload&&!s.isError),s.isError?(s.$previewContainer.removeClass("file-thumb-loading"),s._initCapStatus(),s.$previewStatus.html(""),s.$captionContainer.removeClass("icon-visible")):s._showFileIcon(),s._setCaption(r,s.isError),s.$container.removeClass("file-input-new file-input-ajax-new"),s._raise("fileselect",[e,i]),s.previewCache.count(!0)&&s._initPreviewActions()},_setThumbStatus:function(e,i){var a=this +if(a.showPreview){var r="indicator"+i,n=r+"Title",o="file-preview-"+i.toLowerCase(),s=e.find(".file-upload-indicator"),l=a.fileActionSettings +e.removeClass("file-preview-success file-preview-error file-preview-paused file-preview-loading"),"Success"===i&&e.find(".file-drag-handle").remove(),t.setHtml(s,l[r]),s.attr("title",l[n]),e.addClass(o),"Error"!==i||a.retryErrorUploads||e.find(".kv-file-upload").attr("disabled",!0)}},_setProgressCancelled:function(){var e=this +e._setProgress(101,e.$progress,e.msgCancelled)},_setProgress:function(e,i,a,r){var n=this +if(i=i||n.$progress,i.length){var o,s=Math.min(e,100),l=n.progressUploadThreshold,d=100>=e?n.progressTemplate:n.progressCompleteTemplate,c=100>s?n.progressTemplate:a?n.paused?n.progressPauseTemplate:n.progressErrorTemplate:d +e>=100&&(r=""),t.isEmpty(c)||(o=l&&s>l&&100>=e?c.setTokens({percent:l,status:n.msgUploadThreshold}):c.setTokens({percent:s,status:e>100?n.msgUploadEnd:s+"%"}),r=r||"",o=o.setTokens({stats:r}),t.setHtml(i,o),a&&t.setHtml(i.find('[role="progressbar"]'),a))}},_hasFiles:function(){var e=this.$element[0] +return!!(e&&e.files&&e.files.length)},_setFileDropZoneTitle:function(){var e,i=this,a=i.$container.find(".file-drop-zone"),r=i.dropZoneTitle +i.isClickable&&(e=t.isEmpty(i.$element.attr("multiple"))?i.fileSingle:i.filePlural,r+=i.dropZoneClickTitle.replace("{files}",e)),a.find("."+i.dropZoneTitleClass).remove(),!i.showPreview||0===a.length||i.fileManager.count()>0||!i.dropZoneEnabled||i.previewCache.count()>0||!i.isAjaxUpload&&i._hasFiles()||(0===a.find(t.FRAMES).length&&t.isEmpty(i.defaultPreviewContent)&&a.prepend('
    '+r+"
    "),i.$container.removeClass("file-input-new"),t.addCss(i.$container,"file-input-ajax-new"))},_getStats:function(e){var i,a,r=this +return r.showUploadStats&&e&&e.bitrate?(a=r._getLayoutTemplate("stats"),i=e.elapsed&&e.bps?r.msgPendingTime.setTokens({time:t.getElapsed(Math.ceil(e.pendingBytes/e.bps))}):r.msgCalculatingTime,a.setTokens({uploadSpeed:e.bitrate,pendingTime:i})):""},_setResumableProgress:function(e,t,i){var a=this,r=a.resumableManager,n=i?r:a,o=i?i.find(".file-thumb-progress"):null +0===n.lastProgress&&(n.lastProgress=e),e0&&e._getFileCount(t-1)=g:g>=d,u||(l=p["msgImage"+o+i].setTokens({name:n,size:g}),p._showFileError(l,s),p._setPreviewError(r)))},_getExifObj:function(e){var i,a=this,r=t.logMessages.exifWarning +if("data:image/jpeg;base64,"!==e.slice(0,23)&&"data:image/jpg;base64,"!==e.slice(0,22))return void(i=null) +try{i=window.piexif?window.piexif.load(e):null}catch(n){i=null,r=n&&n.message||""}return i||a._log(t.logMessages.badExifParser,{details:r}),i},setImageOrientation:function(i,a,r,n){var o,s,l,d=this,c=!i||!i.length,u=!a||!a.length,p=!1,f=c&&n&&"image"===n.attr("data-template") +c&&u||(l="load.fileinputimageorient",f?(i=a,a=null,i.css(d.previewSettings.image),s=e(document.createElement("div")).appendTo(n.find(".kv-file-content")),o=e(document.createElement("span")).insertBefore(i),i.css("visibility","hidden").removeClass("file-zoom-detail").appendTo(s)):p=!i.is(":visible"),i.off(l).on(l,function(){p&&(d.$preview.removeClass("hide-content"),n.find(".kv-file-content").css("visibility","hidden")) +var e=i[0],l=a&&a.length?a[0]:null,c=e.offsetHeight,u=e.offsetWidth,g=t.getRotation(r) +if(p&&(n.find(".kv-file-content").css("visibility","visible"),d.$preview.addClass("hide-content")),i.data("orientation",r),l&&a.data("orientation",r),5>r)return t.setTransform(e,g),void t.setTransform(l,g) +var m=Math.atan(u/c),h=Math.sqrt(Math.pow(c,2)+Math.pow(u,2)),v=h?c/Math.cos(Math.PI/2+m)/h:1,w=" scale("+Math.abs(v)+")" +t.setTransform(e,g+w),t.setTransform(l,g+w),f&&(i.css("visibility","visible").insertAfter(o).addClass("file-zoom-detail"),o.remove(),s.remove())}))},_validateImageOrientation:function(i,a,r,n,o,s,l,d){var c,u,p=this,f=null,g=p.autoOrientImage +return p.canOrientImage?(i.css("image-orientation",g?"from-image":"none"),void p._validateImage(r,n,o,s,l,d,f)):(u=t.getZoomSelector(r," img"),f=g?p._getExifObj(d):null,(c=f?f["0th"][piexif.ImageIFD.Orientation]:null)?(p.setImageOrientation(i,e(u),c,p._getFrame(r)),p._raise("fileimageoriented",{$img:i,file:a}),void p._validateImage(r,n,o,s,l,d,f)):void p._validateImage(r,n,o,s,l,d,f))},_validateImage:function(e,t,i,a,r,n,o){var s,l,d,c=this,u=c.$preview,p=c._getFrame(e),f=p.attr("data-fileindex"),g=p.find("img") +i=i||"Untitled",g.one("load",function(){l=p.width(),d=u.width(),l>d&&g.css("width","100%"),s={ind:f,id:e,fileId:t},c._checkDimensions(f,"Small",g,p,i,"Width",s),c._checkDimensions(f,"Small",g,p,i,"Height",s),c.resizeImage||(c._checkDimensions(f,"Large",g,p,i,"Width",s),c._checkDimensions(f,"Large",g,p,i,"Height",s)),c._raise("fileimageloaded",[e]),c.fileManager.addImage(t,{ind:f,img:g,thumb:p,pid:e,typ:a,siz:r,validated:!1,imgData:n,exifObj:o}),p.data("exif",o),c._validateAllImages()}).one("error",function(){c._raise("fileimageloaderror",[e])})},_validateAllImages:function(){var t,i=this,a={val:0},r=i.fileManager.getImageCount(),n=i.resizeIfSizeMoreThan +r===i.fileManager.totalImages&&(i._raise("fileimagesloaded"),i.resizeImage&&e.each(i.fileManager.loadedImages,function(e,o){o.validated||(t=o.siz,t&&t>n*i.bytesToKB&&i._getResizedImage(e,o,a,r),o.validated=!0)}))},_getResizedImage:function(i,a,r,n){var o,s,l,d,c,u,p,f,g,m,h=this,v=e(a.img)[0],w=v.naturalWidth,b=v.naturalHeight,_=1,C=h.maxImageWidth||w,y=h.maxImageHeight||b,x=!(!w||!b),T=h.imageCanvas,P=h.imageCanvasContext,F=a.typ,k=a.pid,E=a.ind,S=a.thumb,I=a.exifObj +if(c=function(e,t,i){h.isAjaxUpload?h._showFileError(e,t,i):h._showError(e,t,i),h._setPreviewError(S)},f=h.fileManager.getFile(i),g={id:k,index:E,fileId:i},m=[i,k,E],(!f||!x||C>=w&&y>=b)&&(x&&f&&h._raise("fileimageresized",m),r.val++,r.val===n&&h._raise("fileimagesresized"),!x))return void c(h.msgImageResizeError,g,"fileimageresizeerror") +F=F||h.resizeDefaultImageType,s=w>C,l=b>y,_="width"===h.resizePreference?s?C/w:l?y/b:1:l?y/b:s?C/w:1,h._resetCanvas(),w*=_,b*=_,T.width=w,T.height=b +try{P.drawImage(v,0,0,w,b),d=T.toDataURL(F,h.resizeQuality),I&&(p=window.piexif.dump(I),d=window.piexif.insert(p,d)),o=t.dataURI2Blob(d),h.fileManager.setFile(i,o),h._raise("fileimageresized",m),r.val++,r.val===n&&h._raise("fileimagesresized",[void 0,void 0]),o instanceof Blob||c(h.msgImageResizeError,g,"fileimageresizeerror")}catch(A){r.val++,r.val===n&&h._raise("fileimagesresized",[void 0,void 0]),u=h.msgImageResizeException.replace("{errors}",A.message),c(u,g,"fileimageresizeexception")}},_showProgress:function(){var e=this +e.$progress&&e.$progress.length&&e.$progress.show()},_hideProgress:function(){var e=this +e.$progress&&e.$progress.length&&e.$progress.hide()},_initBrowse:function(e){var i=this,a=i.$element +i.showBrowse?i.$btnFile=e.find(".btn-file").append(a):(a.appendTo(e).attr("tabindex",-1),t.addCss(a,"file-no-browse"))},_initClickable:function(){var i,a,r=this +r.isClickable&&(i=r.$dropZone,r.isAjaxUpload||(a=r.$preview.find(".file-default-preview"),a.length&&(i=a)),t.addCss(i,"clickable"),i.attr("tabindex",-1),r._handler(i,"click",function(t){var a=e(t.target) +r.$errorContainer.is(":visible")||a.parents(".file-preview-thumbnails").length&&!a.parents(".file-default-preview").length||(r.$element.data("zoneClicked",!0).trigger("click"),i.blur())}))},_initCaption:function(){var e=this,i=e.initialCaption||"" +return e.overwriteInitial||t.isEmpty(i)?(e.$caption.val(""),!1):(e._setCaption(i),!0)},_setCaption:function(i,a){var r,n,o,s,l,d,c=this +if(c.$caption.length){if(c.$captionContainer.removeClass("icon-visible"),a)r=e("
    "+c.msgValidationError+"
    ").text(),s=c.fileManager.count(),s?(d=c.fileManager.getFirstFile(),l=1===s&&d?d.nameFmt:c._getMsgSelected(s)):l=c._getMsgSelected(c.msgNo),n=t.isEmpty(i)?l:i,o=''+c.msgValidationErrorIcon+"" +else{if(t.isEmpty(i))return void c.$caption.attr("title","") +r=e("
    "+i+"
    ").text(),n=r,o=c._getLayoutTemplate("fileIcon")}c.$captionContainer.addClass("icon-visible"),c.$caption.attr("title",r).val(n),t.setHtml(c.$captionIcon,o)}},_createContainer:function(){var e=this,i={"class":"file-input file-input-new"+(e.rtl?" kv-rtl":"")},a=t.createElement(t.cspBuffer.stash(e._renderMain())) +return t.cspBuffer.apply(a),a.insertBefore(e.$element).attr(i),e._initBrowse(a),e.theme&&a.addClass("theme-"+e.theme),a},_refreshContainer:function(){var e=this,i=e.$container,a=e.$element +a.insertAfter(i),t.setHtml(i,e._renderMain()),e._initBrowse(i),e._validateDisabled()},_validateDisabled:function(){var e=this +e.$caption.attr({readonly:e.isDisabled})},_setTabIndex:function(e,t){var i=this,a=i.tabIndexConfig[e] +return t.setTokens({tabIndexConfig:void 0===a||null===a?"":'tabindex="'+a+'"'})},_renderMain:function(){var e=this,t=e.dropZoneEnabled?" file-drop-zone":"file-drop-disabled",i=e.showClose?e._getLayoutTemplate("close"):"",a=e.showPreview?e._getLayoutTemplate("preview").setTokens({"class":e.previewClass,dropClass:t}):"",r=e.isDisabled?e.captionClass+" file-caption-disabled":e.captionClass,n=e.captionTemplate.setTokens({"class":r+" kv-fileinput-caption"}) +return n=e._setTabIndex("caption",n),e.mainTemplate.setTokens({"class":e.mainClass+(!e.showBrowse&&e.showCaption?" no-browse":""),inputGroupClass:e.inputGroupClass,preview:a,close:i,caption:n,upload:e._renderButton("upload"),remove:e._renderButton("remove"),cancel:e._renderButton("cancel"),pause:e._renderButton("pause"),browse:e._renderButton("browse")})},_renderButton:function(e){var i=this,a=i._getLayoutTemplate("btnDefault"),r=i[e+"Class"],n=i[e+"Title"],o=i[e+"Icon"],s=i[e+"Label"],l=i.isDisabled?" disabled":"",d="button" +switch(e){case"remove":if(!i.showRemove)return"" +break +case"cancel":if(!i.showCancel)return"" +r+=" kv-hidden" +break +case"pause":if(!i.showPause)return"" +r+=" kv-hidden" +break +case"upload":if(!i.showUpload)return"" +i.isAjaxUpload&&!i.isDisabled?a=i._getLayoutTemplate("btnLink").replace("{href}",i.uploadUrl):d="submit" +break +case"browse":if(!i.showBrowse)return"" +a=i._getLayoutTemplate("btnBrowse") +break +default:return""}return a=i._setTabIndex(e,a),r+="browse"===e?" btn-file":" fileinput-"+e+" fileinput-"+e+"-button",t.isEmpty(s)||(s=' '+s+""),a.setTokens({type:d,css:r,title:n,status:l,icon:o,label:s})},_renderThumbProgress:function(){var e=this +return'
    '+e.progressInfoTemplate.setTokens({percent:101,status:e.msgUploadBegin,stats:""})+"
    "},_renderFileFooter:function(e,i,a,r,n){var o,s,l=this,d=l.fileActionSettings,c=d.showRemove,u=d.showDrag,p=d.showUpload,f=d.showZoom,g=l._getLayoutTemplate("footer"),m=l._getLayoutTemplate("indicator"),h=n?d.indicatorError:d.indicatorNew,v=n?d.indicatorErrorTitle:d.indicatorNewTitle,w=m.setTokens({indicator:h,indicatorTitle:v}) +return a=l._getSize(a),s={type:e,caption:i,size:a,width:r,progress:"",indicator:w},l.isAjaxUpload?(s.progress=l._renderThumbProgress(),s.actions=l._renderFileActions(s,p,!1,c,f,u,!1,!1,!1)):s.actions=l._renderFileActions(s,!1,!1,!1,f,u,!1,!1,!1),o=g.setTokens(s),o=t.replaceTags(o,l.previewThumbTags)},_renderFileActions:function(e,t,i,a,r,n,o,s,l,d,c,u){var p=this +if(!e.type&&d&&(e.type="image"),p.enableResumableUpload?t=!1:"function"==typeof t&&(t=t(e)),"function"==typeof i&&(i=i(e)),"function"==typeof a&&(a=a(e)),"function"==typeof r&&(r=r(e)),"function"==typeof n&&(n=n(e)),!(t||i||a||r||n))return"" +var f,g=s===!1?"":' data-url="'+s+'"',m="",h="",v=l===!1?"":' data-key="'+l+'"',w="",b="",_="",C=p._getLayoutTemplate("actions"),y=p.fileActionSettings,x=p.otherActionButtons.setTokens({dataKey:v,key:l}),T=o?y.removeClass+" disabled":y.removeClass +return a&&(w=p._getLayoutTemplate("actionDelete").setTokens({removeClass:T,removeIcon:y.removeIcon,removeTitle:y.removeTitle,dataUrl:g,dataKey:v,key:l})),t&&(b=p._getLayoutTemplate("actionUpload").setTokens({uploadClass:y.uploadClass,uploadIcon:y.uploadIcon,uploadTitle:y.uploadTitle})),i&&(_=p._getLayoutTemplate("actionDownload").setTokens({downloadClass:y.downloadClass,downloadIcon:y.downloadIcon,downloadTitle:y.downloadTitle,downloadUrl:c||p.initialPreviewDownloadUrl}),_=_.setTokens({filename:u,key:l})),r&&(m=p._getLayoutTemplate("actionZoom").setTokens({zoomClass:y.zoomClass,zoomIcon:y.zoomIcon,zoomTitle:y.zoomTitle})),n&&d&&(f="drag-handle-init "+y.dragClass,h=p._getLayoutTemplate("actionDrag").setTokens({dragClass:f,dragTitle:y.dragTitle,dragIcon:y.dragIcon})),C.setTokens({"delete":w,upload:b,download:_,zoom:m,drag:h,other:x})},_browse:function(e){var t=this +e&&e.isDefaultPrevented()||!t._raise("filebrowse")||(t.isError&&!t.isAjaxUpload&&t.clear(),t.focusCaptionOnBrowse&&t.$captionContainer.focus())},_change:function(i){var a=this +if(e(document.body).off("focusin.fileinput focusout.fileinput"),!a.changeTriggered){a._setLoading("show") +var r,n,o,s,l=a.$element,d=arguments.length>1,c=a.isAjaxUpload,u=d?arguments[1]:l[0].files,p=a.fileManager.count(),f=t.isEmpty(l.attr("multiple")),g=!c&&f?1:a.maxFileCount,m=a.maxTotalFileCount,h=m>0&&m>g,v=f&&p>0,w=function(t,i,r,n){var o=e.extend(!0,{},a._getOutData(null,{},{},u),{id:r,index:n}),s={id:r,index:n,file:i,files:u} +return a.isPersistentError=!0,a._setLoading("hide"),c?a._showFileError(t,o):a._showError(t,s)},b=function(e,t,i){var r=i?a.msgTotalFilesTooMany:a.msgFilesTooMany +r=r.replace("{m}",t).replace("{n}",e),a.isError=w(r,null,null,null),a.$captionContainer.removeClass("icon-visible"),a._setCaption("",!0),a.$container.removeClass("file-input-new file-input-ajax-new")} +if(a.reader=null,a._resetUpload(),a._hideFileIcon(),a.dropZoneEnabled&&a.$container.find(".file-drop-zone ."+a.dropZoneTitleClass).remove(),c||(u=i.target&&void 0===i.target.files?i.target.value?[{name:i.target.value.replace(/^.+\\/,"")}]:[]:i.target.files||{}),r=u,t.isEmpty(r)||0===r.length)return c||a.clear(),void a._raise("fileselectnone") +if(a._resetErrors(),s=r.length,o=c?a.fileManager.count()+s:s,n=a._getFileCount(o,h?!1:void 0),g>0&&n>g){if(!a.autoReplace||s>g)return void b(a.autoReplace&&s>g?s:n,g) +n>g&&a._resetPreviewThumbs(c)}else{if(h&&(n=a._getFileCount(o,!0),m>0&&n>m)){if(!a.autoReplace||s>g)return void b(a.autoReplace&&s>m?s:n,m,!0) +n>g&&a._resetPreviewThumbs(c)}!c||v?(a._resetPreviewThumbs(!1),v&&a.clearFileStack()):!c||0!==p||a.previewCache.count(!0)&&!a.overwriteInitial||a._resetPreviewThumbs(!0)}a.readFiles(r),a._setLoading("hide")}},_abort:function(t){var i,a=this +return a.ajaxAborted&&"object"==typeof a.ajaxAborted&&void 0!==a.ajaxAborted.message?(i=e.extend(!0,{},a._getOutData(null),t),i.abortData=a.ajaxAborted.data||{},i.abortMessage=a.ajaxAborted.message,a._setProgress(101,a.$progress,a.msgCancelled),a._showFileError(a.ajaxAborted.message,i,"filecustomerror"),a.cancel(),a.unlock(),!0):!!a.ajaxAborted},_resetFileStack:function(){var t=this,i=0 +t._getThumbs().each(function(){var a=e(this),r=a.attr("data-fileindex"),n=a.attr("id") +"-1"!==r&&-1!==r&&(t._getThumbFile(a)?a.attr({"data-fileindex":"-1"}):(a.attr({"data-fileindex":i}),i++),t._getZoom(n).attr({"data-fileindex":a.attr("data-fileindex")}))})},_isFileSelectionValid:function(e){var t=this +return e=e||0,t.required&&!t.getFilesCount()?(t.$errorContainer.html(""),t._showFileError(t.msgFileRequired),!1):t.minFileCount>0&&t._getFileCount(e)v,!o&&(a||r||n)},addToStack:function(e,t){this.fileManager.add(e,t)},clearFileStack:function(){var e=this +return e.fileManager.clear(),e._initResumableUpload(),e.enableResumableUpload?(null===e.showPause&&(e.showPause=!0),null===e.showCancel&&(e.showCancel=!1)):(e.showPause=!1,null===e.showCancel&&(e.showCancel=!0)),e.$element},getFileStack:function(){return this.fileManager.stack},getFileList:function(){return this.fileManager.list()},getFilesSize:function(){return this.fileManager.getTotalSize()},getFilesCount:function(e){var t=this,i=t.isAjaxUpload?t.fileManager.count():t._inputFileCount() +return e&&(i+=t.previewCache.count(!0)),t._getFileCount(i)},_initCapStatus:function(e){var t=this,i=t.$caption +i.removeClass("is-valid file-processing"),e&&("processing"===e?i.addClass("file-processing"):i.addClass("is-valid"))},_setLoading:function(e){var t=this +t.$previewStatus.html("hide"===e?"":t.msgProcessing),t.$container.removeClass("file-thumb-loading"),t._initCapStatus("hide"===e?"":"processing"),"hide"!==e&&(t.dropZoneEnabled&&t.$container.find(".file-drop-zone ."+t.dropZoneTitleClass).remove(),t.$container.addClass("file-thumb-loading"))},_initFileSelected:function(){var t=this,i=t.$element,a=e(document.body),r="focusin.fileinput focusout.fileinput" +a.length?a.off(r).on("focusout.fileinput",function(){t._setLoading("show")}).on("focusin.fileinput",function(){setTimeout(function(){i.val()||(t._setLoading("hide"),t._setFileDropZoneTitle()),a.off(r)},2500)}):t._setLoading("hide")},readFiles:function(i){this.reader=new FileReader +var a,r=this,n=r.reader,o=r.$previewContainer,s=r.$previewStatus,l=r.msgLoading,d=r.msgProgress,c=r.previewInitId,u=i.length,p=r.fileTypeSettings,f=r.allowedFileTypes,g=f?f.length:0,m=r.allowedFileExtensions,h=t.isEmpty(m)?"":m.join(", "),v=function(t,n,o,s,l){var d,c=e.extend(!0,{},r._getOutData(null,{},{},i),{id:o,index:s,fileId:l}),p={id:o,index:s,fileId:l,file:n,files:i} +r._previewDefault(n,!0),d=r._getFrame(o,!0),r._setLoading("hide"),r.isAjaxUpload?setTimeout(function(){a(s+1)},r.processDelay):(r.unlock(),u=0),r.removeFromPreviewOnError&&d.length?d.remove():(r._initFileActions(),d.find(".kv-file-upload").remove()),r.isPersistentError=!0,r.isError=r.isAjaxUpload?r._showFileError(t,c):r._showError(t,p),r._updateFileDetails(u)} +r.fileManager.clearImages(),e.each(i,function(e,t){var i=r.fileTypeSettings.image +i&&i(t.type)&&r.fileManager.totalImages++}),a=function(w){var b,_=r.$errorContainer,C=r.fileManager +if(w>=u)return r.unlock(),r.duplicateErrors.length&&(b="
  • "+r.duplicateErrors.join("
  • ")+"
  • ",0===_.find("ul").length?t.setHtml(_,r.errorCloseButton+"
      "+b+"
    "):_.find("ul").append(b),_.fadeIn(r.fadeDelay),r._handler(_.find(".kv-error-close"),"click",function(){_.fadeOut(r.fadeDelay)}),r.duplicateErrors=[]),r.isAjaxUpload?(r._raise("filebatchselected",[C.stack]),0!==C.count()||r.isError||r.reset()):r._raise("filebatchselected",[i]),o.removeClass("file-thumb-loading"),r._initCapStatus("valid"),void s.html("") +r.lock(!0) +var y,x,T,P,F,k,E,S,I,A,z,D,U=i[w],j=r._getFileId(U),$=c+"-"+j,M=p.image,B=r._getFileName(U,""),R=(U&&U.size||0)/r.bytesToKB,O="",L=t.createObjectURL(U),N=0,Z="",H=!1,W=0,K=function(){var e=!!C.loadedImages[j],t=d.setTokens({index:w+1,files:u,percent:50,name:B}) +setTimeout(function(){s.html(t),r._updateFileDetails(u),a(w+1)},r.processDelay),r._raise("fileloaded",[U,$,j,w,n])&&r.isAjaxUpload?e||C.add(U):e&&C.removeFile(j)} +if(U){if(S=C.getId(U),g>0)for(x=0;g>x;x++)k=f[x],E=r.msgFileTypes[k]||k,Z+=0===x?E:", "+E +if(B===!1)return void a(w+1) +if(0===B.length)return T=r.msgInvalidFileName.replace("{name}",t.htmlEncode(t.getFileName(U),"[unknown]")),void v(T,U,$,w,S) +if(t.isEmpty(m)||(O=RegExp("\\.("+m.join("|")+")$","i")),y=R.toFixed(2),r.isAjaxUpload&&C.exists(S)||r._getFrame($,!0).length){var q={id:$,index:w,fileId:S,file:U,files:i} +return T=r.msgDuplicateFile.setTokens({name:B,size:y}),void(r.isAjaxUpload?(r.duplicateErrors.push(T),r.isDuplicateError=!0,r._raise("fileduplicateerror",[U,S,B,y,$,w]),a(w+1),r._updateFileDetails(u)):(r._showError(T,q),r.unlock(),u=0,r._clearFileInput(),r.reset(),r._updateFileDetails(u)))}if(r.maxFileSize>0&&R>r.maxFileSize)return T=r.msgSizeTooLarge.setTokens({name:B,size:y,maxSize:r.maxFileSize}),void v(T,U,$,w,S) +if(null!==r.minFileSize&&R<=t.getNum(r.minFileSize))return T=r.msgSizeTooSmall.setTokens({name:B,size:y,minSize:r.minFileSize}),void v(T,U,$,w,S) +if(!t.isEmpty(f)&&t.isArray(f)){for(x=0;x0)for(t=0;n>t;t+=1)i.paused=!0,r[t].abort() +return i.showPreview&&i._getThumbs().each(function(){var t,a=e(this),r=i._getLayoutTemplate("stats"),n=a.find(".file-upload-indicator") +a.removeClass("file-uploading"),n.attr("title")===s.indicatorLoadingTitle&&(i._setThumbStatus(a,"Paused"),t=r.setTokens({pendingTime:i.msgPaused,uploadSpeed:""}),i.paused=!0,i._setProgress(o,a.find(".file-thumb-progress"),o+"%",t)),i._getThumbFile(a)||a.find(".kv-file-remove").removeClass("disabled").removeAttr("disabled")}),i._setProgress(101,i.$progress,i.msgPaused),i.$element},cancel:function(){var t,i=this,a=i.ajaxRequests,r=i.resumableManager,n=i.taskManager,o=r?n.getPool(r.id):void 0,s=a.length +if(i.enableResumableUpload&&o?(o.cancel().done(function(){i._setProgressCancelled()}),r.reset(),i._raise("fileuploadcancelled",[i.fileManager,r])):i._raise("fileuploadcancelled",[i.fileManager]),i._initAjax(),s>0)for(t=0;s>t;t+=1)i.cancelling=!0,a[t].abort() +return i._getThumbs().each(function(){var t=e(this),a=t.find(".file-thumb-progress") +t.removeClass("file-uploading"),i._setProgress(0,a),a.hide(),i._getThumbFile(t)||(t.find(".kv-file-upload").removeClass("disabled").removeAttr("disabled"),t.find(".kv-file-remove").removeClass("disabled").removeAttr("disabled")),i.unlock()}),setTimeout(function(){i._setProgressCancelled()},i.processDelay),i.$element},clear:function(){var i,a=this +if(a._raise("fileclear"))return a.$btnUpload.removeAttr("disabled"),a._getThumbs().find("video,audio,img").each(function(){t.cleanMemory(e(this))}),a._clearFileInput(),a._resetUpload(),a.clearFileStack(),a.isDuplicateError=!1,a.isPersistentError=!1,a._resetErrors(!0),a._hasInitialPreview()?(a._showFileIcon(),a._resetPreview(),a._initPreviewActions(),a.$container.removeClass("file-input-new")):(a._getThumbs().each(function(){a._clearObjects(e(this))}),a.isAjaxUpload&&(a.previewCache.data={}),a.$preview.html(""),i=!a.overwriteInitial&&a.initialCaption.length>0?a.initialCaption:"",a.$caption.attr("title","").val(i),t.addCss(a.$container,"file-input-new"),a._validateDefaultPreview()),0===a.$container.find(t.FRAMES).length&&(a._initCaption()||a.$captionContainer.removeClass("icon-visible")),a._hideFileIcon(),a.focusCaptionOnClear&&a.$captionContainer.focus(),a._setFileDropZoneTitle(),a._raise("filecleared"),a.$element},reset:function(){var e=this +if(e._raise("filereset"))return e.lastProgress=0,e._resetPreview(),e.$container.find(".fileinput-filename").text(""),t.addCss(e.$container,"file-input-new"),e.getFrames().length&&e.$container.removeClass("file-input-new"),e.clearFileStack(),e._setFileDropZoneTitle(),e.$element},disable:function(){var e=this,i=e.$container +return e.isDisabled=!0,e._raise("filedisabled"),e.$element.attr("disabled","disabled"),i.addClass("is-locked"),t.addCss(i.find(".btn-file"),"disabled"),i.find(".kv-fileinput-caption").addClass("file-caption-disabled"),i.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button").attr("disabled",!0),e._initDragDrop(),e.$element},enable:function(){var e=this,t=e.$container +return e.isDisabled=!1,e._raise("fileenabled"),e.$element.removeAttr("disabled"),t.removeClass("is-locked"),t.find(".kv-fileinput-caption").removeClass("file-caption-disabled"),t.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled"),t.find(".btn-file").removeClass("disabled"),e._initDragDrop(),e.$element},upload:function(){var i,a,r=this,n=r.fileManager,o=n.count(),s=!e.isEmptyObject(r._getExtraData()) +if(n.bpsLog=[],n.bps=0,r.isAjaxUpload&&!r.isDisabled&&r._isFileSelectionValid(o)){if(r.lastProgress=0,r._resetUpload(),0===o&&!s)return void r._showFileError(r.msgUploadEmpty) +if(r.cancelling=!1,r._showProgress(),r.lock(),0===o&&s)return r._setProgress(2),void r._uploadExtraOnly() +if(r.enableResumableUpload)return r.resume() +if(r.uploadAsync||r.enableResumableUpload){if(a=r._getOutData(null),!r._checkBatchPreupload(a))return +r.fileBatchCompleted=!1,r.uploadCache=[],e.each(r.getFileStack(),function(e){var t=r._getThumbId(e) +r.uploadCache.push({id:t,content:null,config:null,tags:null,append:!0})}),r.$preview.find(".file-preview-initial").removeClass(t.SORT_CSS),r._initSortable()}return r._setProgress(2),r.hasInitData=!1,r.uploadAsync?(i=0,void e.each(r.getFileStack(),function(e){r._uploadSingle(i,e,!0),i++})):(r._uploadBatch(),r.$element)}},destroy:function(){var t=this,i=t.$form,a=t.$container,r=t.$element,n=t.namespace +return e(document).off(n),e(window).off(n),i&&i.length&&i.off(n),t.isAjaxUpload&&t._clearFileInput(),t._cleanup(),t._initPreviewCache(),r.insertBefore(a).off(n).removeData(),a.off().remove(),r},refresh:function(i){var a=this,r=a.$element +return i="object"!=typeof i||t.isEmpty(i)?a.options:e.extend(!0,{},a.options,i),a._init(i,!0),a._listen(),r},zoom:function(e){var t=this,i=t._getFrame(e) +t._showModal(i)},getExif:function(e){var t=this,i=t._getFrame(e) +return i&&i.data("exif")||null},getFrames:function(i){var a,r=this +return i=i||"",a=r.$preview.find(t.FRAMES+i),r.reversePreviewOrder&&(a=e(a.get().reverse())),a},getPreview:function(){var e=this +return{content:e.initialPreview,config:e.initialPreviewConfig,tags:e.initialPreviewThumbTags}}},e.fn.fileinput=function(a){if(t.hasFileAPISupport()||t.isIE(9)){var r=Array.apply(null,arguments),n=[] +switch(r.shift(),this.each(function(){var o,s=e(this),l=s.data("fileinput"),d="object"==typeof a&&a,c=d.theme||s.data("theme"),u={},p={},f=d.language||s.data("language")||e.fn.fileinput.defaults.language||"en" +l||(c&&(p=e.fn.fileinputThemes[c]||{}),"en"===f||t.isEmpty(e.fn.fileinputLocales[f])||(u=e.fn.fileinputLocales[f]||{}),o=e.extend(!0,{},e.fn.fileinput.defaults,p,e.fn.fileinputLocales.en,u,d,s.data()),l=new i(this,o),s.data("fileinput",l)),"string"==typeof a&&n.push(l[a].apply(l,r))}),n.length){case 0:return this +case 1:return n[0] +default:return n}}} +var a='class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}',r="btn btn-sm btn-kv "+t.defaultButtonCss(),n="btn "+t.defaultButtonCss(!0) +e.fn.fileinput.defaults={language:"zh",bytesToKB:1024,showCaption:!0,showBrowse:!0,showPreview:!0,showRemove:!0,showUpload:!0,showUploadStats:!0,showCancel:null,showPause:null,showClose:!0,showUploadedThumbs:!0,showConsoleLogs:!1,browseOnZoneClick:!1,autoReplace:!1,showDescriptionClose:!0,autoOrientImage:function(){var e=window.navigator.userAgent,t=!!e.match(/WebKit/i),i=!!e.match(/iP(od|ad|hone)/i),a=i&&t&&!e.match(/CriOS/i) +return!a},autoOrientImageInitial:!0,required:!1,rtl:!1,hideThumbnailContent:!1,encodeUrl:!0,focusCaptionOnBrowse:!0,focusCaptionOnClear:!0,generateFileId:null,previewClass:"",captionClass:"",frameClass:"krajee-default",mainClass:"",inputGroupClass:"",mainTemplate:null,fileSizeGetter:null,initialCaption:"",initialPreview:[],initialPreviewDelimiter:"*$$*",initialPreviewAsData:!1,initialPreviewFileType:"image",initialPreviewConfig:[],initialPreviewThumbTags:[],previewThumbTags:{},initialPreviewShowDelete:!0,initialPreviewDownloadUrl:"",removeFromPreviewOnError:!1,deleteUrl:"",deleteExtraData:{},overwriteInitial:!0,sanitizeZoomCache:function(e){var i=t.createElement(e) +return i.find("input,textarea,select,datalist,form,.file-thumbnail-footer").remove(),i.html()},previewZoomButtonIcons:{prev:'',next:'',toggleheader:'',fullscreen:'',borderless:'',close:''},previewZoomButtonClasses:{prev:"btn btn-default btn-outline-secondary btn-navigate",next:"btn btn-default btn-outline-secondary btn-navigate",toggleheader:r,fullscreen:r,borderless:r,close:r},previewTemplates:{},previewContentTemplates:{},preferIconicPreview:!1,preferIconicZoomPreview:!1,allowedFileTypes:null,allowedFileExtensions:null,allowedPreviewTypes:void 0,allowedPreviewMimeTypes:null,allowedPreviewExtensions:null,disabledPreviewTypes:void 0,disabledPreviewExtensions:["msi","exe","com","zip","rar","app","vb","scr"],disabledPreviewMimeTypes:null,defaultPreviewContent:null,customLayoutTags:{},customPreviewTags:{},previewFileIcon:'',previewFileIconClass:"file-other-icon",previewFileIconSettings:{},previewFileExtSettings:{},buttonLabelClass:"hidden-xs",browseIcon:' ',browseClass:"btn btn-primary",removeIcon:'',removeClass:n,cancelIcon:'',cancelClass:n,pauseIcon:'',pauseClass:n,uploadIcon:'',uploadClass:n,uploadUrl:null,uploadUrlThumb:null,uploadAsync:!0,uploadParamNames:{chunkCount:"chunkCount",chunkIndex:"chunkIndex",chunkSize:"chunkSize",chunkSizeStart:"chunkSizeStart",chunksUploaded:"chunksUploaded",fileBlob:"fileBlob",fileId:"fileId",fileName:"fileName",fileRelativePath:"fileRelativePath",fileSize:"fileSize",retryCount:"retryCount"},maxAjaxThreads:5,fadeDelay:800,processDelay:100,bitrateUpdateDelay:500,queueDelay:10,progressDelay:0,enableResumableUpload:!1,resumableUploadOptions:{fallback:null,testUrl:null,chunkSize:2048,maxThreads:4,maxRetries:3,showErrorLog:!0,retainErrorHistory:!0,skipErrorsAndProceed:!1},uploadExtraData:{},zoomModalHeight:480,minImageWidth:null,minImageHeight:null,maxImageWidth:null,maxImageHeight:null,resizeImage:!1,resizePreference:"width",resizeQuality:.92,resizeDefaultImageType:"image/jpeg",resizeIfSizeMoreThan:0,minFileSize:-1,maxFileSize:0,maxFilePreviewSize:25600,minFileCount:0,maxFileCount:0,maxTotalFileCount:0,validateInitialCount:!1,msgValidationErrorClass:"text-danger",msgValidationErrorIcon:' ',msgErrorClass:"file-error-message",progressThumbClass:"progress-bar progress-bar-striped active progress-bar-animated",progressClass:"progress-bar bg-success progress-bar-success progress-bar-striped active progress-bar-animated",progressInfoClass:"progress-bar bg-info progress-bar-info progress-bar-striped active progress-bar-animated",progressCompleteClass:"progress-bar bg-success progress-bar-success",progressPauseClass:"progress-bar bg-primary progress-bar-primary progress-bar-striped active progress-bar-animated",progressErrorClass:"progress-bar bg-danger progress-bar-danger",progressUploadThreshold:99,previewFileType:"image",elCaptionContainer:null,elCaptionText:null,elPreviewContainer:null,elPreviewImage:null,elPreviewStatus:null,elErrorContainer:null,errorCloseButton:void 0,slugCallback:null,dropZoneEnabled:!0,dropZoneTitleClass:"file-drop-zone-title",fileActionSettings:{},otherActionButtons:"",textEncoding:"UTF-8",preProcessUpload:null,ajaxSettings:{},ajaxDeleteSettings:{},showAjaxErrorDetails:!0,mergeAjaxCallbacks:!1,mergeAjaxDeleteCallbacks:!1,retryErrorUploads:!0,reversePreviewOrder:!1,usePdfRenderer:function(){var e=!!window.MSInputMethodContext&&!!document.documentMode +return!!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i)||e},pdfRendererUrl:"",pdfRendererTemplate:"",tabIndexConfig:{browse:500,remove:500,upload:500,cancel:null,pause:null,modal:-1}},e.fn.fileinputLocales.en={sizeUnits:["B","KB","MB","GB","TB","PB","EB","ZB","YB"],bitRateUnits:["B/s","KB/s","MB/s","GB/s","TB/s","PB/s","EB/s","ZB/s","YB/s"],fileSingle:"file",filePlural:"files",browseLabel:"Browse …",removeLabel:"Remove",removeTitle:"Clear all unprocessed files",cancelLabel:"Cancel",cancelTitle:"Abort ongoing upload",pauseLabel:"Pause",pauseTitle:"Pause ongoing upload",uploadLabel:"Upload",uploadTitle:"Upload selected files",msgNo:"No",msgNoFilesSelected:"No files selected",msgCancelled:"Cancelled",msgPaused:"Paused",msgPlaceholder:"Select {files} ...",msgZoomModalHeading:"Detailed Preview",msgFileRequired:"You must select a file to upload.",msgSizeTooSmall:'File "{name}" ({size} KB) is too small and must be larger than {minSize} KB.',msgSizeTooLarge:'File "{name}" ({size} KB) exceeds maximum allowed upload size of {maxSize} KB.',msgFilesTooLess:"You must select at least {n} {files} to upload.",msgFilesTooMany:"Number of files selected for upload ({n}) exceeds maximum allowed limit of {m}.",msgTotalFilesTooMany:"You can upload a maximum of {m} files ({n} files detected).",msgFileNotFound:'File "{name}" not found!',msgFileSecured:'Security restrictions prevent reading the file "{name}".',msgFileNotReadable:'File "{name}" is not readable.',msgFilePreviewAborted:'File preview aborted for "{name}".',msgFilePreviewError:'An error occurred while reading the file "{name}".',msgInvalidFileName:'Invalid or unsupported characters in file name "{name}".',msgInvalidFileType:'Invalid type for file "{name}". Only "{types}" files are supported.',msgInvalidFileExtension:'Invalid extension for file "{name}". Only "{extensions}" files are supported.',msgFileTypes:{image:"image",html:"HTML",text:"text",video:"video",audio:"audio",flash:"flash",pdf:"PDF",object:"object"},msgUploadAborted:"The file upload was aborted",msgUploadThreshold:"Processing …",msgUploadBegin:"Initializing …",msgUploadEnd:"Done",msgUploadResume:"Resuming upload …",msgUploadEmpty:"No valid data available for upload.",msgUploadError:"Upload Error",msgDeleteError:"Delete Error",msgProgressError:"Error",msgValidationError:"Validation Error",msgLoading:"Loading file {index} of {files} …",msgProgress:"Loading file {index} of {files} - {name} - {percent}% completed.",msgSelected:"{n} {files} selected",msgProcessing:"Processing ...",msgFoldersNotAllowed:"Drag & drop files only! {n} folder(s) dropped were skipped.",msgImageWidthSmall:'Width of image file "{name}" must be at least {size} px.',msgImageHeightSmall:'Height of image file "{name}" must be at least {size} px.',msgImageWidthLarge:'Width of image file "{name}" cannot exceed {size} px.',msgImageHeightLarge:'Height of image file "{name}" cannot exceed {size} px.',msgImageResizeError:"Could not get the image dimensions to resize.",msgImageResizeException:"Error while resizing the image.
    {errors}
    ",msgAjaxError:"Something went wrong with the {operation} operation. Please try again later!",msgAjaxProgressError:"{operation} failed",msgDuplicateFile:'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',msgResumableUploadRetriesExceeded:"Upload aborted beyond {max} retries for file {file}! Error Details:
    {error}
    ",msgPendingTime:"{time} remaining",msgCalculatingTime:"calculating time remaining",ajaxOperations:{deleteThumb:"file delete",uploadThumb:"file upload",uploadBatch:"batch file upload",uploadExtra:"form data upload"},dropZoneTitle:"Drag & drop files here …",dropZoneClickTitle:"
    (or click to select {files})",previewZoomButtonTitles:{prev:"View previous file",next:"View next file",toggleheader:"Toggle header",fullscreen:"Toggle full screen",borderless:"Toggle borderless mode",close:"Close detailed preview"}},e.fn.fileinputLocales.zh={sizeUnits:["B","KB","MB","GB","TB","PB","EB","ZB","YB"],bitRateUnits:["B/s","KB/s","MB/s","GB/s","TB/s","PB/s","EB/s","ZB/s","YB/s"],fileSingle:"文件",filePlural:"个文件",browseLabel:"选择 …",removeLabel:"移除",removeTitle:"清除选中文件",cancelLabel:"取消",cancelTitle:"取消进行中的上传",pauseLabel:"暂停",pauseTitle:"暂停上传",uploadLabel:"上传",uploadTitle:"上传选中文件",msgNo:"没有",msgNoFilesSelected:"未选择文件",msgPaused:"已暂停",msgCancelled:"取消",msgPlaceholder:"选择 {files} ...",msgZoomModalHeading:"详细预览",msgFileRequired:"必须选择一个文件上传.",msgSizeTooSmall:'文件 "{name}" ({size} KB) 必须大于限定大小 {minSize} KB.',msgSizeTooLarge:'文件 "{name}" ({size} KB) 超过了允许大小 {maxSize} KB.',msgFilesTooLess:"你必须选择最少 {n} {files} 来上传. ",msgFilesTooMany:"选择的上传文件个数 ({n}) 超出最大文件的限制个数 {m}.",msgTotalFilesTooMany:"你最多可以上传 {m} 个文件 (当前有{n} 个文件).",msgFileNotFound:'文件 "{name}" 未找到!',msgFileSecured:'安全限制,为了防止读取文件 "{name}".',msgFileNotReadable:'文件 "{name}" 不可读.',msgFilePreviewAborted:'取消 "{name}" 的预览.',msgFilePreviewError:'读取 "{name}" 时出现了一个错误.',msgInvalidFileName:'文件名 "{name}" 包含非法字符.',msgInvalidFileType:'不正确的类型 "{name}". 只支持 "{types}" 类型的文件.',msgInvalidFileExtension:'不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.',msgFileTypes:{image:"image",html:"HTML",text:"text",video:"video",audio:"audio",flash:"flash",pdf:"PDF",object:"object"},msgUploadAborted:"该文件上传被中止",msgUploadThreshold:"处理中 …",msgUploadBegin:"正在初始化 …",msgUploadEnd:"完成",msgUploadResume:"继续上传 …",msgUploadEmpty:"无效的文件上传.",msgUploadError:"上传出错",msgDeleteError:"删除出错",msgProgressError:"上传出错",msgValidationError:"验证错误",msgLoading:"加载第 {index} 文件 共 {files} …",msgProgress:"加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.",msgSelected:"{n} {files} 选中",msgProcessing:"处理中 ...",msgFoldersNotAllowed:"只支持拖拽文件! 跳过 {n} 拖拽的文件夹.",msgImageWidthSmall:'图像文件的"{name}"的宽度必须是至少{size}像素.',msgImageHeightSmall:'图像文件的"{name}"的高度必须至少为{size}像素.',msgImageWidthLarge:'图像文件"{name}"的宽度不能超过{size}像素.',msgImageHeightLarge:'图像文件"{name}"的高度不能超过{size}像素.',msgImageResizeError:"无法获取的图像尺寸调整。",msgImageResizeException:"调整图像大小时发生错误。
    {errors}
    ",msgAjaxError:"{operation} 发生错误. 请重试!",msgAjaxProgressError:"{operation} 失败",msgDuplicateFile:'文件 "{name}",大小 "{size} KB" 已经被选中.忽略相同的文件.',msgResumableUploadRetriesExceeded:"文件 {file} 上传失败超过 {max} 次重试 ! 错误详情:
    {error}
    ",msgPendingTime:"{time} 剩余",msgCalculatingTime:"计算剩余时间",ajaxOperations:{deleteThumb:"删除文件",uploadThumb:"上传文件",uploadBatch:"批量上传",uploadExtra:"表单数据上传"},dropZoneTitle:"拖拽文件到这里 …
    支持多文件同时上传",dropZoneClickTitle:"
    (或点击{files}按钮选择文件)",fileActionSettings:{removeTitle:"删除文件",uploadTitle:"上传文件",downloadTitle:"下载文件",uploadRetryTitle:"重试",zoomTitle:"查看详情",dragTitle:"移动 / 重置",indicatorNewTitle:"没有上传",indicatorSuccessTitle:"上传",indicatorErrorTitle:"上传错误",indicatorPausedTitle:"上传已暂停",indicatorLoadingTitle:"上传 …"},previewZoomButtonTitles:{prev:"预览上一个文件",next:"预览下一个文件",toggleheader:"缩放",fullscreen:"全屏",borderless:"无边界模式",close:"关闭当前预览"}},e.fn.fileinput.Constructor=i,e(document).ready(function(){var t=e("input.file[type=file]") +t.length&&t.fileinput()})}) diff --git a/ruoyi-admin/src/main/resources/templates/demo/form/upload.html b/ruoyi-admin/src/main/resources/templates/demo/form/upload.html index b851a9e5..92bc7107 100644 --- a/ruoyi-admin/src/main/resources/templates/demo/form/upload.html +++ b/ruoyi-admin/src/main/resources/templates/demo/form/upload.html @@ -60,11 +60,8 @@ uploadAsync: false }).on('filebatchuploadsuccess', function (event, data, previewId, index) { var rsp = data.response; - var fileJson = rsp.data; - for (var i in fileJson) { - log.info("return data.url:" + fileJson[i].url) - log.info("reutrn data.name:" + fileJson[i].name) - } + log.info("return urls:" + rsp.urls) + log.info("reutrn fileNames:" + rsp.fileNames) }).on('fileremoved', function (event, id, index) { $("input[name='" + event.currentTarget.id + "']").val('') }) diff --git a/ruoyi-admin/src/main/resources/templates/include.html b/ruoyi-admin/src/main/resources/templates/include.html index dbe7f62e..fd8cb7d5 100644 --- a/ruoyi-admin/src/main/resources/templates/include.html +++ b/ruoyi-admin/src/main/resources/templates/include.html @@ -108,10 +108,10 @@
    - +
    - +
    diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/FileInfo.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/FileInfo.java deleted file mode 100644 index d197a5ab..00000000 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/FileInfo.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.ruoyi.common.core.domain; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -/** - * 文件信息 - * - * @author ruoyi - */ -public class FileInfo -{ - /** - * 文件名称 - */ - private String name; - - /** - * 文件地址 - */ - private String url; - - public FileInfo() - { - - } - - public FileInfo(String name, String url) - { - this.name = name; - this.url = url; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public String getUrl() - { - return url; - } - - public void setUrl(String url) - { - this.url = url; - } - - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("name", getName()) - .append("url", getUrl()) - .toString(); - } - } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java index 73a40cf0..9465b752 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java @@ -418,6 +418,22 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils return false; } + /** + * 删除最后一个字符串 + * + * @param str 输入字符串 + * @param spit 以什么类型结尾的 + * @return 截取后的字符串 + */ + public static String lastStringDel(String str, String spit) + { + if (!StringUtils.isEmpty(str) && str.endsWith(spit)) + { + return str.subSequence(0, str.length() - 1).toString(); + } + return str; + } + /** * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld *