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) { 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 (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 = CategoryService.Get(topicViewModel.Category); // First check this user is allowed to create topics in this category var permissions = PermissionService.GetPermissions(category, _membersGroup, MemberService, CategoryPermissionService); // 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 = 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 = 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.Any(x => !string.IsNullOrEmpty(x.Answer))) { // 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 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; 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 = TopicService.Add(topic); // Save the changes unitOfWork.SaveChanges(); // Now create and add the post to the topic TopicService.AddLastPost(topic, topicViewModel.TopicContent, PostService); // Update the users points score for posting 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 TopicNotificationService.Add(topicNotification); } try { unitOfWork.Commit(); if (!moderate) { successfullyCreated = true; } // Update the users post count 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($"{topic.Url}?postbadges=true")); } if (moderate) { // Moderation needed // Tell the user the topic is awaiting moderation return(MessageToHomePage(Lang("Moderate.AwaitingModeration"))); } } } ShowMessage(); return(Redirect(Urls.GenerateUrl(Urls.UrlType.TopicCreate))); }
public PartialViewResult CreatePost(CreateAjaxPostViewModel post) { // Make sure correct culture on Ajax Call PermissionSet permissions; Post newPost; Topic topic; string postContent; using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Quick check to see if user is locked out, when logged in if (CurrentMember.IsLockedOut | !CurrentMember.IsApproved) { MemberService.LogOff(); throw new Exception(Lang("Errors.NoAccess")); } // Check for banned links if (BannedLinkService.ContainsBannedLink(post.PostContent)) { throw new Exception(Lang("Errors.BannedLink")); } topic = TopicService.Get(post.Topic); postContent = BannedWordService.SanitiseBannedWords(post.PostContent); var akismetHelper = new AkismetHelper(); // Create the new post newPost = PostService.AddNewPost(postContent, topic, CurrentMember, PermissionService, MemberService, CategoryPermissionService, MemberPointsService, out permissions); if (!akismetHelper.IsSpam(newPost)) { try { unitOfWork.Commit(); } catch (Exception ex) { unitOfWork.Rollback(); LogError(ex); throw new Exception(Lang("Errors.GenericMessage")); } } else { unitOfWork.Rollback(); throw new Exception(Lang("Errors.PossibleSpam")); } } //Check for moderation if (newPost.Pending) { return(PartialView(PathHelper.GetThemePartialViewPath("PostModeration"))); } // All good send the notifications and send the post back using (UnitOfWorkManager.NewUnitOfWork()) { // Create the view model var viewModel = PostMapper.MapPostViewModel(permissions, newPost, CurrentMember, Settings, topic, new List <Vote>(), new List <Favourite>()); // Success send any notifications NotifyNewTopics(topic, postContent); return(PartialView(PathHelper.GetThemePartialViewPath("Post"), viewModel)); } }
public ActionResult MemberRegisterLogic(RegisterViewModel userModel) { var forumReturnUrl = Settings.ForumRootUrl; var newMemberGroup = Settings.Group; if (userModel.ForumId != null && userModel.ForumId != Settings.ForumId) { var correctForum = Dialogue.Settings((int)userModel.ForumId); forumReturnUrl = correctForum.ForumRootUrl; newMemberGroup = correctForum.Group; } using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Secondly see if the email is banned if (BannedEmailService.EmailIsBanned(userModel.Email)) { ModelState.AddModelError(string.Empty, Lang("Error.EmailIsBanned")); if (userModel.LoginType != LoginType.Standard) { ShowMessage(); return(Redirect(Settings.RegisterUrl)); } return(CurrentUmbracoPage()); } var userToSave = AppHelpers.UmbMemberHelper().CreateRegistrationModel(DialogueConfiguration.Instance.MemberTypeAlias); userToSave.Username = BannedWordService.SanitiseBannedWords(userModel.UserName); userToSave.Name = userToSave.Username; userToSave.UsernameIsEmail = false; userToSave.Email = userModel.Email; userToSave.Password = userModel.Password; var homeRedirect = false; MembershipCreateStatus createStatus; AppHelpers.UmbMemberHelper().RegisterMember(userToSave, out createStatus, false); if (createStatus != MembershipCreateStatus.Success) { ModelState.AddModelError(string.Empty, MemberService.ErrorCodeToString(createStatus)); } else { // Get the umbraco member var umbracoMember = AppHelpers.UmbServices().MemberService.GetByUsername(userToSave.Username); // Set the role/group they should be in AppHelpers.UmbServices().MemberService.AssignRole(umbracoMember.Id, newMemberGroup.Name); // See if this is a social login and we have their profile pic if (!string.IsNullOrEmpty(userModel.SocialProfileImageUrl)) { // We have an image url - Need to save it to their profile var image = AppHelpers.GetImageFromExternalUrl(userModel.SocialProfileImageUrl); // Upload folder path for member var uploadFolderPath = MemberService.GetMemberUploadPath(umbracoMember.Id); // Upload the file var uploadResult = UploadedFileService.UploadFile(image, uploadFolderPath); // Don't throw error if problem saving avatar, just don't save it. if (uploadResult.UploadSuccessful) { umbracoMember.Properties[AppConstants.PropMemberAvatar].Value = string.Concat(VirtualPathUtility.ToAbsolute(AppConstants.UploadFolderPath), umbracoMember.Id, "/", uploadResult.UploadedFileName); } } // Now check settings, see if users need to be manually authorised // OR Does the user need to confirm their email var manuallyAuthoriseMembers = Settings.ManuallyAuthoriseNewMembers; var memberEmailAuthorisationNeeded = Settings.NewMembersMustConfirmAccountsViaEmail; if (manuallyAuthoriseMembers || memberEmailAuthorisationNeeded) { umbracoMember.IsApproved = false; } // Store access token for social media account in case we want to do anything with it if (userModel.LoginType == LoginType.Facebook) { umbracoMember.Properties[AppConstants.PropMemberFacebookAccessToken].Value = userModel.UserAccessToken; } if (userModel.LoginType == LoginType.Google) { umbracoMember.Properties[AppConstants.PropMemberGoogleAccessToken].Value = userModel.UserAccessToken; } // Do a save on the member AppHelpers.UmbServices().MemberService.Save(umbracoMember); if (Settings.EmailAdminOnNewMemberSignup) { var sb = new StringBuilder(); sb.AppendFormat("<p>{0}</p>", string.Format(Lang("Members.NewMemberRegistered"), Settings.ForumName, Settings.ForumRootUrl)); sb.AppendFormat("<p>{0} - {1}</p>", userToSave.Username, userToSave.Email); var email = new Email { EmailTo = Settings.AdminEmailAddress, EmailFrom = Settings.NotificationReplyEmailAddress, NameTo = Lang("Members.Admin"), Subject = Lang("Members.NewMemberSubject") }; email.Body = EmailService.EmailTemplate(email.NameTo, sb.ToString()); EmailService.SendMail(email); } // Fire the activity Service ActivityService.MemberJoined(MemberMapper.MapMember(umbracoMember)); var userMessage = new GenericMessageViewModel(); // Set the view bag message here if (manuallyAuthoriseMembers) { userMessage.Message = Lang("Members.NowRegisteredNeedApproval"); userMessage.MessageType = GenericMessages.Success; } else if (memberEmailAuthorisationNeeded) { userMessage.Message = Lang("Members.MemberEmailAuthorisationNeeded"); userMessage.MessageType = GenericMessages.Success; } else { // If not manually authorise then log the user in FormsAuthentication.SetAuthCookie(userToSave.Username, true); userMessage.Message = Lang("Members.NowRegistered"); userMessage.MessageType = GenericMessages.Success; } //Show the message ShowMessage(userMessage); if (!manuallyAuthoriseMembers && !memberEmailAuthorisationNeeded) { homeRedirect = true; } try { unitOfWork.Commit(); // Only send the email if the admin is not manually authorising emails or it's pointless EmailService.SendEmailConfirmationEmail(umbracoMember, Settings); if (homeRedirect && !string.IsNullOrEmpty(forumReturnUrl)) { if (Url.IsLocalUrl(userModel.ReturnUrl) && userModel.ReturnUrl.Length >= 1 && userModel.ReturnUrl.StartsWith("/") && !userModel.ReturnUrl.StartsWith("//") && !userModel.ReturnUrl.StartsWith("/\\")) { return(Redirect(userModel.ReturnUrl)); } return(Redirect(forumReturnUrl)); } } catch (Exception ex) { unitOfWork.Rollback(); LogError("Eror during member registering", ex); FormsAuthentication.SignOut(); ModelState.AddModelError(string.Empty, ex.Message); } } if (userModel.LoginType != LoginType.Standard) { ShowMessage(); return(Redirect(Settings.RegisterUrl)); } return(CurrentUmbracoPage()); } }
public ActionResult EditPost(EditPostViewModel editPostViewModel) { 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; var category = CategoryService.Get(topic.CategoryId); topic.Category = category; // get the users permissions var permissions = PermissionService.GetPermissions(category, _membersGroup, MemberService, CategoryPermissionService); if (post.MemberId == CurrentMember.Id || permissions[AppConstants.PermissionModerate].IsTicked) { // User has permission so update the post post.PostContent = AppHelpers.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 = AppHelpers.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 postedIds = editPostViewModel.PollAnswers.Select(x => x.Id); //var existingAnswers = topic.Poll.PollAnswers.Where(x => postedIds.Contains(x.Id)).ToList(); var existingAnswers = editPostViewModel.PollAnswers.Where(x => topic.Poll.PollAnswers.Select(p => p.Id).Contains(x.Id)).ToList(); var newPollAnswers = editPostViewModel.PollAnswers.Where(x => !topic.Poll.PollAnswers.Select(p => p.Id).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 PollService.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 }; PollService.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 PollService.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; } } } // redirect back to topic var message = new GenericMessageViewModel { Message = Lang("Post.Updated"), MessageType = GenericMessages.Success }; try { unitOfWork.Commit(); ShowMessage(message); return(Redirect(topic.Url)); } catch (Exception ex) { unitOfWork.Rollback(); LogError(ex); throw new Exception(Lang("Errors.GenericError")); } } return(NoPermission(topic)); } }
public ActionResult Edit(PostMemberEditViewModel userModel) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var user = MemberService.Get(userModel.MemberEditViewModel.Id); var userEditUrl = $"{Urls.GenerateUrl(Urls.UrlType.EditMember)}?id={user.Id}"; // Before we do anything DB wise, check it contains no bad links if (BannedLinkService.ContainsBannedLink(userModel.MemberEditViewModel.Signature) || BannedLinkService.ContainsBannedLink(userModel.MemberEditViewModel.Website)) { ShowMessage(new GenericMessageViewModel { Message = Lang("Errors.BannedLink"), MessageType = GenericMessages.Danger }); return(Redirect(userEditUrl)); } // Sort image out first if (userModel.MemberEditViewModel.Files != null) { // Before we save anything, check the user already has an upload folder and if not create one //var uploadFolderPath = AppHelpers.GetMemberUploadPath(CurrentMember.Id); // Loop through each file and get the file info and save to the users folder and Db var file = userModel.MemberEditViewModel.Files[0]; if (file != null) { // If successful then upload the file var memberMediFolderId = MemberService.ConfirmMemberAvatarMediaFolder(); var uploadResult = UploadedFileService.UploadFile(file, memberMediFolderId, true); if (!uploadResult.UploadSuccessful) { ShowMessage(new GenericMessageViewModel { Message = uploadResult.ErrorMessage, MessageType = GenericMessages.Danger }); return(Redirect(userEditUrl)); } // Save avatar to user user.Avatar = uploadResult.UploadedFileUrl; } } user.Signature = BannedWordService.SanitiseBannedWords(AppHelpers.ScrubHtml(userModel.MemberEditViewModel.Signature)); if (userModel.MemberEditViewModel.Twitter != null && userModel.MemberEditViewModel.Twitter.IndexOf("http", StringComparison.OrdinalIgnoreCase) <= 0) { user.Twitter = BannedWordService.SanitiseBannedWords(AppHelpers.SafePlainText(userModel.MemberEditViewModel.Twitter)); } user.Website = BannedWordService.SanitiseBannedWords(AppHelpers.SafePlainText(userModel.MemberEditViewModel.Website)); user.Comments = BannedWordService.SanitiseBannedWords(AppHelpers.SafePlainText(userModel.MemberEditViewModel.Comments)); // User is trying to update their email address, need to // check the email is not already in use if (userModel.MemberEditViewModel.Email != user.Email) { // Add get by email address var sanitisedEmail = AppHelpers.SafePlainText(userModel.MemberEditViewModel.Email); var userWithSameEmail = MemberService.GetByEmail(sanitisedEmail); //Firstly check new email isn't banned! if (BannedEmailService.EmailIsBanned(sanitisedEmail)) { unitOfWork.Rollback(); ModelState.AddModelError(string.Empty, Lang("Error.EmailIsBanned")); ShowMessage(); return(Redirect(userEditUrl)); } // If the username doesn't match this user then someone else has this email address already if (userWithSameEmail != null && userWithSameEmail.UserName != user.UserName) { unitOfWork.Rollback(); ModelState.AddModelError(string.Empty, Lang("Members.Errors.DuplicateEmail")); ShowMessage(); return(Redirect(userEditUrl)); } user.Email = sanitisedEmail; } // User is trying to change username, need to check if a user already exists // with the username they are trying to change to var changedUsername = false; var sanitisedUsername = BannedWordService.SanitiseBannedWords(AppHelpers.SafePlainText(userModel.MemberEditViewModel.UserName)); if (sanitisedUsername != user.UserName) { if (MemberService.Get(sanitisedUsername) != null) { unitOfWork.Rollback(); ModelState.AddModelError(string.Empty, Lang("Members.Errors.DuplicateUserName")); ShowMessage(); return(Redirect(userEditUrl)); } user.UserName = sanitisedUsername; changedUsername = true; } // Update Everything MemberService.SaveMember(user, changedUsername); ActivityService.ProfileUpdated(user); ShowMessage(new GenericMessageViewModel { Message = Lang("Member.ProfileUpdated"), MessageType = GenericMessages.Success }); try { // Need to save member here unitOfWork.Commit(); if (changedUsername) { // User has changed their username so need to log them in // as there new username of var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { var authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket != null) { var newFormsIdentity = new FormsIdentity(new FormsAuthenticationTicket(authTicket.Version, user.UserName, authTicket.IssueDate, authTicket.Expiration, authTicket.IsPersistent, authTicket.UserData)); var roles = authTicket.UserData.Split("|".ToCharArray()); var newGenericPrincipal = new GenericPrincipal(newFormsIdentity, roles); System.Web.HttpContext.Current.User = newGenericPrincipal; } } // sign out current user FormsAuthentication.SignOut(); // Abandon the session Session.Abandon(); // Sign in new user FormsAuthentication.SetAuthCookie(user.UserName, false); } } catch (Exception ex) { unitOfWork.Rollback(); LogError(ex); ModelState.AddModelError(string.Empty, Lang("Errors.GenericMessage")); } ShowMessage(); return(Redirect(userEditUrl)); } }