fileinput.js 202 KB

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