fileinput.js 299 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574
  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, isIconic, ext = filename.split('.').pop().toLowerCase(),
  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. alwaysPreview = $.inArray(ext, self.alwaysPreviewFileExtensions) !== -1,
  4359. forcePrevIcon = self.preferIconicPreview && !alwaysPreview,
  4360. forceZoomIcon = self.preferIconicZoomPreview && !alwaysPreview, newCat = forcePrevIcon ? 'other' : cat;
  4361. config = screenW < 400 ? (self.previewSettingsSmall[newCat] || self.defaults.previewSettingsSmall[newCat]) :
  4362. (self.previewSettings[newCat] || self.defaults.previewSettings[newCat]);
  4363. if (config) {
  4364. $.each(config, function (key, val) {
  4365. styleAttribs += key + ':' + val + ';';
  4366. });
  4367. }
  4368. getContent = function (vCat, vData, zoom, frameCss, vZoomData) {
  4369. var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(vCat),
  4370. css = (frameClass || '') + ' ' + frameCss, tokens;
  4371. if (self.frameClass) {
  4372. css = self.frameClass + ' ' + css;
  4373. }
  4374. if (zoom) {
  4375. css = css.replace(' ' + $h.SORT_CSS, '');
  4376. }
  4377. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  4378. if (cat === 'object' && !ftype) {
  4379. $.each(self.defaults.fileTypeSettings, function (key, func) {
  4380. if (key === 'object' || key === 'other') {
  4381. return;
  4382. }
  4383. if (func(fname, ftype)) {
  4384. typeCss = 'type-' + key;
  4385. }
  4386. });
  4387. }
  4388. if (!$h.isEmpty(attrs)) {
  4389. if (attrs.title !== undefined && attrs.title !== null) {
  4390. title = attrs.title;
  4391. }
  4392. if (attrs.alt !== undefined && attrs.alt !== null) {
  4393. alt = title = attrs.alt;
  4394. }
  4395. }
  4396. tokens = {
  4397. 'previewId': id,
  4398. 'caption': caption,
  4399. 'title': title,
  4400. 'alt': alt,
  4401. 'frameClass': css,
  4402. 'type': self._getFileType(ftype),
  4403. 'fileindex': ind,
  4404. 'fileid': fileId || '',
  4405. 'filename': filename,
  4406. 'typeCss': typeCss,
  4407. 'footer': footer,
  4408. 'data': zoom && vZoomData ? self.zoomPlaceholder + '{zoomData}' : vData,
  4409. 'template': templ || cat,
  4410. 'style': styleAttribs ? 'style="' + styleAttribs + '"' : '',
  4411. 'zoomData': vZoomData ? encodeURIComponent(vZoomData) : ''
  4412. };
  4413. if (zoom) {
  4414. tokens.zoomCache = '';
  4415. tokens.zoomData = '{zoomData}';
  4416. }
  4417. return tmplt.setTokens(tokens);
  4418. };
  4419. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  4420. isRotatable = self.fileActionSettings.showRotate && $.inArray(ext, self.rotatableFileExtensions) !== -1;
  4421. if (self.fileActionSettings.showZoom) {
  4422. addFrameCss = 'kv-zoom-thumb';
  4423. if (isRotatable) {
  4424. addFrameCss += ' rotatable' + (forceZoomIcon ? ' hide-rotate' : '');
  4425. }
  4426. zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, addFrameCss, zoomData);
  4427. }
  4428. zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent);
  4429. if (typeof self.sanitizeZoomCache === 'function') {
  4430. zoomContent = self.sanitizeZoomCache(zoomContent);
  4431. }
  4432. addFrameCss = 'kv-preview-thumb';
  4433. if (isRotatable) {
  4434. isIconic = forcePrevIcon || self.hideThumbnailContent || !!self.previewFileIconSettings[ext];
  4435. addFrameCss += ' rotatable' + (isIconic ? ' hide-rotate' : '');
  4436. }
  4437. prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, addFrameCss, zoomData);
  4438. return prevContent.setTokens({zoomCache: zoomContent});
  4439. },
  4440. _addToPreview: function ($preview, content) {
  4441. var self = this, $el;
  4442. content = $h.cspBuffer.stash(content);
  4443. $el = self.reversePreviewOrder ? $preview.prepend(content) : $preview.append(content);
  4444. $h.cspBuffer.apply($preview);
  4445. return $el;
  4446. },
  4447. _previewDefault: function (file, isDisabled) {
  4448. var self = this, $preview = self.$preview;
  4449. if (!self.showPreview) {
  4450. return;
  4451. }
  4452. var fname = $h.getFileName(file), ftype = file ? file.type : '', content, size = file.size || 0,
  4453. caption = self._getFileName(file, ''), isError = isDisabled === true && !self.isAjaxUpload,
  4454. data = $h.createObjectURL(file), fileId = self.fileManager.getId(file),
  4455. previewId = self._getThumbId(fileId);
  4456. self._clearDefaultPreview();
  4457. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, fileId, isError, size);
  4458. self._addToPreview($preview, content);
  4459. self._setThumbAttr(previewId, caption, size);
  4460. if (isDisabled === true && self.isAjaxUpload) {
  4461. self._setThumbStatus(self._getFrame(previewId), 'Error');
  4462. }
  4463. },
  4464. _previewFile: function (i, file, theFile, data, fileInfo) {
  4465. if (!this.showPreview) {
  4466. return;
  4467. }
  4468. var self = this, fname = $h.getFileName(file), ftype = fileInfo.type, content,
  4469. caption = fileInfo.name, cat = self._parseFileType(ftype, fname), $preview = self.$preview,
  4470. fsize = file.size || 0, iData = cat === 'image' ? theFile.target.result : data, fm = self.fileManager,
  4471. fileId = fm.getId(file), previewId = self._getThumbId(fileId);
  4472. /** @namespace window.DOMPurify */
  4473. content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, fileId, false, fsize, fileInfo.filename);
  4474. self._clearDefaultPreview();
  4475. self._addToPreview($preview, content);
  4476. var $thumb = self._getFrame(previewId);
  4477. self._validateImageOrientation($thumb.find('img'), file, previewId, fileId, caption, ftype, fsize, iData);
  4478. self._setThumbAttr(previewId, caption, fsize);
  4479. self._initSortable();
  4480. },
  4481. _setThumbAttr: function (id, caption, size, description) {
  4482. var self = this, $frame = self._getFrame(id);
  4483. if ($frame.length) {
  4484. size = size && size > 0 ? self._getSize(size) : '';
  4485. $frame.data({'caption': caption, 'size': size, 'description': description || ''});
  4486. }
  4487. },
  4488. _setInitThumbAttr: function () {
  4489. var self = this, data = self.previewCache.data, len = self.previewCache.count(true), config,
  4490. caption, size, description, previewId;
  4491. if (len === 0) {
  4492. return;
  4493. }
  4494. for (var i = 0; i < len; i++) {
  4495. config = data.config[i];
  4496. previewId = self.previewInitId + '-' + $h.INIT_FLAG + i;
  4497. caption = $h.ifSet('caption', config, $h.ifSet('filename', config));
  4498. size = $h.ifSet('size', config);
  4499. description = $h.ifSet('description', config);
  4500. self._setThumbAttr(previewId, caption, size, description);
  4501. }
  4502. },
  4503. _slugDefault: function (text) {
  4504. // noinspection RegExpRedundantEscape
  4505. return $h.isEmpty(text, true) ? '' : String(text).replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  4506. },
  4507. _updateFileDetails: function (numFiles) {
  4508. var self = this, $el = self.$element, label, n, log, nFiles, file,
  4509. name = ($h.isIE(9) && $h.findFileName($el.val())) || ($el[0].files[0] && $el[0].files[0].name);
  4510. if (!name && self.fileManager.count() > 0) {
  4511. file = self.fileManager.getFirstFile();
  4512. label = file.nameFmt;
  4513. } else {
  4514. label = name ? self.slug(name) : '_';
  4515. }
  4516. n = self.isAjaxUpload ? self.fileManager.count() : numFiles;
  4517. nFiles = self.previewCache.count(true) + n;
  4518. log = n === 1 ? label : self._getMsgSelected(nFiles, !self.isAjaxUpload && !self.isError);
  4519. if (self.isError) {
  4520. self.$previewContainer.removeClass('file-thumb-loading');
  4521. self._initCapStatus();
  4522. self.$previewStatus.html('');
  4523. self.$captionContainer.removeClass('icon-visible');
  4524. } else {
  4525. self._showFileIcon();
  4526. }
  4527. self._setCaption(log, self.isError);
  4528. self.$container.removeClass('file-input-new file-input-ajax-new');
  4529. self._raise('fileselect', [numFiles, label]);
  4530. if (self.previewCache.count(true)) {
  4531. self._initPreviewActions();
  4532. }
  4533. },
  4534. _setThumbStatus: function ($thumb, status) {
  4535. var self = this;
  4536. if (!self.showPreview) {
  4537. return;
  4538. }
  4539. var icon = 'indicator' + status, msg = icon + 'Title',
  4540. css = 'file-preview-' + status.toLowerCase(),
  4541. $indicator = $thumb.find('.file-upload-indicator'),
  4542. config = self.fileActionSettings;
  4543. $thumb.removeClass('file-preview-success file-preview-error file-preview-paused file-preview-loading');
  4544. if (status === 'Success') {
  4545. $thumb.find('.file-drag-handle').remove();
  4546. }
  4547. $h.setHtml($indicator, config[icon]);
  4548. $indicator.attr('title', config[msg]);
  4549. $thumb.addClass(css);
  4550. if (status === 'Error' && !self.retryErrorUploads) {
  4551. $thumb.find('.kv-file-upload').attr('disabled', true);
  4552. }
  4553. },
  4554. _setProgressCancelled: function () {
  4555. var self = this;
  4556. self._setProgress(101, self.$progress, self.msgCancelled);
  4557. },
  4558. _setProgress: function (p, $el, error, stats) {
  4559. var self = this;
  4560. $el = $el || self.$progress;
  4561. if (!$el.length) {
  4562. return;
  4563. }
  4564. var pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold,
  4565. t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate,
  4566. template = pct < 100 ? self.progressTemplate :
  4567. (error ? (self.paused ? self.progressPauseTemplate : self.progressErrorTemplate) : t);
  4568. if (p >= 100) {
  4569. stats = '';
  4570. }
  4571. if (!$h.isEmpty(template)) {
  4572. if (pctLimit && pct > pctLimit && p <= 100) {
  4573. out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold});
  4574. } else {
  4575. out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')});
  4576. }
  4577. stats = stats || '';
  4578. out = out.setTokens({stats: stats});
  4579. $h.setHtml($el, out);
  4580. if (error) {
  4581. $h.setHtml($el.find('[role="progressbar"]'), error);
  4582. }
  4583. }
  4584. },
  4585. _hasFiles: function () {
  4586. var el = this.$element[0];
  4587. return !!(el && el.files && el.files.length);
  4588. },
  4589. _setFileDropZoneTitle: function () {
  4590. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  4591. if (self.isClickable) {
  4592. strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  4593. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  4594. }
  4595. $zone.find('.' + self.dropZoneTitleClass).remove();
  4596. if (!self.showPreview || $zone.length === 0 || self.fileManager.count() > 0 || !self.dropZoneEnabled ||
  4597. self.previewCache.count() > 0 || (!self.isAjaxUpload && self._hasFiles())) {
  4598. return;
  4599. }
  4600. if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) {
  4601. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  4602. }
  4603. self.$container.removeClass('file-input-new');
  4604. $h.addCss(self.$container, 'file-input-ajax-new');
  4605. },
  4606. _getStats: function (stats) {
  4607. var self = this, pendingTime, t;
  4608. if (!self.showUploadStats || !stats || !stats.bitrate) {
  4609. return '';
  4610. }
  4611. t = self._getLayoutTemplate('stats');
  4612. pendingTime = (!stats.elapsed || !stats.bps) ? self.msgCalculatingTime :
  4613. self.msgPendingTime.setTokens({time: $h.getElapsed(Math.ceil(stats.pendingBytes / stats.bps))});
  4614. return t.setTokens({
  4615. uploadSpeed: stats.bitrate,
  4616. pendingTime: pendingTime
  4617. });
  4618. },
  4619. _setResumableProgress: function (pct, stats, $thumb) {
  4620. var self = this, rm = self.resumableManager, obj = $thumb ? rm : self,
  4621. $prog = $thumb ? $thumb.find('.file-thumb-progress') : null;
  4622. if (obj.lastProgress === 0) {
  4623. obj.lastProgress = pct;
  4624. }
  4625. if (pct < obj.lastProgress) {
  4626. pct = obj.lastProgress;
  4627. }
  4628. self._setProgress(pct, $prog, null, self._getStats(stats));
  4629. obj.lastProgress = pct;
  4630. },
  4631. _toggleResumableProgress: function (template, message) {
  4632. var self = this, $progress = self.$progress;
  4633. if ($progress && $progress.length) {
  4634. $h.setHtml($progress, template.setTokens({
  4635. percent: 101,
  4636. status: message,
  4637. stats: ''
  4638. }));
  4639. }
  4640. },
  4641. _setFileUploadStats: function (id, pct, stats) {
  4642. var self = this, $prog = self.$progress;
  4643. if (!self.showPreview && (!$prog || !$prog.length)) {
  4644. return;
  4645. }
  4646. var fm = self.fileManager, rm = self.resumableManager, $thumb = fm.getThumb(id), pctTot,
  4647. totUpSize = 0, totSize = fm.getTotalSize(), totStats = $.extend(true, {}, stats);
  4648. if (self.enableResumableUpload) {
  4649. var loaded = stats.loaded, currUplSize = rm.getUploadedSize(), currTotSize = rm.file.size, totLoaded;
  4650. loaded += currUplSize;
  4651. totLoaded = fm.uploadedSize + loaded;
  4652. pct = $h.round(100 * loaded / currTotSize);
  4653. stats.pendingBytes = currTotSize - currUplSize;
  4654. self._setResumableProgress(pct, stats, $thumb);
  4655. pctTot = Math.floor(100 * totLoaded / totSize);
  4656. totStats.pendingBytes = totSize - totLoaded;
  4657. self._setResumableProgress(pctTot, totStats);
  4658. } else {
  4659. fm.setProgress(id, pct);
  4660. $prog = $thumb && $thumb.length ? $thumb.find('.file-thumb-progress') : null;
  4661. self._setProgress(pct, $prog, null, self._getStats(stats));
  4662. $.each(fm.stats, function (id, cfg) {
  4663. totUpSize += cfg.loaded;
  4664. });
  4665. totStats.pendingBytes = totSize - totUpSize;
  4666. pctTot = $h.round(totUpSize / totSize * 100);
  4667. self._setProgress(pctTot, null, null, self._getStats(totStats));
  4668. }
  4669. },
  4670. _validateMinCount: function () {
  4671. var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount();
  4672. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  4673. self._noFilesError({});
  4674. return false;
  4675. }
  4676. return true;
  4677. },
  4678. _getFileCount: function (fileCount, includeInitial) {
  4679. var self = this, addCount = 0;
  4680. if (includeInitial === undefined) {
  4681. includeInitial = self.validateInitialCount && !self.overwriteInitial;
  4682. }
  4683. if (includeInitial) {
  4684. addCount = self.previewCache.count(true);
  4685. fileCount += addCount;
  4686. }
  4687. return fileCount;
  4688. },
  4689. _getFileId: function (file) {
  4690. return $h.getFileId(file, this.generateFileId);
  4691. },
  4692. _getFileName: function (file, defaultValue) {
  4693. var self = this, fileName = $h.getFileName(file);
  4694. return fileName ? self.slug(fileName) : defaultValue;
  4695. },
  4696. _getFileNames: function (skipNull) {
  4697. var self = this;
  4698. return self.filenames.filter(function (n) {
  4699. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  4700. });
  4701. },
  4702. _setPreviewError: function ($thumb, keepFile) {
  4703. var self = this, removeFrame = self.removeFromPreviewOnError && !self.retryErrorUploads;
  4704. if (!keepFile || removeFrame) {
  4705. self.fileManager.remove($thumb);
  4706. }
  4707. if (!self.showPreview) {
  4708. return;
  4709. }
  4710. if (removeFrame) {
  4711. $thumb.remove();
  4712. return;
  4713. } else {
  4714. self._setThumbStatus($thumb, 'Error');
  4715. }
  4716. self._refreshUploadButton($thumb);
  4717. },
  4718. _refreshUploadButton: function ($thumb) {
  4719. var self = this, $btn = $thumb.find('.kv-file-upload'), cfg = self.fileActionSettings,
  4720. icon = cfg.uploadIcon, title = cfg.uploadTitle;
  4721. if (!$btn.length) {
  4722. return;
  4723. }
  4724. if (self.retryErrorUploads) {
  4725. icon = cfg.uploadRetryIcon;
  4726. title = cfg.uploadRetryTitle;
  4727. }
  4728. $btn.attr('title', title);
  4729. $h.setHtml($btn, icon);
  4730. },
  4731. _isValidSize: function (size, type, $image, $thumb, filename, params) {
  4732. var self = this, msg, dim, $img, tag = size === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type];
  4733. if ($h.isEmpty(limit) || !$image.length) {
  4734. return true;
  4735. }
  4736. $img = $image[0];
  4737. dim = (type === 'Width') ? $img.naturalWidth || $img.width : $img.naturalHeight || $img.height;
  4738. if (size === 'Small' ? dim >= limit : dim <= limit) {
  4739. return true;
  4740. }
  4741. msg = self['msgImage' + type + size] || 'Image "{name}" has a size validation error (limit "{size}").';
  4742. self._showFileError(msg.setTokens({'name': filename, 'size': limit, 'dimension': dim}), params);
  4743. self._setPreviewError($thumb);
  4744. self.fileManager.remove($thumb);
  4745. self._clearFileInput();
  4746. return false;
  4747. },
  4748. _getExifObj: function (data) {
  4749. var self = this, exifObj, error = $h.logMessages.exifWarning;
  4750. if (data.slice(0, 23) !== 'data:image/jpeg;base64,' && data.slice(0, 22) !== 'data:image/jpg;base64,') {
  4751. exifObj = null;
  4752. return;
  4753. }
  4754. try {
  4755. exifObj = window.piexif ? window.piexif.load(data) : null;
  4756. } catch (err) {
  4757. exifObj = null;
  4758. error = err && err.message || '';
  4759. }
  4760. if (!exifObj && self.showExifErrorLog) {
  4761. self._log($h.logMessages.badExifParser, {details: error});
  4762. }
  4763. return exifObj;
  4764. },
  4765. setImageOrientation: function ($img, $zoomImg, value, $thumb) {
  4766. var self = this, invalidImg = !$img || !$img.length, invalidZoomImg = !$zoomImg || !$zoomImg.length, $mark,
  4767. isHidden = false, $div, zoomOnly = invalidImg && $thumb && $thumb.attr('data-template') === 'image', ev;
  4768. if (invalidImg && invalidZoomImg) {
  4769. return;
  4770. }
  4771. ev = 'load.fileinputimageorient';
  4772. if (zoomOnly) {
  4773. $img = $zoomImg;
  4774. $zoomImg = null;
  4775. $img.css(self.previewSettings.image);
  4776. $div = $(document.createElement('div')).appendTo($thumb.find('.kv-file-content'));
  4777. $mark = $(document.createElement('span')).insertBefore($img);
  4778. $img.css('visibility', 'hidden').removeClass('file-zoom-detail').appendTo($div);
  4779. } else {
  4780. isHidden = !$img.is(':visible');
  4781. }
  4782. $img.off(ev).on(ev, function () {
  4783. if (isHidden) {
  4784. self.$preview.removeClass('hide-content');
  4785. $thumb.find('.kv-file-content').css('visibility', 'hidden');
  4786. }
  4787. var img = $img[0], zoomImg = $zoomImg && $zoomImg.length ? $zoomImg[0] : null,
  4788. h = img.offsetHeight, w = img.offsetWidth, r = $h.getRotation(value);
  4789. if (isHidden) {
  4790. $thumb.find('.kv-file-content').css('visibility', 'visible');
  4791. self.$preview.addClass('hide-content');
  4792. }
  4793. $img.data('orientation', value);
  4794. if (zoomImg) {
  4795. $zoomImg.data('orientation', value);
  4796. }
  4797. if (value < 5) {
  4798. $h.setTransform(img, r);
  4799. $h.setTransform(zoomImg, r);
  4800. return;
  4801. }
  4802. var offsetAngle = Math.atan(w / h), origFactor = Math.sqrt(Math.pow(h, 2) + Math.pow(w, 2)),
  4803. scale = !origFactor ? 1 : (h / Math.cos(Math.PI / 2 + offsetAngle)) / origFactor,
  4804. s = ' scale(' + Math.abs(scale) + ')';
  4805. $h.setTransform(img, r + s);
  4806. $h.setTransform(zoomImg, r + s);
  4807. if (zoomOnly) {
  4808. $img.css('visibility', 'visible').insertAfter($mark).addClass('file-zoom-detail');
  4809. $mark.remove();
  4810. $div.remove();
  4811. }
  4812. });
  4813. },
  4814. _validateImageOrientation: function ($img, file, previewId, fileId, caption, ftype, fsize, iData) {
  4815. var self = this, exifObj = null, value, autoOrientImage = self.autoOrientImage, selector;
  4816. exifObj = self._getExifObj(iData);
  4817. if (self.canOrientImage) {
  4818. $img.css('image-orientation', (autoOrientImage ? 'from-image' : 'none'));
  4819. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4820. return;
  4821. }
  4822. selector = $h.getZoomSelector(previewId, ' img');
  4823. value = exifObj ? exifObj['0th'][piexif.ImageIFD.Orientation] : null; // jshint ignore:line
  4824. if (!value) {
  4825. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4826. return;
  4827. }
  4828. self.setImageOrientation($img, $(selector), value, self._getFrame(previewId));
  4829. self._raise('fileimageoriented', {'$img': $img, 'file': file});
  4830. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4831. },
  4832. _validateImage: function (previewId, fileId, fname, ftype, fsize, iData, exifObj) {
  4833. var self = this, $preview = self.$preview, params, w1, w2, $thumb = self._getFrame(previewId),
  4834. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img');
  4835. fname = fname || 'Untitled';
  4836. $img.one('load', function () {
  4837. if ($img.data('validated')) {
  4838. return;
  4839. }
  4840. $img.data('validated', true);
  4841. w1 = $thumb.width();
  4842. w2 = $preview.width();
  4843. if (w1 > w2) {
  4844. $img.css('width', '100%');
  4845. }
  4846. params = {ind: i, id: previewId, fileId: fileId};
  4847. setTimeout(function () {
  4848. var isValidWidth, isValidHeight;
  4849. isValidWidth = self._isValidSize('Small', 'Width', $img, $thumb, fname, params);
  4850. isValidHeight = self._isValidSize('Small', 'Height', $img, $thumb, fname, params);
  4851. if (!self.resizeImage) {
  4852. isValidWidth = isValidWidth && self._isValidSize('Large', 'Width', $img, $thumb, fname, params);
  4853. isValidHeight = isValidHeight && self._isValidSize('Large', 'Height', $img, $thumb, fname, params);
  4854. }
  4855. self._raise('fileimageloaded', [previewId]);
  4856. $thumb.data('exif', exifObj);
  4857. if (isValidWidth && isValidHeight) {
  4858. self.fileManager.addImage(fileId, {
  4859. ind: i,
  4860. img: $img,
  4861. thumb: $thumb,
  4862. pid: previewId,
  4863. typ: ftype,
  4864. siz: fsize,
  4865. validated: false,
  4866. imgData: iData,
  4867. exifObj: exifObj
  4868. });
  4869. self._validateAllImages();
  4870. }
  4871. }, self.processDelay);
  4872. }).one('error', function () {
  4873. self._raise('fileimageloaderror', [previewId]);
  4874. });
  4875. },
  4876. _validateAllImages: function () {
  4877. var self = this, counter = {val: 0}, numImgs = self.fileManager.getImageCount(), fsize,
  4878. minSize = self.resizeIfSizeMoreThan;
  4879. if (numImgs !== self.fileManager.totalImages) {
  4880. return;
  4881. }
  4882. self._raise('fileimagesloaded');
  4883. if (!self.resizeImage) {
  4884. return;
  4885. }
  4886. $.each(self.fileManager.loadedImages, function (id, config) {
  4887. if (!config.validated) {
  4888. fsize = config.siz;
  4889. if (fsize && fsize > minSize * self.bytesToKB) {
  4890. self._getResizedImage(id, config, counter, numImgs);
  4891. }
  4892. config.validated = true;
  4893. }
  4894. });
  4895. },
  4896. _getResizedImage: function (id, config, counter, numImgs) {
  4897. var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob,
  4898. ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  4899. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI,
  4900. context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
  4901. $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr, file, params, evParams;
  4902. throwError = function (msg, params, ev) {
  4903. if (self.isAjaxUpload) {
  4904. self._showFileError(msg, params, ev);
  4905. } else {
  4906. self._showError(msg, params, ev);
  4907. }
  4908. self._setPreviewError($thumb);
  4909. };
  4910. file = self.fileManager.getFile(id);
  4911. params = {id: pid, 'index': ind, fileId: id};
  4912. evParams = [id, pid, ind];
  4913. if (!file || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  4914. if (isValidImage && file) {
  4915. self._raise('fileimageresized', evParams);
  4916. }
  4917. counter.val++;
  4918. if (counter.val === numImgs) {
  4919. self._raise('fileimagesresized');
  4920. }
  4921. if (!isValidImage) {
  4922. throwError(self.msgImageResizeError, params, 'fileimageresizeerror');
  4923. return;
  4924. }
  4925. }
  4926. type = type || self.resizeDefaultImageType;
  4927. chkWidth = width > maxWidth;
  4928. chkHeight = height > maxHeight;
  4929. if (self.resizePreference === 'width') {
  4930. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  4931. } else {
  4932. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  4933. }
  4934. self._resetCanvas();
  4935. width *= ratio;
  4936. height *= ratio;
  4937. canvas.width = width;
  4938. canvas.height = height;
  4939. try {
  4940. context.drawImage(img, 0, 0, width, height);
  4941. dataURI = canvas.toDataURL(type, self.resizeQuality);
  4942. if (exifObj) {
  4943. exifStr = window.piexif.dump(exifObj);
  4944. dataURI = window.piexif.insert(exifStr, dataURI);
  4945. }
  4946. blob = $h.dataURI2Blob(dataURI);
  4947. self.fileManager.setFile(id, blob);
  4948. self._raise('fileimageresized', evParams);
  4949. counter.val++;
  4950. if (counter.val === numImgs) {
  4951. self._raise('fileimagesresized', [undefined, undefined]);
  4952. }
  4953. if (!(blob instanceof Blob)) {
  4954. throwError(self.msgImageResizeError, params, 'fileimageresizeerror');
  4955. }
  4956. } catch (err) {
  4957. counter.val++;
  4958. if (counter.val === numImgs) {
  4959. self._raise('fileimagesresized', [undefined, undefined]);
  4960. }
  4961. msg = self.msgImageResizeException.replace('{errors}', err.message);
  4962. throwError(msg, params, 'fileimageresizeexception');
  4963. }
  4964. },
  4965. _showProgress: function () {
  4966. var self = this;
  4967. if (self.$progress && self.$progress.length) {
  4968. self.$progress.show();
  4969. }
  4970. },
  4971. _hideProgress: function () {
  4972. var self = this;
  4973. if (self.$progress && self.$progress.length) {
  4974. self.$progress.hide();
  4975. }
  4976. },
  4977. _initBrowse: function ($container) {
  4978. var self = this, $el = self.$element;
  4979. if (self.showBrowse) {
  4980. self.$btnFile = $container.find('.btn-file').append($el);
  4981. } else {
  4982. $el.appendTo($container).attr('tabindex', -1);
  4983. $h.addCss($el, 'file-no-browse');
  4984. }
  4985. },
  4986. _initClickable: function () {
  4987. var self = this, $zone, $tmpZone;
  4988. if (!self.isClickable) {
  4989. return;
  4990. }
  4991. $zone = self.$dropZone;
  4992. if (!self.isAjaxUpload) {
  4993. $tmpZone = self.$preview.find('.file-default-preview');
  4994. if ($tmpZone.length) {
  4995. $zone = $tmpZone;
  4996. }
  4997. }
  4998. $h.addCss($zone, 'clickable');
  4999. $zone.attr('tabindex', -1);
  5000. self._handler($zone, 'click', function (e) {
  5001. var $tar = $(e.target);
  5002. if (!self.$errorContainer.is(':visible') && (!$tar.parents(
  5003. '.file-preview-thumbnails').length || $tar.parents(
  5004. '.file-default-preview').length)) {
  5005. self.$element.data('zoneClicked', true).trigger('click');
  5006. $zone.blur();
  5007. }
  5008. });
  5009. },
  5010. _initCaption: function () {
  5011. var self = this, cap = self.initialCaption || '';
  5012. if (self.overwriteInitial || $h.isEmpty(cap)) {
  5013. self.$caption.val('');
  5014. return false;
  5015. }
  5016. self._setCaption(cap);
  5017. return true;
  5018. },
  5019. _setCaption: function (content, isError) {
  5020. var self = this, title, out, icon, n, cap, file;
  5021. if (!self.$caption.length) {
  5022. return;
  5023. }
  5024. self.$captionContainer.removeClass('icon-visible');
  5025. if (isError) {
  5026. title = $('<div>' + self.msgValidationError + '</div>').text();
  5027. n = self.fileManager.count();
  5028. if (n) {
  5029. file = self.fileManager.getFirstFile();
  5030. cap = n === 1 && file ? file.nameFmt : self._getMsgSelected(n);
  5031. } else {
  5032. cap = self._getMsgSelected(self.msgNo);
  5033. }
  5034. out = $h.isEmpty(content) ? cap : content;
  5035. icon = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon + '</span>';
  5036. } else {
  5037. if ($h.isEmpty(content)) {
  5038. self.$caption.attr('title', '');
  5039. return;
  5040. }
  5041. title = $('<div>' + content + '</div>').text();
  5042. out = title;
  5043. icon = self._getLayoutTemplate('fileIcon');
  5044. }
  5045. self.$captionContainer.addClass('icon-visible');
  5046. self.$caption.attr('title', title).val(out);
  5047. $h.setHtml(self.$captionIcon, icon);
  5048. },
  5049. _createContainer: function () {
  5050. var self = this, attribs = {'class': 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')},
  5051. $container = $h.createElement($h.cspBuffer.stash(self._renderMain()));
  5052. $h.cspBuffer.apply($container);
  5053. $container.insertBefore(self.$element).attr(attribs);
  5054. self._initBrowse($container);
  5055. if (self.theme) {
  5056. $container.addClass('theme-' + self.theme);
  5057. }
  5058. return $container;
  5059. },
  5060. _refreshContainer: function () {
  5061. var self = this, $container = self.$container, $el = self.$element;
  5062. $el.insertAfter($container);
  5063. $h.setHtml($container, self._renderMain());
  5064. self._initBrowse($container);
  5065. self._validateDisabled();
  5066. },
  5067. _validateDisabled: function () {
  5068. var self = this;
  5069. self.$caption.attr({readonly: self.isDisabled});
  5070. },
  5071. _setTabIndex: function (type, html) {
  5072. var self = this, index = self.tabIndexConfig[type];
  5073. return html.setTokens({
  5074. tabIndexConfig: index === undefined || index === null ? '' : 'tabindex="' + index + '"'
  5075. });
  5076. },
  5077. _renderMain: function () {
  5078. var self = this,
  5079. dropCss = self.dropZoneEnabled ? ' file-drop-zone' : 'file-drop-disabled',
  5080. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  5081. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  5082. .setTokens({'class': self.previewClass, 'dropClass': dropCss}),
  5083. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  5084. caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'});
  5085. caption = self._setTabIndex('caption', caption);
  5086. return self.mainTemplate.setTokens({
  5087. 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''),
  5088. 'inputGroupClass': self.inputGroupClass,
  5089. 'preview': preview,
  5090. 'close': close,
  5091. 'caption': caption,
  5092. 'upload': self._renderButton('upload'),
  5093. 'remove': self._renderButton('remove'),
  5094. 'cancel': self._renderButton('cancel'),
  5095. 'pause': self._renderButton('pause'),
  5096. 'browse': self._renderButton('browse')
  5097. });
  5098. },
  5099. _renderButton: function (type) {
  5100. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  5101. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  5102. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  5103. switch (type) {
  5104. case 'remove':
  5105. if (!self.showRemove) {
  5106. return '';
  5107. }
  5108. break;
  5109. case 'cancel':
  5110. if (!self.showCancel) {
  5111. return '';
  5112. }
  5113. css += ' kv-hidden';
  5114. break;
  5115. case 'pause':
  5116. if (!self.showPause) {
  5117. return '';
  5118. }
  5119. css += ' kv-hidden';
  5120. break;
  5121. case 'upload':
  5122. if (!self.showUpload) {
  5123. return '';
  5124. }
  5125. if (self.isAjaxUpload && !self.isDisabled) {
  5126. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  5127. } else {
  5128. btnType = 'submit';
  5129. }
  5130. break;
  5131. case 'browse':
  5132. if (!self.showBrowse) {
  5133. return '';
  5134. }
  5135. tmplt = self._getLayoutTemplate('btnBrowse');
  5136. break;
  5137. default:
  5138. return '';
  5139. }
  5140. tmplt = self._setTabIndex(type, tmplt);
  5141. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  5142. if (!$h.isEmpty(label)) {
  5143. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  5144. }
  5145. return tmplt.setTokens({
  5146. 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label
  5147. });
  5148. },
  5149. _renderThumbProgress: function () {
  5150. var self = this;
  5151. return '<div class="file-thumb-progress kv-hidden">' +
  5152. self.progressInfoTemplate.setTokens({percent: 101, status: self.msgUploadBegin, stats: ''}) +
  5153. '</div>';
  5154. },
  5155. _renderFileFooter: function (cat, caption, size, width, isError) {
  5156. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  5157. upl = config.showUpload, rot = config.showRotate, zoom = config.showZoom, out, params,
  5158. template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'),
  5159. ind = isError ? config.indicatorError : config.indicatorNew,
  5160. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle,
  5161. indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title});
  5162. size = self._getSize(size);
  5163. params = {type: cat, caption: caption, size: size, width: width, progress: '', indicator: indicator};
  5164. if (self.isAjaxUpload) {
  5165. params.progress = self._renderThumbProgress();
  5166. params.actions = self._renderFileActions(params, upl, false, rem, rot, zoom, drg, false, false, false);
  5167. } else {
  5168. params.actions = self._renderFileActions(params, false, false, false, false, zoom, drg, false, false, false);
  5169. }
  5170. out = template.setTokens(params);
  5171. out = $h.replaceTags(out, self.previewThumbTags);
  5172. return out;
  5173. },
  5174. _renderFileActions: function (
  5175. cfg,
  5176. showUpl,
  5177. showDwn,
  5178. showDel,
  5179. showRot,
  5180. showZoom,
  5181. showDrag,
  5182. disabled,
  5183. url,
  5184. key,
  5185. isInit,
  5186. dUrl,
  5187. dFile
  5188. ) {
  5189. var self = this;
  5190. if (!cfg.type && isInit) {
  5191. cfg.type = 'image';
  5192. }
  5193. if (self.enableResumableUpload) {
  5194. showUpl = false;
  5195. } else {
  5196. if (typeof showUpl === 'function') {
  5197. showUpl = showUpl(cfg);
  5198. }
  5199. }
  5200. if (typeof showDwn === 'function') {
  5201. showDwn = showDwn(cfg);
  5202. }
  5203. if (typeof showDel === 'function') {
  5204. showDel = showDel(cfg);
  5205. }
  5206. if (typeof showZoom === 'function') {
  5207. showZoom = showZoom(cfg);
  5208. }
  5209. if (typeof showDrag === 'function') {
  5210. showDrag = showDrag(cfg);
  5211. }
  5212. if (typeof showRot === 'function') {
  5213. showRot = showRot(cfg);
  5214. }
  5215. if (!showUpl && !showDwn && !showDel && !showRot && !showZoom && !showDrag) {
  5216. return '';
  5217. }
  5218. var vUrl = url === false ? '' : ' data-url="' + url + '"', btnZoom = '', btnDrag = '', btnRotate = '', css,
  5219. vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '',
  5220. template = self._getLayoutTemplate('actions'), config = self.fileActionSettings,
  5221. otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}),
  5222. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  5223. if (showDel) {
  5224. btnDelete = self._getLayoutTemplate('actionDelete').setTokens({
  5225. 'removeClass': removeClass,
  5226. 'removeIcon': config.removeIcon,
  5227. 'removeTitle': config.removeTitle,
  5228. 'dataUrl': vUrl,
  5229. 'dataKey': vKey,
  5230. 'key': key
  5231. });
  5232. }
  5233. if (showRot) {
  5234. btnRotate = self._getLayoutTemplate('actionRotate').setTokens({
  5235. 'rotateClass': config.rotateClass,
  5236. 'rotateIcon': config.rotateIcon,
  5237. 'rotateTitle': config.rotateTitle
  5238. });
  5239. }
  5240. if (showUpl) {
  5241. btnUpload = self._getLayoutTemplate('actionUpload').setTokens({
  5242. 'uploadClass': config.uploadClass,
  5243. 'uploadIcon': config.uploadIcon,
  5244. 'uploadTitle': config.uploadTitle
  5245. });
  5246. }
  5247. if (showDwn) {
  5248. btnDownload = self._getLayoutTemplate('actionDownload').setTokens({
  5249. 'downloadClass': config.downloadClass,
  5250. 'downloadIcon': config.downloadIcon,
  5251. 'downloadTitle': config.downloadTitle,
  5252. 'downloadUrl': dUrl || self.initialPreviewDownloadUrl
  5253. });
  5254. btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key});
  5255. }
  5256. if (showZoom) {
  5257. btnZoom = self._getLayoutTemplate('actionZoom').setTokens({
  5258. 'zoomClass': config.zoomClass,
  5259. 'zoomIcon': config.zoomIcon,
  5260. 'zoomTitle': config.zoomTitle
  5261. });
  5262. }
  5263. if (showDrag && isInit) {
  5264. css = 'drag-handle-init ' + config.dragClass;
  5265. btnDrag = self._getLayoutTemplate('actionDrag').setTokens({
  5266. 'dragClass': css,
  5267. 'dragTitle': config.dragTitle,
  5268. 'dragIcon': config.dragIcon
  5269. });
  5270. }
  5271. return template.setTokens({
  5272. 'delete': btnDelete,
  5273. 'upload': btnUpload,
  5274. 'download': btnDownload,
  5275. 'rotate': btnRotate,
  5276. 'zoom': btnZoom,
  5277. 'drag': btnDrag,
  5278. 'other': otherButtons
  5279. });
  5280. },
  5281. _browse: function (e) {
  5282. var self = this;
  5283. if (e && e.isDefaultPrevented() || !self._raise('filebrowse')) {
  5284. return;
  5285. }
  5286. if (self.isError && !self.isAjaxUpload) {
  5287. self.clear();
  5288. }
  5289. if (self.focusCaptionOnBrowse) {
  5290. self.$captionContainer.focus();
  5291. }
  5292. },
  5293. _change: function (e) {
  5294. var self = this;
  5295. $(document.body).off('focusin.fileinput focusout.fileinput');
  5296. if (self.changeTriggered) {
  5297. self._toggleLoading('hide');
  5298. return;
  5299. }
  5300. self._toggleLoading('show');
  5301. var $el = self.$element, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload,
  5302. tfiles, files = isDragDrop ? arguments[1] : $el[0].files, ctr = self.fileManager.count(),
  5303. total, initCount, len, isSingleUpl = $h.isEmpty($el.attr('multiple')),
  5304. maxCount = !isAjaxUpload && isSingleUpl ? 1 : self.maxFileCount, maxTotCount = self.maxTotalFileCount,
  5305. inclAll = maxTotCount > 0 && maxTotCount > maxCount, flagSingle = (isSingleUpl && ctr > 0),
  5306. throwError = function (mesg, file, previewId, index) {
  5307. var p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files), {id: previewId, index: index}),
  5308. p2 = {id: previewId, index: index, file: file, files: files};
  5309. self.isPersistentError = true;
  5310. self._toggleLoading('hide');
  5311. return isAjaxUpload ? self._showFileError(mesg, p1) : self._showError(mesg, p2);
  5312. },
  5313. maxCountCheck = function (n, m, all) {
  5314. var msg = all ? self.msgTotalFilesTooMany : self.msgFilesTooMany;
  5315. msg = msg.replace('{m}', m).replace('{n}', n);
  5316. self.isError = throwError(msg, null, null, null);
  5317. self.$captionContainer.removeClass('icon-visible');
  5318. self._setCaption('', true);
  5319. self.$container.removeClass('file-input-new file-input-ajax-new');
  5320. };
  5321. self.reader = null;
  5322. self._resetUpload();
  5323. self._hideFileIcon();
  5324. if (self.dropZoneEnabled) {
  5325. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  5326. }
  5327. if (!isAjaxUpload) {
  5328. if (e.target && e.target.files === undefined) {
  5329. files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
  5330. } else {
  5331. files = e.target.files || {};
  5332. }
  5333. }
  5334. tfiles = files;
  5335. if ($h.isEmpty(tfiles) || tfiles.length === 0) {
  5336. if (!isAjaxUpload) {
  5337. self.clear();
  5338. }
  5339. self._raise('fileselectnone');
  5340. return;
  5341. }
  5342. self._resetErrors();
  5343. len = tfiles.length;
  5344. initCount = isAjaxUpload ? (self.fileManager.count() + len) : len;
  5345. total = self._getFileCount(initCount, inclAll ? false : undefined);
  5346. if (maxCount > 0 && total > maxCount) {
  5347. if (!self.autoReplace || len > maxCount) {
  5348. maxCountCheck((self.autoReplace && len > maxCount ? len : total), maxCount);
  5349. return;
  5350. }
  5351. if (total > maxCount) {
  5352. self._resetPreviewThumbs(isAjaxUpload);
  5353. }
  5354. } else {
  5355. if (inclAll) {
  5356. total = self._getFileCount(initCount, true);
  5357. if (maxTotCount > 0 && total > maxTotCount) {
  5358. if (!self.autoReplace || len > maxCount) {
  5359. maxCountCheck((self.autoReplace && len > maxTotCount ? len : total), maxTotCount, true);
  5360. return;
  5361. }
  5362. if (total > maxCount) {
  5363. self._resetPreviewThumbs(isAjaxUpload);
  5364. }
  5365. }
  5366. }
  5367. if (!isAjaxUpload || flagSingle) {
  5368. self._resetPreviewThumbs(false);
  5369. if (flagSingle) {
  5370. self.clearFileStack();
  5371. }
  5372. } else {
  5373. if (isAjaxUpload && ctr === 0 && (!self.previewCache.count(true) || self.overwriteInitial)) {
  5374. self._resetPreviewThumbs(true);
  5375. }
  5376. }
  5377. }
  5378. if (self.autoReplace) {
  5379. self._getThumbs().each(function () {
  5380. var $thumb = $(this);
  5381. if ($thumb.hasClass('file-preview-success') || $thumb.hasClass('file-preview-error')) {
  5382. $thumb.remove();
  5383. }
  5384. });
  5385. }
  5386. self.readFiles(tfiles);
  5387. self._toggleLoading('hide');
  5388. },
  5389. _abort: function (params) {
  5390. var self = this, data;
  5391. if (self.ajaxAborted && typeof self.ajaxAborted === 'object' && self.ajaxAborted.message !== undefined) {
  5392. data = $.extend(true, {}, self._getOutData(null), params);
  5393. data.abortData = self.ajaxAborted.data || {};
  5394. data.abortMessage = self.ajaxAborted.message;
  5395. self._setProgress(101, self.$progress, self.msgCancelled);
  5396. self._showFileError(self.ajaxAborted.message, data, 'filecustomerror');
  5397. self.cancel();
  5398. self.unlock();
  5399. return true;
  5400. }
  5401. return !!self.ajaxAborted;
  5402. },
  5403. _resetFileStack: function () {
  5404. var self = this, i = 0;
  5405. self._getThumbs().each(function () {
  5406. var $thumb = $(this), ind = $thumb.attr('data-fileindex'), pid = $thumb.attr('id');
  5407. if (ind === '-1' || ind === -1) {
  5408. return;
  5409. }
  5410. if (!self._getThumbFile($thumb)) {
  5411. $thumb.attr({'data-fileindex': i});
  5412. i++;
  5413. } else {
  5414. $thumb.attr({'data-fileindex': '-1'});
  5415. }
  5416. self._getZoom(pid).attr({
  5417. 'data-fileindex': $thumb.attr('data-fileindex')
  5418. });
  5419. });
  5420. },
  5421. _isFileSelectionValid: function (cnt) {
  5422. var self = this;
  5423. cnt = cnt || 0;
  5424. if (self.required && !self.getFilesCount()) {
  5425. self.$errorContainer.html('');
  5426. self._showFileError(self.msgFileRequired);
  5427. return false;
  5428. }
  5429. if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) {
  5430. self._noFilesError({});
  5431. return false;
  5432. }
  5433. return true;
  5434. },
  5435. _canPreview: function (file) {
  5436. var self = this;
  5437. if (!file || !self.showPreview || !self.$preview || !self.$preview.length) {
  5438. return false;
  5439. }
  5440. var name = file.name || '', type = file.type || '', size = (file.size || 0) / self.bytesToKB,
  5441. cat = self._parseFileType(type, name), allowedTypes, allowedMimes, allowedExts, skipPreview,
  5442. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  5443. exts = self.allowedPreviewExtensions || [], dTypes = self.disabledPreviewTypes,
  5444. dMimes = self.disabledPreviewMimeTypes, dExts = self.disabledPreviewExtensions || [],
  5445. maxSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize) || 0,
  5446. expAllExt = new RegExp('\\.(' + exts.join('|') + ')$', 'i'),
  5447. expDisExt = new RegExp('\\.(' + dExts.join('|') + ')$', 'i');
  5448. allowedTypes = !types || types.indexOf(cat) !== -1;
  5449. allowedMimes = !mimes || mimes.indexOf(type) !== -1;
  5450. allowedExts = !exts.length || $h.compare(name, expAllExt);
  5451. skipPreview = (dTypes && dTypes.indexOf(cat) !== -1) || (dMimes && dMimes.indexOf(type) !== -1) ||
  5452. (dExts.length && $h.compare(name, expDisExt)) || (maxSize && !isNaN(maxSize) && size > maxSize);
  5453. return !skipPreview && (allowedTypes || allowedMimes || allowedExts);
  5454. },
  5455. addToStack: function (file, id) {
  5456. var self = this;
  5457. self.stackIsUpdating = true;
  5458. self.fileManager.add(file, id);
  5459. self._refreshPreview();
  5460. self.stackIsUpdating = false;
  5461. },
  5462. clearFileStack: function () {
  5463. var self = this;
  5464. self.fileManager.clear();
  5465. self._initResumableUpload();
  5466. if (self.enableResumableUpload) {
  5467. if (self.showPause === null) {
  5468. self.showPause = true;
  5469. }
  5470. if (self.showCancel === null) {
  5471. self.showCancel = false;
  5472. }
  5473. } else {
  5474. self.showPause = false;
  5475. if (self.showCancel === null) {
  5476. self.showCancel = true;
  5477. }
  5478. }
  5479. return self.$element;
  5480. },
  5481. getFileStack: function () {
  5482. return this.fileManager.stack;
  5483. },
  5484. getFileList: function () {
  5485. return this.fileManager.list();
  5486. },
  5487. getFilesSize: function () {
  5488. return this.fileManager.getTotalSize();
  5489. },
  5490. getFilesCount: function (includeInitial) {
  5491. var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount();
  5492. if (includeInitial) {
  5493. len += self.previewCache.count(true);
  5494. }
  5495. return self._getFileCount(len);
  5496. },
  5497. _initCapStatus: function (status) {
  5498. var self = this, $cap = self.$caption;
  5499. $cap.removeClass('is-valid file-processing');
  5500. if (!status) {
  5501. return;
  5502. }
  5503. if (status === 'processing') {
  5504. $cap.addClass('file-processing');
  5505. } else {
  5506. $cap.addClass('is-valid');
  5507. }
  5508. },
  5509. _toggleLoading: function (type) {
  5510. var self = this;
  5511. self.$previewStatus.html(type === 'hide' ? '' : self.msgProcessing);
  5512. self.$container.removeClass('file-thumb-loading');
  5513. self._initCapStatus(type === 'hide' ? '' : 'processing');
  5514. if (type !== 'hide') {
  5515. if (self.dropZoneEnabled) {
  5516. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  5517. }
  5518. self.$container.addClass('file-thumb-loading');
  5519. }
  5520. },
  5521. _initFileSelected: function () {
  5522. var self = this, $el = self.$element, $body = $(document.body), ev = 'focusin.fileinput focusout.fileinput';
  5523. if ($body.length) {
  5524. $body.off(ev).on('focusout.fileinput', function () {
  5525. self._toggleLoading('show');
  5526. }).on('focusin.fileinput', function () {
  5527. setTimeout(function () {
  5528. if (!$el.val()) {
  5529. self._toggleLoading('hide');
  5530. self._setFileDropZoneTitle();
  5531. }
  5532. $body.off(ev);
  5533. }, 2500);
  5534. });
  5535. } else {
  5536. self._toggleLoading('hide');
  5537. }
  5538. },
  5539. readFiles: function (files) {
  5540. this.reader = new FileReader();
  5541. var self = this, reader = self.reader, $container = self.$previewContainer,
  5542. $status = self.$previewStatus, msgLoading = self.msgLoading, msgProgress = self.msgProgress,
  5543. previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings,
  5544. readFile, fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
  5545. fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
  5546. throwError = function (msg, file, previewId, index, fileId) {
  5547. var $thumb, p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files),
  5548. {id: previewId, index: index, fileId: fileId}),
  5549. p2 = {id: previewId, index: index, fileId: fileId, file: file, files: files};
  5550. self._previewDefault(file, true);
  5551. $thumb = self._getFrame(previewId, true);
  5552. self._toggleLoading('hide');
  5553. if (self.isAjaxUpload) {
  5554. setTimeout(function () {
  5555. readFile(index + 1);
  5556. }, self.processDelay);
  5557. } else {
  5558. self.unlock();
  5559. numFiles = 0;
  5560. }
  5561. if (self.removeFromPreviewOnError && $thumb.length) {
  5562. $thumb.remove();
  5563. } else {
  5564. self._initFileActions();
  5565. $thumb.find('.kv-file-upload').remove();
  5566. }
  5567. self.isPersistentError = true;
  5568. self.isError = self.isAjaxUpload ? self._showFileError(msg, p1) : self._showError(msg, p2);
  5569. self._updateFileDetails(numFiles);
  5570. };
  5571. self.fileManager.clearImages();
  5572. $.each(files, function (key, file) {
  5573. var func = self.fileTypeSettings.image;
  5574. if (func && func(file.type)) {
  5575. self.fileManager.totalImages++;
  5576. }
  5577. });
  5578. readFile = function (i) {
  5579. var $error = self.$errorContainer, errors, fm = self.fileManager;
  5580. if (i >= numFiles) {
  5581. self.unlock();
  5582. if (self.duplicateErrors.length) {
  5583. errors = '<li>' + self.duplicateErrors.join('</li><li>') + '</li>';
  5584. if ($error.find('ul').length === 0) {
  5585. $h.setHtml($error, self.errorCloseButton + '<ul>' + errors + '</ul>');
  5586. } else {
  5587. $error.find('ul').append(errors);
  5588. }
  5589. $error.fadeIn(self.fadeDelay);
  5590. self._handler($error.find('.kv-error-close'), 'click', function () {
  5591. $error.fadeOut(self.fadeDelay);
  5592. });
  5593. self.duplicateErrors = [];
  5594. }
  5595. if (self.isAjaxUpload) {
  5596. self._raise('filebatchselected', [fm.stack]);
  5597. if (fm.count() === 0 && !self.isError) {
  5598. self.reset();
  5599. }
  5600. } else {
  5601. self._raise('filebatchselected', [files]);
  5602. }
  5603. $container.removeClass('file-thumb-loading');
  5604. self._initCapStatus('valid');
  5605. $status.html('');
  5606. return;
  5607. }
  5608. self.lock(true);
  5609. var file = files[i], id, previewId, fileProcessed,
  5610. fSize = (file && file.size || 0), sizeHuman = self._getSize(fSize, true), j, msg,
  5611. fnImage = settings.image, chk, typ, typ1, typ2, caption, fileSize = fSize / self.bytesToKB,
  5612. fileExtExpr = '', previewData, fileCount = 0, strTypes = '', fileId, canLoad,
  5613. fileReaderAborted = false, func, knownTypes = 0, isImage, processFileLoaded, initFileData;
  5614. initFileData = function (dataSource) {
  5615. dataSource = dataSource || file;
  5616. id = fileId = self._getFileId(file);
  5617. previewId = previewInitId + '-' + id;
  5618. previewData = $h.createObjectURL(dataSource);
  5619. caption = self._getFileName(file, '');
  5620. };
  5621. processFileLoaded = function () {
  5622. var isImageResized = !!fm.loadedImages[id], msg = msgProgress.setTokens({
  5623. 'index': i + 1,
  5624. 'files': numFiles,
  5625. 'percent': 50,
  5626. 'name': caption
  5627. });
  5628. setTimeout(function () {
  5629. $status.html(msg);
  5630. self._updateFileDetails(numFiles);
  5631. if (self.getFilesCount(true) > 0 && self.getFrames(':visible')) {
  5632. self.$dropZone.find('.' + self.dropZoneTitleClass).remove();
  5633. }
  5634. readFile(i + 1);
  5635. }, self.processDelay);
  5636. if (self._raise('fileloaded', [file, previewId, id, i, reader]) && self.isAjaxUpload) {
  5637. if (!isImageResized) {
  5638. fm.add(file);
  5639. }
  5640. } else {
  5641. if (isImageResized) {
  5642. fm.removeFile(id);
  5643. }
  5644. }
  5645. };
  5646. if (!file) {
  5647. return;
  5648. }
  5649. initFileData();
  5650. if (typLen > 0) {
  5651. for (j = 0; j < typLen; j++) {
  5652. typ1 = fileTypes[j];
  5653. typ2 = self.msgFileTypes[typ1] || typ1;
  5654. strTypes += j === 0 ? typ2 : ', ' + typ2;
  5655. }
  5656. }
  5657. if (caption === false) {
  5658. readFile(i + 1);
  5659. return;
  5660. }
  5661. if (caption.length === 0) {
  5662. msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode($h.getFileName(file), '[unknown]'));
  5663. throwError(msg, file, previewId, i, fileId);
  5664. return;
  5665. }
  5666. if (!$h.isEmpty(fileExt)) {
  5667. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  5668. }
  5669. if (self.isAjaxUpload && fm.exists(fileId) || self._getFrame(previewId, true).length) {
  5670. var p2 = {id: previewId, index: i, fileId: fileId, file: file, files: files};
  5671. msg = self.msgDuplicateFile.setTokens({name: caption, size: sizeHuman});
  5672. if (self.isAjaxUpload) {
  5673. if (!self.stackIsUpdating) {
  5674. self.duplicateErrors.push(msg);
  5675. self.isDuplicateError = true;
  5676. self._raise('fileduplicateerror', [file, fileId, caption, sizeHuman, previewId, i]);
  5677. }
  5678. readFile(i + 1);
  5679. self._updateFileDetails(numFiles);
  5680. } else {
  5681. self._showError(msg, p2);
  5682. self.unlock();
  5683. numFiles = 0;
  5684. self._clearFileInput();
  5685. self.reset();
  5686. self._updateFileDetails(numFiles);
  5687. }
  5688. return;
  5689. }
  5690. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  5691. msg = self.msgSizeTooLarge.setTokens({
  5692. 'name': caption,
  5693. 'size': sizeHuman,
  5694. 'maxSize': self._getSize(self.maxFileSize * self.bytesToKB, true)
  5695. });
  5696. throwError(msg, file, previewId, i, fileId);
  5697. return;
  5698. }
  5699. if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
  5700. msg = self.msgSizeTooSmall.setTokens({
  5701. 'name': caption,
  5702. 'size': sizeHuman,
  5703. 'minSize': self._getSize(self.minFileSize * self.bytesToKB, true)
  5704. });
  5705. throwError(msg, file, previewId, i, fileId);
  5706. return;
  5707. }
  5708. if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
  5709. for (j = 0; j < fileTypes.length; j += 1) {
  5710. typ = fileTypes[j];
  5711. func = settings[typ];
  5712. fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type,
  5713. $h.getFileName(file)) ? 1 : 0);
  5714. }
  5715. if (fileCount === 0) {
  5716. msg = self.msgInvalidFileType.setTokens({name: caption, types: strTypes});
  5717. throwError(msg, file, previewId, i, fileId);
  5718. return;
  5719. }
  5720. }
  5721. if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
  5722. chk = $h.compare(caption, fileExtExpr);
  5723. fileCount += $h.isEmpty(chk) ? 0 : chk.length;
  5724. if (fileCount === 0) {
  5725. msg = self.msgInvalidFileExtension.setTokens({name: caption, extensions: strExt});
  5726. throwError(msg, file, previewId, i, fileId);
  5727. return;
  5728. }
  5729. }
  5730. if (!self._canPreview(file)) {
  5731. canLoad = self._raise('filebeforeload', [file, i, reader]);
  5732. if (self.isAjaxUpload && canLoad) {
  5733. fm.add(file);
  5734. }
  5735. if (self.showPreview && canLoad) {
  5736. $container.addClass('file-thumb-loading');
  5737. self._initCapStatus('processing');
  5738. self._previewDefault(file);
  5739. self._initFileActions();
  5740. }
  5741. setTimeout(function () {
  5742. if (canLoad) {
  5743. self._updateFileDetails(numFiles);
  5744. }
  5745. readFile(i + 1);
  5746. self._raise('fileloaded', [file, previewId, id, i]);
  5747. }, 10);
  5748. return;
  5749. }
  5750. isImage = fnImage(file.type, caption);
  5751. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  5752. $container.addClass('file-thumb-loading');
  5753. self._initCapStatus('processing');
  5754. reader.onerror = function (evt) {
  5755. self._errorHandler(evt, caption);
  5756. };
  5757. reader.onload = function (theFile) {
  5758. var hex, fileInfo, fileData, byte, bytes = [], contents, mime,
  5759. processPreview = function (fType, ext) {
  5760. if ($h.isEmpty(fType)) { // look for ascii text content
  5761. contents = $h.arrayBuffer2String(reader.result);
  5762. fType = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type);
  5763. }
  5764. fileInfo = {'name': caption, 'type': fType || ''};
  5765. if (ext && typeof File !== "undefined") {
  5766. try {
  5767. var fName = fileInfo.filename = caption + '.' + ext;
  5768. fileProcessed = new File([file], fName, {type: fileInfo.type});
  5769. initFileData(fileProcessed);
  5770. } catch (err) {
  5771. }
  5772. }
  5773. isImage = fnImage(fType, '');
  5774. if (isImage) {
  5775. var newReader = new FileReader();
  5776. newReader.onerror = function (theFileNew) {
  5777. self._errorHandler(theFileNew, caption);
  5778. };
  5779. newReader.onload = function (theFileNew) {
  5780. if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) {
  5781. fileReaderAborted = true;
  5782. self._resetCaption();
  5783. reader.abort();
  5784. $status.html('');
  5785. $container.removeClass('file-thumb-loading');
  5786. self._initCapStatus('valid');
  5787. self.enable();
  5788. return;
  5789. }
  5790. self._previewFile(i, file, theFileNew, previewData, fileInfo);
  5791. self._initFileActions();
  5792. processFileLoaded();
  5793. };
  5794. newReader.readAsDataURL(file);
  5795. return;
  5796. }
  5797. if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) {
  5798. fileReaderAborted = true;
  5799. self._resetCaption();
  5800. reader.abort();
  5801. $status.html('');
  5802. $container.removeClass('file-thumb-loading');
  5803. self._initCapStatus('valid');
  5804. self.enable();
  5805. return;
  5806. }
  5807. self._previewFile(i, file, theFile, previewData, fileInfo);
  5808. self._initFileActions();
  5809. processFileLoaded();
  5810. };
  5811. mime = file.type;
  5812. fileInfo = {'name': caption, 'type': mime};
  5813. $.each(settings, function (k, f) {
  5814. if (k !== 'object' && k !== 'other' && typeof f === 'function' && f(mime, caption)) {
  5815. knownTypes++;
  5816. }
  5817. });
  5818. if (typeof FileTypeParser !== "undefined") {
  5819. fileData = new Uint8Array(theFile.target.result);
  5820. new FileTypeParser().parse(fileData).then(function (result) {
  5821. processPreview(result && result.mime || mime, result && result.ext || '');
  5822. });
  5823. } else {
  5824. if (knownTypes === 0) { // auto detect mime types from content if no known file types detected
  5825. fileData = new Uint8Array(theFile.target.result);
  5826. for (j = 0; j < fileData.length; j++) {
  5827. byte = fileData[j].toString(16);
  5828. bytes.push(byte);
  5829. }
  5830. hex = bytes.join('').toLowerCase().substring(0, 8);
  5831. mime = $h.getMimeType(hex, '', '');
  5832. }
  5833. processPreview(mime);
  5834. }
  5835. };
  5836. reader.onprogress = function (data) {
  5837. if (data.lengthComputable) {
  5838. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  5839. msg = msgProgress.setTokens({
  5840. 'index': i + 1,
  5841. 'files': numFiles,
  5842. 'percent': progress,
  5843. 'name': caption
  5844. });
  5845. setTimeout(function () {
  5846. if (!fileReaderAborted) {
  5847. $status.html(msg);
  5848. }
  5849. }, self.processDelay);
  5850. }
  5851. };
  5852. reader.readAsArrayBuffer(file);
  5853. };
  5854. readFile(0);
  5855. self._updateFileDetails(numFiles);
  5856. },
  5857. lock: function (selectMode) {
  5858. var self = this, $container = self.$container;
  5859. self._resetErrors();
  5860. self.disable();
  5861. if (!selectMode && self.showCancel) {
  5862. $container.find('.fileinput-cancel').show();
  5863. }
  5864. if (!selectMode && self.showPause) {
  5865. $container.find('.fileinput-pause').show();
  5866. }
  5867. self._initCapStatus('processing');
  5868. self._raise('filelock', [self.fileManager.stack, self._getExtraData()]);
  5869. return self.$element;
  5870. },
  5871. unlock: function (reset) {
  5872. var self = this, $container = self.$container;
  5873. if (reset === undefined) {
  5874. reset = true;
  5875. }
  5876. self.enable();
  5877. $container.removeClass('is-locked');
  5878. if (self.showCancel) {
  5879. $container.find('.fileinput-cancel').hide();
  5880. }
  5881. if (self.showPause) {
  5882. $container.find('.fileinput-pause').hide();
  5883. }
  5884. if (reset) {
  5885. self._resetFileStack();
  5886. }
  5887. self._initCapStatus();
  5888. self._raise('fileunlock', [self.fileManager.stack, self._getExtraData()]);
  5889. return self.$element;
  5890. },
  5891. resume: function () {
  5892. var self = this, fm = self.fileManager, flag = false, rm = self.resumableManager;
  5893. fm.bpsLog = [];
  5894. fm.bps = 0;
  5895. if (!self.enableResumableUpload) {
  5896. return self.$element;
  5897. }
  5898. if (self.paused) {
  5899. self._toggleResumableProgress(self.progressPauseTemplate, self.msgUploadResume);
  5900. } else {
  5901. flag = true;
  5902. }
  5903. self.paused = false;
  5904. if (flag) {
  5905. self._toggleResumableProgress(self.progressInfoTemplate, self.msgUploadBegin);
  5906. }
  5907. setTimeout(function () {
  5908. rm.upload();
  5909. }, self.processDelay);
  5910. return self.$element;
  5911. },
  5912. paste: function (e) {
  5913. var self = this, ev = e.originalEvent, files = ev.clipboardData && ev.clipboardData.files || null;
  5914. if (files) {
  5915. self._dropFiles(e, files);
  5916. }
  5917. return self.$element;
  5918. },
  5919. pause: function () {
  5920. var self = this, rm = self.resumableManager, xhr = self.ajaxRequests, len = xhr.length, i,
  5921. pct = rm.getProgress(), actions = self.fileActionSettings, tm = self.taskManager,
  5922. pool = tm.getPool(rm.id);
  5923. if (!self.enableResumableUpload) {
  5924. return self.$element;
  5925. } else {
  5926. if (pool) {
  5927. pool.cancel();
  5928. }
  5929. }
  5930. self._raise('fileuploadpaused', [self.fileManager, rm]);
  5931. if (len > 0) {
  5932. for (i = 0; i < len; i += 1) {
  5933. self.paused = true;
  5934. xhr[i].abort();
  5935. }
  5936. }
  5937. if (self.showPreview) {
  5938. self._getThumbs().each(function () {
  5939. var $thumb = $(this), t = self._getLayoutTemplate('stats'), stats,
  5940. $indicator = $thumb.find('.file-upload-indicator');
  5941. $thumb.removeClass('file-uploading');
  5942. if ($indicator.attr('title') === actions.indicatorLoadingTitle) {
  5943. self._setThumbStatus($thumb, 'Paused');
  5944. stats = t.setTokens({pendingTime: self.msgPaused, uploadSpeed: ''});
  5945. self.paused = true;
  5946. self._setProgress(pct, $thumb.find('.file-thumb-progress'), pct + '%', stats);
  5947. }
  5948. if (!self._getThumbFile($thumb)) {
  5949. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  5950. }
  5951. });
  5952. }
  5953. self._setProgress(101, self.$progress, self.msgPaused);
  5954. return self.$element;
  5955. },
  5956. cancel: function () {
  5957. var self = this, xhr = self.ajaxRequests,
  5958. rm = self.resumableManager, tm = self.taskManager,
  5959. pool = rm ? tm.getPool(rm.id) : undefined, len = xhr.length, i;
  5960. if (self.enableResumableUpload && pool) {
  5961. pool.cancel().done(function () {
  5962. self._setProgressCancelled();
  5963. });
  5964. rm.reset();
  5965. self._raise('fileuploadcancelled', [self.fileManager, rm]);
  5966. } else {
  5967. if (self.ajaxPool) {
  5968. self.ajaxPool.cancel();
  5969. }
  5970. self._raise('fileuploadcancelled', [self.fileManager]);
  5971. }
  5972. self._initAjax();
  5973. if (len > 0) {
  5974. for (i = 0; i < len; i += 1) {
  5975. self.cancelling = true;
  5976. xhr[i].abort();
  5977. }
  5978. }
  5979. self._getThumbs().each(function () {
  5980. var $thumb = $(this), $prog = $thumb.find('.file-thumb-progress');
  5981. $thumb.removeClass('file-uploading');
  5982. self._setProgress(0, $prog);
  5983. $prog.hide();
  5984. if (!self._getThumbFile($thumb)) {
  5985. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  5986. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  5987. }
  5988. self.unlock();
  5989. });
  5990. setTimeout(function () {
  5991. self._setProgressCancelled();
  5992. }, self.processDelay);
  5993. return self.$element;
  5994. },
  5995. clear: function () {
  5996. var self = this, cap;
  5997. if (!self._raise('fileclear')) {
  5998. return;
  5999. }
  6000. self.clearInput = true;
  6001. self.$btnUpload.removeAttr('disabled');
  6002. self._getThumbs().find('video,audio,img').each(function () {
  6003. $h.cleanMemory($(this));
  6004. });
  6005. self._clearFileInput();
  6006. self._resetUpload();
  6007. self.clearFileStack();
  6008. self.isDuplicateError = false;
  6009. self.isPersistentError = false;
  6010. self._resetErrors(true);
  6011. if (self._hasInitialPreview()) {
  6012. self._showFileIcon();
  6013. self._resetPreview();
  6014. self._initPreviewActions();
  6015. self.$container.removeClass('file-input-new');
  6016. } else {
  6017. self._getThumbs().each(function () {
  6018. self._clearObjects($(this));
  6019. });
  6020. if (self.isAjaxUpload) {
  6021. self.previewCache.data = {};
  6022. }
  6023. self.$preview.html('');
  6024. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  6025. self.$caption.attr('title', '').val(cap);
  6026. $h.addCss(self.$container, 'file-input-new');
  6027. self._validateDefaultPreview();
  6028. }
  6029. if (self.$container.find($h.FRAMES).length === 0) {
  6030. if (!self._initCaption()) {
  6031. self.$captionContainer.removeClass('icon-visible');
  6032. }
  6033. }
  6034. self._hideFileIcon();
  6035. if (self.focusCaptionOnClear) {
  6036. self.$captionContainer.focus();
  6037. }
  6038. self._setFileDropZoneTitle();
  6039. self._raise('filecleared');
  6040. return self.$element;
  6041. },
  6042. reset: function () {
  6043. var self = this;
  6044. if (!self._raise('filereset')) {
  6045. return;
  6046. }
  6047. self.lastProgress = 0;
  6048. self._resetPreview();
  6049. self.$container.find('.fileinput-filename').text('');
  6050. $h.addCss(self.$container, 'file-input-new');
  6051. if (self.getFrames().length) {
  6052. self.$container.removeClass('file-input-new');
  6053. }
  6054. self.clearFileStack();
  6055. self._setFileDropZoneTitle();
  6056. return self.$element;
  6057. },
  6058. disable: function () {
  6059. var self = this, $container = self.$container;
  6060. self.isDisabled = true;
  6061. self._raise('filedisabled');
  6062. self.$element.attr('disabled', 'disabled');
  6063. $container.addClass('is-locked');
  6064. $h.addCss($container.find('.btn-file'), 'disabled');
  6065. $container.find('.kv-fileinput-caption').addClass('file-caption-disabled');
  6066. $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  6067. .attr('disabled', true);
  6068. self._initDragDrop();
  6069. return self.$element;
  6070. },
  6071. enable: function () {
  6072. var self = this, $container = self.$container;
  6073. self.isDisabled = false;
  6074. self._raise('fileenabled');
  6075. self.$element.removeAttr('disabled');
  6076. $container.removeClass('is-locked');
  6077. $container.find('.kv-fileinput-caption').removeClass('file-caption-disabled');
  6078. $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  6079. .removeAttr('disabled');
  6080. $container.find('.btn-file').removeClass('disabled');
  6081. self._initDragDrop();
  6082. return self.$element;
  6083. },
  6084. upload: function () {
  6085. var self = this, fm = self.fileManager, totLen = fm.count(), i, outData, tm = self.taskManager,
  6086. hasExtraData = !$.isEmptyObject(self._getExtraData());
  6087. fm.bpsLog = [];
  6088. fm.bps = 0;
  6089. if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) {
  6090. return;
  6091. }
  6092. self.lastProgress = 0;
  6093. self._resetUpload();
  6094. if (totLen === 0 && !hasExtraData) {
  6095. self._showFileError(self.msgUploadEmpty);
  6096. return;
  6097. }
  6098. self.cancelling = false;
  6099. self.uploadInitiated = true;
  6100. self._showProgress();
  6101. self.lock();
  6102. if (totLen === 0 && hasExtraData) {
  6103. self._setProgress(2);
  6104. self._uploadExtraOnly();
  6105. return;
  6106. }
  6107. if (self.enableResumableUpload) {
  6108. return self.resume();
  6109. }
  6110. if (self.uploadAsync || self.enableResumableUpload) {
  6111. outData = self._getOutData(null);
  6112. if (!self._checkBatchPreupload(outData)) {
  6113. return;
  6114. }
  6115. self.fileBatchCompleted = false;
  6116. self.uploadCache = [];
  6117. $.each(self.getFileStack(), function (id) {
  6118. var previewId = self._getThumbId(id);
  6119. self.uploadCache.push({id: previewId, content: null, config: null, tags: null, append: true});
  6120. });
  6121. self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
  6122. self._initSortable();
  6123. }
  6124. self._setProgress(2);
  6125. self.hasInitData = false;
  6126. if (self.uploadAsync) {
  6127. i = 0;
  6128. var pool = self.ajaxPool = tm.addPool($h.uniqId());
  6129. $.each(self.getFileStack(), function (id) {
  6130. pool.addTask(id + i, function (deferrer) {
  6131. self._uploadSingle(i, id, true, deferrer);
  6132. });
  6133. i++;
  6134. });
  6135. pool.run(self.maxAjaxThreads).done(function () {
  6136. self._log('Async upload batch completed successfully.');
  6137. self._raise('filebatchuploadsuccess', [fm.stack, self._getExtraData()]);
  6138. }).fail(function () {
  6139. self._log('Async upload batch completed with errors.');
  6140. self._raise('filebatchuploaderror', [fm.stack, self._getExtraData()]);
  6141. });
  6142. return;
  6143. }
  6144. self._uploadBatch();
  6145. return self.$element;
  6146. },
  6147. destroy: function () {
  6148. var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace;
  6149. $(document).off(ns);
  6150. $(window).off(ns);
  6151. if ($form && $form.length) {
  6152. $form.off(ns);
  6153. }
  6154. if (self.isAjaxUpload) {
  6155. self._clearFileInput();
  6156. }
  6157. self._cleanup();
  6158. self._initPreviewCache();
  6159. $el.insertBefore($cont).off(ns).removeData();
  6160. $cont.off().remove();
  6161. return $el;
  6162. },
  6163. refresh: function (options) {
  6164. var self = this, $el = self.$element;
  6165. if (typeof options !== 'object' || $h.isEmpty(options)) {
  6166. options = self.options;
  6167. } else {
  6168. options = $.extend(true, {}, self.options, options);
  6169. }
  6170. self._init(options, true);
  6171. self._listen();
  6172. return $el;
  6173. },
  6174. zoom: function (frameId) {
  6175. var self = this, $frame = self._getFrame(frameId);
  6176. self._showModal($frame);
  6177. },
  6178. getExif: function (frameId) {
  6179. var self = this, $frame = self._getFrame(frameId);
  6180. return $frame && $frame.data('exif') || null;
  6181. },
  6182. getFrames: function (cssFilter) {
  6183. var self = this, $frames;
  6184. cssFilter = cssFilter || '';
  6185. $frames = self.$preview.find($h.FRAMES + cssFilter);
  6186. if (self.reversePreviewOrder) {
  6187. $frames = $($frames.get().reverse());
  6188. }
  6189. return $frames;
  6190. },
  6191. getPreview: function () {
  6192. var self = this;
  6193. return {
  6194. content: self.initialPreview,
  6195. config: self.initialPreviewConfig,
  6196. tags: self.initialPreviewThumbTags
  6197. };
  6198. }
  6199. };
  6200. $.fn.fileinput = function (option) {
  6201. if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
  6202. return;
  6203. }
  6204. var args = Array.apply(null, arguments), retvals = [];
  6205. args.shift();
  6206. this.each(function () {
  6207. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  6208. theme = options.theme || self.data('theme'), l = {}, t = {},
  6209. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
  6210. if (!data) {
  6211. if (theme) {
  6212. t = $.fn.fileinputThemes[theme] || {};
  6213. }
  6214. if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
  6215. l = $.fn.fileinputLocales[lang] || {};
  6216. }
  6217. opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data());
  6218. data = new FileInput(this, opt);
  6219. self.data('fileinput', data);
  6220. }
  6221. if (typeof option === 'string') {
  6222. retvals.push(data[option].apply(data, args));
  6223. }
  6224. });
  6225. switch (retvals.length) {
  6226. case 0:
  6227. return this;
  6228. case 1:
  6229. return retvals[0];
  6230. default:
  6231. return retvals;
  6232. }
  6233. };
  6234. var IFRAME_ATTRIBS = 'class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}',
  6235. defBtnCss1 = 'btn btn-sm btn-kv ' + $h.defaultButtonCss(), defBtnCss2 = 'btn ' + $h.defaultButtonCss();
  6236. $.fn.fileinput.defaults = {
  6237. language: 'en',
  6238. bytesToKB: 1024,
  6239. showCaption: true,
  6240. showBrowse: true,
  6241. showPreview: true,
  6242. showRemove: true,
  6243. showUpload: true,
  6244. showUploadStats: true,
  6245. showCancel: null,
  6246. showPause: null,
  6247. showClose: true,
  6248. showUploadedThumbs: true,
  6249. showConsoleLogs: false,
  6250. browseOnZoneClick: false,
  6251. autoReplace: false,
  6252. showDescriptionClose: true,
  6253. autoOrientImage: function () { // applicable for JPEG images only and non ios safari
  6254. var ua = window.navigator.userAgent, webkit = !!ua.match(/WebKit/i),
  6255. iOS = !!ua.match(/iP(od|ad|hone)/i), iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
  6256. return !iOSSafari;
  6257. },
  6258. autoOrientImageInitial: true,
  6259. showExifErrorLog: false,
  6260. required: false,
  6261. rtl: false,
  6262. hideThumbnailContent: false,
  6263. encodeUrl: true,
  6264. focusCaptionOnBrowse: true,
  6265. focusCaptionOnClear: true,
  6266. generateFileId: null,
  6267. previewClass: '',
  6268. captionClass: '',
  6269. frameClass: 'krajee-default',
  6270. mainClass: '',
  6271. inputGroupClass: '',
  6272. mainTemplate: null,
  6273. fileSizeGetter: null,
  6274. initialCaption: '',
  6275. initialPreview: [],
  6276. initialPreviewDelimiter: '*$$*',
  6277. initialPreviewAsData: false,
  6278. initialPreviewFileType: 'image',
  6279. initialPreviewConfig: [],
  6280. initialPreviewThumbTags: [],
  6281. previewThumbTags: {},
  6282. initialPreviewShowDelete: true,
  6283. initialPreviewDownloadUrl: '',
  6284. removeFromPreviewOnError: false,
  6285. deleteUrl: '',
  6286. deleteExtraData: {},
  6287. overwriteInitial: true,
  6288. sanitizeZoomCache: function (content) {
  6289. var $container = $h.createElement(content);
  6290. $container.find('input,textarea,select,datalist,form,.file-thumbnail-footer').remove();
  6291. return $container.html();
  6292. },
  6293. previewZoomButtonIcons: {
  6294. prev: '<i class="bi-chevron-left"></i>',
  6295. next: '<i class="bi-chevron-right"></i>',
  6296. rotate: '<i class="bi-arrow-clockwise"></i>',
  6297. toggleheader: '<i class="bi-arrows-expand"></i>',
  6298. fullscreen: '<i class="bi-arrows-fullscreen"></i>',
  6299. borderless: '<i class="bi-arrows-angle-expand"></i>',
  6300. close: '<i class="bi-x-lg"></i>'
  6301. },
  6302. previewZoomButtonClasses: {
  6303. prev: 'btn btn-default btn-outline-secondary btn-navigate',
  6304. next: 'btn btn-default btn-outline-secondary btn-navigate',
  6305. rotate: defBtnCss1,
  6306. toggleheader: defBtnCss1,
  6307. fullscreen: defBtnCss1,
  6308. borderless: defBtnCss1,
  6309. close: defBtnCss1
  6310. },
  6311. previewTemplates: {},
  6312. previewContentTemplates: {},
  6313. preferIconicPreview: false,
  6314. preferIconicZoomPreview: false,
  6315. alwaysPreviewFileExtensions: [],
  6316. rotatableFileExtensions: ['jpg', 'jpeg', 'png', 'gif'],
  6317. allowedFileTypes: null,
  6318. allowedFileExtensions: null,
  6319. allowedPreviewTypes: undefined,
  6320. allowedPreviewMimeTypes: null,
  6321. allowedPreviewExtensions: null,
  6322. disabledPreviewTypes: undefined,
  6323. disabledPreviewExtensions: ['msi', 'exe', 'com', 'zip', 'rar', 'app', 'vb', 'scr'],
  6324. disabledPreviewMimeTypes: null,
  6325. defaultPreviewContent: null,
  6326. customLayoutTags: {},
  6327. customPreviewTags: {},
  6328. previewFileIcon: '<i class="bi-file-earmark-fill"></i>',
  6329. previewFileIconClass: 'file-other-icon',
  6330. previewFileIconSettings: {},
  6331. previewFileExtSettings: {},
  6332. buttonLabelClass: 'hidden-xs',
  6333. browseIcon: '<i class="bi-folder2-open"></i> ',
  6334. browseClass: 'btn btn-primary',
  6335. removeIcon: '<i class="bi-trash"></i>',
  6336. removeClass: defBtnCss2,
  6337. cancelIcon: '<i class="bi-slash-circle"></i>',
  6338. cancelClass: defBtnCss2,
  6339. pauseIcon: '<i class="bi-pause-fill"></i>',
  6340. pauseClass: defBtnCss2,
  6341. uploadIcon: '<i class="bi-upload"></i>',
  6342. uploadClass: defBtnCss2,
  6343. uploadUrl: null,
  6344. uploadUrlThumb: null,
  6345. uploadAsync: true,
  6346. uploadParamNames: {
  6347. chunkCount: 'chunkCount',
  6348. chunkIndex: 'chunkIndex',
  6349. chunkSize: 'chunkSize',
  6350. chunkSizeStart: 'chunkSizeStart',
  6351. chunksUploaded: 'chunksUploaded',
  6352. fileBlob: 'fileBlob',
  6353. fileId: 'fileId',
  6354. fileName: 'fileName',
  6355. fileRelativePath: 'fileRelativePath',
  6356. fileSize: 'fileSize',
  6357. retryCount: 'retryCount'
  6358. },
  6359. maxAjaxThreads: 5,
  6360. fadeDelay: 800,
  6361. processDelay: 100,
  6362. bitrateUpdateDelay: 500,
  6363. queueDelay: 10, // must be lesser than process delay
  6364. progressDelay: 0, // must be lesser than process delay
  6365. enableResumableUpload: false,
  6366. resumableUploadOptions: {
  6367. fallback: null,
  6368. testUrl: null, // used for checking status of chunks/ files previously / partially uploaded
  6369. chunkSize: 2048, // in KB
  6370. maxThreads: 4,
  6371. maxRetries: 3,
  6372. showErrorLog: true,
  6373. retainErrorHistory: false, // when set to true, display complete error history always unless user explicitly resets upload
  6374. skipErrorsAndProceed: false // when set to true, files with errors will be skipped and upload will continue with other files
  6375. },
  6376. uploadExtraData: {},
  6377. zoomModalHeight: 485, // 5px more than the default preview content heights set for text, html, pdf etc.
  6378. minImageWidth: null,
  6379. minImageHeight: null,
  6380. maxImageWidth: null,
  6381. maxImageHeight: null,
  6382. resizeImage: false,
  6383. resizePreference: 'width',
  6384. resizeQuality: 0.92,
  6385. resizeDefaultImageType: 'image/jpeg',
  6386. resizeIfSizeMoreThan: 0, // in KB
  6387. minFileSize: -1,
  6388. maxFileSize: 0,
  6389. maxFilePreviewSize: 25600, // 25 MB
  6390. minFileCount: 0,
  6391. maxFileCount: 0,
  6392. maxTotalFileCount: 0,
  6393. validateInitialCount: false,
  6394. msgValidationErrorClass: 'text-danger',
  6395. msgValidationErrorIcon: '<i class="bi-exclamation-circle-fill"></i> ',
  6396. msgErrorClass: 'file-error-message',
  6397. progressThumbClass: 'progress-bar progress-bar-striped active progress-bar-animated',
  6398. progressClass: 'progress-bar bg-success progress-bar-success progress-bar-striped active progress-bar-animated',
  6399. progressInfoClass: 'progress-bar bg-info progress-bar-info progress-bar-striped active progress-bar-animated',
  6400. progressCompleteClass: 'progress-bar bg-success progress-bar-success',
  6401. progressPauseClass: 'progress-bar bg-primary progress-bar-primary progress-bar-striped active progress-bar-animated',
  6402. progressErrorClass: 'progress-bar bg-danger progress-bar-danger',
  6403. progressUploadThreshold: 99,
  6404. previewFileType: 'image',
  6405. elCaptionContainer: null,
  6406. elCaptionText: null,
  6407. elPreviewContainer: null,
  6408. elPreviewImage: null,
  6409. elPreviewStatus: null,
  6410. elErrorContainer: null,
  6411. errorCloseButton: undefined,
  6412. slugCallback: null,
  6413. dropZoneEnabled: true,
  6414. dropZoneTitleClass: 'file-drop-zone-title',
  6415. fileActionSettings: {},
  6416. otherActionButtons: '',
  6417. textEncoding: 'UTF-8',
  6418. preProcessUpload: null,
  6419. ajaxSettings: {},
  6420. ajaxDeleteSettings: {},
  6421. showAjaxErrorDetails: true,
  6422. mergeAjaxCallbacks: false,
  6423. mergeAjaxDeleteCallbacks: false,
  6424. retryErrorUploads: true,
  6425. reversePreviewOrder: false,
  6426. usePdfRenderer: function () {
  6427. var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
  6428. return !!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i) || isIE11;
  6429. },
  6430. pdfRendererUrl: '',
  6431. pdfRendererTemplate: '<iframe ' + IFRAME_ATTRIBS + '></iframe>',
  6432. tabIndexConfig: {
  6433. browse: 500,
  6434. remove: 500,
  6435. upload: 500,
  6436. cancel: null,
  6437. pause: null,
  6438. modal: -1
  6439. }
  6440. };
  6441. // noinspection HtmlUnknownAttribute
  6442. $.fn.fileinputLocales.en = {
  6443. sizeUnits: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
  6444. bitRateUnits: ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s', 'PB/s', 'EB/s', 'ZB/s', 'YB/s'],
  6445. fileSingle: 'file',
  6446. filePlural: 'files',
  6447. browseLabel: 'Browse &hellip;',
  6448. removeLabel: 'Remove',
  6449. removeTitle: 'Clear all unprocessed files',
  6450. cancelLabel: 'Cancel',
  6451. cancelTitle: 'Abort ongoing upload',
  6452. pauseLabel: 'Pause',
  6453. pauseTitle: 'Pause ongoing upload',
  6454. uploadLabel: 'Upload',
  6455. uploadTitle: 'Upload selected files',
  6456. msgNo: 'No',
  6457. msgNoFilesSelected: 'No files selected',
  6458. msgCancelled: 'Cancelled',
  6459. msgPaused: 'Paused',
  6460. msgPlaceholder: 'Select {files} ...',
  6461. msgZoomModalHeading: 'Detailed Preview',
  6462. msgFileRequired: 'You must select a file to upload.',
  6463. msgSizeTooSmall: 'File "{name}" (<b>{size}</b>) is too small and must be larger than <b>{minSize}</b>.',
  6464. msgSizeTooLarge: 'File "{name}" (<b>{size}</b>) exceeds maximum allowed upload size of <b>{maxSize}</b>.',
  6465. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  6466. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  6467. msgTotalFilesTooMany: 'You can upload a maximum of <b>{m}</b> files (<b>{n}</b> files detected).',
  6468. msgFileNotFound: 'File "{name}" not found!',
  6469. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  6470. msgFileNotReadable: 'File "{name}" is not readable.',
  6471. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  6472. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  6473. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  6474. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  6475. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  6476. msgFileTypes: {
  6477. 'image': 'image',
  6478. 'html': 'HTML',
  6479. 'text': 'text',
  6480. 'video': 'video',
  6481. 'audio': 'audio',
  6482. 'flash': 'flash',
  6483. 'pdf': 'PDF',
  6484. 'object': 'object'
  6485. },
  6486. msgUploadAborted: 'The file upload was aborted',
  6487. msgUploadThreshold: 'Processing &hellip;',
  6488. msgUploadBegin: 'Initializing &hellip;',
  6489. msgUploadEnd: 'Done',
  6490. msgUploadResume: 'Resuming upload &hellip;',
  6491. msgUploadEmpty: 'No valid data available for upload.',
  6492. msgUploadError: 'Upload Error',
  6493. msgDeleteError: 'Delete Error',
  6494. msgProgressError: 'Error',
  6495. msgValidationError: 'Validation Error',
  6496. msgLoading: 'Loading file {index} of {files} &hellip;',
  6497. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  6498. msgSelected: '{n} {files} selected',
  6499. msgProcessing: 'Processing ...',
  6500. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  6501. msgImageWidthSmall: 'Width of image file "{name}" must be at least <b>{size} px</b> (detected <b>{dimension} px</b>).',
  6502. msgImageHeightSmall: 'Height of image file "{name}" must be at least <b>{size} px</b> (detected <b>{dimension} px</b>).',
  6503. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed <b>{size} px</b> (detected <b>{dimension} px</b>).',
  6504. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed <b>{size} px</b> (detected <b>{dimension} px</b>).',
  6505. msgImageResizeError: 'Could not get the image dimensions to resize.',
  6506. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  6507. msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  6508. msgAjaxProgressError: '{operation} failed',
  6509. msgDuplicateFile: 'File "{name}" of same size "{size}" has already been selected earlier. Skipping duplicate selection.',
  6510. msgResumableUploadRetriesExceeded: 'Upload aborted beyond <b>{max}</b> retries for file <b>{file}</b>! Error Details: <pre>{error}</pre>',
  6511. msgPendingTime: '{time} remaining',
  6512. msgCalculatingTime: 'calculating time remaining',
  6513. ajaxOperations: {
  6514. deleteThumb: 'file delete',
  6515. uploadThumb: 'file upload',
  6516. uploadBatch: 'batch file upload',
  6517. uploadExtra: 'form data upload'
  6518. },
  6519. dropZoneTitle: 'Drag & drop files here &hellip;',
  6520. dropZoneClickTitle: '<br>(or click to select {files})',
  6521. previewZoomButtonTitles: {
  6522. prev: 'View previous file',
  6523. next: 'View next file',
  6524. rotate: 'Rotate 90 deg. clockwise',
  6525. toggleheader: 'Toggle header',
  6526. fullscreen: 'Toggle full screen',
  6527. borderless: 'Toggle borderless mode',
  6528. close: 'Close detailed preview'
  6529. }
  6530. };
  6531. $.fn.fileinput.Constructor = FileInput;
  6532. /**
  6533. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  6534. */
  6535. $(document).ready(function () {
  6536. var $input = $('input.file[type=file]');
  6537. if ($input.length) {
  6538. $input.fileinput();
  6539. }
  6540. });
  6541. }));