예제 #1
0
        public ActionResult EditPost(EditPostViewModel editPostViewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Got to get a lot of things here as we have to check permissions
                // Get the post
                var post = _postService.Get(editPostViewModel.Id);

                // Get the topic
                var topic = post.Topic;

                // get the users permissions
                var permissions = RoleService.GetPermissions(topic.Category, UsersRole);

                if (post.User.Id == LoggedOnUser.Id || permissions[AppConstants.PermissionEditPosts].IsTicked)
                {
                    // User has permission so update the post
                    post.PostContent = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Content));
                    post.DateEdited  = DateTime.UtcNow;

                    // if topic starter update the topic
                    if (post.IsTopicStarter)
                    {
                        // if category has changed then update it
                        if (topic.Category.Id != editPostViewModel.Category)
                        {
                            var cat = _categoryService.Get(editPostViewModel.Category);
                            topic.Category = cat;
                        }

                        topic.IsLocked = editPostViewModel.IsLocked;
                        topic.IsSticky = editPostViewModel.IsSticky;
                        topic.Name     = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Name));

                        // See if there is a poll
                        if (editPostViewModel.PollAnswers != null && editPostViewModel.PollAnswers.Count > 0)
                        {
                            // Now sort the poll answers, what to add and what to remove
                            // Poll answers already in this poll.
                            var postedIds = editPostViewModel.PollAnswers.Select(x => x.Id);
                            //var existingAnswers = topic.Poll.PollAnswers.Where(x => postedIds.Contains(x.Id)).ToList();
                            var existingAnswers     = editPostViewModel.PollAnswers.Where(x => topic.Poll.PollAnswers.Select(p => p.Id).Contains(x.Id)).ToList();
                            var newPollAnswers      = editPostViewModel.PollAnswers.Where(x => !topic.Poll.PollAnswers.Select(p => p.Id).Contains(x.Id)).ToList();
                            var pollAnswersToRemove = topic.Poll.PollAnswers.Where(x => !postedIds.Contains(x.Id)).ToList();

                            // Loop through existing and update names if need be
                            //TODO: Need to think about this in future versions if they change the name
                            //TODO: As they could game the system by getting votes and changing name?
                            foreach (var existPollAnswer in existingAnswers)
                            {
                                // Get the existing answer from the current topic
                                var pa = topic.Poll.PollAnswers.FirstOrDefault(x => x.Id == existPollAnswer.Id);
                                if (pa != null && pa.Answer != existPollAnswer.Answer)
                                {
                                    // If the answer has changed then update it
                                    pa.Answer = existPollAnswer.Answer;
                                }
                            }

                            // Loop through and remove the old poll answers and delete
                            foreach (var oldPollAnswer in pollAnswersToRemove)
                            {
                                // Delete
                                _pollAnswerService.Delete(oldPollAnswer);

                                // Remove from Poll
                                topic.Poll.PollAnswers.Remove(oldPollAnswer);
                            }

                            // Poll answers to add
                            foreach (var newPollAnswer in newPollAnswers)
                            {
                                var npa = new PollAnswer
                                {
                                    Poll   = topic.Poll,
                                    Answer = newPollAnswer.Answer
                                };
                                _pollAnswerService.Add(npa);
                                topic.Poll.PollAnswers.Add(npa);
                            }
                        }
                        else
                        {
                            // Need to check if this topic has a poll, because if it does
                            // All the answers have now been removed so remove the poll.
                            if (topic.Poll != null)
                            {
                                //Firstly remove the answers if there are any
                                if (topic.Poll.PollAnswers != null && topic.Poll.PollAnswers.Any())
                                {
                                    var answersToDelete = new List <PollAnswer>();
                                    answersToDelete.AddRange(topic.Poll.PollAnswers);
                                    foreach (var answer in answersToDelete)
                                    {
                                        // Delete
                                        _pollAnswerService.Delete(answer);

                                        // Remove from Poll
                                        topic.Poll.PollAnswers.Remove(answer);
                                    }
                                }

                                // Now delete the poll
                                var pollToDelete = topic.Poll;
                                _pollService.Delete(pollToDelete);

                                // Remove from topic.
                                topic.Poll = null;
                            }
                        }

                        // Tags
                        topic.Tags.Clear();
                        if (!string.IsNullOrEmpty(editPostViewModel.Tags))
                        {
                            _topicTagService.Add(editPostViewModel.Tags.ToLower(), topic);
                        }
                    }

                    // redirect back to topic
                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                    {
                        Message     = LocalizationService.GetResourceString("Post.Updated"),
                        MessageType = GenericMessages.success
                    };
                    try
                    {
                        unitOfWork.Commit();

                        // Successful, add this post to the Lucene index
                        if (_luceneService.CheckIndexExists())
                        {
                            _luceneService.AddUpdate(_luceneService.MapToModel(post));
                        }

                        return(Redirect(topic.NiceUrl));
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        throw new Exception(LocalizationService.GetResourceString("Errors.GenericError"));
                    }
                }

                return(NoPermission(topic));
            }
        }
예제 #2
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")));
        }
예제 #3
0
        public ActionResult EditPostTopic(CreateEditTopicViewModel editPostViewModel)
        {
            // Get the category
            var category = _categoryService.Get(editPostViewModel.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);

            editPostViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions);
            editPostViewModel.Categories          = GetBaseSelectListCategories(allowedCategories);
            editPostViewModel.IsTopicStarter      = editPostViewModel.Id == Guid.Empty;
            if (editPostViewModel.PollAnswers == null)
            {
                editPostViewModel.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")));
                }

                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    // Got to get a lot of things here as we have to check permissions
                    // Get the post
                    var post = _postService.Get(editPostViewModel.Id);

                    // Get the topic
                    var topic = post.Topic;

                    if (post.User.Id == LoggedOnUser.Id || permissions[AppConstants.PermissionEditPosts].IsTicked)
                    {
                        // User has permission so update the post
                        post.PostContent = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Content));
                        post.DateEdited  = DateTime.UtcNow;

                        // if topic starter update the topic
                        if (post.IsTopicStarter)
                        {
                            // if category has changed then update it
                            if (topic.Category.Id != editPostViewModel.Category)
                            {
                                var cat = _categoryService.Get(editPostViewModel.Category);
                                topic.Category = cat;
                            }

                            topic.IsLocked = editPostViewModel.IsLocked;
                            topic.IsSticky = editPostViewModel.IsSticky;
                            topic.Name     = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Name));

                            // See if there is a poll
                            if (editPostViewModel.PollAnswers != null && editPostViewModel.PollAnswers.Count > 0)
                            {
                                // Now sort the poll answers, what to add and what to remove
                                // Poll answers already in this poll.
                                //var existingAnswers = topic.Poll.PollAnswers.Where(x => postedIds.Contains(x.Id)).ToList();
                                var postedIds           = editPostViewModel.PollAnswers.Select(x => x.Id);
                                var topicPollAnswerIds  = topic.Poll.PollAnswers.Select(p => p.Id).ToList();
                                var existingAnswers     = editPostViewModel.PollAnswers.Where(x => topicPollAnswerIds.Contains(x.Id)).ToList();
                                var newPollAnswers      = editPostViewModel.PollAnswers.Where(x => !topicPollAnswerIds.Contains(x.Id)).ToList();
                                var pollAnswersToRemove = topic.Poll.PollAnswers.Where(x => !postedIds.Contains(x.Id)).ToList();

                                // Loop through existing and update names if need be
                                //TODO: Need to think about this in future versions if they change the name
                                //TODO: As they could game the system by getting votes and changing name?
                                foreach (var existPollAnswer in existingAnswers)
                                {
                                    // Get the existing answer from the current topic
                                    var pa = topic.Poll.PollAnswers.FirstOrDefault(x => x.Id == existPollAnswer.Id);
                                    if (pa != null && pa.Answer != existPollAnswer.Answer)
                                    {
                                        // If the answer has changed then update it
                                        pa.Answer = existPollAnswer.Answer;
                                    }
                                }

                                // Loop through and remove the old poll answers and delete
                                foreach (var oldPollAnswer in pollAnswersToRemove)
                                {
                                    // Delete
                                    _pollAnswerService.Delete(oldPollAnswer);

                                    // Remove from Poll
                                    topic.Poll.PollAnswers.Remove(oldPollAnswer);
                                }

                                // Poll answers to add
                                foreach (var newPollAnswer in newPollAnswers)
                                {
                                    var npa = new PollAnswer
                                    {
                                        Poll   = topic.Poll,
                                        Answer = newPollAnswer.Answer
                                    };
                                    _pollAnswerService.Add(npa);
                                    topic.Poll.PollAnswers.Add(npa);
                                }
                            }
                            else
                            {
                                // Need to check if this topic has a poll, because if it does
                                // All the answers have now been removed so remove the poll.
                                if (topic.Poll != null)
                                {
                                    //Firstly remove the answers if there are any
                                    if (topic.Poll.PollAnswers != null && topic.Poll.PollAnswers.Any())
                                    {
                                        var answersToDelete = new List <PollAnswer>();
                                        answersToDelete.AddRange(topic.Poll.PollAnswers);
                                        foreach (var answer in answersToDelete)
                                        {
                                            // Delete
                                            _pollAnswerService.Delete(answer);

                                            // Remove from Poll
                                            topic.Poll.PollAnswers.Remove(answer);
                                        }
                                    }

                                    // Now delete the poll
                                    var pollToDelete = topic.Poll;
                                    _pollService.Delete(pollToDelete);

                                    // Remove from topic.
                                    topic.Poll = null;
                                }
                            }

                            // Tags
                            topic.Tags.Clear();
                            if (!string.IsNullOrEmpty(editPostViewModel.Tags))
                            {
                                _topicTagService.Add(editPostViewModel.Tags.ToLower(), topic);
                            }
                        }

                        // redirect back to topic
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = LocalizationService.GetResourceString("Post.Updated"),
                            MessageType = GenericMessages.success
                        };
                        try
                        {
                            unitOfWork.Commit();
                            return(Redirect(string.Format("{0}?postbadges=true", topic.NiceUrl)));
                        }
                        catch (Exception ex)
                        {
                            unitOfWork.Rollback();
                            LoggingService.Error(ex);
                            TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                            {
                                Message     = LocalizationService.GetResourceString("Errors.GenericError"),
                                MessageType = GenericMessages.danger
                            };
                        }
                    }

                    return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
                }
            }
            return(View(editPostViewModel));
        }