fileinput.js 258 KB

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