fileinput.js 208 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613
  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('Error loading the piexif.js library.');
  3250. }
  3251. return exifObj;
  3252. },
  3253. _validateImageOrientation: function ($img, file, previewId, caption, ftype, fsize, iData) {
  3254. var self = this, exifObj, value, autoOrientImage = self.autoOrientImage;
  3255. if (typeof autoOrientImage === 'function') {
  3256. autoOrientImage = autoOrientImage();
  3257. }
  3258. exifObj = $img.length && autoOrientImage ? self._getExifObj(iData) : null;
  3259. value = exifObj ? exifObj['0th'][piexif.ImageIFD.Orientation] : null; // jshint ignore:line
  3260. if (!value) {
  3261. self._validateImage(previewId, caption, ftype, fsize, iData, exifObj);
  3262. return;
  3263. }
  3264. $h.setImageOrientation($img, self.$preview.find('#zoom-' + previewId + ' img'), value);
  3265. self._raise('fileimageoriented', {'$img': $img, 'file': file});
  3266. self._validateImage(previewId, caption, ftype, fsize, iData, exifObj);
  3267. },
  3268. _validateImage: function (previewId, fname, ftype, fsize, iData, exifObj) {
  3269. var self = this, $preview = self.$preview, params, w1, w2, $thumb = $preview.find('#' + previewId),
  3270. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img');
  3271. fname = fname || 'Untitled';
  3272. $img.one('load', function () {
  3273. w1 = $thumb.width();
  3274. w2 = $preview.width();
  3275. if (w1 > w2) {
  3276. $img.css('width', '100%');
  3277. }
  3278. params = {ind: i, id: previewId};
  3279. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  3280. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  3281. if (!self.resizeImage) {
  3282. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  3283. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  3284. }
  3285. self._raise('fileimageloaded', [previewId]);
  3286. self.loadedImages.push({
  3287. ind: i,
  3288. img: $img,
  3289. thumb: $thumb,
  3290. pid: previewId,
  3291. typ: ftype,
  3292. siz: fsize,
  3293. validated: false,
  3294. imgData: iData,
  3295. exifObj: exifObj
  3296. });
  3297. $thumb.data('exif', exifObj);
  3298. self._validateAllImages();
  3299. }).one('error', function () {
  3300. self._raise('fileimageloaderror', [previewId]);
  3301. }).each(function () {
  3302. if (this.complete) {
  3303. $(this).trigger('load');
  3304. } else {
  3305. if (this.error) {
  3306. $(this).trigger('error');
  3307. }
  3308. }
  3309. });
  3310. },
  3311. _validateAllImages: function () {
  3312. var self = this, i, counter = {val: 0}, numImgs = self.loadedImages.length, config,
  3313. fsize, minSize = self.resizeIfSizeMoreThan;
  3314. if (numImgs !== self.totalImagesCount) {
  3315. return;
  3316. }
  3317. self._raise('fileimagesloaded');
  3318. if (!self.resizeImage) {
  3319. return;
  3320. }
  3321. for (i = 0; i < self.loadedImages.length; i++) {
  3322. config = self.loadedImages[i];
  3323. if (config.validated) {
  3324. continue;
  3325. }
  3326. fsize = config.siz;
  3327. if (fsize && fsize > minSize * 1000) {
  3328. self._getResizedImage(config, counter, numImgs);
  3329. }
  3330. self.loadedImages[i].validated = true;
  3331. }
  3332. },
  3333. _getResizedImage: function (config, counter, numImgs) {
  3334. var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob,
  3335. ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  3336. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI,
  3337. context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
  3338. $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr;
  3339. throwError = function (msg, params, ev) {
  3340. if (self.isAjaxUpload) {
  3341. self._showUploadError(msg, params, ev);
  3342. } else {
  3343. self._showError(msg, params, ev);
  3344. }
  3345. self._setPreviewError($thumb, ind);
  3346. };
  3347. if (!self.filestack[ind] || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  3348. if (isValidImage && self.filestack[ind]) {
  3349. self._raise('fileimageresized', [pid, ind]);
  3350. }
  3351. counter.val++;
  3352. if (counter.val === numImgs) {
  3353. self._raise('fileimagesresized');
  3354. }
  3355. if (!isValidImage) {
  3356. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  3357. return;
  3358. }
  3359. }
  3360. type = type || self.resizeDefaultImageType;
  3361. chkWidth = width > maxWidth;
  3362. chkHeight = height > maxHeight;
  3363. if (self.resizePreference === 'width') {
  3364. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  3365. } else {
  3366. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  3367. }
  3368. self._resetCanvas();
  3369. width *= ratio;
  3370. height *= ratio;
  3371. canvas.width = width;
  3372. canvas.height = height;
  3373. try {
  3374. context.drawImage(img, 0, 0, width, height);
  3375. dataURI = canvas.toDataURL(type, self.resizeQuality);
  3376. if (exifObj) {
  3377. exifStr = window.piexif.dump(exifObj);
  3378. dataURI = window.piexif.insert(exifStr, dataURI);
  3379. }
  3380. blob = $h.dataURI2Blob(dataURI);
  3381. self.filestack[ind] = blob;
  3382. self._raise('fileimageresized', [pid, ind]);
  3383. counter.val++;
  3384. if (counter.val === numImgs) {
  3385. self._raise('fileimagesresized', [undefined, undefined]);
  3386. }
  3387. if (!(blob instanceof Blob)) {
  3388. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  3389. }
  3390. }
  3391. catch (err) {
  3392. counter.val++;
  3393. if (counter.val === numImgs) {
  3394. self._raise('fileimagesresized', [undefined, undefined]);
  3395. }
  3396. msg = self.msgImageResizeException.replace('{errors}', err.message);
  3397. throwError(msg, {id: pid, 'index': ind}, 'fileimageresizeexception');
  3398. }
  3399. },
  3400. _initBrowse: function ($container) {
  3401. var self = this, $el = self.$element;
  3402. if (self.showBrowse) {
  3403. self.$btnFile = $container.find('.btn-file').append($el);
  3404. } else {
  3405. $el.appendTo($container).attr('tabindex', -1);
  3406. $h.addCss($el, 'file-no-browse');
  3407. }
  3408. },
  3409. _initClickable: function () {
  3410. var self = this, $zone, $tmpZone;
  3411. if (!self.isClickable) {
  3412. return;
  3413. }
  3414. $zone = self.$dropZone;
  3415. if (!self.isAjaxUpload) {
  3416. $tmpZone = self.$preview.find('.file-default-preview');
  3417. if ($tmpZone.length) {
  3418. $zone = $tmpZone;
  3419. }
  3420. }
  3421. $h.addCss($zone, 'clickable');
  3422. $zone.attr('tabindex', -1);
  3423. self._handler($zone, 'click', function (e) {
  3424. var $tar = $(e.target);
  3425. if (!$(self.elErrorContainer + ':visible').length &&
  3426. (!$tar.parents('.file-preview-thumbnails').length || $tar.parents(
  3427. '.file-default-preview').length)) {
  3428. self.$element.data('zoneClicked', true).trigger('click');
  3429. $zone.blur();
  3430. }
  3431. });
  3432. },
  3433. _initCaption: function () {
  3434. var self = this, cap = self.initialCaption || '';
  3435. if (self.overwriteInitial || $h.isEmpty(cap)) {
  3436. self.$caption.val('');
  3437. return false;
  3438. }
  3439. self._setCaption(cap);
  3440. return true;
  3441. },
  3442. _setCaption: function (content, isError) {
  3443. var self = this, title, out, icon, n, cap, stack = self.getFileStack();
  3444. if (!self.$caption.length) {
  3445. return;
  3446. }
  3447. self.$captionContainer.removeClass('icon-visible');
  3448. if (isError) {
  3449. title = $('<div>' + self.msgValidationError + '</div>').text();
  3450. n = stack.length;
  3451. if (n) {
  3452. cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n);
  3453. } else {
  3454. cap = self._getMsgSelected(self.msgNo);
  3455. }
  3456. out = $h.isEmpty(content) ? cap : content;
  3457. icon = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon + '</span>';
  3458. } else {
  3459. if ($h.isEmpty(content)) {
  3460. return;
  3461. }
  3462. title = $('<div>' + content + '</div>').text();
  3463. out = title;
  3464. icon = self._getLayoutTemplate('fileIcon');
  3465. }
  3466. self.$captionContainer.addClass('icon-visible');
  3467. self.$caption.attr('title', title).val(out);
  3468. self.$captionIcon.html(icon);
  3469. },
  3470. _createContainer: function () {
  3471. var self = this, attribs = {'class': 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')},
  3472. $container = $(document.createElement('div')).attr(attribs).html(self._renderMain());
  3473. $container.insertBefore(self.$element);
  3474. self._initBrowse($container);
  3475. if (self.theme) {
  3476. $container.addClass('theme-' + self.theme);
  3477. }
  3478. return $container;
  3479. },
  3480. _refreshContainer: function () {
  3481. var self = this, $container = self.$container, $el = self.$element;
  3482. $el.insertAfter($container);
  3483. $container.html(self._renderMain());
  3484. self._initBrowse($container);
  3485. self._validateDisabled();
  3486. },
  3487. _validateDisabled: function () {
  3488. var self = this;
  3489. self.$caption.attr({readonly: self.isDisabled});
  3490. },
  3491. _renderMain: function () {
  3492. var self = this,
  3493. dropCss = self.dropZoneEnabled ? ' file-drop-zone' : 'file-drop-disabled',
  3494. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  3495. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  3496. .setTokens({'class': self.previewClass, 'dropClass': dropCss}),
  3497. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  3498. caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'});
  3499. return self.mainTemplate.setTokens({
  3500. 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''),
  3501. 'preview': preview,
  3502. 'close': close,
  3503. 'caption': caption,
  3504. 'upload': self._renderButton('upload'),
  3505. 'remove': self._renderButton('remove'),
  3506. 'cancel': self._renderButton('cancel'),
  3507. 'browse': self._renderButton('browse')
  3508. });
  3509. },
  3510. _renderButton: function (type) {
  3511. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  3512. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  3513. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  3514. switch (type) {
  3515. case 'remove':
  3516. if (!self.showRemove) {
  3517. return '';
  3518. }
  3519. break;
  3520. case 'cancel':
  3521. if (!self.showCancel) {
  3522. return '';
  3523. }
  3524. css += ' kv-hidden';
  3525. break;
  3526. case 'upload':
  3527. if (!self.showUpload) {
  3528. return '';
  3529. }
  3530. if (self.isAjaxUpload && !self.isDisabled) {
  3531. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  3532. } else {
  3533. btnType = 'submit';
  3534. }
  3535. break;
  3536. case 'browse':
  3537. if (!self.showBrowse) {
  3538. return '';
  3539. }
  3540. tmplt = self._getLayoutTemplate('btnBrowse');
  3541. break;
  3542. default:
  3543. return '';
  3544. }
  3545. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  3546. if (!$h.isEmpty(label)) {
  3547. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  3548. }
  3549. return tmplt.setTokens({
  3550. 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label
  3551. });
  3552. },
  3553. _renderThumbProgress: function () {
  3554. var self = this;
  3555. return '<div class="file-thumb-progress kv-hidden">' +
  3556. self.progressTemplate.setTokens({'percent': '0', 'status': self.msgUploadBegin}) +
  3557. '</div>';
  3558. },
  3559. _renderFileFooter: function (caption, size, width, isError) {
  3560. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  3561. upl = config.showUpload, zoom = config.showZoom, out,
  3562. template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'),
  3563. ind = isError ? config.indicatorError : config.indicatorNew,
  3564. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle,
  3565. indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title});
  3566. size = self._getSize(size);
  3567. if (self.isAjaxUpload) {
  3568. out = template.setTokens({
  3569. 'actions': self._renderFileActions(upl, false, rem, zoom, drg, false, false, false),
  3570. 'caption': caption,
  3571. 'size': size,
  3572. 'width': width,
  3573. 'progress': self._renderThumbProgress(),
  3574. 'indicator': indicator
  3575. });
  3576. } else {
  3577. out = template.setTokens({
  3578. 'actions': self._renderFileActions(false, false, false, zoom, drg, false, false, false),
  3579. 'caption': caption,
  3580. 'size': size,
  3581. 'width': width,
  3582. 'progress': '',
  3583. 'indicator': indicator
  3584. });
  3585. }
  3586. out = $h.replaceTags(out, self.previewThumbTags);
  3587. return out;
  3588. },
  3589. _renderFileActions: function (
  3590. showUpl,
  3591. showDwn,
  3592. showDel,
  3593. showZoom,
  3594. showDrag,
  3595. disabled,
  3596. url,
  3597. key,
  3598. isInit,
  3599. dUrl,
  3600. dFile
  3601. ) {
  3602. if (!showUpl && !showDwn && !showDel && !showZoom && !showDrag) {
  3603. return '';
  3604. }
  3605. var self = this, vUrl = url === false ? '' : ' data-url="' + url + '"',
  3606. vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '',
  3607. btnZoom = '', btnDrag = '', css, template = self._getLayoutTemplate('actions'),
  3608. config = self.fileActionSettings,
  3609. otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}),
  3610. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  3611. if (showDel) {
  3612. btnDelete = self._getLayoutTemplate('actionDelete').setTokens({
  3613. 'removeClass': removeClass,
  3614. 'removeIcon': config.removeIcon,
  3615. 'removeTitle': config.removeTitle,
  3616. 'dataUrl': vUrl,
  3617. 'dataKey': vKey,
  3618. 'key': key
  3619. });
  3620. }
  3621. if (showUpl) {
  3622. btnUpload = self._getLayoutTemplate('actionUpload').setTokens({
  3623. 'uploadClass': config.uploadClass,
  3624. 'uploadIcon': config.uploadIcon,
  3625. 'uploadTitle': config.uploadTitle
  3626. });
  3627. }
  3628. if (showDwn) {
  3629. btnDownload = self._getLayoutTemplate('actionDownload').setTokens({
  3630. 'downloadClass': config.downloadClass,
  3631. 'downloadIcon': config.downloadIcon,
  3632. 'downloadTitle': config.downloadTitle,
  3633. 'downloadUrl': dUrl || self.initialPreviewDownloadUrl
  3634. });
  3635. btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key});
  3636. }
  3637. if (showZoom) {
  3638. btnZoom = self._getLayoutTemplate('actionZoom').setTokens({
  3639. 'zoomClass': config.zoomClass,
  3640. 'zoomIcon': config.zoomIcon,
  3641. 'zoomTitle': config.zoomTitle
  3642. });
  3643. }
  3644. if (showDrag && isInit) {
  3645. css = 'drag-handle-init ' + config.dragClass;
  3646. btnDrag = self._getLayoutTemplate('actionDrag').setTokens({
  3647. 'dragClass': css,
  3648. 'dragTitle': config.dragTitle,
  3649. 'dragIcon': config.dragIcon
  3650. });
  3651. }
  3652. return template.setTokens({
  3653. 'delete': btnDelete,
  3654. 'upload': btnUpload,
  3655. 'download': btnDownload,
  3656. 'zoom': btnZoom,
  3657. 'drag': btnDrag,
  3658. 'other': otherButtons
  3659. });
  3660. },
  3661. _browse: function (e) {
  3662. var self = this;
  3663. if (e && e.isDefaultPrevented() || !self._raise('filebrowse')) {
  3664. return;
  3665. }
  3666. if (self.isError && !self.isAjaxUpload) {
  3667. self.clear();
  3668. }
  3669. self.$captionContainer.focus();
  3670. },
  3671. _filterDuplicate: function (file, files, fileIds) {
  3672. var self = this, fileId = self._getFileId(file);
  3673. if (fileId && fileIds && fileIds.indexOf(fileId) > -1) {
  3674. return;
  3675. }
  3676. if (!fileIds) {
  3677. fileIds = [];
  3678. }
  3679. files.push(file);
  3680. fileIds.push(fileId);
  3681. },
  3682. _change: function (e) {
  3683. var self = this;
  3684. if (self.changeTriggered) {
  3685. return;
  3686. }
  3687. var $el = self.$element, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload,
  3688. tfiles = [], files = isDragDrop ? arguments[1] : $el.get(0).files, total,
  3689. maxCount = !isAjaxUpload && $h.isEmpty($el.attr('multiple')) ? 1 : self.maxFileCount,
  3690. len, ctr = self.filestack.length, isSingleUpload = $h.isEmpty($el.attr('multiple')),
  3691. flagSingle = (isSingleUpload && ctr > 0), fileIds = self._getFileIds(),
  3692. throwError = function (mesg, file, previewId, index) {
  3693. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  3694. p2 = {id: previewId, index: index, file: file, files: files};
  3695. return isAjaxUpload ? self._showUploadError(mesg, p1) : self._showError(mesg, p2);
  3696. },
  3697. maxCountCheck = function (n, m) {
  3698. var msg = self.msgFilesTooMany.replace('{m}', m).replace('{n}', n);
  3699. self.isError = throwError(msg, null, null, null);
  3700. self.$captionContainer.removeClass('icon-visible');
  3701. self._setCaption('', true);
  3702. self.$container.removeClass('file-input-new file-input-ajax-new');
  3703. };
  3704. self.reader = null;
  3705. self._resetUpload();
  3706. self._hideFileIcon();
  3707. if (self.dropZoneEnabled) {
  3708. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  3709. }
  3710. if (isAjaxUpload) {
  3711. $.each(files, function (vKey, vFile) {
  3712. self._filterDuplicate(vFile, tfiles, fileIds);
  3713. });
  3714. } else {
  3715. if (e.target && e.target.files === undefined) {
  3716. files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
  3717. } else {
  3718. files = e.target.files || {};
  3719. }
  3720. tfiles = files;
  3721. }
  3722. if ($h.isEmpty(tfiles) || tfiles.length === 0) {
  3723. if (!isAjaxUpload) {
  3724. self.clear();
  3725. }
  3726. self._raise('fileselectnone');
  3727. return;
  3728. }
  3729. self._resetErrors();
  3730. len = tfiles.length;
  3731. total = self._getFileCount(isAjaxUpload ? (self.getFileStack().length + len) : len);
  3732. if (maxCount > 0 && total > maxCount) {
  3733. if (!self.autoReplace || len > maxCount) {
  3734. maxCountCheck((self.autoReplace && len > maxCount ? len : total), maxCount);
  3735. return;
  3736. }
  3737. if (total > maxCount) {
  3738. self._resetPreviewThumbs(isAjaxUpload);
  3739. }
  3740. } else {
  3741. if (!isAjaxUpload || flagSingle) {
  3742. self._resetPreviewThumbs(false);
  3743. if (flagSingle) {
  3744. self.clearStack();
  3745. }
  3746. } else {
  3747. if (isAjaxUpload && ctr === 0 && (!self.previewCache.count() || self.overwriteInitial)) {
  3748. self._resetPreviewThumbs(true);
  3749. }
  3750. }
  3751. }
  3752. if (self.isPreviewable) {
  3753. self.readFiles(tfiles);
  3754. } else {
  3755. self._updateFileDetails(1);
  3756. }
  3757. },
  3758. _abort: function (params) {
  3759. var self = this, data;
  3760. if (self.ajaxAborted && typeof self.ajaxAborted === 'object' && self.ajaxAborted.message !== undefined) {
  3761. data = $.extend(true, {}, self._getOutData(), params);
  3762. data.abortData = self.ajaxAborted.data || {};
  3763. data.abortMessage = self.ajaxAborted.message;
  3764. self._setProgress(101, self.$progress, self.msgCancelled);
  3765. self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  3766. self.cancel();
  3767. return true;
  3768. }
  3769. return !!self.ajaxAborted;
  3770. },
  3771. _resetFileStack: function () {
  3772. var self = this, i = 0, newstack = [], newnames = [], newids = [];
  3773. self._getThumbs().each(function () {
  3774. var $thumb = $(this), ind = $thumb.attr('data-fileindex'), file = self.filestack[ind],
  3775. pid = $thumb.attr('id');
  3776. if (ind === '-1' || ind === -1) {
  3777. return;
  3778. }
  3779. if (file !== undefined) {
  3780. newstack[i] = file;
  3781. newnames[i] = self._getFileName(file);
  3782. newids[i] = self._getFileId(file);
  3783. $thumb.attr({'id': self.previewInitId + '-' + i, 'data-fileindex': i});
  3784. i++;
  3785. } else {
  3786. $thumb.attr({'id': 'uploaded-' + $h.uniqId(), 'data-fileindex': '-1'});
  3787. }
  3788. self.$preview.find('#zoom-' + pid).attr({
  3789. 'id': 'zoom-' + $thumb.attr('id'),
  3790. 'data-fileindex': $thumb.attr('data-fileindex')
  3791. });
  3792. });
  3793. self.filestack = newstack;
  3794. self.filenames = newnames;
  3795. self.fileids = newids;
  3796. },
  3797. _isFileSelectionValid: function (cnt) {
  3798. var self = this;
  3799. cnt = cnt || 0;
  3800. if (self.required && !self.getFilesCount()) {
  3801. self.$errorContainer.html('');
  3802. self._showUploadError(self.msgFileRequired);
  3803. return false;
  3804. }
  3805. if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) {
  3806. self._noFilesError({});
  3807. return false;
  3808. }
  3809. return true;
  3810. },
  3811. clearStack: function () {
  3812. var self = this;
  3813. self.filestack = [];
  3814. self.filenames = [];
  3815. self.fileids = [];
  3816. return self.$element;
  3817. },
  3818. updateStack: function (i, file) {
  3819. var self = this;
  3820. self.filestack[i] = file;
  3821. self.filenames[i] = self._getFileName(file);
  3822. self.fileids[i] = file && self._getFileId(file) || null;
  3823. return self.$element;
  3824. },
  3825. addToStack: function (file) {
  3826. var self = this;
  3827. self.filestack.push(file);
  3828. self.filenames.push(self._getFileName(file));
  3829. self.fileids.push(self._getFileId(file));
  3830. return self.$element;
  3831. },
  3832. getFileStack: function (skipNull) {
  3833. var self = this;
  3834. return self.filestack.filter(function (n) {
  3835. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3836. });
  3837. },
  3838. getFilesCount: function () {
  3839. var self = this, len = self.isAjaxUpload ? self.getFileStack().length : self._inputFileCount();
  3840. return self._getFileCount(len);
  3841. },
  3842. readFiles: function (files) {
  3843. this.reader = new FileReader();
  3844. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  3845. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  3846. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  3847. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  3848. fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
  3849. fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
  3850. maxPreviewSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize),
  3851. canPreview = $preview.length && (!maxPreviewSize || isNaN(maxPreviewSize)),
  3852. throwError = function (msg, file, previewId, index) {
  3853. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  3854. p2 = {id: previewId, index: index, file: file, files: files}, $thumb;
  3855. self._previewDefault(file, previewId, true);
  3856. if (self.isAjaxUpload) {
  3857. self.addToStack(undefined);
  3858. setTimeout(function () {
  3859. readFile(index + 1);
  3860. }, 100);
  3861. } else {
  3862. numFiles = 0;
  3863. }
  3864. self._initFileActions();
  3865. $thumb = $('#' + previewId);
  3866. $thumb.find('.kv-file-upload').hide();
  3867. if (self.removeFromPreviewOnError) {
  3868. $thumb.remove();
  3869. }
  3870. self.isError = self.isAjaxUpload ? self._showUploadError(msg, p1) : self._showError(msg, p2);
  3871. self._updateFileDetails(numFiles);
  3872. };
  3873. self.loadedImages = [];
  3874. self.totalImagesCount = 0;
  3875. $.each(files, function (key, file) {
  3876. var func = self.fileTypeSettings.image;
  3877. if (func && func(file.type)) {
  3878. self.totalImagesCount++;
  3879. }
  3880. });
  3881. readFile = function (i) {
  3882. if ($h.isEmpty($el.attr('multiple'))) {
  3883. numFiles = 1;
  3884. }
  3885. if (i >= numFiles) {
  3886. if (self.isAjaxUpload && self.filestack.length > 0) {
  3887. self._raise('filebatchselected', [self.getFileStack()]);
  3888. } else {
  3889. self._raise('filebatchselected', [files]);
  3890. }
  3891. $container.removeClass('file-thumb-loading');
  3892. $status.html('');
  3893. return;
  3894. }
  3895. var node = ctr + i, previewId = previewInitId + '-' + node, file = files[i], fSizeKB, j, msg,
  3896. fnText = settings.text, fnImage = settings.image, fnHtml = settings.html, typ, chk, typ1, typ2,
  3897. caption = self._getFileName(file, ''), fileSize = (file && file.size || 0) / 1000,
  3898. fileExtExpr = '', previewData = $h.createObjectURL(file), fileCount = 0,
  3899. strTypes = '',
  3900. func, knownTypes = 0, isText, isHtml, isImage, txtFlag, processFileLoaded = function () {
  3901. var msg = msgProgress.setTokens({
  3902. 'index': i + 1,
  3903. 'files': numFiles,
  3904. 'percent': 50,
  3905. 'name': caption
  3906. });
  3907. setTimeout(function () {
  3908. $status.html(msg);
  3909. self._updateFileDetails(numFiles);
  3910. readFile(i + 1);
  3911. }, 100);
  3912. self._raise('fileloaded', [file, previewId, i, reader]);
  3913. };
  3914. if (!file) {
  3915. return;
  3916. }
  3917. if (typLen > 0) {
  3918. for (j = 0; j < typLen; j++) {
  3919. typ1 = fileTypes[j];
  3920. typ2 = self.msgFileTypes[typ1] || typ1;
  3921. strTypes += j === 0 ? typ2 : ', ' + typ2;
  3922. }
  3923. }
  3924. if (caption === false) {
  3925. readFile(i + 1);
  3926. return;
  3927. }
  3928. if (caption.length === 0) {
  3929. msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode($h.getFileName(file), '[unknown]'));
  3930. throwError(msg, file, previewId, i);
  3931. return;
  3932. }
  3933. if (!$h.isEmpty(fileExt)) {
  3934. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  3935. }
  3936. fSizeKB = fileSize.toFixed(2);
  3937. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  3938. msg = self.msgSizeTooLarge.setTokens({
  3939. 'name': caption,
  3940. 'size': fSizeKB,
  3941. 'maxSize': self.maxFileSize
  3942. });
  3943. throwError(msg, file, previewId, i);
  3944. return;
  3945. }
  3946. if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
  3947. msg = self.msgSizeTooSmall.setTokens({
  3948. 'name': caption,
  3949. 'size': fSizeKB,
  3950. 'minSize': self.minFileSize
  3951. });
  3952. throwError(msg, file, previewId, i);
  3953. return;
  3954. }
  3955. if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
  3956. for (j = 0; j < fileTypes.length; j += 1) {
  3957. typ = fileTypes[j];
  3958. func = settings[typ];
  3959. fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type,
  3960. $h.getFileName(file)) ? 1 : 0);
  3961. }
  3962. if (fileCount === 0) {
  3963. msg = self.msgInvalidFileType.setTokens({'name': caption, 'types': strTypes});
  3964. throwError(msg, file, previewId, i);
  3965. return;
  3966. }
  3967. }
  3968. if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
  3969. chk = $h.compare(caption, fileExtExpr);
  3970. fileCount += $h.isEmpty(chk) ? 0 : chk.length;
  3971. if (fileCount === 0) {
  3972. msg = self.msgInvalidFileExtension.setTokens({'name': caption, 'extensions': strExt});
  3973. throwError(msg, file, previewId, i);
  3974. return;
  3975. }
  3976. }
  3977. if (!self.showPreview) {
  3978. if (self.isAjaxUpload) {
  3979. self.addToStack(file);
  3980. }
  3981. setTimeout(function () {
  3982. readFile(i + 1);
  3983. self._updateFileDetails(numFiles);
  3984. }, 100);
  3985. self._raise('fileloaded', [file, previewId, i, reader]);
  3986. return;
  3987. }
  3988. if (!canPreview && fileSize > maxPreviewSize) {
  3989. self.addToStack(file);
  3990. $container.addClass('file-thumb-loading');
  3991. self._previewDefault(file, previewId);
  3992. self._initFileActions();
  3993. self._updateFileDetails(numFiles);
  3994. readFile(i + 1);
  3995. return;
  3996. }
  3997. if ($preview.length && FileReader !== undefined) {
  3998. isText = fnText(file.type, caption);
  3999. isHtml = fnHtml(file.type, caption);
  4000. isImage = fnImage(file.type, caption);
  4001. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  4002. $container.addClass('file-thumb-loading');
  4003. reader.onerror = function (evt) {
  4004. self._errorHandler(evt, caption);
  4005. };
  4006. reader.onload = function (theFile) {
  4007. var hex, fileInfo, uint, byte, bytes = [], contents, mime, readTextImage = function (textFlag) {
  4008. var newReader = new FileReader();
  4009. newReader.onerror = function (theFileNew) {
  4010. self._errorHandler(theFileNew, caption);
  4011. };
  4012. newReader.onload = function (theFileNew) {
  4013. self._previewFile(i, file, theFileNew, previewId, previewData, fileInfo);
  4014. self._initFileActions();
  4015. processFileLoaded();
  4016. };
  4017. if (textFlag) {
  4018. newReader.readAsText(file, self.textEncoding);
  4019. } else {
  4020. newReader.readAsDataURL(file);
  4021. }
  4022. };
  4023. fileInfo = {'name': caption, 'type': file.type};
  4024. $.each(settings, function (k, f) {
  4025. if (k !== 'object' && k !== 'other' && typeof f === 'function' && f(file.type, caption)) {
  4026. knownTypes++;
  4027. }
  4028. });
  4029. if (knownTypes === 0) {// auto detect mime types from content if no known file types detected
  4030. uint = new Uint8Array(theFile.target.result);
  4031. for (j = 0; j < uint.length; j++) {
  4032. byte = uint[j].toString(16);
  4033. bytes.push(byte);
  4034. }
  4035. hex = bytes.join('').toLowerCase().substring(0, 8);
  4036. mime = $h.getMimeType(hex, '', '');
  4037. if ($h.isEmpty(mime)) { // look for ascii text content
  4038. contents = $h.arrayBuffer2String(reader.result);
  4039. mime = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type);
  4040. }
  4041. fileInfo = {'name': caption, 'type': mime};
  4042. isText = fnText(mime, '');
  4043. isHtml = fnHtml(mime, '');
  4044. isImage = fnImage(mime, '');
  4045. txtFlag = isText || isHtml;
  4046. if (txtFlag || isImage) {
  4047. readTextImage(txtFlag);
  4048. return;
  4049. }
  4050. }
  4051. self._previewFile(i, file, theFile, previewId, previewData, fileInfo);
  4052. self._initFileActions();
  4053. processFileLoaded();
  4054. };
  4055. reader.onprogress = function (data) {
  4056. if (data.lengthComputable) {
  4057. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  4058. msg = msgProgress.setTokens({
  4059. 'index': i + 1,
  4060. 'files': numFiles,
  4061. 'percent': progress,
  4062. 'name': caption
  4063. });
  4064. setTimeout(function () {
  4065. $status.html(msg);
  4066. }, 100);
  4067. }
  4068. };
  4069. if (isText || isHtml) {
  4070. reader.readAsText(file, self.textEncoding);
  4071. } else {
  4072. if (isImage) {
  4073. reader.readAsDataURL(file);
  4074. } else {
  4075. reader.readAsArrayBuffer(file);
  4076. }
  4077. }
  4078. } else {
  4079. self._previewDefault(file, previewId);
  4080. setTimeout(function () {
  4081. readFile(i + 1);
  4082. self._updateFileDetails(numFiles);
  4083. }, 100);
  4084. self._raise('fileloaded', [file, previewId, i, reader]);
  4085. }
  4086. self.addToStack(file);
  4087. };
  4088. readFile(0);
  4089. self._updateFileDetails(numFiles, false);
  4090. },
  4091. lock: function () {
  4092. var self = this;
  4093. self._resetErrors();
  4094. self.disable();
  4095. if (self.showRemove) {
  4096. self.$container.find('.fileinput-remove').hide();
  4097. }
  4098. if (self.showCancel) {
  4099. self.$container.find('.fileinput-cancel').show();
  4100. }
  4101. self._raise('filelock', [self.filestack, self._getExtraData()]);
  4102. return self.$element;
  4103. },
  4104. unlock: function (reset) {
  4105. var self = this;
  4106. if (reset === undefined) {
  4107. reset = true;
  4108. }
  4109. self.enable();
  4110. if (self.showCancel) {
  4111. self.$container.find('.fileinput-cancel').hide();
  4112. }
  4113. if (self.showRemove) {
  4114. self.$container.find('.fileinput-remove').show();
  4115. }
  4116. if (reset) {
  4117. self._resetFileStack();
  4118. }
  4119. self._raise('fileunlock', [self.filestack, self._getExtraData()]);
  4120. return self.$element;
  4121. },
  4122. cancel: function () {
  4123. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  4124. if (len > 0) {
  4125. for (i = 0; i < len; i += 1) {
  4126. self.cancelling = true;
  4127. xhr[i].abort();
  4128. }
  4129. }
  4130. self._setProgressCancelled();
  4131. self._getThumbs().each(function () {
  4132. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  4133. $thumb.removeClass('file-uploading');
  4134. if (self.filestack[ind] !== undefined) {
  4135. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  4136. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  4137. }
  4138. self.unlock();
  4139. });
  4140. return self.$element;
  4141. },
  4142. clear: function () {
  4143. var self = this, cap;
  4144. if (!self._raise('fileclear')) {
  4145. return;
  4146. }
  4147. self.$btnUpload.removeAttr('disabled');
  4148. self._getThumbs().find('video,audio,img').each(function () {
  4149. $h.cleanMemory($(this));
  4150. });
  4151. self._clearFileInput();
  4152. self._resetUpload();
  4153. self.clearStack();
  4154. self._resetErrors(true);
  4155. if (self._hasInitialPreview()) {
  4156. self._showFileIcon();
  4157. self._resetPreview();
  4158. self._initPreviewActions();
  4159. self.$container.removeClass('file-input-new');
  4160. } else {
  4161. self._getThumbs().each(function () {
  4162. self._clearObjects($(this));
  4163. });
  4164. if (self.isAjaxUpload) {
  4165. self.previewCache.data = {};
  4166. }
  4167. self.$preview.html('');
  4168. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  4169. self.$caption.attr('title', '').val(cap);
  4170. $h.addCss(self.$container, 'file-input-new');
  4171. self._validateDefaultPreview();
  4172. }
  4173. if (self.$container.find($h.FRAMES).length === 0) {
  4174. if (!self._initCaption()) {
  4175. self.$captionContainer.removeClass('icon-visible');
  4176. }
  4177. }
  4178. self._hideFileIcon();
  4179. self._raise('filecleared');
  4180. self.$captionContainer.focus();
  4181. self._setFileDropZoneTitle();
  4182. return self.$element;
  4183. },
  4184. reset: function () {
  4185. var self = this;
  4186. if (!self._raise('filereset')) {
  4187. return;
  4188. }
  4189. self._resetPreview();
  4190. self.$container.find('.fileinput-filename').text('');
  4191. $h.addCss(self.$container, 'file-input-new');
  4192. if (self.getFrames().length || self.dropZoneEnabled) {
  4193. self.$container.removeClass('file-input-new');
  4194. }
  4195. self.clearStack();
  4196. self.formdata = {};
  4197. self._setFileDropZoneTitle();
  4198. return self.$element;
  4199. },
  4200. disable: function () {
  4201. var self = this;
  4202. self.isDisabled = true;
  4203. self._raise('filedisabled');
  4204. self.$element.attr('disabled', 'disabled');
  4205. self.$container.find('.kv-fileinput-caption').addClass('file-caption-disabled');
  4206. self.$container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  4207. .attr('disabled', true);
  4208. $h.addCss(self.$container.find('.btn-file'), 'disabled');
  4209. self._initDragDrop();
  4210. return self.$element;
  4211. },
  4212. enable: function () {
  4213. var self = this;
  4214. self.isDisabled = false;
  4215. self._raise('fileenabled');
  4216. self.$element.removeAttr('disabled');
  4217. self.$container.find('.kv-fileinput-caption').removeClass('file-caption-disabled');
  4218. self.$container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  4219. .removeAttr('disabled');
  4220. self.$container.find('.btn-file').removeClass('disabled');
  4221. self._initDragDrop();
  4222. return self.$element;
  4223. },
  4224. upload: function () {
  4225. var self = this, totLen = self.getFileStack().length, i, outData, len,
  4226. hasExtraData = !$.isEmptyObject(self._getExtraData());
  4227. if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) {
  4228. return;
  4229. }
  4230. self._resetUpload();
  4231. if (totLen === 0 && !hasExtraData) {
  4232. self._showUploadError(self.msgUploadEmpty);
  4233. return;
  4234. }
  4235. self.$progress.show();
  4236. self.uploadCount = 0;
  4237. self.uploadStatus = {};
  4238. self.uploadLog = [];
  4239. self.lock();
  4240. self._setProgress(2);
  4241. if (totLen === 0 && hasExtraData) {
  4242. self._uploadExtraOnly();
  4243. return;
  4244. }
  4245. len = self.filestack.length;
  4246. self.hasInitData = false;
  4247. if (self.uploadAsync) {
  4248. outData = self._getOutData();
  4249. self._raise('filebatchpreupload', [outData]);
  4250. self.fileBatchCompleted = false;
  4251. self.uploadCache = {content: [], config: [], tags: [], append: true};
  4252. self.uploadAsyncCount = self.getFileStack().length;
  4253. for (i = 0; i < len; i++) {
  4254. self.uploadCache.content[i] = null;
  4255. self.uploadCache.config[i] = null;
  4256. self.uploadCache.tags[i] = null;
  4257. }
  4258. self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
  4259. self._initSortable();
  4260. self.cacheInitialPreview = self.getPreview();
  4261. for (i = 0; i < len; i++) {
  4262. if (self.filestack[i]) {
  4263. self._uploadSingle(i, true);
  4264. }
  4265. }
  4266. return;
  4267. }
  4268. self._uploadBatch();
  4269. return self.$element;
  4270. },
  4271. destroy: function () {
  4272. var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace;
  4273. $(document).off(ns);
  4274. $(window).off(ns);
  4275. if ($form && $form.length) {
  4276. $form.off(ns);
  4277. }
  4278. if (self.isAjaxUpload) {
  4279. self._clearFileInput();
  4280. }
  4281. self._cleanup();
  4282. self._initPreviewCache();
  4283. $el.insertBefore($cont).off(ns).removeData();
  4284. $cont.off().remove();
  4285. return $el;
  4286. },
  4287. refresh: function (options) {
  4288. var self = this, $el = self.$element;
  4289. if (typeof options !== 'object' || $h.isEmpty(options)) {
  4290. options = self.options;
  4291. } else {
  4292. options = $.extend(true, {}, self.options, options);
  4293. }
  4294. self._init(options, true);
  4295. self._listen();
  4296. return $el;
  4297. },
  4298. zoom: function (frameId) {
  4299. var self = this, $frame = self._getFrame(frameId), $modal = self.$modal;
  4300. if (!$frame) {
  4301. return;
  4302. }
  4303. $h.initModal($modal);
  4304. $modal.html(self._getModalContent());
  4305. self._setZoomContent($frame);
  4306. $modal.modal('show');
  4307. self._initZoomButtons();
  4308. },
  4309. getExif: function (frameId) {
  4310. var self = this, $frame = self._getFrame(frameId);
  4311. return $frame && $frame.data('exif') || null;
  4312. },
  4313. getFrames: function (cssFilter) {
  4314. var self = this, $frames;
  4315. cssFilter = cssFilter || '';
  4316. $frames = self.$preview.find($h.FRAMES + cssFilter);
  4317. if (self.reversePreviewOrder) {
  4318. $frames = $($frames.get().reverse());
  4319. }
  4320. return $frames;
  4321. },
  4322. getPreview: function () {
  4323. var self = this;
  4324. return {
  4325. content: self.initialPreview,
  4326. config: self.initialPreviewConfig,
  4327. tags: self.initialPreviewThumbTags
  4328. };
  4329. }
  4330. };
  4331. $.fn.fileinput = function (option) {
  4332. if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
  4333. return;
  4334. }
  4335. var args = Array.apply(null, arguments), retvals = [];
  4336. args.shift();
  4337. this.each(function () {
  4338. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  4339. theme = options.theme || self.data('theme'), l = {}, t = {},
  4340. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
  4341. if (!data) {
  4342. if (theme) {
  4343. t = $.fn.fileinputThemes[theme] || {};
  4344. }
  4345. if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
  4346. l = $.fn.fileinputLocales[lang] || {};
  4347. }
  4348. opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data());
  4349. data = new FileInput(this, opt);
  4350. self.data('fileinput', data);
  4351. }
  4352. if (typeof option === 'string') {
  4353. retvals.push(data[option].apply(data, args));
  4354. }
  4355. });
  4356. switch (retvals.length) {
  4357. case 0:
  4358. return this;
  4359. case 1:
  4360. return retvals[0];
  4361. default:
  4362. return retvals;
  4363. }
  4364. };
  4365. $.fn.fileinput.defaults = {
  4366. language: 'en',
  4367. showCaption: true,
  4368. showBrowse: true,
  4369. showPreview: true,
  4370. showRemove: true,
  4371. showUpload: true,
  4372. showCancel: true,
  4373. showClose: true,
  4374. showUploadedThumbs: true,
  4375. browseOnZoneClick: false,
  4376. autoReplace: false,
  4377. autoOrientImage: function () { // applicable for JPEG images only and non ios safari
  4378. var ua = window.navigator.userAgent, webkit = !!ua.match(/WebKit/i),
  4379. iOS = !!ua.match(/iP(od|ad|hone)/i), iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
  4380. return !iOSSafari;
  4381. },
  4382. required: false,
  4383. rtl: false,
  4384. hideThumbnailContent: false,
  4385. encodeUrl: true,
  4386. generateFileId: null,
  4387. previewClass: '',
  4388. captionClass: '',
  4389. frameClass: 'krajee-default',
  4390. mainClass: 'file-caption-main',
  4391. mainTemplate: null,
  4392. purifyHtml: true,
  4393. fileSizeGetter: null,
  4394. initialCaption: '',
  4395. initialPreview: [],
  4396. initialPreviewDelimiter: '*$$*',
  4397. initialPreviewAsData: false,
  4398. initialPreviewFileType: 'image',
  4399. initialPreviewConfig: [],
  4400. initialPreviewThumbTags: [],
  4401. previewThumbTags: {},
  4402. initialPreviewShowDelete: true,
  4403. initialPreviewDownloadUrl: '',
  4404. removeFromPreviewOnError: false,
  4405. deleteUrl: '',
  4406. deleteExtraData: {},
  4407. overwriteInitial: true,
  4408. previewZoomButtonIcons: {
  4409. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  4410. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  4411. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  4412. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  4413. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  4414. close: '<i class="glyphicon glyphicon-remove"></i>'
  4415. },
  4416. previewZoomButtonClasses: {
  4417. prev: 'btn btn-navigate',
  4418. next: 'btn btn-navigate',
  4419. toggleheader: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
  4420. fullscreen: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
  4421. borderless: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
  4422. close: 'btn btn-sm btn-kv btn-default btn-outline-secondary'
  4423. },
  4424. previewTemplates: {},
  4425. previewContentTemplates: {},
  4426. preferIconicPreview: false,
  4427. preferIconicZoomPreview: false,
  4428. allowedPreviewTypes: undefined,
  4429. allowedPreviewMimeTypes: null,
  4430. allowedFileTypes: null,
  4431. allowedFileExtensions: null,
  4432. defaultPreviewContent: null,
  4433. customLayoutTags: {},
  4434. customPreviewTags: {},
  4435. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  4436. previewFileIconClass: 'file-other-icon',
  4437. previewFileIconSettings: {},
  4438. previewFileExtSettings: {},
  4439. buttonLabelClass: 'hidden-xs',
  4440. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  4441. browseClass: 'btn btn-primary',
  4442. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  4443. removeClass: 'btn btn-default btn-secondary',
  4444. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  4445. cancelClass: 'btn btn-default btn-secondary',
  4446. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  4447. uploadClass: 'btn btn-default btn-secondary',
  4448. uploadUrl: null,
  4449. uploadUrlThumb: null,
  4450. uploadAsync: true,
  4451. uploadExtraData: {},
  4452. zoomModalHeight: 480,
  4453. minImageWidth: null,
  4454. minImageHeight: null,
  4455. maxImageWidth: null,
  4456. maxImageHeight: null,
  4457. resizeImage: false,
  4458. resizePreference: 'width',
  4459. resizeQuality: 0.92,
  4460. resizeDefaultImageType: 'image/jpeg',
  4461. resizeIfSizeMoreThan: 0, // in KB
  4462. minFileSize: 0,
  4463. maxFileSize: 0,
  4464. maxFilePreviewSize: 25600, // 25 MB
  4465. minFileCount: 0,
  4466. maxFileCount: 0,
  4467. validateInitialCount: false,
  4468. msgValidationErrorClass: 'text-danger',
  4469. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  4470. msgErrorClass: 'file-error-message',
  4471. progressThumbClass: 'progress-bar bg-success progress-bar-success progress-bar-striped active',
  4472. progressClass: 'progress-bar bg-success progress-bar-success progress-bar-striped active',
  4473. progressCompleteClass: 'progress-bar bg-success progress-bar-success',
  4474. progressErrorClass: 'progress-bar bg-danger progress-bar-danger',
  4475. progressUploadThreshold: 99,
  4476. previewFileType: 'image',
  4477. elCaptionContainer: null,
  4478. elCaptionText: null,
  4479. elPreviewContainer: null,
  4480. elPreviewImage: null,
  4481. elPreviewStatus: null,
  4482. elErrorContainer: null,
  4483. errorCloseButton: $h.closeButton('kv-error-close'),
  4484. slugCallback: null,
  4485. dropZoneEnabled: true,
  4486. dropZoneTitleClass: 'file-drop-zone-title',
  4487. fileActionSettings: {},
  4488. otherActionButtons: '',
  4489. textEncoding: 'UTF-8',
  4490. ajaxSettings: {},
  4491. ajaxDeleteSettings: {},
  4492. showAjaxErrorDetails: true,
  4493. mergeAjaxCallbacks: false,
  4494. mergeAjaxDeleteCallbacks: false,
  4495. retryErrorUploads: true,
  4496. reversePreviewOrder: false
  4497. };
  4498. // noinspection HtmlUnknownAttribute
  4499. $.fn.fileinputLocales.en = {
  4500. fileSingle: 'file',
  4501. filePlural: 'files',
  4502. browseLabel: 'Browse &hellip;',
  4503. removeLabel: 'Remove',
  4504. removeTitle: 'Clear selected files',
  4505. cancelLabel: 'Cancel',
  4506. cancelTitle: 'Abort ongoing upload',
  4507. uploadLabel: 'Upload',
  4508. uploadTitle: 'Upload selected files',
  4509. msgNo: 'No',
  4510. msgNoFilesSelected: 'No files selected',
  4511. msgCancelled: 'Cancelled',
  4512. msgPlaceholder: 'Select {files}...',
  4513. msgZoomModalHeading: 'Detailed Preview',
  4514. msgFileRequired: 'You must select a file to upload.',
  4515. msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  4516. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  4517. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  4518. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  4519. msgFileNotFound: 'File "{name}" not found!',
  4520. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  4521. msgFileNotReadable: 'File "{name}" is not readable.',
  4522. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  4523. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  4524. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  4525. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  4526. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  4527. msgFileTypes: {
  4528. 'image': 'image',
  4529. 'html': 'HTML',
  4530. 'text': 'text',
  4531. 'video': 'video',
  4532. 'audio': 'audio',
  4533. 'flash': 'flash',
  4534. 'pdf': 'PDF',
  4535. 'object': 'object'
  4536. },
  4537. msgUploadAborted: 'The file upload was aborted',
  4538. msgUploadThreshold: 'Processing...',
  4539. msgUploadBegin: 'Initializing...',
  4540. msgUploadEnd: 'Done',
  4541. msgUploadEmpty: 'No valid data available for upload.',
  4542. msgUploadError: 'Error',
  4543. msgValidationError: 'Validation Error',
  4544. msgLoading: 'Loading file {index} of {files} &hellip;',
  4545. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  4546. msgSelected: '{n} {files} selected',
  4547. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  4548. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  4549. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  4550. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  4551. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  4552. msgImageResizeError: 'Could not get the image dimensions to resize.',
  4553. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  4554. msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  4555. msgAjaxProgressError: '{operation} failed',
  4556. ajaxOperations: {
  4557. deleteThumb: 'file delete',
  4558. uploadThumb: 'file upload',
  4559. uploadBatch: 'batch file upload',
  4560. uploadExtra: 'form data upload'
  4561. },
  4562. dropZoneTitle: 'Drag & drop files here &hellip;',
  4563. dropZoneClickTitle: '<br>(or click to select {files})',
  4564. previewZoomButtonTitles: {
  4565. prev: 'View previous file',
  4566. next: 'View next file',
  4567. toggleheader: 'Toggle header',
  4568. fullscreen: 'Toggle full screen',
  4569. borderless: 'Toggle borderless mode',
  4570. close: 'Close detailed preview'
  4571. },
  4572. usePdfRenderer: function () {
  4573. //noinspection JSUnresolvedVariable
  4574. var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
  4575. return !!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i) || isIE11;
  4576. },
  4577. pdfRendererUrl: '',
  4578. pdfRendererTemplate: '<iframe class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}></iframe>'
  4579. };
  4580. $.fn.fileinput.Constructor = FileInput;
  4581. /**
  4582. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  4583. */
  4584. $(document).ready(function () {
  4585. var $input = $('input.file[type=file]');
  4586. if ($input.length) {
  4587. $input.fileinput();
  4588. }
  4589. });
  4590. }));