fileinput.js 197 KB

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