fileinput.js 284 KB

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