/// <summary> /// Handles the ItemCommand event of the UserList control. /// </summary> /// <param name="source">The source of the event.</param> /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterCommandEventArgs"/> instance containing the event data.</param> public void UserListItemCommand([NotNull] object source, [NotNull] RepeaterCommandEventArgs e) { switch (e.CommandName) { case "edit": BuildLink.Redirect(ForumPages.Admin_EditUser, "u={0}", e.CommandArgument); break; case "resendEmail": var commandArgument = e.CommandArgument.ToString().Split(';'); var checkMail = this.GetRepository <CheckEmail>().ListTyped(commandArgument[0]).FirstOrDefault(); if (checkMail != null) { var verifyEmail = new TemplateEmail("VERIFYEMAIL"); var subject = this.Get <ILocalization>() .GetTextFormatted("VERIFICATION_EMAIL_SUBJECT", this.Get <BoardSettings>().Name); verifyEmail.TemplateParams["{link}"] = BuildLink.GetLink( ForumPages.Account_Approve, true, "code={0}", checkMail.Hash); verifyEmail.TemplateParams["{key}"] = checkMail.Hash; verifyEmail.TemplateParams["{forumname}"] = this.Get <BoardSettings>().Name; verifyEmail.TemplateParams["{forumlink}"] = BoardInfo.ForumURL; verifyEmail.SendEmail(new MailAddress(checkMail.Email, commandArgument[1]), subject); this.PageContext.AddLoadMessage( this.GetText("ADMIN_ADMIN", "MSG_MESSAGE_SEND"), MessageTypes.success); } else { var userFound = this.Get <IUserDisplayName>().FindUserContainsName(commandArgument[1]).FirstOrDefault(); var user = this.Get <IAspNetUsersHelper>().GetUserByName(userFound.Name); this.Get <ISendNotification>().SendVerificationEmail(user, commandArgument[0], userFound.ID); } break; case "delete": if (!Config.IsAnyPortal) { this.Get <IAspNetUsersHelper>().DeleteUser(e.CommandArgument.ToType <int>()); } this.GetRepository <User>().Delete(e.CommandArgument.ToType <int>()); this.BindData(); break; case "approve": this.Get <IAspNetUsersHelper>().ApproveUser(e.CommandArgument.ToType <int>()); this.BindData(); break; case "deleteall": // vzrus: Should not delete the whole providers portal data? Under investigation. var daysValueAll = this.PageContext.CurrentForumPage.FindControlRecursiveAs <TextBox>("DaysOld").Text.Trim(); if (!ValidationHelper.IsValidInt(daysValueAll)) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_ADMIN", "MSG_VALID_DAYS"), MessageTypes.warning); return; } if (!Config.IsAnyPortal) { this.Get <IAspNetUsersHelper>().DeleteAllUnapproved(System.DateTime.UtcNow.AddDays(-daysValueAll.ToType <int>())); } else { this.GetRepository <User>().DeleteOld(this.PageContext.PageBoardID, daysValueAll.ToType <int>()); } this.BindData(); break; case "approveall": this.Get <IAspNetUsersHelper>().ApproveAll(); // vzrus: Should delete users from send email list this.GetRepository <User>().ApproveAll(this.PageContext.PageBoardID); this.BindData(); break; } }
/// <summary> /// Render the Main Header Menu Links /// </summary> private void RenderMainHeaderMenu() { // Search if (this.Get <IPermissions>().Check(this.Get <BoardSettings>().SearchPermissions)) { RenderMenuItem( this.menuListItems, "nav-link", this.GetText("TOOLBAR", "SEARCH"), "SEARCH_TITLE", BuildLink.GetLink(ForumPages.Search), false, false, null, null, this.PageContext.ForumPageType == ForumPages.Search, string.Empty); } // Members if (this.Get <IPermissions>().Check(this.Get <BoardSettings>().MembersListViewPermissions)) { RenderMenuItem( this.menuListItems, "nav-link", this.GetText("TOOLBAR", "MEMBERS"), "MEMBERS_TITLE", BuildLink.GetLink(ForumPages.Members), false, false, null, null, this.PageContext.ForumPageType == ForumPages.Members, string.Empty); } // Team if (this.Get <IPermissions>().Check(this.Get <BoardSettings>().ShowTeamTo)) { RenderMenuItem( this.menuListItems, "nav-link", this.GetText("TOOLBAR", "TEAM"), "TEAM_TITLE", BuildLink.GetLink(ForumPages.Team), false, false, null, null, this.PageContext.ForumPageType == ForumPages.Team, string.Empty); } // Help if (this.Get <IPermissions>().Check(this.Get <BoardSettings>().ShowHelpTo)) { RenderMenuItem( this.menuListItems, "nav-link", this.GetText("TOOLBAR", "HELP"), "HELP_TITLE", BuildLink.GetLink(ForumPages.Help), false, false, null, null, this.PageContext.ForumPageType == ForumPages.Help, string.Empty); } if (!this.PageContext.IsGuest || Config.IsAnyPortal) { return; } // Login if (Config.AllowLoginAndLogoff) { RenderMenuItem( this.menuListItems, "nav-link LoginLink", this.GetText("TOOLBAR", "LOGIN"), "LOGIN_TITLE", "javascript:void(0);", true, false, null, null, false, string.Empty); } // Register if (!this.Get <BoardSettings>().DisableRegistrations) { RenderMenuItem( this.menuListItems, "nav-link", this.GetText("TOOLBAR", "REGISTER"), "REGISTER_TITLE", this.Get <BoardSettings>().ShowRulesForRegistration ? BuildLink.GetLink(ForumPages.RulesAndPrivacy) : !this.Get <BoardSettings>().UseSSLToRegister ? BuildLink.GetLink(ForumPages.Register) : BuildLink.GetLink(ForumPages.Register, true).Replace("http:", "https:"), true, false, null, null, this.PageContext.ForumPageType == ForumPages.Register, string.Empty); } }
/// <summary> /// Create user /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void RegisterClick(object sender, EventArgs e) { if (!this.Page.IsValid) { return; } if (!this.ValidateUser()) { return; } var user = new AspNetUsers { Id = Guid.NewGuid().ToString(), ApplicationId = this.Get <BoardSettings>().ApplicationId, UserName = this.UserName.Text, LoweredUserName = this.UserName.Text, Email = this.Email.Text, IsApproved = false, EmailConfirmed = false }; var result = this.Get <IAspNetUsersHelper>().Create(user, this.Password.Text.Trim()); if (!result.Succeeded) { // error of some kind this.PageContext.AddLoadMessage(result.Errors.FirstOrDefault(), MessageTypes.danger); } else { // setup initial roles (if any) for this user AspNetRolesHelper.SetupUserRoles(this.PageContext.PageBoardID, user); var displayName = this.DisplayName.Text; // create the user in the YAF DB as well as sync roles... var userID = AspNetRolesHelper.CreateForumUser(user, displayName, this.PageContext.PageBoardID); if (userID == null) { // something is seriously wrong here -- redirect to failure... BuildLink.RedirectInfoPage(InfoMessage.Failure); } if (this.IsPossibleSpamBot) { if (this.Get <BoardSettings>().BotHandlingOnRegister.Equals(1)) { this.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value); } } else { // handle e-mail verification var email = this.Email.Text.Trim(); this.Get <ISendNotification>().SendVerificationEmail(user, email, userID); if (this.Get <BoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... this.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } } this.BodyRegister.Visible = false; this.Footer.Visible = false; // success notification localization this.Message.Visible = true; this.AccountCreated.Text = this.Get <IBBCode>().MakeHtml( this.GetText("ACCOUNT_CREATED_VERIFICATION"), true, true); } }
/// <summary> /// Sends Notifications to Moderators that a Message was Reported /// </summary> /// <param name="pageForumID"> /// The page Forum ID. /// </param> /// <param name="reportedMessageId"> /// The reported message id. /// </param> /// <param name="reporter"> /// The reporter. /// </param> /// <param name="reportText"> /// The report Text. /// </param> public void ToModeratorsThatMessageWasReported( int pageForumID, int reportedMessageId, int reporter, string reportText) { try { var moderatorsFiltered = this.Get <DataBroker>().GetAllModerators().Where(f => f.ForumID.Equals(pageForumID)); var moderatorUserNames = new List <string>(); moderatorsFiltered.ForEach( moderator => { if (moderator.IsGroup) { moderatorUserNames.AddRange( this.Get <IAspNetRolesHelper>().GetUsersInRole(moderator.Name).Select(u => u.UserName)); } else { moderatorUserNames.Add(moderator.Name); } }); var currentContext = HttpContext.Current; // send each message... moderatorUserNames.Distinct().AsParallel().ForAll( userName => { HttpContext.Current = currentContext; try { // add each member of the group var membershipUser = this.Get <IAspNetUsersHelper>().GetUserByName(userName); var userId = this.Get <IAspNetUsersHelper>().GetUserIDFromProviderUserKey(membershipUser.Id); var languageFile = UserHelper.GetUserLanguageFile(userId); var subject = string.Format( this.Get <ILocalization>().GetText( "COMMON", "NOTIFICATION_ON_MODERATOR_REPORTED_MESSAGE", languageFile), this.BoardSettings.Name); var notifyModerators = new TemplateEmail("NOTIFICATION_ON_MODERATOR_REPORTED_MESSAGE") { // get the user localization... TemplateLanguageFile = languageFile, TemplateParams = { ["{user}"] = userName, ["{reason}"] = reportText, ["{reporter}"] = this.Get <IUserDisplayName>() .GetName(reporter), ["{adminlink}"] = BuildLink.GetLink( ForumPages.Moderate_ReportedPosts, true, "f={0}", pageForumID) } }; notifyModerators.SendEmail( new MailAddress(membershipUser.Email, membershipUser.UserName), subject); } finally { HttpContext.Current = null; } }); } catch (Exception x) { // report exception to the forum's event log this.Get <ILogger>().Error( x, $"Send Message Report Notification Error for UserID {BoardContext.Current.PageUserID}"); } }
/// <summary> /// The to watching users. /// </summary> /// <param name="newMessageId"> /// The new message id. /// </param> public void ToWatchingUsers(int newMessageId) { var mailMessages = new List <MailMessage>(); var boardName = this.BoardSettings.Name; var forumEmail = this.BoardSettings.ForumEmail; var message = this.GetRepository <Message>().GetById(newMessageId); var messageAuthorUserID = message.UserID; // cleaned body as text... var bodyText = this.Get <IBadWordReplace>() .Replace(BBCodeHelper.StripBBCode(HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(message.MessageText)))) .RemoveMultipleWhitespace(); var watchUsers = this.GetRepository <User>() .WatchMailListAsDataTable(message.TopicID, messageAuthorUserID); var watchEmail = new TemplateEmail("TOPICPOST") { TemplateParams = { ["{topic}"] = HttpUtility.HtmlDecode( this.Get <IBadWordReplace>().Replace(message.Topic)), ["{postedby}"] = this.Get <IUserDisplayName>().GetName(messageAuthorUserID), ["{body}"] = bodyText, ["{bodytruncated}"] = bodyText.Truncate(160), ["{link}"] = BuildLink.GetLink( ForumPages.Posts, true, "m={0}&name={1}#post{0}", newMessageId, message.Topic), ["{subscriptionlink}"] = BuildLink.GetLink( ForumPages.Profile_Subscriptions, true) } }; var currentContext = HttpContext.Current; watchUsers.Rows.Cast <DataRow>().AsParallel().ForAll( row => { HttpContext.Current = currentContext; try { var languageFile = row.Field <string>("LanguageFile").IsSet() && this.Get <BoardSettings>().AllowUserLanguage ? row.Field <string>("LanguageFile") : this.Get <BoardSettings>().Language; var subject = string.Format( this.Get <ILocalization>().GetText("COMMON", "TOPIC_NOTIFICATION_SUBJECT", languageFile), boardName); watchEmail.TemplateLanguageFile = languageFile; mailMessages.Add(watchEmail.CreateEmail( new MailAddress(forumEmail, boardName), new MailAddress( row.Field <string>("Email"), this.BoardSettings.EnableDisplayName ? row.Field <string>("DisplayName") : row.Field <string>("Name")), subject)); } finally { HttpContext.Current = null; } }); if (this.BoardSettings.AllowNotificationAllPostsAllTopics) { var usersWithAll = this.GetRepository <User>().FindUserTyped( false, notificationType: UserNotificationSetting.AllTopics.ToInt()); // create individual watch emails for all users who have All Posts on... usersWithAll.Where(x => x.ID != messageAuthorUserID && x.ProviderUserKey != null).AsParallel().ForAll( user => { HttpContext.Current = currentContext; try { if (user.Email.IsNotSet()) { return; } var languageFile = user.LanguageFile.IsSet() && this.Get <BoardSettings>().AllowUserLanguage ? user.LanguageFile : this.Get <BoardSettings>().Language; var subject = string.Format( this.Get <ILocalization>().GetText("COMMON", "TOPIC_NOTIFICATION_SUBJECT", languageFile), boardName); watchEmail.TemplateLanguageFile = languageFile; mailMessages.Add( watchEmail.CreateEmail( new MailAddress(forumEmail, boardName), new MailAddress( user.Email, this.Get <IUserDisplayName>().GetName(user)), subject)); } finally { HttpContext.Current = null; } }); } if (mailMessages.Any()) { // Now send all mails.. this.Get <ISendMail>().SendAll( mailMessages, (mailMessage, exception) => this.Get <ILogger>().Log( "Mail Error", EventLogTypes.Error, null, null, exception)); } }
/// <summary> /// The method creates Syndication Feed for topics in a forum. /// </summary> /// <param name="feedType"> /// The FeedType. /// </param> /// <param name="atomFeedByVar"> /// The Atom feed checker. /// </param> /// <param name="lastPostName"> /// The last post name. /// </param> /// <returns> /// The <see cref="YafSyndicationFeed"/>. /// </returns> private YafSyndicationFeed GetPostLatestFeed( RssFeeds feedType, bool atomFeedByVar, [NotNull] string lastPostName) { var syndicationItems = new List <SyndicationItem>(); var urlAlphaNum = FormatUrlForFeed(BaseUrlBuilder.BaseUrl); var feed = new YafSyndicationFeed( this.GetText("ACTIVE_DISCUSSIONS"), feedType, atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt(), urlAlphaNum); using (var dataTopics = this.GetRepository <Topic>().RssLatestAsDataTable( this.PageContext.PageBoardID, this.Get <BoardSettings>().ActiveDiscussionsCount <= 50 ? this.Get <BoardSettings>().ActiveDiscussionsCount : 50, this.PageContext.PageUserID, this.Get <BoardSettings>().UseStyledNicks, this.Get <BoardSettings>().NoCountForumsInActiveDiscussions)) { var altItem = false; dataTopics.Rows.Cast <DataRow>().Where(row => !row["TopicMovedID"].IsNullOrEmptyDBField()).ForEach( row => { var lastPosted = Convert.ToDateTime(row["LastPosted"]) + this.Get <IDateTime>().TimeOffset; if (syndicationItems.Count <= 0) { feed.LastUpdatedTime = lastPosted + this.Get <IDateTime>().TimeOffset; feed.Authors.Add( SyndicationItemExtensions.NewSyndicationPerson( string.Empty, row["UserID"].ToType <long>(), row["UserName"].ToString(), row["UserDisplayName"].ToString())); } feed.Contributors.Add( SyndicationItemExtensions.NewSyndicationPerson( string.Empty, row["LastUserID"].ToType <long>(), row["LastUserName"].ToString(), row["LastUserDisplayName"].ToString())); var messageLink = BuildLink.GetLinkNotEscaped( ForumPages.Posts, true, "m={0}#post{0}", row["LastMessageID"]); syndicationItems.AddSyndicationItem( row["Topic"].ToString(), GetPostLatestContent( messageLink, lastPostName, row["LastMessage"].ToString(), !row["LastMessageFlags"].IsNullOrEmptyDBField() ? row["LastMessageFlags"].ToType <int>() : 22, altItem), null, BuildLink.GetLinkNotEscaped( ForumPages.Posts, true, "t={0}", row["TopicID"].ToType <int>()), $"urn:{urlAlphaNum}:ft{feedType}:st{(atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt())}:tid{row["TopicID"]}:mid{row["LastMessageID"]}:{this.PageContext.PageBoardID}" .Unidecode(), lastPosted, feed); altItem = !altItem; feed.Items = syndicationItems; }); return(feed); } }
/// <summary> /// The method creates the SyndicationFeed for posts. /// </summary> /// <param name="feedType"> /// The FeedType. /// </param> /// <param name="atomFeedByVar"> /// The Atom feed checker. /// </param> /// <param name="topicId"> /// The TopicID /// </param> /// <returns> /// The <see cref="YafSyndicationFeed"/>. /// </returns> private YafSyndicationFeed GetPostsFeed(RssFeeds feedType, bool atomFeedByVar, int topicId) { YafSyndicationFeed feed; var syndicationItems = new List <SyndicationItem>(); var showDeleted = false; var userId = 0; if (this.Get <BoardSettings>().ShowDeletedMessagesToAll) { showDeleted = true; } if (!showDeleted && (this.Get <BoardSettings>().ShowDeletedMessages&& !this.Get <BoardSettings>().ShowDeletedMessagesToAll || this.PageContext.IsAdmin || this.PageContext.IsForumModerator)) { userId = this.PageContext.PageUserID; } using (var dt = this.GetRepository <Message>().PostListAsDataTable( topicId, this.PageContext.PageUserID, userId, 0, showDeleted, true, false, DateTimeHelper.SqlDbMinTime(), DateTime.UtcNow, DateTimeHelper.SqlDbMinTime(), DateTime.UtcNow, 0, this.Get <BoardSettings>().PostsPerPage, 2, 0, 0, false, -1)) { // convert to linq... var rowList = dt.AsEnumerable(); // last page posts var dataRows = rowList.Take(this.Get <BoardSettings>().PostsPerPage); var altItem = false; var urlAlphaNum = FormatUrlForFeed(BaseUrlBuilder.BaseUrl); feed = new YafSyndicationFeed( $"{this.GetText("PROFILE", "TOPIC")}{this.PageContext.PageTopicName} - {this.Get<BoardSettings>().PostsPerPage}", feedType, atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt(), urlAlphaNum); dataRows.ForEach( row => { var posted = Convert.ToDateTime(row["Edited"]) + this.Get <IDateTime>().TimeOffset; if (syndicationItems.Count <= 0) { feed.Authors.Add( SyndicationItemExtensions.NewSyndicationPerson( string.Empty, row["UserID"].ToType <long>(), null, null)); feed.LastUpdatedTime = DateTime.UtcNow + this.Get <IDateTime>().TimeOffset; } List <SyndicationLink> attachmentLinks = null; // if the user doesn't have download access we simply don't show enclosure links. if (this.PageContext.ForumDownloadAccess) { attachmentLinks = this.GetMediaLinks(row["MessageID"].ToType <int>()); } feed.Contributors.Add( SyndicationItemExtensions.NewSyndicationPerson( string.Empty, row["UserID"].ToType <long>(), null, null)); syndicationItems.AddSyndicationItem( row["Topic"].ToString(), this.Get <IFormatMessage>().FormatSyndicationMessage( row["Message"].ToString(), new MessageFlags(row["Flags"]), altItem, 4000), null, BuildLink.GetLinkNotEscaped( ForumPages.Posts, true, "m={0}&find=lastpost", row["MessageID"]), $"urn:{urlAlphaNum}:ft{feedType}:st{(atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt())}:meid{row["MessageID"]}:{this.PageContext.PageBoardID}" .Unidecode(), posted, feed, attachmentLinks); // used to format feeds altItem = !altItem; }); feed.Items = syndicationItems; } return(feed); }
/// <summary> /// The bind data. /// </summary> private void BindData() { var user = this.GetRepository <User>().GetBoardUser(this.UserId); if (user == null || user.Item1.ID == 0) { // No such user exists or this is an nntp user ("0") BuildLink.AccessDenied(); } // populate user information controls... // Is BuddyList feature enabled? if (this.Get <BoardSettings>().EnableBuddyList) { this.SetupBuddyList(this.UserId, user); } else { // BuddyList feature is disabled. don't show any link. this.lnkBuddy.Visible = false; this.BuddyCard.Visible = false; } var userNameOrDisplayName = this.HtmlEncode( this.Get <IUserDisplayName>().GetName(user.Item1)); this.SetupUserProfileInfo(user); this.AddPageLinks(userNameOrDisplayName); this.SetupUserStatistics(user); this.SetupUserLinks(user, userNameOrDisplayName); this.SetupAvatar(user.Item1); var groups = this.GetRepository <UserGroup>().List(user.Item1.ID); if (this.PageContext.BoardSettings.UseStyledNicks) { this.Get <IStyleTransform>().DecodeStyleByGroupList(groups); } this.Groups.DataSource = groups; this.ModerateTab.Visible = this.PageContext.IsAdmin || this.PageContext.IsForumModerator; this.AdminUserButton.Visible = this.PageContext.IsAdmin; if (this.LastPosts.Visible) { this.LastPosts.DataSource = this.GetRepository <Message>().GetAllUserMessagesWithAccess( this.PageContext.PageBoardID, this.UserId, this.PageContext.PageUserID, 10); this.SearchUser.NavigateUrl = BuildLink.GetLink( ForumPages.Search, "postedby={0}", userNameOrDisplayName); } this.DataBind(); }
/// <summary> /// The setup user links. /// </summary> /// <param name="user"> /// The user. /// </param> /// <param name="userName"> /// Name of the user. /// </param> private void SetupUserLinks([NotNull] Tuple <User, AspNetUsers, Rank, vaccess> user, string userName) { // homepage link this.HomePlaceHolder.Visible = user.Item2.Profile_Homepage.IsSet(); this.Home.NavigateUrl = user.Item2.Profile_Homepage; // blog link this.Blog.Visible = user.Item2.Profile_Blog.IsSet(); this.SetupThemeButtonWithLink(this.Blog, user.Item2.Profile_Blog); this.Blog.ParamTitle0 = userName; this.Facebook.Visible = user.Item2.Profile_Facebook.IsSet(); if (user.Item2.Profile_Facebook.IsSet()) { this.Facebook.NavigateUrl = ValidationHelper.IsNumeric(user.Item2.Profile_Facebook) ? $"https://www.facebook.com/profile.php?id={user.Item2.Profile_Facebook}" : user.Item2.Profile_Facebook; } this.Facebook.ParamTitle0 = userName; this.Twitter.Visible = user.Item2.Profile_Twitter.IsSet(); this.Twitter.NavigateUrl = $"http://twitter.com/{this.HtmlEncode(user.Item2.Profile_Twitter)}"; this.Twitter.ParamTitle0 = userName; if (!this.Skype.Visible && !this.Blog.Visible && !this.XMPP.Visible && !this.Facebook.Visible && !this.Twitter.Visible) { this.SocialMediaHolder.Visible = false; } this.CustomProfile.DataSource = this.GetRepository <ProfileCustom>().ListByUser(this.UserId); this.CustomProfile.DataBind(); if (user.Item1.ID == this.PageContext.PageUserID) { return; } var isFriend = this.Get <IFriends>().IsBuddy(user.Item1.ID, true); this.PM.Visible = !user.Item1.IsGuest.Value && this.Get <BoardSettings>().AllowPrivateMessages; if (this.PM.Visible) { if (user.Item1.Block.BlockPMs) { this.PM.Visible = false; } if (this.PageContext.IsAdmin || isFriend) { this.PM.Visible = true; } } this.PM.NavigateUrl = BuildLink.GetLink(ForumPages.PostPrivateMessage, "u={0}", user.Item1.ID); this.PM.ParamTitle0 = userName; // email link this.Email.Visible = !user.Item1.IsGuest.Value && this.Get <BoardSettings>().AllowEmailSending; if (this.Email.Visible) { if (user.Item1.Block.BlockEmails && !this.PageContext.IsAdmin) { this.Email.Visible = false; } if (this.PageContext.IsAdmin || isFriend) { this.Email.Visible = true; } } this.Email.NavigateUrl = BuildLink.GetLink(ForumPages.Email, "u={0}", user.Item1.ID); if (this.PageContext.IsAdmin) { this.Email.TitleNonLocalized = user.Item1.Email; } this.Email.ParamTitle0 = userName; this.XMPP.Visible = user.Item2.Profile_XMPP.IsSet(); this.XMPP.NavigateUrl = BuildLink.GetLink(ForumPages.Jabber, "u={0}", user.Item1.ID); this.XMPP.ParamTitle0 = userName; this.Skype.Visible = user.Item2.Profile_Skype.IsSet(); this.Skype.NavigateUrl = $"skype:{user.Item2.Profile_Skype}?call"; this.Skype.ParamTitle0 = userName; }
/// <summary> /// Handles click on cancel button. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void CancelClick([NotNull] object sender, [NotNull] EventArgs e) { // go back to medals administration BuildLink.Redirect(ForumPages.Admin_Medals); }
/// <summary> /// Handles the Click event of the Save control. /// </summary> /// <param name="sender"> /// The source of the event. /// </param> /// <param name="e"> /// The <see cref="EventArgs"/> instance containing the event data. /// </param> private void SaveClick([NotNull] object sender, [NotNull] EventArgs e) { if (this.CategoryList.SelectedValue.Trim().Length == 0) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_CATEGORY"), MessageTypes.warning); return; } if (this.Name.Text.Trim().Length == 0) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_EDITFORUM", "MSG_NAME_FORUM"), MessageTypes.warning); return; } if (this.SortOrder.Text.Trim().Length == 0) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_VALUE"), MessageTypes.warning); return; } if (!ValidationHelper.IsValidPosShort(this.SortOrder.Text.Trim())) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_EDITFORUM", "MSG_POSITIVE_VALUE"), MessageTypes.warning); return; } if (!short.TryParse(this.SortOrder.Text.Trim(), out var sortOrder)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_NUMBER"), MessageTypes.warning); return; } // Forum // vzrus: it's stored in the DB as int var forumId = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefaultAsInt("fa"); var forumCopyId = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefaultAsInt("copy"); int?parentId = null; if (this.ParentList.SelectedValue.Length > 0) { parentId = this.ParentList.SelectedValue.ToType <int>(); } // parent selection check. if (parentId != null && parentId.ToString() == this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("fa")) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_EDITFORUM", "MSG_PARENT_SELF"), MessageTypes.warning); return; } // The picked forum cannot be a child forum as it's a parent // If we update a forum ForumID > 0 if (forumId.HasValue && parentId != null) { var dependency = this.GetRepository <Forum>() .SaveParentsChecker(forumId.Value, parentId.Value); if (dependency > 0) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_EDITFORUM", "MSG_CHILD_PARENT"), MessageTypes.warning); return; } } // duplicate name checking... if (!forumId.HasValue) { var forumList = this.GetRepository <Forum>().Get(f => f.Name == this.Name.Text.Trim()); if (forumList.Any() && !this.Get <BoardSettings>().AllowForumsWithSameName) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_EDITFORUM", "MSG_FORUMNAME_EXISTS"), MessageTypes.warning); return; } } var themeUrl = string.Empty; if (this.ThemeList.SelectedValue.Length > 0) { themeUrl = this.ThemeList.SelectedValue; } int?moderatedPostCount = null; if (!this.ModerateAllPosts.Checked) { moderatedPostCount = this.ModeratedPostCount.Text.ToType <int>(); } // empty out access table(s) this.GetRepository <Active>().DeleteAll(); this.GetRepository <ActiveAccess>().DeleteAll(); var newForumId = this.GetRepository <Forum>().Save( forumId, this.CategoryList.SelectedValue.ToType <int>(), parentId, this.Name.Text.Trim(), this.Description.Text.Trim(), sortOrder.ToType <int>(), this.Locked.Checked, this.HideNoAccess.Checked, this.IsTest.Checked, this.Moderated.Checked, moderatedPostCount, this.ModerateNewTopicOnly.Checked, this.remoteurl.Text, themeUrl, this.ForumImages.SelectedIndex > 0 ? this.ForumImages.SelectedItem.Text : string.Empty, this.Styles.Text); // Access if (forumId.HasValue || forumCopyId.HasValue) { this.AccessList.Items.OfType <RepeaterItem>().ForEach( item => { var groupId = int.Parse(item.FindControlAs <HiddenField>("GroupID").Value); this.GetRepository <ForumAccess>().Save( newForumId.ToType <int>(), groupId, item.FindControlAs <DropDownList>("AccessmaskID").SelectedValue.ToType <int>()); }); } else { this.AccessList.Items.OfType <RepeaterItem>().ForEach( item => { var groupId = int.Parse(item.FindControlAs <HiddenField>("GroupID").Value); this.GetRepository <ForumAccess>().Create( newForumId.ToType <int>(), groupId, item.FindControlAs <DropDownList>("AccessmaskID").SelectedValue.ToType <int>()); }); } this.ClearCaches(); BuildLink.Redirect(ForumPages.Admin_Forums); }
/// <summary> /// Handles the Click event of the Back control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void Back_Click([NotNull] object sender, [NotNull] EventArgs e) { BuildLink.Redirect(ForumPages.Account); }
/// <summary> /// Save the attached file both physically and in the Database /// </summary> /// <param name="file">the file.</param> /// <exception cref="Exception">Album Image File is too big</exception> private void SaveAttachment([NotNull] HtmlInputFile file) { if (file.PostedFile == null || file.PostedFile.FileName.Trim().Length == 0 || file.PostedFile.ContentLength == 0) { return; } var path = this.Get <HttpRequestBase>() .MapPath(string.Concat(BaseUrlBuilder.ServerFileRoot, BoardFolders.Current.Uploads)); // check if Uploads folder exists if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var filename = file.PostedFile.FileName; var pos = filename.LastIndexOfAny(new[] { '/', '\\' }); if (pos >= 0) { filename = filename.Substring(pos + 1); } // filename can be only 255 characters long (due to table column) if (filename.Length > 255) { filename = filename.Substring(filename.Length - 255); } // verify the size of the attachment if (this.Get <BoardSettings>().AlbumImagesSizeMax > 0 && file.PostedFile.ContentLength > this.Get <BoardSettings>().AlbumImagesSizeMax) { this.PageContext.AddLoadMessage(this.GetText("ERROR_TOOBIG"), MessageTypes.danger); return; } // vzrus: the checks here are useless but in a case... var sigData = this.GetRepository <User>().AlbumsDataAsDataTable( this.PageContext.PageUserID, BoardContext.Current.PageBoardID); var usrAlbumsAllowed = sigData.GetFirstRowColumnAsValue <int?>("UsrAlbums", null); var usrAlbumImagesAllowed = sigData.GetFirstRowColumnAsValue <int?>("UsrAlbumImages", null); // if (!usrAlbums.HasValue || usrAlbums <= 0) return; if (this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("a") == "new") { var allStats = this.GetRepository <UserAlbum>().CountUserAlbum(this.PageContext.PageUserID); // Albums count. If we reached limit then we exit. if (allStats >= usrAlbumsAllowed) { this.PageContext.AddLoadMessage(this.GetTextFormatted("ALBUMS_COUNT_LIMIT", usrAlbumImagesAllowed), MessageTypes.warning); return; } var newAlbumId = this.GetRepository <UserAlbum>().Save( this.PageContext.PageUserID, this.txtTitle.Text, null); file.PostedFile.SaveAs( $"{path}/{this.PageContext.PageUserID}.{newAlbumId.ToString()}.{filename}.yafalbum"); this.GetRepository <UserAlbumImage>().Save( null, newAlbumId, null, filename, file.PostedFile.ContentLength, file.PostedFile.ContentType); // clear the cache for this user to update albums|images stats... this.Get <IRaiseEvent>().Raise(new UpdateUserEvent(this.PageContext.PageUserID)); BuildLink.Redirect(ForumPages.EditAlbumImages, "a={0}", newAlbumId); } else { // vzrus: the checks here are useless but in a case... var allStats = this.GetRepository <UserAlbumImage>().CountAlbumImages( this.Get <HttpRequestBase>().QueryString.GetFirstOrDefaultAs <int>("a")); // Images count. If we reached limit then we exit. if (allStats >= usrAlbumImagesAllowed) { this.PageContext.AddLoadMessage(this.GetTextFormatted("IMAGES_COUNT_LIMIT", usrAlbumImagesAllowed), MessageTypes.warning); return; } file.PostedFile.SaveAs( $"{path}/{this.PageContext.PageUserID}.{this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("a")}.{filename}.yafalbum"); this.GetRepository <UserAlbumImage>().Save( null, this.Get <HttpRequestBase>().QueryString.GetFirstOrDefaultAs <int>("a"), null, filename, file.PostedFile.ContentLength, file.PostedFile.ContentType); } }
/// <summary> /// the page load event. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (!this.Get <BoardSettings>().EnableAlbum) { BuildLink.AccessDenied(); } if (this.IsPostBack) { return; } var sigData = this.GetRepository <User>().AlbumsDataAsDataTable( this.PageContext.PageUserID, BoardContext.Current.PageBoardID); var usrAlbumsAllowed = sigData.GetFirstRowColumnAsValue <int?>("UsrAlbums", null); var albumSize = this.GetRepository <UserAlbum>().CountUserAlbum(this.PageContext.PageUserID); int userID; switch (this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("a")) { // A new album is being created. check the permissions. case "new": // Is album feature enabled? if (!this.Get <BoardSettings>().EnableAlbum) { BuildLink.AccessDenied(); } // Has the user created maximum number of albums? if (usrAlbumsAllowed.HasValue && usrAlbumsAllowed > 0) { // Albums count. If we reached limit then we go to info page. if (usrAlbumsAllowed > 0 && albumSize >= usrAlbumsAllowed) { BuildLink.RedirectInfoPage(InfoMessage.AccessDenied); } } /* if (this.Get<BoardSettings>().AlbumsMax > 0 && * albumSize[0] > this.Get<BoardSettings>().AlbumsMax - 1) * { * BuildLink.RedirectInfoPage(InfoMessage.AccessDenied); * }*/ userID = this.PageContext.PageUserID; break; default: userID = this.GetRepository <UserAlbum>().List( Security.StringToIntOrRedirect( this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("a"))) .FirstOrDefault().UserID; if (userID != this.PageContext.PageUserID) { BuildLink.AccessDenied(); } break; } var displayName = BoardContext.Current.Get <BoardSettings>().EnableDisplayName ? UserMembershipHelper.GetDisplayNameFromID(userID) : UserMembershipHelper.GetUserNameFromID(userID); // Add the page links. this.PageLinks.AddRoot(); this.PageLinks.AddLink( displayName, BuildLink.GetLink(ForumPages.Profile, "u={0}&name={1}", userID.ToString(), displayName)); this.PageLinks.AddLink( this.GetText("ALBUMS"), BuildLink.GetLink(ForumPages.Albums, "u={0}", userID.ToString())); this.PageLinks.AddLink(this.GetText("TITLE"), string.Empty); this.BindData(); var usrAlbumImagesAllowed = sigData.GetFirstRowColumnAsValue <int?>("UsrAlbumImages", null); // Has the user uploaded maximum number of images? // vzrus: changed for DB check The default number of album images is 0. In the case albums are disabled. if (usrAlbumImagesAllowed.HasValue && usrAlbumImagesAllowed > 0) { if (this.List.Items.Count >= usrAlbumImagesAllowed) { this.uploadtitletr.Visible = false; this.selectfiletr.Visible = false; } else { this.uploadtitletr.Visible = true; this.selectfiletr.Visible = true; } this.imagesInfo.Text = this.GetTextFormatted( "IMAGES_INFO", this.List.Items.Count, usrAlbumImagesAllowed, this.Get <BoardSettings>().AlbumImagesSizeMax / 1024); } else { this.uploadtitletr.Visible = false; this.selectfiletr.Visible = false; } }
/// <summary> /// method the SyndicationFeed for Favorite topics. /// </summary> /// <param name="feedType"> /// The FeedType. /// </param> /// <param name="atomFeedByVar"> /// The Atom feed checker. /// </param> /// <param name="lastPostName"> /// The last post name. /// </param> /// <param name="categoryActiveId"> /// The category active id. /// </param> /// <returns> /// The <see cref="YafSyndicationFeed"/>. /// </returns> private YafSyndicationFeed GetFavoriteFeed( RssFeeds feedType, bool atomFeedByVar, [NotNull] string lastPostName, [NotNull] object categoryActiveId) { YafSyndicationFeed feed; var syndicationItems = new List <SyndicationItem>(); DateTime toFavDate; var toFavText = this.GetText("MYTOPICS", "LAST_MONTH"); if (this.Get <HttpRequestBase>().QueryString.Exists("txt")) { toFavText = this.Server.UrlDecode( this.Server.HtmlDecode(this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("txt"))); } if (this.Get <HttpRequestBase>().QueryString.Exists("d")) { if (!DateTime.TryParse( this.Server.UrlDecode( this.Server.HtmlDecode(this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("d"))), out toFavDate)) { toFavDate = PageContext.CurrentUserData.Joined ?? DateTimeHelper.SqlDbMinTime() + TimeSpan.FromDays(2); toFavText = this.GetText("MYTOPICS", "SHOW_ALL"); } } else { toFavDate = PageContext.CurrentUserData.Joined ?? DateTimeHelper.SqlDbMinTime() + TimeSpan.FromDays(2); toFavText = this.GetText("MYTOPICS", "SHOW_ALL"); } using (var dt = TabledCleanUpByDate( this.GetRepository <FavoriteTopic>().Details( categoryActiveId.ToType <int?>(), this.PageContext.PageUserID, toFavDate, DateTime.UtcNow, 0, // page index in db is 1 based! 20, // set the page size here false, false), "LastPosted", toFavDate)) { var urlAlphaNum = FormatUrlForFeed(BoardInfo.ForumBaseUrl); var feedNameAlphaNum = new Regex(@"[^A-Za-z0-9]", RegexOptions.IgnoreCase).Replace(toFavText, string.Empty); feed = new YafSyndicationFeed( $"{this.GetText("MYTOPICS", "FAVORITETOPICS")} - {toFavText}", feedType, atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt(), urlAlphaNum); dt.Rows.Cast <DataRow>().Where(row => !row["TopicMovedID"].IsNullOrEmptyDBField()).ForEach( row => { var lastPosted = Convert.ToDateTime(row["LastPosted"]) + this.Get <IDateTime>().TimeOffset; if (syndicationItems.Count <= 0) { feed.Authors.Add( SyndicationItemExtensions.NewSyndicationPerson( string.Empty, row["UserID"].ToType <long>(), null, null)); feed.LastUpdatedTime = DateTime.UtcNow + this.Get <IDateTime>().TimeOffset; } feed.Contributors.Add( SyndicationItemExtensions.NewSyndicationPerson( string.Empty, row["LastUserID"].ToType <long>(), null, null)); syndicationItems.AddSyndicationItem( row["Subject"].ToString(), GetPostLatestContent( BuildLink.GetLinkNotEscaped( ForumPages.Posts, true, "m={0}#post{0}", row["LastMessageID"]), lastPostName, lastPostName, !row["LastMessageFlags"].IsNullOrEmptyDBField() ? row["LastMessageFlags"].ToType <int>() : 22, false), null, BuildLink.GetLinkNotEscaped(ForumPages.Posts, true, "t={0}", row["LinkTopicID"]), $"urn:{urlAlphaNum}:ft{feedType}:st{(atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt())}:span{feedNameAlphaNum}:ltid{row["LinkTopicID"].ToType<int>()}:lmid{row["LastMessageID"]}:{this.PageContext.PageBoardID}" .Unidecode(), lastPosted, feed); }); feed.Items = syndicationItems; } return(feed); }
/// <summary> /// Called when Password Recovery is Clicked /// </summary> /// <param name="sender"> /// standard event object sender /// </param> /// <param name="e"> /// event args /// </param> protected void PasswordRecovery_Click([NotNull] object sender, [NotNull] EventArgs e) { BuildLink.Redirect(ForumPages.Account_ForgotPassword); }
/// <summary> /// The method creates YAF SyndicationFeed for forums in a category. /// </summary> /// <param name="feedType"> /// The FeedType. /// </param> /// <param name="atomFeedByVar"> /// The Atom feed checker. /// </param> /// <param name="categoryId"> /// The category id. /// </param> /// <returns> /// The <see cref="YafSyndicationFeed"/>. /// </returns> private YafSyndicationFeed GetForumFeed(RssFeeds feedType, bool atomFeedByVar, [NotNull] int?categoryId) { YafSyndicationFeed feed; var syndicationItems = new List <SyndicationItem>(); using (var dt = this.GetRepository <Forum>().ListReadAsDataTable( this.PageContext.PageBoardID, this.PageContext.PageUserID, categoryId, null, false, false)) { var urlAlphaNum = FormatUrlForFeed(BaseUrlBuilder.BaseUrl); feed = new YafSyndicationFeed( this.GetText("DEFAULT", "FORUM"), feedType, atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt(), urlAlphaNum); foreach (DataRow row in dt.Rows) { if (row["TopicMovedID"].IsNullOrEmptyDBField() && row["LastPosted"].IsNullOrEmptyDBField()) { continue; } var lastPosted = Convert.ToDateTime(row["LastPosted"]) + this.Get <IDateTime>().TimeOffset; if (syndicationItems.Count <= 0) { if (row["LastUserID"].IsNullOrEmptyDBField() || row["LastUserID"].IsNullOrEmptyDBField()) { break; } feed.Authors.Add( SyndicationItemExtensions.NewSyndicationPerson( string.Empty, row["LastUserID"].ToType <long>(), null, null)); feed.LastUpdatedTime = DateTime.UtcNow + this.Get <IDateTime>().TimeOffset; // Alternate Link // feed.Links.Add(new SyndicationLink(new Uri(BuildLink.GetLinkNotEscaped(ForumPages.topics, true)))); } if (!row["LastUserID"].IsNullOrEmptyDBField()) { feed.Contributors.Add( SyndicationItemExtensions.NewSyndicationPerson( string.Empty, row["LastUserID"].ToType <long>(), null, null)); } syndicationItems.AddSyndicationItem( row["Forum"].ToString(), this.HtmlEncode(row["Description"].ToString()), null, BuildLink.GetLinkNotEscaped(ForumPages.topics, true, "f={0}", row["ForumID"]), $"urn:{urlAlphaNum}:ft{feedType}:st{(atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt())}:fid{row["ForumID"]}:lmid{row["LastMessageID"]}:{this.PageContext.PageBoardID}" .Unidecode(), lastPosted, feed); } feed.Items = syndicationItems; } return(feed); }
/// <summary> /// Redirects to the Register Page /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void RegisterLinkClick(object sender, EventArgs e) { BuildLink.Redirect( this.Get <BoardSettings>().ShowRulesForRegistration ? ForumPages.RulesAndPrivacy : ForumPages.Account_Register); }
/// <summary> /// The page_ load. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { // Put user code to initialize the page here if (!(this.Get <BoardSettings>().ShowRSSLink || this.Get <BoardSettings>().ShowAtomLink)) { BuildLink.RedirectInfoPage(InfoMessage.AccessDenied); } // Atom feed as variable var atomFeedByVar = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("type") == SyndicationFormats.Atom.ToInt().ToString(); YafSyndicationFeed feed = null; // var syndicationItems = new List<SyndicationItem>(); var lastPostName = this.GetText("DEFAULT", "GO_LAST_POST"); RssFeeds feedType; try { feedType = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("feed").ToEnum <RssFeeds>(true); } catch { // default to Forum Feed. feedType = RssFeeds.Forum; } switch (feedType) { // Latest posts feed case RssFeeds.LatestPosts: if (!(this.Get <BoardSettings>().ShowActiveDiscussions&& this.Get <IPermissions>() .Check(this.Get <BoardSettings>().PostLatestFeedAccess))) { BuildLink.AccessDenied(); } feed = this.GetPostLatestFeed(feedType, atomFeedByVar, lastPostName); break; // Latest Announcements feed case RssFeeds.LatestAnnouncements: if (!this.Get <IPermissions>().Check(this.Get <BoardSettings>().ForumFeedAccess)) { BuildLink.AccessDenied(); } feed = this.GetLatestAnnouncementsFeed(feedType, atomFeedByVar); break; // Posts Feed case RssFeeds.Posts: if (!(this.PageContext.ForumReadAccess && this.Get <IPermissions>().Check(this.Get <BoardSettings>().PostsFeedAccess))) { BuildLink.AccessDenied(); } if (this.Get <HttpRequestBase>().QueryString.Exists("t")) { var topicId = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefaultAsInt("t"); feed = this.GetPostsFeed(feedType, atomFeedByVar, topicId.Value); } break; // Forum Feed case RssFeeds.Forum: if (!this.Get <IPermissions>().Check(this.Get <BoardSettings>().ForumFeedAccess)) { BuildLink.AccessDenied(); } int?categoryId = null; if (this.Get <HttpRequestBase>().QueryString.Exists("c")) { categoryId = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefaultAsInt("c"); } feed = this.GetForumFeed(feedType, atomFeedByVar, categoryId); break; // Topics Feed case RssFeeds.Topics: if (!(this.PageContext.ForumReadAccess && this.Get <IPermissions>().Check(this.Get <BoardSettings>().TopicsFeedAccess))) { BuildLink.AccessDenied(); } if (this.Get <HttpRequestBase>().QueryString.Exists("f")) { var forumId = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefaultAsInt("f"); feed = this.GetTopicsFeed(feedType, atomFeedByVar, lastPostName, forumId.Value); } break; // Active Topics case RssFeeds.Active: if (!this.Get <IPermissions>().Check(this.Get <BoardSettings>().ActiveTopicFeedAccess)) { BuildLink.AccessDenied(); } int?categoryActiveId = null; if (this.Get <HttpRequestBase>().QueryString.Exists("f")) { categoryActiveId = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefaultAsInt("f"); } feed = this.GetActiveFeed(feedType, atomFeedByVar, lastPostName, categoryActiveId); break; case RssFeeds.Favorite: if (!this.Get <IPermissions>().Check(this.Get <BoardSettings>().FavoriteTopicFeedAccess)) { BuildLink.AccessDenied(); } int?categoryFavId = null; if (this.Get <HttpRequestBase>().QueryString.Exists("f")) { categoryFavId = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefaultAsInt("f"); } feed = this.GetFavoriteFeed(feedType, atomFeedByVar, lastPostName, categoryFavId); break; default: BuildLink.AccessDenied(); break; } // update the feed with the item list... // the list should be added after all other feed properties are set if (feed != null) { var writer = new XmlTextWriter(this.Get <HttpResponseBase>().OutputStream, Encoding.UTF8); writer.WriteStartDocument(); // write the feed to the response writer); if (!atomFeedByVar) { var rssFormatter = new Rss20FeedFormatter(feed); rssFormatter.WriteTo(writer); this.Get <HttpResponseBase>().ContentType = "application/rss+xml"; } else { var atomFormatter = new Atom10FeedFormatter(feed); atomFormatter.WriteTo(writer); this.Get <HttpResponseBase>().ContentType = "application/atom+xml"; } writer.WriteEndDocument(); writer.Close(); this.Get <HttpResponseBase>().ContentEncoding = Encoding.UTF8; this.Get <HttpResponseBase>().Cache.SetCacheability(HttpCacheability.Public); this.Get <HttpResponseBase>().End(); } else { BuildLink.RedirectInfoPage(InfoMessage.AccessDenied); } }
/// <summary> /// Try to Import from selected File /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Import_OnClick([NotNull] object sender, [NotNull] EventArgs e) { try { int importedCount; // import selected file (if it's the proper format)... switch (this.importFile.PostedFile.ContentType) { case "text/xml": { importedCount = this.ImportingUsers(this.importFile.PostedFile.InputStream, true); } break; case "text/csv": { importedCount = this.ImportingUsers(this.importFile.PostedFile.InputStream, false); } break; case "text/comma-separated-values": { importedCount = this.ImportingUsers(this.importFile.PostedFile.InputStream, false); } break; case "application/csv": { importedCount = this.ImportingUsers(this.importFile.PostedFile.InputStream, false); } break; case "application/vnd.csv": { importedCount = this.ImportingUsers(this.importFile.PostedFile.InputStream, false); } break; case "application/vnd.ms-excel": { importedCount = this.ImportingUsers(this.importFile.PostedFile.InputStream, false); } break; default: { this.PageContext.AddLoadMessage( this.GetText("ADMIN_USERS_IMPORT", "IMPORT_FAILED_FORMAT"), MessageTypes.danger); return; } } this.PageContext.LoadMessage.AddSession( importedCount > 0 ? string.Format(this.GetText("ADMIN_USERS_IMPORT", "IMPORT_SUCESS"), importedCount) : this.GetText("ADMIN_USERS_IMPORT", "IMPORT_NOTHING"), importedCount > 0 ? MessageTypes.success : MessageTypes.info); } catch (Exception x) { this.PageContext.LoadMessage.AddSession( string.Format(this.GetText("ADMIN_USERS_IMPORT", "IMPORT_FAILED"), x.Message), MessageTypes.danger); } BuildLink.Redirect(ForumPages.Admin_Users); }
/// <summary> /// Sends Notifications to Moderators that Message Needs Approval /// </summary> /// <param name="forumId">The forum id.</param> /// <param name="newMessageId">The new message id.</param> /// <param name="isSpamMessage">if set to <c>true</c> [is spam message].</param> public void ToModeratorsThatMessageNeedsApproval(int forumId, int newMessageId, bool isSpamMessage) { var moderatorsFiltered = this.Get <DataBroker>().GetAllModerators().Where(f => f.ForumID.Equals(forumId)); var moderatorUserNames = new List <string>(); moderatorsFiltered.ForEach( moderator => { if (moderator.IsGroup) { moderatorUserNames.AddRange(this.Get <IAspNetRolesHelper>().GetUsersInRole(moderator.Name).Select(u => u.UserName)); } else { moderatorUserNames.Add(moderator.Name); } }); var themeCss = $"{this.Get<BoardSettings>().BaseUrlMask}{this.Get<ITheme>().BuildThemePath("bootstrap-forum.min.css")}"; var forumLink = BoardInfo.ForumURL; var adminLink = BuildLink.GetLink(ForumPages.Moderate_UnapprovedPosts, true, "f={0}", forumId); var currentContext = HttpContext.Current; // send each message... moderatorUserNames.Distinct().AsParallel().ForAll( userName => { HttpContext.Current = currentContext; try { // add each member of the group var membershipUser = this.Get <IAspNetUsersHelper>().GetUserByName(userName); var userId = this.Get <IAspNetUsersHelper>().GetUserIDFromProviderUserKey(membershipUser.Id); var languageFile = UserHelper.GetUserLanguageFile(userId); var subject = string.Format( this.Get <ILocalization>().GetText( "COMMON", isSpamMessage ? "NOTIFICATION_ON_MODERATOR_SPAMMESSAGE_APPROVAL" : "NOTIFICATION_ON_MODERATOR_MESSAGE_APPROVAL", languageFile), this.BoardSettings.Name); var notifyModerators = new TemplateEmail( isSpamMessage ? "NOTIFICATION_ON_MODERATOR_SPAMMESSAGE_APPROVAL" : "NOTIFICATION_ON_MODERATOR_MESSAGE_APPROVAL") { TemplateLanguageFile = languageFile, TemplateParams = { ["{user}"] = userName, ["{adminlink}"] = adminLink, ["{themecss}"] = themeCss, ["{forumlink}"] = forumLink } }; notifyModerators.SendEmail( new MailAddress(membershipUser.Email, membershipUser.UserName), subject); } finally { HttpContext.Current = null; } }); }
/// <summary> /// Render The User related Links /// </summary> private void RenderUserContainer() { if (this.PageContext.IsGuest) { return; } RenderMenuItem( this.MyProfile, "dropdown-item", this.GetText("TOOLBAR", "MYPROFILE"), this.GetText("TOOLBAR", "MYPROFILE_TITLE"), BuildLink.GetLink(ForumPages.Account), false, false, null, null, this.PageContext.ForumPageType == ForumPages.Account, "address-card"); if (!Config.IsDotNetNuke) { RenderMenuItem( this.MySettings, "dropdown-item", this.GetText("EDIT_PROFILE"), this.GetText("EDIT_PROFILE"), BuildLink.GetLink(ForumPages.EditProfile), false, false, null, null, this.PageContext.ForumPageType == ForumPages.EditProfile, "user-edit"); RenderMenuItem( this.MySettings, "dropdown-item", this.GetText("ACCOUNT", "EDIT_SETTINGS"), this.GetText("ACCOUNT", "EDIT_SETTINGS"), BuildLink.GetLink(ForumPages.EditSettings), false, false, null, null, this.PageContext.ForumPageType == ForumPages.EditSettings, "user-cog"); } RenderMenuItem( this.MySettings, "dropdown-item", this.GetText("ATTACHMENTS", "TITLE"), this.GetText("ATTACHMENTS", "TITLE"), BuildLink.GetLink(ForumPages.Attachments), false, false, null, null, this.PageContext.ForumPageType == ForumPages.Attachments, "paperclip"); if (!Config.IsDotNetNuke && (this.Get <BoardSettings>().AvatarRemote || this.Get <BoardSettings>().AvatarUpload || this.Get <BoardSettings>().AvatarGallery || this.Get <BoardSettings>().AvatarGravatar)) { RenderMenuItem( this.MySettings, "dropdown-item", this.GetText("ACCOUNT", "EDIT_AVATAR"), this.GetText("ACCOUNT", "EDIT_AVATAR"), BuildLink.GetLink(ForumPages.EditAvatar), false, false, null, null, this.PageContext.ForumPageType == ForumPages.EditAvatar, "user-tie"); } if (this.Get <BoardSettings>().AllowSignatures) { RenderMenuItem( this.MySettings, "dropdown-item", this.GetText("ACCOUNT", "SIGNATURE"), this.GetText("ACCOUNT", "SIGNATURE"), BuildLink.GetLink(ForumPages.EditSignature), false, false, null, null, this.PageContext.ForumPageType == ForumPages.EditSignature, "signature"); } RenderMenuItem( this.MySettings, "dropdown-item", this.GetText("ACCOUNT", "SUBSCRIPTIONS"), this.GetText("ACCOUNT", "SUBSCRIPTIONS"), BuildLink.GetLink(ForumPages.Subscriptions), false, false, null, null, this.PageContext.ForumPageType == ForumPages.Subscriptions, "envelope"); RenderMenuItem( this.MySettings, "dropdown-item", this.GetText("BLOCK_OPTIONS", "TITLE"), this.GetText("BLOCK_OPTIONS", "TITLE"), BuildLink.GetLink(ForumPages.BlockOptions), false, false, null, null, this.PageContext.ForumPageType == ForumPages.BlockOptions, "user-lock"); if (!Config.IsDotNetNuke && this.Get <BoardSettings>().AllowPasswordChange) { // Render Change Password Item RenderMenuItem( this.MySettings, "dropdown-item", this.GetText("ACCOUNT", "CHANGE_PASSWORD"), this.GetText("ACCOUNT", "CHANGE_PASSWORD"), BuildLink.GetLink(ForumPages.ChangePassword), false, false, null, null, this.PageContext.ForumPageType == ForumPages.ChangePassword, "lock"); } if (!Config.IsDotNetNuke && !this.PageContext.IsAdmin && !this.PageContext.IsHostAdmin) { // Render Delete Account Item RenderMenuItem( this.MySettings, "dropdown-item", this.GetText("ACCOUNT", "DELETE_ACCOUNT"), this.GetText("ACCOUNT", "DELETE_ACCOUNT"), BuildLink.GetLink(ForumPages.DeleteAccount), false, false, null, null, this.PageContext.ForumPageType == ForumPages.DeleteAccount, "user-alt-slash"); } // My Inbox if (this.Get <BoardSettings>().AllowPrivateMessages) { RenderMenuItem( this.MyInboxItem, "dropdown-item", this.GetText("TOOLBAR", "INBOX"), this.GetText("TOOLBAR", "INBOX_TITLE"), BuildLink.GetLink(ForumPages.PM), false, this.PageContext.UnreadPrivate > 0, this.PageContext.UnreadPrivate.ToString(), this.GetTextFormatted("NEWPM", this.PageContext.UnreadPrivate), this.PageContext.ForumPageType == ForumPages.PM, "inbox"); } // My Buddies if (this.Get <BoardSettings>().EnableBuddyList&& this.PageContext.UserHasBuddies) { RenderMenuItem( this.MyBuddiesItem, "dropdown-item", this.GetText("TOOLBAR", "BUDDIES"), this.GetText("TOOLBAR", "BUDDIES_TITLE"), BuildLink.GetLink(ForumPages.Friends), false, this.PageContext.PendingBuddies > 0, this.PageContext.PendingBuddies.ToString(), this.GetTextFormatted("BUDDYREQUEST", this.PageContext.PendingBuddies), this.PageContext.ForumPageType == ForumPages.Friends, "users"); } // My Albums if (this.Get <BoardSettings>().EnableAlbum && (this.PageContext.UsrAlbums > 0 || this.PageContext.NumAlbums > 0)) { RenderMenuItem( this.MyAlbumsItem, "dropdown-item", this.GetText("TOOLBAR", "MYALBUMS"), this.GetText("TOOLBAR", "MYALBUMS_TITLE"), BuildLink.GetLinkNotEscaped(ForumPages.Albums, "u={0}", this.PageContext.PageUserID), false, false, null, null, this.PageContext.ForumPageType == ForumPages.Albums, "images"); } // My Topics RenderMenuItem( this.MyTopicItem, "dropdown-item", this.GetText("TOOLBAR", "MYTOPICS"), this.GetText("TOOLBAR", "MYTOPICS"), BuildLink.GetLink(ForumPages.MyTopics), false, false, string.Empty, string.Empty, this.PageContext.ForumPageType == ForumPages.MyTopics, "comment"); // Logout if (!Config.IsAnyPortal && Config.AllowLoginAndLogoff) { this.LogutItem.Visible = true; this.LogOutButton.Text = $"<i class=\"fa fa-sign-out-alt fa-fw\"></i> {this.GetText("TOOLBAR", "LOGOUT")}"; this.LogOutButton.ToolTip = this.GetText("TOOLBAR", "LOGOUT"); } this.UserAvatar.ImageUrl = this.Get <IAvatars>().GetAvatarUrlForCurrentUser(); this.UserDropDown.DataToggle = "dropdown"; this.UserDropDown.Type = ButtonAction.None; if (this.PageContext.ForumPageType == ForumPages.Account || this.PageContext.ForumPageType == ForumPages.EditProfile || this.PageContext.ForumPageType == ForumPages.PM || this.PageContext.ForumPageType == ForumPages.Friends || this.PageContext.ForumPageType == ForumPages.MyTopics || this.PageContext.ForumPageType == ForumPages.EditProfile || this.PageContext.ForumPageType == ForumPages.EditSettings || this.PageContext.ForumPageType == ForumPages.ChangePassword || this.PageContext.ForumPageType == ForumPages.Attachments || this.PageContext.ForumPageType == ForumPages.Avatar || this.PageContext.ForumPageType == ForumPages.EditAvatar || this.PageContext.ForumPageType == ForumPages.EditSignature || this.PageContext.ForumPageType == ForumPages.Subscriptions || this.PageContext.ForumPageType == ForumPages.BlockOptions) { this.UserDropDown.CssClass = "nav-link active dropdown-toggle"; } else { this.UserDropDown.CssClass = "nav-link dropdown-toggle"; } this.UserDropDown.NavigateUrl = BuildLink.GetLink( ForumPages.Profile, "u={0}&name={1}", this.PageContext.PageUserID, this.Get <BoardSettings>().EnableDisplayName ? this.PageContext.CurrentUserData.DisplayName : this.PageContext.CurrentUserData.UserName); var unreadCount = this.PageContext.UnreadPrivate + this.PageContext.PendingBuddies; var unreadNotify = this.PageContext.Mention + this.PageContext.Quoted + this.PageContext.ReceivedThanks; if (!this.PageContext.CurrentUserData.Activity) { this.MyNotifications.Visible = false; } else { if (unreadNotify == 0) { this.NotifyPopMenu.Visible = false; this.NotifyIcon.IconType = string.Empty; this.UnreadIcon.Visible = false; this.NotifyItem.DataToggle = "tooltip"; this.NotifyItem.CssClass = "nav-link mb-1"; this.NotifyItem.NavigateUrl = BuildLink.GetLink(ForumPages.Notification); } } if (unreadCount <= 0) { this.UnreadPlaceHolder.Visible = false; return; } this.UnreadLabel.Text = unreadCount.ToString(); this.UnreadPlaceHolder.Visible = true; }
/// <summary> /// Sends notification about new PM in user's inbox. /// </summary> /// <param name="toUserId"> /// User supposed to receive notification about new PM. /// </param> /// <param name="subject"> /// Subject of PM user is notified about. /// </param> public void ToPrivateMessageRecipient(int toUserId, [NotNull] string subject) { try { // user's PM notification setting var privateMessageNotificationEnabled = false; // user's email var toEMail = string.Empty; var toUser = this.GetRepository <User>().GetById(toUserId); if (toUser != null) { privateMessageNotificationEnabled = toUser.PMNotification; toEMail = toUser.Email; } if (!privateMessageNotificationEnabled) { return; } // get the PM ID var userPMessageId = this.GetRepository <PMessage>().ListAsDataTable(toUserId, null, null).GetFirstRow() .Field <int>("UserPMessageID"); var languageFile = UserHelper.GetUserLanguageFile(toUserId); var displayName = this.Get <IUserDisplayName>().GetName(BoardContext.Current.User); // send this user a PM notification e-mail var notificationTemplate = new TemplateEmail("PMNOTIFICATION") { TemplateLanguageFile = languageFile, TemplateParams = { ["{fromuser}"] = displayName, ["{link}"] = $"{BuildLink.GetLink(ForumPages.PrivateMessage, true, "pm={0}", userPMessageId)}\r\n\r\n", ["{subject}"] = subject, ["{username}"] = this.Get <IUserDisplayName>().GetName(toUser) } }; // create notification email subject var emailSubject = string.Format( this.Get <ILocalization>().GetText("COMMON", "PM_NOTIFICATION_SUBJECT", languageFile), displayName, this.BoardSettings.Name, subject); // send email notificationTemplate.SendEmail(new MailAddress(toEMail), emailSubject); } catch (Exception x) { // report exception to the forum's event log this.Get <ILogger>().Error(x, $"Send PM Notification Error for UserID {BoardContext.Current.PageUserID}"); // tell user about failure BoardContext.Current.AddLoadMessage( this.Get <ILocalization>().GetTextFormatted("Failed", x.Message), MessageTypes.danger); } }
/// <summary> /// Returns Back to The Languages Page /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private static void CancelClick([NotNull] object sender, [NotNull] EventArgs e) { BuildLink.Redirect(ForumPages.Admin_Languages); }
/// <summary> /// Handles click on new medal button. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void NewMedalClick([NotNull] object sender, [NotNull] EventArgs e) { // redirect to medal edit page BuildLink.Redirect(ForumPages.Admin_EditMedal); }
/// <summary> /// The method creates SyndicationFeed for topics in a forum. /// </summary> /// <param name="feedType"> /// The FeedType. /// </param> /// <param name="atomFeedByVar"> /// The Atom feed checker. /// </param> /// <param name="lastPostName"> /// The last post name. /// </param> /// <param name="forumId"> /// The forum id. /// </param> /// <returns> /// The <see cref="YafSyndicationFeed"/>. /// </returns> private YafSyndicationFeed GetTopicsFeed( RssFeeds feedType, bool atomFeedByVar, [NotNull] string lastPostName, int forumId) { YafSyndicationFeed feed; var syndicationItems = new List <SyndicationItem>(); // vzrus changed to separate DLL specific code using (var dt = this.GetRepository <Topic>().RssListAsDataTable( forumId, this.Get <BoardSettings>().TopicsFeedItemsCount)) { var urlAlphaNum = FormatUrlForFeed(BaseUrlBuilder.BaseUrl); feed = new YafSyndicationFeed( $"{this.GetText("DEFAULT", "FORUM")}:{this.PageContext.PageForumName}", feedType, atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt(), urlAlphaNum); dt.Rows.Cast <DataRow>().ForEach( row => { var lastPosted = Convert.ToDateTime(row["LastPosted"]) + this.Get <IDateTime>().TimeOffset; if (syndicationItems.Count <= 0) { feed.Authors.Add( SyndicationItemExtensions.NewSyndicationPerson( string.Empty, row["LastUserID"].ToType <long>(), null, null)); feed.LastUpdatedTime = DateTime.UtcNow + this.Get <IDateTime>().TimeOffset; // Alternate Link // feed.Links.Add(new SyndicationLink(new Uri(BuildLink.GetLinkNotEscaped(ForumPages.Posts, true)))); } feed.Contributors.Add( SyndicationItemExtensions.NewSyndicationPerson( string.Empty, row["LastUserID"].ToType <long>(), null, null)); syndicationItems.AddSyndicationItem( row["Topic"].ToString(), GetPostLatestContent( BuildLink.GetLinkNotEscaped( ForumPages.Posts, true, "m={0}#post{0}", row["LastMessageID"]), lastPostName, row["LastMessage"].ToString(), !row["LastMessageFlags"].IsNullOrEmptyDBField() ? row["LastMessageFlags"].ToType <int>() : 22, false), null, BuildLink.GetLinkNotEscaped(ForumPages.Posts, true, "t={0}", row["TopicID"]), $"urn:{urlAlphaNum}:ft{feedType}:st{(atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt())}:tid{row["TopicID"]}:lmid{row["LastMessageID"]}:{this.PageContext.PageBoardID}" .Unidecode(), lastPosted, feed); }); feed.Items = syndicationItems; } return(feed); }
/// <summary> /// Render The GuestBar /// </summary> private void RenderGuestControls() { if (!this.PageContext.IsGuest) { // Logged in as : username this.LoggedInUserPanel.Visible = true; return; } this.GuestUserMessage.Visible = true; this.GuestMessage.Text = this.GetText("TOOLBAR", "WELCOME_GUEST_FULL"); var endPoint = new Label { Text = "." }; var isLoginAllowed = false; var isRegisterAllowed = false; if (Config.IsAnyPortal) { this.GuestMessage.Text = this.GetText("TOOLBAR", "WELCOME_GUEST"); } else { if (Config.AllowLoginAndLogoff) { // show login var loginLink = new HyperLink { Text = this.GetText("TOOLBAR", "LOGIN"), ToolTip = this.GetText("TOOLBAR", "LOGIN"), NavigateUrl = "javascript:void(0);", CssClass = "alert-link LoginLink" }; this.GuestUserMessage.Controls.Add(loginLink); isLoginAllowed = true; } if (!this.Get <BoardSettings>().DisableRegistrations) { if (isLoginAllowed) { this.GuestUserMessage.Controls.Add( new Label { Text = $" {this.GetText("COMMON", "OR")} " }); } // show register link var registerLink = new HyperLink { Text = this.GetText("TOOLBAR", "REGISTER"), NavigateUrl = this.Get <BoardSettings>().ShowRulesForRegistration ? BuildLink.GetLink(ForumPages.RulesAndPrivacy) : !this.Get <BoardSettings>().UseSSLToRegister ? BuildLink.GetLink(ForumPages.Register) : BuildLink.GetLink( ForumPages.Register, true).Replace("http:", "https:"), CssClass = "alert-link" }; this.GuestUserMessage.Controls.Add(registerLink); this.GuestUserMessage.Controls.Add(endPoint); isRegisterAllowed = true; } else { this.GuestUserMessage.Controls.Add(endPoint); this.GuestUserMessage.Controls.Add( new Label { Text = this.GetText("TOOLBAR", "DISABLED_REGISTER") }); } // If both disallowed if (isLoginAllowed || isRegisterAllowed) { return; } this.GuestUserMessage.Controls.Clear(); this.GuestUserMessage.Controls.Add(new Label { Text = this.GetText("TOOLBAR", "WELCOME_GUEST_NO") }); } }
/// <summary> /// The method creates SyndicationFeed for Active topics. /// </summary> /// <param name="feedType"> /// The FeedType. /// </param> /// <param name="atomFeedByVar"> /// The Atom feed checker. /// </param> /// <param name="lastPostName"> /// The last post name. /// </param> /// <param name="categoryActiveId"> /// The category active id. /// </param> /// <returns> /// The <see cref="YafSyndicationFeed"/>. /// </returns> private YafSyndicationFeed GetActiveFeed( RssFeeds feedType, bool atomFeedByVar, [NotNull] string lastPostName, [NotNull] int?categoryActiveId) { var syndicationItems = new List <SyndicationItem>(); var toActDate = DateTime.UtcNow; var toActText = this.GetText("MYTOPICS", "LAST_MONTH"); if (this.Get <HttpRequestBase>().QueryString.Exists("txt")) { toActText = this.Server.UrlDecode( this.Server.HtmlDecode(this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("txt"))); } if (this.Get <HttpRequestBase>().QueryString.Exists("d")) { if (!DateTime.TryParse( this.Server.UrlDecode( this.Server.HtmlDecode(this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("d"))), out toActDate)) { toActDate = Convert.ToDateTime(this.Get <IDateTime>().FormatDateTimeShort(DateTime.UtcNow)) + TimeSpan.FromDays(-31); toActText = this.GetText("MYTOPICS", "LAST_MONTH"); } else { // To limit number of feeds items by timespan if we are getting an unreasonable time if (toActDate < DateTime.UtcNow + TimeSpan.FromDays(-31)) { toActDate = DateTime.UtcNow + TimeSpan.FromDays(-31); toActText = this.GetText("MYTOPICS", "LAST_MONTH"); } } } var urlAlphaNum = FormatUrlForFeed(BaseUrlBuilder.BaseUrl); var feedNameAlphaNum = new Regex(@"[^A-Za-z0-9]", RegexOptions.IgnoreCase).Replace(toActText, string.Empty); var feed = new YafSyndicationFeed( $"{this.GetText("MYTOPICS", "ACTIVETOPICS")} - {toActText}", feedType, atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt(), urlAlphaNum); using (var dt = TabledCleanUpByDate( this.GetRepository <Topic>().ActiveAsDataTable( this.PageContext.PageBoardID, categoryActiveId, this.PageContext.PageUserID, toActDate, DateTime.UtcNow, 0, // page index in db which is returned back is +1 based! 20, // set the page size here false, this.Get <BoardSettings>().UseReadTrackingByDatabase), "LastPosted", toActDate)) { dt.Rows.Cast <DataRow>().Where(row => !row["TopicMovedID"].IsNullOrEmptyDBField()).ForEach( row => { var lastPosted = Convert.ToDateTime(row["LastPosted"]) + this.Get <IDateTime>().TimeOffset; if (syndicationItems.Count <= 0) { feed.Authors.Add( SyndicationItemExtensions.NewSyndicationPerson( string.Empty, row["UserID"].ToType <long>(), null, null)); feed.LastUpdatedTime = DateTime.UtcNow + this.Get <IDateTime>().TimeOffset; } feed.Contributors.Add( SyndicationItemExtensions.NewSyndicationPerson( string.Empty, row["LastUserID"].ToType <long>(), null, null)); var messageLink = BuildLink.GetLinkNotEscaped( ForumPages.Posts, true, "m={0}#post{0}", row["LastMessageID"]); syndicationItems.AddSyndicationItem( row["Subject"].ToString(), GetPostLatestContent( messageLink, lastPostName, lastPostName, !row["LastMessageFlags"].IsNullOrEmptyDBField() ? row["LastMessageFlags"].ToType <int>() : 22, false), null, messageLink, $"urn:{urlAlphaNum}:ft{feedNameAlphaNum}:st{feedType}:span{(atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt())}:ltid{row["LinkTopicID"]}:lmid{row["LastMessageID"]}:{this.PageContext.PageBoardID}" .Unidecode(), lastPosted, feed); }); feed.Items = syndicationItems; } return(feed); }
/// <summary> /// The page_ load. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (this.IsPostBack) { return; } this.Login1.MembershipProvider = Config.MembershipProvider; // Login1.CreateUserText = "Sign up for a new account."; // Login1.CreateUserUrl = BuildLink.GetLink( ForumPages.register ); this.Login1.PasswordRecoveryText = this.GetText("lostpassword"); this.Login1.PasswordRecoveryUrl = BuildLink.GetLink(ForumPages.RecoverPassword); this.Login1.FailureText = this.GetText("password_error"); this.Login1.DestinationPageUrl = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("ReturnUrl").IsSet() ? this.HtmlEncode(this.Server.UrlDecode(this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("ReturnUrl"))) : BuildLink.GetLink(ForumPages.forum); // localize controls var rememberMe = this.Login1.FindControlAs <CheckBox>("RememberMe"); var userName = this.Login1.FindControlAs <TextBox>("UserName"); var password = this.Login1.FindControlAs <TextBox>("Password"); var forumLogin = this.Login1.FindControlAs <Button>("LoginButton"); var passwordRecovery = this.Login1.FindControlAs <Button>("PasswordRecovery"); var cancelAuthLogin = this.Login1.FindControlAs <ThemeButton>("Cancel"); var userNameRow = this.Login1.FindControlAs <PlaceHolder>("UserNameRow"); var passwordRow = this.Login1.FindControlAs <PlaceHolder>("PasswordRow"); var singleSignOnOptionsRow = this.Login1.FindControlAs <PlaceHolder>("SingleSignOnOptionsRow"); var singleSignOnOptions = this.Login1.FindControlAs <RadioButtonList>("SingleSignOnOptions"); var registerLink = this.Login1.FindControlAs <ThemeButton>("RegisterLink"); var registerLinkPlaceHolder = this.Login1.FindControlAs <PlaceHolder>("RegisterLinkPlaceHolder"); var singleSignOnRow = this.Login1.FindControlAs <PlaceHolder>("SingleSignOnRow"); var facebookHolder = this.Login1.FindControlAs <PlaceHolder>("FacebookHolder"); var facebookLogin = this.Login1.FindControlAs <ThemeButton>("FacebookLogin"); var twitterHolder = this.Login1.FindControlAs <PlaceHolder>("TwitterHolder"); var twitterLogin = this.Login1.FindControlAs <ThemeButton>("TwitterLogin"); var googleHolder = this.Login1.FindControlAs <PlaceHolder>("GoogleHolder"); var googleLogin = this.Login1.FindControlAs <ThemeButton>("GoogleLogin"); var facebookRegister = this.Login1.FindControlAs <ThemeButton>("FacebookRegister"); var twitterRegister = this.Login1.FindControlAs <ThemeButton>("TwitterRegister"); var googleRegister = this.Login1.FindControlAs <ThemeButton>("GoogleRegister"); userName.Focus(); /* * RequiredFieldValidator usernameRequired = ( RequiredFieldValidator ) Login1.FindControl( "UsernameRequired" ); * RequiredFieldValidator passwordRequired = ( RequiredFieldValidator ) Login1.FindControl( "PasswordRequired" ); * * usernameRequired.ToolTip = usernameRequired.ErrorMessage = GetText( "REGISTER", "NEED_USERNAME" ); * passwordRequired.ToolTip = passwordRequired.ErrorMessage = GetText( "REGISTER", "NEED_PASSWORD" ); */ if (rememberMe != null) { rememberMe.Text = this.GetText("auto"); } if (forumLogin != null) { forumLogin.Text = this.GetText("FORUM_LOGIN"); } if (passwordRecovery != null) { passwordRecovery.Text = this.GetText("LOSTPASSWORD"); } if (password != null && forumLogin != null) { password.Attributes.Add( "onkeydown", $@"if(event.which || event.keyCode){{if ((event.which == 13) || (event.keyCode == 13)) {{ document.getElementById('{forumLogin.ClientID}').click();return false;}}}} else {{return true}}; "); } if (registerLinkPlaceHolder != null && this.PageContext.IsGuest && !this.Get <BoardSettings>().DisableRegistrations&& !Config.IsAnyPortal) { registerLinkPlaceHolder.Visible = true; registerLink.TextLocalizedTag = "REGISTER_INSTEAD"; } if (this.Get <BoardSettings>().AllowSingleSignOn && (Config.FacebookAPIKey.IsSet() || Config.TwitterConsumerKey.IsSet() || Config.GoogleClientID.IsSet())) { singleSignOnRow.Visible = true; var facebookEnabled = Config.FacebookAPIKey.IsSet() && Config.FacebookSecretKey.IsSet(); var twitterEnabled = Config.TwitterConsumerKey.IsSet() && Config.TwitterConsumerSecret.IsSet(); var googleEnabled = Config.GoogleClientID.IsSet() && Config.GoogleClientSecret.IsSet(); var loginAuth = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("auth"); if (loginAuth.IsNotSet()) { if (facebookEnabled) { facebookRegister.Visible = true; facebookRegister.Text = this.GetTextFormatted("AUTH_CONNECT", "Facebook"); facebookRegister.TitleLocalizedTag = "AUTH_CONNECT_HELP"; facebookRegister.ParamTitle0 = "Facebook"; } if (twitterEnabled) { twitterRegister.Visible = true; twitterRegister.Text = this.GetTextFormatted("AUTH_CONNECT", "Twitter"); twitterRegister.TitleLocalizedTag = "AUTH_CONNECT_HELP"; twitterRegister.ParamTitle0 = "Twitter"; } if (googleEnabled) { googleRegister.Visible = true; googleRegister.Text = this.GetTextFormatted("AUTH_CONNECT", "Google"); googleRegister.TitleLocalizedTag = "AUTH_CONNECT_HELP"; googleRegister.ParamTitle0 = "Google"; } } else { singleSignOnOptionsRow.Visible = true; facebookRegister.Visible = false; twitterRegister.Visible = false; googleRegister.Visible = false; userNameRow.Visible = false; passwordRow.Visible = false; registerLinkPlaceHolder.Visible = false; passwordRecovery.Visible = false; forumLogin.Visible = false; rememberMe.Visible = false; cancelAuthLogin.Visible = true; switch ((AuthService)Enum.Parse(typeof(AuthService), loginAuth, true)) { case AuthService.twitter: { twitterHolder.Visible = twitterEnabled; singleSignOnOptions.Items.Clear(); singleSignOnOptions.Items.Add( new ListItem { Value = "login", Text = this.GetTextFormatted("AUTH_LOGIN_EXISTING", "Twitter"), Selected = true }); singleSignOnOptions.Items.Add( new ListItem { Value = "connect", Text = this.GetTextFormatted( "AUTH_CONNECT_ACCOUNT", "Twitter", this.GetText("AUTH_CONNECT_TWITTER")) }); if (twitterEnabled) { try { var twitterLoginUrl = SingleSignOnUser.GenerateLoginUrl(AuthService.twitter, true); // Redirect the user to Twitter for authorization. twitterLogin.Attributes.Add("onclick", twitterLoginUrl); } catch (Exception exception) { this.Logger.Warn( exception, "YAF encountered an error when loading the Twitter Login Link"); twitterHolder.Visible = false; } } } break; case AuthService.facebook: { facebookHolder.Visible = facebookEnabled; singleSignOnOptions.Items.Clear(); singleSignOnOptions.Items.Add( new ListItem { Value = "login", Text = this.GetTextFormatted("AUTH_LOGIN_EXISTING", "Facebook"), Selected = true }); singleSignOnOptions.Items.Add( new ListItem { Value = "connect", Text = this.GetTextFormatted( "AUTH_CONNECT_ACCOUNT", "Facebook", this.GetText("AUTH_CONNECT_FACEBOOK")) }); if (facebookEnabled) { try { var facebookLoginUrl = SingleSignOnUser.GenerateLoginUrl(AuthService.facebook, true); // Redirect the user to Twitter for authorization. facebookLogin.Attributes.Add( "onclick", $"location.href='{facebookLoginUrl}'"); } catch (Exception exception) { this.Logger.Warn( exception, "YAF encountered an error when loading the facebook Login Link"); facebookHolder.Visible = false; } } } break; case AuthService.google: { googleHolder.Visible = googleEnabled; singleSignOnOptions.Items.Clear(); singleSignOnOptions.Items.Add( new ListItem { Value = "login", Text = this.GetTextFormatted("AUTH_LOGIN_EXISTING", "Google"), Selected = true }); singleSignOnOptions.Items.Add( new ListItem { Value = "connect", Text = this.GetTextFormatted( "AUTH_CONNECT_ACCOUNT", "Facebook", this.GetText("AUTH_CONNECT_GOOGLE")) }); if (googleEnabled) { try { var googleLoginUrl = SingleSignOnUser.GenerateLoginUrl(AuthService.google, true); // Redirect the user to Twitter for authorization. googleLogin.Attributes.Add( "onclick", $"location.href='{googleLoginUrl}'"); } catch (Exception exception) { this.Logger.Warn( exception, "YAF encountered an error when loading the Google Login Link"); googleHolder.Visible = false; } } } break; } } } this.DataBind(); }
/// <summary> /// Saves the Host Settings /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void SaveClick([NotNull] object sender, [NotNull] EventArgs e) { // write all the settings back to the settings class // load Board Setting collection information... var settingCollection = new BoardSettingCollection(this.Get <BoardSettings>()); // handle checked fields... settingCollection.SettingsBool.Keys.ForEach( name => { var control = this.HostSettingsTabs.FindControlRecursive(name); if (control is CheckBox box && settingCollection.SettingsBool[name].CanWrite) { settingCollection.SettingsBool[name].SetValue( this.Get <BoardSettings>(), box.Checked, null); } }); // handle string fields... settingCollection.SettingsString.Keys.ForEach( name => { var control = this.HostSettingsTabs.FindControlRecursive(name); switch (control) { case TextBox box when settingCollection.SettingsString[name].CanWrite: settingCollection.SettingsString[name].SetValue( this.Get <BoardSettings>(), box.Text.Trim(), null); break; case DropDownList list when settingCollection.SettingsString[name].CanWrite: settingCollection.SettingsString[name].SetValue( this.Get <BoardSettings>(), Convert.ToString(list.SelectedItem.Value), null); break; } }); // handle int fields... settingCollection.SettingsInt.Keys.ForEach( name => { var control = this.HostSettingsTabs.FindControlRecursive(name); switch (control) { case TextBox box when settingCollection.SettingsInt[name].CanWrite: { var value = box.Text.Trim(); int i; if (value.IsNotSet()) { i = 0; } else { int.TryParse(value, out i); } settingCollection.SettingsInt[name].SetValue(this.Get <BoardSettings>(), i, null); break; } case DropDownList list when settingCollection.SettingsInt[name].CanWrite: settingCollection.SettingsInt[name].SetValue( this.Get <BoardSettings>(), list.SelectedItem.Value.ToType <int>(), null); break; } }); // handle double fields... settingCollection.SettingsDouble.Keys.ForEach( name => { var control = this.HostSettingsTabs.FindControlRecursive(name); switch (control) { case TextBox box when settingCollection.SettingsDouble[name].CanWrite: { var value = box.Text.Trim(); double i; if (value.IsNotSet()) { i = 0; } else { double.TryParse(value, out i); } settingCollection.SettingsDouble[name].SetValue( this.Get <BoardSettings>(), i, null); break; } case DropDownList list when settingCollection.SettingsDouble[name].CanWrite: settingCollection.SettingsDouble[name].SetValue( this.Get <BoardSettings>(), Convert.ToDouble(list.SelectedItem.Value), null); break; } }); // save the settings to the database ((LoadBoardSettings)this.Get <BoardSettings>()).SaveRegistry(); // reload all settings from the DB this.PageContext.BoardSettings = null; BuildLink.Redirect(ForumPages.Admin_Admin); }