fileinput.js 186 KB

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