fileinput.js 259 KB

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