/// <summary> /// Creates a backup of the database /// </summary> public virtual void BackupDatabase() { CheckBackupSupported(); var fileName = _fileProvider.Combine(GetBackupDirectoryPath(), $"database_{DateTime.Now:yyyy-MM-dd-HH-mm-ss}_{CommonHelper.GenerateRandomDigitCode(10)}.{NopCommonDefaults.DbBackupFileExtension}"); var commandText = $"BACKUP DATABASE [{_dbContext.DbName()}] TO DISK = '{fileName}' WITH FORMAT"; _dbContext.ExecuteSqlCommand(commandText, true); }
/// <summary> /// Copy the plugin file to shadow copy directory /// </summary> /// <param name="pluginFilePath">Plugin file path</param> /// <param name="shadowCopyPlugFolder">Path to shadow copy folder</param> /// <returns>File path to shadow copy of plugin file</returns> private static string ShadowCopyFile(string pluginFilePath, string shadowCopyPlugFolder) { var shouldCopy = true; var shadowCopiedPlug = _fileProvider.Combine(shadowCopyPlugFolder, _fileProvider.GetFileName(pluginFilePath)); //check if a shadow copied file already exists and if it does, check if it's updated, if not don't copy if (_fileProvider.FileExists(shadowCopiedPlug)) { //it's better to use LastWriteTimeUTC, but not all file systems have this property //maybe it is better to compare file hash? var areFilesIdentical = _fileProvider.GetCreationTime(shadowCopiedPlug).ToUniversalTime().Ticks >= _fileProvider.GetCreationTime(pluginFilePath).ToUniversalTime().Ticks; if (areFilesIdentical) { Debug.WriteLine("Not copying; files appear identical: '{0}'", _fileProvider.GetFileName(shadowCopiedPlug)); shouldCopy = false; } else { //delete an existing file //More info: https://www.nopcommerce.com/boards/t/11511/access-error-nopplugindiscountrulesbillingcountrydll.aspx?p=4#60838 Debug.WriteLine("New plugin found; Deleting the old file: '{0}'", _fileProvider.GetFileName(shadowCopiedPlug)); _fileProvider.DeleteFile(shadowCopiedPlug); } } if (!shouldCopy) { return(shadowCopiedPlug); } try { _fileProvider.FileCopy(pluginFilePath, shadowCopiedPlug, true); } catch (IOException) { Debug.WriteLine(shadowCopiedPlug + " is locked, attempting to rename"); //this occurs when the files are locked, //for some reason devenv locks plugin files some times and for another crazy reason you are allowed to rename them //which releases the lock, so that it what we are doing here, once it's renamed, we can re-shadow copy try { var oldFile = shadowCopiedPlug + Guid.NewGuid().ToString("N") + ".old"; _fileProvider.FileMove(shadowCopiedPlug, oldFile); } catch (IOException exc) { throw new IOException(shadowCopiedPlug + " rename failed, cannot initialize plugin", exc); } //OK, we've made it this far, now retry the shadow copy _fileProvider.FileCopy(pluginFilePath, shadowCopiedPlug, true); } return(shadowCopiedPlug); }
/// <summary> /// Сopy the directory with the embedded files and directories /// </summary> /// <param name="sourcePath">Path to the source directory</param> /// <param name="destinationPath">Path to the destination directory</param> protected virtual void CopyDirectory(string sourcePath, string destinationPath) { var existingFiles = _fileProvider.GetFiles(sourcePath); var existingDirectories = _fileProvider.GetDirectories(sourcePath); if (!_fileProvider.DirectoryExists(destinationPath)) { _fileProvider.CreateDirectory(destinationPath); } foreach (var file in existingFiles) { var filePath = _fileProvider.Combine(destinationPath, _fileProvider.GetFileName(file)); if (!_fileProvider.FileExists(filePath)) { _fileProvider.FileCopy(file, filePath); } } foreach (var directory in existingDirectories) { var directoryPath = _fileProvider.Combine(destinationPath, _fileProvider.GetDirectoryName(directory)); CopyDirectory(directory, directoryPath); } }
/// <summary> /// Get the absolute path by virtual path /// </summary> /// <param name="virtualPath">Virtual path</param> /// <returns>Path</returns> protected virtual string GetFullPath(string virtualPath) { virtualPath = virtualPath ?? string.Empty; if (!virtualPath.StartsWith("/")) { virtualPath = "/" + virtualPath; } virtualPath = virtualPath.TrimEnd('/'); return(_fileProvider.Combine(_hostingEnvironment.WebRootPath, virtualPath)); }
/// <summary> /// Get picture (thumb) local path /// </summary> /// <param name="thumbFileName">Filename</param> /// <returns>Local picture thumb path</returns> protected virtual string GetThumbLocalPath(string thumbFileName) { var thumbsDirectoryPath = _fileProvider.GetAbsolutePath(NopMediaDefaults.ImageThumbsPath); if (_mediaSettings.MultipleThumbDirectories) { //get the first two letters of the file name var fileNameWithoutExtension = _fileProvider.GetFileNameWithoutExtension(thumbFileName); if (fileNameWithoutExtension != null && fileNameWithoutExtension.Length > NopMediaDefaults.MultipleThumbDirectoriesLength) { var subDirectoryName = fileNameWithoutExtension.Substring(0, NopMediaDefaults.MultipleThumbDirectoriesLength); thumbsDirectoryPath = _fileProvider.GetAbsolutePath(NopMediaDefaults.ImageThumbsPath, subDirectoryName); _fileProvider.CreateDirectory(thumbsDirectoryPath); } } var thumbFilePath = _fileProvider.Combine(thumbsDirectoryPath, thumbFileName); if (thumbFilePath.ToLower().Contains("localhost")) { thumbFilePath = thumbFilePath.Replace("localhost", PublicIP); } return(thumbFilePath); }
/// <summary> /// Get tinyMCE language name for current language /// </summary> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the inyMCE language name /// </returns> public async Task <string> GetTinyMceLanguageAsync() { //nopCommerce supports TinyMCE's localization for 10 languages: //Chinese, Spanish, Arabic, Portuguese, Russian, German, French, Italian, Dutch and English out-of-the-box. //Additional languages can be downloaded from the website TinyMCE(https://www.tinymce.com/download/language-packages/) var languageCulture = (await _workContext.GetWorkingLanguageAsync()).LanguageCulture; var langFile = $"{languageCulture}.js"; var directoryPath = _nopFileProvider.Combine(_webHostEnvironment.WebRootPath, @"lib_npm\tinymce\langs"); var fileExists = _nopFileProvider.FileExists($"{directoryPath}\\{langFile}"); if (!fileExists) { languageCulture = languageCulture.Replace('-', '_'); langFile = $"{languageCulture}.js"; fileExists = _nopFileProvider.FileExists($"{directoryPath}\\{langFile}"); } if (!fileExists) { languageCulture = languageCulture.Split('_', '-')[0]; langFile = $"{languageCulture}.js"; fileExists = _nopFileProvider.FileExists($"{directoryPath}\\{langFile}"); } return(fileExists ? languageCulture : string.Empty); }
static ApplicationPartManagerExtensions() { //we use the default file provider, since the DI isn't initialized yet _fileProvider = CommonHelper.DefaultFileProvider; _baseAppLibraries = new List <string>(); //get all libraries from /bin/{version}/ directory _baseAppLibraries.AddRange(_fileProvider.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll") .Select(fileName => _fileProvider.GetFileName(fileName))); //get all libraries from base site directory if (!AppDomain.CurrentDomain.BaseDirectory.Equals(Environment.CurrentDirectory, StringComparison.InvariantCultureIgnoreCase)) { _baseAppLibraries.AddRange(_fileProvider.GetFiles(Environment.CurrentDirectory, "*.dll") .Select(fileName => _fileProvider.GetFileName(fileName))); } //get all libraries from refs directory var refsPathName = _fileProvider.Combine(Environment.CurrentDirectory, NopPluginDefaults.RefsPathName); if (_fileProvider.DirectoryExists(refsPathName)) { _baseAppLibraries.AddRange(_fileProvider.GetFiles(refsPathName, "*.dll") .Select(fileName => _fileProvider.GetFileName(fileName))); } }
private string DownloadFile(string urlString, IList <string> downloadedFiles) { if (string.IsNullOrEmpty(urlString)) { return(string.Empty); } if (!Uri.IsWellFormedUriString(urlString, UriKind.Absolute)) { return(urlString); } //ensure that temp directory is created var tempDirectory = _fileProvider.MapPath(UPLOADS_TEMP_PATH); _fileProvider.CreateDirectory(tempDirectory); var fileName = _fileProvider.GetFileName(urlString); if (string.IsNullOrEmpty(fileName)) { return(string.Empty); } var filePath = _fileProvider.Combine(tempDirectory, fileName); try { WebRequest.Create(urlString); } catch { return(string.Empty); } try { byte[] fileData; using (var client = new WebClient()) { fileData = client.DownloadData(urlString); } using (var fs = new FileStream(filePath, FileMode.OpenOrCreate)) { fs.Write(fileData, 0, fileData.Length); } downloadedFiles?.Add(filePath); return(filePath); } catch (Exception ex) { _logger.Error("Download image failed", ex); } return(string.Empty); }
public virtual IActionResult Upload() { if (!_permissionService.Authorize(StandardPermissionProvider.HtmlEditorManagePictures)) { ViewData[RESULTCODE_FIELD_KEY] = "failed"; ViewData[RESULT_FIELD_KEY] = "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_FIELD_KEY] = "failed"; ViewData[RESULT_FIELD_KEY] = "No file name provided"; return(View()); } var fileName = _fileProvider.GetFileName(uploadFile.FileName); if (string.IsNullOrEmpty(fileName)) { ViewData[RESULTCODE_FIELD_KEY] = "failed"; ViewData[RESULT_FIELD_KEY] = "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_FIELD_KEY] = "failed"; ViewData[RESULT_FIELD_KEY] = $"Files with {fileExtension} extension cannot be uploaded"; return(View()); } //A warning (SCS0018 - Path Traversal) from the "Security Code Scan" analyzer may appear at this point. //In this case, it is not relevant. The input is not supplied by user. using (var fileStream = new FileStream(filePath, FileMode.Create)) { uploadFile.CopyTo(fileStream); } ViewData[RESULTCODE_FIELD_KEY] = "success"; ViewData[RESULT_FIELD_KEY] = "success"; ViewData[FILENAME_FIELD_KEY] = Url.Content($"{directory}{fileName}"); return(View()); }
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()); }
/// <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> /// Prepare the favicon model /// </summary> /// <returns>Favicon model</returns> public virtual FaviconModel PrepareFaviconModel() { var model = new FaviconModel(); //try loading a store specific favicon var faviconFileName = $"favicon-{_storeContext.CurrentStore.Id}.ico"; var localFaviconPath = _fileProvider.Combine(_hostingEnvironment.WebRootPath, faviconFileName); if (!_fileProvider.FileExists(localFaviconPath)) { //try loading a generic favicon faviconFileName = "favicon.ico"; localFaviconPath = _fileProvider.Combine(_hostingEnvironment.WebRootPath, faviconFileName); if (!_fileProvider.FileExists(localFaviconPath)) { return(model); } } model.FaviconUrl = _webHelper.GetStoreLocation() + faviconFileName; return(model); }
/// <summary> /// Executes a task /// </summary> public virtual void Execute() { try { var products = _productService.SearchProducts(); _logger.InsertLog(Core.Domain.Logging.LogLevel.Information, "Fetch products start"); //_logger.ClearLog(); var filePath = _fileProvider.Combine(_fileProvider.MapPath("~/wwwroot/files/"), "GMCFetch.txt"); using (var fileStream = new FileStream(filePath, FileMode.Create)) { string domain = "https://arrowwarehousing.co.nz/"; Core.Domain.Media.Picture picture; string pictureUrl; string seName; string availability; string price; StringBuilder sb = new StringBuilder(); string row = "ID" + "\t" + "title" + "\t" + "description" + "\t" + "link" + "\t" + "image_link" + "\t" + "availability" + "\t" + "price" + "\t" + "google_product_category" + "\t" + "identifier_exists"; sb.AppendLine(row); for (int i = 0; i < products.Count; i++) { availability = products[i].StockQuantity > 0 ? "in stock" : "out of stock"; seName = string.Format("{0}{1}", domain, _urlRecordService.GetSeName(products[i])); picture = _pictureService.GetPicturesByProductId(products[i].Id).FirstOrDefault(); pictureUrl = _pictureService.GetPictureUrl(picture.Id); price = string.Format("{0:0.00} NZD", products[i].Price); row = string.Format("{0}" + "\t" + "{1}" + "\t" + "{2}" + "\t" + "{3}" + "\t" + "{4}" + "\t" + "{5}" + "\t" + "{6}" + "\t" + "{7}" + "\t" + "false", products[i].Id, products[i].Name, products[i].ShortDescription, seName, pictureUrl, availability, price, products[i].ProductCategories.FirstOrDefault().Category.Name); sb.AppendLine(row); } byte[] bdata = Encoding.Default.GetBytes(sb.ToString()); fileStream.Write(bdata, 0, bdata.Length); fileStream.Close(); } _logger.InsertLog(Core.Domain.Logging.LogLevel.Information, "Fetch products end"); } catch (Exception ex) { _logger.Error("Fetch products exception: ", ex); } }
public virtual IActionResult MaintenanceDeleteFiles(MaintenanceModel model) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenance)) { return(AccessDeniedView()); } var startDateValue = model.DeleteExportedFiles.StartDate == null ? null : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.DeleteExportedFiles.StartDate.Value, _dateTimeHelper.CurrentTimeZone); var endDateValue = model.DeleteExportedFiles.EndDate == null ? null : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.DeleteExportedFiles.EndDate.Value, _dateTimeHelper.CurrentTimeZone).AddDays(1); model.DeleteExportedFiles.NumberOfDeletedFiles = 0; foreach (var fullPath in _fileProvider.GetFiles(_fileProvider.GetAbsolutePath(EXPORT_IMPORT_PATH))) { try { var fileName = _fileProvider.GetFileName(fullPath); if (fileName.Equals("index.htm", StringComparison.InvariantCultureIgnoreCase)) { continue; } var info = _fileProvider.GetFileInfo(_fileProvider.Combine(EXPORT_IMPORT_PATH, fileName)); var lastModifiedTimeUtc = info.LastModified.UtcDateTime; if ((!startDateValue.HasValue || startDateValue.Value < lastModifiedTimeUtc) && (!endDateValue.HasValue || lastModifiedTimeUtc < endDateValue.Value)) { _fileProvider.DeleteFile(fullPath); model.DeleteExportedFiles.NumberOfDeletedFiles++; } } catch (Exception exc) { ErrorNotification(exc, false); } } return(View(model)); }
/// <summary> /// Get picture (thumb) local path /// </summary> /// <param name="thumbFileName">Filename</param> /// <returns>Local picture thumb path</returns> protected virtual string GetThumbLocalPath(string thumbFileName) { var thumbsDirectoryPath = _fileProvider.GetAbsolutePath(NopMediaDefaults.ImageThumbsPath); //if (_mediaSettings.MultipleThumbDirectories) //{ // //get the first two letters of the file name // var fileNameWithoutExtension = _fileProvider.GetFileNameWithoutExtension(thumbFileName); // if (fileNameWithoutExtension != null && fileNameWithoutExtension.Length > NopMediaDefaults.MultipleThumbDirectoriesLength) // { // var subDirectoryName = fileNameWithoutExtension.Substring(0, NopMediaDefaults.MultipleThumbDirectoriesLength); // thumbsDirectoryPath = _fileProvider.GetAbsolutePath(NopMediaDefaults.ImageThumbsPath, subDirectoryName); // _fileProvider.CreateDirectory(thumbsDirectoryPath); // } //} var thumbFilePath = _fileProvider.Combine(thumbsDirectoryPath, thumbFileName); return(thumbFilePath); }
/// <summary> /// Get picture (thumb) local path /// </summary> /// <param name="thumbFileName">Filename</param> /// <returns>Local picture thumb path</returns> protected virtual string GetThumbLocalPath(string thumbFileName) { var thumbsDirectoryPath = _fileProvider.GetAbsolutePath(THUMBS_PATH); if (_mediaSettings.MultipleThumbDirectories) { //get the first two letters of the file name var fileNameWithoutExtension = _fileProvider.GetFileNameWithoutExtension(thumbFileName); if (fileNameWithoutExtension != null && fileNameWithoutExtension.Length > MULTIPLE_THUMB_DIRECTORIES_LENGTH) { var subDirectoryName = fileNameWithoutExtension.Substring(0, MULTIPLE_THUMB_DIRECTORIES_LENGTH); thumbsDirectoryPath = _fileProvider.GetAbsolutePath(THUMBS_PATH, subDirectoryName); _fileProvider.CreateDirectory(thumbsDirectoryPath); } } var thumbFilePath = _fileProvider.Combine(thumbsDirectoryPath, thumbFileName); return(thumbFilePath); }
/// <summary> /// Get plugin logo URL /// </summary> /// <param name="pluginDescriptor">Plugin descriptor</param> /// <returns>Logo URL</returns> public virtual string GetPluginLogoUrl(PluginDescriptor pluginDescriptor) { var pluginDirectory = _fileProvider.GetDirectoryName(pluginDescriptor.OriginalAssemblyFile); if (string.IsNullOrEmpty(pluginDirectory)) { return(null); } //check for supported extensions var logoExtension = NopPluginDefaults.SupportedLogoImageExtensions .FirstOrDefault(ext => _fileProvider.FileExists(_fileProvider.Combine(pluginDirectory, $"{NopPluginDefaults.LogoFileName}.{ext}"))); if (string.IsNullOrWhiteSpace(logoExtension)) { return(null); } var storeLocation = _webHelper.GetStoreLocation(); var logoUrl = $"{storeLocation}{NopPluginDefaults.PathName}/" + $"{_fileProvider.GetDirectoryNameOnly(pluginDirectory)}/{NopPluginDefaults.LogoFileName}.{logoExtension}"; return(logoUrl); }
static PerformDeployOfAbstration() { _fileProvider = CommonHelper.DefaultFileProvider; _shadowCopyFolder = _fileProvider.MapPath(ShadowCopyPath); _reserveShadowCopyFolder = _fileProvider.Combine(_fileProvider.MapPath(ShadowCopyPath), $"{RESERVE_SHADOW_COPY_FOLDER_NAME}{DateTime.Now.ToFileTimeUtc()}"); }
/// <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()); }
/// <summary> /// Upload single item from the archive into the physical directory /// </summary> /// <param name="archivePath">Path to the archive</param> /// <returns>Uploaded item descriptor</returns> protected virtual IDescriptor UploadSingleItem(string archivePath) { //get path to the plugins directory var pluginsDirectory = _fileProvider.MapPath(NopPluginDefaults.Path); //get path to the themes directory var themesDirectory = string.Empty; if (!string.IsNullOrEmpty(NopPluginDefaults.ThemesPath)) { themesDirectory = _fileProvider.MapPath(NopPluginDefaults.ThemesPath); } IDescriptor descriptor = null; string uploadedItemDirectoryName; using (var archive = ZipFile.OpenRead(archivePath)) { //the archive should contain only one root directory (the plugin one or the theme one) var rootDirectories = archive.Entries.Select(p => p.FullName.Split('/')[0]).Distinct().ToList(); if (rootDirectories.Count != 1) { throw new Exception("The archive should contain only one root plugin or theme directory. " + "For example, Payments.PayPalDirect or DefaultClean. " + $"To upload multiple items, the archive should have the '{NopPluginDefaults.UploadedItemsFileName}' file in the root"); } //get directory name (remove the ending /) uploadedItemDirectoryName = rootDirectories.First(); //try to get descriptor of the uploaded item foreach (var entry in archive.Entries) { //whether it's a plugin descriptor var isPluginDescriptor = entry.FullName .Equals($"{uploadedItemDirectoryName}/{NopPluginDefaults.DescriptionFileName}", StringComparison.InvariantCultureIgnoreCase); //or whether it's a theme descriptor var isThemeDescriptor = entry.FullName .Equals($"{uploadedItemDirectoryName}/{NopPluginDefaults.ThemeDescriptionFileName}", StringComparison.InvariantCultureIgnoreCase); if (!isPluginDescriptor && !isThemeDescriptor) { continue; } using var unzippedEntryStream = entry.Open(); using var reader = new StreamReader(unzippedEntryStream); //whether a plugin is upload if (isPluginDescriptor) { descriptor = PluginDescriptor.GetPluginDescriptorFromText(reader.ReadToEnd()); //ensure that the plugin current version is supported if (!((PluginDescriptor)descriptor).SupportedVersions.Contains(NopVersion.CURRENT_VERSION)) { throw new Exception($"This plugin doesn't support the current version - {NopVersion.CURRENT_VERSION}"); } } //or whether a theme is upload if (isThemeDescriptor) { descriptor = _themeProvider.GetThemeDescriptorFromText(reader.ReadToEnd()); } break; } } if (descriptor == null) { throw new Exception("No descriptor file is found. It should be in the root of the archive."); } if (string.IsNullOrEmpty(uploadedItemDirectoryName)) { throw new Exception($"Cannot get the {(descriptor is PluginDescriptor ? "plugin" : "theme")} directory name"); } //get path to upload var directoryPath = descriptor is PluginDescriptor ? pluginsDirectory : themesDirectory; var pathToUpload = _fileProvider.Combine(directoryPath, uploadedItemDirectoryName); //ensure it's a new directory (e.g. some old files are not required when re-uploading a plugin) //furthermore, zip extract functionality cannot override existing files //but there could deletion issues (related to file locking, etc). In such cases the directory should be deleted manually if (_fileProvider.DirectoryExists(pathToUpload)) { _fileProvider.DeleteDirectory(pathToUpload); } //unzip archive ZipFile.ExtractToDirectory(archivePath, directoryPath); return(descriptor); }
/// <summary> /// Returns the path to the backup file /// </summary> /// <param name="backupFileName">The name of the backup file</param> /// <returns>The path to the backup file</returns> public virtual string GetBackupPath(string backupFileName) { return(_fileProvider.Combine(GetBackupDirectoryPath(), backupFileName)); }
/// <summary> /// Initialize /// </summary> /// <param name="applicationPartManager">Application part manager</param> /// <param name="config">Config</param> public static void Initialize(IPerformDeploy performDeploy, NopConfig config) { if (performDeploy == null) { throw new ArgumentNullException(nameof(performDeploy)); } if (config == null) { throw new ArgumentNullException(nameof(config)); } using (new WriteLockDisposable(Locker)) { // TODO: Add verbose exception handling / raising here since this is happening on app startup and could // prevent app from starting altogether var pluginFolder = _fileProvider.MapPath(PluginsPath); _shadowCopyFolder = _fileProvider.MapPath(ShadowCopyPath); _reserveShadowCopyFolder = _fileProvider.Combine(_fileProvider.MapPath(ShadowCopyPath), $"{RESERVE_SHADOW_COPY_FOLDER_NAME}{DateTime.Now.ToFileTimeUtc()}"); var referencedPlugins = new List <PluginDescriptor>(); var incompatiblePlugins = new List <string>(); try { var installedPluginSystemNames = GetInstalledPluginNames(_fileProvider.MapPath(InstalledPluginsFilePath)); Debug.WriteLine("Creating shadow copy folder and querying for DLLs"); //ensure folders are created _fileProvider.CreateDirectory(pluginFolder); _fileProvider.CreateDirectory(_shadowCopyFolder); //get list of all files in bin var binFiles = _fileProvider.GetFiles(_shadowCopyFolder, "*", false); if (config.ClearPluginShadowDirectoryOnStartup) { //clear out shadow copied plugins foreach (var f in binFiles) { if (_fileProvider.GetFileName(f).Equals("placeholder.txt", StringComparison.InvariantCultureIgnoreCase)) { continue; } Debug.WriteLine("Deleting " + f); try { //ignore index.htm var fileName = _fileProvider.GetFileName(f); if (fileName.Equals("index.htm", StringComparison.InvariantCultureIgnoreCase)) { continue; } _fileProvider.DeleteFile(f); } catch (Exception exc) { Debug.WriteLine("Error deleting file " + f + ". Exception: " + exc); } } //delete all reserve folders foreach (var directory in _fileProvider.GetDirectories(_shadowCopyFolder, RESERVE_SHADOW_COPY_FOLDER_NAME_PATTERN)) { try { _fileProvider.DeleteDirectory(directory); } catch { //do nothing } } } //load description files foreach (var dfd in GetDescriptionFilesAndDescriptors(pluginFolder)) { var descriptionFile = dfd.Key; var pluginDescriptor = dfd.Value; //ensure that version of plugin is valid if (!pluginDescriptor.SupportedVersions.Contains(NopVersion.CurrentVersion, StringComparer.InvariantCultureIgnoreCase)) { incompatiblePlugins.Add(pluginDescriptor.SystemName); continue; } //some validation if (string.IsNullOrWhiteSpace(pluginDescriptor.SystemName)) { throw new Exception($"A plugin '{descriptionFile}' has no system name. Try assigning the plugin a unique name and recompiling."); } if (referencedPlugins.Contains(pluginDescriptor)) { throw new Exception($"A plugin with '{pluginDescriptor.SystemName}' system name is already defined"); } //set 'Installed' property pluginDescriptor.Installed = installedPluginSystemNames .FirstOrDefault(x => x.Equals(pluginDescriptor.SystemName, StringComparison.InvariantCultureIgnoreCase)) != null; try { var directoryName = _fileProvider.GetDirectoryName(descriptionFile); if (string.IsNullOrEmpty(directoryName)) { throw new Exception($"Directory cannot be resolved for '{_fileProvider.GetFileName(descriptionFile)}' description file"); } //get list of all DLLs in plugins (not in bin!) var pluginFiles = _fileProvider.GetFiles(directoryName, "*.dll", false) //just make sure we're not registering shadow copied plugins .Where(x => !binFiles.Select(q => q).Contains(x)) .Where(x => IsPackagePluginFolder(_fileProvider.GetDirectoryName(x))) .ToList(); //other plugin description info var mainPluginFile = pluginFiles .FirstOrDefault(x => _fileProvider.GetFileName(x).Equals(pluginDescriptor.AssemblyFileName, StringComparison.InvariantCultureIgnoreCase)); //plugin have wrong directory if (mainPluginFile == null) { incompatiblePlugins.Add(pluginDescriptor.SystemName); continue; } pluginDescriptor.OriginalAssemblyFile = mainPluginFile; //shadow copy main plugin file pluginDescriptor.ReferencedAssembly = performDeploy.PerformFileDeploy(mainPluginFile, config); //load all other referenced assemblies now foreach (var plugin in pluginFiles .Where(x => !_fileProvider.GetFileName(x).Equals(_fileProvider.GetFileName(mainPluginFile), StringComparison.InvariantCultureIgnoreCase)) .Where(x => !IsAlreadyLoaded(x))) { performDeploy.PerformFileDeploy(plugin, config); } //init plugin type (only one plugin per assembly is allowed) foreach (var t in pluginDescriptor.ReferencedAssembly.GetTypes()) { if (typeof(IPlugin).IsAssignableFrom(t)) { if (!t.IsInterface) { if (t.IsClass && !t.IsAbstract) { pluginDescriptor.PluginType = t; break; } } } } referencedPlugins.Add(pluginDescriptor); } catch (ReflectionTypeLoadException ex) { //add a plugin name. this way we can easily identify a problematic plugin var msg = $"Plugin '{pluginDescriptor.FriendlyName}'. "; foreach (var e in ex.LoaderExceptions) { msg += e.Message + Environment.NewLine; } var fail = new Exception(msg, ex); throw fail; } catch (Exception ex) { //add a plugin name. this way we can easily identify a problematic plugin var msg = $"Plugin '{pluginDescriptor.FriendlyName}'. {ex.Message}"; var fail = new Exception(msg, ex); throw fail; } } } catch (Exception ex) { var msg = string.Empty; for (var e = ex; e != null; e = e.InnerException) { msg += e.Message + Environment.NewLine; } var fail = new Exception(msg, ex); throw fail; } ReferencedPlugins = referencedPlugins; IncompatiblePlugins = incompatiblePlugins; } }
/// <summary> /// Install plugin /// </summary> public override void Install() { //pictures var sampleImagesPath = _fileProvider.MapPath("~/Plugins/Widgets.NivoSlider/Content/nivoslider/sample-images/"); //settings var settings = new NivoSliderSettings { Picture1Id = _pictureService.InsertPicture(_fileProvider.ReadAllBytes(_fileProvider.Combine(sampleImagesPath, "banner1.jpg")), MimeTypes.ImagePJpeg, "banner_1").Id, Text1 = "", Link1 = _webHelper.GetStoreLocation(false), Picture2Id = _pictureService.InsertPicture(_fileProvider.ReadAllBytes(_fileProvider.Combine(sampleImagesPath, "banner2.jpg")), MimeTypes.ImagePJpeg, "banner_2").Id, Text2 = "", Link2 = _webHelper.GetStoreLocation(false) //Picture3Id = _pictureService.InsertPicture(File.ReadAllBytes(_fileProvider.Combine(sampleImagesPath,"banner3.jpg")), MimeTypes.ImagePJpeg, "banner_3").Id, //Text3 = "", //Link3 = _webHelper.GetStoreLocation(false), }; _settingService.SaveSetting(settings); _localizationService.AddLocaleResource(new Dictionary <string, string> { ["Plugins.Widgets.NivoSlider.Picture1"] = "Picture 1", ["Plugins.Widgets.NivoSlider.Picture2"] = "Picture 2", ["Plugins.Widgets.NivoSlider.Picture3"] = "Picture 3", ["Plugins.Widgets.NivoSlider.Picture4"] = "Picture 4", ["Plugins.Widgets.NivoSlider.Picture5"] = "Picture 5", ["Plugins.Widgets.NivoSlider.Picture"] = "Picture", ["Plugins.Widgets.NivoSlider.Picture.Hint"] = "Upload picture.", ["Plugins.Widgets.NivoSlider.Text"] = "Comment", ["Plugins.Widgets.NivoSlider.Text.Hint"] = "Enter comment for picture. Leave empty if you don't want to display any text.", ["Plugins.Widgets.NivoSlider.Link"] = "URL", ["Plugins.Widgets.NivoSlider.Link.Hint"] = "Enter URL. Leave empty if you don't want this picture to be clickable.", ["Plugins.Widgets.NivoSlider.AltText"] = "Image alternate text", ["Plugins.Widgets.NivoSlider.AltText.Hint"] = "Enter alternate text that will be added to image." }); base.Install(); }
/// <summary> /// Gets a list of directories (physical paths) which require write permission /// </summary> /// <returns>Result</returns> public static IEnumerable <string> GetDirectoriesWrite(this INopFileProvider fileProvider) { var rootDir = fileProvider.MapPath("~/"); var dirsToCheck = new List <string> { fileProvider.Combine(rootDir, "App_Data"), fileProvider.Combine(rootDir, "bin"), fileProvider.Combine(rootDir, "logs"), fileProvider.Combine(rootDir, "Plugins"), fileProvider.Combine(rootDir, @"Plugins\bin"), fileProvider.Combine(rootDir, @"wwwroot\bundles"), fileProvider.Combine(rootDir, @"wwwroot\db_backups"), fileProvider.Combine(rootDir, @"wwwroot\files\exportimport"), fileProvider.Combine(rootDir, @"wwwroot\icons"), fileProvider.Combine(rootDir, @"wwwroot\images"), fileProvider.Combine(rootDir, @"wwwroot\images\thumbs"), fileProvider.Combine(rootDir, @"wwwroot\images\uploaded") }; return(dirsToCheck); }