fileinput.js 203 KB

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