fileinput.js 204 KB

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