fileinput.js 205 KB

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