public static ViewPostViewModel MapPostViewModel(PermissionSet permissions, Post post, Member currentMember, DialogueSettings settings, Topic topic, List<Vote> allPostVotes, List<Favourite> favourites, bool showTopicLinks = false) { var postViewModel = new ViewPostViewModel { Permissions = permissions, Post = post, User = currentMember, ParentTopic = topic, Votes = allPostVotes.Where(x => x.Post.Id == post.Id).ToList(), LoggedOnMemberId = currentMember != null ? currentMember.Id : 0, AllowedToVote = (currentMember != null && currentMember.Id != post.MemberId && currentMember.TotalPoints > settings.AmountOfPointsBeforeAUserCanVote), PostCount = post.Member.PostCount, IsAdminOrMod = HttpContext.Current.User.IsInRole(AppConstants.AdminRoleName) || permissions[AppConstants.PermissionModerate].IsTicked, HasFavourited = favourites.Any(x => x.PostId == post.Id), IsTopicStarter = post.IsTopicStarter, ShowTopicLinks = showTopicLinks }; postViewModel.UpVotes = postViewModel.Votes.Count(x => x.Amount > 0); postViewModel.DownVotes = postViewModel.Votes.Count(x => x.Amount < 0); return postViewModel; }
/// <summary> /// Check whether a topic is spam or not /// </summary> /// <param name="topic"></param> /// <returns></returns> public bool IsSpam(Topic topic) { // If akisment is is not enable always return false if (Dialogue.Settings().EnableAkismetSpamControl == false || string.IsNullOrEmpty(Dialogue.Settings().AkismetKey)) return false; // Akisment must be enabled var firstOrDefault = topic.Posts.FirstOrDefault(x => x.IsTopicStarter); if (firstOrDefault != null) { var comment = new Comment { blog = AppHelpers.CheckLinkHasHttp(Dialogue.Settings().ForumRootUrlWithDomain), comment_type = "comment", comment_author = topic.Member.UserName, comment_author_email = topic.Member.Email, comment_content = firstOrDefault.PostContent, permalink = String.Empty, referrer = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"], user_agent = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"], user_ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] }; var validator = new Validator(Dialogue.Settings().AkismetKey); return validator.IsSpam(comment); } return true; }
/// <summary> /// Delete a topic /// </summary> /// <param name="topic"></param> public void Delete(Topic topic) { topic.LastPost = null; var memberIds = new List<int>(); // Delete all posts if (topic.Posts != null) { var postsToDelete = new List<Post>(); postsToDelete.AddRange(topic.Posts); memberIds = postsToDelete.Select(x => x.MemberId).Distinct().ToList(); foreach (var post in postsToDelete) { ServiceFactory.PostService.Delete(post); } // Sync the members post count. For all members who had a post deleted. var members = ServiceFactory.MemberService.GetAllById(memberIds); ServiceFactory.PostService.SyncMembersPostCount(members); } if (topic.TopicNotifications != null) { var notificationsToDelete = new List<TopicNotification>(); notificationsToDelete.AddRange(topic.TopicNotifications); foreach (var topicNotification in notificationsToDelete) { ServiceFactory.TopicNotificationService.Delete(topicNotification); } } ContextPerRequest.Db.Topic.Remove(topic); }
/// <summary> /// Create a new topic and also the topic starter post /// </summary> /// <param name="topic"></param> /// <returns></returns> public Topic Add(Topic topic) { topic = SanitizeTopic(topic); topic.CreateDate = DateTime.UtcNow; // url slug generator topic.Slug = AppHelpers.GenerateSlug(topic.Name, GetTopicBySlugUrls(AppHelpers.CreateUrl(topic.Name)), null); return ContextPerRequest.Db.Topic.Add(topic); }
public ActionResult NoPermission(Topic topic) { // Trying to be a sneaky mo fo, so tell them var message = new GenericMessageViewModel { Message = Lang("Errors.NoPermission"), MessageType = GenericMessages.Warning }; ShowMessage(message); return Redirect(topic.Url); }
/// <summary> /// Add a last post to a topic. Must be part of a separate database update /// in EF because of circular dependencies. So save the topic before calling this. /// </summary> /// <param name="topic"></param> /// <param name="postContent"></param> /// <returns></returns> public Topic AddLastPost(Topic topic, string postContent) { topic = SanitizeTopic(topic); // Create the post var post = new Post { DateCreated = DateTime.UtcNow, IsTopicStarter = true, DateEdited = DateTime.UtcNow, PostContent = AppHelpers.GetSafeHtml(postContent), MemberId = topic.MemberId, Topic = topic }; // Add the post ServiceFactory.PostService.Add(post); topic.LastPost = post; return topic; }
/// <summary> /// Add a new post /// </summary> /// <param name="postContent"> </param> /// <param name="topic"> </param> /// <param name="user"></param> /// <param name="permissions"> </param> /// <returns>True if post added</returns> public Post AddNewPost(string postContent, Topic topic, Member user, out PermissionSet permissions) { // Get the permissions for the category that this topic is in permissions = ServiceFactory.PermissionService.GetPermissions(topic.Category, user.Groups.FirstOrDefault()); // Check this users role has permission to create a post if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked) { // Throw exception so Ajax caller picks it up throw new ApplicationException(AppHelpers.Lang("Errors.NoPermission")); } // Has permission so create the post var newPost = new Post { PostContent = postContent, Member = user, MemberId = user.Id, Topic = topic, IpAddress = AppHelpers.GetUsersIpAddress(), DateCreated = DateTime.UtcNow, DateEdited = DateTime.UtcNow }; newPost = SanitizePost(newPost); var category = topic.Category; if (category.ModerateAllPostsInThisCategory == true) { newPost.Pending = true; } // create the post Add(newPost); // Update the users points score and post count for posting ServiceFactory.MemberPointsService.Add(new MemberPoints { Points = Dialogue.Settings().PointsAddedPerNewPost, MemberId = user.Id, RelatedPostId = newPost.Id }); // add the last post to the topic topic.LastPost = newPost; // Add post to members count ServiceFactory.MemberService.AddPostCount(user); return newPost; }
public Topic SanitizeTopic(Topic topic) { topic.Name = AppHelpers.SafePlainText(topic.Name); return topic; }
/// <summary> /// Mark a topic as solved /// </summary> /// <param name="topic"></param> /// <param name="post"></param> /// <param name="marker"></param> /// <param name="solutionWriter"></param> /// <returns>True if topic has been marked as solved</returns> public bool SolveTopic(Topic topic, Post post, Member marker, Member solutionWriter) { var solved = false; // Make sure this user owns the topic, if not do nothing if (topic.MemberId == marker.Id) { // Update the post post.IsSolution = true; // Update the topic topic.Solved = true; // Assign points // Do not give points to the user if they are marking their own post as the solution if (marker.Id != solutionWriter.Id) { ServiceFactory.MemberPointsService.Add(new MemberPoints { Points = Dialogue.Settings().PointsAddedForASolution, Member = solutionWriter, MemberId = solutionWriter.Id, RelatedPostId = post.Id }); } solved = true; } return solved; }
private void NotifyNewTopics(Topic topic, string postContent) { // Get all notifications for this category var notifications = ServiceFactory.TopicNotificationService.GetByTopic(topic).Select(x => x.MemberId).ToList(); if (notifications.Any()) { // remove the current user from the notification, don't want to notify yourself that you // have just made a topic! notifications.Remove(CurrentMember.Id); if (notifications.Count > 0) { // Now get all the users that need notifying var usersToNotify = ServiceFactory.MemberService.GetUsersById(notifications); // Create the email var sb = new StringBuilder(); sb.AppendFormat("<p>{0}</p>", string.Format(Lang("Post.Notification.NewPosts"), topic.Name)); sb.AppendFormat("<p>{0}</p>", string.Concat(Settings.ForumRootUrlWithDomain, topic.Url)); sb.Append(postContent); // create the emails only to people who haven't had notifications disabled var emails = usersToNotify.Where(x => x.DisableEmailNotifications != true).Select(user => new Email { Body = ServiceFactory.EmailService.EmailTemplate(user.UserName, sb.ToString()), EmailFrom = Settings.NotificationReplyEmailAddress, EmailTo = user.Email, NameTo = user.UserName, Subject = string.Concat(Lang("Post.Notification.Subject"), Settings.ForumName) }).ToList(); // and now pass the emails in to be sent ServiceFactory.EmailService.SendMail(emails); } } }
public ActionResult Create(CreateTopicViewModel topicViewModel) { if (ModelState.IsValid) { // Quick check to see if user is locked out, when logged in if (CurrentMember.IsLockedOut || CurrentMember.DisablePosting == true || !CurrentMember.IsApproved) { ServiceFactory.MemberService.LogOff(); return ErrorToHomePage(Lang("Errors.NoPermission")); } var successfullyCreated = false; var moderate = false; Category category; var topic = new Topic(); using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Before we do anything DB wise, check it contains no bad links if (ServiceFactory.BannedLinkService.ContainsBannedLink(topicViewModel.TopicContent)) { ShowMessage(new GenericMessageViewModel { Message = Lang("Errors.BannedLink"), MessageType = GenericMessages.Danger }); return Redirect(Urls.GenerateUrl(Urls.UrlType.TopicCreate)); } // Not using automapper for this one only, as a topic is a post and topic in one category = ServiceFactory.CategoryService.Get(topicViewModel.Category); // First check this user is allowed to create topics in this category var permissions = ServiceFactory.PermissionService.GetPermissions(category, _membersGroup); // Check this users role has permission to create a post if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked || !permissions[AppConstants.PermissionCreateTopics].IsTicked) { // Throw exception so Ajax caller picks it up ModelState.AddModelError(string.Empty, Lang("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 topic = new Topic { Name = ServiceFactory.BannedWordService.SanitiseBannedWords(topicViewModel.TopicName, Dialogue.Settings().BannedWords), Category = category, CategoryId = category.Id, Member = CurrentMember, MemberId = CurrentMember.Id }; // See if the user has actually added some content to the topic if (!string.IsNullOrEmpty(topicViewModel.TopicContent)) { // Check for any banned words topicViewModel.TopicContent = ServiceFactory.BannedWordService.SanitiseBannedWords(topicViewModel.TopicContent, Dialogue.Settings().BannedWords); // See if this is a poll and add it to the topic if (topicViewModel.PollAnswers != null && 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 { Member = CurrentMember, MemberId = CurrentMember.Id }; // Create the poll ServiceFactory.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; ServiceFactory.PollService.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 ShowMessage(new GenericMessageViewModel { Message = Lang("Errors.NoPermissionPolls"), MessageType = GenericMessages.Info }); } } // Check for moderation if (category.ModerateAllTopicsInThisCategory) { topic.Pending = true; moderate = true; } // Create the topic topic = ServiceFactory.TopicService.Add(topic); // Save the changes unitOfWork.SaveChanges(); // Now create and add the post to the topic ServiceFactory.TopicService.AddLastPost(topic, topicViewModel.TopicContent); // Update the users points score for posting ServiceFactory.MemberPointsService.Add(new MemberPoints { Points = Settings.PointsAddedPerNewPost, Member = CurrentMember, MemberId = CurrentMember.Id, RelatedPostId = topic.LastPost.Id }); // Now check its not spam var akismetHelper = new AkismetHelper(); if (akismetHelper.IsSpam(topic)) { // Could be spam, mark as pending topic.Pending = true; } // Subscribe the user to the topic as they have checked the checkbox if (topicViewModel.SubscribeToTopic) { // Create the notification var topicNotification = new TopicNotification { Topic = topic, Member = CurrentMember, MemberId = CurrentMember.Id }; //save ServiceFactory.TopicNotificationService.Add(topicNotification); } try { unitOfWork.Commit(); if (!moderate) { successfullyCreated = true; } // Update the users post count ServiceFactory.MemberService.AddPostCount(CurrentMember); } catch (Exception ex) { unitOfWork.Rollback(); LogError(ex); ModelState.AddModelError(string.Empty, Lang("Errors.GenericMessage")); } } else { ModelState.AddModelError(string.Empty, Lang("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.Url)); } if (moderate) { // Moderation needed // Tell the user the topic is awaiting moderation return MessageToHomePage(Lang("Moderate.AwaitingModeration")); } } } ShowModelErrors(); return Redirect(Urls.GenerateUrl(Urls.UrlType.TopicCreate)); }
public PartialViewResult GetTopicBreadcrumb(Topic topic) { var category = ServiceFactory.CategoryService.Get(topic.CategoryId, true); var viewModel = new BreadCrumbViewModel { Categories = category.ParentCategories, Topic = topic }; if (!viewModel.Categories.Any()) { viewModel.Categories.Add(topic.Category); } return PartialView(PathHelper.GetThemePartialViewPath("GetTopicBreadcrumb"), viewModel); }
/// <summary> /// return notifications for a specified user on a specified topic /// </summary> /// <param name="user"></param> /// <param name="topic"></param> /// <returns></returns> public IList<TopicNotification> GetByUserAndTopic(Member user, Topic topic) { return ContextPerRequest.Db.TopicNotification.Where(x => x.Topic.Id == topic.Id && x.MemberId == user.Id).Include(x => x.Topic).ToList(); }
/// <summary> /// Return all notifications for a specified topic /// </summary> /// <param name="topic"></param> /// <returns></returns> public IList<TopicNotification> GetByTopic(Topic topic) { return ContextPerRequest.Db.TopicNotification.AsNoTracking().Where(x => x.Topic.Id == topic.Id).Include(x => x.Topic).ToList(); }