fileinput.js 203 KB

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