public static bool CanViewControlPanel(IGraffitiUser user) { if (user == null) return false; if (GraffitiUsers.IsAdmin(user)) return true; foreach (string role in user.Roles) { foreach (RolePermissions rp in GetRolePermissions()) { if (rp.RoleName == role) { if (rp.HasEdit || rp.HasPublish) return true; } } foreach (RoleCategoryPermissions rcp in GetRoleCategoryPermissions()) { if (rcp.RoleName == role) { if (rcp.HasEdit || rcp.HasPublish) return true; } } } return false; }
private static string UpdateComment(XmlDocument doc, IGraffitiUser user) { int id = Int32.Parse(doc.SelectSingleNode("/comment").Attributes["id"].Value); Comment comment = new Comment(id); if(comment.IsNew) throw new Exception("Comment with id " + id + " does not exist. The REST API only supports updating existing comments at this time."); XmlNode node = doc.SelectSingleNode("/comment"); comment.Body = GetNodeValue(node.SelectSingleNode("body"), comment.Body); comment.Name = GetNodeValue(node.SelectSingleNode("name"), comment.Name); comment.IsPublished = GetNodeValue(node.SelectSingleNode("isPublished"), comment.IsPublished); comment.IsDeleted = GetNodeValue(node.SelectSingleNode("isDeleted"), comment.IsDeleted); comment.SpamScore = GetNodeValue(node.SelectSingleNode("spamScore"), comment.SpamScore); comment.Email = GetNodeValue(node.SelectSingleNode("email"), comment.Email); comment.WebSite = GetNodeValue(node.SelectSingleNode("webSite"), comment.WebSite); if (!RolePermissionManager.GetPermissions(comment.Post.CategoryId, user).Edit) throw new Exception("You do not have sufficient privileges to update this comment."); comment.Save(GraffitiUsers.Current.Name); return "<result id=\"" + id + "\">true</result>"; }
public static int CommitPost(Post p, IGraffitiUser user, bool isFeaturedPost, bool isFeaturedCategory) { Permission perm = RolePermissionManager.GetPermissions(p.CategoryId, user); bool isMan = perm.Publish; bool isEdit = GraffitiUsers.IsAdmin(user); if (isMan || isEdit) { p.IsPublished = (p.PostStatus == PostStatus.Publish); } else { p.IsPublished = false; if(p.PostStatus != PostStatus.Draft && p.PostStatus != PostStatus.PendingApproval) { p.PostStatus = PostStatus.Draft; } } p.ModifiedBy = user.Name; if(p.IsNew) //No VERSION WORK, just save it. { p.Version = 1; p.Save(user.Name,SiteSettings.CurrentUserTime); } else if(p.IsPublished) //Make a copy of the current post, then save this one. { Post old_Post = new Post(p.Id); //if(old_Post.PostStatus == PostStatus.Publish) VersionPost(old_Post); p.Version = GetNextVersionId(p.Id, p.Version); p.Save(user.Name); } else { p.Version = GetNextVersionId(p.Id, p.Version); VersionPost(p); Post.UpdatePostStatus(p.Id,p.PostStatus); } ProcessFeaturedPosts(p, user, isFeaturedPost, isFeaturedCategory); if(p.PostStatus == PostStatus.PendingApproval) SendPReqiresApprovalMessage(p,user); else if(p.PostStatus == PostStatus.RequiresChanges) SendRequestedChangesMessage(p,user); return p.Id; }
private static string DeleteComment(XmlDocument doc, IGraffitiUser user) { int id = Int32.Parse(doc.SelectSingleNode("/comment").Attributes["id"].Value); Comment comment = new Comment(id); if (comment.IsNew) throw new Exception("Comment with id " + id + " does not exist"); if (!RolePermissionManager.GetPermissions(comment.Post.CategoryId, user).Publish) throw new Exception("You do not have sufficient privileges to delete this comment."); Comment.Delete(id); return "<result id=\"" + id + "\">deleted</result>"; }
public static void SendPReqiresApprovalMessage(Post p, IGraffitiUser user) { List<IGraffitiUser> users = new List<IGraffitiUser>(); foreach(IGraffitiUser u in GraffitiUsers.GetUsers("*")) { if (GraffitiUsers.IsAdmin(u) || RolePermissionManager.GetPermissions(p.CategoryId, u).Publish) users.Add(u); } Macros m = new Macros(); EmailTemplateToolboxContext pttc = new EmailTemplateToolboxContext(); pttc.Put("sitesettings", SiteSettings.Get()); pttc.Put("post", p); pttc.Put("user", user); pttc.Put("macros", m); pttc.Put("home", m.FullUrl(new Urls().Home)); pttc.Put("adminUrl", m.FullUrl(VirtualPathUtility.ToAbsolute("~/graffiti-admin/posts/write/")) + "?id=" + p.Id + "&v=" + p.Version); string adminApprovalUrl = m.FullUrl(VirtualPathUtility.ToAbsolute("~/api/approve.ashx")) + "?key={0}&u={1}&id={2}&v={3}"; EmailTemplate template = new EmailTemplate(); template.Context = pttc; template.Subject = "You have content to approve: " + p.Title; template.TemplateName = "QueuedPost.view"; foreach (IGraffitiUser admin in users) { template.Context.Put("adminApprovalUrl", string.Format(adminApprovalUrl, admin.UniqueId, admin.Name, p.Id, p.Version)); try { template.To = admin.Email; Emailer.Send(template); //Emailer.Send("QueuedPost.view", admin.Email, "You have content to approve: " + p.Title, pttc); } catch(Exception ex) { Log.Error("Email Error", ex.Message); } } Log.Info("Post approval email", "{0} user(s) were sent an email to approve the post \"{1}\" (id: {2}).", users.Count,p.Title,p.Id); }
/// <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 static string DeleteComment(XmlDocument doc, IGraffitiUser user) { int id = Int32.Parse(doc.SelectSingleNode("/comment").Attributes["id"].Value); Comment comment = new Comment(id); if (comment.IsNew) { throw new Exception("Comment with id " + id + " does not exist"); } if (!RolePermissionManager.GetPermissions(comment.Post.CategoryId, user).Publish) { throw new Exception("You do not have sufficient privileges to delete this comment."); } Comment.Delete(id); return("<result id=\"" + id + "\">deleted</result>"); }
public static void SendRequestedChangesMessage(Post p, IGraffitiUser user) { List <IGraffitiUser> users = new List <IGraffitiUser>(); foreach (IGraffitiUser u in GraffitiUsers.GetUsers("*")) { if (GraffitiUsers.IsAdmin(u) || RolePermissionManager.GetPermissions(p.CategoryId, u).Publish) { users.Add(u); } } Macros m = new Macros(); EmailTemplateToolboxContext pttc = new EmailTemplateToolboxContext(); pttc.Put("sitesettings", SiteSettings.Get()); pttc.Put("post", p); pttc.Put("user", user); pttc.Put("macros", m); pttc.Put("home", m.FullUrl(new Urls().Home)); pttc.Put("adminUrl", m.FullUrl(VirtualPathUtility.ToAbsolute("~/graffiti-admin/posts/write/")) + "?id=" + p.Id + "&v=" + p.Version); EmailTemplate template = new EmailTemplate(); template.Context = pttc; template.To = p.User.Email; template.Subject = "Changes Requested: " + p.Title; template.TemplateName = "RequestChanges.view"; try { Emailer.Send(template); //Emailer.Send("RequestChanges.view", p.User.Email, "Changes Requested: " + p.Title, pttc); Log.Info("Post Changes Email", p.User.Email + " was sent an email requesting changes"); } catch (Exception ex) { Log.Error("Email Requested Changes Error", ex.Message); } }
protected override void HandleRequest(IGraffitiUser user, XmlTextWriter writer) { switch (Context.Request.HttpMethod.ToUpper()) { case "GET": GetComments(writer); break; case "POST": UpdateOrDeleteComment(writer, user); break; default: break; } }
protected override void BeforeValidate() { base.BeforeValidate(); //By default we allow no markup if (IsNew) { UniqueId = Guid.NewGuid(); Body = Util.ConvertTextToHTML(Body); IGraffitiUser gu = GraffitiUsers.Current; if (gu != null) { if (!DontChangeUser) { Name = gu.ProperName; WebSite = gu.WebSite; Email = gu.Email; IsPublished = true; UserName = gu.Name; } } else { if (!string.IsNullOrEmpty(WebSite)) { WebSite = HttpUtility.HtmlEncode(WebSite); } if (!string.IsNullOrEmpty(Email)) { Email = HttpUtility.HtmlEncode(Email); } Name = HttpUtility.HtmlEncode(Name); SpamScore = CommentSettings.ScoreComment(this, new Post(PostId)); IsPublished = SpamScore < CommentSettings.Get().SpamScore; } } }
void ga_AfterNewUser(IGraffitiUser user, EventArgs e) { // If users are added or updated, refresh the list of available creators in the custom dropdown field CustomFormSettings cfs = CustomFormSettings.Get(); if (cfs.Fields == null || cfs.Fields.Count == 0) { SetupCustomFields(); } else { CustomField creatorField = cfs.Fields.Find(field => Util.AreEqualIgnoreCase(field.Name, "Creator")); if (creatorField != null) { UpdateCreatorsFieldOptions(creatorField); cfs.Name = "-1"; cfs.Save(); } } }
public override void ProcessRequest(HttpContext context) { if (context.Request.QueryString["Username"] != null && context.Request.QueryString["Ticket"] != null) { IGraffitiUser user = GraffitiUsers.GetUser(context.Request.QueryString["Username"], true); if (user == null || user.UniqueId.ToString() != context.Request.QueryString["Ticket"] || user.UniqueId == Guid.Empty) { throw new InvalidOperationException("The upload form can only be used by users who are logged in"); } } else { IGraffitiUser user = GraffitiUsers.Current; if (user == null) { throw new InvalidOperationException("The upload form can only be used by users who are logged in"); } } base.ProcessRequest(context); }
public static bool CanViewControlPanel(IGraffitiUser user) { if (user == null) { return(false); } if (GraffitiUsers.IsAdmin(user)) { return(true); } foreach (string role in user.Roles) { foreach (RolePermissions rp in GetRolePermissions()) { if (rp.RoleName == role) { if (rp.HasEdit || rp.HasPublish) { return(true); } } } foreach (RoleCategoryPermissions rcp in GetRoleCategoryPermissions()) { if (rcp.RoleName == role) { if (rcp.HasEdit || rcp.HasPublish) { return(true); } } } } return(false); }
public MetaWeblog.UserInfo getUserInfo(string appKey, string username, string password) { if (ValidateUser(username, password)) { IGraffitiUser gu = GraffitiUsers.GetUser(username); UserInfo ui = new UserInfo(); ui.userid = gu.Name; ui.firstname = gu.ProperName; ui.lastname = ""; ui.email = gu.Email; ui.nickname = gu.ProperName; ui.url = gu.WebSite ?? new Macros().FullUrl(new Urls().Home); return(ui); } throw new XmlRpcFaultException(0, "User does not exist"); }
protected override void HandleRequest(IGraffitiUser user, XmlTextWriter writer) { switch (Context.Request.HttpMethod.ToUpper()) { case "GET": if(!String.IsNullOrEmpty(Context.Request.QueryString["revision"])) GetPostsForRevision(writer); else GetPosts(writer); break; case "POST": CreateUpdateDeletePost(writer, user); break; default: break; } }
public static bool IsAdmin(IGraffitiUser user) { return(IsUserInRole(user, AdminRole)); }
public void Save(IGraffitiUser user, string modifed_by) { User internal_User = user as User; internal_User.Save(modifed_by); }
/// <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); }
public static Permission GetPermissions(int categoryId, IGraffitiUser user, bool calledFromMultipleCategoryPage) { string[] roles; // if there is no users, setup the roles collection to be everyone if (user == null) { roles = new string[1] { GraffitiUsers.EveryoneRole }; } else // get the users roles roles = user.Roles; Permission p = new Permission(); // if the user is an admin, they have access to everything if(GraffitiUsers.IsAdmin(user)) { p.Read = true; p.Edit = true; p.Publish = true; return p; } // determines if category permissions are setup, which overrides individual role permissions bool setInCategoryPermissions = false; if (categoryId != -1 || calledFromMultipleCategoryPage) { foreach (string role in roles) { foreach (RoleCategoryPermissions rcp in GetRoleCategoryPermissions()) { if (rcp.RoleName == role) { if (rcp.CategoryId == categoryId || calledFromMultipleCategoryPage) { // only set it if it's false. if another permissions allowed this category, // the user has permissions if (!p.Read) p.Read = rcp.HasRead; if (!p.Edit) p.Edit = rcp.HasEdit; if (!p.Publish) p.Publish = rcp.HasPublish; } setInCategoryPermissions = true; } } } } if (!setInCategoryPermissions) { foreach (string role in roles) { foreach (RolePermissions rp in GetRolePermissions()) { if (rp.RoleName == role) { // only set it if it's false. if another permissions allowed, // the user has permissions if (!p.Read) p.Read = rp.HasRead; if (!p.Edit) p.Edit = rp.HasEdit; if (!p.Publish) p.Publish = rp.HasPublish; } } } } return p; }
public static string GetInClauseForReadPermissions(IGraffitiUser user) { StringBuilder sb = new StringBuilder(); sb.Append("("); bool first = true; foreach (Category c in new CategoryController().GetAllCachedCategories()) { if (GetPermissions(c.Id, user).Read) { if (first) { sb.Append(c.Id.ToString()); first = false; } else { sb.Append(","); sb.Append(c.Id.ToString()); } } } sb.Append(")"); return sb.ToString(); }
public void DeleteUser(IGraffitiUser user) { throw new NotImplementedException("The ASPNetGraffitiUserController does not support deleting users."); }
public void ProcessRequest(HttpContext context) { if (context.Request.RequestType != "POST") { context.Response.StatusCode = 403; context.Response.StatusDescription = "Forbidden"; context.Response.End(); return; } context.Response.ContentType = "text/plain"; try { IGraffitiUser currentUser = GraffitiUsers.Current; if (!context.Request.IsAuthenticated || currentUser == null || !GraffitiUsers.IsAdmin(currentUser)) { throw new SecurityException("Please log in using an administrative account before setting up Graffiti-UserGroups."); } switch (context.Request.QueryString["command"]) { case "create-event-category": CreateCategory <EventPlugin>(); break; case "configure-event-plugin": ConfigurePlugin <EventPlugin>(); break; case "enable-event-plugin": EnablePlugin <EventPlugin>(); break; case "create-sample-events": CreateSampleEvents(10, currentUser); break; case "create-registration-post": CreateRegistrationPost(currentUser); break; case "create-talk-category": CreateCategory <TalkPlugin>(); break; case "configure-talk-plugin": ConfigurePlugin <TalkPlugin>(); break; case "enable-talk-plugin": EnablePlugin <TalkPlugin>(); break; case "create-sample-talks": CreateSampleTalks(10, currentUser); break; case "create-navigation-links": CreateNavigationLink <EventPlugin>(); CreateNavigationLink <TalkPlugin>(); CreateNavigationLink(RegisterPostTitle); break; case "load-navigation": context.Response.Write(RenderNavigation()); break; default: throw new InvalidOperationException(String.Format("Unknown command '{0}'", context.Request.QueryString["command"])); } } catch (Exception ex) { Log.Error(String.Format("{0}: Could not process request", GetType().Name), ex.ToString()); context.Response.StatusCode = 500; context.Response.StatusDescription = "Internal server error"; context.Response.Clear(); context.Response.Write(ex.Message); } }
public void DeleteUser(IGraffitiUser user) { User.Destroy(User.Columns.UniqueId, user.UniqueId); }
public void Save(IGraffitiUser user, string modifed_by) { ASPNetMembershipGraffitiUser the_User = user as ASPNetMembershipGraffitiUser; the_User.Save(); }
private static string CreateUpdatePost(XmlDocument doc, IGraffitiUser user) { Post post = null; XmlAttribute postidAttribute = doc.SelectSingleNode("/post").Attributes["id"]; if (postidAttribute == null) post = new Post(); else { int pid = Int32.Parse(postidAttribute.Value); if (pid > 0) post = new Post(pid); else post = new Post(); } XmlNode node = doc.SelectSingleNode("/post"); if (GraffitiUsers.IsUserInRole(user.Name, GraffitiUsers.AdminRole)) { XmlNode usernameNode = node.SelectSingleNode("author"); if (usernameNode != null && !string.IsNullOrEmpty(usernameNode.Value)) { post.UserName = GraffitiUsers.GetUser(usernameNode.Value).Name; } } if (string.IsNullOrEmpty(post.UserName) && post.IsNew) post.UserName = user.Name; post.PostBody = GetNodeValue(node.SelectSingleNode("postBody"), null); if (string.IsNullOrEmpty(post.PostBody)) throw new RESTConflict("The Post body element is missing and is required"); post.CategoryId = GetNodeValue(node.SelectSingleNode("categoryId"), -1); if(post.CategoryId <= 0) throw new RESTConflict("The category element is missing (or has an invalid value) and is required"); post.Title = GetNodeValue(node.SelectSingleNode("title"), null); if (string.IsNullOrEmpty(post.Title)) throw new RESTConflict("The title element is missing and is required"); post.ExtendedBody = GetNodeValue(node.SelectSingleNode("extendedBody"), null); XmlNode publishedDateNode = node.SelectSingleNode("publishedDate"); if (publishedDateNode != null && !string.IsNullOrEmpty(publishedDateNode.InnerText) && DateTime.Parse(publishedDateNode.InnerText) > new DateTime(2000, 1, 1)) post.Published = DateTime.Parse(publishedDateNode.InnerText); else if (post.IsNew) post.Published = SiteSettings.CurrentUserTime; post.Name = GetNodeValue(node.SelectSingleNode("name"), post.Name); post.Status = GetNodeValue(node.SelectSingleNode("status"), post.IsNew ? (int)PostStatus.Draft : post.Status); post.TagList = GetNodeValue(node.SelectSingleNode("tags"), null); post.ContentType = GetNodeValue(node.SelectSingleNode("contenttype"), null); post.SortOrder = GetNodeValue(node.SelectSingleNode("sortOrder"), post.SortOrder); post.HomeSortOrder = GetNodeValue(node.SelectSingleNode("homeSortOrder"), post.HomeSortOrder); post.MetaDescription = GetNodeValue(node.SelectSingleNode("metaDescription"), post.MetaDescription); post.MetaKeywords = GetNodeValue(node.SelectSingleNode("metaKeywords"), post.MetaKeywords); post.IsHome = GetNodeValue(node.SelectSingleNode("isHome"), post.IsHome); post.EnableComments = GetNodeValue(node.SelectSingleNode("enableComments"), post.EnableComments); XmlNodeList customFields = node.SelectNodes("customFields/customField"); foreach (XmlNode cNode in customFields) { post[cNode.Attributes["key"].Value] = cNode.InnerText; } Permission perm = RolePermissionManager.GetPermissions(post.CategoryId, user); if (GraffitiUsers.IsAdmin(user) || perm.Publish) post.IsDeleted = GetNodeValue(node.SelectSingleNode("isDeleted"), post.IsDeleted); int id = PostRevisionManager.CommitPost(post, user, SiteSettings.Get().FeaturedId == post.Id, post.Category.FeaturedId == post.Id); return string.Format("<result id=\"{0}\">true</result>", id); }
private void CreateUpdateDeletePost(XmlTextWriter writer, IGraffitiUser user) { XmlDocument doc = new XmlDocument(); doc.Load(Request.InputStream); if (Request.Headers["Graffiti-Method"] != "DELETE") { writer.WriteRaw(CreateUpdatePost(doc,user)); } else { XmlAttribute postidAttribute = doc.SelectSingleNode("/post").Attributes["id"]; int pid = Int32.Parse(postidAttribute.Value); Post p = new Post(pid); Permission perm = RolePermissionManager.GetPermissions(p.CategoryId, user); if (GraffitiUsers.IsAdmin(user) || perm.Publish) writer.WriteRaw(DeletePost(doc)); else UnuathorizedRequest(); } }
public static void SendRequestedChangesMessage(Post p, IGraffitiUser user) { List<IGraffitiUser> users = new List<IGraffitiUser>(); foreach (IGraffitiUser u in GraffitiUsers.GetUsers("*")) { if (GraffitiUsers.IsAdmin(u) || RolePermissionManager.GetPermissions(p.CategoryId, u).Publish) users.Add(u); } Macros m = new Macros(); EmailTemplateToolboxContext pttc = new EmailTemplateToolboxContext(); pttc.Put("sitesettings", SiteSettings.Get()); pttc.Put("post", p); pttc.Put("user", user); pttc.Put("macros", m); pttc.Put("home", m.FullUrl(new Urls().Home)); pttc.Put("adminUrl", m.FullUrl(VirtualPathUtility.ToAbsolute("~/graffiti-admin/posts/write/")) + "?id=" + p.Id + "&v=" + p.Version); EmailTemplate template = new EmailTemplate(); template.Context = pttc; template.To = p.User.Email; template.Subject = "Changes Requested: " + p.Title; template.TemplateName = "RequestChanges.view"; try { Emailer.Send(template); //Emailer.Send("RequestChanges.view", p.User.Email, "Changes Requested: " + p.Title, pttc); Log.Info("Post Changes Email", p.User.Email + " was sent an email requesting changes"); } catch (Exception ex) { Log.Error("Email Requested Changes Error", ex.Message); } }
private static Graffiti.Core.Category AddOrFetchCategory(string name, IGraffitiUser user) { int index = name.IndexOf(">"); if (index > -1) { string parentName = name.Substring(0, index).Trim(); string childName = name.Substring(index+1).Trim(); Graffiti.Core.Category parent = new CategoryController().GetCachedCategory(parentName, true); if (parent != null) { foreach (Graffiti.Core.Category childCategory in parent.Children) { if (Util.AreEqualIgnoreCase(childCategory.Name, childName)) return childCategory; } if (GraffitiUsers.IsAdmin(user)) { Core.Category child = new Core.Category(); child.Name = HttpUtility.HtmlEncode(childName); child.ParentId = parent.Id; child.Save(); return child; } } else { if (GraffitiUsers.IsAdmin(user)) { parent = new Core.Category(); parent.Name = HttpUtility.HtmlEncode(parentName); parent.Save(); Core.Category child = new Core.Category(); child.Name = HttpUtility.HtmlEncode(childName); child.ParentId = parent.Id; child.Save(); return child; } } } else { Core.Category category = new CategoryController().GetCachedCategory(name, true); if (category == null) { if (GraffitiUsers.IsAdmin(user)) { category = new Core.Category(); category.Name = name; category.Save(); } } return category; } Log.Warn("Categories", "The user {0} does not have permission to create the category {1}", user.ProperName,HttpUtility.HtmlEncode(name)); throw new Exception("You do not have permission to create a new category or sub-category"); }
protected void publish_return_click(object sender, EventArgs e) { try { if (!IsValid) { return; } IGraffitiUser user = GraffitiUsers.Current; ListItem catItem = CategoryList.SelectedItem; if (catItem.Value == "-1" && String.IsNullOrEmpty(newCategory.Text)) { SetMessage("Please enter a name for the new Category.", StatusType.Error); return; } string extenedBody = txtContent_extend.Text; string postBody = txtContent.Text; if (string.IsNullOrEmpty(postBody)) { SetMessage("Please enter a post body.", StatusType.Warning); return; } Category c = new Category(); if (catItem.Value == "-1") { try { Category temp = new Category(); temp.Name = newCategory.Text; temp.Save(); c = temp; CategoryController.Reset(); } catch (Exception ex) { SetMessage("The category could not be created. Reason: " + ex.Message, StatusType.Error); } } else { c = new CategoryController().GetCachedCategory(Int32.Parse(catItem.Value), false); } string pid = Request.QueryString["id"]; Post p = pid == null ? new Post() : new Post(pid); if (p.IsNew) { p["where"] = "web"; p.UserName = user.Name; if (Request.Form["dateChangeFlag"] == "true") { p.Published = PublishDate.DateTime; } else { p.Published = DateTime.Now.AddHours(SiteSettings.Get().TimeZoneOffSet); } } else { p.Published = PublishDate.DateTime; } p.ModifiedOn = DateTime.Now.AddHours(SiteSettings.Get().TimeZoneOffSet); p.PostBody = postBody; if (string.IsNullOrEmpty(extenedBody) || extenedBody == "<p></p>" || extenedBody == "<p> </p>" || extenedBody == "<br />\r\n") { p.ExtendedBody = null; } else { p.ExtendedBody = extenedBody; } p.Title = Server.HtmlEncode(txtTitle.Text); p.EnableComments = EnableComments.Checked; p.Name = txtName.Text; p.TagList = txtTags.Text.Trim(); p.ContentType = "text/html"; p.CategoryId = c.Id; p.Notes = txtNotes.Text; p.ImageUrl = postImage.Text; p.MetaKeywords = Server.HtmlEncode(txtKeywords.Text.Trim()); p.MetaDescription = Server.HtmlEncode(txtMetaScription.Text.Trim()); p.IsHome = HomeSortOverride.Checked; p.PostStatus = (PostStatus)Enum.Parse(typeof(PostStatus), Request.Form[PublishStatus.UniqueID]); CustomFormSettings cfs = CustomFormSettings.Get(c); if (cfs.HasFields) { foreach (CustomField cf in cfs.Fields) { if (cf.FieldType == FieldType.CheckBox && Request.Form[cf.Id.ToString()] == null) { p[cf.Name] = null; // false.ToString(); } else if (cf.FieldType == FieldType.DateTime && Request.Form[cf.Id.ToString()].IndexOf("_") > -1) { p[cf.Name] = null; } else { p[cf.Name] = Request.Form[cf.Id.ToString()]; } } } if (HasDuplicateName(p)) { SetMessage("A post in the selected category already exists with the same name.", StatusType.Error); return; } PostRevisionManager.CommitPost(p, user, FeaturedSite.Checked, FeaturedCategory.Checked); string CatQuery = (Request.QueryString["category"] == null) ? null : (p.Status == 1) ? "&category=" + p.CategoryId : "&category=" + Request.QueryString["category"]; string AuthQuery = (Request.QueryString["author"] == null) ? null : "&author=" + Request.QueryString["author"]; Response.Redirect("~/graffiti-admin/posts/" + "?id=" + p.Id + "&status=" + p.Status + CatQuery + AuthQuery); } catch (Exception ex) { SetMessage("Your post could not be saved. Reason: " + ex.Message, StatusType.Error); } }
protected override void HandleRequest(IGraffitiUser user, XmlTextWriter writer) { switch (Context.Request.HttpMethod.ToUpper()) { case "GET": CategoryController controller = new CategoryController(); CategoryCollection cc = null; int count = 1; if(Request.QueryString["id"] != null) { Category category = controller.GetCachedCategory(Int32.Parse(Request.QueryString["id"]), false); cc = new CategoryCollection(); cc.Add(category); } else if (Request.QueryString["name"] != null) { Category category = controller.GetCachedCategory(Request.QueryString["name"], false); cc = new CategoryCollection(); cc.Add(category); } else { cc = controller.GetAllTopLevelCachedCategories(); count = controller.GetAllCachedCategories().Count; } writer.WriteStartElement("categories"); writer.WriteAttributeString("pageIndex", "1"); writer.WriteAttributeString("pageSize", count.ToString() ); writer.WriteAttributeString("totalCategories", count.ToString()); foreach(Category category in cc) { WriteCategoryToXML(category, writer); } writer.WriteEndElement(); writer.Close(); break; case "POST": XmlDocument doc = new XmlDocument(); doc.Load(Request.InputStream); if (Request.Headers["Graffiti-Method"] != "DELETE") { if (GraffitiUsers.IsAdmin(user)) { string xml = CreateUpdateCategory(doc); writer.WriteRaw(xml); } else { UnuathorizedRequest(); } } else { XmlAttribute categoryIdAttribute = doc.SelectSingleNode("/category").Attributes["id"]; foreach (Post p in PostCollection.FetchAll()) { if (p.CategoryId == Int32.Parse(categoryIdAttribute.Value)) { if (p.IsDeleted) { Post.DestroyDeletedPost(p.Id); } else { Response.StatusCode = 500; writer.WriteRaw("<error>You can not delete a category that contains post.</error>"); return; } } } Category.Destroy(Int32.Parse(categoryIdAttribute.Value)); CategoryController.Reset(); writer.WriteRaw("<result id=\"" + Int32.Parse(categoryIdAttribute.Value) + "\">deleted</result>"); } break; default: break; } }
protected virtual bool IsValidAccess(IGraffitiUser user) { return(GraffitiUsers.IsAdmin(user)); }
protected virtual bool IsValidAccess(IGraffitiUser user) { return GraffitiUsers.IsAdmin(user); }
/// <summary> /// Executes the user is known event. /// </summary> /// <param name="user"></param> public void ExecuteUserIsKnown(IGraffitiUser user) { ExecuteUserEvent(UserIsKnownObject, user); }
public static Permission GetPermissions(int categoryId, IGraffitiUser user) { return GetPermissions(categoryId, user, false); }
/// <summary> /// Executes the BeforeUserUpdate Event /// </summary> /// <param name="user"></param> internal void ExecuteUserBeforeUserUpdate(IGraffitiUser user) { ExecuteUserEvent(BeforeUserUpdateObject, user); }
protected abstract void HandleRequest(IGraffitiUser user, XmlTextWriter writer);
/// <summary> /// Determines if the logged in user can view the control panel /// </summary> /// <param name="user"></param> /// <returns></returns> public bool CanViewControlPanel(IGraffitiUser user) { return RolePermissionManager.CanViewControlPanel(user); }
private static void ProcessFeaturedPosts(Post p, IGraffitiUser user, bool isFeaturedPost, bool isFeaturedCategory) { SiteSettings settings = SiteSettings.Get(); if (p.IsPublished && isFeaturedPost) { settings.FeaturedId = p.Id; settings.Save(); } else if (settings.FeaturedId == p.Id) { settings.FeaturedId = -1; settings.Save(); } Category c = p.Category; if (p.IsPublished && isFeaturedCategory) { c.FeaturedId = p.Id; c.Save(user.Name); } else if (c.FeaturedId == p.Id) { c.FeaturedId = -1; c.Save(user.Name); } }
protected void Page_Load(object sender, EventArgs e) { NameValueCollection nvcCustomFields = null; IGraffitiUser user = GraffitiUsers.Current; bool isAdmin = GraffitiUsers.IsAdmin(user); CategoryController cc = new CategoryController(); Category uncategorized = cc.GetCachedCategory(CategoryController.UncategorizedName, false); Post post = null; if (Request.QueryString["id"] != null) { post = new Post(Request.QueryString["id"]); } ProcessCategoryDropdownList(cc, isAdmin, uncategorized); if (!IsPostBack) { ClientScripts.RegisterScriptsForDateTimeSelector(this); Util.CanWriteRedirect(Context); SetDefaultFormValues(isAdmin); if (Request.QueryString["nid"] != null) { post = new Post(Request.QueryString["nid"]); if (post.IsLoaded) { if (isAdmin) { SetMessage("Your post was saved. View: <a href=\"" + post.Url + "\">" + post.Title + "</a>.", StatusType.Success); } else { SetMessage( "Your post was saved. However, since you do not have permission to publish new content, it will need to be approved before it is viewable.", StatusType.Success); } FormWrapper.Visible = false; } } if (post != null) { bool isOriginalPublished = post.IsPublished; int currentVersionNumber = post.Version; VersionStoreCollection vsc = VersionStore.GetVersionHistory(post.Id); if (vsc.Count > 0) { var the_Posts = new List <Post>(); foreach (VersionStore vs in vsc) { the_Posts.Add(ObjectManager.ConvertToObject <Post>(vs.Data)); } the_Posts.Add(post); the_Posts.Sort(delegate(Post p1, Post p2) { return(Comparer <int> .Default.Compare(p2.Version, p1.Version)); }); string versionHtml = "<div style=\"width: 280px; overflow: hidden; padding: 6px 0; border-bottom: 1px solid #ccc;\"><b>Revision {0}</b> ({1})<div>by {2}</div><div style=\"font-style: italic;\">{3}</div></div>"; string versionText = "Revision {0}"; foreach (Post px in the_Posts) { VersionHistory.Items.Add( new DropDownListItem( string.Format(versionHtml, px.Version, px.ModifiedOn.ToString("dd-MMM-yyyy"), GraffitiUsers.GetUser(px.ModifiedBy).ProperName, px.Notes), string.Format(versionText, px.Version), px.Version.ToString())); } int versionToEdit = Int32.Parse(Request.QueryString["v"] ?? "-1"); if (versionToEdit > -1) { foreach (Post px in the_Posts) { if (px.Version == versionToEdit) { post = px; // add logic to change category if it was deleted here CategoryCollection cats = new CategoryController().GetCachedCategories(); Category temp = cats.Find( delegate(Category c) { return(c.Id == post.CategoryId); }); if (temp == null && post.CategoryId != 1) { post.CategoryId = uncategorized.Id; SetMessage( "The category ID on this post revision could not be located. It has been marked as Uncategorized. ", StatusType.Warning); } break; } } } else { post = the_Posts[0]; } VersionHistoryArea.Visible = true; VersionHistory.SelectedValue = post.Version.ToString(); VersionHistory.Attributes["onchange"] = "window.location = '" + VirtualPathUtility.ToAbsolute("~/graffiti-admin/posts/write/") + "?id=" + Request.QueryString["id"] + "&v=' + this.options[this.selectedIndex].value;"; } if (post.Id > 0) { nvcCustomFields = post.CustomFields(); txtTitle.Text = Server.HtmlDecode(post.Title); txtContent.Text = post.PostBody; txtContent_extend.Text = post.ExtendedBody; txtTags.Text = post.TagList; txtName.Text = Util.UnCleanForUrl(post.Name); EnableComments.Checked = post.EnableComments; PublishDate.DateTime = post.Published; txtNotes.Text = post.Notes; postImage.Text = post.ImageUrl; FeaturedSite.Checked = (post.Id == SiteSettings.Get().FeaturedId); FeaturedCategory.Checked = (post.Id == post.Category.FeaturedId); txtKeywords.Text = Server.HtmlDecode(post.MetaKeywords ?? string.Empty); txtMetaScription.Text = Server.HtmlDecode(post.MetaDescription ?? string.Empty); HomeSortOverride.Checked = post.IsHome; ListItem li = CategoryList.Items.FindByValue(post.CategoryId.ToString()); if (li != null) { CategoryList.SelectedIndex = CategoryList.Items.IndexOf(li); } else { CategoryList.SelectedIndex = CategoryList.Items.IndexOf(CategoryList.Items.FindByValue(uncategorized.Id.ToString())); } li = PublishStatus.Items.FindByValue(post.Status.ToString()); if (li != null && post.Status != (int)PostStatus.PendingApproval && post.Status != (int)PostStatus.RequiresChanges) { PublishStatus.SelectedIndex = PublishStatus.Items.IndexOf(li); } else if (post.Status == (int)PostStatus.PendingApproval || post.Status == (int)PostStatus.RequiresChanges) { // turn published on if it is in req changes ListItem li2 = PublishStatus.Items.FindByValue(Convert.ToString((int)PostStatus.Publish)); if (li2 != null) { PublishStatus.SelectedIndex = PublishStatus.Items.IndexOf(li2); } } if (post.Version != currentVersionNumber && !isOriginalPublished) { SetMessage("You are editing an unpublished revision of this post.", StatusType.Warning); } else if (post.Version != currentVersionNumber && isOriginalPublished) { SetMessage( "The post your are editing has been published. However, the revision you are editing has not been published.", StatusType.Warning); } else if (!isOriginalPublished) { SetMessage("You are editing an unpublished revision of this post.", StatusType.Warning); } } else { FormWrapper.Visible = false; SetMessage("The post with the id " + Request.QueryString["id"] + " could not be found.", StatusType.Warning); } } else { ListItem liUncat = CategoryList.Items.FindByText(CategoryController.UncategorizedName); if (liUncat != null) { CategoryList.SelectedIndex = CategoryList.Items.IndexOf(liUncat); } } } if (FormWrapper.Visible) { NavigationConfirmation.RegisterPage(this); NavigationConfirmation.RegisterControlForCancel(Publish_Button); Page.ClientScript.RegisterStartupScript(GetType(), "Writer-Page-StartUp", "$(document).ready(function() { var eBody = $('#extended_body')[0]; " + (!string.IsNullOrEmpty(txtContent_extend.Text) ? "eBody.style.position = 'static'; eBody.style.visibility = 'visible';" : "eBody.style.position = 'absolute'; eBody.style.visibility = 'hidden';") + "categoryChanged($('#" + CategoryList.ClientID + "')[0]); Publish_Status_Change();});", true); Page.ClientScript.RegisterHiddenField("dateChangeFlag", "false"); } CustomFormSettings cfs = CustomFormSettings.Get(int.Parse(CategoryList.SelectedItem.Value)); if (cfs.HasFields) { if (nvcCustomFields == null) { nvcCustomFields = new NameValueCollection(); foreach (CustomField cf in cfs.Fields) { if (Request.Form[cf.Id.ToString()] != null) { nvcCustomFields[cf.Name] = Request.Form[cf.Id.ToString()]; } } } bool isNewPost = (post != null) && (post.Id < 1); the_CustomFields.Text = cfs.GetHtmlForm(nvcCustomFields, isNewPost); } else { CustomFieldsTab.Tab.Enabled = false; the_CustomFields.Text = ""; } PublishStatus.Attributes.Add("onchange", "Publish_Status_Change();"); }
//public void ExecuteBeforeNewUser(IGraffitiUser user) //{ // ExecuteUserEvent(BeforeNewUserObject, user); //} /// <summary> /// Executes the AfterNewUser Event /// </summary> /// <param name="user"></param> internal void ExecuteAfterNewUser(IGraffitiUser user) { ExecuteUserEvent(AfterNewUserObject, user); }
protected override void HandleRequest(IGraffitiUser user, XmlTextWriter writer) { switch (Context.Request.HttpMethod.ToUpper()) { case "GET": CategoryController controller = new CategoryController(); CategoryCollection cc = null; int count = 1; if (Request.QueryString["id"] != null) { Category category = controller.GetCachedCategory(Int32.Parse(Request.QueryString["id"]), false); cc = new CategoryCollection(); cc.Add(category); } else if (Request.QueryString["name"] != null) { Category category = controller.GetCachedCategory(Request.QueryString["name"], false); cc = new CategoryCollection(); cc.Add(category); } else { cc = controller.GetAllTopLevelCachedCategories(); count = controller.GetAllCachedCategories().Count; } writer.WriteStartElement("categories"); writer.WriteAttributeString("pageIndex", "1"); writer.WriteAttributeString("pageSize", count.ToString()); writer.WriteAttributeString("totalCategories", count.ToString()); foreach (Category category in cc) { WriteCategoryToXML(category, writer); } writer.WriteEndElement(); writer.Close(); break; case "POST": XmlDocument doc = new XmlDocument(); doc.Load(Request.InputStream); if (Request.Headers["Graffiti-Method"] != "DELETE") { if (GraffitiUsers.IsAdmin(user)) { string xml = CreateUpdateCategory(doc); writer.WriteRaw(xml); } else { UnuathorizedRequest(); } } else { XmlAttribute categoryIdAttribute = doc.SelectSingleNode("/category").Attributes["id"]; foreach (Post p in PostCollection.FetchAll()) { if (p.CategoryId == Int32.Parse(categoryIdAttribute.Value)) { if (p.IsDeleted) { Post.DestroyDeletedPost(p.Id); } else { Response.StatusCode = 500; writer.WriteRaw("<error>You can not delete a category that contains post.</error>"); return; } } } Category.Destroy(Int32.Parse(categoryIdAttribute.Value)); CategoryController.Reset(); writer.WriteRaw("<result id=\"" + Int32.Parse(categoryIdAttribute.Value) + "\">deleted</result>"); } break; default: break; } }
/// <summary> /// Executes the AfterUserUpdate event /// </summary> /// <param name="user"></param> internal void ExecuteAfterUserUpdated(IGraffitiUser user) { ExecuteUserEvent(AfterUserUpdateObject, user); }
private static string CreateUpdatePost(XmlDocument doc, IGraffitiUser user) { Post post = null; XmlAttribute postidAttribute = doc.SelectSingleNode("/post").Attributes["id"]; if (postidAttribute == null) { post = new Post(); } else { int pid = Int32.Parse(postidAttribute.Value); if (pid > 0) { post = new Post(pid); } else { post = new Post(); } } XmlNode node = doc.SelectSingleNode("/post"); if (GraffitiUsers.IsUserInRole(user.Name, GraffitiUsers.AdminRole)) { XmlNode usernameNode = node.SelectSingleNode("author"); if (usernameNode != null && !string.IsNullOrEmpty(usernameNode.Value)) { post.UserName = GraffitiUsers.GetUser(usernameNode.Value).Name; } } if (string.IsNullOrEmpty(post.UserName) && post.IsNew) { post.UserName = user.Name; } post.PostBody = GetNodeValue(node.SelectSingleNode("postBody"), null); if (string.IsNullOrEmpty(post.PostBody)) { throw new RESTConflict("The Post body element is missing and is required"); } post.CategoryId = GetNodeValue(node.SelectSingleNode("categoryId"), -1); if (post.CategoryId <= 0) { throw new RESTConflict("The category element is missing (or has an invalid value) and is required"); } post.Title = GetNodeValue(node.SelectSingleNode("title"), null); if (string.IsNullOrEmpty(post.Title)) { throw new RESTConflict("The title element is missing and is required"); } post.ExtendedBody = GetNodeValue(node.SelectSingleNode("extendedBody"), null); XmlNode publishedDateNode = node.SelectSingleNode("publishedDate"); if (publishedDateNode != null && !string.IsNullOrEmpty(publishedDateNode.InnerText) && DateTime.Parse(publishedDateNode.InnerText) > new DateTime(2000, 1, 1)) { post.Published = DateTime.Parse(publishedDateNode.InnerText); } else if (post.IsNew) { post.Published = SiteSettings.CurrentUserTime; } post.Name = GetNodeValue(node.SelectSingleNode("name"), post.Name); post.Status = GetNodeValue(node.SelectSingleNode("status"), post.IsNew ? (int)PostStatus.Draft : post.Status); post.TagList = GetNodeValue(node.SelectSingleNode("tags"), null); post.ContentType = GetNodeValue(node.SelectSingleNode("contenttype"), null); post.SortOrder = GetNodeValue(node.SelectSingleNode("sortOrder"), post.SortOrder); post.HomeSortOrder = GetNodeValue(node.SelectSingleNode("homeSortOrder"), post.HomeSortOrder); post.MetaDescription = GetNodeValue(node.SelectSingleNode("metaDescription"), post.MetaDescription); post.MetaKeywords = GetNodeValue(node.SelectSingleNode("metaKeywords"), post.MetaKeywords); post.IsHome = GetNodeValue(node.SelectSingleNode("isHome"), post.IsHome); post.EnableComments = GetNodeValue(node.SelectSingleNode("enableComments"), post.EnableComments); XmlNodeList customFields = node.SelectNodes("customFields/customField"); foreach (XmlNode cNode in customFields) { post[cNode.Attributes["key"].Value] = cNode.InnerText; } Permission perm = RolePermissionManager.GetPermissions(post.CategoryId, user); if (GraffitiUsers.IsAdmin(user) || perm.Publish) { post.IsDeleted = GetNodeValue(node.SelectSingleNode("isDeleted"), post.IsDeleted); } int id = PostRevisionManager.CommitPost(post, user, SiteSettings.Get().FeaturedId == post.Id, post.Category.FeaturedId == post.Id); return(string.Format("<result id=\"{0}\">true</result>", id)); }
private void ExecuteUserEvent(object key, IGraffitiUser user) { UserEventHandler uv = Events[key] as UserEventHandler; if (uv != null) { uv(user, EventArgs.Empty); } }
protected void Page_Load(object sender, EventArgs e) { LiHyperLink.SetNameToCompare(Context, "UserManagement"); IGraffitiUser currentUser = GraffitiUsers.Current; if (Request.QueryString["user"] != null) { if (!IsPostBack) { user = GraffitiUsers.GetUser(Request.QueryString["user"]); if (user == null) throw new Exception("This user does not exist or cannot be edited."); if (!GraffitiUsers.IsAdmin(currentUser) && user.Name != currentUser.Name) throw new SecurityException("You do not have permission to edit this user"); if (Request.QueryString["new"] != null && !IsPostBack) { Message.Text = "The user <strong>" + user.Name + "</strong> was created."; Message.Type = StatusType.Success; } PageText.Text = "Update " + user.ProperName + "'s profile."; AdminUserLinks.Visible = true; PasswordLink.NavigateUrl = string.Format("~/graffiti-admin/user-management/users/changepassword.aspx?user={0}", Request.QueryString["user"]); if (GraffitiUsers.CanRenameUsers && GraffitiUsers.IsAdmin(GraffitiUsers.Current)) { AdminUserLinksDelim.Visible = true; RenameLink.Visible = true; RenameLink.NavigateUrl = string.Format("javascript:Telligent_Modal.Open('RenameUser.aspx?user={0}', 400, 200, null);", Request.QueryString["user"]); } txtExistingUserName.Text = Server.HtmlDecode(user.Name); txtProperName.Text = Server.HtmlDecode(user.ProperName); txtExistingEmail.Text = user.Email; txtAvatar.Text = user.Avatar; Editor.Text = user.Bio; txtWebsite.Text = string.IsNullOrEmpty(user.WebSite) ? new Macros().FullUrl(new Urls().Home) : Server.HtmlEncode(user.WebSite); bool isAdmin = GraffitiUsers.IsUserInRole(GraffitiUsers.Current.Name, GraffitiUsers.AdminRole); role_section.Visible = isAdmin; AllRoles.Visible = isAdmin; if (!isAdmin) Cancel_Edit.NavigateUrl = "~/graffiti-admin/"; if (isAdmin) { RolePermissionsCollection rp = RolePermissionManager.GetRolePermissions(); RolePermissionsCollection newrp = new RolePermissionsCollection(); newrp.AddRange(rp); RolePermissions temp = newrp.Find(delegate(RolePermissions r) { return r.RoleName == GraffitiUsers.EveryoneRole; }); if (temp != null) newrp.Remove(temp); newrp.Sort(delegate(RolePermissions rp1, RolePermissions rp2) { return Comparer<string>.Default.Compare(rp1.RoleName, rp2.RoleName); }); Roles.DataSource = newrp; Roles.DataBind(); foreach (string role in user.Roles) { if (role == GraffitiUsers.AdminRole) { chkAdmin.Checked = true; if (GraffitiUsers.Current.Name == user.Name) chkAdmin.Enabled = false; } } } } new_user_container.Visible = false; User_List.Visible = false; user_edit_form.Visible = true; } else { if (!GraffitiUsers.IsUserInRole(currentUser.Name, GraffitiUsers.AdminRole)) Response.Redirect("?user="******"*"); User_List.DataSource = users; User_List.DataBind(); // filter out everyone if they are not a content publisher for licensing List<IGraffitiUser> filteredUsers = new List<IGraffitiUser>(); filteredUsers.AddRange(users); bool isEveryonePublisher = RolePermissionManager.IsEveryoneAContentPublisher(); if (!isEveryonePublisher) { foreach (IGraffitiUser user in users) { if (user.Roles != null && user.Roles[0] == GraffitiUsers.EveryoneRole) filteredUsers.Remove(user); } } } }
private static Graffiti.Core.Category AddOrFetchCategory(string name, IGraffitiUser user) { int index = name.IndexOf(">"); if (index > -1) { string parentName = name.Substring(0, index).Trim(); string childName = name.Substring(index + 1).Trim(); Graffiti.Core.Category parent = new CategoryController().GetCachedCategory(parentName, true); if (parent != null) { foreach (Graffiti.Core.Category childCategory in parent.Children) { if (Util.AreEqualIgnoreCase(childCategory.Name, childName)) { return(childCategory); } } if (GraffitiUsers.IsAdmin(user)) { Core.Category child = new Core.Category(); child.Name = HttpUtility.HtmlEncode(childName); child.ParentId = parent.Id; child.Save(); return(child); } } else { if (GraffitiUsers.IsAdmin(user)) { parent = new Core.Category(); parent.Name = HttpUtility.HtmlEncode(parentName); parent.Save(); Core.Category child = new Core.Category(); child.Name = HttpUtility.HtmlEncode(childName); child.ParentId = parent.Id; child.Save(); return(child); } } } else { Core.Category category = new CategoryController().GetCachedCategory(name, true); if (category == null) { if (GraffitiUsers.IsAdmin(user)) { category = new Core.Category(); category.Name = name; category.Save(); } } return(category); } Log.Warn("Categories", "The user {0} does not have permission to create the category {1}", user.ProperName, HttpUtility.HtmlEncode(name)); throw new Exception("You do not have permission to create a new category or sub-category"); }
/// <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; }
public string newPost(string blogid, string username, string password, MetaWeblog.Post post, bool publish) { if (ValidateUser(username, password)) { IGraffitiUser user = GraffitiUsers.Current; Graffiti.Core.Post postToAdd = new Graffiti.Core.Post(); postToAdd.ContentType = "text/html"; postToAdd.PostStatus = (publish ? PostStatus.Publish : PostStatus.Draft); postToAdd.IsPublished = publish; postToAdd.PostBody = post.description; postToAdd.Title = post.title; postToAdd.TagList = post.GetTagList(); postToAdd.UserName = username; postToAdd.EnableComments = CommentSettings.Get().EnableCommentsDefault; if (post.categories != null && post.categories.Length > 0) { postToAdd.CategoryId = AddOrFetchCategory(post.categories[0], user).Id; } else { postToAdd.CategoryId = CategoryController.UnCategorizedId; } postToAdd.Name = post.GetSlug(); if (!string.IsNullOrEmpty(post.mt_text_more)) { postToAdd.ExtendedBody = post.mt_text_more; } // Get UserTime safely (some clients pass in a DateTime that is not valid) try { if (post.dateCreated != DateTime.MinValue) { DateTime dtUTC = post.dateCreated; DateTime dtLocal = dtUTC.ToLocalTime(); postToAdd.Published = dtLocal.AddHours(SiteSettings.Get().TimeZoneOffSet); } } catch { postToAdd.Published = DateTime.Now.AddHours(SiteSettings.Get().TimeZoneOffSet); } if (postToAdd.Published <= new DateTime(2000, 1, 1)) { postToAdd.Published = DateTime.Now.AddHours(SiteSettings.Get().TimeZoneOffSet); } try { return(PostRevisionManager.CommitPost(postToAdd, user, false, false).ToString()); } catch (Exception ex) { if (ex.Message.IndexOf("UNIQUE") > -1) { throw new XmlRpcFaultException(2, "Duplicate Post Name"); } else { Log.Error("MetaBlog Error", "An error occored editing the post {0}. Exception: {1} Stack: {2}", post.postid, ex.Message, ex.StackTrace); throw; } } } throw new XmlRpcFaultException(0, "User does not exist"); }
/// <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-"); } }
public bool editPost(string postid, string username, string password, Post post, bool publish) { if (ValidateUser(username, password)) { Graffiti.Core.Post wp = new Graffiti.Core.Post(postid); IGraffitiUser user = GraffitiUsers.Current; if (post.categories != null && post.categories.Length > 0) { wp.CategoryId = AddOrFetchCategory(post.categories[0], user).Id; } wp.Name = post.wp_slug ?? wp.Name; if (!string.IsNullOrEmpty(post.mt_text_more)) { wp.ExtendedBody = post.mt_text_more; } else { wp.ExtendedBody = null; } wp.PostBody = post.description; wp.Title = post.title; wp.PostStatus = (publish ? PostStatus.Publish : PostStatus.Draft); wp.IsPublished = publish; wp.TagList = post.GetTagList() ?? wp.TagList; try { if (post.dateCreated != DateTime.MinValue) { DateTime dtUTC = post.dateCreated; DateTime dtLocal = dtUTC.ToLocalTime(); wp.Published = dtLocal.AddHours(SiteSettings.Get().TimeZoneOffSet); //wp.Published = post.dateCreated; } } catch { } try { PostRevisionManager.CommitPost(wp, user, SiteSettings.Get().FeaturedId == wp.Id, wp.Category.FeaturedId == wp.Id); return(true); } catch (Exception ex) { if (ex.Message.IndexOf("UNIQUE") > -1) { throw new XmlRpcFaultException(2, "Sorry, but the name of this post is not unqiue and the post was not saved"); } else { Log.Error("MetaBlog Error", "An error occored editing the post {0}. Exception: {1} Stack: {2}", post.postid, ex.Message, ex.StackTrace); throw; } } } throw new XmlRpcFaultException(0, "User does not exist"); }