Example #1
0
        public static IHtmlControl GetCenter(HttpContext httpContext, SiteState state,
                                             LightObject currentUser, string kind, int?id,
                                             out string title, out string description, out SchemaOrg schema, out bool wideContent)
        {
            title       = "";
            description = "";
            schema      = null;
            wideContent = false;

            SiteSettings settings = context.SiteSettings;

            switch (kind)
            {
            case "":
            {
                title       = store.SEO.Get(SEOType.MainTitle);
                description = store.SEO.Get(SEOType.MainDescription);
                LightSection main = store.Sections.FindMenu("main");
                return(ViewHlp.GetMainView(state, currentUser));
            }

            case "news":
            {
                if (!context.News.ObjectById.Exist(id))
                {
                    return(null);
                }
                TopicStorage topicStorage = context.NewsStorages.ForTopic(id ?? 0);
                LightKin     topic        = topicStorage.Topic;
                //string tagsDisplay;
                IHtmlControl view = ViewNewsHlp.GetNewsView(state, currentUser, topicStorage, out description);

                title = topic.Get(NewsType.Title);

                //string postfix = "";
                //if (!StringHlp.IsEmpty(tagsDisplay))
                //  postfix = ". ";
                //description = string.Format("{0}{1}Живое обсуждение баскетбольных событий на basketball.ru.com",
                //  tagsDisplay, postfix
                //);

                string logoUrl = settings.FullUrl("/images/logo.gif");
                schema = new SchemaOrg("NewsArticle", settings.FullUrl(UrlHlp.ShopUrl("news", id)),
                                       title, new string[] { logoUrl }, topic.Get(ObjectType.ActFrom), topic.Get(ObjectType.ActTill),
                                       topic.Get(TopicType.OriginName), settings.Organization,
                                       logoUrl, description
                                       );

                return(view);
            }

            case "article":
            {
                if (!context.Articles.ObjectById.Exist(id))
                {
                    return(null);
                }
                TopicStorage topicStorage = context.ArticleStorages.ForTopic(id ?? 0);
                LightKin     topic        = topicStorage.Topic;
                title       = topic.Get(ArticleType.Title);
                description = topic.Get(ArticleType.Annotation);

                string logoUrl = settings.FullUrl("/images/logo.gif");
                schema = new SchemaOrg("Article", settings.FullUrl(UrlHlp.ShopUrl("article", id)),
                                       title, new string[] { logoUrl }, topic.Get(ObjectType.ActFrom), topic.Get(ObjectType.ActTill),
                                       topic.Get(TopicType.OriginName), settings.Organization,
                                       logoUrl, description
                                       );
                wideContent = topic.Get(ArticleType.WideContent);
                return(ViewArticleHlp.GetArticleView(state, currentUser, topicStorage));
            }

            case "topic":
            {
                TopicStorage topic = context.Forum.TopicsStorages.ForTopic(id ?? 0);
                title = topic.Topic.Get(TopicType.Title);

                int pageNumber = 0;
                {
                    string pageArg      = httpContext.Get("page");
                    int    messageCount = topic.MessageLink.AllRows.Length;
                    if (pageArg == "last" && messageCount > 0)
                    {
                        pageNumber = BinaryHlp.RoundUp(messageCount, ViewForumHlp.forumMessageCountOnPage) - 1;
                    }
                    else
                    {
                        pageNumber = ConvertHlp.ToInt(pageArg) ?? 0;
                    }
                }

                return(ViewForumHlp.GetTopicView(state, currentUser, topic, pageNumber));
            }

            case "tags":
            {
                int?tagId      = httpContext.GetUInt("tag");
                int pageNumber = httpContext.GetUInt("page") ?? 0;
                return(ViewNewsHlp.GetTagView(state, currentUser, tagId, pageNumber, out title, out description));
            }

            case "search":
            {
                return(ViewNewsHlp.GetFoundTagListView(state, out title));
            }

            case "user":
            {
                LightObject user = context.UserStorage.FindUser(id ?? -1);
                if (user == null)
                {
                    return(null);
                }
                title = string.Format("{0} - Basketball.ru.com", user.Get(UserType.Login));
                return(ViewUserHlp.GetUserView(state, currentUser, user));
            }

            case "page":
            {
                LightSection section = store.Sections.FindSection(id);
                title       = FabricHlp.GetSeoTitle(section, section.Get(SectionType.Title));
                description = FabricHlp.GetSeoDescription(section, section.Get(SectionType.Annotation));

                int    pageNumber = httpContext.GetUInt("page") ?? 0;
                string designKind = section.Get(SectionType.DesignKind);
                switch (designKind)
                {
                case "news":
                {
                    int[] allNewsIds = context.News.AllObjectIds;
                    return(ViewNewsHlp.GetNewsListView(state, currentUser, pageNumber));
                }

                case "articles":
                    return(ViewArticleHlp.GetArticleListView(state, currentUser, pageNumber));

                case "forum":
                    return(ViewForumHlp.GetForumView(state, currentUser, section));

                case "forumSection":
                    return(ViewForumHlp.GetForumSectionView(state, currentUser, section));

                default:
                    return(null);
                }
            }

            case "dialog":
            {
                if (currentUser == null)
                {
                    return(null);
                }

                if (id == null)
                {
                    return(ViewDialogueHlp.GetDialogueView(state,
                                                           context.ForumConnection, context.UserStorage, currentUser, out title
                                                           ));
                }

                LightObject collocutor = context.UserStorage.FindUser(id.Value);
                if (collocutor == null)
                {
                    return(null);
                }

                return(ViewDialogueHlp.GetCorrespondenceView(state, context.ForumConnection,
                                                             currentUser, collocutor, out title
                                                             ));
            }

            case "passwordreset":
                title = "Восстановление пароля - basketball.ru.com";
                return(ViewHlp.GetRestorePasswordView(state));

            case "register":
                title = "Регистрация - basketball.ru.com";
                return(ViewHlp.GetRegisterView(state));

            case "confirmation":
            {
                title = "Подтверждение аккаунта";

                int?   userId = httpContext.GetUInt("id");
                string hash   = httpContext.Get("hash");

                if (userId == null)
                {
                    return(ViewUserHlp.GetMessageView(
                               "Вам выслано письмо с кодом активации. Чтобы завершить процедуру регистрации, пройдите по ссылке, указанной в письме, и учётная запись будет активирована. Если вы не получили письмо, то попробуйте войти на сайт со своим логином и паролем. Тогда письмо будет отправлено повторно."
                               ));
                }

                if (StringHlp.IsEmpty(hash))
                {
                    return(null);
                }

                LightObject user = context.UserStorage.FindUser(userId.Value);
                if (userId == null)
                {
                    return(null);
                }

                if (!user.Get(UserType.NotConfirmed))
                {
                    return(ViewUserHlp.GetMessageView("Пользователь успешно активирован"));
                }

                string login  = user.Get(UserType.Login);
                string etalon = UserHlp.CalcConfirmationCode(user.Id, login, "bbbin");
                if (hash?.ToLower() != etalon?.ToLower())
                {
                    return(ViewUserHlp.GetMessageView("Неверный хэш"));
                }

                LightObject editUser = DataBox.LoadObject(context.UserConnection, UserType.User, user.Id);
                editUser.Set(UserType.NotConfirmed, false);
                editUser.Box.Update();

                context.UserStorage.Update();

                string xmlLogin = UserType.Login.CreateXmlIds("", login);
                HttpContext.Current.SetUserAndCookie(xmlLogin);

                state.RedirectUrl = "/";

                return(new HPanel());
            }
            }

            return(null);
        }
Example #2
0
        public static IHtmlControl GetRegisterView(SiteState state)
        {
            return(new HPanel(
                       Decor.Title("Регистрация"),
                       Decor.AuthEdit("login", "Логин (*):"),
                       Decor.AuthEdit("yourname", "Ваше имя (*):"),
                       Decor.AuthEdit("email", "E-mail (*):"),
                       Decor.AuthEdit(new HPasswordEdit("password"), "Пароль (*):"),
                       Decor.AuthEdit(new HPasswordEdit("passwordRepeat"), "Введите пароль ещё раз (*):"),
                       new HPanel(
                           Decor.Button("Зарегистрироваться").Event("user_register", "registerData",
                                                                    delegate(JsonData json)
            {
                string login = json.GetText("login");
                string name = json.GetText("yourname");
                string email = json.GetText("email");
                string password = json.GetText("password");
                string passwordRepeat = json.GetText("passwordRepeat");

                WebOperation operation = state.Operation;

                if (!operation.Validate(login, "Не задан логин"))
                {
                    return;
                }
                if (!operation.Validate(email, "Не задана электронная почта"))
                {
                    return;
                }
                if (!operation.Validate(!email.Contains("@"), "Некорректный адрес электронной почты"))
                {
                    return;
                }
                if (!operation.Validate(name, "Не задано имя"))
                {
                    return;
                }
                if (!operation.Validate(password, "Не задан пароль"))
                {
                    return;
                }
                if (!operation.Validate(password != passwordRepeat, "Повтор не совпадает с паролем"))
                {
                    return;
                }

                foreach (LightObject userObj in context.UserStorage.All)
                {
                    if (!operation.Validate(userObj.Get(UserType.Email)?.ToLower() == email?.ToLower(),
                                            "Пользователь с такой электронной почтой уже существует"))
                    {
                        return;
                    }
                }

                ObjectBox box = new ObjectBox(context.UserConnection, "1=0");

                int?createUserId = box.CreateUniqueObject(UserType.User,
                                                          UserType.Login.CreateXmlIds("", login), null);
                if (!operation.Validate(createUserId == null,
                                        "Пользователь с таким логином уже существует"))
                {
                    return;
                }

                LightObject user = new LightObject(box, createUserId.Value);
                FabricHlp.SetCreateTime(user);
                user.Set(UserType.Email, email);
                user.Set(UserType.FirstName, name);
                user.Set(UserType.Password, password);
                user.Set(UserType.NotConfirmed, true);

                box.Update();

                SiteContext.Default.UserStorage.Update();

                Logger.AddMessage("Зарегистрирован пользователь: {0}, {1}, {2}", user.Id, login, email);

                try
                {
                    BasketballHlp.SendRegistrationConfirmation(user.Id, login, email);

                    Logger.AddMessage("Отправлено письмо с подтверждением регистрации.");
                }
                catch (Exception ex)
                {
                    Logger.WriteException(ex);

                    //operation.Validate(true, string.Format("Непредвиденная ошибка при отправке подтверждения: {0}", ex.Message));
                    //return;
                }

                //string xmlLogin = UserType.Login.CreateXmlIds("", login);
                //HttpContext.Current.SetUserAndCookie(xmlLogin);

                //operation.Complete("Вы успешно зарегистрированы!", "");

                state.RedirectUrl = "/confirmation";
            }
                                                                    )
                           )
                       ).EditContainer("registerData"));
        }
Example #3
0
        protected void Application_Start(object sender, EventArgs e)
        {
            string appPath   = HttpContext.Current.Server.MapPath("");
            string logFolder = ApplicationHlp.CheckAndCreateFolderPath(appPath, "Logs");

            try
            {
                Logger.EnableLogging(Path.Combine(logFolder, "site.log"), 2);

                GlobalConfiguration.Configure(WebApiConfig.Register);

                string databaseFolder = ApplicationHlp.CheckAndCreateFolderPath(appPath, "Data");

                IDataLayer userConnection = new SQLiteDataLayer(string.Format(
                                                                    connectionStringFormat, Path.Combine(databaseFolder, "user.db3")));

                IDataLayer fabricConnection = new SQLiteDataLayer(string.Format(
                                                                      connectionStringFormat, Path.Combine(databaseFolder, "fabric.db3")));

                IDataLayer messageConnection = new SQLiteDataLayer(string.Format(
                                                                       connectionStringFormat, Path.Combine(databaseFolder, "message.db3")));

                IDataLayer forumConnection = new SQLiteDataLayer(string.Format(
                                                                     connectionStringFormat, Path.Combine(databaseFolder, "forum.db3")));

                Logger.AddMessage("Подключения к базам данных успешно созданы");

                SQLiteDatabaseHlp.CheckAndCreateDataBoxTables(userConnection);
                SQLiteDatabaseHlp.CheckAndCreateDataBoxTables(fabricConnection);
                MessageHlp.CheckAndCreateMessageTables(messageConnection);
                MessageHlp.CheckAndCreateMessageTables(forumConnection);
                DialogueHlp.CheckAndCreateDialogueTables(forumConnection);

                MetaHlp.ReserveDiapasonForMetaProperty(fabricConnection);

                FabricHlp.CheckAndCreateMenu(fabricConnection, "main");

                EditorSelector sectionEditorSelector = new EditorSelector(
                    new SectionTunes("news", "Новости"),
                    new SectionTunes("articles", "Статьи"),
                    new SectionTunes("forum", "Форум"),
                    new SectionTunes("rules", "Правила").Link(),
                    new SectionTunes("forumSection", "Раздел форума")
                    );

                EditorSelector unitEditorSelector = new EditorSelector(
                    new UnitTunes("reclame", "Рекламный блок").Tile().ImageAlt().Link().Annotation()
                    );

                Shop.Engine.Site.Novosti         = "news";
                Shop.Engine.Site.DirectPageLinks = true;
                //Shop.Engine.Site.AddFolderForNews = true;

                try
                {
                    string fabricScriptPath = Path.Combine(appPath, "FabricScript.sql");
                    if (File.Exists(fabricScriptPath))
                    {
                        string script = File.ReadAllText(fabricScriptPath);
                        Logger.AddMessage("Выполняем стартовый скрипт для fabric.db3: {0}", script);
                        fabricConnection.GetScalar("", script);
                    }

                    string userScriptPath = Path.Combine(appPath, "UserScript.sql");
                    if (File.Exists(userScriptPath))
                    {
                        string script = File.ReadAllText(userScriptPath);
                        Logger.AddMessage("Выполняем стартовый скрипт для user.db3: {0}", script);
                        userConnection.GetScalar("", script);
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteException(ex, "Ошибка при выполнении стартового скрипта");
                }

                SiteContext.Default = new BasketballContext(
                    appPath, sectionEditorSelector, unitEditorSelector,
                    userConnection, fabricConnection, messageConnection, forumConnection
                    );

                SiteContext.Default.Pull.StartTask(Labels.Service,
                                                   MemoryChecker((BasketballContext)SiteContext.Default)
                                                   );

                SiteContext.Default.Pull.StartTask(Labels.Service,
                                                   SiteTasks.CleaningSessions(SiteContext.Default,
                                                                              TimeSpan.FromHours(1), TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(1)
                                                                              )
                                                   );
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex, "Ошибка создания подключения к базе данных:");
            }
        }