fileinput.js 204 KB

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