fileinput.js 265 KB

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