fileinput.js 178 KB

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