public static Topic ToTopic(this CreateEditTopicViewModel viewModel, Group Group, MembershipUser user, Topic existingTopic) { if (existingTopic == null) { existingTopic = new Topic { CreateDate = DateTime.UtcNow, User = user }; } existingTopic.Name = viewModel.Name; existingTopic.Group = Group; existingTopic.IsLocked = viewModel.IsLocked; existingTopic.IsSticky = viewModel.IsSticky; // See if we have a poll and add it unless there is already one, as we'll need to refresh // The poll in a later pipeline if (viewModel.PollAnswers.Any(x => x != null) && existingTopic.Poll == null) { // Create a new Poll as one does not already exist var newPoll = new Poll { User = user, ClosePollAfterDays = viewModel.PollCloseAfterDays, DateCreated = DateTime.UtcNow }; // Now sort the answers var newPollAnswers = new List <PollAnswer>(); foreach (var pollAnswer in viewModel.PollAnswers) { if (pollAnswer.Answer != null) { // Attach newly created poll to each answer pollAnswer.Poll = newPoll; newPollAnswers.Add(pollAnswer); } } // Attach answers to poll newPoll.PollAnswers = newPollAnswers; // Add the poll to the topic existingTopic.Poll = newPoll; } return(existingTopic); }
public ActionResult Edit(Guid Id) { using (UnitOfWorkManager.NewUnitOfWork()) { var cats = _categoryService.GetAllowedEditCategories(UsersRole); if (cats.Count > 0) { var viewModel = new CreateEditTopicViewModel(); viewModel.Categories = _categoryService.GetBaseSelectListCategories(cats); var topic = _topicServic.Get(Id); if (topic == null) { TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Errors.NoFindTopic"), MessageType = GenericMessages.warning }; return(RedirectToAction("Index")); } viewModel.Id = topic.Id; viewModel.Name = topic.Name; viewModel.Category = topic.Category_Id; viewModel.IsLocked = topic.IsLocked; viewModel.IsSticky = topic.IsSticky; viewModel.Image = topic.Image; if (topic.Post_Id != null) { var post = _postSevice.Get((Guid)topic.Post_Id); if (post != null) { viewModel.Content = post.PostContent; } } //viewModel.Po = topic.IsLocked; return(View(viewModel)); } return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); } }
public ActionResult Create() { using (UnitOfWorkManager.NewUnitOfWork()) { var cats = _categoryService.GetAllowedEditCategories(UsersRole); if (cats.Count > 0) { var viewModel = new CreateEditTopicViewModel(); viewModel.Categories = _categoryService.GetBaseSelectListCategories(cats); return(View(viewModel)); } return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); } }
public ActionResult Create() { using (UnitOfWorkManager.NewUnitOfWork()) { var allowedCategories = _categoryService.GetAllowedCategories(UsersRole); if (allowedCategories.Any() && LoggedOnUser.DisablePosting != true) { var viewModel = new CreateEditTopicViewModel { SubscribeToTopic = true, Categories = GetBaseSelectListCategories(allowedCategories), OptionalPermissions = new CheckCreateTopicPermissions { CanLockTopic = false, CanStickyTopic = false, CanUploadFiles = false }, PollAnswers = new List <PollAnswer>(), IsTopicStarter = true }; return(View(viewModel)); } return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); } }
public virtual async Task <ActionResult> EditPostTopic(CreateEditTopicViewModel editPostViewModel) { // Get the current user and role var loggedOnUser = User.GetMembershipUser(MembershipService, false); var loggedOnUsersRole = loggedOnUser.GetRole(RoleService, false); // Get the category var category = _categoryService.Get(editPostViewModel.Category); // Get all the permissions for this user 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 // Get the allowed categories for this user var allowedAccessCategories = _categoryService.GetAllowedCategories(loggedOnUsersRole); var allowedCreateTopicCategories = _categoryService.GetAllowedCategories(loggedOnUsersRole, ForumConfiguration.Instance.PermissionCreateTopics); var allowedCreateTopicCategoryIds = allowedCreateTopicCategories.Select(x => x.Id); // TODO ??? Is this correct ?? allowedAccessCategories.RemoveAll(x => allowedCreateTopicCategoryIds.Contains(x.Id)); // Set the categories editPostViewModel.Categories = _categoryService.GetBaseSelectListCategories(allowedAccessCategories); // Get the users permissions for the topic editPostViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions); // See if this is a topic starter or not editPostViewModel.IsTopicStarter = editPostViewModel.Id == Guid.Empty; // IS the model valid if (ModelState.IsValid) { // Got to get a lot of things here as we have to check permissions // Get the post var originalPost = _postService.Get(editPostViewModel.Id); // Get the topic var originalTopic = originalPost.Topic; // See if the user has actually added some content to the topic if (string.IsNullOrWhiteSpace(editPostViewModel.Content)) { ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } else { bool successful; bool? moderate = false; string message; if (editPostViewModel.IsPostEdit) { var editPostPipe = await _postService.Edit(originalPost, editPostViewModel.Files, originalPost.IsTopicStarter, string.Empty, editPostViewModel.Content); successful = editPostPipe.Successful; message = editPostPipe.ProcessLog.FirstOrDefault(); if (editPostPipe.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Moderate)) { moderate = editPostPipe.ExtendedData[Constants.ExtendedDataKeys.Moderate] as bool?; } } else { // Map the new topic (Pass null for new topic) var topic = editPostViewModel.ToTopic(category, loggedOnUser, originalTopic); // Run the create pipeline var editPipeLine = await _topicService.Edit(topic, editPostViewModel.Files, editPostViewModel.Tags, editPostViewModel.SubscribeToTopic, editPostViewModel.Content, editPostViewModel.Name, editPostViewModel.PollAnswers, editPostViewModel.PollCloseAfterDays); successful = editPipeLine.Successful; message = editPipeLine.ProcessLog.FirstOrDefault(); if (editPipeLine.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Moderate)) { moderate = editPipeLine.ExtendedData[Constants.ExtendedDataKeys.Moderate] as bool?; } } // Check if successful if (successful == false) { // Tell the user the topic is awaiting moderation ModelState.AddModelError(string.Empty, message); return(View(editPostViewModel)); } if (moderate == true) { // Tell the user the topic is awaiting moderation TempData[Constants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Moderate.AwaitingModeration"), MessageType = GenericMessages.info }; return(RedirectToAction("Index", "Home")); } // Redirect to the newly created topic return(Redirect($"{originalTopic.NiceUrl}?postbadges=true")); } } return(View(editPostViewModel)); }
public virtual ActionResult EditPostTopic(Guid id) { // Get the post var post = _postService.Get(id); // Get the topic var topic = post.Topic; // Get the current logged on user var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService); var loggedOnloggedOnUsersRole = loggedOnReadOnlyUser.GetRole(RoleService); // get the users permissions var permissions = RoleService.GetPermissions(topic.Category, loggedOnloggedOnUsersRole); // Is the user allowed to edit this post if (post.User.Id == loggedOnReadOnlyUser.Id || permissions[ForumConfiguration.Instance.PermissionEditPosts].IsTicked) { // Get the allowed categories for this user var allowedAccessCategories = _categoryService.GetAllowedCategories(loggedOnloggedOnUsersRole); var allowedCreateTopicCategories = _categoryService.GetAllowedCategories(loggedOnloggedOnUsersRole, ForumConfiguration.Instance.PermissionCreateTopics); var allowedCreateTopicCategoryIds = allowedCreateTopicCategories.Select(x => x.Id); // If this user hasn't got any allowed cats OR they are not allowed to post then abandon if (allowedAccessCategories.Any() && loggedOnReadOnlyUser.DisablePosting != true) { // Create the model for just the post var viewModel = new CreateEditTopicViewModel { Content = post.PostContent, Id = post.Id, Category = topic.Category.Id, Name = topic.Name, TopicId = topic.Id, OptionalPermissions = GetCheckCreateTopicPermissions(permissions), IsPostEdit = true }; // Now check if this is a topic starter, if so add the rest of the field if (post.IsTopicStarter) { // Remove all Categories that don't have create topic permission allowedAccessCategories.RemoveAll(x => allowedCreateTopicCategoryIds.Contains(x.Id)); // See if this user is subscribed to this topic var topicNotifications = _notificationService.GetTopicNotificationsByUserAndTopic(loggedOnReadOnlyUser, topic); // Populate the properties we can viewModel.IsLocked = topic.IsLocked; viewModel.IsSticky = topic.IsSticky; viewModel.IsTopicStarter = post.IsTopicStarter; viewModel.SubscribeToTopic = topicNotifications.Any(); viewModel.Categories = _categoryService.GetBaseSelectListCategories(allowedAccessCategories); // Tags - Populate from the topic if (topic.Tags.Any()) { viewModel.Tags = string.Join <string>(",", topic.Tags.Select(x => x.Tag)); } // Populate the poll answers if (topic.Poll != null && topic.Poll.PollAnswers.Any()) { // Has a poll so add it to the view model viewModel.PollAnswers = topic.Poll.PollAnswers; viewModel.PollCloseAfterDays = topic.Poll.ClosePollAfterDays ?? 0; } // It's a topic viewModel.IsPostEdit = false; } // Return the edit view return(View(viewModel)); } } // If we get here the user has no permission to try and edit the post return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); }
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)); }
public ActionResult Create(CreateEditTopicViewModel model) { if (IsPostingDisabled(User.Identity.Name)) { ModelState.AddModelError("", "Administrator disabled posting for you."); return View(model); } if (ModelState.IsValid) { var category = _categoryService.Get(model.CategoryId); var user = _membershipServise.GetUserByEmail(User.Identity.Name); var createDate = DateTime.UtcNow; var existedTags = _topicTagService.GetAll().ToList(); var newTagsStrings = model.Tags.Replace(", ",",").Split(','); var newTagsBll = new List<BllTopicTag>(); foreach (var newTag in newTagsStrings) { if (existedTags.Select(et => et.Tag).Contains(newTag)) { newTagsBll.Add(existedTags.First(et => et.Tag == newTag)); } else { var addTagToDbAndTopic = new BllTopicTag { Id = Guid.NewGuid(), Tag = newTag }; _topicTagService.Add(addTagToDbAndTopic); newTagsBll.Add(addTagToDbAndTopic); } } var topic = new BllTopic { Id = Guid.NewGuid(), Name = model.Title.Trim(), CategoryId = category.Id, CreateDate = DateTime.UtcNow, Posts = new List<BllPost>(), TopicTags = newTagsBll, User = user }; var firstPost = new BllPost() { Id = Guid.NewGuid(), DateCreated = createDate, DateEdited = null, IsTopicStarter = true, PostContent = model.Content.Trim(), ParentTopicId = topic.Id, User = user }; _topicService.Add(topic); _postService.Add(firstPost); return RedirectToAction("Details",new{id=topic.Id}); } return View(model); }
public ActionResult Create(Guid categoryId) { var model = new CreateEditTopicViewModel { CategoryId = categoryId }; return View(model); }
public ActionResult EditPostTopic(CreateEditTopicViewModel editPostViewModel) { // Get the category var category = _categoryService.Get(editPostViewModel.Category); // First check this user is allowed to create topics in this category var permissions = RoleService.GetPermissions(category, UsersRole); // Now we have the category and permissionSet - Populate the optional permissions // This is just in case the viewModel is return back to the view also sort the allowedCategories var allowedCategories = _categoryService.GetAllowedCategories(UsersRole); editPostViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions); editPostViewModel.Categories = GetBaseSelectListCategories(allowedCategories); editPostViewModel.IsTopicStarter = editPostViewModel.Id == Guid.Empty; if (editPostViewModel.PollAnswers == null) { editPostViewModel.PollAnswers = new List <PollAnswer>(); } /*---- End Re-populate ViewModel ----*/ if (ModelState.IsValid) { // Quick check to see if user is locked out, when logged in if (LoggedOnUser.IsLockedOut || LoggedOnUser.DisablePosting == true || !LoggedOnUser.IsApproved) { FormsAuthentication.SignOut(); return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoAccess"))); } using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Got to get a lot of things here as we have to check permissions // Get the post var post = _postService.Get(editPostViewModel.Id); // Get the topic var topic = post.Topic; if (post.User.Id == LoggedOnUser.Id || permissions[AppConstants.PermissionEditPosts].IsTicked) { // User has permission so update the post post.PostContent = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Content)); post.DateEdited = DateTime.UtcNow; // if topic starter update the topic if (post.IsTopicStarter) { // if category has changed then update it if (topic.Category.Id != editPostViewModel.Category) { var cat = _categoryService.Get(editPostViewModel.Category); topic.Category = cat; } topic.IsLocked = editPostViewModel.IsLocked; topic.IsSticky = editPostViewModel.IsSticky; topic.Name = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Name)); // See if there is a poll if (editPostViewModel.PollAnswers != null && editPostViewModel.PollAnswers.Count > 0) { // Now sort the poll answers, what to add and what to remove // Poll answers already in this poll. //var existingAnswers = topic.Poll.PollAnswers.Where(x => postedIds.Contains(x.Id)).ToList(); var postedIds = editPostViewModel.PollAnswers.Select(x => x.Id); var topicPollAnswerIds = topic.Poll.PollAnswers.Select(p => p.Id).ToList(); var existingAnswers = editPostViewModel.PollAnswers.Where(x => topicPollAnswerIds.Contains(x.Id)).ToList(); var newPollAnswers = editPostViewModel.PollAnswers.Where(x => !topicPollAnswerIds.Contains(x.Id)).ToList(); var pollAnswersToRemove = topic.Poll.PollAnswers.Where(x => !postedIds.Contains(x.Id)).ToList(); // Loop through existing and update names if need be //TODO: Need to think about this in future versions if they change the name //TODO: As they could game the system by getting votes and changing name? foreach (var existPollAnswer in existingAnswers) { // Get the existing answer from the current topic var pa = topic.Poll.PollAnswers.FirstOrDefault(x => x.Id == existPollAnswer.Id); if (pa != null && pa.Answer != existPollAnswer.Answer) { // If the answer has changed then update it pa.Answer = existPollAnswer.Answer; } } // Loop through and remove the old poll answers and delete foreach (var oldPollAnswer in pollAnswersToRemove) { // Delete _pollAnswerService.Delete(oldPollAnswer); // Remove from Poll topic.Poll.PollAnswers.Remove(oldPollAnswer); } // Poll answers to add foreach (var newPollAnswer in newPollAnswers) { var npa = new PollAnswer { Poll = topic.Poll, Answer = newPollAnswer.Answer }; _pollAnswerService.Add(npa); topic.Poll.PollAnswers.Add(npa); } } else { // Need to check if this topic has a poll, because if it does // All the answers have now been removed so remove the poll. if (topic.Poll != null) { //Firstly remove the answers if there are any if (topic.Poll.PollAnswers != null && topic.Poll.PollAnswers.Any()) { var answersToDelete = new List <PollAnswer>(); answersToDelete.AddRange(topic.Poll.PollAnswers); foreach (var answer in answersToDelete) { // Delete _pollAnswerService.Delete(answer); // Remove from Poll topic.Poll.PollAnswers.Remove(answer); } } // Now delete the poll var pollToDelete = topic.Poll; _pollService.Delete(pollToDelete); // Remove from topic. topic.Poll = null; } } // Tags topic.Tags.Clear(); if (!string.IsNullOrEmpty(editPostViewModel.Tags)) { _topicTagService.Add(editPostViewModel.Tags.ToLower(), topic); } } // redirect back to topic TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Post.Updated"), MessageType = GenericMessages.success }; try { unitOfWork.Commit(); return(Redirect(string.Format("{0}?postbadges=true", topic.NiceUrl))); } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Errors.GenericError"), MessageType = GenericMessages.danger }; } } return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); } } return(View(editPostViewModel)); }
public ActionResult EditPostTopic(Guid id) { using (UnitOfWorkManager.NewUnitOfWork()) { // Get the post var post = _postService.Get(id); // Get the topic var topic = post.Topic; // get the users permissions var permissions = RoleService.GetPermissions(topic.Category, UsersRole); // Is the user allowed to edit this post if (post.User.Id == LoggedOnReadOnlyUser.Id || permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked) { // Get the allowed categories for this user var allowedAccessCategories = _categoryService.GetAllowedCategories(UsersRole); var allowedCreateTopicCategories = _categoryService.GetAllowedCategories(UsersRole, SiteConstants.Instance.PermissionCreateTopics); var allowedCreateTopicCategoryIds = allowedCreateTopicCategories.Select(x => x.Id); // If this user hasn't got any allowed cats OR they are not allowed to post then abandon if (allowedAccessCategories.Any() && LoggedOnReadOnlyUser.DisablePosting != true) { // Create the model for just the post var viewModel = new CreateEditTopicViewModel { Content = post.PostContent, Id = post.Id, Category = topic.Category.Id, Name = topic.Name, TopicId = topic.Id, OptionalPermissions = GetCheckCreateTopicPermissions(permissions) }; // Now check if this is a topic starter, if so add the rest of the field if (post.IsTopicStarter) { // Remove all Categories that don't have create topic permission allowedAccessCategories.RemoveAll(x => allowedCreateTopicCategoryIds.Contains(x.Id)); // See if this user is subscribed to this topic var topicNotifications = _topicNotificationService.GetByUserAndTopic(LoggedOnReadOnlyUser, topic); // Populate the properties we can viewModel.IsLocked = topic.IsLocked; viewModel.IsSticky = topic.IsSticky; viewModel.IsTopicStarter = post.IsTopicStarter; viewModel.SubscribeToTopic = topicNotifications.Any(); viewModel.Categories = _categoryService.GetBaseSelectListCategories(allowedAccessCategories); // Tags - Populate from the topic if (topic.Tags.Any()) { viewModel.Tags = string.Join<string>(",", topic.Tags.Select(x => x.Tag)); } // Populate the poll answers if (topic.Poll != null && topic.Poll.PollAnswers.Any()) { // Has a poll so add it to the view model viewModel.PollAnswers = topic.Poll.PollAnswers; viewModel.PollCloseAfterDays = topic.Poll.ClosePollAfterDays ?? 0; } } // Return the edit view return View(viewModel); } } // If we get here the user has no permission to try and edit the post return ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")); } }
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 posting flood control // Flood control test if (!_topicService.PassedTopicFloodTest(topicViewModel.Name, LoggedOnReadOnlyUser)) { // Failed test so don't post topic return View(topicViewModel); } // 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) > 1) { // 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); }
public ActionResult Create(CreateEditTopicViewModel viewModel) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var cats = _categoryService.GetAllowedEditCategories(UsersRole); if (cats.Count > 0) { if (ModelState.IsValid) { if (CheckCats(viewModel.Category, cats)) { var topic = new Topic(); var post = new Post(); topic.Name = viewModel.Name; topic.Category_Id = viewModel.Category; topic.IsLocked = viewModel.IsLocked; topic.IsSticky = viewModel.IsSticky; topic.MembershipUser_Id = LoggedOnReadOnlyUser.Id; topic.Post_Id = post.Id; post.PostContent = viewModel.Content; post.MembershipUser_Id = LoggedOnReadOnlyUser.Id; post.Topic_Id = topic.Id; post.IsTopicStarter = true; topic.ShotContent = string.Concat(StringUtils.ReturnAmountWordsFromString(StringUtils.StripHtmlFromString(post.PostContent), 50), "...."); topic.isAutoShotContent = true; // Sort image out first if (viewModel.Files != null) { // 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, topic.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 var file = viewModel.Files[0]; if (file != null) { // If successful then upload the file var uploadResult = AppHelpers.UploadFile(file, uploadFolderPath, LocalizationService, true); if (!uploadResult.UploadSuccessful) { TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = uploadResult.ErrorMessage, MessageType = GenericMessages.danger }; return(View(viewModel)); } // Save avatar to user topic.Image = uploadResult.UploadedFileName; //viewModel.Image = topic.Image; } } try { _topicServic.Add(topic); _postSevice.Add(post); unitOfWork.Commit(); return(RedirectToAction("Edit", new { Id = topic.Id })); } catch (Exception ex) { LoggingService.Error(ex.Message); unitOfWork.Rollback(); } } else { //viewModel.Category = null; //No permission to create a Poll so show a message but create the topic //TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel //{ // Message = LocalizationService.GetResourceString("Errors.NoPermissionCatergory"), // MessageType = GenericMessages.info //}; ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.CatergoryMessage")); } } viewModel.Categories = _categoryService.GetBaseSelectListCategories(cats); return(View(viewModel)); } return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); } }
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)); }
public ActionResult EditPostTopic(CreateEditTopicViewModel editPostViewModel) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Get the category var category = _categoryService.Get(editPostViewModel.Category); // First check this user is allowed to create topics in this category var permissions = RoleService.GetPermissions(category, UsersRole); // Now we have the category and permissionSet - Populate the optional permissions // This is just in case the viewModel is return back to the view also sort the allowedCategories // Get the allowed categories for this user var allowedAccessCategories = _categoryService.GetAllowedCategories(UsersRole); var allowedCreateTopicCategories = _categoryService.GetAllowedCategories(UsersRole, SiteConstants.Instance.PermissionCreateTopics); var allowedCreateTopicCategoryIds = allowedCreateTopicCategories.Select(x => x.Id); allowedAccessCategories.RemoveAll(x => allowedCreateTopicCategoryIds.Contains(x.Id)); editPostViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions); editPostViewModel.Categories = _categoryService.GetBaseSelectListCategories(allowedAccessCategories); editPostViewModel.IsTopicStarter = editPostViewModel.Id == Guid.Empty; if (editPostViewModel.PollAnswers == null) { editPostViewModel.PollAnswers = new List<PollAnswer>(); } if (ModelState.IsValid) { try { var topicPostInModeration = false; // Check stop words var stopWords = _bannedWordService.GetAll(true); foreach (var stopWord in stopWords) { if (editPostViewModel.Content.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0 || editPostViewModel.Name.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0) { ShowMessage(new GenericMessageViewModel { Message = LocalizationService.GetResourceString("StopWord.Error"), MessageType = GenericMessages.danger }); var p = _postService.Get(editPostViewModel.Id); var t = p.Topic; // Ahhh found a stop word. Abandon operation captain. return Redirect(t.NiceUrl); } } // Quick check to see if user is locked out, when logged in if (LoggedOnReadOnlyUser.IsLockedOut || LoggedOnReadOnlyUser.DisablePosting == true || !LoggedOnReadOnlyUser.IsApproved) { FormsAuthentication.SignOut(); return ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoAccess")); } // Got to get a lot of things here as we have to check permissions // Get the post var post = _postService.Get(editPostViewModel.Id); // Get the topic var topic = post.Topic; if (post.User.Id == LoggedOnReadOnlyUser.Id || permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked) { // Get the DB user so we can use lazy loading and update var loggedOnUser = MembershipService.GetUser(LoggedOnReadOnlyUser.Id); // Want the same edit date on both post and postedit var dateEdited = DateTime.UtcNow; // Create a post edit var postEdit = new PostEdit { Post = post, DateEdited = dateEdited, EditedBy = loggedOnUser, OriginalPostContent = post.PostContent, OriginalPostTitle = post.IsTopicStarter ? topic.Name : string.Empty }; // User has permission so update the post post.PostContent = _bannedWordService.SanitiseBannedWords(editPostViewModel.Content); post.DateEdited = dateEdited; post = _postService.SanitizePost(post); // Update postedit content postEdit.EditedPostContent = post.PostContent; // if topic starter update the topic if (post.IsTopicStarter) { // if category has changed then update it if (topic.Category.Id != editPostViewModel.Category) { var cat = _categoryService.Get(editPostViewModel.Category); topic.Category = cat; } topic.IsLocked = editPostViewModel.IsLocked; topic.IsSticky = editPostViewModel.IsSticky; topic.Name = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Name)); // Update post edit postEdit.EditedPostTitle = topic.Name; // See if there is a poll if (editPostViewModel.PollAnswers != null && editPostViewModel.PollAnswers.Count(x => !string.IsNullOrEmpty(x?.Answer)) > 1 && permissions[SiteConstants.Instance.PermissionCreatePolls].IsTicked) { // Now sort the poll answers, what to add and what to remove // Poll answers already in this poll. //var existingAnswers = topic.Poll.PollAnswers.Where(x => postedIds.Contains(x.Id)).ToList(); var postedIds = editPostViewModel.PollAnswers.Where(x => !string.IsNullOrEmpty(x?.Answer)).Select(x => x.Id); // This post might not have a poll on it, if not they are creating a poll for the first time var topicPollAnswerIds = new List<Guid>(); var pollAnswersToRemove = new List<PollAnswer>(); if (topic.Poll == null) { // Create a new Poll var newPoll = new Poll { User = loggedOnUser }; // Create the poll _pollService.Add(newPoll); // Save the poll in the context so we can add answers unitOfWork.SaveChanges(); // Add the poll to the topic topic.Poll = newPoll; } else { topicPollAnswerIds = topic.Poll.PollAnswers.Select(p => p.Id).ToList(); pollAnswersToRemove = topic.Poll.PollAnswers.Where(x => !postedIds.Contains(x.Id)).ToList(); } // Set the amount of days to close the poll topic.Poll.ClosePollAfterDays = editPostViewModel.PollCloseAfterDays; var existingAnswers = editPostViewModel.PollAnswers.Where(x => !string.IsNullOrEmpty(x.Answer) && topicPollAnswerIds.Contains(x.Id)).ToList(); var newPollAnswers = editPostViewModel.PollAnswers.Where(x => !string.IsNullOrEmpty(x.Answer) && !topicPollAnswerIds.Contains(x.Id)).ToList(); // Loop through existing and update names if need be //TODO: Need to think about this in future versions if they change the name //TODO: As they could game the system by getting votes and changing name? foreach (var existPollAnswer in existingAnswers) { // Get the existing answer from the current topic var pa = topic.Poll.PollAnswers.FirstOrDefault(x => x.Id == existPollAnswer.Id); if (pa != null && pa.Answer != existPollAnswer.Answer) { // If the answer has changed then update it pa.Answer = existPollAnswer.Answer; } } // Loop through and remove the old poll answers and delete foreach (var oldPollAnswer in pollAnswersToRemove) { // Delete _pollAnswerService.Delete(oldPollAnswer); // Remove from Poll topic.Poll.PollAnswers.Remove(oldPollAnswer); } // Poll answers to add foreach (var newPollAnswer in newPollAnswers) { if (newPollAnswer != null) { var npa = new PollAnswer { Poll = topic.Poll, Answer = newPollAnswer.Answer }; _pollAnswerService.Add(npa); topic.Poll.PollAnswers.Add(npa); } } } else { // Need to check if this topic has a poll, because if it does // All the answers have now been removed so remove the poll. if (topic.Poll != null) { //Firstly remove the answers if there are any if (topic.Poll.PollAnswers != null && topic.Poll.PollAnswers.Any()) { var answersToDelete = new List<PollAnswer>(); answersToDelete.AddRange(topic.Poll.PollAnswers); foreach (var answer in answersToDelete) { // Delete _pollAnswerService.Delete(answer); // Remove from Poll topic.Poll.PollAnswers.Remove(answer); } } // Now delete the poll var pollToDelete = topic.Poll; _pollService.Delete(pollToDelete); // Remove from topic. topic.Poll = null; } } // Tags topic.Tags.Clear(); if (!string.IsNullOrEmpty(editPostViewModel.Tags)) { _topicTagService.Add(editPostViewModel.Tags.ToLower(), topic); } // if the Category has moderation marked then the topic needs to // go back into moderation if (topic.Category.ModerateTopics == true) { topic.Pending = true; topicPostInModeration = true; } // Sort the post search field post.SearchField = _postService.SortSearchField(post.IsTopicStarter, topic, topic.Tags); } else { // if the Category has moderation marked then the post needs to // go back into moderation if (topic.Category.ModeratePosts == true) { post.Pending = true; topicPostInModeration = true; } } // Add the post edit too _postEditService.Add(postEdit); // Commit the changes unitOfWork.Commit(); if (topicPostInModeration) { // If in moderation then let the user now TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Moderate.AwaitingModeration"), MessageType = GenericMessages.info }; } else { TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Post.Updated"), MessageType = GenericMessages.success }; } // redirect back to topic return Redirect($"{topic.NiceUrl}?postbadges=true"); } } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Errors.GenericError"), MessageType = GenericMessages.danger }; } return ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")); } } return View(editPostViewModel); }
public ActionResult Create(CreateEditTopicViewModel viewModel) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var cats = _categoryService.GetAllowedEditCategories(UsersRole); if (cats.Count > 0) { if (ModelState.IsValid) { if (CheckCats(viewModel.Category, cats)) { var topic = new Topic(); var post = new Post(); topic.Name = viewModel.Name; topic.Category_Id = viewModel.Category; topic.IsLocked = viewModel.IsLocked; topic.IsSticky = viewModel.IsSticky; topic.MembershipUser_Id = LoggedOnReadOnlyUser.Id; topic.Id = post.Id; post.PostContent = viewModel.Content; post.MembershipUser_Id = LoggedOnReadOnlyUser.Id; post.Topic_Id = topic.Id; post.IsTopicStarter = true; try { _topicServic.Add(topic); _postSevice.Add(post); unitOfWork.Commit(); } catch (Exception ex) { LoggingService.Error(ex.Message); unitOfWork.Rollback(); } } else { //viewModel.Category = null; //No permission to create a Poll so show a message but create the topic //TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel //{ // Message = LocalizationService.GetResourceString("Errors.NoPermissionCatergory"), // MessageType = GenericMessages.info //}; ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.CatergoryMessage")); } } viewModel.Categories = _categoryService.GetBaseSelectListCategories(cats); return(View(viewModel)); } return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); } }
public ActionResult EditPostTopic(Guid id) { using (UnitOfWorkManager.NewUnitOfWork()) { // Get the post var post = _postService.Get(id); // Get the topic var topic = post.Topic; // get the users permissions var permissions = RoleService.GetPermissions(topic.Category, UsersRole); // Is the user allowed to edit this post if (post.User.Id == LoggedOnUser.Id || permissions[AppConstants.PermissionEditPosts].IsTicked) { // Get the allowed categories for this user var allowedCategories = _categoryService.GetAllowedCategories(UsersRole); // If this user hasn't got any allowed cats OR they are not allowed to post then abandon if (allowedCategories.Any() && LoggedOnUser.DisablePosting != true) { // Create the model for just the post var viewModel = new CreateEditTopicViewModel { Content = Server.HtmlDecode(post.PostContent), Id = post.Id, Category = topic.Category.Id, Name = topic.Name }; // Now check if this is a topic starter, if so add the rest of the field if (post.IsTopicStarter) { // See if this user is subscribed to this topic var subscribedToTopic = LoggedOnUser.TopicNotifications.Any(x => x.Topic.Id == topic.Id); // Populate the properties we can viewModel.IsLocked = topic.IsLocked; viewModel.IsSticky = topic.IsSticky; viewModel.IsTopicStarter = post.IsTopicStarter; viewModel.SubscribeToTopic = subscribedToTopic; viewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions); viewModel.Categories = GetBaseSelectListCategories(allowedCategories); // Tags - Populate from the topic if (topic.Tags.Any()) { viewModel.Tags = string.Join <string>(",", topic.Tags.Select(x => x.Tag)); } // Populate the poll answers if (topic.Poll != null && topic.Poll.PollAnswers.Any()) { // Has a poll so add it to the view model viewModel.PollAnswers = topic.Poll.PollAnswers; } } // Return the edit view return(View(viewModel)); } } // If we get here the user has no permission to try and edit the post return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); } }