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 EditUserData(CMSDatabase db, UserModel model, HttpContext context, out int statusCode) { if (!model.ID.HasValue || !CorrectLogin(model.Login) || (!string.IsNullOrEmpty(model.NewPassword) && !CorrectPassword(model.NewPassword)) || model.IdleTime < 10 || model.IdleTime > 10080 ) { statusCode = 422; return; } User editableUser = db.Users.FirstOrDefault(u => u.ID == model.ID.Value); if (editableUser == null) { statusCode = 404; return; } else if (editableUser != context.Items["User"] as User || !editableUser.Password.Equals(SecurityFunctions.GetPasswordHash(model.CurrentPassword))) { statusCode = 403; return; } else if (!editableUser.Login.Equals(model.Login, StringComparison.Ordinal) && db.Users.FirstOrDefault(u => u.Login.Equals(model.Login, StringComparison.Ordinal)) != null) { statusCode = 409; return; } editableUser.Login = model.Login; if (!string.IsNullOrEmpty(model.NewPassword)) { editableUser.Password = SecurityFunctions.GetPasswordHash(model.NewPassword); } editableUser.IdleTime = model.IdleTime; editableUser.Email = model.Email; db.SaveChanges(); statusCode = 200; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.UserDataEdited}" ); }
public IActionResult EditSettings(CMSDatabase db, SettingsModel model, HttpContext context) { ConfigurationHandler configurationHandler = context.RequestServices.GetRequiredService <ConfigurationHandler>(); configurationHandler.ChangeConfigFile(model); if (!string.IsNullOrEmpty(model.ProductBlockTemplate)) { IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>(); string pathToTemplate = env.GetProductBlockTemplateFullPath(); string oldTemplate = OtherFunctions.GetFileContent(pathToTemplate); if (!model.ProductBlockTemplate.Equals(oldTemplate, StringComparison.Ordinal)) { using (StreamWriter writer = new StreamWriter(pathToTemplate)) { writer.Write(model.ProductBlockTemplate); } string[] additions = { "@using Treynessen.Functions;", "@using Treynessen.Database.Entities;", "@addTagHelper Treynessen.TagHelpers.ImageTagHelper, StoreCMS" }; string cshtmlTemplate = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: model.ProductBlockTemplate, modelType: "ProductPage", env: env, skipChunkName: null, additions: additions ); using (StreamWriter writer = new StreamWriter(env.GetProductBlockCshtmlFullPath())) { writer.Write(cshtmlTemplate); } } } LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.SettingsEdited ); return(StatusCode(200)); }
public static void AddTemplate(CMSDatabase db, TemplateModel model, HttpContext context, out bool successfullyCompleted) { Template template = TemplatesManagementFunctions.TemplateModelToITemplate <Template>(model, context); if (template == null) { successfullyCompleted = false; return; } IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>(); if (template.Name.Equals("_ViewImports", System.StringComparison.OrdinalIgnoreCase)) { template.Name = "view_imports"; } template.TemplatePath = env.GetTemplatesFolderShortPath(); TemplatesManagementFunctions.SetUniqueITemplateName(db, template); template.TemplatePath += $"{template.Name}.cshtml"; string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: template.TemplateSource, modelType: "Page", env: env, skipChunkName: null ); TemplatesManagementFunctions.WriteCshtmlContentToFile( pathToTemplatesFolder: env.GetTemplatesFolderFullPath(), templateName: template.Name, chstmlContent: cshtmlContent ); db.Templates.Add(template); db.SaveChanges(); model.ID = template.ID; successfullyCompleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{template.Name} (ID-{template.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.TemplateAdded}" ); }
private static LinkedList <Chunk> GetChunks(CMSDatabase db, string source, string currentChunkName = null) { LinkedList <Chunk> chunks = new LinkedList <Chunk>(); int pointer = 0; while (pointer != -1) { pointer = GetNextChunk(pointer, source, out string chunkName); if (!string.IsNullOrEmpty(chunkName) && !chunkName.Equals(currentChunkName, StringComparison.Ordinal)) { Chunk chunk = db.Chunks.FirstOrDefaultAsync(tc => tc.Name.Equals(chunkName, StringComparison.Ordinal)).Result; if (chunk != null) { db.Entry(chunk).State = EntityState.Detached; chunks.AddLast(chunk); } } } return(chunks); }
public static void Main(string[] args) { IWebHost host = WebHost.CreateDefaultBuilder(args) .UseStartup <Startup>() .UseWebRoot("Storage") .Build(); using (var scope = host.Services.CreateScope()) { ConfigurationHandler config = scope.ServiceProvider.GetRequiredService <ConfigurationHandler>(); try { CultureInfo.CurrentCulture = new CultureInfo(config.GetConfigValue("LanguageSettings:CurrentLanguage")); } catch { } CMSDatabase db = scope.ServiceProvider.GetRequiredService <CMSDatabase>(); SetDeafaultUserType(db); SetDeafaultUser(db); } host.Run(); }
// Сравниваем данные в кукисах и хедерах с данными на сервере. public static User CheckCookies(CMSDatabase db, HttpContext context) { string userName = context.Request.Cookies["userName"]; if (string.IsNullOrEmpty(userName)) { return(null); } ConnectedUser connectedUser = db.ConnectedUsers.FirstOrDefault( cu => cu.UserName.Equals(userName, StringComparison.Ordinal) // loginKey - это случайно сгенерированный в методе SecurityFunctions.GetRandomKey ключ && cu.LoginKey.Equals(context.Request.Cookies["loginKey"], StringComparison.Ordinal) // Проверка ip-адреса && cu.IPAdress.Equals(context.Connection.RemoteIpAddress.ToString(), StringComparison.Ordinal) && cu.UserAgent.Equals(context.Request.Headers["User-Agent"], StringComparison.Ordinal) ); if (connectedUser == null) { return(null); } db.Entry(connectedUser).Reference(cu => cu.User).Load(); if ((DateTime.Now - connectedUser.LastActionTime).TotalMinutes > connectedUser.User.IdleTime) { db.ConnectedUsers.Remove(connectedUser); db.SaveChanges(); return(null); } connectedUser.LastActionTime = DateTime.Now; db.Update(connectedUser); db.SaveChanges(); db.Entry(connectedUser.User).Reference(u => u.UserType).Load(); return(connectedUser.User); }
public static void AddSynonymForString(CMSDatabase db, SynonymForStringModel model, HttpContext context, out bool successfullyCompleted) { if (!string.IsNullOrEmpty(model.String) && !string.IsNullOrEmpty(model.Synonym)) { SynonymForString match = db.SynonymsForStrings.AsNoTracking() .FirstOrDefault(s => (s.String.Equals(model.String, StringComparison.InvariantCultureIgnoreCase) && s.Synonym.Equals(model.Synonym, StringComparison.InvariantCultureIgnoreCase)) || (s.String.Equals(model.Synonym, StringComparison.InvariantCultureIgnoreCase) && s.Synonym.Equals(model.String, StringComparison.InvariantCultureIgnoreCase))); if (match != null) { successfullyCompleted = false; return; } SynonymForString synonymForString = new SynonymForString { String = model.String, Synonym = model.Synonym }; db.SynonymsForStrings.Add(synonymForString); try { db.SaveChanges(); } catch (DbUpdateException) { successfullyCompleted = false; return; } successfullyCompleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{synonymForString.String} -> {synonymForString.Synonym}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.SynonymForStringAdded}" ); } else { successfullyCompleted = false; } }
public static void AddRedirection(CMSDatabase db, RedirectionModel model, HttpContext context, out bool successfullyCompleted) { if (string.IsNullOrEmpty(model.RedirectionPath) || string.IsNullOrEmpty(model.RequestPath) || model.RequestPath.Equals(model.RedirectionPath, StringComparison.OrdinalIgnoreCase)) { successfullyCompleted = false; return; } Redirection match = db.Redirections.FirstOrDefault(r => r.RequestPathHash == OtherFunctions.GetHashFromString(model.RequestPath) && r.RequestPath.Equals(model.RequestPath, StringComparison.Ordinal) && r.RedirectionPath.Equals(model.RedirectionPath, StringComparison.Ordinal)); if (match != null) { successfullyCompleted = false; return; } model.RequestPath = GetCorrectUrlPath(model.RequestPath); model.RedirectionPath = GetCorrectUrlPath(model.RedirectionPath); if (model.RequestPath.Equals(model.RedirectionPath, StringComparison.Ordinal)) { successfullyCompleted = false; return; } Redirection redirection = new Redirection { RequestPath = model.RequestPath, RequestPathHash = OtherFunctions.GetHashFromString(model.RequestPath), RedirectionPath = model.RedirectionPath }; db.Redirections.Add(redirection); db.SaveChanges(); successfullyCompleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{redirection.RequestPath} -> {redirection.RedirectionPath}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.RedirectionAdded}" ); }
public static void AddPage(CMSDatabase db, PageModel model, HttpContext context, out bool successfullyCompleted) { Page page = PagesManagementFunctions.PageModelToPage(db, model, context); if (page == null) { successfullyCompleted = false; return; } db.Add(page); db.SaveChanges(); model.ID = page.ID; successfullyCompleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{page.PageName} (ID-{page.ID.ToString()}): " + (page is UsualPage ? (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.PageAdded : (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.CategoryAdded) ); }
public static void AddUser(CMSDatabase db, UserModel model, HttpContext context, out int statusCode) { if (!CorrectLogin(model.Login) || !CorrectPassword(model.NewPassword) || !model.UserTypeId.HasValue || db.UserTypes.FirstOrDefault(ut => ut.ID == model.UserTypeId.Value) == null) { statusCode = 422; return; } if (db.Users.AsNoTracking().FirstOrDefault(u => u.Login.Equals(model.Login, StringComparison.Ordinal)) != null) { statusCode = 409; return; } User user = new User { Login = model.Login, Password = SecurityFunctions.GetPasswordHash(model.NewPassword), IdleTime = 10, UserTypeID = model.UserTypeId.Value }; try { db.Users.Add(user); } catch (DbUpdateException) { statusCode = 409; return; } db.SaveChanges(); statusCode = 201; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{user.Login} (ID-{user.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.UserAdded}" ); }
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { CMSDatabase db = httpContext.RequestServices.GetRequiredService <CMSDatabase>(); RequestHandler requestHandler = new RequestHandler(db, httpContext.Request.Path); Page page = requestHandler.FindPage(); if (page != null) { httpContext.Items["RequestedPage"] = page; return(true); } string redirection = requestHandler.GetRedirection(); if (!string.IsNullOrEmpty(redirection)) { httpContext.Items["Redirection"] = redirection; return(true); } else { return(false); } }
public static void AddUserType(CMSDatabase db, UserTypeModel model, HttpContext context, out bool successfullyCompleted) { if (string.IsNullOrEmpty(model.Name) || !model.AccessLevel.HasValue || !Enum.IsDefined(typeof(AccessLevel), model.AccessLevel.Value)) { successfullyCompleted = false; return; } UserType userType = new UserType { Name = model.Name, AccessLevel = model.AccessLevel.Value }; db.UserTypes.Add(userType); db.SaveChanges(); successfullyCompleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{userType.Name} ({userType.AccessLevel.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.UserTypeAdded}" ); }
public static bool IsValidLoginFormData(CMSDatabase db, LoginFormModel data, HttpContext context, out User user) { if (string.IsNullOrEmpty(data.Login) || string.IsNullOrEmpty(data.Password)) { user = null; return(false); } user = db.Users.FirstOrDefault(u => u.Login.Equals(data.Login, StringComparison.Ordinal)); if (user == null) { return(false); } if (!user.Password.Equals(GetPasswordHash(data.Password), StringComparison.Ordinal)) { LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.FailedLoginAttempt}. IP: {context.Connection.RemoteIpAddress.ToString()}", user: user ); return(false); } return(true); }
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}" ); } }
public static void EditPage(CMSDatabase db, Model model, HttpContext context, out bool successfullyCompleted) { if (!model.itemID.HasValue || model.PageModel == null || !model.PageType.HasValue) { successfullyCompleted = false; return; } model.PageModel.PageType = model.PageType; bool isMainPage = false; model.PageModel.IsMainPage = false; Page editablePage = null; switch (model.PageModel.PageType) { case PageType.Usual: editablePage = db.UsualPages.AsNoTracking().FirstOrDefault(up => up.ID == model.itemID); if (editablePage == null) { successfullyCompleted = false; return; } model.PageModel.ID = editablePage.ID; isMainPage = editablePage.RequestPath.Equals("/", StringComparison.Ordinal); break; case PageType.Category: editablePage = db.CategoryPages.AsNoTracking().FirstOrDefault(cp => cp.ID == model.itemID); if (editablePage == null) { successfullyCompleted = false; return; } model.PageModel.ID = editablePage.ID; break; default: successfullyCompleted = false; return; } model.PageModel.PageType = model.PageModel.PageType.Value; Page editedPage = PagesManagementFunctions.PageModelToPage(db, model.PageModel, context); if (editedPage != null) { if (editedPage is UsualPage up) { if (isMainPage) { up.Alias = "index"; up.RequestPath = "/"; up.RequestPathHash = OtherFunctions.GetHashFromString(up.RequestPath); up.PreviousPage = null; } // Если родителем страницы является сама страница или зависимая страница, то возвращаем сообщение об ошибке if (up.PreviousPage != null && PagesManagementFunctions.GetDependentPageIDs(db, up).Contains(up.PreviousPage.ID)) { successfullyCompleted = false; return; } } else if (editedPage is CategoryPage cp) { cp.ProductsCount = (editablePage as CategoryPage).ProductsCount; cp.LastProductTemplateID = (editablePage as CategoryPage).LastProductTemplateID; } } else { successfullyCompleted = false; return; } db.Update(editedPage); // Обновляем все зависимые страницы, если изменилось имя страницы и/или url страницы if (!editablePage.PageName.Equals(editedPage.PageName, StringComparison.InvariantCulture) || !editablePage.RequestPath.Equals(editedPage.RequestPath, StringComparison.Ordinal)) { if (editedPage is UsualPage) { List <UsualPage> usualPages = db.UsualPages.Where(p => p.PreviousPageID == editedPage.ID).ToList(); List <CategoryPage> categoryPages = db.CategoryPages.Where(p => p.PreviousPageID == editedPage.ID).ToList(); foreach (var u_page in usualPages) { RefreshPageAndDependencies(db, u_page); } foreach (var c_page in categoryPages) { RefreshPageAndDependencies(db, c_page); } } if (editedPage is CategoryPage) { List <ProductPage> productPages = db.ProductPages.Where(p => p.PreviousPageID == editedPage.ID).ToList(); foreach (var p_page in productPages) { RefreshPageAndDependencies(db, p_page); } } } db.SaveChanges(); successfullyCompleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{editablePage.PageName} (ID-{editablePage.ID.ToString()}): " + (editablePage is UsualPage ? (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.PageEdited : (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.CategoryEdited) ); }
public ImageTagHelper(IHostingEnvironment env, CMSDatabase db) { this.db = db; this.env = env; }
public static void DeletePage(CMSDatabase db, PageType?pageType, int?itemID, HttpContext context, out bool successfullyDeleted) { if (!pageType.HasValue || !itemID.HasValue) { successfullyDeleted = false; return; } Page page = null; switch (pageType) { case PageType.Usual: page = db.UsualPages.FirstOrDefault(p => p.ID == itemID); break; case PageType.Category: page = db.CategoryPages.FirstOrDefault(p => p.ID == itemID); break; default: successfullyDeleted = false; return; } if (page == null) { successfullyDeleted = false; return; } if (page is UsualPage up) { // Получаем все зависимые страницы List <UsualPage> usualPages = db.UsualPages.Where(p => p.PreviousPageID == up.ID).ToList(); List <CategoryPage> categoryPages = db.CategoryPages.Where(p => p.PreviousPageID == up.ID).ToList(); db.UsualPages.Remove(up); db.SaveChanges(); // Обновляем полученные зависимые страницы foreach (var u_page in usualPages) { u_page.PreviousPageID = up.PreviousPageID; RefreshPageAndDependencies(db, u_page); } foreach (var c_page in categoryPages) { c_page.PreviousPageID = up.PreviousPageID; RefreshPageAndDependencies(db, c_page); } } else if (page is CategoryPage cp) { IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>(); cp.ProductPages = db.ProductPages.Where(pp => pp.PreviousPageID == cp.ID).ToList(); foreach (var p in cp.ProductPages) { string[] images = ImagesManagementFunctions.GetProductImageUrls(p, env); for (int i = 0; i < images.Length; ++i) { Image image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(images[i]) && img.ShortPath.Equals(images[i], StringComparison.Ordinal)); if (image != null) { db.Images.Remove(image); } } string pathToImages = $"{env.GetProductsImagesFolderFullPath()}{p.ID}/"; if (Directory.Exists(pathToImages)) { Directory.Delete(pathToImages, true); } } db.Remove(page); } db.SaveChanges(); successfullyDeleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{page.PageName} (ID-{page.ID.ToString()}): " + (page is UsualPage ? (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.PageDeleted : (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.CategoryDeleted) ); }
public static void EditTemplate(CMSDatabase db, int?itemID, TemplateModel model, HttpContext context, out bool successfullyCompleted) { if (!itemID.HasValue || model == null || string.IsNullOrEmpty(model.Name)) { successfullyCompleted = false; return; } Template editableTemplate = db.Templates.AsNoTracking().FirstOrDefault(t => t.ID == itemID); if (editableTemplate == null) { successfullyCompleted = false; return; } Template editedTemplate = TemplatesManagementFunctions.TemplateModelToITemplate <Template>(model, context); if (editedTemplate == null) { successfullyCompleted = false; return; } if (editedTemplate.Name.Equals("_ViewImports", StringComparison.OrdinalIgnoreCase)) { editedTemplate.Name = "view_imports"; } IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>(); editedTemplate.ID = itemID.Value; editedTemplate.TemplatePath = env.GetTemplatesFolderShortPath(); TemplatesManagementFunctions.SetUniqueITemplateName(db, editedTemplate); editedTemplate.TemplatePath += $"{editedTemplate.Name}.cshtml"; db.Templates.Update(editedTemplate); db.SaveChanges(); successfullyCompleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{editableTemplate.Name} (ID-{editableTemplate.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.TemplateEdited}" ); // Изменяем cshtml файл, если изменилось имя шаблона и/или код шаблона bool changedName = !editedTemplate.Name.Equals(editableTemplate.Name, StringComparison.Ordinal); bool changedTemplateSource = !editedTemplate.TemplateSource.Equals(editableTemplate.TemplateSource, StringComparison.InvariantCulture); if (changedName && changedTemplateSource) { string pathToOldFileName = $"{env.GetTemplatesFolderFullPath()}{editableTemplate.Name}.cshtml"; if (File.Exists(pathToOldFileName)) { File.Delete(pathToOldFileName); } string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: editedTemplate.TemplateSource, modelType: "Page", env: env, skipChunkName: null ); TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetTemplatesFolderFullPath(), editedTemplate.Name, cshtmlContent); } else if (changedName) { string pathToOldFileName = $"{env.GetTemplatesFolderFullPath()}{editableTemplate.Name}.cshtml"; if (File.Exists(pathToOldFileName)) { File.Move(pathToOldFileName, $"{env.GetTemplatesFolderFullPath()}{editedTemplate.Name}.cshtml"); } else { string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: editedTemplate.TemplateSource, modelType: "Page", env: env, skipChunkName: null ); TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetTemplatesFolderFullPath(), editedTemplate.Name, cshtmlContent); } } else if (changedTemplateSource) { string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: editedTemplate.TemplateSource, modelType: "Page", env: env, skipChunkName: null ); TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetTemplatesFolderFullPath(), editedTemplate.Name, cshtmlContent); } }
public PageController(CMSDatabase db) { this.db = db; }
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); }
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 AddChunk(CMSDatabase db, TemplateModel model, HttpContext context, out bool successfullyCompleted) { Chunk chunk = TemplatesManagementFunctions.TemplateModelToITemplate <Chunk>(model, context); if (chunk == null) { successfullyCompleted = false; return; } IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>(); if (chunk.Name.Equals("_ViewImports", System.StringComparison.OrdinalIgnoreCase)) { chunk.Name = "view_imports"; } chunk.TemplatePath = env.GetChunksFolderShortPath(); TemplatesManagementFunctions.SetUniqueITemplateName(db, chunk); chunk.TemplatePath += $"{chunk.Name}.cshtml"; string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: chunk.TemplateSource, modelType: "Page", env: env, skipChunkName: chunk.Name ); TemplatesManagementFunctions.WriteCshtmlContentToFile( pathToTemplatesFolder: env.GetChunksFolderFullPath(), templateName: chunk.Name, chstmlContent: cshtmlContent ); db.Chunks.Add(chunk); db.SaveChanges(); model.ID = chunk.ID; successfullyCompleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{chunk.Name} (ID-{chunk.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ChunkAdded}" ); // Получаем список шаблонов и чанков, которые содержат данный чанк var templates = db.Templates.AsNoTracking().Where(t => t.TemplateSource.Contains($"[#{chunk.Name}]")).ToList(); var chunks = db.Chunks.AsNoTracking().Where(tc => tc.ID != chunk.ID && (tc.TemplateSource.Contains($"[#{chunk.Name}]"))).ToList(); // Делаем рендер, содержащих данный чанк, шаблонов и чанков var renderTask = Task.Run(() => { foreach (var t in templates) { string _cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: t.TemplateSource, modelType: "Page", env: env, skipChunkName: null ); TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetTemplatesFolderFullPath(), t.Name, _cshtmlContent); } }); foreach (var c in chunks) { string _cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: c.TemplateSource, modelType: "Page", env: env, skipChunkName: c.Name ); TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetChunksFolderFullPath(), c.Name, _cshtmlContent); } // Если шаблон блока товара содержит текущий чанк, то делаем его перерендер string productBlockFileContent = OtherFunctions.GetFileContent(env.GetProductBlockTemplateFullPath()); if (productBlockFileContent.Contains($"[#{chunk.Name}]")) { string[] additions = { "@using Treynessen.Functions;", "@using Treynessen.Database.Entities;", "@addTagHelper Treynessen.TagHelpers.ImageTagHelper, StoreCMS" }; string productBlockCshtmlTemplate = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: productBlockFileContent, modelType: "ProductPage", env: env, skipChunkName: null, additions: additions ); using (StreamWriter writer = new StreamWriter(env.GetProductBlockCshtmlFullPath())) { writer.Write(productBlockCshtmlTemplate); } } renderTask.Wait(); }
public static void SetUniqueAliasName(CMSDatabase db, Page page) { if (page == null) { throw new ArgumentException(); } // Страницы с редиректами не входят в проверку, ибо в этом нет никакого смысла // По очередности при обработке запроса редиректы стоят после обработки обычных // запросов, поэтому при определении страницы url редиректа == url страницы, обработчик // отправит нас на страницу, а редирект будет перекрыт var usualPageUrls = db.UsualPages.AsNoTracking() .Where(up => up.GetType() == page.GetType() ? up.ID != page.ID : true) .Select(up => up.RequestPath).ToList(); var categoryPageUrls = db.CategoryPages.AsNoTracking() .Where(cp => cp.GetType() == page.GetType() ? cp.ID != page.ID : true) .Select(cp => cp.RequestPath).ToList(); var productPageUrls = db.ProductPages.AsNoTracking() .Where(pp => pp.GetType() == page.GetType() ? pp.ID != page.ID : true) .Select(pp => pp.RequestPath).ToList(); int index = 1; bool has = false; bool putUnderscore = false; string currentPath = page.RequestPath; do { CancellationTokenSource usualPageTokenSource = new CancellationTokenSource(); CancellationTokenSource categoryPageTokenSource = new CancellationTokenSource(); CancellationTokenSource productPageTokenSource = new CancellationTokenSource(); has = false; string checkPath = $"{currentPath}{(index == 1 && !putUnderscore ? string.Empty : index.ToString())}"; var hasInUsualPagesTask = ContainedInCollection(usualPageUrls, checkPath, usualPageTokenSource.Token, categoryPageTokenSource, productPageTokenSource); var hasInCategoryPagesTask = ContainedInCollection(categoryPageUrls, checkPath, categoryPageTokenSource.Token, usualPageTokenSource, productPageTokenSource); var hasInProductPagesTask = ContainedInCollection(productPageUrls, checkPath, productPageTokenSource.Token, usualPageTokenSource, categoryPageTokenSource); if (hasInUsualPagesTask.Result || hasInCategoryPagesTask.Result || hasInProductPagesTask.Result) { has = true; } if (has && !putUnderscore && index == 1) { int oldAliasLength = page.Alias.Length; page.Alias = OtherFunctions.GetNameWithUnderscore(page.Alias); page.RequestPath = page.RequestPath.Substring(0, page.RequestPath.Length - oldAliasLength) + page.Alias; currentPath = page.RequestPath; putUnderscore = true; } if (!has && !(index == 1 && !putUnderscore)) { page.Alias += index.ToString(); page.RequestPath = checkPath; } if (index == int.MaxValue) { page.Alias += index.ToString(); currentPath = checkPath; index = 0; } ++index; usualPageTokenSource.Dispose(); categoryPageTokenSource.Dispose(); productPageTokenSource.Dispose(); } while (has); }
// ЭТОТ МЕТОД НЕ СОХРАНЯЕТ ИЗМЕНЕНИЯ, ТОЛЬКО ВНОСИТ ИХ // После изменения или удаления страницы-родителя, необходимо изменить все страницы, наследующиеся от // этой родительской страницы. public static void RefreshPageAndDependencies(CMSDatabase db, Page page) { switch (page) { case UsualPage up: db.Entry(up).Reference(p => p.PreviousPage).LoadAsync().Wait(); if (up.PreviousPage == null && up.Alias.Equals("index", StringComparison.Ordinal)) { up.Alias = "ind"; } if (up.PreviousPage == null || up.PreviousPage.RequestPath.Equals("/", StringComparison.Ordinal)) { up.RequestPath = $"/{up.Alias}"; } else { up.RequestPath = $"{up.PreviousPage.RequestPath}/{up.Alias}"; } up.BreadcrumbsHtml = PagesManagementFunctions.GetBreadcrumbsHTML(up); break; case CategoryPage cp: db.Entry(cp).Reference(p => p.PreviousPage).LoadAsync().Wait(); if (cp.PreviousPage == null && cp.Alias.Equals("index", StringComparison.Ordinal)) { cp.Alias = "ind"; } if (cp.PreviousPage == null || cp.PreviousPage.RequestPath.Equals("/", StringComparison.Ordinal)) { cp.RequestPath = $"/{cp.Alias}"; } else { cp.RequestPath = $"{cp.PreviousPage.RequestPath}/{cp.Alias}"; } cp.BreadcrumbsHtml = PagesManagementFunctions.GetBreadcrumbsHTML(cp); break; case ProductPage pp: db.Entry(pp).Reference(p => p.PreviousPage).LoadAsync().Wait(); pp.RequestPath = $"{pp.PreviousPage.RequestPath}/{pp.Alias}"; pp.BreadcrumbsHtml = PagesManagementFunctions.GetBreadcrumbsHTML(pp); break; } PagesManagementFunctions.SetUniqueAliasName(db, page); page.RequestPathHash = OtherFunctions.GetHashFromString(page.RequestPath); switch (page) { case UsualPage up: List <UsualPage> usualPages = db.UsualPages.Where(p => p.PreviousPageID == up.ID).ToList(); List <CategoryPage> categoryPages = db.CategoryPages.Where(p => p.PreviousPageID == up.ID).ToList(); foreach (var u_page in usualPages) { RefreshPageAndDependencies(db, u_page); } foreach (var c_page in categoryPages) { RefreshPageAndDependencies(db, c_page); } break; case CategoryPage cp: List <ProductPage> productPages = db.ProductPages.Where(p => p.PreviousPageID == cp.ID).ToList(); foreach (var p_page in productPages) { RefreshPageAndDependencies(db, p_page); } break; } }
public static void EditChunk(CMSDatabase db, int?itemID, TemplateModel model, HttpContext context, out bool successfullyCompleted) { if (!itemID.HasValue || model == null) { successfullyCompleted = false; return; } Chunk editableChunk = db.Chunks.AsNoTracking().FirstOrDefault(t => t.ID == itemID); if (editableChunk == null) { successfullyCompleted = false; return; } Chunk editedChunk = TemplatesManagementFunctions.TemplateModelToITemplate <Chunk>(model, context); if (editedChunk == null) { successfullyCompleted = false; return; } if (editedChunk.Name.Equals("_ViewImports", StringComparison.OrdinalIgnoreCase)) { editedChunk.Name = "view_imports"; } IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>(); editedChunk.ID = itemID.Value; editedChunk.TemplatePath = env.GetChunksFolderShortPath(); TemplatesManagementFunctions.SetUniqueITemplateName(db, editedChunk); editedChunk.TemplatePath += $"{editedChunk.Name}.cshtml"; db.Chunks.Update(editedChunk); db.SaveChanges(); successfullyCompleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{editableChunk.Name} (ID-{editableChunk.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ChunkEdited}" ); // Изменяем cshtml файл, если изменилось имя шаблона и/или код шаблона bool changedName = !editedChunk.Name.Equals(editableChunk.Name, StringComparison.Ordinal); bool changedTemplateSource = !editedChunk.TemplateSource.Equals(editableChunk.TemplateSource, StringComparison.Ordinal); if (changedName && changedTemplateSource) { string pathToOldFileName = $"{env.GetChunksFolderFullPath()}{editableChunk.Name}.cshtml"; if (File.Exists(pathToOldFileName)) { File.Delete(pathToOldFileName); } string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: editedChunk.TemplateSource, modelType: "Page", env: env, skipChunkName: editedChunk.Name ); TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetChunksFolderFullPath(), editedChunk.Name, cshtmlContent); } else if (changedName) { string pathToOldFileName = $"{env.GetChunksFolderFullPath()}{editableChunk.Name}.cshtml"; if (File.Exists(pathToOldFileName)) { File.Move(pathToOldFileName, $"{env.GetChunksFolderFullPath()}{editedChunk.Name}.cshtml"); } else { string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: editedChunk.TemplateSource, modelType: "Page", env: env, skipChunkName: editedChunk.Name ); TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetChunksFolderFullPath(), editedChunk.Name, cshtmlContent); } } else if (changedTemplateSource) { string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: editedChunk.TemplateSource, modelType: "Page", env: env, skipChunkName: editedChunk.Name ); TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetChunksFolderFullPath(), editedChunk.Name, cshtmlContent); } // Если изменилось название чанка, то получаем список шаблонов и чанков, которые использовали или теперь используют данный чанк // и делаем их перерендер if (changedName) { var templates = db.Templates.AsNoTracking() .Where(t => t.TemplateSource.Contains($"[#{editableChunk.Name}]") || t.TemplateSource.Contains($"[#{editedChunk.Name}]")) .ToList(); var chunks = db.Chunks.AsNoTracking() .Where(tc => tc.ID != itemID.Value && (tc.TemplateSource.Contains($"[#{editableChunk.Name}]") || tc.TemplateSource.Contains($"[#{editedChunk.Name}]"))) .ToList(); var renderTask = Task.Run(() => { foreach (var t in templates) { string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: t.TemplateSource, modelType: "Page", env: env, skipChunkName: null ); TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetTemplatesFolderFullPath(), t.Name, cshtmlContent); } }); foreach (var c in chunks) { string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: c.TemplateSource, modelType: "Page", env: env, skipChunkName: c.Name ); TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetChunksFolderFullPath(), c.Name, cshtmlContent); } string productBlockFileContent = OtherFunctions.GetFileContent(env.GetProductBlockTemplateFullPath()); if (changedName && productBlockFileContent.Contains($"[#{editableChunk.Name}]")) { string[] additions = { "@using Treynessen.Functions;", "@using Treynessen.Database.Entities;", "@addTagHelper Treynessen.TagHelpers.ImageTagHelper, StoreCMS" }; string productBlockCshtmlTemplate = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: productBlockFileContent, modelType: "ProductPage", env: env, skipChunkName: null, additions: additions ); using (StreamWriter writer = new StreamWriter(env.GetProductBlockCshtmlFullPath())) { writer.Write(productBlockCshtmlTemplate); } } renderTask.Wait(); } }
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 EditProduct(CMSDatabase db, PageModel model, int?productID, HttpContext context, out bool successfullyCompleted) { if (model == null || !productID.HasValue) { successfullyCompleted = false; return; } model.PageType = PageType.Product; ProductPage editableProduct = db.ProductPages.AsNoTracking().FirstOrDefault(pp => pp.ID == productID.Value); if (editableProduct == null) { successfullyCompleted = false; return; } model.ID = editableProduct.ID; model.PreviousPageID = editableProduct.PreviousPageID; ProductPage editedProduct = PagesManagementFunctions.PageModelToPage(db, model, context) as ProductPage; if (editedProduct == null) { successfullyCompleted = false; return; } editedProduct.PreviousPage.LastProductTemplate = editedProduct.Template; db.ProductPages.Update(editedProduct); db.SaveChanges(); // Изменяем имена изображений продукта, если изменился псевдоним страницы if (!editableProduct.Alias.Equals(editedProduct.Alias, StringComparison.Ordinal)) { IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>(); string pathToImages = $"{env.GetProductsImagesFolderFullPath()}{editedProduct.ID}/"; if (Directory.Exists(pathToImages)) { string oldName = editableProduct.Alias; string newName = editedProduct.Alias; Regex imageChecker = new Regex($"{oldName}(_\\d+)?.jpg$"); string[] oldImagesNames = Directory.GetFiles(pathToImages, $"*{oldName}*.jpg"); string[] imagePaths = (from img in oldImagesNames where imageChecker.IsMatch(img) select img).ToArray(); // Можно было бы заменить разом имена всем изображениям через перебор в цикле, но // проблема в том, что путь до папки с изображениями может содержать старое название // изображения. В итоге замена имени через File.Move(старый_путь, старый_путь.Replace(oldName, newName)) // может привести к переносу изображений в другую директорию. LinkedList <KeyValuePair <string, string> > renameErrors = new LinkedList <KeyValuePair <string, string> >(); for (int i = 0; i < imagePaths.Length; ++i) { string oldImageName = imagePaths[i].Substring(pathToImages.Length, imagePaths[i].Length - pathToImages.Length - 4); string newImageName = oldImageName.Replace(oldName, newName); try { ImagesManagementFunctions.RenameImageAndDependencies( db: db, env: env, pathToImages: pathToImages, oldImageName: oldImageName, newImageName: newImageName, imageExtension: ".jpg", saveChangesInDB: false ); } catch (IOException) { // Добавляем все ошибки переименования в список для второй попытки. Например, старое название было // "Название" и мы переименовали страницу на "Название_2", но у товара было несколько картинок, // соответственно при ренейминге будет попытка присвоить первой картинке название Название_2, что приведет // к ошибке, т.к. картинка с таким названием уже существует. Поэтому после первого прохода сделаем второй, // что поможет избежать этих ошибок переименования renameErrors.AddLast(new KeyValuePair <string, string>(oldImageName, newImageName)); } } if (renameErrors.Count > 0) { foreach (var e in renameErrors) { ImagesManagementFunctions.RenameImageAndDependencies( db: db, env: env, pathToImages: pathToImages, oldImageName: e.Key, newImageName: e.Value, imageExtension: ".jpg", saveChangesInDB: false ); } } db.SaveChanges(); } } successfullyCompleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{editableProduct.PageName} (ID-{editableProduct.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ProductEdited}" ); }
public static void DeleteChunk(CMSDatabase db, int?itemID, HttpContext context, out bool successfullyDeleted) { if (!itemID.HasValue) { successfullyDeleted = false; return; } Chunk chunk = db.Chunks.FirstOrDefault(t => t.ID == itemID); if (chunk == null) { successfullyDeleted = false; return; } IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>(); string pathToChunkFile = $"{env.GetChunksFolderFullPath()}{chunk.Name}.cshtml"; if (File.Exists(pathToChunkFile)) { File.Delete(pathToChunkFile); } db.Chunks.Remove(chunk); db.SaveChanges(); successfullyDeleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{chunk.Name} (ID-{chunk.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ChunkDeleted}" ); // Получаем список чанков и шаблонов, использующих данный чанк и делаем перерендер var templates = db.Templates.AsNoTracking().Where(t => t.TemplateSource.Contains($"[#{chunk.Name}]")).ToList(); var chunks = db.Chunks.AsNoTracking().Where(tc => tc.TemplateSource.Contains($"[#{chunk.Name}]")).ToList(); var renderTask = Task.Run(() => { foreach (var t in templates) { string _cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: t.TemplateSource, modelType: "Page", env: env, skipChunkName: null ); TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetTemplatesFolderFullPath(), t.Name, _cshtmlContent); } }); foreach (var c in chunks) { string _cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: c.TemplateSource, modelType: "Page", env: env, skipChunkName: c.Name ); TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetChunksFolderFullPath(), c.Name, _cshtmlContent); } string productBlockFileContent = OtherFunctions.GetFileContent(env.GetProductBlockTemplateFullPath()); if (productBlockFileContent.Contains($"[#{chunk.Name}]")) { string[] additions = { "@using Treynessen.Functions;", "@using Treynessen.Database.Entities;", "@addTagHelper Treynessen.TagHelpers.ImageTagHelper, StoreCMS" }; string productBlockCshtmlTemplate = TemplatesManagementFunctions.SourceToCSHTML( db: db, source: productBlockFileContent, modelType: "ProductPage", env: env, skipChunkName: null, additions: additions ); using (StreamWriter writer = new StreamWriter(env.GetProductBlockCshtmlFullPath())) { writer.Write(productBlockCshtmlTemplate); } } renderTask.Wait(); }
private static void CreateInsertionReplacementsCollection(CMSDatabase db, string source, string skipChunkName, IHostingEnvironment env) { if (insertionReplacements.Count > 0) { insertionReplacements.Clear(); } foreach (var c in GetChunks(db, source, skipChunkName)) { // Вызывать в catch функцию, записывающую информацию об ошибке в лог-файл insertionReplacements.AddLast(new InsertionReplacement { Insertion = $"[#{c.Name}]", Replacement = "@{ try { @await Html.PartialAsync(\"" + $"{c.TemplatePath}" + "\", Model) } catch { } }" }); } Regex parser_1 = new Regex(@"\[Product:Images{skip: (?<Type1>\d+)}{left_side: (?<Type2>.*)}{right_side: (?<Type3>.*)}\]"); foreach (var m in parser_1.Matches(source) as IEnumerable <Match> ) { int skip = Convert.ToInt32(m.Groups[1].Value); string leftSubvalue = m.Groups[2].Value.Replace("@", "@@"); string rightSubvalue = m.Groups[3].Value.Replace("@", "@@"); string result = "@{ var env = Context.RequestServices.GetService(typeof(Microsoft.AspNetCore.Hosting.IHostingEnvironment)) as Microsoft.AspNetCore.Hosting.IHostingEnvironment; " + "foreach (var imgUrl in ImagesManagementFunctions.GetProductImageUrls(Model as ProductPage, env, " + $"{skip}))" + " { " + $"<text>{leftSubvalue}@(imgUrl){rightSubvalue}</text>" + " } }"; insertionReplacements.AddLast(new InsertionReplacement { Insertion = m.Value.Replace("@", "@@"), Replacement = result }); } insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Page:Title]", Replacement = "@(Model != null ? Html.Raw(Model.Title) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Page:Name]", Replacement = "@(Model != null ? Html.Raw(Model.PageName) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Page:Url]", Replacement = "@(Model != null ? Html.Raw(Model.RequestPath) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Page:Breadcrumbs]", Replacement = "@(Model != null ? Html.Raw(Model.BreadcrumbsHtml) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Page:Content]", Replacement = "@(Model != null ? Html.Raw(Model.Content) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Page:Description]", Replacement = "@(Model != null ? Html.Raw(Model.PageDescription) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Page:Keywords]", Replacement = "@(Model != null ? Html.Raw(Model.PageKeywords) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Page:RobotsIndex]", Replacement = "@(Model != null ? (Model.IsIndex ? Html.Raw(\"index\") : Html.Raw(\"noindex\")) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Page:RobotsFollow]", Replacement = "@(Model != null ? (Model.IsFollow ? Html.Raw(\"follow\") : Html.Raw(\"nofollow\")) : Html.Raw(string.Empty))" }); // Вызывать в catch функцию, записывающую информацию об ошибке в лог-файл insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[ProductList]", Replacement = "@{ if (products != null) { foreach (var p in products) { try { @await Html.PartialAsync(@\"" + $"{env.GetProductBlockCshtmlShortPath()}" + "\", p); } catch { } } } }" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[PageButtons]", Replacement = "@{ if (products != null) { " + "<page-buttons class=\"@Context.Items[\"PaginationStyleName\"]\" " + "current-path=\"@Context.Request.Path\" " + "current-page=\"@(Context.Items[\"CurrentPage\"] as int?)\" " + "pages-count=\"@(Context.Items[\"PagesCount\"] as int?)\"" + "></page-buttons>" + " } }" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Product:Name]", Replacement = "@(Model is ProductPage ? Html.Raw((Model as ProductPage).PageName) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Product:ShortDescription]", Replacement = "@(Model is ProductPage ? Html.Raw((Model as ProductPage).ShortDescription) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Product:Price]", Replacement = "@(Model is ProductPage ? Html.Raw((Model as ProductPage).Price) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Product:OldPrice]", Replacement = "@(Model is ProductPage ? Html.Raw((Model as ProductPage).OldPrice) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Product:CurrentPrice]", Replacement = "@(Model is ProductPage && (Model as ProductPage).OldPrice != 0 ? Html.Raw(\"<span>\" + (Model as ProductPage).Price + \"</span><span>\" + (Model as ProductPage).OldPrice + \"</span>\") : Html.Raw(\"<span>\" + (Model as ProductPage).Price + \"</span>\"))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Product:Price-Formatted]", Replacement = "@(Model is ProductPage ? Html.Raw(OtherFunctions.PriceFormatting((Model as ProductPage).Price)) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Product:OldPrice-Formatted]", Replacement = "@(Model is ProductPage ? Html.Raw(OtherFunctions.PriceFormatting((Model as ProductPage).OldPrice)) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Product:CurrentPrice-Formatted]", Replacement = "@(Model is ProductPage && (Model as ProductPage).OldPrice != 0 ? Html.Raw(\"<span>\" + OtherFunctions.PriceFormatting((Model as ProductPage).Price) + \"</span><span>\" + OtherFunctions.PriceFormatting((Model as ProductPage).OldPrice) + \"</span>\") : Html.Raw(\"<span>\" + OtherFunctions.PriceFormatting((Model as ProductPage).Price) + \"</span>\"))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Product:Barcode]", Replacement = "@(Model is ProductPage ? Html.Raw((Model as ProductPage).Barcode) : Html.Raw(string.Empty))" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[Product:MainImageUrl]", Replacement = $"@(Model is ProductPage ? \"{env.GetProductsImagesFolderSrc()}\" + Model.ID.ToString() + \"/\" + Model.Alias + \".jpg\" : string.Empty)" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[HOUR]", Replacement = "@(DateTime.Now.Hour)" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[MINUTE]", Replacement = "@(DateTime.Now.Minute)" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[SECOND]", Replacement = "@(DateTime.Now.Second)" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[DAY]", Replacement = "@(DateTime.Now.Day)" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[MONTH]", Replacement = "@(DateTime.Now.Month)" }); insertionReplacements.AddLast(new InsertionReplacement { Insertion = "[YEAR]", Replacement = "@(DateTime.Now.Year)" }); }