fileinput.js 283 KB

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