fileinput.js 275 KB

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