Example #1
0
        public PostEdit Add(PostEdit entity)
        {
            var isTheSame = false;
            var isEmpty = true;
            // only add if they are not the same
            if (!string.IsNullOrEmpty(entity.EditedPostTitle) && !string.IsNullOrEmpty(entity.OriginalPostTitle))
            {
                if (string.Compare(entity.EditedPostTitle, entity.OriginalPostTitle, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    isTheSame = true;
                }
                isEmpty = false;
            }            
            if (!string.IsNullOrEmpty(entity.EditedPostContent) && !string.IsNullOrEmpty(entity.OriginalPostContent))
            {
                if (string.Compare(entity.EditedPostContent, entity.OriginalPostContent, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // If we get here, and is empty is false and isthesame is false, it means the titles are 
                    // different - So DON't set as the same.
                    if (isEmpty == false && isTheSame == false)
                    {
                        // DO Nothing
                    }
                    else
                    {
                        isTheSame = true;
                    }
                }
                isEmpty = false;
            }

            // Check it's not empty and the data is not the same
            if (!isEmpty && !isTheSame)
            {
                return _context.PostEdit.Add(entity);
            }
            return entity;
        }
Example #2
0
 public void Delete(PostEdit entity)
 {
     _context.PostEdit.Remove(entity);
 }
Example #3
0
        public ActionResult EditPostTopic(CreateEditTopicViewModel editPostViewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // 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
                // Get the allowed categories for this user
                var allowedAccessCategories = _categoryService.GetAllowedCategories(UsersRole);
                var allowedCreateTopicCategories = _categoryService.GetAllowedCategories(UsersRole, SiteConstants.Instance.PermissionCreateTopics);
                var allowedCreateTopicCategoryIds = allowedCreateTopicCategories.Select(x => x.Id);
                allowedAccessCategories.RemoveAll(x => allowedCreateTopicCategoryIds.Contains(x.Id));
                editPostViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions);
                editPostViewModel.Categories = _categoryService.GetBaseSelectListCategories(allowedAccessCategories);
                editPostViewModel.IsTopicStarter = editPostViewModel.Id == Guid.Empty;
                if (editPostViewModel.PollAnswers == null)
                {
                    editPostViewModel.PollAnswers = new List<PollAnswer>();
                }

                if (ModelState.IsValid)
                {

                    try
                    {
                        var topicPostInModeration = false;

                        // Check stop words
                        var stopWords = _bannedWordService.GetAll(true);
                        foreach (var stopWord in stopWords)
                        {
                            if (editPostViewModel.Content.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
                                editPostViewModel.Name.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0)
                            {

                                ShowMessage(new GenericMessageViewModel
                                {
                                    Message = LocalizationService.GetResourceString("StopWord.Error"),
                                    MessageType = GenericMessages.danger
                                });

                                var p = _postService.Get(editPostViewModel.Id);
                                var t = p.Topic;

                                // Ahhh found a stop word. Abandon operation captain.
                                return Redirect(t.NiceUrl);
                            }
                        }

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

                        // 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 == LoggedOnReadOnlyUser.Id || permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked)
                        {

                            // Get the DB user so we can use lazy loading and update
                            var loggedOnUser = MembershipService.GetUser(LoggedOnReadOnlyUser.Id);

                            // Want the same edit date on both post and postedit
                            var dateEdited = DateTime.UtcNow;

                            // Create a post edit
                            var postEdit = new PostEdit
                            {
                                Post = post,
                                DateEdited = dateEdited,
                                EditedBy = loggedOnUser,
                                OriginalPostContent = post.PostContent,
                                OriginalPostTitle = post.IsTopicStarter ? topic.Name : string.Empty
                            };

                            // User has permission so update the post
                            post.PostContent = _bannedWordService.SanitiseBannedWords(editPostViewModel.Content);
                            post.DateEdited = dateEdited;

                            post = _postService.SanitizePost(post);

                            // Update postedit content
                            postEdit.EditedPostContent = post.PostContent;

                            // 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));

                                // Update post edit
                                postEdit.EditedPostTitle = topic.Name;

                                // See if there is a poll
                                if (editPostViewModel.PollAnswers != null && editPostViewModel.PollAnswers.Count(x => x != null && !string.IsNullOrEmpty(x.Answer)) > 0 && permissions[SiteConstants.Instance.PermissionCreatePolls].IsTicked)
                                {
                                    // 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.Where(x => x != null && !string.IsNullOrEmpty(x.Answer)).Select(x => x.Id);

                                    // This post might not have a poll on it, if not they are creating a poll for the first time
                                    var topicPollAnswerIds = new List<Guid>();
                                    var pollAnswersToRemove = new List<PollAnswer>();
                                    if (topic.Poll == null)
                                    {
                                        // 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();

                                        // Add the poll to the topic
                                        topic.Poll = newPoll;
                                    }
                                    else
                                    {
                                        topicPollAnswerIds = topic.Poll.PollAnswers.Select(p => p.Id).ToList();
                                        pollAnswersToRemove = topic.Poll.PollAnswers.Where(x => !postedIds.Contains(x.Id)).ToList();
                                    }

                                    // Set the amount of days to close the poll
                                    topic.Poll.ClosePollAfterDays = editPostViewModel.PollCloseAfterDays;

                                    var existingAnswers = editPostViewModel.PollAnswers.Where(x => !string.IsNullOrEmpty(x.Answer) && topicPollAnswerIds.Contains(x.Id)).ToList();
                                    var newPollAnswers = editPostViewModel.PollAnswers.Where(x => !string.IsNullOrEmpty(x.Answer) && !topicPollAnswerIds.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)
                                    {
                                        if (newPollAnswer != null)
                                        {
                                            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);
                                }

                                // if the Category has moderation marked then the topic needs to 
                                // go back into moderation
                                if (topic.Category.ModerateTopics == true)
                                {
                                    topic.Pending = true;
                                    topicPostInModeration = true;
                                }

                                // Sort the post search field
                                post.SearchField = _postService.SortSearchField(post.IsTopicStarter, topic, topic.Tags);
                            }
                            else
                            {
                                // if the Category has moderation marked then the post needs to 
                                // go back into moderation
                                if (topic.Category.ModeratePosts == true)
                                {
                                    post.Pending = true;
                                    topicPostInModeration = true;
                                }
                            }

                            // Add the post edit too
                            _postEditService.Add(postEdit);

                            // Commit the changes
                            unitOfWork.Commit();

                            if (topicPostInModeration)
                            {
                                // If in moderation then let the user now
                                TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                {
                                    Message = LocalizationService.GetResourceString("Moderate.AwaitingModeration"),
                                    MessageType = GenericMessages.info
                                };
                            }
                            else
                            {
                                TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                {
                                    Message = LocalizationService.GetResourceString("Post.Updated"),
                                    MessageType = GenericMessages.success
                                };
                            }

                            // redirect back to topic
                            return Redirect($"{topic.NiceUrl}?postbadges=true");
                        }
                    }
                    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);
        }