/// <summary> /// Create a new topic and also the topic starter post /// </summary> /// <param name="topic"></param> /// <param name="files"></param> /// <param name="tags"></param> /// <param name="subscribe"></param> /// <param name="postContent"></param> /// <param name="post">Optional Post: Used for moving a existing post into a new topic</param> /// <returns></returns> public async Task <IPipelineProcess <Topic> > Create(Topic topic, HttpPostedFileBase[] files, string tags, bool subscribe, string postContent, Post post) { // url slug generator topic.Slug = ServiceHelpers.GenerateSlug(topic.Name, GetTopicBySlugLike(ServiceHelpers.CreateUrl(topic.Name)) .Select(x => x.Slug).ToList(), null); // Get the pipelines var topicCreatePipes = ForumConfiguration.Instance.PipelinesTopicCreate; // The model to process var piplineModel = new PipelineProcess <Topic>(topic); // See if we have any files if (files != null && files.Any(x => x != null)) { piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.PostedFiles, files); } // See if we have any tags if (!string.IsNullOrWhiteSpace(tags)) { piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Tags, tags); } // See if we have a post if (post != null) { piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Post, post); } // Add the extended data we need piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Subscribe, subscribe); piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.IsEdit, false); piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Content, postContent); piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Username, HttpContext.Current.User.Identity.Name); // Get instance of the pipeline to use var pipeline = new Pipeline <IPipelineProcess <Topic>, Topic>(_context); // Register the pipes var allTopicPipes = ImplementationManager.GetInstances <IPipe <IPipelineProcess <Topic> > >(); // Loop through the pipes and add the ones we want foreach (var pipe in topicCreatePipes) { if (allTopicPipes.ContainsKey(pipe)) { pipeline.Register(allTopicPipes[pipe]); } } // Process the pipeline return(await pipeline.Process(piplineModel)); }
/// <summary> /// Create new user /// </summary> /// <param name="newUser"></param> /// <param name="loginType"></param> /// <returns></returns> public async Task <IPipelineProcess <MembershipUser> > CreateUser(MembershipUser newUser, LoginType loginType) { // Get the site settings var settings = _settingsService.GetSettings(false); // Santise the user fields newUser = SanitizeUser(newUser); // Hash the password var salt = StringUtils.CreateSalt(Constants.SaltSize); var hash = StringUtils.GenerateSaltedHash(newUser.Password, salt); newUser.Password = hash; newUser.PasswordSalt = salt; // Add the roles newUser.Roles = new List <MembershipRole> { settings.NewMemberStartingRole }; // Set dates newUser.CreateDate = newUser.LastPasswordChangedDate = DateTime.UtcNow; newUser.LastLockoutDate = (DateTime)SqlDateTime.MinValue; newUser.LastLoginDate = DateTime.UtcNow; newUser.IsLockedOut = false; newUser.Slug = ServiceHelpers.GenerateSlug(newUser.UserName, GetUserBySlugLike(ServiceHelpers.CreateUrl(newUser.UserName)).Select(x => x.Slug).ToList(), null); // Get the pipelines var userCreatePipes = ForumConfiguration.Instance.PipelinesUserCreate; // The model to process var piplineModel = new PipelineProcess <MembershipUser>(newUser); // Add the login type to piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.LoginType, loginType); // Get instance of the pipeline to use var createUserPipeline = new Pipeline <IPipelineProcess <MembershipUser>, MembershipUser>(_context); // Register the pipes var allMembershipUserPipes = ImplementationManager.GetInstances <IPipe <IPipelineProcess <MembershipUser> > >(); // Loop through the pipes and add the ones we want foreach (var pipe in userCreatePipes) { if (allMembershipUserPipes.ContainsKey(pipe)) { createUserPipeline.Register(allMembershipUserPipes[pipe]); } } // Process the pipeline return(await createUserPipeline.Process(piplineModel)); }
/// <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 = ServiceHelpers.GenerateSlug(topic.Name, GetTopicBySlugLike(ServiceHelpers.CreateUrl(topic.Name)), null); return(_context.Topic.Add(topic)); }
/// <summary> /// Add a new category /// </summary> /// <param name="category"></param> public Category Add(Category category) { // Sanitize category = SanitizeCategory(category); // Set the create date category.DateCreated = DateTime.UtcNow; // url slug generator category.Slug = ServiceHelpers.GenerateSlug(category.Name, GetBySlugLike(ServiceHelpers.CreateUrl(category.Name)), null); // Add the category return _context.Category.Add(category); }
/// <summary> /// Add new tags to a topic, ignore existing ones /// </summary> /// <param name="tags"></param> /// <param name="topic"></param> public void Add(string tags, Topic topic) { if (!string.IsNullOrWhiteSpace(tags)) { tags = StringUtils.SafePlainText(tags); var newTagNames = tags.ToLower().TrimStart().TrimEnd() .Replace(" ", "-").Split(',') .Select(tag => tag) .Where(x => !string.IsNullOrWhiteSpace(x)) .Distinct(); if (topic.Tags == null) { topic.Tags = new List <TopicTag>(); } var entityTags = new List <TopicTag>(); foreach (var newTag in newTagNames) { var tag = GetTagName(newTag); if (tag != null) { // Exists entityTags.Add(tag); } else { // Doesn't exists var nTag = new TopicTag { Tag = newTag, Slug = ServiceHelpers.CreateUrl(newTag) }; Add(nTag); entityTags.Add(nTag); } } topic.Tags = entityTags; // Fire the tag badge check _badgeService.ProcessBadge(BadgeType.Tag, topic.User); } }
/// <summary> /// Add new tags to a topic, ignore existing ones /// </summary> /// <param name="tags"></param> /// <param name="topic"></param> public void Add(string tags, Topic topic) { if (!string.IsNullOrWhiteSpace(tags)) { tags = StringUtils.SafePlainText(tags); var splitTags = tags.Replace(" ", "").Split(','); if (topic.Tags == null) { topic.Tags = new List <TopicTag>(); } var newTagNames = splitTags.Select(tag => tag); var newTags = new List <TopicTag>(); var existingTags = new List <TopicTag>(); foreach (var newTag in newTagNames.Distinct()) { var tag = GetTagName(newTag); if (tag != null) { // Exists existingTags.Add(tag); } else { // Doesn't exists var nTag = new TopicTag { Tag = newTag, Slug = ServiceHelpers.CreateUrl(newTag) }; Add(nTag); newTags.Add(nTag); } } newTags.AddRange(existingTags); topic.Tags = newTags; // Fire the tag badge check _badgeService.ProcessBadge(BadgeType.Tag, topic.User); } }
/// <inheritdoc /> public async Task <IPipelineProcess <Topic> > Edit(Topic topic, HttpPostedFileBase[] files, string tags, bool subscribe, string postContent, string topicName, List <PollAnswer> pollAnswers, int closePollAfterDays) { // url slug generator topic.Slug = ServiceHelpers.GenerateSlug(topic.Name, GetTopicBySlugLike(ServiceHelpers.CreateUrl(topic.Name)) .Select(x => x.Slug).ToList(), null); // Get the pipelines var topicPipes = ForumConfiguration.Instance.PipelinesTopicUpdate; // The model to process var piplineModel = new PipelineProcess <Topic>(topic); // Add the extended data we need piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Subscribe, subscribe); piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.PostedFiles, files); piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Tags, tags); piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.IsEdit, true); piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Content, postContent); piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.PollNewAnswers, pollAnswers); piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.PollCloseAfterDays, closePollAfterDays); piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Name, topicName); piplineModel.ExtendedData.Add(Constants.ExtendedDataKeys.Username, HttpContext.Current.User.Identity.Name); // Get instance of the pipeline to use var pipeline = new Pipeline <IPipelineProcess <Topic>, Topic>(_context); // Register the pipes var allTopicPipes = ImplementationManager.GetInstances <IPipe <IPipelineProcess <Topic> > >(); // Loop through the pipes and add the ones we want foreach (var pipe in topicPipes) { if (allTopicPipes.ContainsKey(pipe)) { pipeline.Register(allTopicPipes[pipe]); } } // Process the pipeline return(await pipeline.Process(piplineModel)); }
/// <summary> /// Extract users from CSV format and import them /// </summary> /// <returns></returns> public CsvReport FromCsv(List <string> allLines) { var usersProcessed = new List <string>(); var commaSeparator = new[] { ',' }; var report = new CsvReport(); if (allLines == null || allLines.Count == 0) { report.Errors.Add(new CsvErrorWarning { ErrorWarningType = CsvErrorWarningType.BadDataFormat, Message = "No users found." }); return(report); } var settings = _settingsService.GetSettings(true); var lineCounter = 0; foreach (var line in allLines) { try { lineCounter++; // Each line is made up of n items in a predefined order var values = line.Split(commaSeparator); if (values.Length < 2) { report.Errors.Add(new CsvErrorWarning { ErrorWarningType = CsvErrorWarningType.MissingKeyOrValue, Message = $"Line {lineCounter}: insufficient values supplied." }); continue; } var userName = values[0]; if (userName.IsNullEmpty()) { report.Errors.Add(new CsvErrorWarning { ErrorWarningType = CsvErrorWarningType.MissingKeyOrValue, Message = $"Line {lineCounter}: no username supplied." }); continue; } var email = values[1]; if (email.IsNullEmpty()) { report.Errors.Add(new CsvErrorWarning { ErrorWarningType = CsvErrorWarningType.MissingKeyOrValue, Message = $"Line {lineCounter}: no email supplied." }); continue; } // get the user var userToImport = GetUser(userName); if (userToImport != null) { report.Errors.Add(new CsvErrorWarning { ErrorWarningType = CsvErrorWarningType.AlreadyExists, Message = $"Line {lineCounter}: user already exists in forum." }); continue; } if (usersProcessed.Contains(userName)) { report.Errors.Add(new CsvErrorWarning { ErrorWarningType = CsvErrorWarningType.AlreadyExists, Message = $"Line {lineCounter}: user already exists in import file." }); continue; } usersProcessed.Add(userName); userToImport = CreateEmptyUser(); userToImport.UserName = userName; userToImport.Slug = ServiceHelpers.GenerateSlug(userToImport.UserName, GetUserBySlugLike(ServiceHelpers.CreateUrl(userToImport.UserName)), userToImport.Slug); userToImport.Email = email; userToImport.IsApproved = true; userToImport.PasswordSalt = StringUtils.CreateSalt(AppConstants.SaltSize); string createDateStr = null; if (values.Length >= 3) { createDateStr = values[2]; } userToImport.CreateDate = createDateStr.IsNullEmpty() ? DateTime.UtcNow : DateTime.Parse(createDateStr); if (values.Length >= 4) { userToImport.Age = int.Parse(values[3]); } if (values.Length >= 5) { userToImport.Location = values[4]; } if (values.Length >= 6) { userToImport.Website = values[5]; } if (values.Length >= 7) { userToImport.Facebook = values[6]; } if (values.Length >= 8) { userToImport.Signature = values[7]; } userToImport.Roles = new List <MembershipRole> { settings.NewMemberStartingRole }; Add(userToImport); } catch (Exception ex) { report.Errors.Add(new CsvErrorWarning { ErrorWarningType = CsvErrorWarningType.GeneralError, Message = ex.Message }); } } return(report); }
/// <summary> /// Create new user /// </summary> /// <param name="newUser"></param> /// <returns></returns> public MembershipCreateStatus CreateUser(MembershipUser newUser) { newUser = SanitizeUser(newUser); var settings = _settingsService.GetSettings(false); var status = MembershipCreateStatus.Success; var e = new RegisterUserEventArgs { User = newUser }; EventManager.Instance.FireBeforeRegisterUser(this, e); if (e.Cancel) { status = e.CreateStatus; } else { if (string.IsNullOrWhiteSpace(newUser.UserName)) { status = MembershipCreateStatus.InvalidUserName; } // get by username if (GetUser(newUser.UserName, true) != null) { status = MembershipCreateStatus.DuplicateUserName; } // Add get by email address if (GetUserByEmail(newUser.Email, true) != null) { status = MembershipCreateStatus.DuplicateEmail; } if (string.IsNullOrWhiteSpace(newUser.Password)) { status = MembershipCreateStatus.InvalidPassword; } if (status == MembershipCreateStatus.Success) { // Hash the password var salt = StringUtils.CreateSalt(AppConstants.SaltSize); var hash = StringUtils.GenerateSaltedHash(newUser.Password, salt); newUser.Password = hash; newUser.PasswordSalt = salt; newUser.Roles = new List <MembershipRole> { settings.NewMemberStartingRole }; // Set dates newUser.CreateDate = newUser.LastPasswordChangedDate = DateTime.UtcNow; newUser.LastLockoutDate = (DateTime)SqlDateTime.MinValue; newUser.LastLoginDate = DateTime.UtcNow; newUser.IsLockedOut = false; var manuallyAuthoriseMembers = settings.ManuallyAuthoriseNewMembers; var memberEmailAuthorisationNeeded = settings.NewMemberEmailConfirmation == true; if (manuallyAuthoriseMembers || memberEmailAuthorisationNeeded) { newUser.IsApproved = false; } else { newUser.IsApproved = true; } // url generator newUser.Slug = ServiceHelpers.GenerateSlug(newUser.UserName, GetUserBySlugLike(ServiceHelpers.CreateUrl(newUser.UserName)), null); try { Add(newUser); if (settings.EmailAdminOnNewMemberSignUp) { var sb = new StringBuilder(); sb.Append( $"<p>{string.Format(_localizationService.GetResourceString("Members.NewMemberRegistered"), settings.ForumName, settings.ForumUrl)}</p>"); sb.Append($"<p>{newUser.UserName} - {newUser.Email}</p>"); var email = new Email { EmailTo = settings.AdminEmailAddress, NameTo = _localizationService.GetResourceString("Members.Admin"), Subject = _localizationService.GetResourceString("Members.NewMemberSubject") }; email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString()); _emailService.SendMail(email); } _activityService.MemberJoined(newUser); EventManager.Instance.FireAfterRegisterUser(this, new RegisterUserEventArgs { User = newUser }); } catch (Exception) { status = MembershipCreateStatus.UserRejected; } } } return(status); }
/// <summary> /// Add new tags to a topic if they are allowed, ignore existing ones, remove ones that have been deleted /// </summary> /// <param name="tags"></param> /// <param name="topic"></param> /// <param name="isAllowedToAddTags"></param> public void Add(string[] tags, Topic topic, bool isAllowedToAddTags) { if (topic.Tags == null) { topic.Tags = new List <TopicTag>(); } foreach (var newTag in tags) { var tagExists = false; // Check it's not already in the list foreach (var topicTag in topic.Tags) { if (topicTag.Tag == newTag) { tagExists = true; break; } } // Continue if tag doesn't already exist on topic if (!tagExists) { var tag = GetTagName(newTag); if (tag != null) { // Exists topic.Tags.Add(tag); } else if (isAllowedToAddTags) { // Doesn't exists var nTag = new TopicTag { Tag = newTag, Slug = ServiceHelpers.CreateUrl(newTag) }; //Add(nTag); topic.Tags.Add(nTag); } } } // Find tags that don't exist now var tagsRemoved = new List <TopicTag>(); foreach (var topicTag in topic.Tags) { var hasTag = false; // Finally check for removed tags foreach (var tag in tags) { if (topicTag.Tag == tag) { hasTag = true; } } if (hasTag == false) { tagsRemoved.Add(topicTag); } } // Now remove from Topic foreach (var topicTag in tagsRemoved) { topic.Tags.Remove(topicTag); } }