fileinput.js 199 KB

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