fileinput.js 208 KB

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