fileinput.js 197 KB

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