Esempio n. 1
0
        public virtual ActionResult UploadPostFiles(AttachFileToPostViewModel attachFileToPostViewModel)
        {
            var topic = new Topic();

            try
            {
                User.GetMembershipUser(MembershipService);
                var loggedOnUsersRole = LoggedOnReadOnlyUser.GetRole(RoleService);

                // First this to do is get the post
                var post = _postService.Get(attachFileToPostViewModel.UploadPostId);
                if (post != null)
                {
                    // Now get the topic
                    topic = post.Topic;

                    // Check we get a valid post back and have some file
                    if (attachFileToPostViewModel.Files != null && attachFileToPostViewModel.Files.Any())
                    {
                        // Now get the Group
                        var Group = topic.Group;

                        // Get the permissions for this Group, and check they are allowed to update and
                        // not trying to be a sneaky mofo
                        var permissions = RoleService.GetPermissions(Group, loggedOnUsersRole);
                        if (permissions[ForumConfiguration.Instance.PermissionAttachFiles].IsTicked == false)
                        {
                            TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                            {
                                Message     = LocalizationService.GetResourceString("Errors.NoPermission"),
                                MessageType = GenericMessages.danger
                            };

                            return(Redirect(topic.NiceUrl));
                        }

                        // 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(ForumConfiguration.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 attachFileToPostViewModel.Files)
                        {
                            if (file != null)
                            {
                                // If successful then upload the file
                                var uploadResult = file.UploadFile(uploadFolderPath, LocalizationService);
                                if (!uploadResult.UploadSuccessful)
                                {
                                    TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                                    {
                                        Message     = uploadResult.ErrorMessage,
                                        MessageType = GenericMessages.danger
                                    };
                                    return(Redirect(topic.NiceUrl));
                                }

                                // Add the filename to the database
                                var loggedOnUser = MembershipService.GetUser(LoggedOnReadOnlyUser?.Id);
                                var uploadedFile = new UploadedFile
                                {
                                    Filename       = uploadResult.UploadedFileName,
                                    Post           = post,
                                    MembershipUser = loggedOnUser
                                };
                                _uploadedFileService.Add(uploadedFile);
                            }
                        }

                        //Commit
                        Context.SaveChanges();

                        // Redirect to the topic with a success message
                        TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = LocalizationService.GetResourceString("Post.FilesUploaded"),
                            MessageType = GenericMessages.success
                        };

                        return(Redirect(topic.NiceUrl));
                    }
                    // Else return with error to home page
                    return(topic != null
                        ? Redirect(topic.NiceUrl)
                        : ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
                }
                // Else return with error to home page
                return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
            }
            catch (Exception ex)
            {
                Context.RollBack();
                LoggingService.Error(ex);
                TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                {
                    Message     = LocalizationService.GetResourceString("Errors.GenericMessage"),
                    MessageType = GenericMessages.danger
                };
                return(topic != null
                    ? Redirect(topic.NiceUrl)
                    : ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
            }
        }
Esempio n. 2
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
            var allowedCategories = _categoryService.GetAllowedCategories(UsersRole);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                            // Save the changes
                            unitOfWork.SaveChanges();

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

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

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

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

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

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

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

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

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

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

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

            return(View(topicViewModel));
        }
Esempio n. 3
0
        public ActionResult UploadPostFiles(AttachFileToPostViewModel attachFileToPostViewModel)
        {
            if (attachFileToPostViewModel != null && attachFileToPostViewModel.Files != null)
            {
                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    // First this to do is get the post
                    var post = _postService.Get(attachFileToPostViewModel.UploadPostId);

                    // Check we get a valid post back and have some file
                    if (post != null && attachFileToPostViewModel.Files != null)
                    {
                        Topic topic = null;
                        try
                        {
                            // Now get the topic
                            topic = post.Topic;

                            // Now get the category
                            var category = topic.Category;

                            // Get the permissions for this category, and check they are allowed to update and
                            // not trying to be a sneaky mofo
                            var permissions = RoleService.GetPermissions(category, UsersRole);
                            if (permissions[AppConstants.PermissionAttachFiles].IsTicked == false || LoggedOnUser.DisableFileUploads == true)
                            {
                                TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                {
                                    Message     = LocalizationService.GetResourceString("Errors.NoPermission"),
                                    MessageType = GenericMessages.danger
                                };

                                return(Redirect(topic.NiceUrl));
                            }

                            // woot! User has permission and all seems ok
                            // Before we save anything, check the user already has an upload folder and if not create one
                            var uploadFolderPath = Server.MapPath(string.Concat(SiteConstants.UploadFolderPath, LoggedOnUser.Id));
                            if (!Directory.Exists(uploadFolderPath))
                            {
                                Directory.CreateDirectory(uploadFolderPath);
                            }

                            // Loop through each file and get the file info and save to the users folder and Db
                            foreach (var file in attachFileToPostViewModel.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
                                        };
                                        return(Redirect(topic.NiceUrl));
                                    }

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

                            //Commit
                            unitOfWork.Commit();

                            // Redirect to the topic with a success message
                            TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                            {
                                Message     = LocalizationService.GetResourceString("Post.FilesUploaded"),
                                MessageType = GenericMessages.success
                            };

                            return(Redirect(topic.NiceUrl));
                        }
                        catch (Exception ex)
                        {
                            unitOfWork.Rollback();
                            LoggingService.Error(ex);
                            TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                            {
                                Message     = LocalizationService.GetResourceString("Errors.GenericMessage"),
                                MessageType = GenericMessages.danger
                            };
                            return(topic != null?Redirect(topic.NiceUrl) : ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
                        }
                    }
                }
            }

            // Else return with error to home page
            return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
        }
Esempio n. 4
0
        /// <inheritdoc />
        public async Task <IPipelineProcess <Post> > Process(IPipelineProcess <Post> input, IMvcForumContext context)
        {
            _localizationService.RefreshContext(context);
            _uploadedFileService.RefreshContext(context);

            try
            {
                // Files
                if (input.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.PostedFiles))
                {
                    // Get the files
                    if (input.ExtendedData[Constants.ExtendedDataKeys.PostedFiles] is HttpPostedFileBase[] files)
                    {
                        if (files.Any(x => x != null))
                        {
                            // Username
                            var username = input.ExtendedData[Constants.ExtendedDataKeys.Username] as string;

                            // Loggedonuser
                            var loggedOnUser = await context.MembershipUser.FirstOrDefaultAsync(x => x.UserName == username);

                            // Before we save anything, check the user already has an upload folder and if not create one
                            var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(ForumConfiguration.Instance.UploadFolderPath,
                                                                                            loggedOnUser.Id));
                            if (!Directory.Exists(uploadFolderPath))
                            {
                                Directory.CreateDirectory(uploadFolderPath);
                            }

                            // Loop through each file and get the file info and save to the users folder and Db
                            foreach (var file in files)
                            {
                                if (file != null)
                                {
                                    // If successful then upload the file
                                    var uploadResult = file.UploadFile(uploadFolderPath, _localizationService);
                                    if (!uploadResult.UploadSuccessful)
                                    {
                                        input.AddError(uploadResult.ErrorMessage);
                                        return(input);
                                    }

                                    // Add the filename to the database
                                    var uploadedFile = new UploadedFile
                                    {
                                        Filename       = uploadResult.UploadedFileName,
                                        Post           = input.EntityToProcess,
                                        MembershipUser = input.EntityToProcess.User
                                    };

                                    _uploadedFileService.Add(uploadedFile);
                                }
                            }

                            // Was the post successful
                            if (await context.SaveChangesAsync() <= 0)
                            {
                                // Problem
                                input.AddError(_localizationService.GetResourceString("Errors.GenericMessage"));
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                input.AddError(ex.Message);
                _loggingService.Error(ex);
            }

            return(input);
        }