public TagStore(ObjectHeadBox tagBox) { this.TagBox = tagBox; foreach (int tagId in tagBox.AllObjectIds) { string tagName = TagType.DisplayName.Get(tagBox, tagId); if (StringHlp.IsEmpty(tagName)) { continue; } string tagKey = tagName.ToLower(); TagIdByKey[tagKey] = tagId; } foreach (string key in TagIdByKey.Keys) { int tagId = TagIdByKey[key]; string[] words = key.Split(new char[] { ' ', ',', '-' }, StringSplitOptions.RemoveEmptyEntries); foreach (string word in words) { List <int> ids; if (!tagIdsByWord.TryGetValue(word, out ids)) { ids = new List <int>(); tagIdsByWord[word] = ids; } ids.Add(tagId); } } }
public int[] SearchByTags(IDataLayer fabricConnection, string searchQuery) { if (StringHlp.IsEmpty(searchQuery)) { return(new int[0]); } searchQuery = searchQuery.ToLower(); string[] words = searchQuery.Split(new char[] { ' ', ',', '-' }, StringSplitOptions.RemoveEmptyEntries); if (words.Length == 0) { return(new int[0]); } //IEnumerable<int> tagIds = DictionaryHlp.GetValueOrDefault(tagIdsByWord, words[0]); //if (tagIds == null) // return new int[0]; IEnumerable <int> intersectTagIds = null; foreach (string word in words) { IEnumerable <int> tagIds = DictionaryHlp.GetValueOrDefault(tagIdsByWord, word); if (tagIds == null) { return(new int[0]); } if (intersectTagIds == null) { intersectTagIds = tagIds; } else { intersectTagIds = intersectTagIds.Intersect(tagIds); } } List <Tuple <int, int> > tagIdsWithNewsCount = new List <Tuple <int, int> >(); foreach (int tagId in intersectTagIds) { int[] newsIds = ViewTagHlp.GetNewsIdsForTag(fabricConnection, tagId); if (newsIds.Length > 0) { tagIdsWithNewsCount.Add(new Tuple <int, int>(tagId, newsIds.Length)); } } return(_.SortBy(tagIdsWithNewsCount, delegate(Tuple <int, int> tag) { return tag.Item2; }).Select(ti => ti.Item1).Reverse().ToArray()); }
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) )); }
static HLabel ValueLabel(string value) { if (StringHlp.IsEmpty(value)) { value = "не указано"; } HLabel valueLabel = new HLabel(value); if (StringHlp.IsEmpty(value)) { valueLabel.Color(Decor.minorColor); } return(valueLabel); }
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 )); }
public static string GetDescriptionForNews(LightObject topic) { try { string text = topic.Get(NewsType.Text); if (StringHlp.IsEmpty(text)) { return(""); } int[] endIndices = new int[] { text.IndexOf("</p>"), text.IndexOf("</h3>"), text.IndexOf("<br") }; int endIndex = -1; foreach (int index in endIndices) { if (index < 0) { continue; } if (endIndex < 0 || index < endIndex) { endIndex = index; } } //if (topic.Id == 102001) //{ // Logger.AddMessage("EndIndices: {0}, {1}, {2}, {3}", text, endIndices[0], endIndices[1], endIndices[2]); //} if (endIndex < 0) { return(""); } StringBuilder builder = new StringBuilder(); string rawDescription = text.Substring(0, endIndex); bool openBracket = false; int currentIndex = 0; while (currentIndex < rawDescription.Length) { int startIndex = currentIndex; if (openBracket) { openBracket = false; currentIndex = rawDescription.IndexOf('>', currentIndex) + 1; if (currentIndex == 0) { break; } continue; } openBracket = true; currentIndex = rawDescription.IndexOf('<', currentIndex); if (currentIndex < 0) { currentIndex = rawDescription.Length; } builder.Append(rawDescription.Substring(startIndex, currentIndex - startIndex).Trim('\n')); continue; } string description = builder.ToString(); return(description.Replace("«", "«").Replace("»", "»") .Replace(""", "").Replace(" ", " ")); } catch (Exception ex) { Logger.WriteException(ex, "TopicId: {0}", topic?.Id); return(""); } //return text.Substring(startIndex + 3, endIndex - startIndex - 3).Replace("«", "«").Replace("»", "»"); }
public static string PreViewComment(string content) { try { if (StringHlp.IsEmpty(content)) { return(""); } LinkInfo[] links = GetLinks(content); if (links.Length > 0) { StringBuilder builder = new StringBuilder(); if (links[0].Index > 0) { builder.Append(content.Substring(0, links[0].Index)); } for (int i = 0; i < links.Length; ++i) { LinkInfo link = links[i]; if (!link.IsImage) { string display = link.Value; if (display.StartsWith(httpPrefix)) { display = display.Substring(httpPrefix.Length); } else if (display.StartsWith(httpsPrefix)) { display = display.Substring(httpsPrefix.Length); } if (display.Length > 50) { display = display.Substring(0, 50); } builder.AppendFormat(linkFormat, link.Value, display); } else { builder.AppendFormat(imageFormat, link.Value); } int startIndex = link.Index + link.Value.Length; int endIndex = content.Length; if (i + 1 < links.Length) { endIndex = links[i + 1].Index; } if (endIndex > startIndex) { builder.Append(content.Substring(startIndex, endIndex - startIndex)); } } content = builder.ToString(); } content = content.Replace("\n", "<br>"); content = content.Replace(":)", Smiley.Smile); content = content.Replace(":(", Smiley.Sad); content = content.Replace(" :/", Smiley.Blah); content = content.Replace(" ;)", Smiley.Wink); return(content); } catch (Exception ex) { Logger.WriteException(ex); return(content); } }
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 )); }
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")); }
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)); }
public static Func <object, JsonData[], HttpRequestMessage, HtmlResult <HElement> > HViewCreator( string kind, int?id) { return(delegate(object _state, JsonData[] jsons, HttpRequestMessage context) { SiteState state = _state as SiteState; if (state == null) { state = new SiteState(); } LinkInfo link = null; if (kind == "news" || kind == "user" || (kind == "novosti" && id != null) || kind == "article" || kind == "topic" || kind == "tags" || kind == "dialog" || kind == "confirmation") { link = new LinkInfo("", kind, id); } else { if (StringHlp.IsEmpty(kind)) { link = new LinkInfo("", "", null); } else if (id == null) { link = store.Links.FindLink(kind, ""); if (link == null) { link = store.Links.FindLink("page", kind); } } } if (link == null) { return new HtmlResult { RawResponse = new HttpResponseMessage() { StatusCode = HttpStatusCode.NotFound } }; } if (jsons.Length > 0) { state.AccessTime = DateTime.UtcNow; } foreach (JsonData json in jsons) { try { if (state.IsRattling(json)) { continue; } try { string command = json.JPath("data", "command")?.ToString(); if (command != null && StringHlp.IsEmpty(state.BlockHint)) { if (command.StartsWith("save_")) { object id1 = json.JPath("data", "id1"); string hint = command.Substring(5); if (id != null) { hint = string.Format("{0}_{1}", hint, id1); } state.BlockHint = hint; Logger.AddMessage("Restore: {0}", hint); } else if (command == "tag_add" && kind == "") { state.BlockHint = "news_add"; Logger.AddMessage("Restore: news_add"); } } } catch (Exception ex) { Logger.WriteException(ex); } state.Operation.Reset(); HElement cachePage = Page(HttpContext.Current, state, link.Kind, link.Id); hevent eventh = cachePage.FindEvent(json, true); if (eventh != null) { eventh.Execute(json); } } catch (Exception ex) { Logger.WriteException(ex); state.Operation.Message = string.Format("Непредвиденная ошибка: {0}", ex.Message); } } HElement page = Page(HttpContext.Current, state, link.Kind, link.Id); if (page == null) { return new HtmlResult { RawResponse = new HttpResponseMessage() { StatusCode = HttpStatusCode.NotFound } }; } return HtmlHlp.FirstHtmlResult(page, state, TimeSpan.FromHours(1)); }); }
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), ) )); }
public static IHtmlControl[] GetArticleItems(SiteState state, IEnumerable <LightObject> articleList) { List <IHtmlControl> items = new List <IHtmlControl>(); foreach (LightObject article in articleList) { DateTime localTime = (article.Get(ObjectType.ActFrom) ?? DateTime.UtcNow).ToLocalTime(); int commentCount = context.ArticleStorages.ForTopic(article.Id).MessageLink.AllRows.Length; string articleUrl = UrlHlp.ShopUrl("article", article.Id); string imageUrl = UrlHlp.ImageUrl(article.Id, false); string author = article.Get(ArticleType.Author); string annotationWithLink = string.Format( "{0} <a href='{1}'><img src='/images/full.gif'></img></a>", article.Get(ArticleType.Annotation), articleUrl ); items.Add( new HPanel( new HPanel( new HLink(articleUrl, article.Get(NewsType.Title) ).FontSize("14.4px").FontBold(), ViewNewsHlp.GetCommentElement(commentCount, articleUrl) ).FontSize("90%"), new HXPanel( new HPanel( new HPanel().InlineBlock().Size(Decor.ArticleThumbWidth, Decor.ArticleThumbHeight) .Background(imageUrl, "no-repeat", "center").CssAttribute("background-size", "100%") .MarginTop(2).MarginBottom(5) ), new HPanel( new HPanel( new HLabel(string.Format("{0},", author)).MarginRight(5).Hide(StringHlp.IsEmpty(author)), new HLabel(article.Get(ArticleType.OriginName)), new HLabel("//").MarginLeft(5).MarginRight(5), new HLabel(localTime.ToString("dd MMMM yyyy")) ).FontSize("90%").MarginBottom(7).MarginTop(2), new HTextView( annotationWithLink ) ).PaddingLeft(20) ) ).Padding(1).BorderBottom("1px solid #e0dede").MarginBottom(5) ); } return(items.ToArray()); }
public static void SaveTags(BasketballContext context, SiteState state, LightParent editTopic) { List <string> tags = state.Tag as List <string>; if (tags == null) { return; } ObjectHeadBox editBox = null; List <int> tagIds = new List <int>(); foreach (string tag in tags) { if (StringHlp.IsEmpty(tag)) { continue; } string tagKey = tag.ToLower(); { int tagId; if (context.TagIdByKey.TryGetValue(tagKey, out tagId)) { tagIds.Add(tagId); continue; } } string xmlIds = TagType.DisplayName.CreateXmlIds(tag); //RowLink tagRow = context.Tags.ObjectByXmlIds.AnyRow(xmlIds); //if (tagRow != null) //{ // tagIds.Add(tagRow.Get(ObjectType.ObjectId)); // continue; //} if (editBox == null) { editBox = new ObjectHeadBox(context.FabricConnection, "1=0"); } int?newTagId = editBox.CreateUniqueObject(TagType.Tag, xmlIds, null); if (newTagId == null) { continue; } tagIds.Add(newTagId.Value); } if (editBox != null) { editBox.Update(); context.UpdateTags(); } for (int i = 0; i < tagIds.Count; ++i) { int tagId = tagIds[i]; if (tagId != editTopic.GetChildId(TopicType.TagLinks, i)) { editTopic.SetChildId(TopicType.TagLinks, i, tagId); } } RowLink[] allTagRows = editTopic.AllChildRows(TopicType.TagLinks); for (int i = allTagRows.Length - 1; i >= tagIds.Count; --i) { editTopic.RemoveChildLink(TopicType.TagLinks, i); } }
public static IHtmlControl GetCenter(HttpContext httpContext, SiteState state, LightObject currentUser, string kind, int?id, out string title, out string description, out SchemaOrg schema, out bool wideContent) { title = ""; description = ""; schema = null; wideContent = false; SiteSettings settings = context.SiteSettings; switch (kind) { case "": { title = store.SEO.Get(SEOType.MainTitle); description = store.SEO.Get(SEOType.MainDescription); LightSection main = store.Sections.FindMenu("main"); return(ViewHlp.GetMainView(state, currentUser)); } case "news": { if (!context.News.ObjectById.Exist(id)) { return(null); } TopicStorage topicStorage = context.NewsStorages.ForTopic(id ?? 0); LightKin topic = topicStorage.Topic; //string tagsDisplay; IHtmlControl view = ViewNewsHlp.GetNewsView(state, currentUser, topicStorage, out description); title = topic.Get(NewsType.Title); //string postfix = ""; //if (!StringHlp.IsEmpty(tagsDisplay)) // postfix = ". "; //description = string.Format("{0}{1}Живое обсуждение баскетбольных событий на basketball.ru.com", // tagsDisplay, postfix //); string logoUrl = settings.FullUrl("/images/logo.gif"); schema = new SchemaOrg("NewsArticle", settings.FullUrl(UrlHlp.ShopUrl("news", id)), title, new string[] { logoUrl }, topic.Get(ObjectType.ActFrom), topic.Get(ObjectType.ActTill), topic.Get(TopicType.OriginName), settings.Organization, logoUrl, description ); return(view); } case "article": { if (!context.Articles.ObjectById.Exist(id)) { return(null); } TopicStorage topicStorage = context.ArticleStorages.ForTopic(id ?? 0); LightKin topic = topicStorage.Topic; title = topic.Get(ArticleType.Title); description = topic.Get(ArticleType.Annotation); string logoUrl = settings.FullUrl("/images/logo.gif"); schema = new SchemaOrg("Article", settings.FullUrl(UrlHlp.ShopUrl("article", id)), title, new string[] { logoUrl }, topic.Get(ObjectType.ActFrom), topic.Get(ObjectType.ActTill), topic.Get(TopicType.OriginName), settings.Organization, logoUrl, description ); wideContent = topic.Get(ArticleType.WideContent); return(ViewArticleHlp.GetArticleView(state, currentUser, topicStorage)); } case "topic": { TopicStorage topic = context.Forum.TopicsStorages.ForTopic(id ?? 0); title = topic.Topic.Get(TopicType.Title); int pageNumber = 0; { string pageArg = httpContext.Get("page"); int messageCount = topic.MessageLink.AllRows.Length; if (pageArg == "last" && messageCount > 0) { pageNumber = BinaryHlp.RoundUp(messageCount, ViewForumHlp.forumMessageCountOnPage) - 1; } else { pageNumber = ConvertHlp.ToInt(pageArg) ?? 0; } } return(ViewForumHlp.GetTopicView(state, currentUser, topic, pageNumber)); } case "tags": { int?tagId = httpContext.GetUInt("tag"); int pageNumber = httpContext.GetUInt("page") ?? 0; return(ViewNewsHlp.GetTagView(state, currentUser, tagId, pageNumber, out title, out description)); } case "search": { return(ViewNewsHlp.GetFoundTagListView(state, out title)); } case "user": { LightObject user = context.UserStorage.FindUser(id ?? -1); if (user == null) { return(null); } title = string.Format("{0} - Basketball.ru.com", user.Get(UserType.Login)); return(ViewUserHlp.GetUserView(state, currentUser, user)); } case "page": { LightSection section = store.Sections.FindSection(id); title = FabricHlp.GetSeoTitle(section, section.Get(SectionType.Title)); description = FabricHlp.GetSeoDescription(section, section.Get(SectionType.Annotation)); int pageNumber = httpContext.GetUInt("page") ?? 0; string designKind = section.Get(SectionType.DesignKind); switch (designKind) { case "news": { int[] allNewsIds = context.News.AllObjectIds; return(ViewNewsHlp.GetNewsListView(state, currentUser, pageNumber)); } case "articles": return(ViewArticleHlp.GetArticleListView(state, currentUser, pageNumber)); case "forum": return(ViewForumHlp.GetForumView(state, currentUser, section)); case "forumSection": return(ViewForumHlp.GetForumSectionView(state, currentUser, section)); default: return(null); } } case "dialog": { if (currentUser == null) { return(null); } if (id == null) { return(ViewDialogueHlp.GetDialogueView(state, context.ForumConnection, context.UserStorage, currentUser, out title )); } LightObject collocutor = context.UserStorage.FindUser(id.Value); if (collocutor == null) { return(null); } return(ViewDialogueHlp.GetCorrespondenceView(state, context.ForumConnection, currentUser, collocutor, out title )); } case "passwordreset": title = "Восстановление пароля - basketball.ru.com"; return(ViewHlp.GetRestorePasswordView(state)); case "register": title = "Регистрация - basketball.ru.com"; return(ViewHlp.GetRegisterView(state)); case "confirmation": { title = "Подтверждение аккаунта"; int? userId = httpContext.GetUInt("id"); string hash = httpContext.Get("hash"); if (userId == null) { return(ViewUserHlp.GetMessageView( "Вам выслано письмо с кодом активации. Чтобы завершить процедуру регистрации, пройдите по ссылке, указанной в письме, и учётная запись будет активирована. Если вы не получили письмо, то попробуйте войти на сайт со своим логином и паролем. Тогда письмо будет отправлено повторно." )); } if (StringHlp.IsEmpty(hash)) { return(null); } LightObject user = context.UserStorage.FindUser(userId.Value); if (userId == null) { return(null); } if (!user.Get(UserType.NotConfirmed)) { return(ViewUserHlp.GetMessageView("Пользователь успешно активирован")); } string login = user.Get(UserType.Login); string etalon = UserHlp.CalcConfirmationCode(user.Id, login, "bbbin"); if (hash?.ToLower() != etalon?.ToLower()) { return(ViewUserHlp.GetMessageView("Неверный хэш")); } LightObject editUser = DataBox.LoadObject(context.UserConnection, UserType.User, user.Id); editUser.Set(UserType.NotConfirmed, false); editUser.Box.Update(); context.UserStorage.Update(); string xmlLogin = UserType.Login.CreateXmlIds("", login); HttpContext.Current.SetUserAndCookie(xmlLogin); state.RedirectUrl = "/"; return(new HPanel()); } } return(null); }
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)); }
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")); }