fileinput.js 197 KB

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