fileinput.js 260 KB

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