fileinput.js 283 KB

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