fileinput.js 299 KB

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