fileinput.js 285 KB

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