Ejemplo n.º 1
0
        public void FireAfterTopicMade(object sender, TopicMadeEventArgs eventArgs)
        {
            var handler = AfterTopicMade;

            if (handler != null)
            {
                handler(this, eventArgs);
            }
        }
Ejemplo n.º 2
0
        public ActionResult MovePost(MovePostViewModel viewModel)
        {

            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Firstly check if this is a post and they are allowed to move it
                var post = _postService.Get(viewModel.PostId);
                if (post == null)
                {
                    return ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage"));
                }

                var permissions = RoleService.GetPermissions(post.Topic.Category, UsersRole);
                var allowedCategories = _categoryService.GetAllowedCategories(UsersRole);

                // Does the user have permission to this posts category
                var cat = allowedCategories.FirstOrDefault(x => x.Id == post.Topic.Category.Id);
                if (cat == null)
                {
                    return ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"));
                }

                // Does this user have permission to move
                if (!permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked)
                {
                    return NoPermission(post.Topic);
                }

                var previousTopic = post.Topic;
                var category = post.Topic.Category;
                var postCreator = post.User;

                Topic topic;
                var cancelledByEvent = false;
                // If the dropdown has a value, then we choose that first
                if (viewModel.TopicId != null)
                {
                    // Get the selected topic
                    topic = _topicService.Get((Guid) viewModel.TopicId);
                }
                else if(!string.IsNullOrEmpty(viewModel.TopicTitle))
                {
                    // We get the banned words here and pass them in, so its just one call
                    // instead of calling it several times and each call getting all the words back
                    var bannedWordsList = _bannedWordService.GetAll();
                    List<string> bannedWords = null;
                    if (bannedWordsList.Any())
                    {
                        bannedWords = bannedWordsList.Select(x => x.Word).ToList();
                    }

                    // Create the topic
                    topic = new Topic
                    {
                        Name = _bannedWordService.SanitiseBannedWords(viewModel.TopicTitle, bannedWords),
                        Category = category,
                        User = postCreator
                    };

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

                    // Save the changes
                    unitOfWork.SaveChanges();

                    // Set the post to be a topic starter
                    post.IsTopicStarter = true;

                    // Check the Events
                    var e = new TopicMadeEventArgs { Topic = topic };
                    EventManager.Instance.FireBeforeTopicMade(this, e);
                    if (e.Cancel)
                    {
                        cancelledByEvent = true;
                        ShowMessage(new GenericMessageViewModel
                        {
                            MessageType = GenericMessages.warning, Message = LocalizationService.GetResourceString("Errors.GenericMessage")
                        });
                    }                    
                }
                else
                {
                    // No selected topic OR topic title, just redirect back to the topic
                    return Redirect(post.Topic.NiceUrl);
                }

                // If this create was cancelled by an event then don't continue
                if (!cancelledByEvent)
                {
                    // Now update the post to the new topic
                    post.Topic = topic;

                    // Also move any posts, which were in reply to this post
                    if (viewModel.MoveReplyToPosts)
                    {
                        var relatedPosts = _postService.GetReplyToPosts(viewModel.PostId);
                        foreach (var relatedPost in relatedPosts)
                        {
                            relatedPost.Topic = topic;
                        }
                    }

                    unitOfWork.SaveChanges();

                    // Update Last post..  As we have done a save, we should get all posts including the added ones
                    var lastPost = topic.Posts.OrderByDescending(x => x.DateCreated).FirstOrDefault();
                    topic.LastPost = lastPost;

                    // If any of the posts we are moving, were the last post - We need to update the old Topic
                    var previousTopicLastPost = previousTopic.Posts.OrderByDescending(x => x.DateCreated).FirstOrDefault();
                    previousTopic.LastPost = previousTopicLastPost;

                    try
                    {
                        unitOfWork.Commit();

                        EventManager.Instance.FireAfterTopicMade(this, new TopicMadeEventArgs { Topic = topic });

                        // On Update redirect to the topic
                        return RedirectToAction("Show", "Topic", new { slug = topic.Slug });
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        ShowMessage(new GenericMessageViewModel
                        {
                            Message = ex.Message,
                            MessageType = GenericMessages.danger
                        });
                    }
                }

                // Repopulate the topics
                var topics = _topicService.GetAllSelectList(allowedCategories, 30);
                topics.Insert(0, new SelectListItem
                {
                    Text = LocalizationService.GetResourceString("Topic.Choose"),
                    Value = ""
                });

                viewModel.LatestTopics = topics;
                viewModel.Post = ViewModelMapping.CreatePostViewModel(post, post.Votes.ToList(), permissions, post.Topic, LoggedOnReadOnlyUser, SettingsService.GetSettings(), post.Favourites.ToList());
                viewModel.Post.MinimalPost = true;
                viewModel.PostId = post.Id;

                return View(viewModel);
            }

        }
Ejemplo n.º 3
0
        public ActionResult Create(CreateEditTopicViewModel topicViewModel)
        {
            // Get the category
            var category = _categoryService.Get(topicViewModel.Category);

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

            // Now we have the category and permissionSet - Populate the optional permissions 
            // This is just in case the viewModel is return back to the view also sort the allowedCategories
            topicViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions);
            topicViewModel.Categories = _categoryService.GetBaseSelectListCategories(AllowedCreateCategories());
            topicViewModel.IsTopicStarter = true;
            if (topicViewModel.PollAnswers == null)
            {
                topicViewModel.PollAnswers = new List<PollAnswer>();
            }
            /*---- End Re-populate ViewModel ----*/

            if (ModelState.IsValid)
            {

                // Check stop words
                var stopWords = _bannedWordService.GetAll(true);
                foreach (var stopWord in stopWords)
                {
                    if (topicViewModel.Content.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
                        topicViewModel.Name.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0)
                    {
                        ShowMessage(new GenericMessageViewModel
                        {
                            Message = LocalizationService.GetResourceString("StopWord.Error"),
                            MessageType = GenericMessages.danger
                        });

                        // Ahhh found a stop word. Abandon operation captain.
                        return View(topicViewModel);
                    }
                }

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

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

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

                        // Create the topic model
                        var loggedOnUser = MembershipService.GetUser(LoggedOnReadOnlyUser.Id);
                        topic = new Topic
                        {
                            Name = _bannedWordService.SanitiseBannedWords(topicViewModel.Name, bannedWords),
                            Category = category,
                            User = loggedOnUser
                        };

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

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

                            var e = new TopicMadeEventArgs { Topic = topic };
                            EventManager.Instance.FireBeforeTopicMade(this, e);
                            if (!e.Cancel)
                            {

                                // See if this is a poll and add it to the topic
                                if (topicViewModel.PollAnswers.Count(x => x != null) > 0)
                                {
                                    // Do they have permission to create a new poll
                                    if (permissions[SiteConstants.Instance.PermissionCreatePolls].IsTicked)
                                    {
                                        // Create a new Poll
                                        var newPoll = new Poll
                                        {
                                            User = loggedOnUser,
                                            ClosePollAfterDays = topicViewModel.PollCloseAfterDays
                                        };

                                        // 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)
                                        {
                                            if (pollAnswer.Answer != null)
                                            {
                                                // 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
                                        };
                                    }
                                }

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

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

                                // Save the changes
                                unitOfWork.SaveChanges();

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

                                // Update the users points score for posting
                                _membershipUserPointsService.Add(new MembershipUserPoints
                                {
                                    Points = SettingsService.GetSettings().PointsAddedPerPost,
                                    User = loggedOnUser,
                                    PointsFor = PointsFor.Post,
                                    PointsForId = topicPost.Id
                                });


                                // Now check its not spam
                                var akismetHelper = new AkismetHelper(SettingsService);
                                if (akismetHelper.IsSpam(topic))
                                {
                                    topic.Pending = true;
                                    moderate = true;
                                }

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

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

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

                                }

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

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

                                // After tags sort the search field for the post
                                topicPost.SearchField = _postService.SortSearchField(topicPost.IsTopicStarter, topic,
                                    topic.Tags);

                                // 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);
                                }
                            }
                            else
                            {
                                cancelledByEvent = true;
                            }

                            try
                            {
                                unitOfWork.Commit();
                                if (!moderate)
                                {
                                    successfullyCreated = true;
                                }

                                // Only fire this if the create topic wasn't cancelled
                                if (!cancelledByEvent)
                                {
                                    EventManager.Instance.FireAfterTopicMade(this, new TopicMadeEventArgs { Topic = topic });
                                }
                            }
                            catch (Exception ex)
                            {
                                unitOfWork.Rollback();
                                LoggingService.Error(ex);
                                ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                            }

                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                        }
                    }
                }

                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    if (successfullyCreated && !cancelledByEvent)
                    {
                        // Success so now send the emails
                        NotifyNewTopics(category, topic, unitOfWork);

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

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

            return View(topicViewModel);
        }
Ejemplo n.º 4
0
        public void FireAfterTopicMade(object sender, TopicMadeEventArgs eventArgs)
        {
            var handler = AfterTopicMade;

            if (handler != null)
            {
                handler(this, eventArgs);
            }
        }