fileinput.js 179 KB

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