Пример #1
0
        protected void Add_Html()
        {
            if (Session["Last_Exception"] != null)
            {
                Exception lastException = (Exception)Session["Last_Exception"];
                SobekCM_Traced_Exception tracedException = lastException as SobekCM_Traced_Exception;
                if (tracedException != null)
                {
                    Response.Output.WriteLine("<h1>EXCEPTION CAUGHT</h1><br />");
                    Response.Output.WriteLine("<h2>SobekCM Message</h2>");
                    Response.Output.WriteLine("<blockquote>" + tracedException.Message + "</blockquote>");
                    Response.Output.WriteLine("<h2>Inner Message</h2>");
                    Response.Output.WriteLine("<blockquote>" + tracedException.InnerException.Message + "</blockquote>");
                    if (tracedException.InnerException.StackTrace.Length > 0)
                    {
                        Response.Output.WriteLine("<h2>Stack Trace</h2>");
                        Response.Output.WriteLine("<blockquote>" + tracedException.InnerException.StackTrace.Replace("\n", "<br />") + "</blockquote>");
                    }
                    Response.Output.WriteLine("<h2>SobekCM Tracer</h2>");

                    Response.Output.WriteLine("<style type=\"text/css\">");
                    Response.Output.WriteLine("table.Traceroute { border-width: 2px; border-style: solid; border-color: gray; border-collapse: collapse; background-color: white; font-size: small; }");
                    Response.Output.WriteLine("table.Traceroute th { border-width: 2px; padding: 3px; border-style: solid; border-color: gray; background-color: gray; color: white; }");
                    Response.Output.WriteLine("table.Traceroute td { border-width: 2px; padding: 3px; border-style: solid; border-color: gray;	background-color: white; }");
                    Response.Output.WriteLine("</style>");
                    Response.Output.WriteLine("<blockquote>");
                    Response.Output.WriteLine(tracedException.Trace_Route_HTML);
                    Response.Output.WriteLine("</blockquote>");
                }
                else
                {
                    Response.Output.WriteLine("<h1>EXCEPTION CAUGHT</h1><br /><br />");
                    Response.Output.WriteLine("<h2>Message</h2>");
                    Response.Output.WriteLine("<blockquote>" + lastException.Message + "</blockquote>");
                    if (lastException.StackTrace.Length > 0)
                    {
                        Response.Output.WriteLine("<h2>Stack Trace</h2>");
                        Response.Output.WriteLine("<blockquote>" + lastException.StackTrace + "</blockquote>");
                    }
                }

                // Clear this exception now
                HttpContext.Current.Session.Remove("Last_Exception");
            }
            else
            {
                Response.Output.WriteLine("<h1>SobekCM Dashboard</h1>");
                Response.Output.WriteLine("This dashboard is currently only used to display exceptions when the application is run locally.<br /><br />");
                Response.Output.WriteLine("In upcoming versions this screen will be used to assess the overall health of the SobekCM system and spot possible problems.");
            }
        }
Пример #2
0
        protected void Page_Load(object Sender, EventArgs E)
        {
            // Pull out the http request
            HttpRequest request = HttpContext.Current.Request;

            if (String.IsNullOrEmpty(SobekCM_Database.Connection_String))
            {
                Custom_Tracer tracer = new Custom_Tracer();
                try
                {
                    tracer.Add_Trace("SobekCM_Page_Globals.Constructor", String.Empty);

                    // Don't really need to *build* these, so just define them as a new ones if null
                    if (Global.Checked_List == null)
                    {
                        Global.Checked_List = new Checked_Out_Items_List();
                    }
                    if (Global.Search_History == null)
                    {
                        Global.Search_History = new Recent_Searches();
                    }

                    // Make sure all the needed data is loaded into the Application State
                    Application_State_Builder.Build_Application_State(tracer, false, ref Global.Skins, ref Global.Translation,
                                                                      ref Global.Codes, ref Global.Item_List, ref Global.Icon_List,
                                                                      ref Global.Stats_Date_Range, ref Global.Thematic_Headings, ref Global.Collection_Aliases, ref Global.IP_Restrictions,
                                                                      ref Global.URL_Portals, ref Global.Mime_Types, ref Global.Item_Viewer_Priority);

                    tracer.Add_Trace("SobekCM_Page_Globals.Constructor", "Application State validated or built");

                    // Check that something is saved for the original requested URL (may not exist if not forwarded)
                    if (!HttpContext.Current.Items.Contains("Original_URL"))
                    {
                        HttpContext.Current.Items["Original_URL"] = request.Url.ToString();
                    }
                }
                catch (Exception ee)
                {
                    // Send to the dashboard
                    if ((HttpContext.Current.Request.UserHostAddress == "127.0.0.1") || (HttpContext.Current.Request.UserHostAddress == HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]) || (HttpContext.Current.Request.Url.ToString().IndexOf("localhost") >= 0))
                    {
                        // Create an error message
                        string errorMessage;
                        if ((SobekCM_Library_Settings.Database_Connections.Count == 0) || (String.IsNullOrEmpty(SobekCM_Library_Settings.Database_Connections[0].Connection_String)))
                        {
                            errorMessage = "No database connection string found!";
                            string configFileLocation = AppDomain.CurrentDomain.BaseDirectory + "config/sobekcm.xml";
                            try
                            {
                                if (!File.Exists(configFileLocation))
                                {
                                    errorMessage = "Missing config/sobekcm.xml configuration file on the web server.<br />Ensure the configuration file 'sobekcm.xml' exists in a 'config' subfolder directly under the web application.<br />Example configuration is:" +
                                                   "<div style=\"background-color: #bbbbbb; margin-left: 30px; margin-top:10px; padding: 3px;\">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;  ?&gt;<br /> &lt;configuration&gt;<br /> &nbsp; &nbsp &lt;connection_string type=&quot;MSSQL&quot;&gt;data source=localhost\\instance;initial catalog=SobekCM;integrated security=Yes;&lt;/connection_string&gt;<br /> &nbsp; &nbsp &lt;error_emails&gt;[email protected]&lt;/error_emails&gt;<br /> &nbsp; &nbsp &lt;error_page&gt;http://ufdc.ufl.edu/error.html&lt;/error_page&gt;<br />&lt;/configuration&gt;</div>";
                                }
                            }
                            catch
                            {
                                errorMessage = "No database connection string found.<br />Likely an error reading the configuration file due to permissions on the web server.<br />Ensure the configuration file 'sobekcm.xml' exists in a 'config' subfolder directly under the web application.<br />Example configuration is:" +
                                               "<div style=\"background-color: #bbbbbb; margin-left: 30px; margin-top:10px; padding: 3px;\">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;  ?&gt;<br /> &lt;configuration&gt;<br /> &nbsp; &nbsp &lt;connection_string type=&quot;MSSQL&quot;&gt;data source=localhost\\instance;initial catalog=SobekCM;integrated security=Yes;&lt;/connection_string&gt;<br /> &nbsp; &nbsp &lt;error_emails&gt;[email protected]&lt;/error_emails&gt;<br /> &nbsp; &nbsp &lt;error_page&gt;http://ufdc.ufl.edu/error.html&lt;/error_page&gt;<br />&lt;/configuration&gt;</div>";
                            }
                        }
                        else
                        {
                            if (ee.Message.IndexOf("The EXECUTE permission") >= 0)
                            {
                                errorMessage = "Permissions error while connecting to the database and pulling necessary data.<br /><br />Confirm the following:<ul><li>IIS is configured correctly to use anonymous authentication</li><li>Anonymous user (or service account) is part of the sobek_users role in the database.</li></ul>";
                            }
                            else
                            {
                                errorMessage = "Error connecting to the database and pulling necessary data.<br /><br />Confirm the following:<ul><li>Database connection string is correct ( " + SobekCM_Library_Settings.Database_Connections[0].Connection_String + ")</li><li>IIS is configured correctly to use anonymous authentication</li><li>Anonymous user (or service account) is part of the sobek_users role in the database.</li></ul>";
                            }
                        }
                        // Wrap this into the SobekCM Exception
                        SobekCM_Traced_Exception newException = new SobekCM_Traced_Exception(errorMessage, ee, tracer);

                        // Save this to the session state, and then forward to the dashboard
                        HttpContext.Current.Session["Last_Exception"] = newException;
                        HttpContext.Current.Response.Redirect("dashboard.aspx", true);
                    }
                    else
                    {
                        throw ee;
                    }
                }
            }


            string bibID = null;
            string vid   = null;

            // Is this a robot?  They should never get access to files this way
            if (SobekCM_Navigation_Object.Is_UserAgent_IP_Robot(request.UserAgent, request.UserHostAddress))
            {
                Response.Clear();
                Response.Output.WriteLine("RESTRICTED ITEM");
                return;
            }

            // Get any url rewrite which occurred
            if (Request.QueryString["urlrelative"] != null)
            {
                string urlrewrite = Request.QueryString["urlrelative"].ToLower();
                if (urlrewrite.Length > 4)
                {
                    // Split the url relative list
                    string[]      url_relative_info = urlrewrite.Split("/".ToCharArray());
                    List <string> url_relative_list = (from thisPart in url_relative_info where thisPart.Length > 0 select thisPart.ToLower()).ToList();

                    // Now, look for BIBID and VID
                    //if ((SobekCM_Database.Verify_Item_Lookup_Object(true, ref Global.Item_List, null)) && (Global.Item_List.Contains_BibID(url_relative_list[2].ToUpper())))
                    if ((url_relative_list.Count > 2) && (url_relative_list[2].Length == 10))
                    {
                        // This is a BibID for an existing title with at least one public item
                        bibID = url_relative_list[2].ToUpper();

                        // Is the next part a VID?
                        if (url_relative_list.Count > 3)
                        {
                            string possible_vid = url_relative_list[3].Trim().PadLeft(5, '0');
                            int    vid_as_int;
                            if (Int32.TryParse(possible_vid, out vid_as_int))
                            {
                                vid = possible_vid;
                            }
                        }
                    }

                    // Only continue if there is a BibID / VID
                    if ((!String.IsNullOrEmpty(bibID)) && (!String.IsNullOrEmpty(vid)))
                    {
                        // Determine the new URL
                        StringBuilder urlBuilder = new StringBuilder(SobekCM_Library_Settings.Image_Server_Network + bibID.Substring(0, 2) + "\\" + bibID.Substring(2, 2) + "\\" + bibID.Substring(4, 2) + "\\" + bibID.Substring(6, 2) + "\\" + bibID.Substring(8) + "\\" + vid + "\\" + url_relative_list[4], 250);
                        for (int i = 5; i < url_relative_list.Count; i++)
                        {
                            urlBuilder.Append("\\" + url_relative_list[i]);
                        }

                        file_url = urlBuilder.ToString();


                        // Get the extension
                        string extension = Path.GetExtension(file_url);
                        if (extension != null)
                        {
                            // Lookup the MIME type by extension
                            Mime_Type_Info mimeType = null;
                            if (Global.Mime_Types.ContainsKey(extension.ToLower()))
                            {
                                mimeType = Global.Mime_Types[extension.ToLower()];
                            }

                            if ((mimeType != null) && (!mimeType.isBlocked))
                            {
                                // Since everything is valid, check the database
                                bool  isDark;
                                short restrictions;
                                SobekCM_Database.Get_Item_Restrictions(bibID, vid, null, out isDark, out restrictions);

                                // If not DARK, and is restricted, check for access here
                                if ((!isDark) && (restrictions > 0))
                                {
                                    // Does this user already have IP restriction mask determined?
                                    // Determine which IP Ranges this IP address belongs to, if not already determined.

                                    if (HttpContext.Current.Session["IP_Range_Membership"] == null)
                                    {
                                        int ip_mask = Global.IP_Restrictions.Restrictive_Range_Membership(request.UserHostAddress);
                                        HttpContext.Current.Session["IP_Range_Membership"] = ip_mask;
                                    }

                                    int current_user_mask = Convert.ToInt32(HttpContext.Current.Session["IP_Range_Membership"]);

                                    // Perform bitwise comparison
                                    int comparison = restrictions & current_user_mask;
                                    if (comparison == 0)
                                    {
                                        // If the user is Shibboleth authenticated, that is okay
                                        User_Object possible_user = HttpContext.Current.Session["user"] as User_Object;
                                        if ((possible_user == null) || (possible_user.Authentication_Type != User_Authentication_Type_Enum.Shibboleth))
                                        {
                                            isDark = true;
                                        }
                                    }
                                }

                                if (!isDark)
                                {
                                    // Should this be forwarded for this mimetype?
                                    if (mimeType.shouldForward)
                                    {
                                        StringBuilder forwardBuilder = new StringBuilder(SobekCM_Library_Settings.Image_URL + bibID.Substring(0, 2) + "/" + bibID.Substring(2, 2) + "/" + bibID.Substring(4, 2) + "/" + bibID.Substring(6, 2) + "/" + bibID.Substring(8) + "/" + vid + "/" + url_relative_list[4], 250);
                                        for (int i = 5; i < url_relative_list.Count; i++)
                                        {
                                            forwardBuilder.Append("/" + url_relative_list[i]);
                                        }
                                        Response.Redirect(forwardBuilder.ToString());
                                    }
                                    else
                                    {
                                        Response.Clear();
                                        Response.ContentType = mimeType.MIME_Type;

                                        string filename = file_url;

                                        if (File.Exists(filename))
                                        {
                                            using (FileStream sourceStream = File.OpenRead(filename))
                                            {
                                                sourceStream.CopyTo(Response.OutputStream, 32768);
                                            }
                                        }

                                        Response.End();
                                    }
                                }
                                else
                                {
                                    Response.Clear();
                                    Response.Output.WriteLine("RESTRICTED ITEM");
                                }
                            }
                        }
                    }
                }
            }

            //public static async Task CopyToAsync(this Stream source, Stream destination)
            //{
            //    int i = 0;
            //    var buffers = new [] { new byte[0x1000], new byte[0x1000] };
            //    Task writeTask = null;
            //    while(true)
            //    {
            //        var readTask = source.ReadAsync(buffers[i], 0, buffers[i].Length))>0;
            //        if (writeTask != null) await Task.WhenAll(readTask, writeTask);
            //        int bytesRead = await readTask;
            //        if (bytesRead == 0) break;
            //        writeTask = destination.WriteAsync(buffers[i], 0, bytesRead);
            //        i ^= 1; // swap buffers
            //    }
            //}
        }
        protected void Application_Error(object Sender, EventArgs E)
        {
            // Get the exception
            Exception objErr = Server.GetLastError();

            if (objErr == null)
            {
                return;
            }

            objErr = objErr.GetBaseException();

            try
            {
                // Justs clear the error for a number of common errors, caused by invalid requests to the server
                if ((objErr.Message.IndexOf("potentially dangerous") >= 0) || (objErr.Message.IndexOf("a control with id ") >= 0) || (objErr.Message.IndexOf("Padding is invalid and cannot be removed") >= 0) || (objErr.Message.IndexOf("This is an invalid webresource request") >= 0) ||
                    ((objErr.Message.IndexOf("File") >= 0) && (objErr.Message.IndexOf("does not exist") >= 0)))
                {
                    // Clear the error
                    Server.ClearError();
                }
                else
                {
                    try
                    {
                        StreamWriter writer = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\temp\\exceptions.txt", true);
                        writer.WriteLine();
                        writer.WriteLine("Error Caught in Application_Error event ( " + DateTime.Now.ToString() + ")");
                        writer.WriteLine("User Host Address: " + Request.UserHostAddress);
                        writer.WriteLine("Requested URL: " + Request.Url);
                        if (objErr is SobekCM_Traced_Exception)
                        {
                            SobekCM_Traced_Exception sobekException = (SobekCM_Traced_Exception)objErr;

                            writer.WriteLine("Error Message: " + sobekException.InnerException.Message);
                            writer.WriteLine("Stack Trace: " + objErr.StackTrace);
                            writer.WriteLine("Error Message:" + sobekException.InnerException.StackTrace);
                            writer.WriteLine();
                            writer.WriteLine(sobekException.Trace_Route);
                        }
                        else
                        {
                            writer.WriteLine("Error Message: " + objErr.Message);
                            writer.WriteLine("Stack Trace: " + objErr.StackTrace);
                        }

                        writer.WriteLine();
                        writer.WriteLine("------------------------------------------------------------------");
                        writer.Flush();
                        writer.Close();
                    }
                    catch (Exception)
                    {
                        // Nothing else to do here.. no other known way to log this error
                    }
                }
            }
            catch (Exception)
            {
                // Nothing else to do here.. no other known way to log this error
            }
            finally
            {
                // Clear the error
                Server.ClearError();

                string error_message = objErr.Message;
                if (objErr is SobekCM_Traced_Exception)
                {
                    SobekCM_Traced_Exception sobekException = (SobekCM_Traced_Exception)objErr;
                    error_message = sobekException.InnerException.Message;
                }

                try
                {
                    if ((HttpContext.Current.Request.UserHostAddress == "127.0.0.1") || (HttpContext.Current.Request.UserHostAddress == HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]) || (HttpContext.Current.Request.Url.ToString().IndexOf("localhost") >= 0))
                    {
                        Response.Redirect("error_echo.html?text=" + error_message.Replace(" ", "_").Replace("&", "and").Replace("?", ""), false);
                    }
                    else
                    {
                        // Forward if there is a place to forward to.
                        if (!String.IsNullOrEmpty(SobekCM_Library_Settings.System_Error_URL))
                        {
                            Response.Redirect(SobekCM_Library_Settings.System_Error_URL, false);
                        }
                        else
                        {
                            Response.Redirect("http://ufdc.ufl.edu/sobekcm/missing_config", false);
                        }
                    }
                }
                catch (Exception)
                {
                    // Nothing else to do here.. no other known way to log this error
                }
            }
        }
        public SobekCM_Page_Globals(bool isPostBack, string page_name)
        {
            // Pull out the http request
            HttpRequest request = HttpContext.Current.Request;

            // Get the base url
            string base_url = request.Url.AbsoluteUri.ToLower().Replace("sobekcm.aspx", "");
            if (base_url.IndexOf("?") > 0)
                base_url = base_url.Substring(0, base_url.IndexOf("?"));

            try
            {
                tracer = new Custom_Tracer();
                tracer.Add_Trace("SobekCM_Page_Globals.Constructor", "Starting");
                SobekCM_Database.Connection_String = UI_ApplicationCache_Gateway.Settings.Database_Connections[0].Connection_String;

                // If this is running on localhost, and in debug, set base directory to this one
            #if DEBUG
                if (base_url.IndexOf("localhost:") > 0)
                {
                    UI_ApplicationCache_Gateway.Settings.Servers.System_Base_URL = base_url;
                    UI_ApplicationCache_Gateway.Settings.Servers.Base_URL = base_url;

                }
            #endif

                // Ensure the settings base directory is set correctly
                if ( String.IsNullOrEmpty(UI_ApplicationCache_Gateway.Settings.Servers.Base_Directory))
                {
                    string baseDir = System.Web.HttpContext.Current.Server.MapPath("~");
                    if ((baseDir.Length > 0) && (baseDir[baseDir.Length - 1] != '\\'))
                        baseDir = baseDir + "\\";
                    UI_ApplicationCache_Gateway.Settings.Servers.Base_Directory = baseDir;

                    SobekCM_Database.Set_Setting("Application Server Network", baseDir);
                }

                // Ensure the web server IP address is set correctly
                if (String.IsNullOrEmpty(UI_ApplicationCache_Gateway.Settings.Servers.SobekCM_Web_Server_IP))
                {
                    string ip = get_local_ip();
                    if (ip.Length > 0)
                    {
                        UI_ApplicationCache_Gateway.Settings.Servers.SobekCM_Web_Server_IP = ip;

                        SobekCM_Database.Set_Setting("SobekCM Web Server IP", ip);
                    }
                }

                // (TEMPORARY FOR UF)
                if (( !String.IsNullOrEmpty(UI_ApplicationCache_Gateway.Settings.System.System_Abbreviation)) && ( UI_ApplicationCache_Gateway.Settings.System.System_Abbreviation.IndexOf("UFDC") == 0))
                {
                    string baseDir = System.Web.HttpContext.Current.Server.MapPath("~");
                    UI_ApplicationCache_Gateway.Settings.Servers.Base_Directory = baseDir;
                }

                // Check that something is saved for the original requested URL (may not exist if not forwarded)
                if (!HttpContext.Current.Items.Contains("Original_URL"))
                    HttpContext.Current.Items["Original_URL"] = request.Url.ToString();
            }
            catch (Exception ee)
            {
                tracer.Add_Trace("SobekCM_Page_Globals.Constructor", "Exception caught around line 129: " + ee.Message);
                tracer.Add_Trace("SobekCM_Page_Globals.Constructor", ee.StackTrace);

                // Send to the dashboard
                if ((HttpContext.Current.Request.UserHostAddress == "127.0.0.1") || (HttpContext.Current.Request.UserHostAddress == HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]) || (HttpContext.Current.Request.Url.ToString().IndexOf("localhost") >= 0))
                {
                    // Create an error message
                    string errorMessage = "Error caught while validating application state";
                    if ((UI_ApplicationCache_Gateway.Settings.Database_Connections.Count == 0) || (String.IsNullOrEmpty(UI_ApplicationCache_Gateway.Settings.Database_Connections[0].Connection_String)))
                    {
                        errorMessage = "No database connection string found!";
                        string configFileLocation = AppDomain.CurrentDomain.BaseDirectory + "config/sobekcm.xml";
                        try
                        {
                            if (!File.Exists(configFileLocation))
                            {
                                errorMessage = "Missing config/sobekcm.xml configuration file on the web server.<br />Ensure the configuration file 'sobekcm.xml' exists in a 'config' subfolder directly under the web application.<br />Example configuration is:" +
                                               "<div style=\"background-color: #bbbbbb; margin-left: 30px; margin-top:10px; padding: 3px;\">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;  ?&gt;<br /> &lt;configuration&gt;<br /> &nbsp; &nbsp &lt;connection_string type=&quot;MSSQL&quot;&gt;data source=localhost\\instance;initial catalog=SobekCM;integrated security=Yes;&lt;/connection_string&gt;<br /> &nbsp; &nbsp &lt;error_emails&gt;[email protected]&lt;/error_emails&gt;<br /> &nbsp; &nbsp &lt;error_page&gt;http://ufdc.ufl.edu/error.html&lt;/error_page&gt;<br />&lt;/configuration&gt;</div>";
                            }
                        }
                        catch
                        {
                            errorMessage = "No database connection string found.<br />Likely an error reading the configuration file due to permissions on the web server.<br />Ensure the configuration file 'sobekcm.xml' exists in a 'config' subfolder directly under the web application.<br />Example configuration is:" +
                                           "<div style=\"background-color: #bbbbbb; margin-left: 30px; margin-top:10px; padding: 3px;\">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;  ?&gt;<br /> &lt;configuration&gt;<br /> &nbsp; &nbsp &lt;connection_string type=&quot;MSSQL&quot;&gt;data source=localhost\\instance;initial catalog=SobekCM;integrated security=Yes;&lt;/connection_string&gt;<br /> &nbsp; &nbsp &lt;error_emails&gt;[email protected]&lt;/error_emails&gt;<br /> &nbsp; &nbsp &lt;error_page&gt;http://ufdc.ufl.edu/error.html&lt;/error_page&gt;<br />&lt;/configuration&gt;</div>";
                        }
                    }
                    else
                    {
                        if (ee.Message.IndexOf("The EXECUTE permission") >= 0)
                        {
                            errorMessage = "Permissions error while connecting to the database and pulling necessary data.<br /><br />Confirm the following:<ul><li>IIS is configured correctly to use anonymous authentication</li><li>Anonymous user (or service account) is part of the sobek_users role in the database.</li></ul>";
                        }
                        else
                        {
                            errorMessage = "Error connecting to the database and pulling necessary data.<br /><br />Confirm the following:<ul><li>Database connection string is correct ( " + UI_ApplicationCache_Gateway.Settings.Database_Connections[0].Connection_String + ")</li><li>IIS is configured correctly to use anonymous authentication</li><li>Anonymous user (or service account) is part of the sobek_users role in the database.</li></ul>";
                        }
                    }
                    // Wrap this into the SobekCM Exception
                    SobekCM_Traced_Exception newException = new SobekCM_Traced_Exception(errorMessage, ee, tracer);

                    // Save this to the session state, and then forward to the dashboard
                    HttpContext.Current.Session["Last_Exception"] = newException;
                    HttpContext.Current.Response.Redirect("dashboard.aspx", false);
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                    return;
                }
                else
                {
                    throw ee;
                }
            }

            tracer.Add_Trace("SobekCM_Page_Globals.Constructor", "About to parse the URL for the navigation object");

            // Analyze the response and get the mode
            try
            {
                currentMode = new Navigation_Object();
                NameValueCollection queryString = request.QueryString;

                QueryString_Analyzer.Parse_Query(queryString, currentMode, base_url, request.UserLanguages, UI_ApplicationCache_Gateway.Aggregations, UI_ApplicationCache_Gateway.Collection_Aliases, UI_ApplicationCache_Gateway.Items, UI_ApplicationCache_Gateway.URL_Portals, UI_ApplicationCache_Gateway.WebContent_Hierarchy, tracer);

                currentMode.Base_URL=base_url;
                currentMode.isPostBack = isPostBack;
                currentMode.Browser_Type = request.Browser.Type.ToUpper();
                currentMode.Set_Robot_Flag(request.UserAgent, request.UserHostAddress);

                defaultSkin = currentMode.Skin;
            }
            catch  ( Exception ee )
            {
                tracer.Add_Trace("SobekCM_Page_Globals.Constructor", "Exception caught around line 198: " + ee.Message);
                tracer.Add_Trace("SobekCM_Page_Globals.Constructor", ee.StackTrace);

                HttpContext.Current.Response.Status = "301 Moved Permanently";
                HttpContext.Current.Response.AddHeader("Location", base_url);
                HttpContext.Current.ApplicationInstance.CompleteRequest();
                return;
            }

            tracer.Add_Trace("SobekCM_Page_Globals.Constructor", "Navigation parse completed");

            // If this was for HTML, but was at the data, just convert to XML
            if ((page_name == "SOBEKCM_DATA") && (currentMode.Writer_Type != Writer_Type_Enum.XML) && (currentMode.Writer_Type != Writer_Type_Enum.JSON) && (currentMode.Writer_Type != Writer_Type_Enum.DataSet) && (currentMode.Writer_Type != Writer_Type_Enum.Data_Provider))
                currentMode.Writer_Type = Writer_Type_Enum.XML;

            tracer.Add_Trace("SobekCM_Page_Globals.Constructor", "Navigation Object created from URI query string");

            try
            {
                // If this was an error, redirect now
                if (currentMode.Mode == Display_Mode_Enum.Error)
                {
                    return;
                }

                // All the user stuff can be skipped if this was from a robot
                if (!currentMode.Is_Robot)
                {
                    // Determine which IP Ranges this IP address belongs to, if not already determined.
                    if (HttpContext.Current.Session["IP_Range_Membership"] == null)
                    {
                        int ip_mask = UI_ApplicationCache_Gateway.IP_Restrictions.Restrictive_Range_Membership(request.UserHostAddress);
                        HttpContext.Current.Session["IP_Range_Membership"] = ip_mask;
                    }

                    // Set the Session TOC, if provided
                    if (currentMode.TOC_Display != TOC_Display_Type_Enum.Undetermined)
                    {
                        if (currentMode.TOC_Display == TOC_Display_Type_Enum.Hide)
                        {
                            HttpContext.Current.Session["Show TOC"] = false;
                        }
                        else
                        {
                            HttpContext.Current.Session["Show TOC"] = true;
                        }
                    }

                    // Only do any of the user stuff if this is from the main SobekCM page
                    if (page_name == "SOBEKCM")
                    {
                        tracer.Add_Trace("SobekCM_Page_Globals.Constructor", "Checking for logged on user by cookie or session");
                        perform_user_checks(isPostBack);
                    }

                    // If this is a system admin, they can run as a different user actually
                    if ((currentUser != null) && (currentUser.Is_System_Admin) && (request.QueryString["userid"] != null))
                    {
                        try
                        {
                            int userid = Convert.ToInt32(request.QueryString["userid"]);
                            User_Object mirroredUser = SobekCM_Database.Get_User(userid, tracer);
                            if (mirroredUser != null)
                            {
                                // Replace the user information in the session state
                                HttpContext.Current.Session["user"] = mirroredUser;
                                currentUser = mirroredUser;
                            }
                        }
                        catch (Exception)
                        {
                            // Nothing to do here.. shouldn't ever really be here..
                        }
                    }

                    if (currentMode.Request_Completed)
                        return;

                    // If this was a call for RESET, clear the memory
                    if ((currentMode.Mode == Display_Mode_Enum.Administrative) && (currentMode.Admin_Type == Admin_Type_Enum.Reset))
                    {
                        Reset_Memory();

                        // Also re-read the configuration file for static resources
                        Static_Resources.Config_Read_Attempted = false;

                        // Since this reset, send to the admin, memory management portion
                        currentMode.Mode = Display_Mode_Enum.Internal;
                        currentMode.Internal_Type = Internal_Type_Enum.Cache;
                    }
                }
                else // THIS IS A ROBOT REQUEST
                {
                    Perform_Search_Engine_Robot_Checks(currentMode, request.QueryString);
                }

                // If this is for a public folder, get the data
                if (currentMode.Mode == Display_Mode_Enum.Public_Folder)
                {
                    Public_Folder();
                }

                // Get the item now, so that you can set the collection code, if there was none listed
                if ((currentMode.Mode == Display_Mode_Enum.Item_Display) || (currentMode.Mode == Display_Mode_Enum.Item_Print) || ((currentMode.Mode == Display_Mode_Enum.My_Sobek) && ((currentMode.My_Sobek_Type == My_Sobek_Type_Enum.Edit_Item_Metadata) || (currentMode.My_Sobek_Type == My_Sobek_Type_Enum.Edit_Item_Behaviors) || (currentMode.My_Sobek_Type == My_Sobek_Type_Enum.Edit_Item_Permissions)))
                    || ((currentMode.Mode == Display_Mode_Enum.My_Sobek) && ((currentMode.My_Sobek_Type == My_Sobek_Type_Enum.Edit_Group_Behaviors) ||  (currentMode.My_Sobek_Type == My_Sobek_Type_Enum.Edit_Group_Serial_Hierarchy) || (currentMode.My_Sobek_Type == My_Sobek_Type_Enum.Group_Add_Volume) || (currentMode.My_Sobek_Type == My_Sobek_Type_Enum.Group_AutoFill_Volumes) || (currentMode.My_Sobek_Type == My_Sobek_Type_Enum.Group_Mass_Update_Items) || (currentMode.My_Sobek_Type == My_Sobek_Type_Enum.File_Management) || (currentMode.My_Sobek_Type == My_Sobek_Type_Enum.Page_Images_Management) || (currentMode.My_Sobek_Type == My_Sobek_Type_Enum.Delete_Item))))
                {
                    Display_Item();
                }

                // Was this a robot?
                if (currentMode.Request_Completed)
                    return;

                // Get the group, collection, or subcollection from the database or cache.
                // This also makes sure they are a proper hierarchy.
                Get_Entire_Collection_Hierarchy();

                // Run the search if this should be done now
                if (currentMode.Mode == Display_Mode_Enum.Results)
                {
                    Search_Block();
                }

                // Run the browse/info work if it is of those modes
                if ((currentMode.Mode == Display_Mode_Enum.Aggregation) && ((currentMode.Aggregation_Type == Aggregation_Type_Enum.Browse_Info) || (currentMode.Aggregation_Type == Aggregation_Type_Enum.Child_Page_Edit)))
                {
                    Browse_Info_Block();
                }

                if (currentMode.Mode == Display_Mode_Enum.My_Sobek)
                {
                    MySobekCM_Block();
                }

                // Run the simple text block if this is that mode
                if (currentMode.Mode == Display_Mode_Enum.Simple_HTML_CMS)
                {
                    Simple_Web_Content_Text_Block();
                }
            }
            catch (OutOfMemoryException ee)
            {
                if (currentMode != null)
                {
                    currentMode.Mode = Display_Mode_Enum.Error;
                    currentMode.Error_Message = "Out of memory exception caught";
                    currentMode.Caught_Exception = ee;
                }
                else
                {
                    Email_Information("Fatal Out of memory exception caught", ee);
                }
            }
            catch (Exception ee)
            {
                if (currentMode != null)
                {
                    currentMode.Mode = Display_Mode_Enum.Error;
                    currentMode.Error_Message = "Unknown error occurred";
                    currentMode.Caught_Exception = ee;
                }
                else
                {
                    Email_Information("Unknown Fatal Error Occurred", ee);
                }
            }
        }
Пример #5
0
        private static void Email_Information(string EmailTitle, Exception ObjErr, Custom_Tracer Tracer, bool Redirect)
        {
            // Is ther an error email address in the configuration?
            if (UI_ApplicationCache_Gateway.Settings.Email.System_Error_Email.Length > 0)
            {
                try
                {
                    // Build the error message
                    string err;
                    if (ObjErr != null)
                    {
                        if (ObjErr.InnerException != null)
                        {
                            err = "<b>" + HttpContext.Current.Request.UserHostAddress + "</b><br /><br />" +
                                  "Error in!!: " + HttpContext.Current.Items["Original_URL"] + "<br /><br />" +
                                  "Error Message: " + ObjErr.Message + "<br /><br />" +
                                  "Inner Exception: " + ObjErr.InnerException.Message + "<br /><br />" +
                                  "Stack Trace: " + ObjErr.InnerException.StackTrace + "<br /><br />";
                        }
                        else
                        {
                            err = "<b>" + HttpContext.Current.Request.UserHostAddress + "</b><br /><br />" +
                                  "Error in!!: " + HttpContext.Current.Items["Original_URL"] + "<br /><br />" +
                                  "Error Message: " + ObjErr.Message + "<br /><br />" +
                                  "Stack Trace: " + ObjErr.StackTrace + "<br /><br />";
                        }

                        if (ObjErr.Message.IndexOf("Timeout expired") >= 0)
                        {
                            EmailTitle = "Database Timeout Expired";
                        }
                    }
                    else
                    {
                        err = "<b>" + HttpContext.Current.Request.UserHostAddress + "</b><br /><br />";
                    }

                    // Email the error message
                    if (Tracer != null)
                    {
                        Email_Helper.SendEmail(UI_ApplicationCache_Gateway.Settings.Email.System_Error_Email, EmailTitle, err + "<br /><br />" + Tracer.Text_Trace, true, String.Empty);
                    }
                    else
                    {
                        Email_Helper.SendEmail(UI_ApplicationCache_Gateway.Settings.Email.System_Error_Email, EmailTitle, err, true, String.Empty);
                    }
                }
                catch (Exception)
                {
                    // Failed to send the email.. but not much else to do here really
                }
            }

            try
            {
                StreamWriter writer = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\temp\\exceptions.txt", true);
                writer.WriteLine();
                writer.WriteLine("Error Caught in Application_Error event ( " + DateTime.Now.ToString() + ")");
                writer.WriteLine("User Host Address: " + HttpContext.Current.Request.UserHostAddress);
                writer.WriteLine("Requested URL: " + HttpContext.Current.Request.Url);
                if (ObjErr is SobekCM_Traced_Exception)
                {
                    SobekCM_Traced_Exception sobekException = (SobekCM_Traced_Exception)ObjErr;
                    writer.WriteLine("Error Message: " + sobekException.InnerException.Message);
                    writer.WriteLine("Stack Trace: " + ObjErr.StackTrace);
                    writer.WriteLine("Error Message:" + sobekException.InnerException.StackTrace);
                    writer.WriteLine();
                    writer.WriteLine(sobekException.Trace_Route);
                }
                else
                {
                    writer.WriteLine("Error Message: " + ObjErr.Message);
                    writer.WriteLine("Stack Trace: " + ObjErr.StackTrace);
                }

                writer.WriteLine();
                writer.WriteLine("------------------------------------------------------------------");
                writer.Flush();
                writer.Close();
            }
            catch (Exception)
            {
                // Nothing else to do here.. no other known way to log this error
            }

            // Forward to our error message
            if (Redirect)
            {
                HttpContext.Current.Response.Redirect(UI_ApplicationCache_Gateway.Settings.Servers.System_Error_URL, false);
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
        }
Пример #6
0
        /// <summary> Constructor for a new instance of the Html_MainWriter class </summary>
        /// <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        public Html_MainWriter(RequestCache RequestSpecificValues) : base(RequestSpecificValues)
        {
            // Add a trace
            RequestSpecificValues.Tracer.Add_Trace("Html_MainWriter.Constructor", "");

            // Check the IE hack CSS is loaded
            if (HttpContext.Current.Application["NonIE_Hack_CSS"] == null)
            {
                string css_file = HttpContext.Current.Server.MapPath("default/SobekCM_NonIE.css");
                if (File.Exists(css_file))
                {
                    try
                    {
                        StreamReader reader = new StreamReader(css_file);
                        HttpContext.Current.Application["NonIE_Hack_CSS"] = reader.ReadToEnd().Trim();
                        reader.Close();
                    }
                    catch (Exception)
                    {
                        HttpContext.Current.Application["NonIE_Hack_CSS"] = "/* ERROR READING FILE: default/SobekCM_NonIE.css */";
                        throw;
                    }
                }
                else
                {
                    HttpContext.Current.Application["NonIE_Hack_CSS"] = String.Empty;
                }
            }

            // Handle basic events which may be fired by the internal header
            if (HttpContext.Current.Request.Form["internal_header_action"] != null)
            {
                // Pull the action value
                string internalHeaderAction = HttpContext.Current.Request.Form["internal_header_action"].Trim();

                // Was this to hide or show the header?
                if ((internalHeaderAction == "hide") || (internalHeaderAction == "show"))
                {
                    // Pull the current visibility from the session
                    bool shown = !((HttpContext.Current.Session["internal_header"] != null) && (HttpContext.Current.Session["internal_header"].ToString() == "hidden"));
                    if ((internalHeaderAction == "hide") && (shown))
                    {
                        HttpContext.Current.Session["internal_header"] = "hidden";
                        UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                        return;
                    }
                    if ((internalHeaderAction == "show") && (!shown))
                    {
                        HttpContext.Current.Session["internal_header"] = "shown";
                        UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                        return;
                    }
                }
            }

            try
            {
                // Create the html sub writer now
                switch (RequestSpecificValues.Current_Mode.Mode)
                {
                case Display_Mode_Enum.Internal:
                    subwriter = new Internal_HtmlSubwriter(RequestSpecificValues);
                    break;

                case Display_Mode_Enum.Statistics:
                    subwriter = new Statistics_HtmlSubwriter(RequestSpecificValues);
                    break;

                case Display_Mode_Enum.Preferences:
                    subwriter = new Preferences_HtmlSubwriter(RequestSpecificValues);
                    break;

                case Display_Mode_Enum.Empty:
                    subwriter = new Empty_HtmlSubwriter(RequestSpecificValues);
                    break;

                case Display_Mode_Enum.Error:
                    subwriter = new Error_HtmlSubwriter(false, RequestSpecificValues);
                    // Send the email now
                    if (RequestSpecificValues.Current_Mode.Caught_Exception != null)
                    {
                        if (String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.Error_Message))
                        {
                            RequestSpecificValues.Current_Mode.Error_Message = "Unknown exception caught";
                        }
                        Email_Information(RequestSpecificValues.Current_Mode.Error_Message, RequestSpecificValues.Current_Mode.Caught_Exception, RequestSpecificValues.Tracer, false);
                    }
                    break;

                case Display_Mode_Enum.Legacy_URL:
                    subwriter = new LegacyUrl_HtmlSubwriter(RequestSpecificValues);
                    break;

                case Display_Mode_Enum.Item_Print:
                    subwriter = new Print_Item_HtmlSubwriter(RequestSpecificValues);
                    break;

                case Display_Mode_Enum.Contact:
                    StringBuilder builder = new StringBuilder();
                    builder.Append("\n\nSUBMISSION INFORMATION\n");
                    builder.Append("\tDate:\t\t\t\t" + DateTime.Now.ToString() + "\n");
                    string lastMode = String.Empty;
                    try
                    {
                        if (HttpContext.Current.Session["Last_Mode"] != null)
                        {
                            lastMode = HttpContext.Current.Session["Last_Mode"].ToString();
                        }
                        builder.Append("\tIP Address:\t\t\t" + HttpContext.Current.Request.UserHostAddress + "\n");
                        builder.Append("\tHost Name:\t\t\t" + HttpContext.Current.Request.UserHostName + "\n");
                        builder.Append("\tBrowser:\t\t\t" + HttpContext.Current.Request.Browser.Browser + "\n");
                        builder.Append("\tBrowser Platform:\t\t" + HttpContext.Current.Request.Browser.Platform + "\n");
                        builder.Append("\tBrowser Version:\t\t" + HttpContext.Current.Request.Browser.Version + "\n");
                        builder.Append("\tBrowser Language:\t\t");
                        bool     first     = true;
                        string[] languages = HttpContext.Current.Request.UserLanguages;
                        if (languages != null)
                        {
                            foreach (string thisLanguage in languages)
                            {
                                if (first)
                                {
                                    builder.Append(thisLanguage);
                                    first = false;
                                }
                                else
                                {
                                    builder.Append(", " + thisLanguage);
                                }
                            }
                        }

                        builder.Append("\n\nHISTORY\n");
                        if (HttpContext.Current.Session["LastSearch"] != null)
                        {
                            builder.Append("\tLast Search:\t\t" + HttpContext.Current.Session["LastSearch"] + "\n");
                        }
                        if (HttpContext.Current.Session["LastResults"] != null)
                        {
                            builder.Append("\tLast Results:\t\t" + HttpContext.Current.Session["LastResults"] + "\n");
                        }
                        if (HttpContext.Current.Session["Last_Mode"] != null)
                        {
                            builder.Append("\tLast Mode:\t\t\t" + HttpContext.Current.Session["Last_Mode"] + "\n");
                        }
                        builder.Append("\tURL:\t\t\t\t" + HttpContext.Current.Items["Original_URL"]);
                    }
                    catch
                    {
                    }
                    subwriter = new Contact_HtmlSubwriter(lastMode, builder.ToString(), RequestSpecificValues);
                    break;


                case Display_Mode_Enum.Contact_Sent:
                    subwriter = new Contact_HtmlSubwriter(String.Empty, String.Empty, RequestSpecificValues);
                    break;

                case Display_Mode_Enum.Simple_HTML_CMS:
                    subwriter = new Web_Content_HtmlSubwriter(RequestSpecificValues);
                    break;

                case Display_Mode_Enum.My_Sobek:
                    subwriter = new MySobek_HtmlSubwriter(RequestSpecificValues);
                    break;

                case Display_Mode_Enum.Administrative:
                    subwriter = new Admin_HtmlSubwriter(RequestSpecificValues);
                    break;

                case Display_Mode_Enum.Results:
                    subwriter = new Search_Results_HtmlSubwriter(RequestSpecificValues);
                    break;

                case Display_Mode_Enum.Public_Folder:
                    subwriter = new Public_Folder_HtmlSubwriter(RequestSpecificValues);
                    break;

                case Display_Mode_Enum.Search:
                case Display_Mode_Enum.Aggregation:
                    subwriter = new Aggregation_HtmlSubwriter(RequestSpecificValues);
                    break;

                case Display_Mode_Enum.Item_Display:
                    if ((!RequestSpecificValues.Current_Mode.Invalid_Item.HasValue || !RequestSpecificValues.Current_Mode.Invalid_Item.Value))
                    {
                        // Create the item viewer writer
                        subwriter = new Item_HtmlSubwriter(RequestSpecificValues);
                    }
                    else
                    {
                        // Create the invalid item html subwrite and write the HTML
                        subwriter = new Error_HtmlSubwriter(true, RequestSpecificValues);
                    }
                    break;
                }

                // Might be redirected
                if (RequestSpecificValues.Current_Mode.Request_Completed)
                {
                    return;
                }

                // Now, look for error or the web content, which is also often
                // used for resource missing type errors
                switch (RequestSpecificValues.Current_Mode.Mode)
                {
                case Display_Mode_Enum.Error:
                    subwriter = new Error_HtmlSubwriter(false, RequestSpecificValues);
                    // Send the email now
                    if (RequestSpecificValues.Current_Mode.Caught_Exception != null)
                    {
                        if (String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.Error_Message))
                        {
                            RequestSpecificValues.Current_Mode.Error_Message = "Unknown exception caught";
                        }
                        Email_Information(RequestSpecificValues.Current_Mode.Error_Message, RequestSpecificValues.Current_Mode.Caught_Exception, RequestSpecificValues.Tracer, false);
                    }
                    break;

                case Display_Mode_Enum.Simple_HTML_CMS:
                    subwriter = new Web_Content_HtmlSubwriter(RequestSpecificValues);
                    break;
                }

                // Now, pull the web skin
                SobekCM_Assistant assistant = new SobekCM_Assistant();

                // Try to get the web skin from the cache or skin collection, otherwise build it
                Web_Skin_Object htmlSkin = assistant.Get_HTML_Skin(RequestSpecificValues.Current_Mode.Skin, RequestSpecificValues.Current_Mode, UI_ApplicationCache_Gateway.Web_Skin_Collection, true, RequestSpecificValues.Tracer);

                // If the skin was somehow overriden, default back to the default skin
                string defaultSkin = RequestSpecificValues.Current_Mode.Base_Skin;
                if ((htmlSkin == null) && (!String.IsNullOrEmpty(defaultSkin)))
                {
                    if (String.Compare(RequestSpecificValues.Current_Mode.Skin, defaultSkin, StringComparison.InvariantCultureIgnoreCase) != 0)
                    {
                        RequestSpecificValues.Current_Mode.Skin = defaultSkin;
                        htmlSkin = assistant.Get_HTML_Skin(defaultSkin, RequestSpecificValues.Current_Mode, UI_ApplicationCache_Gateway.Web_Skin_Collection, true, RequestSpecificValues.Tracer);
                    }
                }

                // If there was no web skin returned, forward user to URL with no web skin.
                // This happens if the web skin code is invalid.  If a robot, just return a bad request
                // value though.
                if (htmlSkin == null)
                {
                    HttpContext.Current.Response.StatusCode = 404;
                    HttpContext.Current.Response.Output.WriteLine("404 - INVALID URL");
                    HttpContext.Current.Response.Output.WriteLine("Web skin indicated is invalid, default web skin invalid - line 1029");
                    HttpContext.Current.Response.Output.WriteLine(RequestSpecificValues.Tracer.Text_Trace);
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                    RequestSpecificValues.Current_Mode.Request_Completed = true;

                    return;
                }

                RequestSpecificValues.HTML_Skin = htmlSkin;
            }
            catch (Exception ee)
            {
                // Send to the dashboard
                if ((HttpContext.Current.Request.UserHostAddress == "127.0.0.1") || (HttpContext.Current.Request.UserHostAddress == HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]) || (HttpContext.Current.Request.Url.ToString().IndexOf("localhost") >= 0))
                {
                    RequestSpecificValues.Tracer.Add_Trace("Html_MainWriter.Constructor", "Exception caught!", Custom_Trace_Type_Enum.Error);
                    RequestSpecificValues.Tracer.Add_Trace("Html_MainWriter.Constructor", ee.Message, Custom_Trace_Type_Enum.Error);
                    RequestSpecificValues.Tracer.Add_Trace("Html_MainWriter.Constructor", ee.StackTrace, Custom_Trace_Type_Enum.Error);

                    // Wrap this into the SobekCM Exception
                    SobekCM_Traced_Exception newException = new SobekCM_Traced_Exception("Exception caught while building the mode-specific HTML Subwriter", ee, RequestSpecificValues.Tracer);

                    // Save this to the session state, and then forward to the dashboard
                    HttpContext.Current.Session["Last_Exception"] = newException;
                    HttpContext.Current.Response.Redirect("dashboard.aspx", false);
                    RequestSpecificValues.Current_Mode.Request_Completed = true;
                }
                else
                {
                    subwriter = new Error_HtmlSubwriter(false, RequestSpecificValues);
                }
            }
        }