fileinput.js 277 KB

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