fileinput.js 199 KB

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