using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml;
using System.Web.Caching;
using System.Runtime.Remoting.Messaging;
using xl_data;
using xl_utils;
using xl_bbs;

namespace xl_data
{
    public class Connection
    {
        // Fields
        public SqlConnection MainConn;
        public SqlConnection Conn;

        // MDB Methods
        public void OpenMainConn()
        {
            if (this.MainConn == null)
            {
                this.MainConn = new SqlConnection("server=.;database=WTODataMaster;user id=sa;pwd=wto123work;");
            }
            if (this.MainConn.State == ConnectionState.Closed)
            {
                this.MainConn.Open();
            }
        }

        public void CloseMainConn()
        {
            if (this.MainConn != null)
            {
                this.MainConn.Close();
            }
        }

        public bool ExecSql_Main(string strSql)
        {
            try
            {
                this.OpenMainConn();
                SqlCommand Cmd = new SqlCommand(strSql, MainConn);
                Cmd.ExecuteNonQuery();
                Cmd.Dispose();
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                this.CloseMainConn();
            }
        }

        public SqlDataReader GetDataReader_Main(string strSql)
        {
            try
            {
                this.OpenMainConn();
                SqlCommand Command = new SqlCommand(strSql, MainConn);
                SqlDataReader dataReader = Command.ExecuteReader();
                Command.Dispose();
                return dataReader;
            }
            catch
            {
                return null;
            }
        }

        public string GetScalar_Main(string strSql)
        {
            try
            {
                this.OpenMainConn();
                SqlCommand Command = new SqlCommand(strSql, MainConn);
                string result = Convert.ToString(Command.ExecuteScalar());
                Command.Dispose();
                return result;
            }
            catch
            {
                return string.Empty;
            }
            finally
            {
                this.CloseMainConn();
            }
        }

        // SDB Methods
        public void OpenConn()
        {
            if (this.Conn == null)
            {
                this.Conn = new SqlConnection(ConfigurationManager.AppSettings["Custmerconn"].ToString());
            }
            if (this.Conn.State == ConnectionState.Closed)
            {
                this.Conn.Open();
            }
        }

        public void CloseConn()
        {
            if (this.Conn != null)
            {
                this.Conn.Close();
            }
        }

        public bool ExecSql(string strSql)
        {
            try
            {
                this.OpenConn();
                SqlCommand Cmd = new SqlCommand(strSql, Conn);
                Cmd.ExecuteNonQuery();
                Cmd.Dispose();
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                this.CloseConn();
            }
        }
        
        public DataSet GetDataSet(string strSql, string strDataSetName)
        {
            try
            {
                this.OpenConn();
                DataSet dataSet = new DataSet();
                SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, Conn);
                dataAdapter.Fill(dataSet, strDataSetName);
                dataAdapter.Dispose();
                return dataSet;
            }
            catch
            {
                return null;
            }
            finally
            {
                this.CloseConn();
            }
        }

        public DataTable GetDataTable(string strSql)
        {
            try
            {
                this.OpenConn();
                DataTable dataTable = new DataTable();
                SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, Conn);
                dataAdapter.Fill(dataTable);
                dataAdapter.Dispose();
                return dataTable;
            }
            catch
            {
                return null;
            }
            finally
            {
                this.CloseConn();
            }
        }

        public SqlDataReader GetDataReader(string strSql)
        {
            try
            {
                this.OpenConn();
                SqlCommand Command = new SqlCommand(strSql, Conn);
                SqlDataReader dataReader = Command.ExecuteReader();
                Command.Dispose();
                return dataReader;
            }
            catch
            {
                return null;
            }
        }

        public string GetScalar(string strSql)
        {
            try
            {
                this.OpenConn();
                SqlCommand Cmd = new SqlCommand(strSql, Conn);
                string sResult = Convert.ToString(Cmd.ExecuteScalar());
                Cmd.Dispose();
                return sResult;
            }
            catch
            {
                return string.Empty;
            }
            finally
            {
                this.CloseConn();
            }
        }

        public string[] GetColumns(string strSql)
        {
            try
            {
                this.OpenConn();
                DataSet dataSet = GetDataSet(strSql, "Data");
                int iCount = dataSet.Tables["Data"].Columns.Count;
                string[] sResult = new string[iCount];
                if (iCount > 0)
                {
                    for (int i = 0; i < iCount; i++)
                    {
                        sResult[i] = dataSet.Tables["Data"].Rows[0][i].ToString();
                    }
                }
                dataSet.Dispose();
                return sResult;
            }
            catch
            {
                return null;
            }
            finally
            {
                this.CloseConn();
            }
        }

        public int GetiScalar(string strSql)
        {
            try
            {
                this.OpenConn();
                SqlCommand Cmd = new SqlCommand(strSql, Conn);
                int iCount = Convert.ToInt32(Cmd.ExecuteScalar());
                Cmd.Dispose();
                return iCount;
            }
            catch
            {
                return 0;
            }
            finally
            {
                this.CloseConn();
            }
        }

        public int GetsRows(string strSql)
        {
            try
            {
                int iCount = 0;
                this.OpenConn();
                SqlCommand Cmd = new SqlCommand(strSql, Conn);
                SqlDataReader dataReader = Cmd.ExecuteReader();
                while (dataReader.Read())
                {
                    iCount += Convert.ToInt32(dataReader[0]);
                }
                dataReader.Close();
                Cmd.Dispose();
                return iCount;
            }
            catch
            {
                return 0;
            }
            finally
            {
                this.CloseConn();
            }
        }

        public int GetiRows(string strSql)
        {
            try
            {
                int iCount = 0;
                this.OpenConn();
                SqlCommand Cmd = new SqlCommand(strSql, Conn);
                SqlDataReader dataReader = Cmd.ExecuteReader();
                while (dataReader.Read())
                {
                    iCount += 1;
                }
                dataReader.Close();
                Cmd.Dispose();
                return iCount;
            }
            catch
            {
                return 0;
            }
            finally
            {
                this.CloseConn();
            }
        }
    }
}

namespace xl_bbs
{
    public class UtilityHandler
    {
        public static string GetBoardJump(int boardid)
        {
            string _content = null;
            _content += "\r\n\t<select name=\"boardjump\" onchange=\"boardJump(this);\" class=\"select\">";
            _content += "\r\n\t<option value=\"-1\" selected=\"selected\">论坛快速跳转...</option>";
            DataTable dataTable = new Connection().GetDataTable("Select B_Id,B_Text From BBS_Board Where B_IsHidden = 0 And B_Pid = 0 Order By B_Orders Asc");
            if (dataTable.Rows.Count > 0)
            {
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    _content += "\r\n\t<option value=\"" + dataTable.Rows[i]["B_Id"].ToString() + "\" style=\"color:#000\">╋ " + dataTable.Rows[i]["B_Text"].ToString();
                    _content += (Convert.ToInt32(dataTable.Rows[i]["B_Id"]) == boardid) ? " √" : "";
                    _content += "</option>";
                    DataTable dataTable_Child = new Connection().GetDataTable("Select B_Id,B_Text From BBS_Board Where B_IsHidden = 0 And B_Pid = " + dataTable.Rows[i]["B_Id"].ToString() + " Order By B_Orders Asc");
                    if (dataTable_Child.Rows.Count > 0)
                    {
                        for (int j = 0; j < dataTable_Child.Rows.Count; j++)
                        {
                            _content += "\r\n\t<option value=\"" + dataTable_Child.Rows[j]["B_Id"].ToString() + "\" style=\"color:#0365BF\"> &nbsp;&nbsp;└ " + dataTable_Child.Rows[j]["B_Text"].ToString();
                            _content += (Convert.ToInt32(dataTable_Child.Rows[j]["B_Id"]) == boardid) ? " √" : "";
                            _content += "</option>";
                        }
                    }
                    dataTable_Child.Dispose();
                }
            }
            dataTable.Dispose();
            _content += "\r\n\t</select>\r\n\t";
            return _content;
        }

        public static string GetNavigation(string boardid, string description)
        {
            string _content = null;
            _content += "<span class=\"notice_bar\">";
            _content += "\r\n\t<a href=\"index.aspx\" onmouseover=\"showMenu(event, 0, 0);\"><b>论坛首页</b></a>";
            if (boardid != string.Empty)
            {
                string[] sArray = new Connection().GetColumns("Select (Select B_Id From BBS_Board Where B_Id in (Select B_Pid From BBS_Board Where B_Id = " + boardid + ")) As MBID, (Select B_Text From BBS_Board Where B_Id in (Select B_Pid From BBS_Board Where B_Id = " + boardid + ")) As MBT, B_Id As SBID, B_Text As SBT From BBS_Board Where B_Id = " + boardid);
                if (sArray != null)
                {
                    if (sArray[0] == string.Empty && sArray[1] == string.Empty)
                    {
                        _content += " &nbsp;→&nbsp; <a href=\"board.aspx?bid=" + sArray[2] + "\">" + sArray[3] + "</a>";
                    }
                    else
                    {
                        _content += " &nbsp;→&nbsp; <a href=\"board.aspx?bid=" + sArray[0] + "\" onmouseover=\"showMenu(event, " + sArray[0] + ", 0);\">" + sArray[1] + "</a> &nbsp;→&nbsp; <a href=\"board.aspx?bid=" + sArray[2] + "\">" + sArray[3] + "</a>";
                    }
                }
            }
            _content += (description != string.Empty) ? description : null;
            _content += "\r\n\t</span>";
            _content += "\r\n\t<script type=\"text/javascript\" src=\"scripts/popmenu.js\"></script>";
            _content += "\r\n\t<script type=\"text/javascript\">\r\n\t<!--";
            _content += "\r\n\tvar boardid = " + boardid + ";";
            _content += "\r\n\tvar boardList = {";
            DataTable dataTable = new Connection().GetDataTable("Select * From BBS_Board Where B_IsHidden = 0 And B_Pid = 0 Order By B_Orders Asc");
            if (dataTable.Rows.Count > 0)
            {
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    _content += "'" + dataTable.Rows[i]["B_Id"].ToString() + "':{'BoardId':" + dataTable.Rows[i]["B_Id"].ToString() + ",'Depth':0,'BoardType':'" + dataTable.Rows[i]["B_Text"].ToString() + "','ParentId':" + dataTable.Rows[i]["B_Pid"].ToString() + ",'urlpath':'board.aspx?bid=" + dataTable.Rows[i]["B_Id"].ToString() + "'},";
                    DataTable dataTable_Child = new Connection().GetDataTable("Select * From BBS_Board Where B_IsHidden = 0 And B_Pid = " + dataTable.Rows[i]["B_Id"].ToString() + " Order By B_Orders Asc");
                    if (dataTable_Child.Rows.Count > 0)
                    {
                        for (int j = 0; j < dataTable_Child.Rows.Count; j++)
                        {
                            _content += "'" + dataTable_Child.Rows[j]["B_Id"].ToString() + "':{'BoardId':" + dataTable_Child.Rows[j]["B_Id"].ToString() + ",'Depth':1,'BoardType':'" + dataTable_Child.Rows[j]["B_Text"].ToString() + "','ParentId':" + dataTable_Child.Rows[j]["B_Pid"].ToString() + ",'urlpath':'board.aspx?bid=" + dataTable_Child.Rows[j]["B_Id"].ToString() + "'},";
                        }
                    }
                    dataTable_Child.Dispose();
                }
            }
            dataTable.Dispose();
            _content += "'0':null};";
            _content += "\r\n\t//-->";
            _content += "\r\n\t</script>";
            _content += "\r\n\t<div id=\"popmenu\" onmouseover=\"clearhidemenu()\" onmouseout=\"dynamichide(event)\" class=\"menuskin\"></div>";
            return _content;
        }

        public static bool IsLogin()
        {
            return ((SessionState.GetString("username") != string.Empty) ? true : false);
        }

        public static void CheckForumStatus()
        {
            bool isCloseForum = false;
            if (Config.Settings["ServiceDown"] != string.Empty)
            {
                isCloseForum = Convert.ToBoolean(Config.Settings["ServiceDown"]);
            }
            if (isCloseForum)
            {
                string _message = "论坛维护，暂时关闭，请稍候访问。";
                if (Config.Settings["ReasonOfServiceDown"] != string.Empty)
                {
                    _message = Config.Settings["ReasonOfServiceDown"];
                }
                new Terminator().Throw(_message);
            }
        }

        public static int UserIdentity()
        {
            return UserIdentity(null);
        }

        public static int UserIdentity(string boardid)
        {
            if ((new UserInfo().Power) == 1 && (new Connection().GetScalar("Select B_Master From BBS_Board Where B_Id = " + boardid)).ToLower().Contains(SessionState.GetString("username").ToLower()))
            {
                return (1);
            }
            else if ((new UserInfo().Power) == 2)
            {
                return (2);
            }
            else if ((new UserInfo().Power) == 3)
            {
                return (3);
            }
            else
            {
                return (0);
            }
        }

        public static string CreateAttachFolder()
        {
            DateTime now = DateTime.Now;
            string str = string.Empty;
            string str4 = ConfigInfo.AttachSaveAt.ToLower();
            if (str4 != null)
            {
                str4 = string.IsInterned(str4);
                if (str4 != "attachs")
                {
                    if (str4 == "yyyymm")
                    {
                        str = now.Year + Text.AddZero(now.Month) + "/";
                        goto Label_00D9;
                    }
                    if (str4 == "yyyymm/dd")
                    {
                        str = string.Concat(new object[] { now.Year, Text.AddZero(now.Month), "/", Text.AddZero(now.Day), "/" });
                        goto Label_00D9;
                    }
                }
            }
            str = "attachs/";
        Label_00D9:
            try
            {
                string path = Fetch.MapPath(ConfigInfo.UploadfilePath + str);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch
            {
                return string.Empty;
            }
            return str;
        }

        public static void Prompt(string message)
        {
            Prompt(message, null, null, null, true, "", true);
        }

        public static void Prompt(string message, bool isParent)
        {
            Prompt(message, null, null, null, true, "", isParent);
        }

        public static void Prompt(string message, string title, string links, string autojump, bool showback, string markpic)
        {
            Prompt(message, title, links, autojump, showback, markpic, false);
        }

        public static void Prompt(string message, string title, string links, string autojump, bool showback, string markpic, bool isParent)
        {
            HttpContext Context = HttpContext.Current;
            string __parent__ = (!isParent) ? " target=\"_blank\"" : " target=\"_top\"";
            string sContent = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
                "<html xmlns=\"http://www.w3.org/1999/xhtml\">" +
                "<head>" +
                "<title>系统提示 - " + ConfigInfo.bbsName + "</title>" +
                "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" />" +
                "</head>" +
                "<body>" +
                "<form name=\"prompt\" action=\"prompt.aspx\" method=\"post\"" + __parent__ + ">" +
                "<input type=\"hidden\" name=\"__Prompt_Pic__\" value=\"" + markpic + "\" />" +
                "<input type=\"hidden\" name=\"__Prompt_Message__\" value=\"" + Context.Server.HtmlEncode(message) + "\" />" +
                "<input type=\"hidden\" name=\"__Prompt_Title__\" value=\"" + Context.Server.HtmlEncode(title) + "\" />" +
                "<input type=\"hidden\" name=\"__Prompt_Links__\" value=\"" + Context.Server.HtmlEncode(links) + "\" />" +
                "<input type=\"hidden\" name=\"__Prompt_AutoJump__\" value=\"" + Context.Server.HtmlEncode(autojump) + "\" />" +
                "<input type=\"hidden\" name=\"__Prompt_IsShowBack__\" value=\"" + Convert.ToUInt32(showback).ToString() + "\" />" +
                "<input type=\"hidden\" name=\"__Prompt_Referer__\" value=\"" + Fetch.UrlReferrer + "\" />" +
                "</form>" +
                "<script type=\"text/javascript\">" +
                "var sForm = document.forms[\"prompt\"];" +
                "if(!sForm){ sForm = document.prompt; }" +
                "sForm.submit();" +
                "</script>" +
                "</body>" +
                "</html>";
            Context.Response.Clear();
            Fetch.Trace(sContent);
            Fetch.End();
        }

        public static void Alert(string message)
        {
            Alert(message, null, false, true);
        }

        public static void Alert(string message, string url)
        {
            Alert(message, url, false, true);
        }

        public static void Alert(string message, string url, bool isAutoJump)
        {
            Alert(message, url, isAutoJump, false);
        }

        public static void Alert(string message, string url, bool isAutoJump, bool isAjaxTip)
        {
            if (isAjaxTip)
            {
                HttpContext.Current.Response.ContentType = "text/html";
                HttpContext.Current.Response.ContentEncoding = HttpContext.Current.Request.ContentEncoding;
                if (url != null)
                {
                    Fetch.Trace("{message:\"" + message + "\", url:\"" + url + "\"};");
                }
                else
                {
                    Fetch.Trace("{message:\"" + message + "\"};");
                }
                Fetch.End();
            }
            else
            {
                if (!isAutoJump)
                {
                    if (url != null)
                    {
                        Prompt(message, null, null, url, true, null, true);
                    }
                    else
                    {
                        Prompt(message);
                    }
                }
                else
                {
                    Fetch.Trace("<script>parent.window.location.href='" + url + "';</script>");
                    Fetch.End();
                }
            }
        }
    }

    public class ConfigInfo
    {
        // Properties
        public static string bbsName
        {
            get
            {
                string _bbsName = "BBS";
                if (Config.Settings["bbsName"] != string.Empty)
                {
                    _bbsName = Config.Settings["bbsName"];
                }
                return _bbsName;
            }
        }

        public static string bbsLogo
        {
            get
            {
                string _bbsLogo = "images/logo.gif";
                if (Config.Settings["bbsLogo"] != string.Empty)
                {
                    _bbsLogo = Config.Settings["bbsLogo"];
                }
                return _bbsLogo;
            }
        }

        public static string MetaKeyWords
        {
            get
            {
                string _MetaKeyWords = null;
                if (Config.Settings["MetaKeyWords"] != string.Empty)
                {
                    _MetaKeyWords = Config.Settings["MetaKeyWords"];
                }
                return _MetaKeyWords;
            }
        }

        public static string MetaDescription
        {
            get
            {
                string _MetaDescription = null;
                if (Config.Settings["MetaDescription"] != string.Empty)
                {
                    _MetaDescription = Config.Settings["MetaDescription"];
                }
                return _MetaDescription;
            }
        }

        public static string MasterEmail
        {
            get
            {
                string _MasterEmail = null;
                if (Config.Settings["MasterEmail"] != string.Empty)
                {
                    _MasterEmail = Config.Settings["MasterEmail"];
                }
                return _MasterEmail;
            }
        }

        public static string BadWords
        {
            get
            {
                string _BadWords = "妈的|你妈|他妈|妈b|妈比|我日|我操|法轮|fuck|shit";
                if (Config.Settings["BadWords"] != string.Empty)
                {
                    _BadWords = Config.Settings["BadWords"];
                }
                return _BadWords;
            }
        }

        public static string SkinPath
        {
            get
            {
                string _SkinName = null;
                if (Config.Settings["SkinName"] != string.Empty)
                {
                    _SkinName = Config.Settings["SkinName"];
                }
                else
                {
                    _SkinName = "default";
                }
                string _SkinPath = string.Concat(new object[] { "skins/", _SkinName, "/" });
                return _SkinPath;
            }
        }

        public static string UploadfilePath
        {
            get
            {
                string _UploadfilePath = "uploadfiles/attachs/";
                if (Config.Settings["UploadfilePath"] != string.Empty)
                {
                    _UploadfilePath = Config.Settings["UploadfilePath"];
                }
                return _UploadfilePath;
            }
        }

        public static string UploadfacePath
        {
            get
            {
                string _UploadfacePath = "uploadfiles/faces/";
                if (Config.Settings["UploadfacePath"] != string.Empty)
                {
                    _UploadfacePath = Config.Settings["UploadfacePath"];
                }
                return _UploadfacePath;
            }
        }

        public static string AllowAttachType
        {
            get
            {
                string _AllowAttachType = ".zip|.rar|.jpg|.gif|.png|.bmp";
                if (Config.Settings["AllowAttachType"] != string.Empty)
                {
                    _AllowAttachType = Config.Settings["AllowAttachType"];
                }
                return _AllowAttachType;
            }
        }

        public static string AttachSaveAt
        {
            get
            {
                string _AttachSaveAt = "YYYYMM";
                if (Config.Settings["AttachSaveAt"] != string.Empty)
                {
                    _AttachSaveAt = Config.Settings["AttachSaveAt"];
                }
                return _AttachSaveAt;
            }
        }

        public static int AllowAttachSize
        {
            get
            {
                int _AllowAttachSize = 1024;
                if (Config.Settings["AllowAttachSize"] != string.Empty)
                {
                    _AllowAttachSize = Convert.ToInt32(Config.Settings["AllowAttachSize"]);
                }
                return _AllowAttachSize;
            }
        }

        public static int UploadRequireExp
        {
            get
            {
                int _UploadRequireExp = 100;
                if (Config.Settings["UploadRequireExp"] != string.Empty)
                {
                    _UploadRequireExp = Convert.ToInt32(Config.Settings["UploadRequireExp"]);
                }
                return _UploadRequireExp;
            }
        }

        public static int BoardPageSize
        {
            get
            {
                int _BoardPageSize = 10;
                if (Config.Settings["PageSizeOfTopics"] != string.Empty)
                {
                    _BoardPageSize = Convert.ToInt32(Config.Settings["PageSizeOfTopics"]);
                }
                return _BoardPageSize;
            }
        }

        public static int ReplyPageSize
        {
            get
            {
                int _ReplyPageSize = 10;
                if (Config.Settings["PageSizeOfReplies"] != string.Empty)
                {
                    _ReplyPageSize = Convert.ToInt32(Config.Settings["PageSizeOfReplies"]);
                }
                return _ReplyPageSize;
            }
        }

        public static int SearchPageSize
        {
            get
            {
                int _SearchPageSize = 10;
                if (Config.Settings["PageSizeOfSearchs"] != string.Empty)
                {
                    _SearchPageSize = Convert.ToInt32(Config.Settings["PageSizeOfSearchs"]);
                }
                return _SearchPageSize;
            }
        }

        public static int TopicTitleLength
        {
            get
            {
                int _TopicTitleLength = 50;
                if (Config.Settings["TopicTitleLength"] != string.Empty)
                {
                    _TopicTitleLength = Convert.ToInt32(Config.Settings["TopicTitleLength"]);
                }
                return _TopicTitleLength;
            }
        }

        public static int TopicContentLength
        {
            get
            {
                int _TopicContentLength = 323835;
                if (Config.Settings["TopicContentLength"] != string.Empty)
                {
                    _TopicContentLength = Convert.ToInt32(Config.Settings["TopicContentLength"]);
                }
                return _TopicContentLength;
            }
        }

        public static int ExperienceAddReply
        {
            get
            {
                int _ExperienceAddReply = 2;
                if (Config.Settings["ExperienceAddReply"] != string.Empty)
                {
                    _ExperienceAddReply = Convert.ToInt32(Config.Settings["ExperienceAddReply"]);
                }
                return _ExperienceAddReply;
            }
        }

        public static int ExperienceAddTopic
        {
            get
            {
                int _ExperienceAddTopic = 5;
                if (Config.Settings["ExperienceAddTopic"] != string.Empty)
                {
                    _ExperienceAddTopic = Convert.ToInt32(Config.Settings["ExperienceAddTopic"]);
                }
                return _ExperienceAddTopic;
            }
        }

        public static int ExperienceLogin
        {
            get
            {
                int _ExperienceLogin = 2;
                if (Config.Settings["ExperienceLogin"] != string.Empty)
                {
                    _ExperienceLogin = Convert.ToInt32(Config.Settings["ExperienceLogin"]);
                }
                return _ExperienceLogin;
            }
        }

        public static int ExperienceDeleteReply
        {
            get
            {
                int _ExperienceDeleteReply = 5;
                if (Config.Settings["ExperienceDeleteReply"] != string.Empty)
                {
                    _ExperienceDeleteReply = Convert.ToInt32(Config.Settings["ExperienceDeleteReply"]);
                }
                return _ExperienceDeleteReply;
            }
        }

        public static int ExperienceDeleteTopic
        {
            get
            {
                int _ExperienceDeleteTopic = 10;
                if (Config.Settings["ExperienceDeleteTopic"] != string.Empty)
                {
                    _ExperienceDeleteTopic = Convert.ToInt32(Config.Settings["ExperienceDeleteTopic"]);
                }
                return _ExperienceDeleteTopic;
            }
        }

        public static bool ShowHeaderAds
        {
            get
            {
                bool _ShowHeaderAds = true;
                if (Config.Settings["ShowHeaderAds"] != string.Empty)
                {
                    _ShowHeaderAds = Convert.ToBoolean(Config.Settings["ShowHeaderAds"]);
                }
                return _ShowHeaderAds;
            }
        }

        public static bool ShowFrienklink
        {
            get
            {
                bool _ShowFrienklink = true;
                if (Config.Settings["ShowFrienklink"] != string.Empty)
                {
                    _ShowFrienklink = Convert.ToBoolean(Config.Settings["ShowFrienklink"]);
                }
                return _ShowFrienklink;
            }
        }

        public static bool ShowAnnouncement
        {
            get
            {
                bool _ShowAnnouncement = true;
                if (Config.Settings["ShowAnnouncement"] != string.Empty)
                {
                    _ShowAnnouncement = Convert.ToBoolean(Config.Settings["ShowAnnouncement"]);
                }
                return _ShowAnnouncement;
            }
        }

        public static bool TopicAudit
        {
            get
            {
                bool _TopicAudit = false;
                if (Config.Settings["TopicAudit"] != string.Empty)
                {
                    _TopicAudit = Convert.ToBoolean(Config.Settings["TopicAudit"]);
                }
                return _TopicAudit;
            }
        }

        public static bool ShowLastModifyUser
        {
            get 
            {
                bool _ShowLastModifyUser = true;
                if (Config.Settings["ShowLastModifyUser"] != string.Empty)
                {
                    _ShowLastModifyUser = Convert.ToBoolean(Config.Settings["ShowLastModifyUser"]);
                }
                return _ShowLastModifyUser;
            }
        }

        public static DateTime StartRunTime
        {
            get { return (new DateTime()); }
        }

        public static string CustomConfigFile
        {
            get
            {
                return "bbs.config";
            }
        }
    }

    public class UserInfo
    {
        // Fields
        private string _userid;
        private string _username;
        private string _name;
        private string _sex;
        private string _address;
        private string _email;
        private string _face;
        private string _blogurl;
        private string _lastloginip;
        private string _status;
        private string _signed;
        private string _grade;
        private string _telephone;
        private string _phone;
        private string _qq;
        private string _getpwdquestion;
        private string _getpwdanswer;
        private string _zipcode;
        private int _rank = 0;
        private int _degree = 0;
        private int _power = 0;
        private int _integral = 0;
        private int _topiccount = 0;
        private int _replycount = 0;
        private DateTime _birthday;
        private DateTime _joindate;
        private DateTime _lastlogindate;
        private static readonly string _CurrentUserContextName;

        // Methods
        static UserInfo()
        {
            _CurrentUserContextName = "User::CallContext::GetData::Current";
        }

        public UserInfo()
        {
            this.Clear();
            if (SessionState.GetString("username") != string.Empty)
            {
                this.SetUserInfo(SessionState.GetString("username"), false);
            }
        }

        public UserInfo(string sUserName)
        {
            this.Clear();
            this.SetUserInfo(sUserName, false);
        }

        public void SetUserInfo(string sUserName, bool isLogin)
        {
            try
            {
                this._integral = new Connection().GetiScalar("Select Integral From MemberVIP Where VipUserName = '" + sUserName + "'");
                DataTable dataTable = new Connection().GetDataTable("Select G_Id,G_Name,G_Integral From User_Grade Order By G_Integral Desc");
                if (dataTable.Rows.Count > 0)
                {
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        if (this._integral > Convert.ToInt32(dataTable.Rows[i][2]))
                        {
                            this._rank = dataTable.Rows.Count - i;
                            this._grade = dataTable.Rows[i][1].ToString();
                            break;
                        }
                        else if (this._integral <= Convert.ToInt32(dataTable.Rows[dataTable.Rows.Count - 1][2]))
                        {
                            this._rank = 1;
                            this._grade = dataTable.Rows[dataTable.Rows.Count - 1][1].ToString();
                            break;
                        }
                    }
                }
                dataTable.Dispose();
                DataTable dataTable_User = new Connection().GetDataTable("Select * From MemberVIP Where VipUserName = '" + sUserName + "'");
                DataRow dataRow = dataTable_User.Rows[0];
                this._userid = dataRow["id"].ToString();
                this._username = dataRow["vipusername"].ToString();
                this._power = Convert.ToInt32(dataRow["vipright"]);
                this._status = dataRow["vipstatus"].ToString();
                this._joindate = Convert.ToDateTime(dataRow["addtime"]);
                this._degree = (int)dataRow["logintimes"];
                this._lastlogindate = Convert.ToDateTime(dataRow["enddate"]);
                this._lastloginip = dataRow["loginIP"].ToString();
                this._topiccount = new Connection().GetiScalar("Select Count(*) As Counts From BBS_Topic Where T_IsDelete = 0 And T_UserName = '" + dataRow["vipusername"].ToString() + "'");
                this._replycount = new Connection().GetiScalar("Select Count(*) As Counts From BBS_Reply Where R_UserName = '" + dataRow["vipusername"].ToString() + "'");
                this._name = dataRow["vipname"].ToString();
                this._sex = (dataRow["vipsex"].ToString() == "n") ? "男" : "女";
                this._address = dataRow["vipaddress"].ToString();
                this._zipcode = dataRow["post"].ToString();
                this._email = dataRow["vipemail"].ToString();
                this._face = dataRow["vipface"].ToString();
                this._birthday = Convert.ToDateTime(dataRow["vipBirthday"]);
                this._qq = dataRow["vipqq"].ToString();
                this._signed = dataRow["vipsigned"].ToString();
                this._telephone = dataRow["Telephone"].ToString();
                this._phone = dataRow["MobilePhone"].ToString();
                this._blogurl = dataRow["vipblogurl"].ToString();
                this._getpwdquestion = dataRow["PWDQuestions"].ToString();
                this._getpwdanswer = dataRow["PWDAnswer"].ToString();
                if (isLogin)
                {
                    SessionState.Set("username", dataRow["vipusername"].ToString());
                    SessionState.Set("userid", dataRow["id"].ToString());
                }
                dataRow.Delete();
                dataTable_User.Dispose();
            }
            catch //(Exception ex)
            {
                //new Terminator().Throw(ex.Message);
            }
        }

        public void Clear()
        {
            this._userid = "";
            this._username = "";
            this._power = 0;
            this._status = "";
            this._joindate = DateTime.Now;
            this._degree = 0;
            this._lastlogindate = DateTime.Now;
            this._lastloginip = "";
            this._topiccount = 0;
            this._replycount = 0;
            this._integral = 0;
            this._rank = 0;
            this._grade = "";
            this._name = "";
            this._sex = "男";
            this._address = "";
            this._zipcode = "";
            this._email = "";
            this._face = "";
            this._birthday = DateTime.Now;
            this._qq = "";
            this._signed = "";
            this._telephone = "";
            this._phone = "";
            this._blogurl = "";
            this._getpwdquestion = "";
            this._getpwdanswer = "";
        }

        // Properties
        public static UserInfo Current
        {
            get
            {
                object data = CallContext.GetData(_CurrentUserContextName);
                if ((data != null) && (data is UserInfo))
                {
                    return (data as UserInfo);
                }
                UserInfo Userinfo = new UserInfo(SessionState.GetString("username"));
                CallContext.SetData(_CurrentUserContextName, Userinfo);
                return Userinfo;
            }
        } 

        public string UserId
        {
            get { return this._userid; }
        }

        public string UserName
        {
            get { return this._username; }
        }

        public string Name
        {
            get { return this._name; }
        }

        public DateTime Birthday
        {
            get { return this._birthday; }
        }

        public string Sex
        {
            get { return this._sex; }
        }

        public string Address
        {
            get { return this._address; }
        }

        public string ZipCode
        {
            get { return this._zipcode; }
        }

        public string Email
        {
            get { return this._email; }
        }

        public string Face
        {
            get 
            {
                string _userface = null;
                if (this._face == string.Empty)
                {
                    _userface = (this._sex == "男") ? "images/face/1.gif" : "images/face/2.gif";
                }
                else
                {
                    _userface = "images/face/userface/" + this._face;
                }
                return _userface; 
            }
        }

        public string Status
        {
            get { return this._status; }
        }

        public string Signed
        {
            get { return this._signed; }
        }

        public string Telephone
        {
            get { return this._telephone; }
        }

        public string Phone
        {
            get { return this._phone; }
        }

        public string QQ
        {
            get { return this._qq; }
        }

        public string BlogUrl
        {
            get 
            {
                if (this._blogurl == string.Empty)
                {
                    this._blogurl = "http://" + Fetch.ServerDomain + "/blog/?id=" + this._userid;
                }
                return this._blogurl; 
            }
        }

        public string IntegrityRate
        {
            get
            {
                int _integrityrate = 0;
                if (this._name != string.Empty) _integrityrate += 1;
                if (this._sex != string.Empty) _integrityrate += 1;
                if (this._address != string.Empty) _integrityrate += 1;
                if (this._zipcode != string.Empty) _integrityrate += 1;
                if (this._email != string.Empty) _integrityrate += 1;
                if (this._face != string.Empty) _integrityrate += 1;
                if (this._birthday != Convert.ToDateTime(null)) _integrityrate += 1;
                if (this._qq != string.Empty) _integrityrate += 1;
                if (this._signed != string.Empty) _integrityrate += 1;
                if (this._telephone != string.Empty) _integrityrate += 1;
                if (this._blogurl != string.Empty) _integrityrate += 1;
                if (this._getpwdquestion != string.Empty) _integrityrate += 1;
                if (this._getpwdanswer != string.Empty) _integrityrate += 1;
                double _rate = Math.Round((double)_integrityrate / 13 * 100);
                return _rate.ToString() + "%";
            }
        }

        public int Rank
        {
            get { return this._rank; }
        }

        public int Integral
        {
            get { return this._integral; }
        }

        public int Topics
        {
            get { return this._topiccount; }
        }

        public int Replys
        {
            get { return this._replycount; }
        }

        public int LoginDegree
        {
            get { return this._degree; }
        }

        public DateTime JoinDate
        {
            get { return this._joindate; }
        }

        public DateTime LoginDate
        {
            get { return this._lastlogindate; }
        }

        public string LoginIP
        {
            get { return this._lastloginip; }
        }

        public int Power
        {
            get { return this._power; }
        }

        public string Grade
        {
            get
            {
                switch (this._power)
                {
                    case 3:
                        return "管理员";
                    case 2:
                        return "超级版主";
                    case 1:
                        return "版主";
                    case 0:
                        return this._grade;
                }
                return this._grade;
            }
        }
    }

    public class Attachment
    {
        // Fields
        private int _attachid;
        private string _attachName;
        private string _attachPath;
        private string _attachSaveAtRoot;
        private long _attachSize;
        private int _attachType;
        private string ext = "";
        private string ImgBigUpfileName = "";
        private string ImgMinUpfileName = "";
        private HttpPostedFile _postedFile;
        private UserInfo _user;

        // Methods
        private string CheckPostedFile()
        {
            if (this._postedFile == null)
            {
                return "上传失败，请选择你要上传的文件！";
            }
            this._attachSize = (long)this._postedFile.ContentLength;
            long _allowSize = (long)ConfigInfo.AllowAttachSize;
            if (this.Uploader.Power == 3)
            {
                _allowSize = Math.Max(_allowSize, 2048);
            }
            if ((this._attachSize / 1024) > _allowSize)
            {
                return ("上传失败，每次上传文件的大小不能超过 " + _allowSize + " KB！");
            }
            string fileName = this._postedFile.FileName;
            if ((fileName.ToString() == string.Empty) || (this._attachSize == 0))
            {
                return "上传失败，请选择你要上传的文件！";
            }
            this.ext = fileName.Substring(fileName.LastIndexOf(".")).ToLower();
            string str2 = ConfigInfo.AllowAttachType;
            string[] strArray = str2.Split(new char[] { '|' });
            bool flag = false;
            for (int i = 0; i < strArray.Length; i++)
            {
                if (flag = this.ext == strArray[i].Trim())
                {
                    break;
                }
            }
            if (!flag)
            {
                return ("上传失败，文件格式只能是：" + str2.Replace("|", " ") + " ！");
            }
            this._attachName = fileName.Substring(fileName.LastIndexOf(@"\") + 1);
            if (Text.Len(this._attachName) > 40)
            {
                return "附件原名过长，最多20个汉字或40个字母，请修改后再上传！";
            }
            this._attachName = this.ReplaceDisabledChars(this._attachName);
            switch (this.ext)
            {
                case ".gif":
                case ".png":
                case ".bmp":
                case ".jpg":
                case ".jpe":
                case ".jpeg":
                    this._attachType = 1;
                    break;
                case ".zip":
                    this._attachType = 3;
                    break;
                case ".doc":
                case ".xls":
                case ".mdb":
                case ".ppt":
                    this._attachType = 4;
                    break;
                case ".swf":
                    this._attachType = 5;
                    break;
                default:
                    this._attachType = 2;
                    break;
            }
            this._attachSaveAtRoot = UtilityHandler.CreateAttachFolder();
            if (this._attachSaveAtRoot == string.Empty)
            {
                return ("创建文件夹失败，请到后台将论坛设置中AttachSaveAt选用“固定位置”&nbsp; <a href=\"javascript:alert('论坛没有足够的权限创建文件夹，需要目录bbs/" + ConfigInfo.UploadfilePath.Replace(@"\", @"\\") + "及其所有上级目录目录具有“列出文件夹”权限。如无法配置该权限，请到论坛后台管理在论坛设置中将“AttachSaveAt”选为固定位置。')\">[详细]</a>");
            }
            DateTime now = DateTime.Now;
            this.ImgBigUpfileName = string.Concat(new object[] { now.Year, Text.AddZero(now.Month), Text.AddZero(now.Day), "_", Text.AddZero(now.Hour), Text.AddZero(now.Minute), Text.AddZero(now.Second), "_", now.Millisecond.ToString() });
            this.ImgMinUpfileName = this._attachSaveAtRoot + this.ImgBigUpfileName + "-i-" + this.ext;
            this._attachPath = this._attachSaveAtRoot + this.ImgBigUpfileName + this.ext;
            this.ImgBigUpfileName = this._attachPath;
            return string.Empty;
        }

        private string ReplaceDisabledChars(string s)
        {
            return s.Replace("[", "【").Replace("]", "】").Replace(",", "，");
        }

        public string Save()
        {
            string str = this.CheckPostedFile();
            if (str != string.Empty)
            {
                return str;
            }
            if (bool.Parse(Config.Settings["EnableAddLogo"]) && (this._attachType == 1))
            {
                UploadImage img = new UploadImage();
                img.file = this._postedFile;
                img.path = ConfigInfo.UploadfilePath + this._attachPath;
                img.mod = int.Parse(Config.Settings["LogoPace"].ToString());
                img.add = int.Parse(Config.Settings["AddLogoMod"].ToString());
                img.zoom = Convert.ToBoolean(Config.Settings["KeepPics"].ToString());
                img.zoompics = Config.Settings["KeppPicsSize"].ToString();
                img.view = false;
                img.viewpics = "10,10";
                img.padding = 1;
                img.text = Config.Settings["AddText"].ToString();
                img.textwh = Config.Settings["AddTextInfo"].ToString();
                img.font = Config.Settings["AddTextFace"].ToString();
                img.size = int.Parse(Config.Settings["AddTextSize"].ToString());
                img.colorstring = Config.Settings["AddTextColor"].ToString();
                img.modpics = Config.Settings["LogoPace0"].ToString();
                img.Save();
            }
            else
            {
                this._postedFile.SaveAs(Fetch.MapPath(ConfigInfo.UploadfilePath + this._attachPath));
            }
            new Connection().ExecSql("Insert Into BBS_Upfile (F_UserName,F_Name,F_Path,F_Type,F_Size,F_DT) Values ('" + Text.SqlEncode(this.Uploader.UserName) + "','" + this._attachName + "','" + this._attachPath + "','" + this._attachType + "','" + this._attachSize + "','" + DateTime.Now.ToString() + "')");
            this._attachid = new Connection().GetiScalar("Select F_Id From BBS_Upfile Where F_UserName = '" + Text.SqlEncode(this.Uploader.UserName) + "' Order By F_Id Desc");
            return string.Empty;
        }

        // Properties
        public int AttachId
        {
            get
            {
                return this._attachid;
            }
        }

        public string AttachName
        {
            get
            {
                return this._attachName;
            }
            set
            {
                this._attachName = value;
            }
        }

        public string AttachPath
        {
            get
            {
                return this._attachPath;
            }
        }

        public string AttachExt
        {
            get
            {
                return this.ext;
            }
        }

        public string AttachSaveAtRoot
        {
            get
            {
                return this._attachSaveAtRoot;
            }
        }

        public long AttachSize
        {
            get
            {
                return this._attachSize;
            }
        }

        public int AttachType
        {
            get
            {
                return this._attachType;
            }
        }

        public HttpPostedFile PostedFile
        {
            get
            {
                return this._postedFile;
            }
            set
            {
                this._postedFile = value;
            }
        }

        public UserInfo Uploader
        {
            get
            {
                if (this._user == null)
                {
                    this._user = UserInfo.Current;
                }
                return this._user;
            }
            set
            {
                this._user = value;
            }
        }
    }

    public class Rss : Page
    {
        // Fields
        private int _boardid;
        private string _url;

        // Methods
        public Rss()
        {
            string temp = "http://" + Context.Request.Url.Host.ToLower() + (80 == Context.Request.Url.Port ? string.Empty : ":" + Context.Request.Url.Port.ToString()) + Fetch.RawUrl;
            this._url = temp.Substring(0, temp.LastIndexOf("/") + 1);
            if (RegExp.IsNumeric(Fetch.Get("bid")))
            {
                this._boardid = int.Parse(Fetch.Get("bid"));
                return;
            }
            _boardid = -1;
        }

        private void RenderItem(string title, DateTime pubDate, string description, int topicid)
        {
            Response.Write("		<item>\r\n");
            Response.Write("			<title>" + title + "</title>\r\n");
            Response.Write("			<pubDate>" + pubDate.ToString("g") + "</pubDate>\r\n");
            Response.Write("			<description><![CDATA[" + description + "]]></description>\r\n");
            Response.Write("			<link>" + _url + "topic.aspx?tid=" + topicid + "</link>\r\n");
            Response.Write("		</item>\r\n");
        }

        private void InitializeComponent()
        {
            this.Load += new EventHandler(this.Page_Load);
        }

        protected override void OnInit(EventArgs e)
        {
            this.InitializeComponent();
            base.OnInit(e);
        }

        private void Page_Load(object sender, EventArgs e)
        {
            string title, link, description;
            if (_boardid == -1)
            {
                title = ConfigInfo.bbsName + "最新主题";
                link = _url + "index.aspx";
                description = ConfigInfo.bbsName + "最新发表的30个主题";
            }
            else
            {
                string boardname = new Connection().GetScalar("Select B_Text From BBS_Board Where B_Id = " + _boardid.ToString());
                title = ConfigInfo.bbsName + boardname + "最新主题";
                link = _url + "board.aspx?bid=" + _boardid;
                description = ConfigInfo.bbsName + boardname + "版面最新发表的30个主题";
            }
            Response.ContentType = "text/xml";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.Write("<?xml version=\"1.0\" encoding=\"gb2312\" ?>\r\n");
            Response.Write("<rss version=\"2.0\">\r\n");
            Response.Write("	<channel>\r\n");
            Response.Write("		<title>" + Text.TextEncode(title) + "</title>\r\n");
            Response.Write("		<link>" + Text.TextEncode(link) + "</link>\r\n");
            Response.Write("		<description>" + Text.TextEncode(description) + "</description>\r\n");
            Response.Write("		<language>zh-cn</language>\r\n");
            string strSql = "Select Top 30 T.T_Id, T.T_Title, T.T_PostDT, T.T_Content From BBS_Topic T, BBS_Board B Where T.T_Bid = B.B_Id And T.T_IsDelete = 0";
            if (_boardid != -1)
            {
                strSql += " And T.T_Bid = " + _boardid.ToString();
            }
            strSql += " Order By T.T_Id Desc";
            DataTable dataTable = new Connection().GetDataTable(strSql);
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                this.RenderItem(dataTable.Rows[i]["T_Title"].ToString(), (DateTime)dataTable.Rows[i]["T_PostDT"], Text.HtmlDecode(Text.Left(dataTable.Rows[i]["T_Content"].ToString(), 250, false)), (int)dataTable.Rows[i]["T_Id"]);
            }
            dataTable.Dispose();
            Response.Write("	</channel>\r\n</rss>");
            Response.End();
        }
    }

    public class Uploadattach : Page
    {
        // Fields
        private string _AllowTypes;
        private int _AllowSize;

        // Methods
        private void Trace(string message, string scriptcode, bool showback)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
            builder.Append("\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">");
            builder.Append("\r\n<head>");
            builder.Append("\r\n<title>上传附件</title>");
            builder.AppendFormat("\r\n<link href=\"{0}style.css\" rel=\"stylesheet\" type=\"text/css\" />", ConfigInfo.SkinPath);
            builder.Append(scriptcode);
            builder.Append("\r\n</head>");
            builder.Append("\r\n<body style=\"margin:0;padding:0;background-image:none;text-align:left;overflow:hidden;\">");
            builder.Append("\r\n<table cellpadding=\"0\" cellspacing=\"0\" class=\"toptable\" style=\"width:100%;height:100%\">");
            builder.Append("\r\n<tr><td style=\"font-size:12px\">");
            builder.AppendFormat("{0}", message);
            if (showback)
            {
                builder.Append(" &nbsp;<a href=\"uploadattach.aspx\">[重新上传]</a>");
            }
            builder.Append("\r\n</td></tr>");
            builder.Append("\r\n</table>");
            builder.Append("\r\n</body>");
            builder.Append("\r\n</html>");
            base.Response.Write(builder.ToString());
            base.Response.End();
        }

        private void InitializeComponent()
        {
            base.Load += new EventHandler(this.Page_Load);
        }

        protected override void OnInit(EventArgs e)
        {
            if ((Fetch.UrlReferrer == string.Empty) || Fetch.IsGetFromAnotherDomain)
            {
                UtilityHandler.Prompt("本页无法直接访问！");
            }
            this.InitializeComponent();
            base.OnInit(e);
        }

        private void Page_Load(object sender, EventArgs e)
        {
            if (!UtilityHandler.IsLogin())
            {
                this.Trace("你还没有登录，请登录后再上传附件！", null, false);
            }
            if ((new UserInfo().Integral) < ConfigInfo.UploadRequireExp)
            {
                this.Trace("积分达到" + ConfigInfo.UploadRequireExp + "分的注册会员才能上传附件！", null, false);
            }
            if (base.Request.Files.Count <= 0)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendFormat("\r\n<input type=\"hidden\" id=\"allowTypes\" value=\"{0}\" />", this.AllowTypes);
                builder.Append("\r\n<form id=\"uploadform\" name=\"uploadform\" method=\"post\" action=\"uploadattach.aspx\" enctype=\"multipart/form-data\" style=\"margin:0;padding:0\">");
                builder.Append("\r\n<input type=\"file\" id=\"upfile\" name=\"upfile\" onfocus=\"IEvent('focus',this);\" onblur=\"IEvent('blur',this);\" onmouseover=\"IEvent('mouseover',this)\" onmouseout=\"IEvent('mouseout',this)\"  style=\"width:280px;height:23px;\" />");
                builder.Append("\r\n<input type=\"submit\" id=\"submit\" name=\"submit\" class=\"button_off\" onmouseover=\"IEvent('mouseover',this)\" onmouseout=\"IEvent('mouseout',this)\"  runat=\"server\" value=\" 上传 \" onclick=\"return CheckUpload(this.form);\" />");
                builder.Append("\r\n<span style=\"font-size:12px\">&nbsp;&nbsp;<a href=\"javascript:void(0);\" onclick=\"javascript:alert('文件大小限制为：" + this.AllowSize + " KB。\\r\\r\\n文件类型限制为：" + this.AllowTypes.Replace("|", " ") + "。');\">[查看限制]</a></span>");
                builder.Append("\r\n</form>");
                this.Trace(builder.ToString(), "\r\n<script type=\"text/javascript\" src=\"scripts/common.js\"></script>", false);
            }
            else
            {
                Attachment attach = new Attachment();
                attach.Uploader = UserInfo.Current;
                attach.PostedFile = base.Request.Files["upfile"];
                string message = attach.Save();
                if (message != string.Empty)
                {
                    this.Trace(message, null, true);
                }
                StringBuilder builder = new StringBuilder();
                builder.Append("\r\n<script type=\"text/javascript\">");
                builder.Append("\r\n<!--");
                builder.Append("\r\nvar f = parent.$('ifrHtmlEditor').contentWindow.document.frames['HtmlEditor'];");
                builder.Append("\r\nif(!f.document.body.focus()){");
                builder.Append("\r\n\tf.document.body.focus();");
                builder.Append("\r\n}");
                switch (attach.AttachType)
                {
                    case 1:
                        builder.Append("\r\nif (f.document.selection){");
                        builder.AppendFormat("\r\n\tf.document.selection.createRange().pasteHTML('<br />[upload={0}]{1}[/upload]<br />');", attach.AttachExt.Replace(".", ""), (ConfigInfo.UploadfilePath.Replace("\\", "/") + attach.AttachPath));
                        builder.Append("\r\n}else if(f.window.getSelection){");
                        builder.AppendFormat("\r\n\tf.window.getSelection().createRange().pasteHTML('<br />[upload={0}]{1}[/upload]<br />');", attach.AttachExt.Replace(".", ""), (ConfigInfo.UploadfilePath.Replace("\\", "/") + attach.AttachPath));
                        builder.Append("\r\n}");
                        break;
                    default:
                        builder.Append("\r\nif (f.document.selection){");
                        builder.AppendFormat("\r\n\tf.document.selection.createRange().pasteHTML('<br />[uploadfile]{0},{1},{2}kb[/uploadfile]<br />');", (ConfigInfo.UploadfilePath.Replace("\\", "/") + attach.AttachPath), attach.AttachName, (((double)attach.AttachSize) / 1024.0).ToString("f1"));
                        builder.Append("\r\n}else if(f.window.getSelection){");
                        builder.AppendFormat("\r\n\tf.window.getSelection().createRange().pasteHTML('<br />[uploadfile]{0},{1},{2}kb[/uploadfile]<br />');", (ConfigInfo.UploadfilePath.Replace("\\", "/") + attach.AttachPath), attach.AttachName, (((double)attach.AttachSize) / 1024.0).ToString("f1"));
                        builder.Append("\r\n}");
                        break;
                }
                builder.Append("\r\n//-->");
                builder.Append("\r\n</script>");
                this.Trace("恭喜，附件成功上传！&nbsp; <a href=\"uploadattach.aspx\">[继续上传]</a>", builder.ToString(), false);
            }
        }

        // Properties
        protected string AllowTypes
        {
            get
            {
                this._AllowTypes = ConfigInfo.AllowAttachType;
                return this._AllowTypes;
            }
        }

        protected int AllowSize
        {
            get
            {
                this._AllowSize = ConfigInfo.AllowAttachSize;
                if ((new UserInfo().Power) == 3)
                {
                    this._AllowSize = Math.Max(this._AllowSize, 2048);
                }
                return this._AllowSize;
            }
        }
    }

    public class Upload : Page
    {
        // Fields
        private string _AllowTypes;
        private int _AllowSize;
        private string _FileName;
        private int _FileType;
        private string _FilePath;
        private string _FileSaveAtRoot;
        private HttpPostedFile _PostedFile;

        // Methods
        private string CheckPostedFile()
        {
            this._PostedFile = base.Request.Files["upfile"];
            if (this._PostedFile == null)
            {
                return "上传失败，请选择你要上传的文件！";
            }
            int filesize = this._PostedFile.ContentLength;
            if ((filesize / 1024) > this.AllowSize)
            {
                return ("上传失败，文件的大小不能超过 " + this.AllowSize + " KB！");
            }
            string filename = this._PostedFile.FileName;
            if ((filename.ToString() == string.Empty) || (filesize == 0))
            {
                return "上传失败，请选择你要上传的文件！";
            }
            string fileext = filename.Substring(filename.LastIndexOf(".")).ToLower();
            string allowtypes = this.AllowTypes;
            string[] strArray = allowtypes.Split(new char[] { '|' });
            bool flag = false;
            for (int i = 0; i < strArray.Length; i++)
            {
                if (flag = fileext == strArray[i].Trim())
                {
                    break;
                }
            }
            if (!flag)
            {
                return ("上传失败，文件格式只能为：" + allowtypes.Replace("|", " ") + " ！");
            }
            filename = filename.Substring(filename.LastIndexOf(@"\") + 1);
            if (Text.Len(filename) > 40)
            {
                return "附件原名过长，最多20个汉字或40个字母，请修改后再上传！";
            }
            switch (fileext)
            {
                case ".gif":
                case ".png":
                case ".bmp":
                case ".jpg":
                case ".jpe":
                case ".jpeg":
                    this._FileType = 1;
                    break;
                case ".zip":
                    this._FileType = 3;
                    break;
                case ".doc":
                case ".xls":
                case ".mdb":
                case ".ppt":
                    this._FileType = 4;
                    break;
                case ".swf":
                    this._FileType = 5;
                    break;
                default:
                    this._FileType = 2;
                    break;
            }
            this._FileName = filename.Replace("[", "【").Replace("]", "】").Replace(",", "，");
            DateTime now = DateTime.Now;
            this._FilePath = string.Concat(new object[] { this.FileSaveAtRoot, now.Year, Text.AddZero(now.Month), Text.AddZero(now.Day), "_", Text.AddZero(now.Hour), Text.AddZero(now.Minute), Text.AddZero(now.Second), "_", now.Millisecond.ToString(), fileext });
            return string.Empty;
        }

        private void Trace(string message, string scriptcode, bool showback)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
            builder.Append("\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">");
            builder.Append("\r\n<head>");
            builder.Append("\r\n<title>上传文件</title>");
            builder.Append("\r\n<link href=\"style/style.css\" rel=\"stylesheet\" type=\"text/css\" />");
            builder.Append(scriptcode);
            builder.Append("\r\n</head>");
            builder.Append("\r\n<body style=\"margin:0;padding:0;background:none;text-align:left;overflow:hidden;\">");
            builder.Append("\r\n<table cellpadding=\"0\" cellspacing=\"0\" class=\"toptable\" style=\"width:100%;height:100%\">");
            builder.Append("\r\n<tr><td style=\"font-size:12px\">");
            builder.AppendFormat("{0}", message);
            if (showback)
            {
                builder.Append(" &nbsp;<a href=\"upload.aspx\">[重新上传]</a>");
            }
            builder.Append("\r\n</td></tr>");
            builder.Append("\r\n</table>");
            builder.Append("\r\n</body>");
            builder.Append("\r\n</html>");
            base.Response.Write(builder.ToString());
            base.Response.End();
        }

        private void InitializeComponent()
        {
            base.Load += new EventHandler(this.Page_Load);
        }

        protected override void OnInit(EventArgs e)
        {
            if ((Fetch.UrlReferrer == string.Empty) || Fetch.IsGetFromAnotherDomain)
            {
                UtilityHandler.Prompt("本页无法直接访问！");
            }
            this.InitializeComponent();
            base.OnInit(e);
        }

        private void Page_Load(object sender, EventArgs e)
        {
            if (Fetch.Get("type") != string.Empty)
            {
                switch (Fetch.Get("type"))
                {
                    case "ads":
                        {
                            this._AllowTypes = ".jpg|.gif|.png|.bmp|.swf";
                            this._FileSaveAtRoot = "uploadfiles/ads/";
                            break;
                        }
                    case "icons":
                        {
                            this._AllowTypes = ".jpg|.gif|.png|.bmp";
                            this._FileSaveAtRoot = "uploadfiles/icons/";
                            break;
                        }
                }
                this._AllowSize = 2048;
            }
            else
            {
                this._AllowSize = ConfigInfo.AllowAttachSize;
                this._AllowTypes = ConfigInfo.AllowAttachType;
                this._FileSaveAtRoot = ConfigInfo.UploadfilePath;
            }
            if (base.Request.Files.Count <= 0)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendFormat("\r\n<input type=\"hidden\" id=\"allowTypes\" value=\"{0}\" />", this.AllowTypes);
                builder.AppendFormat("\r\n<form id=\"uploadform\" name=\"uploadform\" method=\"post\" action=\"upload.aspx?ctrlid={0}&type={1}\" enctype=\"multipart/form-data\" style=\"margin:0;padding:0\">", Fetch.Get("ctrlid"), Fetch.Get("type"));
                builder.Append("\r\n<input type=\"file\" id=\"upfile\" name=\"upfile\" onfocus=\"IEvent('focus',this);\" onblur=\"IEvent('blur',this);\" onmouseover=\"IEvent('mouseover',this)\" onmouseout=\"IEvent('mouseout',this)\"  style=\"width:260px;height:23px;\" />");
                builder.Append("\r\n<input type=\"submit\" id=\"submit\" name=\"submit\" class=\"button_off\" onmouseover=\"IEvent('mouseover',this)\" onmouseout=\"IEvent('mouseout',this)\"  runat=\"server\" value=\" 上传 \" onclick=\"return CheckUpload(this.form);\" />");
                builder.Append("\r\n<br /><span style=\"font-size:12px\">文件大小限制为：" + this.AllowSize + " KB。<br />文件类型限制为：" + this.AllowTypes.Replace("|", " ") + "。</span>");
                builder.Append("\r\n</form>");
                this.Trace(builder.ToString(), "\r\n<script type=\"text/javascript\" src=\"scripts/common.js\"></script>", false);
            }
            else
            {
                string message = this.CheckPostedFile();
                if (message != string.Empty)
                {
                    this.Trace("<span style=\"font-size:14px\">" + message + "</span><br />", null, true);
                }
                else
                {
                    this._PostedFile.SaveAs(Fetch.MapPath("../../bbs/" + this._FilePath));
                }
                StringBuilder builder = new StringBuilder();
                builder.Append("\r\n<script type=\"text/javascript\">");
                builder.Append("\r\n<!--");
                builder.AppendFormat("\r\nparent.$('{0}').value = '{1}';", Fetch.Get("ctrlid"), this._FilePath);
                builder.Append("\r\nparent.$('Uploadfile').style.height = '30px';");
                builder.Append("\r\n//-->");
                builder.Append("\r\n</script>");
                this.Trace("<span style=\"font-size:14px\">恭喜，文件已成功上传！</span>", builder.ToString(), false);
            }
        }

        // Properties
        private string AllowTypes
        {
            get
            {
                return this._AllowTypes;
            }
        }

        private int AllowSize
        {
            get
            {
                return this._AllowSize;
            }
        }

        private string FileSaveAtRoot
        {
            get
            {
                return _FileSaveAtRoot;
            }
        }
    }

    public class Ads : Page
    {
        // Fields
        private string _adfilepath;

        // Methods
        public Ads()
        {
            this._adfilepath = Fetch.MapPath("ads.xml"); 
        }

        private void InitializeComponent()
        {
            this.Load += new EventHandler(this.Page_Load);
        }

        protected override void OnInit(EventArgs e)
        {
            this.InitializeComponent();
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string _name = null;
            string _value = null;
            string _linkurl = null;
            XmlTextReader reader = null;
            try
            {
                reader = new XmlTextReader(this._adfilepath);
                reader.WhitespaceHandling = WhitespaceHandling.None;
                reader.MoveToContent();
                while (reader.Read())
                {
                    if (reader.Depth == 2 && reader.IsStartElement())
                    {
                        if (reader.Name == "Name")
                        {
                            _name += reader.ReadString() + "|";
                        }
                        if (reader.Name == "Value")
                        {
                            _value += reader.ReadString() + "|";
                        }
                        if (reader.Name == "Linkurl")
                        {
                            _linkurl += reader.ReadString() + "|";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                new Terminator().Throw(ex.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader = null;
                }
            }
            _name = _name.Substring(0, _name.LastIndexOf("|"));
            _value = _value.Substring(0, _value.LastIndexOf("|"));
            _linkurl = _linkurl.Substring(0, _linkurl.LastIndexOf("|"));
            string _content = null;
            _content += "\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
            _content += "\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">";
            _content += "\r\n<head>";
            _content += "\r\n<title>论坛广告 - " + ConfigInfo.bbsName + "</title>";
            _content += "\r\n</head>";
            _content += "\r\n<body style=\"margin:0;padding:0\">";
            _content += "\r\n<div id=\"content\"></div>";
            _content += "\r\n<script type=\"text/javascript\">";
            _content += "\r\n<!--";
            _content += "\r\nvar _adname = '" + _name + "';";
            _content += "\r\nvar adname = _adname.split(\"|\")";
            _content += "\r\nvar _advalue = '" + _value + "';";
            _content += "\r\nvar advalue = _advalue.split(\"|\")";
            _content += "\r\nvar _adlinkurl = '" + _linkurl + "';";
            _content += "\r\nvar adlinkurl = _adlinkurl.split(\"|\")";
            _content += "\r\nvar swfwidth = 468;";
            _content += "\r\nvar swfheight = 60;";
            _content += "\r\nvar rndNum = Math.round(Math.random() * (advalue.length-1));";
            _content += "\r\nvar extension = advalue[rndNum].substr(advalue[rndNum].lastIndexOf(\".\")).toLowerCase();";
            _content += "\r\nif (extension == '.png' || extension == '.gif' || extension == '.jpg' || extension == '.bmp'){";
            _content += "\r\n\thtmlcode = '<a href=\"'+adlinkurl[rndNum]+'\" target=\"_blank\"><img src=\"'+advalue[rndNum]+'\" border=\"0\" alt=\"'+adname[rndNum]+'\" /></a>';";
            _content += "\r\n}else if (extension == '.swf'){";
            _content += "\r\n\thtmlcode = '<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0\" width=\"'+swfwidth+'\" height=\"'+swfheight+'\"><param name=movie value=\"'+advalue[rndNum]+'\"><PARAM NAME=\"wmode\" value=\"opaque\"><param name=\"quality\" value=\"high\"><embed src=\"'+advalue[rndNum]+'\" quality=\"high\" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\" type=\"application/x-shockwave-flash\" width=\"'+swfwidth+'\" height=\"'+swfheight+'\"></embed></object>';";
            _content += "\r\n}";
            _content += "\r\ndocument.getElementById('content').innerHTML = htmlcode;";
            _content += "\r\n//-->";
            _content += "\r\n</script>";
            _content += "\r\n</body>";
            _content += "\r\n</html>";
            base.Response.Write(_content);
            base.Response.End();
        }
    }

    public class Announcement : Page
    {
        // Methods
        private void InitializeComponent()
        {
            this.Load += new EventHandler(this.Page_Load);
        }

        protected override void OnInit(EventArgs e)
        {
            this.InitializeComponent();
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            UtilityHandler.CheckForumStatus();
            if (RegExp.IsNumeric(Fetch.Get("id")) && (new Connection().GetScalar("Select A_Id From BBS_Announce Where A_Id = " + Fetch.Get("id"))) != string.Empty)
            {
                string _content = null;
                _content += "\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
                _content += "\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">";
                _content += "\r\n<head>";
                _content += "\r\n<title>论坛公告 - " + ConfigInfo.bbsName + "</title>";
                _content += "\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" />";
                _content += "\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"" + ConfigInfo.SkinPath + "style.css\" />";
                _content += "\r\n</head>";
                _content += "\r\n<body style=\"background-image: none;\">";
                _content += "\r\n<table border=\"0\" cellspacing=\"1\" cellpadding=\"3\" style=\"width:100%\">";
                DataTable dataTable = new Connection().GetDataTable("Select * From BBS_Announce Where A_Id = " + Fetch.Get("id"));
                if (dataTable.Rows.Count > 0)
                {
                    _content += "\r\n<tr><td style=\"text-align: center; font-weight: 700; font-size: 16px; padding-top: 8px;\">" + Text.HtmlDecode(dataTable.Rows[0][1].ToString()) + "</td></tr>";
                    _content += "\r\n<tr><td style=\"padding: 10px; line-height: 16px; width: 100%; word-wrap: break-word; text-indent: 2em;\" valign=\"top\">" + Text.HtmlDecode(dataTable.Rows[0][2].ToString()) + "</td></tr>";
                    _content += "\r\n<tr><td style=\"text-align: right; padding-right: 15px;\"><b>发布人</b>:" + dataTable.Rows[0][3].ToString() + "<br /><b>发布时间</b>:" + dataTable.Rows[0][4].ToString() + "</td></tr>";
                }
                dataTable.Dispose();
                _content += "\r\n</table>";
                _content += "\r\n</body>";
                _content += "\r\n</html>";
                base.Response.Write(_content);
                base.Response.End();
            }
            else
            {
                new Terminator().Throw("地址栏中参数“id”的值不符合要求或具有潜在威胁，请不要手动修改URL。");
            }
        }
    }
}

namespace xl_utils
{
    public class Operation
    {
        public static bool SaveLog(string s)
        {
            string[] objArray = HttpContext.Current.Request.ServerVariables["URL"].ToString().Split('/');
            string _operator = HttpContext.Current.Session["UserName_Back"].ToString();
            if (new Connection().ExecSql_Main("Insert Into Sys_Log (L_Operator,L_Object,L_Content,L_Date,L_Ip) Values('" + _operator + "','" + objArray[objArray.Length - 1] + "','" + s + "','" + DateTime.Now.ToString() + "','" + Fetch.UserIP + "')"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static void WriteFile(string sFileName, string sFileContent)
        {
            if (!File.Exists(sFileName))
            {
                File.Create(sFileName, 1).Close();
            }
            StreamWriter sw = new StreamWriter(sFileName);
            sw.Write(sFileContent);
            sw.Close();
        }
    }

    public class Config
    {
        // Fields
        private static readonly object _lockobject = new object();
        private string _filename;
        private Hashtable _hashtable;
        private static Config _settings;

        // Methods
        public Config()
        {
            this._filename = ConfigInfo.CustomConfigFile;
            this.Initialize();
        }

        public Config(string filename)
        {
            this._filename = filename;
            this.Initialize();
        }

        private void Initialize()
        {
            object obj2 = Caching.Get(this.ConfigFilePath);
            if (obj2 != null)
            {
                this._hashtable = obj2 as Hashtable;
            }
            else if (!File.Exists(this.ConfigFilePath))
            {
                this._filename = "../../bbs/" + this._filename;
                if (!File.Exists(this.ConfigFilePath))
                {
                    new Terminator().Throw("配置文件 " + this._filename + " 不存在或访问被拒绝。");
                }
            }
            else
            {
                this._hashtable = new Hashtable();
                XmlTextReader reader = null;
                try
                {
                    string key = null;
                    string str2 = null;
                    reader = new XmlTextReader(this.ConfigFilePath);
                    reader.WhitespaceHandling = WhitespaceHandling.None;
                    reader.MoveToContent();
                    while (reader.Read())
                    {
                        if (((3 == reader.Depth) && (XmlNodeType.EndElement == reader.NodeType)) && ("Item" == reader.Name))
                        {
                            if (!this._hashtable.ContainsKey(key))
                            {
                                this._hashtable.Add(key, str2);
                            }
                        }
                        else if ((4 == reader.Depth) && reader.IsStartElement())
                        {
                            if ("Name" == reader.Name)
                            {
                                key = reader.ReadString();
                                continue;
                            }
                            if ("Value" == reader.Name)
                            {
                                str2 = reader.ReadString();
                            }
                        }
                    }
                    key = (string)(str2 = null);
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                        reader = null;
                    }
                }
                Caching.Set(this.ConfigFilePath, this._hashtable, new CacheDependency(this.ConfigFilePath), DateTime.Now.AddSeconds(12.0));
            }
        }

        public void RemoveSelfCache()
        {
            Caching.Remove(this.ConfigFilePath);
        }

        // Properties
        public string this[string key]
        {
            get
            {
                if (this._hashtable.ContainsKey(key))
                {
                    return this._hashtable[key].ToString();
                }
                return string.Empty;
            }
            set
            {
                this._hashtable[key] = value;
            }
        }

        private string ConfigFilePath
        {
            get
            {
                if (('/' == this._filename[0]) && (HttpContext.Current != null))
                {
                    return HttpContext.Current.Server.MapPath(this._filename);
                }
                return Fetch.MapPath(this._filename);
            }
        }

        public static Config Settings
        {
            get
            {
                lock (_lockobject)
                {
                    if (_settings == null)
                    {
                        _settings = new Config();
                        return _settings;
                    }
                }
                _settings.Initialize();
                return _settings;
            }
        }
    }

    public class RegExp
    {
        // Methods
        public static string[] GetDifDateAndTime(object todate, object fodate)
        {
            string[] strArray = new string[2];
            TimeSpan span = (TimeSpan)(DateTime.Parse(todate.ToString()) - DateTime.Parse(fodate.ToString()));
            double num = span.TotalSeconds / 86400.0;
            num.ToString();
            int length = num.ToString().Length;
            int startIndex = num.ToString().LastIndexOf(".");
            int num4 = (int)Math.Round(num, 10);
            int num5 = (int)(double.Parse("0" + num.ToString().Substring(startIndex, length - startIndex)) * 24.0);
            strArray[0] = num4.ToString();
            strArray[1] = num5.ToString();
            return strArray;
        }

        public static string GetDifDateAndTime(object todate, object fodate, string v1, string v2, string v3, string v4, string v5, string v6)
        {
            TimeSpan span = (TimeSpan)(DateTime.Parse(todate.ToString()) - DateTime.Parse(fodate.ToString()));
            int num = ((int)span.TotalDays) / 0x16d;
            int num2 = (int)(((span.TotalDays / 365.0) - ((int)(span.TotalDays / 365.0))) * 12.0);
            int num3 = (span.Days - (num * 0x16d)) - (num2 * 30);
            int hours = span.Hours;
            int minutes = span.Minutes;
            string str = "";
            if (num != 0)
            {
                str = str + num.ToString() + v1;
            }
            if (num2 != 0)
            {
                str = str + num2.ToString() + v2;
            }
            if (num3 != 0)
            {
                str = str + num3.ToString() + v3;
            }
            if (hours != 0)
            {
                str = str + hours.ToString() + v4;
            }
            if (minutes != 0)
            {
                str = str + minutes.ToString() + v5;
            }
            if ((((num == 0) && (num2 == 0)) && ((num3 == 0) && (hours == 0))) && (minutes == 0))
            {
                return v6;
            }
            return str;
        }

        public static string[] GetPercence(int a, int b)
        {
        Label_0000:
            while (((a % 2) == 0) && ((b % 2) == 0))
            {
                a /= 2;
                b /= 2;
            }
            if (((a % 3) == 0) && ((b % 3) == 0))
            {
                a /= 3;
                b /= 3;
                goto Label_0000;
            }
            if (((a % 5) == 0) && ((b % 5) == 0))
            {
                a /= 5;
                b /= 5;
                goto Label_0000;
            }
            if (((a % 7) == 0) && ((b % 7) == 0))
            {
                a /= 7;
                b /= 7;
                goto Label_0000;
            }
            return new string[] { a.ToString(), b.ToString() };
        }

        public static bool isChinese(string s)
        {
            string pattern = @"^[\u4e00-\u9fa5]{2,}$";
            return Regex.IsMatch(s, pattern);
        }

        public static bool IsEmail(string s)
        {
            string pattern = @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$";
            return Regex.IsMatch(s, pattern);
        }

        public static bool IsIp(string s)
        {
            string pattern = @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$";
            return Regex.IsMatch(s, pattern);
        }

        public static bool IsNumeric(string s)
        {
            string pattern = @"^\-?[0-9]+$";
            return Regex.IsMatch(s, pattern);
        }

        public static bool IsPhysicalPath(string s)
        {
            string pattern = @"^\s*[a-zA-Z]:.*$";
            return Regex.IsMatch(s, pattern);
        }

        public static bool IsRelativePath(string s)
        {
            if ((s == null) || (s == string.Empty))
            {
                return false;
            }
            if (s.StartsWith("/") || s.StartsWith("?"))
            {
                return false;
            }
            if (Regex.IsMatch(s, @"^\s*[a-zA-Z]{1,10}:.*$"))
            {
                return false;
            }
            return true;
        }

        public static bool IsSafety(string s)
        {
            string input = Regex.Replace(s.Replace("%20", " "), @"\s", " ");
            string pattern = "select |insert |delete from |count\\(|drop table|update |truncate |asc\\(|mid\\(|char\\(|xp_cmdshell|exec master|net localgroup administrators|:|net user|\"|\\'| or ";
            return !Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase);
        }

        public static bool IsUnicode(string s)
        {
            string pattern = @"^[\u4E00-\u9FA5\uE815-\uFA29]+$";
            return Regex.IsMatch(s, pattern);
        }

        public static bool IsUnsFlaot(string s)
        {
            string pattern = "^[0-9]+.?[0-9]+$";
            return Regex.IsMatch(s, pattern);
        }

        public static bool IsUnsNumeric(string s)
        {
            string pattern = "^[0-9]+$";
            return Regex.IsMatch(s, pattern);
        }

        public static bool IsUrl(string s)
        {
            string pattern = @"^(http|https|ftp|rtsp|mms):(\/\/|\\\\)[A-Za-z0-9%\-_@]+\.[A-Za-z0-9%\-_@]+[A-Za-z0-9\.\/=\?%\-&_~`@:\+!;]*$";
            return Regex.IsMatch(s, pattern, RegexOptions.IgnoreCase);
        }

        public static string Replace(string s, string pattern, string replacement)
        {
            return Regex.Replace(s, pattern, replacement, RegexOptions.Multiline | RegexOptions.IgnoreCase);
        }
    }

    public class Fetch
    {
        // Methods
        public static string Get(string name)
        {
            string str = HttpContext.Current.Request.QueryString[name];
            if (str != null)
            {
                return str.Trim();
            }
            return string.Empty;
        }

        public static string Post(string name)
        {
            string str = HttpContext.Current.Request.Form[name];
            if (str != null)
            {
                return str.Trim();
            }
            return string.Empty;
        }

        public static string MapPath(string path)
        {
            if (RegExp.IsPhysicalPath(path))
            {
                return path;
            }
            else
            {
                return HttpContext.Current.Server.MapPath(path);
            }
        }

        public static string UrlEncode(string url)
        {
            return HttpContext.Current.Server.UrlEncode(url);
        }

        public static string UrlDecode(string url)
        {
            return HttpContext.Current.Server.UrlDecode(url);
        }

        public static void Redirect(string url)
        {
            HttpContext.Current.Response.Redirect(url);
        }

        public static void Trace(object obj)
        {
            HttpContext.Current.Response.Write(obj.ToString());
        }

        public static void End()
        {
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 获得当前请求的虚拟路径
        /// </summary>
        public static string Path
        {
            get
            {
                string path = HttpContext.Current.Request.Path;
                path = path.Substring(0, path.LastIndexOf("/"));
                if (path == "/")
                {
                    return string.Empty;
                }
                return path;
            }
        }

        /// <summary>
        /// 获得当前的文件地址
        /// </summary>
        public static string CurrentFileName
        {
            get
            {
                string strUrl = HttpContext.Current.Request.ServerVariables["URL"].ToString();
                string sUrl = null;
                if (strUrl.StartsWith("/"))
                {
                    string[] Url = strUrl.Split('/');
                    for (int i = 1; i < Url.Length; i++)
                    {
                        sUrl += Url[i];
                    }
                }
                return sUrl;
            }
        }

        /// <summary>
        /// 获得上次请求的URL
        /// </summary>
        public static string UrlReferrer
        {
            get
            {
                Uri urlReferrer = HttpContext.Current.Request.UrlReferrer;
                if (urlReferrer == null)
                {
                    return string.Empty;
                }
                return Convert.ToString(urlReferrer);
            }
        }

        /// <summary>
        /// 获取当前请求的原始URL
        /// </summary>
        public static string RawUrl
        {
            get
            {
                return HttpContext.Current.Request.RawUrl.ToString();
            }
        }

        /// <summary>
        /// 获取原始URL的文件地址与参数
        /// </summary>
        public static string CurrentUrl
        {
            get
            {
                string sUrl = HttpContext.Current.Request.RawUrl;
                if (sUrl.Contains("/"))
                {
                    return sUrl.Substring(sUrl.LastIndexOf("/") + 1);
                }
                return string.Empty;
            }
        }

        /// <summary> 
        /// 获得当前URL
        /// </summary>
        public static string Url
        {
            get
            {
                return HttpContext.Current.Request.Url.ToString();
            }
        }

        /// <summary>
        /// 获得当前Url的文件地址
        /// </summary>
        public static string FileUrl
        {
            get
            {
                string sUrl = Convert.ToString(HttpContext.Current.Request.Url);
                if (sUrl.Contains("?"))
                {
                    return sUrl.Substring(0, sUrl.LastIndexOf("?"));
                }
                return string.Empty;
            }
        }

        /// <summary>
        /// 获得网站域名
        /// </summary>
        public static string ServerDomain
        {
            get
            {
                string host = HttpContext.Current.Request.Url.Host.ToLower();
                string[] arr = host.Split('.');
                if (arr.Length < 3 || RegExp.IsIp(host))
                {
                    return host;
                }
                string domain = host.Remove(0, host.IndexOf(".") + 1);
                if (domain.StartsWith("com.") || domain.StartsWith("net.") || domain.StartsWith("org.") || domain.StartsWith("gov."))
                {
                    return host;
                }
                return domain;
            }
        }

        /// <summary>
        /// 获取访问者所使用的浏览器
        /// </summary>
        public static string UserBrowser
        {
            get
            {
                string agent = HttpContext.Current.Request.UserAgent;
                if (agent == null || agent == string.Empty)
                {
                    return "Unknown";
                }
                agent = agent.ToLower();
                HttpBrowserCapabilities browser = HttpContext.Current.Request.Browser;
                if (agent.IndexOf("firefox") >= 0 || agent.IndexOf("firebird") >= 0 || agent.IndexOf("myie") >= 0 || agent.IndexOf("opera") >= 0 || agent.IndexOf("netscape") >= 0 || agent.IndexOf("msie") >= 0)
                {
                    return browser.Browser + " " + browser.Version;
                }
                return "Unknown";
            }
        }

        /// <summary>
        /// 获取访问者所使用的操作系统
        /// </summary>
        public static string UserOS
        {
            get
            {
                string os = null;
                string agent = HttpContext.Current.Request.UserAgent;
                if (agent.Contains("Windows NT 6.0"))
                {
                    os = "Windows Vista";
                }
                else if (agent.Contains("Windows NT 5.2"))
                {
                    os = "Windows 2003";
                }
                else if (agent.Contains("Windows NT 5.1"))
                {
                    os = "Windows XP";
                }
                else if (agent.Contains("Windows NT 5"))
                {
                    os = "Windows 2000";
                }
                else if (agent.Contains("Win 9x 4.90"))
                {
                    os = "Windows ME";
                }
                else if (agent.Contains("Windows NT 98"))
                {
                    os = "Windows 98";
                }
                else if (agent.Contains("Windows NT 95"))
                {
                    os = "Windows 95";
                }
                else if (agent.Contains("Mac"))
                {
                    os = "Mac";
                }
                else if (agent.Contains("Unix") || agent.Contains("SunOS") || agent.Contains("BSD"))
                {
                    os = "Unix";
                }
                else if (agent.Contains("Linux"))
                {
                    os = "Linux";
                }
                else
                {
                    os = "Unknown";
                }
                return os;
            }
        }

        /// <summary>
        /// 获取访问者的系统语言
        /// </summary>
        public static string UserLanguage
        {
            get
            {
                return HttpContext.Current.Request.UserLanguages[0];
            }
        }

        /// <summary>
        /// 获取访问者显示器的分辨率
        /// </summary>
        public static string UserResolution
        {
            get
            {
                return System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width.ToString() + "×" + System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height.ToString();
            }
        }

        /// <summary>
        /// 获取客户端IP 
        /// </summary>
        public static string UserIP
        {
            get
            {
                string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (ip == null || ip == string.Empty)
                {
                    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                if (!RegExp.IsIp(ip))
                {
                    return "Unknown";
                }
                return ip;
            }
        }

        /// <summary>
        /// 获取客户端IP的所在区域
        /// </summary>
        public static string IpLocation
        {
            get
            {
                string[] ip = UserIP.Split('.');
                string ipstr = null;
                for (int i = 0; i < ip.Length; i++)
                {
                    if (ip[i].Length == 1) ip[i] = "00" + ip[i];
                    if (ip[i].Length == 2) ip[i] = "0" + ip[i];
                    ipstr += ip[i];
                }
                string area = new Connection().GetScalar_Main("select address from IP where IPS<='" + ipstr + "' and IPE>='" + ipstr + "'");
                area = area.Replace("CZ88.NET", "");
                area = area.Replace(" ", "");
                if (area == "IANA" || area == "")
                {
                    area = "Unknown";
                }
                if (ipstr == "127000000001")
                {
                    area = "Local";
                }
                return area;
            }
        }

        /// <summary>
        /// 搜索引擎来源判断
        /// </summary>
        private static string[] _WebSearchList = new string[] { "google", "isaac", "surveybot", "baiduspider", "yahoo", "yisou", "3721", "qihoo", "daqi", "ia_archiver", "p.arthur", "fast-webcrawler", "java", "microsoft-atl-native", "turnitinbot", "webgather", "sleipnir", "msn" };
        public static bool IsWebSearch()
        {
            string user_agent = HttpContext.Current.Request.UserAgent;
            if (null == user_agent || string.Empty == user_agent)
            {
                return true;
            }
            else
            {
                user_agent = user_agent.ToLower();
            }
            for (int i = 0; i < _WebSearchList.Length; i++)
            {
                if (-1 != user_agent.IndexOf(_WebSearchList[i]))
                {
                    return true;
                }
            }
            return UserBrowser.Equals("Unknown");
        }

        /// <summary>
        /// 获取HTTP数据传输方法
        /// </summary>
        public static bool IsGetFromAnotherDomain
        {
            get
            {
                if (HttpContext.Current.Request.HttpMethod == "POST")
                {
                    return false;
                }
                return (UrlReferrer.IndexOf(ServerDomain) == -1);
            }
        }
    }

    public class Text
    {
        // Methods
        public static string AddZero(int i)
        {
            return (((i > 9) ? string.Empty : "0") + i);
        }

        public static bool ComparePassword(string pwd1, string pwd2)
        {
            if ((pwd1 == null) && (pwd2 == null))
            {
                return true;
            }
            if ((pwd1 == null) || (pwd2 == null))
            {
                return false;
            }
            int length = pwd1.Length;
            int num2 = pwd2.Length;
            if ((length == num2) && (length != 0))
            {
                return (0 == string.Compare(pwd1, pwd2, true));
            }
            if ((0x20 == length) && (0x10 == num2))
            {
                return (0 == string.Compare(pwd1.Substring(8, 0x10), pwd2, true));
            }
            return (((0x10 == length) && (0x20 == num2)) && (0 == string.Compare(pwd2.Substring(8, 0x10), pwd1, true)));
        }

        public static string EmailEncode(string s)
        {
            string str = TextEncode(s).Replace("@", "&#64;").Replace(".", "&#46;");
            return JoinString(new string[] { "<a href='mailto:", str, "'>", str, "</a>" });
        }

        public static string HtmlDecode(string s)
        {
            StringBuilder builder = new StringBuilder(s);
            builder.Replace("&amp;", "&");
            builder.Replace("&lt;", "<");
            builder.Replace("&gt;", ">");
            builder.Replace("&quot;", "\"");
            builder.Replace("&#39;", "'");
            builder.Replace("&nbsp;", " ");
            return builder.ToString();
        }

        public static string HtmlEncode(string s)
        {
            return HtmlEncode(s, false);
        }

        public static string HtmlEncode(string s, bool bln)
        {
            if ((s == null) || (s.Length == 0))
            {
                return string.Empty;
            }
            StringBuilder builder = new StringBuilder(s);
            builder.Replace("&", "&amp;");
            builder.Replace("<", "&lt;");
            builder.Replace(">", "&gt;");
            builder.Replace("\"", "&quot;");
            builder.Replace("'", "&#39;");
            if (bln)
            {
                return ShitEncode(builder.ToString());
            }
            return builder.ToString();
        }

        public static bool IsNumberList(string str)
        {
            return IsNumberList(str, ',');
        }

        public static bool IsNumberList(string str, char separator)
        {
            if (str == null)
            {
                return false;
            }
            int length = str.Length;
            if (length == 0)
            {
                return false;
            }
            if (!char.IsNumber(str[0]) || !char.IsNumber(str[length - 1]))
            {
                return false;
            }
            length--;
            for (int i = 1; i < length; i++)
            {
                if (separator == str[i])
                {
                    if (!char.IsNumber(str[i - 1]) || !char.IsNumber(str[i + 1]))
                    {
                        return false;
                    }
                }
                else if (!char.IsNumber(str[i]))
                {
                    return false;
                }
            }
            return true;
        }

        public static bool IsNumeric(object value)
        {
            if (value == null)
            {
                return false;
            }
            return IsNumeric(value.ToString());
        }

        public static bool IsNumeric(string value)
        {
            if (value == null)
            {
                return false;
            }
            int length = value.Length;
            if (length == 0)
            {
                return false;
            }
            if (('-' != value[0]) && !char.IsNumber(value[0]))
            {
                return false;
            }
            for (int i = 1; i < length; i++)
            {
                if (!char.IsNumber(value[i]))
                {
                    return false;
                }
            }
            return true;
        }

        public static string JavaScriptEncode(object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            return JavaScriptEncode(obj.ToString());
        }

        public static string JavaScriptEncode(string str)
        {
            StringBuilder builder = new StringBuilder(str);
            builder.Replace(@"\", @"\\");
            builder.Replace("\r", @"\0Dx");
            builder.Replace("\n", @"\x0A");
            builder.Replace("\"", @"\x22");
            builder.Replace("'", @"\x27");
            return builder.ToString();
        }

        public static string JoinString(params string[] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (value.Length == 0)
            {
                return string.Empty;
            }
            return string.Join(string.Empty, value);
        }

        public static string Left(string s, int need, bool encode)
        {
            if (s == null || s == "")
            {
                return string.Empty;
            }
            int len = s.Length;
            if (len < need / 2)
            {
                return encode ? TextEncode(s) : s;
            }
            int i, j, bytes = 0;
            for (i = 0; i < len; i++)
            {
                bytes += RegExp.IsUnicode(s[i].ToString()) ? 2 : 1;
                if (bytes >= need)
                {
                    break;
                }
            }
            string result = s.Substring(0, i);
            if (len > i)
            {
                for (j = 0; j < 5; j++)
                {
                    bytes -= RegExp.IsUnicode(s[i - j].ToString()) ? 2 : 1;
                    if (bytes <= need)
                    {
                        break;
                    }
                }
                result = s.Substring(0, i - j) + "...";
            }
            return encode ? TextEncode(result) : result;
        }

        public static int Len(string s)
        {
            return HttpContext.Current.Request.ContentEncoding.GetByteCount(s);
        }

        public static string MD5(string s)
        {
            return MD5(s, null);
        }

        public static string MD5(string s, Encoding enc)
        {
            if ((s == null) || (s.Length == 0))
            {
                s = string.Empty;
            }
            if (enc == null)
            {
                if (HttpContext.Current != null)
                {
                    enc = HttpContext.Current.Request.ContentEncoding;
                }
                else
                {
                    enc = Encoding.UTF8;
                }
            }
            System.Security.Cryptography.MD5 md = System.Security.Cryptography.MD5.Create();
            byte[] bytes = enc.GetBytes(s);
            return BitConverter.ToString(md.ComputeHash(bytes)).Replace("-", "").ToLower();
        }

        public static string MD5(string s, int start, int length)
        {
            return MD5(s).Substring(start, length);
        }

        public static string MD5(string s, Encoding enc, int start, int length)
        {
            return MD5(s, enc).Substring(start, length);
        }

        public static string ShitEncode(string s)
        {
            string input = null;
            if ((input == null) || (input.Length == 0))
            {
                input = "妈的|你妈|他妈|妈b|妈比|fuck|shit|我日|法轮|我操";
            }
            else
            {
                input = Regex.Replace(Regex.Replace(input, @"\|{2,}", "|"), @"(^\|)|(\|$)", string.Empty);
            }
            return Regex.Replace(s, input, "**", RegexOptions.IgnoreCase);
        }

        public static string SqlEncode(string s)
        {
            if ((s != null) && (s.Length != 0))
            {
                return s.Trim().Replace("'", "''");
            }
            return string.Empty;
        }

        public static string StripHtml(string s)
        {
            if ((s != null) && (s.Length != 0))
            {
                return Regex.Replace(s, "<[^>]+>", string.Empty, RegexOptions.Multiline | RegexOptions.IgnoreCase);
            }
            return string.Empty;
        }

        public static string TextDecode(string s)
        {
            StringBuilder builder = new StringBuilder(s);
            builder.Replace("<br/><br/>", "\r\n");
            builder.Replace("<br/>", "\r");
            builder.Replace("<p></p>", "\r\n\r\n");
            return builder.ToString();
        }

        public static string TextEncode(string s)
        {
            if ((s == null) || (s.Length == 0))
            {
                return string.Empty;
            }
            StringBuilder builder = new StringBuilder(s);
            builder.Replace("&", "&amp;");
            builder.Replace("<", "&lt;");
            builder.Replace(">", "&gt;");
            builder.Replace("\"", "&quot;");
            builder.Replace("'", "&#39;");
            return ShitEncode(builder.ToString());
        }

        public static string GetBadWords(string s)
        {
            string[] _badwords = ConfigInfo.BadWords.Split('|');
            if (_badwords != null)
            {
                for (int i = 0; i < _badwords.Length; i++)
                {
                    if (s.IndexOf(_badwords[i].ToString(), 0) != -1)
                    {
                        return _badwords[i].ToString();
                    }
                }
            }
            return string.Empty;
        }

        public static string FormatFileSize(long l)
        {
            if (l < 0)
            {
                return "0 B";
            }
            else if (l >= (1024 * 1024 * 1024))
            {
                return string.Format("{0:###0.00} GB", ((Double)l) / (1024 * 1024 * 1024));
            }
            else if (l >= (1024 * 1024))
            {
                return string.Format("{0:##0.00} MB", ((Double)l) / (1024 * 1024));
            }
            else if (l >= 1024)
            {
                return string.Format("{0:#0.00} KB", ((Double)l) / 1024);
            }
            else
            {
                return string.Format("{0} B", l);
            }
        }

        public static double DateDiff(DateTime dt1, DateTime dt2, string type)
        {
            double datediff = 0;
            TimeSpan ts = new TimeSpan(dt2.Ticks - dt1.Ticks);
            switch (type.ToLower())
            {
                case "year":
                    {
                        datediff = Convert.ToDouble(ts.TotalDays / 365);
                        break;
                    }
                case "month":
                    {
                        datediff = Convert.ToDouble((ts.TotalDays / 365) * 12);
                        break;
                    }
                case "day":
                    {
                        datediff = Convert.ToDouble(ts.TotalDays);
                        break;
                    }
                case "hour":
                    {
                        datediff = Convert.ToDouble(ts.TotalHours);
                        break;
                    }
                case "minute":
                    {
                        datediff = Convert.ToDouble(ts.TotalMinutes);
                        break;
                    }
                case "second":
                    {
                        datediff = Convert.ToDouble(ts.TotalSeconds);
                        break;
                    }
            }
            return datediff;
        }

        public static string LargerValue(string s)
        {
            int Step = 1;
            int Step_Entries = 1;
            StringBuilder sb = new StringBuilder(s);
            for (int i = 1; i < sb.Length; i++)
            {
                Step = Step * 10;
            }
            switch (sb.Length)
            {
                case 1:
                case 2:
                case 3:
                    {
                        Step = Step * Convert.ToInt32(s.Substring(0, 1)) + Step;
                        break;
                    }
                default:
                    {
                        for (int j = 1; j < sb.Length - 1; j++)
                        {
                            Step_Entries = Step_Entries * 10;
                        }
                        Step = Step * Convert.ToInt32(s.Substring(0, 1)) + Step_Entries * Convert.ToInt32(s.Substring(1, 1)) + Step_Entries;
                        break;
                    }
            }
            return Step.ToString();
        }

        public static string GetDateTime(string type)
        {
            string datetime = (((DateTime.Now.ToString().Replace("/", "")).Replace("-", "")).Replace(":", "")).Replace(" ", "");
            switch (type.ToLower())
            {
                case "short":
                    {
                        return datetime;
                    }
                case "long":
                    {
                        return (datetime + DateTime.Now.Millisecond.ToString());
                    }
                default:
                    {
                        return string.Empty;
                    }
            }
        }

        public static string RandomNumber(int length)
        {
            Random random = new Random(unchecked((int)DateTime.Now.Ticks));
            StringBuilder sb = new StringBuilder(length);
            for (int i = 0; i < length; i++)
            {
                sb.Append(random.Next(0, 9));
            }
            return sb.ToString();
        }
    }

    public class Caching
    {
        // Methods
        public static object Get(string name)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Cache.Get(name);
            }
            return HttpRuntime.Cache.Get(name);
        }

        public static void Remove(string name)
        {
            if (HttpContext.Current.Cache[name] != null)
            {
                HttpContext.Current.Cache.Remove(name);
            }
        }

        public static void Set(string name, object value, CacheDependency cacheDependency)
        {
            Set(name, value, cacheDependency, DateTime.Now.AddSeconds(20.0), TimeSpan.Zero);
        }

        public static void Set(string name, object value, CacheDependency cacheDependency, DateTime dt)
        {
            Set(name, value, cacheDependency, dt, TimeSpan.Zero);
        }

        public static void Set(string name, object value, CacheDependency cacheDependency, TimeSpan ts)
        {
            Set(name, value, cacheDependency, Cache.NoAbsoluteExpiration, ts);
        }

        public static void Set(string name, object value, CacheDependency cacheDependency, DateTime dt, TimeSpan ts)
        {
            HttpRuntime.Cache.Insert(name, value, cacheDependency, dt, ts);
        }
    }

    public class Cookie
    {
        // Methods
        public static HttpCookie Get(string name)
        {
            return HttpContext.Current.Request.Cookies[name];
        }

        public static void Remove(string name)
        {
            Remove(Get(name));
        }

        public static void Remove(HttpCookie cookie)
        {
            if (cookie != null)
            {
                cookie.Expires = new DateTime(0x7bf, 5, 0x15);
                Save(cookie);
            }
        }

        public static void Save(HttpCookie cookie)
        {
            string str = HttpContext.Current.Request.Url.Host.ToLower();
            if (Fetch.ServerDomain != str)
            {
                cookie.Domain = Fetch.ServerDomain;
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public static HttpCookie Set(string name)
        {
            return new HttpCookie(name);
        }
    }

    public class SessionState
    {
        // Methods
        public static object Get(string name)
        {
            return HttpContext.Current.Session[name];
        }

        public static string GetString(string name)
        {
            return Convert.ToString(HttpContext.Current.Session[name]);
        }

        public static void Remove(string name)
        {
            if (HttpContext.Current.Session[name] != null)
            {
                HttpContext.Current.Session.Remove(name);
            }
        }

        public static void RemoveAll()
        {
            HttpContext.Current.Session.RemoveAll();
        }

        public static void Set(string name, object value)
        {
            HttpContext.Current.Session.Add(name, value);
        }
    }

    public class Pager
    {
        // Fields
        public int _pagesize = 10;
        public int _currentPage = 1;
        public int _maxpage = 1;
        public int _total = 0;
        public int _style = 1;
        public string _pagestr;
        public string _url;
        public string _target = "_self";
        public NameValueCollection _itemColl;
        public bool isShowCounts = true;

        // Methods
        public void Calculate()
        {
            this.Calculate(0);
        }

        public void Calculate(int cp)
        {
            if (cp == 0)
            {
                string s = Fetch.Get("page");
                this._currentPage = RegExp.IsNumeric(s) ? int.Parse(s) : 1;
            }
            else
            {
                this._currentPage = cp;
            }
            this._maxpage = this._total / this._pagesize;
            if ((this._total % this._pagesize) != 0)
            {
                this._maxpage++;
            }
            this._maxpage = Math.Max(this._maxpage, 1);
            this._currentPage = Math.Max(Math.Min(this._currentPage, this._maxpage), 1);
            this.SetItem("total", this._total);
        }

        public void Calculate(int cp, int per)
        {
            if (cp == 0)
            {
                string s = Fetch.Get("page");
                this._currentPage = RegExp.IsNumeric(s) ? int.Parse(s) : 1;
            }
            else
            {
                this._currentPage = cp;
            }
            this._maxpage = this._total / per;
            if ((this._total % per) != 0)
            {
                this._maxpage++;
            }
            this._maxpage = Math.Max(this._maxpage, 1);
            this._currentPage = Math.Max(Math.Min(this._currentPage, this._maxpage), 1);
            this.SetItem("total", this._total);
        }

        public void InitPager()
        {
            string PagerString = null;
            if (this._url == null)
            {
                this._url = HttpContext.Current.Request.RawUrl + this.QueryString + "page={p}";
            }
            else
            {
                string[] strArray = this._url.Split(new char[] { '?' });
                if (strArray.Length >= 2)
                {
                    this._url = strArray[0] + "?" + strArray[strArray.Length - 1];
                }
            }
            if (this._style == 0)
            {
                int j = (this._currentPage - 3 < 1) ? 1 : this._currentPage - 3;
                int k = (this._currentPage + 3 > this._maxpage) ? this._maxpage : this._currentPage + 3;
                if (j > 1)
                {
                    PagerString += "\r\n\t<a href=\"" + this.SetPage(this._url, 1) + "\" target=\"" + this._target + "\" class=\"page\">1</a>\r\n\t<span class=\"page\">...</span>\r\n\t";
                }
                for (int i = j; i <= k; i++)
                {
                    if (this._currentPage == i)
                    {
                        PagerString += string.Concat("<span class=\"page\" id=\"currentpage\"><b>", i.ToString(), "</b></span>");
                        continue;
                    }
                    PagerString += string.Concat("<a href=\"", this.SetPage(this._url, i), "\" target=\"" + this._target + "\" class=\"page\"", ">", i.ToString(), "</a>");
                }
                if (this._maxpage > k)
                {
                    PagerString += "\r\n\t<span class=\"page\">...</span>\r\n\t<a href=\"" + this.SetPage(this._url, this._maxpage) + "\" target=\"" + this._target + "\" class=\"page\">" + this._maxpage.ToString() + "</a>";
                }
                PagerString += "\r\n\t<span class=\"page\"><input type=\"text\" id=\"iPage\" title=\"输入数字回车\" size=\"2\" value=\"" + this._currentPage.ToString() + "\" style=\"border:0px;\" onkeydown=\"GotoPage();\"></span>";
                if (this.isShowCounts)
                {
                    PagerString += "\r\n\t<span class=\"page\"><font title=\"总记录数\">" + this._total.ToString() + "</font> | <font title=\"每页显示\">" + this._pagesize.ToString() + "</font></span>";
                }
                PagerString += "\r\n\t<span class=\"page\">" + this._currentPage.ToString() + "/" + this._maxpage.ToString() + " 页</span>\r\n\t";
            }
            else
            {
                if (this._currentPage == 1)
                {
                    PagerString += "<span class=\"page\">首页</span><span class=\"page\">上一页</span>";
                }
                else
                {
                    PagerString += "\r\n\t\t<a href=\"" + this.SetPage(this._url, 1) + "\" target=\"" + this._target + "\" class=\"page\">首页</a> <a href=\"" + this.SetPage(this._url, (this._currentPage - 1)) + "\" target=\"" + this._target + "\" class=\"page\">上一页</a>\r\n\t\t";
                }
                int j = (this._currentPage - 5 < 1) ? 1 : this._currentPage - 5;
                int k = (this._currentPage + 5 > this._maxpage) ? this._maxpage : this._currentPage + 5;
                if (j > 1)
                {
                    PagerString += "<a href=\"" + this.SetPage(this._url, 1) + "\" target=\"" + this._target + "\" class=\"page\">1</a>... \r\n\t\t";
                }
                for (int i = j; i <= k; i++)
                {
                    if (this._currentPage == i)
                    {
                        PagerString += string.Concat(" <span class=\"page\">", i.ToString(), "</span> ");
                        continue;
                    }
                    PagerString += string.Concat(" <a href=\"", this.SetPage(this._url, i), "\" target=\"" + this._target + "\"", " class=\"page\">", i.ToString(), "</a> ");
                }
                if (this._maxpage > k)
                {
                    PagerString += "\r\n\t\t... <a href=\"" + this.SetPage(this._url, this._maxpage) + "\" target=\"" + this._target + "\" class=\"page\">" + this._maxpage.ToString() + "</a>\r\n\t\t";
                }
                if (this._currentPage == this._maxpage)
                {
                    PagerString += "<span class=\"page\">下一页</span><span class=\"page\">尾页</span>";
                }
                else
                {
                    PagerString += "<a href=\"" + this.SetPage(this._url, this._currentPage + 1) + "\" target=\"" + this._target + "\" class=\"page\">下一页</a> <a href=\"" + this.SetPage(this._url, this._maxpage) + "\" target=\"" + this._target + "\" class=\"page\">尾页</a>";
                }
                PagerString += "\r\n\t\t <span class=\"page\"><input type=\"text\" id=\"iPage\" value=\"" + this._currentPage.ToString() + "\" size=\"3\" style=\"border:0px;\" onkeydown=\"GotoPage(\'" + this._target + "\');\" /></span>\r\n\t\t<input type=\"button\" value=\"Go\" onclick=\"OnGoto(\'" + this._target + "\')\" name=\"go\" class=\"page\" />";
                PagerString += "\r\n\t\t <span class=\"page\">总记录:" + this._total.ToString() + "</span> <span class=\"page\">每页:" + this._pagesize.ToString() + "</span><span class=\"page\">总页数:" + this._maxpage.ToString() + "</span>\r\n\t";
            }
            PagerString += "<input type=\"hidden\" id=\"sUrl\" name=\"sUrl\" value=\"" + this._url + "\">\r\n\t<script type=\"text/javascript\" language=\"javascript\">sUrl=\'" + this._url + "\';</script" + ">\r\n\t";
            this._pagestr = PagerString;
        }

        public void InitAjaxPager()
        {
            string PagerString = null;
            if (this._url == null)
            {
                this._url = HttpContext.Current.Request.RawUrl + this.QueryString + "page={p}";
            }
            else
            {
                string[] strArray = this._url.Split(new char[] { '?' });
                if (strArray.Length >= 2)
                {
                    this._url = strArray[0] + "?" + strArray[strArray.Length - 1];
                }
            }
            if (this._style == 0)
            {
                int j = (this._currentPage - 3 < 1) ? 1 : this._currentPage - 3;
                int k = (this._currentPage + 3 > this._maxpage) ? this._maxpage : this._currentPage + 3;
                if (j > 1)
                {
                    PagerString += "\r\n\t<a href=\"" + this.SetPage(this._url, 1) + "\" target=\"" + this._target + "\" onclick=\"AjaxPage(this, '" + Items.Get("divid") + "');return false;\" class=\"page\">1</a>\r\n\t<span class=\"page\">...</span>\r\n\t";
                }
                for (int i = j; i <= k; i++)
                {
                    if (this._currentPage == i)
                    {
                        PagerString += string.Concat("<span class=\"page\" id=\"currentpage\"><b>", i.ToString(), "</b></span>");
                        continue;
                    }
                    PagerString += string.Concat("<a href=\"", this.SetPage(this._url, i), "\" target=\"" + this._target + "\" onclick=\"AjaxPage(this, '" + Items.Get("divid") + "');return false;\" class=\"page\"", ">", i.ToString(), "</a>");
                }
                if (this._maxpage > k)
                {
                    PagerString += "\r\n\t<span class=\"page\">...</span>\r\n\t<a href=\"" + this.SetPage(this._url, this._maxpage) + "\" target=\"" + this._target + "\" onclick=\"AjaxPage(this, '" + Items.Get("divid") + "');return false;\" class=\"page\">" + this._maxpage.ToString() + "</a>";
                }
                if (this.isShowCounts)
                {
                    PagerString += "\r\n\t<span class=\"page\"><font title=\"总记录数\">" + this._total.ToString() + "</font> | <font title=\"每页显示\">" + this._pagesize.ToString() + "</font></span>";
                }
                PagerString += "\r\n\t<span class=\"page\">" + this._currentPage.ToString() + "/" + this._maxpage.ToString() + " 页</span>\r\n\t";
            }
            else
            {
                if (this._currentPage == 1)
                {
                    PagerString += "<span class=\"page\">首页</span><span class=\"page\">上一页</span>";
                }
                else
                {
                    PagerString += "\r\n\t\t<a href=\"" + this.SetPage(this._url, 1) + "\" onclick=\"AjaxPage(this, '" + Items.Get("divid") + "');return false;\" target=\"" + this._target + "\" class=\"page\">首页</a> <a href=\"" + this.SetPage(this._url, (this._currentPage - 1)) + "\" onclick=\"AjaxPage(this, '" + Items.Get("divid") + "');return false;\" target=\"" + this._target + "\" class=\"page\">上一页</a>\r\n\t\t";
                }
                int j = (this._currentPage - 5 < 1) ? 1 : this._currentPage - 5;
                int k = (this._currentPage + 5 > this._maxpage) ? this._maxpage : this._currentPage + 5;
                if (j > 1)
                {
                    PagerString += "<a href=\"" + this.SetPage(this._url, 1) + "\" onclick=\"AjaxPage(this, '" + Items.Get("divid") + "');return false;\" target=\"" + this._target + "\" class=\"page\">1</a>... \r\n\t\t";
                }
                for (int i = j; i <= k; i++)
                {
                    if (this._currentPage == i)
                    {
                        PagerString += string.Concat(" <span class=\"page\">", i.ToString(), "</span> ");
                        continue;
                    }
                    PagerString += string.Concat(" <a href=\"", this.SetPage(this._url, i), "\" onclick=\"AjaxPage(this, '" + Items.Get("divid") + "');return false;\" target=\"" + this._target + "\"", " class=\"page\">", i.ToString(), "</a> ");
                }
                if (this._maxpage > k)
                {
                    PagerString += "\r\n\t\t... <a href=\"" + this.SetPage(this._url, this._maxpage) + "\" onclick=\"AjaxPage(this, '" + Items.Get("divid") + "');return false;\" target=\"" + this._target + "\" class=\"page\">" + this._maxpage.ToString() + "</a>\r\n\t\t";
                }
                if (this._currentPage == this._maxpage)
                {
                    PagerString += "<span class=\"page\">下一页</span><span class=\"page\">尾页</span>";
                }
                else
                {
                    PagerString += "<a href=\"" + this.SetPage(this._url, this._currentPage + 1) + "\" onclick=\"AjaxPage(this, '" + Items.Get("divid") + "');return false;\" target=\"" + this._target + "\" class=\"page\">下一页</a> <a href=\"" + this.SetPage(this._url, this._maxpage) + "\" onclick=\"AjaxPage(this, '" + Items.Get("divid") + "');return false;\" target=\"" + this._target + "\" class=\"page\">尾页</a>";
                }
                PagerString += "\r\n\t\t <span class=\"page\">总记录:" + this._total.ToString() + "</span> <span class=\"page\">每页:" + this._pagesize.ToString() + "</span><span class=\"page\">总页数:" + this._maxpage.ToString() + "</span>\r\n\t";
            }
            PagerString += "<input type=\"hidden\" id=\"sUrl\" name=\"sUrl\" value=\"" + this._url + "\">\r\n\t<script type=\"text/javascript\" language=\"javascript\">sUrl=\'" + this._url + "\';</script" + ">\r\n\t";
            this._pagestr = PagerString;
        }

        public void SetItem(string name, object value)
        {
            this.Items.Add(name, HttpContext.Current.Server.UrlEncode(value.ToString()));
        }

        public void SetItem(string name, string value)
        {
            this.Items.Add(name, HttpContext.Current.Server.UrlEncode(value));
        }

        public string SetPage(string s, int i)
        {
            if (s != null)
            {
                return s.Replace("{p}", i.ToString());
            }
            return null;
        }

        // Properties
        public int PageSize
        {
            get
            {
                return this._pagesize;
            }
            set
            {
                this._pagesize = value;
            }
        }

        public int CurrentPage
        {
            get
            {
                return this._currentPage;
            }
            set
            {
                this._currentPage = value;
            }
        }

        public int MaxPage
        {
            get
            {
                return this._maxpage;
            }
            set
            {
                this._maxpage = value;
            }
        }

        public int Total
        {
            get
            {
                return this._total;
            }
            set
            {
                this._total = value;
            }
        }

        public int Style
        {
            get
            {
                return this._style;
            }
            set
            {
                this._style = value;
            }
        }

        public string PageStr
        {
            get
            {
                return this._pagestr;
            }
        }

        public string Url
        {
            get
            {
                return this._url;
            }
            set
            {
                this._url = value;
            }
        }

        public bool ShowCounts
        {
            get
            {
                return this.isShowCounts;
            }
            set
            {
                this.isShowCounts = value;
            }
        }

        public int PreviousRecords
        {
            get
            {
                return (this._pagesize * (this._currentPage - 1));
            }
        }

        public string QueryString
        {
            get
            {
                string str = "?";
                if (this._itemColl != null)
                {
                    foreach (string str2 in this.Items.AllKeys)
                    {
                        string str3 = str;
                        str = str3 + str2 + "=" + this.Items[str2] + "&";
                    }
                }
                return str;
            }
        }

        private NameValueCollection Items
        {
            get
            {
                if (this._itemColl == null)
                {
                    this._itemColl = new NameValueCollection();
                }
                return this._itemColl;
            }
        }
    }

    public class Terminator
    {
        // Methods
        public virtual void Alert(string s)
        {
            this.Trace("<script type='text/javascript'>");
            this.Trace("alert('" + s.Replace("'", @"\'") + "');");
            this.Trace("history.back();");
            this.Trace("</script>");
            this.End();
        }

        public virtual void Alert(string s, string backurl)
        {
            this.Trace("<script type='text/javascript'>");
            this.Trace("alert('" + s.Replace("'", @"\'") + "');");
            this.Trace("location.href='" + backurl + "';");
            this.Trace("</script>");
            this.End();
        }

        public virtual void Throw(string message)
        {
            HttpContext.Current.Response.ContentType = "text/html";
            HttpContext.Current.Response.AddHeader("Content-Type", "text/html");
            this.Throw(message, null, null, null, true);
        }

        public virtual void Throw(string message, string title, string links, string autojump, bool showback)
        {
            HttpContext.Current.Response.ContentType = "text/html";
            HttpContext.Current.Response.AddHeader("Content-Type", "text/html");
            StringBuilder builder = new StringBuilder(this.template);
            builder.Replace("{$Message}", message);
            builder.Replace("{$Title}", ((title == null) || (title == "")) ? "系统提示" : title);
            if ((links != null) && (links != ""))
            {
                string[] strArray = links.Split(new char[] { '|' });
                for (int i = 0; i < strArray.Length; i++)
                {
                    string[] strArray2 = strArray[i].Split(new char[] { ',' });
                    if (strArray2.Length > 1)
                    {
                        if (strArray2[1].Trim() == "RefHref")
                        {
                            strArray2[1] = Fetch.UrlReferrer;
                        }
                        if ((strArray2[1] != string.Empty) && (strArray2[1] != null))
                        {
                            string str = "\r\n<li><a href='" + strArray2[1] + "'";
                            if (strArray2.Length == 3)
                            {
                                str = str + " target='" + strArray2[2].Trim() + "'";
                            }
                            if (strArray2[0].Trim() == "RefText")
                            {
                                strArray2[0] = Text.TextEncode(Fetch.UrlReferrer);
                            }
                            builder.Replace("{$Links}", (str + ">" + strArray2[0].Trim() + "</a></li>\r\n\t\t\t\t") + "{$Links}");
                        }
                    }
                }
            }
            if ((autojump != null) && (autojump != string.Empty))
            {
                builder.Replace("{$AutoJump}", "\r\n<meta http-equiv='refresh' content='3; url=" + ((autojump == "back") ? "javascript:history.back()" : autojump) + "' />");
            }
            else
            {
                builder.Replace("{$AutoJump}", "\r\n<!-- No Jump -->");
            }
            if (showback)
            {
                builder.Replace("{$Links}", "\r\n<li><a href='javascript:history.back()'>返回上一页</a></li>");
            }
            else
            {
                builder.Replace("{$Links}", "\r\n<!-- No Back -->");
            }
            this.Trace(builder.ToString());
            this.End();
        }

        private void Trace(string s)
        {
            HttpContext.Current.Response.Write(s);
        }

        private void End()
        {
            HttpContext.Current.Response.End();
        }

        // Properties
        private string template
        {
            get
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("<html xmlns:v>");
                builder.Append("\r\n<head>");
                builder.Append("\r\n<title>{$Title}</title>");
                builder.Append("\r\n<meta http-equiv='Content-Type' content='text/html; charset=" + Encoding.Default.BodyName + "' />");
                builder.Append("{$AutoJump}");
                builder.Append("\r\n<style rel='stylesheet'>");
                builder.Append("\r\nv\\:* {behavior:url(#default#vml);}");
                builder.Append("\r\nbody, div, span, li, td, a {color: #222222;font-size: 12px !important;font-size: 11px;font-family: tahoma, arial, 'courier new', verdana, sans-serif;line-height: 19px;}");
                builder.Append("\r\na {color: #2c78c5;text-decoration: none;}");
                builder.Append("\r\na:hover {color: red;text-decoration: none;}");
                builder.Append("\r\n</style>");
                builder.Append("\r\n</head>");
                builder.Append("\r\n<body style='text-align:center;margin:90px 20px 50px 20px'>");
                builder.Append("\r\n<?xml:namespace prefix='v' />");
                builder.Append("\r\n<div style='margin:auto; width:450px; text-align:center'>");
                builder.Append("\r\n\t<v:roundrect style='text-align:left; display:table; margin:auto; padding:15px; width:450px; height:210px; overflow:hidden; position:relative;' arcsize='3200f' coordsize='21600,21600' fillcolor='#fdfdfd' strokecolor='#e6e6e6' strokeweight='1px'>");
                builder.Append("\r\n\t<table width='100%' cellpadding='0' cellspacing='0' border='0' style='padding-bottom:6px; border-bottom:1px #cccccc solid'>");
                builder.Append("\r\n\t<tr><td><b>{$Title}</b></td></tr>");
                builder.Append("\r\n\t</table>");
                builder.Append("\r\n\t<table width='100%' cellpadding='0' cellspacing='0' border='0' style='word-break:break-all; overflow:hidden'>");
                builder.Append("\r\n\t<tr>");
                builder.Append("\r\n\t<td width='80' valign='top' style='padding-top:13px'><span style='font-size:16px; zoom:4; color:#aaaaaa'><font face='webdings'>i</font></span></td>");
                builder.Append("\r\n\t<td valign='top' style='padding-top:17px'>");
                builder.Append("\r\n\t<p style='margin-bottom:22px'>{$Message}</p>");
                builder.Append("{$Links}");
                builder.Append("\r\n\t</td>");
                builder.Append("\r\n\t</tr>");
                builder.Append("\r\n\t</table>");
                builder.Append("\r\n\t</v:roundrect>");
                builder.Append("\r\n</div>");
                builder.Append("\r\n</body>");
                builder.Append("\r\n</html>");
                return builder.ToString();
            }
        }
    }

    public class UploadImage
    {
        // Fields
        public int add;
        public string colorstring;
        public HttpPostedFile file;
        public string font;
        public int mod;
        public string modpics;
        public int padding;
        public string path;
        public float size;
        public string text;
        public string textwh;
        public bool view;
        public string viewpics;
        public bool zoom;
        public string zoompics;

        // Methods
        public string[] Strarray(string str)
        {
            return str.Split(new char[] { ',' });
        }

        public static Color GenerateColor(string colorstring)
        {
            if (colorstring.StartsWith("#"))
            {
                colorstring = colorstring.TrimStart(new char[] { '#' });
            }
            if (colorstring.Length != 6)
            {
                UtilityHandler.Prompt("非法的颜色代码");
            }
            int num = 0;
            try
            {
                num = Convert.ToInt32(colorstring, 0x10);
            }
            catch (OverflowException exception)
            {
                UtilityHandler.Prompt("非法的颜色代码 - " + exception.Message);
            }
            return Color.FromArgb((num & 0xff0000) >> 0x10, (num & 0xff00) >> 8, num & 0xff);
        }

        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(originalImagePath);
            int num = width;
            int num2 = height;
            int num3 = image.Width;
            int num4 = image.Height;
            int x = 0;
            int y = 0;
            int num7 = image.Width;
            int num8 = image.Height;
            string str = mode;
            if (str != null)
            {
                str = string.IsInterned(str);
                if (str != "HW")
                {
                    if (str == "W")
                    {
                        num2 = (image.Height * width) / image.Width;
                    }
                    else if (str == "H")
                    {
                        num = (image.Width * height) / image.Height;
                    }
                    else if (str == "CUT")
                    {
                        if ((num3 > width) && (num4 > height))
                        {
                            double num9 = ((double)Math.Min(num3, num4)) / ((double)Math.Max(num3, num4));
                            if (num3 < num4)
                            {
                                num2 = height;
                                num = (int)(num2 * num9);
                            }
                            else if (num3 > num4)
                            {
                                num = width;
                                num2 = (int)(num * num9);
                            }
                            else
                            {
                                num = width;
                                num2 = height;
                            }
                        }
                        else
                        {
                            if (image.Width < num)
                            {
                                num = image.Width;
                            }
                            else
                            {
                                num = width;
                            }
                            if (image.Height < num2)
                            {
                                num2 = image.Height;
                            }
                            else
                            {
                                num2 = height;
                            }
                        }
                        x = 0;
                        y = 0;
                        num7 = image.Width;
                        num8 = image.Height;
                    }
                }
            }
            System.Drawing.Image image2 = new Bitmap(num, num2);
            Graphics graphics = Graphics.FromImage(image2);
            graphics.InterpolationMode = InterpolationMode.High;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.Clear(Color.Transparent);
            graphics.DrawImage(image, new Rectangle(0, 0, num, num2), new Rectangle(x, y, num7, num8), GraphicsUnit.Pixel);
            try
            {
                image2.Save(thumbnailPath, ImageFormat.Jpeg);
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                image.Dispose();
                image2.Dispose();
                graphics.Dispose();
            }
        }

        public string Mappath(string mpath)
        {
            return HttpContext.Current.Server.MapPath(mpath);
        }

        public string[] Modarray(int ymod, int width, int height, string str, int pwidth, int pheight, int padd)
        {
            switch (ymod)
            {
                case 1:
                    return (Convert.ToString(padd) + "," + Convert.ToString(padd)).Split(new char[] { ',' });
                case 2:
                    return (Convert.ToString((int)((width - pwidth) / 2)) + "," + Convert.ToString(padd)).Split(new char[] { ',' });
                case 3:
                    return (Convert.ToString((int)((width - pwidth) - padd)) + "," + Convert.ToString(padd)).Split(new char[] { ',' });
                case 4:
                    return (Convert.ToString(padd) + "," + Convert.ToString((int)((height - pheight) / 2))).Split(new char[] { ',' });
                case 5:
                    return (Convert.ToString((int)((width - pwidth) / 2)) + "," + Convert.ToString((int)((height - pheight) / 2))).Split(new char[] { ',' });
                case 6:
                    return (Convert.ToString((int)((width - pwidth) - padd)) + "," + Convert.ToString((int)((height - pheight) / 2))).Split(new char[] { ',' });
                case 7:
                    return (Convert.ToString(padd) + "," + Convert.ToString((int)((height - pheight) + padd))).Split(new char[] { ',' });
                case 8:
                    return (Convert.ToString((int)((width - pwidth) / 2)) + "," + Convert.ToString((int)((height - pheight) + padd))).Split(new char[] { ',' });
                case 9:
                    return (Convert.ToString((int)((width - pwidth) - padd)) + "," + Convert.ToString((int)((height - pheight) + padd))).Split(new char[] { ',' });
            }
            return str.Split(new char[] { ',' });
        }

        public string Save()
        {
            System.Drawing.Image image = System.Drawing.Image.FromStream(this.file.InputStream);
            string str = Config.Settings["LogoPathW"];
            string text1 = Config.Settings["LogoPathH"];
            int width = image.Width;
            int height = image.Height;
            if ((this.view && (this.viewpics != null)) && (this.viewpics != ""))
            {
                string[] strArray = this.viewpics.Split(new char[] { '|' });
                int num = 0;
                for (int i = 0; i < strArray.Length; i++)
                {
                    if ((strArray[i] != null) && (strArray[i] != ""))
                    {
                        string[] strArray2 = strArray[i].Split(new char[] { ',' });
                        if (strArray2.Length == 2)
                        {
                            float num5 = Convert.ToSingle(strArray2[0]);
                            float num6 = Convert.ToSingle(strArray2[1]);
                            if (((width - num5) > 0f) || ((height - num6) > 0f))
                            {
                                float num7 = ((float)width) / num5;
                                float num8 = ((float)height) / num6;
                                if ((num8 - num7) > 0f)
                                {
                                    num7 = num8;
                                }
                                num5 = ((float)width) / num7;
                                num6 = ((float)height) / num7;
                            }
                            else
                            {
                                num5 = width;
                                num6 = height;
                            }
                            Bitmap bitmap = new Bitmap(Convert.ToInt32(num5), Convert.ToInt32(num6));
                            Graphics graphics = Graphics.FromImage(bitmap);
                            graphics.InterpolationMode = InterpolationMode.High;
                            graphics.SmoothingMode = SmoothingMode.HighQuality;
                            graphics.DrawImage(image, 0, 0, Convert.ToInt32(num5), Convert.ToInt32(num6));
                            bitmap.Save(this.Mappath(this.Viewpath(this.path, num)), ImageFormat.Jpeg);
                            graphics.Dispose();
                            bitmap.Dispose();
                            num++;
                        }
                    }
                }
            }
            float num9 = 0f;
            float num10 = 0f;
            if (!this.zoom && (this.add == 0))
            {
                this.file.SaveAs(this.Mappath(this.path));
                image.Dispose();
                return (width.ToString() + "," + height.ToString());
            }
            if (this.zoom)
            {
                if ((this.zoompics == null) || (this.zoompics == ""))
                {
                    image.Dispose();
                    return "-3";
                }
                string[] strArray3 = this.Strarray(this.zoompics);
                if (strArray3.Length != 2)
                {
                    image.Dispose();
                    return "-3";
                }
                num9 = Convert.ToSingle(strArray3[0]);
                num10 = Convert.ToSingle(strArray3[1]);
                if (((width - num9) > 0f) || ((height - num10) > 0f))
                {
                    float num11 = ((float)width) / num9;
                    float num12 = ((float)height) / num10;
                    if ((num12 - num11) > 0f)
                    {
                        num11 = num12;
                    }
                    num9 = ((float)width) / num11;
                    num10 = ((float)height) / num11;
                }
                else
                {
                    num9 = width;
                    num10 = height;
                }
            }
            else
            {
                num9 = width;
                num10 = height;
            }
            string str2 = str;
            str2 = Config.Settings["LogoPath"];
            Bitmap bitmap2 = new Bitmap(Convert.ToInt32(num9), Convert.ToInt32(num10));
            Graphics graphics2 = Graphics.FromImage(bitmap2);
            graphics2.InterpolationMode = InterpolationMode.High;
            graphics2.SmoothingMode = SmoothingMode.HighQuality;
            graphics2.DrawImage(image, 0, 0, Convert.ToInt32(num9), Convert.ToInt32(num10));
            if (this.add == 1)
            {
                System.Drawing.Image image2 = System.Drawing.Image.FromFile(Fetch.MapPath(str2));
                int pwidth = image2.Width;
                int pheight = image2.Height;
                if ((((pwidth - num9) + this.padding) > 0f) || (((pheight - num10) + this.padding) > 0f))
                {
                    image2.Dispose();
                    bitmap2.Save(this.Mappath(this.path), ImageFormat.Jpeg);
                }
                else
                {
                    string[] strArray4 = this.Modarray(this.mod, Convert.ToInt32(num9), Convert.ToInt32(num10), this.modpics, pwidth, pheight, this.padding);
                    Rectangle destRect = new Rectangle(Convert.ToInt32(strArray4[0]), Convert.ToInt32(strArray4[1]), pwidth, pheight);
                    GraphicsUnit pixel = GraphicsUnit.Pixel;
                    graphics2.InterpolationMode = InterpolationMode.High;
                    graphics2.SmoothingMode = SmoothingMode.HighQuality;
                    graphics2.DrawImage(image2, destRect, 0, 0, pwidth, pheight, pixel);
                    image2.Dispose();
                    bitmap2.Save(this.Mappath(this.path), ImageFormat.Jpeg);
                }
            }
            else if (this.add == 2)
            {
                if ((this.textwh == null) || (this.textwh == ""))
                {
                    graphics2.Dispose();
                    bitmap2.Dispose();
                    image.Dispose();
                    return "-4";
                }
                string[] strArray5 = this.textwh.Split(new char[] { ',' });
                if (strArray5.Length != 2)
                {
                    graphics2.Dispose();
                    bitmap2.Dispose();
                    image.Dispose();
                    return "-4";
                }
                Color empty = Color.Empty;
                empty = GenerateColor(this.colorstring);
                int num15 = Convert.ToInt32(strArray5[0]);
                int num16 = Convert.ToInt32(strArray5[1]);
                string[] strArray6 = this.Modarray(this.mod, Convert.ToInt32(num9), Convert.ToInt32(num10), this.modpics, num15, num16, this.padding);
                graphics2.InterpolationMode = InterpolationMode.High;
                graphics2.SmoothingMode = SmoothingMode.HighQuality;
                graphics2.DrawString(this.text, new Font(this.font, this.size), new SolidBrush(empty), (float)Convert.ToInt32(strArray6[0]), (float)Convert.ToInt32(strArray6[1]));
                bitmap2.Save(this.Mappath(this.path), ImageFormat.Jpeg);
            }
            else
            {
                bitmap2.Save(this.Mappath(this.path), ImageFormat.Jpeg);
            }
            graphics2.Dispose();
            bitmap2.Dispose();
            image.Dispose();
            return (num9.ToString() + "," + num10.ToString());
        }

        public string Viewpath(string str, int num)
        {
            string str2 = "";
            for (int i = 0; i <= num; i++)
            {
                str2 = str2 + "_";
            }
            return str.Replace(".jpg", str2 + ".jpg");
        }
    }

    public class ImageCode : Page
    {
        // Fields
        private string _checktext;
        private Color _bgcolor = Color.White;
        private bool _bold = true;
        private Color _color = Color.Blue;
        private string _fontFamily = "Arial, Helvetica, Sans-serif";
        private int _fontSize = 22;
        private int _height = 65;
        private int _impurity = 2;
        private bool _italic = false;
        private int _width = 125;
        private int modetype;

        // Methods
        public ImageCode()
        {
            if (Config.Settings["CheckText"] != string.Empty)
            {
                this._checktext = Config.Settings["CheckText"];
            }
            else
            {
                this._checktext = "123456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
            }
        }

        private void FillImageProperties()
        {
            string s = string.Empty;
            s = Fetch.Get("width");
            if (RegExp.IsNumeric(s))
            {
                this._width = int.Parse(s);
            }
            if (this._width > 300)
            {
                this._width = 300;
            }
            s = Fetch.Get("height");
            if (RegExp.IsNumeric(s))
            {
                this._height = int.Parse(s);
            }
            if (this._height > 300)
            {
                this._height = 300;
            }
            s = Fetch.Get("fontsize");
            if (RegExp.IsNumeric(s))
            {
                this._fontSize = int.Parse(s);
            }
            s = Fetch.Get("fontfamily");
            if (s.Length > 0)
            {
                this._fontFamily = s;
            }
            s = Fetch.Get("bold").ToLower();
            if (s.Length > 0)
            {
                this._bold = s == "true";
            }
            s = Fetch.Get("italic").ToLower();
            if (s.Length > 0)
            {
                this._italic = s == "true";
            }
            s = Fetch.Get("impurity");
            if (RegExp.IsNumeric(s))
            {
                this._impurity = int.Parse(s);
            }
            if (this._impurity > 30)
            {
                this._impurity = 30;
            }
        }

        private FontStyle GetFontStyle()
        {
            if (this._bold && this._italic)
            {
                return (FontStyle.Italic | FontStyle.Bold);
            }
            if (this._bold)
            {
                return FontStyle.Bold;
            }
            if (this._italic)
            {
                return FontStyle.Italic;
            }
            return FontStyle.Regular;
        }

        private Bitmap GetneralCodeImage()
        {
            bool flag3;
            Random random = new Random();
            Bitmap image = new Bitmap(this._width, this._height);
            Graphics graphics = Graphics.FromImage(image);
            graphics.Clear(this._bgcolor);
            //Brush brush = new TextureBrush(new Bitmap(Fetch.MapPath(@"images\checkpic\" + random.Next(1, Directory.GetFiles(Fetch.MapPath(@"images\checkpic\"), "*.gif").Length) + ".gif")));
            //graphics.FillRectangle(brush, new Rectangle(0, 0, this._width, this._height));
            int num3 = 4;
            char[] chArray = _checktext.ToCharArray();
            string[] strArray = new string[] { 
            "#666666", "#003300", "#009900", "#330000", "#333300", "#336600", "#660000", "#663300", "#666600", "#FF99FF", "#FF33FF", "#CCCCFF", "#CC66FF", "#CC00FF", "#9999FF", "#9933FF", 
            "#9900FF", "#FF00FF", "#996633", "#CC3333", "#FF3333", "#6633FF", "#0033FF", "#336666", "#CC9900", "#6633CC", "#66FF66", "#009999", "#99CC00", "#615379", "#E6649E", "#B5B495", 
            "#73CEA7"
         };
            bool istop = random.Next(0, 2) == 0;
            Pen pen = new Pen(ColorTranslator.FromHtml(strArray[random.Next(0, strArray.Length)]), 2f);
            pen.DashStyle = DashStyle.DashDotDot;
            Point[] randomPointGroup = this.GetRandomPointGroup(istop);
            for (int i = 0; i < randomPointGroup.Length; i += 2)
            {
                graphics.DrawLine(pen, randomPointGroup[i], randomPointGroup[i + 1]);
            }
            string input = "";
            for (int j = 0; j < num3; j++)
            {
                input = input + chArray[random.Next(chArray.Length)].ToString();
            }
            string[] strArray2 = new string[num3 + 1];
            int index = 0;
        Label_0313:
            while (index != num3)
            {
                string str2 = strArray[random.Next(0, strArray.Length)];
                strArray2[index] = str2;
                index++;
                for (int n = 0; n < strArray2.Length; n++)
                {
                    if (strArray2[n] == str2)
                    {
                        goto Label_0313;
                    }
                    if (n == (strArray2.Length - 1))
                    {
                        strArray2[index] = str2;
                        index++;
                    }
                }
            }
            char[] chArray2 = input.ToCharArray();
            int num8 = random.Next(0, num3 - 1);
            string str3 = strArray2[num8];
            int num9 = random.Next(0, num3 - 2) + 1;
            num9 = (num9 == 1) ? 2 : num9;
            int[] numArray = new int[num9];
            numArray[0] = num8;
            for (int k = 1; k < num9; k++)
            {
                int num11 = random.Next(0, num3 - 1);
                bool flag2 = false;
                for (int num12 = 0; num12 < k; num12++)
                {
                    if (numArray[num12] == num11)
                    {
                        flag2 = true;
                        break;
                    }
                }
                if (!flag2)
                {
                    numArray[k] = num11;
                }
                else
                {
                    k--;
                }
            }
            do
            {
                string str4 = strArray[random.Next(0, strArray.Length)];
                flag3 = false;
                for (int num13 = 0; num13 < strArray2.Length; num13++)
                {
                    if (str4 == strArray2[num13])
                    {
                        flag3 = true;
                        break;
                    }
                }
            }
            while (flag3);
            string str5 = "";
            string s = "";
            int num14 = random.Next(0, 4);
            if (3 == this.ModeType)
            {
                for (int num15 = 0; num15 < num9; num15++)
                {
                    strArray2[numArray[num15]] = str3;
                }
                s = "请输入图中相同色的字符";
            }
            else if (2 == this.ModeType)
            {
                bool flag4 = false;
                while (!flag4)
                {
                    Match match;
                    Match match2;
                    Match match3;
                    switch (num14)
                    {
                        case 0:
                            if (!Regex.IsMatch(input, @"[\u4e00-\u9fa5]+"))
                            {
                                goto Label_0593;
                            }
                            flag4 = true;
                            s = "汉字";
                            match = Regex.Match(input, @"[\u4e00-\u9fa5]+", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                            goto Label_04B1;

                        case 1:
                            if (!Regex.IsMatch(input, "[a-zA-Z]+"))
                            {
                                goto Label_0593;
                            }
                            flag4 = true;
                            s = "字母";
                            match2 = Regex.Match(input, "[a-zA-Z]+", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                            goto Label_0504;

                        case 2:
                            if (!Regex.IsMatch(input, "[0-9]+"))
                            {
                                goto Label_0593;
                            }
                            flag4 = true;
                            s = "数字";
                            match3 = Regex.Match(input, "[0-9]+", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                            goto Label_0554;

                        case 3:
                            if (Regex.IsMatch(input, @"[^\u4e00-\u9fa5|a-zA-Z|0-9]"))
                            {
                                flag4 = true;
                                s = "特殊字符";
                                str5 = new Regex(@"[\u4e00-\u9fa5|a-zA-Z|0-9]+").Replace(input, "");
                            }
                            goto Label_0593;

                        default:
                            goto Label_0593;
                    }
                Label_0498:
                    str5 = str5 + match.Value;
                    match = match.NextMatch();
                Label_04B1:
                    if (match.Success)
                    {
                        goto Label_0498;
                    }
                    goto Label_0593;
                Label_04EB:
                    str5 = str5 + match2.Value;
                    match2 = match2.NextMatch();
                Label_0504:
                    if (match2.Success)
                    {
                        goto Label_04EB;
                    }
                    goto Label_0593;
                Label_053B:
                    str5 = str5 + match3.Value;
                    match3 = match3.NextMatch();
                Label_0554:
                    if (match3.Success)
                    {
                        goto Label_053B;
                    }
                Label_0593:
                    if (!flag4)
                    {
                        num14 = random.Next(0, 4);
                    }
                }
            }
            int num16 = 0;
            for (int m = 0; m < chArray2.Length; m++)
            {
                int num21;
                int num18 = this._fontSize;
                int num19 = (m == 0) ? 10 : 0x19;
                num16 += num19;
                int num20 = num16;
                if (istop)
                {
                    num21 = random.Next(15, this._height - 0x23);
                }
                else
                {
                    num21 = random.Next(0, this._height - 0x2d);
                }
                bool flag5 = false;
                if ((((('.' != chArray2[m]) && ('_' != chArray2[m])) && (('*' != chArray2[m]) && ('`' != chArray2[m]))) && ((('~' != chArray2[m]) && ('.' != chArray2[m])) && ((',' != chArray2[m]) && ('\'' != chArray2[m])))) && ((('-' != chArray2[m]) && ('|' != chArray2[m])) && ('\\' != chArray2[m])))
                {
                    char ch1 = chArray2[m];
                }
                graphics.DrawString(chArray2[m].ToString(), new Font(this._fontFamily, flag5 ? ((float)(num18 + 30)) : ((float)num18), flag5 ? FontStyle.Bold : this.GetFontStyle()), new SolidBrush(ColorTranslator.FromHtml(strArray2[m])), (float)num20, (float)num21);
            }
            if (this.ModeType == 2)
            {
                graphics.DrawString("输入图中出现的", new Font("宋体", 9f, FontStyle.Regular), new SolidBrush(ColorTranslator.FromHtml("#008000")), ((float)4), istop ? ((float)2) : ((float)(this._height - 0x10)));
                graphics.DrawString(s, new Font("宋体", 9f, FontStyle.Regular), new SolidBrush(ColorTranslator.FromHtml("#FF0000")), ((float)90), istop ? ((float)2) : ((float)(this._height - 0x10)));
            }
            else if (this.ModeType == 3)
            {
                graphics.DrawString(s, new Font("宋体", 9f, FontStyle.Regular), new SolidBrush(ColorTranslator.FromHtml("#FF0000")), 6f, istop ? ((float)2) : ((float)(this._height - 0x10)));
            }
            graphics.Dispose();
            SessionState.Set("verification", str5.ToLower());
            return image;
        }

        private Point[] GetRandomPointGroup(bool istop)
        {
            Point[] pointArray = new Point[this._impurity * 2];
            for (int i = 0; i < pointArray.Length; i++)
            {
                int num2 = new Random().Next(0x989680, 0x5f5e0ff);
                int x = new Random((num2 / (i + 2)) * (i + 1)).Next(0, this._width);
                int y = new Random((num2 / (x + 2)) * (x + 1)).Next(istop ? 0x10 : 0, istop ? this._height : (this._height - 0x10));
                pointArray[i] = new Point(x, y);
            }
            return pointArray;
        }

        private void InitializeComponent()
        {
            base.Load += new EventHandler(this.Page_Load);
        }

        protected override void OnInit(EventArgs e)
        {
            this.InitializeComponent();
            base.OnInit(e);
        }

        private void Page_Load(object sender, EventArgs e)
        {
            this.FillImageProperties();
            base.Response.ContentType = "image/Jpeg";
            this.GetneralCodeImage().Save(base.Response.OutputStream, ImageFormat.Jpeg);
        }

        // Properties
        public int ModeType
        {
            get
            {
                if (this.modetype == 0)
                {
                    this.modetype = (Fetch.Get("modetype").Length < 1) ? 2 : int.Parse(Fetch.Get("modetype"));
                }
                if (((this.modetype != 1) && (this.modetype != 2)) && (this.modetype != 3))
                {
                    HttpContext.Current.Response.End();
                }
                return this.modetype;
            }
        }
    }

    public class NumberCode : Page
    {
        // Fields
        private Color _bgcolor = Color.White;
        private bool _bold = true;
        private Color _color = Color.Blue;
        private string _fontFamily = "Verdana";
        private int _fontSize = 12;
        private int _height = 20;
        private int _impurity = 3;
        private bool _italic = true;
        private int _width = 60;

        // Methods
        private void FillImageProperties()
        {
            string s = string.Empty;
            s = Fetch.Get("width");
            if (RegExp.IsNumeric(s))
            {
                this._width = int.Parse(s);
            }
            if (this._width > 300)
            {
                this._width = 300;
            }
            s = Fetch.Get("height");
            if (RegExp.IsNumeric(s))
            {
                this._height = int.Parse(s);
            }
            if (this._height > 300)
            {
                this._height = 300;
            }
            s = Fetch.Get("fontsize");
            if (RegExp.IsNumeric(s))
            {
                this._fontSize = int.Parse(s);
            }
            s = Fetch.Get("fontfamily");
            if (s.Length > 0)
            {
                this._fontFamily = s;
            }
            s = Fetch.Get("bold").ToLower();
            if (s.Length > 0)
            {
                this._bold = s == "true";
            }
            s = Fetch.Get("italic").ToLower();
            if (s.Length > 0)
            {
                this._italic = s == "true";
            }
            s = Fetch.Get("impurity");
            if (RegExp.IsNumeric(s))
            {
                this._impurity = int.Parse(s);
            }
            if (this._impurity > 30)
            {
                this._impurity = 30;
            }
        }

        private FontStyle GetFontStyle()
        {
            if (this._bold && this._italic)
            {
                return (FontStyle.Italic | FontStyle.Bold);
            }
            if (this._bold)
            {
                return FontStyle.Bold;
            }
            if (this._italic)
            {
                return FontStyle.Italic;
            }
            return FontStyle.Regular;
        }

        private Bitmap GetneralCodeImage()
        {
            Bitmap image = new Bitmap(this._width, this._height);
            Graphics graphics = Graphics.FromImage(image);
            graphics.Clear(this._bgcolor);
            Pen pen = new Pen(Color.Blue, 1f);
            pen.DashStyle = DashStyle.DashDotDot;
            Point[] randomPointGroup = this.GetRandomPointGroup();
            for (int i = 0; i < randomPointGroup.Length; i += 2)
            {
                graphics.DrawLine(pen, randomPointGroup[i], randomPointGroup[i + 1]);
                graphics.DrawEllipse(pen, new Random().Next(5, 10), new Random().Next(5, 10), new Random().Next(5, 50), new Random().Next(5, 50));
            }
            string s = new Random().Next(0x3e8, 0x270f).ToString();
            SessionState.Set("verification", s.ToLower());
            graphics.DrawString(s, new Font(this._fontFamily, (float)this._fontSize, this.GetFontStyle()), new SolidBrush(this._color), (float)0f, (float)0f);
            graphics.Dispose();
            return image;
        }

        private Point[] GetRandomPointGroup()
        {
            Point[] pointArray = new Point[this._impurity * 2];
            for (int i = 0; i < pointArray.Length; i++)
            {
                int num2 = new Random().Next(0x989680, 0x5f5e0ff);
                int x = new Random((num2 / (i + 2)) * (i + 1)).Next(0, this._width);
                int y = new Random((num2 / (x + 2)) * (x + 1)).Next(0, this._height);
                pointArray[i] = new Point(x, y);
            }
            return pointArray;
        }

        private void InitializeComponent()
        {
            base.Load += new EventHandler(this.Page_Load);
        }

        protected override void OnInit(EventArgs e)
        {
            this.InitializeComponent();
            base.OnInit(e);
        }

        private void Page_Load(object sender, EventArgs e)
        {
            this.FillImageProperties();
            base.Response.ContentType = "image/Jpeg";
            this.GetneralCodeImage().Save(base.Response.OutputStream, ImageFormat.Jpeg);
        }

        public static byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
                provider.ImportParameters(RSAKeyInfo);
                return provider.Decrypt(DataToDecrypt, DoOAEPPadding);
            }
            catch (CryptographicException exception)
            {
                Console.WriteLine(exception.ToString());
                return null;
            }
        }

        public static byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
                RSAKeyInfo.Modulus = Encoding.ASCII.GetBytes("2841418339");
                RSAKeyInfo.Exponent = Encoding.ASCII.GetBytes("23909");
                provider.ImportParameters(RSAKeyInfo);
                provider.ToXmlString(false);
                return provider.Encrypt(DataToEncrypt, DoOAEPPadding);
            }
            catch
            {
                return null;
            }
        }

        public void StartDemo()
        {
            try
            {
                byte[] bytes = Encoding.ASCII.GetBytes("Ashh");
                RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
                provider.ToXmlString(false);
                provider.ToXmlString(true);
                byte[] inArray = RSAEncrypt(bytes, provider.ExportParameters(false), false);
                Convert.ToBase64String(inArray);
                byte[] buffer3 = RSADecrypt(inArray, provider.ExportParameters(true), false);
                Encoding.ASCII.GetString(buffer3);
            }
            catch (ArgumentNullException)
            {

            }
        }
    }
}

namespace xl_web
{
    namespace admin
    {
        public class Stat_Survey : Page
        {
            // Fields
            public Connection Conn = new Connection();
            public int Stat_Days = 0, iOnline = 0;
            public int iTodayPV = 0, iTodayUV = 0, iTodayIP = 0;
            public int iYesterdayPV = 0, iYesterdayUV = 0, iYesterdayIP = 0;
            public int iAvgdayPV = 0, iAvgdayUV = 0, iAvgdayIP = 0;
            public int iMonthPV = 0, iMonthUV = 0, iMonthIP = 0;
            public int iTotalPV = 0, iTotalUV = 0, iTotalIP = 0;
            public int iHighPV = 0, iHighUV = 0, iHighIP = 0;
            public string Start_Stat_DateTime;

            // Methods
            private void InitializeComponent()
            {
                this.Load += new EventHandler(this.Page_Load);
            }

            protected override void OnInit(EventArgs e)
            {
                this.InitializeComponent();
                base.OnInit(e);
            }

            protected void Page_Load(object sender, EventArgs e)
            {
                DateTime Stat_DateTime = Convert.ToDateTime(new Config("../admin.config")["StatDateTime"].ToString());
                this.Start_Stat_DateTime = Convert.ToString(Stat_DateTime.ToLongDateString());
                this.Stat_Days = Convert.ToInt32(Text.DateDiff(Stat_DateTime, DateTime.Now, "day"));
                this.iOnline = Conn.GetiScalar("Select Count(Distinct S_IP) As Counts From Stat_Details Where S_VisitDate >= '" + DateTime.Now.AddMinutes(-15) + "'");
                this.iTodayPV = Conn.GetiScalar("Select Sum(S_PV) As Sums From Stat_Analysis Where Datediff(day, S_Date, Getdate()) = 0");
                this.iTodayUV = Conn.GetiScalar("Select Sum(S_UV) As Sums From Stat_Analysis Where Datediff(day, S_Date, Getdate()) = 0");
                this.iTodayIP = Conn.GetiScalar("Select Sum(S_IP) As Sums From Stat_Analysis Where Datediff(day, S_Date, Getdate()) = 0");
                this.iYesterdayPV = Conn.GetiScalar("Select Sum(S_PV) As Sums From Stat_Analysis Where Datediff(day, S_Date, Getdate()) = 1");
                this.iYesterdayUV = Conn.GetiScalar("Select Sum(S_UV) As Sums From Stat_Analysis Where Datediff(day, S_Date, Getdate()) = 1");
                this.iYesterdayIP = Conn.GetiScalar("Select Sum(S_IP) As Sums From Stat_Analysis Where Datediff(day, S_Date, Getdate()) = 1");
                this.iMonthPV = Conn.GetiScalar("Select Sum(S_PV) As Sums From Stat_Analysis Where Datediff(month, S_Date, Getdate()) = 0");
                this.iMonthUV = Conn.GetiScalar("Select Sum(S_UV) As Sums From Stat_Analysis Where Datediff(month, S_Date, Getdate()) = 0");
                this.iMonthIP = Conn.GetiScalar("Select Sum(S_IP) As Sums From Stat_Analysis Where Datediff(month, S_Date, Getdate()) = 0");
                this.iTotalPV = Conn.GetiScalar("Select Sum(S_PV) As Sums From Stat_Analysis");
                this.iTotalUV = Conn.GetiScalar("Select Sum(S_UV) As Sums From Stat_Analysis");
                this.iTotalIP = Conn.GetiScalar("Select Sum(S_IP) As Sums From Stat_Analysis");
                this.iAvgdayPV = this.iTotalPV / this.Stat_Days;
                this.iAvgdayUV = this.iTotalUV / this.Stat_Days;
                this.iAvgdayIP = this.iTotalIP / this.Stat_Days;
                this.iHighPV = Conn.GetiScalar("Select S_PV From Stat_Analysis Union Select Sum(S_PV) From Stat_Analysis Group By DatePart(day, S_Date) Order by S_PV Desc");
                this.iHighUV = Conn.GetiScalar("Select S_UV From Stat_Analysis Union Select Sum(S_UV) From Stat_Analysis Group By DatePart(day, S_Date) Order by S_UV Desc");
                this.iHighIP = Conn.GetiScalar("Select S_IP From Stat_Analysis Union Select Sum(S_IP) From Stat_Analysis Group By DatePart(day, S_Date) Order by S_IP Desc");
                this.SaveHourFluxData("chart/hour_analysis.txt");
            }

            public void SaveHourFluxData(string sFileName)
            {
                string sPV = this.GetArray("PV");
                string sUV = this.GetArray("UV");
                string sIP = this.GetArray("IP");
                string sDT = this.GetArray("DT");
                string sHV = Text.LargerValue(this.GetArrayMaxValue(sPV));
                string sFileContent = "&title=,5,&\r\n" +
                                    "&y_ticks=2,10,10&\r\n" +
                                    "&y_legend=Chart,10,0xD2D2D2&\r\n" +
                                    "&y_min=0&\r\n" +
                                    "&bg_colour=#FFFFFF&\r\n" +
                                    "&x_labels=" + sDT + "&\r\n" +
                                    "&values=" + sPV + "&\r\n" +
                                    "&values_2=" + sUV + "&\r\n" +
                                    "&values_3=" + sIP + "&\r\n" +
                                    "&line_dot=2,0xFF6600,访问量,12,5&\r\n" +
                                    "&line_dot_2=2,0x04D215,独立访客,12,5&\r\n" +
                                    "&line_dot_3=2,0x0D8ECF,独立IP,12,5&\r\n" +
                                    "&y_max=" + sHV + "&";
                Operation.WriteFile(Fetch.MapPath(sFileName), sFileContent);
            }

            public string GetArray(string sType)
            {
                string sDT = "";
                for (int x = DateTime.Now.Hour + 1; x < 24; x++)
                {
                    sDT += x.ToString() + ",";
                }
                for (int y = 0; y <= DateTime.Now.Hour; y++)
                {
                    sDT += y.ToString() + ",";
                }
                sDT = sDT.Substring(0, sDT.LastIndexOf(","));
                if (sType.ToUpper() != "DT")
                {
                    string sArray = "";
                    DataSet dataSet = new DataSet();
                    switch (sType.ToUpper())
                    {
                        case "PV":
                            dataSet = Conn.GetDataSet("Select Count(*),DatePart(hour, S_VisitDate) From Stat_Details Where Datediff(day, S_VisitDate, GetDate()) = 0 Group By DatePart(hour, S_VisitDate)", "HourFluxData");
                            break;
                        case "UV":
                            dataSet = Conn.GetDataSet("Select Count(Distinct S_SerialNumber) As Counts,DatePart(hour, S_VisitDate) As Hours into #temptable From Stat_Details Where Datediff(day, S_VisitDate, GetDate()) = 0 Group By DatePart(hour, S_VisitDate),S_IP Select Sum(Counts) As Counts,Hours From #temptable Group By hours Drop Table #temptable", "HourFluxData");
                            break;
                        case "IP":
                            dataSet = Conn.GetDataSet("Select Count(Distinct S_IP) As Counts,DatePart(hour, S_VisitDate) As Hours From Stat_Details Where Datediff(day, S_VisitDate, GetDate()) = 0 Group By DatePart(hour, S_VisitDate)", "HourFluxData");
                            break;
                    }
                    string[] aDT = sDT.Split(',');
                    for (int i = 0; i < aDT.Length; i++)
                    {
                        int iPatch = 0;
                        for (int j = 0; j < dataSet.Tables["HourFluxData"].Rows.Count; j++)
                        {
                            if (aDT[i] == dataSet.Tables["HourFluxData"].Rows[j][1].ToString())
                            {
                                sArray += dataSet.Tables["HourFluxData"].Rows[j][0].ToString() + ",";
                                iPatch = 1;
                                break;
                            }
                            else
                            {
                                iPatch = 0;
                            }
                        }
                        if (iPatch == 0)
                        {
                            sArray += "0,";
                        }
                    }
                    sArray = sArray.Substring(0, sArray.LastIndexOf(","));
                    return sArray;
                }
                else
                {
                    return sDT;
                }
            }

            public string GetArrayMaxValue(string sArray)
            {
                string[] sValue = sArray.Split(',');
                int[] iValue = new int[sValue.Length];
                for (int i = 0; i < sValue.Length; i++)
                {
                    iValue[i] = Convert.ToInt32(sValue[i]);
                }
                Array.Sort(iValue);
                return iValue[iValue.Length - 1].ToString();
            }
        }

        public class Flow_Analysis : Page
        {
            // Methods
            private void InitializeComponent()
            {
                this.Load += new EventHandler(this.Page_Load);
            }

            protected override void OnInit(EventArgs e)
            {
                this.InitializeComponent();
                base.OnInit(e);
            }

            protected void Page_Load(object sender, EventArgs e)
            {
                this.SaveFluxData("Select Sum(S_PV),Sum(S_UV),Sum(S_IP),DatePart(day, S_Date) As Sums From Stat_Analysis Where S_Date > '" + DateTime.Now.AddMonths(-1) + "' Group By DatePart(day, S_Date),DatePart(month, S_Date),DatePart(year, S_Date)", "chart/day_analysis.txt", "day");
                this.SaveFluxData("Select Sum(S_PV),Sum(S_UV),Sum(S_IP),DatePart(month, S_Date) As Sums From Stat_Analysis Where S_Date > '" + DateTime.Now.AddYears(-1) + "' Group By DatePart(month, S_Date),DatePart(year, S_Date)", "chart/month_analysis.txt", "month");
                this.SaveFluxData("Select Sum(S_PV),Sum(S_UV),Sum(S_IP),DatePart(year, S_Date) As Sums From Stat_Analysis Group By DatePart(year, S_Date)", "chart/year_analysis.txt", "year");
            }

            public void SaveFluxData(string sCmd, string sFileName, string sType)
            {
                DateTime Stat_DateTime = Convert.ToDateTime(new Config("../admin.config")["StatDateTime"].ToString());
                string sPV = "";
                string sUV = "";
                string sIP = "";
                string sDT = "";
                int iDT = 0;
                switch (sType)
                {
                    case "day":
                        iDT = Convert.ToInt32(Text.DateDiff(DateTime.Now.AddMonths(-1), DateTime.Now, "day"));
                        for (int i = DateTime.Now.Day + 1; i <= iDT; i++)
                        {
                            sDT += i.ToString() + ",";
                        }
                        for (int j = 1; j <= DateTime.Now.Day; j++)
                        {
                            sDT += j.ToString() + ",";
                        }
                        break;
                    case "month":
                        for (int i = DateTime.Now.Month + 1; i <= 12; i++)
                        {
                            sDT += i.ToString() + ",";
                        }
                        for (int j = 1; j <= DateTime.Now.Month; j++)
                        {
                            sDT += j.ToString() + ",";
                        }
                        break;
                    case "year":
                        for (int i = (Stat_DateTime.Year); i <= DateTime.Now.Year + 10; i++)
                        {
                            sDT += i.ToString() + ",";
                        }
                        break;
                }
                sDT = sDT.Substring(0, sDT.LastIndexOf(","));
                string[] aDT = sDT.Split(',');
                int[] iPV = new int[aDT.Length];
                DataSet dataSet = new Connection().GetDataSet(sCmd, "FluxData");
                for (int x = 0; x < aDT.Length; x++)
                {
                    int iPatch = 0;
                    for (int y = 0; y < dataSet.Tables["FluxData"].Rows.Count; y++)
                    {
                        if (aDT[x] == dataSet.Tables["FluxData"].Rows[y][3].ToString())
                        {
                            sPV += dataSet.Tables["FluxData"].Rows[y][0].ToString() + ",";
                            sUV += dataSet.Tables["FluxData"].Rows[y][1].ToString() + ",";
                            sIP += dataSet.Tables["FluxData"].Rows[y][2].ToString() + ",";
                            iPV.SetValue(dataSet.Tables["FluxData"].Rows[y][0], x);
                            iPatch = 1;
                            break;
                        }
                        else
                        {
                            iPatch = 0;
                        }
                    }
                    if (iPatch == 0)
                    {
                        sPV += "0,";
                        sUV += "0,";
                        sIP += "0,";
                    }
                }
                sPV = sPV.Substring(0, sPV.LastIndexOf(","));
                sUV = sUV.Substring(0, sUV.LastIndexOf(","));
                sIP = sIP.Substring(0, sIP.LastIndexOf(","));
                Array.Sort(iPV);
                string sFileContent = "&title=,5,&\r\n" +
                                    "&y_ticks=2,10,10&\r\n" +
                                    "&y_legend=Chart,10,0xD2D2D2&\r\n" +
                                    "&y_min=0&\r\n" +
                                    "&bg_colour=#FFFFFF&\r\n" +
                                    "&x_labels=" + sDT + "&\r\n" +
                                    "&values=" + sPV + "&\r\n" +
                                    "&values_2=" + sUV + "&\r\n" +
                                    "&values_3=" + sIP + "&\r\n" +
                                    "&line_dot=2,0xFF6600,访问量,12,5&\r\n" +
                                    "&line_dot_2=2,0x04D215,独立访客,12,5&\r\n" +
                                    "&line_dot_3=2,0x0D8ECF,独立IP,12,5&\r\n" +
                                    "&y_max=" + Text.LargerValue(iPV[iPV.Length - 1].ToString()) + "&";
                Operation.WriteFile(Fetch.MapPath(sFileName), sFileContent);
            }
        }

        public class Content_Analysis : Page
        {
            // Methods
            private void InitializeComponent()
            {
                this.Load += new EventHandler(this.Page_Load);
            }

            protected override void OnInit(EventArgs e)
            {
                this.InitializeComponent();
                base.OnInit(e);
            }

            protected void Page_Load(object sender, EventArgs e)
            {
                this.SaveContentData("chart/search_analysis.xml", "seanalysis");
                this.SaveContentData("chart/keywords_analysis.xml", "kwanalysis");
            }

            public void SaveContentData(string sFileName, string sType)
            {
                string[] Colors = new string[] { "0x54F034", "0x04D215", "0xB0DE09", "0xF8FF01", "0xFF9E01", "0xFF6600", "0xFF1F11", "0x814EE6", "0x008800", "0x880000", "0xF234B0", "0x0D8ECF" };
                string sLice = "";
                DataSet dataSet = new DataSet();
                switch (sType.ToLower())
                {
                    case "seanalysis":
                        dataSet = new Connection().GetDataSet("Select Top 12 S_Name,S_Url From Stat_Search_Engine", "SearchEngine");
                        int iRecordCount = dataSet.Tables["SearchEngine"].Rows.Count;
                        string[,] Lices = new string[iRecordCount, 2];
                        int[] aCount = new int[iRecordCount];
                        for (int i = 0; i < iRecordCount; i++)
                        {
                            Lices[i, 0] = dataSet.Tables["SearchEngine"].Rows[i][0].ToString();
                            int iCount = new Connection().GetiScalar("Select Count(S_SourceUrl) As Counts From Stat_Details Where S_SourceUrl like '%" + dataSet.Tables["SearchEngine"].Rows[i][1].ToString() + "%'");
                            if (iCount != 0)
                            {
                                Lices[i, 1] = Convert.ToString(iCount);
                                aCount[i] = iCount;
                            }
                            else
                            {
                                Lices[i, 1] = "0";
                                aCount[i] = 0;
                            }
                        }
                        Array.Sort(aCount);
                        for (int j = 0; j < iRecordCount; j++)
                        {
                            if (Lices[j, 1] == aCount[aCount.Length - 1].ToString())
                            {
                                sLice += "<slice title=\"" + Lices[j, 0] + "\" color=\"" + Colors[j] + "\" pull_out=\"true\">" + Lices[j, 1] + "</slice>\r\n";
                            }
                            else
                            {
                                sLice += "<slice title=\"" + Lices[j, 0] + "\" color=\"" + Colors[j] + "\">" + Lices[j, 1] + "</slice>\r\n";
                            }
                        }
                        break;
                    case "kwanalysis":
                        string[] SearchKeys = new string[] { "query=", "q=", "w=", "wd=", "word=", "p=", "search:" };
                        string[] UTF8Sites = new string[] { "google", "live", "youdao", "yisou", "yahoo" };
                        dataSet = new Connection().GetDataSet("Select S_SourceUrl,Count(S_SourceUrl) As Counts into #tempTable From Stat_Details Group By S_SourceUrl Having Patindex('%/%', Replace(S_SourceUrl, 'http://', '')) > 0 And (Patindex('%?%', Replace(S_SourceUrl, 'http://', '')) > 0 Or Patindex('%:%', Replace(S_SourceUrl, 'http://', '')) > 0) Select Top 12 S_SourceUrl,Counts From #tempTable Order By Counts Desc Drop Table #tempTable", "KeyWords");
                        for (int i = 0; i < dataSet.Tables["KeyWords"].Rows.Count; i++)
                        {
                            bool isSub = false;
                            bool isUTFKey = false;
                            string sKeyWord = dataSet.Tables["KeyWords"].Rows[i][0].ToString();
                            for (int k = 0; k < UTF8Sites.Length; k++)
                            {
                                if (sKeyWord.Contains(UTF8Sites[k]) && sKeyWord.Contains("cn.yahoo") == false)
                                {
                                    isUTFKey = true;
                                }
                            }
                            for (int j = 0; j < SearchKeys.Length; j++)
                            {
                                if (sKeyWord.Contains(SearchKeys[j]))
                                {
                                    sKeyWord = sKeyWord.Substring(sKeyWord.IndexOf(SearchKeys[j]) + SearchKeys[j].Length);
                                    if (sKeyWord.Contains("&"))
                                    {
                                        sKeyWord = sKeyWord.Substring(0, sKeyWord.IndexOf("&"));
                                    }
                                    isSub = true;
                                    break;
                                }
                            }
                            if (isSub && sKeyWord != "")
                            {
                                if (isUTFKey)
                                {
                                    sKeyWord = HttpUtility.UrlDecode(sKeyWord, System.Text.Encoding.UTF8);
                                }
                                else
                                {
                                    sKeyWord = Fetch.UrlDecode(sKeyWord);
                                }
                                if (i == 0)
                                {
                                    sLice += "<slice title=\"" + sKeyWord + "\" color=\"" + Colors[i] + "\" pull_out=\"true\">" + dataSet.Tables["KeyWords"].Rows[i][1].ToString() + "</slice>\r\n";
                                }
                                else
                                {
                                    sLice += "<slice title=\"" + sKeyWord + "\" color=\"" + Colors[i] + "\">" + dataSet.Tables["KeyWords"].Rows[i][1].ToString() + "</slice>\r\n";
                                }
                            }
                        }
                        break;
                }
                string sFileContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<pie>\r\n" + sLice + "</pie>\r\n";
                Operation.WriteFile(Fetch.MapPath(sFileName), sFileContent);
            }
        }

        public class Visit_Details : Page
        {
            // Fields
            public string action;
            public string _visitdetails;
            private int pageSize = 10;
            private int absolutePage = 1;

            // Methods
            private string GetVisitDetails()
            {
                string _content = null;
                _content += "\r\n\t\t\t<form name=\"visitdetails\" action=\"visit_details.aspx\" method=\"post\" style=\"margin:0;padding:0\">";
                _content += "\r\n\t\t\t<table class=\"maintable\" border=\"0\" cellspacing=\"1\" cellpadding=\"0\">";
                _content += "\r\n\t\t\t<tr>";
                _content += "<td class=\"title\" style=\"width:8%;text-align:center\"><input type=\"checkbox\" name=\"selectall\" onclick=\"selectallcheckbox('visitdetails', 'selectall');\" style=\"border:none\" title=\"全选\" /></td>";
                _content += "<td class=\"title\" style=\"width:17%\">时间</td>";
                _content += "<td class=\"title\" style=\"width:10%\">IP</td>";
                _content += "<td class=\"title\" style=\"width:25%\">来源网址</td>";
                _content += "<td class=\"title\" style=\"width:25%\">访问网址</td>";
                _content += "<td class=\"title\" style=\"width:15%\">地区</td>";
                _content += "</tr>";
                string strSql = null;
                if (1 == this.absolutePage)
                {
                    strSql = Text.JoinString("Select * From Stat_Details Where S_Id in (Select Top ", this.pageSize.ToString(), " t1.S_Id From Stat_Details As t1 Order By t1.S_Id Desc) Order By S_Id Desc");
                }
                else
                {
                    strSql = Text.JoinString("Select * From Stat_Details Where S_Id in (Select Top ", this.pageSize.ToString(), " t3.S_Id From Stat_Details As t3 Where t3.S_Id < (Select Min(S_Id) From (Select Top ", ((this.absolutePage - 1) * this.pageSize).ToString(), " t1.S_Id From Stat_Details As t1 Order By t1.S_Id Desc) As t2) Order By t3.S_Id Desc) Order By S_Id Desc");
                }
                DataTable dataTable = new Connection().GetDataTable(strSql);
                if (dataTable.Rows.Count == 0)
                {
                    dataTable.Clear();
                    dataTable = new Connection().GetDataTable(Text.JoinString("Select * From Stat_Details Where S_Id in (Select Top ", this.pageSize.ToString(), " t1.S_Id From Stat_Details As t1 Order By t1.S_Id Desc) Order By S_Id Desc"));
                }
                if (dataTable.Rows.Count > 0)
                {
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        _content += "\r\n\t\t\t<tr>";
                        _content += "<td style=\"text-align:center\"><input type=\"checkbox\" name=\"id\" value=\"" + dataTable.Rows[i]["S_Id"].ToString() + "\" style=\"border:none\" /></td>";
                        _content += "<td>" + dataTable.Rows[i]["S_VisitDate"].ToString() + "</td>";
                        _content += "<td>" + dataTable.Rows[i]["S_IP"].ToString() + "</td>";
                        _content += "<td title=\"" + dataTable.Rows[i]["S_SourceUrl"].ToString() + "\">" + Text.Left(dataTable.Rows[i]["S_SourceUrl"].ToString(), 25, false) + "</td>";
                        _content += "<td title=\"" + dataTable.Rows[i]["S_VisitUrl"].ToString() + "\">" + Text.Left(dataTable.Rows[i]["S_VisitUrl"].ToString(), 25, false) + "</td>";
                        _content += "<td>" + dataTable.Rows[i]["S_Area"].ToString() + "</td>";
                        _content += "</tr>";
                    }
                }
                else
                {
                    _content += "\r\n\t\t\t<tr><td style=\"height:25px;text-align:center;color:red\" colspan=\"5\">还没有发布任何论坛公告！</td></tr>";
                }
                _content += "\r\n\t\t\t</table>\r\n\t\t\t</form>";
                if (dataTable.Rows.Count > 0)
                {
                    Pager xlPager = new Pager();
                    xlPager.Style = 0;
                    xlPager.PageSize = this.pageSize;
                    xlPager.CurrentPage = this.absolutePage;
                    xlPager.Total = new Connection().GetiScalar("Select Count(*) As Counts From Stat_Details");
                    xlPager.Calculate();
                    xlPager.Url = "visit_details.aspx?page={p}";
                    xlPager.InitPager();
                    _content += "\r\n\t\t\t<div style=\"margin:0;padding:0\">";
                    _content += "\r\n\t\t\t<span style=\"float:left;padding:5px 0;\">";
                    _content += "\r\n\t\t\t<select name=\"operation\" onchange=\"chkPost(this, 'visitdetails');\">";
                    _content += "\r\n\t\t\t<option value=\"\" selected=\"selected\">管理选中记录...</option><option value=\"delsel\">·删除选择的记录</option><option value=\"delall\">·删除所有记录</option>";
                    _content += "\r\n\t\t\t</select>";
                    _content += "\r\n\t\t\t</span>";
                    _content += "\r\n\t\t\t<span style=\"float:right;padding:5px 0;\">\r\n\t\t\t" + xlPager.PageStr + "</span>";
                    _content += "\r\n\t\t\t</div>";
                }
                dataTable.Dispose();
                return _content;
            }

            private void InitializeComponent()
            {
                this.Load += new EventHandler(this.Page_Load);
            }

            protected override void OnInit(EventArgs e)
            {
                this.InitializeComponent();
                base.OnInit(e);
            }

            protected void Page_Load(object sender, EventArgs e)
            {
                if (RegExp.IsNumeric(Fetch.Get("page")))
                {
                    this.absolutePage = Convert.ToInt32(Fetch.Get("page"));
                }
                if (Fetch.Get("action") != string.Empty)
                {
                    string strSql = null;
                    switch (Fetch.Get("action"))
                    {
                        case "delsel":
                            {
                                if (Fetch.Get("id") != string.Empty)
                                {
                                    strSql = "Delete From Stat_Details Where S_Id In (" + Fetch.Get("id") + ")";
                                    new Connection().ExecSql(strSql);
                                    Fetch.Redirect("visit_details.aspx");
                                }
                                break;
                            }
                        case "delall":
                            {
                                strSql = "Delete From Stat_Details";
                                new Connection().ExecSql(strSql);
                                Fetch.Redirect("visit_details.aspx");
                                break;
                            }
                    }
                }
                this._visitdetails = this.GetVisitDetails();           
            }
        }
    }

    namespace web
    {
        public class Stat : UserControl
        {
            // Fields
            private Connection Conn = new Connection();
            private string type;
            public string OutStr;

            // Methods
            private void InitializeComponent()
            {
                this.Load += new EventHandler(this.Page_Load);
            }

            protected override void OnInit(EventArgs e)
            {
                this.InitializeComponent();
                base.OnInit(e);
            }

            protected void Page_Load(object sender, EventArgs e)
            {
                // 网页立即超时
                Response.Expires = 0;

                // 检查Cookie是否存在
                bool isEcho = false;
                string sSerialNumber = Text.GetDateTime("short") + Text.RandomNumber(3);
                HttpCookie readCookie = Request.Cookies["XL_SN"];
                if (readCookie != null && readCookie.Values["SN"] != null)
                {
                    isEcho = true;
                }
                if (!isEcho)
                {
                    HttpCookie Cookie = new HttpCookie("XL_SN");
                    Cookie.Expires = DateTime.Now.AddDays(0.01);
                    Cookie.Values.Add("SN", sSerialNumber);
                    Response.AppendCookie(Cookie);
                }

                // 获取客户端数据
                string sIp = Fetch.UserIP;
                string sArea = Fetch.IpLocation;
                string sUrl = (Fetch.UrlReferrer == string.Empty) ? "直接输入" : null;
                string vUrl = Fetch.Url;
                string sOs = Fetch.UserOS;
                string sBrowser = Fetch.UserBrowser;
                string sLanguage = Fetch.UserLanguage;
                string sResolution = Fetch.UserResolution;
                string sVisitdate = DateTime.Now.ToString();

                // 保存客户端数据
                Conn.ExecSql("Insert Into Stat_Details(S_SerialNumber,S_IP,S_Area,S_SourceUrl,S_VisitUrl,S_OS,S_Browser,S_Language,S_Resolution,S_VisitDate) Values('" + Request.Cookies["XL_SN"].Values["SN"] + "','" + sIp + "','" + sArea + "','" + sUrl + "','" + vUrl + "','" + sOs + "','" + sBrowser + "','" + sLanguage + "','" + sResolution + "','" + sVisitdate + "')");

                // 统计
                int iOnline = Conn.GetiScalar("Select Count(Distinct S_IP) As Counts From Stat_Details Where S_VisitDate >= '" + DateTime.Now.AddMinutes(-15) + "'");
                int iTodayPV = Conn.GetiScalar("Select Count(*) As Counts From Stat_Details Where Datediff(day, S_VisitDate, Getdate()) = 0");
                int iYesterdayPV = Conn.GetiScalar("Select Count(*) As Counts From Stat_Details Where Datediff(day, S_VisitDate, Getdate()) = 1");
                int iTotalPV = Conn.GetiScalar("Select Count(*) As Counts From Stat_Details");
                int iTodayIP = Conn.GetiScalar("Select Count(Distinct S_IP) As Counts From Stat_Details Where Datediff(day, S_VisitDate, Getdate()) = 0");
                int iYesterdayIP = Conn.GetiScalar("Select Count(Distinct S_SerialNumber) As Counts From Stat_Details Where Datediff(day, S_VisitDate, Getdate()) = 1");
                int iTotalIP = Conn.GetiScalar("Select Count(Distinct S_IP) As Counts From Stat_Details");
                int iTodayUV = Conn.GetsRows("Select Count(Distinct S_SerialNumber) As Counts From Stat_Details Where Datediff(day, S_VisitDate, Getdate()) = 0 Group By S_IP Having S_IP = S_IP");
                int iYesterdayUV = Conn.GetsRows("Select Count(Distinct S_SerialNumber) As Counts From Stat_Details Where Datediff(day, S_VisitDate, Getdate()) = 1 Group By S_IP Having S_IP = S_IP");
                int iTotalUV = Conn.GetsRows("Select Count(Distinct S_SerialNumber) As Counts From Stat_Details Group By S_IP Having S_IP = S_IP");
                int iDepth = Conn.GetiRows("Select Count(Distinct S_VisitUrl) As Counts From Stat_Details Group By S_IP,S_SerialNumber Having S_IP = S_IP And S_SerialNumber = S_SerialNumber And Count(S_VisitUrl) > 1");

                // 保存统计数据
                int iDay = DateTime.Now.Day;
                int iMonth = DateTime.Now.Month;
                int iYear = DateTime.Now.Year;
                if (Conn.GetiScalar("Select Count(*) As Counts From Stat_Analysis") == 0)
                {
                    Conn.ExecSql("Insert Into Stat_Analysis(S_PV,S_UV,S_IP,S_Date) Values(" + iTodayPV + "," + iTodayUV + "," + iTodayIP + ",'" + DateTime.Now.ToShortDateString() + "')");
                }
                else
                {
                    DateTime dateTime = Convert.ToDateTime(Conn.GetScalar("Select S_Date From Stat_Analysis Order By S_Id Desc"));
                    int iGetDay = dateTime.Day;
                    int iGetMonth = dateTime.Month;
                    int iGetYear = dateTime.Year;
                    if (iGetDay == iDay && iGetMonth == iMonth && iGetYear == iYear)
                    {
                        Conn.ExecSql("Update Stat_Analysis Set S_PV=" + iTodayPV + ",S_UV=" + iTodayUV + ",S_IP=" + iTodayIP + ",S_Date='" + DateTime.Now.ToShortDateString() + "' Where Datediff(day, S_Date, Getdate()) = 0");
                    }
                    else
                    {
                        Conn.ExecSql("Insert Into Stat_Analysis(S_PV,S_UV,S_IP,S_Date) Values(" + iTodayPV + "," + iTodayUV + "," + iTodayIP + ",'" + DateTime.Now.ToShortDateString() + "')");
                    }
                }

                // 输出数据
                if (this.Type != string.Empty)
                {
                    string _outstr = null;
                    switch (this.Type)
                    {
                        case "text":
                            _outstr = "你是本站的第 " + iTotalPV.ToString() + " 位访客";
                            break;
                        case "text1":
                            _outstr = "当前在线：" + iOnline.ToString() + "人";
                            break;
                        case "text2":
                            _outstr = "昨日访问量：" + iYesterdayPV.ToString() + " | 今日访问量：" + iTodayPV.ToString() + " | 总访问量：" + iTotalPV.ToString() + " | 当前在线：" + iOnline.ToString() + "人";
                            break;
                        case "text3":
                            _outstr = "今日IP[" + iTodayIP.ToString() + "] | 今日PV[" + iTodayPV.ToString() + "] | 昨日IP[" + iYesterdayIP.ToString() + "] | 昨日PV[" + iYesterdayPV.ToString() + "] | 当前在线[" + iOnline.ToString() + "]";
                            break;
                        case "text4":
                            _outstr = "今日IP：" + iTodayIP.ToString() + " <br /> 今日PV：" + iTodayPV.ToString() + " <br /> 昨日IP：" + iYesterdayIP.ToString() + " <br /> 昨日PV：" + iYesterdayPV.ToString() + " <br /> 当前在线：" + iOnline.ToString() + "人";
                            break;
                        case "flash":
                            _outstr = "<embed src='/images/counter.swf?cgi=load=start&total=" + iTotalPV + "&yes=" + iYesterdayPV + "&today=" + iTodayPV + "&you=0&load=end' type='application/x-shockwave-flash' width='130' height='58'></embed>";
                            break;
                        default:
                            _outstr = "";
                            break;
                    }
                    string _content = "\r\n<script type=\"text/javascript\">";
                    _content += "\r\n<!--";
                    _content += "\r\ndocument.write(\"" + _outstr + "\");";
                    _content += "\r\n//-->";
                    _content += "\r\n</script>";
                    this.OutStr = _content;
                }
            }

            // Properties
            public string Type
            {
                get
                {
                    return this.type;
                }
                set
                {
                    this.type = value;
                }
            }
        }
    }
}