public static void EditScriptFile(CMSDatabase db, string path, StyleModel model, HttpContext context, out string redirectPath, out bool successfullyCompleted) { Regex regex = new Regex(@"^((\w|-|_)+)(>(\w|-|_)+)*\.js$"); if (!regex.IsMatch(path)) { successfullyCompleted = false; redirectPath = string.Empty; return; } IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>(); string scriptFileFullName = path.Substring(path.LastIndexOf('>') + 1); path = path.Substring(0, path.Length - scriptFileFullName.Length); if (!string.IsNullOrEmpty(path)) { path = path.Replace('>', '/'); if (!path[path.Length - 1].Equals('/')) { path = path.Insert(path.Length, "/"); } } path = $"{env.GetStorageFolderFullPath()}{path}"; string pathToFile = path + scriptFileFullName; if (!File.Exists(pathToFile) || !HasAccessToFolder(path, env)) { successfullyCompleted = false; redirectPath = string.Empty; return; } model.FileName = OtherFunctions.GetCorrectName(model.FileName, context); if (string.IsNullOrEmpty(model.FileName)) { successfullyCompleted = false; redirectPath = string.Empty; return; } string oldScriptFileName = scriptFileFullName.Substring(0, scriptFileFullName.Length - 3); string scriptFileFullPath = $"{path}{model.FileName}.js"; if (!oldScriptFileName.Equals(model.FileName, StringComparison.Ordinal)) { File.Move($"{pathToFile}", scriptFileFullPath); } using (StreamWriter writer = new StreamWriter(scriptFileFullPath)) { writer.Write(model.FileContent); } successfullyCompleted = true; redirectPath = scriptFileFullPath.Substring(env.GetStorageFolderFullPath().Length).Replace('/', '>'); LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{pathToFile.Substring(env.GetStorageFolderFullPath().Length - 1)}{(!oldScriptFileName.Equals(model.FileName, StringComparison.Ordinal) ? $" -> {scriptFileFullPath.Substring(env.GetStorageFolderFullPath().Length - 1)}" : string.Empty)}: " + $"{(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.FileEdited}" ); }
public IActionResult FileManager(string path) { string fullPath = string.Empty; IHostingEnvironment env = HttpContext.RequestServices.GetService <IHostingEnvironment>(); if (string.IsNullOrEmpty(path)) { fullPath = env.GetStorageFolderFullPath(); } else { Regex regex = new Regex(@"^((\w|-|_)+)(>(\w|-|_)+)*$"); if (!regex.IsMatch(path)) { return(Redirect($"{HttpContext.Request.Path}?pageID={(int)AdminPanelPages.FileManager}")); } fullPath = env.GetStorageFolderFullPath() + path.Replace('>', '/').Insert(path.Length, "/"); } // Проверяем можно ли зайти в текущую директорию if (!FileManagerManagementFunctions.HasAccessToFolder(fullPath, env)) { return(Redirect($"{HttpContext.Request.Path}?pageID={(int)AdminPanelPages.FileManager}")); } // Получаем файлы и папки в текущей директории FileManagerObject[] fileManagerObjects = FileManagerManagementFunctions.GetFilesAndFolders(fullPath, env, out bool pathExists); if (!pathExists) { return(Redirect($"{HttpContext.Request.Path}?pageID={(int)AdminPanelPages.FileManager}")); } HttpContext.Items["pageID"] = AdminPanelPages.FileManager; // Получаем навигационную цепочку LinkedList <KeyValuePair <string, string> > breadcrumbs = new LinkedList <KeyValuePair <string, string> >(); // Key - название; Value - путь StringBuilder pathBuilder = new StringBuilder(); breadcrumbs.AddLast(new KeyValuePair <string, string>("/", string.Empty)); if (!string.IsNullOrEmpty(path)) { string[] subdirectories = path.Split('>'); for (int i = 0; i < subdirectories.Length; ++i) { pathBuilder.Clear(); for (int j = 0; j <= i; ++j) { pathBuilder.Append($"{subdirectories[j]}"); if (j != i) { pathBuilder.Append(">"); } } breadcrumbs.AddLast(new KeyValuePair <string, string>(subdirectories[i], pathBuilder.ToString())); } } HttpContext.Items["CurrentDirectoryBreadcrumbs"] = breadcrumbs; return(View("FileManager/Index", fileManagerObjects)); }
public ImageHandler(string pathToImage, bool itsFullPath, CMSDatabase db, IHostingEnvironment env) { this.db = db; this.env = env; if (pathToImage[pathToImage.Length - 1].Equals('/')) { return; } pathToImageFolder = pathToImage.Substring(0, pathToImage.LastIndexOf('/') + 1); sourceImageName = pathToImage.Substring(pathToImageFolder.Length); if (!sourceImageName.Contains(".")) { return; } sourceImageName = sourceImageName.Substring(0, sourceImageName.LastIndexOf('.')); sourceImageExtension = pathToImage.Substring(pathToImageFolder.Length + sourceImageName.Length); if ((!sourceImageExtension.Equals(".jpg", StringComparison.OrdinalIgnoreCase) && !sourceImageExtension.Equals(".jpeg", StringComparison.OrdinalIgnoreCase) && !sourceImageExtension.Equals(".png", StringComparison.OrdinalIgnoreCase))) { return; } if (!itsFullPath) { if (pathToImageFolder[0].Equals('/')) { pathToImageFolder = pathToImageFolder.Substring(1); } pathToImageFolder = env.GetStorageFolderFullPath() + pathToImageFolder; } sourceImageFullName = sourceImageName + sourceImageExtension; sourceImageFullPath = pathToImageFolder + sourceImageFullName; isExisted = File.Exists(sourceImageFullPath); sourceImageShortPath = sourceImageFullPath.Substring(env.GetStorageFolderFullPath().Length).Insert(0, "/"); // Если изображения не существует, то удаляем зависимые изображения, если таковые имеются и информацию из БД if (!isExisted) { // Удаляем информацию об изображении из БД Image image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(sourceImageShortPath) && img.ShortPath.Equals(sourceImageShortPath, StringComparison.Ordinal)); if (image != null) { db.Images.Remove(image); db.SaveChanges(); } ImagesManagementFunctions.DeleteDependentImages(pathToImageFolder, sourceImageFullName); } else { GetSourceImageInfo(); } }
public static void RenameImageAndDependencies(CMSDatabase db, IHostingEnvironment env, string pathToImages, string oldImageName, string newImageName, string imageExtension, bool saveChangesInDB = true) { if (string.IsNullOrEmpty(pathToImages) || string.IsNullOrEmpty(oldImageName) || string.IsNullOrEmpty(newImageName) || !Directory.Exists(pathToImages)) { return; } if (!pathToImages[pathToImages.Length - 1].Equals('/')) { pathToImages = pathToImages.Insert(pathToImages.Length, "/"); } string[] images = Directory.GetFiles(pathToImages, $"*{oldImageName}*{imageExtension}"); Regex regex = new Regex($"{oldImageName}(_\\d+x\\d+)?(_q\\d{{1,3}})?{imageExtension}$"); images = (from img in images where regex.IsMatch(img) select img).ToArray(); foreach (var img in images) { string fileEnding = img.Substring(pathToImages.Length + oldImageName.Length); File.Move(img, $"{pathToImages}{newImageName}{fileEnding}"); } string shortPathToOldImage = pathToImages.Substring(env.GetStorageFolderFullPath().Length).Insert(0, "/") + oldImageName + imageExtension; string shortPathToNewImage = pathToImages.Substring(env.GetStorageFolderFullPath().Length).Insert(0, "/") + newImageName + imageExtension; // Изменяем данные в БД // Если в БД есть неудаленная информация, то удаляем её Image image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(shortPathToNewImage) && img.ShortPath.Equals(shortPathToNewImage, StringComparison.Ordinal)); if (image != null && db.Entry(image).State != EntityState.Modified) { db.Remove(image); } image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(shortPathToOldImage) && img.ShortPath.Equals(shortPathToOldImage, StringComparison.Ordinal)); if (image != null) { if (db.Entry(image).State == EntityState.Deleted) { db.Entry(image).State = EntityState.Modified; } image.ShortPath = shortPathToNewImage; image.ShortPathHash = OtherFunctions.GetHashFromString(shortPathToNewImage); image.FullName = shortPathToNewImage.Substring(shortPathToNewImage.LastIndexOf('/') + 1); } if (saveChangesInDB) { db.SaveChanges(); } }
public static void DeleteImage(string pathToImageFolder, string imageFullName, CMSDatabase db, IHostingEnvironment env) { if (string.IsNullOrEmpty(pathToImageFolder) || string.IsNullOrEmpty(imageFullName)) { return; } if (!pathToImageFolder[pathToImageFolder.Length - 1].Equals('/')) { pathToImageFolder = pathToImageFolder.Insert(pathToImageFolder.Length, "/"); } if (!Directory.Exists(pathToImageFolder)) { return; } string pathToFile = $"{pathToImageFolder}{imageFullName}"; if (!File.Exists(pathToFile)) { return; } File.Delete(pathToFile); // Удаляем информацию об изображении из БД string shortPathToImage = pathToImageFolder.Substring(env.GetStorageFolderFullPath().Length).Insert(0, "/") + imageFullName; Image image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(shortPathToImage) && img.ShortPath.Equals(shortPathToImage, StringComparison.Ordinal)); if (image != null) { db.Images.Remove(image); db.SaveChanges(); } // Если у изображения были зависимости (сжатые или ресайзнутые вариации), то удаляем их DeleteDependentImages(pathToImageFolder, imageFullName); }
public static string GetImagesFolderFullPath(this IHostingEnvironment env) { if (string.IsNullOrEmpty(imagesFolderFullPath)) { imagesFolderFullPath = $"{env.GetStorageFolderFullPath()}images/"; } return(imagesFolderFullPath); }
public static string GetScriptsFolderFullPath(this IHostingEnvironment env) { if (string.IsNullOrEmpty(scriptsFolderFullPath)) { scriptsFolderFullPath = $"{env.GetStorageFolderFullPath()}scripts/"; } return(scriptsFolderFullPath); }
public static void CreateFolder(CMSDatabase db, string path, string folderName, HttpContext context, out bool successfullyCreated) { IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>(); if (string.IsNullOrEmpty(path)) { path = env.GetStorageFolderFullPath(); } else { Regex regex = new Regex(@"^((\w|-|_)+)(>(\w|-|_)+)*$"); if (!regex.IsMatch(path)) { successfullyCreated = false; return; } path = path.Replace('>', '/'); if (!path[path.Length - 1].Equals('/')) { path = path.Insert(path.Length, "/"); } path = $"{env.GetStorageFolderFullPath()}{path}"; } if (!Directory.Exists(path) || !HasAccessToFolder(path, env)) { successfullyCreated = false; return; } folderName = OtherFunctions.GetCorrectName(folderName, context); if (string.IsNullOrEmpty(folderName)) { successfullyCreated = false; return; } folderName = GetUniqueFileOrFolderName(path, folderName); Directory.CreateDirectory($"{path}{folderName}"); successfullyCreated = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{folderName}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.FolderCreatedIn} {path.Substring(env.GetStorageFolderFullPath().Length - 1)}" ); }
public static string[] GetProductImageUrls(ProductPage product, IHostingEnvironment env, int skipImages = 0) { string[] productImages = new string[0]; if (product != null) { string imagesPath = $"{env.GetProductsImagesFolderFullPath()}{product.ID}/"; if (Directory.Exists(imagesPath)) { productImages = Directory.GetFiles(imagesPath, $"*{product.Alias}*.jpg"); if (productImages.Length > 0) { Regex regex = new Regex($"{product.Alias}(_(\\d)+)?.jpg$"); productImages = (from img in productImages where regex.IsMatch(img) let imageNameEnding = regex.Match(img).Value.Substring(product.Alias.Length) orderby imageNameEnding.Length == 4 ? 0 : Convert.ToInt32(imageNameEnding.Substring(1, imageNameEnding.IndexOf('.') - 1)) select img.Substring(env.GetStorageFolderFullPath().Length - 1)).Skip(skipImages).ToArray(); } } } return(productImages); }
private static IEnumerable <FileManagerObject> GetFolders(string path, IHostingEnvironment env) { // Без проверки на существование директории path, т.к. этот метод работает в паре с GetFilesAndFolders return(Directory.GetDirectories(path) .Where(directory => { if (!directory[directory.Length - 1].Equals('/')) { directory = directory.Insert(directory.Length, "/"); } return HasAccessToFolder(directory, env); }) .Select(directory => { string shortPathToFolder = directory.Substring(env.GetStorageFolderFullPath().Length); if (shortPathToFolder[shortPathToFolder.Length - 1].Equals('/')) { shortPathToFolder = shortPathToFolder.Substring(0, shortPathToFolder.Length - 1); } string folderName = shortPathToFolder.Substring(shortPathToFolder.LastIndexOf('/') + 1); shortPathToFolder = shortPathToFolder.Replace('/', '>'); bool canDelete = true; if (!directory[directory.Length - 1].Equals('/')) { directory = directory.Insert(directory.Length, "/"); } foreach (var directoryInfo in env.GetStorageDirectoriesInfo()) { if (directory.Equals(directoryInfo.Path, StringComparison.OrdinalIgnoreCase)) { canDelete = false; break; } } return new FileManagerObject { Name = folderName, ShortPath = shortPathToFolder, Type = FileManagerObjectType.Folder, CanDelete = canDelete }; }).OrderBy(o => o.Name)); }
public IActionResult EditScriptFile(string path) { Regex regex = new Regex(@"^((\w|-|_)+)(>(\w|-|_)+)*\.js$"); if (!regex.IsMatch(path)) { return(Redirect($"{HttpContext.Request.Path}?pageID={(int)AdminPanelPages.FileManager}")); } HttpContext.Items["PathToFile"] = path; IHostingEnvironment env = HttpContext.RequestServices.GetService <IHostingEnvironment>(); HttpContext.Items["pageID"] = AdminPanelPages.EditScript; string scriptFileFullName = path.Substring(path.LastIndexOf('>') + 1); path = path.Substring(0, path.Length - scriptFileFullName.Length); if (!string.IsNullOrEmpty(path)) { path = path.Replace('>', '/'); if (!path[path.Length - 1].Equals('/')) { path = path.Insert(path.Length, "/"); } } path = $"{env.GetStorageFolderFullPath()}{path}"; string pathToFile = path + scriptFileFullName; if (!System.IO.File.Exists(pathToFile) || !FileManagerManagementFunctions.HasAccessToFolder(path, env)) { return(Redirect($"{HttpContext.Request.Path}?pageID={(int)AdminPanelPages.FileManager}")); } string scriptFileContent = OtherFunctions.GetFileContent(pathToFile); StyleModel model = new StyleModel { FileName = scriptFileFullName.Substring(0, scriptFileFullName.Length - 3), FileContent = scriptFileContent }; return(View("FileManager/EditScriptFile", model)); }
public static void UploadFileToServer(CMSDatabase db, string path, IFormFile file, HttpContext context, out bool successfulUpload) { IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>(); if (string.IsNullOrEmpty(path)) { path = env.GetStorageFolderFullPath(); } else { Regex regex = new Regex(@"^((\w|-|_)+)(>(\w|-|_)+)*$"); if (!regex.IsMatch(path)) { successfulUpload = false; return; } path = path.Replace('>', '/'); if (!path[path.Length - 1].Equals('/')) { path = path.Insert(path.Length, "/"); } path = $"{env.GetStorageFolderFullPath()}{path}"; } if (!Directory.Exists(path) || !HasAccessToFolder(path, env)) { successfulUpload = false; return; } int pointIndex = file.FileName.LastIndexOf('.'); if (pointIndex == -1) { successfulUpload = false; return; } string fileExtension = file.FileName.Substring(pointIndex).ToLower(); bool itsCorrectExtension = false; foreach (var typeOfExtension in typesOfExtensions) { if (fileExtension.Equals(typeOfExtension.Key, StringComparison.Ordinal)) { itsCorrectExtension = true; break; } } if (!itsCorrectExtension) { successfulUpload = false; return; } string fileName = file.FileName.Substring(0, pointIndex); fileName = OtherFunctions.GetCorrectName(fileName, context); if (string.IsNullOrEmpty(fileName)) { fileName = "uploaded_file"; } fileName = GetUniqueFileOrFolderName(path, fileName, fileExtension); using (FileStream fs = new FileStream($"{path}{fileName}", FileMode.Create)) { file.CopyTo(fs); } successfulUpload = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{fileName}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.FileUploadedTo} {path.Substring(env.GetStorageFolderFullPath().Length - 1)}" ); }
public static void UploadProductImageToServer(CMSDatabase db, IFormFile file, int?itemID, HttpContext context, out bool successfullyUploaded) { successfullyUploaded = true; if (!itemID.HasValue || file == null) { successfullyUploaded = false; return; } ProductPage product = db.ProductPages.AsNoTracking().FirstOrDefault(pp => pp.ID == itemID); if (product == null) { successfullyUploaded = false; return; } IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>(); string imagesPath = $"{env.GetProductsImagesFolderFullPath()}{product.ID}/"; Directory.CreateDirectory(imagesPath); string fullImageName = FileManagerManagementFunctions.GetUniqueFileOrFolderName(imagesPath, product.Alias, ".jpg"); string pathToFile = $"{imagesPath}{fullImageName}"; using (Stream stream = file.OpenReadStream()) { try { using (Image <Rgba32> source = SixLabors.ImageSharp.Image.Load(stream)) { // Если остались зависимости от предыдущего изображения, то удаляем их DeleteDependentImages(imagesPath, fullImageName); // Добавляем или изменяем информацию в БД string shortPathToImage = pathToFile.Substring(env.GetStorageFolderFullPath().Length).Insert(0, "/"); Database.Entities.Image image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(shortPathToImage) && img.ShortPath.Equals(shortPathToImage, StringComparison.Ordinal)); if (image == null) { image = new Database.Entities.Image { ShortPath = shortPathToImage, ShortPathHash = OtherFunctions.GetHashFromString(shortPathToImage), FullName = shortPathToImage.Substring(shortPathToImage.LastIndexOf('/') + 1), Width = (uint)source.Width, Height = (uint)source.Height }; db.Images.Add(image); } else // Если вдруг каким-то образом информация об изображении не была удалена из БД { image.Width = (uint)source.Width; image.Height = (uint)source.Height; } db.SaveChanges(); source.Save(pathToFile); LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{product.PageName} (ID-{product.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ProductImageUploaded}" ); } } catch (NotSupportedException) { successfullyUploaded = false; } } }
public static void DeleteFileOrFolder(CMSDatabase db, string path, HttpContext context, out string redirectPath) { IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>(); Regex regex = new Regex(@"^((\w|-|_)+)(>(\w|-|_)+)*(\.\w+)?$"); if (!regex.IsMatch(path)) { redirectPath = null; return; } string fileOrFolderFullName = path.Substring(path.LastIndexOf('>') + 1); redirectPath = path = path.Substring(0, path.Length - fileOrFolderFullName.Length); if (!string.IsNullOrEmpty(path)) { path = path.Replace('>', '/'); if (!path[path.Length - 1].Equals('/')) { path = path.Insert(path.Length, "/"); } if (redirectPath[redirectPath.Length - 1].Equals('>')) { redirectPath = redirectPath.Substring(0, redirectPath.Length - 1); } } path = $"{env.GetStorageFolderFullPath()}{path}"; if (!Directory.Exists(path) || !HasAccessToFolder(path, env)) { redirectPath = null; return; } FileManagerObjectType?type = null; int pointIndex = fileOrFolderFullName.LastIndexOf('.'); if (pointIndex == -1) { type = FileManagerObjectType.Folder; } else { string fileExtension = fileOrFolderFullName.Substring(pointIndex); foreach (var typeOfExtension in typesOfExtensions) { if (fileExtension.Equals(typeOfExtension.Key)) { type = typeOfExtension.Value; break; } } if (!type.HasValue) { redirectPath = null; return; } for (int i = 0; i < pointIndex; ++i) { bool correctSymbol = false; foreach (var symbol in availableSymbolsInName) { if (fileOrFolderFullName[i].Equals(symbol)) { correctSymbol = true; break; } } if (!correctSymbol) { redirectPath = null; return; } } } if (type != FileManagerObjectType.Folder) { string pathToFile = $"{path}{fileOrFolderFullName}"; if (File.Exists(pathToFile)) { if (type == FileManagerObjectType.Image) { ImagesManagementFunctions.DeleteImage(path, fileOrFolderFullName, db, env); } else { File.Delete(pathToFile); } } else { redirectPath = null; } LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{pathToFile.Substring(env.GetStorageFolderFullPath().Length - 1)}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.FileDeleted}" ); } else { string pathToFolder = $"{path}{fileOrFolderFullName}/"; if (!Directory.Exists(pathToFolder)) { redirectPath = null; return; } foreach (var dir in env.GetStorageDirectoriesInfo()) { if (pathToFolder.Equals(dir.Path, StringComparison.OrdinalIgnoreCase)) { redirectPath = null; return; } } Directory.Delete(pathToFolder, true); LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{pathToFolder.Substring(env.GetStorageFolderFullPath().Length - 1)}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.FolderDeleted}" ); } }
private static IEnumerable <FileManagerObject> GetFiles(string path, IHostingEnvironment env) { // Без проверки на существование директории path, т.к. этот метод работает в паре с GetFilesAndFolders return(Directory.GetFiles(path) .Where(pathToFile => { // Проверяем соответствует ли именование файла требованиям: // - название должно быть написано маленькими буквами и содержать только допустимые символы // список допустимых символов: qwertyuiopasdfghjklzxcvbnm1234567890-_ // - файл должен иметь допустимое расширение // список допустимых расширений: .jpg, .jpeg, .png, .bmp, .gif, .ico, .css bool correctExtension = false; foreach (var typeOfExtension in typesOfExtensions) { if (pathToFile.EndsWith(typeOfExtension.Key, StringComparison.Ordinal)) { correctExtension = true; break; } } if (!correctExtension) { return false; } string fileName = pathToFile.Substring(path.Length + 1); int pointIndex = fileName.LastIndexOf('.'); for (int i = 0; i < pointIndex; ++i) { bool correctSymbol = false; foreach (var symbol in availableSymbolsInName) { if (fileName[i].Equals(symbol)) { correctSymbol = true; break; } } if (!correctSymbol) { return false; } } return true; }) .Select(pathToFile => { string shortPath = pathToFile.Substring(env.GetStorageFolderFullPath().Length).Replace('/', '>'); string fileName = shortPath.Substring(shortPath.LastIndexOf('>') + 1); string fileExtension = fileName.Substring(fileName.LastIndexOf('.')); string name = fileName.Substring(0, fileName.Length - fileExtension.Length); FileManagerObject fileManagerObject = new FileManagerObject { Name = name, ShortPath = shortPath, CanDelete = true }; foreach (var typeOfExtension in typesOfExtensions) { if (fileExtension.Equals(typeOfExtension.Key, StringComparison.OrdinalIgnoreCase)) { fileManagerObject.Type = typeOfExtension.Value; break; } } return fileManagerObject; }).OrderBy(o => o.Name)); }