PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/BlogEngine/BlogEngine.NET/default.aspx.cs

#
C# | 307 lines | 252 code | 31 blank | 24 comment | 60 complexity | 0b6294c79128cc9798b9aedbbceab40f MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, BSD-3-Clause
  1. #region Using
  2. using System;
  3. using System.Globalization;
  4. using System.Text.RegularExpressions;
  5. using System.Web;
  6. using System.Xml;
  7. using System.Collections.Generic;
  8. using BlogEngine.Core;
  9. using System.Web.UI;
  10. #endregion
  11. //TODO Remove All URL redirects to Business layer? To speed up page loading instead of having the most visited page handling so many tasks
  12. public partial class _default : BlogEngine.Core.Web.Controls.BlogBasePage
  13. {
  14. bool SearchEngine = false;
  15. protected void Page_Load(object sender, EventArgs e)
  16. {
  17. //Check to see if Client is a SearchEngine or Bot trying to craw the website
  18. CheckBrowserCaps();
  19. if (Page.IsCallback)
  20. return;
  21. // If Client is a SearchEngine or Bot Start the Processing of SearchEngine
  22. if (SearchEngine == true)
  23. {
  24. ProcessSearchEngine();
  25. }
  26. if (Request.RawUrl.ToLowerInvariant().Contains("/category/"))
  27. {
  28. DisplayCategories();
  29. }
  30. else if (Request.RawUrl.ToLowerInvariant().Contains("/author/"))
  31. {
  32. DisplayAuthors();
  33. }
  34. else if (Request.RawUrl.ToLowerInvariant().Contains("?tag="))
  35. {
  36. DisplayTags();
  37. }
  38. else if (Request.QueryString["year"] != null || Request.QueryString["date"] != null || Request.QueryString["calendar"] != null)
  39. {
  40. if (Request.RawUrl.Contains("year="))
  41. Redirect();
  42. else
  43. DisplayDateRange();
  44. // base.AddMetaTag("description", Server.HtmlEncode(BlogSettings.Instance.Description)); This only should be for default.aspx page once.
  45. //TODO Removing all BlogSettings.Instance.Description AddMetaTags so that each page and post has unique description
  46. }
  47. else if (Request.QueryString["apml"] != null)
  48. {
  49. DisplayApmlFiltering();
  50. }
  51. else
  52. {
  53. if (!BlogSettings.Instance.UseBlogNameInPageTitles)
  54. Page.Title = BlogSettings.Instance.Name + " | ";
  55. if (!string.IsNullOrEmpty(BlogSettings.Instance.Description))
  56. Page.Title += Server.HtmlEncode(BlogSettings.Instance.Description);
  57. base.AddMetaTag("description", Server.HtmlEncode(BlogSettings.Instance.Description));
  58. }
  59. AddMetaKeywords();
  60. base.AddMetaTag("author", Server.HtmlEncode(BlogSettings.Instance.AuthorName));
  61. }
  62. void CheckBrowserCaps()
  63. {
  64. System.Web.HttpBrowserCapabilities myBrowserCaps = Request.Browser;
  65. if (((System.Web.Configuration.HttpCapabilitiesBase)myBrowserCaps).Crawler)
  66. {
  67. SearchEngine = true;
  68. }
  69. }
  70. /// <summary>
  71. /// Blocks SearchEngine and Bots from indexing Human Only webpages
  72. /// pager,keywords,tags,categories,search and archive page
  73. /// </summary>
  74. private void ProcessSearchEngine ()
  75. {
  76. string CrawlerUrl = Request.RawUrl.ToLowerInvariant();
  77. if (CrawlerUrl.Contains("/category/") ||
  78. CrawlerUrl.Contains("?tag") ||
  79. CrawlerUrl.Contains("?page=") ||
  80. // Post with Date has format http://MainWebsite.com/post/2014/02/13/post-2
  81. CrawlerUrl.Contains(Utils.RelativeWebRoot + "/2013/", StringComparison.OrdinalIgnoreCase) || //Stops Calendar from being indexed
  82. CrawlerUrl.Contains(Utils.RelativeWebRoot + "/2014/", StringComparison.OrdinalIgnoreCase) ||
  83. CrawlerUrl.StartsWith(Utils.RelativeWebRoot + "search.aspx", StringComparison.OrdinalIgnoreCase) ||
  84. CrawlerUrl.StartsWith(Utils.RelativeWebRoot + "archive.aspx", StringComparison.OrdinalIgnoreCase))
  85. {
  86. base.AddMetaTag("ROBOT", "NOINDEX, NOFOLLOW");
  87. //Sends SearchEngine or Bot to the default page
  88. Response.RedirectPermanent(Utils.RelativeWebRoot);
  89. }
  90. }
  91. private void DisplayApmlFiltering()
  92. {
  93. Uri url = null;
  94. if (Uri.TryCreate(Request.QueryString["apml"], UriKind.Absolute, out url))
  95. {
  96. Page.Title = Resources.labels.apmlFilteredList;
  97. try
  98. {
  99. Dictionary<Uri, XmlDocument> docs = Utils.FindSemanticDocuments(url, "apml");
  100. if (docs.Count > 0)
  101. {
  102. foreach (Uri key in docs.Keys)
  103. {
  104. PostList1.ContentBy = ServingContentBy.Apml;
  105. PostList1.Posts = Search.ApmlMatches(docs[key], 30).FindAll(delegate(IPublishable p) { return p is Post; });
  106. PostList1.Posts.Sort(delegate(IPublishable ip1, IPublishable ip2) { return ip2.DateCreated.CompareTo(ip1.DateCreated); });
  107. Page.Title += Resources.labels.per + Server.HtmlEncode(key.Host);
  108. break;
  109. }
  110. }
  111. else
  112. {
  113. divError.InnerHtml = "<h1 style=\"text-align:center\">"+Resources.labels.apmlNotFoundDesc+"</h1><br /><br />";
  114. Page.Title = Resources.labels.apmlNotFound;
  115. }
  116. }
  117. catch (NotSupportedException)
  118. {
  119. divError.InnerHtml = "<h1 style=\"text-align:center\">"+Resources.labels.apmlNoInfoWebsite+"</h1><br /><br />";
  120. Page.Title = Resources.labels.apmlNotFound;
  121. }
  122. catch (System.Net.WebException)
  123. {
  124. divError.InnerHtml = "<h1 style=\"text-align:center\">"+Resources.labels.apmlNoConnWebsite+"</h1><br /><br />";
  125. Page.Title = Resources.labels.apmlAddrInvalid;
  126. }
  127. catch (XmlException)
  128. {
  129. divError.InnerHtml = "<h1 style=\"text-align:center\">"+Resources.labels.apmlInvalidXml+"</h1><br /><br />";
  130. Page.Title = Resources.labels.apmlDocErr;
  131. }
  132. }
  133. else if (PostList1.Posts == null || PostList1.Posts.Count == 0)
  134. {
  135. divError.InnerHtml = "<h1 style=\"text-align:center\">"+Resources.labels.apmlInvalidUrl+"</h1><br /><br />";
  136. Page.Title = Resources.labels.apmlNotFound;
  137. }
  138. }
  139. //TODO Does the old URL redirect still needed with BE 2.9 and above?
  140. /// <summary>
  141. /// Permanently redirects to the correct URL format if the page is requested with
  142. /// the old URL: /default.aspx?year=2007&month=12
  143. /// <remarks>
  144. /// The redirection is important so that we don't end up having 2 URLs
  145. /// to the same resource. It's for SEO purposes.
  146. /// </remarks>
  147. /// </summary>
  148. private void Redirect()
  149. {
  150. string year = Request.QueryString["year"];
  151. string month = Request.QueryString["month"];
  152. string date = Request.QueryString["date"];
  153. string page = string.IsNullOrEmpty(Request.QueryString["page"]) ? string.Empty : "?page=" + Request.QueryString["page"];
  154. string rewrite = null;
  155. if (!string.IsNullOrEmpty(date))
  156. {
  157. DateTime dateParsed = DateTime.Parse(date);
  158. rewrite = Utils.RelativeWebRoot + dateParsed.Year + "/" + dateParsed.Month + "/" + dateParsed.Day + "/default.aspx";
  159. }
  160. else if (!string.IsNullOrEmpty(year) && !string.IsNullOrEmpty(month))
  161. {
  162. rewrite = Utils.RelativeWebRoot + year + "/" + month + "/default.aspx";
  163. }
  164. else if (!string.IsNullOrEmpty(year))
  165. {
  166. rewrite = Utils.RelativeWebRoot + year + "/default.aspx";
  167. }
  168. if (rewrite != null)
  169. {
  170. //TODO Replace this Block of code with Response.RedirectPermanent? Since Asp.net 4.0 has new method saves on code.
  171. Response.Clear();
  172. Response.StatusCode = 301;
  173. Response.AppendHeader("location", rewrite + page);
  174. Response.End();
  175. }
  176. }
  177. private static readonly Regex YEAR_MONTH = new Regex("/([0-9][0-9][0-9][0-9])/([0-1][0-9])", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  178. private static readonly Regex YEAR_MONTH_DAY = new Regex("/([0-9][0-9][0-9][0-9])/([0-1][0-9])/([0-3][0-9])", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  179. /// <summary>
  180. /// Adds the post's tags as meta keywords.
  181. /// </summary>
  182. private void AddMetaKeywords()
  183. {
  184. if (Category.Categories.Count > 0)
  185. {
  186. string[] categories = new string[Category.Categories.Count];
  187. for (int i = 0; i < Category.Categories.Count; i++)
  188. {
  189. categories[i] = Category.Categories[i].Title;
  190. }
  191. string metakeywords = Server.HtmlEncode(string.Join(",", categories));
  192. System.Web.UI.HtmlControls.HtmlMeta tag = null;
  193. foreach (Control c in Page.Header.Controls)
  194. {
  195. if (c is System.Web.UI.HtmlControls.HtmlMeta && (c as System.Web.UI.HtmlControls.HtmlMeta).Name.ToLower() == "keywords")
  196. {
  197. tag = c as System.Web.UI.HtmlControls.HtmlMeta;
  198. tag.Content += ", " + metakeywords;
  199. break;
  200. }
  201. }
  202. if (tag == null)
  203. {
  204. base.AddMetaTag("keywords", metakeywords);
  205. }
  206. }
  207. }
  208. private void DisplayCategories()
  209. {
  210. if (!String.IsNullOrEmpty(Request.QueryString["id"]))
  211. {
  212. Guid categoryId = new Guid(Request.QueryString["id"]);
  213. PostList1.ContentBy = ServingContentBy.Category;
  214. Category category = Category.GetCategory(categoryId, Blog.CurrentInstance.IsSiteAggregation);
  215. PostList1.Posts = Post.GetPostsByCategory(category).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
  216. Page.Title = category.Title;
  217. base.AddMetaTag("description", string.IsNullOrWhiteSpace(category.Description) ? Server.HtmlEncode(category.Title) : category.Description);
  218. }
  219. }
  220. private void DisplayAuthors()
  221. {
  222. if (!string.IsNullOrEmpty(Request.QueryString["name"]))
  223. {
  224. string author = Server.UrlDecode(Request.QueryString["name"]);
  225. PostList1.ContentBy = ServingContentBy.Author;
  226. PostList1.Posts = Post.GetPostsByAuthor(author).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
  227. Title = Resources.labels.AllPostsBy +" " + Server.HtmlEncode(author);
  228. base.AddMetaTag("description", Server.HtmlEncode(Title));
  229. }
  230. }
  231. private void DisplayTags()
  232. {
  233. if (!string.IsNullOrEmpty(Request.QueryString["tag"]))
  234. {
  235. PostList1.ContentBy = ServingContentBy.Tag;
  236. PostList1.Posts = Post.GetPostsByTag(Request.QueryString["tag"].Substring(1)).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
  237. base.Title = Resources.labels.AllPostsTagged + " '" + Request.QueryString["tag"].Substring(1) + "'";
  238. base.AddMetaTag("description", Server.HtmlEncode(base.Title));
  239. }
  240. }
  241. private void DisplayDateRange()
  242. {
  243. string year = Request.QueryString["year"];
  244. string month = Request.QueryString["month"];
  245. string specificDate = Request.QueryString["date"];
  246. if (!string.IsNullOrEmpty(year) && !string.IsNullOrEmpty(month))
  247. {
  248. DateTime dateFrom = DateTime.Parse(year + "-" + month + "-01", CultureInfo.InvariantCulture);
  249. DateTime dateTo = dateFrom.AddMonths(1).AddMilliseconds(-1);
  250. PostList1.ContentBy = ServingContentBy.DateRange;
  251. PostList1.Posts = Post.GetPostsByDate(dateFrom, dateTo).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
  252. Title = dateFrom.ToString("MMMM yyyy");
  253. }
  254. else if (!string.IsNullOrEmpty(year))
  255. {
  256. DateTime dateFrom = DateTime.Parse(year + "-01-01", CultureInfo.InvariantCulture);
  257. DateTime dateTo = dateFrom.AddYears(1).AddMilliseconds(-1);
  258. PostList1.ContentBy = ServingContentBy.DateRange;
  259. PostList1.Posts = Post.GetPostsByDate(dateFrom, dateTo).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; })); ;
  260. Title = dateFrom.ToString("yyyy");
  261. }
  262. else if (!string.IsNullOrEmpty(specificDate) && specificDate.Length == 10)
  263. {
  264. DateTime date = DateTime.Parse(specificDate, CultureInfo.InvariantCulture);
  265. PostList1.ContentBy = ServingContentBy.DateRange;
  266. PostList1.Posts = Post.GetPostsByDate(date, date).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; })); ;
  267. Title = date.ToString("MMMM d. yyyy");
  268. }
  269. else if (!string.IsNullOrEmpty(Request.QueryString["calendar"]))
  270. {
  271. calendar.Visible = true;
  272. PostList1.Visible = false;
  273. Title = Server.HtmlEncode(Resources.labels.calendar);
  274. }
  275. }
  276. }