/// <summary> /// Handles the BeginRequest event of the AppleseedApplication control. /// </summary> /// <param name="sender"> /// The source of the event. /// </param> /// <param name="e"> /// The <see cref="System.EventArgs"/> instance containing the event data. /// </param> protected void AppleseedApplication_BeginRequest(object sender, EventArgs e) { string Addwww = System.Configuration.ConfigurationManager.AppSettings.Get("AddWwwToRequest"); if (Addwww != null && Addwww.Equals("true")) { if (!Request.IsSecureConnection) { if (!Request.Url.AbsoluteUri.ToLower().Contains("www")) { var newUrl = Request.Url.AbsoluteUri.Replace("http://", "http://www."); Response.Redirect(newUrl, true); } } } /*Send a signal to allow custom js registration (not enabled yet)*/ Bus.Send(new JSRegisterDescriptor() { Scripts = new List<string>() }); var contextReader = new Reader(new WebContextReader()); var context = contextReader.Current; var currentUrl = context.Request.Path.ToLower(); if (Debugger.IsAttached && currentUrl.Contains("trace.axd")) { return; } context.Trace.Warn("Application_BeginRequest :: " + currentUrl); if (Portal.PageID > 0) { var physicalPath = context.Server.MapPath(currentUrl.Substring(currentUrl.LastIndexOf("/") + 1)); if (!File.Exists(physicalPath)) { // Rewrites the path context.RewritePath("~/default.aspx?" + context.Request.ServerVariables["QUERY_STRING"]); } } else { var pname = currentUrl.Substring(currentUrl.LastIndexOf("/") + 1); // if the request was not caused by an MS Ajax Client script invoking a WS. if (!currentUrl.ToLower().EndsWith(".asmx/js")) { if (!String.IsNullOrEmpty(pname) && pname.Length > 5) { pname = pname.Substring(0, pname.Length - 5); } if (Regex.IsMatch(pname, @"^\d+$")) { context.RewritePath( string.Format( "~/default.aspx?pageid={0}{1}", pname, context.Request.ServerVariables["QUERY_STRING"])); } } } // 1st Check: is it a dangerously malformed request? #region // Important patch http://support.microsoft.com/?kbid=887459 if (context.Request.Path.IndexOf('\\') >= 0 || Path.GetFullPath(context.Request.PhysicalPath) != context.Request.PhysicalPath) { throw new AppleseedRedirect(LogLevel.Warn, HttpStatusCode.NotFound, "Malformed request", null); } #endregion // 2nd Check: is the AllPortals Lock switched on? // let the user through if client IP address is in LockExceptions list, otherwise throw... #region if (Config.LockAllPortals) { var rawUrl = context.Request.RawUrl.ToLower(CultureInfo.InvariantCulture); var lockRedirect = Config.LockRedirect; if (!rawUrl.EndsWith(lockRedirect)) { // construct IPList var lockKeyHolders = Config.LockKeyHolders.Split(new[] { ';' }); var ipList = new IPList(); foreach (var lockKeyHolder in lockKeyHolders) { if (lockKeyHolder.IndexOf("-") > -1) { ipList.AddRange( lockKeyHolder.Substring(0, lockKeyHolder.IndexOf("-")), lockKeyHolder.Substring(lockKeyHolder.IndexOf("-") + 1)); } else { ipList.Add(lockKeyHolder); } } // check if requestor's IP address is in allowed list if (!ipList.CheckNumber(context.Request.UserHostAddress)) { throw new PortalsLockedException(); } } } #endregion // 3rd Check: is database/code version correct? var requestUri = context.Request.Url; var requestPath = requestUri.AbsolutePath.ToLower(CultureInfo.InvariantCulture); var returnToRequest = CheckAndUpdateDB(context, requestPath); if (returnToRequest) { return; } PortalSettings portalSettings = null; var pageId = Portal.PageID; // Get PageID from QueryString var portalAlias = Portal.UniqueID; // Get requested alias from querystring, cookies or hostname var defaultAlias = Config.DefaultPortal; // get default portal from config try { portalSettings = PortalSettings.GetPortalSettings(pageId, portalAlias); } catch (DatabaseUnreachableException dexc) { // If no database, must update ErrorHandler.Publish(LogLevel.Error, dexc); using (var s = new Services()) { s.RunDBUpdate(Config.ConnectionString); } portalSettings = PortalSettings.GetPortalSettings(pageId, portalAlias); } if (portalSettings == null || (portalSettings != null && portalSettings.PortalAlias == null)) { portalSettings = PortalSettings.GetPortalSettings(pageId, defaultAlias); } //if (portalSettings.PortalAlias == null) { // // critical error - neither requested alias nor default alias could be found in DB // throw new AppleseedRedirect( // Config.NoPortalErrorRedirect, // LogLevel.Fatal, // Config.NoPortalErrorResponse, // "Unable to load any portal - redirecting request to ErrorNoPortal page.", // null); //} Membership.Provider.ApplicationName = portalSettings.PortalAlias; ProfileManager.Provider.ApplicationName = portalSettings.PortalAlias; Roles.ApplicationName = portalSettings.PortalAlias; // Portal Settings has passed the test so add it to Context context.Items.Add("PortalSettings", portalSettings); context.Items.Add("PortalID", portalSettings.PortalID); // jes1111 var smartErrorRedirect = Config.SmartErrorRedirect; if (smartErrorRedirect.StartsWith("~/")) { smartErrorRedirect = smartErrorRedirect.TrimStart(new[] { '~' }); } if (requestPath.EndsWith(smartErrorRedirect.ToLower(CultureInfo.InvariantCulture))) { return; // this is SmartError page... so continue } // WLF: This was backwards before so it would always set refreshSite true because the cookie was changed before it was checked. // WLF: REVIEW: This whole section needs a code review. // Try to get alias from cookie to determine if alias has been changed var refreshSite = false; var portalAliasCookie = context.Request.Cookies["PortalAlias"]; if (portalAliasCookie != null && portalAliasCookie.Value.ToLower() != Portal.UniqueID) { refreshSite = true; // Portal has changed since last page request } if (portalSettings != null) { portalAliasCookie = new HttpCookie("PortalAlias") { Path = "/", Value = portalSettings.PortalAlias }; if (context.Response.Cookies["PortalAlias"] == null) { context.Response.Cookies.Add(portalAliasCookie); } else { context.Response.Cookies.Set(portalAliasCookie); } } // if switching portals then clean parameters [TipTopWeb] // Must be the last instruction in this method var refreshedCookie = context.Request.Cookies["refreshed"]; // 5/7/2006 Ed Daniel // Added hack for Http 302 by extending condition below to check for more than 3 cookies if (refreshSite && context.Request.Cookies.Keys.Count > 3) { // Sign out and force the browser to refresh only once to avoid any dead-lock if (refreshedCookie == null || refreshedCookie.Value == "false") { var rawUrl = context.Request.RawUrl; var newRefreshedCookie = new HttpCookie("refreshed", "true") { Path = "/", Expires = DateTime.Now.AddMinutes(1) }; if (refreshedCookie == null) { context.Response.Cookies.Add(newRefreshedCookie); } else { context.Response.Cookies.Set(newRefreshedCookie); } var msg = string.Format( "User logged out on global.asax line 423. Values -> refreshsite: {0}, context.Request.Cookies.Keys.count: {1}, rawurl: {2}", refreshSite, context.Request.Cookies.Keys.Count, rawUrl); ErrorHandler.Publish( LogLevel.Warn, msg); // sign-out, if refreshed parameter on the command line we will not call it again PortalSecurity.SignOut(rawUrl, false); } } // invalidate cookie, so the page can be refreshed when needed refreshedCookie = context.Request.Cookies["refreshed"]; if (refreshedCookie != null && context.Request.Cookies.Keys.Count > 3) { var newRefreshedCookie = new HttpCookie("refreshed", "false") { Path = "/", Expires = DateTime.Now.AddMinutes(1) }; context.Response.Cookies.Set(newRefreshedCookie); } // This is done in order to allow the sitemap to reference a page that is outside this website. var targetPage = this.Request.Params["sitemapTargetPage"]; if (!string.IsNullOrEmpty(targetPage)) { int mvcPageId; if (int.TryParse(targetPage, out mvcPageId)) { var url = HttpUrlBuilder.BuildUrl(mvcPageId); this.Response.Redirect(url); } } }
/// <summary> /// Handles OnLoad event at Page level<br/> /// Performs OnLoad actions that are common to all Pages. /// </summary> /// <param name="e"> /// The <see cref="T:System.EventArgs"/> object that contains the event data. /// </param> /// <remarks> /// </remarks> protected override void OnLoad(EventArgs e) { base.OnLoad(e); // load the dedicated CSS if (!this.IsCssFileRegistered("SmartError")) { this.RegisterCssFile("Mod_SmartError"); } List<object> storedError = null; var sb = new StringBuilder(); // to build response text var httpStatusCode = (int)HttpStatusCode.InternalServerError; // default value const string ValidStatus = "301;307;403;404;410;500;501;502;503;504"; if (this.Request.QueryString.Count > 0 && this.Request.QueryString[0] != null) { // is this a "MagicUrl" request if (this.Request.QueryString[0].StartsWith("404;http://")) { var redirectUrl = string.Empty; var qPart = string.Empty; var qPartPos = this.Request.QueryString[0].LastIndexOf("/") + 1; qPart = qPartPos < this.Request.QueryString[0].Length ? this.Request.QueryString[0].Substring(qPartPos) : string.Empty; if (qPart.Length > 0) { if (Utils.IsInteger(qPart)) { redirectUrl = HttpUrlBuilder.BuildUrl(Int32.Parse(qPart)); } else { Hashtable magicUrlList = this.GetMagicUrlList(Portal.UniqueID); if (magicUrlList != null && magicUrlList.ContainsKey(HttpUtility.HtmlEncode(qPart))) { redirectUrl = HttpUtility.HtmlDecode(magicUrlList[HttpUtility.HtmlEncode(qPart)].ToString()); if (Utils.IsInteger(redirectUrl)) { redirectUrl = HttpUrlBuilder.BuildUrl(Int32.Parse(redirectUrl)); } } } if (redirectUrl.Length != 0) { this.Response.Redirect(redirectUrl, true); } else { httpStatusCode = (int)HttpStatusCode.NotFound; } } } else if (Utils.IsInteger(this.Request.QueryString[0]) && ValidStatus.IndexOf(this.Request.QueryString[0]) > -1) { // get status code from query string httpStatusCode = int.Parse(this.Request.QueryString[0]); } } // get stored error if (this.Request.QueryString["eid"] != null && this.Request.QueryString["eid"].Length > 0) { storedError = (List<object>)CurrentCache.Get(this.Request.QueryString["eid"]); } string renderedEvent = storedError != null && storedError[_RENDEREDEVENT_] != null ? storedError[_RENDEREDEVENT_].ToString() : @"<p>No exception event stored or cache has expired.</p>"; // get home link var homeUrl = HttpUrlBuilder.BuildUrl(); // try localizing message try { switch (httpStatusCode) { case (int)HttpStatusCode.NotFound: // 404 case (int)HttpStatusCode.Gone: // 410 case (int)HttpStatusCode.MovedPermanently: // 301 case (int)HttpStatusCode.TemporaryRedirect: // 307 sb.AppendFormat( "<h3>{0}</h3>", General.GetString("SMARTERROR_404HEADING", "Page Not Found", null)); sb.AppendFormat( "<p>{0}</p>", General.GetString( "SMARTERROR_404TEXT", "We're sorry, but there is no page that matches your entry. It is possible you typed the address incorrectly, or the page may no longer exist. You may wish to try another entry or choose from the links below, which we hope will help you find what you’re looking for.", null)); break; case (int)HttpStatusCode.Forbidden: // 403 sb.AppendFormat( "<h3>{0}</h3>", General.GetString("SMARTERROR_403HEADING", "Not Authorised", null)); sb.AppendFormat( "<p>{0}</p>", General.GetString( "SMARTERROR_403TEXT", "You do not have the required authority for the requested page or action.", null)); break; default: sb.AppendFormat( "<h3>{0}</h3>", General.GetString("SMARTERROR_500HEADING", "Our Apologies", null)); sb.AppendFormat( "<p>{0}</p>", General.GetString( "SMARTERROR_500TEXT", "We're sorry, but we were unable to service your request. It's possible that the problem is a temporary condition.", null)); break; } sb.AppendFormat("<p><a href=\"{0}\">{1}</a></p>", homeUrl, General.GetString("HOME", "Home Page", null)); } catch { // default to english message switch (httpStatusCode) { case (int)HttpStatusCode.NotFound: sb.Append("<h3>Page Not Found</h3>"); sb.Append( "<p>We're sorry, but there is no page that matches your entry. It is possible you typed the address incorrectly, or the page may no longer exist. You may wish to try another entry or choose from the links below, which we hope will help you find what you’re looking for.</p>"); break; case (int)HttpStatusCode.Forbidden: sb.Append("<h3>Not Authorised</h3>"); sb.Append("<p>You do not have the required authority for the requested page or action.</p>"); break; default: sb.Append("<h3>Our Apologies</h3>"); sb.AppendFormat( "<p>We're sorry, but we were unable to service your request. It's possible that the problem is a temporary condition.</p>"); break; } sb.AppendFormat("<p><a href=\"{0}\">{1}</a></p>", homeUrl, "Home Page"); } // find out if user is on allowed IP Address if (this.Request.UserHostAddress != null && this.Request.UserHostAddress.Length > 0) { // construct IPList var lockKeyHolders = Config.LockKeyHolders.Split(new[] { ';' }); // ConfigurationSettings.AppSettings["LockKeyHolders"].Split(new char[]{';'}); var ipList = new IPList(); try { foreach (var lockKeyHolder in lockKeyHolders) { if (lockKeyHolder.IndexOf("-") > -1) { ipList.AddRange( lockKeyHolder.Substring(0, lockKeyHolder.IndexOf("-")), lockKeyHolder.Substring(lockKeyHolder.IndexOf("-") + 1)); } else { ipList.Add(lockKeyHolder); } } // check if it has to show the full detail error message bool showError = false; if (this.PortalSettings.CustomSettings["DETAIL_ERROR_MESSAGE"] != null) { showError = bool.Parse(this.PortalSettings.CustomSettings["DETAIL_ERROR_MESSAGE"].ToString()); } // check if requestor's IP address is in allowed list if (ipList.CheckNumber(this.Request.UserHostAddress) || showError) { // we can show error details sb.AppendFormat( "<h3>{0} - {1}</h3>", General.GetString("SMARTERROR_SUPPORTDETAILS_HEADING", "Support Details", null), httpStatusCode); sb.Append(renderedEvent); } } catch { // if there was a problem, let's assume that user is not authorized } } //this.Response.StatusCode = httpStatusCode; this.Response.Cache.SetCacheability(HttpCacheability.NoCache); }