fileinput.js 275 KB

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