fileinput.js 181 KB

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