fileinput.js 285 KB

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