fileinput.js 195 KB

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