fileinput.js 257 KB

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