コード例 #1
0
ファイル: PostService.cs プロジェクト: yicong1352013/mvcforum
        /// <summary>
        /// Add a new post
        /// </summary>
        /// <param name="postContent"> </param>
        /// <param name="topic"> </param>
        /// <param name="user"></param>
        /// <param name="permissions"> </param>
        /// <returns>True if post added</returns>
        public Post AddNewPost(string postContent, Topic topic, MembershipUser user, out PermissionSet permissions)
        {
            // Get the permissions for the category that this topic is in
            permissions = _roleService.GetPermissions(topic.Category, UsersRole(user));

            // Check this users role has permission to create a post
            if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked)
            {
                // Throw exception so Ajax caller picks it up
                throw new ApplicationException(_localizationService.GetResourceString("Errors.NoPermission"));
            }

            // Has permission so create the post
            var newPost = new Post
            {
                PostContent = postContent,
                User        = user,
                Topic       = topic,
                IpAddress   = StringUtils.GetUsersIpAddress()
            };

            newPost = SanitizePost(newPost);

            var category = topic.Category;

            if (category.ModeratePosts == true)
            {
                newPost.Pending = true;
            }

            var e = new PostMadeEventArgs {
                Post = newPost, Api = _api
            };

            EventManager.Instance.FireBeforePostMade(this, e);

            if (!e.Cancel)
            {
                // create the post
                Add(newPost);

                // Update the users points score and post count for posting
                _membershipUserPointsService.Add(new MembershipUserPoints
                {
                    Points = _settingsService.GetSettings().PointsAddedPerPost,
                    User   = user
                });

                // add the last post to the topic
                topic.LastPost = newPost;

                EventManager.Instance.FireAfterPostMade(this, new PostMadeEventArgs {
                    Post = newPost, Api = _api
                });

                return(newPost);
            }

            return(newPost);
        }
コード例 #2
0
        private void MarkPostUpOrDown(Post post, MembershipUser postWriter, MembershipUser voter, PostType postType)
        {
            // Check this user is not the post owner
            if (voter.Id != postWriter.Id)
            {
                // Not the same person, now check they haven't voted on this post before
                if (post.Votes.All(x => x.User.Id != LoggedOnUser.Id))
                {
                    // Points to add or subtract to a user
                    var usersPoints = (postType == PostType.Negative) ?
                                      (-SettingsService.GetSettings().PointsDeductedNagativeVote) : (SettingsService.GetSettings().PointsAddedPostiveVote);

                    // Update the users points who wrote the post
                    _membershipUserPointsService.Add(new MembershipUserPoints {
                        Points = usersPoints, User = postWriter
                    });

                    // Update the post with the new vote of the voter
                    var vote = new Vote
                    {
                        Post   = post,
                        User   = voter,
                        Amount = (postType == PostType.Negative) ? (-1) : (1),
                        VotedByMembershipUser = LoggedOnUser,
                        DateVoted             = DateTime.Now
                    };
                    _voteService.Add(vote);

                    // Update the post with the new points amount
                    var newPointTotal = (postType == PostType.Negative) ? (post.VoteCount - 1) : (post.VoteCount + 1);
                    post.VoteCount = newPointTotal;
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// Mark a topic as solved
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="post"></param>
        /// <param name="marker"></param>
        /// <param name="solutionWriter"></param>
        /// <returns>True if topic has been marked as solved</returns>
        public async Task <bool> SolveTopic(Topic topic, Post post, MembershipUser marker, MembershipUser solutionWriter)
        {
            var solved = false;

            var e = new MarkedAsSolutionEventArgs
            {
                Topic          = topic,
                Post           = post,
                Marker         = marker,
                SolutionWriter = solutionWriter
            };

            EventManager.Instance.FireBeforeMarkedAsSolution(this, e);

            if (!e.Cancel)
            {
                // Make sure this user owns the topic or this is an admin, if not do nothing

                if (topic.User.Id == marker.Id || marker.Roles.Any(x => x.RoleName == Constants.AdminRoleName))
                {
                    // Update the post
                    post.IsSolution = true;
                    //_postRepository.Update(post);

                    // Update the topic
                    topic.Solved = true;
                    //SaveOrUpdate(topic);

                    // Assign points
                    // Do not give points to the user if they are marking their own post as the solution
                    if (marker.Id != solutionWriter.Id)
                    {
                        var result = await _membershipUserPointsService.Add(new MembershipUserPoints
                        {
                            Points      = _settingsService.GetSettings().PointsAddedForSolution,
                            User        = solutionWriter,
                            PointsFor   = PointsFor.Solution,
                            PointsForId = post.Id
                        });

                        if (!result.Successful)
                        {
                            // Just log don't throw
                            _loggingService.Error(result.ProcessLog.FirstOrDefault());
                        }
                    }

                    EventManager.Instance.FireAfterMarkedAsSolution(this, new MarkedAsSolutionEventArgs
                    {
                        Topic          = topic,
                        Post           = post,
                        Marker         = marker,
                        SolutionWriter = solutionWriter
                    });
                    solved = true;
                }
            }

            return(solved);
        }
コード例 #4
0
ファイル: VoteController.cs プロジェクト: zhyqhb/mvcforum
        private async Task <bool> MarkPostUpOrDown(Post post, MembershipUser postWriter, MembershipUser voter, PostType postType,
                                                   MembershipUser loggedOnReadOnlyUser)
        {
            var settings = SettingsService.GetSettings();

            // Check this user is not the post owner
            if (voter.Id != postWriter.Id)
            {
                // Not the same person, now check they haven't voted on this post before
                var votes = post.Votes.Where(x => x.VotedByMembershipUser.Id == loggedOnReadOnlyUser.Id).ToList();
                if (votes.Any())
                {
                    // Already voted, so delete the vote and remove the points
                    var votesToDelete = new List <Vote>();
                    votesToDelete.AddRange(votes);
                    foreach (var vote in votesToDelete)
                    {
                        _voteService.Delete(vote);
                    }

                    // Update the post with the new points amount
                    var newPointTotal = postType == PostType.Negative ? post.VoteCount + 1 : post.VoteCount - 1;
                    post.VoteCount = newPointTotal;
                }
                else
                {
                    // Points to add or subtract to a user
                    var usersPoints = postType == PostType.Negative
                        ? -settings.PointsDeductedNagativeVote
                        : settings.PointsAddedPostiveVote;

                    // Update the post with the new vote of the voter
                    var vote = new Vote
                    {
                        Post   = post,
                        User   = postWriter,
                        Amount = postType == PostType.Negative ? -1 : 1,
                        VotedByMembershipUser = voter,
                        DateVoted             = DateTime.UtcNow
                    };
                    _voteService.Add(vote);

                    // Update the users points who wrote the post
                    await _membershipUserPointsService.Add(new MembershipUserPoints
                    {
                        Points      = usersPoints,
                        User        = postWriter,
                        PointsFor   = PointsFor.Vote,
                        PointsForId = vote.Id
                    });

                    // Update the post with the new points amount
                    var newPointTotal = postType == PostType.Negative ? post.VoteCount - 1 : post.VoteCount + 1;
                    post.VoteCount = newPointTotal;
                }
            }

            return(true);
        }
コード例 #5
0
        /// <summary>
        /// Mark a topic as solved
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="post"></param>
        /// <param name="marker"></param>
        /// <param name="solutionWriter"></param>
        /// <returns>True if topic has been marked as solved</returns>
        public bool SolveTopic(Topic topic, Post post, MembershipUser marker, MembershipUser solutionWriter)
        {
            var solved = false;

            var e = new MarkedAsSolutionEventArgs
            {
                Topic          = topic,
                Post           = post,
                Marker         = marker,
                SolutionWriter = solutionWriter,
                Api            = _api
            };

            EventManager.Instance.FireBeforeMarkedAsSolution(this, e);

            if (!e.Cancel)
            {
                // Make sure this user owns the topic, if not do nothing
                if (topic.User.Id == marker.Id)
                {
                    // Update the post
                    post.IsSolution = true;
                    //_postRepository.Update(post);

                    // Update the topic
                    topic.Solved = true;
                    //SaveOrUpdate(topic);

                    // Assign points
                    // Do not give points to the user if they are marking their own post as the solution
                    if (marker.Id != solutionWriter.Id)
                    {
                        _membershipUserPointsService.Add(new MembershipUserPoints
                        {
                            Points = _settingsService.GetSettings().PointsAddedForSolution,
                            User   = solutionWriter
                        });
                    }

                    EventManager.Instance.FireAfterMarkedAsSolution(this, new MarkedAsSolutionEventArgs
                    {
                        Topic          = topic,
                        Post           = post,
                        Marker         = marker,
                        SolutionWriter = solutionWriter,
                        Api            = _api
                    });
                    solved = true;
                }
            }

            return(solved);
        }
コード例 #6
0
        public ActionResult ManageUserPoints(ManageUsersPointsViewModel viewModel)
        {
            using (var uow = UnitOfWorkManager.NewUnitOfWork())
            {
                // Repopulate viewmodel
                var user = MembershipService.GetUser(viewModel.Id);
                viewModel.AllPoints = _membershipUserPointsService.GetByUser(user).OrderByDescending(x => x.DateAdded).ToList();
                viewModel.User      = user;

                if (viewModel.Amount > 0)
                {
                    // Add the new points
                    var newPoints = new MembershipUserPoints
                    {
                        DateAdded = DateTime.UtcNow,
                        Notes     = viewModel.Note,
                        Points    = (int)viewModel.Amount,
                        PointsFor = PointsFor.Manual,
                        User      = user
                    };

                    _membershipUserPointsService.Add(newPoints);

                    try
                    {
                        uow.Commit();

                        ShowMessage(new GenericMessageViewModel
                        {
                            Message     = "Points Added",
                            MessageType = GenericMessages.success
                        });
                    }
                    catch (Exception ex)
                    {
                        uow.Rollback();
                        LoggingService.Error(ex);
                        ShowMessage(new GenericMessageViewModel
                        {
                            Message     = "There was an error adding the points",
                            MessageType = GenericMessages.danger
                        });
                    }
                }


                return(RedirectToAction("ManageUserPoints", new { id = user.Id }));
            }
        }
コード例 #7
0
ファイル: BadgeService.cs プロジェクト: yaobos/mvcforum
        /// <summary>
        /// Processes the user for the specified badge type
        /// </summary>
        /// <param name="badgeType"></param>
        /// <param name="user"></param>
        /// <returns>True if badge was awarded</returns>
        public bool ProcessBadge(BadgeType badgeType, MembershipUser user)
        {
            var databaseUpdateNeeded = false;

            var e = new BadgeEventArgs {
                User = user, BadgeType = badgeType
            };

            EventManager.Instance.FireBeforeBadgeAwarded(this, e);

            if (!e.Cancel)
            {
                if (_badges.ContainsKey(badgeType))
                {
                    if (!RecentlyProcessed(badgeType, user))
                    {
                        databaseUpdateNeeded = true;

                        var badgeSet = _badges[badgeType];

                        foreach (var badgeMapping in badgeSet)
                        {
                            if (!BadgeCanBeAwarded(user, badgeMapping))
                            {
                                continue;
                            }

                            // Instantiate the badge and execute the rule
                            var badge = GetInstance <IBadge>(badgeMapping);

                            if (badge != null)
                            {
                                var dbBadge = _badgeRepository.Get(badgeMapping.DbBadge.Id);

                                // Award badge?
                                if (badge.Rule(user))
                                {
                                    // Re-fetch the badge otherwise system will try and create new badges!
                                    if (dbBadge.AwardsPoints != null && dbBadge.AwardsPoints > 0)
                                    {
                                        var points = new MembershipUserPoints
                                        {
                                            Points      = (int)dbBadge.AwardsPoints,
                                            PointsFor   = PointsFor.Badge,
                                            PointsForId = dbBadge.Id,
                                            User        = user
                                        };
                                        _membershipUserPointsService.Add(points);
                                    }
                                    user.Badges.Add(dbBadge);
                                    _activityService.BadgeAwarded(badgeMapping.DbBadge, user, DateTime.UtcNow);

                                    EventManager.Instance.FireAfterBadgeAwarded(this,
                                                                                new BadgeEventArgs
                                    {
                                        User      = user,
                                        BadgeType = badgeType
                                    });
                                }
                                //else
                                //{
                                //    // If we get here the user should not have the badge
                                //    // Remove the badge if the user no longer has the criteria to be awarded it
                                //    // and also remove any points associated with it.
                                //    user.Badges.Remove(dbBadge);
                                //    _membershipUserPointsService.Delete(user, PointsFor.Badge, dbBadge.Id);
                                //}
                            }
                        }
                    }
                }
            }
            return(databaseUpdateNeeded);
        }
コード例 #8
0
        /// <inheritdoc />
        public async Task <IPipelineProcess <Post> > Process(IPipelineProcess <Post> input, IMvcForumContext context)
        {
            // Refresh contexts for all services
            _postEditService.RefreshContext(context);
            _membershipUserPointsService.RefreshContext(context);
            _settingsService.RefreshContext(context);
            _activityService.RefreshContext(context);
            _notificationService.RefreshContext(context);

            try
            {
                // Get the Current user from ExtendedData
                var username     = input.ExtendedData[Constants.ExtendedDataKeys.Username] as string;
                var loggedOnUser = await context.MembershipUser.FirstOrDefaultAsync(x => x.UserName == username);

                // Is this an edit? If so, create a post edit
                var isEdit = false;
                if (input.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.IsEdit))
                {
                    isEdit = input.ExtendedData[Constants.ExtendedDataKeys.IsEdit] as bool? == true;
                }

                if (isEdit)
                {
                    // Get the original post
                    var originalPost = await context.Post.Include(x => x.Topic).FirstOrDefaultAsync(x => x.Id == input.EntityToProcess.Id);

                    // Get content from Extended data
                    var postedContent = input.ExtendedData[Constants.ExtendedDataKeys.Content] as string;
                    input.EntityToProcess.PostContent = postedContent;

                    // This is an edit of a post
                    input.EntityToProcess.DateEdited = DateTime.Now;

                    // Grab the original name out the extended data
                    var topicName = input.ExtendedData[Constants.ExtendedDataKeys.Name] as string;
                    if (!originalPost.PostContent.Equals(postedContent, StringComparison.OrdinalIgnoreCase) || !originalPost.Topic.Name.Equals(topicName, StringComparison.OrdinalIgnoreCase))
                    {
                        // Create a post edit
                        var postEdit = new PostEdit
                        {
                            Post                = input.EntityToProcess,
                            DateEdited          = input.EntityToProcess.DateEdited,
                            EditedBy            = loggedOnUser,
                            OriginalPostContent = originalPost.PostContent,
                            OriginalPostTitle   = originalPost.IsTopicStarter ? originalPost.Topic.Name : string.Empty
                        };

                        // Add the post edit too
                        _postEditService.Add(postEdit);
                    }
                }
                else
                {
                    // Add the post
                    context.Post.Add(input.EntityToProcess);
                }

                // Now do a save
                await context.SaveChangesAsync();

                // Update the users points score and post count for posting a new post
                if (!isEdit)
                {
                    // make it last post if this is a new post
                    input.EntityToProcess.Topic.LastPost = input.EntityToProcess;

                    await _membershipUserPointsService.Add(new MembershipUserPoints
                    {
                        Points      = _settingsService.GetSettings().PointsAddedPerPost,
                        User        = input.EntityToProcess.User,
                        PointsFor   = PointsFor.Post,
                        PointsForId = input.EntityToProcess.Id
                    });

                    // Add post activity if it's not an edit, or topic starter and it's not pending
                    if (input.EntityToProcess.IsTopicStarter == false && input.EntityToProcess.Pending != true)
                    {
                        _activityService.PostCreated(input.EntityToProcess);
                    }
                }


                if (input.EntityToProcess.IsTopicStarter == false && input.EntityToProcess.Pending != true)
                {
                    // Send notifications
                    _notificationService.Notify(input.EntityToProcess.Topic, loggedOnUser, NotificationType.Post);
                }

                // Now do a final save
                await context.SaveChangesAsync();

                input.ProcessLog.Add("Post created successfully");
            }
            catch (Exception ex)
            {
                input.AddError(ex.Message);
                _loggingService.Error(ex);
            }

            return(input);
        }
コード例 #9
0
        public ActionResult Create(CreateTopicViewModel topicViewModel)
        {
            if (ModelState.IsValid)
            {
                // Quick check to see if user is locked out, when logged in
                if (LoggedOnUser.IsLockedOut || LoggedOnUser.DisablePosting == true || !LoggedOnUser.IsApproved)
                {
                    FormsAuthentication.SignOut();
                    return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoAccess")));
                }

                var      successfullyCreated = false;
                Category category;
                var      topic = new Topic();

                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    // Not using automapper for this one only, as a topic is a post and topic in one
                    category = _categoryService.Get(topicViewModel.Category);

                    // First check this user is allowed to create topics in this category
                    var permissions = RoleService.GetPermissions(category, UsersRole);

                    // Check this users role has permission to create a post
                    if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked || !permissions[AppConstants.PermissionCreateTopics].IsTicked)
                    {
                        // Throw exception so Ajax caller picks it up
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.NoPermission"));
                    }
                    else
                    {
                        // We get the banned words here and pass them in, so its just one call
                        // instead of calling it several times and each call getting all the words back
                        var           bannedWordsList = _bannedWordService.GetAll();
                        List <string> bannedWords     = null;
                        if (bannedWordsList.Any())
                        {
                            bannedWords = bannedWordsList.Select(x => x.Word).ToList();
                        }

                        topic = new Topic
                        {
                            Name     = _bannedWordService.SanitiseBannedWords(topicViewModel.Name, bannedWords),
                            Category = category,
                            User     = LoggedOnUser
                        };

                        // See if the user has actually added some content to the topic
                        if (!string.IsNullOrEmpty(topicViewModel.Content))
                        {
                            // Check for any banned words
                            topicViewModel.Content = _bannedWordService.SanitiseBannedWords(topicViewModel.Content, bannedWords);

                            // See if this is a poll and add it to the topic
                            if (topicViewModel.PollAnswers != null && topicViewModel.PollAnswers.Count > 0)
                            {
                                if (permissions[AppConstants.PermissionCreatePolls].IsTicked)
                                {
                                    // Create a new Poll
                                    var newPoll = new Poll
                                    {
                                        User = LoggedOnUser
                                    };

                                    // Create the poll
                                    _pollService.Add(newPoll);

                                    // Save the poll in the context so we can add answers
                                    unitOfWork.SaveChanges();

                                    // Now sort the answers
                                    var newPollAnswers = new List <PollAnswer>();
                                    foreach (var pollAnswer in topicViewModel.PollAnswers)
                                    {
                                        // Attach newly created poll to each answer
                                        pollAnswer.Poll = newPoll;
                                        _pollAnswerService.Add(pollAnswer);
                                        newPollAnswers.Add(pollAnswer);
                                    }
                                    // Attach answers to poll
                                    newPoll.PollAnswers = newPollAnswers;

                                    // Save the new answers in the context
                                    unitOfWork.SaveChanges();

                                    // Add the poll to the topic
                                    topic.Poll = newPoll;
                                }
                                else
                                {
                                    //No permission to create a Poll so show a message but create the topic
                                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                    {
                                        Message     = LocalizationService.GetResourceString("Errors.NoPermissionPolls"),
                                        MessageType = GenericMessages.info
                                    };
                                }
                            }

                            // Update the users points score for posting
                            _membershipUserPointsService.Add(new MembershipUserPoints
                            {
                                Points = SettingsService.GetSettings().PointsAddedPerPost,
                                User   = LoggedOnUser
                            });

                            // Create the topic
                            topic = _topicService.Add(topic);

                            // Save the changes
                            unitOfWork.SaveChanges();

                            // Now create and add the post to the topic
                            _topicService.AddLastPost(topic, topicViewModel.Content);

                            // Now check its not spam
                            var akismetHelper = new AkismetHelper(SettingsService);
                            if (!akismetHelper.IsSpam(topic))
                            {
                                // Add the tags if any too
                                if (!string.IsNullOrEmpty(topicViewModel.Tags))
                                {
                                    // Sanitise the tags
                                    topicViewModel.Tags = _bannedWordService.SanitiseBannedWords(topicViewModel.Tags, bannedWords);

                                    // Now add the tags
                                    _topicTagService.Add(topicViewModel.Tags.ToLower(), topic);
                                }

                                // Subscribe the user to the topic as they have checked the checkbox
                                if (topicViewModel.SubscribeToTopic)
                                {
                                    // Create the notification
                                    var topicNotification = new TopicNotification
                                    {
                                        Topic = topic,
                                        User  = LoggedOnUser
                                    };
                                    //save
                                    _topicNotificationService.Add(topicNotification);
                                }

                                try
                                {
                                    unitOfWork.Commit();
                                    successfullyCreated = true;

                                    // Successful, add this post to the Lucene index
                                    if (_luceneService.CheckIndexExists())
                                    {
                                        _luceneService.AddUpdate(_luceneService.MapToModel(topic));
                                    }
                                }
                                catch (Exception ex)
                                {
                                    unitOfWork.Rollback();
                                    LoggingService.Error(ex);
                                    ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                                }
                            }
                            else
                            {
                                unitOfWork.Rollback();
                                ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.PossibleSpam"));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                        }
                    }
                }

                using (UnitOfWorkManager.NewUnitOfWork())
                {
                    if (successfullyCreated)
                    {
                        // Success so now send the emails
                        NotifyNewTopics(category);

                        // Redirect to the newly created topic
                        return(Redirect(string.Format("{0}?postbadges=true", topic.NiceUrl)));
                    }

                    var allowedCategories = _categoryService.GetAllowedCategories(UsersRole).ToList();
                    if (allowedCategories.Any())
                    {
                        topicViewModel.Categories = allowedCategories;
                    }
                }
                return(View(topicViewModel));
            }

            return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
        }
コード例 #10
0
ファイル: BadgeService.cs プロジェクト: zhyqhb/mvcforum
        /// <summary>
        ///     Processes the user for the specified badge type
        /// </summary>
        /// <param name="badgeType"></param>
        /// <param name="user"></param>
        /// <returns>True if badge was awarded</returns>
        public async Task <bool> ProcessBadge(BadgeType badgeType, MembershipUser user)
        {
            var databaseUpdateNeeded = false;

            var e = new BadgeEventArgs {
                User = user, BadgeType = badgeType
            };

            EventManager.Instance.FireBeforeBadgeAwarded(this, e);

            if (!e.Cancel)
            {
                try
                {
                    if (_badges.ContainsKey(badgeType))
                    {
                        if (!RecentlyProcessed(badgeType, user))
                        {
                            databaseUpdateNeeded = true;

                            var badgeSet = _badges[badgeType];

                            foreach (var badgeMapping in badgeSet)
                            {
                                if (!BadgeCanBeAwarded(user, badgeMapping))
                                {
                                    continue;
                                }

                                // Instantiate the badge and execute the rule
                                IBadge badge;
                                if (badgeMapping.BadgeClassInstance != null)
                                {
                                    badge = badgeMapping.BadgeClassInstance;
                                }
                                else
                                {
                                    badgeMapping.BadgeClassInstance = UnityHelper.Container.Resolve(badgeMapping.BadgeClass) as IBadge;
                                    badge = badgeMapping.BadgeClassInstance;
                                }

                                if (badge != null)
                                {
                                    var dbBadge = Get(badgeMapping.DbBadge.Id);

                                    // Award badge?
                                    if (badge.Rule(user))
                                    {
                                        // Re-fetch the badge otherwise system will try and create new badges!
                                        if (dbBadge.AwardsPoints != null && dbBadge.AwardsPoints > 0)
                                        {
                                            var points = new MembershipUserPoints
                                            {
                                                Points      = (int)dbBadge.AwardsPoints,
                                                PointsFor   = PointsFor.Badge,
                                                PointsForId = dbBadge.Id,
                                                User        = user
                                            };
                                            var pointsAddResult = await _membershipUserPointsService.Add(points);

                                            if (!pointsAddResult.Successful)
                                            {
                                                _loggingService.Error(pointsAddResult.ProcessLog.FirstOrDefault());
                                                return(false);
                                            }
                                        }
                                        user.Badges.Add(dbBadge);
                                        //_activityService.BadgeAwarded(badgeMapping.DbBadge, user, DateTime.UtcNow);
                                        var badgeActivity =
                                            BadgeActivity.GenerateMappedRecord(badgeMapping.DbBadge, user, DateTime.UtcNow);
                                        _context.Activity.Add(badgeActivity);
                                        EventManager.Instance.FireAfterBadgeAwarded(this,
                                                                                    new BadgeEventArgs
                                        {
                                            User      = user,
                                            BadgeType = badgeType
                                        });
                                    }
                                    //else
                                    //{
                                    //    // If we get here the user should not have the badge
                                    //    // Remove the badge if the user no longer has the criteria to be awarded it
                                    //    // and also remove any points associated with it.
                                    //    user.Badges.Remove(dbBadge);
                                    //    _membershipUserPointsService.Delete(user, PointsFor.Badge, dbBadge.Id);
                                    //}
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _loggingService.Error(ex);
                }
            }
            return(databaseUpdateNeeded);
        }
コード例 #11
0
ファイル: TopicController.cs プロジェクト: NineMvp/mvcforum
        public ActionResult Create(CreateEditTopicViewModel topicViewModel)
        {
            // Get the category
            var category = _categoryService.Get(topicViewModel.Category);

            // First check this user is allowed to create topics in this category
            var permissions = RoleService.GetPermissions(category, UsersRole);

            // Now we have the category and permissionSet - Populate the optional permissions
            // This is just in case the viewModel is return back to the view also sort the allowedCategories
            var allowedCategories = _categoryService.GetAllowedCategories(UsersRole);

            topicViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions);
            topicViewModel.Categories          = GetBaseSelectListCategories(allowedCategories);
            topicViewModel.IsTopicStarter      = true;
            if (topicViewModel.PollAnswers == null)
            {
                topicViewModel.PollAnswers = new List <PollAnswer>();
            }
            /*---- End Re-populate ViewModel ----*/

            if (ModelState.IsValid)
            {
                // Quick check to see if user is locked out, when logged in
                if (LoggedOnUser.IsLockedOut || LoggedOnUser.DisablePosting == true || !LoggedOnUser.IsApproved)
                {
                    FormsAuthentication.SignOut();
                    return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoAccess")));
                }

                var successfullyCreated = false;
                var moderate            = false;
                var topic = new Topic();

                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    // Check this users role has permission to create a post
                    if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked || !permissions[AppConstants.PermissionCreateTopics].IsTicked)
                    {
                        // Add a model error that the user has no permissions
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.NoPermission"));
                    }
                    else
                    {
                        // We get the banned words here and pass them in, so its just one call
                        // instead of calling it several times and each call getting all the words back
                        var           bannedWordsList = _bannedWordService.GetAll();
                        List <string> bannedWords     = null;
                        if (bannedWordsList.Any())
                        {
                            bannedWords = bannedWordsList.Select(x => x.Word).ToList();
                        }

                        // Create the topic model
                        topic = new Topic
                        {
                            Name     = _bannedWordService.SanitiseBannedWords(topicViewModel.Name, bannedWords),
                            Category = category,
                            User     = LoggedOnUser
                        };

                        // Check Permissions for topic topions
                        if (permissions[AppConstants.PermissionLockTopics].IsTicked)
                        {
                            topic.IsLocked = topicViewModel.IsLocked;
                        }
                        if (permissions[AppConstants.PermissionCreateStickyTopics].IsTicked)
                        {
                            topic.IsSticky = topicViewModel.IsSticky;
                        }

                        // See if the user has actually added some content to the topic
                        if (!string.IsNullOrEmpty(topicViewModel.Content))
                        {
                            // Check for any banned words
                            topicViewModel.Content = _bannedWordService.SanitiseBannedWords(topicViewModel.Content, bannedWords);

                            // See if this is a poll and add it to the topic
                            if (topicViewModel.PollAnswers.Count > 0)
                            {
                                // Do they have permission to create a new poll
                                if (permissions[AppConstants.PermissionCreatePolls].IsTicked)
                                {
                                    // Create a new Poll
                                    var newPoll = new Poll
                                    {
                                        User = LoggedOnUser
                                    };

                                    // Create the poll
                                    _pollService.Add(newPoll);

                                    // Save the poll in the context so we can add answers
                                    unitOfWork.SaveChanges();

                                    // Now sort the answers
                                    var newPollAnswers = new List <PollAnswer>();
                                    foreach (var pollAnswer in topicViewModel.PollAnswers)
                                    {
                                        // Attach newly created poll to each answer
                                        pollAnswer.Poll = newPoll;
                                        _pollAnswerService.Add(pollAnswer);
                                        newPollAnswers.Add(pollAnswer);
                                    }
                                    // Attach answers to poll
                                    newPoll.PollAnswers = newPollAnswers;

                                    // Save the new answers in the context
                                    unitOfWork.SaveChanges();

                                    // Add the poll to the topic
                                    topic.Poll = newPoll;
                                }
                                else
                                {
                                    //No permission to create a Poll so show a message but create the topic
                                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                    {
                                        Message     = LocalizationService.GetResourceString("Errors.NoPermissionPolls"),
                                        MessageType = GenericMessages.info
                                    };
                                }
                            }

                            // Update the users points score for posting
                            _membershipUserPointsService.Add(new MembershipUserPoints
                            {
                                Points = SettingsService.GetSettings().PointsAddedPerPost,
                                User   = LoggedOnUser
                            });

                            // Check for moderation
                            if (category.ModerateTopics == true)
                            {
                                topic.Pending = true;
                                moderate      = true;
                            }

                            // Create the topic
                            topic = _topicService.Add(topic);

                            // Save the changes
                            unitOfWork.SaveChanges();

                            // Now create and add the post to the topic
                            var topicPost = _topicService.AddLastPost(topic, topicViewModel.Content);

                            // Now check its not spam
                            var akismetHelper = new AkismetHelper(SettingsService);
                            if (!akismetHelper.IsSpam(topic))
                            {
                                if (topicViewModel.Files != null)
                                {
                                    // Get the permissions for this category, and check they are allowed to update
                                    if (permissions[AppConstants.PermissionAttachFiles].IsTicked && LoggedOnUser.DisableFileUploads != true)
                                    {
                                        // woot! User has permission and all seems ok
                                        // Before we save anything, check the user already has an upload folder and if not create one
                                        var uploadFolderPath = Server.MapPath(string.Concat(SiteConstants.UploadFolderPath, LoggedOnUser.Id));
                                        if (!Directory.Exists(uploadFolderPath))
                                        {
                                            Directory.CreateDirectory(uploadFolderPath);
                                        }

                                        // Loop through each file and get the file info and save to the users folder and Db
                                        foreach (var file in topicViewModel.Files)
                                        {
                                            if (file != null)
                                            {
                                                // If successful then upload the file
                                                var uploadResult = AppHelpers.UploadFile(file, uploadFolderPath, LocalizationService);
                                                if (!uploadResult.UploadSuccessful)
                                                {
                                                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                                    {
                                                        Message     = uploadResult.ErrorMessage,
                                                        MessageType = GenericMessages.danger
                                                    };
                                                    unitOfWork.Rollback();
                                                    return(View(topicViewModel));
                                                }

                                                // Add the filename to the database
                                                var uploadedFile = new UploadedFile
                                                {
                                                    Filename       = uploadResult.UploadedFileName,
                                                    Post           = topicPost,
                                                    MembershipUser = LoggedOnUser
                                                };
                                                _uploadedFileService.Add(uploadedFile);
                                            }
                                        }
                                    }
                                }

                                // Add the tags if any too
                                if (!string.IsNullOrEmpty(topicViewModel.Tags))
                                {
                                    // Sanitise the tags
                                    topicViewModel.Tags = _bannedWordService.SanitiseBannedWords(topicViewModel.Tags, bannedWords);

                                    // Now add the tags
                                    _topicTagService.Add(topicViewModel.Tags.ToLower(), topic);
                                }

                                // Subscribe the user to the topic as they have checked the checkbox
                                if (topicViewModel.SubscribeToTopic)
                                {
                                    // Create the notification
                                    var topicNotification = new TopicNotification
                                    {
                                        Topic = topic,
                                        User  = LoggedOnUser
                                    };
                                    //save
                                    _topicNotificationService.Add(topicNotification);
                                }

                                try
                                {
                                    unitOfWork.Commit();
                                    if (!moderate)
                                    {
                                        successfullyCreated = true;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    unitOfWork.Rollback();
                                    LoggingService.Error(ex);
                                    ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                                }
                            }
                            else
                            {
                                unitOfWork.Rollback();
                                ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.PossibleSpam"));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                        }
                    }
                }

                using (UnitOfWorkManager.NewUnitOfWork())
                {
                    if (successfullyCreated)
                    {
                        // Success so now send the emails
                        NotifyNewTopics(category);

                        // Redirect to the newly created topic
                        return(Redirect(string.Format("{0}?postbadges=true", topic.NiceUrl)));
                    }
                    if (moderate)
                    {
                        // Moderation needed
                        // Tell the user the topic is awaiting moderation
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = LocalizationService.GetResourceString("Moderate.AwaitingModeration"),
                            MessageType = GenericMessages.info
                        };

                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(View(topicViewModel));
        }