/// <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",
                    "/changecurrency",
                    "/changelanguage",
                    "/changetaxtype",
                    "/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",
                    "/eucookielawaccept",
                    "/inboxupdate",
                    "/newsletter/subscriptionactivation",
                    "/onepagecheckout",
                    "/order/history",
                    "/orderdetails",
                    "/passwordrecovery/confirm",
                    "/poll/vote",
                    "/privatemessages",
                    "/returnrequest",
                    "/returnrequest/history",
                    "/rewardpoints/history",
                    "/search?",
                    "/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 (_sitemapXmlSettings.SitemapXmlEnabled)
                {
                    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());
        }
        public virtual async Task <IActionResult> Index(InstallModel model)
        {
            if (DataSettingsManager.DatabaseIsInstalled)
            {
                return(RedirectToRoute("Homepage"));
            }

            //prepare language list
            foreach (var lang in _locService.GetAvailableLanguages())
            {
                model.AvailableLanguages.Add(new SelectListItem
                {
                    Value    = Url.Action("ChangeLanguage", "Install", new { language = lang.Code }),
                    Text     = lang.Name,
                    Selected = _locService.GetCurrentLanguage().Code == lang.Code
                });
            }

            model.AvailableDataProviders.AddRange(
                _locService.GetAvailableProviderTypes()
                .OrderBy(v => v.Value)
                .Select(pt => new SelectListItem
            {
                Value = pt.Key.ToString(),
                Text  = pt.Value
            }));

            model.DisableSampleDataOption = _config.DisableSampleDataDuringInstallation;

            //Consider granting access rights to the resource to the ASP.NET request identity.
            //ASP.NET has a base process identity
            //(typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7,
            //and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating.
            //If the application is impersonating via <identity impersonate="true"/>,
            //the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
            var webHelper = EngineContext.Current.Resolve <IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite();

            foreach (var dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), CurrentOSUser.FullName, dir));
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

            foreach (var file in filesToCheck)
            {
                if (!_fileProvider.FileExists(file))
                {
                    continue;
                }

                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("ConfigureFilePermissions"), CurrentOSUser.FullName, file));
                }
            }

            //if (!ModelState.IsValid)
            //    return View(model);

            try
            {
                var dataProvider = DataProviderManager.GetDataProvider(model.DataProvider);

                var connectionString = model.ConnectionStringRaw ? model.ConnectionString : dataProvider.BuildConnectionString(model);

                if (string.IsNullOrEmpty(connectionString))
                {
                    throw new Exception(_locService.GetResource("ConnectionStringWrongFormat"));
                }

                DataSettingsManager.SaveSettings(new DataSettings
                {
                    DataProvider     = model.DataProvider,
                    ConnectionString = connectionString
                }, _fileProvider);

                DataSettingsManager.LoadSettings(reloadSettings: true);

                if (model.CreateDatabaseIfNotExists)
                {
                    try
                    {
                        dataProvider.CreateDatabase(model.Collation);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format(_locService.GetResource("DatabaseCreationError"), ex.Message));
                    }
                }
                else
                {
                    //check whether database exists
                    if (!dataProvider.IsDatabaseExists())
                    {
                        throw new Exception(_locService.GetResource("DatabaseNotExists"));
                    }
                }

                dataProvider.InitializeDatabase();

                //now resolve installation service
                var installationService = EngineContext.Current.Resolve <IInstallationService>();
                installationService.InstallRequiredData(model.AdminEmail, model.AdminPassword);

                if (model.InstallSampleData)
                {
                    installationService.InstallSampleData(model.AdminEmail);
                }

                //prepare plugins to install
                var pluginService = EngineContext.Current.Resolve <IPluginService>();
                pluginService.ClearInstalledPluginsList();

                var pluginsIgnoredDuringInstallation = new List <string>();
                if (!string.IsNullOrEmpty(_config.PluginsIgnoredDuringInstallation))
                {
                    pluginsIgnoredDuringInstallation = _config.PluginsIgnoredDuringInstallation
                                                       .Split(',', StringSplitOptions.RemoveEmptyEntries).Select(pluginName => pluginName.Trim()).ToList();
                }

                var plugins = pluginService.GetPluginDescriptors <IPlugin>(LoadPluginsMode.All)
                              .Where(pluginDescriptor => !pluginsIgnoredDuringInstallation.Contains(pluginDescriptor.SystemName))
                              .OrderBy(pluginDescriptor => pluginDescriptor.Group).ThenBy(pluginDescriptor => pluginDescriptor.DisplayOrder)
                              .ToList();

                foreach (var plugin in plugins)
                {
                    pluginService.PreparePluginToInstall(plugin.SystemName, checkDependencies: false);
                }

                //register default permissions
                //var permissionProviders = EngineContext.Current.Resolve<ITypeFinder>().FindClassesOfType<IPermissionProvider>();
                var permissionProviders = new List <Type> {
                    typeof(StandardPermissionProvider)
                };
                foreach (var providerType in permissionProviders)
                {
                    var provider = (IPermissionProvider)Activator.CreateInstance(providerType);
                    EngineContext.Current.Resolve <IPermissionService>().InstallPermissions(provider);
                }

                //installation completed notification
                try
                {
                    var languageCode = _locService.GetCurrentLanguage().Code?.Substring(0, 2);
                    var client       = EngineContext.Current.Resolve <NopHttpClient>();
                    await client.InstallationCompletedAsync(model.AdminEmail, languageCode);
                }
                catch { }

                return(View(new InstallModel {
                    RestartUrl = Url.RouteUrl("Homepage")
                }));
            }
            catch (Exception exception)
            {
                //reset cache
                DataSettingsManager.ResetCache();

                var staticCacheManager = EngineContext.Current.Resolve <IStaticCacheManager>();
                staticCacheManager.Clear();

                //clear provider settings if something got wrong
                DataSettingsManager.SaveSettings(new DataSettings(), _fileProvider);

                ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("SetupFailed"), exception.Message));
            }

            return(View(model));
        }
        private static bool CheckPermissionsInWindows(INopFileProvider fileProvider, string path, bool checkRead, bool checkWrite, bool checkModify, bool checkDelete)
        {
            var permissionsAreGranted = true;

            try
            {
                if (!(fileProvider.FileExists(path) || fileProvider.DirectoryExists(path)))
                {
                    return(true);
                }

                var current = WindowsIdentity.GetCurrent();

                var readIsDeny   = false;
                var writeIsDeny  = false;
                var modifyIsDeny = false;
                var deleteIsDeny = false;

                var readIsAllow   = false;
                var writeIsAllow  = false;
                var modifyIsAllow = false;
                var deleteIsAllow = false;

                var rules = fileProvider.GetAccessControl(path).GetAccessRules(true, true, typeof(SecurityIdentifier))
                            .Cast <FileSystemAccessRule>()
                            .ToList();

                foreach (var rule in rules.Where(rule => current.User?.Equals(rule.IdentityReference) ?? false))
                {
                    CheckAccessRule(rule, ref deleteIsDeny, ref modifyIsDeny, ref readIsDeny, ref writeIsDeny, ref deleteIsAllow, ref modifyIsAllow, ref readIsAllow, ref writeIsAllow);
                }

                if (current.Groups != null)
                {
                    foreach (var reference in current.Groups)
                    {
                        foreach (var rule in rules.Where(rule => reference.Equals(rule.IdentityReference)))
                        {
                            CheckAccessRule(rule, ref deleteIsDeny, ref modifyIsDeny, ref readIsDeny, ref writeIsDeny, ref deleteIsAllow, ref modifyIsAllow, ref readIsAllow, ref writeIsAllow);
                        }
                    }
                }

                deleteIsAllow = !deleteIsDeny && deleteIsAllow;
                modifyIsAllow = !modifyIsDeny && modifyIsAllow;
                readIsAllow   = !readIsDeny && readIsAllow;
                writeIsAllow  = !writeIsDeny && writeIsAllow;

                if (checkRead)
                {
                    permissionsAreGranted = readIsAllow;
                }

                if (checkWrite)
                {
                    permissionsAreGranted = permissionsAreGranted && writeIsAllow;
                }

                if (checkModify)
                {
                    permissionsAreGranted = permissionsAreGranted && modifyIsAllow;
                }

                if (checkDelete)
                {
                    permissionsAreGranted = permissionsAreGranted && deleteIsAllow;
                }
            }
            catch (IOException)
            {
                return(false);
            }
            catch
            {
                return(true);
            }

            return(permissionsAreGranted);
        }
 /// <summary>
 /// Get a value indicating whether some file (thumb) already exists
 /// </summary>
 /// <param name="thumbFilePath">Thumb file path</param>
 /// <param name="thumbFileName">Thumb file name</param>
 /// <returns>Result</returns>
 protected virtual bool GeneratedThumbExists(string thumbFilePath, string thumbFileName)
 {
     return(_fileProvider.FileExists(thumbFilePath));
 }
        /// <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, INopFileProvider fileProvider = null)
        {
            if (!reloadSettings && Singleton <DataSettings> .Instance != null)
            {
                return(Singleton <DataSettings> .Instance);
            }

            fileProvider = fileProvider ?? CommonHelper.DefaultFileProvider;
            filePath     = filePath ?? fileProvider.MapPath(DataSettingsFilePath);

            //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(ObsoleteDataSettingsFilePath);
                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);
        }
Exemple #6
0
        public virtual async Task <IActionResult> Index(InstallModel model)
        {
            if (await DataSettingsManager.IsDatabaseInstalledAsync())
            {
                return(RedirectToRoute("Homepage"));
            }

            model.DisableSampleDataOption  = _appSettings.Get <InstallationConfig>().DisableSampleData;
            model.InstallRegionalResources = _appSettings.Get <InstallationConfig>().InstallRegionalResources;

            PrepareAvailableDataProviders(model);
            PrepareLanguageList(model);
            PrepareCountryList(model);

            //Consider granting access rights to the resource to the ASP.NET request identity.
            //ASP.NET has a base process identity
            //(typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7,
            //and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating.
            //If the application is impersonating via <identity impersonate="true"/>,
            //the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
            var webHelper = EngineContext.Current.Resolve <IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite();

            foreach (var dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), CurrentOSUser.FullName, dir));
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

            foreach (var file in filesToCheck)
            {
                if (!_fileProvider.FileExists(file))
                {
                    continue;
                }

                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("ConfigureFilePermissions"), CurrentOSUser.FullName, file));
                }
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                var dataProvider = DataProviderManager.GetDataProvider(model.DataProvider);

                var connectionString = model.ConnectionStringRaw ? model.ConnectionString : dataProvider.BuildConnectionString(model);

                if (string.IsNullOrEmpty(connectionString))
                {
                    throw new Exception(_locService.GetResource("ConnectionStringWrongFormat"));
                }

                DataSettingsManager.SaveSettings(new DataConfig
                {
                    DataProvider     = model.DataProvider,
                    ConnectionString = connectionString
                }, _fileProvider);

                if (model.CreateDatabaseIfNotExists)
                {
                    try
                    {
                        dataProvider.CreateDatabase(model.Collation);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format(_locService.GetResource("DatabaseCreationError"), ex.Message));
                    }
                }
                else
                {
                    //check whether database exists
                    if (!await dataProvider.DatabaseExistsAsync())
                    {
                        throw new Exception(_locService.GetResource("DatabaseNotExists"));
                    }
                }

                dataProvider.InitializeDatabase();

                var cultureInfo = new CultureInfo(NopCommonDefaults.DefaultLanguageCulture);
                var regionInfo  = new RegionInfo(NopCommonDefaults.DefaultLanguageCulture);

                var languagePackInfo = (DownloadUrl : string.Empty, Progress : 0);
                if (model.InstallRegionalResources)
                {
                    //try to get CultureInfo and RegionInfo
                    try
                    {
                        cultureInfo = new CultureInfo(model.Country[3..]);
                        regionInfo  = new RegionInfo(model.Country[3..]);