Esempio n. 1
0
        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();
                }
            }
        }
Esempio n. 2
0
    protected bool CanDelete()
    {
        if (GraffitiUsers.CanDeleteUsers && GraffitiUsers.IsAdmin(GraffitiUsers.Current))
        {
            return(true);
        }

        return(false);
    }
Esempio n. 3
0
        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));
        }
 protected virtual bool IsValidAccess(IGraffitiUser user)
 {
     return(GraffitiUsers.IsAdmin(user));
 }
Esempio n. 5
0
        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;
            }
        }
Esempio n. 6
0
    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();");
    }
Esempio n. 7
0
 protected bool CanDelete()
 {
     return(GraffitiUsers.IsAdmin(GraffitiUsers.Current));
 }
        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);
            }
        }
Esempio n. 9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            LiHyperLink.SetNameToCompare(Context, "settings");

            DeleteButton.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this file? This action cannot be undone!');");

            string rootPath = Server.MapPath("~/");
            string path     = Request.QueryString["path"] ?? "";

            if (!path.ToLower().StartsWith(basicFilesMediaPath) && !GraffitiUsers.IsAdmin(GraffitiUsers.Current))
            {
                Response.Redirect(Request.Url.AbsolutePath + "?path=" + basicFilesMediaPath, true);
            }

            path = Path.Combine(rootPath, Util.NormalizePath(path));
            string fileName = Request.QueryString["f"];

            DirectoryInfo di = new DirectoryInfo(path);

            if (!di.FullName.ToLower().StartsWith(rootPath.ToLower()))
            {
                Log.Error("FileBrowser", "A request was made to an invalid directory {0}. If this persists, you should contact your ISP", di.FullName);
                throw new Exception("Bad Path");
            }

            SetBreadCrumbs(fileName);
            SetFolders(di, rootPath);

            if (string.IsNullOrEmpty(fileName))
            {
                FileViews.SetActiveView(FileLists);
                SetFileList(di);
            }
            else
            {
                FileInfo fi = new FileInfo(Path.Combine(path, fileName));
                if (!fi.Exists)
                {
                    Log.Warn("FileBrowser", "A requested file {0} does not exist", fi.FullName);
                    throw new Exception("File does not exist");
                }

                if (!FileFilters.IsValidFile(fi.Name))
                {
                    Log.Error("FileBrowser",
                              "A forbidden file {0} was requested by the FileBrowser. Access to view/edit this file has been denied.",
                              fi.FullName);
                    throw new Exception("File does not exist");
                }


                if (Request.QueryString["edit"] != "true")
                {
                    SetFileDetails(fi);
                }
                else
                {
                    SetFileEdit(fi);
                }
            }
        }
Esempio n. 10
0
        private void SetBreadCrumbs(string fileName)
        {
            string thePath = Request.QueryString["path"] ?? "";

            if (thePath.EndsWith("\\"))
            {
                thePath = thePath.Substring(0, thePath.Length - 1);
            }

            //            if(thePath.Trim().Length == 0 && string.IsNullOrEmpty(fileName))
            //                return;

            StringBuilder sb = new StringBuilder("<div class=\"breadcrumbs\">");

            if (this.IncludeUtilityBreadCrumbs)
            {
                sb.Append("<a href=\"../\">Site Options</a>");
                sb.Append("<span class=\"seperator\">></span>");
                sb.Append("<a href=\"../utilities/\">Utilities</a>");
                sb.Append("<span class=\"seperator\">></span>");
            }

            bool isAdmin = GraffitiUsers.IsAdmin(GraffitiUsers.Current);

            if (isAdmin)
            {
                sb.Append("<a href=\"?path=\">Home</a>");
            }
            else
            {
                sb.Append("Home");
            }


            string previous = "?path=";

            if (thePath.IndexOf("\\") > -1)
            {
                while (thePath.IndexOf("\\") != -1)
                {
                    sb.Append("<span class=\"seperator\">></span>");
                    string text = thePath.Substring(0, thePath.IndexOf("\\"));
                    previous += text + "\\";
                    thePath   = thePath.Substring(text.Length + 1);

                    if (previous.ToLower().StartsWith("?path=" + basicFilesMediaPath) || isAdmin)
                    {
                        sb.AppendFormat("<a href=\"{0}\">{1}</a>", previous.Substring(0, previous.Length - 1), text);
                    }
                    else
                    {
                        sb.Append(text);
                    }
                }
            }

            if (thePath.Trim().Length > 0)
            {
                sb.Append("<span class=\"seperator\">></span>");
                if (!string.IsNullOrEmpty(fileName))
                {
                    sb.AppendFormat("<a href=\"?path={0}\">{1}</a>", Request.QueryString["path"] ?? "", thePath.Trim());
                }
                else
                {
                    sb.Append(thePath.Trim());
                }
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                sb.Append("<span class=\"seperator\">></span>");
                sb.Append(fileName);
            }

            sb.Append("</div>");

            theBreadCrumbs.Text = sb.ToString();
        }
Esempio n. 11
0
    protected void EditPerson_Click(object sender, EventArgs e)
    {
        try
        {
            IGraffitiUser currentUser = GraffitiUsers.Current;
            IGraffitiUser user        = GraffitiUsers.GetUser(Request.QueryString["user"]);
            bool          isAdmin     = GraffitiUsers.IsAdmin(currentUser);

            if (!isAdmin && user.Name != currentUser.Name)
            {
                throw new SecurityException("You do not have permission to edit this user");
            }

            user.ProperName = Server.HtmlEncode(txtProperName.Text.Trim());
            user.Bio        = Editor.Text.Trim();
            user.Email      = txtExistingEmail.Text.Trim();

            if (!string.IsNullOrEmpty(txtWebsite.Text.Trim()))
            {
                user.WebSite = Server.HtmlEncode(txtWebsite.Text.Trim());
            }
            else
            {
                user.WebSite = null;
            }

            if (!string.IsNullOrEmpty(txtAvatar.Text.Trim()))
            {
                user.Avatar = Server.HtmlEncode(txtAvatar.Text.Trim());
            }
            else
            {
                user.Avatar = null;
            }

            if (isAdmin)
            {
                foreach (string role in user.Roles)
                {
                    GraffitiUsers.RemoveUserFromRole(user.Name, role);
                }

                GraffitiUsers.AddUserToRole(user.Name, GraffitiUsers.EveryoneRole);

                if (chkAdmin.Checked == true)
                {
                    GraffitiUsers.AddUserToRole(user.Name, GraffitiUsers.AdminRole);
                }

                foreach (DataListItem dli in Roles.Items)
                {
                    CheckBox role = dli.FindControl("role") as CheckBox;

                    if (role.Checked)
                    {
                        GraffitiUsers.AddUserToRole(user.Name, role.Text);
                    }
                }
            }

            GraffitiUsers.Save(user, GraffitiUsers.Current.Name);

            Message.Text = "The user <strong>" + user.ProperName + "</strong> was updated.";
            Message.Type = StatusType.Success;
        }
        catch (Exception ex)
        {
            string exMessage = ex.Message;
            if (!string.IsNullOrEmpty(exMessage) && exMessage.IndexOf("UNIQUE") > -1)
            {
                exMessage = "This username (or email) already exists.";
            }

            Message.Text = "A user with the name of " + txtExistingUserName.Text + " could not be updated.<br />" +
                           exMessage;
            Message.Type = StatusType.Error;
        }
    }
Esempio n. 12
0
    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);
                    }
                }
            }
        }
    }
Esempio n. 13
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"];
                var    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
                {
                    var   posts = new Dictionary <int, Post>();
                    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
                {
                    var   posts = new Dictionary <int, Post>();
                    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"]);

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

                    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"]);
                    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 = db;

                        break;

                    case "Wordpress":

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

                        break;

                    case "BlogML":

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

                        break;

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

                        break;

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

                        break;
                    }

                    var 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;
            }
        }