fileinput.js 199 KB

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