fileinput.js 257 KB

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