public static string GenerateTrackbackRDF(Post post)
        {
            Macros macros = new Macros();
            StringBuilder sb = new StringBuilder();

            string postUrl = macros.FullUrl(post.Url);
            string pingUrl = macros.FullUrl(string.Format("{0}?id={1}", VirtualPathUtility.ToAbsolute("~/trackback.ashx"), post.Id));

            sb.Append("\n<!--\n");
            sb.Append("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n");
            sb.Append("xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
            sb.Append("xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">\n");
            sb.Append("<rdf:Description\n");
            sb.AppendFormat("rdf:about=\"{0}\"\n", postUrl);
            sb.AppendFormat("dc:identifier=\"{0}\"\n", postUrl);
            sb.AppendFormat("dc:title=\"{0}\"\n", post.Title);
            sb.AppendFormat("trackback:ping=\"{0}\" />\n", pingUrl);
            sb.Append("</rdf:RDF>\n");
            sb.Append("-->\n");

            return sb.ToString();
        }
Exemple #2
0
 public static void RedirectToSSL(HttpContext context)
 {
     if (!context.Request.IsSecureConnection)
     {
         string url = new Macros().FullUrl(context.Request.RawUrl);
         context.Response.Redirect("https://" + url.Substring(7));
     }
 }
Exemple #3
0
        public static bool CheckUrlRoutingSupport()
        {
            Macros macros = new Macros();
            try
            {
                HttpWebResponse response = GRequest.GetResponse(macros.FullUrl(VirtualPathUtility.ToAbsolute("~/__utility/GraffitiUrlRoutingCheck")));

                if (response.StatusCode == HttpStatusCode.NoContent)
                {
                    string headerValue = response.Headers.Get("GraffitiCMS-UrlRouting");
                    if (!string.IsNullOrEmpty(headerValue))
                    {
                        bool urlRoutingSupported = false;
                        if (bool.TryParse(headerValue, out urlRoutingSupported))
                            return urlRoutingSupported;
                    }
                }
            }
            catch { }

            return false;
        }
Exemple #4
0
        /// <summary>
        /// Renders the view.
        /// </summary>
        /// <param name="view">The view.</param>
        /// <param name="context">The context.</param>
        private void RenderView(string view, ControllerContext context)
        {
            context["request"] = context.Request;
            context["response"] = context.Response;
            context["url"] = context.Request.RawUrl;
            context["urls"] = new Urls();
            context["util"] = new UtilWrapper();
            context["macros"] = new Macros();
            context["data"] = new Data();
            context["site"] = SiteSettings.Get();

            context.Response.ClearContent();
            context.Response.ContentType = contentType;
            if (!String.IsNullOrEmpty(filename))
                context.Response.AddHeader("Content-Disposition", new ContentDisposition { FileName = filename }.ToString());
            TemplateEngine.Evaluate(context.Response.Output, view, context);
            context.Response.End();
        }
 static string RenderNavigation()
 {
     Graffiti.Core.Macros macros = new Graffiti.Core.Macros();
     return(macros.LoadThemeView("components/site/menu.view"));
 }
        public void ProcessRequest(HttpContext context)
        {
            Macros macros = new Macros();
            context.Response.ContentType = "text/xml";

            int postId = 0;
            try { postId = int.Parse(context.Request.QueryString["id"]); }
            catch { }

            if (postId <= 0)
                TrackbackResponse(context, "PostId is invalid or missing");

            if (context.Request.HttpMethod == "POST")
            {
                string title = SafeParam(context, "title");
                string excerpt = SafeParam(context, "excerpt");
                string url = SafeParam(context, "url");
                string blog_name = SafeParam(context, "blog_name");

                try
                {
                    // Check if params are valid
                    if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(title) || string.IsNullOrEmpty(blog_name) || string.IsNullOrEmpty(excerpt))
                    {
                        TrackbackResponse(context, "One or more parameters are invalid or missing");
                    }

                    Post trackedEntry = Post.GetCachedPost(postId);
                    if (trackedEntry == null)
                    {
                        TrackbackResponse(context, "The link does not exist");
                        return;
                    }

                    if (!trackedEntry.EnableComments || !trackedEntry.EnableNewComments)
                    {
                        TrackbackResponse(context, "Trackbacks are not enabled");
                        return;
                    }

                    if (!IsNewTrackBack(trackedEntry.Id, url))
                    {
                        TrackbackResponse(context, "Trackbacks already exists");
                        return;
                    }

                    string pageTitle = null;
                    if (!LinkParser.SourceContainsTarget(url, macros.FullUrl(trackedEntry.Url), out pageTitle))
                    {
                        TrackbackResponse(context, "Sorry couldn't find a relevant link in " + url);
                    }

                    if (string.IsNullOrEmpty(pageTitle))
                    {
                        TrackbackResponse(context, "Could not find a readable HTML title in the remote page at " + url);
                        return;
                    }

                    if (!string.IsNullOrEmpty(excerpt))
                        excerpt = Util.RemoveHtml(excerpt, 250);

                    // Create the Trackback item
                    Comment comment = new Comment();
                    comment.IsTrackback = true;
                    comment.PostId = trackedEntry.Id;
                    comment.Name = title;
                    comment.WebSite = url;
                    comment.Body = excerpt;
                    comment.IPAddress = context.Request.UserHostAddress;
                    comment.Published = DateTime.Now.AddHours(SiteSettings.Get().TimeZoneOffSet);
                    comment.Save();

                    // Log success message to EventLog
                    string message = String.Format("Trackback request received from {0} and saved to post {1}.", url, trackedEntry.Title);
                    Log.Info("Trackback Received", message);

                    context.Response.Write(successResponseXML);
                    context.Response.End();
                }
                catch (System.Threading.ThreadAbortException) { }
                catch (System.Exception ex)
                {
                    if (ex.Message != null)
                        TrackbackResponse(context, string.Format("Error occurred while processing Trackback: {0}", ex.Message));
                    else
                        TrackbackResponse(context, "Unknown error occurred while processing Trackback.");
                }

            }
        }
        protected override void OnLoad(EventArgs e)
        {
            SiteSettings settings = SiteSettings.Get();
            CommentCollection cc = new Data().RecentComments(Util.PageSize);

            DateTime lastModified = DateTime.Now;
            if (cc.Count > 0)
            {
                string lastMod = Context.Request.Headers["If-Modified-Since"];
                if (lastMod != null)
                {
                    if (lastMod == cc[0].Published.AddHours(-1 * settings.TimeZoneOffSet).ToUniversalTime().ToString("r"))
                    {
                        Context.Response.StatusCode = 304;
                        Context.Response.Status = "304 Not Modified";
                        Context.Response.End();
                    }
                }
                lastModified = cc[0].Published.AddHours(-1 * settings.TimeZoneOffSet);
                Context.Response.Clear();
                Context.Response.Cache.SetCacheability(HttpCacheability.Public);
                Context.Response.Cache.SetLastModified(lastModified);
                Context.Response.Cache.SetETag(lastModified.ToString());
            }

            Macros macros = new Macros();

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

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

            writer.WriteStartElement("channel");
            writer.WriteElementString("title", settings.Title + ": All Comments");
            writer.WriteElementString("link", macros.FullUrl(new Urls().Home));
            writer.WriteElementString("description", settings.TagLine);
            writer.WriteElementString("generator", SiteSettings.VersionDescription);
            writer.WriteElementString("lastBuildDate", lastModified.AddHours(-1 * settings.TimeZoneOffSet).ToUniversalTime().ToString("r"));

            string baseUrl = SiteSettings.BaseUrl;
            foreach (Comment comment in cc)
            {
                string link = macros.FullUrl(comment.Url);
                string body = Util.FullyQualifyRelativeUrls(comment.Body, baseUrl);
                if (comment.IsTrackback)
                    body = string.Format("{0}\n<br />\nTrackback url: {1}", body, comment.WebSite);

                writer.WriteStartElement("item");
                writer.WriteElementString("title", HttpUtility.HtmlDecode(comment.Title));
                writer.WriteElementString("link", link);
                writer.WriteElementString("pubDate", comment.Published.AddHours(-1 * settings.TimeZoneOffSet).ToUniversalTime().ToString("r"));

                writer.WriteStartElement("guid");
                writer.WriteAttributeString("isPermaLink", "true");
                writer.WriteString(link);
                writer.WriteEndElement();

                writer.WriteElementString("dc:creator", comment.Name);
                writer.WriteElementString("description", body);

                writer.WriteEndElement(); // End Item
            }

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

            // save XML into response
            Context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            Context.Response.ContentType = "application/rss+xml";
            Context.Response.Write(sw.ToString());
        }
        /// <summary>
        /// Builds the sitemap.
        /// </summary>
        /// <returns></returns>
        private string BuildSitemap()
        {
            StringBuilder xml = new StringBuilder();
            using (Utf8EncodedStringWriter encodedStringWriter = new Utf8EncodedStringWriter(xml))
            using (XmlWriter writer = XmlWriter.Create(encodedStringWriter, new XmlWriterSettings { Indent = true }))
            {
                // Root of the document
                writer.WriteStartDocument();
                writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");

                Macros macros = new Macros();
                Urls urls = new Urls();

                // Home
                WriteSitemapNode(writer, macros.FullUrl(urls.Home), DateTime.Today, "daily", "0.5");

                // Categories
                // Temporary solution for last modified date - use today
                foreach (Category category in CategoryCollection.FetchAll())
                {
                    if (category.IsUncategorized || category.IsDeleted)
                        continue;

                    WriteSitemapNode(writer, macros.FullUrl(category.Url), DateTime.Today, "daily", "0.5");
                }

                // Posts
                PostCollection posts = PostCollection.FetchAll();
                posts.Sort(delegate(Post p1, Post p2)
               	{
               		return Comparer<DateTime>.Default.Compare(p1.Published, p2.Published);
               	});

                foreach (Post post in posts)
                {
                    if (!post.IsPublished || post.IsDeleted || post.IsDirty || post.Published > DateTime.Now)
                        continue;

                    if (post.Category.IsUncategorized && !this.IncludeUncategorizedPosts)
                        continue;

                    WriteSitemapNode(writer, macros.FullUrl(post.Url), post.ModifiedOn, "daily", "0.5");
                }

                writer.WriteEndDocument();
            }

            return xml.ToString();
        }
Exemple #9
0
        protected override string BuildFeed()
        {
            Macros macros = new Macros();
            string downloadUrlPrefix = macros.FullUrl(VirtualPathUtility.ToAbsolute("~/download/"));

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

            writer.WriteStartElement("items");

            foreach (Post post in GetPosts())
            {
                Dictionary<int, ItemStatistics> stats = DataHelper.GetMarketplaceCategoryStats(_categoryId);

                writer.WriteStartElement("itemInfo");
                writer.WriteAttributeString("id", post.Id.ToString());
                writer.WriteAttributeString("categoryId", post.CategoryId.ToString());
                writer.WriteAttributeString("creatorId", post.Custom("Creator"));
                writer.WriteElementString("name", post.Title);
                writer.WriteElementString("description", Util.FullyQualifyRelativeUrls(post.Excerpt("", "", "Read More", 300), SiteSettings.BaseUrl));
                writer.WriteElementString("version", post.Custom("Version"));
                writer.WriteElementString("downloadUrl", downloadUrlPrefix + post.Id.ToString());

                string fileName = post.Custom("FileName");
                if (!string.IsNullOrEmpty(fileName))
                {
                    if (fileName.Contains('/'))
                        fileName = fileName.Substring(fileName.LastIndexOf('/') + 1);
                    writer.WriteElementString("fileName", fileName);
                }
                else
                    writer.WriteElementString("fileName", post.Name);

                if (!string.IsNullOrEmpty(post.Custom("ImageLarge")))
                    writer.WriteElementString("screenshotUrl", macros.FullUrl(post.Custom("ImageLarge")));
                if (!string.IsNullOrEmpty(post.ImageUrl))
                    writer.WriteElementString("iconUrl", macros.FullUrl(post.ImageUrl));
                writer.WriteElementString("worksWithMajorVersion", post.Custom("RequiredMajorVersion"));
                writer.WriteElementString("worksWithMinorVersion", post.Custom("RequiredMinorVersion"));
                writer.WriteElementString("requiresManualIntervention", post.Custom("RequiresManualIntervention") ?? "False" );
                writer.WriteElementString("isApproved", post.IsPublished.ToString());
                writer.WriteElementString("dateAdded", post.Published.ToUniversalTime().ToString("u"));

                writer.WriteStartElement("statisticsInfo");
                if (stats.ContainsKey(post.Id))
                    writer.WriteElementString("downloadCount", stats[post.Id].DownloadCount.ToString());
                else
                    writer.WriteElementString("downloadCount", "0");
                writer.WriteElementString("viewCount", post.Views.ToString());
                writer.WriteEndElement(); // End statisticsInfo

                writer.WriteStartElement("purchaseInfo");
                writer.WriteElementString("price", post.Custom("Price") ?? "0.0");
                if (!string.IsNullOrEmpty(post.Custom("BuyUrl")))
                    writer.WriteElementString("buyUrl", post.Custom("BuyUrl"));
                writer.WriteEndElement(); // End purchaseInfo

                writer.WriteStartElement("tags");
                foreach (string tag in Util.ConvertStringToList(post.TagList))
                {
                    writer.WriteElementString("tag", tag);
                }
                writer.WriteEndElement(); // End tags

                writer.WriteEndElement(); // End itemInfo
            }

            writer.WriteEndElement(); // End items

            return sw.ToString();
        }
        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);
        }
        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);
            }
        }
Exemple #12
0
        public MetaWeblog.CategoryInfo[] getCategories(string blogid,string username,string password)
        {
            if(ValidateUser(username,password))
            {
                CategoryCollection cc = new CategoryController().GetAllTopLevelCachedCategories();
                ArrayList al = new ArrayList();
                Macros m = new Macros();
                foreach(Graffiti.Core.Category c in cc)
                {
                    CategoryInfo ci = new CategoryInfo();
                    ci.categoryid = c.Id.ToString();
                    ci.description = c.Name;
                    ci.title = c.Name;
                    ci.htmlUrl = m.FullUrl(c.Url);
                    ci.rssUrl = m.FullUrl(c.Url + "feed/");
                    al.Add(ci);

                    if (c.HasChildren)
                    {
                        foreach (Core.Category child in c.Children)
                        {
                            CategoryInfo ci2 = new CategoryInfo();
                            ci2.categoryid = child.Id.ToString();
                            ci2.description = c.Name + " > " + child.Name;
                            ci2.title = c.Name + " > " + child.Name;
                            ci2.htmlUrl = m.FullUrl(child.Url);
                            ci2.rssUrl = m.FullUrl(child.Url + "feed/");
                            al.Add(ci2);
                        }
                    }
                }

                return al.ToArray(typeof(CategoryInfo)) as CategoryInfo[];
            }
            throw new XmlRpcFaultException(0,"User does not exist");
        }