Пример #1
0
        public ActionResult ModerateTopic(ModerateActionViewModel viewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                try
                {
                    var topic      = _topicService.Get(viewModel.TopicId);
                    var postIdList = new List <Guid>();

                    if (viewModel.IsApproved)
                    {
                        topic.Pending = false;
                    }
                    else
                    {
                        var postId      = topic.LastPost.Id;
                        var post        = _postService.Get(postId);
                        var deleteTopic = _postService.Delete(post);

                        unitOfWork.SaveChanges();

                        if (deleteTopic)
                        {
                            postIdList = topic.Posts.Select(x => x.Id).ToList();
                            _topicService.Delete(topic);
                        }
                    }

                    // We use temp data because we are doing a redirect
                    //TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                    //{
                    //    Message = "Category Created",
                    //    MessageType =
                    //        GenericMessages.success
                    //};
                    unitOfWork.Commit();

                    // Delete the topic posts if
                    if (_luceneService.CheckIndexExists() && !viewModel.IsApproved)
                    {
                        foreach (var guid in postIdList)
                        {
                            _luceneService.Delete(guid);
                        }
                    }
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    LoggingService.Error(ex);
                    return(Content("error"));
                }
            }

            return(Content("allgood"));
        }
Пример #2
0
        public async Task <IActionResult> Delete(TopicDeleteModel model)
        {
            await _postService.DeletePostsByTopic(model.Id);

            await _topicService.Delete(model.Id);

            TempData["TopicDeletedMessage"] = "Topic deleted!";
            TempData.Keep("TopicDeletedMessage");

            return(RedirectToAction("Topics", "Forum", new { id = model.ForumId }));
        }
Пример #3
0
        public IActionResult Delete(int id)
        {
            var topic  = _topicService.GetById(id).Data;
            var result = _topicService.Delete(topic);

            if (result.Success)
            {
                return(Ok(result));
            }
            return(BadRequest(result));
        }
Пример #4
0
        /// <summary>
        /// Asks the service to delete the topic uniquely identified through Id.
        /// </summary>
        /// <param name="id">
        /// The topics unique identifier.
        /// </param>
        /// <returns>
        /// HTTP Status Code 204 - No Content if topic was successfully deleted, or did not exist,
        ///     HTTP Status Code 500 - Internal Server Error if the other codes don't apply. Contains exception on DEBUG.
        /// </returns>
        public IHttpActionResult Delete(int id)
        {
            var result = _topicService.Delete(id);

            if (result.ActionStatus.Status == ActionStatusEnum.Success)
            {
                return(StatusCode(HttpStatusCode.NoContent));
            }

            return(HandleErrorActionResult(result));
        }
Пример #5
0
        public virtual async Task <ActionResult> ModerateTopicAsync(ModerateActionViewModel viewModel, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                User.GetMembershipUser(MembershipService);
                var loggedOnUsersRole = LoggedOnReadOnlyUser.GetRole(RoleService);

                var topic       = _topicService.Get(viewModel.TopicId);
                var permissions = RoleService.GetPermissions(topic.Group, loggedOnUsersRole);

                // Is this user allowed to moderate - We use EditPosts for now until we change the permissions system
                if (!permissions[ForumConfiguration.Instance.PermissionEditPosts].IsTicked)
                {
                    return(Content(LocalizationService.GetResourceString("Errors.NoPermission")));
                }

                if (viewModel.IsApproved)
                {
                    topic.Pending = false;
                    _activityService.TopicCreated(topic);
                }
                else
                {
                    var topicResult = await _topicService.Delete(topic);

                    if (!topicResult.Successful)
                    {
                        return(Content(topicResult.ProcessLog.FirstOrDefault()));
                    }
                }

                Context.SaveChanges();
            }
            catch (Exception ex)
            {
                Context.RollBack();
                LoggingService.Error(ex);
                return(Content(ex.Message));
            }


            return(Content("allgood"));
        }
Пример #6
0
        public IActionResult Delete(string topicId)
        {
            if (topicId == null)
            {
                return(BadRequest("Topic info must not be null"));
            }

            int result = _topic.Delete(topicId);

            if (result == 0)
            {
                return(BadRequest("Faulthy topic info."));
            }
            if (result == 1)
            {
                return(NotFound("Topic not found"));
            }

            return(Ok("Topic is deleted."));
        }
        public ActionResult ModerateTopic(ModerateActionViewModel viewModel)
        {
            try
            {
                var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);
                var loggedOnUsersRole    = loggedOnReadOnlyUser.GetRole(RoleService);

                var topic       = _topicService.Get(viewModel.TopicId);
                var permissions = RoleService.GetPermissions(topic.Category, loggedOnUsersRole);

                // Is this user allowed to moderate - We use EditPosts for now until we change the permissions system
                if (!permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked)
                {
                    return(Content(LocalizationService.GetResourceString("Errors.NoPermission")));
                }

                if (viewModel.IsApproved)
                {
                    topic.Pending = false;
                    _activityService.TopicCreated(topic);
                }
                else
                {
                    _topicService.Delete(topic);
                }

                Context.SaveChanges();
            }
            catch (Exception ex)
            {
                Context.RollBack();
                LoggingService.Error(ex);
                return(Content(ex.Message));
            }


            return(Content("allgood"));
        }
Пример #8
0
        public ActionResult ModerateTopic(ModerateActionViewModel viewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                try
                {
                    var topic = _topicService.Get(viewModel.TopicId);

                    if (viewModel.IsApproved)
                    {
                        topic.Pending = false;
                    }
                    else
                    {
                        var postId      = topic.LastPost.Id;
                        var post        = _postService.Get(postId);
                        var deleteTopic = _postService.Delete(post);

                        unitOfWork.SaveChanges();

                        if (deleteTopic)
                        {
                            _topicService.Delete(topic);
                        }
                    }

                    unitOfWork.Commit();
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    LoggingService.Error(ex);
                    return(Content("error"));
                }
            }

            return(Content("allgood"));
        }
Пример #9
0
        public ActionResult ModerateTopic(ModerateActionViewModel viewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                try
                {
                    var topic       = _topicService.Get(viewModel.TopicId);
                    var permissions = RoleService.GetPermissions(topic.Category, UsersRole);

                    // Is this user allowed to moderate - We use EditPosts for now until we change the permissions system
                    if (!permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked)
                    {
                        return(Content(LocalizationService.GetResourceString("Errors.NoPermission")));
                    }

                    if (viewModel.IsApproved)
                    {
                        topic.Pending = false;
                    }
                    else
                    {
                        _topicService.Delete(topic, unitOfWork);
                    }

                    unitOfWork.Commit();
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    LoggingService.Error(ex);
                    return(Content(ex.Message));
                }
            }

            return(Content("allgood"));
        }
Пример #10
0
        private void DeleteUsersPostsPollsVotesAndPoints(MembershipUser user, IUnitOfWork unitOfWork)
        {
            // Delete all file uploads
            var files     = _uploadedFileService.GetAllByUser(user.Id);
            var filesList = new List <UploadedFile>();

            filesList.AddRange(files);
            foreach (var file in filesList)
            {
                // store the file path as we'll need it to delete on the file system
                var filePath = file.FilePath;

                // Now delete it
                _uploadedFileService.Delete(file);

                // And finally delete from the file system
                System.IO.File.Delete(Server.MapPath(filePath));
            }

            // Delete all posts
            var posts    = user.Posts;
            var postList = new List <Post>();

            postList.AddRange(posts);
            foreach (var post in postList)
            {
                post.Files.Clear();
                _postService.Delete(post);
            }

            unitOfWork.SaveChanges();

            // Also clear their poll votes
            var userPollVotes = user.PollVotes;

            if (userPollVotes.Any())
            {
                var pollList = new List <PollVote>();
                pollList.AddRange(userPollVotes);
                foreach (var vote in pollList)
                {
                    vote.User = null;
                    _pollVoteService.Delete(vote);
                }
                user.PollVotes.Clear();
            }

            unitOfWork.SaveChanges();


            // Also clear their polls
            var userPolls = user.Polls;

            if (userPolls.Any())
            {
                var polls = new List <Poll>();
                polls.AddRange(userPolls);
                foreach (var poll in polls)
                {
                    //Delete the poll answers
                    var pollAnswers = poll.PollAnswers;
                    if (pollAnswers.Any())
                    {
                        var pollAnswersList = new List <PollAnswer>();
                        pollAnswersList.AddRange(pollAnswers);
                        foreach (var answer in pollAnswersList)
                        {
                            answer.Poll = null;
                            _pollAnswerService.Delete(answer);
                        }
                    }

                    poll.PollAnswers.Clear();
                    poll.User = null;
                    _pollService.Delete(poll);
                }
                user.Polls.Clear();
            }

            unitOfWork.SaveChanges();

            // Delete all topics
            var topics    = user.Topics;
            var topicList = new List <Topic>();

            topicList.AddRange(topics);
            foreach (var topic in topicList)
            {
                _topicService.Delete(topic);
            }

            // Also clear their points
            var userPoints = user.Points;

            if (userPoints.Any())
            {
                var pointsList = new List <MembershipUserPoints>();
                pointsList.AddRange(userPoints);
                foreach (var point in pointsList)
                {
                    point.User = null;
                    _membershipUserPointsService.Delete(point);
                }
                user.Points.Clear();
            }

            unitOfWork.SaveChanges();

            // Now clear all activities for this user
            var usersActivities = _activityService.GetDataFieldByGuid(user.Id);

            _activityService.Delete(usersActivities.ToList());
        }
Пример #11
0
        public virtual async Task <ActionResult> Create(CreateEditTopicViewModel topicViewModel)
        {
            // Get the user and roles
            var loggedOnUser      = User.GetMembershipUser(MembershipService, false);
            var loggedOnUsersRole = loggedOnUser.GetRole(RoleService);

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

            // 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
            topicViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions);
            topicViewModel.Categories          =
                _categoryService.GetBaseSelectListCategories(AllowedCreateCategories(loggedOnUsersRole));
            topicViewModel.IsTopicStarter = true;
            if (topicViewModel.PollAnswers == null)
            {
                topicViewModel.PollAnswers = new List <PollAnswer>();
            }

            if (ModelState.IsValid)
            {
                // See if the user has actually added some content to the topic
                if (string.IsNullOrWhiteSpace(topicViewModel.Content))
                {
                    ModelState.AddModelError(string.Empty,
                                             LocalizationService.GetResourceString("Errors.GenericMessage"));
                }
                else
                {
                    // Map the new topic (Pass null for new topic)
                    var topic = topicViewModel.ToTopic(category, loggedOnUser, null);

                    // Run the create pipeline
                    var createPipeLine = await _topicService.Create(topic, topicViewModel.Files, topicViewModel.Tags,
                                                                    topicViewModel.SubscribeToTopic, topicViewModel.Content, null);

                    if (createPipeLine.Successful == false)
                    {
                        // TODO - Not sure on this?
                        // Remove the topic if unsuccessful, as we may have saved some items.
                        await _topicService.Delete(createPipeLine.EntityToProcess);

                        // Tell the user the topic is awaiting moderation
                        ModelState.AddModelError(string.Empty, createPipeLine.ProcessLog.FirstOrDefault());
                        return(View(topicViewModel));
                    }

                    if (createPipeLine.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Moderate))
                    {
                        var moderate = createPipeLine.ExtendedData[Constants.ExtendedDataKeys.Moderate] as bool?;
                        if (moderate == true)
                        {
                            // Tell the user the topic is awaiting moderation
                            TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                            {
                                Message     = LocalizationService.GetResourceString("Moderate.AwaitingModeration"),
                                MessageType = GenericMessages.info
                            };

                            var settings = SettingsService.GetSettings();
                            var sb       = new StringBuilder();
                            sb.Append($"<p>{string.Concat("New Topic is pending approval.")}</p>");
                            var email = new Email
                            {
                                EmailTo = settings.AdminEmailAddress,
                                NameTo  = "Dear Admin",
                                Subject = string.Concat("New Topic is pending approval")
                            };
                            email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                            _emailService.SendMail(email);
                            try
                            {
                                Context.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                Context.RollBack();
                                LoggingService.Error(ex);
                            }
                        }
                    }

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

            return(View(topicViewModel));
        }
Пример #12
0
        public ActionResult DeletePost(Guid id)
        {
            bool  isTopicStarter;
            Topic topic;

            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(id);

                // get this so we know where to redirect after
                isTopicStarter = post.IsTopicStarter;

                // Get the topic
                topic = post.Topic;

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

                if (post.User.Id == LoggedOnReadOnlyUser.Id || permissions[AppConstants.PermissionDeletePosts].IsTicked)
                {
                    var deleteTopic = _postService.Delete(post);

                    unitOfWork.SaveChanges();

                    if (deleteTopic)
                    {
                        _topicService.Delete(topic);
                    }

                    try
                    {
                        unitOfWork.Commit();
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
                    }
                }
            }

            // Deleted successfully
            if (isTopicStarter)
            {
                // Redirect to root as this was a topic and deleted
                TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                {
                    Message     = LocalizationService.GetResourceString("Topic.Deleted"),
                    MessageType = GenericMessages.success
                };
                return(RedirectToAction("Index", "Home"));
            }

            // Show message that post is deleted
            TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
            {
                Message     = LocalizationService.GetResourceString("Post.Deleted"),
                MessageType = GenericMessages.success
            };

            return(Redirect(topic.NiceUrl));
        }
Пример #13
0
        /// <inheritdoc />
        public async Task <IPipelineProcess <MembershipUser> > Process(IPipelineProcess <MembershipUser> input,
                                                                       IMvcForumContext context)
        {
            _voteService.RefreshContext(context);
            _notificationService.RefreshContext(context);
            _favouriteService.RefreshContext(context);
            _membershipUserPointsService.RefreshContext(context);
            _activityService.RefreshContext(context);
            _pollService.RefreshContext(context);
            _topicService.RefreshContext(context);
            _groupService.RefreshContext(context);
            _postService.RefreshContext(context);

            try
            {
                // Delete all topics
                var topics = input.EntityToProcess.Topics;
                if (topics != null && topics.Any())
                {
                    var topicList = new List <Topic>();
                    topicList.AddRange(topics);
                    foreach (var topic in topicList)
                    {
                        var topicDeleteResult = await _topicService.Delete(topic);

                        if (!topicDeleteResult.Successful)
                        {
                            input.AddError(topicDeleteResult.ProcessLog.FirstOrDefault());
                            return(input);
                        }
                    }
                    input.EntityToProcess.Topics.Clear();
                    await context.SaveChangesAsync();
                }

                // Now sorts Last Posts on topics and delete all the users posts
                var posts = input.EntityToProcess.Posts;
                if (posts != null && posts.Any())
                {
                    var postIds = posts.Select(x => x.Id).ToList();

                    // Get all Groups
                    var allGroups = _groupService.GetAll(input.EntityToProcess.Id);

                    // Need to see if any of these are last posts on Topics
                    // If so, need to swap out last post
                    var lastPostTopics = _topicService.GetTopicsByLastPost(postIds, allGroups.ToList());
                    foreach (var topic in lastPostTopics.Where(x => x.User.Id != input.EntityToProcess.Id))
                    {
                        var lastPost = topic.Posts.Where(x => !postIds.Contains(x.Id))
                                       .OrderByDescending(x => x.DateCreated)
                                       .FirstOrDefault();
                        topic.LastPost = lastPost;
                    }

                    await context.SaveChangesAsync();

                    // Delete all posts
                    var postList = new List <Post>();
                    postList.AddRange(posts);
                    foreach (var post in postList)
                    {
                        // Delete post via pipeline
                        var postDeleteResult = await _postService.Delete(post, true);

                        if (!postDeleteResult.Successful)
                        {
                            input.AddError(postDeleteResult.ProcessLog.FirstOrDefault());
                            return(input);
                        }
                    }

                    input.EntityToProcess.UploadedFiles.Clear();
                    input.EntityToProcess.Posts.Clear();

                    await context.SaveChangesAsync();
                }

                // User Votes
                if (input.EntityToProcess.Votes != null)
                {
                    var votesToDelete = new List <Vote>();
                    votesToDelete.AddRange(input.EntityToProcess.Votes);
                    votesToDelete.AddRange(input.EntityToProcess.VotesGiven);
                    foreach (var d in votesToDelete)
                    {
                        _voteService.Delete(d);
                    }
                    input.EntityToProcess.Votes.Clear();
                    input.EntityToProcess.VotesGiven.Clear();
                    await context.SaveChangesAsync();
                }

                // User Group notifications
                if (input.EntityToProcess.GroupNotifications != null)
                {
                    var toDelete = new List <GroupNotification>();
                    toDelete.AddRange(input.EntityToProcess.GroupNotifications);
                    foreach (var obj in toDelete)
                    {
                        _notificationService.Delete(obj);
                    }
                    input.EntityToProcess.GroupNotifications.Clear();
                    await context.SaveChangesAsync();
                }

                // User Favourites
                if (input.EntityToProcess.Favourites != null)
                {
                    var toDelete = new List <Favourite>();
                    toDelete.AddRange(input.EntityToProcess.Favourites);
                    foreach (var obj in toDelete)
                    {
                        _favouriteService.Delete(obj);
                    }
                    input.EntityToProcess.Favourites.Clear();
                    await context.SaveChangesAsync();
                }

                if (input.EntityToProcess.TopicNotifications != null)
                {
                    var notificationsToDelete = new List <TopicNotification>();
                    notificationsToDelete.AddRange(input.EntityToProcess.TopicNotifications);
                    foreach (var topicNotification in notificationsToDelete)
                    {
                        _notificationService.Delete(topicNotification);
                    }
                    input.EntityToProcess.TopicNotifications.Clear();
                }

                // Also clear their points
                var userPoints = input.EntityToProcess.Points;
                if (userPoints.Any())
                {
                    var pointsList = new List <MembershipUserPoints>();
                    pointsList.AddRange(userPoints);
                    foreach (var point in pointsList)
                    {
                        point.User = null;
                        await _membershipUserPointsService.Delete(point);
                    }
                    input.EntityToProcess.Points.Clear();
                }

                // Now clear all activities for this user
                var usersActivities = _activityService.GetDataFieldByGuid(input.EntityToProcess.Id);
                _activityService.Delete(usersActivities.ToList());
                await context.SaveChangesAsync();

                // Also clear their poll votes
                var userPollVotes = input.EntityToProcess.PollVotes;
                if (userPollVotes.Any())
                {
                    var pollList = new List <PollVote>();
                    pollList.AddRange(userPollVotes);
                    foreach (var vote in pollList)
                    {
                        vote.User = null;
                        _pollService.Delete(vote);
                    }
                    input.EntityToProcess.PollVotes.Clear();
                    await context.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                input.AddError(ex.Message);
                _loggingService.Error(ex);
            }

            return(input);
        }
Пример #14
0
        public IActionResult DeleteTopic([FromQuery] string id)
        {
            var result = _topicService.Delete(id);

            return(Ok(result));
        }
Пример #15
0
        public ActionResult DeletePost(Guid id)
        {
            bool  isTopicStarter;
            Topic topic;

            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(id);
                var postId = post.Id;

                // get this so we know where to redirect after
                isTopicStarter = post.IsTopicStarter;

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

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

                if (post.User.Id == LoggedOnReadOnlyUser.Id || permissions[SiteConstants.Instance.PermissionDeletePosts].IsTicked)
                {
                    // Delete post / topic
                    if (post.IsTopicStarter)
                    {
                        // Delete entire topic
                        _topicService.Delete(topic, unitOfWork);
                    }
                    else
                    {
                        // Deletes single post and associated data
                        _postService.Delete(post, unitOfWork, false);

                        // Remove in replyto's
                        var relatedPosts = _postService.GetReplyToPosts(postId);
                        foreach (var relatedPost in relatedPosts)
                        {
                            relatedPost.InReplyTo = null;
                        }
                    }

                    try
                    {
                        unitOfWork.Commit();
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        ShowMessage(new GenericMessageViewModel
                        {
                            Message     = LocalizationService.GetResourceString("Errors.GenericMessage"),
                            MessageType = GenericMessages.danger
                        });
                        return(Redirect(topicUrl));
                    }
                }
            }

            // Deleted successfully
            if (isTopicStarter)
            {
                // Redirect to root as this was a topic and deleted
                TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                {
                    Message     = LocalizationService.GetResourceString("Topic.Deleted"),
                    MessageType = GenericMessages.success
                };
                return(RedirectToAction("Index", "Home"));
            }

            // Show message that post is deleted
            TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
            {
                Message     = LocalizationService.GetResourceString("Post.Deleted"),
                MessageType = GenericMessages.success
            };

            return(Redirect(topic.NiceUrl));
        }
Пример #16
0
 public JsonResult Delete(string _id)
 {
     return(Json(_TopicService.Delete(_id)));
 }
Пример #17
0
 public void Delete(int id)
 {
     topicService.Delete(id);
 }
Пример #18
0
        public void ScrubUsers(MembershipUser user)
        {
            //// TODO - This REALLY needs to be refactored

            // PROFILE
            user.Website   = string.Empty;
            user.Twitter   = string.Empty;
            user.Facebook  = string.Empty;
            user.Avatar    = string.Empty;
            user.Signature = string.Empty;

            //// User Votes
            if (user.Votes != null)
            {
                var votesToDelete = new List <Vote>();
                votesToDelete.AddRange(user.Votes);
                votesToDelete.AddRange(user.VotesGiven);
                foreach (var d in votesToDelete)
                {
                    _voteService.Delete(d);
                }
                user.Votes.Clear();
                user.VotesGiven.Clear();
                _context.SaveChanges();
            }

            // User badge time checks
            if (user.BadgeTypesTimeLastChecked != null)
            {
                var toDelete = new List <BadgeTypeTimeLastChecked>();
                toDelete.AddRange(user.BadgeTypesTimeLastChecked);
                foreach (var obj in toDelete)
                {
                    _badgeService.DeleteTimeLastChecked(obj);
                }
                user.BadgeTypesTimeLastChecked.Clear();
                _context.SaveChanges();
            }

            // User Badges
            if (user.Badges != null)
            {
                var toDelete = new List <Badge>();
                toDelete.AddRange(user.Badges);
                foreach (var obj in toDelete)
                {
                    _badgeService.Delete(obj);
                }
                user.Badges.Clear();
                _context.SaveChanges();
            }

            // User category notifications
            if (user.CategoryNotifications != null)
            {
                var toDelete = new List <CategoryNotification>();
                toDelete.AddRange(user.CategoryNotifications);
                foreach (var obj in toDelete)
                {
                    _categoryNotificationService.Delete(obj);
                }
                user.CategoryNotifications.Clear();
                _context.SaveChanges();
            }

            // User PM Received
            if (user.PrivateMessagesReceived != null)
            {
                var toDelete = new List <PrivateMessage>();
                toDelete.AddRange(user.PrivateMessagesReceived);
                foreach (var obj in toDelete)
                {
                    _privateMessageService.DeleteMessage(obj);
                }
                user.PrivateMessagesReceived.Clear();
                _context.SaveChanges();
            }

            // User PM Sent
            if (user.PrivateMessagesSent != null)
            {
                var toDelete = new List <PrivateMessage>();
                toDelete.AddRange(user.PrivateMessagesSent);
                foreach (var obj in toDelete)
                {
                    _privateMessageService.DeleteMessage(obj);
                }
                user.PrivateMessagesSent.Clear();
                _context.SaveChanges();
            }

            // User Favourites
            if (user.Favourites != null)
            {
                var toDelete = new List <Favourite>();
                toDelete.AddRange(user.Favourites);
                foreach (var obj in toDelete)
                {
                    _favouriteService.Delete(obj);
                }
                user.Favourites.Clear();
                _context.SaveChanges();
            }

            if (user.TopicNotifications != null)
            {
                var notificationsToDelete = new List <TopicNotification>();
                notificationsToDelete.AddRange(user.TopicNotifications);
                foreach (var topicNotification in notificationsToDelete)
                {
                    _topicNotificationService.Delete(topicNotification);
                }
                user.TopicNotifications.Clear();
            }

            // Also clear their points
            var userPoints = user.Points;

            if (userPoints.Any())
            {
                var pointsList = new List <MembershipUserPoints>();
                pointsList.AddRange(userPoints);
                foreach (var point in pointsList)
                {
                    point.User = null;
                    _membershipUserPointsService.Delete(point);
                }
                user.Points.Clear();
            }

            // Now clear all activities for this user
            var usersActivities = _activityService.GetDataFieldByGuid(user.Id);

            _activityService.Delete(usersActivities.ToList());
            _context.SaveChanges();

            // Also clear their poll votes
            var userPollVotes = user.PollVotes;

            if (userPollVotes.Any())
            {
                var pollList = new List <PollVote>();
                pollList.AddRange(userPollVotes);
                foreach (var vote in pollList)
                {
                    vote.User = null;
                    _pollVoteService.Delete(vote);
                }
                user.PollVotes.Clear();
                _context.SaveChanges();
            }

            //// ######### POSTS TOPICS ########

            // Delete all topics first
            // This will get rid of everyone elses posts associated with this users topic too
            var topics = user.Topics;

            if (topics != null && topics.Any())
            {
                var topicList = new List <Topic>();
                topicList.AddRange(topics);
                foreach (var topic in topicList)
                {
                    _topicService.Delete(topic);
                }
                user.Topics.Clear();
                _context.SaveChanges();
            }

            // Now sorts Last Posts on topics and delete all the users posts
            var posts = user.Posts;

            if (posts != null && posts.Any())
            {
                var postIds = posts.Select(x => x.Id).ToList();

                // Get all categories
                var allCategories = _categoryService.GetAll();

                // Need to see if any of these are last posts on Topics
                // If so, need to swap out last post
                var lastPostTopics = _topicService.GetTopicsByLastPost(postIds, allCategories.ToList());
                foreach (var topic in lastPostTopics.Where(x => x.User.Id != user.Id))
                {
                    var lastPost = topic.Posts.Where(x => !postIds.Contains(x.Id)).OrderByDescending(x => x.DateCreated).FirstOrDefault();
                    topic.LastPost = lastPost;
                }

                _context.SaveChanges();

                // Delete all posts
                var postList = new List <Post>();
                postList.AddRange(posts);
                foreach (var post in postList)
                {
                    _postService.Delete(post, true);
                }

                user.UploadedFiles.Clear();
                user.Posts.Clear();

                _context.SaveChanges();
            }
        }
Пример #19
0
 public Task <IResultModel> Delete([BindRequired] int id)
 {
     return(_service.Delete(id));
 }
Пример #20
0
 public ActionResult <Topic> Delete(int id)
 {
     return(_topService.Delete(id));
 }
Пример #21
0
        public ActionResult DeletePost(Guid id)
        {
            bool  isTopicStarter;
            Topic topic;

            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(id);

                // get this so we know where to redirect after
                isTopicStarter = post.IsTopicStarter;

                // Get the topic
                topic = post.Topic;

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

                if (post.User.Id == LoggedOnUser.Id || permissions[AppConstants.PermissionDeletePosts].IsTicked)
                {
                    var postUser = post.User;

                    var deleteTopic = _postService.Delete(post);
                    unitOfWork.SaveChanges();

                    var postIdList = new List <Guid>();
                    if (deleteTopic)
                    {
                        postIdList = topic.Posts.Select(x => x.Id).ToList();
                        _topicService.Delete(topic);
                    }

                    // Remove the points the user got for this post
                    _membershipUserPointsService.Delete(SettingsService.GetSettings().PointsAddedPerPost, postUser);

                    try
                    {
                        unitOfWork.Commit();

                        // Successful, delete post or posts if its a topic deleted
                        if (_luceneService.CheckIndexExists())
                        {
                            if (deleteTopic)
                            {
                                foreach (var guid in postIdList)
                                {
                                    _luceneService.Delete(guid);
                                }
                            }
                            else
                            {
                                _luceneService.Delete(post.Id);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
                    }
                }
            }

            // Deleted successfully
            if (isTopicStarter)
            {
                // Redirect to root as this was a topic and deleted
                TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                {
                    Message     = LocalizationService.GetResourceString("Topic.Deleted"),
                    MessageType = GenericMessages.success
                };
                return(RedirectToAction("Index", "Home"));
            }

            // Show message that post is deleted
            TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
            {
                Message     = LocalizationService.GetResourceString("Post.Deleted"),
                MessageType = GenericMessages.success
            };

            return(Redirect(topic.NiceUrl));
        }
Пример #22
0
 public IActionResult Delete(int id)
 {
     _topicService.Delete(id);
     return(Ok());
 }
Пример #23
0
        public void ScrubUsers(MembershipUser user, IUnitOfWork unitOfWork)
        {
            // TODO - This REALLY needs to be refactored

            // PROFILE
            user.Website   = string.Empty;
            user.Twitter   = string.Empty;
            user.Facebook  = string.Empty;
            user.Avatar    = string.Empty;
            user.Signature = string.Empty;

            // User Votes
            if (user.Votes != null)
            {
                var votesToDelete = new List <Vote>();
                votesToDelete.AddRange(user.Votes);
                foreach (var d in votesToDelete)
                {
                    _voteService.Delete(d);
                }
                user.Votes.Clear();
            }

            // User Badges
            if (user.Badges != null)
            {
                var toDelete = new List <Badge>();
                toDelete.AddRange(user.Badges);
                foreach (var obj in toDelete)
                {
                    _badgeService.Delete(obj);
                }
                user.Badges.Clear();
            }

            // User badge time checks
            if (user.BadgeTypesTimeLastChecked != null)
            {
                var toDelete = new List <BadgeTypeTimeLastChecked>();
                toDelete.AddRange(user.BadgeTypesTimeLastChecked);
                foreach (var obj in toDelete)
                {
                    _badgeService.DeleteTimeLastChecked(obj);
                }
                user.BadgeTypesTimeLastChecked.Clear();
            }

            // User category notifications
            if (user.CategoryNotifications != null)
            {
                var toDelete = new List <CategoryNotification>();
                toDelete.AddRange(user.CategoryNotifications);
                foreach (var obj in toDelete)
                {
                    _categoryNotificationService.Delete(obj);
                }
                user.CategoryNotifications.Clear();
            }

            // User PM Received
            var pmUpdate = false;

            if (user.PrivateMessagesReceived != null)
            {
                pmUpdate = true;
                var toDelete = new List <PrivateMessage>();
                toDelete.AddRange(user.PrivateMessagesReceived);
                foreach (var obj in toDelete)
                {
                    _privateMessageService.DeleteMessage(obj);
                }
                user.PrivateMessagesReceived.Clear();
            }

            // User PM Sent
            if (user.PrivateMessagesSent != null)
            {
                pmUpdate = true;
                var toDelete = new List <PrivateMessage>();
                toDelete.AddRange(user.PrivateMessagesSent);
                foreach (var obj in toDelete)
                {
                    _privateMessageService.DeleteMessage(obj);
                }
                user.PrivateMessagesSent.Clear();
            }

            if (pmUpdate)
            {
                unitOfWork.SaveChanges();
            }

            // User Favourites
            if (user.Favourites != null)
            {
                var toDelete = new List <Favourite>();
                toDelete.AddRange(user.Favourites);
                foreach (var obj in toDelete)
                {
                    _favouriteService.Delete(obj);
                }
                user.Favourites.Clear();
            }

            if (user.TopicNotifications != null)
            {
                var notificationsToDelete = new List <TopicNotification>();
                notificationsToDelete.AddRange(user.TopicNotifications);
                foreach (var topicNotification in notificationsToDelete)
                {
                    _topicNotificationService.Delete(topicNotification);
                }
                user.TopicNotifications.Clear();
            }

            // Also clear their points
            var userPoints = user.Points;

            if (userPoints.Any())
            {
                var pointsList = new List <MembershipUserPoints>();
                pointsList.AddRange(userPoints);
                foreach (var point in pointsList)
                {
                    point.User = null;
                    _membershipUserPointsService.Delete(point);
                }
                user.Points.Clear();
            }

            // Now clear all activities for this user
            var usersActivities = _activityService.GetDataFieldByGuid(user.Id);

            _activityService.Delete(usersActivities.ToList());

            // Also clear their poll votes
            var userPollVotes = user.PollVotes;

            if (userPollVotes.Any())
            {
                var pollList = new List <PollVote>();
                pollList.AddRange(userPollVotes);
                foreach (var vote in pollList)
                {
                    vote.User = null;
                    _pollVoteService.Delete(vote);
                }
                user.PollVotes.Clear();
            }

            unitOfWork.SaveChanges();


            // Also clear their polls
            var userPolls = user.Polls;

            if (userPolls.Any())
            {
                var polls = new List <Poll>();
                polls.AddRange(userPolls);
                foreach (var poll in polls)
                {
                    //Delete the poll answers
                    var pollAnswers = poll.PollAnswers;
                    if (pollAnswers.Any())
                    {
                        var pollAnswersList = new List <PollAnswer>();
                        pollAnswersList.AddRange(pollAnswers);
                        foreach (var answer in pollAnswersList)
                        {
                            answer.Poll = null;
                            _pollAnswerService.Delete(answer);
                        }
                    }

                    poll.PollAnswers.Clear();
                    poll.User = null;
                    _pollService.Delete(poll);
                }
                user.Polls.Clear();
            }

            unitOfWork.SaveChanges();

            // ######### POSTS TOPICS ########

            // Delete all topics first
            var topics = user.Topics;

            if (topics != null && topics.Any())
            {
                var topicList = new List <Topic>();
                topicList.AddRange(topics);
                foreach (var topic in topicList)
                {
                    topic.LastPost = null;
                    topic.Posts.Clear();
                    topic.Tags.Clear();
                    _topicService.Delete(topic, unitOfWork);
                }
                user.Topics.Clear();
                unitOfWork.SaveChanges();
            }

            // Now sorts Last Posts on topics and delete all the users posts
            var posts = user.Posts;

            if (posts != null && posts.Any())
            {
                var postIds = posts.Select(x => x.Id).ToList();

                // Get all categories
                var allCategories = _categoryService.GetAll();

                // Need to see if any of these are last posts on Topics
                // If so, need to swap out last post
                var lastPostTopics = _topicService.GetTopicsByLastPost(postIds, allCategories.ToList());
                foreach (var topic in lastPostTopics.Where(x => x.User.Id != user.Id))
                {
                    var lastPost = topic.Posts.Where(x => !postIds.Contains(x.Id)).OrderByDescending(x => x.DateCreated).FirstOrDefault();
                    topic.LastPost = lastPost;
                }

                unitOfWork.SaveChanges();

                user.UploadedFiles.Clear();

                // Delete all posts

                var postList = new List <Post>();
                postList.AddRange(posts);
                foreach (var post in postList)
                {
                    if (post.Files != null)
                    {
                        var files     = post.Files;
                        var filesList = new List <UploadedFile>();
                        filesList.AddRange(files);
                        foreach (var file in filesList)
                        {
                            // store the file path as we'll need it to delete on the file system
                            var filePath = file.FilePath;

                            // Now delete it
                            _uploadedFileService.Delete(file);

                            // And finally delete from the file system
                            System.IO.File.Delete(HostingEnvironment.MapPath(filePath));
                        }
                        post.Files.Clear();
                    }
                    var postEdits = new List <PostEdit>();
                    postEdits.AddRange(post.PostEdits);
                    _postEditService.Delete(postEdits);
                    post.PostEdits.Clear();
                    _postService.Delete(post, unitOfWork, true);
                }
                user.Posts.Clear();

                unitOfWork.SaveChanges();
            }
        }
Пример #24
0
        public virtual async Task <ActionResult> DeletePost(Guid id)
        {
            var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);
            var loggedOnUsersRole    = loggedOnReadOnlyUser.GetRole(RoleService);

            // Got to get a lot of things here as we have to check permissions
            // Get the post
            var post   = _postService.Get(id);
            var postId = post.Id;

            // get this so we know where to redirect after
            var isTopicStarter = post.IsTopicStarter;

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

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

            if (post.User.Id == loggedOnReadOnlyUser.Id ||
                permissions[ForumConfiguration.Instance.PermissionDeletePosts].IsTicked)
            {
                try
                {
                    // Delete post / topic
                    if (post.IsTopicStarter)
                    {
                        // Delete entire topic
                        var result = await _topicService.Delete(topic);

                        if (!result.Successful)
                        {
                            TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                            {
                                Message     = result.ProcessLog.FirstOrDefault(),
                                MessageType = GenericMessages.success
                            };

                            return(Redirect(topic.NiceUrl));
                        }
                    }
                    else
                    {
                        // Deletes single post and associated data
                        var result = await _postService.Delete(post, false);

                        if (!result.Successful)
                        {
                            TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                            {
                                Message     = result.ProcessLog.FirstOrDefault(),
                                MessageType = GenericMessages.success
                            };

                            return(Redirect(topic.NiceUrl));
                        }

                        // Remove in replyto's
                        var relatedPosts = _postService.GetReplyToPosts(postId);
                        foreach (var relatedPost in relatedPosts)
                        {
                            relatedPost.InReplyTo = null;
                        }
                    }

                    Context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Context.RollBack();
                    LoggingService.Error(ex);
                    ShowMessage(new GenericMessageViewModel
                    {
                        Message     = LocalizationService.GetResourceString("Errors.GenericMessage"),
                        MessageType = GenericMessages.danger
                    });
                    return(Redirect(topicUrl));
                }
            }

            // Deleted successfully
            if (isTopicStarter)
            {
                // Redirect to root as this was a topic and deleted
                TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                {
                    Message     = LocalizationService.GetResourceString("Topic.Deleted"),
                    MessageType = GenericMessages.success
                };
                return(RedirectToAction("Index", "Home"));
            }

            // Show message that post is deleted
            TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
            {
                Message     = LocalizationService.GetResourceString("Post.Deleted"),
                MessageType = GenericMessages.success
            };

            return(Redirect(topic.NiceUrl));
        }
Пример #25
0
 public IActionResult Delete(int id)
 {
     topicService.Delete(id);
     return(RedirectToAction("Index", "Topic"));
 }