Beispiel #1
0
 public RequestHandler(CMSDatabase db, string requestString)
 {
     if (requestString.Length > 1 && requestString[requestString.Length - 1].Equals('/'))
     {
         requestString = requestString.Substring(0, requestString.Length - 1);
     }
     this.requestString = requestString.ToLower();
     requestStringHash  = OtherFunctions.GetHashFromString(requestString);
     this.db            = db;
 }
Beispiel #2
0
        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();
            }
        }
Beispiel #4
0
        public static void EditRedirection(CMSDatabase db, int?itemID, RedirectionModel model, HttpContext context, out bool successfullyCompleted)
        {
            if (string.IsNullOrEmpty(model.RedirectionPath) || string.IsNullOrEmpty(model.RequestPath) || !itemID.HasValue ||
                model.RequestPath.Equals(model.RedirectionPath, StringComparison.OrdinalIgnoreCase))
            {
                successfullyCompleted = false;
                return;
            }
            Redirection redirection = db.Redirections.FirstOrDefault(r => r.ID == itemID.Value);

            if (redirection == null)
            {
                successfullyCompleted = false;
                return;
            }
            string oldRequestPath     = redirection.RequestPath;
            string oldRedirectionPath = redirection.RedirectionPath;

            model.RequestPath     = GetCorrectUrlPath(model.RequestPath);
            model.RedirectionPath = GetCorrectUrlPath(model.RedirectionPath);
            if (model.RequestPath.Equals(model.RedirectionPath, StringComparison.Ordinal))
            {
                successfullyCompleted = false;
                return;
            }
            Redirection match = db.Redirections.FirstOrDefault(r => r.ID != itemID.Value && 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;
            }
            redirection.RequestPath     = model.RequestPath;
            redirection.RequestPathHash = OtherFunctions.GetHashFromString(model.RequestPath);
            redirection.RedirectionPath = model.RedirectionPath;
            db.SaveChanges();
            successfullyCompleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{oldRequestPath} -> {oldRedirectionPath}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.RedirectionEditedTo} {redirection.RequestPath} -> {redirection.RedirectionPath}"
                );
        }
Beispiel #5
0
        public static void DeleteProduct(CMSDatabase db, int?productID, HttpContext context, out bool successfullyDeleted)
        {
            if (!productID.HasValue)
            {
                successfullyDeleted = false;
                return;
            }
            ProductPage product = db.ProductPages.FirstOrDefault(pp => pp.ID == productID.Value);

            if (product == null)
            {
                successfullyDeleted = false;
                return;
            }
            IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>();
            string pathToImages     = $"{env.GetProductsImagesFolderFullPath()}{product.ID}/";

            // Удаляем данные об изображениях из БД
            string[] images = ImagesManagementFunctions.GetProductImageUrls(product, 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);
                }
            }
            db.Entry(product).Reference(pp => pp.PreviousPage).Load();
            --product.PreviousPage.ProductsCount;
            db.ProductPages.Remove(product);
            db.SaveChanges();
            // Удаляем папку с изображениями товара
            if (Directory.Exists(pathToImages))
            {
                Directory.Delete(pathToImages, true);
            }
            successfullyDeleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{product.PageName} (ID-{product.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ProductDeleted}"
                );
        }
Beispiel #6
0
        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)
                );
        }
Beispiel #7
0
        public void ApplySettings()
        {
            if (!isExisted)
            {
                return;
            }
            string createdImageFullName = sourceImageName;

            if (widthSetting.HasValue && heightSetting.HasValue)
            {
                createdImageFullName += $"_{widthSetting.Value}x{heightSetting.Value}";
            }
            if (qualitySetting.HasValue)
            {
                createdImageFullName += $"_q{qualitySetting.Value}";
            }
            createdImageFullName += sourceImageExtension;
            CreatedImageFullPath  = pathToImageFolder + createdImageFullName;
            if (!File.Exists(CreatedImageFullPath))
            {
                using (Image <Rgba32> sourceImage = Image.Load(sourceImageFullPath))
                {
                    if (widthSetting.HasValue && heightSetting.HasValue)
                    {
                        sourceImage.Mutate(x => x.Resize(widthSetting.Value, heightSetting.Value));
                    }
                    if (qualitySetting.HasValue)
                    {
                        IImageEncoder imageEncoder = null;
                        switch (sourceImageExtension.ToLower())
                        {
                        case ".jpg":
                        case ".jpeg":
                            var jpegEncoder = new JpegEncoder();
                            jpegEncoder.Quality = qualitySetting.Value;
                            imageEncoder        = jpegEncoder;
                            break;
                            // Настройки сжатия для png
                        }
                        sourceImage.Save(CreatedImageFullPath, imageEncoder);
                    }
                    else
                    {
                        sourceImage.Save(CreatedImageFullPath);
                    }
                }
            }
            CreatedImageSrc = CreatedImageFullPath.Substring(env.GetStorageFolderFullPath().Length - 1);
            if (addImageInfoToDB)
            {
                Database.Entities.Image image = new Database.Entities.Image
                {
                    ShortPath     = sourceImageShortPath,
                    ShortPathHash = OtherFunctions.GetHashFromString(sourceImageShortPath),
                    FullName      = sourceImageShortPath.Substring(sourceImageShortPath.LastIndexOf('/') + 1),
                    Height        = (uint)sourceImageHeight.Value,
                    Width         = (uint)sourceImageWidth.Value
                };
                db.Images.Add(image);
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateException) { }
            }
        }
Beispiel #8
0
        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; }
            }
        }
Beispiel #10
0
        public void SetVisitorInfo(int pageID, PageType pageType)
        {
            Visitor visitor = null;

            // Если в кукисах пользователя хранится информация о последнем заходе, тогда проверяем её
            // Если она равна текущей дате, тогда выполняем поиск посетителя по ID
            if (HttpContext.Request.Cookies.ContainsKey("visitor_id"))
            {
                try
                {
                    int visitorID = Convert.ToInt32(HttpContext.Request.Cookies["visitor_id"]);
                    visitor = db.Visitors.FirstOrDefault(v => v.ID == visitorID);
                }
                catch { }
            }
            // Если у пользователя нет информации о последнем визите или, если его ID не был найден в БД, тогда
            // ищем пользователя по IP
            if (visitor == null && correctUserAgents.IsMatch(HttpContext.Request.Headers["User-Agent"]))
            {
                string ip           = HttpContext.Connection.RemoteIpAddress.ToString();
                int    ipStringHash = OtherFunctions.GetHashFromString(ip);
                visitor = db.Visitors.FirstOrDefault(v => v.IPStringHash == ipStringHash && v.IPAdress.Equals(ip, StringComparison.Ordinal));
                // Если пользователь не найден, тогда добавляем его
                if (visitor == null)
                {
                    visitor = new Visitor
                    {
                        IPAdress     = ip,
                        IPStringHash = ipStringHash,
                        FirstVisit   = DateTime.Now,
                        LastVisit    = DateTime.Now
                    };
                    db.Visitors.Add(visitor);
                    try
                    {
                        // Если тут возникнет исключение, тогда в лог ошибок будет сделана соответствующая запись
                        db.SaveChanges();
                    }
                    catch (DbUpdateException)
                    {
                        // При одновременных запросах от одного пользователя может быть произведено одновременное добавление посетителя в БД,
                        // поэтому, если выбивает исключение, то отменяем добавление посетителя и производим ещё один поиск в БД
                        db.Entry(visitor).State = EntityState.Detached;
                        visitor = db.Visitors.FirstOrDefault(v => v.IPStringHash == ipStringHash && v.IPAdress.Equals(ip, StringComparison.Ordinal));
                    }
                }
                DateTime      dtNow         = DateTime.Now;
                DateTime      nextDay       = new DateTime(dtNow.Year, dtNow.Month, dtNow.Day).AddDays(1);
                CookieOptions cookieOptions = new CookieOptions {
                    MaxAge = nextDay - dtNow
                };
                HttpContext.Response.Cookies.Append("visitor_id", visitor.ID.ToString(), cookieOptions);
            }
            if (visitor != null)
            {
                visitor.LastVisit = DateTime.Now;
                db.VisitedPages.Add(new VisitedPage
                {
                    VisitedPageId = pageID,
                    PageType      = pageType,
                    Visitor       = visitor
                });
                db.SaveChanges();
            }
        }
        // ЭТОТ МЕТОД НЕ СОХРАНЯЕТ ИЗМЕНЕНИЯ, ТОЛЬКО ВНОСИТ ИХ
        // После изменения или удаления страницы-родителя, необходимо изменить все страницы, наследующиеся от
        // этой родительской страницы.
        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;
            }
        }
Beispiel #12
0
        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)
                );
        }
Beispiel #13
0
        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);
        }
 private void GetSourceImageInfo()
 {
     if (!isExisted)
     {
         return;
     }
     Database.Entities.Image image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(sourceImageShortPath) &&
                                                              img.ShortPath.Equals(sourceImageShortPath, StringComparison.Ordinal));
     if (image != null)
     {
         sourceImageWidth  = (int)image.Width;
         sourceImageHeight = (int)image.Height;
     }
     if (!sourceImageWidth.HasValue && !sourceImageHeight.HasValue)
     {
         using (Image <Rgba32> sourceImage = Image.Load(sourceImageFullPath))
         {
             sourceImageWidth  = sourceImage.Width;
             sourceImageHeight = sourceImage.Height;
             addImageInfoToDB  = true;
         }
     }
 }