fileinput.js 208 KB

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