fileinput.js 251 KB

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