fileinput.js 207 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581
  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="{caption}" ' +
  767. 'alt="{caption}"' + 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. parseTemplate = function (cat, dat, fn, ft, id, ftr, ind, fc, t) {
  1005. fc = ' file-preview-initial ' + $h.SORT_CSS + (fc ? ' ' + fc : '');
  1006. return self._generatePreviewTemplate(cat, dat, fn, ft, id, false, null, fc, ftr, ind, t);
  1007. };
  1008. if (!content) {
  1009. return '';
  1010. }
  1011. isDisabled = isDisabled === undefined ? true : isDisabled;
  1012. cat = $h.ifSet('type', config, self.initialPreviewFileType || 'generic');
  1013. fname = $h.ifSet('filename', config, $h.ifSet('caption', config));
  1014. ftype = $h.ifSet('filetype', config, cat);
  1015. ftr = self.previewCache.footer(i, isDisabled, (config && config.size || null));
  1016. frameClass = $h.ifSet('frameClass', config);
  1017. if (asData) {
  1018. out = parseTemplate(cat, content, fname, ftype, previewId, ftr, ind, frameClass);
  1019. } else {
  1020. out = parseTemplate('generic', content, fname, ftype, previewId, ftr, ind, frameClass, cat)
  1021. .setTokens({'content': data.content[i]});
  1022. }
  1023. if (data.tags.length && data.tags[i]) {
  1024. out = $h.replaceTags(out, data.tags[i]);
  1025. }
  1026. /** @namespace config.frameAttr */
  1027. if (!$h.isEmpty(config) && !$h.isEmpty(config.frameAttr)) {
  1028. $tmp = $(document.createElement('div')).html(out);
  1029. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  1030. out = $tmp.html();
  1031. $tmp.remove();
  1032. }
  1033. return out;
  1034. },
  1035. add: function (content, config, tags, append) {
  1036. var data = self.previewCache.data, index;
  1037. if (!$h.isArray(content)) {
  1038. content = content.split(self.initialPreviewDelimiter);
  1039. }
  1040. if (append) {
  1041. index = data.content.push(content) - 1;
  1042. data.config[index] = config;
  1043. data.tags[index] = tags;
  1044. } else {
  1045. index = content.length - 1;
  1046. data.content = content;
  1047. data.config = config;
  1048. data.tags = tags;
  1049. }
  1050. self.previewCache.data = data;
  1051. return index;
  1052. },
  1053. set: function (content, config, tags, append) {
  1054. var data = self.previewCache.data, i, chk;
  1055. if (!content || !content.length) {
  1056. return;
  1057. }
  1058. if (!$h.isArray(content)) {
  1059. content = content.split(self.initialPreviewDelimiter);
  1060. }
  1061. chk = content.filter(function (n) {
  1062. return n !== null;
  1063. });
  1064. if (!chk.length) {
  1065. return;
  1066. }
  1067. if (data.content === undefined) {
  1068. data.content = [];
  1069. }
  1070. if (data.config === undefined) {
  1071. data.config = [];
  1072. }
  1073. if (data.tags === undefined) {
  1074. data.tags = [];
  1075. }
  1076. if (append) {
  1077. for (i = 0; i < content.length; i++) {
  1078. if (content[i]) {
  1079. data.content.push(content[i]);
  1080. }
  1081. }
  1082. for (i = 0; i < config.length; i++) {
  1083. if (config[i]) {
  1084. data.config.push(config[i]);
  1085. }
  1086. }
  1087. for (i = 0; i < tags.length; i++) {
  1088. if (tags[i]) {
  1089. data.tags.push(tags[i]);
  1090. }
  1091. }
  1092. } else {
  1093. data.content = content;
  1094. data.config = config;
  1095. data.tags = tags;
  1096. }
  1097. self.previewCache.data = data;
  1098. },
  1099. unset: function (index) {
  1100. var chk = self.previewCache.count(), rev = self.reversePreviewOrder;
  1101. if (!chk) {
  1102. return;
  1103. }
  1104. if (chk === 1) {
  1105. self.previewCache.data.content = [];
  1106. self.previewCache.data.config = [];
  1107. self.previewCache.data.tags = [];
  1108. self.initialPreview = [];
  1109. self.initialPreviewConfig = [];
  1110. self.initialPreviewThumbTags = [];
  1111. return;
  1112. }
  1113. self.previewCache.data.content = $h.spliceArray(self.previewCache.data.content, index, rev);
  1114. self.previewCache.data.config = $h.spliceArray(self.previewCache.data.config, index, rev);
  1115. self.previewCache.data.tags = $h.spliceArray(self.previewCache.data.tags, index, rev);
  1116. },
  1117. out: function () {
  1118. var html = '', caption, len = self.previewCache.count(), i, content;
  1119. if (len === 0) {
  1120. return {content: '', caption: ''};
  1121. }
  1122. for (i = 0; i < len; i++) {
  1123. content = self.previewCache.get(i);
  1124. html = self.reversePreviewOrder ? (content + html) : (html + content);
  1125. }
  1126. caption = self._getMsgSelected(len);
  1127. return {content: html, caption: caption};
  1128. },
  1129. footer: function (i, isDisabled, size) {
  1130. var data = self.previewCache.data || {};
  1131. if ($h.isEmpty(data.content)) {
  1132. return '';
  1133. }
  1134. if ($h.isEmpty(data.config) || $h.isEmpty(data.config[i])) {
  1135. data.config[i] = {};
  1136. }
  1137. isDisabled = isDisabled === undefined ? true : isDisabled;
  1138. var config = data.config[i], caption = $h.ifSet('caption', config), a,
  1139. width = $h.ifSet('width', config, 'auto'), url = $h.ifSet('url', config, false),
  1140. key = $h.ifSet('key', config, null), fs = self.fileActionSettings,
  1141. initPreviewShowDel = self.initialPreviewShowDelete || false,
  1142. dUrl = config.downloadUrl || self.initialPreviewDownloadUrl || '',
  1143. dFil = config.filename || config.caption || '',
  1144. initPreviewShowDwl = !!(dUrl),
  1145. sDel = $h.ifSet('showRemove', config, $h.ifSet('showRemove', fs, initPreviewShowDel)),
  1146. sDwl = $h.ifSet('showDownload', config, $h.ifSet('showDownload', fs, initPreviewShowDwl)),
  1147. sZm = $h.ifSet('showZoom', config, $h.ifSet('showZoom', fs, true)),
  1148. sDrg = $h.ifSet('showDrag', config, $h.ifSet('showDrag', fs, true)),
  1149. dis = (url === false) && isDisabled;
  1150. sDwl = sDwl && config.downloadUrl !== false && !!dUrl;
  1151. a = self._renderFileActions(false, sDwl, sDel, sZm, sDrg, dis, url, key, true, dUrl, dFil);
  1152. return self._getLayoutTemplate('footer').setTokens({
  1153. 'progress': self._renderThumbProgress(),
  1154. 'actions': a,
  1155. 'caption': caption,
  1156. 'size': self._getSize(size),
  1157. 'width': width,
  1158. 'indicator': ''
  1159. });
  1160. }
  1161. };
  1162. self.previewCache.init();
  1163. },
  1164. _isPdfRendered: function () {
  1165. var self = this, useLib = self.usePdfRenderer,
  1166. flag = typeof useLib === 'function' ? useLib() : !!useLib;
  1167. return flag && self.pdfRendererUrl;
  1168. },
  1169. _handler: function ($el, event, callback) {
  1170. var self = this, ns = self.namespace, ev = event.split(' ').join(ns + ' ') + ns;
  1171. if (!$el || !$el.length) {
  1172. return;
  1173. }
  1174. $el.off(ev).on(ev, callback);
  1175. },
  1176. _encodeURI: function (vUrl) {
  1177. var self = this;
  1178. return self.encodeUrl ? encodeURI(vUrl) : vUrl;
  1179. },
  1180. _log: function (msg) {
  1181. var self = this, id = self.$element.attr('id');
  1182. if (id) {
  1183. msg = '"' + id + '": ' + msg;
  1184. }
  1185. msg = 'bootstrap-fileinput: ' + msg;
  1186. if (typeof window.console.log !== 'undefined') {
  1187. window.console.log(msg);
  1188. } else {
  1189. window.alert(msg);
  1190. }
  1191. },
  1192. _validate: function () {
  1193. var self = this, status = self.$element.attr('type') === 'file';
  1194. if (!status) {
  1195. self._log('The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.');
  1196. }
  1197. return status;
  1198. },
  1199. _errorsExist: function () {
  1200. var self = this, $err, $errList = self.$errorContainer.find('li');
  1201. if ($errList.length) {
  1202. return true;
  1203. }
  1204. $err = $(document.createElement('div')).html(self.$errorContainer.html());
  1205. $err.find('.kv-error-close').remove();
  1206. $err.find('ul').remove();
  1207. return !!$.trim($err.text()).length;
  1208. },
  1209. _errorHandler: function (evt, caption) {
  1210. var self = this, err = evt.target.error, showError = function (msg) {
  1211. self._showError(msg.replace('{name}', caption));
  1212. };
  1213. /** @namespace err.NOT_FOUND_ERR */
  1214. /** @namespace err.SECURITY_ERR */
  1215. /** @namespace err.NOT_READABLE_ERR */
  1216. if (err.code === err.NOT_FOUND_ERR) {
  1217. showError(self.msgFileNotFound);
  1218. } else {
  1219. if (err.code === err.SECURITY_ERR) {
  1220. showError(self.msgFileSecured);
  1221. } else {
  1222. if (err.code === err.NOT_READABLE_ERR) {
  1223. showError(self.msgFileNotReadable);
  1224. } else {
  1225. if (err.code === err.ABORT_ERR) {
  1226. showError(self.msgFilePreviewAborted);
  1227. } else {
  1228. showError(self.msgFilePreviewError);
  1229. }
  1230. }
  1231. }
  1232. }
  1233. },
  1234. _addError: function (msg) {
  1235. var self = this, $error = self.$errorContainer;
  1236. if (msg && $error.length) {
  1237. $error.html(self.errorCloseButton + msg);
  1238. self._handler($error.find('.kv-error-close'), 'click', function () {
  1239. setTimeout(function () {
  1240. if (self.showPreview && !self.getFrames().length) {
  1241. self.clear();
  1242. }
  1243. $error.fadeOut('slow');
  1244. }, 10);
  1245. });
  1246. }
  1247. },
  1248. _setValidationError: function (css) {
  1249. var self = this;
  1250. css = (css ? css + ' ' : '') + 'has-error';
  1251. self.$container.removeClass(css).addClass('has-error');
  1252. $h.addCss(self.$captionContainer, 'is-invalid');
  1253. },
  1254. _resetErrors: function (fade) {
  1255. var self = this, $error = self.$errorContainer;
  1256. self.isError = false;
  1257. self.$container.removeClass('has-error');
  1258. self.$captionContainer.removeClass('is-invalid');
  1259. $error.html('');
  1260. if (fade) {
  1261. $error.fadeOut('slow');
  1262. } else {
  1263. $error.hide();
  1264. }
  1265. },
  1266. _showFolderError: function (folders) {
  1267. var self = this, $error = self.$errorContainer, msg;
  1268. if (!folders) {
  1269. return;
  1270. }
  1271. if (!self.isAjaxUpload) {
  1272. self._clearFileInput();
  1273. }
  1274. msg = self.msgFoldersNotAllowed.replace('{n}', folders);
  1275. self._addError(msg);
  1276. self._setValidationError();
  1277. $error.fadeIn(800);
  1278. self._raise('filefoldererror', [folders, msg]);
  1279. },
  1280. _showUploadError: function (msg, params, event) {
  1281. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', e = params && params.id ?
  1282. '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  1283. if ($error.find('ul').length === 0) {
  1284. self._addError('<ul>' + e + '</ul>');
  1285. } else {
  1286. $error.find('ul').append(e);
  1287. }
  1288. $error.fadeIn(800);
  1289. self._raise(ev, [params, msg]);
  1290. self._setValidationError('file-input-new');
  1291. return true;
  1292. },
  1293. _showError: function (msg, params, event) {
  1294. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1295. params = params || {};
  1296. params.reader = self.reader;
  1297. self._addError(msg);
  1298. $error.fadeIn(800);
  1299. self._raise(ev, [params, msg]);
  1300. if (!self.isAjaxUpload) {
  1301. self._clearFileInput();
  1302. }
  1303. self._setValidationError('file-input-new');
  1304. self.$btnUpload.attr('disabled', true);
  1305. return true;
  1306. },
  1307. _noFilesError: function (params) {
  1308. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  1309. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  1310. $error = self.$errorContainer;
  1311. self._addError(msg);
  1312. self.isError = true;
  1313. self._updateFileDetails(0);
  1314. $error.fadeIn(800);
  1315. self._raise('fileerror', [params, msg]);
  1316. self._clearFileInput();
  1317. self._setValidationError();
  1318. },
  1319. _parseError: function (operation, jqXHR, errorThrown, fileName) {
  1320. /** @namespace jqXHR.responseJSON */
  1321. var self = this, errMsg = $.trim(errorThrown + ''), textPre,
  1322. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  1323. jqXHR.responseJSON.error : jqXHR.responseText;
  1324. if (self.cancelling && self.msgUploadAborted) {
  1325. errMsg = self.msgUploadAborted;
  1326. }
  1327. if (self.showAjaxErrorDetails && text) {
  1328. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  1329. textPre = text.length ? '<pre>' + text + '</pre>' : '';
  1330. errMsg += errMsg ? textPre : text;
  1331. }
  1332. if (!errMsg) {
  1333. errMsg = self.msgAjaxError.replace('{operation}', operation);
  1334. }
  1335. self.cancelling = false;
  1336. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  1337. },
  1338. _parseFileType: function (type, name) {
  1339. var self = this, isValid, vType, cat, i, types = self.allowedPreviewTypes || [];
  1340. if (type === 'application/text-plain') {
  1341. return 'text';
  1342. }
  1343. for (i = 0; i < types.length; i++) {
  1344. cat = types[i];
  1345. isValid = self.fileTypeSettings[cat];
  1346. vType = isValid(type, name) ? cat : '';
  1347. if (!$h.isEmpty(vType)) {
  1348. return vType;
  1349. }
  1350. }
  1351. return 'other';
  1352. },
  1353. _getPreviewIcon: function (fname) {
  1354. var self = this, ext, out = null;
  1355. if (fname && fname.indexOf('.') > -1) {
  1356. ext = fname.split('.').pop();
  1357. if (self.previewFileIconSettings) {
  1358. out = self.previewFileIconSettings[ext] || self.previewFileIconSettings[ext.toLowerCase()] || null;
  1359. }
  1360. if (self.previewFileExtSettings) {
  1361. $.each(self.previewFileExtSettings, function (key, func) {
  1362. if (self.previewFileIconSettings[key] && func(ext)) {
  1363. out = self.previewFileIconSettings[key];
  1364. //noinspection UnnecessaryReturnStatementJS
  1365. return;
  1366. }
  1367. });
  1368. }
  1369. }
  1370. return out;
  1371. },
  1372. _parseFilePreviewIcon: function (content, fname) {
  1373. var self = this, icn = self._getPreviewIcon(fname) || self.previewFileIcon, out = content;
  1374. if (out.indexOf('{previewFileIcon}') > -1) {
  1375. out = out.setTokens({'previewFileIconClass': self.previewFileIconClass, 'previewFileIcon': icn});
  1376. }
  1377. return out;
  1378. },
  1379. _raise: function (event, params) {
  1380. var self = this, e = $.Event(event);
  1381. if (params !== undefined) {
  1382. self.$element.trigger(e, params);
  1383. } else {
  1384. self.$element.trigger(e);
  1385. }
  1386. if (e.isDefaultPrevented() || e.result === false) {
  1387. return false;
  1388. }
  1389. switch (event) {
  1390. // ignore these events
  1391. case 'filebatchuploadcomplete':
  1392. case 'filebatchuploadsuccess':
  1393. case 'fileuploaded':
  1394. case 'fileclear':
  1395. case 'filecleared':
  1396. case 'filereset':
  1397. case 'fileerror':
  1398. case 'filefoldererror':
  1399. case 'fileuploaderror':
  1400. case 'filebatchuploaderror':
  1401. case 'filedeleteerror':
  1402. case 'filecustomerror':
  1403. case 'filesuccessremove':
  1404. break;
  1405. // receive data response via `filecustomerror` event`
  1406. default:
  1407. if (!self.ajaxAborted) {
  1408. self.ajaxAborted = e.result;
  1409. }
  1410. break;
  1411. }
  1412. return true;
  1413. },
  1414. _listenFullScreen: function (isFullScreen) {
  1415. var self = this, $modal = self.$modal, $btnFull, $btnBord;
  1416. if (!$modal || !$modal.length) {
  1417. return;
  1418. }
  1419. $btnFull = $modal && $modal.find('.btn-fullscreen');
  1420. $btnBord = $modal && $modal.find('.btn-borderless');
  1421. if (!$btnFull.length || !$btnBord.length) {
  1422. return;
  1423. }
  1424. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1425. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1426. if (isFullScreen) {
  1427. $btnFull.addClass('active').attr('aria-pressed', 'true');
  1428. } else {
  1429. $btnBord.addClass('active').attr('aria-pressed', 'true');
  1430. }
  1431. if ($modal.hasClass('file-zoom-fullscreen')) {
  1432. self._maximizeZoomDialog();
  1433. } else {
  1434. if (isFullScreen) {
  1435. self._maximizeZoomDialog();
  1436. } else {
  1437. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1438. }
  1439. }
  1440. },
  1441. _listen: function () {
  1442. var self = this, $el = self.$element, $form = self.$form, $cont = self.$container, fullScreenEvents;
  1443. self._handler($el, 'click', function (e) {
  1444. if ($el.hasClass('file-no-browse')) {
  1445. if ($el.data('zoneClicked')) {
  1446. $el.data('zoneClicked', false);
  1447. } else {
  1448. e.preventDefault();
  1449. }
  1450. }
  1451. });
  1452. self._handler($el, 'change', $.proxy(self._change, self));
  1453. if (self.showBrowse) {
  1454. self._handler(self.$btnFile, 'click', $.proxy(self._browse, self));
  1455. }
  1456. self._handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  1457. self._handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  1458. self._initDragDrop();
  1459. self._handler($form, 'reset', $.proxy(self.clear, self));
  1460. if (!self.isAjaxUpload) {
  1461. self._handler($form, 'submit', $.proxy(self._submitForm, self));
  1462. }
  1463. self._handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
  1464. self._handler($(window), 'resize', function () {
  1465. self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight);
  1466. });
  1467. fullScreenEvents = 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange';
  1468. self._handler($(document), fullScreenEvents, function () {
  1469. self._listenFullScreen($h.checkFullScreen());
  1470. });
  1471. self._autoFitContent();
  1472. self._initClickable();
  1473. self._refreshPreview();
  1474. },
  1475. _autoFitContent: function () {
  1476. var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  1477. self = this, config = width < 400 ? (self.previewSettingsSmall || self.defaults.previewSettingsSmall) :
  1478. (self.previewSettings || self.defaults.previewSettings), sel;
  1479. $.each(config, function (cat, settings) {
  1480. sel = '.file-preview-frame .file-preview-' + cat;
  1481. self.$preview.find(sel + '.kv-preview-data,' + sel + ' .kv-preview-data').css(settings);
  1482. });
  1483. },
  1484. _scanDroppedItems: function (item, files, path) {
  1485. path = path || '';
  1486. var self = this, i, dirReader, readDir, errorHandler = function (e) {
  1487. self._log('Error scanning dropped files!');
  1488. self._log(e);
  1489. };
  1490. if (item.isFile) {
  1491. item.file(function (file) {
  1492. files.push(file);
  1493. }, errorHandler);
  1494. } else {
  1495. if (item.isDirectory) {
  1496. dirReader = item.createReader();
  1497. readDir = function () {
  1498. dirReader.readEntries(function (entries) {
  1499. if (entries && entries.length > 0) {
  1500. for (i = 0; i < entries.length; i++) {
  1501. self._scanDroppedItems(entries[i], files, path + item.name + '/');
  1502. }
  1503. // recursively call readDir() again, since browser can only handle first 100 entries.
  1504. readDir();
  1505. }
  1506. return null;
  1507. }, errorHandler);
  1508. };
  1509. readDir();
  1510. }
  1511. }
  1512. },
  1513. _initDragDrop: function () {
  1514. var self = this, $zone = self.$dropZone;
  1515. if (self.dropZoneEnabled && self.showPreview) {
  1516. self._handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
  1517. self._handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
  1518. self._handler($zone, 'drop', $.proxy(self._zoneDrop, self));
  1519. self._handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
  1520. }
  1521. },
  1522. _zoneDragDropInit: function (e) {
  1523. e.stopPropagation();
  1524. e.preventDefault();
  1525. },
  1526. _zoneDragEnter: function (e) {
  1527. var self = this, dataTransfer = e.originalEvent.dataTransfer,
  1528. hasFiles = $.inArray('Files', dataTransfer.types) > -1;
  1529. self._zoneDragDropInit(e);
  1530. if (self.isDisabled || !hasFiles) {
  1531. e.originalEvent.dataTransfer.effectAllowed = 'none';
  1532. e.originalEvent.dataTransfer.dropEffect = 'none';
  1533. return;
  1534. }
  1535. if (self._raise('fileDragEnter', {'sourceEvent': e, 'files': dataTransfer.types.Files})) {
  1536. $h.addCss(self.$dropZone, 'file-highlighted');
  1537. }
  1538. },
  1539. _zoneDragLeave: function (e) {
  1540. var self = this;
  1541. self._zoneDragDropInit(e);
  1542. if (self.isDisabled) {
  1543. return;
  1544. }
  1545. if (self._raise('fileDragLeave', {'sourceEvent': e})) {
  1546. self.$dropZone.removeClass('file-highlighted');
  1547. }
  1548. },
  1549. _zoneDrop: function (e) {
  1550. /** @namespace e.originalEvent.dataTransfer */
  1551. var self = this, i, $el = self.$element, dataTransfer = e.originalEvent.dataTransfer,
  1552. files = dataTransfer.files, items = dataTransfer.items, folders = $h.getDragDropFolders(items),
  1553. processFiles = function () {
  1554. if (!self.isAjaxUpload) {
  1555. self.changeTriggered = true;
  1556. $el.get(0).files = files;
  1557. setTimeout(function () {
  1558. self.changeTriggered = false;
  1559. $el.trigger('change' + self.namespace);
  1560. }, 10);
  1561. } else {
  1562. self._change(e, files);
  1563. }
  1564. self.$dropZone.removeClass('file-highlighted');
  1565. };
  1566. e.preventDefault();
  1567. if (self.isDisabled || $h.isEmpty(files)) {
  1568. return;
  1569. }
  1570. if (!self._raise('fileDragDrop', {'sourceEvent': e, 'files': files})) {
  1571. return;
  1572. }
  1573. if (folders > 0) {
  1574. if (!self.isAjaxUpload) {
  1575. self._showFolderError(folders);
  1576. return;
  1577. }
  1578. files = [];
  1579. for (i = 0; i < items.length; i++) {
  1580. var item = items[i].webkitGetAsEntry();
  1581. if (item) {
  1582. self._scanDroppedItems(item, files);
  1583. }
  1584. }
  1585. setTimeout(function () {
  1586. processFiles();
  1587. }, 500);
  1588. } else {
  1589. processFiles();
  1590. }
  1591. },
  1592. _uploadClick: function (e) {
  1593. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  1594. isEnabled = !$btn.hasClass('disabled') && $h.isEmpty($btn.attr('disabled'));
  1595. if (e && e.isDefaultPrevented()) {
  1596. return;
  1597. }
  1598. if (!self.isAjaxUpload) {
  1599. if (isEnabled && $btn.attr('type') !== 'submit') {
  1600. $form = $btn.closest('form');
  1601. // downgrade to normal form submit if possible
  1602. if ($form.length) {
  1603. $form.trigger('submit');
  1604. }
  1605. e.preventDefault();
  1606. }
  1607. return;
  1608. }
  1609. e.preventDefault();
  1610. if (isEnabled) {
  1611. self.upload();
  1612. }
  1613. },
  1614. _submitForm: function () {
  1615. var self = this;
  1616. return self._isFileSelectionValid() && !self._abort({});
  1617. },
  1618. _clearPreview: function () {
  1619. var self = this, $p = self.$preview,
  1620. $thumbs = self.showUploadedThumbs ? self.getFrames(':not(.file-preview-success)') : self.getFrames();
  1621. $thumbs.each(function () {
  1622. var $thumb = $(this);
  1623. $thumb.remove();
  1624. $h.cleanZoomCache($p.find('#zoom-' + $thumb.attr('id')));
  1625. });
  1626. if (!self.getFrames().length || !self.showPreview) {
  1627. self._resetUpload();
  1628. }
  1629. self._validateDefaultPreview();
  1630. },
  1631. _initSortable: function () {
  1632. var self = this, $el = self.$preview, settings, selector = '.' + $h.SORT_CSS,
  1633. rev = self.reversePreviewOrder;
  1634. if (!window.KvSortable || $el.find(selector).length === 0) {
  1635. return;
  1636. }
  1637. //noinspection JSUnusedGlobalSymbols
  1638. settings = {
  1639. handle: '.drag-handle-init',
  1640. dataIdAttr: 'data-preview-id',
  1641. scroll: false,
  1642. draggable: selector,
  1643. onSort: function (e) {
  1644. var oldIndex = e.oldIndex, newIndex = e.newIndex, i = 0;
  1645. self.initialPreview = $h.moveArray(self.initialPreview, oldIndex, newIndex, rev);
  1646. self.initialPreviewConfig = $h.moveArray(self.initialPreviewConfig, oldIndex, newIndex, rev);
  1647. self.previewCache.init();
  1648. self.getFrames('.file-preview-initial').each(function () {
  1649. $(this).attr('data-fileindex', 'init_' + i);
  1650. i++;
  1651. });
  1652. self._raise('filesorted', {
  1653. previewId: $(e.item).attr('id'),
  1654. 'oldIndex': oldIndex,
  1655. 'newIndex': newIndex,
  1656. stack: self.initialPreviewConfig
  1657. });
  1658. }
  1659. };
  1660. if ($el.data('kvsortable')) {
  1661. $el.kvsortable('destroy');
  1662. }
  1663. $.extend(true, settings, self.fileActionSettings.dragSettings);
  1664. $el.kvsortable(settings);
  1665. },
  1666. _setPreviewContent: function (content) {
  1667. var self = this;
  1668. self.$preview.html(content);
  1669. self._autoFitContent();
  1670. },
  1671. _initPreview: function (isInit) {
  1672. var self = this, cap = self.initialCaption || '', out;
  1673. if (!self.previewCache.count()) {
  1674. self._clearPreview();
  1675. if (isInit) {
  1676. self._setCaption(cap);
  1677. } else {
  1678. self._initCaption();
  1679. }
  1680. return;
  1681. }
  1682. out = self.previewCache.out();
  1683. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  1684. self._setPreviewContent(out.content);
  1685. self._setInitThumbAttr();
  1686. self._setCaption(cap);
  1687. self._initSortable();
  1688. if (!$h.isEmpty(out.content)) {
  1689. self.$container.removeClass('file-input-new');
  1690. }
  1691. },
  1692. _getZoomButton: function (type) {
  1693. var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type],
  1694. title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ',
  1695. params = title + (type === 'close' ? ' data-dismiss="modal" aria-hidden="true"' : '');
  1696. if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') {
  1697. params += ' data-toggle="button" aria-pressed="false" autocomplete="off"';
  1698. }
  1699. return '<button type="button" class="' + css + ' btn-' + type + '"' + params + '>' + label + '</button>';
  1700. },
  1701. _getModalContent: function () {
  1702. var self = this;
  1703. return self._getLayoutTemplate('modal').setTokens({
  1704. 'rtl': self.rtl ? ' kv-rtl' : '',
  1705. 'zoomFrameClass': self.frameClass,
  1706. 'heading': self.msgZoomModalHeading,
  1707. 'prev': self._getZoomButton('prev'),
  1708. 'next': self._getZoomButton('next'),
  1709. 'toggleheader': self._getZoomButton('toggleheader'),
  1710. 'fullscreen': self._getZoomButton('fullscreen'),
  1711. 'borderless': self._getZoomButton('borderless'),
  1712. 'close': self._getZoomButton('close')
  1713. });
  1714. },
  1715. _listenModalEvent: function (event) {
  1716. var self = this, $modal = self.$modal, getParams = function (e) {
  1717. return {
  1718. sourceEvent: e,
  1719. previewId: $modal.data('previewId'),
  1720. modal: $modal
  1721. };
  1722. };
  1723. $modal.on(event + '.bs.modal', function (e) {
  1724. var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
  1725. self._raise('filezoom' + event, getParams(e));
  1726. if (event === 'shown') {
  1727. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1728. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1729. if ($modal.hasClass('file-zoom-fullscreen')) {
  1730. self._maximizeZoomDialog();
  1731. if ($h.checkFullScreen()) {
  1732. $btnFull.addClass('active').attr('aria-pressed', 'true');
  1733. } else {
  1734. $btnBord.addClass('active').attr('aria-pressed', 'true');
  1735. }
  1736. }
  1737. }
  1738. });
  1739. },
  1740. _initZoom: function () {
  1741. var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID;
  1742. if (!self.showPreview) {
  1743. return;
  1744. }
  1745. self.$modal = $(modalId);
  1746. if (!self.$modal || !self.$modal.length) {
  1747. $dialog = $(document.createElement('div')).html(modalMain).insertAfter(self.$container);
  1748. self.$modal = $(modalId).insertBefore($dialog);
  1749. $dialog.remove();
  1750. }
  1751. $h.initModal(self.$modal);
  1752. self.$modal.html(self._getModalContent());
  1753. $.each($h.MODAL_EVENTS, function (key, event) {
  1754. self._listenModalEvent(event);
  1755. });
  1756. },
  1757. _initZoomButtons: function () {
  1758. var self = this, previewId = self.$modal.data('previewId') || '', $first, $last,
  1759. thumbs = self.getFrames().toArray(), len = thumbs.length, $prev = self.$modal.find('.btn-prev'),
  1760. $next = self.$modal.find('.btn-next');
  1761. if (thumbs.length < 2) {
  1762. $prev.hide();
  1763. $next.hide();
  1764. return;
  1765. } else {
  1766. $prev.show();
  1767. $next.show();
  1768. }
  1769. if (!len) {
  1770. return;
  1771. }
  1772. $first = $(thumbs[0]);
  1773. $last = $(thumbs[len - 1]);
  1774. $prev.removeAttr('disabled');
  1775. $next.removeAttr('disabled');
  1776. if ($first.length && $first.attr('id') === previewId) {
  1777. $prev.attr('disabled', true);
  1778. }
  1779. if ($last.length && $last.attr('id') === previewId) {
  1780. $next.attr('disabled', true);
  1781. }
  1782. },
  1783. _maximizeZoomDialog: function () {
  1784. var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
  1785. $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'),
  1786. h = $(window).height(), diff = 0;
  1787. $modal.addClass('file-zoom-fullscreen');
  1788. if ($head && $head.length) {
  1789. h -= $head.outerHeight(true);
  1790. }
  1791. if ($foot && $foot.length) {
  1792. h -= $foot.outerHeight(true);
  1793. }
  1794. if ($body && $body.length) {
  1795. diff = $body.outerHeight(true) - $body.height();
  1796. h -= diff;
  1797. }
  1798. $modal.find('.kv-zoom-body').height(h);
  1799. },
  1800. _resizeZoomDialog: function (fullScreen) {
  1801. var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'),
  1802. $btnBord = $modal.find('.btn-borderless');
  1803. if ($modal.hasClass('file-zoom-fullscreen')) {
  1804. $h.toggleFullScreen(false);
  1805. if (!fullScreen) {
  1806. if (!$btnFull.hasClass('active')) {
  1807. $modal.removeClass('file-zoom-fullscreen');
  1808. self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
  1809. } else {
  1810. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1811. }
  1812. } else {
  1813. if (!$btnFull.hasClass('active')) {
  1814. $modal.removeClass('file-zoom-fullscreen');
  1815. self._resizeZoomDialog(true);
  1816. if ($btnBord.hasClass('active')) {
  1817. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1818. }
  1819. }
  1820. }
  1821. } else {
  1822. if (!fullScreen) {
  1823. self._maximizeZoomDialog();
  1824. return;
  1825. }
  1826. $h.toggleFullScreen(true);
  1827. }
  1828. $modal.focus();
  1829. },
  1830. _setZoomContent: function ($frame, animate) {
  1831. var self = this, $content, tmplt, body, title, $body, $dataEl, config, previewId = $frame.attr('id'),
  1832. $zoomPreview = self.$preview.find('#zoom-' + previewId), $modal = self.$modal, $tmp,
  1833. $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'), cap, size,
  1834. $btnTogh = $modal.find('.btn-toggleheader');
  1835. tmplt = $zoomPreview.attr('data-template') || 'generic';
  1836. $content = $zoomPreview.find('.kv-file-content');
  1837. body = $content.length ? $content.html() : '';
  1838. cap = $frame.data('caption') || '';
  1839. size = $frame.data('size') || '';
  1840. title = cap + ' ' + size;
  1841. $modal.find('.kv-zoom-title').attr('title', $('<div/>').html(title).text()).html(title);
  1842. $body = $modal.find('.kv-zoom-body');
  1843. $modal.removeClass('kv-single-content');
  1844. if (animate) {
  1845. $tmp = $body.addClass('file-thumb-loading').clone().insertAfter($body);
  1846. $body.html(body).hide();
  1847. $tmp.fadeOut('fast', function () {
  1848. $body.fadeIn('fast', function () {
  1849. $body.removeClass('file-thumb-loading');
  1850. });
  1851. $tmp.remove();
  1852. });
  1853. } else {
  1854. $body.html(body);
  1855. }
  1856. config = self.previewZoomSettings[tmplt];
  1857. if (config) {
  1858. $dataEl = $body.find('.kv-preview-data');
  1859. $h.addCss($dataEl, 'file-zoom-detail');
  1860. $.each(config, function (key, value) {
  1861. $dataEl.css(key, value);
  1862. if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
  1863. $dataEl.removeAttr(key);
  1864. }
  1865. });
  1866. }
  1867. $modal.data('previewId', previewId);
  1868. self._handler($modal.find('.btn-prev'), 'click', function () {
  1869. self._zoomSlideShow('prev', previewId);
  1870. });
  1871. self._handler($modal.find('.btn-next'), 'click', function () {
  1872. self._zoomSlideShow('next', previewId);
  1873. });
  1874. self._handler($btnFull, 'click', function () {
  1875. self._resizeZoomDialog(true);
  1876. });
  1877. self._handler($btnBord, 'click', function () {
  1878. self._resizeZoomDialog(false);
  1879. });
  1880. self._handler($btnTogh, 'click', function () {
  1881. var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'),
  1882. ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
  1883. var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
  1884. if ($modal.hasClass('file-zoom-fullscreen')) {
  1885. h = $body.outerHeight(true);
  1886. if (!height) {
  1887. h = h - $header.outerHeight(true);
  1888. }
  1889. }
  1890. $body.css('height', height ? h + height : h);
  1891. };
  1892. if ($header.is(':visible')) {
  1893. ht = $header.outerHeight(true);
  1894. $header.slideUp('slow', function () {
  1895. $actions.find('.btn').appendTo($floatBar);
  1896. resize(ht);
  1897. });
  1898. } else {
  1899. $floatBar.find('.btn').appendTo($actions);
  1900. $header.slideDown('slow', function () {
  1901. resize();
  1902. });
  1903. }
  1904. $modal.focus();
  1905. });
  1906. self._handler($modal, 'keydown', function (e) {
  1907. var key = e.which || e.keyCode, $prev = $(this).find('.btn-prev'), $next = $(this).find('.btn-next'),
  1908. vId = $(this).data('previewId'), vPrevKey = self.rtl ? 39 : 37, vNextKey = self.rtl ? 37 : 39;
  1909. if (key === vPrevKey && $prev.length && !$prev.attr('disabled')) {
  1910. self._zoomSlideShow('prev', vId);
  1911. }
  1912. if (key === vNextKey && $next.length && !$next.attr('disabled')) {
  1913. self._zoomSlideShow('next', vId);
  1914. }
  1915. });
  1916. },
  1917. _zoomPreview: function ($btn) {
  1918. var self = this, $frame, $modal = self.$modal;
  1919. if (!$btn.length) {
  1920. throw 'Cannot zoom to detailed preview!';
  1921. }
  1922. $h.initModal($modal);
  1923. $modal.html(self._getModalContent());
  1924. $frame = $btn.closest($h.FRAMES);
  1925. self._setZoomContent($frame);
  1926. $modal.modal('show');
  1927. self._initZoomButtons();
  1928. },
  1929. _zoomSlideShow: function (dir, previewId) {
  1930. var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i,
  1931. thumbs = self.getFrames().toArray(), len = thumbs.length, out;
  1932. if ($btn.attr('disabled')) {
  1933. return;
  1934. }
  1935. for (i = 0; i < len; i++) {
  1936. if ($(thumbs[i]).attr('id') === previewId) {
  1937. out = dir === 'prev' ? i - 1 : i + 1;
  1938. break;
  1939. }
  1940. }
  1941. if (out < 0 || out >= len || !thumbs[out]) {
  1942. return;
  1943. }
  1944. $targFrame = $(thumbs[out]);
  1945. if ($targFrame.length) {
  1946. self._setZoomContent($targFrame, true);
  1947. }
  1948. self._initZoomButtons();
  1949. self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
  1950. },
  1951. _initZoomButton: function () {
  1952. var self = this;
  1953. self.$preview.find('.kv-file-zoom').each(function () {
  1954. var $el = $(this);
  1955. self._handler($el, 'click', function () {
  1956. self._zoomPreview($el);
  1957. });
  1958. });
  1959. },
  1960. _inputFileCount: function () {
  1961. return this.$element.get(0).files.length;
  1962. },
  1963. _refreshPreview: function () {
  1964. var self = this, files;
  1965. if ((!self._inputFileCount() && !self.isAjaxUpload) || !self.showPreview || !self.isPreviewable) {
  1966. return;
  1967. }
  1968. if (self.isAjaxUpload) {
  1969. files = self.getFileStack();
  1970. self.filestack = [];
  1971. if (files.length) {
  1972. self._clearFileInput();
  1973. } else {
  1974. files = self.$element.get(0).files;
  1975. }
  1976. } else {
  1977. files = self.$element.get(0).files;
  1978. }
  1979. if (files && files.length) {
  1980. self.readFiles(files);
  1981. self._setFileDropZoneTitle();
  1982. }
  1983. },
  1984. _clearObjects: function ($el) {
  1985. $el.find('video audio').each(function () {
  1986. this.pause();
  1987. $(this).remove();
  1988. });
  1989. $el.find('img object div').each(function () {
  1990. $(this).remove();
  1991. });
  1992. },
  1993. _clearFileInput: function () {
  1994. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1995. if (!self._inputFileCount()) {
  1996. return;
  1997. }
  1998. $srcFrm = $el.closest('form');
  1999. $tmpFrm = $(document.createElement('form'));
  2000. $tmpEl = $(document.createElement('div'));
  2001. $el.before($tmpEl);
  2002. if ($srcFrm.length) {
  2003. $srcFrm.after($tmpFrm);
  2004. } else {
  2005. $tmpEl.after($tmpFrm);
  2006. }
  2007. $tmpFrm.append($el).trigger('reset');
  2008. $tmpEl.before($el).remove();
  2009. $tmpFrm.remove();
  2010. },
  2011. _resetUpload: function () {
  2012. var self = this;
  2013. self.uploadCache = {content: [], config: [], tags: [], append: true};
  2014. self.uploadCount = 0;
  2015. self.uploadStatus = {};
  2016. self.uploadLog = [];
  2017. self.uploadAsyncCount = 0;
  2018. self.loadedImages = [];
  2019. self.totalImagesCount = 0;
  2020. self.$btnUpload.removeAttr('disabled');
  2021. self._setProgress(0);
  2022. self.$progress.hide();
  2023. self._resetErrors(false);
  2024. self.ajaxAborted = false;
  2025. self.ajaxRequests = [];
  2026. self._resetCanvas();
  2027. self.cacheInitialPreview = {};
  2028. if (self.overwriteInitial) {
  2029. self.initialPreview = [];
  2030. self.initialPreviewConfig = [];
  2031. self.initialPreviewThumbTags = [];
  2032. self.previewCache.data = {
  2033. content: [],
  2034. config: [],
  2035. tags: []
  2036. };
  2037. }
  2038. },
  2039. _resetCanvas: function () {
  2040. var self = this;
  2041. if (self.canvas && self.imageCanvasContext) {
  2042. self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
  2043. }
  2044. },
  2045. _hasInitialPreview: function () {
  2046. var self = this;
  2047. return !self.overwriteInitial && self.previewCache.count();
  2048. },
  2049. _resetPreview: function () {
  2050. var self = this, out, cap;
  2051. if (self.previewCache.count()) {
  2052. out = self.previewCache.out();
  2053. self._setPreviewContent(out.content);
  2054. self._setInitThumbAttr();
  2055. cap = self.initialCaption ? self.initialCaption : out.caption;
  2056. self._setCaption(cap);
  2057. } else {
  2058. self._clearPreview();
  2059. self._initCaption();
  2060. }
  2061. if (self.showPreview) {
  2062. self._initZoom();
  2063. self._initSortable();
  2064. }
  2065. },
  2066. _clearDefaultPreview: function () {
  2067. var self = this;
  2068. self.$preview.find('.file-default-preview').remove();
  2069. },
  2070. _validateDefaultPreview: function () {
  2071. var self = this;
  2072. if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) {
  2073. return;
  2074. }
  2075. self._setPreviewContent('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  2076. self.$container.removeClass('file-input-new');
  2077. self._initClickable();
  2078. },
  2079. _resetPreviewThumbs: function (isAjax) {
  2080. var self = this, out;
  2081. if (isAjax) {
  2082. self._clearPreview();
  2083. self.clearStack();
  2084. return;
  2085. }
  2086. if (self._hasInitialPreview()) {
  2087. out = self.previewCache.out();
  2088. self._setPreviewContent(out.content);
  2089. self._setInitThumbAttr();
  2090. self._setCaption(out.caption);
  2091. self._initPreviewActions();
  2092. } else {
  2093. self._clearPreview();
  2094. }
  2095. },
  2096. _getLayoutTemplate: function (t) {
  2097. var self = this, template = self.layoutTemplates[t];
  2098. if ($h.isEmpty(self.customLayoutTags)) {
  2099. return template;
  2100. }
  2101. return $h.replaceTags(template, self.customLayoutTags);
  2102. },
  2103. _getPreviewTemplate: function (t) {
  2104. var self = this, template = self.previewTemplates[t];
  2105. if ($h.isEmpty(self.customPreviewTags)) {
  2106. return template;
  2107. }
  2108. return $h.replaceTags(template, self.customPreviewTags);
  2109. },
  2110. _getOutData: function (jqXHR, responseData, filesData) {
  2111. var self = this;
  2112. jqXHR = jqXHR || {};
  2113. responseData = responseData || {};
  2114. filesData = filesData || self.filestack.slice(0) || {};
  2115. return {
  2116. form: self.formdata,
  2117. files: filesData,
  2118. filenames: self.filenames,
  2119. filescount: self.getFilesCount(),
  2120. extra: self._getExtraData(),
  2121. response: responseData,
  2122. reader: self.reader,
  2123. jqXHR: jqXHR
  2124. };
  2125. },
  2126. _getMsgSelected: function (n) {
  2127. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  2128. return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected;
  2129. },
  2130. _getFrame: function (id) {
  2131. var self = this, $frame = $('#' + id);
  2132. if (!$frame.length) {
  2133. self._log('Invalid thumb frame with id: "' + id + '".');
  2134. return null;
  2135. }
  2136. return $frame;
  2137. },
  2138. _getThumbs: function (css) {
  2139. css = css || '';
  2140. return this.getFrames(':not(.file-preview-initial)' + css);
  2141. },
  2142. _getExtraData: function (previewId, index) {
  2143. var self = this, data = self.uploadExtraData;
  2144. if (typeof self.uploadExtraData === 'function') {
  2145. data = self.uploadExtraData(previewId, index);
  2146. }
  2147. return data;
  2148. },
  2149. _initXhr: function (xhrobj, previewId, fileCount) {
  2150. var self = this;
  2151. if (xhrobj.upload) {
  2152. xhrobj.upload.addEventListener('progress', function (event) {
  2153. var pct = 0, total = event.total, position = event.loaded || event.position;
  2154. /** @namespace event.lengthComputable */
  2155. if (event.lengthComputable) {
  2156. pct = Math.floor(position / total * 100);
  2157. }
  2158. if (previewId) {
  2159. self._setAsyncUploadStatus(previewId, pct, fileCount);
  2160. } else {
  2161. self._setProgress(pct);
  2162. }
  2163. }, false);
  2164. }
  2165. return xhrobj;
  2166. },
  2167. _initAjaxSettings: function () {
  2168. var self = this;
  2169. self._ajaxSettings = $.extend(true, {}, self.ajaxSettings);
  2170. self._ajaxDeleteSettings = $.extend(true, {}, self.ajaxDeleteSettings);
  2171. },
  2172. _mergeAjaxCallback: function (funcName, srcFunc, type) {
  2173. var self = this, settings = self._ajaxSettings, flag = self.mergeAjaxCallbacks, targFunc;
  2174. if (type === 'delete') {
  2175. settings = self._ajaxDeleteSettings;
  2176. flag = self.mergeAjaxDeleteCallbacks;
  2177. }
  2178. targFunc = settings[funcName];
  2179. if (flag && typeof targFunc === 'function') {
  2180. if (flag === 'before') {
  2181. settings[funcName] = function () {
  2182. targFunc.apply(this, arguments);
  2183. srcFunc.apply(this, arguments);
  2184. };
  2185. } else {
  2186. settings[funcName] = function () {
  2187. srcFunc.apply(this, arguments);
  2188. targFunc.apply(this, arguments);
  2189. };
  2190. }
  2191. } else {
  2192. settings[funcName] = srcFunc;
  2193. }
  2194. },
  2195. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  2196. var self = this, settings, vUrl;
  2197. if (!self._raise('filepreajax', [previewId, index])) {
  2198. return;
  2199. }
  2200. self._uploadExtra(previewId, index);
  2201. self._initAjaxSettings();
  2202. self._mergeAjaxCallback('beforeSend', fnBefore);
  2203. self._mergeAjaxCallback('success', fnSuccess);
  2204. self._mergeAjaxCallback('complete', fnComplete);
  2205. self._mergeAjaxCallback('error', fnError);
  2206. vUrl = index && self.uploadUrlThumb ? self.uploadUrlThumb : self.uploadUrl;
  2207. settings = $.extend(true, {}, {
  2208. xhr: function () {
  2209. var xhrobj = $.ajaxSettings.xhr();
  2210. return self._initXhr(xhrobj, previewId, self.getFileStack().length);
  2211. },
  2212. url: self._encodeURI(vUrl),
  2213. type: 'POST',
  2214. dataType: 'json',
  2215. data: self.formdata,
  2216. cache: false,
  2217. processData: false,
  2218. contentType: false
  2219. }, self._ajaxSettings);
  2220. self.ajaxRequests.push($.ajax(settings));
  2221. },
  2222. _mergeArray: function (prop, content) {
  2223. var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content);
  2224. self[prop] = arr1.concat(arr2);
  2225. },
  2226. _initUploadSuccess: function (out, $thumb, allFiles) {
  2227. var self = this, append, data, index, $div, $newCache, content, config, tags, i;
  2228. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  2229. return;
  2230. }
  2231. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  2232. self.hasInitData = true;
  2233. content = out.initialPreview || [];
  2234. config = out.initialPreviewConfig || [];
  2235. tags = out.initialPreviewThumbTags || [];
  2236. append = out.append === undefined || out.append;
  2237. if (content.length > 0 && !$h.isArray(content)) {
  2238. content = content.split(self.initialPreviewDelimiter);
  2239. }
  2240. self._mergeArray('initialPreview', content);
  2241. self._mergeArray('initialPreviewConfig', config);
  2242. self._mergeArray('initialPreviewThumbTags', tags);
  2243. if ($thumb !== undefined) {
  2244. if (!allFiles) {
  2245. index = self.previewCache.add(content, config[0], tags[0], append);
  2246. data = self.previewCache.get(index, false);
  2247. $div = $(document.createElement('div')).html(data).hide().insertAfter($thumb);
  2248. $newCache = $div.find('.kv-zoom-cache');
  2249. if ($newCache && $newCache.length) {
  2250. $newCache.insertAfter($thumb);
  2251. }
  2252. $thumb.fadeOut('slow', function () {
  2253. var $newThumb = $div.find('.file-preview-frame');
  2254. if ($newThumb && $newThumb.length) {
  2255. $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');
  2256. }
  2257. self._initPreviewActions();
  2258. self._clearFileInput();
  2259. $h.cleanZoomCache(self.$preview.find('#zoom-' + $thumb.attr('id')));
  2260. $thumb.remove();
  2261. $div.remove();
  2262. self._initSortable();
  2263. });
  2264. } else {
  2265. i = $thumb.attr('data-fileindex');
  2266. self.uploadCache.content[i] = content[0];
  2267. self.uploadCache.config[i] = config[0] || [];
  2268. self.uploadCache.tags[i] = tags[0] || [];
  2269. self.uploadCache.append = append;
  2270. }
  2271. } else {
  2272. self.previewCache.set(content, config, tags, append);
  2273. self._initPreview();
  2274. self._initPreviewActions();
  2275. }
  2276. }
  2277. },
  2278. _initSuccessThumbs: function () {
  2279. var self = this;
  2280. if (!self.showPreview) {
  2281. return;
  2282. }
  2283. self._getThumbs($h.FRAMES + '.file-preview-success').each(function () {
  2284. var $thumb = $(this), $preview = self.$preview, $remove = $thumb.find('.kv-file-remove');
  2285. $remove.removeAttr('disabled');
  2286. self._handler($remove, 'click', function () {
  2287. var id = $thumb.attr('id'),
  2288. out = self._raise('filesuccessremove', [id, $thumb.attr('data-fileindex')]);
  2289. $h.cleanMemory($thumb);
  2290. if (out === false) {
  2291. return;
  2292. }
  2293. $thumb.fadeOut('slow', function () {
  2294. $h.cleanZoomCache($preview.find('#zoom-' + id));
  2295. $thumb.remove();
  2296. if (!self.getFrames().length) {
  2297. self.reset();
  2298. }
  2299. });
  2300. });
  2301. });
  2302. },
  2303. _checkAsyncComplete: function () {
  2304. var self = this, previewId, i;
  2305. for (i = 0; i < self.filestack.length; i++) {
  2306. if (self.filestack[i]) {
  2307. previewId = self.previewInitId + '-' + i;
  2308. if ($.inArray(previewId, self.uploadLog) === -1) {
  2309. return false;
  2310. }
  2311. }
  2312. }
  2313. return (self.uploadAsyncCount === self.uploadLog.length);
  2314. },
  2315. _uploadExtra: function (previewId, index) {
  2316. var self = this, data = self._getExtraData(previewId, index);
  2317. if (data.length === 0) {
  2318. return;
  2319. }
  2320. $.each(data, function (key, value) {
  2321. self.formdata.append(key, value);
  2322. });
  2323. },
  2324. _uploadSingle: function (i, isBatch) {
  2325. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  2326. previewId = self.previewInitId + '-' + i, $thumb, chkComplete, $btnUpload, $btnDelete,
  2327. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData), uploadFailed,
  2328. $prog = $('#' + previewId).find('.file-thumb-progress'), fnBefore, fnSuccess, fnComplete, fnError,
  2329. updateUploadLog, params = {id: previewId, index: i};
  2330. self.formdata = formdata;
  2331. if (self.showPreview) {
  2332. $thumb = $('#' + previewId + ':not(.file-preview-initial)');
  2333. $btnUpload = $thumb.find('.kv-file-upload');
  2334. $btnDelete = $thumb.find('.kv-file-remove');
  2335. $prog.show();
  2336. }
  2337. if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self._abort(params)) {
  2338. return;
  2339. }
  2340. updateUploadLog = function (i, previewId) {
  2341. if (!uploadFailed) {
  2342. self.updateStack(i, undefined);
  2343. }
  2344. self.uploadLog.push(previewId);
  2345. if (self._checkAsyncComplete()) {
  2346. self.fileBatchCompleted = true;
  2347. }
  2348. };
  2349. chkComplete = function () {
  2350. var u = self.uploadCache, $initThumbs, i, j, len = 0, data = self.cacheInitialPreview;
  2351. if (!self.fileBatchCompleted) {
  2352. return;
  2353. }
  2354. if (data && data.content) {
  2355. len = data.content.length;
  2356. }
  2357. setTimeout(function () {
  2358. var triggerReset = self.getFileStack(true).length === 0;
  2359. if (self.showPreview) {
  2360. self.previewCache.set(u.content, u.config, u.tags, u.append);
  2361. if (len) {
  2362. for (i = 0; i < u.content.length; i++) {
  2363. j = i + len;
  2364. data.content[j] = u.content[i];
  2365. //noinspection JSUnresolvedVariable
  2366. if (data.config.length) {
  2367. data.config[j] = u.config[i];
  2368. }
  2369. if (data.tags.length) {
  2370. data.tags[j] = u.tags[i];
  2371. }
  2372. }
  2373. self.initialPreview = $h.cleanArray(data.content);
  2374. self.initialPreviewConfig = $h.cleanArray(data.config);
  2375. self.initialPreviewThumbTags = $h.cleanArray(data.tags);
  2376. } else {
  2377. self.initialPreview = u.content;
  2378. self.initialPreviewConfig = u.config;
  2379. self.initialPreviewThumbTags = u.tags;
  2380. }
  2381. self.cacheInitialPreview = {};
  2382. if (self.hasInitData) {
  2383. self._initPreview();
  2384. self._initPreviewActions();
  2385. }
  2386. }
  2387. self.unlock(triggerReset);
  2388. if (triggerReset) {
  2389. self._clearFileInput();
  2390. }
  2391. $initThumbs = self.$preview.find('.file-preview-initial');
  2392. if (self.uploadAsync && $initThumbs.length) {
  2393. $h.addCss($initThumbs, $h.SORT_CSS);
  2394. self._initSortable();
  2395. }
  2396. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2397. self.uploadCount = 0;
  2398. self.uploadStatus = {};
  2399. self.uploadLog = [];
  2400. self._setProgress(101);
  2401. self.ajaxAborted = false;
  2402. }, 100);
  2403. };
  2404. fnBefore = function (jqXHR) {
  2405. outData = self._getOutData(jqXHR);
  2406. self.fileBatchCompleted = false;
  2407. if (!isBatch) {
  2408. self.ajaxAborted = false;
  2409. }
  2410. if (self.showPreview) {
  2411. if (!$thumb.hasClass('file-preview-success')) {
  2412. self._setThumbStatus($thumb, 'Loading');
  2413. $h.addCss($thumb, 'file-uploading');
  2414. }
  2415. $btnUpload.attr('disabled', true);
  2416. $btnDelete.attr('disabled', true);
  2417. }
  2418. if (!isBatch) {
  2419. self.lock();
  2420. }
  2421. self._raise('filepreupload', [outData, previewId, i]);
  2422. $.extend(true, params, outData);
  2423. if (self._abort(params)) {
  2424. jqXHR.abort();
  2425. if (!isBatch) {
  2426. self._setThumbStatus($thumb, 'New');
  2427. $thumb.removeClass('file-uploading');
  2428. $btnUpload.removeAttr('disabled');
  2429. $btnDelete.removeAttr('disabled');
  2430. self.unlock();
  2431. }
  2432. self._setProgressCancelled();
  2433. }
  2434. };
  2435. fnSuccess = function (data, textStatus, jqXHR) {
  2436. var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
  2437. outData = self._getOutData(jqXHR, data);
  2438. $.extend(true, params, outData);
  2439. setTimeout(function () {
  2440. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2441. if (self.showPreview) {
  2442. self._setThumbStatus($thumb, 'Success');
  2443. $btnUpload.hide();
  2444. self._initUploadSuccess(data, $thumb, isBatch);
  2445. self._setProgress(101, $prog);
  2446. }
  2447. self._raise('fileuploaded', [outData, pid, i]);
  2448. if (!isBatch) {
  2449. self.updateStack(i, undefined);
  2450. } else {
  2451. updateUploadLog(i, pid);
  2452. }
  2453. } else {
  2454. uploadFailed = true;
  2455. self._showUploadError(data.error, params);
  2456. self._setPreviewError($thumb, i, self.filestack[i], self.retryErrorUploads);
  2457. if (!self.retryErrorUploads) {
  2458. $btnUpload.hide();
  2459. }
  2460. if (isBatch) {
  2461. updateUploadLog(i, pid);
  2462. }
  2463. self._setProgress(101, $('#' + pid).find('.file-thumb-progress'), self.msgUploadError);
  2464. }
  2465. }, 100);
  2466. };
  2467. fnComplete = function () {
  2468. setTimeout(function () {
  2469. if (self.showPreview) {
  2470. $btnUpload.removeAttr('disabled');
  2471. $btnDelete.removeAttr('disabled');
  2472. $thumb.removeClass('file-uploading');
  2473. }
  2474. if (!isBatch) {
  2475. self.unlock(false);
  2476. self._clearFileInput();
  2477. } else {
  2478. chkComplete();
  2479. }
  2480. self._initSuccessThumbs();
  2481. }, 100);
  2482. };
  2483. fnError = function (jqXHR, textStatus, errorThrown) {
  2484. var op = self.ajaxOperations.uploadThumb,
  2485. errMsg = self._parseError(op, jqXHR, errorThrown,
  2486. (isBatch && self.filestack[i].name ? self.filestack[i].name : null));
  2487. uploadFailed = true;
  2488. setTimeout(function () {
  2489. if (isBatch) {
  2490. updateUploadLog(i, previewId);
  2491. }
  2492. self.uploadStatus[previewId] = 100;
  2493. self._setPreviewError($thumb, i, self.filestack[i], self.retryErrorUploads);
  2494. if (!self.retryErrorUploads) {
  2495. $btnUpload.hide();
  2496. }
  2497. $.extend(true, params, self._getOutData(jqXHR));
  2498. self._setProgress(101, $prog, self.msgAjaxProgressError.replace('{operation}', op));
  2499. self._setProgress(101, $('#' + previewId).find('.file-thumb-progress'), self.msgUploadError);
  2500. self._showUploadError(errMsg, params);
  2501. }, 100);
  2502. };
  2503. formdata.append(self.uploadFileAttr, self.filestack[i], self.filenames[i]);
  2504. formdata.append('file_id', i);
  2505. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  2506. },
  2507. _uploadBatch: function () {
  2508. var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError,
  2509. fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  2510. setAllUploaded;
  2511. self.formdata = new FormData();
  2512. if (total === 0 || !hasPostData || self._abort(params)) {
  2513. return;
  2514. }
  2515. setAllUploaded = function () {
  2516. $.each(files, function (key) {
  2517. self.updateStack(key, undefined);
  2518. });
  2519. self._clearFileInput();
  2520. };
  2521. fnBefore = function (jqXHR) {
  2522. self.lock();
  2523. var outData = self._getOutData(jqXHR);
  2524. self.ajaxAborted = false;
  2525. if (self.showPreview) {
  2526. self._getThumbs().each(function () {
  2527. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  2528. $btnDelete = $thumb.find('.kv-file-remove');
  2529. if (!$thumb.hasClass('file-preview-success')) {
  2530. self._setThumbStatus($thumb, 'Loading');
  2531. $h.addCss($thumb, 'file-uploading');
  2532. }
  2533. $btnUpload.attr('disabled', true);
  2534. $btnDelete.attr('disabled', true);
  2535. });
  2536. }
  2537. self._raise('filebatchpreupload', [outData]);
  2538. if (self._abort(outData)) {
  2539. jqXHR.abort();
  2540. self._getThumbs().each(function () {
  2541. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  2542. $btnDelete = $thumb.find('.kv-file-remove');
  2543. if ($thumb.hasClass('file-preview-loading')) {
  2544. self._setThumbStatus($thumb, 'New');
  2545. $thumb.removeClass('file-uploading');
  2546. }
  2547. $btnUpload.removeAttr('disabled');
  2548. $btnDelete.removeAttr('disabled');
  2549. });
  2550. self._setProgressCancelled();
  2551. }
  2552. };
  2553. fnSuccess = function (data, textStatus, jqXHR) {
  2554. /** @namespace data.errorkeys */
  2555. var outData = self._getOutData(jqXHR, data), key = 0,
  2556. $thumbs = self._getThumbs(':not(.file-preview-success)'),
  2557. keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys;
  2558. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2559. self._raise('filebatchuploadsuccess', [outData]);
  2560. setAllUploaded();
  2561. if (self.showPreview) {
  2562. $thumbs.each(function () {
  2563. var $thumb = $(this);
  2564. self._setThumbStatus($thumb, 'Success');
  2565. $thumb.removeClass('file-uploading');
  2566. $thumb.find('.kv-file-upload').hide().removeAttr('disabled');
  2567. });
  2568. self._initUploadSuccess(data);
  2569. } else {
  2570. self.reset();
  2571. }
  2572. self._setProgress(101);
  2573. } else {
  2574. if (self.showPreview) {
  2575. $thumbs.each(function () {
  2576. var $thumb = $(this), i = $thumb.attr('data-fileindex');
  2577. $thumb.removeClass('file-uploading');
  2578. $thumb.find('.kv-file-upload').removeAttr('disabled');
  2579. $thumb.find('.kv-file-remove').removeAttr('disabled');
  2580. if (keys.length === 0 || $.inArray(key, keys) !== -1) {
  2581. self._setPreviewError($thumb, i, self.filestack[i], self.retryErrorUploads);
  2582. if (!self.retryErrorUploads) {
  2583. $thumb.find('.kv-file-upload').hide();
  2584. self.updateStack(i, undefined);
  2585. }
  2586. } else {
  2587. $thumb.find('.kv-file-upload').hide();
  2588. self._setThumbStatus($thumb, 'Success');
  2589. self.updateStack(i, undefined);
  2590. }
  2591. if (!$thumb.hasClass('file-preview-error') || self.retryErrorUploads) {
  2592. key++;
  2593. }
  2594. });
  2595. self._initUploadSuccess(data);
  2596. }
  2597. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  2598. self._setProgress(101, self.$progress, self.msgUploadError);
  2599. }
  2600. };
  2601. fnComplete = function () {
  2602. self.unlock();
  2603. self._initSuccessThumbs();
  2604. self._clearFileInput();
  2605. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2606. };
  2607. fnError = function (jqXHR, textStatus, errorThrown) {
  2608. var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadBatch,
  2609. errMsg = self._parseError(op, jqXHR, errorThrown);
  2610. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2611. self.uploadFileCount = total - 1;
  2612. if (!self.showPreview) {
  2613. return;
  2614. }
  2615. self._getThumbs().each(function () {
  2616. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  2617. $thumb.removeClass('file-uploading');
  2618. if (self.filestack[key] !== undefined) {
  2619. self._setPreviewError($thumb);
  2620. }
  2621. });
  2622. self._getThumbs().removeClass('file-uploading');
  2623. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  2624. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  2625. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  2626. };
  2627. $.each(files, function (key, data) {
  2628. if (!$h.isEmpty(files[key])) {
  2629. self.formdata.append(self.uploadFileAttr, data, self.filenames[key]);
  2630. }
  2631. });
  2632. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2633. },
  2634. _uploadExtraOnly: function () {
  2635. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  2636. self.formdata = new FormData();
  2637. if (self._abort(params)) {
  2638. return;
  2639. }
  2640. fnBefore = function (jqXHR) {
  2641. self.lock();
  2642. var outData = self._getOutData(jqXHR);
  2643. self._raise('filebatchpreupload', [outData]);
  2644. self._setProgress(50);
  2645. params.data = outData;
  2646. params.xhr = jqXHR;
  2647. if (self._abort(params)) {
  2648. jqXHR.abort();
  2649. self._setProgressCancelled();
  2650. }
  2651. };
  2652. fnSuccess = function (data, textStatus, jqXHR) {
  2653. var outData = self._getOutData(jqXHR, data);
  2654. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2655. self._raise('filebatchuploadsuccess', [outData]);
  2656. self._clearFileInput();
  2657. self._initUploadSuccess(data);
  2658. self._setProgress(101);
  2659. } else {
  2660. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  2661. }
  2662. };
  2663. fnComplete = function () {
  2664. self.unlock();
  2665. self._clearFileInput();
  2666. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2667. };
  2668. fnError = function (jqXHR, textStatus, errorThrown) {
  2669. var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadExtra,
  2670. errMsg = self._parseError(op, jqXHR, errorThrown);
  2671. params.data = outData;
  2672. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2673. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  2674. };
  2675. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2676. },
  2677. _deleteFileIndex: function ($frame) {
  2678. var self = this, ind = $frame.attr('data-fileindex'), rev = self.reversePreviewOrder;
  2679. if (ind.substring(0, 5) === 'init_') {
  2680. ind = parseInt(ind.replace('init_', ''));
  2681. self.initialPreview = $h.spliceArray(self.initialPreview, ind, rev);
  2682. self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind, rev);
  2683. self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind, rev);
  2684. self.getFrames().each(function () {
  2685. var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex');
  2686. if (nInd.substring(0, 5) === 'init_') {
  2687. nInd = parseInt(nInd.replace('init_', ''));
  2688. if (nInd > ind) {
  2689. nInd--;
  2690. $nFrame.attr('data-fileindex', 'init_' + nInd);
  2691. }
  2692. }
  2693. });
  2694. if (self.uploadAsync) {
  2695. self.cacheInitialPreview = self.getPreview();
  2696. }
  2697. }
  2698. },
  2699. _initFileActions: function () {
  2700. var self = this, $preview = self.$preview;
  2701. if (!self.showPreview) {
  2702. return;
  2703. }
  2704. self._initZoomButton();
  2705. self.getFrames(' .kv-file-remove').each(function () {
  2706. var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'),
  2707. ind = $frame.attr('data-fileindex'), n, cap, status;
  2708. self._handler($el, 'click', function () {
  2709. status = self._raise('filepreremove', [id, ind]);
  2710. if (status === false || !self._validateMinCount()) {
  2711. return false;
  2712. }
  2713. hasError = $frame.hasClass('file-preview-error');
  2714. $h.cleanMemory($frame);
  2715. $frame.fadeOut('slow', function () {
  2716. $h.cleanZoomCache($preview.find('#zoom-' + id));
  2717. self.updateStack(ind, undefined);
  2718. self._clearObjects($frame);
  2719. $frame.remove();
  2720. if (id && hasError) {
  2721. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () {
  2722. $(this).remove();
  2723. if (!self._errorsExist()) {
  2724. self._resetErrors();
  2725. }
  2726. });
  2727. }
  2728. self._clearFileInput();
  2729. var filestack = self.getFileStack(true), chk = self.previewCache.count(),
  2730. len = filestack.length, hasThumb = self.showPreview && self.getFrames().length;
  2731. if (len === 0 && chk === 0 && !hasThumb) {
  2732. self.reset();
  2733. } else {
  2734. n = chk + len;
  2735. cap = n > 1 ? self._getMsgSelected(n) : (filestack[0] ? self._getFileNames()[0] : '');
  2736. self._setCaption(cap);
  2737. }
  2738. self._raise('fileremoved', [id, ind]);
  2739. });
  2740. });
  2741. });
  2742. self.getFrames(' .kv-file-upload').each(function () {
  2743. var $el = $(this);
  2744. self._handler($el, 'click', function () {
  2745. var $frame = $el.closest($h.FRAMES), ind = $frame.attr('data-fileindex');
  2746. self.$progress.hide();
  2747. if ($frame.hasClass('file-preview-error') && !self.retryErrorUploads) {
  2748. return;
  2749. }
  2750. self._uploadSingle(ind, false);
  2751. });
  2752. });
  2753. },
  2754. _initPreviewActions: function () {
  2755. var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {},
  2756. btnRemove = $h.FRAMES + ' .kv-file-remove', settings = self.fileActionSettings,
  2757. origClass = settings.removeClass, errClass = settings.removeErrorClass,
  2758. resetProgress = function () {
  2759. var hasFiles = self.isAjaxUpload ? self.previewCache.count() : self._inputFileCount();
  2760. if (!$preview.find($h.FRAMES).length && !hasFiles) {
  2761. self._setCaption('');
  2762. self.reset();
  2763. self.initialCaption = '';
  2764. }
  2765. };
  2766. self._initZoomButton();
  2767. $preview.find(btnRemove).each(function () {
  2768. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'),
  2769. fnBefore, fnSuccess, fnError;
  2770. if ($h.isEmpty(vUrl) || vKey === undefined) {
  2771. return;
  2772. }
  2773. var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data,
  2774. settings, params, index = $frame.attr('data-fileindex'), config, extraData;
  2775. index = parseInt(index.replace('init_', ''));
  2776. config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index];
  2777. extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra;
  2778. if (typeof extraData === 'function') {
  2779. extraData = extraData();
  2780. }
  2781. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  2782. fnBefore = function (jqXHR) {
  2783. self.ajaxAborted = false;
  2784. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  2785. if (self._abort()) {
  2786. jqXHR.abort();
  2787. } else {
  2788. $el.removeClass(errClass);
  2789. $h.addCss($frame, 'file-uploading');
  2790. $h.addCss($el, 'disabled ' + origClass);
  2791. }
  2792. };
  2793. fnSuccess = function (data, textStatus, jqXHR) {
  2794. var n, cap;
  2795. if (!$h.isEmpty(data) && !$h.isEmpty(data.error)) {
  2796. params.jqXHR = jqXHR;
  2797. params.response = data;
  2798. self._showError(data.error, params, 'filedeleteerror');
  2799. $frame.removeClass('file-uploading');
  2800. $el.removeClass('disabled ' + origClass).addClass(errClass);
  2801. resetProgress();
  2802. return;
  2803. }
  2804. $frame.removeClass('file-uploading').addClass('file-deleted');
  2805. $frame.fadeOut('slow', function () {
  2806. index = parseInt(($frame.attr('data-fileindex')).replace('init_', ''));
  2807. self.previewCache.unset(index);
  2808. self._deleteFileIndex($frame);
  2809. n = self.previewCache.count();
  2810. cap = n > 0 ? self._getMsgSelected(n) : '';
  2811. self._setCaption(cap);
  2812. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  2813. $h.cleanZoomCache($preview.find('#zoom-' + $frame.attr('id')));
  2814. self._clearObjects($frame);
  2815. $frame.remove();
  2816. resetProgress();
  2817. });
  2818. };
  2819. fnError = function (jqXHR, textStatus, errorThrown) {
  2820. var op = self.ajaxOperations.deleteThumb, errMsg = self._parseError(op, jqXHR, errorThrown);
  2821. params.jqXHR = jqXHR;
  2822. params.response = {};
  2823. self._showError(errMsg, params, 'filedeleteerror');
  2824. $frame.removeClass('file-uploading');
  2825. $el.removeClass('disabled ' + origClass).addClass(errClass);
  2826. resetProgress();
  2827. };
  2828. self._initAjaxSettings();
  2829. self._mergeAjaxCallback('beforeSend', fnBefore, 'delete');
  2830. self._mergeAjaxCallback('success', fnSuccess, 'delete');
  2831. self._mergeAjaxCallback('error', fnError, 'delete');
  2832. settings = $.extend(true, {}, {
  2833. url: self._encodeURI(vUrl),
  2834. type: 'POST',
  2835. dataType: 'json',
  2836. data: $.extend(true, {}, {key: vKey}, extraData)
  2837. }, self._ajaxDeleteSettings);
  2838. self._handler($el, 'click', function () {
  2839. if (!self._validateMinCount()) {
  2840. return false;
  2841. }
  2842. self.ajaxAborted = false;
  2843. self._raise('filebeforedelete', [vKey, extraData]);
  2844. //noinspection JSUnresolvedVariable,JSHint
  2845. if (self.ajaxAborted instanceof Promise) {
  2846. self.ajaxAborted.then(function (result) {
  2847. if (!result) {
  2848. $.ajax(settings);
  2849. }
  2850. });
  2851. } else {
  2852. if (!self.ajaxAborted) {
  2853. $.ajax(settings);
  2854. }
  2855. }
  2856. });
  2857. });
  2858. },
  2859. _hideFileIcon: function () {
  2860. var self = this;
  2861. if (self.overwriteInitial) {
  2862. self.$captionContainer.removeClass('icon-visible');
  2863. }
  2864. },
  2865. _showFileIcon: function () {
  2866. var self = this;
  2867. $h.addCss(self.$captionContainer, 'icon-visible');
  2868. },
  2869. _getSize: function (bytes) {
  2870. var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, sizes, out;
  2871. if (!$.isNumeric(bytes) || !$.isNumeric(size)) {
  2872. return '';
  2873. }
  2874. if (typeof func === 'function') {
  2875. out = func(size);
  2876. } else {
  2877. if (size === 0) {
  2878. out = '0.00 B';
  2879. } else {
  2880. i = Math.floor(Math.log(size) / Math.log(1024));
  2881. sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  2882. out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
  2883. }
  2884. }
  2885. return self._getLayoutTemplate('size').replace('{sizeText}', out);
  2886. },
  2887. _getFileType: function (ftype) {
  2888. var self = this;
  2889. return self.mimeTypeAliases[ftype] || ftype;
  2890. },
  2891. _generatePreviewTemplate: function (
  2892. cat,
  2893. data,
  2894. fname,
  2895. ftype,
  2896. previewId,
  2897. isError,
  2898. size,
  2899. frameClass,
  2900. foot,
  2901. ind,
  2902. templ
  2903. ) {
  2904. var self = this, caption = self.slug(fname), prevContent, zoomContent = '', styleAttribs = '',
  2905. screenW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  2906. config = screenW < 400 ? (self.previewSettingsSmall[cat] || self.defaults.previewSettingsSmall[cat]) :
  2907. (self.previewSettings[cat] || self.defaults.previewSettings[cat]),
  2908. footer = foot || self._renderFileFooter(caption, size, 'auto', isError),
  2909. hasIconSetting = self._getPreviewIcon(fname), typeCss = 'type-default',
  2910. forcePrevIcon = hasIconSetting && self.preferIconicPreview,
  2911. forceZoomIcon = hasIconSetting && self.preferIconicZoomPreview, getContent;
  2912. if (config) {
  2913. $.each(config, function (key, val) {
  2914. styleAttribs += key + ':' + val + ';';
  2915. });
  2916. }
  2917. getContent = function (c, d, zoom, frameCss) {
  2918. var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(c),
  2919. css = (frameClass || '') + ' ' + frameCss;
  2920. if (self.frameClass) {
  2921. css = self.frameClass + ' ' + css;
  2922. }
  2923. if (zoom) {
  2924. css = css.replace(' ' + $h.SORT_CSS, '');
  2925. }
  2926. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  2927. if (c === 'text') {
  2928. d = $h.htmlEncode(d);
  2929. }
  2930. if (cat === 'object' && !ftype) {
  2931. $.each(self.defaults.fileTypeSettings, function (key, func) {
  2932. if (key === 'object' || key === 'other') {
  2933. return;
  2934. }
  2935. if (func(fname, ftype)) {
  2936. typeCss = 'type-' + key;
  2937. }
  2938. });
  2939. }
  2940. return tmplt.setTokens({
  2941. 'previewId': id,
  2942. 'caption': caption,
  2943. 'frameClass': css,
  2944. 'type': self._getFileType(ftype),
  2945. 'fileindex': ind,
  2946. 'typeCss': typeCss,
  2947. 'footer': footer,
  2948. 'data': d,
  2949. 'template': templ || cat,
  2950. 'style': styleAttribs ? 'style="' + styleAttribs + '"' : ''
  2951. });
  2952. };
  2953. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  2954. if (self.fileActionSettings.showZoom) {
  2955. zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, 'kv-zoom-thumb');
  2956. }
  2957. zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent);
  2958. prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb');
  2959. return prevContent + zoomContent;
  2960. },
  2961. _addToPreview: function ($preview, content) {
  2962. var self = this;
  2963. return self.reversePreviewOrder ? $preview.prepend(content) : $preview.append(content);
  2964. },
  2965. _previewDefault: function (file, previewId, isDisabled) {
  2966. var self = this, $preview = self.$preview;
  2967. if (!self.showPreview) {
  2968. return;
  2969. }
  2970. var fname = file ? file.name : '', ftype = file ? file.type : '', content, size = file.size || 0,
  2971. caption = self.slug(fname), isError = isDisabled === true && !self.isAjaxUpload,
  2972. data = $h.createObjectURL(file);
  2973. self._clearDefaultPreview();
  2974. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, isError, size);
  2975. self._addToPreview($preview, content);
  2976. self._setThumbAttr(previewId, caption, size);
  2977. if (isDisabled === true && self.isAjaxUpload) {
  2978. self._setThumbStatus($('#' + previewId), 'Error');
  2979. }
  2980. },
  2981. _previewFile: function (i, file, theFile, previewId, data, fileInfo) {
  2982. if (!this.showPreview) {
  2983. return;
  2984. }
  2985. var self = this, fname = file ? file.name : '', ftype = fileInfo.type, caption = fileInfo.name,
  2986. cat = self._parseFileType(ftype, fname), types = self.allowedPreviewTypes, content,
  2987. mimes = self.allowedPreviewMimeTypes, $preview = self.$preview, fsize = file.size || 0,
  2988. chkTypes = types && types.indexOf(cat) >= 0, chkMimes = mimes && mimes.indexOf(ftype) !== -1,
  2989. iData = (cat === 'text' || cat === 'html' || cat === 'image') ? theFile.target.result : data;
  2990. /** @namespace window.DOMPurify */
  2991. if (cat === 'html' && self.purifyHtml && window.DOMPurify) {
  2992. iData = window.DOMPurify.sanitize(iData);
  2993. }
  2994. if (chkTypes || chkMimes) {
  2995. content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, false, fsize);
  2996. self._clearDefaultPreview();
  2997. self._addToPreview($preview, content);
  2998. var $img = $preview.find('#' + previewId + ' img');
  2999. self._validateImageOrientation($img, file, previewId, caption, ftype, fsize, iData);
  3000. } else {
  3001. self._previewDefault(file, previewId);
  3002. }
  3003. self._setThumbAttr(previewId, caption, fsize);
  3004. self._initSortable();
  3005. },
  3006. _setThumbAttr: function (id, caption, size) {
  3007. var self = this, $frame = $('#' + id);
  3008. if ($frame.length) {
  3009. size = size && size > 0 ? self._getSize(size) : '';
  3010. $frame.data({'caption': caption, 'size': size});
  3011. }
  3012. },
  3013. _setInitThumbAttr: function () {
  3014. var self = this, data = self.previewCache.data, len = self.previewCache.count(), config,
  3015. caption, size, previewId;
  3016. if (len === 0) {
  3017. return;
  3018. }
  3019. for (var i = 0; i < len; i++) {
  3020. config = data.config[i];
  3021. previewId = self.previewInitId + '-' + 'init_' + i;
  3022. caption = $h.ifSet('caption', config, $h.ifSet('filename', config));
  3023. size = $h.ifSet('size', config);
  3024. self._setThumbAttr(previewId, caption, size);
  3025. }
  3026. },
  3027. _slugDefault: function (text) {
  3028. // noinspection RegExpRedundantEscape
  3029. return $h.isEmpty(text) ? '' : String(text).replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  3030. },
  3031. _updateFileDetails: function (numFiles) {
  3032. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  3033. name = ($h.isIE(9) && $h.findFileName($el.val())) ||
  3034. ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '',
  3035. label = self.slug(name), n = self.isAjaxUpload ? fileStack.length : numFiles,
  3036. nFiles = self.previewCache.count() + n, log = n === 1 ? label : self._getMsgSelected(nFiles);
  3037. if (self.isError) {
  3038. self.$previewContainer.removeClass('file-thumb-loading');
  3039. self.$previewStatus.html('');
  3040. self.$captionContainer.removeClass('icon-visible');
  3041. } else {
  3042. self._showFileIcon();
  3043. }
  3044. self._setCaption(log, self.isError);
  3045. self.$container.removeClass('file-input-new file-input-ajax-new');
  3046. if (arguments.length === 1) {
  3047. self._raise('fileselect', [numFiles, label]);
  3048. }
  3049. if (self.previewCache.count()) {
  3050. self._initPreviewActions();
  3051. }
  3052. },
  3053. _setThumbStatus: function ($thumb, status) {
  3054. var self = this;
  3055. if (!self.showPreview) {
  3056. return;
  3057. }
  3058. var icon = 'indicator' + status, msg = icon + 'Title',
  3059. css = 'file-preview-' + status.toLowerCase(),
  3060. $indicator = $thumb.find('.file-upload-indicator'),
  3061. config = self.fileActionSettings;
  3062. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  3063. if (status === 'Success') {
  3064. $thumb.find('.file-drag-handle').remove();
  3065. }
  3066. $indicator.html(config[icon]);
  3067. $indicator.attr('title', config[msg]);
  3068. $thumb.addClass(css);
  3069. if (status === 'Error' && !self.retryErrorUploads) {
  3070. $thumb.find('.kv-file-upload').attr('disabled', true);
  3071. }
  3072. },
  3073. _setProgressCancelled: function () {
  3074. var self = this;
  3075. self._setProgress(101, self.$progress, self.msgCancelled);
  3076. },
  3077. _setProgress: function (p, $el, error) {
  3078. var self = this, pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold,
  3079. t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate,
  3080. template = pct < 100 ? self.progressTemplate : (error ? self.progressErrorTemplate : t);
  3081. $el = $el || self.$progress;
  3082. if (!$h.isEmpty(template)) {
  3083. if (pctLimit && pct > pctLimit && p <= 100) {
  3084. out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold});
  3085. } else {
  3086. out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')});
  3087. }
  3088. $el.html(out);
  3089. if (error) {
  3090. $el.find('[role="progressbar"]').html(error);
  3091. }
  3092. }
  3093. },
  3094. _setFileDropZoneTitle: function () {
  3095. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  3096. if (self.isClickable) {
  3097. strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  3098. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  3099. }
  3100. $zone.find('.' + self.dropZoneTitleClass).remove();
  3101. if (!self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled ||
  3102. (!self.isAjaxUpload && self.$element.files)) {
  3103. return;
  3104. }
  3105. if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) {
  3106. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  3107. }
  3108. self.$container.removeClass('file-input-new');
  3109. $h.addCss(self.$container, 'file-input-ajax-new');
  3110. },
  3111. _setAsyncUploadStatus: function (previewId, pct, total) {
  3112. var self = this, sum = 0;
  3113. self._setProgress(pct, $('#' + previewId).find('.file-thumb-progress'));
  3114. self.uploadStatus[previewId] = pct;
  3115. $.each(self.uploadStatus, function (key, value) {
  3116. sum += value;
  3117. });
  3118. self._setProgress(Math.floor(sum / total));
  3119. },
  3120. _validateMinCount: function () {
  3121. var self = this, len = self.isAjaxUpload ? self.getFileStack().length : self._inputFileCount();
  3122. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  3123. self._noFilesError({});
  3124. return false;
  3125. }
  3126. return true;
  3127. },
  3128. _getFileCount: function (fileCount) {
  3129. var self = this, addCount = 0;
  3130. if (self.validateInitialCount && !self.overwriteInitial) {
  3131. addCount = self.previewCache.count();
  3132. fileCount += addCount;
  3133. }
  3134. return fileCount;
  3135. },
  3136. _getFileId: function (file) {
  3137. var self = this, custom = self.generateFileId, relativePath;
  3138. if (typeof custom === 'function') {
  3139. return custom(file, event);
  3140. }
  3141. if (!file) {
  3142. return null;
  3143. }
  3144. /** @namespace file.webkitRelativePath */
  3145. /** @namespace file.fileName */
  3146. relativePath = String(file.webkitRelativePath || file.fileName || file.name || null);
  3147. if (!relativePath) {
  3148. return null;
  3149. }
  3150. return (file.size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/img, ''));
  3151. },
  3152. _getFileName: function (file) {
  3153. return file && file.name ? this.slug(file.name) : undefined;
  3154. },
  3155. _getFileIds: function (skipNull) {
  3156. var self = this;
  3157. return self.fileids.filter(function (n) {
  3158. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3159. });
  3160. },
  3161. _getFileNames: function (skipNull) {
  3162. var self = this;
  3163. return self.filenames.filter(function (n) {
  3164. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3165. });
  3166. },
  3167. _setPreviewError: function ($thumb, i, val, repeat) {
  3168. var self = this;
  3169. if (i !== undefined) {
  3170. self.updateStack(i, val);
  3171. }
  3172. if (!self.showPreview) {
  3173. return;
  3174. }
  3175. if (self.removeFromPreviewOnError && !repeat) {
  3176. $thumb.remove();
  3177. return;
  3178. } else {
  3179. self._setThumbStatus($thumb, 'Error');
  3180. }
  3181. self._refreshUploadButton($thumb, repeat);
  3182. },
  3183. _refreshUploadButton: function ($thumb, repeat) {
  3184. var self = this, $btn = $thumb.find('.kv-file-upload'), cfg = self.fileActionSettings,
  3185. icon = cfg.uploadIcon, title = cfg.uploadTitle;
  3186. if (!$btn.length) {
  3187. return;
  3188. }
  3189. if (repeat) {
  3190. icon = cfg.uploadRetryIcon;
  3191. title = cfg.uploadRetryTitle;
  3192. }
  3193. $btn.attr('title', title).html(icon);
  3194. },
  3195. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  3196. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  3197. $imgEl, isValid;
  3198. if ($h.isEmpty(limit) || !$img.length) {
  3199. return;
  3200. }
  3201. $imgEl = $img[0];
  3202. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  3203. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  3204. if (isValid) {
  3205. return;
  3206. }
  3207. msg = self['msgImage' + type + chk].setTokens({'name': fname, 'size': limit});
  3208. self._showUploadError(msg, params);
  3209. self._setPreviewError($thumb, i, null);
  3210. },
  3211. _getExifObj: function (iData) {
  3212. var self = this, exifObj = null;
  3213. try {
  3214. exifObj = window.piexif ? window.piexif.load(iData) : null;
  3215. } catch (err) {
  3216. exifObj = null;
  3217. }
  3218. if (!exifObj) {
  3219. self._log('Error loading the piexif.js library.');
  3220. }
  3221. return exifObj;
  3222. },
  3223. _validateImageOrientation: function ($img, file, previewId, caption, ftype, fsize, iData) {
  3224. var self = this, exifObj, value, autoOrientImage = self.autoOrientImage;
  3225. if (typeof autoOrientImage === 'function') {
  3226. autoOrientImage = autoOrientImage();
  3227. }
  3228. exifObj = $img.length && autoOrientImage ? self._getExifObj(iData) : null;
  3229. value = exifObj ? exifObj['0th'][piexif.ImageIFD.Orientation] : null; // jshint ignore:line
  3230. if (!value) {
  3231. self._validateImage(previewId, caption, ftype, fsize, iData, exifObj);
  3232. return;
  3233. }
  3234. $h.setImageOrientation($img, self.$preview.find('#zoom-' + previewId + ' img'), value);
  3235. self._raise('fileimageoriented', {'$img': $img, 'file': file});
  3236. self._validateImage(previewId, caption, ftype, fsize, iData, exifObj);
  3237. },
  3238. _validateImage: function (previewId, fname, ftype, fsize, iData, exifObj) {
  3239. var self = this, $preview = self.$preview, params, w1, w2, $thumb = $preview.find('#' + previewId),
  3240. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img');
  3241. fname = fname || 'Untitled';
  3242. $img.one('load', function () {
  3243. w1 = $thumb.width();
  3244. w2 = $preview.width();
  3245. if (w1 > w2) {
  3246. $img.css('width', '100%');
  3247. }
  3248. params = {ind: i, id: previewId};
  3249. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  3250. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  3251. if (!self.resizeImage) {
  3252. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  3253. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  3254. }
  3255. self._raise('fileimageloaded', [previewId]);
  3256. self.loadedImages.push({
  3257. ind: i,
  3258. img: $img,
  3259. thumb: $thumb,
  3260. pid: previewId,
  3261. typ: ftype,
  3262. siz: fsize,
  3263. validated: false,
  3264. imgData: iData,
  3265. exifObj: exifObj
  3266. });
  3267. $thumb.data('exif', exifObj);
  3268. self._validateAllImages();
  3269. }).one('error', function () {
  3270. self._raise('fileimageloaderror', [previewId]);
  3271. }).each(function () {
  3272. if (this.complete) {
  3273. $(this).trigger('load');
  3274. } else {
  3275. if (this.error) {
  3276. $(this).trigger('error');
  3277. }
  3278. }
  3279. });
  3280. },
  3281. _validateAllImages: function () {
  3282. var self = this, i, counter = {val: 0}, numImgs = self.loadedImages.length, config,
  3283. fsize, minSize = self.resizeIfSizeMoreThan;
  3284. if (numImgs !== self.totalImagesCount) {
  3285. return;
  3286. }
  3287. self._raise('fileimagesloaded');
  3288. if (!self.resizeImage) {
  3289. return;
  3290. }
  3291. for (i = 0; i < self.loadedImages.length; i++) {
  3292. config = self.loadedImages[i];
  3293. if (config.validated) {
  3294. continue;
  3295. }
  3296. fsize = config.siz;
  3297. if (fsize && fsize > minSize * 1000) {
  3298. self._getResizedImage(config, counter, numImgs);
  3299. }
  3300. self.loadedImages[i].validated = true;
  3301. }
  3302. },
  3303. _getResizedImage: function (config, counter, numImgs) {
  3304. var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob,
  3305. ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  3306. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI,
  3307. context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
  3308. $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr;
  3309. throwError = function (msg, params, ev) {
  3310. if (self.isAjaxUpload) {
  3311. self._showUploadError(msg, params, ev);
  3312. } else {
  3313. self._showError(msg, params, ev);
  3314. }
  3315. self._setPreviewError($thumb, ind);
  3316. };
  3317. if (!self.filestack[ind] || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  3318. if (isValidImage && self.filestack[ind]) {
  3319. self._raise('fileimageresized', [pid, ind]);
  3320. }
  3321. counter.val++;
  3322. if (counter.val === numImgs) {
  3323. self._raise('fileimagesresized');
  3324. }
  3325. if (!isValidImage) {
  3326. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  3327. return;
  3328. }
  3329. }
  3330. type = type || self.resizeDefaultImageType;
  3331. chkWidth = width > maxWidth;
  3332. chkHeight = height > maxHeight;
  3333. if (self.resizePreference === 'width') {
  3334. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  3335. } else {
  3336. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  3337. }
  3338. self._resetCanvas();
  3339. width *= ratio;
  3340. height *= ratio;
  3341. canvas.width = width;
  3342. canvas.height = height;
  3343. try {
  3344. context.drawImage(img, 0, 0, width, height);
  3345. dataURI = canvas.toDataURL(type, self.resizeQuality);
  3346. if (exifObj) {
  3347. exifStr = window.piexif.dump(exifObj);
  3348. dataURI = window.piexif.insert(exifStr, dataURI);
  3349. }
  3350. blob = $h.dataURI2Blob(dataURI);
  3351. self.filestack[ind] = blob;
  3352. self._raise('fileimageresized', [pid, ind]);
  3353. counter.val++;
  3354. if (counter.val === numImgs) {
  3355. self._raise('fileimagesresized', [undefined, undefined]);
  3356. }
  3357. if (!(blob instanceof Blob)) {
  3358. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  3359. }
  3360. }
  3361. catch (err) {
  3362. counter.val++;
  3363. if (counter.val === numImgs) {
  3364. self._raise('fileimagesresized', [undefined, undefined]);
  3365. }
  3366. msg = self.msgImageResizeException.replace('{errors}', err.message);
  3367. throwError(msg, {id: pid, 'index': ind}, 'fileimageresizeexception');
  3368. }
  3369. },
  3370. _initBrowse: function ($container) {
  3371. var self = this, $el = self.$element;
  3372. if (self.showBrowse) {
  3373. self.$btnFile = $container.find('.btn-file').append($el);
  3374. } else {
  3375. $el.appendTo($container).attr('tabindex', -1);
  3376. $h.addCss($el, 'file-no-browse');
  3377. }
  3378. },
  3379. _initClickable: function () {
  3380. var self = this, $zone, $tmpZone;
  3381. if (!self.isClickable) {
  3382. return;
  3383. }
  3384. $zone = self.$dropZone;
  3385. if (!self.isAjaxUpload) {
  3386. $tmpZone = self.$preview.find('.file-default-preview');
  3387. if ($tmpZone.length) {
  3388. $zone = $tmpZone;
  3389. }
  3390. }
  3391. $h.addCss($zone, 'clickable');
  3392. $zone.attr('tabindex', -1);
  3393. self._handler($zone, 'click', function (e) {
  3394. var $tar = $(e.target);
  3395. if (!$(self.elErrorContainer + ':visible').length &&
  3396. (!$tar.parents('.file-preview-thumbnails').length || $tar.parents(
  3397. '.file-default-preview').length)) {
  3398. self.$element.data('zoneClicked', true).trigger('click');
  3399. $zone.blur();
  3400. }
  3401. });
  3402. },
  3403. _initCaption: function () {
  3404. var self = this, cap = self.initialCaption || '';
  3405. if (self.overwriteInitial || $h.isEmpty(cap)) {
  3406. self.$caption.val('');
  3407. return false;
  3408. }
  3409. self._setCaption(cap);
  3410. return true;
  3411. },
  3412. _setCaption: function (content, isError) {
  3413. var self = this, title, out, icon, n, cap, stack = self.getFileStack();
  3414. if (!self.$caption.length) {
  3415. return;
  3416. }
  3417. self.$captionContainer.removeClass('icon-visible');
  3418. if (isError) {
  3419. title = $('<div>' + self.msgValidationError + '</div>').text();
  3420. n = stack.length;
  3421. if (n) {
  3422. cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n);
  3423. } else {
  3424. cap = self._getMsgSelected(self.msgNo);
  3425. }
  3426. out = $h.isEmpty(content) ? cap : content;
  3427. icon = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon + '</span>';
  3428. } else {
  3429. if ($h.isEmpty(content)) {
  3430. return;
  3431. }
  3432. title = $('<div>' + content + '</div>').text();
  3433. out = title;
  3434. icon = self._getLayoutTemplate('fileIcon');
  3435. }
  3436. self.$captionContainer.addClass('icon-visible');
  3437. self.$caption.attr('title', title).val(out);
  3438. self.$captionIcon.html(icon);
  3439. },
  3440. _createContainer: function () {
  3441. var self = this, attribs = {'class': 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')},
  3442. $container = $(document.createElement('div')).attr(attribs).html(self._renderMain());
  3443. $container.insertBefore(self.$element);
  3444. self._initBrowse($container);
  3445. if (self.theme) {
  3446. $container.addClass('theme-' + self.theme);
  3447. }
  3448. return $container;
  3449. },
  3450. _refreshContainer: function () {
  3451. var self = this, $container = self.$container, $el = self.$element;
  3452. $el.insertAfter($container);
  3453. $container.html(self._renderMain());
  3454. self._initBrowse($container);
  3455. self._validateDisabled();
  3456. },
  3457. _validateDisabled: function () {
  3458. var self = this;
  3459. self.$caption.attr({readonly: self.isDisabled});
  3460. },
  3461. _renderMain: function () {
  3462. var self = this,
  3463. dropCss = self.dropZoneEnabled ? ' file-drop-zone' : 'file-drop-disabled',
  3464. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  3465. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  3466. .setTokens({'class': self.previewClass, 'dropClass': dropCss}),
  3467. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  3468. caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'});
  3469. return self.mainTemplate.setTokens({
  3470. 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''),
  3471. 'preview': preview,
  3472. 'close': close,
  3473. 'caption': caption,
  3474. 'upload': self._renderButton('upload'),
  3475. 'remove': self._renderButton('remove'),
  3476. 'cancel': self._renderButton('cancel'),
  3477. 'browse': self._renderButton('browse')
  3478. });
  3479. },
  3480. _renderButton: function (type) {
  3481. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  3482. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  3483. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  3484. switch (type) {
  3485. case 'remove':
  3486. if (!self.showRemove) {
  3487. return '';
  3488. }
  3489. break;
  3490. case 'cancel':
  3491. if (!self.showCancel) {
  3492. return '';
  3493. }
  3494. css += ' kv-hidden';
  3495. break;
  3496. case 'upload':
  3497. if (!self.showUpload) {
  3498. return '';
  3499. }
  3500. if (self.isAjaxUpload && !self.isDisabled) {
  3501. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  3502. } else {
  3503. btnType = 'submit';
  3504. }
  3505. break;
  3506. case 'browse':
  3507. if (!self.showBrowse) {
  3508. return '';
  3509. }
  3510. tmplt = self._getLayoutTemplate('btnBrowse');
  3511. break;
  3512. default:
  3513. return '';
  3514. }
  3515. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  3516. if (!$h.isEmpty(label)) {
  3517. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  3518. }
  3519. return tmplt.setTokens({
  3520. 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label
  3521. });
  3522. },
  3523. _renderThumbProgress: function () {
  3524. var self = this;
  3525. return '<div class="file-thumb-progress kv-hidden">' +
  3526. self.progressTemplate.setTokens({'percent': '0', 'status': self.msgUploadBegin}) +
  3527. '</div>';
  3528. },
  3529. _renderFileFooter: function (caption, size, width, isError) {
  3530. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  3531. upl = config.showUpload, zoom = config.showZoom, out,
  3532. template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'),
  3533. ind = isError ? config.indicatorError : config.indicatorNew,
  3534. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle,
  3535. indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title});
  3536. size = self._getSize(size);
  3537. if (self.isAjaxUpload) {
  3538. out = template.setTokens({
  3539. 'actions': self._renderFileActions(upl, false, rem, zoom, drg, false, false, false),
  3540. 'caption': caption,
  3541. 'size': size,
  3542. 'width': width,
  3543. 'progress': self._renderThumbProgress(),
  3544. 'indicator': indicator
  3545. });
  3546. } else {
  3547. out = template.setTokens({
  3548. 'actions': self._renderFileActions(false, false, false, zoom, drg, false, false, false),
  3549. 'caption': caption,
  3550. 'size': size,
  3551. 'width': width,
  3552. 'progress': '',
  3553. 'indicator': indicator
  3554. });
  3555. }
  3556. out = $h.replaceTags(out, self.previewThumbTags);
  3557. return out;
  3558. },
  3559. _renderFileActions: function (
  3560. showUpl,
  3561. showDwn,
  3562. showDel,
  3563. showZoom,
  3564. showDrag,
  3565. disabled,
  3566. url,
  3567. key,
  3568. isInit,
  3569. dUrl,
  3570. dFile
  3571. ) {
  3572. if (!showUpl && !showDwn && !showDel && !showZoom && !showDrag) {
  3573. return '';
  3574. }
  3575. var self = this, vUrl = url === false ? '' : ' data-url="' + url + '"',
  3576. vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '',
  3577. btnZoom = '', btnDrag = '', css, template = self._getLayoutTemplate('actions'),
  3578. config = self.fileActionSettings,
  3579. otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}),
  3580. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  3581. if (showDel) {
  3582. btnDelete = self._getLayoutTemplate('actionDelete').setTokens({
  3583. 'removeClass': removeClass,
  3584. 'removeIcon': config.removeIcon,
  3585. 'removeTitle': config.removeTitle,
  3586. 'dataUrl': vUrl,
  3587. 'dataKey': vKey,
  3588. 'key': key
  3589. });
  3590. }
  3591. if (showUpl) {
  3592. btnUpload = self._getLayoutTemplate('actionUpload').setTokens({
  3593. 'uploadClass': config.uploadClass,
  3594. 'uploadIcon': config.uploadIcon,
  3595. 'uploadTitle': config.uploadTitle
  3596. });
  3597. }
  3598. if (showDwn) {
  3599. btnDownload = self._getLayoutTemplate('actionDownload').setTokens({
  3600. 'downloadClass': config.downloadClass,
  3601. 'downloadIcon': config.downloadIcon,
  3602. 'downloadTitle': config.downloadTitle,
  3603. 'downloadUrl': dUrl || self.initialPreviewDownloadUrl
  3604. });
  3605. btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key});
  3606. }
  3607. if (showZoom) {
  3608. btnZoom = self._getLayoutTemplate('actionZoom').setTokens({
  3609. 'zoomClass': config.zoomClass,
  3610. 'zoomIcon': config.zoomIcon,
  3611. 'zoomTitle': config.zoomTitle
  3612. });
  3613. }
  3614. if (showDrag && isInit) {
  3615. css = 'drag-handle-init ' + config.dragClass;
  3616. btnDrag = self._getLayoutTemplate('actionDrag').setTokens({
  3617. 'dragClass': css,
  3618. 'dragTitle': config.dragTitle,
  3619. 'dragIcon': config.dragIcon
  3620. });
  3621. }
  3622. return template.setTokens({
  3623. 'delete': btnDelete,
  3624. 'upload': btnUpload,
  3625. 'download': btnDownload,
  3626. 'zoom': btnZoom,
  3627. 'drag': btnDrag,
  3628. 'other': otherButtons
  3629. });
  3630. },
  3631. _browse: function (e) {
  3632. var self = this;
  3633. if (e && e.isDefaultPrevented() || !self._raise('filebrowse')) {
  3634. return;
  3635. }
  3636. if (self.isError && !self.isAjaxUpload) {
  3637. self.clear();
  3638. }
  3639. self.$captionContainer.focus();
  3640. },
  3641. _filterDuplicate: function (file, files, fileIds) {
  3642. var self = this, fileId = self._getFileId(file);
  3643. if (fileId && fileIds && fileIds.indexOf(fileId) > -1) {
  3644. return;
  3645. }
  3646. if (!fileIds) {
  3647. fileIds = [];
  3648. }
  3649. files.push(file);
  3650. fileIds.push(fileId);
  3651. },
  3652. _change: function (e) {
  3653. var self = this;
  3654. if (self.changeTriggered) {
  3655. return;
  3656. }
  3657. var $el = self.$element, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload,
  3658. tfiles = [], files = isDragDrop ? arguments[1] : $el.get(0).files, total,
  3659. maxCount = !isAjaxUpload && $h.isEmpty($el.attr('multiple')) ? 1 : self.maxFileCount,
  3660. len, ctr = self.filestack.length, isSingleUpload = $h.isEmpty($el.attr('multiple')),
  3661. flagSingle = (isSingleUpload && ctr > 0), fileIds = self._getFileIds(),
  3662. throwError = function (mesg, file, previewId, index) {
  3663. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  3664. p2 = {id: previewId, index: index, file: file, files: files};
  3665. return isAjaxUpload ? self._showUploadError(mesg, p1) : self._showError(mesg, p2);
  3666. },
  3667. maxCountCheck = function (n, m) {
  3668. var msg = self.msgFilesTooMany.replace('{m}', m).replace('{n}', n);
  3669. self.isError = throwError(msg, null, null, null);
  3670. self.$captionContainer.removeClass('icon-visible');
  3671. self._setCaption('', true);
  3672. self.$container.removeClass('file-input-new file-input-ajax-new');
  3673. };
  3674. self.reader = null;
  3675. self._resetUpload();
  3676. self._hideFileIcon();
  3677. if (self.dropZoneEnabled) {
  3678. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  3679. }
  3680. if (isAjaxUpload) {
  3681. $.each(files, function (vKey, vFile) {
  3682. self._filterDuplicate(vFile, tfiles, fileIds);
  3683. });
  3684. } else {
  3685. if (e.target && e.target.files === undefined) {
  3686. files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
  3687. } else {
  3688. files = e.target.files || {};
  3689. }
  3690. tfiles = files;
  3691. }
  3692. if ($h.isEmpty(tfiles) || tfiles.length === 0) {
  3693. if (!isAjaxUpload) {
  3694. self.clear();
  3695. }
  3696. self._raise('fileselectnone');
  3697. return;
  3698. }
  3699. self._resetErrors();
  3700. len = tfiles.length;
  3701. total = self._getFileCount(isAjaxUpload ? (self.getFileStack().length + len) : len);
  3702. if (maxCount > 0 && total > maxCount) {
  3703. if (!self.autoReplace || len > maxCount) {
  3704. maxCountCheck((self.autoReplace && len > maxCount ? len : total), maxCount);
  3705. return;
  3706. }
  3707. if (total > maxCount) {
  3708. self._resetPreviewThumbs(isAjaxUpload);
  3709. }
  3710. } else {
  3711. if (!isAjaxUpload || flagSingle) {
  3712. self._resetPreviewThumbs(false);
  3713. if (flagSingle) {
  3714. self.clearStack();
  3715. }
  3716. } else {
  3717. if (isAjaxUpload && ctr === 0 && (!self.previewCache.count() || self.overwriteInitial)) {
  3718. self._resetPreviewThumbs(true);
  3719. }
  3720. }
  3721. }
  3722. if (self.isPreviewable) {
  3723. self.readFiles(tfiles);
  3724. } else {
  3725. self._updateFileDetails(1);
  3726. }
  3727. },
  3728. _abort: function (params) {
  3729. var self = this, data;
  3730. if (self.ajaxAborted && typeof self.ajaxAborted === 'object' && self.ajaxAborted.message !== undefined) {
  3731. data = $.extend(true, {}, self._getOutData(), params);
  3732. data.abortData = self.ajaxAborted.data || {};
  3733. data.abortMessage = self.ajaxAborted.message;
  3734. self._setProgress(101, self.$progress, self.msgCancelled);
  3735. self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  3736. self.cancel();
  3737. return true;
  3738. }
  3739. return !!self.ajaxAborted;
  3740. },
  3741. _resetFileStack: function () {
  3742. var self = this, i = 0, newstack = [], newnames = [], newids = [];
  3743. self._getThumbs().each(function () {
  3744. var $thumb = $(this), ind = $thumb.attr('data-fileindex'), file = self.filestack[ind],
  3745. pid = $thumb.attr('id');
  3746. if (ind === '-1' || ind === -1) {
  3747. return;
  3748. }
  3749. if (file !== undefined) {
  3750. newstack[i] = file;
  3751. newnames[i] = self._getFileName(file);
  3752. newids[i] = self._getFileId(file);
  3753. $thumb.attr({'id': self.previewInitId + '-' + i, 'data-fileindex': i});
  3754. i++;
  3755. } else {
  3756. $thumb.attr({'id': 'uploaded-' + $h.uniqId(), 'data-fileindex': '-1'});
  3757. }
  3758. self.$preview.find('#zoom-' + pid).attr({
  3759. 'id': 'zoom-' + $thumb.attr('id'),
  3760. 'data-fileindex': $thumb.attr('data-fileindex')
  3761. });
  3762. });
  3763. self.filestack = newstack;
  3764. self.filenames = newnames;
  3765. self.fileids = newids;
  3766. },
  3767. _isFileSelectionValid: function (cnt) {
  3768. var self = this;
  3769. cnt = cnt || 0;
  3770. if (self.required && !self.getFilesCount()) {
  3771. self.$errorContainer.html('');
  3772. self._showUploadError(self.msgFileRequired);
  3773. return false;
  3774. }
  3775. if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) {
  3776. self._noFilesError({});
  3777. return false;
  3778. }
  3779. return true;
  3780. },
  3781. clearStack: function () {
  3782. var self = this;
  3783. self.filestack = [];
  3784. self.filenames = [];
  3785. self.fileids = [];
  3786. return self.$element;
  3787. },
  3788. updateStack: function (i, file) {
  3789. var self = this;
  3790. self.filestack[i] = file;
  3791. self.filenames[i] = self._getFileName(file);
  3792. self.fileids[i] = file && self._getFileId(file) || null;
  3793. return self.$element;
  3794. },
  3795. addToStack: function (file) {
  3796. var self = this;
  3797. self.filestack.push(file);
  3798. self.filenames.push(self._getFileName(file));
  3799. self.fileids.push(self._getFileId(file));
  3800. return self.$element;
  3801. },
  3802. getFileStack: function (skipNull) {
  3803. var self = this;
  3804. return self.filestack.filter(function (n) {
  3805. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3806. });
  3807. },
  3808. getFilesCount: function () {
  3809. var self = this, len = self.isAjaxUpload ? self.getFileStack().length : self._inputFileCount();
  3810. return self._getFileCount(len);
  3811. },
  3812. readFiles: function (files) {
  3813. this.reader = new FileReader();
  3814. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  3815. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  3816. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  3817. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  3818. fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
  3819. fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
  3820. maxPreviewSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize),
  3821. canPreview = $preview.length && (!maxPreviewSize || isNaN(maxPreviewSize)),
  3822. throwError = function (msg, file, previewId, index) {
  3823. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  3824. p2 = {id: previewId, index: index, file: file, files: files}, $thumb;
  3825. self._previewDefault(file, previewId, true);
  3826. if (self.isAjaxUpload) {
  3827. self.addToStack(undefined);
  3828. setTimeout(function () {
  3829. readFile(index + 1);
  3830. }, 100);
  3831. } else {
  3832. numFiles = 0;
  3833. }
  3834. self._initFileActions();
  3835. $thumb = $('#' + previewId);
  3836. $thumb.find('.kv-file-upload').hide();
  3837. if (self.removeFromPreviewOnError) {
  3838. $thumb.remove();
  3839. }
  3840. self.isError = self.isAjaxUpload ? self._showUploadError(msg, p1) : self._showError(msg, p2);
  3841. self._updateFileDetails(numFiles);
  3842. };
  3843. self.loadedImages = [];
  3844. self.totalImagesCount = 0;
  3845. $.each(files, function (key, file) {
  3846. var func = self.fileTypeSettings.image;
  3847. if (func && func(file.type)) {
  3848. self.totalImagesCount++;
  3849. }
  3850. });
  3851. readFile = function (i) {
  3852. if ($h.isEmpty($el.attr('multiple'))) {
  3853. numFiles = 1;
  3854. }
  3855. if (i >= numFiles) {
  3856. if (self.isAjaxUpload && self.filestack.length > 0) {
  3857. self._raise('filebatchselected', [self.getFileStack()]);
  3858. } else {
  3859. self._raise('filebatchselected', [files]);
  3860. }
  3861. $container.removeClass('file-thumb-loading');
  3862. $status.html('');
  3863. return;
  3864. }
  3865. var node = ctr + i, previewId = previewInitId + '-' + node, file = files[i], fSizeKB, j, msg,
  3866. fnText = settings.text, fnImage = settings.image, fnHtml = settings.html, typ, chk, typ1, typ2,
  3867. caption = file && file.name ? self.slug(file.name) : '', fileSize = (file && file.size || 0) / 1000,
  3868. fileExtExpr = '', previewData = $h.createObjectURL(file), fileCount = 0,
  3869. strTypes = '',
  3870. func, knownTypes = 0, isText, isHtml, isImage, txtFlag, processFileLoaded = function () {
  3871. var msg = msgProgress.setTokens({
  3872. 'index': i + 1,
  3873. 'files': numFiles,
  3874. 'percent': 50,
  3875. 'name': caption
  3876. });
  3877. setTimeout(function () {
  3878. $status.html(msg);
  3879. self._updateFileDetails(numFiles);
  3880. readFile(i + 1);
  3881. }, 100);
  3882. self._raise('fileloaded', [file, previewId, i, reader]);
  3883. };
  3884. if (!file) {
  3885. return;
  3886. }
  3887. if (typLen > 0) {
  3888. for (j = 0; j < typLen; j++) {
  3889. typ1 = fileTypes[j];
  3890. typ2 = self.msgFileTypes[typ1] || typ1;
  3891. strTypes += j === 0 ? typ2 : ', ' + typ2;
  3892. }
  3893. }
  3894. if (caption === false) {
  3895. readFile(i + 1);
  3896. return;
  3897. }
  3898. if (caption.length === 0) {
  3899. msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode(file.name, '[unknown]'));
  3900. throwError(msg, file, previewId, i);
  3901. return;
  3902. }
  3903. if (!$h.isEmpty(fileExt)) {
  3904. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  3905. }
  3906. fSizeKB = fileSize.toFixed(2);
  3907. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  3908. msg = self.msgSizeTooLarge.setTokens({
  3909. 'name': caption,
  3910. 'size': fSizeKB,
  3911. 'maxSize': self.maxFileSize
  3912. });
  3913. throwError(msg, file, previewId, i);
  3914. return;
  3915. }
  3916. if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
  3917. msg = self.msgSizeTooSmall.setTokens({
  3918. 'name': caption,
  3919. 'size': fSizeKB,
  3920. 'minSize': self.minFileSize
  3921. });
  3922. throwError(msg, file, previewId, i);
  3923. return;
  3924. }
  3925. if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
  3926. for (j = 0; j < fileTypes.length; j += 1) {
  3927. typ = fileTypes[j];
  3928. func = settings[typ];
  3929. fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type, file.name) ? 1 : 0);
  3930. }
  3931. if (fileCount === 0) {
  3932. msg = self.msgInvalidFileType.setTokens({'name': caption, 'types': strTypes});
  3933. throwError(msg, file, previewId, i);
  3934. return;
  3935. }
  3936. }
  3937. if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
  3938. chk = $h.compare(caption, fileExtExpr);
  3939. fileCount += $h.isEmpty(chk) ? 0 : chk.length;
  3940. if (fileCount === 0) {
  3941. msg = self.msgInvalidFileExtension.setTokens({'name': caption, 'extensions': strExt});
  3942. throwError(msg, file, previewId, i);
  3943. return;
  3944. }
  3945. }
  3946. if (!self.showPreview) {
  3947. if (self.isAjaxUpload) {
  3948. self.addToStack(file);
  3949. }
  3950. setTimeout(function () {
  3951. readFile(i + 1);
  3952. self._updateFileDetails(numFiles);
  3953. }, 100);
  3954. self._raise('fileloaded', [file, previewId, i, reader]);
  3955. return;
  3956. }
  3957. if (!canPreview && fileSize > maxPreviewSize) {
  3958. self.addToStack(file);
  3959. $container.addClass('file-thumb-loading');
  3960. self._previewDefault(file, previewId);
  3961. self._initFileActions();
  3962. self._updateFileDetails(numFiles);
  3963. readFile(i + 1);
  3964. return;
  3965. }
  3966. if ($preview.length && FileReader !== undefined) {
  3967. isText = fnText(file.type, caption);
  3968. isHtml = fnHtml(file.type, caption);
  3969. isImage = fnImage(file.type, caption);
  3970. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  3971. $container.addClass('file-thumb-loading');
  3972. reader.onerror = function (evt) {
  3973. self._errorHandler(evt, caption);
  3974. };
  3975. reader.onload = function (theFile) {
  3976. var hex, fileInfo, uint, byte, bytes = [], contents, mime, readTextImage = function (textFlag) {
  3977. var newReader = new FileReader();
  3978. newReader.onerror = function (theFileNew) {
  3979. self._errorHandler(theFileNew, caption);
  3980. };
  3981. newReader.onload = function (theFileNew) {
  3982. self._previewFile(i, file, theFileNew, previewId, previewData, fileInfo);
  3983. self._initFileActions();
  3984. processFileLoaded();
  3985. };
  3986. if (textFlag) {
  3987. newReader.readAsText(file, self.textEncoding);
  3988. } else {
  3989. newReader.readAsDataURL(file);
  3990. }
  3991. };
  3992. fileInfo = {'name': caption, 'type': file.type};
  3993. $.each(settings, function (k, f) {
  3994. if (k !== 'object' && k !== 'other' && typeof f === 'function' && f(file.type, caption)) {
  3995. knownTypes++;
  3996. }
  3997. });
  3998. if (knownTypes === 0) {// auto detect mime types from content if no known file types detected
  3999. uint = new Uint8Array(theFile.target.result);
  4000. for (j = 0; j < uint.length; j++) {
  4001. byte = uint[j].toString(16);
  4002. bytes.push(byte);
  4003. }
  4004. hex = bytes.join('').toLowerCase().substring(0, 8);
  4005. mime = $h.getMimeType(hex, '', '');
  4006. if ($h.isEmpty(mime)) { // look for ascii text content
  4007. contents = $h.arrayBuffer2String(reader.result);
  4008. mime = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type);
  4009. }
  4010. fileInfo = {'name': caption, 'type': mime};
  4011. isText = fnText(mime, '');
  4012. isHtml = fnHtml(mime, '');
  4013. isImage = fnImage(mime, '');
  4014. txtFlag = isText || isHtml;
  4015. if (txtFlag || isImage) {
  4016. readTextImage(txtFlag);
  4017. return;
  4018. }
  4019. }
  4020. self._previewFile(i, file, theFile, previewId, previewData, fileInfo);
  4021. self._initFileActions();
  4022. processFileLoaded();
  4023. };
  4024. reader.onprogress = function (data) {
  4025. if (data.lengthComputable) {
  4026. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  4027. msg = msgProgress.setTokens({
  4028. 'index': i + 1,
  4029. 'files': numFiles,
  4030. 'percent': progress,
  4031. 'name': caption
  4032. });
  4033. setTimeout(function () {
  4034. $status.html(msg);
  4035. }, 100);
  4036. }
  4037. };
  4038. if (isText || isHtml) {
  4039. reader.readAsText(file, self.textEncoding);
  4040. } else {
  4041. if (isImage) {
  4042. reader.readAsDataURL(file);
  4043. } else {
  4044. reader.readAsArrayBuffer(file);
  4045. }
  4046. }
  4047. } else {
  4048. self._previewDefault(file, previewId);
  4049. setTimeout(function () {
  4050. readFile(i + 1);
  4051. self._updateFileDetails(numFiles);
  4052. }, 100);
  4053. self._raise('fileloaded', [file, previewId, i, reader]);
  4054. }
  4055. self.addToStack(file);
  4056. };
  4057. readFile(0);
  4058. self._updateFileDetails(numFiles, false);
  4059. },
  4060. lock: function () {
  4061. var self = this;
  4062. self._resetErrors();
  4063. self.disable();
  4064. if (self.showRemove) {
  4065. self.$container.find('.fileinput-remove').hide();
  4066. }
  4067. if (self.showCancel) {
  4068. self.$container.find('.fileinput-cancel').show();
  4069. }
  4070. self._raise('filelock', [self.filestack, self._getExtraData()]);
  4071. return self.$element;
  4072. },
  4073. unlock: function (reset) {
  4074. var self = this;
  4075. if (reset === undefined) {
  4076. reset = true;
  4077. }
  4078. self.enable();
  4079. if (self.showCancel) {
  4080. self.$container.find('.fileinput-cancel').hide();
  4081. }
  4082. if (self.showRemove) {
  4083. self.$container.find('.fileinput-remove').show();
  4084. }
  4085. if (reset) {
  4086. self._resetFileStack();
  4087. }
  4088. self._raise('fileunlock', [self.filestack, self._getExtraData()]);
  4089. return self.$element;
  4090. },
  4091. cancel: function () {
  4092. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  4093. if (len > 0) {
  4094. for (i = 0; i < len; i += 1) {
  4095. self.cancelling = true;
  4096. xhr[i].abort();
  4097. }
  4098. }
  4099. self._setProgressCancelled();
  4100. self._getThumbs().each(function () {
  4101. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  4102. $thumb.removeClass('file-uploading');
  4103. if (self.filestack[ind] !== undefined) {
  4104. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  4105. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  4106. }
  4107. self.unlock();
  4108. });
  4109. return self.$element;
  4110. },
  4111. clear: function () {
  4112. var self = this, cap;
  4113. if (!self._raise('fileclear')) {
  4114. return;
  4115. }
  4116. self.$btnUpload.removeAttr('disabled');
  4117. self._getThumbs().find('video,audio,img').each(function () {
  4118. $h.cleanMemory($(this));
  4119. });
  4120. self._clearFileInput();
  4121. self._resetUpload();
  4122. self.clearStack();
  4123. self._resetErrors(true);
  4124. if (self._hasInitialPreview()) {
  4125. self._showFileIcon();
  4126. self._resetPreview();
  4127. self._initPreviewActions();
  4128. self.$container.removeClass('file-input-new');
  4129. } else {
  4130. self._getThumbs().each(function () {
  4131. self._clearObjects($(this));
  4132. });
  4133. if (self.isAjaxUpload) {
  4134. self.previewCache.data = {};
  4135. }
  4136. self.$preview.html('');
  4137. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  4138. self.$caption.attr('title', '').val(cap);
  4139. $h.addCss(self.$container, 'file-input-new');
  4140. self._validateDefaultPreview();
  4141. }
  4142. if (self.$container.find($h.FRAMES).length === 0) {
  4143. if (!self._initCaption()) {
  4144. self.$captionContainer.removeClass('icon-visible');
  4145. }
  4146. }
  4147. self._hideFileIcon();
  4148. self._raise('filecleared');
  4149. self.$captionContainer.focus();
  4150. self._setFileDropZoneTitle();
  4151. return self.$element;
  4152. },
  4153. reset: function () {
  4154. var self = this;
  4155. if (!self._raise('filereset')) {
  4156. return;
  4157. }
  4158. self._resetPreview();
  4159. self.$container.find('.fileinput-filename').text('');
  4160. $h.addCss(self.$container, 'file-input-new');
  4161. if (self.getFrames().length || self.dropZoneEnabled) {
  4162. self.$container.removeClass('file-input-new');
  4163. }
  4164. self.clearStack();
  4165. self.formdata = {};
  4166. self._setFileDropZoneTitle();
  4167. return self.$element;
  4168. },
  4169. disable: function () {
  4170. var self = this;
  4171. self.isDisabled = true;
  4172. self._raise('filedisabled');
  4173. self.$element.attr('disabled', 'disabled');
  4174. self.$container.find('.kv-fileinput-caption').addClass('file-caption-disabled');
  4175. self.$container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  4176. .attr('disabled', true);
  4177. $h.addCss(self.$container.find('.btn-file'), 'disabled');
  4178. self._initDragDrop();
  4179. return self.$element;
  4180. },
  4181. enable: function () {
  4182. var self = this;
  4183. self.isDisabled = false;
  4184. self._raise('fileenabled');
  4185. self.$element.removeAttr('disabled');
  4186. self.$container.find('.kv-fileinput-caption').removeClass('file-caption-disabled');
  4187. self.$container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  4188. .removeAttr('disabled');
  4189. self.$container.find('.btn-file').removeClass('disabled');
  4190. self._initDragDrop();
  4191. return self.$element;
  4192. },
  4193. upload: function () {
  4194. var self = this, totLen = self.getFileStack().length, i, outData, len,
  4195. hasExtraData = !$.isEmptyObject(self._getExtraData());
  4196. if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) {
  4197. return;
  4198. }
  4199. self._resetUpload();
  4200. if (totLen === 0 && !hasExtraData) {
  4201. self._showUploadError(self.msgUploadEmpty);
  4202. return;
  4203. }
  4204. self.$progress.show();
  4205. self.uploadCount = 0;
  4206. self.uploadStatus = {};
  4207. self.uploadLog = [];
  4208. self.lock();
  4209. self._setProgress(2);
  4210. if (totLen === 0 && hasExtraData) {
  4211. self._uploadExtraOnly();
  4212. return;
  4213. }
  4214. len = self.filestack.length;
  4215. self.hasInitData = false;
  4216. if (self.uploadAsync) {
  4217. outData = self._getOutData();
  4218. self._raise('filebatchpreupload', [outData]);
  4219. self.fileBatchCompleted = false;
  4220. self.uploadCache = {content: [], config: [], tags: [], append: true};
  4221. self.uploadAsyncCount = self.getFileStack().length;
  4222. for (i = 0; i < len; i++) {
  4223. self.uploadCache.content[i] = null;
  4224. self.uploadCache.config[i] = null;
  4225. self.uploadCache.tags[i] = null;
  4226. }
  4227. self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
  4228. self._initSortable();
  4229. self.cacheInitialPreview = self.getPreview();
  4230. for (i = 0; i < len; i++) {
  4231. if (self.filestack[i]) {
  4232. self._uploadSingle(i, true);
  4233. }
  4234. }
  4235. return;
  4236. }
  4237. self._uploadBatch();
  4238. return self.$element;
  4239. },
  4240. destroy: function () {
  4241. var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace;
  4242. $(document).off(ns);
  4243. $(window).off(ns);
  4244. if ($form && $form.length) {
  4245. $form.off(ns);
  4246. }
  4247. if (self.isAjaxUpload) {
  4248. self._clearFileInput();
  4249. }
  4250. self._cleanup();
  4251. self._initPreviewCache();
  4252. $el.insertBefore($cont).off(ns).removeData();
  4253. $cont.off().remove();
  4254. return $el;
  4255. },
  4256. refresh: function (options) {
  4257. var self = this, $el = self.$element;
  4258. if (typeof options !== 'object' || $h.isEmpty(options)) {
  4259. options = self.options;
  4260. } else {
  4261. options = $.extend(true, {}, self.options, options);
  4262. }
  4263. self._init(options, true);
  4264. self._listen();
  4265. return $el;
  4266. },
  4267. zoom: function (frameId) {
  4268. var self = this, $frame = self._getFrame(frameId), $modal = self.$modal;
  4269. if (!$frame) {
  4270. return;
  4271. }
  4272. $h.initModal($modal);
  4273. $modal.html(self._getModalContent());
  4274. self._setZoomContent($frame);
  4275. $modal.modal('show');
  4276. self._initZoomButtons();
  4277. },
  4278. getExif: function (frameId) {
  4279. var self = this, $frame = self._getFrame(frameId);
  4280. return $frame && $frame.data('exif') || null;
  4281. },
  4282. getFrames: function (cssFilter) {
  4283. var self = this, $frames;
  4284. cssFilter = cssFilter || '';
  4285. $frames = self.$preview.find($h.FRAMES + cssFilter);
  4286. if (self.reversePreviewOrder) {
  4287. $frames = $($frames.get().reverse());
  4288. }
  4289. return $frames;
  4290. },
  4291. getPreview: function () {
  4292. var self = this;
  4293. return {
  4294. content: self.initialPreview,
  4295. config: self.initialPreviewConfig,
  4296. tags: self.initialPreviewThumbTags
  4297. };
  4298. }
  4299. };
  4300. $.fn.fileinput = function (option) {
  4301. if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
  4302. return;
  4303. }
  4304. var args = Array.apply(null, arguments), retvals = [];
  4305. args.shift();
  4306. this.each(function () {
  4307. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  4308. theme = options.theme || self.data('theme'), l = {}, t = {},
  4309. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
  4310. if (!data) {
  4311. if (theme) {
  4312. t = $.fn.fileinputThemes[theme] || {};
  4313. }
  4314. if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
  4315. l = $.fn.fileinputLocales[lang] || {};
  4316. }
  4317. opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data());
  4318. data = new FileInput(this, opt);
  4319. self.data('fileinput', data);
  4320. }
  4321. if (typeof option === 'string') {
  4322. retvals.push(data[option].apply(data, args));
  4323. }
  4324. });
  4325. switch (retvals.length) {
  4326. case 0:
  4327. return this;
  4328. case 1:
  4329. return retvals[0];
  4330. default:
  4331. return retvals;
  4332. }
  4333. };
  4334. $.fn.fileinput.defaults = {
  4335. language: 'en',
  4336. showCaption: true,
  4337. showBrowse: true,
  4338. showPreview: true,
  4339. showRemove: true,
  4340. showUpload: true,
  4341. showCancel: true,
  4342. showClose: true,
  4343. showUploadedThumbs: true,
  4344. browseOnZoneClick: false,
  4345. autoReplace: false,
  4346. autoOrientImage: function () { // applicable for JPEG images only and non ios safari
  4347. var ua = window.navigator.userAgent, webkit = !!ua.match(/WebKit/i),
  4348. iOS = !!ua.match(/iP(od|ad|hone)/i), iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
  4349. return !iOSSafari;
  4350. },
  4351. required: false,
  4352. rtl: false,
  4353. hideThumbnailContent: false,
  4354. encodeUrl: true,
  4355. generateFileId: null,
  4356. previewClass: '',
  4357. captionClass: '',
  4358. frameClass: 'krajee-default',
  4359. mainClass: 'file-caption-main',
  4360. mainTemplate: null,
  4361. purifyHtml: true,
  4362. fileSizeGetter: null,
  4363. initialCaption: '',
  4364. initialPreview: [],
  4365. initialPreviewDelimiter: '*$$*',
  4366. initialPreviewAsData: false,
  4367. initialPreviewFileType: 'image',
  4368. initialPreviewConfig: [],
  4369. initialPreviewThumbTags: [],
  4370. previewThumbTags: {},
  4371. initialPreviewShowDelete: true,
  4372. initialPreviewDownloadUrl: '',
  4373. removeFromPreviewOnError: false,
  4374. deleteUrl: '',
  4375. deleteExtraData: {},
  4376. overwriteInitial: true,
  4377. previewZoomButtonIcons: {
  4378. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  4379. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  4380. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  4381. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  4382. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  4383. close: '<i class="glyphicon glyphicon-remove"></i>'
  4384. },
  4385. previewZoomButtonClasses: {
  4386. prev: 'btn btn-navigate',
  4387. next: 'btn btn-navigate',
  4388. toggleheader: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
  4389. fullscreen: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
  4390. borderless: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
  4391. close: 'btn btn-sm btn-kv btn-default btn-outline-secondary'
  4392. },
  4393. previewTemplates: {},
  4394. previewContentTemplates: {},
  4395. preferIconicPreview: false,
  4396. preferIconicZoomPreview: false,
  4397. allowedPreviewTypes: undefined,
  4398. allowedPreviewMimeTypes: null,
  4399. allowedFileTypes: null,
  4400. allowedFileExtensions: null,
  4401. defaultPreviewContent: null,
  4402. customLayoutTags: {},
  4403. customPreviewTags: {},
  4404. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  4405. previewFileIconClass: 'file-other-icon',
  4406. previewFileIconSettings: {},
  4407. previewFileExtSettings: {},
  4408. buttonLabelClass: 'hidden-xs',
  4409. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  4410. browseClass: 'btn btn-primary',
  4411. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  4412. removeClass: 'btn btn-default btn-secondary',
  4413. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  4414. cancelClass: 'btn btn-default btn-secondary',
  4415. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  4416. uploadClass: 'btn btn-default btn-secondary',
  4417. uploadUrl: null,
  4418. uploadUrlThumb: null,
  4419. uploadAsync: true,
  4420. uploadExtraData: {},
  4421. zoomModalHeight: 480,
  4422. minImageWidth: null,
  4423. minImageHeight: null,
  4424. maxImageWidth: null,
  4425. maxImageHeight: null,
  4426. resizeImage: false,
  4427. resizePreference: 'width',
  4428. resizeQuality: 0.92,
  4429. resizeDefaultImageType: 'image/jpeg',
  4430. resizeIfSizeMoreThan: 0, // in KB
  4431. minFileSize: 0,
  4432. maxFileSize: 0,
  4433. maxFilePreviewSize: 25600, // 25 MB
  4434. minFileCount: 0,
  4435. maxFileCount: 0,
  4436. validateInitialCount: false,
  4437. msgValidationErrorClass: 'text-danger',
  4438. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  4439. msgErrorClass: 'file-error-message',
  4440. progressThumbClass: 'progress-bar bg-success progress-bar-success progress-bar-striped active',
  4441. progressClass: 'progress-bar bg-success progress-bar-success progress-bar-striped active',
  4442. progressCompleteClass: 'progress-bar bg-success progress-bar-success',
  4443. progressErrorClass: 'progress-bar bg-danger progress-bar-danger',
  4444. progressUploadThreshold: 99,
  4445. previewFileType: 'image',
  4446. elCaptionContainer: null,
  4447. elCaptionText: null,
  4448. elPreviewContainer: null,
  4449. elPreviewImage: null,
  4450. elPreviewStatus: null,
  4451. elErrorContainer: null,
  4452. errorCloseButton: $h.closeButton('kv-error-close'),
  4453. slugCallback: null,
  4454. dropZoneEnabled: true,
  4455. dropZoneTitleClass: 'file-drop-zone-title',
  4456. fileActionSettings: {},
  4457. otherActionButtons: '',
  4458. textEncoding: 'UTF-8',
  4459. ajaxSettings: {},
  4460. ajaxDeleteSettings: {},
  4461. showAjaxErrorDetails: true,
  4462. mergeAjaxCallbacks: false,
  4463. mergeAjaxDeleteCallbacks: false,
  4464. retryErrorUploads: true,
  4465. reversePreviewOrder: false
  4466. };
  4467. // noinspection HtmlUnknownAttribute
  4468. $.fn.fileinputLocales.en = {
  4469. fileSingle: 'file',
  4470. filePlural: 'files',
  4471. browseLabel: 'Browse &hellip;',
  4472. removeLabel: 'Remove',
  4473. removeTitle: 'Clear selected files',
  4474. cancelLabel: 'Cancel',
  4475. cancelTitle: 'Abort ongoing upload',
  4476. uploadLabel: 'Upload',
  4477. uploadTitle: 'Upload selected files',
  4478. msgNo: 'No',
  4479. msgNoFilesSelected: 'No files selected',
  4480. msgCancelled: 'Cancelled',
  4481. msgPlaceholder: 'Select {files}...',
  4482. msgZoomModalHeading: 'Detailed Preview',
  4483. msgFileRequired: 'You must select a file to upload.',
  4484. msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  4485. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  4486. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  4487. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  4488. msgFileNotFound: 'File "{name}" not found!',
  4489. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  4490. msgFileNotReadable: 'File "{name}" is not readable.',
  4491. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  4492. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  4493. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  4494. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  4495. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  4496. msgFileTypes: {
  4497. 'image': 'image',
  4498. 'html': 'HTML',
  4499. 'text': 'text',
  4500. 'video': 'video',
  4501. 'audio': 'audio',
  4502. 'flash': 'flash',
  4503. 'pdf': 'PDF',
  4504. 'object': 'object'
  4505. },
  4506. msgUploadAborted: 'The file upload was aborted',
  4507. msgUploadThreshold: 'Processing...',
  4508. msgUploadBegin: 'Initializing...',
  4509. msgUploadEnd: 'Done',
  4510. msgUploadEmpty: 'No valid data available for upload.',
  4511. msgUploadError: 'Error',
  4512. msgValidationError: 'Validation Error',
  4513. msgLoading: 'Loading file {index} of {files} &hellip;',
  4514. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  4515. msgSelected: '{n} {files} selected',
  4516. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  4517. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  4518. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  4519. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  4520. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  4521. msgImageResizeError: 'Could not get the image dimensions to resize.',
  4522. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  4523. msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  4524. msgAjaxProgressError: '{operation} failed',
  4525. ajaxOperations: {
  4526. deleteThumb: 'file delete',
  4527. uploadThumb: 'file upload',
  4528. uploadBatch: 'batch file upload',
  4529. uploadExtra: 'form data upload'
  4530. },
  4531. dropZoneTitle: 'Drag & drop files here &hellip;',
  4532. dropZoneClickTitle: '<br>(or click to select {files})',
  4533. previewZoomButtonTitles: {
  4534. prev: 'View previous file',
  4535. next: 'View next file',
  4536. toggleheader: 'Toggle header',
  4537. fullscreen: 'Toggle full screen',
  4538. borderless: 'Toggle borderless mode',
  4539. close: 'Close detailed preview'
  4540. },
  4541. usePdfRenderer: function () {
  4542. //noinspection JSUnresolvedVariable
  4543. var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
  4544. return !!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i) || isIE11;
  4545. },
  4546. pdfRendererUrl: '',
  4547. pdfRendererTemplate: '<iframe class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}></iframe>'
  4548. };
  4549. $.fn.fileinput.Constructor = FileInput;
  4550. /**
  4551. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  4552. */
  4553. $(document).ready(function () {
  4554. var $input = $('input.file[type=file]');
  4555. if ($input.length) {
  4556. $input.fileinput();
  4557. }
  4558. });
  4559. }));