fileinput.js 204 KB

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