fileinput.js 279 KB

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