fileinput.js 287 KB

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