Beispiel #1
0
        protected virtual BrowscapXmlHelper GetBrowscapXmlHelper()
        {
            if (Singleton <BrowscapXmlHelper> .Instance != null)
            {
                return(Singleton <BrowscapXmlHelper> .Instance);
            }

            //no database created
            if (string.IsNullOrEmpty(_nopConfig.UserAgentStringsPath))
            {
                return(null);
            }

            //prevent multi loading data
            lock (_locker)
            {
                //data can be loaded while we waited
                if (Singleton <BrowscapXmlHelper> .Instance != null)
                {
                    return(Singleton <BrowscapXmlHelper> .Instance);
                }

                var userAgentStringsPath            = _fileProvider.MapPath(_nopConfig.UserAgentStringsPath);
                var crawlerOnlyUserAgentStringsPath = !string.IsNullOrEmpty(_nopConfig.CrawlerOnlyUserAgentStringsPath)
                    ? _fileProvider.MapPath(_nopConfig.CrawlerOnlyUserAgentStringsPath)
                    : string.Empty;

                var browscapXmlHelper = new BrowscapXmlHelper(userAgentStringsPath, crawlerOnlyUserAgentStringsPath, _fileProvider);
                Singleton <BrowscapXmlHelper> .Instance = browscapXmlHelper;

                return(Singleton <BrowscapXmlHelper> .Instance);
            }
        }
        /// <summary>
        /// Luu work file
        /// </summary>
        /// <param name="item"></param>
        /// <param name="fileContent"></param>
        void SaveWorkFileOnDisk(WorkFile item, byte[] fileContent)
        {
            string _pathStore = item.CreatedDate.ToPathFolderStore();

            _pathStore = _fileProvider.Combine(_fileProvider.MapPath(GSDataSettingsDefaults.FolderWorkFiles), _pathStore);
            _fileProvider.CreateDirectory(_pathStore);
            var _fileStore = _fileProvider.Combine(_pathStore, item.FileGuid.ToString() + item.Extension);

            _fileProvider.WriteAllBytes(_fileStore, fileContent);
        }
Beispiel #3
0
        /// <summary>
        /// Get all themes
        /// </summary>
        /// <returns>List of the theme descriptor</returns>
        public IList <ThemeDescriptor> GetThemes()
        {
            if (_themeDescriptors != null)
            {
                return(_themeDescriptors);
            }

            //load all theme descriptors
            _themeDescriptors = new List <ThemeDescriptor>();

            var themeDirectoryPath = _fileProvider.MapPath(GSPluginDefaults.ThemesPath);

            foreach (var descriptionFile in _fileProvider.GetFiles(themeDirectoryPath, GSPluginDefaults.ThemeDescriptionFileName, false))
            {
                var text = _fileProvider.ReadAllText(descriptionFile, Encoding.UTF8);
                if (string.IsNullOrEmpty(text))
                {
                    continue;
                }

                //get theme descriptor
                var themeDescriptor = GetThemeDescriptorFromText(text);

                //some validation
                if (string.IsNullOrEmpty(themeDescriptor?.SystemName))
                {
                    throw new Exception($"A theme descriptor '{descriptionFile}' has no system name");
                }

                _themeDescriptors.Add(themeDescriptor);
            }

            return(_themeDescriptors);
        }
        /// <summary>
        /// Install locales
        /// </summary>
        protected virtual void InstallLocaleResources()
        {
            //'English' language
            var language = _languageRepository.Table.Single(l => l.Name == "English");

            //save resources
            var directoryPath = _fileProvider.MapPath(GSInstallationDefaults.LocalizationResourcesPath);
            var pattern       = $"*.{GSInstallationDefaults.LocalizationResourcesFileExtension}";

            foreach (var filePath in _fileProvider.EnumerateFiles(directoryPath, pattern))
            {
                var localesXml          = _fileProvider.ReadAllText(filePath, Encoding.UTF8);
                var localizationService = EngineContext.Current.Resolve <ILocalizationService>();
                localizationService.ImportResourcesFromXml(language, localesXml);
            }
        }
        public virtual IActionResult Upload()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.HtmlEditorManagePictures))
            {
                ViewData["resultCode"] = "failed";
                ViewData["result"]     = "No access to this functionality";
                return(View());
            }

            if (Request.Form.Files.Count == 0)
            {
                throw new Exception("No file uploaded");
            }

            var uploadFile = Request.Form.Files.FirstOrDefault();

            if (uploadFile == null)
            {
                ViewData["resultCode"] = "failed";
                ViewData["result"]     = "No file name provided";
                return(View());
            }

            var fileName = _fileProvider.GetFileName(uploadFile.FileName);

            if (string.IsNullOrEmpty(fileName))
            {
                ViewData["resultCode"] = "failed";
                ViewData["result"]     = "No file name provided";
                return(View());
            }

            var directory = "~/wwwroot/images/uploaded/";
            var filePath  = _fileProvider.Combine(_fileProvider.MapPath(directory), fileName);

            var fileExtension = _fileProvider.GetFileExtension(filePath);

            if (!GetAllowedFileTypes().Contains(fileExtension))
            {
                ViewData["resultCode"] = "failed";
                ViewData["result"]     = $"Files with {fileExtension} extension cannot be uploaded";
                return(View());
            }

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                uploadFile.CopyTo(fileStream);
            }

            ViewData["resultCode"] = "success";
            ViewData["result"]     = "success";
            ViewData["filename"]   = Url.Content($"{directory}{fileName}");
            return(View());
        }
Beispiel #6
0
 /// <summary>
 /// Try to write web.config file
 /// </summary>
 /// <returns></returns>
 protected virtual bool TryWriteWebConfig()
 {
     try
     {
         _fileProvider.SetLastWriteTimeUtc(_fileProvider.MapPath(GSInfrastructureDefaults.WebConfigPath), DateTime.UtcNow);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Beispiel #7
0
        /// <summary>
        /// Get system names of installed plugins
        /// </summary>
        /// <param name="filePath">Path to the file</param>
        /// <returns>List of plugin system names</returns>
        private static IList <string> GetInstalledPluginNames(string filePath)
        {
            //check whether file exists
            if (!_fileProvider.FileExists(filePath))
            {
                //if not, try to parse the file that was used in previous nopCommerce versions
                filePath = _fileProvider.MapPath(GSPluginDefaults.ObsoleteInstalledPluginsFilePath);
                if (!_fileProvider.FileExists(filePath))
                {
                    return(new List <string>());
                }

                //get plugin system names from the old txt file
                var pluginSystemNames = new List <string>();
                using (var reader = new StringReader(_fileProvider.ReadAllText(filePath, Encoding.UTF8)))
                {
                    string pluginName;
                    while ((pluginName = reader.ReadLine()) != null)
                    {
                        if (!string.IsNullOrWhiteSpace(pluginName))
                        {
                            pluginSystemNames.Add(pluginName.Trim());
                        }
                    }
                }

                //save system names of installed plugins to the new file
                SaveInstalledPluginNames(pluginSystemNames, _fileProvider.MapPath(GSPluginDefaults.InstalledPluginsFilePath));

                //and delete the old one
                _fileProvider.DeleteFile(filePath);

                return(pluginSystemNames);
            }

            var text = _fileProvider.ReadAllText(filePath, Encoding.UTF8);

            if (string.IsNullOrEmpty(text))
            {
                return(new List <string>());
            }

            //get plugin system names from the JSON file
            return(JsonConvert.DeserializeObject <IList <string> >(text));
        }
Beispiel #8
0
        /// <summary>
        /// Get font
        /// </summary>
        /// <param name="fontFileName">Font file name</param>
        /// <returns>Font</returns>
        protected virtual Font GetFont(string fontFileName)
        {
            if (fontFileName == null)
            {
                throw new ArgumentNullException(nameof(fontFileName));
            }

            var fontPath = _fileProvider.Combine(_fileProvider.MapPath("~/App_Data/Pdf/"), fontFileName);
            var baseFont = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            var font     = new Font(baseFont, 10, Font.NORMAL);

            return(font);
        }
        /// <summary>
        /// Save data settings to the file
        /// </summary>
        /// <param name="settings">Data settings</param>
        /// <param name="fileProvider">File provider</param>
        public static void SaveSettings(DataSettings settings, IGSFileProvider fileProvider = null)
        {
            Singleton <DataSettings> .Instance = settings ?? throw new ArgumentNullException(nameof(settings));

            fileProvider = fileProvider ?? CommonHelper.DefaultFileProvider;
            var filePath = fileProvider.MapPath(GSDataSettingsDefaults.FilePath);

            //create file if not exists
            fileProvider.CreateFile(filePath);

            //save data settings to the file
            var text = JsonConvert.SerializeObject(Singleton <DataSettings> .Instance, Formatting.Indented);

            fileProvider.WriteAllText(filePath, text, Encoding.UTF8);
        }
Beispiel #10
0
        /// <summary>
        /// Get information
        /// </summary>
        /// <param name="ipAddress">IP address</param>
        /// <returns>Information</returns>
        protected virtual CountryResponse GetInformation(string ipAddress)
        {
            if (string.IsNullOrEmpty(ipAddress))
            {
                return(null);
            }

            try
            {
                //This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com
                var databasePath = _fileProvider.MapPath("~/App_Data/GeoLite2-Country.mmdb");
                var reader       = new DatabaseReader(databasePath);
                var omni         = reader.Country(ipAddress);
                return(omni);
                //more info: http://maxmind.github.io/GeoIP2-dotnet/
                //more info: https://github.com/maxmind/GeoIP2-dotnet
                //more info: http://dev.maxmind.com/geoip/geoip2/geolite2/
                //Console.WriteLine(omni.Country.IsoCode); // 'US'
                //Console.WriteLine(omni.Country.Name); // 'United States'
                //Console.WriteLine(omni.Country.Names["zh-CN"]); // '美国'
                //Console.WriteLine(omni.MostSpecificSubdivision.Name); // 'Minnesota'
                //Console.WriteLine(omni.MostSpecificSubdivision.IsoCode); // 'MN'
                //Console.WriteLine(omni.City.Name); // 'Minneapolis'
                //Console.WriteLine(omni.Postal.Code); // '55455'
                //Console.WriteLine(omni.Location.Latitude); // 44.9733
                //Console.WriteLine(omni.Location.Longitude); // -93.2323
            }
            //catch (AddressNotFoundException exc)
            catch (GeoIP2Exception)
            {
                //address is not found
                //do not throw exceptions
                return(null);
            }
            catch (Exception exc)
            {
                //do not throw exceptions
                _logger.Warning("Cannot load MaxMind record", exc);
                return(null);
            }
        }
        /// <summary>
        /// Get a list of available languages
        /// </summary>
        /// <returns>Available installation languages</returns>
        public virtual IList <InstallationLanguage> GetAvailableLanguages()
        {
            if (_availableLanguages != null)
            {
                return(_availableLanguages);
            }

            _availableLanguages = new List <InstallationLanguage>();
            foreach (var filePath in _fileProvider.EnumerateFiles(_fileProvider.MapPath("~/App_Data/Localization/Installation/"), "*.xml"))
            {
                var xmlDocument = new XmlDocument();
                xmlDocument.Load(filePath);

                //get language code
                var languageCode = "";
                //we file name format: installation.{languagecode}.xml
                var r       = new Regex(Regex.Escape("installation.") + "(.*?)" + Regex.Escape(".xml"));
                var matches = r.Matches(_fileProvider.GetFileName(filePath));
                foreach (Match match in matches)
                {
                    languageCode = match.Groups[1].Value;
                }

                var languageNode = xmlDocument.SelectSingleNode(@"//Language");

                if (languageNode == null || languageNode.Attributes == null)
                {
                    continue;
                }

                //get language friendly name
                var languageName = languageNode.Attributes["Name"].InnerText.Trim();

                //is default
                var isDefaultAttribute = languageNode.Attributes["IsDefault"];
                var isDefault          = isDefaultAttribute != null && Convert.ToBoolean(isDefaultAttribute.InnerText.Trim());

                //is default
                var isRightToLeftAttribute = languageNode.Attributes["IsRightToLeft"];
                var isRightToLeft          = isRightToLeftAttribute != null && Convert.ToBoolean(isRightToLeftAttribute.InnerText.Trim());

                //create language
                var language = new InstallationLanguage
                {
                    Code          = languageCode,
                    Name          = languageName,
                    IsDefault     = isDefault,
                    IsRightToLeft = isRightToLeft,
                };

                //load resources
                var resources = xmlDocument.SelectNodes(@"//Language/LocaleResource");
                if (resources == null)
                {
                    continue;
                }
                foreach (XmlNode resNode in resources)
                {
                    if (resNode.Attributes == null)
                    {
                        continue;
                    }

                    var resNameAttribute = resNode.Attributes["Name"];
                    var resValueNode     = resNode.SelectSingleNode("Value");

                    if (resNameAttribute == null)
                    {
                        throw new GSException("All installation resources must have an attribute Name=\"Value\".");
                    }
                    var resourceName = resNameAttribute.Value.Trim();
                    if (string.IsNullOrEmpty(resourceName))
                    {
                        throw new GSException("All installation resource attributes 'Name' must have a value.'");
                    }

                    if (resValueNode == null)
                    {
                        throw new GSException("All installation resources must have an element \"Value\".");
                    }
                    var resourceValue = resValueNode.InnerText.Trim();

                    language.Resources.Add(new InstallationLocaleResource
                    {
                        Name  = resourceName,
                        Value = resourceValue
                    });
                }

                _availableLanguages.Add(language);
                _availableLanguages = _availableLanguages.OrderBy(l => l.Name).ToList();
            }
            return(_availableLanguages);
        }
        /// <summary>
        /// Get robots.txt file
        /// </summary>
        /// <returns>Robots.txt file as string</returns>
        public virtual string PrepareRobotsTextFile()
        {
            var sb = new StringBuilder();

            //if robots.custom.txt exists, let's use it instead of hard-coded data below
            var robotsFilePath = _fileProvider.Combine(_fileProvider.MapPath("~/"), "robots.custom.txt");

            if (_fileProvider.FileExists(robotsFilePath))
            {
                //the robots.txt file exists
                var robotsFileContent = _fileProvider.ReadAllText(robotsFilePath, Encoding.UTF8);
                sb.Append(robotsFileContent);
            }
            else
            {
                //doesn't exist. Let's generate it (default behavior)

                var disallowPaths = new List <string>
                {
                    "/admin",
                    "/bin/",
                    "/files/",
                    "/files/exportimport/",
                    "/country/getstatesbycountryid",
                    "/install",
                    "/setproductreviewhelpfulness",
                };
                var localizableDisallowPaths = new List <string>
                {
                    "/addproducttocart/catalog/",
                    "/addproducttocart/details/",
                    "/backinstocksubscriptions/manage",
                    "/boards/forumsubscriptions",
                    "/boards/forumwatch",
                    "/boards/postedit",
                    "/boards/postdelete",
                    "/boards/postcreate",
                    "/boards/topicedit",
                    "/boards/topicdelete",
                    "/boards/topiccreate",
                    "/boards/topicmove",
                    "/boards/topicwatch",
                    "/cart",
                    "/checkout",
                    "/checkout/billingaddress",
                    "/checkout/completed",
                    "/checkout/confirm",
                    "/checkout/shippingaddress",
                    "/checkout/shippingmethod",
                    "/checkout/paymentinfo",
                    "/checkout/paymentmethod",
                    "/clearcomparelist",
                    "/compareproducts",
                    "/compareproducts/add/*",
                    "/customer/avatar",
                    "/customer/activation",
                    "/customer/addresses",
                    "/customer/changepassword",
                    "/customer/checkusernameavailability",
                    "/customer/downloadableproducts",
                    "/customer/info",
                    "/deletepm",
                    "/emailwishlist",
                    "/inboxupdate",
                    "/newsletter/subscriptionactivation",
                    "/onepagecheckout",
                    "/order/history",
                    "/orderdetails",
                    "/passwordrecovery/confirm",
                    "/poll/vote",
                    "/privatemessages",
                    "/returnrequest",
                    "/returnrequest/history",
                    "/rewardpoints/history",
                    "/sendpm",
                    "/sentupdate",
                    "/shoppingcart/*",
                    "/storeclosed",
                    "/subscribenewsletter",
                    "/topic/authenticate",
                    "/viewpm",
                    "/uploadfilecheckoutattribute",
                    "/uploadfileproductattribute",
                    "/uploadfilereturnrequest",
                    "/wishlist",
                };

                const string newLine = "\r\n"; //Environment.NewLine
                sb.Append("User-agent: *");
                sb.Append(newLine);
                //sitemaps
                if (_commonSettings.SitemapEnabled)
                {
                    if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
                    {
                        //URLs are localizable. Append SEO code
                        foreach (var language in _languageService.GetAllLanguages(storeId: _storeContext.CurrentStore.Id))
                        {
                            sb.AppendFormat("Sitemap: {0}{1}/sitemap.xml", _webHelper.GetStoreLocation(), language.UniqueSeoCode);
                            sb.Append(newLine);
                        }
                    }
                    else
                    {
                        //localizable paths (without SEO code)
                        sb.AppendFormat("Sitemap: {0}sitemap.xml", _webHelper.GetStoreLocation());
                        sb.Append(newLine);
                    }
                }
                //host
                sb.AppendFormat("Host: {0}", _webHelper.GetStoreLocation());
                sb.Append(newLine);

                //usual paths
                foreach (var path in disallowPaths)
                {
                    sb.AppendFormat("Disallow: {0}", path);
                    sb.Append(newLine);
                }
                //localizable paths (without SEO code)
                foreach (var path in localizableDisallowPaths)
                {
                    sb.AppendFormat("Disallow: {0}", path);
                    sb.Append(newLine);
                }
                if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
                {
                    //URLs are localizable. Append SEO code
                    foreach (var language in _languageService.GetAllLanguages(storeId: _storeContext.CurrentStore.Id))
                    {
                        foreach (var path in localizableDisallowPaths)
                        {
                            sb.AppendFormat("Disallow: /{0}{1}", language.UniqueSeoCode, path);
                            sb.Append(newLine);
                        }
                    }
                }

                //load and add robots.txt additions to the end of file.
                var robotsAdditionsFile = _fileProvider.Combine(_fileProvider.MapPath("~/"), "robots.additions.txt");
                if (_fileProvider.FileExists(robotsAdditionsFile))
                {
                    var robotsFileContent = _fileProvider.ReadAllText(robotsAdditionsFile, Encoding.UTF8);
                    sb.Append(robotsFileContent);
                }
            }

            return(sb.ToString());
        }
        /// <summary>
        /// Load data settings
        /// </summary>
        /// <param name="filePath">File path; pass null to use the default settings file</param>
        /// <param name="reloadSettings">Whether to reload data, if they already loaded</param>
        /// <param name="fileProvider">File provider</param>
        /// <returns>Data settings</returns>
        public static DataSettings LoadSettings(string filePath = null, bool reloadSettings = false, IGSFileProvider fileProvider = null)
        {
            if (!reloadSettings && Singleton <DataSettings> .Instance != null)
            {
                return(Singleton <DataSettings> .Instance);
            }

            fileProvider = fileProvider ?? CommonHelper.DefaultFileProvider;
            filePath     = filePath ?? fileProvider.MapPath(GSDataSettingsDefaults.FilePath);

            //check whether file exists
            if (!fileProvider.FileExists(filePath))
            {
                //if not, try to parse the file that was used in previous nopCommerce versions
                filePath = fileProvider.MapPath(GSDataSettingsDefaults.ObsoleteFilePath);
                if (!fileProvider.FileExists(filePath))
                {
                    return(new DataSettings());
                }

                //get data settings from the old txt file
                var dataSettings = new DataSettings();
                using (var reader = new StringReader(fileProvider.ReadAllText(filePath, Encoding.UTF8)))
                {
                    string settingsLine;
                    while ((settingsLine = reader.ReadLine()) != null)
                    {
                        var separatorIndex = settingsLine.IndexOf(':');
                        if (separatorIndex == -1)
                        {
                            continue;
                        }

                        var key   = settingsLine.Substring(0, separatorIndex).Trim();
                        var value = settingsLine.Substring(separatorIndex + 1).Trim();

                        switch (key)
                        {
                        case "DataProvider":
                            dataSettings.DataProvider = Enum.TryParse(value, true, out DataProviderType providerType) ? providerType : DataProviderType.Unknown;
                            continue;

                        case "DataConnectionString":
                            dataSettings.DataConnectionString = value;
                            continue;

                        default:
                            dataSettings.RawDataSettings.Add(key, value);
                            continue;
                        }
                    }
                }

                //save data settings to the new file
                SaveSettings(dataSettings, fileProvider);

                //and delete the old one
                fileProvider.DeleteFile(filePath);

                Singleton <DataSettings> .Instance = dataSettings;
                return(Singleton <DataSettings> .Instance);
            }

            var text = fileProvider.ReadAllText(filePath, Encoding.UTF8);

            if (string.IsNullOrEmpty(text))
            {
                return(new DataSettings());
            }

            //get data settings from the JSON file
            Singleton <DataSettings> .Instance = JsonConvert.DeserializeObject <DataSettings>(text);

            return(Singleton <DataSettings> .Instance);
        }