public virtual PartialViewResult ListMainCategories()
        {
            // TODO - OutputCache and add clear to post/topic/category delete/create/edit

            var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);
            var loggedOnUsersRole    = loggedOnReadOnlyUser.GetRole(RoleService);
            var catViewModel         = new CategoryListSummaryViewModel
            {
                AllPermissionSets =
                    ViewModelMapping.GetPermissionsForCategories(_categoryService.GetAllMainCategoriesInSummary(),
                                                                 _roleService, loggedOnUsersRole)
            };

            return(PartialView(catViewModel));
        }
        public virtual ActionResult GetAllPostLikes(Guid id)
        {
            User.GetMembershipUser(MembershipService);
            var loggedOnUsersRole = LoggedOnReadOnlyUser.GetRole(RoleService);
            var post        = _postService.Get(id);
            var permissions = RoleService.GetPermissions(post.Topic.Group, loggedOnUsersRole);
            var votes       = _voteService.GetVotesByPosts(new List <Guid> {
                id
            });
            var viewModel = ViewModelMapping.CreatePostViewModel(post, votes[id], permissions, post.Topic,
                                                                 LoggedOnReadOnlyUser, SettingsService.GetSettings(), new List <Favourite>());
            var upVotes = viewModel.Votes.Where(x => x.Amount > 0).ToList();

            return(View(upVotes));
        }
Exemple #3
0
        public ActionResult Index(EditSettingsViewModel settingsViewModel)
        {
            if (ModelState.IsValid)
            {
                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    try
                    {
                        var existingSettings = SettingsService.GetSettings(false);
                        var updatedSettings  = ViewModelMapping.SettingsViewModelToSettings(settingsViewModel, existingSettings);

                        // Map over viewModel from
                        if (settingsViewModel.NewMemberStartingRole != null)
                        {
                            updatedSettings.NewMemberStartingRole =
                                _roleService.GetRole(settingsViewModel.NewMemberStartingRole.Value);
                        }

                        if (settingsViewModel.DefaultLanguage != null)
                        {
                            updatedSettings.DefaultLanguage =
                                LocalizationService.Get(settingsViewModel.DefaultLanguage.Value);
                        }

                        unitOfWork.Commit();
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                    }
                }

                // All good clear cache and get reliant lists
                using (UnitOfWorkManager.NewUnitOfWork())
                {
                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                    {
                        Message     = "Settings Updated",
                        MessageType = GenericMessages.success
                    };
                    settingsViewModel.Themes    = AppHelpers.GetThemeFolders();
                    settingsViewModel.Roles     = _roleService.AllRoles().ToList();
                    settingsViewModel.Languages = LocalizationService.AllLanguages.ToList();
                }
            }
            return(View(settingsViewModel));
        }
        public virtual async Task <ActionResult> TopicsByTag(string tag, int?p)
        {
            var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);
            var loggedOnUsersRole    = loggedOnReadOnlyUser.GetRole(RoleService);

            var allowedCategories = _categoryService.GetAllowedCategories(loggedOnUsersRole);
            var settings          = SettingsService.GetSettings();
            var tagModel          = _topicTagService.Get(tag);

            if (tag != null)
            {
                // Set the page index
                var pageIndex = p ?? 1;

                // Get the topics
                var topics = await _topicService.GetPagedTopicsByTag(pageIndex,
                                                                     settings.TopicsPerPage,
                                                                     int.MaxValue,
                                                                     tag, allowedCategories);

                // See if the user has subscribed to this topic or not
                var isSubscribed = User.Identity.IsAuthenticated &&
                                   _notificationService.GetTagNotificationsByUserAndTag(loggedOnReadOnlyUser, tagModel)
                                   .Any();

                // Get the Topic View Models
                var topicViewModels = ViewModelMapping.CreateTopicViewModels(topics, RoleService, loggedOnUsersRole,
                                                                             loggedOnReadOnlyUser, allowedCategories, settings, _postService, _notificationService,
                                                                             _pollService, _voteService, _favouriteService);

                // create the view model
                var viewModel = new TagTopicsViewModel();
                viewModel.Topics       = topicViewModels;
                viewModel.PageIndex    = pageIndex;
                viewModel.TotalCount   = topics.TotalCount;
                viewModel.TotalPages   = topics.TotalPages;
                viewModel.Tag          = tag;
                viewModel.IsSubscribed = isSubscribed;
                viewModel.TagId        = tagModel.Id;


                return(View(viewModel));
            }

            return(ErrorToHomePage("No Such Tag"));
        }
Exemple #5
0
        public PartialViewResult GetSubscribedTopics()
        {
            var viewModel = new List <TopicViewModel>();

            using (UnitOfWorkManager.NewUnitOfWork())
            {
                var topicIds = LoggedOnUser.TopicNotifications.Select(x => x.Topic.Id).ToList();
                if (topicIds.Any())
                {
                    var topics = _topicService.Get(topicIds);

                    // Get the Topic View Models
                    viewModel = ViewModelMapping.CreateTopicViewModels(topics, RoleService, UsersRole, LoggedOnUser, SettingsService.GetSettings());
                }
            }
            return(PartialView("GetSubscribedTopics", viewModel));
        }
Exemple #6
0
        public ActionResult Index(EditSettingsViewModel settingsViewModel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var existingSettings = SettingsService.GetSettings(false);
                    var updatedSettings  =
                        ViewModelMapping.SettingsViewModelToSettings(settingsViewModel, existingSettings);

                    // Map over viewModel from
                    if (settingsViewModel.NewMemberStartingRole != null)
                    {
                        updatedSettings.NewMemberStartingRole =
                            _roleService.GetRole(settingsViewModel.NewMemberStartingRole.Value);
                    }

                    if (settingsViewModel.DefaultLanguage != null)
                    {
                        updatedSettings.DefaultLanguage =
                            LocalizationService.Get(settingsViewModel.DefaultLanguage.Value);
                    }

                    Context.SaveChanges();
                    _cacheService.ClearStartsWith(CacheKeys.Settings.Main);
                }
                catch (Exception ex)
                {
                    Context.RollBack();
                    LoggingService.Error(ex);
                }


                // All good clear cache and get reliant lists

                TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                {
                    Message     = "Settings Updated",
                    MessageType = GenericMessages.success
                };
                settingsViewModel.Themes    = AppHelpers.GetThemeFolders();
                settingsViewModel.Roles     = _roleService.AllRoles().ToList();
                settingsViewModel.Languages = LocalizationService.AllLanguages.ToList();
            }
            return(View(settingsViewModel));
        }
Exemple #7
0
        public virtual async Task <ActionResult> MovePost(MovePostViewModel viewModel)
        {
            // Firstly check if this is a post and they are allowed to move it
            var post = _postService.Get(viewModel.PostId);

            if (post == null)
            {
                return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
            }

            var moveResult = await _postService.Move(post, viewModel.TopicId, viewModel.TopicTitle,
                                                     viewModel.MoveReplyToPosts);

            if (moveResult.Successful)
            {
                // On Update redirect to the topic
                return(RedirectToAction("Show", "Topic", new { slug = moveResult.EntityToProcess.Topic.Slug }));
            }

            // Add a model error to show issue
            ModelState.AddModelError("", moveResult.ProcessLog.FirstOrDefault());

            // Sort the view model before sending back
            var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);
            var loggedOnUsersRole    = loggedOnReadOnlyUser.GetRole(RoleService);
            var permissions          = RoleService.GetPermissions(post.Topic.Category, loggedOnUsersRole);
            var allowedCategories    = _categoryService.GetAllowedCategories(loggedOnUsersRole);

            // Repopulate the topics
            var topics = _topicService.GetAllSelectList(allowedCategories, 30);

            topics.Insert(0, new SelectListItem
            {
                Text  = LocalizationService.GetResourceString("Topic.Choose"),
                Value = ""
            });

            viewModel.LatestTopics = topics;
            viewModel.Post         = ViewModelMapping.CreatePostViewModel(post, post.Votes.ToList(), permissions,
                                                                          post.Topic, loggedOnReadOnlyUser, SettingsService.GetSettings(), post.Favourites.ToList());
            viewModel.Post.MinimalPost = true;
            viewModel.PostId           = post.Id;

            return(View(viewModel));
        }
        public virtual PartialViewResult ListMainGroups()
        {
            // TODO - OutputCache and add clear to post/topic/Group delete/create/edit
            if (LoggedOnReadOnlyUser is null)
            {
                throw new ArgumentNullException(nameof(LoggedOnReadOnlyUser));
            }

            var loggedOnUsersRole = LoggedOnReadOnlyUser.GetRole(RoleService);
            var catViewModel      = new GroupListSummaryViewModel
            {
                AllPermissionSets =
                    ViewModelMapping.GetPermissionsForGroups(_groupService.GetAllMainGroupsInSummary(LoggedOnReadOnlyUser.Id),
                                                             _roleService, loggedOnUsersRole)
            };

            return(PartialView(catViewModel));
        }
        public async Task <IActionResult> Index()
        {
            var users = await unitOfWork
                        .UsersService
                        .GetAll();

            var roles = await unitOfWork
                        .RolesService
                        .GetAll();

            var groups = await unitOfWork
                         .UserGroupsService
                         .GetAll();

            ViewBag.Roles      = new SelectList(roles, "Name", "Name");
            ViewBag.UserGroups = new SelectList(groups, nameof(UserGroup.IdUserGroup), nameof(UserGroup.Name));

            return(View(ViewModelMapping.ConvertToViewModel(users, userManager)));
        }
Exemple #10
0
        public ActionResult DeleteUsersPosts(Guid id, bool profileClick = false)
        {
            var user = MembershipService.GetUser(id);

            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                if (!user.Roles.Any(x => x.RoleName.Contains(AppConstants.AdminRoleName)))
                {
                    MembershipService.ScrubUsers(user, unitOfWork);

                    try
                    {
                        unitOfWork.Commit();
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = "All posts and topics deleted",
                            MessageType = GenericMessages.success
                        };
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = "Error trying to delete posts and topics",
                            MessageType = GenericMessages.danger
                        };
                    }
                }
            }

            using (UnitOfWorkManager.NewUnitOfWork())
            {
                if (profileClick)
                {
                    return(Redirect(user.NiceUrl));
                }
                var viewModel = ViewModelMapping.UserToMemberEditViewModel(user);
                viewModel.AllRoles = _roleService.AllRoles();
                return(View("Edit", viewModel));
            }
        }
        public virtual ActionResult HotTopics(DateTime?from, DateTime?to, int?amountToShow)
        {
            if (amountToShow == null)
            {
                amountToShow = 5;
            }

            var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);
            var loggedOnUsersRole    = loggedOnReadOnlyUser.GetRole(RoleService);

            var fromString = from != null?Convert.ToDateTime(from).ToShortDateString() : null;

            var toString = to != null?Convert.ToDateTime(to).ToShortDateString() : null;

            var cacheKey  = string.Concat("HotTopics", loggedOnUsersRole.Id, fromString, toString, amountToShow);
            var viewModel = CacheService.Get <HotTopicsViewModel>(cacheKey);

            if (viewModel == null)
            {
                // Allowed Categories
                var allowedCategories = _categoryService.GetAllowedCategories(loggedOnUsersRole);

                // Get the topics
                var topics = _topicService.GetPopularTopics(from, to, allowedCategories, (int)amountToShow);

                topics = topics.Where(x => x.Pending != null && !x.Pending.GetValueOrDefault()).ToList();
                // Get the Topic View Models
                var topicViewModels = ViewModelMapping.CreateTopicViewModels(topics.ToList(), RoleService,
                                                                             loggedOnUsersRole, loggedOnReadOnlyUser, allowedCategories, SettingsService.GetSettings(),
                                                                             _postService, _notificationService, _pollService, _voteService, _favouriteService);

                // create the view model
                viewModel = new HotTopicsViewModel
                {
                    Topics = topicViewModels
                };
                CacheService.Set(cacheKey, viewModel, CacheTimes.TwoHours);
            }

            return(PartialView(viewModel));
        }
Exemple #12
0
        public virtual async Task <ActionResult> CreatePost(CreateAjaxPostViewModel post)
        {
            // See if the user has actually added some content to the topic
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("PostContent",
                                         LocalizationService.GetResourceString("Post.Errors.NoInputPostContent"));
                return(View());
            }

            var topic             = _topicService.Get(post.Topic);
            var loggedOnUser      = User.GetMembershipUser(MembershipService, false);
            var loggedOnUsersRole = loggedOnUser.GetRole(RoleService);
            var permissions       = RoleService.GetPermissions(topic.Category, loggedOnUsersRole);

            var postPipelineResult = await _postService.Create(post.PostContent, topic, loggedOnUser, null, false, post.InReplyTo);

            if (!postPipelineResult.Successful)
            {
                // TODO - This is shit. We need to return an object to process
                throw new Exception(postPipelineResult.ProcessLog.FirstOrDefault());
            }

            // Count up total posts User
            var user = _membershipService.UpdateTotalPosts(postPipelineResult.EntityToProcess.User.Id, true);

            Context.SaveChanges();

            //Check for moderation
            if (postPipelineResult.EntityToProcess.Pending == true)
            {
                return(PartialView("_PostModeration"));
            }

            // Create the view model
            var viewModel = ViewModelMapping.CreatePostViewModel(postPipelineResult.EntityToProcess, new List <Vote>(), permissions, topic,
                                                                 loggedOnUser, SettingsService.GetSettings(), new List <Favourite>());

            // Return view
            return(PartialView("_Post", viewModel));
        }
        public ActionResult Index()
        {
            // Get the favourites
            var favourites = _favouriteService.GetAllByMember(LoggedOnUser.Id);

            // Pull out the posts
            var posts = favourites.Select(x => x.Post);

            // Create the view Model
            var viewModel = new MyFavouritesViewModel();

            // Map the view models
            // TODO - Need to improve performance of this
            foreach (var post in posts)
            {
                var permissions = RoleService.GetPermissions(post.Topic.Category, UsersRole);
                viewModel.Posts.Add(ViewModelMapping.CreatePostViewModel(post, post.Votes.ToList(), permissions, post.Topic, LoggedOnUser, SettingsService.GetSettings(), post.Favourites.ToList()));
            }

            return(View(viewModel));
        }
Exemple #14
0
        public IHttpActionResult GetTopicsPostedIn(string id)
        {
            try
            {
                var user = _membershipService.GetUserByUniversalId(id);
                if (user == null)
                {
                    return(NotFound());
                }
                int pageIndex = 1;

                // Get the topics
                var topics = _topicService.GetMembersActivity(pageIndex,
                                                              SettingsService.GetSettings().TopicsPerPage,
                                                              SiteConstants.MembersActivityListSize,
                                                              user.Id);

                // Get the Topic View Models
                var topicViewModels = ViewModelMapping.CreateTopicViewModels(topics,
                                                                             RoleService, user.Roles.FirstOrDefault(), user, SettingsService.GetSettings());

                // create the view model
                var viewModel = new PostedInViewModel
                {
                    Topics     = topicViewModels,
                    PageIndex  = pageIndex,
                    TotalCount = topics.TotalCount,
                    TotalPages = topics.TotalPages
                };

                return(Ok(viewModel));
            }
            catch (Exception ex)
            {
                LoggingService.Error(ex);
                ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
            }

            return(BadRequest(ModelState));
        }
        public virtual PartialViewResult AjaxMorePosts(GetMorePostsViewModel getMorePostsViewModel)
        {
            var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);
            var loggedOnUsersRole    = loggedOnReadOnlyUser.GetRole(RoleService);

            // Get the topic
            var topic    = _topicService.Get(getMorePostsViewModel.TopicId);
            var settings = SettingsService.GetSettings();

            // Get the permissions for the category that this topic is in
            var permissions = RoleService.GetPermissions(topic.Category, loggedOnUsersRole);

            // If this user doesn't have access to this topic then just return nothing
            if (permissions[ForumConfiguration.Instance.PermissionDenyAccess].IsTicked)
            {
                return(null);
            }

            var orderBy = !string.IsNullOrWhiteSpace(getMorePostsViewModel.Order)
                ? EnumUtils.ReturnEnumValueFromString <PostOrderBy>(getMorePostsViewModel.Order)
                : PostOrderBy.Standard;

            var posts = Task.Run(() => _postService.GetPagedPostsByTopic(getMorePostsViewModel.PageIndex,
                                                                         settings.PostsPerPage, int.MaxValue, topic.Id, orderBy)).Result;
            var postIds   = posts.Select(x => x.Id).ToList();
            var votes     = _voteService.GetVotesByPosts(postIds);
            var favs      = _favouriteService.GetAllPostFavourites(postIds);
            var viewModel = new ShowMorePostsViewModel
            {
                Posts = ViewModelMapping.CreatePostViewModels(posts, votes, permissions, topic,
                                                              loggedOnReadOnlyUser, settings, favs),
                Topic       = topic,
                Permissions = permissions
            };

            return(PartialView(viewModel));
        }
Exemple #16
0
        public ActionResult HotTopics(DateTime?from, DateTime?to, int?amountToShow)
        {
            using (UnitOfWorkManager.NewUnitOfWork())
            {
                if (amountToShow == null)
                {
                    amountToShow = 5;
                }

                // Get the topics
                var topics = _topicService.GetPopularTopics(from, to, (int)amountToShow);

                // Get the Topic View Models
                var topicViewModels = ViewModelMapping.CreateTopicViewModels(topics.ToList(), RoleService, UsersRole, LoggedOnUser, SettingsService.GetSettings());

                // create the view model
                var viewModel = new HotTopicsViewModel
                {
                    Topics = topicViewModels
                };

                return(PartialView(viewModel));
            }
        }
        public virtual PartialViewResult GetMemberDiscussions(Guid id)
        {
            if (Request.IsAjaxRequest())
            {
                var loggedOnUser = User.Identity.IsAuthenticated
                    ? MembershipService.GetUser(User.Identity.Name, true)
                    : null;
                var usersRole = loggedOnUser == null
                    ? RoleService.GetRole(Constants.GuestRoleName, true)
                    : loggedOnUser.Roles.FirstOrDefault();

                var allowedGroups = _groupService.GetAllowedGroups(usersRole, loggedOnUser.Id).ToList();

                // Get the user discussions, only grab 100 posts
                var posts = _postService.GetByMember(id, 100, allowedGroups);

                // Get the distinct topics
                var topics = posts.Select(x => x.Topic).Distinct().Take(6)
                             .OrderByDescending(x => x.LastPost.DateCreated).ToList();

                // Get the Topic View Models
                var topicViewModels = ViewModelMapping.CreateTopicViewModels(topics, RoleService, usersRole,
                                                                             loggedOnUser, allowedGroups, SettingsService.GetSettings(), _postService,
                                                                             _notificationService, _pollService, _voteService, _favouriteService);

                // create the view model
                var viewModel = new ViewMemberDiscussionsViewModel
                {
                    Topics = topicViewModels
                };


                return(PartialView(viewModel));
            }
            return(null);
        }
        public virtual PartialViewResult LoadMoreTopics(Guid groupId, int?p)
        {
            var group             = _groupService.Get(groupId);
            var loggedOnUsersRole = GetGroupMembershipRole(groupId);

            // Allowed Groups for this user
            var allowedGroups = _groupService.GetAllowedGroups(loggedOnUsersRole, LoggedOnReadOnlyUser?.Id);

            // Set the page index
            var pageIndex = p ?? 1;

            // check the user has permission to this Group
            var permissions     = RoleService.GetPermissions(group, loggedOnUsersRole);
            var topicViewModels = new List <TopicViewModel>();

            if (!permissions[ForumConfiguration.Instance.PermissionDenyAccess].IsTicked)
            {
                if (loggedOnUsersRole.RoleName != MvcForum.Core.Constants.Constants.GuestRoleName || group.PublicGroup)
                {
                    var topics = _topicService.GetPagedTopicsByGroup(pageIndex,
                                                                     SettingsService.GetSettings().DiscussionsPerPage,
                                                                     int.MaxValue, @group.Id);

                    if (!allowedGroups.Contains(group))
                    {
                        allowedGroups.Add(group);
                    }

                    topicViewModels = ViewModelMapping.CreateTopicViewModels(topics.ToList(), RoleService,
                                                                             loggedOnUsersRole, LoggedOnReadOnlyUser, allowedGroups, SettingsService.GetSettings(),
                                                                             _postService, _notificationService, _pollAnswerService, _voteService, _favouriteService);
                }
            }

            return(PartialView("_Topics", topicViewModels));
        }
Exemple #19
0
        public ActionResult MovePost(MovePostViewModel viewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Firstly check if this is a post and they are allowed to move it
                var post = _postService.Get(viewModel.PostId);
                if (post == null)
                {
                    return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
                }

                var permissions       = RoleService.GetPermissions(post.Topic.Category, UsersRole);
                var allowedCategories = _categoryService.GetAllowedCategories(UsersRole);

                // Does the user have permission to this posts category
                var cat = allowedCategories.FirstOrDefault(x => x.Id == post.Topic.Category.Id);
                if (cat == null)
                {
                    return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
                }

                // Does this user have permission to move
                if (!permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked)
                {
                    return(NoPermission(post.Topic));
                }

                var previousTopic = post.Topic;
                var category      = post.Topic.Category;
                var postCreator   = post.User;

                Topic topic;
                var   cancelledByEvent = false;
                // If the dropdown has a value, then we choose that first
                if (viewModel.TopicId != null)
                {
                    // Get the selected topic
                    topic = _topicService.Get((Guid)viewModel.TopicId);
                }
                else if (!string.IsNullOrEmpty(viewModel.TopicTitle))
                {
                    // 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
                    topic = new Topic
                    {
                        Name     = _bannedWordService.SanitiseBannedWords(viewModel.TopicTitle, bannedWords),
                        Category = category,
                        User     = postCreator
                    };

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

                    // Save the changes
                    unitOfWork.SaveChanges();

                    // Set the post to be a topic starter
                    post.IsTopicStarter = true;

                    // Check the Events
                    var e = new TopicMadeEventArgs {
                        Topic = topic
                    };
                    EventManager.Instance.FireBeforeTopicMade(this, e);
                    if (e.Cancel)
                    {
                        cancelledByEvent = true;
                        ShowMessage(new GenericMessageViewModel
                        {
                            MessageType = GenericMessages.warning, Message = LocalizationService.GetResourceString("Errors.GenericMessage")
                        });
                    }
                }
                else
                {
                    // No selected topic OR topic title, just redirect back to the topic
                    return(Redirect(post.Topic.NiceUrl));
                }

                // If this create was cancelled by an event then don't continue
                if (!cancelledByEvent)
                {
                    // Now update the post to the new topic
                    post.Topic = topic;

                    // Also move any posts, which were in reply to this post
                    if (viewModel.MoveReplyToPosts)
                    {
                        var relatedPosts = _postService.GetReplyToPosts(viewModel.PostId);
                        foreach (var relatedPost in relatedPosts)
                        {
                            relatedPost.Topic = topic;
                        }
                    }

                    unitOfWork.SaveChanges();

                    // Update Last post..  As we have done a save, we should get all posts including the added ones
                    var lastPost = topic.Posts.OrderByDescending(x => x.DateCreated).FirstOrDefault();
                    topic.LastPost = lastPost;

                    // If any of the posts we are moving, were the last post - We need to update the old Topic
                    var previousTopicLastPost = previousTopic.Posts.OrderByDescending(x => x.DateCreated).FirstOrDefault();
                    previousTopic.LastPost = previousTopicLastPost;

                    try
                    {
                        unitOfWork.Commit();

                        EventManager.Instance.FireAfterTopicMade(this, new TopicMadeEventArgs {
                            Topic = topic
                        });

                        // On Update redirect to the topic
                        return(RedirectToAction("Show", "Topic", new { slug = topic.Slug }));
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        ShowMessage(new GenericMessageViewModel
                        {
                            Message     = ex.Message,
                            MessageType = GenericMessages.danger
                        });
                    }
                }

                // Repopulate the topics
                var topics = _topicService.GetAllSelectList(allowedCategories, 30);
                topics.Insert(0, new SelectListItem
                {
                    Text  = LocalizationService.GetResourceString("Topic.Choose"),
                    Value = ""
                });

                viewModel.LatestTopics     = topics;
                viewModel.Post             = ViewModelMapping.CreatePostViewModel(post, post.Votes.ToList(), permissions, post.Topic, LoggedOnReadOnlyUser, SettingsService.GetSettings(), post.Favourites.ToList());
                viewModel.Post.MinimalPost = true;
                viewModel.PostId           = post.Id;

                return(View(viewModel));
            }
        }
        public virtual PartialViewResult ListSections()
        {
            // TODO - How can we cache this effectively??
            // Get all sections, and include all Categories

            var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);
            var loggedOnUsersRole    = loggedOnReadOnlyUser.GetRole(RoleService);

            // Model for the sections
            var allSections = new List <SectionListViewModel>();

            // Get sections from the DB
            var dbSections = _categoryService.GetAllSections();

            // Get all categories grouped by section
            var groupedCategories = _categoryService.GetAllMainCategoriesInSummaryGroupedBySection();

            // Loop sections
            foreach (var dbSection in dbSections)
            {
                var categoriesInSection = groupedCategories[dbSection.Id];
                //var allPermissionSets = ViewModelMapping.GetPermissionsForCategories(categoriesInSection, _roleService, loggedOnUsersRole, true);

                // Permissions
                // loop through the categories and get the permissions
                var allPermissionSets = new Dictionary <CategorySummary, PermissionSet>();
                foreach (var summary in categoriesInSection)
                {
                    var permissionSet = _roleService.GetPermissions(summary.Category, loggedOnUsersRole);

                    // Should we add if deny access is ticked
                    if (permissionSet[ForumConfiguration.Instance.PermissionDenyAccess].IsTicked)
                    {
                        continue;
                    }

                    var subCategories = _categoryService.GetAllDeepSubCategories(summary.Category).SelectMany(x => x.Topics);
                    if (subCategories.Any())
                    {
                        summary.TopicCount += subCategories.Count();
                        summary.PostCount  += subCategories.SelectMany(x => x.Posts).Count();
                        if (summary.MostRecentTopic != null)
                        {
                            summary.MostRecentTopic = summary.MostRecentTopic.LastPost.DateCreated >
                                                      subCategories.OrderByDescending(t => t.LastPost.DateCreated).FirstOrDefault().LastPost.DateCreated ?
                                                      summary.MostRecentTopic : subCategories.OrderByDescending(t => t.LastPost.DateCreated).FirstOrDefault(); // TODO - Should this be a seperate call?
                        }
                        else
                        {
                            summary.MostRecentTopic = subCategories.OrderByDescending(t => t.LastPost.DateCreated).FirstOrDefault();
                        }
                    }

                    allPermissionSets.Add(summary, permissionSet);

                    summary.SubCategoriesAllPermissionSets = ViewModelMapping.GetPermissionsForCategories(_categoryService.GetAllSubCategories(summary.Category.Id), _roleService, loggedOnUsersRole);
                }

                allSections.Add(new SectionListViewModel
                {
                    Section           = dbSection,
                    AllPermissionSets = allPermissionSets
                });
            }
            return(PartialView(allSections));
        }
Exemple #21
0
        public ActionResult CreatePost(CreateAjaxPostViewModel post)
        {
            PermissionSet permissions;
            Post          newPost;
            Topic         topic;

            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Quick check to see if user is locked out, when logged in
                if (LoggedOnUser.IsLockedOut | !LoggedOnUser.IsApproved)
                {
                    FormsAuthentication.SignOut();
                    throw new Exception(LocalizationService.GetResourceString("Errors.NoAccess"));
                }

                topic = _topicService.Get(post.Topic);

                var postContent = _bannedWordService.SanitiseBannedWords(post.PostContent);

                var akismetHelper = new AkismetHelper(SettingsService);

                newPost = _postService.AddNewPost(postContent, topic, LoggedOnUser, out permissions);

                if (!akismetHelper.IsSpam(newPost))
                {
                    try
                    {
                        unitOfWork.Commit();
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
                    }
                }
                else
                {
                    unitOfWork.Rollback();
                    throw new Exception(LocalizationService.GetResourceString("Errors.PossibleSpam"));
                }
            }

            //Check for moderation
            if (newPost.Pending == true)
            {
                return(PartialView("_PostModeration"));
            }

            // All good send the notifications and send the post back
            using (UnitOfWorkManager.NewUnitOfWork())
            {
                // Create the view model
                var viewModel = ViewModelMapping.CreatePostViewModel(newPost, new List <Vote>(), permissions, topic, LoggedOnUser, SettingsService.GetSettings(), new List <Favourite>());

                // Success send any notifications
                NotifyNewTopics(topic);

                // Return view
                return(PartialView("_Post", viewModel));
            }
        }
        public virtual async Task <ActionResult> Show(string slug, int?p)
        {
            // Set the page index
            var pageIndex = p ?? 1;

            var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);
            var loggedOnUsersRole    = loggedOnReadOnlyUser.GetRole(RoleService);

            // Get the topic
            var topic = _topicService.GetTopicBySlug(slug);

            if (topic != null)
            {
                var settings = SettingsService.GetSettings();

                // Note: Don't use topic.Posts as its not a very efficient SQL statement
                // Use the post service to get them as it includes other used entities in one
                // statement rather than loads of sql selects

                var sortQuerystring = Request.QueryString[Constants.PostOrderBy];
                var orderBy         = !string.IsNullOrWhiteSpace(sortQuerystring)
                    ? EnumUtils.ReturnEnumValueFromString <PostOrderBy>(sortQuerystring)
                    : PostOrderBy.Standard;

                // Store the amount per page
                var amountPerPage = settings.PostsPerPage;

                if (sortQuerystring == Constants.AllPosts)
                {
                    // Overide to show all posts
                    amountPerPage = int.MaxValue;
                }

                // Get the posts
                var posts = await _postService.GetPagedPostsByTopic(pageIndex,
                                                                    amountPerPage,
                                                                    int.MaxValue,
                                                                    topic.Id,
                                                                    orderBy);

                // Get the topic starter post
                var starterPost = _postService.GetTopicStarterPost(topic.Id);

                // Get the permissions for the category that this topic is in
                var permissions = RoleService.GetPermissions(topic.Category, loggedOnUsersRole);

                // If this user doesn't have access to this topic then
                // redirect with message
                if (permissions[ForumConfiguration.Instance.PermissionDenyAccess].IsTicked)
                {
                    return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
                }

                // Set editor permissions
                ViewBag.ImageUploadType = permissions[ForumConfiguration.Instance.PermissionInsertEditorImages].IsTicked
                    ? "forumimageinsert"
                    : "image";

                var postIds = posts.Select(x => x.Id).ToList();

                var votes = _voteService.GetVotesByPosts(postIds);

                var favourites = _favouriteService.GetAllPostFavourites(postIds);

                var viewModel = ViewModelMapping.CreateTopicViewModel(topic, permissions, posts, postIds,
                                                                      starterPost, posts.PageIndex, posts.TotalCount, posts.TotalPages, loggedOnReadOnlyUser,
                                                                      settings, _notificationService, _pollService, votes, favourites, true);

                // If there is a quote querystring
                var quote = Request["quote"];
                if (!string.IsNullOrWhiteSpace(quote))
                {
                    try
                    {
                        // Got a quote
                        var postToQuote = _postService.Get(new Guid(quote));
                        viewModel.QuotedPost      = postToQuote.PostContent;
                        viewModel.ReplyTo         = postToQuote.Id;
                        viewModel.ReplyToUsername = postToQuote.User.UserName;
                    }
                    catch (Exception ex)
                    {
                        LoggingService.Error(ex);
                    }
                }

                var reply = Request["reply"];
                if (!string.IsNullOrWhiteSpace(reply))
                {
                    try
                    {
                        // Set the reply
                        var toReply = _postService.Get(new Guid(reply));
                        viewModel.ReplyTo         = toReply.Id;
                        viewModel.ReplyToUsername = toReply.User.UserName;
                    }
                    catch (Exception ex)
                    {
                        LoggingService.Error(ex);
                    }
                }

                var updateDatabase = false;

                // User has permission lets update the topic view count
                // but only if this topic doesn't belong to the user looking at it
                var addView = !(User.Identity.IsAuthenticated && loggedOnReadOnlyUser.Id == topic.User.Id);
                if (addView)
                {
                    updateDatabase = true;
                }

                // Check the poll - To see if it has one, and whether it needs to be closed.
                if (viewModel.Poll?.Poll?.ClosePollAfterDays != null &&
                    viewModel.Poll.Poll.ClosePollAfterDays > 0 &&
                    !viewModel.Poll.Poll.IsClosed)
                {
                    // Check the date the topic was created
                    var endDate =
                        viewModel.Poll.Poll.DateCreated.AddDays((int)viewModel.Poll.Poll.ClosePollAfterDays);
                    if (DateTime.Now > endDate)
                    {
                        topic.Poll.IsClosed           = true;
                        viewModel.Topic.Poll.IsClosed = true;
                        updateDatabase = true;
                    }
                }

                if (!BotUtils.UserIsBot() && updateDatabase)
                {
                    if (addView)
                    {
                        // Increase the topic views
                        topic.Views = topic.Views + 1;
                    }

                    try
                    {
                        Context.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        LoggingService.Error(ex);
                    }
                }

                return(View(viewModel));
            }

            return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
        }
Exemple #23
0
        public ActionResult CreatePost(CreateAjaxPostViewModel post)
        {
            PermissionSet permissions;
            Post          newPost;
            Topic         topic;

            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var loggedOnUser = MembershipService.GetUser(LoggedOnReadOnlyUser.Id);

                // Check stop words
                var stopWords = _bannedWordService.GetAll(true);
                foreach (var stopWord in stopWords)
                {
                    if (post.PostContent.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0)
                    {
                        throw new Exception(LocalizationService.GetResourceString("StopWord.Error"));
                    }
                }

                // Quick check to see if user is locked out, when logged in
                if (loggedOnUser.IsLockedOut || !loggedOnUser.IsApproved)
                {
                    FormsAuthentication.SignOut();
                    throw new Exception(LocalizationService.GetResourceString("Errors.NoAccess"));
                }

                topic = _topicService.Get(post.Topic);

                var postContent = _bannedWordService.SanitiseBannedWords(post.PostContent);

                var akismetHelper = new AkismetHelper(SettingsService);

                newPost = _postService.AddNewPost(postContent, topic, loggedOnUser, out permissions);

                if (akismetHelper.IsSpam(newPost))
                {
                    newPost.Pending = true;
                }

                try
                {
                    unitOfWork.Commit();
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    LoggingService.Error(ex);
                    throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
                }
            }

            //Check for moderation
            if (newPost.Pending == true)
            {
                return(PartialView("_PostModeration"));
            }

            // All good send the notifications and send the post back

            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Create the view model
                var viewModel = ViewModelMapping.CreatePostViewModel(newPost, new List <Vote>(), permissions, topic, LoggedOnReadOnlyUser, SettingsService.GetSettings(), new List <Favourite>());

                // Success send any notifications
                NotifyNewTopics(topic, unitOfWork);

                // Return view
                return(PartialView("_Post", viewModel));
            }
        }
        public async Task <IActionResult> GetDocumentDataTemplateItems(int id)
        {
            var items = await unitOfWork.DocumentsStatesService.GetDocumentDataTemplateItems(id);

            return(PartialView("_DocumentUploadTemplateItems", ViewModelMapping.ConvertToViewModel(items)));
        }
        public async Task <ActionResult> Show(string slug, int?p)
        {
            var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);
            var loggedOnUsersRole    = loggedOnReadOnlyUser.GetRole(RoleService);

            // Get the category
            var category = _categoryService.GetBySlugWithSubCategories(slug);

            // Allowed Categories for this user
            var allowedCategories = _categoryService.GetAllowedCategories(loggedOnUsersRole);

            // Set the page index
            var pageIndex = p ?? 1;

            // check the user has permission to this category
            var permissions = RoleService.GetPermissions(category.Category, loggedOnUsersRole);

            if (!permissions[SiteConstants.Instance.PermissionDenyAccess].IsTicked)
            {
                var topics = await _topicService.GetPagedTopicsByCategory(pageIndex,
                                                                          SettingsService.GetSettings().TopicsPerPage,
                                                                          int.MaxValue, category.Category.Id);

                var topicViewModels = ViewModelMapping.CreateTopicViewModels(topics.ToList(), RoleService,
                                                                             loggedOnUsersRole, loggedOnReadOnlyUser, allowedCategories, SettingsService.GetSettings(),
                                                                             _postService, _topicNotificationService, _pollAnswerService, _voteService, _favouriteService);

                // Create the main view model for the category
                var viewModel = new CategoryViewModel
                {
                    Permissions  = permissions,
                    Topics       = topicViewModels,
                    Category     = category.Category,
                    PageIndex    = pageIndex,
                    TotalCount   = topics.TotalCount,
                    TotalPages   = topics.TotalPages,
                    User         = loggedOnReadOnlyUser,
                    IsSubscribed = User.Identity.IsAuthenticated && _categoryNotificationService
                                   .GetByUserAndCategory(loggedOnReadOnlyUser, category.Category).Any()
                };

                // If there are subcategories then add then with their permissions
                if (category.SubCategories.Any())
                {
                    var subCatViewModel = new CategoryListViewModel
                    {
                        AllPermissionSets = new Dictionary <Category, PermissionSet>()
                    };
                    foreach (var subCategory in category.SubCategories)
                    {
                        var permissionSet = RoleService.GetPermissions(subCategory, loggedOnUsersRole);
                        subCatViewModel.AllPermissionSets.Add(subCategory, permissionSet);
                    }
                    viewModel.SubCategories = subCatViewModel;
                }

                return(View(viewModel));
            }

            return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
        }
        public ActionResult CreatePost(CreateAjaxPostViewModel post)
        {
            PermissionSet permissions;


            var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);

            var loggedOnUser = MembershipService.GetUser(loggedOnReadOnlyUser.Id);

            // Flood control
            if (!_postService.PassedPostFloodTest(loggedOnReadOnlyUser))
            {
                throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
            }

            // Check stop words
            var stopWords = _bannedWordService.GetAll(true);

            foreach (var stopWord in stopWords)
            {
                if (post.PostContent.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0)
                {
                    throw new Exception(LocalizationService.GetResourceString("StopWord.Error"));
                }
            }

            // Quick check to see if user is locked out, when logged in
            if (loggedOnUser.IsLockedOut || !loggedOnUser.IsApproved)
            {
                FormsAuthentication.SignOut();
                throw new Exception(LocalizationService.GetResourceString("Errors.NoAccess"));
            }

            var topic = _topicService.Get(post.Topic);

            var postContent = _bannedWordService.SanitiseBannedWords(post.PostContent);

            var akismetHelper = new AkismetHelper(SettingsService);

            var newPost = _postService.AddNewPost(postContent, topic, loggedOnUser, out permissions);

            // Set the reply to
            newPost.InReplyTo = post.InReplyTo;


            if (akismetHelper.IsSpam(newPost))
            {
                newPost.Pending = true;
            }

            if (!newPost.Pending.HasValue || !newPost.Pending.Value)
            {
                _activityService.PostCreated(newPost);
            }

            try
            {
                Context.SaveChanges();
            }
            catch (Exception ex)
            {
                Context.RollBack();
                LoggingService.Error(ex);
                throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
            }

            //Check for moderation
            if (newPost.Pending == true)
            {
                return(PartialView("_PostModeration"));
            }

            // All good send the notifications and send the post back


            // Create the view model
            var viewModel = ViewModelMapping.CreatePostViewModel(newPost, new List <Vote>(), permissions, topic,
                                                                 loggedOnReadOnlyUser, SettingsService.GetSettings(), new List <Favourite>());

            // Success send any notifications
            NotifyNewTopics(topic, loggedOnReadOnlyUser);

            // Return view
            return(PartialView("_Post", viewModel));
        }
        public virtual async Task <ActionResult> Index(int?p, string term)
        {
            if (!string.IsNullOrWhiteSpace(term))
            {
                if (!string.IsNullOrWhiteSpace(term))
                {
                    term = term.Trim();
                }

                var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService);
                var loggedOnUsersRole    = loggedOnReadOnlyUser.GetRole(RoleService);

                // Get the global settings
                var settings = SettingsService.GetSettings();

                // Get allowed categories
                var allowedCategories = _categoryService.GetAllowedCategories(loggedOnUsersRole);


                // Set the page index
                var pageIndex = p ?? 1;

                // Get all the topics based on the search value
                var posts = await _postService.SearchPosts(pageIndex,
                                                           ForumConfiguration.Instance.SearchListSize,
                                                           int.MaxValue,
                                                           term,
                                                           allowedCategories);

                // Get all the permissions for these topics
                var topicPermissions =
                    ViewModelMapping.GetPermissionsForTopics(posts.Select(x => x.Topic), RoleService,
                                                             loggedOnUsersRole);

                // Get the post Ids
                var postIds = posts.Select(x => x.Id).ToList();

                // Get all votes for these posts
                var votes = _voteService.GetVotesByPosts(postIds);

                // Get all favourites for these posts
                var favs = _favouriteService.GetAllPostFavourites(postIds);

                // Create the post view models
                var viewModels = ViewModelMapping.CreatePostViewModels(posts.ToList(), votes, topicPermissions,
                                                                       loggedOnReadOnlyUser, settings, favs);

                // create the view model
                var viewModel = new SearchViewModel
                {
                    Posts      = viewModels,
                    PageIndex  = pageIndex,
                    TotalCount = posts.TotalCount,
                    TotalPages = posts.TotalPages,
                    Term       = term
                };

                return(View(viewModel));
            }

            return(RedirectToAction("Index", "Home"));
        }
Exemple #28
0
        public ActionResult Show(string slug, int?p)
        {
            // Set the page index
            var pageIndex = p ?? 1;

            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Get the topic
                var topic = _topicService.GetTopicBySlug(slug);

                if (topic != null)
                {
                    // Note: Don't use topic.Posts as its not a very efficient SQL statement
                    // Use the post service to get them as it includes other used entities in one
                    // statement rather than loads of sql selects

                    var sortQuerystring = Request.QueryString[AppConstants.PostOrderBy];
                    var orderBy         = !string.IsNullOrEmpty(sortQuerystring) ?
                                          EnumUtils.ReturnEnumValueFromString <PostOrderBy>(sortQuerystring) : PostOrderBy.Standard;

                    // Store the amount per page
                    var amountPerPage = SettingsService.GetSettings().PostsPerPage;

                    if (sortQuerystring == AppConstants.AllPosts)
                    {
                        // Overide to show all posts
                        amountPerPage = int.MaxValue;
                    }

                    // Get the posts
                    var posts = _postService.GetPagedPostsByTopic(pageIndex,
                                                                  amountPerPage,
                                                                  int.MaxValue,
                                                                  topic.Id,
                                                                  orderBy);

                    // Get the topic starter post
                    var starterPost = _postService.GetTopicStarterPost(topic.Id);

                    // Get the permissions for the category that this topic is in
                    var permissions = RoleService.GetPermissions(topic.Category, UsersRole);

                    // If this user doesn't have access to this topic then
                    // redirect with message
                    if (permissions[AppConstants.PermissionDenyAccess].IsTicked)
                    {
                        return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
                    }

                    var viewModel = ViewModelMapping.CreateTopicViewModel(topic, permissions, posts.ToList(), starterPost, posts.PageIndex, posts.TotalCount, posts.TotalPages, LoggedOnUser, SettingsService.GetSettings(), true);

                    // If there is a quote querystring
                    var quote = Request["quote"];
                    if (!string.IsNullOrEmpty(quote))
                    {
                        try
                        {
                            // Got a quote
                            var postToQuote = _postService.Get(new Guid(quote));
                            viewModel.QuotedPost = postToQuote.PostContent;
                        }
                        catch (Exception ex)
                        {
                            LoggingService.Error(ex);
                        }
                    }

                    // User has permission lets update the topic view count
                    // but only if this topic doesn't belong to the user looking at it
                    var addView = !(UserIsAuthenticated && LoggedOnUser.Id == topic.User.Id);

                    if (!BotUtils.UserIsBot() && addView)
                    {
                        // Cool, user doesn't own this topic
                        topic.Views = (topic.Views + 1);
                        try
                        {
                            unitOfWork.Commit();
                        }
                        catch (Exception ex)
                        {
                            LoggingService.Error(ex);
                        }
                    }

                    return(View(viewModel));
                }
            }
            return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
        }