fileinput.js 276 KB

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