fileinput.js 179 KB

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