fileinput.js 275 KB

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