fileinput.js 204 KB

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