fileinput.js 256 KB

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