fileinput.js 298 KB

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