fileinput.js 275 KB

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