fileinput.js 177 KB

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