fileinput.js 178 KB

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