fileinput.js 257 KB

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