<?php
function showMessage($urlstr,$title = 'Power by QQ:16953292,Msn:xufyong@gmail.com,Tel:13628392015')
{ 
	$tS = '<html xmlns="http://www.w3.org/1999/xhtml">';
    $tS .= '<head>';
    $tS .= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
    $tS .= '<title>'.$title.'</title>';
    $tS .= '</head>';
    $tS .= '<body>';
    $tS .= '<div style="float:left;margin:100px 50px 50px 50px; padding:10px 10px 10px 10px;width:516px;border-bottom:1px solid #cbcbcb;border-left:1px solid #cbcbcb;border-top:1px solid #cbcbcb;border-right:1px solid #cbcbcb;font-size:12px">';
    $tS .= $urlstr;
    $tS .= '</div>';
    $tS .= '</body>';
    $tS .= '</html>';
    return $tS;
} 

function clean_html($string){
	$search = array ("'<script[^>]*?>.*?</script>'si",
				 "'<[\/\!]*?[^<>]*?>'si",
				 "'([\r\n])[\s]+'",
				 "'&(quot|#34);'i",
				 "'&(amp|#38);'i",
				 "'&(lt|#60);'i",
				 "'&(gt|#62);'i",
				 "'&(nbsp|#160);'i",
				 "'&(iexcl|#161);'i",
				 "'&(cent|#162);'i",
				 "'&(pound|#163);'i",
				 "'&(copy|#169);'i",
				 "'&#(\d+);'e",
				 "'\"'si",
				 "'\''si"); 
	$replace = array ("",
					  "",
					  "",
					  "",
					  "",
					  "",
					  "",
					  "",
					  "",
					  "",
					  "",
					  "",
					  "",
					  "“",
					  "‘");

	$string = preg_replace ($search, $replace, $string);
	return $string;
}

//分页
class ShowPage {  
    var $PageSize; //每页显示的记录数 
    var $Total; //记录总数  
    var $LinkAry; //Url参数数组，对于复合条件查询分页显示情况非常好用 
	var $PHP_SELF;
    
    //取得总页数
    function PageCount() {
        $TotalPage = ($this->Total % $this->PageSize == 0) ? floor($this->Total / $this->PageSize) : floor($this->Total / $this->PageSize)+1;
        return $TotalPage;
    }
    //取得当前页
    function PageNum() {
        $page = ((isset($_GET["page"])) != '') ? $_GET["page"] : $page = 1; 
        if (isset($_POST["page"])) $page = $_POST["page"];
        if ($page < 1 ) $page =1;
        return $page;
    }
    //查询语句定位指针        
    function OffSet() {
        if ($this->PageNum() > $this->PageCount()) {
        //$this->PageNum = $this->PageCount();
        $pagemin = max(0,$this->Total - $this->PageSize - 1);
        }else if ($this->PageNum() == 1){
         $pagemin = 0;
        }else {
         $pagemin = min($this->Total - 1,$this->PageSize * ($this->PageNum() - 1));
        }
        return $pagemin . "," . $this->PageSize;
     }
    //定位首页        
    function FristPage() {
        global $Aconf;
        $LinkAry   =  $this->Url($this->LinkAry);
        if($Aconf["rewrite"]){ 
            $A = explode(".",$this->PHP_SELF);
            $preFile = $A[0]; 

            $strurl = ' <a href="'.$preFile.$LinkAry.'-1.html">首页</a> ';
            $Frist = ($this->PageNum() <= 1) ? "" : $strurl;
        }else{ 
            $Frist = ($this->PageNum() <= 1) ? "" : "<a href=\"?page=1".$this->Url($this->LinkAry)."\">首页</a> ";
        }
        return $Frist;
    }
//定位上一页
    function PrePage() {
        global $Aconf;

        $prepage=$this->PageNum() - 1;
        $LinkAry   =  $this->Url($this->LinkAry);
        if($Aconf["rewrite"]){ 
            $A = explode(".",$this->PHP_SELF);
            $preFile = $A[0]; 
            $strurl = ' <a href="'.$preFile.$LinkAry.'-'.$prepage.'.html">上一页</a> ';
            $Previous = ($this->PageNum() >= 2) ? $strurl : "";
        }else{ 
            $Previous = ($this->PageNum() >= 2) ? " <a href=\"?page=".$prepage.$this->Url($this->LinkAry)."\">上一页</a> " : "";
        }
        return $Previous;
    }
//定位下一页
    function NextPage() {
        global $Aconf;
        $nextpage = $this->PageNum() + 1;
        $LinkAry   =  $this->Url($this->LinkAry);
        if($Aconf["rewrite"]){ 
            $A = explode(".",$this->PHP_SELF);
            $preFile = $A[0]; 
            $strurl = ' <a href="'.$preFile.$LinkAry.'-'.$nextpage.'.html">下一页</a> ';
            $Next = ($this->PageNum() <= $this->PageCount()-1) ? $strurl : "";
        }else{
             $Next = ($this->PageNum() <= $this->PageCount()-1) ? " <a href=\"?page=".$nextpage.$this->Url($this->LinkAry)."\">下一页</a> " : "";
        }
        return $Next;
    }
//定位最后一页
    function LastPage() {
        global $Aconf;
        $LinkAry   =  $this->Url($this->LinkAry);
        if($Aconf["rewrite"]){ 
            $A = explode(".",$this->PHP_SELF); 
            $preFile = $A[0]; 
            $strurl = ' <a href="'.$preFile.$LinkAry.'-'.$this->PageCount().'.html">尾页</a> ';
            $Last = ($this->PageNum() >= $this->PageCount()) ?" ": $strurl;
        }else{
            $Last = ($this->PageNum() >= $this->PageCount()) ? " " : " <a href=\"?page=".$this->PageCount().$this->Url($this->LinkAry)."\">尾页</a> ";
        }
        return $Last;
    }
//下拉跳转页面
    function JumpPage() {
        $Jump = " 当前第 <b>".$this->PageNum()."</b> 页 共 <b>".$this->PageCount()."</b> 页 跳到 <select name=page onchange=\"javascript:location=this.options[this.selectedIndex].value;\">";
        for ($i=1; $i<=$this->PageCount(); $i++) {
        if ($i==$this->PageNum())
            $Jump .= "<option value=\"?page=".$i.$this->Url($this->LinkAry)."\" selected>$i</option>";
        else 
            $Jump .="<option value=\"?page=".$i.$this->Url($this->LinkAry)."\">$i</option> ";    
        }
        $Jump .= "</select> 页 <b>[".$this->PageSize."条/页]共".$this->Total."条</b>";
        return $Jump;
    }
    function JumpPage2() {
        $Jump = "共 <b>".$this->PageCount()."</b> 页 转到 <select name=page onchange=\"javascript:location=this.options[this.selectedIndex].value;\">";
        for ($i=1; $i<=$this->PageCount(); $i++) {
        if ($i==$this->PageNum())
            $Jump .= "<option value=\"?page=".$i.$this->Url($this->LinkAry)."\" selected>$i</option>";
        else 
            $Jump .="<option value=\"?page=".$i.$this->Url($this->LinkAry)."\">$i</option> ";    
        }
     $Jump .= "</select>";
        return $Jump;
    }
    function JumpPage_num($num = 10) {
        global $Aconf;
        //$num 翻页偏移量
        $nowpage  = $this->PageNum();
        $totalpage = $this->PageCount();
        $totalnum  = $this->Total;
        $PageSize =  $this->PageSize;
        $LinkAry   =  $this->Url($this->LinkAry);
        if($Aconf["rewrite"]){ 
            $A = explode(".",$this->PHP_SELF);
            $preFile = $A[0]; 
        }
        
        if($num > 0 ){
            $j = ceil($nowpage /  $num);
        }else{
            return false;
        }

        $num_satrt = ($j - 1) * $num;
        $num_satrt = (!$num_satrt)?1:$num_satrt;

        $num_end = $j * $num;
        $num_end = ($num_end>$totalpage)?$totalpage:$num_end;
 
        $strurl = '';
        for ($i=$num_satrt; $i<=$num_end; $i++) 
        {
              if($nowpage == $i) {
                  if($Aconf["rewrite"]){
                        $strurl .= ' <A HREF="'.$preFile.$LinkAry.'-'.$i.'.html" style="background-color:#FFCC00">'.$i.'</A> ';
                  }else{
                        $strurl .= ' <A HREF="'.$this->PHP_SELF.'?page='.$i.$LinkAry.'" style="background-color:#FFCC00">'.$i.'</A> ';
                  }
              } else {
                  if($Aconf["rewrite"]){
                        $strurl .= ' <A HREF="'.$preFile.$LinkAry.'-'.$i.'.html">'.$i.'</A> ';
                  }else{
                        $strurl .= ' <A HREF="'.$this->PHP_SELF.'?page='.$i.$LinkAry.'">'.$i.'</A> ';
                  }
              }
        }
        return $this->FristPage().' '.$this->PrePage().$strurl.' '.$this->NextPage().' '.$this->LastPage().' <a href="#" style="color:#CCC" title="[当前第'.$this->PageNum().'页,每页'.$this->PageSize.'条,共'.$this->Total.'条"]>共<b>'.$this->PageCount().'</b>页</a>';
    }    
//URL参数处理
    function Url($ary) {
        global $Aconf;
        $Linkstr = "";
        if (count($ary) > 0) {
             if($Aconf["rewrite"]){ 
                foreach ($ary as $key => $val) {
                    $Linkstr .= "-".$val;
                }
             }else{
                foreach ($ary as $key => $val) {
                    $Linkstr .= "&".$key."=".$val;
                }
             }
        }
        return $Linkstr;
    }
   //生成导航条
    function ShowLink() {
        return $this->FristPage().$this->PrePage().$this->NextPage().$this->LastPage().$this->JumpPage();
    }   
    function ShowLink2() {
        return $this->JumpPage2();
    }    
    function ShowLink_num() {
        return $this->JumpPage_num();
    }     
}
//end  

/**
 * 获得用户的真实IP地址
 *
 * @access  public
 * @return  string
 */
function real_ip() {
    static $realip = NULL; 
    if ($realip !== NULL) {
        return $realip;
    } 
    if (isset($_SERVER)) {
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            $arr = explode(',', $_SERVER["HTTP_X_FORWARDED_FOR"]); 
            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip) {
                $ip = trim($ip); 
                if ($ip != 'unknown') {
                    $realip = $ip; 
                    break;
                }
            }
        } elseif (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $realip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            if (isset($_SERVER["REMOTE_ADDR"])) {
                $realip = $_SERVER["REMOTE_ADDR"];
            }  else {
                $realip = '0.0.0.0';
            }
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_CLIENT_IP')) {
            $realip = getenv('HTTP_CLIENT_IP');
        } else {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0'; 
    return $realip;
}

function gzip_enabled() {
    static $enabled_gzip = NULL; 
    if ($enabled_gzip === NULL) {
        $enabled_gzip = ( function_exists('ob_gzhandler'));
    } 
    return $enabled_gzip;
}

 
 /**
 * 用于后台
 * 生成编辑器
 * @param   string  input_name  输入框名称
 * @param   string  input_value 输入框值
 */
function create_html_ckreplace($input_name)
{
	$ckeditor = new CKEditor( ) ;
	$ckeditor->basePath	= '../includes/ckeditor/' ;
	//CKFinder::SetupCKEditor( $ckeditor,"../includes/ckfinder/") ;
	$FCKeditor = $ckeditor->replace($input_name);
    return $FCKeditor;
}
function create_html_ck($input_name, $input_value = '',$config='', $events='')
{
	/*
		$config["toolbar"] = array( array( 'Source', '-', 'Bold', 'Italic', 'Underline', 'Strike' ), array( 'Image', 'Link', 'Unlink', 'Anchor' ) );
		$config["toolbar"] = 'Basic'; 
		$config.toolbarStartupExpanded = true; 
	*/
	 $config["width"] = 850;
	$config["height"] = 550;
	$ckeditor = new CKEditor( ) ;
	$ckeditor->basePath	= '../includes/ckeditor/' ;
	//CKFinder::SetupCKEditor( $ckeditor,"../includes/ckfinder/") ; 
	$FCKeditor = $ckeditor->editor($input_name, $input_value,$config, $events);
    return $FCKeditor;
}
 
 
/**
 * 用于前台
 * 生成编辑器
 * @param   string  input_name  输入框名称
 * @param   string  input_value 输入框值
 */
function create_html_pre($input_name, $input_value = '') {
    global $smarty;
	$config["toolbar"] = array(); 
	$config["width"] = 500;
	$config["height"] = 150;
	$config["uiColor"]='#F5F5F5'; 
	$config["forcePasteAsPlainText"] =true ;
	$config["entities"] = false;
	$config["toolbarStartupExpanded"] = false; 
	$config["resize_enabled"]  = false; 
	$config["toolbarCanCollapse"]  = false;   

	$ckeditor = new CKEditor( ) ;
	$ckeditor->basePath	= 'includes/ckeditor/' ;
	$FCKeditor = $ckeditor->editor($input_name, $input_value,$config); 
	$smarty->assign('FCKeditor', $FCKeditor ); 
}

/**
 * 获得指定页面的动态内容
 *
 * @access  public
 * @param   string  $tmp    模板名称
 * @return  void
 */
function assign_dynamic($url_type)
{
	  global $smarty,$Aconf; 
	  //$smarty->assign('header_title',  $Aconf["header_title"].' - '.$Aconf["web_title"] );

      $smarty->assign('list_news' , "test list_newsssssssssssss<br/>");
}


/**
 * 截取UTF-8编码下字符串的函数
 *
 * @param   string      $str        被截取的字符串
 * @param   int         $length     截取的长度
 * @param   bool        $append     是否附加省略号
 *
 * @return  string
 */
function sub_str($str, $length = 0, $append = true)
{
    $str = trim($str);
    $strlength = strlen($str);

    if ($length == 0 || $length >= $strlength)
    {
        return $str;
    }
    elseif ($length < 0)
    {
        $length = $strlength + $length;
        if ($length < 0)
        {
            $length = $strlength;
        }
    }

    if (function_exists('mb_substr'))
    {
        $newstr = mb_substr($str, 0, $length, 'UTF-8');
    }
    elseif (function_exists('iconv_substr'))
    {
        $newstr = iconv_substr($str, 0, $length, 'UTF-8');
    }
    else
    {
        $newstr = trim_right(substr($str, 0, $length));
    }

    if ($append && $str != $newstr)
    {
        $newstr .= '...';
    }

    return $newstr;
}

/**
 * 去除字符串右侧可能出现的乱码
 *
 * @param   string      $str        字符串
 *
 * @return  string
 */
function trim_right($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]+/', '', $str)) % 3;

    if ($length > 0)
    {
        $str = substr($str, 0, 0 - $length);
    }

    return $str;
}

/**
 * 计算字符串的长度（汉字按照两个字符计算）
 *
 * @param   string      $str        字符串
 *
 * @return  int
 */
function str_len($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));

    if ($length)
    {
        return strlen($str) - $length + intval($length / 3) * 2;
    }
    else
    {
        return strlen($str);
    }
}
/**
 * 验证输入的邮件地址是否合法
 *
 * @access  public
 * @param   string      $email      需要验证的邮件地址
 *
 * @return bool
 */
function is_email($user_email)
{
	$chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
	if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false)
     {
        if (preg_match($chars, $user_email))
        {
            return true;
        } else
        {
            return false;
        }
    } 
	else
    {
       return false;
    }
}

function gmtime()
{
    return time();
}
function local_strtotime($str)
{
	$time = strtotime($str);
    return $time;

}
/**
 * 文件或目录权限检查函数
 *
 * @access          public
 * @param           string  $file_path   文件路径
 * @param           bool    $rename_prv  是否在检查修改权限时检查执行rename()函数的权限
 *
 * @return          int     返回值的取值范围为{0 <= x <= 15}，每个值表示的含义可由四位二进制数组合推出。
 *                          返回值在二进制计数法中，四位由高到低分别代表
 *                          可执行rename()函数权限、可对文件追加内容权限、可写入文件权限、可读取文件权限。
 */
function file_mode_info($file_path)
{
    /* 如果不存在，则不可读、不可写、不可改 */
    if (!file_exists($file_path))
    {
        return false;
    }

    $mark = 0;

    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
    {
        /* 测试文件 */
        $test_file = $file_path . '/cf_test.txt';

        /* 如果是目录 */
        if (is_dir($file_path))
        {
            /* 检查目录是否可读 */
            $dir = @opendir($file_path);
            if ($dir === false)
            {
                return $mark; //如果目录打开失败，直接返回目录不可修改、不可写、不可读
            }
            if (@readdir($dir) !== false)
            {
                $mark ^= 1; //目录可读 001，目录不可读 000
            }
            @closedir($dir);

            /* 检查目录是否可写 */
            $fp = @fopen($test_file, 'wb');
            if ($fp === false)
            {
                return $mark; //如果目录中的文件创建失败，返回不可写。
            }
            if (@fwrite($fp, 'directory access testing.') !== false)
            {
                $mark ^= 2; //目录可写可读011，目录可写不可读 010
            }
            @fclose($fp);

            @unlink($test_file);

            /* 检查目录是否可修改 */
            $fp = @fopen($test_file, 'ab+');
            if ($fp === false)
            {
                return $mark;
            }
            if (@fwrite($fp, "modify test.\r\n") !== false)
            {
                $mark ^= 4;
            }
            @fclose($fp);

            /* 检查目录下是否有执行rename()函数的权限 */
            if (@rename($test_file, $test_file) !== false)
            {
                $mark ^= 8;
            }
            @unlink($test_file);
        }
        /* 如果是文件 */
        elseif (is_file($file_path))
        {
            /* 以读方式打开 */
            $fp = @fopen($file_path, 'rb');
            if ($fp)
            {
                $mark ^= 1; //可读 001
            }
            @fclose($fp);

            /* 试着修改文件 */
            $fp = @fopen($file_path, 'ab+');
            if ($fp && @fwrite($fp, '') !== false)
            {
                $mark ^= 6; //可修改可写可读 111，不可修改可写可读011...
            }
            @fclose($fp);

            /* 检查目录下是否有执行rename()函数的权限 */
            if (@rename($test_file, $test_file) !== false)
            {
                $mark ^= 8;
            }
        }
    }
    else
    {
        if (@is_readable($file_path))
        {
            $mark ^= 1;
        }

        if (@is_writable($file_path))
        {
            $mark ^= 14;
        }
    }

    return $mark;
} 
//字符类型判断 是否为Utf8
function isUTF8($str)
{
	 $length=strlen($str);
	 for($i=0;$i<$length;$i++){
	  $high=ord($str{$i});
	  if(($high==0xC0)||($high==0xC1)){
	   return false;
	  }elseif($high<0x80){
	   continue;
	  }elseif($high<0xC0){
	   return false;
	  }elseif($high<0xE0){
	   if(++$i>=$length)
		return true;
	   elseif(($str{$i}&"\xC0")=="\x80")
		continue;
	  }elseif($high<0xF0){
	   if(++$i>=$length){
		return true;
	   }elseif(($str{$i}&"\xC0")=="\x80"){
		if(++$i>=$length)
		 return true;
		elseif(($str{$i}&"\xC0")=="\x80")
		 continue;
	   }
	  }elseif($high<0xF5){
	   if(++$i>=$length){
		return true;
	   }elseif(($str{$i}&"\xC0")=="\x80"){
		if(++$i>=$length){
		 return true;
		}elseif(($str{$i}&"\xC0")=="\x80"){
		 if(++$i>=$length)
		  return true;
		 elseif(($str{$i}&"\xC0")=="\x80")
		  continue;
		}
	   }
	  }
	  return false;
	 }
	 return true;
} 
/* 
 * js escape 编码，的php->utf8 方法 
 * UnEscapeToUtf8() getUtf8($value= " ")
 */
function UnEscapeToUtf8($ar)
{ 
    $c = "";
    foreach($ar as $val)
	{ 
        $val = intval(substr($val,2),16);
        if ($val < 0x7F){ // 0000-007F
            $c .= chr($val);
        } elseif ($val < 0x800) { // 0080-0800
            $c .= chr(0xC0 | ($val / 64));
            $c .= chr(0x80 | ($val % 64));
        } else { // 0800-FFFF
            $c .= chr(0xE0 | (($val / 64) / 64));
            $c .= chr(0x80 | (($val / 64) % 64));
            $c .= chr(0x80 | ($val % 64));
        }
     } 
     return   $c; 
} 

function getUtf8($value= " ")
{ 
    $text =  preg_replace_callback( "/%u[0-9A-Za-z]{4}/ ","UnEscapeToUtf8",$value); 
    return   urldecode($text); 
}

/**
 * 检查目标文件夹是否存在，如果不存在则自动创建该目录
 *
 * @access      public
 * @param       string      folder     目录路径。不能使用相对于网站根目录的URL
 *
 * @return      bool
 */
function make_dir($folder)
{
    $reval = false;

    if (!file_exists($folder))
    {
        /* 如果目录不存在则尝试创建该目录 */
        @umask(0);

        /* 将目录路径拆分成数组 */
        preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);

        /* 如果第一个字符为/则当作物理路径处理 */
        $base = ($atmp[0][0] == '/') ? '/' : '';

        /* 遍历包含路径信息的数组 */
        foreach ($atmp[1] AS $val)
        {
            if ('' != $val)
            {
                $base .= $val;

                if ('..' == $val || '.' == $val)
                {
                    /* 如果目录为.或者..则直接补/继续下一个循环 */
                    $base .= '/';

                    continue;
                }
            }
            else
            {
                continue;
            }

            $base .= '/';

            if (!file_exists($base))
            {
                /* 尝试创建目录，如果创建失败则继续循环 */
                if (@mkdir($base, 0777))
                {
                    @chmod($base, 0777);
                    $reval = true;
                }
            }
        }
    }
    else
    {
        /* 路径已经存在。返回该路径是不是一个目录 */
        $reval = is_dir($folder);
    }

    clearstatcache();

    return $reval;
}


/* 复制目录 
    $target_dir = ROOT_PATH .'templates/user_themes/'.$_SESSION[$un_domain_id];
    $source_dir = ROOT_PATH.'themes/'.$Aconf["template"].'/';
   结果：文件及目录属性 0777
*/
function dir_copy($source_dir,$target_dir)
{
	if(!is_dir($source_dir))  
		return false;

	if(!is_dir($target_dir))
   {
	   if(!make_dir($target_dir, 0777))
	   {
		   return false;
	   }
   }

   if ($dh = opendir($source_dir))
  {
		while (($file = readdir($dh)) !== false )
		{
			 if(filetype($source_dir . $file) != 'dir')
			{
				  copy($source_dir.$file,$target_dir.'/'.$file);
				  @chmod($target_dir.'/'.$file, 0777);
			 }
			 else if($file != '.' && $file != '..')
			{
				 $target_img_dir = $target_dir.'/'.$file;
				 $source_img_dir = $source_dir.$file.'/';
				 dir_copy($source_img_dir,$target_img_dir);
			 
			}
		}
		closedir($dh);
   }
   return true;
}


/**
 * 递归方式的对变量中的特殊字符进行转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function addslashes_deep($value)
{
    if (empty($value))
    {
        return $value;
    }
    else
    {
        return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
    }
}

/**
 *  清除指定后缀的模板缓存或编译文件
 *
 * @access  public
 * @param  bool       $is_cache  是否清除缓存还是清出编译文件
 * @param  string     $ext       需要删除的文件名，不包含后缀
 *
 * @return int        返回清除的文件个数
 */
function clear_tpl_files($is_cache = true, $ext = '')
{
    global $Aconf;
    $dirs = array();
    if ($is_cache)
    {
        $dirs[] = ROOT_PATH . 'templates/caches/'.$Aconf["domain_id"].'/';
    }
    else
    {
        $dirs[] = ROOT_PATH . 'templates/compiled/'.$Aconf["domain_id"].'/';
        $dirs[] = ROOT_PATH . 'templates/compiled/admin/'.$Aconf["domain_id"].'/';
    }

    $str_len = strlen($ext);
    $count   = 0;

    foreach ($dirs AS $dir)
    {
        $folder = @opendir($dir);

        if ($folder == false)
        {
            continue;
        }

        while ($file = readdir($folder))
        {
            if ($file == '.' || $file == '..' || $file == 'index.htm' || $file == 'index.html')
            {
                continue;
            }
            if (is_file($dir . $file))
            {
                /* 如果有文件名则判断是否匹配 */
                $pos = ($is_cache) ? strrpos($file, '_') : strrpos($file, '.');

                if ($str_len > 0 && $pos !== false)
                {
                    $ext_str = substr($file, 0, $pos);

                    if ($ext_str == $ext)
                    {
                        if (@unlink($dir . $file))
                        {
                            $count++;
                        }
                    }
                }
                else
                {
                    if (@unlink($dir . $file))
                    {
                        $count++;
                    }
                }
            }
        }
        closedir($folder);
    }

    return $count;
}

/**
 * 清除模版编译文件
 *
 * @access  public
 * @param   mix     $ext    模版文件名， 不包含后缀
 * @return  void
 */
function clear_compiled_files($ext = null)
{
    return clear_tpl_files(false, $ext);
}

/**
 * 清除缓存文件
 *
 * @access  public
 * @param   mix     $ext    模版文件名， 不包含后缀
 * @return  void
 */
function clear_cache_files($ext = null)
{
    return clear_tpl_files(true, $ext);
}

/**
 * 清除模版编译和缓存文件
 *
 * @access  public
 * @param   mix     $ext    模版文件名后缀
 * @return  void
 */
function clear_all_files($ext = null)
{
    return clear_tpl_files(false, $ext) + clear_tpl_files(true,  $ext);
}
 
/* 
取当前分类及所有的下级显示分类 
$id        号
$db_table  数据表名
$idtype    id字段名
$grand     true取得所有下级分类 false只取得一级分类
return  id字串 1,2,3
*/
function next_node_all($id,$db_table,$idtype="acid",$grand=true) {
   global $oPub;
   $sql = "SELECT next_node FROM ".$db_table." where ".$idtype." ='".$id."' AND ifshow = 1";
   $next_node = $oPub->getOne($sql);
   $Agrad = explode(',',$next_node);
   $strID = '';
   if(count($Agrad) > 0 ) {
		while( @list( $k, $v ) = @each( $Agrad ) ) {
			if (!$v) {
			  break;
			}

			$sql = "SELECT ".$idtype.",next_node FROM ".$db_table." where ".$idtype." ='".$v."' AND ifshow = 1";
			$Anorm = $oPub->selectrow($sql);
			if( $Anorm["$idtype"] > 0) {
				$strID  .= ','.$Anorm["$idtype"];
				if($grand) {
				   $strID .= next_node_all($Anorm["$idtype"],$db_table,$idtype,$grand);
				} 
			}
		} 
	} 
	return $strID == ''?false:$strID;
}

/* 
取当前分类的所有前置分类
$fid        当前分类的id号
$db_table  数据表名
$idtype    id字段名
return  id字串 1,2,3  (以顶级->一级->二级方式排序)
*/
function pre_node_orders($fid,$db_table,$idtype="acid")
{
	global $oPub; 
	$sql = "SELECT ".$idtype.",fid FROM ".$db_table." where ".$idtype." = '".$fid."'"; 
	$Anorm = $oPub->selectrow($sql);
	if( $Anorm["fid"] > 0)
	{ 
		return pre_node_orders($Anorm["fid"],$db_table,$idtype).','.$Anorm[$idtype];
	}else{
		return  $Anorm[$idtype];
	}
}
/* 
取当前分类的所有前置分类 
$fid       当前分类的父id号
$db_table  数据表名
$idtype    id字段名
$grand     true取得所有下级分类 false只取得一级分类
return  id字串 1,2,3
*/
function pre_node($fid,$db_table,$idtype="acid",$navefile='articles.php',$grand=true,$strid="id")
{
   global $oPub,$Aconf;
   if($fid > 0 ){
        $sql = "SELECT ".$idtype.",fid,name FROM ".$db_table." where ".$idtype." = '".$fid."'";
        $Anorm = $oPub->selectrow($sql);
		if( $Anorm["name"] != '') {
			if($Aconf["rewrite"]){
				$Atmp = explode(".",$navefile); 
				$href = $Atmp[0].'-'.$Anorm[$idtype].'-0.html'; 
			}else{
				if(strpos($navefile,"?")) {
					$href = $navefile.'&'.$strid.'='.$Anorm[$idtype];
				}else{
					$href = $navefile.'?'.$strid.'='.$Anorm[$idtype];
				}
			}
			$Str = ' <a href="'.$href.'">'.$Anorm["name"].'</a>'; 
			if($grand) {
                  $Stropt = pre_node($Anorm["fid"],$db_table,$idtype,$navefile,$grand).'> '.$Str;
			} else {
                  $Stropt = $Str;
			}
		}
	} else {
        $Stropt = '';
	}
	return $Stropt;
}
/* 
取当前分类的顶级分类 
$fid        对应的fid值
$db_table  数据表名
$idtype    id字段名 

return     id 顶级分类id
*/
function pre_node_top($fid,$db_table,$idtype="acid")
{
     global $oPub;
     $sql = "SELECT ".$idtype.",fid  FROM ".$db_table." where ".$idtype." = '".$fid."'";
     $row = $oPub->selectrow($sql);
	 if( $row["fid"] > 0 ) {
         pre_node_top($row["fid"],$db_table,$idtype);
	 } else {
         return $row[$idtype];
	 }	
}
/* 得到文章列表 */
function articles_list( $orderby='arid', $limit='',$acid='',$substr=26,$where_ext='') {
	global $oPub,$pre,$_SESSION,$un_domain_id,$Aconf;
	$GlobstrAcid_fun = (!empty($acid))?" AND a.acid in(".$acid.") ":'';
	$GlobstrAcid_fun = (!empty($where_ext))?" and ".$where_ext." ":$GlobstrAcid_fun;
	$limit = empty($limit)?'':' limit '.$limit;
    $sql = "SELECT a.arid,a.acid,a.name,a.subname,a.otherurl,a.colors,a.arti_date,a.dateadd,a.comms,a.min_thumb,a.arti_thumb,a.edit_comm,b.cltion      
        FROM ".$pre."artitxt as a,".$pre."article as b 
		WHERE a.arid=b.arid and  a.states = 0 ".$GlobstrAcid_fun."  
		and a.domain_id=".$_SESSION[$un_domain_id]. 
        " ORDER BY a.".$orderby." desc,a.arti_date desc ".$limit;
	$rowarticles = $oPub->select($sql);
	if($rowarticles)
    foreach ($rowarticles AS $key=>$val) {
		$subname = sub_str($val["subname"],$substr,false);
		if($val["colors"]){
		    $rowarticles[$key]["subname"]       =  '<span style="color:'.$val["colors"].'">'.$subname.'</span>'; 
		}else{
            $rowarticles[$key]["subname"] = $subname;
		}
		$rowarticles[$key]["name"]       =  $val["name"];

		if($val["otherurl"]) {
             $rowarticles[$key]["article_url"] =$val["otherurl"];
		}else{
			if($Aconf["rewrite"]){
				$rowarticles[$key]["article_url"] = 'article-'.$val["arid"].'-0.html';
			}else{
				$rowarticles[$key]["article_url"] = 'article.php?id='.$val["arid"];
			}
		}

		if(!$val["min_thumb"]){
              $rowarticles[$key]["min_thumb"] = 'images/command/no_imgs.png';
		}

		if(!$val["arti_thumb"]){
              $rowarticles[$key]["arti_thumb"] = 'images/command/no_imgsbig.png';
		}		
		$rowarticles[$key]["edit_comm"] =  $val["edit_comm"]; 
		$rowarticles[$key]["dateadd"]  = ($val["dateadd"])?date("Y年m月d日h:i", $val["dateadd"]):'';
		$rowarticles[$key]["arti_date"]  = ($val["arti_date"])?date("y年n月j日G:i", $val["arti_date"]):''; 

		$sql = "SELECT name FROM ".$pre."articat WHERE acid='".$val["acid"]."'";
		$row = $oPub->getRow($sql);
		$rowarticles[$key]["acname"] = $row["name"];
		if($Aconf["rewrite"]){
			$rowarticles[$key]["acname_url"] = 'articles-'.$val["acid"].'-0.html';
			$rowarticles[$key]["arcomms_url"] = 'acomms-'.$rowarticles[$key]["arid"].'-0.html';
		}else{
			$rowarticles[$key]["acname_url"] = 'articles.php?id='.$val["acid"];
			$rowarticles[$key]["arcomms_url"] = 'acomms.php?id='.$rowarticles[$key]["arid"];
		}
		//关联文章
		if(!empty($val["cltion"])) {
			$strCltion = '';
			$Acltion = explode("{|}",$val["cltion"]);
			$n = 1;
			$AstrCltion = array();
			while( @list( $k, $v) = @each($Acltion) ) {
			   $Akeysname = explode("[|]",$v);
			   if($Akeysname[0]) {
					 $n ++ ;
					 $AstrCltion[$n] = '<A HREF="'.$Akeysname[1].'">'.$Akeysname[0].'</A>';
				}
			}
			if(count($AstrCltion) > 0) { 
				 $rowarticles[$key]["cltion"] =$AstrCltion;
			} else {
				 $rowarticles[$key]["cltion"] = false;
			}
		}
		//关联图库
		$sql = "SELECT thumb_url,filename,descs FROM " . $pre."arti_file WHERE arid = '".$val["arid"]."' limit 3";
		$rowarticles[$key]["img_list"] = $oPub->select($sql); 

	}
	return $rowarticles;
}
/* 得到产品列表 */
function products_list( $orderby='prid', $limit='',$pcid='') {

	global $oPub,$pre,$_SESSION,$un_domain_id,$Aconf;
	$GlobstrPcid_fun = !empty($pcid)?" and a.pcid in(".$pcid.") ":''; 
	$limit = empty($limit)?'':' limit '.$limit; 
    $sql = "SELECT a.prid,a.pcid,a.name,a.shop_number,a.shop_price,a.s_discount,a.s_dis_exp,a.colors,a.up_date,a.dateadd,a.comms,a.min_thumb,a.shop_thumb FROM ".$pre."producttxt as a   
		WHERE  a.states <> 1 "
		.$GlobstrPcid_fun.
		"AND a.domain_id=".$_SESSION[$un_domain_id]. 
        " ORDER BY a.".$orderby." DESC,up_date desc ". $limit;  
    $rowproduct = $oPub->select($sql);
    if($rowproduct )
    foreach ($rowproduct AS $key=>$val) { 
		if($val["colors"]){
		    $rowproduct[$key]["name"] =  '<span style="color:'.$val["colors"].'">'.$val["name"].'</span>'; 
		} 
		if(!$val["min_thumb"]){
            $rowproduct[$key]["min_thumb"] = 'images/command/no_imgs.png';
		}

		if(!$val["shop_thumb"]){
            $rowproduct[$key]["shop_thumb"] = 'images/command/no_imgsbig.png';
		}	
		
		$rowproduct[$key]["shop_price"] = ($val[shop_price] == '0.00')?'':$val[shop_price];
		$rowproduct[$key]["s_discount"] = ($val[s_discount] == '0.00')?'':$val[s_discount];
        $rowproduct[$key]["dateadd"]  = ($val["dateadd"])?date("Y年m月d日h:i", $val["dateadd"]):'';
		$rowproduct[$key]["up_date"]  = ($val["up_date"] > 0)?date("y年n月j日",$val["up_date"]):'dddddddd';  
        $sql = "SELECT name FROM ".$pre."productcat WHERE pcid=$val[pcid]";
		$row = $oPub->getRow($sql);
		$rowproduct[$key]["pcname"] = $row["name"]; 

		if($Aconf["rewrite"]){
			$rowproduct[$key]["product_url"] = 'product-'.$val[prid].'.html';
			$rowproduct[$key]["pcomms_url"] = 'product_comms-'.$val[prid].'.html';
			$rowproduct[$key]["pcname_url"] = 'products-'.$val[pcid].'-0.html';
		}else{
			$rowproduct[$key]["product_url"] = 'product.php?id='.$val[prid];
			$rowproduct[$key]["pcomms_url"] = 'product_comms.php?id='.$val[prid];
			$rowproduct[$key]["pcname_url"] = 'products.php?id='.$val[pcid];
		} 
    }
	return $rowproduct;
}
/* 得到当前分类名及导航 */
function catname_url($table='articat',$files='articles.php',$filed='acid',$id=0)
{
	 global $oPub,$pre;

	 if(!$id)
		 return false;

		$sql = "SELECT name FROM ".$pre.$table." WHERE ".$filed."=".$id;
		$row = $oPub->getRow($sql);
		$Arow["catname"] = $row["name"];
		$Arow["catname_url"] = $files.'?'.$filed.'='.$id;

		return $Arow;
}  
 /* 判断是否为搜索引擎蜘蛛
 *
 * @access  public
 * @return  string
 */
function is_spider($record = true) {
    static $spider = NULL;                            
    if ($spider !== NULL) {
        return $spider;
    }       
    if (empty($_SERVER["HTTP_USER_AGENT"])) {
        $spider = '';                       
        return '';
    }          
    $searchengine_bot = array(
        'googlebot',
        'mediapartners-google',
        'baiduspider+',
        'msnbot',
        'yodaobot',
        'yahoo! slurp;',
        'yahoo! slurp china;',
        'iaskspider',
        'sogou web spider',
        'sogou push spider'
    );

    $searchengine_name = array(
        'GOOGLE',
        'GOOGLE ADSENSE',
        'BAIDU',
        'MSN',
        'YODAO',
        'YAHOO',
        'Yahoo China',
        'IASK',
        'SOGOU',
        'SOGOU'
    );

    $spider = strtolower($_SERVER["HTTP_USER_AGENT"]);
    foreach ($searchengine_bot AS $key => $value)
    {
        if (strpos($spider, $value) !== false)
        {
            $spider = $searchengine_name[$key];

            if ($record === true)
            {
                //数据库记录,暂无
            }
            return $spider;
        }
    }

    $spider = '';

    return '';
}
 

/**
 * 更新用户SESSION,COOKIE及登录时间、登录次数。
 *
 * @access  public
 * @return  void
 */
function update_user_info()
{
	global $oPub,$pre,$_SESSION;
    if (!$_SESSION["user_id"])
    {
        return false;
    }         

    /* 更新SESSION */
    $sql = 'SELECT u.last_login, u.last_ip,u.visit_count'.
            ' FROM ' .$pre. 'users  AS u ' .
            " WHERE u.user_id = '$_SESSION[user_id]'";
    $row = $oPub->getRow($sql);

    $_SESSION["last_time"]   =  date("m月d日H:s:i",$row[last_login]);
    $_SESSION["last_ip"]     =  $row[last_ip];
	$_SESSION["visit_count"] =  $row[visit_count]+1;	

    $last_login = gmtime();
    $last_time  = date("Y-m-d H:s:i",gmtime());
    $last_ip = real_ip();

    $_SESSION["login_fail"]  = 1;
    /* 更新登录时间，登录次数及登录ip */
    $sql = "UPDATE " .$pre."users SET".
           " visit_count = visit_count + 1, ".
           " last_ip = '" .$last_ip. "',".
		   " last_time  = '" .$last_time. "',".
           " last_login = '" .$last_login. "'".
           " WHERE user_id = '" . $_SESSION["user_id"] . "'";
    $oPub->query($sql);
	
}
//农历日期显示 start
function nlday(){
     $everymonth=array(
                    0=>array(8,0,0,0,0,0,0,0,0,0,0,0,29,30,7,1),
                    1=>array(0,29,30,29,29,30,29,30,29,30,30,30,29,0,8,2),
                    2=>array(0,30,29,30,29,29,30,29,30,29,30,30,30,0,9,3),
                    3=>array(5,29,30,29,30,29,29,30,29,29,30,30,29,30,10,4),
                    4=>array(0,30,30,29,30,29,29,30,29,29,30,30,29,0,1,5),
                    5=>array(0,30,30,29,30,30,29,29,30,29,30,29,30,0,2,6),
                    6=>array(4,29,30,30,29,30,29,30,29,30,29,30,29,30,3,7),
                    7=>array(0,29,30,29,30,29,30,30,29,30,29,30,29,0,4,8),
                    8=>array(0,30,29,29,30,30,29,30,29,30,30,29,30,0,5,9),
                    9=>array(2,29,30,29,29,30,29,30,29,30,30,30,29,30,6,10),
                    10=>array(0,29,30,29,29,30,29,30,29,30,30,30,29,0,7,11),
                    11=>array(6,30,29,30,29,29,30,29,29,30,30,29,30,30,8,12),
                    12=>array(0,30,29,30,29,29,30,29,29,30,30,29,30,0,9,1),
                    13=>array(0,30,30,29,30,29,29,30,29,29,30,29,30,0,10,2),
                    14=>array(5,30,30,29,30,29,30,29,30,29,30,29,29,30,1,3),
                    15=>array(0,30,29,30,30,29,30,29,30,29,30,29,30,0,2,4),
                    16=>array(0,29,30,29,30,29,30,30,29,30,29,30,29,0,3,5),
                    17=>array(2,30,29,29,30,29,30,30,29,30,30,29,30,29,4,6),
                    18=>array(0,30,29,29,30,29,30,29,30,30,29,30,30,0,5,7),
                    19=>array(7,29,30,29,29,30,29,29,30,30,29,30,30,30,6,8),
                    20=>array(0,29,30,29,29,30,29,29,30,30,29,30,30,0,7,9),
                    21=>array(0,30,29,30,29,29,30,29,29,30,29,30,30,0,8,10),
                    22=>array(5,30,29,30,30,29,29,30,29,29,30,29,30,30,9,11),
                    23=>array(0,29,30,30,29,30,29,30,29,29,30,29,30,0,10,12),
                    24=>array(0,29,30,30,29,30,30,29,30,29,30,29,29,0,1,1),
                    25=>array(4,30,29,30,29,30,30,29,30,30,29,30,29,30,2,2),
                    26=>array(0,29,29,30,29,30,29,30,30,29,30,30,29,0,3,3),
                    27=>array(0,30,29,29,30,29,30,29,30,29,30,30,30,0,4,4),
                    28=>array(2,29,30,29,29,30,29,29,30,29,30,30,30,30,5,5),
                    29=>array(0,29,30,29,29,30,29,29,30,29,30,30,30,0,6,6),
                    30=>array(6,29,30,30,29,29,30,29,29,30,29,30,30,29,7,7),
                    31=>array(0,30,30,29,30,29,30,29,29,30,29,30,29,0,8,8),
                    32=>array(0,30,30,30,29,30,29,30,29,29,30,29,30,0,9,9),
                    33=>array(5,29,30,30,29,30,30,29,30,29,30,29,29,30,10,10),
                    34=>array(0,29,30,29,30,30,29,30,29,30,30,29,30,0,1,11),
                    35=>array(0,29,29,30,29,30,29,30,30,29,30,30,29,0,2,12),
                    36=>array(3,30,29,29,30,29,29,30,30,29,30,30,30,29,3,1),
                    37=>array(0,30,29,29,30,29,29,30,29,30,30,30,29,0,4,2),
                    38=>array(7,30,30,29,29,30,29,29,30,29,30,30,29,30,5,3),
                    39=>array(0,30,30,29,29,30,29,29,30,29,30,29,30,0,6,4),
                    40=>array(0,30,30,29,30,29,30,29,29,30,29,30,29,0,7,5),
                    41=>array(6,30,30,29,30,30,29,30,29,29,30,29,30,29,8,6),
                    42=>array(0,30,29,30,30,29,30,29,30,29,30,29,30,0,9,7),
                    43=>array(0,29,30,29,30,29,30,30,29,30,29,30,29,0,10,8),
                    44=>array(4,30,29,30,29,30,29,30,29,30,30,29,30,30,1,9),
                    45=>array(0,29,29,30,29,29,30,29,30,30,30,29,30,0,2,10),
                    46=>array(0,30,29,29,30,29,29,30,29,30,30,29,30,0,3,11),
                    47=>array(2,30,30,29,29,30,29,29,30,29,30,29,30,30,4,12),
                    48=>array(0,30,29,30,29,30,29,29,30,29,30,29,30,0,5,1),
                    49=>array(7,30,29,30,30,29,30,29,29,30,29,30,29,30,6,2),
                    50=>array(0,29,30,30,29,30,30,29,29,30,29,30,29,0,7,3),
                    51=>array(0,30,29,30,30,29,30,29,30,29,30,29,30,0,8,4),
                    52=>array(5,29,30,29,30,29,30,29,30,30,29,30,29,30,9,5),
                    53=>array(0,29,30,29,29,30,30,29,30,30,29,30,29,0,10,6),
                    54=>array(0,30,29,30,29,29,30,29,30,30,29,30,30,0,1,7),
                    55=>array(3,29,30,29,30,29,29,30,29,30,29,30,30,30,2,8),
                    56=>array(0,29,30,29,30,29,29,30,29,30,29,30,30,0,3,9),
                    57=>array(8,30,29,30,29,30,29,29,30,29,30,29,30,29,4,10),
                    58=>array(0,30,30,30,29,30,29,29,30,29,30,29,30,0,5,11),
                    59=>array(0,29,30,30,29,30,29,30,29,30,29,30,29,0,6,12),
                    60=>array(6,30,29,30,29,30,30,29,30,29,30,29,30,29,7,1),
                    61=>array(0,30,29,30,29,30,29,30,30,29,30,29,30,0,8,2),
                    62=>array(0,29,30,29,29,30,29,30,30,29,30,30,29,0,9,3),
                    63=>array(4,30,29,30,29,29,30,29,30,29,30,30,30,29,10,4),
                    64=>array(0,30,29,30,29,29,30,29,30,29,30,30,30,0,1,5),
                    65=>array(0,29,30,29,30,29,29,30,29,29,30,30,29,0,2,6),
                    66=>array(3,30,30,30,29,30,29,29,30,29,29,30,30,29,3,7),
                    67=>array(0,30,30,29,30,30,29,29,30,29,30,29,30,0,4,8),
                    68=>array(7,29,30,29,30,30,29,30,29,30,29,30,29,30,5,9),
                    69=>array(0,29,30,29,30,29,30,30,29,30,29,30,29,0,6,10),
                    70=>array(0,30,29,29,30,29,30,30,29,30,30,29,30,0,7,11),
                    71=>array(5,29,30,29,29,30,29,30,29,30,30,30,29,30,8,12),
                    72=>array(0,29,30,29,29,30,29,30,29,30,30,29,30,0,9,1),
                    73=>array(0,30,29,30,29,29,30,29,29,30,30,29,30,0,10,2),
                    74=>array(4,30,30,29,30,29,29,30,29,29,30,30,29,30,1,3),
                    75=>array(0,30,30,29,30,29,29,30,29,29,30,29,30,0,2,4),
                    76=>array(8,30,30,29,30,29,30,29,30,29,29,30,29,30,3,5),
                    77=>array(0,30,29,30,30,29,30,29,30,29,30,29,29,0,4,6),
                    78=>array(0,30,29,30,30,29,30,30,29,30,29,30,29,0,5,7),
                    79=>array(6,30,29,29,30,29,30,30,29,30,30,29,30,29,6,8),
                    80=>array(0,30,29,29,30,29,30,29,30,30,29,30,30,0,7,9),
                    81=>array(0,29,30,29,29,30,29,29,30,30,29,30,30,0,8,10),
                    82=>array(4,30,29,30,29,29,30,29,29,30,29,30,30,30,9,11),
                    83=>array(0,30,29,30,29,29,30,29,29,30,29,30,30,0,10,12),
                    84=>array(10,30,29,30,30,29,29,30,29,29,30,29,30,30,1,1),
                    85=>array(0,29,30,30,29,30,29,30,29,29,30,29,30,0,2,2),
                    86=>array(0,29,30,30,29,30,30,29,30,29,30,29,29,0,3,3),
                    87=>array(6,30,29,30,29,30,30,29,30,30,29,30,29,29,4,4),
                    88=>array(0,30,29,30,29,30,29,30,30,29,30,30,29,0,5,5),
                    89=>array(0,30,29,29,30,29,29,30,30,29,30,30,30,0,6,6),
                    90=>array(5,29,30,29,29,30,29,29,30,29,30,30,30,30,7,7),
                    91=>array(0,29,30,29,29,30,29,29,30,29,30,30,30,0,8,8),
                    92=>array(0,29,30,30,29,29,30,29,29,30,29,30,30,0,9,9),
                    93=>array(3,29,30,30,29,30,29,30,29,29,30,29,30,29,10,10),
                    94=>array(0,30,30,30,29,30,29,30,29,29,30,29,30,0,1,11),
                    95=>array(8,29,30,30,29,30,29,30,30,29,29,30,29,30,2,12),
                    96=>array(0,29,30,29,30,30,29,30,29,30,30,29,29,0,3,1),
                    97=>array(0,30,29,30,29,30,29,30,30,29,30,30,29,0,4,2),
                    98=>array(5,30,29,29,30,29,29,30,30,29,30,30,29,30,5,3),
                    99=>array(0,30,29,29,30,29,29,30,29,30,30,30,29,0,6,4),
                    100=>array(0,30,30,29,29,30,29,29,30,29,30,30,29,0,7,5),
                    101=>array(4,30,30,29,30,29,30,29,29,30,29,30,29,30,8,6),
                    102=>array(0,30,30,29,30,29,30,29,29,30,29,30,29,0,9,7),
                    103=>array(0,30,30,29,30,30,29,30,29,29,30,29,30,0,10,8),
                    104=>array(2,29,30,29,30,30,29,30,29,30,29,30,29,30,1,9),
                    105=>array(0,29,30,29,30,29,30,30,29,30,29,30,29,0,2,10),
                    106=>array(7,30,29,30,29,30,29,30,29,30,30,29,30,30,3,11),
                    107=>array(0,29,29,30,29,29,30,29,30,30,30,29,30,0,4,12),
                    108=>array(0,30,29,29,30,29,29,30,29,30,30,29,30,0,5,1),
                    109=>array(5,30,30,29,29,30,29,29,30,29,30,29,30,30,6,2),
                    110=>array(0,30,29,30,29,30,29,29,30,29,30,29,30,0,7,3),
                    111=>array(0,30,29,30,30,29,30,29,29,30,29,30,29,0,8,4),
                    112=>array(4,30,29,30,30,29,30,29,30,29,30,29,30,29,9,5),
                    113=>array(0,30,29,30,29,30,30,29,30,29,30,29,30,0,10,6),
                    114=>array(9,29,30,29,30,29,30,29,30,30,29,30,29,30,1,7),
                    115=>array(0,29,30,29,29,30,29,30,30,30,29,30,29,0,2,8),
                    116=>array(0,30,29,30,29,29,30,29,30,30,29,30,30,0,3,9),
                    117=>array(6,29,30,29,30,29,29,30,29,30,29,30,30,30,4,10),
                    118=>array(0,29,30,29,30,29,29,30,29,30,29,30,30,0,5,11),
                    119=>array(0,30,29,30,29,30,29,29,30,29,29,30,30,0,6,12),
                    120=>array(4,29,30,30,30,29,30,29,29,30,29,30,29,30,7,1)
                   );
##############################
  #农历天干
  $mten=array("null","甲","乙","丙","丁","戊","己","庚","辛","壬","癸");
  #农历地支
  $mtwelve=array("null","子(鼠)","丑(牛)","寅(虎)","卯(兔)","辰(龙)",
                 "巳(蛇)","午(马)","未(羊)","申(猴)","酉(鸡)","戌(狗)","亥(猪)");
  #农历月份
  $mmonth=array("闰","正","二","三","四","五","六",
                "七","八","九","十","十一","十二","月");
  #农历日
  $mday=array("null","初一","初二","初三","初四","初五","初六","初七","初八","初九","初十",
              "十一","十二","十三","十四","十五","十六","十七","十八","十九","二十",
              "廿一","廿二","廿三","廿四","廿五","廿六","廿七","廿八","廿九","三十");
##############################
  #星期
  $weekday = array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");

  #阳历总天数 至1900年12月21日
  $total=11;
  #阴历总天数
  $mtotal=0;
##############################
  #获得当日日期
  $today=getdate();
  if($today["year"]<1901 || $today["year"]>2020) die("年份出错！");

  $cur_wday=$today["wday"];

  for($y=1901;$y<$today["year"];$y++) { //计算到所求日期阳历的总天数-自1900年12月21日始,先算年的和
       $total+=365;
       if ($y%4==0) $total++;
  }

  switch($today["mon"]) { //再加当年的几个月
         case 12:
              $total+=30;
         case 11:
              $total+=31;
         case 10:
              $total+=30;
         case 9:
              $total+=31;
         case 8:
              $total+=31;
         case 7:
              $total+=30;
         case 6:
              $total+=31;
         case 5:
              $total+=30;
         case 4:
              $total+=31;
         case 3:
              $total+=28;
         case 2:
              $total+=31;
  }

  if($today["year"]%4 == 0 && $today["mon"]>2) $total++; //如果当年是闰年还要加一天

  $total=$total+$today["mday"]-1; //加当月的天数

  $flag1=0;  //判断跳出循环的条件
  $j=0;
  while ($j<=120){  //用农历的天数累加来判断是否超过阳历的天数
      $i=1;
      while ($i<=13){
            $mtotal+=$everymonth[$j][$i];
            if ($mtotal>=$total){
                 $flag1=1;
                 break;
            }
            $i++;
      }
      if ($flag1==1) break;
      $j++;
  }

  if($everymonth[$j][0]<>0 and $everymonth[$j][0]<$i){ //原来错在这里，对闰月没有修补
      $mm=$i-1;
  }
  else{
      $mm=$i;
  }

  if($i==$everymonth[$j][0]+1 and $everymonth[$j][0]<>0) {
      $nlmon=$mmonth[0].$mmonth[$mm];#闰月
  }
  else {
      $nlmon=$mmonth[$mm].$mmonth[13];
  }

  #计算所求月份1号的农历日期
  $md=$everymonth[$j][$i]-($mtotal-$total);
  if($md > $everymonth[$j][$i])
      $md-=$everymonth[$j][$i];
  $nlday=$mday[$md];

  $nowday =date("n月j日 ").$weekday[$cur_wday]." ".$mten[$everymonth[$j][14]].$mtwelve[$everymonth[$j][15]]."年".$nlmon.$nlday;

  return $nowday;
}
//农历日期显示 end

/**
 * 取得当前的域名
 *
 * @access  public
 *
 * @return  string      当前的域名
 */
function get_domain()
{
	/* 协议 */
	$protocol = http();

	/* 域名或IP地址 */
	if (isset($_SERVER["HTTP_X_FORWARDED_HOST"]))
	{
		$host = $_SERVER["HTTP_X_FORWARDED_HOST"];
	}
	elseif (isset($_SERVER["HTTP_HOST"]))
	{
		$host = $_SERVER["HTTP_HOST"];
	}
	else
	{
		/* 端口 */
		if (isset($_SERVER["SERVER_PORT"]))
		{
			$port = ':' . $_SERVER["SERVER_PORT"];

			if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol))
			{
				$port = '';
			}
		}
		else
		{
			$port = '';
		}

		if (isset($_SERVER["SERVER_NAME"]))
		{
			$host = $_SERVER["SERVER_NAME"] . $port;
		}
		elseif (isset($_SERVER["SERVER_ADDR"]))
		{
			$host = $_SERVER["SERVER_ADDR"] . $port;
		}
	}

	return $protocol . $host;
}

/**
 * 获得 当前环境的 URL 地址
 *
 * @access  public
 *
 * @return  void
 */
function url()
{
	$curr = strpos($PHP_SELF, 'admin/') !== false ?
			preg_replace('/(.*)(admin)(\/?)(.)*/i', '\1', dirname($PHP_SELF)) :
			dirname($PHP_SELF);

	$root = str_replace('\\', '/', $curr);

	if (substr($root, -1) != '/')
	{
		$root .= '/';
	}

	return get_domain() . $root;
}

/**
 * 获得当前环境的 HTTP 协议方式
 *
 * @access  public
 *
 * @return  void
 */
function http()
{
	return (isset($_SERVER["HTTPS"]) && (strtolower($_SERVER["HTTPS"]) != 'off')) ? 'https://' : 'http://';
}

function daddslashes($string, $force = 0) {
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = daddslashes($val, $force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}
function dhtmlspecialchars($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dhtmlspecialchars($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', 
		str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	return $string;
}
/**
 * 保存某图库及相册图片
 * @param   int     $workid
 * @param   array   $image_files
 * @param   array   $image_descs
 * @return  void
 */ 
function handle_gallery_image($arid, $image_files, $image_descs,$type='')
{
	global $image,$oPub,$pre,$_SESSION,$un_domain_id,$Aconf; 
	$imgType = array(1 => 'image/gif', 2 => 'image/jpeg', 3 => 'image/png',4 => 'image/pjpeg');
	while( @list( $key, $img_desc ) = @each( $image_descs) ) {
        /* 是否成功上传 */
        $flag = false;
        if (isset($image_files["error"])) {
            if ($image_files["error"][$key] == 0) {
                $flag = true;
            }
        } else {
            if ($image_files["tmp_name"][$key] != 'none') {
                $flag = true;
            }
        }

        if ($flag ){
            // 生成缩略图
			if($image->check_img_type($image_files["type"][$key])) { 
               $thumb_url = $image->make_thumb($image_files["tmp_name"][$key], 120,  90);
			}
            $thumb_url = is_string($thumb_url) ? $thumb_url : '';

            $upload = array(
                'name' => $image_files["name"][$key],
                'type' => $image_files["type"][$key],
                'tmp_name' => $image_files["tmp_name"][$key],
                'size' => $image_files["size"][$key],
            );
            if (isset($image_files["error"]))
            {
                $upload["error"] = $image_files["error"][$key];
            }

            $img_original = $image->upload_image($upload);


			$target_file = $filename = ROOT_PATH.$img_original;
			$watermark = ROOT_PATH.'data/weblogo/'.$Aconf["watermark"]; 
			if(file_exists($watermark)){ 
				$image->add_watermark($filename, $target_file, $watermark,5,80 ); 
			}
            $img_url = $img_original;

            $db_table = $pre.'arti_file';
			if(empty($img_desc)){
				$A = explode(".",$image_files["name"][$key]);
				$img_desc = $A[0];
			}
            $sql = "INSERT INTO " . $db_table. " (arid,type, filename,thumb_url,descs,domain_id) " .
                    "VALUES ('$arid','$type', '$img_url', '$thumb_url','$img_desc',$_SESSION[$un_domain_id])";
            $oPub->query($sql);
        }
    }
}

function assign_template($Aconf = array())
{
    global $smarty; 
	while( @list( $k, $v ) = @each( $Aconf) ) { 
 		$smarty->assign($k,   $v );
	}
}
/*
 * 导航
 * @access  private
 * @return  array
 */
function get_nav() {
	global $_SESSION,$un_domain_id,$oPub,$pre;  
	$sql = "SELECT name,opennew,url  FROM ".$pre."nav WHERE ifshow=0 AND domain_id = $_SESSION[$un_domain_id] ORDER BY vieworder,id asc ";
	$Anav = $oPub->select($sql);
	while(@list( $k, $v ) = @each( $Anav)) {
		 if(stristr($v["url"], '://') === FALSE) {
			$Anav[$k]["url"] = $v["url"];
		}
	}
	return $Anav;
}
/*
 *调查选项提取
*/
function vote($vtid) {
	global $_SESSION,$un_domain_id,$oPub,$pre,$Aconf; 
	$vtid = $vtid + 0;
	if($vtid < 1){
		break;
	} 
	$voteurl = $Aconf["rewrite"]?'vote-'.$vtid.'.html':'vote.php?id='.$vtid; 
	$sql = "SELECT vgid,vg_name,vg_desc,is_show FROM ".$pre."vote_group 
			WHERE  vtid = '".$vtid."' 
			ORDER BY  orders  desc,vgid ASC ";
	$rowgroup = $oPub->select($sql); 
	if($rowgroup){ 
		foreach ($rowgroup AS $kg=>$vg) { 
			$sql = "SELECT viid,vi_name,vi_type,thumb_url  FROM ".$pre."vote_item 
					WHERE  vtid = '".$vtid."' AND  states = 0  AND is_show = 1 
					AND vgid = '".$vg["vgid"]."' AND domain_id=".$_SESSION[$un_domain_id].
					" ORDER BY orders asc,vi_type asc,viid asc"; 
			$rowvote_item = $oPub->select($sql);  
			if($rowvote_item) { 
				foreach ($rowvote_item AS $key=>$val) { 
					$vi_name = $val["vi_name"];
					$rowvote_item[$key]["thumb_url"] = (!empty($val["thumb_url"]))?'data/vote/'.$val["thumb_url"]:'';
					if ($val["vi_type"] < 1) {
						$input = '<INPUT TYPE="radio" NAME="vote_vgid_radio[".$vg["vgid"]."]" value="'.$val["viid"].'">';
					} elseif($val["vi_type"] == 1) {
						$input = '<INPUT TYPE="checkbox" NAME="vote_item[".$val["viid"]."]" value="'.$val["viid"].'">';
					} elseif($val["vi_type"] == 2){ 
						$selectname = '';
						$Avi_name = explode(",",$val["vi_name"]); 
						if(count($Avi_name) > 0){
							$inputselect =  '<SELECT NAME="vote_item[".$val["viid"]."]">';
								$n = 0;
								foreach ($Avi_name AS $kt=>$vt) { 
									if($n < 1){
										$selectname = $vt;
									}else{
										$inputselect .= '<OPTION VALUE="'.$vt.'" >'.$vt.'</OPITON>'; 
									}
									$n ++ ;
								}
							$inputselect .= '</SELECT>';
							$input = $inputselect;
						}
						$vi_name = $selectname;

					} elseif($val["vi_type"] == 3) { 
						$input = '<INPUT TYPE="text" NAME="vote_item[".$val["viid"]."]" value="" style="12">';
					} elseif($val["vi_type"] == 4) {
						$input = '<TEXTAREA NAME="vote_item[".$val["viid"]."]" style="width:500px;height:200px"></TEXTAREA>';
					}
					
					$rowvote_item[$key]["input"] = $input;
					$rowvote_item[$key]["vi_name"] = $vi_name;
				} 
			}  
			$rowgroup[$kg]["vote_item"] = $rowvote_item; 
		}//foreach ($rowgroup AS $kg=>$vg) 
	}
	//$Ahome["vote"][for_vote_group]= $rowgroup;
	return $rowgroup;
}
/*
 *调查结果
*/
function vote_show($vtid) {
	global $_SESSION,$un_domain_id,$oPub,$pre,$Aconf; 
	$vtid = $vtid + 0;
	if($vtid < 1){
		break;
	} 
 
	$sql = "SELECT vgid,vg_name,vg_desc,is_show,vg_nums FROM ".$pre."vote_group 
			WHERE  vtid = '".$vtid."' 
			ORDER BY  orders  desc,vgid ASC ";
	$rowgroup = $oPub->select($sql); 
	if($rowgroup){ 
		foreach ($rowgroup AS $kg=>$vg) { 
			$sql = "SELECT viid,vi_name,vi_type,vi_nums  FROM ".$pre."vote_item 
					WHERE  vtid = '".$vtid."' AND  states = 0  AND is_show = 1 
					AND vgid = '".$vg["vgid"]."' AND domain_id=".$_SESSION[$un_domain_id].
					" ORDER BY orders asc,vi_type asc,viid asc"; 
			$rowvote_item = $oPub->select($sql);  
			if($rowvote_item) {
				$input = '';
				$j = 0;
				foreach ($rowvote_item AS $key=>$val) { 
					$inputstr = '';
					if ($val["vi_type"] < 1) { 
						$inputstr = $val["vi_name"];
					} elseif($val["vi_type"] == 1) {
						$inputstr = $val["vi_name"];
					} elseif($val["vi_type"] == 2){ 
						$Avi_name = explode(",",$val["vi_name"]); 
						if(count($Avi_name) > 0){
							$inputselect =  '';
								$n = 0;
								foreach ($Avi_name AS $kt=>$vt) { 
									if($n < 1){
										$selectname = $vt;
									}else{
										$sql = "SELECT  count(*) as count FROM  ".$pre."vote_poll where viid='".$val["viid"]."' and descs LIKE '$vt'";
										$count = $oPub->getOne($sql); 
										$count = $count > 0 ?$count :0;
										$inputselect .= $vt.'('.$count.')<br/>';
									}
									$n ++ ;
								}
							$inputstr =$selectname.'<br/>'.$inputselect;
						}
					} elseif($val["vi_type"] == 3) { 
						$inputstr = $val["vi_name"].'<br/>';
						$sql = "SELECT  descs FROM  ".$pre."vote_poll where viid='".$val["viid"]."'";
						$row = $oPub->select($sql);
						$tmp = '';
						while( @list( $k, $v) = @each($row) ) { 
							$tmp .= $v[descs].'<br/>';
						}
						$inputstr = $inputstr.$tmp; 
					} elseif($val["vi_type"] == 4) { 
						$inputstr = $val["vi_name"].'<br/>';
						$sql = "SELECT  descs FROM  ".$pre."vote_poll where viid='".$val["viid"]."'";
						$row = $oPub->select($sql);
						$tmp = '';
						while( @list( $k, $v) = @each($row) ) { 
							$tmp  .= $v[descs].'<br/>';
						}
						$inputstr = $inputstr.$tmp; 
					}
					$j ++ ;
					$inputstr = $j.'、'.$inputstr;
					$mypre = number_format($val[vi_nums] / $vg[vg_nums] *100,2); 
					$myprewidth = $mypre*2;
					
					$strbg =($j % 2)? 'bgcolor="#E4EBF8"': 'bgcolor="#EFEFEF"';
					$input .= '<tr '.$strbg.'><td valign="top" width="400">'.$inputstr.'</td><td valign="top"><IMG SRC="images/command/vote.gif" WIDTH="'.$myprewidth.'" HEIGHT="10" BORDER="0" ALT="'.$mypre.'">['.$val[vi_nums].']'.$mypre.'%</td></tr>';
				}
				 
				$rowvote_item["input"] = '<table width="98%" border="0" cellpadding="5" cellspacing="2">'.$input.'</TABLE>';
			}  
			$rowgroup[$kg]["vote_item"] = $rowvote_item["input"]; 
		}//foreach ($rowgroup AS $kg=>$vg) 
	}
	//$Ahome["vote"][for_vote_group]= $rowgroup;
	return $rowgroup;
}
/*
 *过滤模版中的PHPD
*/
function delete_php_code($content) {
	if(!empty($content)) {
		$pattern='/\<\?(.|\r\n|\s)*\?\>/U'; 
		return preg_replace($pattern,'',$content);
	}
}
?>
