using System;
using System.Data;
using System.Configuration;
using System.IO;
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.Xml;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using JuSNS.Config;


namespace JuSNS.Common
{
    public class Public
    {
        /// <summary>
        /// 去掉结尾,
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string LostDot(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return string.Empty;
            }
            else
            {
                if (input.IndexOf(",") > -1)
                {
                    int intLast = input.LastIndexOf(",");
                    if ((intLast+1) == input.Length)
                    {
                        return input.Remove(intLast);
                    }
                    else
                    {
                        return input;
                    }
                }
                else
                {
                    return input;
                }
            }
        }

        /// <summary>
        /// 根目录
        /// </summary>
        public static string rootDir
        {
            get
            {
                return JuSNS.Config.UiConfig.RootDir;
            }
        }
        /// <summary>
        /// 打招呼表情
        /// </summary>
        public static string GetAction(int t, string from, string to, string isPub)
        {
            string astr = string.Empty;
            string isPubs = string.Empty;
            if (isPub == "0")
            {
                isPubs = "[<span class=\"reshow\">偷偷</span>]";
            }
            if (t == -1)
            {
                astr = from + " 你 " + to;
            }
            else
            {
                astr = JuSNS.Config.PokeConfig.Config[t].More;
            }
            return isPubs + astr.Replace("xx", "你");
        }

        /// <summary>
        /// 获得等级
        /// </summary>
        /// <param name="Num"></param>
        /// <returns></returns>
        public static string GetRank(int root, int JFNum)
        {
            string Rank = string.Empty;
            int sunNumber = 10000;
            int moonNumber = 2000;
            int StarNumber = 400;
            if (JFNum > sunNumber)
            {
                Rank += "<img src=\"" + root + "/template/" + JuSNS.Config.UiConfig.SkinStyle + "/images/rank/sun.gif\" /> ";
                Rank += "<img src=\"" + root + "/template/" + JuSNS.Config.UiConfig.SkinStyle + "/images/rank/sun.gif\" /> ";
                Rank += "<img src=\"" + root + "/template/" + JuSNS.Config.UiConfig.SkinStyle + "/images/rank/sun.gif\" /> ";
                Rank += "<img src=\"" + root + "/template/" + JuSNS.Config.UiConfig.SkinStyle + "/images/rank/sun.gif\" /> ";
            }
            return Rank;
        }

        /// <summary>
        /// 读取模板
        /// </summary>
        /// <param name="path"></param>
        /// <param name="isSpace"></param>
        /// <returns></returns>
        public static string GetTempleContent(string path,bool isSpace)
        {
            if (isSpace)
            {
                return GetTempleContent(path);
            }
            else
            {
                string result = string.Empty;
                string sFileName = HttpContext.Current.Server.MapPath(path);
                if (File.Exists(sFileName))
                {
                    try
                    {
                        using (StreamReader sr = new StreamReader(sFileName))
                        {
                            result = sr.ReadToEnd();
                        }
                    }
                    catch
                    {
                        result = "读取模板文件(" + path + ")出错";
                    }
                }
                else
                {
                    result = "找不到模板文件：" + path;
                }
                return result;
            }
        }
        /// <summary>
        /// 读取模板内容(个人空间)
        /// </summary>
        /// <param name="path">模板路径</param>
        /// <returns></returns>
        public static string GetTempleContent(string path)
        {
            string result = string.Empty;
            string sFileName = HttpContext.Current.Server.MapPath(path);
            if (File.Exists(sFileName))
            {
                try
                {
                    using (StreamReader sr = new StreamReader(sFileName))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                catch
                {
                    result = GetTempleContent("~/template/space/default/index.html");
                }
            }
            else
            {
                result = GetTempleContent("~/template/space/default/index.html");
            }
            return result;
        }

        public static string ReplacePublic(string Content)
        {
            Content = Content.Replace("{SiteName}", JuSNS.Config.UiConfig.SiteName);
            Content = Content.Replace("{SkinStyle}", JuSNS.Config.UiConfig.SkinStyle);
            Content = Content.Replace("{RootDir}", rootDir);
            Content = Content.Replace("{Version}", JuSNS.Config.UiConfig.PVersion);
            return Content;
        }

        /// <summary>
        /// 检查当前IP是否是受限IP
        /// </summary>
        /// <param name="LimitedIP">受限的IP，格式如:192.168.1.110|212.235.*.*|232.*.*.*</param>
        /// <returns>返回true表示IP未受到限制</returns>
        static public bool ValidateIP(string LimitedIP)
        {
            string CurrentIP = GetClientIP();
            if (string.IsNullOrEmpty(LimitedIP))
                return true;
            LimitedIP.Replace(".", @"\.");
            LimitedIP.Replace("*", @"[^\.]{1,3}");
            Regex reg = new Regex(LimitedIP, RegexOptions.Compiled);
            Match match = reg.Match(CurrentIP);
            return !match.Success;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path">文件路径</param>
        public static void DelFile(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
            catch (IOException e) { }
        }

        /// <summary>
        /// 删除照片或头像
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="_type">0为头像， 1为照片， 2头像照片</param>
        public static void DelFile(string filename, int _type)
        {
            Dictionary<string, PicConfigInfo> pci;
            string rootdir = rootDir;
            string dirroot = string.Empty;
            string server = "";
            switch (_type)
            {
                case 0:
                    pci = PicConfig.Portrait;
                    dirroot = PicConfig.ProtraitRoot;
                    server = PicConfig.ProtraitServer;
                    break;
                case 1:
                    pci = PicConfig.Photo;
                    dirroot = PicConfig.PhotoRoot;
                    server = PicConfig.PhotoServer;
                    break;
                case 2:
                    pci = PicConfig.GroupHead;
                    dirroot = PicConfig.GroupDir;
                    server = PicConfig.GroupServer;
                    break;
                default:
                    pci = PicConfig.Photo;
                    dirroot = PicConfig.PhotoRoot;
                    server = PicConfig.PhotoServer;
                    break;
            }
            string dir;
            string cPath;
            foreach (string k in pci.Keys)
            {
                if (k != "")
                {
                    dir = rootdir + "/" + pci[k].Directory;
                    cPath = HttpContext.Current.Server.MapPath(dir) + @"\" + filename;
                    if (string.IsNullOrEmpty(server) || server == "~")
                    {
                        DelFile(cPath);
                    }
                    else
                    {
                        JuSNS.Common.WebService.UploadService upsrv = new JuSNS.Common.WebService.UploadService();
                        JuSNS.Common.WebService.MySoapHeader soapheader = new JuSNS.Common.WebService.MySoapHeader();
                        soapheader.Password = PicConfig.SoapPass;
                        upsrv.MySoapHeaderValue = soapheader;
                        upsrv.DeleteFile(dir + "/" + filename);
                    }
                }
            }
            dir = rootdir + "/" + dirroot;
            cPath = HttpContext.Current.Server.MapPath(dir) + @"\" + filename;
            if (string.IsNullOrEmpty(server) || server == "~")
            {
                DelFile(cPath);
            }
            else
            {
                JuSNS.Common.WebService.UploadService upsrv = new JuSNS.Common.WebService.UploadService();
                JuSNS.Common.WebService.MySoapHeader soapheader = new JuSNS.Common.WebService.MySoapHeader();
                soapheader.Password = PicConfig.SoapPass;
                upsrv.MySoapHeaderValue = soapheader;
                upsrv.DeleteFile(dir + "/" + filename);
            }
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="path">文件夹路径</param>
        public static void DelDir(string path)
        {
            try
            {
                if (Directory.Exists(path))
                {
                    Directory.Delete(path);
                }
            }
            catch (IOException e) { }
        }


        /// <summary>
        /// 取得用户客户端IP(穿过代理服务器取远程用户真实IP地址)
        /// </summary>
        public static string GetClientIP()
        {
            if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
            {
                return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
        }

        /// <summary>
        /// 取得前一个（上次提交或链接进来的）网页的URL
        /// </summary>
        /// <returns></returns>
        public static string GetReferrerUrl()
        {
            Uri uri = HttpContext.Current.Request.UrlReferrer;
            if (uri != null)
            {
                return uri.ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 读取配置
        /// </summary>
        /// <param name="strTarget">接点名</param>
        /// <returns></returns>
        public static string ReadConfig(string strTarget)
        {
            string rstr = "";
            string xmlPath = HttpContext.Current.Server.MapPath("~/config/JuSite.config");
            FileInfo finfo = new FileInfo(xmlPath);
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName(strTarget);
            rstr += elemList[0].InnerXml;
            return rstr;
        }

        /// <summary>
        /// 读取IM配置
        /// </summary>
        /// <param name="strTarget">接点名</param>
        /// <returns></returns>
        public static string readIMConfig(string strTarget)
        {
            string rstr = "";
            string xmlPath = HttpContext.Current.Server.MapPath("~/config/email/im.config");
            FileInfo finfo = new FileInfo(xmlPath);
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName(strTarget);
            rstr += elemList[0].InnerXml;
            return rstr;
        }


        /// <summary>
        /// 读取频道配置
        /// </summary>
        public static string readCHparamConfig(string strTarget, int ChID)
        {
            string rstr = "";
            string xmlPath = HttpContext.Current.Server.MapPath("~/xml/sys/Channel/ChParams/CH_" + ChID.ToString() + ".config");
            FileInfo finfo = new FileInfo(xmlPath);
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName(strTarget);
            rstr += elemList[0].InnerXml;
            return rstr;
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="strTarget">接点名</param>
        public static void SaveXmlConfig(string strTarget, string strValue, string strSource)
        {
            string xmlPath = HttpContext.Current.Server.MapPath("~/" + strSource);
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName(strTarget);
            elemList[0].InnerXml = strValue;
            xdoc.Save(xmlPath);
        }

        /// <summary>
        /// 取得与当前时间的间隔(MM-dd hh:mm-刚刚更新)
        /// </summary>
        public static string getTimeSpan(DateTime time1)
        {
            string strTime = "";
            DateTime date1 = DateTime.Now;
            DateTime date2 = time1;
            TimeSpan dt = date1 - date2;

            // 相差天数
            int days = dt.Days;
            // 时间点相差小时数
            int hours = dt.Hours;
            // 相差总小时数
            double Minutes = dt.Minutes;
            // 相差总秒数
            int second = dt.Seconds;

            if (second < 0) { second = 0; }
            if (days == 0 && hours == 0 && Minutes == 0)
            {
                strTime = "刚刚更新";
            }
            else if (days == 0 && hours == 0)
            {
                strTime = Minutes + "分钟前";
            }
            else if (days == 0)
            {
                strTime = hours + "小时前";
            }
            else
            {
                strTime = time1.ToString("MM-dd hh:mm");
            }
            return strTime;
        }


        /// <summary>
        /// 取得与当前时间的间隔(yyyy年MM月dd日 刚刚更新)
        /// </summary>
        public static string getTimeLEXYearSpan(DateTime time1)
        {
            string strTime = "";
            DateTime date1 = DateTime.Now;
            DateTime date2 = time1;
            TimeSpan dt = date1 - date2;

            // 相差天数
            int days = dt.Days;
            // 时间点相差小时数
            int hours = dt.Hours;
            // 相差总小时数
            double Minutes = dt.Minutes;
            // 相差总秒数
            int second = dt.Seconds;

            if (days == 0 && hours == 0 && Minutes == 0)
            {
                strTime = "刚刚更新";
            }
            else if (days == 0 && hours == 0)
            {
                strTime = Minutes + "分钟前";
            }
            else if (days == 0)
            {
                strTime = hours + "小时前";
            }
            else
            {
                strTime = time1.ToString("yyyy年MM月dd日");
            }
            return strTime;
        }

        /// <summary>
        /// 取得与当前时间的间隔(yy-MM-dd 刚刚更新)
        /// </summary>
        public static string getTimeEXYearSpan(DateTime time1)
        {
            string strTime = "";
            DateTime date1 = DateTime.Now;
            DateTime date2 = time1;
            TimeSpan dt = date1 - date2;

            // 相差天数
            int days = dt.Days;
            // 时间点相差小时数
            int hours = dt.Hours;
            // 相差总小时数
            double Minutes = dt.Minutes;
            // 相差总秒数
            int second = dt.Seconds;

            if (days == 0 && hours == 0 && Minutes == 0)
            {
                strTime = "刚刚更新";
            }
            else if (days == 0 && hours == 0)
            {
                strTime = Minutes + "分钟前";
            }
            else if (days == 0)
            {
                strTime = hours + "小时前";
            }
            else
            {
                strTime = time1.ToString("yy-MM-dd");
            }
            return strTime;
        }


        /// <summary>
        /// 取得与当前时间的间隔(MM-dd-刚刚更新)
        /// </summary>
        public static string getTimeEXSpan(DateTime time1)
        {
            string strTime = "";
            DateTime date1 = DateTime.Now;
            DateTime date2 = time1;
            TimeSpan dt = date1 - date2;

            // 相差天数
            int days = dt.Days;
            // 时间点相差小时数
            int hours = dt.Hours;
            // 相差总小时数
            double Minutes = dt.Minutes;
            // 相差总秒数
            int second = dt.Seconds;

            if (days == 0 && hours == 0 && Minutes == 0)
            {
                //strTime = second + "秒钟前";
                strTime = "刚刚更新";
            }
            else if (days == 0 && hours == 0)
            {
                strTime = Minutes + "分钟前";
            }
            else if (days == 0)
            {
                strTime = hours + "小时前";
            }
            else
            {
                strTime = time1.ToString("MM-dd");
            }
            return strTime;
        }

        /// <summary>
        /// 取得与当前时间的间隔(MM月dd日 刚刚更新)
        /// </summary>
        public static string getTimeEXPINSpan(DateTime time1)
        {
            string strTime = "";
            DateTime date1 = DateTime.Now;
            DateTime date2 = time1;
            TimeSpan dt = date1 - date2;

            // 相差天数
            int days = dt.Days;
            // 时间点相差小时数
            int hours = dt.Hours;
            // 相差总小时数
            double Minutes = dt.Minutes;
            // 相差总秒数
            int second = dt.Seconds;

            if (days == 0 && hours == 0 && Minutes == 0)
            {
                strTime = "刚刚更新";
            }
            else if (days == 0 && hours == 0)
            {
                strTime = Minutes + "分钟前";
            }
            else if (days == 0)
            {
                strTime = hours + "小时前";
            }
            else
            {
                strTime = time1.ToString("MM月dd日");
            }
            return strTime;
        }

        /// <summary>
        /// 取得与当前时间的间隔(MM月dd日-刚刚)
        /// </summary>
        public static string getTimeEXTSpan(DateTime time1)
        {
            string strTime = "";
            DateTime date1 = DateTime.Now;
            DateTime date2 = time1;
            TimeSpan dt = date1 - date2;

            // 相差天数
            int days = dt.Days;
            // 时间点相差小时数
            int hours = dt.Hours;
            // 相差总小时数
            double Minutes = dt.Minutes;
            // 相差总秒数
            int second = dt.Seconds;

            if (days == 0 && hours == 0 && Minutes == 0)
            {
                strTime = "刚刚";
            }
            else if (days == 0 && hours == 0)
            {
                strTime = Minutes + "分钟前";
            }
            else if (days == 0)
            {
                strTime = hours + "小时前";
            }
            else
            {
                strTime = time1.ToString("MM月dd日");
            }
            return strTime;
        }

        /// <summary>
        /// 获取时间相隔天数
        /// </summary>
        /// <param name="time1">时间1</param>
        /// <returns></returns>
        public static string getDaySpan(DateTime time1)
        {
            TimeSpan ts = DateTime.Now - time1;
            return ts.Days.ToString();
        }

        /// <summary>
        /// 读取并返回一个文本文件的内容
        /// </summary>
        /// <param name="filePath">文件的物理路径</param>
        /// <returns></returns>
        public static string GetTextFileContent(string filePath)
        {
            string result = string.Empty;
            if (File.Exists(filePath))
            {
                try
                {
                    using (StreamReader sr = new StreamReader(filePath))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                catch
                { }
            }
            return result;
        }

        /// <summary>
        /// 替换文本中的空格和换行
        /// </summary>
        public static string ReplaceSpace(string str)
        {
            string s = str;
            s = s.Replace(" ", "&nbsp;");
            s = s.Replace("\n", "<BR />");
            return s;
        }

        /// <summary>
        /// 过滤关键字，查看是否是禁用姓名
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="flag">true：关键字 false：姓名</param>
        /// <returns></returns>
        public static string CheckKey(string key, bool flag)
        {
            string fg = "";
            string strKey = "";
            if (flag)
            {
                strKey = JuSNS.Config.SysConfig.KeyWord;
            }
            else
            {
                strKey = JuSNS.Config.SysConfig.UserName;
            }

            string[] Str = strKey.Split('|');
            for (int i = 0; i < Str.Length; i++)
            {
                try
                {
                    if (key.Contains(Str[i].ToString()))
                    {
                        fg = Str[i].ToString();
                        break;
                    }
                }
                catch { }
            }
            return fg;
        }

        /// <summary>
        /// 替换表情
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public static string CheckSma(string Input)
        {
            string rootDir = string.Empty;
            string TMPDir = JuSNS.Config.UiConfig.RootDir;
            if (!string.IsNullOrEmpty(Input))
            {
                string contentStr = Input;
                if (contentStr.IndexOf("[em:") > -1 && contentStr.IndexOf(":]") > -1)
                {
                    for (int i = 1; i < 136; i++)
                    {
                        contentStr = contentStr.Replace("[em:" + i + ":]", "<img src=\"" + rootDir + "/template/images/face/" + i + ".gif\"   align=\"absmiddle\"  />");
                    }
                }
                return contentStr;
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 读取,添加，修改xml文件
        /// </summary>
        /// <param name="Xmlpath">Xml路径</param>
        /// <param name="Node">新的子节点名称</param>
        /// <param name="Value">新节点对应的值</param>
        /// <param name="flag">1：读取，否则为 修改或者添加</param>
        /// <returns>1：修改添加成功，为空字符串表示修改添加成功，否则是读取成功</returns>
        public static string getXML(string Xmlpath, string Node, string Value, int flag)
        {
            try
            {
                string filepath = HttpContext.Current.Server.MapPath(Xmlpath);
                XmlDocument xmlDoc = new XmlDocument();
                if (!File.Exists(filepath))
                {
                    XmlDeclaration xn = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                    XmlElement root = xmlDoc.CreateElement("rss");
                    XmlElement root1 = xmlDoc.CreateElement("item");

                    root.AppendChild(root1);
                    xmlDoc.AppendChild(xn);
                    xmlDoc.AppendChild(root);
                    xmlDoc.Save(filepath);//本地路径名字
                }
                xmlDoc.Load(filepath);//你的xml文件
                string ReStr = string.Empty;
                XmlElement xmlObj = xmlDoc.DocumentElement;

                XmlNodeList xmlList = xmlDoc.SelectSingleNode(xmlObj.Name.ToString()).ChildNodes;

                foreach (XmlNode xmlNo in xmlList)
                {
                    if (xmlNo.NodeType != XmlNodeType.Comment)//判断是不是注释类型
                    {
                        XmlElement xe = (XmlElement)xmlNo;
                        {
                            if (xe.Name == xmlObj.FirstChild.Name)
                            {
                                XmlNodeList xmlNList = xmlObj.FirstChild.ChildNodes;

                                foreach (XmlNode xmld in xmlNList)
                                {
                                    XmlElement xe1 = (XmlElement)xmld;
                                    {
                                        if (xe1.Name == Node)
                                        {
                                            if (flag == 1)//读取值
                                            {
                                                if (xmld.InnerText != null && xmld.InnerText != "")
                                                {
                                                    ReStr = xmld.InnerText;
                                                }
                                            }
                                            else//修改值
                                            {
                                                xmld.InnerText = Value;//给节点赋值
                                                xmlDoc.Save(filepath);
                                                ReStr = Value.Trim();
                                            }
                                        }
                                    }
                                }
                                if (ReStr == string.Empty)// 添加节点
                                {
                                    XmlNode newNode;
                                    newNode = xmlDoc.CreateNode("element", Node, Value);//创建节点
                                    newNode.InnerText = Value;//给节点赋值
                                    xe.AppendChild(newNode);//把节点添加到doc
                                    xmlDoc.Save(filepath);
                                    ReStr = Value.Trim();
                                }
                            }
                        }
                    }
                }
                return ReStr;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        ///获取文件地址
        /// </summary>
        public static string URLWrite(string Dir, string Req, string ID)
        {
            string ReturnStr = string.Empty;
            string isURLWrite = JuSNS.Config.UiConfig.Openurl;
            if (isURLWrite == "1")
            {
                if (Dir != string.Empty)
                {
                    ReturnStr = Dir + "/" + ID;
                }
                else
                {
                    ReturnStr = "u" + ID + ".aspx";
                }
            }
            else
            {
                if (Dir != string.Empty)
                {
                    if (Dir == "index")
                    {
                        ReturnStr = "?" + Req + "=" + ID;
                    }
                    else
                    {
                        ReturnStr = Dir + ".aspx?" + Req + "=" + ID;
                    }
                }
                else
                    ReturnStr = "?" + Req + "=" + ID;
            }
            return ReturnStr;
        }

        /// <summary>
        /// 朋友关系
        /// </summary>
        public static string ShowDfe(int Num)
        {
            string dfe = string.Empty;
            if (Num < 300)
            {
                dfe = "一面之识";
            }
            else if (Num >= 300 && Num < 800)
            {
                dfe = "一面之交";
            }
            else if (Num >= 800 && Num < 1500)
            {
                dfe = "你来我往";
            }
            else if (Num >= 1500 && Num < 3000)
            {
                dfe = "君子之交";
            }
            else if (Num >= 3000 && Num < 5000)
            {
                dfe = "莫逆之交";
            }
            else if (Num >= 5000 && Num < 10000)
            {
                dfe = "生死之交";
            }
            else if (Num >= 10000 && Num < 20000)
            {
                dfe = "肝胆相照";
            }
            else if (Num >= 20000)
            {
                dfe = "刎颈之交";
            }
            return dfe;
        }


        public static bool GetHeadLimite(int Num)
        {
            bool fg = true;
            string lStr = GetXMLValue("limitType");
            if (!string.IsNullOrEmpty(lStr))
            {
                try
                {
                    string[] lStrARR = lStr.Split('|');
                    if (lStrARR[Num] != "0")
                    {
                        fg = false;
                    }
                }
                catch
                {
                    fg = true;
                }
            }
            return fg;
        }

        /// <summary>
        /// 取得文件扩展名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>扩展名</returns>
        public static string GetFileEXT(string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return "";
            }
            if (filename.IndexOf(@".") == -1)
            {
                return "";
            }
            int pos = -1;
            if (!(filename.IndexOf(@"\") == -1))
            {
                pos = filename.LastIndexOf(@"\");
            }
            string[] s = filename.Substring(pos + 1).Split('.');
            return s[1];
        }

        /// <summary>
        /// 读JuSite.config取配置文件
        /// </summary>
        public static string GetXMLValue(string Target)
        {
            string XmlPath = HttpContext.Current.Server.MapPath("~/config/base/JuSite.config");
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(XmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNode node = root.SelectSingleNode(Target);
            if (node != null)
            {
                return node.InnerXml;
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 读dyn.config取配置文件
        /// </summary>
        public static string GetDynXMLValue(string Target)
        {
            string XmlPath = HttpContext.Current.Server.MapPath("~/config/base/dyn.config");
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(XmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNode node = root.SelectSingleNode(Target);
            if (node != null)
            {
                return node.InnerText;
            }
            else
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 转换头像路径为缩略路径
        /// </summary>
        /// <param name="orgPicPath">原始路径</param>
        /// <param name="size">缩小级别</param>
        /// <returns></returns>
        public static string GetSmallHeadPic(object orgHeadPicPath, int size)
        {
            if (orgHeadPicPath == null || orgHeadPicPath == DBNull.Value)
                return GetSmallHeadPic((object)"default.jpg", size);
            if (orgHeadPicPath.ToString().Trim() == "")
                return GetSmallHeadPic((object)"default.jpg", size);
            string name = size.ToString();
            Dictionary<string, PicConfigInfo> _portrait = PicConfig.Portrait;
            string rvalue = string.Empty;
            try
            {
                rvalue = (string)orgHeadPicPath;
            }
            catch { }
            if (rvalue.Trim() == string.Empty)
                return string.Empty;
            if (_portrait[name].Directory.EndsWith("/"))
            {
                rvalue = _portrait[name].Directory + rvalue;
            }
            else
            {
                rvalue = _portrait[name].Directory + "/" + rvalue;
            }
            if (rvalue.StartsWith("/"))
            {
                return rootDir + rvalue;
            }
            if (rvalue.StartsWith("http"))
            {
                return rvalue;
            }
            return rootDir + "/" + rvalue;
        }
        /// <summary>
        /// 取得原始头像路径
        /// </summary>
        /// <param name="filename">文件名称</param>
        /// <returns></returns>
        public static string GetOrgHeadPic(string filename)
        {
            if (string.IsNullOrEmpty(filename) || filename.Trim() == "")
                return GetOrgHeadPic("default.jpg");
            string dir = "";
            dir += PicConfig.ProtraitServer + "/";
            dir += PicConfig.ProtraitRoot;
            if (dir.StartsWith("~/"))
            {
                dir = dir.Substring(2);
            }
            string rvalue = filename;
            rvalue = dir + "/" + filename;
            if (rvalue.StartsWith("http") || rvalue.StartsWith("/"))
            {
                return rvalue;
            }
            return rootDir + "/" + rvalue;
        }
        /// <summary>
        /// 取得原始照片路径
        /// </summary>
        /// <param name="filename">文件名称</param>
        /// <returns></returns>
        static public string GetOrgPic(string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return GetOrgPic("default.jpg");
            }
            string dir = string.Empty;
            dir += PicConfig.PhotoServer + "/";
            dir += PicConfig.PhotoRoot;
            string rvalue = filename;
            if (dir.StartsWith("~/"))
            {
                dir = dir.Substring(2);
            }
            rvalue = dir + "/" + filename;
            if (rvalue.StartsWith("http") || rvalue.StartsWith("/"))
            {
                return rvalue;
            }
            return rootDir + "/" + rvalue;
        }
        /// <summary>
        /// 转换照片路径为缩略图路径
        /// </summary>
        /// <param name="orgPicPath">原始路径</param>
        /// <param name="name">缩小级别</param>
        /// <returns></returns>
        static public string GetSmallPic(string orgPicPath, int size)
        {
            if (string.IsNullOrEmpty(orgPicPath) || orgPicPath.Trim() == "")
                return GetSmallPic("default.jpg", size);
            string name = size.ToString();
            Dictionary<string, PicConfigInfo> _photo = PicConfig.Photo;
            if (string.IsNullOrEmpty(orgPicPath))
            {
                return "";
            }
            if (orgPicPath.StartsWith("" + rootDir + "/template/" + JuSNS.Config.UiConfig.SkinStyle + "/images"))
            {
                return orgPicPath.Substring(0);
            }
            string rvalue = orgPicPath;
            if (_photo[name].Directory.EndsWith("/"))
            {
                rvalue = _photo[name].Directory + rvalue;
            }
            else
            {
                rvalue = _photo[name].Directory + "/" + rvalue;
            }
            if (rvalue.StartsWith("http") || rvalue.StartsWith("/"))
            {
                return rvalue;
            }
            return rootDir + "/" + rvalue;
        }
        /// <summary>
        /// 取得群组头像
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="n">大小级别</param>
        /// <returns></returns>
        static public string GetGroupHead(object filename, int n)
        {
            string defaultImg = "" + rootDir + "/template/" + JuSNS.Config.UiConfig.SkinStyle + "/images/000.jpg";
            string name = string.Empty;
            if (filename == DBNull.Value || filename == null)
            {
                return defaultImg;
            }
            name = filename.ToString();
            if (string.IsNullOrEmpty(name))
            {
                return defaultImg;
            }
            Dictionary<string, PicConfigInfo> config = PicConfig.GroupHead;
            string path = rootDir + "/" + config[n.ToString()].Directory + "/" + filename;
            return path;
        }
        /// <summary>
        /// 取得用户ID,未验证是否合法
        /// </summary>
        /// <returns></returns>
        static public int GetUserID()
        {
            int UserID = 0;
            HttpCookie cookieToken = HttpContext.Current.Request.Cookies["SNSUserPassPort"];
            if (cookieToken == null || cookieToken["token"] == null || cookieToken["token"] == "")
                return UserID;
            string userCookie = cookieToken["token"];
            string desstr = DES.Decrypt(userCookie, SecretConfig.UserKey, SecretConfig.UserIV);
            string[] userInfo = desstr.Split(SecretConfig.UserSeparator);
            UserID = int.Parse(userInfo[0]);
            return UserID;
        }
        /// <summary>
        /// 取得appIcon
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        static public string GetAppIcon(string filename)
        {
            string str = string.Empty;
            str = rootDir + "/" + JuSNS.Config.PicConfig.AppDir + "/" + filename;
            if (JuSNS.Config.PicConfig.AppServer == "~" || JuSNS.Config.PicConfig.AppServer ==string.Empty)
            {
                return str;
            }
            Uri uri = new Uri(JuSNS.Config.PicConfig.AppServer);
            str = "http://" + uri.Host + str;
            return str;
        }

        /// <summary>
        /// 取得空间连接
        /// </summary>
        /// <param name="userid">用户ID</param>
        /// <returns></returns>
        static public string GetSpaceLink(int userid)
        {
            return rootDir + "/user/" + JuSNS.Common.Public.URLWrite("", "r", userid.ToString());
        }
        /// <summary>
        /// 取得app链接
        /// </summary>
        /// <param name="appname"></param>
        /// <returns></returns>
        static public string GetAppUrl(string appname)
        {
            return "/" + rootDir + "/home/" + appname;
        }
        /// <summary>
        /// 新文件名
        /// </summary>
        /// <returns></returns>
        static public string GetNewFileName()
        {
            return DateTime.Now.ToString("yyyyMMddhhmmss") + Common.Rand.Str(5);
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="pf">文件</param>
        /// <param name="avalExt">允许的扩展名</param>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
        static public void UpdateIcon(HttpPostedFile pf, string avalExt, out string filename)
        {
            filename = GetNewFileName();
            string orgFileName = pf.FileName;
            string ext = pf.FileName.Substring(pf.FileName.LastIndexOf('.') + 1);
            bool aval = false;
            foreach (string s in avalExt.Split(','))
            {
                if (ext.ToLower() == s.ToLower())
                {
                    aval = true;
                    break;
                }
            }
            if (aval == false)
            {
                filename = "err";
                return;
            }
            filename = filename + "." + ext ;
            string filepath = HttpContext.Current.Server.MapPath(rootDir + "/" + JuSNS.Config.PicConfig.AppDir + "/" + filename);

            pf.SaveAs(filepath);
        }
    }
}
