fileinput.js 195 KB

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