fileinput.js 261 KB

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