Exemple #1
0
        public static IHtmlControl GetNewsView(SiteState state, LightObject currentUser, TopicStorage topic,
                                               out string description)
        {
            LightObject news = topic.Topic;

            description = BasketballHlp.GetDescriptionForNews(news);

            DateTime    localTime   = (news.Get(ObjectType.ActFrom) ?? DateTime.UtcNow).ToLocalTime();
            int         publisherId = news.Get(NewsType.PublisherId);
            LightObject publisher   = context.UserStorage.FindUser(publisherId);

            IHtmlControl editPanel = null;

            if (currentUser != null && (currentUser.Id == publisherId || currentUser.Get(BasketballUserType.IsModerator)))
            {
                editPanel = ViewNewsHlp.GetNewsEditPanel(state, topic);
            }

            IHtmlControl moderatorPanel = GetModeratorPanel(state, currentUser, topic, localTime);

            return(new HPanel(
                       Decor.Title(news.Get(NewsType.Title)),
                       new HLabel(localTime.ToString(Decor.timeFormat)).Block().FontBold(),
                       new HTextView(news.Get(NewsType.Text)).PositionRelative().Overflow("hidden"),
                       new HPanel(
                           new HLabel("Добавил:").MarginRight(5),
                           new HLink(UrlHlp.ShopUrl("user", publisherId), publisher?.Get(UserType.Login))
                           ),
                       new HLink(news.Get(NewsType.OriginUrl), news.Get(NewsType.OriginName)),
                       ViewTagHlp.GetViewTagsPanel(context.Tags.TagBox, topic.Topic),
                       editPanel,
                       moderatorPanel,
                       ViewCommentHlp.GetCommentsPanel(context.MessageConnection, state, currentUser, topic, topic.MessageLink.AllRows)
                       ));
        }
Exemple #2
0
        public static IHtmlControl DeleteTopicPanel(SiteState state, TopicStorage topic)
        {
            return(new HPanel(
                       Decor.Button("Удалить").Event("delete_topic", "", delegate
            {
                int messageCount = topic.MessageLink.AllRows.Length;
                if (!state.Operation.Validate(messageCount > 0, "Новость с комментариями не может быть удалена"))
                {
                    return;
                }

                MessageHlp.DeleteTopicMessages(context.MessageConnection, topic.Topic.Id);
                BasketballHlp.DeleteTopic(context.FabricConnection, topic.TopicId);

                topic.UpdateTopic();
                topic.UpdateMessages();
                context.UpdateLastComments(false);
                context.UpdateNews();
                context.UpdateArticles();

                state.RedirectUrl = "/";
            }
                                                     )
                       ).Align(false));
        }
Exemple #3
0
        public TopicStorage(IDataLayer topicConnection, IDataLayer messageConnection, int topicTypeId, int topicId)
        {
            this.TopicId = topicId;

            this.topicCache = new Cache <LightKin, long>(
                delegate
            {
                return(DataBox.LoadKin(topicConnection, topicTypeId, topicId));
            },
                delegate { return(topicChangeTick); }
                );

            this.messageLinkCache = new Cache <Tuple <TableLink, Dictionary <int, string> >, long>(
                delegate
            {
                TableLink messageLink = MessageHlp.LoadMessageLink(messageConnection, topicId);

                Dictionary <int, string> htmlRepresentById = new Dictionary <int, string>(messageLink.AllRows.Length);
                foreach (RowLink message in messageLink.AllRows)
                {
                    int messageId                = message.Get(MessageType.Id);
                    string content               = message.Get(MessageType.Content);
                    string htmlRepresent         = BasketballHlp.PreViewComment(content);
                    htmlRepresentById[messageId] = htmlRepresent;
                }

                return(_.Tuple(messageLink, htmlRepresentById));
            },
                delegate { return(messageChangeTick); }
                );
        }
Exemple #4
0
        public static IHtmlControl GetEditTagsPanel(SiteState state,
                                                    ObjectHeadBox tagBox, List <string> tags, bool isAdd)
        {
            if (tags == null)
            {
                return(null);
            }

            List <IHtmlControl> tagElements = new List <IHtmlControl>();
            int i = -1;

            foreach (string tag in tags)
            {
                ++i;
                int index = i;
                tagElements.Add(
                    new HPanel(
                        new HLabel(tag),
                        new HButton("",
                                    std.BeforeAwesome(@"\f00d", 0)
                                    ).MarginLeft(5).Color(Decor.redColor).Title("удалить тег")
                        .Event("tag_remove", "", delegate
                {
                    if (index < tags.Count)
                    {
                        tags.RemoveAt(index);
                    }
                },
                               index
                               )
                        ).InlineBlock().MarginTop(5).MarginRight(5)
                    );
            }

            string addTagName = string.Format("addTag_{0}", state.OperationCounter);
            string onClick    = !isAdd ? ";" :
                                string.Format("CK_updateAll(); {0}", BasketballHlp.AddCommentToCookieScript("newsText"));

            return(new HPanel(
                       new HPanel(
                           tagElements.ToArray()
                           ).MarginBottom(5),
                       new HPanel(
                           new HTextEdit(addTagName).Width(400).MarginRight(5).MarginBottom(5)
                           .MediaSmartfon(new HStyle().Width("100%")),
                           Decor.Button("Добавить тэг").VAlign(-1).MarginBottom(5)
                           .OnClick(onClick)
                           .Event("tag_add", "addTagData",
                                  delegate(JsonData json)
            {
                string addTag = json.GetText(addTagName);
                if (StringHlp.IsEmpty(addTag))
                {
                    return;
                }

                if (tags.Contains(addTag))
                {
                    return;
                }

                string[] newTags = addTag.Split(',');
                foreach (string rawTag in newTags)
                {
                    string tag = rawTag.Trim();
                    if (!StringHlp.IsEmpty(tag))
                    {
                        tags.Add(tag);
                    }
                }

                state.OperationCounter++;
            })
                           ).EditContainer("addTagData")
                       ).MarginTop(5));
        }
Exemple #5
0
        static IHtmlControl GetTopicRedoPanel(SiteState state,
                                              LightObject currentUser, LightSection forumSection, TopicStorage topic)
        {
            string blockHint = string.Format("topic_edit_{0}", topic.TopicId);

            IHtmlControl redoPanel = null;

            if (state.BlockHint == blockHint)
            {
                redoPanel = new HPanel(
                    new HPanel(
                        Decor.Button("Удалить тему").Event("delete_topic", "", delegate
                {
                    int messageCount = topic.MessageLink.AllRows.Length;
                    if (!state.Operation.Validate(messageCount > 1, "Тема с комментариями не может быть удалена"))
                    {
                        return;
                    }

                    MessageHlp.DeleteTopicMessages(context.ForumConnection, topic.Topic.Id);
                    BasketballHlp.DeleteTopic(context.FabricConnection, topic.TopicId);

                    topic.UpdateTopic();
                    topic.UpdateMessages();
                    context.UpdateLastComments(true);
                    context.Forum.ForSection(forumSection.Id).Update();

                    state.RedirectUrl = "/";
                }
                                                           )
                        ).Align(false),
                    Decor.PropertyEdit("editTopicTitle", "Заголовок темы", topic.Topic.Get(TopicType.Title)),
                    Decor.Button("Переименовать тему")
                    .Event("save_topic_edit", "editTopicData",
                           delegate(JsonData json)
                {
                    string title = json.GetText("editTopicTitle");

                    WebOperation operation = state.Operation;

                    if (!operation.Validate(title, "Не задан заголовок"))
                    {
                        return;
                    }

                    LightObject editTopic = DataBox.LoadObject(context.FabricConnection, TopicType.Topic, topic.TopicId);
                    editTopic.SetWithoutCheck(TopicType.Title, title);

                    editTopic.Box.Update();

                    context.Forum.ForSection(forumSection.Id).Update();
                    topic.UpdateTopic();

                    state.BlockHint = "";
                },
                           topic.TopicId
                           )
                    ).EditContainer("editTopicData")
                            .Padding(5, 10).MarginTop(5).Background(Decor.pageBackground);
            }

            return(new HPanel(
                       Decor.Button("Редактировать")
                       .Event("topic_edit", "", delegate
            {
                state.SetBlockHint(blockHint);
            }
                              ),
                       redoPanel
                       ).MarginTop(5).MarginBottom(10));
        }
Exemple #6
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"));
        }
Exemple #7
0
        public static IHtmlControl GetActualNewsBlock(SiteState state, LightObject currentUser)
        {
            IHtmlControl[] items = ViewNewsHlp.GetNewsItems(state, context.ActualNews);

            HPanel editBlock = null;
            string editHint  = "news_add";

            if (state.BlockHint == editHint)
            {
                if (state.Tag == null)
                {
                    state.Tag = new List <string>();
                }

                string unsaveText = BasketballHlp.AddCommentFromCookie();

                editBlock = new HPanel(
                    Decor.PropertyEdit("newsTitle", "Заголовок новости"),
                    new HPanel(
                        HtmlHlp.CKEditorCreate("newsText", unsaveText, "300px", true)
                        ),
                    ViewTagHlp.GetEditTagsPanel(state, context.Tags.TagBox, state.Tag as List <string>, true),
                    Decor.PropertyEdit("newsOriginName", "Источник"),
                    Decor.PropertyEdit("newsOriginUrl", "Ссылка"),
                    Decor.Button("Добавить новость").MarginTop(10) //.CKEditorOnUpdateAll()
                    .OnClick(string.Format("CK_updateAll(); {0}", BasketballHlp.AddCommentToCookieScript("newsText")))
                    .Event("save_news_add", "addNewsData",
                           delegate(JsonData json)
                {
                    string title      = json.GetText("newsTitle");
                    string text       = json.GetText("newsText");
                    string originName = json.GetText("newsOriginName");
                    string originUrl  = json.GetText("newsOriginUrl");

                    WebOperation operation = state.Operation;

                    if (!operation.Validate(title, "Не задан заголовок"))
                    {
                        return;
                    }

                    if (!operation.Validate(text, "Не задан текст"))
                    {
                        return;
                    }

                    ParentBox editBox = new ParentBox(context.FabricConnection, "1=0");

                    int addNewsId        = editBox.CreateObject(NewsType.News, NewsType.Title.CreateXmlIds(title), DateTime.UtcNow);
                    LightParent editNews = new LightParent(editBox, addNewsId);

                    editNews.Set(NewsType.PublisherId, currentUser.Id);
                    editNews.Set(NewsType.Text, text);
                    editNews.Set(NewsType.OriginName, originName);
                    editNews.Set(NewsType.OriginUrl, originUrl);

                    ViewTagHlp.SaveTags(context, state, editNews);

                    editBox.Update();

                    context.UpdateNews();

                    state.BlockHint = "";
                    state.Tag       = null;

                    BasketballHlp.ResetAddComment();
                }
                           )
                    ).EditContainer("addNewsData").Padding(5, 10).MarginTop(10).Background(Decor.pageBackground);
            }

            IHtmlControl addButton = null;

            if (currentUser != null && !BasketballHlp.NoRedactor(currentUser))
            {
                addButton = Decor.Button("Добавить").MarginLeft(10)
                            .Event("news_add", "", delegate
                {
                    state.Tag = null;
                    state.SetBlockHint(editHint);
                }
                                   );
            }

            return(new HPanel(
                       Decor.Subtitle("Новости"),
                       new HPanel(
                           items.ToArray()
                           ),
                       new HPanel(
                           new HLink("/novosti",
                                     "Все новости",
                                     new HBefore().ContentIcon(5, 12).BackgroundImage(UrlHlp.ImageUrl("pointer.gif")).MarginRight(5).VAlign(-2)
                                     ).FontBold(),
                           addButton
                           ).MarginTop(15),
                       editBlock
                       ));
        }
        static IHtmlControl GetMessageBlock(IDataLayer forumConnection, SiteState state,
                                            LightObject user, LightObject collocutor, RowLink message, int messageIndex)
        {
            int         messageId = message.Get(CorrespondenceType.Id);
            LightObject author    = message.Get(CorrespondenceType.Inbox) ? collocutor : user;
            DateTime    localTime = message.Get(CorrespondenceType.CreateTime).ToLocalTime();

            IHtmlControl deleteElement = null;

            if (state.BlockHint == "correspondence_moderation")
            {
                deleteElement = new HButton("",
                                            std.BeforeAwesome(@"\f00d", 0)
                                            ).MarginLeft(5).Color(Decor.redColor).Title("удалить комментарий")
                                .Event("delete_message", "", delegate
                {
                    forumConnection.GetScalar("", "Delete From correspondence Where id = @messageId",
                                              new DbParameter("messageId", messageId)
                                              );
                },
                                       messageId
                                       );
            }

            IHtmlControl messageBlock = new HPanel("", new IHtmlControl[] {
                new HPanel(
                    ViewUserHlp.AvatarBlock(author)
                    ).PositionAbsolute().Left(0).Top(0).Padding(7, 5, 10, 5),
                new HPanel(
                    new HPanel(
                        //new HLabel(author.Get(UserType.Login)).FontBold(),
                        new HLink(UrlHlp.ShopUrl("user", author.Id),
                                  author.Get(UserType.FirstName)
                                  ).FontBold(),
                        //new HLabel(author.Get(UserType.FirstName)).MarginLeft(5),
                        new HPanel(
                            new HLabel(localTime.ToString("dd.MM.yyyy HH:mm")).FontSize("90%").Color(Decor.minorColor),
                            deleteElement
                            ).InlineBlock().PositionAbsolute().Right(5)
                        ).PositionRelative().MarginBottom(6),
                    new HTextView(
                        BasketballHlp.PreViewComment(message.Get(CorrespondenceType.Content))
                        ).Block().PaddingBottom(15).BorderBottom("1px solid silver").MarginBottom(5)
                    ).BoxSizing().Width("100%").BorderLeft(Decor.columnBorder).Padding(7, 5, 5, 5)
            }
                                                   ).PositionRelative().PaddingLeft(64).BorderTop("2px solid #fff").Color(Decor.textColor);

            //IHtmlControl messageBlock = new HXPanel(
            //  new HPanel(
            //    new HLink(UrlHlp.ShopUrl("user", author.Id),
            //      author.Get(UserType.Login)
            //    ).FontBold(),
            //    new HLabel(author.Get(UserType.FirstName)).Block()
            //      .MediaTablet(new HStyle().InlineBlock().MarginLeft(5)),
            //    new HPanel(
            //      ViewUserHlp.AvatarBlock(author)
            //    ).MarginTop(5)
            //      .MediaTablet(new HStyle().Display("none"))
            //  ).BoxSizing().WidthLimit("100px", "").Padding(7, 5, 10, 5)
            //    .MediaTablet(new HStyle().Block().PaddingBottom(0).PaddingRight(110)),
            //  new HPanel(
            //    new HPanel(
            //      new HLabel(localTime.ToString("dd.MM.yyyy HH:mm")).MarginRight(5)
            //        .MediaTablet(new HStyle().MarginBottom(5)),
            //      deleteElement
            //    ).Align(false).FontSize("90%").Color(Decor.minorColor),
            //    new HTextView(
            //      BasketballHlp.PreViewComment(message.Get(CorrespondenceType.Content))
            //    ).PaddingBottom(15).MarginBottom(5).BorderBottom("1px solid silver")
            //  ).BoxSizing().Width("100%").BorderLeft(Decor.columnBorder).Padding(7, 5, 5, 5)
            //    .MediaTablet(new HStyle().Block().MarginTop(-19))
            //).BorderTop("2px solid #fff");

            if (messageIndex % 2 != 0)
            {
                messageBlock.Background(Decor.evenBackground);
            }

            return(messageBlock);
        }
        public static IHtmlControl GetAddPanel(BasketballContext context, SiteState state,
                                               LightObject user, LightObject collocutor, bool sendFromUserView)
        {
            if (user == null)
            {
                return(null);
            }

            if (user.Id == collocutor.Id)
            {
                return(null);
            }

            IHtmlControl editPanel = null;

            if (state.BlockHint == "messageAdd")
            {
                string commentValue = BasketballHlp.AddCommentFromCookie();

                editPanel = new HPanel(
                    new HTextArea("messageContent", commentValue).BoxSizing().Width("100%")
                    .Height("10em").MarginTop(5).MarginBottom(5),
                    Decor.Button("отправить")
                    .OnClick(BasketballHlp.AddCommentToCookieScript("messageContent"))
                    .Event("message_add_save", "messageData",
                           delegate(JsonData json)
                {
                    string content = json.GetText("messageContent");
                    if (StringHlp.IsEmpty(content))
                    {
                        return;
                    }

                    DialogueHlp.SendMessage(context, user.Id, collocutor.Id, content);

                    state.BlockHint = "";

                    BasketballHlp.ResetAddComment();

                    if (sendFromUserView)
                    {
                        state.Operation.Message = "Сообщение успешно отправлено";
                    }
                }
                           ),
                    new HElementControl(
                        h.Script(h.type("text/javascript"), "$('.messageContent').focus();"),
                        ""
                        )
                    ).EditContainer("messageData");
            }

            HButton moderatorButton = null;
            HPanel  moderatorPanel  = null;

            if (!sendFromUserView)
            {
                moderatorButton = new HButton("",
                                              std.BeforeAwesome(@"\f1e2", 0)
                                              ).PositionAbsolute().Right(5).Top(0)
                                  .Title("Модерирование личных сообщений").FontSize(14)
                                  .Color(state.BlockHint == correspondenceModeration ? Decor.redColor : Decor.disabledColor)
                                  .Event("correspondence_moderation_set", "", delegate
                {
                    state.SetBlockHint(correspondenceModeration);
                });

                if (state.BlockHint == correspondenceModeration)
                {
                    bool lockedCollocutor = user.Get(BasketballUserType.LockedUserIds, collocutor.Id);
                    moderatorPanel = new HPanel(
                        Decor.ButtonMidi(!lockedCollocutor ? "Заблокировать собеседника" : "Разблокировать собеседника")
                        .Event("collocutor_locked", "", delegate
                    {
                        LightObject editUser = DataBox.LoadObject(context.UserConnection, UserType.User, user.Id);
                        editUser.Set(BasketballUserType.LockedUserIds, collocutor.Id, !lockedCollocutor);
                        editUser.Box.Update();
                        context.UserStorage.Update();
                    }),
                        new HSpoiler(Decor.ButtonMidi("Удаление переписки").Block().FontBold(false),
                                     new HPanel(
                                         Decor.ButtonMidi("Удалить? (без подтверждения)")
                                         .MarginTop(5).MarginLeft(10)
                                         .Event("correspondence_delete", "", delegate
                    {
                        context.ForumConnection.GetScalar("",
                                                          "Delete From correspondence Where user_id = @userId and collocutor_id = @collocutorId",
                                                          new DbParameter("userId", user.Id), new DbParameter("collocutorId", collocutor.Id)
                                                          );

                        context.ForumConnection.GetScalar("",
                                                          "Delete From dialogue Where user_id = @userId and collocutor_id = @collocutorId",
                                                          new DbParameter("userId", user.Id), new DbParameter("collocutorId", collocutor.Id)
                                                          );

                        context.UpdateUnreadDialogs();
                    })
                                         )
                                     ).MarginTop(10)
                        ).MarginTop(10);
                }
            }

            bool locked = user.Get(BasketballUserType.LockedUserIds, collocutor.Id) ||
                          collocutor.Get(BasketballUserType.LockedUserIds, user.Id);

            return(new HPanel(
                       new HPanel(
                           Decor.ButtonMidi("Написать сообщение")
                           .Hide(locked)
                           .Event("message_add", "", delegate
            {
                state.SetBlockHint("messageAdd");
            }
                                  ),
                           new HLabel("Вы не можете отправить сообщение этому пользователю").Hide(!locked)
                           .MarginLeft(10).Color(Decor.subtitleColor),
                           moderatorButton
                           ).PositionRelative(),
                       editPanel,
                       moderatorPanel
                       ).MarginTop(10).MarginBottom(10));
        }
Exemple #10
0
        static HElement Page(HttpContext httpContext, SiteState state, string kind, int?id)
        {
            UserHlp.DirectAuthorization(httpContext, SiteContext.Default.SiteSettings);

            LightObject currentUser = UserHlp.GetCurrentUser(httpContext, SiteContext.Default.UserStorage);

            if (currentUser != null && (BasketballHlp.IsBanned(currentUser) || currentUser.Get(UserType.NotConfirmed)))
            {
                currentUser = null;
                httpContext.Logout();
            }

            state.EditMode = httpContext.IsInRole("edit");
            state.SeoMode  = httpContext.IsInRole("seo");
            state.UserMode = currentUser != null;

            int[] foundTagIds = state.Option.Get(OptionType.FoundTagIds);
            if (foundTagIds != null && foundTagIds.Length > 0)
            {
                kind = "search";
                id   = null;
            }

            IHtmlControl adminSectionPanel = null;

            if (kind == "page")
            {
                LightSection section = store.Sections.FindSection(id);
                adminSectionPanel = DecorEdit.AdminSectionPanel(
                    state.EditMode, state.SeoMode, kind, section, false
                    );
            }

            IHtmlControl dialogBox = null;

            if (!StringHlp.IsEmpty(state.Operation.Message))
            {
                dialogBox = DecorEdit.GetDialogBox(state);
            }

            bool isForum = kind == "topic";

            if (kind == "page")
            {
                LightSection pageSection = store.Sections.FindSection(id);
                string       designKind  = pageSection.Get(SectionType.DesignKind);
                if (pageSection != null && (designKind == "forum" || designKind == "forumSection"))
                {
                    isForum = true;
                }
            }


            string    title       = "";
            string    description = "";
            SchemaOrg schema      = null;
            bool      wideContent;

            IHtmlControl centerView = ViewHlp.GetCenter(httpContext,
                                                        state, currentUser, kind, id, out title, out description, out schema, out wideContent
                                                        );

            if (centerView == null && StringHlp.IsEmpty(state.RedirectUrl))
            {
                return(null);
            }

            BasketballContext context = (BasketballContext)SiteContext.Default;

            try
            {
                if (currentUser != null && kind == "dialog" && id != null)
                {
                    if (context.UnreadDialogLink.FindRow(DialogReadType.UnreadByUserId, currentUser.Id) != null)
                    {
                        DialogueHlp.MarkReadCorrespondence(context.ForumConnection, currentUser.Id, id.Value);
                        context.UpdateUnreadDialogs();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex);
            }

            HEventPanel mainPanel = new HEventPanel(
                new HPanel(
                    new HAnchor("top"),
                    DecorEdit.AdminMainPanel(SiteContext.Default.SiteSettings, httpContext),
                    ViewHeaderHlp.GetHeader(httpContext, state, currentUser, kind, id, isForum),
                    adminSectionPanel,
                    new HPanel(
                        new HPanel(
                            centerView,
                            new HPanel(
                                ViewRightColumnHlp.GetRightColumnView(state, isForum).InlineBlock().MarginRight(15)
                                .MediaLaptop(new HStyle().Block().MarginRight(0))
                                .MediaTablet(new HStyle().InlineBlock().MarginRight(15))
                                .MediaSmartfon(new HStyle().Width("100%").MarginRight(0)),
                                ViewRightColumnHlp.GetReclameColumnView(state).InlineBlock().VAlign(true)
                                ).Hide(wideContent).PositionAbsolute().Top(13).Right(15)
                            .MediaTablet(new HStyle().Position("static").MarginTop(15))
                            //.MediaSmartfon(new HStyle().Width("100%"))
                            ).PositionRelative().Align(true)
                        .Padding(15).PaddingRight(485)
                        .WidthLimit("", kind == "" ? "727px" : "892px")
                        .MediaLaptop(new HStyle().PaddingRight(250))
                        .MediaTablet(new HStyle().PaddingRight(15))
                        .MediaSmartfon(new HStyle().PaddingLeft(5).PaddingRight(5))
                        ).MarginLeft(12).MarginRight(12).PaddingBottom(160).Background(Decor.panelBackground)
                    .BoxSizing().HeightLimit("900px", "")
                    .MediaTablet(new HStyle().MarginLeft(0).MarginRight(0))
                    ),
                ViewHlp.GetFooterView(kind == ""),
                dialogBox
                //popupPanel
                ).Width("100%").BoxSizing().Align(null).Background(Decor.pageBackground)
                                    .Padding(1)
                                    .FontFamily("Tahoma").FontSize(12); //.Color(Decor.textColor);

            if (!StringHlp.IsEmpty(state.PopupHint) || dialogBox != null)
            {
                mainPanel.OnClick(";");
                mainPanel.Event("popup_reset", "", delegate
                {
                    state.PopupHint = "";
                    state.Operation.Reset();
                });
            }

            StringBuilder css = new StringBuilder();

            std.AddStyleForFileUploaderButtons(css);

            HElement mainElement = mainPanel.ToHtml("main", css);

            SiteSettings settings = SiteContext.Default.SiteSettings;

            //string blockHint = state.BlockHint;
            //bool withCkeditor = false;
            //if (!StringHlp.IsEmpty(blockHint))
            //{
            //  withCkeditor = blockHint == "news_add" || blockHint.StartsWith("article_edit_") ||
            //    blockHint.StartsWith("news_edit_");
            //}
            //bool withFileuploader = kind == "user" || withCkeditor;

            return(h.Html
                   (
                       h.Head(
                           h.Element("title", title),
                           h.MetaDescription(description),
                           h.LinkCss(UrlHlp.FileUrl("/css/static.css")),
                           h.LinkShortcutIcon("/images/favicon.ico"),
                           h.Meta("viewport", "width=device-width"),
                           //h.LinkCss("/css/font-awesome.css"),
                           //h.LinkCss("/css/fileuploader.css"),
                           h.LinkScript("/scripts/fileuploader.js"),
                           h.LinkScript("/ckeditor/ckeditor.js?v=4113"),
                           HtmlHlp.CKEditorUpdateAll(),
                           h.Raw(store.SeoWidgets.WidgetsCode),
                           HtmlHlp.SchemaOrg(schema),
                           h.OpenGraph("type", "website"),
                           h.OpenGraph("title", title),
                           h.OpenGraph("url", description),
                           h.OpenGraph("site_name", settings.Organization),
                           h.OpenGraph("image", settings.FullUrl("/images/logo_mini.jpg"))
                           ),
                       h.Body(
                           h.Css(h.Raw(css.ToString())),
                           h.Div(
                               HtmlHlp.RedirectScript(state.RedirectUrl)
                               ),
                           //h.Div(
                           //  withFileuploader ? h.LinkScript("/scripts/fileuploader.js") : null,
                           //  withCkeditor ? h.LinkScript("/ckeditor/ckeditor.js") : null,
                           //  withCkeditor ? HtmlHlp.CKEditorUpdateAll() : null
                           //),
                           mainElement
                           //withEditor ? h.Script(h.type("text/javascript"), "console.log('withScript');") : null,
                           //!withFileuploader && withEditor ? h.LinkScript("/scripts/fileuploader.js") : null,
                           //withEditor ? h.LinkScript("/ckeditor/ckeditor.js") : null,
                           //withEditor ? HtmlHlp.CKEditorUpdateAll() : null
                           //HtmlHlp.SchemaOrg(schema),
                           )
                   ));
        }
Exemple #11
0
        public static IHtmlControl GetActualArticleBlock(SiteState state, LightObject currentUser)
        {
            IHtmlControl[] items = ViewArticleHlp.GetArticleItems(state, context.ActualArticles);

            HPanel editBlock = null;

            if (state.BlockHint == "articleAdd")
            {
                editBlock = new HPanel(
                    Decor.PropertyEdit("addArticleTitle", "Заголовок статьи"),
                    Decor.Button("Добавить статью").MarginTop(10)
                    .Event("article_add_save", "addArticleData",
                           delegate(JsonData json)
                {
                    string title = json.GetText("addArticleTitle");

                    WebOperation operation = state.Operation;

                    if (!operation.Validate(title, "Не задан заголовок"))
                    {
                        return;
                    }

                    ObjectBox editBox = new ObjectBox(context.FabricConnection, "1=0");

                    int addArticleId = editBox.CreateObject(
                        ArticleType.Article, ArticleType.Title.CreateXmlIds(title), DateTime.UtcNow
                        );
                    LightObject editArticle = new LightObject(editBox, addArticleId);

                    editArticle.Set(ArticleType.PublisherId, currentUser.Id);

                    editBox.Update();
                    context.UpdateArticles();

                    state.BlockHint = "";

                    state.RedirectUrl = UrlHlp.ShopUrl("article", addArticleId);
                }
                           )
                    ).EditContainer("addArticleData")
                            .Padding(5, 10).MarginTop(10).Background(Decor.pageBackground);
            }

            HButton addButton = null;

            if (currentUser != null && !BasketballHlp.NoRedactor(currentUser))
            {
                addButton = Decor.Button("Добавить").Hide(currentUser == null).MarginLeft(10)
                            .Event("article_add", "", delegate
                {
                    state.SetBlockHint("articleAdd");
                }
                                   );
            }

            return(new HPanel(
                       Decor.Subtitle("Статьи").MarginBottom(12),
                       new HPanel(
                           items.ToArray()
                           ),
                       new HPanel(
                           new HLink("/stati",
                                     "Все статьи",
                                     new HBefore().ContentIcon(5, 12).BackgroundImage(UrlHlp.ImageUrl("pointer.gif")).MarginRight(5).VAlign(-2)
                                     ).FontBold(),
                           addButton
                           ).MarginTop(15),
                       editBlock
                       ).MarginTop(10));
        }
Exemple #12
0
        public static IHtmlControl GetCommentsPanel(IDataLayer commentConnection,
                                                    SiteState state, LightObject currentUser, TopicStorage topic, RowLink[] pageMessages)
        {
            HPanel addPanel = null;

            if (currentUser != null)
            {
                HPanel editPanel = null;
                if (state.BlockHint == "commentAdd")
                {
                    string commentValue = BasketballHlp.AddCommentFromCookie();

                    editPanel = new HPanel(
                        new HTextArea("commentContent", commentValue).Width("100%").Height("10em").MarginTop(5).MarginBottom(5),
                        Decor.Button("отправить")
                        .OnClick(BasketballHlp.AddCommentToCookieScript("commentContent"))
                        .Event("comment_add_save", "commentData",
                               delegate(JsonData json)
                    {
                        lock (lockObj)
                        {
                            string content = json.GetText("commentContent");
                            if (StringHlp.IsEmpty(content))
                            {
                                return;
                            }

                            if (BasketballHlp.IsDuplicate(topic, currentUser.Id, content))
                            {
                                return;
                            }

                            InsertMessageAndUpdate(commentConnection, topic, currentUser, null, content);

                            state.BlockHint = "";

                            BasketballHlp.ResetAddComment();
                        }
                    }
                               ),
                        new HElementControl(
                            h.Script(h.type("text/javascript"), "$('.commentContent').focus();"),
                            ""
                            )
                        ).EditContainer("commentData");
                }

                addPanel = new HPanel(
                    Decor.ButtonMini("оставить комментарий").FontBold().FontSize(12).Padding(2, 7).
                    Event("comment_add", "", delegate
                {
                    state.SetBlockHint("commentAdd");
                }
                          ),
                    new HButton("",
                                new HBefore().ContentIcon(11, 11).BackgroundImage(UrlHlp.ImageUrl("refresh.png"))
                                ).Color("#9c9c9c").MarginLeft(10).Title("Загрузить новые комментарии")
                    .Event("comments_refresh", "", delegate { }),
                    editPanel
                    );
            }

            Dictionary <int, string> htmlRepresentByMessageId = topic.HtmlRepresentByMessageId;

            //RowLink[] allMessages = topic.MessageLink.AllRows;
            RowLink bottomMessage = null;

            if (pageMessages.Length > 0)
            {
                bottomMessage = pageMessages[Math.Max(0, pageMessages.Length - 2)];
            }

            return(new HPanel(
                       new HAnchor("comments"),
                       new HLabel("Комментарии:").MarginTop(30).MarginBottom(20).FontSize("160%")
                       .Hide(commentConnection == context.ForumConnection),
                       new HPanel(
                           new HLabel("Автор").PositionAbsolute().Top(0).Left(0)
                           .BoxSizing().Width(100).Padding(7, 5, 5, 5),
                           new HLabel("Сообщение").Block().Padding(7, 5, 5, 5).BorderLeft(Decor.columnBorder)
                           ).PositionRelative().Align(null).PaddingLeft(100).Background("#dddddd").FontBold(),
                       new HGrid <RowLink>(pageMessages, delegate(RowLink comment)
            {
                IHtmlControl commentBlock = ViewCommentHlp.GetCommentBlock(
                    commentConnection, state, currentUser, topic, htmlRepresentByMessageId, comment
                    );

                if (bottomMessage == comment)
                {
                    return new HPanel(new HAnchor("bottom"), commentBlock);
                }
                return commentBlock;
            },
                                           new HRowStyle().Even(new HTone().Background(Decor.evenBackground))
                                           ).BorderBottom(Decor.bottomBorder).MarginBottom(10),
                       //new HAnchor("bottom"),
                       addPanel
                       ));
        }
Exemple #13
0
        public static IHtmlControl GetCommentBlock(IDataLayer commentConnection, SiteState state,
                                                   LightObject currentUser, TopicStorage topic, Dictionary <int, string> htmlRepresentByMessageId, RowLink comment)
        {
            LightObject user      = context.UserStorage.FindUser(comment.Get(MessageType.UserId));
            DateTime    localTime = comment.Get(MessageType.CreateTime).ToLocalTime();

            IHtmlControl whomBlock = GetWhomBlock(state, context.UserStorage, topic, htmlRepresentByMessageId, comment);

            int          commentId   = comment.Get(MessageType.Id);
            string       answerHint  = string.Format("answer_{0}", commentId);
            IHtmlControl answerBlock = null;

            if (currentUser != null && state.BlockHint == answerHint)
            {
                string commentValue = BasketballHlp.AddCommentFromCookie();

                answerBlock = new HPanel(
                    new HTextArea("answerContent", commentValue).Width("100%").Height("10em").MarginTop(5).MarginBottom(5),
                    Decor.Button("отправить")
                    .OnClick(BasketballHlp.AddCommentToCookieScript("answerContent"))
                    .Event("save_answer", "answerContainer",
                           delegate(JsonData json)
                {
                    lock (lockObj)
                    {
                        string content = json.GetText("answerContent");
                        if (StringHlp.IsEmpty(content))
                        {
                            return;
                        }

                        if (BasketballHlp.IsDuplicate(topic, currentUser.Id, content))
                        {
                            return;
                        }

                        InsertMessageAndUpdate(commentConnection, topic, currentUser, commentId, content);

                        state.BlockHint = "";

                        BasketballHlp.ResetAddComment();
                    }
                },
                           commentId
                           ),
                    new HElementControl(
                        h.Script(h.type("text/javascript"), "$('.answerContent').focus();"),
                        ""
                        )
                    ).EditContainer("answerContainer");
            }

            IHtmlControl editBlock = null;

            if (currentUser != null && currentUser.Id == user?.Id)
            {
                editBlock = new HPanel(
                    );
            }

            string  redoHint   = string.Format("redo_{0}", commentId);
            HButton redoButton = null;

            if (currentUser != null && currentUser.Id == user?.Id)
            {
                redoButton = Decor.ButtonMini("редактировать").Event("comment_redo", "",
                                                                     delegate(JsonData json)
                {
                    state.SetBlockHint(redoHint);
                },
                                                                     commentId
                                                                     );
            }

            IHtmlControl redoBlock = null;

            if (currentUser != null && state.BlockHint == redoHint)
            {
                redoBlock = new HPanel(
                    new HTextArea("redoContent", comment.Get(MessageType.Content))
                    .Width("100%").Height("10em").MarginTop(5).MarginBottom(5),
                    Decor.Button("изменить").Event("save_redo", "redoContainer",
                                                   delegate(JsonData json)
                {
                    string content = json.GetText("redoContent");
                    if (StringHlp.IsEmpty(content))
                    {
                        return;
                    }

                    //content = BasketballHlp.PreSaveComment(content);

                    commentConnection.GetScalar("",
                                                "Update message Set content=@content, modify_time=@time Where id=@id",
                                                new DbParameter("content", content),
                                                new DbParameter("time", DateTime.UtcNow),
                                                new DbParameter("id", commentId)
                                                );
                    topic.UpdateMessages();

                    state.BlockHint = "";
                },
                                                   commentId
                                                   ),
                    new HElementControl(
                        h.Script(h.type("text/javascript"), "$('.redoContent').focus();"),
                        ""
                        )
                    ).EditContainer("redoContainer");
            }

            IHtmlControl deleteElement = null;

            if (state.ModeratorMode)
            {
                deleteElement = new HButton("",
                                            std.BeforeAwesome(@"\f00d", 0)
                                            ).MarginLeft(5).Color(Decor.redColor).Title("удалить комментарий")
                                .Event("delete_comment", "", delegate
                {
                    MessageHlp.DeleteMessage(commentConnection, commentId);
                    topic.UpdateMessages();
                    context.UpdateLastComments(commentConnection == context.ForumConnection);
                },
                                       commentId
                                       );
            }

            string topicType = topic.Topic.Get(ObjectType.TypeId) == NewsType.News ? "news" : "article";

            string anchor = string.Format("reply{0}", commentId);

            return(new HXPanel(
                       new HAnchor(anchor),
                       new HPanel(
                           new HLink(UrlHlp.ShopUrl("user", user?.Id),
                                     user?.Get(UserType.Login)
                                     ).FontBold(),
                           new HLabel(user?.Get(UserType.FirstName)).Block()
                           .MediaTablet(new HStyle().InlineBlock().MarginLeft(5)),
                           new HPanel(
                               ViewUserHlp.AvatarBlock(user)
                               ).MarginTop(5)
                           .MediaTablet(new HStyle().Display("none"))
                           ).BoxSizing().WidthLimit("100px", "").Padding(7, 5, 10, 5)
                       .MediaTablet(new HStyle().Block().PaddingBottom(0).PaddingRight(110)),
                       new HPanel(
                           new HPanel(
                               new HLabel(localTime.ToString("dd.MM.yyyy HH:mm")).MarginRight(5)
                               .MediaTablet(new HStyle().MarginBottom(5)),
                               new HLink(string.Format("/{0}/{1}#{2}", topicType, topic.TopicId, anchor), "#").TextDecoration("none")
                               .Hide(commentConnection == context.ForumConnection),
                               deleteElement
                               ).Align(false).FontSize("90%").Color(Decor.minorColor),
                           whomBlock,
                           new HTextView(
                               DictionaryHlp.GetValueOrDefault(htmlRepresentByMessageId, commentId)
                               ).PaddingBottom(15).MarginBottom(5).BorderBottom("1px solid silver"),
                           new HPanel(
                               Decor.ButtonMini("ответить").Event("comment_answer", "",
                                                                  delegate
            {
                state.SetBlockHint(answerHint);
            },
                                                                  commentId
                                                                  ),
                               redoButton
                               ).Hide(currentUser == null),
                           answerBlock,
                           redoBlock
                           ).BoxSizing().Width("100%").BorderLeft(Decor.columnBorder).Padding(7, 5, 5, 5)
                       .MediaTablet(new HStyle().Block().MarginTop(-19))
                       ).BorderTop("2px solid #fff"));
        }
Exemple #14
0
        public static IHtmlControl GetAuthBlock(HttpContext httpContext, SiteState state, LightObject currentUser)
        {
            HImage keyImage = new HImage(UrlHlp.ImageUrl("key.gif")).MarginRight(8).VAlign(false);

            if (currentUser == null)
            {
                return(new HPanel(
                           keyImage,
                           new HTextEdit("authLogin").Width(90).MarginRight(5),
                           new HPasswordEdit("authPassword").Width(90).MarginRight(5),
                           Decor.Button("Войти").Event("user_login", "loginData", delegate(JsonData json)
                {
                    string login = json.GetText("authLogin");
                    string password = json.GetText("authPassword");

                    WebOperation operation = state.Operation;

                    if (!operation.Validate(login, "Введите логин"))
                    {
                        return;
                    }

                    if (!operation.Validate(password, "Введите пароль"))
                    {
                        return;
                    }

                    string xmlLogin = UserType.Login.CreateXmlIds("", login);
                    LightObject user = SiteContext.Default.UserStorage.FindUser(xmlLogin);
                    if (!operation.Validate(user == null, "Логин не найден"))
                    {
                        return;
                    }
                    if (!operation.Validate(user.Get(UserType.Password) != password, "Неверный пароль"))
                    {
                        return;
                    }

                    if (!operation.Validate(user.Get(UserType.NotConfirmed), "Ваш аккаунт не подтвержден через электронную почту. Письмо для подтверждения выслано вам на почту еще раз."))
                    {
                        try
                        {
                            BasketballHlp.SendRegistrationConfirmation(user.Id, login, user.Get(UserType.Email));
                        }
                        catch (Exception ex)
                        {
                            Logger.WriteException(ex);
                        }
                        return;
                    }

                    if (!operation.Validate(BasketballHlp.IsBanned(user),
                                            string.Format("Вы заблокированы до {0} и не можете войти на сайт",
                                                          user.Get(BasketballUserType.BannedUntil)?.ToLocalTime().ToString("dd-MM-yyyy HH:mm")
                                                          )
                                            ))
                    {
                        return;
                    }


                    httpContext.SetUserAndCookie(xmlLogin);
                }
                                                       ),
                           new HPanel(
                               new HPanel(new HLink("/register", "Регистрация"))
                               .MediaSmartfon(new HStyle().InlineBlock()),
                               new HPanel(new HLink("/passwordreset", "Забыли пароль"))
                               .MediaSmartfon(new HStyle().InlineBlock().MarginLeft(10))
                               ).Align(true).InlineBlock().MarginLeft(5).FontSize("80%").VAlign(false)
                           .MediaSmartfon(new HStyle().Block().MarginLeft(18))
                           ).EditContainer("loginData").PositionRelative().InlineBlock().MarginTop(10)
                       .MediaTablet(new HStyle().MarginTop(5))
                       .MediaSmartfon(new HStyle().MarginTop(0)));
            }

            HButton moderatorButton = null;

            if (currentUser.Get(BasketballUserType.IsModerator))
            {
                moderatorButton = new HButton("",
                                              std.BeforeAwesome(@"\f1e2", 0)
                                              ).Title("Режим модерирования").MarginRight(3).MarginLeft(5).FontSize(14)
                                  .Color(state.ModeratorMode ? Decor.redColor : Decor.disabledColor)
                                  .Event("moderator_mode_set", "", delegate
                {
                    state.ModeratorMode = !state.ModeratorMode;
                });
            }

            return(new HPanel(
                       keyImage,
                       new HLabel("Здравствуйте,").MarginRight(5),
                       new HLink(UrlHlp.ShopUrl("user", currentUser.Id), currentUser.Get(UserType.FirstName)).FontBold(),
                       new HLabel("!"),
                       moderatorButton,
                       Decor.Button("Выйти").MarginLeft(5).Event("user_logout", "", delegate(JsonData json)
            {
                httpContext.Logout();
            }
                                                                 )
                       ).InlineBlock().MarginTop(10));
        }