/// <summary> /// Handles the URL Rewriting for the application /// </summary> /// <param name="context">Http context</param> public static void BeginRequest(HttpContext context) { string path = context.Request.Path.Substring(context.Request.ApplicationPath.Length > 1 ? context.Request.ApplicationPath.Length : 0); string[] args = path.Split(new char[] { '/' }).Subset(1); if (args.Length > 0) { // Ensure database if (args[0] == "" && SysParam.GetByName("SITE_VERSION") == null) { context.Response.Redirect("~/manager"); } // Find the correct request handler foreach (RequestHandlerRegistration hr in Handlers.Values) { if (hr.UrlPrefix.ToLower() == args[0].ToLower()) { // Execute the handler hr.Handler.HandleRequest(context, args.Subset(1)); break; } } } }
/// <summary> /// Checks the given users access to the permissions specified in the given /// access attribute. /// </summary> /// <param name="user">The user</param> /// <param name="access">The attribute</param> private static void CheckAccess(IPrincipal user, Piranha.AccessAttribute access) { if (access != null) { if (!user.HasAccess(access.Function)) { if (!String.IsNullOrEmpty(access.RedirectUrl)) { HttpContext.Current.Response.Redirect(access.RedirectUrl); } else { SysParam param = SysParam.GetByName("LOGIN_PAGE"); if (param != null) { HttpContext.Current.Response.Redirect(param.Value); } else { HttpContext.Current.Response.Redirect("~/"); } } } } }
/// <summary> /// Check if the current user has access to the action before continuing. /// </summary> /// <param name="context">The current context</param> protected override void OnActionExecuting(ActionExecutingContext context) { // Get the current permalink CurrentPermalink = Request["permalink"]; try { if ((this is SinglePageController && User.HasAccess("ADMIN_PAGE")) || (this is SinglePageController && User.HasAccess("ADMIN_POST"))) { IsDraft = !String.IsNullOrEmpty(Request["draft"]) ? Convert.ToBoolean(Request["draft"]) : false; } else { IsDraft = false; } } catch {} // Authorize and execute if (Authorize(context.ActionDescriptor.ActionName)) { base.OnActionExecuting(context); } else { var param = SysParam.GetByName("LOGIN_PAGE"); if (param != null) { context.Result = Redirect(param.Value); } else { context.Result = Redirect("~/"); } } }
/// <summary> /// Triggered before an action is executed on the controller /// </summary> /// <param name="filterContext">The context</param> protected override void OnActionExecuting(ActionExecutingContext filterContext) { string permalink = Request["permalink"]; bool draft = false; bool cached = false; // Check if we want to see the draft if (User.HasAccess("ADMIN_PAGE")) { if (!String.IsNullOrEmpty(Request["draft"])) { try { draft = Convert.ToBoolean(Request["draft"]); } catch {} } } // Load the current page if (!String.IsNullOrEmpty(permalink)) { page = Models.Page.GetByPermalink(permalink, draft); } else { page = Models.Page.GetStartpage(draft); } // Check permissions if (page.GroupId != Guid.Empty) { if (!User.IsMember(page.GroupId)) { SysParam param = SysParam.GetByName("LOGIN_PAGE"); if (param != null) { Response.Redirect(param.Value); } else { Response.Redirect("~/"); } } Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); } else { // Only cache public pages DateTime mod = GetLastModified(); cached = false; // ClientCache.HandleClientCache(HttpContext.Current, page.Id.ToString(), mod) ; } // Load the model if the page wasn't cached if (!cached) { model = PageModel.Get(page); } base.OnActionExecuting(filterContext); }
/// <summary> /// Check if the current user has access to the action before continuing. /// </summary> /// <param name="context">The current context</param> protected override void OnActionExecuting(ActionExecutingContext context) { // Perform base class stuff base.OnActionExecuting(context); // Check permissions & client cache if (string.IsNullOrEmpty(CurrentPermalink)) { return; } var page = Page.GetByPermalink(CurrentPermalink, IsDraft); if (page != null) { if (page.GroupId != Guid.Empty) { if (!User.IsMember(page.GroupId)) { SysParam param = SysParam.GetByName("LOGIN_PAGE"); if (param != null) { context.Result = Redirect(param.Value); } else { context.Result = Redirect("~/"); } } Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); } else if (!IsDraft) { // Only cache public non drafts DateTime mod = page.LastModified; Web.ClientCache.HandleClientCache(HttpContext.ApplicationInstance.Context, WebPages.WebPiranha.GetCulturePrefix() + page.Id.ToString(), mod); } // Check for disabled groups if (page.DisabledGroups.Contains(User.GetProfile().GroupId)) { SysParam param = SysParam.GetByName("LOGIN_PAGE"); if (param != null) { context.Result = Redirect(param.Value); } else { context.Result = Redirect("~/"); } } } }
/// <summary> /// Handles the current request. /// </summary> /// <param name="context">The current context</param> /// <param name="args">Optional url arguments passed to the handler</param> public virtual void HandleRequest(System.Web.HttpContext context, params string[] args) { var top = Convert.ToInt32(SysParam.GetByName("RSS_NUM_POSTS").Value); var posts = Post.Get("post_draft = 0 AND post_rss = 1 AND post_template_id IN (SELECT posttemplate_id FROM posttemplate WHERE posttemplate_rss = 1)", new Params() { OrderBy = "post_published DESC", Top = top }); Web.RssHelper.Generate(context, WebPages.WebPiranha.CurrentSite.MetaTitle, WebPages.WebPiranha.CurrentSite.MetaDescription, posts); }
/// <summary> /// Handles the current request. /// </summary> /// <param name="context">The current context</param> /// <param name="args">Optional url arguments passed to the handler</param> public virtual void HandleRequest(System.Web.HttpContext context, params string[] args) { var top = Convert.ToInt32(SysParam.GetByName("RSS_NUM_POSTS").Value); var posts = Post.Get("post_draft = 0 AND post_rss = 1 AND post_template_id IN (SELECT posttemplate_id FROM posttemplate WHERE posttemplate_rss = 1)", new Params() { OrderBy = "post_published DESC", Top = top }); Web.RssHelper.Generate(context, SysParam.GetByName("SITE_TITLE").Value, SysParam.GetByName("SITE_DESCRIPTION").Value, posts); }
/// <summary> /// Checks request headers against the given etag and last modification data and /// sets the correct response headers. Returns whether the file is client cached /// or should be loaded/rendered. /// </summary> /// <param name="context">The current context</param> /// <param name="id">The entity id</param> /// <param name="modified">Last nodification</param> /// <param name="noexpire">Whether to use persistent cookies or not</param> /// <param name="minutes">Optional minutes to cache the resource for</param> /// <returns>If the file is cached</returns> public static bool HandleClientCache(HttpContext context, string id, DateTime modified, bool noexpire = false, int?minutes = null) { #if !DEBUG // Get expire & maxage int expires = 30, maxage = 30; try { expires = !minutes.HasValue ? Convert.ToInt32(SysParam.GetByName("CACHE_PUBLIC_EXPIRES").Value) : minutes.Value; maxage = !minutes.HasValue ? Convert.ToInt32(SysParam.GetByName("CACHE_PUBLIC_MAXAGE").Value) : minutes.Value; } catch {} // Handle cache if (!context.Request.IsLocal && expires > 0) { try { if (!minutes.HasValue) { modified = modified > SiteLastModified ? modified : SiteLastModified; } } catch {} string etag = GenerateETag(id, modified); context.Response.Cache.SetETag(etag); context.Response.Cache.SetLastModified(modified <= DateTime.Now ? modified : DateTime.Now); context.Response.Cache.SetCacheability(System.Web.HttpCacheability.ServerAndPrivate); if (!noexpire) { context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(expires)); context.Response.Cache.SetMaxAge(new TimeSpan(0, maxage, 0)); } else { context.Response.Cache.SetExpires(DateTime.Now); } if (IsCached(context, modified, etag)) { context.Response.StatusCode = 304; context.Response.SuppressContent = true; context.Response.EndClean(); return(true); } } else { context.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); } #else context.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); #endif return(false); }
/// <summary> /// Registers all of the hostnames configured in the database. /// </summary> public static void RegisterDefaultHostNames() { // Make sure we don't try to register the host names before // the database has been installed. if (SysParam.GetByName("SITE_VERSION") != null) { if (hostNames == null) { hostNames = new Dictionary <string, Entities.SiteTree>(); } HostNames.Clear(); // We need to check version so we don't try to access the column sitetree_hostnames // before it's been created in the database. if (Data.Database.InstalledVersion > 26) { using (var db = new DataContext()) { var sites = db.SiteTrees.ToList(); foreach (var site in sites) { if (HttpContext.Current != null) { Page.InvalidateStartpage(site.Id); } if (!String.IsNullOrEmpty(site.HostNames)) { var hostnames = site.HostNames.Split(new char[] { ',' }); foreach (var host in hostnames) { if (HostNames.ContainsKey(host)) { throw new Exception("Duplicates of the hostname [" + host + "] was found configured"); } HostNames.Add(host.ToLower(), site); } } if (site.Id == Config.DefaultSiteTreeId) { DefaultSite = site; } } } } } }
/// <summary> /// Outputs the rss feed on the given http context /// </summary> /// <param name="context">The current context</param> /// <param name="title">The feed title</param> /// <param name="description">The feed description</param> /// <param name="posts">The posts to output</param> public static void Generate(HttpContext context, string title, string description, IList <Post> posts) { // Read configuration var exerpt = SysParam.GetByName("RSS_USE_EXCERPT").Value == "1"; // Create the feed context.Response.Clear(); context.Response.ContentType = "text/xml"; context.Response.ContentEncoding = Encoding.UTF8; var feed = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8); // Open the feed feed.WriteStartDocument(); feed.WriteStartElement("rss"); feed.WriteAttributeString("version", "2.0"); feed.WriteStartElement("channel"); feed.WriteElementString("title", title); feed.WriteElementString("link", WebPages.WebPiranha.GetSiteUrl()); feed.WriteElementString("description", description); feed.WriteElementString("generator", Generator()); foreach (var post in posts) { feed.WriteStartElement("item"); feed.WriteElementString("title", post.Title); if (exerpt) { feed.WriteElementString("description", post.Excerpt); } else { feed.WriteElementString("description", post.Body.ToString()); } feed.WriteElementString("link", PublicLink(context.Request, post.Permalink)); feed.WriteElementString("pubDate", post.Published.ToLongDateString()); feed.WriteEndElement(); } // Close the feed feed.WriteEndElement(); feed.WriteEndElement(); feed.WriteEndDocument(); feed.Flush(); feed.Close(); context.Response.EndClean(); }
/// <summary> /// Initializes the web page. /// </summary> protected override void InitializePage() { base.InitializePage(); ExecutePage(); if (IsPost) { if (Request.Form.AllKeys.Contains("piranha_form_action")) { MethodInfo m = GetType().GetMethod(Request.Form["piranha_form_action"], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase); if (m != null) { // Check for access rules var access = m.GetCustomAttribute <AccessAttribute>(true); if (access != null) { if (!User.HasAccess(access.Function)) { SysParam param = SysParam.GetByName("LOGIN_PAGE"); if (param != null) { Response.Redirect(param.Value); } else { Response.Redirect("~/"); } } } // Bind model List <object> args = new List <object>(); foreach (var param in m.GetParameters()) { args.Add(ModelBinder.BindModel(param.ParameterType, param.Name)); } m.Invoke(this, args.ToArray()); } } } }
/// <summary> /// Check if the current user has access to the action before continuing. /// </summary> /// <param name="context">The current context</param> protected override void OnActionExecuting(ActionExecutingContext context) { // Get the current permalink CurrentPermalink = Request["permalink"]; // Authorize and execute if (Authorize(context.ActionDescriptor.ActionName)) { base.OnActionExecuting(context); } else { var param = SysParam.GetByName("LOGIN_PAGE"); if (param != null) { context.Result = Redirect(param.Value); } else { context.Result = Redirect("~/"); } } }
/// <summary> /// Generates the tags appropriate for the html head. /// </summary> /// <returns>The head information</returns> public IHtmlString Head() { StringBuilder str = new StringBuilder(); str.AppendLine("<meta name=\"generator\" content=\"Piranha\" />"); str.AppendLine("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" />"); /** * Basic meta tags */ if (CurrentPage != null || CurrentPost != null) { var keywords = CurrentPage != null ? CurrentPage.Keywords : CurrentPost.Keywords; var description = CurrentPage != null ? CurrentPage.Description : (!String.IsNullOrEmpty(CurrentPost.Description) ? CurrentPost.Description : CurrentPost.Excerpt); if (!String.IsNullOrEmpty(description)) { str.AppendLine("<meta name=\"description\" content=\"" + description + "\" />"); } if (!String.IsNullOrEmpty(keywords)) { str.AppendLine("<meta name=\"keywords\" content=\"" + keywords + "\" />"); } } /** * Open graph meta tags */ str.AppendLine("<meta property=\"og:site_name\" content=\"" + SysParam.GetByName("SITE_TITLE").Value + "\" />"); str.AppendLine("<meta property=\"og:url\" content=\"" + "http://" + Context.Request.Url.DnsSafeHost + Context.Request.RawUrl + "\" />"); if (CurrentPage != null && CurrentPage.IsStartpage) { str.AppendLine("<meta property=\"og:type\" content=\"website\" />"); str.AppendLine("<meta property=\"og:description\" content=\"" + SysParam.GetByName("SITE_DESCRIPTION").Value + "\" />"); } else if (CurrentPage != null || CurrentPost != null) { var title = CurrentPage != null ? CurrentPage.Title : CurrentPost.Title; var description = CurrentPage != null ? CurrentPage.Description : (!String.IsNullOrEmpty(CurrentPost.Description) ? CurrentPost.Description : CurrentPost.Excerpt); str.AppendLine("<meta property=\"og:type\" content=\"article\" />"); if (!String.IsNullOrEmpty(description)) { str.AppendLine("<meta property=\"og:description\" content=\"" + description + "\" />"); } str.AppendLine("<meta property=\"og:title\" content=\"" + title + "\" />"); } /** * RSS Feeds */ str.AppendLine("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"" + SysParam.GetByName("SITE_TITLE").Value + "\" href=\"" + WebPages.WebPiranha.GetSiteUrl() + "/" + WebPages.WebPiranha.GetUrlPrefixForHandlerId("rss") + "\" />"); return(new HtmlString(str.ToString())); }
/// <summary> /// Saves the page and all of it's related regions. /// </summary> /// <param name="publish">If the page should be published</param> /// <returns>If the operation succeeded</returns> public virtual bool SaveAll(bool draft = true) { using (IDbTransaction tx = Database.OpenConnection().BeginTransaction()) { try { bool permalinkfirst = Page.IsNew; // Save permalink first if the page is new if (permalinkfirst) { if (Permalink.IsNew && String.IsNullOrEmpty(Permalink.Name)) { Permalink.Name = Permalink.Generate(!String.IsNullOrEmpty(Page.NavigationTitle) ? Page.NavigationTitle : Page.Title); var param = SysParam.GetByName("HIERARCHICAL_PERMALINKS"); if (param != null && param.Value == "1" && Page.ParentId != Guid.Empty) { var parent = Page.GetSingle(Page.ParentId, true); Permalink.Name = parent.Permalink + "/" + Permalink.Name; } } Permalink.Save(tx); } // Save page if (draft) { Page.Save(tx); } else { Page.SaveAndPublish(tx); } // Save regions & properties Regions.ForEach(r => { r.IsDraft = r.IsPageDraft = true; // Call OnSave r.Body.OnManagerSave(Page); r.Save(tx); if (!draft) { if (Region.GetScalar("SELECT COUNT(region_id) FROM region WHERE region_id=@0 AND region_draft=0", r.Id) == 0) { r.IsNew = true; } r.IsDraft = r.IsPageDraft = false; r.Save(tx); } }); Properties.ForEach(p => { p.IsDraft = true; p.Save(tx); if (!draft) { if (Property.GetScalar("SELECT COUNT(property_id) FROM property WHERE property_id=@0 AND property_draft=0", p.Id) == 0) { p.IsNew = true; } p.IsDraft = false; p.Save(tx); } }); // Save extensions foreach (var ext in Extensions) { // Call OnSave ext.Body.OnManagerSave(Page); ext.ParentId = Page.Id; ext.Save(tx); if (!draft) { if (Extension.GetScalar("SELECT COUNT(extension_id) FROM extension WHERE extension_id=@0 AND extension_draft=0", ext.Id) == 0) { ext.IsNew = true; } ext.IsDraft = false; ext.Save(tx); } } // Save permalink last if the page isn't new if (!permalinkfirst) { Permalink.Save(tx); } // Change global last modified if (!draft) { Web.ClientCache.SetSiteLastModified(tx); } // Clear cache for all post regions if we're publishing if (!String.IsNullOrEmpty(Page.Permalink) && !draft) { foreach (var reg in Regions) { if (reg.Body is Extend.Regions.PostRegion) { ((Extend.Regions.PostRegion)reg.Body).ClearCache(Page, reg); } } } tx.Commit(); if (IsSite) { using (var db = new DataContext()) { var site = db.SiteTrees.Where(s => s.Id == Page.SiteTreeId).Single(); site.MetaTitle = SiteTree.MetaTitle; site.MetaDescription = SiteTree.MetaDescription; db.SaveChanges(); } if (!draft) { PageModel.RemoveSitePageFromCache(Page.SiteTreeId); WebPages.WebPiranha.RegisterDefaultHostNames(); } } } catch { tx.Rollback(); throw; } } return(true); }
/// <summary> /// Handles the URL Rewriting for the application /// </summary> /// <param name="context">Http context</param> public static void BeginRequest(HttpContext context) { try { string path = context.Request.Path.Substring(context.Request.ApplicationPath.Length > 1 ? context.Request.ApplicationPath.Length : 0); string[] args = path.Split(new char[] { '/' }).Subset(1); if (args.Length > 0) { int pos = 0; // Ensure database if (args[0] == "" && SysParam.GetByName("SITE_VERSION") == null) { context.Response.Redirect("~/manager", false); context.Response.EndClean(); } // Check for culture prefix if (Cultures.ContainsKey(args[0])) { System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = Cultures[args[0]]; pos = 1; } else { var def = (GlobalizationSection)WebConfigurationManager.GetSection("system.web/globalization"); if (def != null && !String.IsNullOrWhiteSpace(def.Culture) && !def.Culture.StartsWith("auto:")) { System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(def.UICulture); } } // Check for hostname extension. This feature can't be combined with culture prefixes if (pos == 0) { var segments = context.Request.RawUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (segments.Length > 0) { var hostExt = context.Request.Url.Host + "/" + segments[0]; if (HostNames.ContainsKey(hostExt)) { RequestedSite = new ExtendedHostName() { HostName = context.Request.Url.Host, Extension = segments[0], SiteTree = HostNames[hostExt] }; if (segments[0] == args[0]) { pos = 1; // If this was the last argument, add an empty one if (args.Length == 1) { args = args.Concat(new string[] { "" }).ToArray(); } } } } } var handled = false; // Find the correct request handler foreach (var hr in Application.Current.Handlers) { if (hr.UrlPrefix.ToLower() == args[pos].ToLower()) { if (hr.Id != "PERMALINK" || !Config.PrefixlessPermalinks) { // Don't execute permalink routing in passive mode if ((hr.Id != "PERMALINK" && hr.Id != "STARTPAGE") || !Config.PassiveMode) { // Execute the handler hr.Handler.HandleRequest(context, args.Subset(pos + 1)); handled = true; break; } } } } if (!handled && args[pos].ToLower() == "res.ashx") { Application.Current.Resources.HandleRequest(context, args.Subset(pos + 1)); handled = true; } // If no handler was found and we are using prefixless permalinks, // route traffic to the permalink handler. if (!Config.PassiveMode) { if (!handled && Config.PrefixlessPermalinks && args[pos].ToLower() != "manager" && String.IsNullOrEmpty(context.Request["permalink"])) { if (Permalink.GetByName(Config.SiteTreeNamespaceId, args[pos]) != null || Permalink.GetByName(Config.DefaultNamespaceId, args[pos]) != null) { var handler = Application.Current.Handlers["PERMALINK"]; handler.HandleRequest(context, args.Subset(pos)); } } } } } catch (ThreadAbortException) { // We simply swallow this exception as we don't want unhandled // exceptions flying around causing the app pool to die. } catch (Exception e) { // One catch to rule them all, and in the log file bind them. Application.Current.LogProvider.Error("WebPiranha.BeginRequest", "Unhandled exception", e); context.Response.StatusCode = 500; context.Response.EndClean(); } }
/// <summary> /// Handles the URL Rewriting for the application /// </summary> /// <param name="context">Http context</param> public static void BeginRequest(HttpContext context) { string path = context.Request.Path.Substring(context.Request.ApplicationPath.Length > 1 ? context.Request.ApplicationPath.Length : 0); string[] args = path.Split(new char[] { '/' }).Subset(1); if (args.Length > 0) { int pos = 0; // Ensure database if (args[0] == "" && SysParam.GetByName("SITE_VERSION") == null) { context.Response.Redirect("~/manager"); } // Check for culture prefix if (Cultures.ContainsKey(args[0])) { System.Threading.Thread.CurrentThread.CurrentUICulture = Cultures[args[0]]; pos = 1; } else { var def = (GlobalizationSection)WebConfigurationManager.GetSection("system.web/globalization"); if (def != null) { System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(def.UICulture); } } var handled = false; // Find the correct request handler foreach (RequestHandlerRegistration hr in Handlers.Values) { if (hr.UrlPrefix.ToLower() == args[pos].ToLower()) { if (hr.Id != "PERMALINK" || !PrefixlessPermalinks) { // Execute the handler hr.Handler.HandleRequest(context, args.Subset(pos + 1)); handled = false; break; } } } // If no handler was found and we are using prefixless permalinks, // route traffic to the permalink handler. if (!handled && PrefixlessPermalinks && args[0].ToLower() != "manager") { if (Permalink.GetByName(Config.SiteTreeNamespaceId, args[0]) != null) { var handler = new PermalinkHandler(); handler.HandleRequest(context, args); } } } }
/// <summary> /// Handles the URL Rewriting for the application /// </summary> /// <param name="context">Http context</param> public static void BeginRequest(HttpContext context) { try { string path = context.Request.Path.Substring(context.Request.ApplicationPath.Length > 1 ? context.Request.ApplicationPath.Length : 0); string[] args = path.Split(new char[] { '/' }).Subset(1); if (args.Length > 0) { int pos = 0; // Ensure database if (args[0] == "" && SysParam.GetByName("SITE_VERSION") == null) { context.Response.Redirect("~/manager", false); context.Response.EndClean(); } // Check for culture prefix if (Cultures.ContainsKey(args[0])) { System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = Cultures[args[0]]; pos = 1; } else { var def = (GlobalizationSection)WebConfigurationManager.GetSection("system.web/globalization"); if (def != null) { System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(def.UICulture); } } var handled = false; // Find the correct request handler foreach (var hr in Application.Current.Handlers) { if (hr.UrlPrefix.ToLower() == args[pos].ToLower()) { if (hr.Id != "PERMALINK" || !PrefixlessPermalinks) { // Don't execute permalink routing in passive mode if ((hr.Id != "PERMALINK" && hr.Id != "STARTPAGE") || !Config.PassiveMode) { // Execute the handler hr.Handler.HandleRequest(context, args.Subset(pos + 1)); handled = true; break; } } } } if (!handled && args[pos].ToLower() == "res.ashx") { Application.Current.Resources.HandleRequest(context, args.Subset(pos + 1)); handled = true; } // If no handler was found and we are using prefixless permalinks, // route traffic to the permalink handler. if (!Config.PassiveMode) { if (!handled && PrefixlessPermalinks && args[0].ToLower() != "manager" && String.IsNullOrEmpty(context.Request["permalink"])) { if (Permalink.GetByName(Config.SiteTreeNamespaceId, args[0]) != null || Permalink.GetByName(Config.DefaultNamespaceId, args[0]) != null) { var handler = new PermalinkHandler(); handler.HandleRequest(context, args); } } } } } catch (ThreadAbortException) { // We simply swallow this exception as we don't want unhandled // exceptions flying around causing the app pool to die. } catch (Exception e) { // One catch to rule them all, and in the log file bind them. Application.Current.LogProvider.Error("WebPiranha.BeginRequest", "Unhandled exception", e); context.Response.StatusCode = 500; context.Response.EndClean(); } }
/// <summary> /// Saves the edit model. /// </summary> public bool SaveAll() { var context = HttpContext.Current; var hasfile = UploadedFile != null; byte[] data = null; WebClient web = new WebClient(); if (!hasfile && !String.IsNullOrEmpty(FileUrl)) { data = web.DownloadData(FileUrl); } if (hasfile || data != null) { // Check if this is an image try { Image img = null; if (hasfile) { img = Image.FromStream(UploadedFile.InputStream); } else { MemoryStream mem = new MemoryStream(data); img = Image.FromStream(mem); } // Image img = Image.FromStream(UploadedFile.InputStream) ; try { // Resize the image according to image max width int max = Convert.ToInt32(SysParam.GetByName("IMAGE_MAX_WIDTH").Value); if (max > 0) { img = Drawing.ImageUtils.Resize(img, max); } } catch {} Content.IsImage = true; Content.Width = img.Width; Content.Height = img.Height; } catch { Content.IsImage = false; } if (hasfile) { Content.Filename = UploadedFile.FileName; Content.Type = UploadedFile.ContentType; Content.Size = UploadedFile.ContentLength; } else { Content.Filename = FileUrl.Substring(FileUrl.LastIndexOf('/') + 1); Content.Type = web.ResponseHeaders["Content-Type"]; Content.Size = Convert.ToInt32(web.ResponseHeaders["Content-Length"]); } } if (Content.Save()) { // Save related information Relation.DeleteByDataId(Content.Id); List <Relation> relations = new List <Relation>(); ContentCategories.ForEach(c => relations.Add(new Relation() { DataId = Content.Id, RelatedId = c, IsDraft = false, Type = Relation.RelationType.CONTENTCATEGORY }) ); relations.ForEach(r => r.Save()); // Save the physical file if (hasfile || data != null) { string path = context.Server.MapPath("~/App_Data/content"); if (File.Exists(Content.PhysicalPath)) { File.Delete(Content.PhysicalPath); Content.DeleteCache(); } if (hasfile) { UploadedFile.SaveAs(Content.PhysicalPath); } else { FileStream writer = new FileStream(Content.PhysicalPath, FileMode.Create); BinaryWriter binary = new BinaryWriter(writer); binary.Write(data); binary.Flush(); binary.Close(); } } // Reset file url FileUrl = ""; // Delete possible old thumbnails Content.DeleteCache(); return(true); } return(false); }