fileinput.js 276 KB

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