fileinput.js 199 KB

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