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 static T TemplateModelToITemplate <T>(TemplateModel model, HttpContext context) where T : class, ITemplate, new() { if (model == null) { return(null); } T template = new T(); template.Name = OtherFunctions.GetCorrectName(model.Name, context); if (string.IsNullOrEmpty(template.Name)) { return(null); } template.TemplatePath = model.TemplatePath; template.TemplateSource = model.TemplateSource == null ? string.Empty : model.TemplateSource; return(template); }
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 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 Page PageModelToPage(CMSDatabase db, PageModel model, HttpContext context) { if (model == null) { return(null); } if (!model.PageType.HasValue) { return(null); } if (string.IsNullOrEmpty(model.Title) || string.IsNullOrEmpty(model.PageName)) { return(null); } Page page = null; switch (model.PageType.Value) { case PageType.Usual: UsualPage usualPage = new UsualPage(); page = usualPage; // Главной страницей может быть только та страница, у которой стоит галка isMainPage на форме, // тип которой == PageType.Usual и которая не имеет страницы-родителя. // Так же в БД не должно быть страницы, Url которой == "/" if (model.IsMainPage && !model.PreviousPageID.HasValue && !HasMainPage(db)) { model.Alias = "index"; } // Если потенциальная главная страница не прошла какое-нибудь из условий, описанных выше, то // возвращаем пользователю сообщение об ошибке else if (model.IsMainPage) { return(null); } if (model.PreviousPageID.HasValue) { usualPage.PreviousPage = db.UsualPages.FirstOrDefault(up => up.ID == model.PreviousPageID.Value); if (usualPage.PreviousPage == null) { usualPage.PreviousPageID = null; } } if (usualPage.PreviousPage == null || usualPage.PreviousPage.RequestPath.Equals("/", StringComparison.Ordinal)) { usualPage.RequestPath = "/"; } else { usualPage.RequestPath = $"{usualPage.PreviousPage.RequestPath}/"; } break; case PageType.Category: // Т.к. категория не может быть главной страницей if (model.IsMainPage) { return(null); } CategoryPage categoryPage = new CategoryPage(); page = categoryPage; if (model.PreviousPageID.HasValue) { categoryPage.PreviousPage = db.UsualPages.FirstOrDefault(up => up.ID == model.PreviousPageID.Value); if (categoryPage.PreviousPage == null) { categoryPage.PreviousPageID = null; } } if (categoryPage.PreviousPage == null || categoryPage.PreviousPage.RequestPath.Equals("/", StringComparison.Ordinal)) { categoryPage.RequestPath = "/"; } else { categoryPage.RequestPath = $"{categoryPage.PreviousPage.RequestPath}/"; } break; case PageType.Product: // Т.к. продукт не может быть главной страницей if (model.IsMainPage) { return(null); } // Продукт всегда должен иметь страницу-родителя в виде категории if (!model.PreviousPageID.HasValue) { return(null); } ProductPage productPage = new ProductPage(); productPage.PreviousPage = db.CategoryPages.FirstOrDefault(cp => cp.ID == model.PreviousPageID); // ← if (productPage.PreviousPage == null) { return(null); } page = productPage; productPage.Price = model.Price; productPage.OldPrice = model.OldPrice; productPage.Barcode = model.Barcode; productPage.ShortDescription = model.ShortDescription; productPage.SpecialProduct = model.SpecialProduct; productPage.RequestPath = $"{productPage.PreviousPage.RequestPath}/"; productPage.LastUpdate = DateTime.Now; break; default: return(null); } page.Title = model.Title; page.PageName = model.PageName; // Если псевдоним страницы не указан, то переводим в транслит имя страницы // Если же псевдоним указан, то просто проверяем его на корректность if (string.IsNullOrEmpty(model.Alias)) { page.Alias = OtherFunctions.GetCorrectName(model.PageName, context); } else { page.Alias = OtherFunctions.GetCorrectName(model.Alias, context); } // Если псевдоним содержал только некорректные символы (то есть после проверок он равен null), // тогда возвращаем пользователю сообщение об ошибке if (string.IsNullOrEmpty(page.Alias)) { return(null); } if (page.RequestPath.Equals("/") && page.Alias.Equals("index", StringComparison.Ordinal) && !model.IsMainPage) { page.Alias = "ind"; } if (model.ID.HasValue) { page.ID = model.ID.Value; } if (!model.IsMainPage) { page.RequestPath += page.Alias; SetUniqueAliasName(db, page); } // Проверка на то, не присвоен ли запрещенный url текущей странице IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>(); for (LinkedListNode <string> it = env.GetForbiddenUrls().First; it != null; it = it.Next) { if (page.RequestPath.Equals(it.Value, StringComparison.OrdinalIgnoreCase)) { page.Alias += "_page"; page.RequestPath += "_page"; SetUniqueAliasName(db, page); it = env.GetForbiddenUrls().First; } } page.RequestPathHash = OtherFunctions.GetHashFromString(page.RequestPath); page.BreadcrumbsHtml = GetBreadcrumbsHTML(page); page.Content = model.Content; if (model.TemplateId.HasValue) { page.Template = db.Templates.FirstOrDefault(t => t.ID == model.TemplateId); } page.Published = model.Published; page.PageDescription = model.PageDescription; page.PageKeywords = model.PageKeywords; page.IsIndex = model.IsIndex; page.IsFollow = model.IsFollow; // Вставляем тег <p>, если стоит галка if (page is ProductPage pp && model.AddParagraphTag) { pp.Content = GetContentWithParagraphTag(pp.Content); pp.ShortDescription = GetContentWithParagraphTag(pp.ShortDescription); } return(page); }