fileinput.js 299 KB

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