fileinput.js 205 KB

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