fileinput.js 276 KB

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