fileinput.js 197 KB

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