コード例 #1
0
        /// <summary>
        /// Suspends a user when clicked.
        /// </summary>
        /// <param name="sender">
        /// The object sender inherit from Page.
        /// </param>
        /// <param name="e">
        /// The System.EventArgs inherit from Page.
        /// </param>
        protected void Suspend_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            // Admins can suspend anyone not admins
            // Forum Moderators can suspend anyone not admin or forum moderator
            using (var dt = LegacyDb.user_list(this.PageContext.PageBoardID, this.CurrentUserID, null))
            {
                foreach (DataRow row in dt.Rows)
                {
                    // is user to be suspended admin?
                    if (row["IsAdmin"] != DBNull.Value && row["IsAdmin"].ToType <int>() > 0)
                    {
                        // tell user he can't suspend admin
                        this.PageContext.AddLoadMessage(
                            this.GetText("PROFILE", "ERROR_ADMINISTRATORS"),
                            MessageTypes.danger);
                        return;
                    }

                    // is user to be suspended forum moderator, while user suspending him is not admin?
                    if (!this.PageContext.IsAdmin && int.Parse(row["IsForumModerator"].ToString()) > 0)
                    {
                        // tell user he can't suspend forum moderator when he's not admin
                        this.PageContext.AddLoadMessage(
                            this.GetText("PROFILE", "ERROR_FORUMMODERATORS"),
                            MessageTypes.danger);
                        return;
                    }

                    var isGuest = row["IsGuest"];

                    // verify the user isn't guest...
                    if (isGuest != DBNull.Value && isGuest.ToType <int>() > 0)
                    {
                        this.PageContext.AddLoadMessage(
                            this.GetText("PROFILE", "ERROR_GUESTACCOUNT"),
                            MessageTypes.danger);
                        return;
                    }
                }
            }

            // time until when user is suspended
            var suspend = this.Get <IDateTime>()
                          .GetUserDateTime(DateTime.UtcNow, this.UserData.TimeZone.Value, this.UserData.DSTUser);

            // number inserted by suspending user
            var count = int.Parse(this.SuspendCount.Text);

            // what time units are used for suspending
            switch (this.SuspendUnit.SelectedValue)
            {
            // days
            case "1":

                // add user inserted suspension time to current time
                suspend = suspend.AddDays(count);
                break;

            // hours
            case "2":

                // add user inserted suspension time to current time
                suspend = suspend.AddHours(count);
                break;

            // minutes
            case "3":

                // add user inserted suspension time to current time
                suspend = suspend.AddHours(count);
                break;
            }

            // suspend user by calling appropriate method
            LegacyDb.user_suspend(
                this.CurrentUserID,
                suspend,
                this.SuspendedReason.Text.Trim(),
                this.PageContext.PageUserID);

            var usr =
                LegacyDb.UserList(
                    this.PageContext.PageBoardID,
                    this.CurrentUserID.ToType <int?>(),
                    null,
                    null,
                    null,
                    false).ToList();

            if (usr.Any())
            {
                this.Get <ILogger>()
                .Log(
                    this.PageContext.PageUserID,
                    "YAF.Controls.EditUsersSuspend",
                    "User {0} was suspended by {1} until: {2} (UTC)".FormatWith(
                        this.Get <YafBoardSettings>().EnableDisplayName ? usr.First().DisplayName : usr.First().Name,
                        this.Get <YafBoardSettings>().EnableDisplayName
                                ? this.PageContext.CurrentUserData.DisplayName
                                : this.PageContext.CurrentUserData.UserName,
                        suspend),
                    EventLogTypes.UserSuspended);

                this.Get <IRaiseEvent>().Raise(new UpdateUserEvent(this.CurrentUserID.ToType <int>()));

                this.Get <ISendNotification>()
                .SendUserSuspensionNotification(
                    suspend,
                    this.SuspendedReason.Text.Trim(),
                    this.UserData.Email,
                    this.PageContext.BoardSettings.EnableDisplayName
                            ? this.UserData.DisplayName
                            : this.UserData.UserName);
            }

            this.SuspendedReason.Text = string.Empty;

            // re-bind data
            this.BindData();
        }
コード例 #2
0
        /// <summary>
        /// Creates the Google user
        /// </summary>
        /// <param name="googleUser">
        /// The Google user.
        /// </param>
        /// <param name="userGender">
        /// The user gender.
        /// </param>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// Returns if the login was successfully or not
        /// </returns>
        private bool CreateGoogleUser(GoogleUser googleUser, int userGender, out string message)
        {
            if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations)
            {
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            // Check user for bot
            var    spamChecker = new YafSpamCheck();
            string result;
            var    isPossibleSpamBot = false;

            var userIpAddress = YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress();

            // Check content for spam
            if (spamChecker.CheckUserForSpamBot(googleUser.UserName, googleUser.Email, userIpAddress, out result))
            {
                YafContext.Current.Get <ILogger>().Log(
                    null,
                    "Bot Detected",
                    "Bot Check detected a possible SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}', reason : {3}), user was rejected."
                    .FormatWith(googleUser.UserName, googleUser.Email, userIpAddress, result),
                    EventLogTypes.SpamBotDetected);

                if (YafContext.Current.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1))
                {
                    // Flag user as spam bot
                    isPossibleSpamBot = true;
                }
                else if (YafContext.Current.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(2))
                {
                    message = YafContext.Current.Get <ILocalization>().GetText("BOT_MESSAGE");

                    if (!YafContext.Current.Get <YafBoardSettings>().BanBotIpOnDetection)
                    {
                        return(false);
                    }

                    YafContext.Current.GetRepository <BannedIP>()
                    .Save(
                        null,
                        userIpAddress,
                        "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress),
                        YafContext.Current.PageUserID);

                    // Clear cache
                    YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.BannedIP);

                    if (YafContext.Current.Get <YafBoardSettings>().LogBannedIP)
                    {
                        YafContext.Current.Get <ILogger>()
                        .Log(
                            null,
                            "IP BAN of Bot During Registration",
                            "A spam Bot who was trying to register was banned by IP {0}".FormatWith(
                                userIpAddress),
                            EventLogTypes.IpBanSet);
                    }

                    return(false);
                }
            }

            MembershipCreateStatus status;

            var memberShipProvider = YafContext.Current.Get <MembershipProvider>();

            var pass           = Membership.GeneratePassword(32, 16);
            var securityAnswer = Membership.GeneratePassword(64, 30);

            var user = memberShipProvider.CreateUser(
                googleUser.UserName,
                pass,
                googleUser.Email,
                memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null,
                memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null,
                true,
                null,
                out status);

            // setup initial roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, googleUser.UserName);

            // create the user in the YAF DB as well as sync roles...
            var userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            var userProfile = YafUserProfile.GetProfile(googleUser.UserName);

            // setup their initial profile information
            userProfile.Save();

            userProfile.Google   = googleUser.ProfileURL;
            userProfile.GoogleId = googleUser.UserID;
            userProfile.Homepage = googleUser.ProfileURL;

            userProfile.Gender = userGender;

            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet())
            {
                // send user register notification to the following admin users...
                YafContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value);
            }

            if (isPossibleSpamBot)
            {
                YafContext.Current.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value);
            }

            // send user register notification to the user...
            YafContext.Current.Get <ISendNotification>()
            .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_GOOGLE_REGISTER");

            // save the time zone...
            var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            var autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            LegacyDb.user_save(
                userId,
                YafContext.Current.PageBoardID,
                googleUser.UserName,
                googleUser.UserName,
                googleUser.Email,
                0,
                null,
                null,
                true,
                null,
                null,
                null,
                YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting,
                autoWatchTopicsEnabled,
                null,
                null,
                null);

            // save the settings...
            LegacyDb.user_savenotification(
                userId,
                true,
                autoWatchTopicsEnabled,
                YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting,
                YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail);

            // save avatar
            LegacyDb.user_saveavatar(userId, googleUser.ProfileImage, null, null);

            YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId));

            YafSingleSignOnUser.LoginSuccess(AuthService.google, user.UserName, userId, true);

            message = string.Empty;

            return(true);
        }
コード例 #3
0
ファイル: topics.ascx.cs プロジェクト: zghlx/YAFNET
        /// <summary>
        /// The page_ load.
        /// </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)
        {
            this.Get <IYafSession>().UnreadTopics = 0;
            this.AtomFeed.AdditionalParameters    =
                "f={0}".FormatWith(this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("f"));
            this.RssFeed.AdditionalParameters =
                "f={0}".FormatWith(this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("f"));
            this.MarkRead.Text           = this.GetText("MARKREAD");
            this.ForumJumpHolder.Visible = this.Get <YafBoardSettings>().ShowForumJump &&
                                           this.PageContext.Settings.LockedForum == 0;

            this.LastPostImageTT = this.GetText("DEFAULT", "GO_LAST_POST");

            if (this.ForumSearchHolder.Visible)
            {
                this.forumSearch.Attributes["onkeydown"] =
                    "if(event.which || event.keyCode){{if ((event.which == 13) || (event.keyCode == 13)) {{document.getElementById('{0}').click();return false;}}}} else {{return true}}; "
                    .FormatWith(this.forumSearchOK.ClientID);
            }

            if (!this.IsPostBack)
            {
                // PageLinks.Clear();
                if (this.PageContext.Settings.LockedForum == 0)
                {
                    this.PageLinks.AddRoot();
                    this.PageLinks.AddLink(
                        this.PageContext.PageCategoryName,
                        YafBuildLink.GetLink(ForumPages.forum, "c={0}", this.PageContext.PageCategoryID));
                }

                this.PageLinks.AddForum(this.PageContext.PageForumID, true);

                this.ShowList.DataSource     = StaticDataHelper.TopicTimes();
                this.ShowList.DataTextField  = "TopicText";
                this.ShowList.DataValueField = "TopicValue";
                this._showTopicListSelected  = (this.Get <IYafSession>().ShowList == -1)
                                                  ? this.Get <YafBoardSettings>().ShowTopicsDefault
                                                  : this.Get <IYafSession>().ShowList;

                this.moderate1.NavigateUrl     =
                    this.moderate2.NavigateUrl =
                        YafBuildLink.GetLinkNotEscaped(ForumPages.moderating, "f={0}", this.PageContext.PageForumID);

                this.NewTopic1.NavigateUrl     =
                    this.NewTopic2.NavigateUrl =
                        YafBuildLink.GetLinkNotEscaped(ForumPages.postmessage, "f={0}", this.PageContext.PageForumID);

                this.HandleWatchForum();
            }

            if (this.Request.QueryString.GetFirstOrDefault("f") == null)
            {
                YafBuildLink.AccessDenied();
            }

            if (this.PageContext.IsGuest && !this.PageContext.ForumReadAccess)
            {
                // attempt to get permission by redirecting to login...
                this.Get <IPermissions>().HandleRequest(ViewPermissions.RegisteredUsers);
            }
            else if (!this.PageContext.ForumReadAccess)
            {
                YafBuildLink.AccessDenied();
            }

            using (DataTable dt = LegacyDb.forum_list(this.PageContext.PageBoardID, this.PageContext.PageForumID))
            {
                this._forum = dt.Rows[0];
            }

            if (this._forum["RemoteURL"] != DBNull.Value)
            {
                this.Response.Clear();
                this.Response.Redirect((string)this._forum["RemoteURL"]);
            }

            this._forumFlags = new ForumFlags(this._forum["Flags"]);

            this.PageTitle.Text = this._forum["Description"].ToString().IsSet()
                                      ? "{0} - <em>{1}</em>".FormatWith(
                this.HtmlEncode(this._forum["Name"]),
                this.HtmlEncode(this._forum["Description"]))
                                      : this.HtmlEncode(this._forum["Name"]);

            this.BindData(); // Always because of yaf:TopicLine

            if (!this.PageContext.ForumPostAccess ||
                (this._forumFlags.IsLocked && !this.PageContext.ForumModeratorAccess))
            {
                this.NewTopic1.Visible = false;
                this.NewTopic2.Visible = false;
            }

            if (this.PageContext.ForumModeratorAccess)
            {
                return;
            }

            this.moderate1.Visible = false;
            this.moderate2.Visible = false;
        }
コード例 #4
0
ファイル: test_data.ascx.cs プロジェクト: ahsan-sally/demo
        /// <summary>
        /// Create forums from Categories
        /// </summary>
        /// <param name="categoryID">
        /// </param>
        /// <param name="parentID">
        /// The parent ID.
        /// </param>
        /// <param name="numForums">
        /// The num Forums.
        /// </param>
        /// <param name="_topicsToCreate">
        /// Number of topics to create.
        /// </param>
        /// <param name="_messagesToCreate">
        /// Number of messages to create.
        /// </param>
        /// <returns>
        /// The create forums.
        /// </returns>
        private int CreateForums(
            int categoryID, [NotNull] object parentID, int numForums, int _topicsToCreate, int _messagesToCreate)
        {
            var countMessagesInStatistics = this.ForumsCountMessages.Text.Trim().IsNotSet();

            var isHiddenIfNoAccess = this.ForumsHideNoAccess.Text.Trim().IsNotSet();

            isHiddenIfNoAccess = true;

            // ForumsCategory.Items.FindByValue("0").Selected = true;
            long uniqueForum = 0;
            int  iforums;

            for (iforums = 0; iforums < numForums; iforums++)
            {
                long _forumID = 0;
                this.randomGuid = Guid.NewGuid().ToString();
                var accessForumList = this.GetRepository <ForumAccess>().GetForumAccessList(_forumID.ToType <int>());
                _forumID = LegacyDb.forum_save(
                    _forumID,
                    categoryID,
                    parentID,
                    this.ForumPrefixTB.Text.Trim() + this.randomGuid,
                    "Description of " + this.ForumPrefixTB.Text.Trim() + this.randomGuid,
                    100,
                    false,
                    isHiddenIfNoAccess,
                    countMessagesInStatistics,
                    false,
                    null,
                    false,
                    this.ForumsStartMask.SelectedValue,
                    null,
                    null,
                    null,
                    null,
                    false);

                if (_forumID <= 0)
                {
                    continue;
                }

                foreach (var access in accessForumList)
                {
                    this.GetRepository <ForumAccess>().Save(
                        _forumID.ToType <int>(),
                        access.GroupID,
                        access.AccessMaskID);
                }

                this.GetRepository <ForumAccess>().Save(
                    _forumID.ToType <int>(),
                    this.ForumsGroups.SelectedValue.ToType <int>(),
                    this.ForumsAdminMask.SelectedValue.ToType <int>());

                if (_topicsToCreate <= 0)
                {
                    continue;
                }

                if (uniqueForum == _forumID)
                {
                    continue;
                }

                this.CreateTopics(_forumID.ToType <int>(), _topicsToCreate, _messagesToCreate);
                uniqueForum = _forumID;
            }

            return(iforums);
        }
コード例 #5
0
        /// <summary>
        /// Handles click on save user 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 AddUserSave_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            // test if there is specified unsername/user id
            if (this.UserID.Text.IsNotSet() && this.UserNameList.SelectedValue.IsNotSet() && this.UserName.Text.IsNotSet())
            {
                // no username, nor userID specified
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITMEDAL", "MSG_VALID_USER"), MessageTypes.warning);
                return;
            }

            if (this.UserNameList.SelectedValue.IsNotSet() && this.UserID.Text.IsNotSet())
            {
                // only username is specified, we must find id for it
                var users = this.GetRepository <User>()
                            .FindUserTyped(filter: true, userName: this.UserName.Text, displayName: this.UserName.Text);

                if (users.Count() > 1)
                {
                    // more than one user is avalilable for this username
                    this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITMEDAL", "MSG_AMBIGOUS_USER"), MessageTypes.warning);
                    return;
                }

                if (!users.Any())
                {
                    // no user found
                    this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITMEDAL", "MSG_VALID_USER"), MessageTypes.warning);
                    return;
                }

                // save id to the control
                this.UserID.Text = users.First().UserID.ToString();
            }
            else if (this.UserID.Text.IsNotSet())
            {
                // user is selected in dropdown, we must get id to UserID control
                this.UserID.Text = this.UserNameList.SelectedValue;
            }

            // save user, if there is no message specified, pass null
            LegacyDb.user_medal_save(
                this.UserID.Text,
                this.CurrentMedalID,
                this.UserMessage.Text.IsNotSet() ? null : this.UserMessage.Text,
                this.UserHide.Checked,
                this.UserOnlyRibbon.Checked,
                this.UserSortOrder.Text,
                null);

            if (this.Get <YafBoardSettings>().EmailUserOnMedalAward)
            {
                this.Get <ISendNotification>().ToUserWithNewMedal(
                    this.UserID.Text.ToType <int>(), this.Name.Text);
            }

            // disable/hide edit controls
            this.AddUserCancel_Click(sender, e);

            // clear cache...
            this.RemoveUserFromCache(this.UserID.Text.ToType <int>());

            // re-bind data
            this.BindData();
        }
コード例 #6
0
ファイル: Facebook.cs プロジェクト: MLindSog/YAFNET
        /// <summary>
        /// Connects the user.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="parameters">The access token.</param>
        /// <param name="message">The message.</param>
        /// <returns>
        /// Returns if the connect was successful or not
        /// </returns>
        public bool ConnectUser(HttpRequest request, string parameters, out string message)
        {
            var facebookUser = this.GetFacebookUser(request, parameters);

            // Check if username is null
            if (facebookUser.UserName.IsNotSet())
            {
                facebookUser.UserName = facebookUser.Name;
            }

            var userGender = 0;

            if (facebookUser.Gender.IsSet())
            {
                switch (facebookUser.Gender)
                {
                case "male":
                    userGender = 1;
                    break;

                case "female":
                    userGender = 2;
                    break;
                }
            }

            // Create User if not exists?!
            if (!YafContext.Current.IsGuest && !YafContext.Current.Get <YafBoardSettings>().DisableRegistrations)
            {
                // match the email address...
                if (facebookUser.Email != YafContext.Current.CurrentUserData.Email)
                {
                    message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOKNAME_NOTMATCH");

                    return(false);
                }

                // Update profile with facebook informations
                YafUserProfile userProfile = YafContext.Current.Profile;

                userProfile.Facebook   = facebookUser.ProfileURL;
                userProfile.FacebookId = facebookUser.UserID;
                userProfile.Homepage   = facebookUser.ProfileURL;

                if (facebookUser.Birthday.IsSet())
                {
                    DateTime userBirthdate;
                    var      ci = CultureInfo.CreateSpecificCulture("en-US");
                    DateTime.TryParse(facebookUser.Birthday, ci, DateTimeStyles.None, out userBirthdate);

                    if (userBirthdate > DateTimeHelper.SqlDbMinTime().Date)
                    {
                        userProfile.Birthday = userBirthdate;
                    }
                }

                userProfile.RealName = facebookUser.Name;
                userProfile.Gender   = userGender;

                if (facebookUser.Location != null && facebookUser.Location.Name.IsSet())
                {
                    userProfile.Location = facebookUser.Location.Name;
                }

                userProfile.Save();

                // save avatar
                LegacyDb.user_saveavatar(
                    YafContext.Current.PageUserID,
                    "https://graph.facebook.com/{0}/picture".FormatWith(facebookUser.UserID),
                    null,
                    null);

                YafSingleSignOnUser.LoginSuccess(AuthService.facebook, null, YafContext.Current.PageUserID, false);

                message = string.Empty;

                return(true);
            }

            message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOK_FAILED");
            return(false);
        }
コード例 #7
0
ファイル: test_data.ascx.cs プロジェクト: ahsan-sally/demo
        /// <summary>
        /// The create topics.
        /// </summary>
        /// <param name="forumID">
        /// The forum id.
        /// </param>
        /// <param name="numTopics">
        /// The num topics.
        /// </param>
        /// <param name="_messagesToCreate">
        /// The _messages to create.
        /// </param>
        /// <returns>
        /// Number of created topics.
        /// </returns>
        private int CreateTopics(int forumID, int numTopics, int _messagesToCreate)
        {
            object _priority = 0;

            if (forumID <= 0)
            {
                _priority = this.TopicsPriorityList.SelectedValue;
            }

            if (numTopics <= 0)
            {
                if (!int.TryParse(this.TopicsNumber.Text.Trim(), out numTopics))
                {
                    return(0);
                }
            }

            if (numTopics <= 0)
            {
                return(0);
            }

            int categoryID;

            if (!int.TryParse(this.TopicsCategory.SelectedValue, out categoryID))
            {
                return(0);
            }

            if (forumID <= 0)
            {
                if (!int.TryParse(this.TopicsForum.SelectedValue, out forumID))
                {
                    return(0);
                }
            }

            if (_messagesToCreate <= 0)
            {
                if (!int.TryParse(this.TopicsMessagesNumber.Text.Trim(), out _messagesToCreate))
                {
                    return(0);
                }
            }

            if (_messagesToCreate < 0)
            {
                return(0);
            }

            // if ( numTopics > createCommonLimit ) numTopics = createCommonLimit;
            int itopics;

            for (itopics = 0; itopics < numTopics; itopics++)
            {
                long messageid = 0;
                this.randomGuid = Guid.NewGuid().ToString();
                object pollID = null;

                var topicID = LegacyDb.topic_save(
                    forumID,
                    this.TopicPrefixTB.Text.Trim() + this.randomGuid,
                    string.Empty,
                    string.Empty,
                    "{0}{1}descr".FormatWith(this.TopicPrefixTB.Text.Trim(), this.randomGuid),
                    this.MessageContentPrefixTB.Text.Trim() + this.randomGuid,
                    this.PageContext.PageUserID,
                    _priority,
                    this.PageContext.User.UserName,
                    this.Request.GetUserRealIPAddress(),
                    DateTime.UtcNow,
                    string.Empty,
                    this.GetMessageFlags(),
                    ref messageid);

                if (this.PollCreate.Checked)
                {
                    // vzrus: always one in current code - a number of  questions
                    const int questionsTotal = 1;

                    var pollList = new List <PollSaveList>(questionsTotal);

                    var rawChoices = new string[3, 2];

                    rawChoices[0, 0] = "ans1-" + this.randomGuid;
                    rawChoices[0, 1] = "ans2-" + this.randomGuid;
                    rawChoices[1, 0] = null;
                    rawChoices[1, 1] = null;
                    rawChoices[2, 0] = null;
                    rawChoices[2, 1] = null;

                    object datePollExpire = null;
                    pollList.Add(
                        new PollSaveList(
                            "quest-" + this.randomGuid,
                            rawChoices,
                            (DateTime?)datePollExpire,
                            this.PageContext.PageUserID,
                            (int?)topicID,
                            null,
                            null,
                            null,
                            null,
                            null,
                            false,
                            false,
                            false,
                            false,
                            false));
                    pollID = LegacyDb.poll_save(pollList);
                }

                if (_messagesToCreate > 0)
                {
                    this.CreatePosts(forumID, topicID.ToType <int>(), _messagesToCreate);
                }

                // User != null ? null : From.Text
            }

            return(itopics);
        }
コード例 #8
0
        /// <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 userList =
                    LegacyDb.UserList(YafContext.Current.PageBoardID, toUserId, true, null, null, null).ToList();

                if (userList.Any())
                {
                    privateMessageNotificationEnabled = userList.First().PMNotification ?? false;
                    toEMail = userList.First().Email;
                }

                if (!privateMessageNotificationEnabled)
                {
                    return;
                }

                // get the PM ID
                // Ederon : 11/21/2007 - PageBoardID as parameter of DB.pmessage_list?
                // using (DataTable dt = DB.pmessage_list(toUserID, PageContext.PageBoardID, null))
                var userPMessageId =
                    LegacyDb.pmessage_list(toUserId, null, null).GetFirstRow().Field <int>("UserPMessageID");

                /*// get the sender e-mail -- DISABLED: too much information...
                 *  // using ( DataTable dt = YAF.Classes.Data.DB.user_list( PageContext.PageBoardID, PageContext.PageUserID, true ) )
                 *  // senderEmail = ( string ) dt.Rows [0] ["Email"];*/

                var languageFile = UserHelper.GetUserLanguageFile(toUserId);

                // send this user a PM notification e-mail
                var notificationTemplate = new YafTemplateEmail("PMNOTIFICATION")
                {
                    TemplateLanguageFile = languageFile
                };

                var displayName = this.Get <IUserDisplayName>().GetName(YafContext.Current.PageUserID);

                // fill the template with relevant info
                notificationTemplate.TemplateParams["{fromuser}"] = displayName;

                notificationTemplate.TemplateParams["{link}"] =
                    "{0}\r\n\r\n".FormatWith(
                        YafBuildLink.GetLinkNotEscaped(ForumPages.cp_message, true, "pm={0}", userPMessageId));
                notificationTemplate.TemplateParams["{forumname}"] = this.BoardSettings.Name;
                notificationTemplate.TemplateParams["{subject}"]   = subject;

                // create notification email subject
                var emailSubject =
                    this.Get <ILocalization>()
                    .GetText("COMMON", "PM_NOTIFICATION_SUBJECT", languageFile)
                    .FormatWith(displayName, this.BoardSettings.Name, subject);

                // send email
                notificationTemplate.SendEmail(new MailAddress(toEMail), emailSubject, true);
            }
            catch (Exception x)
            {
                // report exception to the forum's event log
                this.Get <ILogger>()
                .Error(x, "Send PM Notification Error for UserID {0}".FormatWith(YafContext.Current.PageUserID));

                // tell user about failure
                YafContext.Current.AddLoadMessage(
                    this.Get <ILocalization>().GetTextFormatted("Failed", x.Message),
                    MessageTypes.Error);
            }
        }
コード例 #9
0
        /// <summary>
        /// The to watching users.
        /// </summary>
        /// <param name="newMessageId">
        /// The new message id.
        /// </param>
        public void ToWatchingUsers(int newMessageId)
        {
            IList <User> usersWithAll = new List <User>();

            if (this.BoardSettings.AllowNotificationAllPostsAllTopics)
            {
                usersWithAll = this.GetRepository <User>()
                               .FindUserTyped(filter: false, notificationType: UserNotificationSetting.AllTopics.ToInt());
            }

            // TODO : Rewrite Watch Topic code to allow watch mails in the users language, as workaround send all messages in the default board language
            var languageFile = this.BoardSettings.Language;
            var boardName    = this.BoardSettings.Name;
            var forumEmail   = this.BoardSettings.ForumEmail;

            var message = LegacyDb.MessageList(newMessageId).FirstOrDefault();

            var messageAuthorUserID = message.UserID ?? 0;

            var watchEmail = new YafTemplateEmail("TOPICPOST")
            {
                TemplateLanguageFile = languageFile
            };

            // cleaned body as text...
            var bodyText =
                BBCodeHelper.StripBBCode(HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(message.Message)))
                .RemoveMultipleWhitespace();

            // Send track mails
            var subject =
                this.Get <ILocalization>()
                .GetText("COMMON", "TOPIC_NOTIFICATION_SUBJECT", languageFile)
                .FormatWith(boardName);

            watchEmail.TemplateParams["{forumname}"]     = boardName;
            watchEmail.TemplateParams["{topic}"]         = HttpUtility.HtmlDecode(message.Topic);
            watchEmail.TemplateParams["{postedby}"]      = UserMembershipHelper.GetDisplayNameFromID(messageAuthorUserID);
            watchEmail.TemplateParams["{body}"]          = bodyText;
            watchEmail.TemplateParams["{bodytruncated}"] = bodyText.Truncate(160);
            watchEmail.TemplateParams["{link}"]          = YafBuildLink.GetLinkNotEscaped(
                ForumPages.posts,
                true,
                "m={0}#post{0}",
                newMessageId);
            watchEmail.TemplateParams["{subscriptionlink}"] = YafBuildLink.GetLinkNotEscaped(ForumPages.cp_subscriptions, true);

            watchEmail.CreateWatch(
                message.TopicID ?? 0,
                messageAuthorUserID,
                new MailAddress(forumEmail, boardName),
                subject);

            // create individual watch emails for all users who have All Posts on...
            foreach (var user in usersWithAll.Where(x => x.UserID != messageAuthorUserID && x.ProviderUserKey != null))
            {
                var membershipUser = UserMembershipHelper.GetUser(user.ProviderUserKey.ToType <object>());

                if (membershipUser == null || membershipUser.Email.IsNotSet())
                {
                    continue;
                }

                watchEmail.TemplateLanguageFile = user.LanguageFile.IsSet()
                                                      ? user.LanguageFile
                                                      : this.Get <ILocalization>().LanguageFileName;
                watchEmail.SendEmail(
                    new MailAddress(forumEmail, boardName),
                    new MailAddress(membershipUser.Email, membershipUser.UserName),
                    subject,
                    true);
            }
        }
コード例 #10
0
ファイル: eventloggroups.ascx.cs プロジェクト: zghlx/YAFNET
        /* Methods */

        /// <summary>
        /// Binds the data.
        /// </summary>
        private void BindData()
        {
            // list admins but not host admins
            this.List.DataSource = LegacyDb.group_eventlogaccesslist(null);
            this.DataBind();
        }
コード例 #11
0
        /* Methods */

        /// <summary>
        /// The bind data.
        /// </summary>
        private void BindData()
        {
            bool found = false;

            if (this.Request.QueryString.GetFirstOrDefault("r") != null)
            {
                // Load the page access list.
                var dt = LegacyDb.eventloggroupaccess_list(this.Request.QueryString.GetFirstOrDefault("r"), null);

                // Get admin pages by page prefixes.
                var listEnumValues = Enum.GetValues(typeof(EventLogTypes));

                // Initialize list with a helper class.
                var adminPageAccesses = new List <GroupEventLogAccess>();

                // Iterate thru all admin pages
                foreach (int eventValue in listEnumValues)
                {
                    int eventTypeId = eventValue;
                    foreach (
                        var dr in dt.Rows.Cast <DataRow>().Where(dr => dr["EventTypeID"].ToType <int>() == eventTypeId))
                    {
                        found = true;
                        adminPageAccesses.Add(
                            new GroupEventLogAccess
                        {
                            GroupId       = this.Request.QueryString.GetFirstOrDefault("r").ToType <int>(),
                            EventTypeId   = eventTypeId,
                            EventTypeName = Enum.GetName(typeof(EventLogTypes), eventTypeId),
                            DeleteAccess  = dr["DeleteAccess"].ToType <bool>(),
                            ViewAccess    = true
                        });
                    }

                    // If it doesn't contain page for the user add it.
                    if (!found)
                    {
                        adminPageAccesses.Add(
                            new GroupEventLogAccess
                        {
                            GroupId       = this.Request.QueryString.GetFirstOrDefault("r").ToType <int>(),
                            EventTypeId   = eventTypeId,
                            EventTypeName = Enum.GetName(typeof(EventLogTypes), eventTypeId),
                            DeleteAccess  = false,
                            ViewAccess    = false
                        });
                    }

                    // Reset flag in the end of the outer loop
                    found = false;
                }

                if (dt != null && dt.HasRows())
                {
                    this.GroupName.Text = this.HtmlEncode(dt.Rows[0]["GroupName"]);
                }

                // get admin pages list with access flags.
                this.AccessList.DataSource = adminPageAccesses.AsEnumerable();
            }

            this.DataBind();
        }
コード例 #12
0
        /// <summary>
        /// The save_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void Save_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            string body = this._sig.Text;

            // find forbidden BBcodes in signature
            string detectedBbCode = this.Get <IFormatMessage>().BBCodeForbiddenDetector(body, this._allowedBbcodes, ',');

            if (this._allowedBbcodes.IndexOf("ALL") < 0)
            {
                if (detectedBbCode.IsSet() && detectedBbCode != "ALL")
                {
                    this.PageContext.AddLoadMessage(
                        this.GetTextFormatted("SIGNATURE_BBCODE_WRONG", detectedBbCode));
                    return;
                }

                if (detectedBbCode.IsSet() && detectedBbCode == "ALL")
                {
                    this.PageContext.AddLoadMessage(this.GetText("BBCODE_FORBIDDEN"));
                    return;
                }
            }

            // find forbidden HTMLTags in signature
            if (!this.PageContext.IsAdmin && this._allowedHtml.IndexOf("ALL") < 0)
            {
                string detectedHtmlTag = this.Get <IFormatMessage>().CheckHtmlTags(body, this._allowedHtml, ',');
                if (detectedHtmlTag.IsSet() && detectedHtmlTag != "ALL")
                {
                    this.PageContext.AddLoadMessage(detectedHtmlTag);
                    return;
                }

                if (detectedHtmlTag.IsSet() && detectedHtmlTag == "ALL")
                {
                    this.PageContext.AddLoadMessage(this.GetText("HTML_FORBIDDEN"));
                    return;
                }
            }

            // body = this.Get<IFormatMessage>().RepairHtml(this,body,false);
            if (this._sig.Text.Length > 0)
            {
                if (this._sig.Text.Length <= this._allowedNumberOfCharacters)
                {
                    LegacyDb.user_savesignature(this.CurrentUserID, this.Get <IBadWordReplace>().Replace(body));
                }
                else
                {
                    this.PageContext.AddLoadMessage(
                        this.GetTextFormatted("SIGNATURE_MAX", this._allowedNumberOfCharacters));

                    return;
                }
            }
            else
            {
                LegacyDb.user_savesignature(this.CurrentUserID, DBNull.Value);
            }

            // clear the cache for this user...
            this.Get <IRaiseEvent>().Raise(new UpdateUserEvent(this.CurrentUserID));

            if (this.InAdminPages)
            {
                this.BindData();
            }
            else
            {
                this.DoRedirect();
            }
        }
コード例 #13
0
        /// <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)
        {
            this.PageContext.QueryIDs = new QueryStringIDHelper("u");

            this._sig.BaseDir    = YafForumInfo.ForumClientFileRoot + "editors";
            this._sig.StyleSheet = this.Get <ITheme>().BuildThemePath("theme.css");

            DataTable sigData = LegacyDb.user_getsignaturedata(this.CurrentUserID, YafContext.Current.PageBoardID);

            if (sigData.Rows.Count > 0)
            {
                this._allowedBbcodes = sigData.Rows[0]["UsrSigBBCodes"].ToString().Trim().Trim(',').Trim();

                this._allowedHtml = sigData.Rows[0]["UsrSigHTMLTags"].ToString().Trim().Trim(',').Trim();

                this._allowedNumberOfCharacters = sigData.Rows[0]["UsrSigChars"].ToType <int>();
            }

            if (this.IsPostBack)
            {
                return;
            }

            this.save.Text    = this.GetText("COMMON", "SAVE");
            this.preview.Text = this.GetText("COMMON", "PREVIEW");
            this.cancel.Text  = this.GetText("COMMON", "CANCEL");

            var warningMessage = new StringBuilder();

            warningMessage.Append("<ul>");

            if (this._allowedBbcodes.IsSet())
            {
                warningMessage.AppendFormat(
                    "<li>{0}</li>",
                    this._allowedBbcodes.Contains("ALL")
                    ? this.GetText("BBCODE_ALLOWEDALL")
                    : this.GetTextFormatted("BBCODE_ALLOWEDLIST", this._allowedBbcodes));
            }
            else
            {
                warningMessage.AppendFormat("<li>{0}</li>", this.GetText("BBCODE_FORBIDDEN"));
            }

            if (this._allowedHtml.IsSet())
            {
                warningMessage.AppendFormat(
                    "<li>{0}</li>",
                    this._allowedHtml.Contains("ALL")
                    ? this.GetText("HTML_ALLOWEDALL")
                    : this.GetTextFormatted("HTML_ALLOWEDLIST", this._allowedHtml));
            }
            else
            {
                warningMessage.AppendFormat("<li>{0}</li>", this.GetText("HTML_FORBIDDEN"));
            }

            warningMessage.AppendFormat(
                "<li>{0}</li>",
                this._allowedNumberOfCharacters > 0
                    ? this.GetTextFormatted("SIGNATURE_CHARSMAX", this._allowedNumberOfCharacters)
                    : this.GetText("SIGNATURE_NOEDIT"));

            warningMessage.Append("</ul>");

            this.TagsAllowedWarning.Text = warningMessage.ToString();

            this.BindData();
        }
コード例 #14
0
        /// <summary>
        /// Gets the todays birthdays.
        /// </summary>
        /// TODO: Make DST shift for the user
        private void GetTodaysBirthdays()
        {
            if (!this.Get <YafBoardSettings>().ShowTodaysBirthdays)
            {
                return;
            }

            this.StatsTodaysBirthdays.Text = this.GetText("stats_birthdays");

            var users = this.Get <IDataCache>().GetOrSet(
                Constants.Cache.TodaysBirthdays,
                () => LegacyDb.User_ListTodaysBirthdays(this.PageContext.PageBoardID, this.Get <YafBoardSettings>().UseStyledNicks),
                TimeSpan.FromHours(1));

            if (users == null || !users.HasRows())
            {
                return;
            }

            foreach (DataRow user in users.Rows)
            {
                DateTime birth;

                if (!DateTime.TryParse(user["Birthday"].ToString(), out birth))
                {
                    continue;
                }

                int tz;

                if (!int.TryParse(user["TimeZone"].ToString(), out tz))
                {
                    tz = 0;
                }

                // Get the user birhday based on his timezone date.
                var dtt = birth.AddYears(DateTime.UtcNow.Year - birth.Year);

                // The user can be congratulated. The time zone in profile is saved in the list user timezone
                if (DateTime.UtcNow <= dtt.AddMinutes(-tz).ToUniversalTime() ||
                    DateTime.UtcNow >= dtt.AddMinutes(-tz + 1440).ToUniversalTime())
                {
                    continue;
                }

                this.BirthdayUsers.Controls.Add(
                    new UserLink
                {
                    UserID      = (int)user["UserID"],
                    ReplaceName = this.Get <YafBoardSettings>().EnableDisplayName
                                              ? user["UserDisplayName"].ToString()
                                              : user["UserName"].ToString(),
                    Style       = this.Get <IStyleTransform>().DecodeStyleByString(user["Style"].ToString(), false),
                    PostfixText = " ({0})".FormatWith(DateTime.Now.Year - user["Birthday"].ToType <DateTime>().Year)
                });

                var separator = new HtmlGenericControl {
                    InnerHtml = "&nbsp;,&nbsp;"
                };

                this.BirthdayUsers.Controls.Add(separator);
                if (!this.BirthdayUsers.Visible)
                {
                    this.BirthdayUsers.Visible = true;
                }
            }

            if (this.BirthdayUsers.Visible)
            {
                // Remove last Separator
                this.BirthdayUsers.Controls.RemoveAt(this.BirthdayUsers.Controls.Count - 1);
            }
        }
コード例 #15
0
        /// <summary>
        /// The bind data.
        /// </summary>
        private void BindData()
        {
            // default since date is now
            DateTime sinceDate = DateTime.UtcNow;

            // default since option is "since last visit"
            int sinceValue = 0;

            // is any "since"option selected
            if (this.Since.SelectedItem != null)
            {
                // get selected value
                sinceValue = int.Parse(this.Since.SelectedItem.Value);

                // sinceDate = DateTime.UtcNow;
                // no need to do it again (look above)
                // decrypt selected option
                if (sinceValue == 9999)
                {
                    // all
                    // get all, from the beginning
                    sinceDate = DateTimeHelper.SqlDbMinTime();
                }
                else if (sinceValue > 0)
                {
                    // days
                    // get posts newer then defined number of days
                    sinceDate = DateTime.UtcNow - TimeSpan.FromDays(sinceValue);
                }
                else if (sinceValue < 0)
                {
                    // hours
                    // get posts newer then defined number of hours
                    sinceDate = DateTime.UtcNow + TimeSpan.FromHours(sinceValue);
                }
            }

            // we want to filter topics since last visit
            if (sinceValue == 0)
            {
                sinceDate = this.Get <IYafSession>().LastVisit ?? DateTime.UtcNow;
            }

            // we are going to page results
            var pds = new PagedDataSource {
                AllowPaging = true, PageSize = this.PagerTop.PageSize
            };

            // page size defined by pager's size

            // get users, eventually filter by groups or ranks
            using (
                DataTable dt = LegacyDb.user_list(
                    this.PageContext.PageBoardID,
                    null,
                    null,
                    this.group.SelectedIndex <= 0 ? null : this.group.SelectedValue,
                    this.rank.SelectedIndex <= 0 ? null : this.rank.SelectedValue,
                    false))
            {
                using (DataView dv = dt.DefaultView)
                {
                    // filter by name or email
                    if (this.name.Text.Trim().Length > 0 || (this.Email.Text.Trim().Length > 0))
                    {
                        dv.RowFilter =
                            "(Name LIKE '%{0}%' OR DisplayName LIKE '%{0}%') AND Email LIKE '%{1}%'".FormatWith(
                                this.name.Text.Trim(), this.Email.Text.Trim());
                    }

                    // filter by date of registration
                    if (sinceValue != 9999)
                    {
                        dv.RowFilter += "{1}Joined > '{0}'".FormatWith(
                            sinceDate.ToString(), dv.RowFilter.IsNotSet() ? string.Empty : " AND ");
                    }

                    // set pager and datasource
                    this.PagerTop.Count = dv.Count;
                    pds.DataSource      = dv;

                    // page to render
                    pds.CurrentPageIndex = this.PagerTop.CurrentPageIndex;

                    // if we are above total number of pages, select last
                    if (pds.CurrentPageIndex >= pds.PageCount)
                    {
                        pds.CurrentPageIndex = pds.PageCount - 1;
                    }

                    // bind list
                    this.UserList.DataSource = pds;
                    this.UserList.DataBind();
                }
            }
        }
コード例 #16
0
ファイル: profile.ascx.cs プロジェクト: Nkay20/YAFNET
        /// <summary>
        /// The bind data.
        /// </summary>
        private void BindData()
        {
            MembershipUser user = null;

            try
            {
                user = UserMembershipHelper.GetMembershipUserById(this.UserId);
            }
            catch (Exception ex)
            {
                this.Get <ILogger>().Error(ex, this.UserId.ToString());
            }

            if (user == null || user.ProviderUserKey.ToString() == "0")
            {
                // No such user exists or this is an nntp user ("0")
                YafBuildLink.AccessDenied();
            }

            var userData = new CombinedUserDataHelper(user, this.UserId);

            // populate user information controls...
            // Is BuddyList feature enabled?
            if (this.Get <YafBoardSettings>().EnableBuddyList)
            {
                this.SetupBuddyList(this.UserId, userData);
            }
            else
            {
                // BuddyList feature is disabled. don't show any link.
                this.BuddyLi.Visible      = false;
                this.BuddyListTab.Visible = false;
                this.lnkBuddy.Visible     = false;
                this.ltrApproval.Visible  = false;
            }

            // Is album feature enabled?
            if (this.Get <YafBoardSettings>().EnableAlbum)
            {
                this.AlbumList1.UserID = this.UserId;
            }
            else
            {
                this.AlbumList1.Dispose();
            }

            var userNameOrDisplayName = this.HtmlEncode(this.Get <YafBoardSettings>().EnableDisplayName
                                            ? userData.DisplayName
                                            : userData.UserName);

            this.SetupUserProfileInfo(this.UserId, user, userData, userNameOrDisplayName);

            this.AddPageLinks(userNameOrDisplayName);

            this.SetupUserStatistics(userData);

            this.SetupUserLinks(userData, userNameOrDisplayName);

            this.SetupAvatar(this.UserId, userData);

            this.Groups.DataSource = RoleMembershipHelper.GetRolesForUser(userData.UserName);

            // EmailRow.Visible = PageContext.IsAdmin;
            this.ModerateTab.Visible = this.PageContext.IsAdmin || this.PageContext.IsForumModerator;
            this.ModerateLi.Visible  = this.PageContext.IsAdmin || this.PageContext.IsForumModerator;

            this.AdminUserButton.Visible = this.PageContext.IsAdmin;

            if (this.LastPosts.Visible)
            {
                this.LastPosts.DataSource =
                    LegacyDb.post_alluser(this.PageContext.PageBoardID, this.UserId, this.PageContext.PageUserID, 10)
                    .AsEnumerable();

                this.SearchUser.NavigateUrl = YafBuildLink.GetLinkNotEscaped(
                    ForumPages.search,
                    "postedby={0}",
                    userNameOrDisplayName);
            }

            this.DataBind();
        }
コード例 #17
0
        /// <summary>
        /// Export All Users
        /// </summary>
        /// <param name="type">
        /// The export format type.
        /// </param>
        private void ExportAllUsers(string type)
        {
            var usersList = LegacyDb.user_list(this.PageContext.PageBoardID, null, true);

            usersList.DataSet.DataSetName = "YafUserList";

            usersList.TableName = "YafUser";

            usersList.Columns.Remove("AvatarImage");
            usersList.Columns.Remove("AvatarImageType");

            usersList.Columns.Remove("ProviderUserKey");
            usersList.Columns.Remove("Password");
            usersList.Columns.Remove("Joined");
            usersList.Columns.Remove("LastVisit");
            usersList.Columns.Remove("IP");
            usersList.Columns.Remove("NumPosts");
            usersList.Columns.Remove("RankID");
            usersList.Columns.Remove("Flags");
            usersList.Columns.Remove("Points");
            usersList.Columns.Remove("IsApproved");
            usersList.Columns.Remove("IsActiveExcluded");
            usersList.Columns.Remove("IsCaptchaExcluded");
            usersList.Columns.Remove("IsDirty");
            usersList.Columns.Remove("Style");
            usersList.Columns.Remove("IsAdmin");
            usersList.Columns.Remove("IsGuest1");
            usersList.Columns.Remove("IsHostAdmin");

            // Add Profile Columns
            usersList.Columns.Add("RealName");
            usersList.Columns.Add("BlogServiceUrl");
            usersList.Columns.Add("Blog");
            usersList.Columns.Add("Gender");
            usersList.Columns.Add("MSN");
            usersList.Columns.Add("Birthday");
            usersList.Columns.Add("BlogServiceUsername");
            usersList.Columns.Add("BlogServicePassword");
            usersList.Columns.Add("AIM");
            usersList.Columns.Add("GoogleTalk");
            usersList.Columns.Add("Location");
            usersList.Columns.Add("Country");
            usersList.Columns.Add("Region");
            usersList.Columns.Add("City");
            usersList.Columns.Add("Interests");
            usersList.Columns.Add("Homepage");
            usersList.Columns.Add("Skype");
            usersList.Columns.Add("ICQ");
            usersList.Columns.Add("XMPP");
            usersList.Columns.Add("YIM");
            usersList.Columns.Add("Occupation");
            usersList.Columns.Add("Twitter");
            usersList.Columns.Add("TwitterId");
            usersList.Columns.Add("Facebook");

            usersList.Columns.Add("Roles");

            usersList.AcceptChanges();

            foreach (DataRow user in usersList.Rows)
            {
                var userProfile = YafUserProfile.GetProfile((string)user["Name"]);

                // Add Profile Fields to User List Table.
                user["RealName"]            = userProfile.RealName;
                user["Blog"]                = userProfile.Blog;
                user["Gender"]              = userProfile.Gender;
                user["MSN"]                 = userProfile.MSN;
                user["Birthday"]            = userProfile.Birthday;
                user["BlogServiceUsername"] = userProfile.BlogServiceUsername;
                user["BlogServicePassword"] = userProfile.BlogServicePassword;
                user["AIM"]                 = userProfile.AIM;
                user["Google"]              = userProfile.Google;
                user["GoogleId"]            = userProfile.GoogleId;
                user["Location"]            = userProfile.Location;
                user["Country"]             = userProfile.Country;
                user["Region"]              = userProfile.Region;
                user["City"]                = userProfile.City;
                user["Interests"]           = userProfile.Interests;
                user["Homepage"]            = userProfile.Homepage;
                user["Skype"]               = userProfile.Skype;
                user["ICQ"]                 = userProfile.ICQ;
                user["XMPP"]                = userProfile.XMPP;
                user["YIM"]                 = userProfile.YIM;
                user["Occupation"]          = userProfile.Occupation;
                user["Twitter"]             = userProfile.Twitter;
                user["TwitterId"]           = userProfile.TwitterId;
                user["Facebook"]            = userProfile.Facebook;
                user["FacebookId"]          = userProfile.FacebookId;

                user["Roles"] = this.Get <RoleProvider>().GetRolesForUser((string)user["Name"]).ToDelimitedString(",");

                usersList.AcceptChanges();
            }

            switch (type)
            {
            case "xml":
                this.ExportAsXml(usersList);
                break;

            case "csv":
                this.ExportAsCsv(usersList);
                break;
            }
        }
コード例 #18
0
ファイル: profile.ascx.cs プロジェクト: Nkay20/YAFNET
        /// <summary>
        /// The setup user profile info.
        /// </summary>
        /// <param name="userID">The user id.</param>
        /// <param name="user">The user.</param>
        /// <param name="userData">The user data.</param>
        /// <param name="userDisplayName">The user display name.</param>
        private void SetupUserProfileInfo(
            int userID,
            [NotNull] MembershipUser user,
            [NotNull] IUserData userData,
            [NotNull] string userDisplayName)
        {
            this.UserLabel1.UserID = userData.UserID;

            if (this.PageContext.IsAdmin && userData.DisplayName != user.UserName)
            {
                this.Name.Text = this.HtmlEncode("{0} ({1})".FormatWith(userData.DisplayName, user.UserName));
            }
            else
            {
                this.Name.Text = this.HtmlEncode(userDisplayName);
            }

            this.Joined.Text =
                "{0}".FormatWith(this.Get <IDateTime>().FormatDateLong(Convert.ToDateTime(userData.Joined)));

            // vzrus: Show last visit only to admins if user is hidden
            if (!this.PageContext.IsAdmin && Convert.ToBoolean(userData.DBRow["IsActiveExcluded"]))
            {
                this.LastVisit.Text    = this.GetText("COMMON", "HIDDEN");
                this.LastVisit.Visible = true;
            }
            else
            {
                this.LastVisitDateTime.DateTime = userData.LastVisit;
                this.LastVisitDateTime.Visible  = true;
            }

            if (this.User != null && userData.RankName.IsSet())
            {
                this.RankTR.Visible = true;
                this.Rank.Text      = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.RankName));
            }

            if (this.User != null && userData.Profile.Location.IsSet())
            {
                this.LocationTR.Visible = true;
                this.Location.Text      = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.Location));
            }

            if (this.User != null && userData.Profile.Country.Trim().IsSet() && !userData.Profile.Country.Equals("N/A"))
            {
                this.CountryTR.Visible = true;
                this.CountryLabel.Text =
                    this.HtmlEncode(
                        this.Get <IBadWordReplace>().Replace(this.GetText("COUNTRY", userData.Profile.Country.Trim())));

                this.CountryFlagImage.Src = this.Get <ITheme>()
                                            .GetItem(
                    "FLAGS",
                    "{0}_MEDIUM".FormatWith(userData.Profile.Country.Trim()),
                    YafForumInfo.GetURLToContent("images/flags/{0}.png".FormatWith(userData.Profile.Country.Trim())));

                this.CountryFlagImage.Alt = userData.Profile.Country.Trim();
                this.CountryFlagImage.Attributes.Add("title", this.CountryLabel.Text);
            }

            if (this.User != null && userData.Profile.Region.IsSet())
            {
                this.RegionTR.Visible = true;

                try
                {
                    var tag =
                        "RGN_{0}_{1}".FormatWith(
                            userData.Profile.Country.Trim().IsSet()
                                ? userData.Profile.Country.Trim()
                                : this.Get <ILocalization>().Culture.Name.Remove(0, 3).ToUpperInvariant(),
                            userData.Profile.Region);
                    this.RegionLabel.Text =
                        this.HtmlEncode(this.Get <IBadWordReplace>().Replace(this.GetText("REGION", tag)));
                }
                catch (Exception)
                {
                    this.RegionTR.Visible = false;
                }
            }

            if (this.User != null && userData.Profile.City.IsSet())
            {
                this.CityTR.Visible = true;
                this.CityLabel.Text = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.City));
            }

            if (this.User != null && userData.Profile.Location.IsSet())
            {
                this.LocationTR.Visible = true;
                this.Location.Text      = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.Location));
            }

            if (this.User != null && userData.Profile.RealName.IsSet())
            {
                this.RealNameTR.Visible = true;
                this.RealName.InnerText = this.HtmlEncode(
                    this.Get <IBadWordReplace>().Replace(userData.Profile.RealName));
            }

            if (this.User != null && userData.Profile.Interests.IsSet())
            {
                this.InterestsTR.Visible = true;
                this.Interests.InnerText =
                    this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.Interests));
            }

            if (this.User != null && (userData.Profile.Gender > 0))
            {
                string imagePath = string.Empty;
                string imageAlt  = string.Empty;

                this.GenderTR.Visible = true;
                switch (userData.Profile.Gender)
                {
                case 1:
                    imagePath = this.PageContext.Get <ITheme>().GetItem("ICONS", "GENDER_MALE", null);
                    imageAlt  = this.GetText("USERGENDER_MAS");
                    break;

                case 2:
                    imagePath = this.PageContext.Get <ITheme>().GetItem("ICONS", "GENDER_FEMALE", null);
                    imageAlt  = this.GetText("USERGENDER_FEM");
                    break;
                }

                this.Gender.InnerHtml =
                    @"<a><img src=""{0}"" alt=""{1}"" title=""{1}"" /></a>&nbsp;{1}".FormatWith(imagePath, imageAlt);
            }

            if (this.User != null && userData.Profile.Occupation.IsSet())
            {
                this.OccupationTR.Visible = true;
                this.Occupation.InnerText =
                    this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.Occupation));
            }

            this.ThanksFrom.Text = this.GetRepository <Thanks>().ThanksFromUser(userData.DBRow["userID"].ToType <int>())
                                   .ToString();
            int[] thanksToArray = LegacyDb.user_getthanks_to(userData.DBRow["userID"], this.PageContext.PageUserID);
            this.ThanksToTimes.Text      = thanksToArray[0].ToString();
            this.ThanksToPosts.Text      = thanksToArray[1].ToString();
            this.ReputationReceived.Text = YafReputation.GenerateReputationBar(userData.Points.Value, userData.UserID);

            if (this.Get <YafBoardSettings>().ShowUserOnlineStatus)
            {
                this.OnlineStatusImage1.UserID  = userID;
                this.OnlineStatusImage1.Visible = true;

                var suspended = userData.DBRow["Suspended"].ToType <DateTime?>();

                if (suspended.HasValue && suspended.Value > DateTime.UtcNow)
                {
                    this.ThemeImgSuspended.LocalizedTitle =
                        this.GetText("POSTS", "USERSUSPENDED")
                        .FormatWith(this.Get <IDateTime>().FormatDateTimeShort(suspended.Value));

                    this.ThemeImgSuspended.Visible  = true;
                    this.OnlineStatusImage1.Visible = false;
                }
                else
                {
                    this.ThemeImgSuspended.Visible = false;
                }
            }
            else
            {
                this.ThemeImgSuspended.Visible  = false;
                this.OnlineStatusImage1.Visible = false;
            }

            if (this.User != null && userData.Profile.XMPP.IsSet())
            {
                this.XmppTR.Visible = true;
                this.lblxmpp.Text   = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.XMPP));
            }

            if (this.User != null && userData.Profile.AIM.IsSet())
            {
                this.AimTR.Visible = true;
                this.lblaim.Text   = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.AIM));
            }

            if (this.User != null && userData.Profile.ICQ.IsSet())
            {
                this.IcqTR.Visible = true;
                this.lblicq.Text   = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.ICQ));
            }

            if (this.User != null && userData.Profile.MSN.IsSet())
            {
                this.MsnTR.Visible = true;
                this.lblmsn.Text   = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.MSN));
            }

            if (this.User != null && userData.Profile.Skype.IsSet())
            {
                this.SkypeTR.Visible = true;
                this.lblskype.Text   = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.Skype));
            }

            if (this.User != null && userData.Profile.YIM.IsSet())
            {
                this.YimTR.Visible = true;
                this.lblyim.Text   = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.YIM));
            }

            var loadHoverCardJs = false;

            if (this.User != null && userData.Profile.Facebook.IsSet())
            {
                this.FacebookTR.Visible = true;
                this.lblfacebook.Text   = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.Facebook));

                if (this.Get <YafBoardSettings>().EnableUserInfoHoverCards)
                {
                    this.lblfacebook.Attributes.Add("data-hovercard", this.lblfacebook.Text);
                    this.Facebook.Attributes.Add("data-hovercard", this.lblfacebook.Text);

                    this.lblfacebook.CssClass += " Facebook-HoverCard";
                    this.Facebook.CssClass    += " Facebook-HoverCard";

                    loadHoverCardJs = true;
                }
            }

            if (this.User != null && userData.Profile.Twitter.IsSet())
            {
                this.TwitterTR.Visible = true;
                this.lbltwitter.Text   = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(userData.Profile.Twitter));

                if (this.Get <YafBoardSettings>().EnableUserInfoHoverCards&& Config.IsTwitterEnabled)
                {
                    this.lbltwitter.Attributes.Add("data-hovercard", this.lbltwitter.Text);
                    this.Twitter.Attributes.Add("data-hovercard", this.lbltwitter.Text);

                    this.lbltwitter.CssClass += " Twitter-HoverCard";
                    this.Twitter.CssClass    += " Twitter-HoverCard";

                    loadHoverCardJs = true;
                }
            }

            if (loadHoverCardJs && this.Get <YafBoardSettings>().EnableUserInfoHoverCards&& Config.IsTwitterEnabled)
            {
                var hoverCardLoadJs = new StringBuilder();

                hoverCardLoadJs.Append(
                    JavaScriptBlocks.HoverCardLoadJs(
                        ".Facebook-HoverCard",
                        "Facebook",
                        this.GetText("DEFAULT", "LOADING_FB_HOVERCARD").ToJsString(),
                        this.GetText("DEFAULT", "ERROR_FB_HOVERCARD").ToJsString()));

                hoverCardLoadJs.Append(
                    JavaScriptBlocks.HoverCardLoadJs(
                        ".Twitter-HoverCard",
                        "Twitter",
                        this.GetText("DEFAULT", "LOADING_TWIT_HOVERCARD").ToJsString(),
                        this.GetText("DEFAULT", "ERROR_TWIT_HOVERCARD").ToJsString(),
                        "{0}{1}resource.ashx?twitterinfo=".FormatWith(
                            BaseUrlBuilder.BaseUrl.TrimEnd('/'),
                            BaseUrlBuilder.AppPath)));

                // Setup Hover Card JS
                YafContext.Current.PageElements.RegisterJsBlockStartup(
                    "hovercardtwitterfacebookjs",
                    hoverCardLoadJs.ToString());
            }

            if (this.User != null && userData.Profile.Birthday >= DateTimeHelper.SqlDbMinTime())
            {
                this.BirthdayTR.Visible = true;
                this.Birthday.Text      =
                    this.Get <IDateTime>()
                    .FormatDateLong(userData.Profile.Birthday.AddMinutes((double)(-userData.TimeZone)));
            }
            else
            {
                this.BirthdayTR.Visible = false;
            }

            // Show User Medals
            if (this.Get <YafBoardSettings>().ShowMedals)
            {
                var userMedalsTable = this.Get <YafDbBroker>().UserMedals(this.UserId);

                if (userMedalsTable.Rows.Count <= 0)
                {
                    this.MedalsRow.Visible = false;

                    return;
                }

                var ribbonBar = new StringBuilder(500);
                var medals    = new StringBuilder(500);

                DataRow    r;
                MedalFlags f;

                int i     = 0;
                int inRow = 0;

                // do ribbon bar first
                while (userMedalsTable.Rows.Count > i)
                {
                    r = userMedalsTable.Rows[i];
                    f = new MedalFlags(r["Flags"]);

                    // do only ribbon bar items first
                    if (!r["OnlyRibbon"].ToType <bool>())
                    {
                        break;
                    }

                    // skip hidden medals
                    if (!f.AllowHiding || !r["Hide"].ToType <bool>())
                    {
                        if (inRow == 3)
                        {
                            // add break - only three ribbons in a row
                            ribbonBar.Append("<br />");
                            inRow = 0;
                        }

                        var title = "{0}{1}".FormatWith(
                            r["Name"],
                            f.ShowMessage ? ": {0}".FormatWith(r["Message"]) : string.Empty);

                        ribbonBar.AppendFormat(
                            "<img src=\"{0}{5}/{1}\" width=\"{2}\" height=\"{3}\" alt=\"{4}\" title=\"{4}\" />",
                            YafForumInfo.ForumClientFileRoot,
                            r["SmallRibbonURL"],
                            r["SmallRibbonWidth"],
                            r["SmallRibbonHeight"],
                            title,
                            YafBoardFolders.Current.Medals);

                        inRow++;
                    }

                    // move to next row
                    i++;
                }

                // follow with the rest
                while (userMedalsTable.Rows.Count > i)
                {
                    r = userMedalsTable.Rows[i];
                    f = new MedalFlags(r["Flags"]);

                    // skip hidden medals
                    if (!f.AllowHiding || !r["Hide"].ToType <bool>())
                    {
                        medals.AppendFormat(
                            "<img src=\"{0}{6}/{1}\" width=\"{2}\" height=\"{3}\" alt=\"{4}{5}\" title=\"{4}{5}\" />",
                            YafForumInfo.ForumClientFileRoot,
                            r["SmallMedalURL"],
                            r["SmallMedalWidth"],
                            r["SmallMedalHeight"],
                            r["Name"],
                            f.ShowMessage ? ": {0}".FormatWith(r["Message"]) : string.Empty,
                            YafBoardFolders.Current.Medals);
                    }

                    // move to next row
                    i++;
                }

                this.MedalsPlaceHolder.Text = "{0}<br />{1}".FormatWith(ribbonBar, medals);
                this.MedalsRow.Visible      = true;
            }
        }
コード例 #19
0
 /// <summary>
 /// The bind data.
 /// </summary>
 private void BindData()
 {
     this.RankList.DataSource = LegacyDb.nntpforum_list(this.PageContext.PageBoardID, null, null, DBNull.Value);
     this.DataBind();
 }
コード例 #20
0
ファイル: BaseReportedPosts.cs プロジェクト: wqshabib/YAFNET
        /// <summary>
        /// The render.
        /// </summary>
        /// <param name="writer">
        /// The writer.
        /// </param>
        protected override void Render([NotNull] HtmlTextWriter writer)
        {
            // TODO: Needs better commentting.
            writer.WriteLine(@"<div id=""{0}"" class=""yafReportedPosts"">".FormatWith(this.ClientID));

            DataTable reportersList = LegacyDb.message_listreporters(this.MessageID);

            if (reportersList.Rows.Count <= 0)
            {
                return;
            }

            int i = 0;

            writer.BeginRender();

            foreach (DataRow reporter in reportersList.Rows)
            {
                string howMany = null;
                if (reporter["ReportedNumber"].ToType <int>() > 1)
                {
                    howMany = "({0})".FormatWith(reporter["ReportedNumber"]);
                }

                writer.WriteLine(
                    @"<table cellspacing=""0"" cellpadding=""0"" class=""content"" id=""yafreportedtable{0}"" style=""width:100%"">", this.ClientID);

                // If the message was previously resolved we have not null string
                // and can add an info about last user who resolved the message
                if (!string.IsNullOrEmpty(this.ResolvedDate))
                {
                    string resolvedByName =
                        LegacyDb.user_list(this.PageContext.PageBoardID, this.ResolvedBy.ToType <int>(), true).Rows[0]["Name"].ToString();

                    var resolvedByDisplayName =
                        UserMembershipHelper.GetDisplayNameFromID(this.ResolvedBy.ToType <long>()).IsSet()
                        ? this.Server.HtmlEncode(this.Get <IUserDisplayName>().GetName(this.ResolvedBy.ToType <int>()))
                        : this.Server.HtmlEncode(resolvedByName);

                    writer.Write(@"<tr class=""header2""><td>");
                    writer.Write(
                        @"<span class=""postheader"">{0}</span><a class=""YafReported_Link"" href=""{1}""> {2}</a><span class=""YafReported_ResolvedBy""> : {3}</span>",
                        this.GetText("RESOLVEDBY"),
                        YafBuildLink.GetLink(ForumPages.profile, "u={0}&name={1}", this.ResolvedBy.ToType <int>(), resolvedByDisplayName),
                        resolvedByDisplayName,
                        this.Get <IDateTime>().FormatDateTimeTopic(this.ResolvedDate));
                    writer.WriteLine(@"</td></tr>");
                }

                writer.Write(@"<tr class=""header2""><td>");
                writer.Write(
                    @"<span class=""YafReported_Complainer"">{3}</span><a class=""YafReported_Link"" href=""{1}""> {0}{2} </a>",
                    !string.IsNullOrEmpty(UserMembershipHelper.GetDisplayNameFromID(reporter["UserID"].ToType <long>()))
                    ? this.Server.HtmlEncode(this.Get <IUserDisplayName>().GetName(reporter["UserID"].ToType <int>()))
                    : this.Server.HtmlEncode(reporter["UserName"].ToString()),
                    YafBuildLink.GetLink(ForumPages.profile, "u={0}&name={1}", reporter["UserID"].ToType <int>(), reporter["UserName"].ToString()),
                    howMany,
                    this.GetText("REPORTEDBY"));
                writer.WriteLine(@"</td></tr>");

                string[] reportString = reporter["ReportText"].ToString().Trim().Split('|');

                foreach (string t in reportString)
                {
                    string[] textString = t.Split("??".ToCharArray());
                    writer.Write(@"<tr class=""post""><td>");
                    writer.Write(
                        @"<span class=""YafReported_DateTime"">{0}:</span>",
                        this.Get <IDateTime>().FormatDateTimeTopic(textString[0]));

                    // Apply style if a post was previously resolved
                    string resStyle = "post_res";
                    try
                    {
                        if (!(string.IsNullOrEmpty(textString[0]) && string.IsNullOrEmpty(this.ResolvedDate)))
                        {
                            if (Convert.ToDateTime(textString[0]) < Convert.ToDateTime(this.ResolvedDate))
                            {
                                resStyle = "post";
                            }
                        }
                    }
                    catch (Exception)
                    {
                        resStyle = "post_res";
                    }

                    if (textString.Length > 2)
                    {
                        writer.Write(@"<tr><td class=""{0}"">", resStyle);
                        writer.Write(textString[2]);
                        writer.WriteLine(@"</td></tr>");
                    }
                    else
                    {
                        writer.WriteLine(@"<tr  class=""post""><td>");
                        writer.Write(t);
                        writer.WriteLine(@"</td></tr>");
                    }
                }

                writer.WriteLine(@"<tr class=""postfooter""><td>");

                writer.Write(
                    @"<a class=""YafReported_Link"" href=""{1}"">{2} {0}</a>",
                    !string.IsNullOrEmpty(UserMembershipHelper.GetDisplayNameFromID(reporter["UserID"].ToType <long>()))
                    ? this.Server.HtmlEncode(this.Get <IUserDisplayName>().GetName(reporter["UserID"].ToType <int>()))
                    : this.Server.HtmlEncode(reporter["UserName"].ToString()),
                    YafBuildLink.GetLink(
                        ForumPages.pmessage, "u={0}&r={1}", reporter["UserID"].ToType <int>(), this.MessageID),
                    this.GetText("REPLYTO"));

                writer.WriteLine(@"</td></tr>");

                // TODO: Remove hard-coded formatting.
                if (i < reportersList.Rows.Count - 1)
                {
                    writer.Write("</table></br>");
                }
                else
                {
                    writer.WriteLine(@"</td></tr>");
                }

                i++;
            }

            // render controls...
            writer.Write(@"</table>");
            base.Render(writer);

            writer.WriteLine("</div>");
            writer.EndRender();
        }
コード例 #21
0
ファイル: test_data.ascx.cs プロジェクト: ahsan-sally/demo
        /// <summary>
        /// The create users.
        /// </summary>
        /// <param name="boardID">
        /// The board id.
        /// </param>
        /// <param name="_users_Number">
        /// The _users_ number.
        /// </param>
        /// <param name="_outCounter">
        /// The _out counter.
        /// </param>
        /// <param name="_countLimit">
        /// The _count limit.
        /// </param>
        /// <param name="_excludeCurrentBoard">
        /// The _exclude current board.
        /// </param>
        /// <returns>
        /// The string with number of created users.
        /// </returns>
        private string CreateUsers(
            int boardID, int _users_Number, int _outCounter, int _countLimit, bool _excludeCurrentBoard)
        {
            int iboards;

            // if ( _users_Number > createCommonLimit ) _users_Number = createCommonLimit;
            for (iboards = 0; iboards < _countLimit; iboards++)
            {
                boardID = this.UsersBoardsList.Items[iboards].Value.ToType <int>();
                int i;
                for (i = 0; i < this.UsersNumber.Text.Trim().ToType <int>(); i++)
                {
                    this.randomGuid = Guid.NewGuid().ToString();
                    var newEmail    = this.UserPrefixTB.Text.Trim() + this.randomGuid + "@test.info";
                    var newUsername = this.UserPrefixTB.Text.Trim() + this.randomGuid;

                    if (UserMembershipHelper.UserExists(newUsername, newEmail))
                    {
                        continue;
                    }

                    var hashinput = DateTime.UtcNow + newEmail + Security.CreatePassword(20);
                    var hash      = FormsAuthentication.HashPasswordForStoringInConfigFile(hashinput, "md5");

                    MembershipCreateStatus status;
                    var user = this.Get <MembershipProvider>().CreateUser(
                        newUsername,
                        this.Password.Text.Trim(),
                        newEmail,
                        this.Question.Text.Trim(),
                        this.Answer.Text.Trim(),
                        !this.Get <YafBoardSettings>().EmailVerification,
                        null,
                        out status);

                    if (status != MembershipCreateStatus.Success)
                    {
                        continue;
                    }

                    // setup inital roles (if any) for this user
                    RoleMembershipHelper.SetupUserRoles(boardID, newUsername);

                    // create the user in the YAF DB as well as sync roles...
                    var userID = RoleMembershipHelper.CreateForumUser(user, boardID);

                    // create profile
                    var userProfile = YafUserProfile.GetProfile(newUsername);

                    // setup their inital profile information
                    userProfile.Location = this.Location.Text.Trim();
                    userProfile.Homepage = this.HomePage.Text.Trim();
                    userProfile.Save();

                    // save the time zone...
                    if (
                        !(this.UsersBoardsList.Items[iboards].Value.ToType <int>() == YafContext.Current.PageBoardID &&
                          _excludeCurrentBoard))
                    {
                        LegacyDb.user_save(
                            LegacyDb.user_get(boardID, user.ProviderUserKey),
                            boardID,
                            null,
                            null,
                            null,
                            this.TimeZones.SelectedValue.ToType <int>(),
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null);
                        _outCounter++;
                    }
                }
            }

            return(_outCounter + " Users in " + iboards + " Board(s); ");
        }
コード例 #22
0
        /// <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.PageLinks.AddRoot();
            this.PageLinks.AddLink(
                this.GetText("ADMIN_ADMIN", "Administration"), YafBuildLink.GetLink(ForumPages.admin_admin));

            this.PageLinks.AddLink(this.GetText("TEAM", "FORUMS"), YafBuildLink.GetLink(ForumPages.admin_forums));
            this.PageLinks.AddLink(this.GetText("ADMIN_EDITFORUM", "TITLE"), string.Empty);

            this.Page.Header.Title = "{0} - {1} - {2}".FormatWith(
                this.GetText("ADMIN_ADMIN", "Administration"),
                this.GetText("TEAM", "FORUMS"),
                this.GetText("ADMIN_EDITFORUM", "TITLE"));

            this.Save.Text   = this.GetText("SAVE");
            this.Cancel.Text = this.GetText("CANCEL");

            // Populate Forum Images Table
            this.CreateImagesDataTable();

            this.ForumImages.Attributes["onchange"] =
                "getElementById('{1}').src='{0}{2}/' + this.value".FormatWith(
                    YafForumInfo.ForumClientFileRoot, this.Preview.ClientID, YafBoardFolders.Current.Forums);

            this.BindData();

            var forumId = this.GetQueryStringAsInt("fa") ?? this.GetQueryStringAsInt("copy");

            if (!forumId.HasValue)
            {
                // Currently creating a New Forum, and auto fill the Forum Sort Order + 1
                using (
                    DataTable dt = LegacyDb.forum_list(this.PageContext.PageBoardID, null))
                {
                    int sortOrder = 1;

                    try
                    {
                        DataRow highestRow = dt.Rows[dt.Rows.Count - 1];

                        sortOrder = (short)highestRow["SortOrder"] + sortOrder;
                    }
                    catch
                    {
                        sortOrder = 1;
                    }

                    this.SortOrder.Text = sortOrder.ToString();

                    return;
                }
            }

            using (DataTable dt = LegacyDb.forum_list(this.PageContext.PageBoardID, forumId.Value))
            {
                DataRow row   = dt.Rows[0];
                var     flags = new ForumFlags(row["Flags"]);
                this.Name.Text            = (string)row["Name"];
                this.Description.Text     = (string)row["Description"];
                this.SortOrder.Text       = row["SortOrder"].ToString();
                this.HideNoAccess.Checked = flags.IsHidden;
                this.Locked.Checked       = flags.IsLocked;
                this.IsTest.Checked       = flags.IsTest;
                this.ForumNameTitle.Text  = this.Name.Text;
                this.Moderated.Checked    = flags.IsModerated;
                this.Styles.Text          = row["Styles"].ToString();

                this.CategoryList.SelectedValue = row["CategoryID"].ToString();

                this.Preview.Src = "{0}images/spacer.gif".FormatWith(YafForumInfo.ForumClientFileRoot);

                ListItem item = this.ForumImages.Items.FindByText(row["ImageURL"].ToString());
                if (item != null)
                {
                    item.Selected    = true;
                    this.Preview.Src = "{0}{2}/{1}".FormatWith(
                        YafForumInfo.ForumClientFileRoot, row["ImageURL"], YafBoardFolders.Current.Forums); // path corrected
                }

                // populate parent forums list with forums according to selected category
                this.BindParentList();

                if (!row.IsNull("ParentID"))
                {
                    this.ParentList.SelectedValue = row["ParentID"].ToString();
                }

                if (!row.IsNull("ThemeURL"))
                {
                    this.ThemeList.SelectedValue = row["ThemeURL"].ToString();
                }

                this.remoteurl.Text = row["RemoteURL"].ToString();
            }

            this.NewGroupRow.Visible = false;
        }
コード例 #23
0
ファイル: test_data.ascx.cs プロジェクト: ahsan-sally/demo
        /// <summary>
        /// The create posts.
        /// </summary>
        /// <param name="forumID">
        /// The forum id.
        /// </param>
        /// <param name="topicID">
        /// The topic id.
        /// </param>
        /// <param name="numMessages">
        /// The num messages.
        /// </param>
        /// <returns>
        /// The number of created posts.
        /// </returns>
        private int CreatePosts(int forumID, int topicID, int numMessages)
        {
            if (numMessages <= 0)
            {
                if (!int.TryParse(this.PostsNumber.Text.Trim(), out numMessages))
                {
                    return(0);
                }
            }

            if (numMessages <= 0)
            {
                return(0);
            }

            int categoryID;

            if (!int.TryParse(this.PostsCategory.SelectedValue, out categoryID))
            {
                return(0);
            }

            if (forumID <= 0)
            {
                if (!int.TryParse(this.PostsForum.SelectedValue, out forumID))
                {
                    return(0);
                }
            }

            if (topicID <= 0)
            {
                if (!int.TryParse(this.PostsTopic.SelectedValue, out topicID))
                {
                    return(0);
                }
            }

            // if ( numMessages > createCommonLimit ) numMessages = createCommonLimit;
            long      messageid = 0;
            int       iposts;
            const int _replyTo = -1;

            for (iposts = 0; iposts < numMessages; iposts++)
            {
                this.randomGuid = Guid.NewGuid().ToString();
                LegacyDb.message_save(
                    topicID,
                    this.PageContext.PageUserID,
                    "msgd-" + this.randomGuid + "  " + this.MyMessage.Text.Trim(),
                    this.PageContext.User.UserName,
                    this.Request.GetUserRealIPAddress(),
                    null,
                    _replyTo,
                    this.GetMessageFlags(),
                    ref messageid);

                // User != null ? null : From.Text
            }

            return(iposts);
        }
コード例 #24
0
        /// <summary>
        /// The save_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void Save_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            if (this.CategoryList.SelectedValue.Trim().Length == 0)
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_CATEGORY"));
                return;
            }

            if (this.Name.Text.Trim().Length == 0)
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_NAME_FORUM"));
                return;
            }

            if (this.Description.Text.Trim().Length == 0)
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_DESCRIPTION"));
                return;
            }

            if (this.SortOrder.Text.Trim().Length == 0)
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_VALUE"));
                return;
            }

            short sortOrder;

            if (!ValidationHelper.IsValidPosShort(this.SortOrder.Text.Trim()))
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_POSITIVE_VALUE"));
                return;
            }

            if (!short.TryParse(this.SortOrder.Text.Trim(), out sortOrder))
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_NUMBER"));
                return;
            }

            if (this.remoteurl.Text.IsSet())
            {
                // add http:// by default
                if (!Regex.IsMatch(this.remoteurl.Text.Trim(), @"^(http|https|ftp|ftps|git|svn|news)\://.*"))
                {
                    this.remoteurl.Text = "http://" + this.remoteurl.Text.Trim();
                }

                if (!ValidationHelper.IsValidURL(this.remoteurl.Text))
                {
                    this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_INVALID_URL"));
                    return;
                }
            }

            // Forum
            // vzrus: it's stored in the DB as int
            int?forumId     = this.GetQueryStringAsInt("fa");
            int?forumCopyId = this.GetQueryStringAsInt("copy");

            object parentID = null;

            if (this.ParentList.SelectedValue.Length > 0)
            {
                parentID = this.ParentList.SelectedValue;
            }

            // parent selection check.
            if (parentID != null && parentID.ToString() == this.Request.QueryString.GetFirstOrDefault("fa"))
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_PARENT_SELF"));
                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)
            {
                int dependency = LegacyDb.forum_save_parentschecker(forumId.Value, parentID);
                if (dependency > 0)
                {
                    this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_CHILD_PARENT"));
                    return;
                }
            }

            // inital access mask
            if (!forumId.HasValue && !forumCopyId.HasValue)
            {
                if (this.AccessMaskID.SelectedValue.Length == 0)
                {
                    this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_INITAL_MASK"));
                    return;
                }
            }

            // duplicate name checking...
            if (!forumId.HasValue)
            {
                var forumList = LegacyDb.forum_list(this.PageContext.PageBoardID, null).AsEnumerable();

                if (forumList.Any() && !this.Get <YafBoardSettings>().AllowForumsWithSameName&&
                    forumList.Any(dr => dr.Field <string>("Name") == this.Name.Text.Trim()))
                {
                    this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITFORUM", "MSG_FORUMNAME_EXISTS"));
                    return;
                }
            }

            object themeUrl = null;

            if (this.ThemeList.SelectedValue.Length > 0)
            {
                themeUrl = this.ThemeList.SelectedValue;
            }

            var newForumId = LegacyDb.forum_save(
                forumId,
                this.CategoryList.SelectedValue,
                parentID,
                this.Name.Text.Trim(),
                this.Description.Text.Trim(),
                sortOrder,
                this.Locked.Checked,
                this.HideNoAccess.Checked,
                this.IsTest.Checked,
                this.Moderated.Checked,
                this.AccessMaskID.SelectedValue,
                IsNull(this.remoteurl.Text),
                themeUrl,
                this.ForumImages.SelectedIndex > 0 ? this.ForumImages.SelectedValue.Trim() : null,
                this.Styles.Text,
                false);

            this.GetRepository <ActiveAccess>().Reset();

            // Access
            if (forumId.HasValue || forumCopyId.HasValue)
            {
                foreach (var item in this.AccessList.Items.OfType <RepeaterItem>())
                {
                    int groupId = int.Parse(item.FindControlAs <Label>("GroupID").Text);

                    LegacyDb.forumaccess_save(newForumId, groupId, item.FindControlAs <DropDownList>("AccessmaskID").SelectedValue);
                }
            }

            this.ClearCaches();

            if (forumId.HasValue)
            {
                YafBuildLink.Redirect(ForumPages.admin_forums);
            }
            else
            {
                YafBuildLink.Redirect(ForumPages.admin_editforum, "fa={0}", newForumId);
            }
        }
コード例 #25
0
        /// <summary>
        /// Bind data for this control.
        /// </summary>
        private void BindData()
        {
            // load available images from images/medals folder
            using (var dt = new DataTable("Files"))
            {
                // create structure
                dt.Columns.Add("FileID", typeof(long));
                dt.Columns.Add("FileName", typeof(string));
                dt.Columns.Add("Description", typeof(string));

                // add blank row
                DataRow dr = dt.NewRow();
                dr["FileID"]      = 0;
                dr["FileName"]    = YafForumInfo.GetURLToContent("images/spacer.gif"); // use spacer.gif for Description Entry
                dr["Description"] = this.GetText("ADMIN_EDITMEDAL", "SELECT_IMAGE");
                dt.Rows.Add(dr);

                // add files from medals folder
                var dir =
                    new DirectoryInfo(
                        this.Request.MapPath("{0}{1}".FormatWith(YafForumInfo.ForumServerFileRoot, YafBoardFolders.Current.Medals)));
                FileInfo[] files = dir.GetFiles("*.*");

                long nFileID = 1;

                foreach (FileInfo file in from file in files
                         let sExt = file.Extension.ToLower()
                                    where sExt == ".png" || sExt == ".gif" || sExt == ".jpg"
                                    select file)
                {
                    dr                = dt.NewRow();
                    dr["FileID"]      = nFileID++;
                    dr["FileName"]    = file.Name;
                    dr["Description"] = file.Name;
                    dt.Rows.Add(dr);
                }

                // medal image
                this.MedalImage.DataSource     = dt;
                this.MedalImage.DataValueField = "FileName";
                this.MedalImage.DataTextField  = "Description";

                // ribbon bar image
                this.RibbonImage.DataSource     = dt;
                this.RibbonImage.DataValueField = "FileName";
                this.RibbonImage.DataTextField  = "Description";

                // small medal image
                this.SmallMedalImage.DataSource     = dt;
                this.SmallMedalImage.DataValueField = "FileName";
                this.SmallMedalImage.DataTextField  = "Description";

                // small ribbon bar image
                this.SmallRibbonImage.DataSource     = dt;
                this.SmallRibbonImage.DataValueField = "FileName";
                this.SmallRibbonImage.DataTextField  = "Description";
            }

            // bind data to controls
            this.DataBind();

            // load existing medal if we are editing one
            if (this.CurrentMedalID.HasValue)
            {
                // load users and groups who has been assigned this medal
                this.UserList.DataSource = LegacyDb.user_medal_list(null, this.CurrentMedalID);
                this.UserList.DataBind();
                this.GroupList.DataSource = LegacyDb.group_medal_list(null, this.CurrentMedalID);
                this.GroupList.DataBind();

                // enable adding users/groups
                this.AddUserRow.Visible  = true;
                this.AddGroupRow.Visible = true;

                using (DataTable dt = this.GetRepository <Medal>().List(this.CurrentMedalID))
                {
                    // get data row
                    DataRow row = dt.Rows[0];

                    // load flags
                    var flags = new MedalFlags(row["Flags"]);

                    // set controls
                    this.Name.Text               = row["Name"].ToString();
                    this.Description.Text        = row["Description"].ToString();
                    this.Message.Text            = row["Message"].ToString();
                    this.Category.Text           = row["Category"].ToString();
                    this.SortOrder.Text          = row["SortOrder"].ToString();
                    this.ShowMessage.Checked     = flags.ShowMessage;
                    this.AllowRibbon.Checked     = flags.AllowRibbon;
                    this.AllowHiding.Checked     = flags.AllowHiding;
                    this.AllowReOrdering.Checked = flags.AllowReOrdering;

                    // select images
                    this.SelectImage(this.MedalImage, this.MedalPreview, row["MedalURL"]);
                    this.SelectImage(this.RibbonImage, this.RibbonPreview, row["RibbonURL"]);
                    this.SelectImage(this.SmallMedalImage, this.SmallMedalPreview, row["SmallMedalURL"]);
                    this.SelectImage(this.SmallRibbonImage, this.SmallRibbonPreview, row["SmallRibbonURL"]);
                }

                using (var dt = this.GetRepository <Group>().List(boardId: this.PageContext.PageBoardID))
                {
                    this.AvailableGroupList.DataSource     = dt;
                    this.AvailableGroupList.DataTextField  = "Name";
                    this.AvailableGroupList.DataValueField = "GroupID";
                    this.AvailableGroupList.DataBind();
                }
            }
            else
            {
                // set all previews on blank image
                var spacerPath = YafForumInfo.GetURLToContent("images/spacer.gif"); // use spacer.gif for Description Entry

                this.MedalPreview.Src       = spacerPath;
                this.RibbonPreview.Src      = spacerPath;
                this.SmallMedalPreview.Src  = spacerPath;
                this.SmallRibbonPreview.Src = spacerPath;
            }
        }
コード例 #26
0
        /// <summary>
        ///     Returns the layout of the board
        /// </summary>
        /// <param name="boardID"> The board ID. </param>
        /// <param name="userID"> The user ID. </param>
        /// <param name="categoryID"> The category ID. </param>
        /// <param name="parentID"> The parent ID. </param>
        /// <returns> The board layout. </returns>
        public DataSet BoardLayout(int boardID, int userID, int?categoryID, int?parentID)
        {
            if (categoryID.HasValue && categoryID == 0)
            {
                categoryID = null;
            }

            using (var ds = new DataSet())
            {
                // get the cached version of forum moderators if it's valid
                DataTable moderator;
                if (this.BoardSettings.ShowModeratorList)
                {
                    moderator = this.GetModerators();
                }
                else
                {
                    // add dummy table.
                    moderator = new DataTable("Moderator");
                    moderator.Columns.AddRange(
                        new[]
                    {
                        new DataColumn("ForumID", typeof(int)), new DataColumn("ForumName", typeof(string)),
                        new DataColumn("ModeratorName", typeof(string)),
                        new DataColumn("ModeratorDisplayName", typeof(string)),
                        new DataColumn("ModeratorEmail", typeof(string)),
                        new DataColumn("ModeratorAvatar", typeof(string)),
                        new DataColumn("ModeratorAvatarImage", typeof(bool)),
                        new DataColumn("Style", typeof(string)), new DataColumn("IsGroup", typeof(bool))
                    });
                }

                // insert it into this DataSet
                ds.Tables.Add(moderator.Copy());

                // get the Category Table
                DataTable category = this.DataCache.GetOrSet(
                    Constants.Cache.ForumCategory,
                    () =>
                {
                    var catDt       = this.DbFunction.GetAsDataTable(cdb => cdb.category_list(boardID, null));
                    catDt.TableName = "Category";
                    return(catDt);
                },
                    TimeSpan.FromMinutes(this.BoardSettings.BoardCategoriesCacheTimeout));

                // add it to this dataset
                ds.Tables.Add(category.Copy());

                DataTable categoryTable = ds.Tables["Category"];

                if (categoryID.HasValue)
                {
                    // make sure this only has the category desired in the dataset
                    foreach (
                        DataRow row in
                        categoryTable.AsEnumerable().Where(row => row.Field <int>("CategoryID") != categoryID))
                    {
                        // delete it...
                        row.Delete();
                    }

                    categoryTable.AcceptChanges();
                }

                DataTable forum = LegacyDb.forum_listread(
                    boardID,
                    userID,
                    categoryID,
                    parentID,
                    this.BoardSettings.UseStyledNicks,
                    this.BoardSettings.UseReadTrackingByDatabase);

                forum.TableName = "Forum";
                ds.Tables.Add(forum.Copy());

                ds.Relations.Add(
                    "FK_Forum_Category",
                    categoryTable.Columns["CategoryID"],
                    ds.Tables["Forum"].Columns["CategoryID"],
                    false);

                ds.Relations.Add(
                    "FK_Moderator_Forum",
                    ds.Tables["Forum"].Columns["ForumID"],
                    ds.Tables["Moderator"].Columns["ForumID"],
                    false);

                bool deletedCategory = false;

                // remove empty categories...
                foreach (
                    DataRow row in
                    categoryTable.SelectTypedList(
                        row => new { row, childRows = row.GetChildRows("FK_Forum_Category") })
                    .Where(@t => [email protected]())
                    .Select(@t => @t.row))
                {
                    // remove this category...
                    row.Delete();
                    deletedCategory = true;
                }

                if (deletedCategory)
                {
                    categoryTable.AcceptChanges();
                }

                return(ds);
            }
        }
コード例 #27
0
        /* Methods */

        /// <summary>
        /// The bind data.
        /// </summary>
        private void BindData()
        {
            // list admins but not host admins
            this.List.DataSource = LegacyDb.admin_pageaccesslist(null, true);
            this.DataBind();
        }
コード例 #28
0
        /// <summary>
        /// The page_ load.
        /// </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)
        {
            this.PageContext.PageElements.RegisterJQuery();
            this.PageContext.PageElements.RegisterJsResourceInclude("blockUIJs", "js/jquery.blockUI.js");

            this.Page.Form.DefaultButton = this.search.UniqueID;

            this.search.Focus();

            if (this.IsPostBack)
            {
                return;
            }

            // create page links
            this.CreatePageLinks();

            this.search.Text = this.GetText("ADMIN_USERS", "SEARCH");

            this.NewUser.Text   = this.GetText("ADMIN_USERS", "NEW_USER");
            this.SyncUsers.Text = this.GetText("ADMIN_USERS", "SYNC_ALL");

            this.ImportUsers.Text    = this.GetText("ADMIN_USERS", "IMPORT");
            this.ExportUsersXml.Text = this.GetText("ADMIN_USERS", "EXPORT_XML");
            this.ExportUsersCsv.Text = this.GetText("ADMIN_USERS", "EXPORT_CSV");

            if (Config.IsAnyPortal)
            {
                this.ImportUsers.Visible = false;
                this.SyncUsers.Visible   = false;
            }

            ControlHelper.AddOnClickConfirmDialog(this.SyncUsers, this.GetText("ADMIN_USERS", "CONFIRM_SYNC"));

            // intialize since filter items
            this.InitSinceDropdown();

            // set since filter to last item "All time"
            this.Since.SelectedIndex   = this.Since.Items.Count - 1;
            this.LoadingImage.ImageUrl = YafForumInfo.GetURLToResource("images/loader.gif");

            // get list of user groups for filtering
            using (DataTable dt = LegacyDb.group_list(this.PageContext.PageBoardID, null))
            {
                // add empty item for no filtering
                DataRow newRow = dt.NewRow();
                newRow["Name"]    = string.Empty;
                newRow["GroupID"] = DBNull.Value;
                dt.Rows.InsertAt(newRow, 0);
                this.group.DataSource     = dt;
                this.group.DataTextField  = "Name";
                this.group.DataValueField = "GroupID";
                this.group.DataBind();
            }

            // get list of user ranks for filtering
            using (DataTable dt = LegacyDb.rank_list(this.PageContext.PageBoardID, null))
            {
                // add empty for for no filtering
                DataRow newRow = dt.NewRow();
                newRow["Name"]   = string.Empty;
                newRow["RankID"] = DBNull.Value;
                dt.Rows.InsertAt(newRow, 0);

                this.rank.DataSource     = dt;
                this.rank.DataTextField  = "Name";
                this.rank.DataValueField = "RankID";
                this.rank.DataBind();
            }

            // TODO : page size difinable?
            this.PagerTop.PageSize = 25;

            // Hide "New User" & Sync Button on DotNetNuke
            if (Config.IsDotNetNuke)
            {
                this.NewUser.Visible   = false;
                this.SyncUsers.Visible = false;
            }
        }
コード例 #29
0
ファイル: topics.ascx.cs プロジェクト: zghlx/YAFNET
        /// <summary>
        /// The bind data.
        /// </summary>
        private void BindData()
        {
            DataSet ds = this.Get <YafDbBroker>().BoardLayout(
                this.PageContext.PageBoardID,
                this.PageContext.PageUserID,
                this.PageContext.PageCategoryID,
                this.PageContext.PageForumID);

            if (ds.Tables["Forum"].HasRows())
            {
                this.ForumList.DataSource = ds.Tables["Forum"].Rows;
                this.SubForums.Visible    = true;
            }

            this.Pager.PageSize = this.Get <YafBoardSettings>().TopicsPerPage;

            // when userId is null it returns the count of all deleted messages
            int?userId = null;

            // get the userID to use for the deleted posts count...
            if (!this.Get <YafBoardSettings>().ShowDeletedMessagesToAll)
            {
                // only show deleted messages that belong to this user if they are not admin/mod
                if (!this.PageContext.IsAdmin && !this.PageContext.ForumModeratorAccess)
                {
                    userId = this.PageContext.PageUserID;
                }
            }

            DataTable dt = LegacyDb.announcements_list(
                this.PageContext.PageForumID,
                userId,
                null,
                DateTime.UtcNow,
                0,
                10,
                this.Get <YafBoardSettings>().UseStyledNicks,
                true,
                this.Get <YafBoardSettings>().UseReadTrackingByDatabase);

            if (dt != null)
            {
                dt = this.StyleTransformDataTable(dt);
            }

            int baseSize = this.Get <YafBoardSettings>().TopicsPerPage;

            this.Announcements.DataSource = dt;

            /*if (!m_bIgnoreQueryString && Request.QueryString["p"] != null)
             * {
             *      // show specific page (p is 1 based)
             *      int tPage = (int)Security.StringToLongOrRedirect(Request.QueryString["p"]);
             *
             *      if (tPage > 0)
             *      {
             *              Pager.CurrentPageIndex = tPage - 1;
             *      }
             * }*/

            int nCurrentPageIndex = this.Pager.CurrentPageIndex;

            DataTable dtTopics;

            if (this._showTopicListSelected == 0)
            {
                dtTopics = LegacyDb.topic_list(
                    this.PageContext.PageForumID,
                    userId,
                    DateTimeHelper.SqlDbMinTime(),
                    DateTime.UtcNow,
                    nCurrentPageIndex,
                    baseSize,
                    this.Get <YafBoardSettings>().UseStyledNicks,
                    true,
                    this.Get <YafBoardSettings>().UseReadTrackingByDatabase);
                if (dtTopics != null)
                {
                    dtTopics = this.StyleTransformDataTable(dtTopics);
                }
            }
            else
            {
                int[] days = { 1, 2, 7, 14, 31, 2 * 31, 6 * 31, 356 };

                DateTime date = DateTime.UtcNow.AddDays(-days[this._showTopicListSelected]);

                dtTopics = LegacyDb.topic_list(
                    this.PageContext.PageForumID,
                    userId,
                    date,
                    DateTime.UtcNow,
                    nCurrentPageIndex,
                    baseSize,
                    this.Get <YafBoardSettings>().UseStyledNicks,
                    true,
                    this.Get <YafBoardSettings>().UseReadTrackingByDatabase);

                if (dtTopics != null)
                {
                    dtTopics = this.StyleTransformDataTable(dtTopics);
                }
            }

            this.TopicList.DataSource = dtTopics;

            this.DataBind();

            // setup the show topic list selection after data binding
            this.ShowList.SelectedIndex       = this._showTopicListSelected;
            this.Get <IYafSession>().ShowList = this._showTopicListSelected;
            if (dtTopics != null && dtTopics.HasRows())
            {
                this.Pager.Count = dtTopics.AsEnumerable().First().Field <int>("TotalRows");
            }
        }
コード例 #30
0
        /// <summary>
        /// Binds the data.
        /// </summary>
        private void BindData()
        {
            using (
                DataTable dt =
                    LegacyDb.pmessage_list(
                        Security.StringToLongOrRedirect(this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("pm"))))
            {
                if (dt.Rows.Count > 0)
                {
                    DataRow row = dt.Rows[0];

                    // if the pm isn't from or two the current user--then it's access denied
                    if ((int)row["ToUserID"] != this.PageContext.PageUserID &&
                        (int)row["FromUserID"] != this.PageContext.PageUserID)
                    {
                        YafBuildLink.AccessDenied();
                    }

                    this.SetMessageView(
                        row["FromUserID"],
                        row["ToUserID"],
                        Convert.ToBoolean(row["IsInOutbox"]),
                        Convert.ToBoolean(row["IsArchived"]));

                    // get the return link to the pm listing
                    if (this.IsOutbox)
                    {
                        this.PageLinks.AddLink(
                            this.GetText("SENTITEMS"), YafBuildLink.GetLink(ForumPages.cp_pm, "v=out"));
                    }
                    else if (this.IsArchived)
                    {
                        this.PageLinks.AddLink(
                            this.GetText("ARCHIVE"), YafBuildLink.GetLink(ForumPages.cp_pm, "v=arch"));
                    }
                    else
                    {
                        this.PageLinks.AddLink(this.GetText("INBOX"), YafBuildLink.GetLink(ForumPages.cp_pm));
                    }

                    this.PageLinks.AddLink(row["Subject"].ToString());

                    this.Inbox.DataSource = dt;
                }
                else
                {
                    YafBuildLink.Redirect(ForumPages.cp_pm);
                }
            }

            this.DataBind();

            if (this.IsOutbox)
            {
                return;
            }

            var userPmessageId = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("pm").ToType <int>();

            LegacyDb.pmessage_markread(userPmessageId);
            this.Get <IDataCache>().Remove(Constants.Cache.ActiveUserLazyData.FormatWith(this.PageContext.PageUserID));
            this.Get <IRaiseEvent>().Raise(
                new UpdateUserPrivateMessageEvent(this.PageContext.PageUserID, userPmessageId));
        }