Esempio n. 1
0
        /// <summary>
        ///     Writes empty pages to disk.
        /// </summary>
        public void WritePages()
        {
            PageTemplateToolboxContext templateContext = new PageTemplateToolboxContext();

            templateContext.Put("CategoryId", Id);
            templateContext.Put("CategoryName", LinkName);
            templateContext.Put("MetaDescription",
                                !string.IsNullOrEmpty(MetaDescription)
                                                                        ? MetaDescription
                                                                        : HttpUtility.HtmlEncode(Util.RemoveHtml(Body, 255) ?? string.Empty));

            templateContext.Put("MetaKeywords",
                                !string.IsNullOrEmpty(MetaKeywords)
                                                                        ? MetaKeywords
                                                                        : Name);


            if (!IsUncategorized)
            {
                PageWriter.Write("category.view", "~/" + LinkName + "/" + Util.DEFAULT_PAGE, templateContext);
                PageWriter.Write("categoryrss.view", "~/" + LinkName + "/feed/" + Util.DEFAULT_PAGE, templateContext);
            }

            if (__initialCategoryName != null && __initialCategoryName != LinkName)
            {
                PostCollection pc        = new PostCollection();
                Query          postQuery = Post.CreateQuery();
                postQuery.AndWhere(Post.Columns.CategoryId, Id);
                pc.LoadAndCloseReader(postQuery.ExecuteReader());
                foreach (Post p in pc)
                {
                    p.Save();
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Deletes a user, and reassigns any content created by that user to another existing user
        /// </summary>
        public static bool DeleteUser(IGraffitiUser user, IGraffitiUser userToAssumeContent, out string errorMessage)
        {
            if (!controller.CanDeleteUsers)
            {
                errorMessage = "The membership system in use does not support deleting users.";
                return(false);
            }
            if (user == null)
            {
                throw new Exception("The supplied user object is null and cannot be deleted");
            }

            // Check if the user has created any content
            PostCollection pc = new PostCollection();
            Query          q  = Post.CreateQuery();

            q.AndWhere(Post.Columns.UserName, user.Name);
            pc.LoadAndCloseReader(q.ExecuteReader());

            if (pc != null && pc.Count > 0)
            {
                if (userToAssumeContent == null)
                {
                    errorMessage = "The user you are trying to delete has created posts. Another existing user must be selected to assign these posts to.";
                    return(false);
                }
                foreach (Post p in pc)
                {
                    if (p.UserName == user.Name)
                    {
                        p.UserName = userToAssumeContent.Name;
                    }
                    if (p.ModifiedBy == user.Name)
                    {
                        p.ModifiedBy = userToAssumeContent.Name;
                    }
                    if (p.CreatedBy == user.Name)
                    {
                        p.CreatedBy = userToAssumeContent.Name;
                    }
                }
            }

            // Remove from roles
            if (user.Roles != null && user.Roles.Length > 0)
            {
                foreach (string roleName in user.Roles)
                {
                    controller.RemoveUserFromRole(user.Name, roleName);
                }
                ZCache.RemoveByPattern("usersByRole-");
            }

            controller.DeleteUser(user);

            ZCache.RemoveCache("user-" + user.Name.ToLower());

            errorMessage = string.Empty;
            return(true);
        }
Esempio n. 3
0
        private static List <Post> ItemsToIndex()
        {
            DataBuddy.Query q  = PostCollection.DefaultQuery();
            PostCollection  pc = new PostCollection();

            pc.LoadAndCloseReader(q.ExecuteReader());

            return(pc);
        }
Esempio n. 4
0
        public PostCollection PostsByCategory(Category category, int numberOfPosts, bool filterHome)
        {
            if (category == null)
            {
                return(null);
            }

            const string CacheKey = "Posts-Categories-P:{0}-C:{1}-T:{2}-PS:{3}";

            PostCollection pc =
                ZCache.Get <PostCollection>(string.Format(CacheKey, 1, category.Id, category.SortOrder, numberOfPosts));

            if (pc == null)
            {
                pc = new PostCollection();
                Query q = PostCollection.DefaultQuery(1, numberOfPosts, category.SortOrder);

                if (Category.IncludeChildPosts)
                {
                    if (category.ParentId > 0)
                    {
                        q.AndWhere(Post.Columns.CategoryId, category.Id);
                    }
                    else
                    {
                        var ids = new List <int>(category.Children.Count + 1);
                        foreach (Category child in category.Children)
                        {
                            ids.Add(child.Id);
                        }

                        ids.Add(category.Id);

                        q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                    }
                }
                else
                {
                    q.AndWhere(Post.Columns.CategoryId, category.Id);
                }

                if (filterHome)
                {
                    string where = GraffitiContext.Current["where"] as string;
                    if (!string.IsNullOrEmpty(where) && where == "home" && Site.UseCustomHomeList)
                    {
                        q.AndWhere(Post.Columns.IsHome, true);
                    }
                }

                pc.LoadAndCloseReader(q.ExecuteReader());
                ZCache.InsertCache(string.Format(CacheKey, 1, category.Id, category.SortOrder, numberOfPosts), pc, 60);
            }

            return(pc);
        }
Esempio n. 5
0
        public static PostCollection FetchPostsByTagAndCategory(string tagName, int categoryId)
        {
            QueryCommand command = new QueryCommand("SELECT p.* FROM graffiti_Posts AS p INNER JOIN graffiti_Tags AS t ON p.Id = t.PostId WHERE p.CategoryId = " + categoryId.ToString() + " and p.IsPublished <> 0 and p.IsDeleted = 0 and p.Published <= " + DataService.Provider.SqlVariable("Published") + " and t.Name = " + DataService.Provider.SqlVariable("Name") + " ORDER BY p.Published DESC");

            command.Parameters.Add(Post.FindParameter("Published")).Value = SiteSettings.CurrentUserTime;
            command.Parameters.Add(Tag.FindParameter("Name")).Value       = tagName;
            PostCollection pc = new PostCollection();

            pc.LoadAndCloseReader(DataService.ExecuteReader(command));
            return(pc);
        }
Esempio n. 6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        LiHyperLink.SetNameToCompare(Context, "presentation");

        NavigationSettings settings = NavigationSettings.Get();
        CategoryCollection cc = new CategoryController().GetTopLevelCachedCategories();

        foreach(Category c in cc)
        {
            bool found = false;
            foreach(DynamicNavigationItem di in settings.SafeItems())
            {
                if(di.NavigationType == DynamicNavigationType.Category && di.CategoryId == c.Id)
                {
                    found = true;
                    break;
                }
            }

            if(!found)
                the_Categories.Items.Add(new ListItem(c.Name,"Category-" + c.UniqueId));
        }

        Query q = Post.CreateQuery();
        q.AndWhere(Post.Columns.CategoryId, CategoryController.UnCategorizedId);
        q.AndWhere(Post.Columns.IsDeleted, false);
        q.AndWhere(Post.Columns.Status, 1);

        PostCollection pc = new PostCollection();
        pc.LoadAndCloseReader(q.ExecuteReader());

        foreach (Post p in pc)
        {
            bool found = false;
            foreach (DynamicNavigationItem di in settings.SafeItems())
            {
                if (di.NavigationType == DynamicNavigationType.Post && di.PostId == p.Id)
                {
                    found = true;
                    break;
                }
            }

            if (!found)
                the_Posts.Items.Add(new ListItem(p.Title, "Post-" + p.UniqueId));
        }

        // 0 - Title, 1 - Type, 2 - LID
        string itemFormat = "<div style=\"border: solid 1px #999; padding: 4px;\"><strong>{0} ({1})</strong><div style=\"text-align:right;\"><a title=\"Delete Link\" href=\"javascript:void();\" onclick=\"remove_Link( &#39;{1}&#39;,&#39;{0}&#39;, &#39;{2}&#39;); return false;\">Delete</a></div></div>";
        foreach (DynamicNavigationItem dni in settings.SafeItems())
        {
            lbar.Items.Add(new Telligent.Glow.OrderedListItem(string.Format(itemFormat, dni.Name, dni.NavigationType.ToString(), dni.Id), dni.Name, dni.NavigationType.ToString() + "-" + dni.Id.ToString()));
        }
    }
Esempio n. 7
0
        protected virtual object GetCategoryPosts(string key, GraffitiContext graffitiContext)
        {
            Category       category = new CategoryController().GetCachedCategory(CategoryID, false);
            int            pageSize = SiteSettings.Get().PageSize;
            PostCollection pc       =
                ZCache.Get <PostCollection>(string.Format(CacheKey, PageIndex, CategoryID, category.SortOrder, pageSize));

            if (pc == null)
            {
                pc = new PostCollection();
                Query q = PostCollection.DefaultQuery(PageIndex, pageSize, category.SortOrder);

                if (Category.IncludeChildPosts)
                {
                    if (category.ParentId > 0)
                    {
                        q.AndWhere(Post.Columns.CategoryId, CategoryID);
                    }
                    else
                    {
                        var ids = new List <int>(category.Children.Count + 1);
                        foreach (Category child in category.Children)
                        {
                            ids.Add(child.Id);
                        }

                        ids.Add(category.Id);

                        q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                    }
                }
                else
                {
                    q.AndWhere(Post.Columns.CategoryId, CategoryID);
                }
                pc.LoadAndCloseReader(q.ExecuteReader());
                ZCache.InsertCache(string.Format(CacheKey, PageIndex, CategoryID, category.SortOrder, pageSize), pc, 60);
            }

            graffitiContext.TotalRecords = category.PostCount;
            graffitiContext.PageIndex    = PageIndex;
            graffitiContext.PageSize     = SiteSettings.Get().PageSize;

            return(pc);
        }
Esempio n. 8
0
        /// <summary>
        ///     Gets all posts by the specified user in the specified category name
        /// </summary>
        /// <param name="user"></param>
        /// <param name="category"></param>
        /// <param name="numberOfPosts"></param>
        public PostCollection PostsByUserAndCategory(IGraffitiUser user, Category category, int numberOfPosts)
        {
            if (category == null || user == null)
            {
                return(null);
            }

            const string CacheKey = "Posts-Users-Categories-P:{0}-U:{1}-C:{2}-T:{3}-PS:{4}";

            PostCollection pc =
                ZCache.Get <PostCollection>(string.Format(CacheKey, 1, user.UniqueId, category.Id, category.SortOrder, numberOfPosts));

            if (pc == null)
            {
                pc = new PostCollection();
                Query q = PostCollection.DefaultQuery(1, numberOfPosts, category.SortOrder);
                q.AndWhere(Post.Columns.UserName, user.Name);
                if (Category.IncludeChildPosts)
                {
                    if (category.ParentId > 0)
                    {
                        q.AndWhere(Post.Columns.CategoryId, category.Id);
                    }
                    else
                    {
                        var ids = new List <int>(category.Children.Count + 1);
                        foreach (Category child in category.Children)
                        {
                            ids.Add(child.Id);
                        }
                        ids.Add(category.Id);
                        q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                    }
                }
                else
                {
                    q.AndWhere(Post.Columns.CategoryId, category.Id);
                }
                pc.LoadAndCloseReader(q.ExecuteReader());
                ZCache.InsertCache(string.Format(CacheKey, 1, user.UniqueId, category.Id, category.SortOrder, numberOfPosts), pc, 60);
            }

            return(pc);
        }
    private void BindData(PageWidget widget)
    {
        txtTitle.Text = widget.Title;

        Query q = Post.CreateQuery();
        q.AndWhere(Post.Columns.CategoryId, CategoryController.UnCategorizedId);
        q.AndWhere(Post.Columns.IsDeleted, false);
        q.AndWhere(Post.Columns.Status, 1);

        PostCollection pc = new PostCollection();
        pc.LoadAndCloseReader(q.ExecuteReader());

        PostCollection pcInUse = new PostCollection();
        PostCollection pcNotInUse = new PostCollection();

        foreach(int i in widget.PostIds)
        {
            bool found = false;
            foreach(Post p in pc)
            {
                if(i == p.Id)
                {
                    pcInUse.Add(p);
                    found = true;
                }
            }

            if(found)
            {
                pc.Remove(pcInUse[pcInUse.Count - 1]);
            }
        }

        the_Posts.DataSource = pc;
        the_Posts.DataBind();

        existing_items.Items.Clear();
        foreach (Post p in pcInUse)
        {
            existing_items.Items.Add(new Telligent.Glow.OrderedListItem(string.Format(this.ItemFormat, p.Name, p.Id), p.Name, p.Id.ToString()));
        }
    }
Esempio n. 10
0
        public MetaWeblog.Post[] getRecentPosts(string blogid, string username, string password, int numberOfPosts)
        {
            if (ValidateUser(username, password))
            {
                Query q = Graffiti.Core.Post.CreateQuery();
                q.AndWhere(Core.Post.Columns.IsDeleted, false);
                q.Top = numberOfPosts.ToString();
                q.OrderByDesc(Graffiti.Core.Post.Columns.Published);
                PostCollection pc = new PostCollection();
                pc.LoadAndCloseReader(q.ExecuteReader());

                ArrayList al = new ArrayList(pc.Count);
                foreach (Graffiti.Core.Post p in pc)
                {
                    al.Add(ConvertToPost(p));
                }

                return((Post[])al.ToArray(typeof(Post)));
            }
            throw new XmlRpcFaultException(0, "User does not exist");
        }
Esempio n. 11
0
        protected virtual object GetCategoryPosts(string key, GraffitiContext graffitiContext)
        {
            Category category = new CategoryController().GetCachedCategory(CategoryID, false);
            int pageSize = SiteSettings.Get().PageSize;
            PostCollection pc = ZCache.Get<PostCollection>(string.Format(CacheKey, PageIndex, CategoryID, category.SortOrder, pageSize));
            if (pc == null)
            {
                pc = new PostCollection();
                Query q = PostCollection.DefaultQuery(PageIndex, pageSize, category.SortOrder);

                if (Category.IncludeChildPosts)
                {
                    if (category.ParentId > 0)
                        q.AndWhere(Post.Columns.CategoryId, CategoryID);
                    else
                    {
                        List<int> ids = new List<int>(category.Children.Count + 1);
                        foreach (Category child in category.Children)
                            ids.Add(child.Id);

                        ids.Add(category.Id);

                        q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                    }
                }
                else
                {
                    q.AndWhere(Post.Columns.CategoryId, CategoryID);
                }
                pc.LoadAndCloseReader(q.ExecuteReader());
                ZCache.InsertCache(string.Format(CacheKey, PageIndex, CategoryID, category.SortOrder, pageSize), pc, 60);
            }

            graffitiContext.TotalRecords = category.PostCount;
            graffitiContext.PageIndex = PageIndex;
            graffitiContext.PageSize = SiteSettings.Get().PageSize;

            return pc;
        }
Esempio n. 12
0
        /// <summary>
        /// Gets all posts by the specified user in the specified category name
        /// </summary>
        /// <param name="user"></param>
        /// <param name="category"></param>
        /// <param name="numberOfPosts"></param>
        public PostCollection PostsByUserAndCategory(IGraffitiUser user, Category category, int numberOfPosts)
        {
            if (category == null || user == null)
                  return null;

              const string CacheKey = "Posts-Users-Categories-P:{0}-U:{1}-C:{2}-T:{3}-PS:{4}";

              PostCollection pc = ZCache.Get<PostCollection>(string.Format(CacheKey, 1, user.UniqueId, category.Id, category.SortOrder, numberOfPosts));
              if (pc == null)
              {
                  pc = new PostCollection();
                  Query q = PostCollection.DefaultQuery(1, numberOfPosts, category.SortOrder);
                  q.AndWhere(Post.Columns.UserName, user.Name);
                  if (Category.IncludeChildPosts)
                  {
                      if (category.ParentId > 0)
                          q.AndWhere(Post.Columns.CategoryId, category.Id);
                      else
                      {
                          List<int> ids = new List<int>(category.Children.Count + 1);
                          foreach (Category child in category.Children)
                              ids.Add(child.Id);
                          ids.Add(category.Id);
                          q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                      }
                  }
                  else
                  {
                      q.AndWhere(Post.Columns.CategoryId, category.Id);
                  }
                  pc.LoadAndCloseReader(q.ExecuteReader());
                  ZCache.InsertCache(string.Format(CacheKey, 1, user.UniqueId, category.Id, category.SortOrder, numberOfPosts), pc, 60);
              }

              return pc;
        }
Esempio n. 13
0
        public PostCollection PostsByCategory(Category category, int numberOfPosts, bool filterHome)
        {
            if (category == null)
                return null;

            const string CacheKey = "Posts-Categories-P:{0}-C:{1}-T:{2}-PS:{3}";

            PostCollection pc = ZCache.Get<PostCollection>(string.Format(CacheKey, 1, category.Id, category.SortOrder, numberOfPosts));
            if (pc == null)
            {
                pc = new PostCollection();
                Query q = PostCollection.DefaultQuery(1, numberOfPosts, category.SortOrder);

                if (Category.IncludeChildPosts)
                {
                    if (category.ParentId > 0)
                        q.AndWhere(Post.Columns.CategoryId, category.Id);
                    else
                    {
                        List<int> ids = new List<int>(category.Children.Count + 1);
                        foreach (Category child in category.Children)
                            ids.Add(child.Id);

                        ids.Add(category.Id);

                        q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                    }
                }
                else
                {
                    q.AndWhere(Post.Columns.CategoryId, category.Id);
                }

                if (filterHome)
                {
                    string where = GraffitiContext.Current["where"] as string;
                    if (!string.IsNullOrEmpty(where) && where == "home" && Site.UseCustomHomeList)
                        q.AndWhere(Post.Columns.IsHome, true);
                }

                pc.LoadAndCloseReader(q.ExecuteReader());
                ZCache.InsertCache(string.Format(CacheKey, 1, category.Id, category.SortOrder, numberOfPosts), pc, 60);
            }

            return pc;
        }
Esempio n. 14
0
        /// <summary>
        /// Renames a user account
        /// </summary>
        public static void RenameUser(string oldUserName, string newUserName)
        {
            if (!controller.CanDeleteUsers)
            {
                throw new Exception("The membership system in use does not support deleting users");
            }

            IGraffitiUser user = GetUser(oldUserName);
            if (user == null)
            {
                throw new Exception("The supplied username does not exist!");
            }

            oldUserName = oldUserName.ToLower();
            newUserName = newUserName.ToLower();
            controller.RenameUser(oldUserName, newUserName);

            // Check if the user has created/modified any content
            PostCollection pc = new PostCollection();
            Query q = Post.CreateQuery();
            q.OrWhere(Post.Columns.UserName, oldUserName);
            q.OrWhere(Post.Columns.CreatedBy, oldUserName);
            q.OrWhere(Post.Columns.ModifiedBy, oldUserName);
            pc.LoadAndCloseReader(q.ExecuteReader());

            if (pc != null && pc.Count > 0)
            {
                foreach (Post p in pc)
                {
                    if (p.UserName == oldUserName)
                        p.UserName = newUserName;
                    if (p.ModifiedBy == oldUserName)
                        p.ModifiedBy = newUserName;
                    if (p.CreatedBy == oldUserName)
                        p.CreatedBy = newUserName;

                    p.Save();
                }
            }

            // Check if user has created any comments
            CommentCollection cc = new CommentCollection();
            q = Comment.CreateQuery();
            q.OrWhere(Comment.Columns.UserName, oldUserName);
            q.OrWhere(Comment.Columns.CreatedBy, oldUserName);
            q.OrWhere(Comment.Columns.ModifiedBy, oldUserName);
            cc.LoadAndCloseReader(q.ExecuteReader());

            if (cc != null && cc.Count > 0)
            {
                foreach (Comment c in cc)
                {
                    if (c.UserName == oldUserName)
                        c.UserName = newUserName;
                    if (c.ModifiedBy == oldUserName)
                        c.ModifiedBy = newUserName;
                    if (c.CreatedBy == oldUserName)
                        c.CreatedBy = newUserName;

                    c.Save();
                }
            }

            //Check if the user has created any post versions
            VersionStoreCollection vsc = new VersionStoreCollection();
            vsc = VersionStoreCollection.FetchAll();

            if (vsc != null && vsc.Count > 0)
            {
                foreach (VersionStore v in vsc)
                {
                    Post vp = ObjectManager.ConvertToObject<Graffiti.Core.Post>(v.Data);

                    if (v.CreatedBy == oldUserName)
                        v.CreatedBy = newUserName;
                    if (v.Type == "post/xml")
                    {
                        if (vp.UserName == oldUserName)
                            vp.UserName = newUserName;
                        if (vp.ModifiedBy == oldUserName)
                            vp.ModifiedBy = newUserName;
                        if (vp.CreatedBy == oldUserName)
                            vp.CreatedBy = newUserName;
                        v.Data = vp.ToXML();
                    }

                    v.Save();
                }
            }

            ZCache.RemoveCache("user-" + oldUserName);
            // Clear roles cache
            if (user.Roles != null && user.Roles.Length > 0)
                ZCache.RemoveByPattern("usersByRole-");
        }
Esempio n. 15
0
        public MetaWeblog.Post[] getRecentPosts(string blogid,string username,string password,int numberOfPosts)
        {
            if(ValidateUser(username,password))
            {
                Query q = Graffiti.Core.Post.CreateQuery();
                q.AndWhere(Core.Post.Columns.IsDeleted, false);
                q.Top = numberOfPosts.ToString();
                q.OrderByDesc(Graffiti.Core.Post.Columns.Published);
                PostCollection pc = new PostCollection();
                pc.LoadAndCloseReader(q.ExecuteReader());

                ArrayList al = new ArrayList(pc.Count);
                foreach(Graffiti.Core.Post p in pc)
                {
                    al.Add(ConvertToPost(p));
                }

                return (Post[])al.ToArray(typeof(Post));

            }
            throw new XmlRpcFaultException(0,"User does not exist");
        }
Esempio n. 16
0
        /// <summary>
        /// Renders an unordered list with the sites most recent posts by categoryID
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public string ULPostsInCategory(int categoryId)
        {
            PostCollection pc = new PostCollection();
            Query q = Post.CreateQuery();
            q.PageIndex = 0;
            q.AndWhere(Post.Columns.CategoryId, categoryId);
            q.AndWhere(Post.Columns.IsDeleted, 0);
            q.AndWhere(Post.Columns.IsPublished, 1);

            pc.LoadAndCloseReader(q.ExecuteReader());

            StringBuilder sb = new StringBuilder();
            if (pc.Count > 0)
            {
                foreach (Post p in pc)
                {
                    sb.AppendFormat(liHrefFormat, p.Url, p.Title);
                }
            }

            return sb.ToString();
        }
Esempio n. 17
0
        public IEnumerable Query(IDictionary paramaters)
        {
            string type = paramaters["type"] as string;

            if (type != null)
            {
                paramaters.Remove("type");
            }
            else
            {
                type = "post";
            }

            switch (type)
            {
            case "post":

                Query postQuery = Post.CreateQuery();
                SetLimits(postQuery, paramaters);

                string categoryName = paramaters["category"] as string;
                if (categoryName != null)
                {
                    paramaters.Remove("category");
                }

                if (categoryName == "none")
                {
                    categoryName = CategoryController.UncategorizedName;
                }

                if (categoryName != null)
                {
                    paramaters["categoryid"] = new CategoryController().GetCachedCategory(categoryName, false).Id;
                }

                if (paramaters["isDeleted"] == null)
                {
                    paramaters["isDeleted"] = false;
                }

                if (paramaters["isPublished"] == null)
                {
                    paramaters["isPublished"] = true;
                }

                string orderBy = paramaters["orderby"] as string;
                if (orderBy != null)
                {
                    paramaters.Remove("orderBy");
                }
                else
                {
                    orderBy = "Published DESC";
                }

                postQuery.Orders.Add(orderBy);

                string cacheKey = "Posts-";
                foreach (string key in paramaters.Keys)
                {
                    Column col = GetPostColumn(key);
                    postQuery.AndWhere(col, paramaters[key]);
                    cacheKey += "|" + col.Name + "|" + paramaters[key];
                }

                PostCollection pc = ZCache.Get <PostCollection>(cacheKey);
                if (pc == null)
                {
                    pc = new PostCollection();
                    pc.LoadAndCloseReader(postQuery.ExecuteReader());
                    ZCache.InsertCache(cacheKey, pc, 90);
                }
                return(pc);

            case "comment":

                break;

            case "category":

                break;
            }

            return(null);
        }
Esempio n. 18
0
        /// <summary>
        /// Renders an unordered lists with the sites most recent posts
        /// </summary>
        /// <param name="numberOfPosts"></param>
        /// <returns></returns>
        public string ULRecentPosts(int numberOfPosts)
        {
            PostCollection pc = new PostCollection();
            Query q = PostCollection.DefaultQuery();
            q.PageIndex = 1;
            q.PageSize = numberOfPosts;
            pc.LoadAndCloseReader(q.ExecuteReader());

            StringBuilder sb = new StringBuilder();
            if (pc.Count > 0)
            {
                foreach (Post p in pc)
                {
                    sb.AppendFormat(liHrefFormat, p.Url, p.Title);
                }
            }

            return sb.ToString();
        }
Esempio n. 19
0
        /// <summary>
        /// Deletes a user, and reassigns any content created by that user to another existing user
        /// </summary>
        public static bool DeleteUser(IGraffitiUser user, IGraffitiUser userToAssumeContent, out string errorMessage)
        {
            if (!controller.CanDeleteUsers)
            {
                errorMessage = "The membership system in use does not support deleting users.";
                return false;
            }
            if (user == null)
            {
                throw new Exception("The supplied user object is null and cannot be deleted");
            }

            // Check if the user has created any content
            PostCollection pc = new PostCollection();
            Query q = Post.CreateQuery();
            q.AndWhere(Post.Columns.UserName, user.Name);
            pc.LoadAndCloseReader(q.ExecuteReader());

            if (pc != null && pc.Count > 0)
            {
                if (userToAssumeContent == null)
                {
                    errorMessage = "The user you are trying to delete has created posts. Another existing user must be selected to assign these posts to.";
                    return false;
                }
                foreach (Post p in pc)
                {
                    if (p.UserName == user.Name)
                        p.UserName = userToAssumeContent.Name;
                    if (p.ModifiedBy == user.Name)
                        p.ModifiedBy = userToAssumeContent.Name;
                    if (p.CreatedBy == user.Name)
                        p.CreatedBy = userToAssumeContent.Name;
                }
            }

            // Remove from roles
            if (user.Roles != null && user.Roles.Length > 0)
            {
                foreach (string roleName in user.Roles)
                {
                    controller.RemoveUserFromRole(user.Name, roleName);
                }
                ZCache.RemoveByPattern("usersByRole-");
            }

            controller.DeleteUser(user);

            ZCache.RemoveCache("user-" + user.Name.ToLower());

            errorMessage = string.Empty;
            return true;
        }
Esempio n. 20
0
 public static PostCollection FetchPostsByTagAndCategory(string tagName, int categoryId)
 {
     QueryCommand command = new QueryCommand("SELECT p.* FROM graffiti_Posts AS p INNER JOIN graffiti_Tags AS t ON p.Id = t.PostId WHERE p.CategoryId = " + categoryId.ToString() + " and p.IsPublished <> 0 and p.IsDeleted = 0 and p.Published <= " + DataService.Provider.SqlVariable("Published") + " and t.Name = " + DataService.Provider.SqlVariable("Name") + " ORDER BY p.Published DESC");
     command.Parameters.Add(Post.FindParameter("Published")).Value = SiteSettings.CurrentUserTime;
     command.Parameters.Add(Tag.FindParameter("Name")).Value = tagName;
     PostCollection pc = new PostCollection();
     pc.LoadAndCloseReader(DataService.ExecuteReader(command));
     return pc;
 }
Esempio n. 21
0
        public IEnumerable Query(IDictionary paramaters)
        {
            string type = paramaters["type"] as string;
            if (type != null)
                paramaters.Remove("type");
            else
                type = "post";

            switch(type)
            {
                case "post":

                    Query postQuery = Post.CreateQuery();
                    SetLimits(postQuery,paramaters);

                    string categoryName = paramaters["category"] as string;
                    if (categoryName != null)
                        paramaters.Remove("category");

                        if(categoryName == "none")
                            categoryName = CategoryController.UncategorizedName;

                    if (categoryName != null)
                        paramaters["categoryid"] = new CategoryController().GetCachedCategory(categoryName, false).Id;

                    if(paramaters["isDeleted"] == null)
                        paramaters["isDeleted"] = false;

                    if (paramaters["isPublished"] == null)
                    {
                        paramaters["isPublished"] = true;
                    }

                    string orderBy = paramaters["orderby"] as string;
                    if (orderBy != null)
                        paramaters.Remove("orderBy");
                    else
                        orderBy = "Published DESC";

                    postQuery.Orders.Add(orderBy);

                    string cacheKey = "Posts-";
                    foreach (string key in paramaters.Keys)
                    {
                        Column col = GetPostColumn(key);
                        postQuery.AndWhere(col, paramaters[key]);
                        cacheKey += "|" + col.Name + "|" + paramaters[key];
                    }

                    PostCollection pc = ZCache.Get<PostCollection>(cacheKey);
                    if (pc == null)
                    {
                        pc = new PostCollection();
                        pc.LoadAndCloseReader(postQuery.ExecuteReader());
                        ZCache.InsertCache(cacheKey, pc, 90);
                    }
                    return pc;

                case "comment":

                    break;

                case "category":

                    break;
            }

            return null;
        }
Esempio n. 22
0
        protected override void OnLoad(EventArgs e)
        {
            Initialize();

            SiteSettings settings = SiteSettings.Get();

            string baseUrl = SiteSettings.BaseUrl;

            if (string.IsNullOrEmpty(TagName))
            {
                Category category = null;
                if (CategoryID > -1)
                    category = new CategoryController().GetCachedCategory(CategoryID, false);

                if (category == null)
                {
                    if (!string.IsNullOrEmpty(settings.ExternalFeedUrl) &&
                        Request.UserAgent.IndexOf("FeedBurner", StringComparison.InvariantCultureIgnoreCase) == -1)
                    {
                        Context.Response.RedirectLocation = settings.ExternalFeedUrl;
                        Context.Response.StatusCode = 301;
                        Context.Response.End();
                    }
                }
                else if (!string.IsNullOrEmpty(category.FeedUrlOverride) &&
                         Request.UserAgent.IndexOf("FeedBurner", StringComparison.InvariantCultureIgnoreCase) == -1)
                {
                    Context.Response.RedirectLocation = category.FeedUrlOverride;
                    Context.Response.StatusCode = 301;
                    Context.Response.End();
                }
                else if (CategoryName != null && !Util.AreEqualIgnoreCase(CategoryName, category.LinkName))
                {
                    Context.Response.RedirectLocation = new Uri(Context.Request.Url, category.Url).ToString();
                    Context.Response.StatusCode = 301;
                    Context.Response.End();
                }

                string cacheKey = CategoryID > -1
                                      ? "Posts-Index-" + Util.PageSize + "-" + CategoryID.ToString()
                                      : string.Format("Posts-Categories-P:{0}-C:{1}-T:{2}-PS:{3}", 1, CategoryID,
                                                      SortOrderType.Descending, Util.PageSize);

                PostCollection pc = ZCache.Get<PostCollection>(cacheKey);

                if (pc == null)
                {
                    Query q = PostCollection.DefaultQuery();
                    q.Top = Util.PageSize.ToString();

                    if (SiteSettings.Get().IncludeChildPosts && macros.IsNotNull(category))
                    {
                        if (category.ParentId > 0)
                            q.AndWhere(Post.Columns.CategoryId, CategoryID);
                        else
                        {
                            List<int> ids = new List<int>(category.Children.Count + 1);
                            foreach (Category child in category.Children)
                                ids.Add(child.Id);

                            ids.Add(category.Id);

                            q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                        }
                    }
                    else
                    {
                        if (CategoryID > 0)
                            q.AndWhere(Post.Columns.CategoryId, CategoryID);
                    }

                    pc = new PostCollection();
                    pc.LoadAndCloseReader(q.ExecuteReader());

                    PostCollection permissionsFiltered = new PostCollection();

                    permissionsFiltered.AddRange(pc);

                    foreach (Post p in pc)
                    {
                        if (!RolePermissionManager.GetPermissions(p.CategoryId, GraffitiUsers.Current).Read)
                            permissionsFiltered.Remove(p);
                    }

                    ZCache.InsertCache(cacheKey, permissionsFiltered, 90);
                    pc = permissionsFiltered;
                }

                ValidateAndSetHeaders(pc, settings, Context);

                StringWriter sw = new StringWriter();
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
                XmlTextWriter writer = new XmlTextWriter(sw);

                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                writer.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");
                writer.WriteAttributeString("xmlns:slash", "http://purl.org/rss/1.0/modules/slash/");

                // Allow plugins to add additional xml namespaces
                Core.Events.Instance().ExecuteRssNamespace(writer);

                writer.WriteStartElement("channel");
                WriteChannel(writer, category, settings);

                // Allow plugins to add additional xml to the <channel>
                Core.Events.Instance().ExecuteRssChannel(writer);

                foreach (Post p in pc)
                {
                    writer.WriteStartElement("item");
                    WriteItem(writer, p, settings, baseUrl);

                    // Allow plugins to add additional xml to the <item>
                    Core.Events.Instance().ExecuteRssItem(writer, p);

                    writer.WriteEndElement(); // End Item
                }

                writer.WriteEndElement(); // End Channel
                writer.WriteEndElement(); // End Document

                // save XML into response
                Context.Response.ContentEncoding = System.Text.Encoding.UTF8;
                Context.Response.ContentType = "application/rss+xml";
                Context.Response.Write(sw.ToString());
            }
            else
            {
                PostCollection pc = GetTaggedPosts(TagName);

                ValidateAndSetHeaders(pc, settings, Context);

                StringWriter sw = new StringWriter();
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
                XmlTextWriter writer = new XmlTextWriter(sw);

                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                writer.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");
                writer.WriteAttributeString("xmlns:slash", "http://purl.org/rss/1.0/modules/slash/");

                Core.Events.Instance().ExecuteRssNamespace(writer);

                writer.WriteStartElement("channel");
                WriteChannel(writer, TagName, settings);

                // Allow plugins to add additional xml to the <channel>
                Core.Events.Instance().ExecuteRssChannel(writer);

                foreach (Post p in pc) {
                    writer.WriteStartElement("item");
                    WriteItem(writer, p, settings, baseUrl);

                    Core.Events.Instance().ExecuteRssItem(writer, p);

                    writer.WriteEndElement(); // End Item
                }

                writer.WriteEndElement(); // End Channel
                writer.WriteEndElement(); // End Document

                Context.Response.ContentEncoding = Encoding.UTF8;
                Context.Response.ContentType = "application/rss+xml";
                Context.Response.Write(sw.ToString());
            }
        }
Esempio n. 23
0
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.RequestType != "POST" || !context.Request.IsAuthenticated)
                return;

            IGraffitiUser user = GraffitiUsers.Current;
            if (user == null)
                return;

            if (!RolePermissionManager.CanViewControlPanel(user))
                return;

            context.Response.ContentType = "text/plain";

            switch (context.Request.QueryString["command"])
            {
                case "deleteComment":

                    Comment c = new Comment(context.Request.Form["commentid"]);

                    if (RolePermissionManager.GetPermissions(c.Post.CategoryId, GraffitiUsers.Current).Publish)
                    {
                        Comment.Delete(context.Request.Form["commentid"]);
                        context.Response.Write("success");
                    }

                    break;

                case "deleteCommentWithStatus":

                    Comment c1 = new Comment(context.Request.Form["commentid"]);

                    if (RolePermissionManager.GetPermissions(c1.Post.CategoryId, GraffitiUsers.Current).Publish)
                    {
                        Comment.Delete(context.Request.Form["commentid"]);
                        context.Response.Write("The comment was deleted. <a href=\"javascript:void(0);\" onclick=\"Comments.unDelete('" + new Urls().AdminAjax + "'," + context.Request.Form["commentid"] + "); return false;\">Undo?</a>");
                    }
                    break;

                case "unDelete":
                    Comment c2 = new Comment(context.Request.Form["commentid"]);

                    if (RolePermissionManager.GetPermissions(c2.Post.CategoryId, GraffitiUsers.Current).Publish)
                    {
                        Comment comment = new Comment(context.Request.Form["commentid"]);
                        comment.IsDeleted = false;
                        comment.Save();
                        context.Response.Write("The comment was un-deleted. You may need to refresh the page to see it");
                    }
                    break;

                case "approve":
                    Comment c3 = new Comment(context.Request.Form["commentid"]);

                    if (RolePermissionManager.GetPermissions(c3.Post.CategoryId, GraffitiUsers.Current).Publish)
                    {
                        Comment cmt = new Comment(context.Request.Form["commentid"]);
                        cmt.IsDeleted = false;
                        cmt.IsPublished = true;
                        cmt.Save();
                        context.Response.Write("The comment was un-deleted and/or approved. You may need to refresh the page to see it");
                    }
                    break;

                case "deletePost":
                    try
                    {
                        Post postToDelete = new Post(context.Request.Form["postid"]);

                        Permission perm = RolePermissionManager.GetPermissions(postToDelete.CategoryId, user);

                        if (GraffitiUsers.IsAdmin(user) || perm.Publish)
                        {
                            postToDelete.IsDeleted = true;
                            postToDelete.Save(user.Name, DateTime.Now);

                            //Post.Delete(context.Request.Form["postid"]);
                            //ZCache.RemoveByPattern("Posts-");
                            //ZCache.RemoveCache("Post-" + context.Request.Form["postid"]);
                            context.Response.Write("The post was deleted. <a href=\"javascript:void(0);\" onclick=\"Posts.unDeletePost('" + new Urls().AdminAjax + "'," + context.Request.Form["postid"] + "); return false;\">Undo?</a>");
                        }
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "unDeletePost":
                    Post p = new Post(context.Request.Form["postid"]);
                    p.IsDeleted = false;
                    p.Save();
                    //ZCache.RemoveByPattern("Posts-");
                    //ZCache.RemoveCache("Post-" + context.Request.Form["postid"]);
                    //context.Response.Write("The post was un-deleted. You may need to fresh the page to see it");
                    break;

                case "permanentDeletePost":
                    Post tempPost = new Post(context.Request.Form["postid"]);
                    Post.DestroyDeletedPost(tempPost.Id);
                    context.Response.Write(tempPost.Title);
                    break;

                case "createdWidget":
                    string widgetID = context.Request.Form["id"];
                    List<WidgetDescription> the_widgets = Widgets.GetAvailableWidgets();
                    Widget widget = null;
                    foreach (WidgetDescription wia in the_widgets)
                    {
                        if (wia.UniqueId == widgetID)
                        {
                            widget = Widgets.Create(wia.WidgetType);
                            break;
                        }
                    }

                    context.Response.Write(widget.Id.ToString());

                    break;

                case "updateWidgetsOrder":

                    try
                    {
                        string listID = context.Request.Form["id"];
                        string list = "&" + context.Request.Form["list"];

                        Widgets.ReOrder(listID, list);

                        //StreamWriter sw = new StreamWriter(context.Server.MapPath("~/widgets.txt"), true);
                        //sw.WriteLine(DateTime.Now);
                        //sw.WriteLine();
                        //sw.WriteLine(context.Request.Form["left"]);
                        //sw.WriteLine(context.Request.Form["right"]);
                        //sw.WriteLine(context.Request.Form["queue"]);
                        //sw.WriteLine();
                        //sw.Close();

                        context.Response.Write("Saved!");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "deleteWidget":

                    string deleteID = context.Request.Form["id"];
                    Widgets.Delete(deleteID);
                    context.Response.Write("The widget was removed!");

                    break;

                case "createTextLink":
                    DynamicNavigationItem di = new DynamicNavigationItem();
                    di.NavigationType = DynamicNavigationType.Link;
                    di.Text = context.Request.Form["text"];
                    di.Href = context.Request.Form["href"];
                    di.Id = Guid.NewGuid();
                    NavigationSettings.Add(di);
                    context.Response.Write(di.Id);

                    break;

                case "deleteTextLink":
                    Guid g = new Guid(context.Request.Form["id"]);
                    NavigationSettings.Remove(g);
                    context.Response.Write("Success");
                    break;

                case "reOrderNavigation":
                    try
                    {
                        string navItems = "&" + context.Request.Form["navItems"];
                        NavigationSettings.ReOrder(navItems);
                        context.Response.Write("Success");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "addNavigationItem":

                    try
                    {
                        if (context.Request.Form["type"] == "Post")
                        {
                            Post navPost = Post.FetchByColumn(Post.Columns.UniqueId, new Guid(context.Request.Form["id"]));
                            DynamicNavigationItem item = new DynamicNavigationItem();
                            item.PostId = navPost.Id;
                            item.Id = navPost.UniqueId;
                            item.NavigationType = DynamicNavigationType.Post;
                            NavigationSettings.Add(item);
                            context.Response.Write("Success");
                        }
                        else if (context.Request.Form["type"] == "Category")
                        {
                            Category navCategory = Category.FetchByColumn(Category.Columns.UniqueId, new Guid(context.Request.Form["id"]));
                            DynamicNavigationItem item = new DynamicNavigationItem();
                            item.CategoryId = navCategory.Id;
                            item.Id = navCategory.UniqueId;
                            item.NavigationType = DynamicNavigationType.Category;
                            NavigationSettings.Add(item);
                            context.Response.Write("Success");
                        }

                    }
                    catch (Exception exp)
                    {
                        context.Response.Write(exp.Message);
                    }

                    break;

                case "reOrderPosts":
                    try
                    {
                        Dictionary<int, Post> posts = new Dictionary<int, Post>();
                        DataBuddy.Query query = Post.CreateQuery();
                        query.AndWhere(Post.Columns.CategoryId, int.Parse(context.Request.QueryString["id"]));
                        foreach (Post post in PostCollection.FetchByQuery(query))
                        {
                            posts[post.Id] = post;
                        }

                        string postOrder = context.Request.Form["posts"];
                        int orderNumber = 1;
                        foreach (string sId in postOrder.Split('&'))
                        {
                            Post post = null;
                            posts.TryGetValue(int.Parse(sId), out post);
                            if (post != null && post.SortOrder != orderNumber)
                            {
                                post.SortOrder = orderNumber;
                                post.Save();
                            }

                            orderNumber++;
                        }

                        context.Response.Write("Success");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "reOrderHomePosts":
                    try
                    {
                        Dictionary<int, Post> posts = new Dictionary<int, Post>();
                        DataBuddy.Query query = Post.CreateQuery();
                        query.AndWhere(Post.Columns.IsHome, true);
                        foreach (Post post in PostCollection.FetchByQuery(query))
                        {
                            posts[post.Id] = post;
                        }

                        string postOrder = context.Request.Form["posts"];
                        int orderNumber = 1;
                        foreach (string sId in postOrder.Split('&'))
                        {
                            Post post = null;
                            posts.TryGetValue(int.Parse(sId), out post);
                            if (post != null && post.HomeSortOrder != orderNumber)
                            {
                                post.HomeSortOrder = orderNumber;
                                post.Save();
                            }

                            orderNumber++;
                        }

                        context.Response.Write("Success");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "categoryForm":

                    int selectedCategory = int.Parse(context.Request.QueryString["category"] ?? "-1");
                    int postId = int.Parse(context.Request.QueryString["post"] ?? "-1");
                    NameValueCollection nvcCustomFields;
                    if (postId > 0)
                        nvcCustomFields = new Post(postId).CustomFields();
                    else
                        nvcCustomFields = new NameValueCollection();

                    CustomFormSettings cfs = CustomFormSettings.Get(selectedCategory);

                    if (cfs.HasFields)
                    {
                        foreach (CustomField cf in cfs.Fields)
                        {
                            if (context.Request.Form[cf.Id.ToString()] != null)
                                nvcCustomFields[cf.Name] = context.Request.Form[cf.Id.ToString()];
                        }

                        context.Response.Write(cfs.GetHtmlForm(nvcCustomFields, (postId < 1)));
                    }
                    else
                        context.Response.Write("");

                    break;

                case "toggleEventStatus":

                    try
                    {
                        EventDetails ed = Events.GetEvent(context.Request.QueryString["t"]);
                        ed.Enabled = !ed.Enabled;

                        if (ed.Enabled)
                            ed.Event.EventEnabled();
                        else
                            ed.Event.EventDisabled();

                        Events.Save(ed);

                        context.Response.Write(ed.Enabled ? "Enabled" : "Disabled");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "buildMainFeed":
                    try
                    {
                        FileInfo mainFeedFileInfo = new FileInfo(HttpContext.Current.Server.MapPath("~/Feed/Default.aspx"));

                        if (!mainFeedFileInfo.Directory.Exists)
                            mainFeedFileInfo.Directory.Create();

                        using (StreamWriter sw = new StreamWriter(mainFeedFileInfo.FullName, false))
                        {
                            sw.WriteLine("<%@ Page Language=\"C#\" Inherits=\"Graffiti.Core.RSS\" %>");
                            sw.Close();
                        }

                        context.Response.Write("Success");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                        return;
                    }

                    break;

                case "removeFeedData":
                    try
                    {
                        FeedManager.RemoveFeedData();
                        context.Response.Write("Success");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

                case "buildCategoryPages":

                    try
                    {
                        CategoryCollection cc = new CategoryController().GetCachedCategories();
                        foreach (Category cat in cc)
                            cat.WritePages();

                        context.Response.Write("Success");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                        return;
                    }

                    break;

                case "buildPages":

                    try
                    {

                        Query q = Post.CreateQuery();
                        q.PageIndex = Int32.Parse(context.Request.Form["p"]);
                        q.PageSize = 20;
                        q.OrderByDesc(Post.Columns.Id);

                        PostCollection pc = PostCollection.FetchByQuery(q);
                        if (pc.Count > 0)
                        {

                            foreach (Post postToWrite in pc)
                            {
                                postToWrite.WritePages();
                                foreach (string tagName in Util.ConvertStringToList(postToWrite.TagList))
                                {
                                    if (!string.IsNullOrEmpty(tagName))
                                        Tag.WritePage(tagName);
                                }

                            }

                            context.Response.Write("Next");
                        }
                        else
                        {
                            context.Response.Write("Success");
                        }

                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                        return;
                    }

                    break;

                case "importPosts":

                    try
                    {
                        Post newPost = new Post();
                        newPost.Title = HttpContext.Current.Server.HtmlDecode(context.Request.Form["subject"].ToString());

                        string postName = HttpContext.Current.Server.HtmlDecode(context.Request.Form["name"].ToString());

                        PostCollection pc = new PostCollection();

                        if (!String.IsNullOrEmpty(postName))
                        {
                            Query q = Post.CreateQuery();
                            q.AndWhere(Post.Columns.Name, Util.CleanForUrl(postName));
                            pc.LoadAndCloseReader(q.ExecuteReader());
                        }

                        if (pc.Count > 0)
                        {
                            newPost.Name = "[RENAME ME - " + Guid.NewGuid().ToString().Substring(0, 7) + "]";
                            newPost.Status = (int)PostStatus.Draft;
                        }
                        else if (String.IsNullOrEmpty(postName))
                        {
                            newPost.Name = "[RENAME ME - " + Guid.NewGuid().ToString().Substring(0, 7) + "]";
                            newPost.Status = (int)PostStatus.Draft;
                        }
                        else
                        {
                            newPost.Name = postName;
                            newPost.Status = (int)PostStatus.Publish;
                        }

                        if (String.IsNullOrEmpty(newPost.Title))
                            newPost.Title = newPost.Name;

                        newPost.PostBody = HttpContext.Current.Server.HtmlDecode(context.Request.Form["body"].ToString());
                        newPost.CreatedOn = Convert.ToDateTime(context.Request.Form["createdon"]);
                        newPost.CreatedBy = context.Request.Form["author"];
                        newPost.ModifiedBy = context.Request.Form["author"];
                        newPost.TagList = context.Request.Form["tags"];
                        newPost.ContentType = "text/html";
                        newPost.CategoryId = Convert.ToInt32(context.Request.Form["category"]);
                        newPost.UserName = context.Request.Form["author"];
                        newPost.EnableComments = true;
                        newPost.Published = Convert.ToDateTime(context.Request.Form["createdon"]);
                        newPost.IsPublished = Convert.ToBoolean(context.Request.Form["published"]);

                        // this was causing too many posts to be in draft status.
                        // updated text on migrator to flag users to just move their content/binary directory
                        // into graffiti's root
                        //if (context.Request.Form["method"] == "dasBlog")
                        //{
                        //    if (newPost.Body.ToLower().Contains("/content/binary/"))
                        //        newPost.Status = (int)PostStatus.Draft;
                        //}

                        newPost.Save(GraffitiUsers.Current.Name);

                        int postid = Convert.ToInt32(context.Request.Form["postid"]);

                        IMigrateFrom temp = null;

                        switch (context.Request.Form["method"])
                        {
                            case "CS2007Database":

                                CS2007Database db = new CS2007Database();
                                temp = (IMigrateFrom)db;

                                break;
                            case "Wordpress":

                                Wordpress wp = new Wordpress();
                                temp = (IMigrateFrom)wp;

                                break;

                            case "BlogML":

                                BlogML bml = new BlogML();
                                temp = (IMigrateFrom)bml;

                                break;

                            case "CS21Database":
                                CS21Database csDb = new CS21Database();
                                temp = (IMigrateFrom)csDb;

                                break;

                            case "dasBlog":
                                dasBlog dasb = new dasBlog();
                                temp = (IMigrateFrom)dasb;

                                break;
                        }

                        List<MigratorComment> comments = temp.GetComments(postid);

                        foreach (MigratorComment cmnt in comments)
                        {
                            Comment ct = new Comment();
                            ct.PostId = newPost.Id;
                            ct.Body = cmnt.Body;
                            ct.Published = cmnt.PublishedOn;
                            ct.IPAddress = cmnt.IPAddress;
                            ct.WebSite = cmnt.WebSite;
                            ct.Email = string.IsNullOrEmpty(cmnt.Email) ? "" : cmnt.Email;
                            ct.Name = string.IsNullOrEmpty(cmnt.UserName) ? "" : cmnt.UserName;
                            ct.IsPublished = cmnt.IsPublished;
                            ct.IsTrackback = cmnt.IsTrackback;
                            ct.SpamScore = cmnt.SpamScore;
                            ct.DontSendEmail = true;
                            ct.DontChangeUser = true;

                            ct.Save();

                            Comment ctemp = new Comment(ct.Id);
                            ctemp.DontSendEmail = true;
                            ctemp.DontChangeUser = true;
                            ctemp.Body = HttpContext.Current.Server.HtmlDecode(ctemp.Body);
                            ctemp.Save();
                        }

                        if (newPost.Status == (int)PostStatus.Publish)
                            context.Response.Write("Success" + context.Request.Form["panel"]);
                        else
                            context.Response.Write("Warning" + context.Request.Form["panel"]);
                    }
                    catch (Exception ex)
                    {

                        context.Response.Write(context.Request.Form["panel"] + ":" + ex.Message);
                    }

                    break;

                case "saveHomeSortStatus":

                    SiteSettings siteSettings = SiteSettings.Get();
                    siteSettings.UseCustomHomeList = bool.Parse(context.Request.Form["ic"]);
                    siteSettings.Save();
                    context.Response.Write("Success");

                    break;

                case "checkCategoryPermission":

                    try
                    {
                        int catID = Int32.Parse(context.Request.QueryString["category"]);
                        string permissionName = context.Request.QueryString["permission"];
                        Permission perm = RolePermissionManager.GetPermissions(catID, user);

                        bool permissionResult = false;
                        switch (permissionName)
                        {
                            case "Publish":
                                permissionResult = perm.Publish;
                                break;
                            case "Read":
                                permissionResult = perm.Read;
                                break;
                            case "Edit":
                                permissionResult = perm.Edit;
                                break;
                        }

                        context.Response.Write(permissionResult.ToString().ToLower());
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }
                    break;

            }
        }
Esempio n. 24
0
        protected override void OnLoad(EventArgs e)
        {
            Initialize();

            SiteSettings settings = SiteSettings.Get();

            string baseUrl = SiteSettings.BaseUrl;

            if (string.IsNullOrEmpty(TagName))
            {
                Category category = null;
                if (CategoryID > -1)
                {
                    category = new CategoryController().GetCachedCategory(CategoryID, false);
                }

                if (category == null)
                {
                    if (!string.IsNullOrEmpty(settings.ExternalFeedUrl) &&
                        Request.UserAgent.IndexOf("FeedBurner", StringComparison.InvariantCultureIgnoreCase) == -1)
                    {
                        Context.Response.RedirectLocation = settings.ExternalFeedUrl;
                        Context.Response.StatusCode       = 301;
                        Context.Response.End();
                    }
                }
                else if (!string.IsNullOrEmpty(category.FeedUrlOverride) &&
                         Request.UserAgent.IndexOf("FeedBurner", StringComparison.InvariantCultureIgnoreCase) == -1)
                {
                    Context.Response.RedirectLocation = category.FeedUrlOverride;
                    Context.Response.StatusCode       = 301;
                    Context.Response.End();
                }
                else if (CategoryName != null && !Util.AreEqualIgnoreCase(CategoryName, category.LinkName))
                {
                    Context.Response.RedirectLocation = new Uri(Context.Request.Url, category.Url).ToString();
                    Context.Response.StatusCode       = 301;
                    Context.Response.End();
                }

                string cacheKey = CategoryID > -1
                                                          ? "Posts-Index-" + Util.PageSize + "-" + CategoryID.ToString()
                                                          : string.Format("Posts-Categories-P:{0}-C:{1}-T:{2}-PS:{3}", 1, CategoryID,
                                                                          SortOrderType.Descending, Util.PageSize);

                PostCollection pc = ZCache.Get <PostCollection>(cacheKey);

                if (pc == null)
                {
                    Query q = PostCollection.DefaultQuery();
                    q.Top = Util.PageSize.ToString();

                    if (SiteSettings.Get().IncludeChildPosts&& macros.IsNotNull(category))
                    {
                        if (category.ParentId > 0)
                        {
                            q.AndWhere(Post.Columns.CategoryId, CategoryID);
                        }
                        else
                        {
                            var ids = new List <int>(category.Children.Count + 1);
                            foreach (Category child in category.Children)
                            {
                                ids.Add(child.Id);
                            }

                            ids.Add(category.Id);

                            q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                        }
                    }
                    else
                    {
                        if (CategoryID > 0)
                        {
                            q.AndWhere(Post.Columns.CategoryId, CategoryID);
                        }
                    }

                    pc = new PostCollection();
                    pc.LoadAndCloseReader(q.ExecuteReader());

                    PostCollection permissionsFiltered = new PostCollection();

                    permissionsFiltered.AddRange(pc);

                    foreach (Post p in pc)
                    {
                        if (!RolePermissionManager.GetPermissions(p.CategoryId, GraffitiUsers.Current).Read)
                        {
                            permissionsFiltered.Remove(p);
                        }
                    }

                    ZCache.InsertCache(cacheKey, permissionsFiltered, 90);
                    pc = permissionsFiltered;
                }

                ValidateAndSetHeaders(pc, settings, Context);

                StringWriter sw = new StringWriter();
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
                XmlTextWriter writer = new XmlTextWriter(sw);

                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                writer.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");
                writer.WriteAttributeString("xmlns:slash", "http://purl.org/rss/1.0/modules/slash/");

                // Allow plugins to add additional xml namespaces
                Core.Events.Instance().ExecuteRssNamespace(writer);

                writer.WriteStartElement("channel");
                WriteChannel(writer, category, settings);

                // Allow plugins to add additional xml to the <channel>
                Core.Events.Instance().ExecuteRssChannel(writer);

                foreach (Post p in pc)
                {
                    writer.WriteStartElement("item");
                    WriteItem(writer, p, settings, baseUrl);

                    // Allow plugins to add additional xml to the <item>
                    Core.Events.Instance().ExecuteRssItem(writer, p);

                    writer.WriteEndElement();                     // End Item
                }

                writer.WriteEndElement();                 // End Channel
                writer.WriteEndElement();                 // End Document

                // save XML into response
                Context.Response.ContentEncoding = Encoding.UTF8;
                Context.Response.ContentType     = "application/rss+xml";
                Context.Response.Write(sw.ToString());
            }
            else
            {
                PostCollection pc = GetTaggedPosts(TagName);

                ValidateAndSetHeaders(pc, settings, Context);

                StringWriter sw = new StringWriter();
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
                XmlTextWriter writer = new XmlTextWriter(sw);

                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                writer.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");
                writer.WriteAttributeString("xmlns:slash", "http://purl.org/rss/1.0/modules/slash/");

                Core.Events.Instance().ExecuteRssNamespace(writer);

                writer.WriteStartElement("channel");
                WriteChannel(writer, TagName, settings);

                // Allow plugins to add additional xml to the <channel>
                Core.Events.Instance().ExecuteRssChannel(writer);

                foreach (Post p in pc)
                {
                    writer.WriteStartElement("item");
                    WriteItem(writer, p, settings, baseUrl);

                    Core.Events.Instance().ExecuteRssItem(writer, p);

                    writer.WriteEndElement();                     // End Item
                }

                writer.WriteEndElement();                 // End Channel
                writer.WriteEndElement();                 // End Document

                Context.Response.ContentEncoding = Encoding.UTF8;
                Context.Response.ContentType     = "application/rss+xml";
                Context.Response.Write(sw.ToString());
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Renames a user account
        /// </summary>
        public static void RenameUser(string oldUserName, string newUserName)
        {
            if (!controller.CanDeleteUsers)
            {
                throw new Exception("The membership system in use does not support deleting users");
            }

            IGraffitiUser user = GetUser(oldUserName);

            if (user == null)
            {
                throw new Exception("The supplied username does not exist!");
            }

            oldUserName = oldUserName.ToLower();
            newUserName = newUserName.ToLower();
            controller.RenameUser(oldUserName, newUserName);

            // Check if the user has created/modified any content
            PostCollection pc = new PostCollection();
            Query          q  = Post.CreateQuery();

            q.OrWhere(Post.Columns.UserName, oldUserName);
            q.OrWhere(Post.Columns.CreatedBy, oldUserName);
            q.OrWhere(Post.Columns.ModifiedBy, oldUserName);
            pc.LoadAndCloseReader(q.ExecuteReader());

            if (pc != null && pc.Count > 0)
            {
                foreach (Post p in pc)
                {
                    if (p.UserName == oldUserName)
                    {
                        p.UserName = newUserName;
                    }
                    if (p.ModifiedBy == oldUserName)
                    {
                        p.ModifiedBy = newUserName;
                    }
                    if (p.CreatedBy == oldUserName)
                    {
                        p.CreatedBy = newUserName;
                    }

                    p.Save();
                }
            }

            // Check if user has created any comments
            CommentCollection cc = new CommentCollection();

            q = Comment.CreateQuery();
            q.OrWhere(Comment.Columns.UserName, oldUserName);
            q.OrWhere(Comment.Columns.CreatedBy, oldUserName);
            q.OrWhere(Comment.Columns.ModifiedBy, oldUserName);
            cc.LoadAndCloseReader(q.ExecuteReader());

            if (cc != null && cc.Count > 0)
            {
                foreach (Comment c in cc)
                {
                    if (c.UserName == oldUserName)
                    {
                        c.UserName = newUserName;
                    }
                    if (c.ModifiedBy == oldUserName)
                    {
                        c.ModifiedBy = newUserName;
                    }
                    if (c.CreatedBy == oldUserName)
                    {
                        c.CreatedBy = newUserName;
                    }

                    c.Save();
                }
            }

            //Check if the user has created any post versions
            VersionStoreCollection vsc = new VersionStoreCollection();

            vsc = VersionStoreCollection.FetchAll();

            if (vsc != null && vsc.Count > 0)
            {
                foreach (VersionStore v in vsc)
                {
                    Post vp = ObjectManager.ConvertToObject <Graffiti.Core.Post>(v.Data);

                    if (v.CreatedBy == oldUserName)
                    {
                        v.CreatedBy = newUserName;
                    }
                    if (v.Type == "post/xml")
                    {
                        if (vp.UserName == oldUserName)
                        {
                            vp.UserName = newUserName;
                        }
                        if (vp.ModifiedBy == oldUserName)
                        {
                            vp.ModifiedBy = newUserName;
                        }
                        if (vp.CreatedBy == oldUserName)
                        {
                            vp.CreatedBy = newUserName;
                        }
                        v.Data = vp.ToXML();
                    }

                    v.Save();
                }
            }

            ZCache.RemoveCache("user-" + oldUserName);
            // Clear roles cache
            if (user.Roles != null && user.Roles.Length > 0)
            {
                ZCache.RemoveByPattern("usersByRole-");
            }
        }
Esempio n. 26
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if(Request.QueryString["id"] != null)
        {
            Post the_Post = new Post(Request.QueryString["id"]);
            switch(the_Post.PostStatus)
            {
                case PostStatus.Publish:

                    if (the_Post.Published > SiteSettings.CurrentUserTime)
                    {
                        PostUpdateStatus.Text = "The post, <em>&quot;<a title=\"click to view the post\" href=\"" + the_Post.Url +
                                                "\">" + the_Post.Title +
                                                "</a>&quot;</em>, was published. However, since this is a forward dated post, only site administrators can view it until " + the_Post.Published.ToLongDateString() + " " + the_Post.Published.ToShortTimeString();
                    }
                    else
                    {
                        PostUpdateStatus.Text = "The post, <em>&quot;<a title=\"click to view the post\" href=\"" + the_Post.Url +
                                                "\">" + the_Post.Title +
                                                "</a>&quot;</em>, was published. If this was a revision, the new version is now live.";
                    }
                    PostUpdateStatus.Type = StatusType.Success;
                    break;

                case PostStatus.Draft:

                    PostUpdateStatus.Text = "The post, <em>&quot;" + the_Post.Title +
                                            "&quot;</em>, was saved as a draft.";
                    PostUpdateStatus.Type = StatusType.Success;

                    break;

                case PostStatus.PendingApproval:
                    PostUpdateStatus.Text = "The post, <em>&quot;" + the_Post.Title +
                                            "&quot;</em>, was saved, but requires approval before it can be published. The site editors and publishers have been notified by email about this post. Once they publish it, you will be able to view it live.";

                    PostUpdateStatus.Type = StatusType.Warning;
                    break;

                case PostStatus.RequiresChanges:
                    PostUpdateStatus.Text = "The post, <em>&quot;" + the_Post.Title +
                                            "&quot;</em>, was saved. An email has been sent to the original author with the change notification. You will receive an email once the author sets the post status to <em>Request Approval</em>.";

                    PostUpdateStatus.Type = StatusType.Warning;
                    break;
            }
        }

        if(!IsPostBack)
        {
            string page = Request.QueryString["status"] ?? "1";
            string category = Request.QueryString["category"];
            string author = Request.QueryString["author"];

            Master.FindControl("SideBarRegion").Visible = true;

            List<AuthorCount> auts = null;

            switch (page)
            {
                case "1": // published
                    PostsLinks.SetActiveView(Published);
                    cats = Post.GetCategoryCountForStatus(PostStatus.Publish, author);
                    auts = Post.GetAuthorCountForStatus(PostStatus.Publish, category);
                    break;
                case "2": // draft
                    PostsLinks.SetActiveView(Draft);
                    cats = Post.GetCategoryCountForStatus(PostStatus.Draft, author);
                    auts = Post.GetAuthorCountForStatus(PostStatus.Draft, category);
                    break;
                case "3": // pending review
                    PostsLinks.SetActiveView(PendingReview);
                    cats = Post.GetCategoryCountForStatus(PostStatus.PendingApproval, author);
                    auts = Post.GetAuthorCountForStatus(PostStatus.PendingApproval, category);
                    break;
                case "4": // requires changes
                    PostsLinks.SetActiveView(RequiresChanges);
                    cats = Post.GetCategoryCountForStatus(PostStatus.RequiresChanges, author);
                    auts = Post.GetAuthorCountForStatus(PostStatus.RequiresChanges, category);
                    break;
                case "-1": // deleted
                    PostsLinks.SetActiveView(Deleted);
                    Master.FindControl("SideBarRegion").Visible = false;
                    break;
            }

            if (auts != null)
            {
                rptAuthors.DataSource = auts;
                rptAuthors.DataBind();
            }

            if (cats != null)
            {
                List<CategoryCount> temp = new List<CategoryCount>();
                temp.AddRange((List<CategoryCount>)cats.FindAll(
                                                    delegate(CategoryCount ca)
                                                    {
                                                        return ca.ParentId <= 0; // only want the parents
                                                                                    // the repeater below will handle the children
                                                    }));

                temp.Sort(
                    delegate(CategoryCount c, CategoryCount c1)
                    {
                        return c.Name.CompareTo(c1.Name);
                    });

                rptCategories.DataSource = temp;

                List<CategoryCount> toRemove = new List<CategoryCount>();

                foreach(CategoryCount cc in temp)
                {
                    if (!RolePermissionManager.GetPermissions(cc.ID, GraffitiUsers.Current).Read)
                        toRemove.Add(cc);
                }

                foreach (CategoryCount cc in toRemove)
                {
                    temp.Remove(cc);
                }

                rptCategories.DataBind();
            }

            User user = null;

            if (!String.IsNullOrEmpty(author))
            {
                user = new User(Convert.ToInt32(author));
                author = user.Name;
            }

            Query q = Post.CreateQuery();

            if (Request.QueryString["category"] != null && Request.QueryString["category"] != "-1")
                q.AndWhere(Post.Columns.CategoryId, Request.QueryString["category"]);

            if (!String.IsNullOrEmpty(author))
                q.AndWhere(Post.Columns.CreatedBy, author);

            if (Request.QueryString["status"] == "-1")
                q.AndWhere(Post.Columns.IsDeleted, true);
            else
            {
                q.AndWhere(Post.Columns.IsDeleted, false);
                q.AndWhere(Post.Columns.Status, Request.QueryString["status"] ?? "1");
            }

            q.OrderByDesc(Post.Columns.Published);

            PostCollection tempPC = new PostCollection();
            tempPC.LoadAndCloseReader(q.ExecuteReader());

            PostCollection permissionsFilteredCount = new PostCollection();
            permissionsFilteredCount.AddRange(tempPC);

            foreach (Post p in tempPC)
            {
                if (!RolePermissionManager.GetPermissions(p.CategoryId, GraffitiUsers.Current).Read)
                    permissionsFilteredCount.Remove(p);
            }

            q.PageSize = 15;
            q.PageIndex = Int32.Parse(Request.QueryString["p"] ?? "1");

            PostCollection pc = new PostCollection();
            pc.LoadAndCloseReader(q.ExecuteReader());

            PostList.NoneItemsDataBound += new RepeaterItemEventHandler(PostList_NoneItemsDataBound);

            PostCollection permissionsFiltered = new PostCollection();
            permissionsFiltered.AddRange(pc);

            foreach (Post p in pc)
            {
                if (!RolePermissionManager.GetPermissions(p.CategoryId, GraffitiUsers.Current).Read)
                    permissionsFiltered.Remove(p);
            }

            PostList.DataSource = permissionsFiltered;
            PostList.DataBind();

            string catID = Request.QueryString["category"] ?? "0";
            string autID = Request.QueryString["author"] ?? "0";

            if(pc.Count > 0)
            {
                string qs = "?status=" + page;
                if(catID != "0")
                    qs += "&category=" + catID;
                if (autID != "0")
                    qs += "&author=" + autID;

                Pager.Text = Util.Pager(q.PageIndex, q.PageSize, permissionsFilteredCount.Count, null, qs);
            }

            SetCounts(Int32.Parse(catID));

            #region build the page title

            StringBuilder sb = new StringBuilder();

            sb.Append("Posts ");

            switch (page)
            {
                case "1":
                    sb.Append("Published ");
                    break;
                case "2":
                    sb.Append("Drafted ");
                    break;
                case "3":
                    sb.Append("Pending Review ");
                    break;
                case "4":
                    sb.Append("Requiring Changes ");
                    break;
                case "5":
                    sb.Append("Deleted ");
                    break;
            }

            sb.Append("in ");

            if (Request.QueryString["category"] != null)
            {
                CategoryCollection categories = new CategoryController().GetAllCachedCategories();

                Category temp = categories.Find(
                        delegate(Category c)
                        {
                            return c.Id == Int32.Parse(Request.QueryString["category"]);
                        });

                if (temp != null)
                    sb.Append(temp.Name);
            }
            else
            {
                sb.Append("All Categories");
            }

            if (!String.IsNullOrEmpty(author))
            {
                sb.Append(" for " + user.ProperName);
            }

            lblPageTitle.Text = sb.ToString();

            #endregion

            if(Request.QueryString["dstry"] != null)
            {
                PostUpdateStatus.Text = Server.UrlDecode(Request.QueryString["dstry"]) +
                                        " has been permanently deleted.";
                PostUpdateStatus.Type = StatusType.Success;

            }
        }
    }