Ejemplo n.º 1
0
        public static IHtmlControl GetFoundTagListView(SiteState state, out string title)
        {
            title = string.Format("Найденные теги по запросу: {0}", state.Option.Get(OptionType.SearchQuery));

            List <IHtmlControl> elements = new List <IHtmlControl>();

            int[] foundTagIds = state.Option.Get(OptionType.FoundTagIds);
            if (foundTagIds != null)
            {
                foreach (int tagId in foundTagIds)
                {
                    RowLink tagRow = context.Tags.TagBox.ObjectById.AnyRow(tagId);
                    if (tagRow == null)
                    {
                        continue;
                    }

                    string tagDisplay = TagType.DisplayName.Get(tagRow);

                    elements.Add(
                        new HPanel(
                            new HLink(ViewTagHlp.TagUrl(tagId, 0), tagDisplay)
                            ).MarginBottom(4)
                        );
                }
            }


            return(new HPanel(
                       Decor.Title(title),
                       new HPanel(
                           elements.ToArray()
                           )
                       ));
        }
Ejemplo n.º 2
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)
                       ));
        }
Ejemplo n.º 3
0
        public static IHtmlControl GetDialogueView(SiteState state,
                                                   IDataLayer forumConnection, UserStorage userStorage, LightObject user, out string title)
        {
            title = "Диалоги";

            TableLink dialogueLink = DialogueHlp.LoadDialogueLink(forumConnection,
                                                                  "user_id = @userId order by modify_time desc",
                                                                  new DbParameter("userId", user.Id)
                                                                  );

            IHtmlControl[] messageBlocks = new IHtmlControl[dialogueLink.AllRows.Length];
            int            i             = -1;

            foreach (RowLink dialog in dialogueLink.AllRows)
            {
                ++i;
                messageBlocks[i] = GetDialogBlock(forumConnection, userStorage, user, dialog, i);
            }

            return(new HPanel(
                       Decor.Title("Диалоги"),
                       new HPanel(
                           messageBlocks
                           )
                       ));
        }
Ejemplo n.º 4
0
        public static IHtmlControl GetArticleListView(SiteState state, LightObject currentUser, int pageNumber)
        {
            int[] allArticleIds = context.Articles.AllObjectIds;
            int   pageCount     = BinaryHlp.RoundUp(allArticleIds.Length, articleCountOnPage);
            int   curPos        = pageNumber * articleCountOnPage;

            if (curPos < 0 || curPos >= allArticleIds.Length)
            {
                return(new HPanel());
            }

            int[] articleIds = ArrayHlp.GetRange(allArticleIds, curPos,
                                                 Math.Min(articleCountOnPage, allArticleIds.Length - curPos)
                                                 );
            LightObject[] articleList = ArrayHlp.Convert(articleIds, delegate(int id)
                                                         { return(new LightObject(context.Articles, id)); }
                                                         );

            IHtmlControl[] items = GetArticleItems(state, articleList);

            return(new HPanel(
                       Decor.Title("Статьи").MarginBottom(15),
                       new HPanel(
                           new HPanel(
                               items
                               ),
                           ViewJumpHlp.JumpBar("/stati", context.Articles.AllObjectIds.Length, articleCountOnPage, pageNumber)
                           )
                       ));
        }
Ejemplo n.º 5
0
        public static IHtmlControl GetNewsListView(SiteState state, LightObject currentUser, int pageNumber)
        {
            //int pageCount = BinaryHlp.RoundUp(allNewsIds.Length, newsCountOnPage);
            //int curPos = pageNumber * newsCountOnPage;
            //if (curPos < 0 || curPos >= allNewsIds.Length)
            //  return null;

            //int[] newsIds = ArrayHlp.GetRange(allNewsIds, curPos, Math.Min(newsCountOnPage, allNewsIds.Length - curPos));
            //LightHead[] newsList = ArrayHlp.Convert(newsIds, delegate (int id)
            //{ return new LightHead(context.News, id); }
            //);

            int[]          allNewsIds = context.News.AllObjectIds;
            IHtmlControl[] items      = GetNewsItems(state, allNewsIds, pageNumber);
            if (items == null)
            {
                return(null);
            }

            //string title = StringHlp.IsEmpty(tag) ? "Новости" : "Теги";
            return(new HPanel(
                       Decor.Title("Новости"),
                       //Decor.Subtitle(string.Format("Тег — {0}", tag)),
                       new HPanel(
                           new HPanel(
                               items
                               ),
                           ViewJumpHlp.JumpBar("/novosti", allNewsIds.Length, newsCountOnPage, pageNumber)
                           )
                       ));
        }
Ejemplo n.º 6
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));
        }
Ejemplo n.º 7
0
        static IHtmlControl GetUserRedoPanel(SiteState state, LightObject user)
        {
            return(new HPanel(
                       Decor.PropertyEdit("editUserName", "Ваше имя (*):", user.Get(UserType.FirstName)),
                       Decor.PropertyEdit("editUserEmail", "Email (*):", user.Get(UserType.Email)),
                       Decor.PropertyEdit("editUserCountry", "Страна:", user.Get(BasketballUserType.Country)),
                       Decor.PropertyEdit("editUserCity", "Город:", user.Get(BasketballUserType.City)),
                       Decor.PropertyEdit("editUserInterests", "Интересы:", user.Get(BasketballUserType.Interests)),
                       Decor.PropertyEdit("editUserAboutMe", "О себе:", user.Get(BasketballUserType.AboutMe)),
                       Decor.PropertyEdit("editUserCommunity", "На basketball.ru с:", user.Get(BasketballUserType.CommunityMember)),
                       Decor.Button("Сохранить")
                       .Event("user_edit_save", "userContainer",
                              delegate(JsonData json)
            {
                string name = json.GetText("editUserName");
                string email = json.GetText("editUserEmail");
                string country = json.GetText("editUserCountry");
                string city = json.GetText("editUserCity");
                string interests = json.GetText("editUserInterests");
                string aboutMe = json.GetText("editUserAboutMe");
                string community = json.GetText("editUserCommunity");

                WebOperation operation = state.Operation;

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

                LightObject editUser = DataBox.LoadObject(context.UserConnection, UserType.User, user.Id);

                editUser.Set(UserType.FirstName, name);
                editUser.Set(UserType.Email, email);
                editUser.Set(BasketballUserType.Country, country);
                editUser.Set(BasketballUserType.City, city);
                editUser.Set(BasketballUserType.Interests, interests);
                editUser.Set(BasketballUserType.AboutMe, aboutMe);
                editUser.Set(BasketballUserType.CommunityMember, community);

                editUser.Set(ObjectType.ActTill, DateTime.UtcNow);

                editUser.Box.Update();

                context.UserStorage.Update();

                state.BlockHint = "";
            }
                              )
                       ).EditContainer("userContainer"));
        }
Ejemplo n.º 8
0
        static IHtmlControl GetActualPublicationPanel(SiteState state)
        {
            return(new HPanel(
                       Decor.Subtitle("Обсуждаемое").MarginBottom(10).MarginTop(5),
                       new HGrid <RowLink>(context.LastPublicationComments,
                                           delegate(RowLink comment)
            {
                int topicId = comment.Get(MessageType.ArticleId);

                TopicStorage topic = null;
                string url = "";
                if (context.News.ObjectById.Exist(topicId))
                {
                    topic = context.NewsStorages.ForTopic(topicId);
                    url = UrlHlp.ShopUrl("news", topic?.TopicId);
                }
                else if (context.Articles.ObjectById.Exist(topicId))
                {
                    topic = context.ArticleStorages.ForTopic(topicId);
                    url = UrlHlp.ShopUrl("article", topic?.TopicId);
                }

                if (topic == null || topic.Topic == null)
                {
                    return new HPanel();
                }

                int userId = comment.Get(MessageType.UserId);
                LightObject user = context.UserStorage.FindUser(userId);

                DateTime localTime = comment.Get(MessageType.CreateTime).ToLocalTime();
                string replyUrl = string.Format("{0}#reply{1}", url, comment.Get(MessageType.Id));

                return new HPanel(
                    new HPanel(
                        new HLabel(localTime.ToString("HH:mm")).MarginRight(5)
                        .Title(localTime.ToString(Decor.timeFormat)),
                        new HLabel(user?.Get(UserType.Login))
                        ),
                    new HLink(url,
                              topic.Topic.Get(TopicType.Title)
                              ).MarginRight(5),
                    new HLink(
                        replyUrl, "",
                        new HBefore().ContentIcon(13, 13).Background("/images/full.gif", "no-repeat", "bottom").VAlign(-2)
                        //new HImage("/images/full.gif").VAlign(-2)
                        )
                    //ViewNewsHlp.GetCommentElement(topic.MessageLink.AllRows.Length, url)
                    ).MarginBottom(6);
            },
                                           new HRowStyle()
                                           ).FontSize("90%")
                       ).Padding(15, 15, 10, 15).MarginBottom(5).Background(Decor.pageBackground));
        }
Ejemplo n.º 9
0
 static IHtmlControl GetRedoAvatarPanel(LightObject user)
 {
     return(new HPanel(
                new HFileUploader("/avatarupload", "Выбрать аватар", user.Id),
                Decor.Button("Удалить аватар").MarginTop(5).Event("avatar_delete", "",
                                                                  delegate
     {
         File.Delete(UrlHlp.ImagePath(Path.Combine("users", user.Id.ToString(), "avatar.png")));
     }
                                                                  )
                ).MarginTop(5));
 }
Ejemplo n.º 10
0
        public static IHtmlControl GetArticleView(SiteState state, LightObject currentUser, TopicStorage topic)
        {
            if (topic == null || topic.Topic == null)
            {
                return(null);
            }

            LightObject article = topic.Topic;

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

            IHtmlControl editPanel = null;

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

            string author       = article.Get(ArticleType.Author);
            int    commentCount = topic.MessageLink.AllRows.Length;
            string articleUrl   = UrlHlp.ShopUrl("article", article.Id);

            return(new HPanel(
                       Decor.Title(article.Get(NewsType.Title)),
                       new HPanel(
                           new HLabel(string.Format("{0},", author)).FontBold().MarginRight(5).Hide(StringHlp.IsEmpty(author)),
                           new HLabel(article.Get(ArticleType.OriginName))
                           .FontBold().MarginRight(5),
                           new HLabel(string.Format("| {0}", localTime.ToString("dd MMMM yyyy")))
                           ).FontSize("90%"),
                       new HPanel(
                           new HLabel("Комментарии:").Color(Decor.minorColor),
                           ViewNewsHlp.GetCommentElement(commentCount, articleUrl)
                           ).FontSize("90%"),
                       //new HLabel(localTime.ToString(Decor.timeFormat)).Block().FontBold(),
                       new HTextView(article.Get(NewsType.Text)),
                       new HLabel("Автор:").MarginRight(5).Hide(StringHlp.IsEmpty(author)),
                       new HLabel(author).FontBold().MarginRight(5).Hide(StringHlp.IsEmpty(author)),
                       new HLabel("|").MarginRight(5).Hide(StringHlp.IsEmpty(author)),
                       new HLink(article.Get(NewsType.OriginUrl), article.Get(NewsType.OriginName)),
                       new HPanel(
                           new HLabel("Добавил:").MarginRight(5),
                           new HLink(UrlHlp.ShopUrl("user", publisherId), publisher?.Get(UserType.Login))
                           ).MarginTop(5),
                       editPanel,
                       ViewCommentHlp.GetCommentsPanel(context.MessageConnection, state, currentUser, topic, topic.MessageLink.AllRows)
                       ));
        }
Ejemplo n.º 11
0
        public static IHtmlControl GetTopicView(SiteState state,
                                                LightObject currentUser, TopicStorage topic, int pageNumber)
        {
            if (topic == null || topic.Topic == null)
            {
                return(null);
            }

            int?         forumSectionId = topic.Topic.GetParentId(ForumSectionType.TopicLinks);
            LightSection forumSection   = context.Store.Sections.FindSection(forumSectionId);

            if (forumSection == null)
            {
                return(null);
            }

            IHtmlControl editPanel = null;

            if (state.ModeratorMode)
            {
                editPanel = GetTopicRedoPanel(state, currentUser, forumSection, topic);
            }

            RowLink[] allMessages  = topic.MessageLink.AllRows;
            RowLink[] pageMessages = ViewJumpHlp.GetPageItems(allMessages, forumMessageCountOnPage, pageNumber);

            if (pageMessages == null)
            {
                return(null);
            }

            return(new HPanel(
                       Decor.Title(topic.Topic.Get(TopicType.Title)).MarginBottom(15),
                       new HPanel(
                           new HLink("/forum", "Форумы"),
                           ArrowElement(),
                           new HLink(UrlHlp.ShopUrl("page", forumSectionId),
                                     forumSection?.Get(SectionType.Title)
                                     )
                           ).MarginBottom(10),
                       editPanel,
                       ViewJumpHlp.JumpBar(string.Format("/topic/{0}", topic.TopicId),
                                           allMessages.Length, forumMessageCountOnPage, pageNumber
                                           ).MarginBottom(5),
                       ViewCommentHlp.GetCommentsPanel(context.ForumConnection, state, currentUser, topic, pageMessages),
                       ViewJumpHlp.JumpBar(string.Format("/topic/{0}", topic.TopicId),
                                           allMessages.Length, forumMessageCountOnPage, pageNumber
                                           ).MarginTop(10)
                       ));
        }
Ejemplo n.º 12
0
        static IHtmlControl GetAdminPanel(LightObject user)
        {
            bool isModerator = user.Get(BasketballUserType.IsModerator);

            return(new HPanel(
                       Decor.Button(isModerator ? "Лишить прав модератора" : "Сделать модератором")
                       .Event("moderator_rights", "", delegate
            {
                LightObject editUser = DataBox.LoadObject(context.UserConnection, UserType.User, user.Id);
                editUser.Set(BasketballUserType.IsModerator, !isModerator);
                editUser.Box.Update();

                context.UserStorage.Update();
            }
                              )
                       ));
        }
Ejemplo n.º 13
0
        public static IHtmlControl GetForumView(SiteState state, LightObject currentUser, LightSection forum)
        {
            return(new HPanel(
                       Decor.Title("Форумы").MarginBottom(15),
                       new HGrid <LightSection>(forum.Subsections,
                                                delegate(LightSection subSection)
            {
                TopicStorage lastTopic = GetLastTopicForForumSection(subSection);
                RowLink lastMessage = lastTopic == null ? null : _.Last(lastTopic.MessageLink.AllRows);
                LightObject lastUser = FindUserForMessage(lastMessage);

                return new HPanel(
                    new HPanel(
                        new HLink(UrlHlp.ShopUrl("page", subSection.Id),
                                  subSection.Get(SectionType.Title)
                                  ).FontBold()
                        ).RelativeWidth(50).PaddingLeft(5).VAlign(true).PaddingTop(15)
                    .MediaTablet(new HStyle().Block().Width("auto")),
                    new HPanel(
                        new HPanel(
                            new HLink(UrlHlp.ShopUrl("topic", lastTopic?.TopicId),
                                      lastTopic?.Topic.Get(TopicType.Title)
                                      )
                            ).MarginTop(7).MarginBottom(3),
                        new HPanel(
                            new HLink(UrlHlp.ShopUrl("user", lastUser?.Id),
                                      lastUser?.Get(UserType.Login)
                                      ),
                            new HLabel(
                                lastMessage?.Get(MessageType.CreateTime).ToLocalTime().ToString(Decor.timeFormat)
                                ).MarginLeft(7).MarginRight(7),
                            new HLink(
                                string.Format("{0}?page=last#bottom", UrlHlp.ShopUrl("topic", lastTopic?.TopicId)),
                                new HImage("/images/full.gif")
                                ).Hide(lastMessage == null)
                            ).MarginBottom(7)
                        ).RelativeWidth(50).Padding(0, 5).Height(45).BorderLeft(Decor.columnBorder)
                    .MediaTablet(new HStyle().Width("auto").Border("none"))
                    );
            },
                                                new HRowStyle().Even(new HTone().Background(Decor.evenBackground))
                                                ).BorderBottom(Decor.bottomBorder).MarginBottom(10),
                       DecorEdit.AdminGroupPanel(state.EditMode, forum.Id)
                       ));
        }
Ejemplo n.º 14
0
        public static IHtmlControl GetTagView(SiteState state, LightObject currentUser,
                                              int?tagId, int pageNumber, out string title, out string description)
        {
            title       = "";
            description = "";

            if (tagId == null)
            {
                return(null);
            }

            RowLink tagRow = context.Tags.TagBox.ObjectById.AnyRow(tagId.Value);

            if (tagRow == null)
            {
                return(null);
            }

            string tagDisplay = TagType.DisplayName.Get(tagRow);

            title       = string.Format("{0} - все новости на basketball.ru.com", tagDisplay);
            description = string.Format("{0} - все новости. Живое обсуждение баскетбольных событий на basketball.ru.com", tagDisplay);

            int[] newsIds = ViewTagHlp.GetNewsIdsForTag(context.FabricConnection, tagId.Value);

            IHtmlControl[] items = GetNewsItems(state, newsIds, pageNumber);
            if (items == null)
            {
                return(null);
            }

            string urlWithoutPageIndex = string.Format("/tags?tag={0}", tagId.Value);

            return(new HPanel(
                       Decor.Title(tagDisplay), //.Color(Decor.subtitleColor),
                       //Decor.Subtitle(string.Format("Тег — {0}", tagDisplay)).MarginTop(5),
                       new HPanel(
                           new HPanel(
                               items
                               ),
                           ViewJumpHlp.JumpBar(urlWithoutPageIndex, newsIds.Length, newsCountOnPage, pageNumber)
                           )
                       ));
        }
Ejemplo n.º 15
0
        static IHtmlControl GetModeratorPanel(LightObject user)
        {
            return(new HPanel(
                       Decor.PropertyEdit("editBannedUntil", "Заблокировать до (например, 22.12.2018)",
                                          user.Get(BasketballUserType.BannedUntil)?.ToString("dd.MM.yyyy")
                                          ),
                       Decor.PropertyEdit("editNotRedactorUntil", "Запретить добавление новостей до",
                                          user.Get(BasketballUserType.NotRedactorUntil)?.ToString("dd.MM.yyyy")
                                          ),
                       Decor.Button("Сохранить").Event("user_rights_save", "moderatorEdit",
                                                       delegate(JsonData json)
            {
                string bannedUntilStr = json.GetText("editBannedUntil");
                string notRedactorUntilStr = json.GetText("editNotRedactorUntil");

                LightObject editUser = DataBox.LoadObject(context.UserConnection, UserType.User, user.Id);

                DateTime bannedUntil;
                if (DateTime.TryParse(bannedUntilStr, out bannedUntil))
                {
                    editUser.Set(BasketballUserType.BannedUntil, bannedUntil);
                }
                else
                {
                    editUser.Set(BasketballUserType.BannedUntil, null);
                }

                DateTime notRedactorUntil;
                if (DateTime.TryParse(notRedactorUntilStr, out notRedactorUntil))
                {
                    editUser.Set(BasketballUserType.NotRedactorUntil, notRedactorUntil);
                }
                else
                {
                    editUser.Set(BasketballUserType.NotRedactorUntil, null);
                }

                editUser.Box.Update();
                context.UserStorage.Update();
            }
                                                       )
                       ).EditContainer("moderatorEdit").MarginTop(10));
        }
Ejemplo n.º 16
0
        static IHtmlControl GetModeratorPanel(SiteState state,
                                              LightObject currentUser, TopicStorage topic, DateTime localTime)
        {
            bool isModerator = currentUser != null && currentUser.Get(BasketballUserType.IsModerator);

            if (!state.EditMode && !state.ModeratorMode)
            {
                return(null);
            }

            return(new HPanel(
                       new HTextEdit("newsDate", localTime.ToString(Decor.timeFormat))
                       .Width(100).MarginRight(10).FontFamily("Tahoma").FontSize(12),
                       Decor.Button("Изменить дату").Event("news_date_modify", "newsAdminContainer",
                                                           delegate(JsonData json)
            {
                string dateStr = json.GetText("newsDate");

                WebOperation operation = state.Operation;

                if (!operation.Validate(dateStr, "Дата не задана"))
                {
                    return;
                }
                DateTime editDate;
                if (!operation.Validate(!DateTime.TryParse(dateStr, out editDate), "Неверный формат даты"))
                {
                    return;
                }

                LightObject editNews = DataBox.LoadObject(context.FabricConnection, NewsType.News, topic.TopicId);
                editNews.Set(ObjectType.ActFrom, editDate.ToUniversalTime());
                editNews.Set(ObjectType.ActTill, DateTime.UtcNow);

                editNews.Box.Update();

                context.UpdateNews();
                context.NewsStorages.ForTopic(topic.TopicId).UpdateTopic();
            }
                                                           )
                       ).EditContainer("newsAdminContainer"));
        }
Ejemplo n.º 17
0
        static IHtmlControl GetUserEditPanel(SiteState state, LightObject user)
        {
            string blockHint = string.Format("userEdit_{0}", user.Id);

            IHtmlControl redoPanel = null;

            if (state.BlockHint == blockHint)
            {
                redoPanel = GetUserRedoPanel(state, user);
            }

            return(new HPanel(
                       Decor.Button("Редактировать профиль").MarginBottom(5)
                       .Event("user_edit", "", delegate
            {
                state.SetBlockHint(blockHint);
            }
                              ),
                       redoPanel
                       ).MarginTop(5).WidthLimit("", "480px"));
        }
Ejemplo n.º 18
0
 public static IHtmlControl GetMessageView(string message)
 {
     return(new HPanel(
                Decor.Subtitle(message)
                ));
 }
Ejemplo n.º 19
0
        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));
        }
Ejemplo n.º 20
0
        public static IHtmlControl GetForumSectionView(SiteState state, LightObject currentUser, LightSection section)
        {
            LightHead[] topics = context.Forum.ForSection(section.Id).Topics;

            IHtmlControl addPanel = null;

            if (currentUser != null)
            {
                addPanel = GetTopicAddPanel(state, currentUser, section);
            }

            return(new HPanel(
                       Decor.Title(section.Get(SectionType.Title)).MarginBottom(15),
                       new HPanel(
                           new HLink("/forum", "Форумы")
                           ).MarginBottom(25),
                       //new HPanel(
                       //  new HLink("/forum", "Форумы"),
                       //  ArrowElement(),
                       //  new HLabel(section.Get(SectionType.Title))
                       //).MarginBottom(10),
                       addPanel,
                       new HGrid <LightHead>(topics, delegate(LightHead topic)
            {
                TopicStorage topicStorage = context.Forum.TopicsStorages.ForTopic(topic.Id);
                //int publisherId = topicStorage.Topic.Get(TopicType.PublisherId);
                //LightObject user = context.UserStorage.FindUser(publisherId);

                RowLink lastMessage = _.Last(topicStorage.MessageLink.AllRows);
                LightObject lastUser = FindUserForMessage(lastMessage);

                return new HPanel(
                    new HPanel(
                        new HLink(string.Format("{0}?page=last", UrlHlp.ShopUrl("topic", topic.Id)),
                                  topic.Get(TopicType.Title)
                                  ).FontBold()
                        ).RelativeWidth(55).Padding(8, 5, 9, 5).BorderRight(Decor.columnBorder)
                    .MediaTablet(new HStyle().Block().Width("auto")),
                    //new HPanel(
                    //  new HLink(UrlHlp.ShopUrl("user", publisherId),
                    //    user?.Get(UserType.Login)
                    //  ).FontBold()
                    //).Align(null),
                    new HPanel(
                        new HLabel(topicStorage.MessageLink.AllRows.Length)
                        ).Align(null).RelativeWidth(10).PaddingTop(8).PaddingBottom(9).BorderRight(Decor.columnBorder)
                    .MediaTablet(new HStyle().Width(50).PaddingTop(0)),
                    new HPanel(
                        new HLink(UrlHlp.ShopUrl("user", lastUser?.Id),
                                  lastUser?.Get(UserType.Login)
                                  ),
                        new HLabel(
                            lastMessage?.Get(MessageType.CreateTime).ToLocalTime().ToString(Decor.timeFormat)
                            ).MarginLeft(7).MarginRight(7),
                        new HLink(
                            string.Format("{0}?page=last#bottom", UrlHlp.ShopUrl("topic", topic.Id)),
                            new HImage("/images/full.gif")
                            )
                        ).RelativeWidth(35).Padding(0, 5)
                    .MediaTablet(new HStyle().Width("auto"))
                    );
            },
                                             new HRowStyle().Even(new HTone().Background(Decor.evenBackground))
                                             ).BorderBottom(Decor.bottomBorder).MarginBottom(10)
                       ));
        }
Ejemplo n.º 21
0
        static IHtmlControl GetTopicAddPanel(SiteState state, LightObject currentUser, LightSection section)
        {
            string blockHint = "topic_add";

            IHtmlControl addPanel = null;

            if (state.BlockHint == blockHint)
            {
                addPanel = new HPanel(
                    Decor.PropertyEdit("addTopicTitle", "Заголовок темы"),
                    new HTextArea("addTopicText")
                    .Width("100%").Height("6em").MarginBottom(5),
                    Decor.Button("Сохранить").MarginTop(10)
                    .Event("save_topic_add", "addTopicData", delegate(JsonData json)
                {
                    string title = json.GetText("addTopicTitle");
                    string text  = json.GetText("addTopicText");

                    WebOperation operation = state.Operation;

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

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

                    int addTopicId    = editBox.CreateObject(TopicType.Topic, TopicType.Title.CreateXmlIds(title), DateTime.UtcNow);
                    LightKin addTopic = new LightKin(editBox, addTopicId);

                    addTopic.SetParentId(ForumSectionType.TopicLinks, section.Id);

                    addTopic.Set(ObjectType.ActTill, DateTime.UtcNow);
                    addTopic.Set(TopicType.PublisherId, currentUser.Id);

                    editBox.Update();

                    MessageHlp.InsertMessage(context.ForumConnection, addTopic.Id, currentUser.Id, null, text);

                    context.UpdateLastComments(true);
                    context.Forum.ForSection(section.Id).Update();

                    state.BlockHint = "";

                    //context.Forum.TopicsStorages.ForTopic(addTopic.Id);
                }
                           )
                    ).EditContainer("addTopicData").MarginTop(5);
            }

            return(new HPanel(
                       Decor.Button("Создать тему")
                       .Event("topic_add", "", delegate
            {
                state.SetBlockHint(blockHint);
            }
                              ),
                       addPanel
                       ).MarginTop(5).MarginBottom(10));
        }
Ejemplo n.º 22
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"));
        }
Ejemplo n.º 23
0
        static IHtmlControl GetArticleEditPanel(SiteState state, TopicStorage topic)
        {
            LightObject article = topic.Topic;

            string blockHint = string.Format("article_edit_{0}", article.Id);

            IHtmlControl redoPanel = null;

            if (state.BlockHint == blockHint)
            {
                IHtmlControl deletePanel = null;
                if (state.ModeratorMode)
                {
                    deletePanel = ViewNewsHlp.DeleteTopicPanel(state, topic);
                }

                redoPanel = new HPanel(
                    deletePanel,
                    new HPanel(
                        Decor.PropertyEdit("editArticleTitle", "Заголовок статьи", article.Get(NewsType.Title)),
                        new HPanel(
                            new HLabel("Аннотация").FontBold(),
                            new HTextArea("editArticleAnnotation", article.Get(NewsType.Annotation))
                            .Width("100%").Height("4em").MarginBottom(5)
                            ),
                        new HPanel(
                            new HInputCheck(
                                "editArticleWideContent", article.Get(ArticleType.WideContent),
                                new HAfter().Content("Таблицы шире колонки статьи").MarginLeft(18).MarginBottom(1)
                                ).NoWrap()
                            ).MarginBottom(5),
                        HtmlHlp.CKEditorCreate("editArticleText", article.Get(NewsType.Text), "300px", true),
                        Decor.PropertyEdit("editArticleAuthor", "Автор", article.Get(ArticleType.Author)),
                        Decor.PropertyEdit("editArticleOriginName", "Источник (без префикса http://)", article.Get(NewsType.OriginName)),
                        Decor.PropertyEdit("editArticleOriginUrl", "Ссылка (с префиксом http://)", article.Get(NewsType.OriginUrl)),
                        Decor.Button("Сохранить статью").CKEditorOnUpdateAll().MarginTop(10).MarginBottom(10)
                        .Event("save_article_edit", "editArticleData",
                               delegate(JsonData json)
                {
                    string title      = json.GetText("editArticleTitle");
                    string annotation = json.GetText("editArticleAnnotation");
                    bool wideContent  = json.GetBool("editArticleWideContent");
                    string text       = json.GetText("editArticleText");
                    string author     = json.GetText("editArticleAuthor");
                    string originName = json.GetText("editArticleOriginName");
                    string originUrl  = json.GetText("editArticleOriginUrl");

                    WebOperation operation = state.Operation;

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

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

                    LightObject editNews = DataBox.LoadObject(context.FabricConnection, ArticleType.Article, article.Id);

                    editNews.SetWithoutCheck(NewsType.Title, title);

                    editNews.Set(ArticleType.WideContent, wideContent);
                    editNews.Set(NewsType.Annotation, annotation);
                    editNews.Set(NewsType.Text, text);
                    editNews.Set(ArticleType.Author, author);
                    editNews.Set(NewsType.OriginName, originName);
                    editNews.Set(NewsType.OriginUrl, originUrl);

                    editNews.Set(ObjectType.ActTill, DateTime.UtcNow);

                    editNews.Box.Update();

                    context.UpdateArticles();
                    context.ArticleStorages.ForTopic(article.Id).UpdateTopic();

                    state.BlockHint = "";
                },
                               article.Id
                               )
                        ).EditContainer("editArticleData"),
                    new HPanel(
                        EditElementHlp.GetImageThumb(article.Id)
                        ),
                    new HPanel(
                        EditElementHlp.GetDescriptionImagesPanel(state.Option, article.Id)
                        )
                    ).Padding(5, 10).MarginTop(10).Background(Decor.pageBackground);
            }

            return(new HPanel(
                       Decor.Button("Редактировать")
                       .Event("article_edit", "", delegate
            {
                state.SetBlockHint(blockHint);
            }
                              ),
                       redoPanel
                       ).MarginTop(5));
        }
Ejemplo n.º 24
0
        static IHtmlControl GetNewsEditPanel(SiteState state, TopicStorage topic)
        {
            LightObject news = topic.Topic;

            string blockHint = string.Format("news_edit_{0}", news.Id);

            IHtmlControl redoPanel = null;

            if (state.BlockHint == blockHint)
            {
                IHtmlControl deletePanel = null;
                if (state.ModeratorMode)
                {
                    deletePanel = DeleteTopicPanel(state, topic);
                }

                if (state.Tag == null)
                {
                    state.Tag = ViewTagHlp.GetTopicDisplayTags(context.Tags.TagBox, topic.Topic);
                }

                redoPanel = new HPanel(
                    deletePanel,
                    Decor.PropertyEdit("newsTitle", "Заголовок новости", news.Get(NewsType.Title)),
                    new HPanel(
                        HtmlHlp.CKEditorCreate("newsText", news.Get(NewsType.Text), "300px", true)
                        ),
                    ViewTagHlp.GetEditTagsPanel(state, context.Tags.TagBox, state.Tag as List <string>, false),
                    Decor.PropertyEdit("newsOriginName", "Источник", news.Get(NewsType.OriginName)),
                    Decor.PropertyEdit("newsOriginUrl", "Ссылка", news.Get(NewsType.OriginUrl)),
                    Decor.Button("Изменить новость").CKEditorOnUpdateAll().MarginTop(10)
                    .Event("save_news_edit", "editNewsData",
                           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;
                    }

                    LightKin editNews = DataBox.LoadKin(context.FabricConnection, NewsType.News, news.Id);

                    editNews.SetWithoutCheck(NewsType.Title, title);

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

                    editNews.Set(ObjectType.ActTill, DateTime.UtcNow);

                    ViewTagHlp.SaveTags(context, state, editNews);

                    editNews.Box.Update();

                    context.UpdateNews();
                    context.NewsStorages.ForTopic(news.Id).UpdateTopic();

                    state.BlockHint = "";
                },
                           news.Id
                           )
                    ).EditContainer("editNewsData")
                            .Padding(5, 10).MarginTop(10).Background(Decor.pageBackground);
            }

            return(new HPanel(
                       Decor.Button("Редактировать")
                       .Event("news_edit", "", delegate
            {
                state.SetBlockHint(blockHint);
            }
                              ),
                       redoPanel
                       ).MarginTop(10));
        }
Ejemplo n.º 25
0
        public static IHtmlControl GetCorrespondenceView(SiteState state,
                                                         IDataLayer forumConnection, LightObject user, LightObject collocutor, out string title)
        {
            title = "Личные сообщения";

            int pageIndex    = state.Option.Get(OptionType.CorrespondencePageIndex);
            int messageCount = DatabaseHlp.RowCount(forumConnection, "", "correspondence",
                                                    "user_id = @userId and collocutor_id = @collocutorId",
                                                    new DbParameter("userId", user.Id), new DbParameter("collocutorId", collocutor.Id)
                                                    );
            int pageCount = BinaryHlp.RoundUp(messageCount, 5);

            HButton prevButton = null;

            if (pageCount - 1 > pageIndex)
            {
                prevButton = Decor.ButtonMidi("предыдущие").Event("page_prev", "",
                                                                  delegate
                {
                    state.Option.Set(OptionType.CorrespondencePageIndex, pageIndex + 1);
                }
                                                                  );
            }

            HButton nextButton = null;

            if (pageIndex > 0)
            {
                nextButton = Decor.ButtonMidi("следующие").Event("page_next", "",
                                                                 delegate
                {
                    state.Option.Set(OptionType.CorrespondencePageIndex, pageIndex - 1);
                }
                                                                 );
            }

            TableLink messageLink = DialogueHlp.LoadCorrespondenceLink(forumConnection,
                                                                       string.Format("user_id = @userId and collocutor_id = @collocutorId order by create_time desc limit 5 offset {0}",
                                                                                     pageIndex * 5
                                                                                     ),
                                                                       new DbParameter("userId", user.Id), new DbParameter("collocutorId", collocutor.Id)
                                                                       );

            RowLink[]           messages      = messageLink.AllRows;
            List <IHtmlControl> messageBlocks = new List <IHtmlControl>();

            if (prevButton != null || nextButton != null)
            {
                messageBlocks.Add(
                    new HPanel(
                        new HPanel(prevButton), new HPanel(nextButton)
                        ).MarginTop(5).MarginBottom(5)
                    );
            }

            for (int i = messages.Length - 1; i >= 0; --i)
            {
                //if (i == 2)
                //  messageBlocks.Add(new HAnchor("bottom"));

                messageBlocks.Add(GetMessageBlock(forumConnection, state, user, collocutor, messages[i], i));
            }

            IHtmlControl addPanel = GetAddPanel(context, state, user, collocutor, false);

            return(new HPanel(
                       GetCorrespondenceHeader(state, user, collocutor),
                       new HPanel(
                           messageBlocks.ToArray()
                           ).BorderBottom(Decor.bottomBorder),
                       addPanel
                       ));
        }
Ejemplo n.º 26
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));
        }
Ejemplo n.º 27
0
        public static IHtmlControl GetUserView(SiteState state, LightObject currentUser, LightObject user)
        {
            string communityMember = user.Get(BasketballUserType.CommunityMember);

            bool     isModerator     = user.Get(BasketballUserType.IsModerator);
            DateTime?bannedUntil     = user.Get(BasketballUserType.BannedUntil);
            DateTime?noRedactorUntil = user.Get(BasketballUserType.NotRedactorUntil);
            string   bannedUntilStr  = "";

            if (bannedUntil != null && bannedUntil > DateTime.UtcNow)
            {
                bannedUntilStr = bannedUntil.Value.ToLocalTime().ToString(Decor.timeFormat);
            }
            string noRedactorUntilStr = "";

            if (noRedactorUntil != null && noRedactorUntil > DateTime.UtcNow)
            {
                noRedactorUntilStr = noRedactorUntil.Value.ToLocalTime().ToString(Decor.timeFormat);
            }

            IHtmlControl[] rows = new IHtmlControl[] {
                UserField("Имя", ValueLabel(user.Get(UserType.FirstName)).FontBold()),
                UserField("Дата регистрации",
                          ValueLabel(user.Get(ObjectType.ActFrom)?.ToLocalTime().ToString(Decor.timeFormat))
                          ),
                !StringHlp.IsEmpty(communityMember) ? UserField("На basketball.ru c", ValueLabel(communityMember)) : null,
                UserField("Страна", ValueLabel(user.Get(BasketballUserType.Country))),
                UserField("Город", ValueLabel(user.Get(BasketballUserType.City))),
                UserField("Интересы", ValueLabel(user.Get(BasketballUserType.Interests))),
                UserField("О себе", ValueLabel(user.Get(BasketballUserType.AboutMe))),
                UserField("Статус", ValueLabel("Модератор").FontBold()).Hide(!isModerator),
                UserField("Заблокирован до", ValueLabel(bannedUntilStr).FontBold()).Hide(StringHlp.IsEmpty(bannedUntilStr)),
                UserField("Не добавляет до", ValueLabel(noRedactorUntilStr).FontBold()).Hide(StringHlp.IsEmpty(noRedactorUntilStr))
            };

            int i = -1;

            foreach (IHtmlControl row in rows)
            {
                if (row == null)
                {
                    continue;
                }

                ++i;
                if (i % 2 == 0)
                {
                    row.Background(Decor.pageBackground);
                }
            }

            IHtmlControl redoAvatarPanel = null;
            IHtmlControl editPanel       = null;

            if (currentUser != null && currentUser.Id == user.Id)
            {
                redoAvatarPanel = GetRedoAvatarPanel(user);
                editPanel       = GetUserEditPanel(state, user);
            }

            IHtmlControl adminPanel = null;

            if (state.EditMode)
            {
                adminPanel = GetAdminPanel(user);
            }

            IHtmlControl moderatorPanel = null;

            if (state.ModeratorMode)
            {
                moderatorPanel = GetModeratorPanel(user);
            }

            return(new HPanel(
                       Decor.Title(user.Get(UserType.Login)),
                       new HPanel(
                           AvatarBlock(user).PositionAbsolute().Left(12).Top("50%").MarginTop(-25),
                           new HPanel(
                               rows
                               ).Padding(1).Border("1px solid #eeeeee")
                           ).PositionRelative().BoxSizing().WidthLimit("", "480px").PaddingLeft(74),
                       ViewDialogueHlp.GetAddPanel(context, state, currentUser, user, true),
                       redoAvatarPanel,
                       editPanel,
                       adminPanel,
                       moderatorPanel
                       ));
        }
Ejemplo n.º 28
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
                       ));
        }
Ejemplo n.º 29
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));
        }
Ejemplo n.º 30
0
        public static IHtmlControl GetRestorePasswordView(SiteState state)
        {
            return(new HPanel(
                       Decor.Title("Восстановление пароля"),
                       Decor.AuthEdit("login", "Введите логин:"),
                       Decor.AuthEdit("email", "Или E-mail:"),
                       new HPanel(
                           Decor.Button("Выслать пароль на почту").Event("user_restore", "restoreData",
                                                                         delegate(JsonData json)
            {
                string login = json.GetText("login");
                string email = json.GetText("email");

                WebOperation operation = state.Operation;

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

                LightObject findUser = null;
                if (!StringHlp.IsEmpty(login))
                {
                    string xmlLogin = UserType.Login.CreateXmlIds("", login);
                    findUser = context.UserStorage.FindUser(xmlLogin);
                }
                else
                {
                    foreach (LightObject user in context.UserStorage.All)
                    {
                        if (user.Get(BasketballUserType.Email) == email)
                        {
                            findUser = user;
                            break;
                        }
                    }
                }

                if (!operation.Validate(findUser == null, "Пользователь не найден"))
                {
                    return;
                }

                try
                {
                    HElement answer = h.Div(
                        h.P(string.Format("Ваш логин: {0}", findUser.Get(BasketballUserType.Login))),
                        h.P(string.Format("Ваш пароль: {0}", findUser.Get(BasketballUserType.Password)))
                        );

                    SiteSettings settings = SiteContext.Default.SiteSettings;
                    SmtpClient smtpClient = AuthHlp.CreateSmtpClient(
                        settings.SmtpHost, settings.SmtpPort, settings.SmtpUserName, settings.SmtpPassword);
                    AuthHlp.SendMail(smtpClient, settings.MailFrom, findUser.Get(BasketballUserType.Email),
                                     "Восстановление пароля", answer.ToHtmlText()
                                     );
                }
                catch (Exception ex)
                {
                    Logger.WriteException(ex);

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

                operation.Message = "Пароль выслан вам на почту";
            }
                                                                         )
                           )
                       ).EditContainer("restoreData"));
        }