fileinput.js 251 KB

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