fileinput.js 298 KB

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