fileinput.js 255 KB

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