<?php
/********************************************************************
 *                              DirCMS公用函数
 *                            -------------------
 *   begin                : 2009/11/24
 *   copyright            : (C) 2009 DirCMS
 *   email                : uuturn@126.com
 *
 *   $Id: global.func.php,v 1.0.0 2009/11/24 1:04:01 M Exp $
 ********************************************************************/
@define('CHECK','Dircms');
function fatal_error($msg) //致命错误
{
	exit('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>错误报告 - Powered by DirCMS</title>
<style type="text/css">
body{font-size: 13px;font-family: Verdana, Arial, Helvetica, sans-serif;margin: 0px;padding: 0px; padding-left:10px; padding-top:10px; line-height:2em}
</style>
</head>

<body>

Error:'.$msg.'
<br />
Notice:The same message has been sent to the administrator before.
<br />
Thank you for choosing our product! you can get more information from address by <a href="http://bbs.dircms.net" title="获取技术支持" target="_blank">dircms.net</a>.
</body>
</html>');
}

function showmsg($msg='',$url='',$timeout=1000)
{
	global $DIRCMS;
	if(!defined('DIRCMS_VERSION'))require DIRCMS_ROOT.'/include/version.inc.php';
	if(!$url)$url='javascript:history.back();';

	echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="x-ua-compatible" content="ie=7" />
<meta http-equiv="imagetoolbar" content="false" />
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="'.$DIRCMS['site_url'].'images/js/jquery.min.js"></script>
<style type="text/css">
*{padding:0px; margin:0px}
body {margin: 8em 3em; font: 12px Tahoma;  color: #333333; line-height: 20px; text-align:center;}
p {margin: 1em 0}
ul {}
li {height: 1%; overflow: hidden; list-style-type: none}
a {color: #999; text-decoration: none}
a:hover {color: #333333}
.b {font-size:14px; color:#0066cc}
.info {padding:.5em 0 0 0.2em}
.gray {color: #666666; margin-top: 8px}
.case {width:400px;clear:both;margin:0px auto; padding: 0 2em 2em 2em; border: solid 1px #EAEAEA; background: #FFFFFF; margin-bottom: 2em; height: 1%; overflow: hidden;  text-align:left}
.title {display:block; padding: 0.5em 2em 0.5em 1em; margin: 0 -2em 1.5em -2em; font-weight: bold;  background: #FAFAFA; border-bottom: solid 1px #EAEAEA; font-size:14px; color:#555;background:#FAFAFA url('.$DIRCMS['site_url'].'images/notice.gif) 4px 0 no-repeat; height:15px}

</style>
<script src="/images/js/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function redirect(url)
{
	if(url=="javascript:history.back();")eval(url);
	else self.location.href=url;
}
</script>
</head>
<body>
<div class="case">
 <div class="title"> </div>
 <div class="b">'.$msg.'</div>
 <ul class="info gray">
  <li><a href="'.$url.'" >跳转太慢,点击这里...</a></li>
  <li style="color:#ccc; font-size:9px">Powered by Dircms'.DIRCMS_VERSION.'</li>
 </ul>
</div>
</body>
</html>';
	 exit('<script>setTimeout("redirect(\''.$url.'\');",'.$timeout.');</script>');
}

function showmsg_nourl($msg='') //提示信息无跳转
{
	global $DIRCMS;
	if(!defined('DIRCMS_VERSION'))require DIRCMS_ROOT.'/include/version.inc.php';
	echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<title>'.$DIRCMS['site_name'].'提示信息</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="'.$DIRCMS['site_url'].'images/js/jquery.min.js"></script>
<style type="text/css">
*{padding:0px; margin:0px}
body {margin: 8em 3em; font: 12px Tahoma;  color: #333333; line-height: 20px; text-align:center;}
p {margin: 1em 0}
ul {}
li {height: 1%; overflow: hidden; list-style-type: none}
a {color: #999; text-decoration: none}
a:hover {color: #333333}
.b {font-size:14px; color:#0066cc}
.info {padding:.5em 0 0 0.2em}
.gray {color: #666666; margin-top: 8px}
.case {width:400px;clear:both;margin:0px auto; padding: 0 2em 2em 2em; border: solid 1px #EAEAEA; background: #FFFFFF; margin-bottom: 2em; height: 1%; overflow: hidden;  text-align:left}
.title {display:block; padding: 0.5em 2em 0.5em 1em; margin: 0 -2em 1.5em -2em; font-weight: bold;  background: #FAFAFA; border-bottom: solid 1px #EAEAEA; font-size:14px; color:#555;background:#FAFAFA url('.$DIRCMS['site_url'].'images/notice.gif) 4px 0 no-repeat; height:15px}

</style>
<script src="/images/js/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function redirect(url)
{
	if(url=="javascript:history.back();")eval(url);
	else self.location.href=url;
}
</script>
</head>
<body>
<div class="case">
 <div class="title"></div>
 <div class="b">'.$msg.'</div>
 <ul class="info gray">
  <li style="color:#ccc; font-size:9px">Powered by Dircms'.DIRCMS_VERSION.'</li>
 </ul>
</div>
</body>
</html>';
	exit();
}

function getRootDomain($url)
{
	$url = $url."/"; 
	preg_match("/((\w*):\/\/)?\w*\.?([\w|-]*\.(com.cn|net.cn|gov.cn|org.cn|com|net|cn|org|asia|tel|mobi|me|tv|biz|cc|name|info))\//i", $url, $ohurl); 

	if($ohurl[3] == '')
	{ 
		preg_match("/((\d+\.){3}\d+)\//", $url, $ohip); 
		return $ohip[1];
	} 
	return $ohurl[3]; 
}

function getmenuNamebyid($userid,$menuid)
{
	global $DIRCMS;
	$menu=cache_read('menu'.intval($userid).'.cache.php',DIRCMS_ROOT.'company/cache/menu/');
	$menu=$menu?$menu:array (
	  1 => array('name'=>'网站首页','url'=>$DIRCMS['site_url'].'company/company_'.$userid.'.html'),
	  2 => array('name'=>'公司简介','url'=>$DIRCMS['site_url'].'company/about_'.$userid.'.html'),
	  3 => array('name'=>'新闻动态','url'=>$DIRCMS['site_url'].'company/news_'.$userid.'.html'),
	  4 => array('name'=>'优惠信息','url'=>$DIRCMS['site_url'].'company/coupon_'.$userid.'.html'),
	  5 => array('name'=>'产品展示','url'=>$DIRCMS['site_url'].'company/product_'.$userid.'.html'),
	  6 => array('name'=>'地图位置','url'=>$DIRCMS['site_url'].'company/map_'.$userid.'.html'),
	  7 => array('name'=>'联系方式','url'=>$DIRCMS['site_url'].'company/contact_'.$userid.'.html'),
	  8 => array('name'=>'在线留言','url'=>$DIRCMS['site_url'].'company/guestbook_'.$userid.'.html'),
	);	

	return $menu[$menuid]['name'];
}

function getmenuUrlbyid($userid,$menuid)
{
	global $DIRCMS;
	$menu=cache_read('menu'.intval($userid).'.cache.php',DIRCMS_ROOT.'company/cache/menu/');
	$menu=$menu?$menu:array (
	  1 => array('name'=>'网站首页','url'=>$DIRCMS['site_url'].'company/company_'.$userid.'.html'),
	  2 => array('name'=>'公司简介','url'=>$DIRCMS['site_url'].'company/about_'.$userid.'.html'),
	  3 => array('name'=>'新闻动态','url'=>$DIRCMS['site_url'].'company/news_'.$userid.'.html'),
	  4 => array('name'=>'优惠信息','url'=>$DIRCMS['site_url'].'company/coupon_'.$userid.'.html'),
	  5 => array('name'=>'产品展示','url'=>$DIRCMS['site_url'].'company/product_'.$userid.'.html'),
	  6 => array('name'=>'地图位置','url'=>$DIRCMS['site_url'].'company/map_'.$userid.'.html'),
	  7 => array('name'=>'联系方式','url'=>$DIRCMS['site_url'].'company/contact_'.$userid.'.html'),
	  8 => array('name'=>'在线留言','url'=>$DIRCMS['site_url'].'company/guestbook_'.$userid.'.html'),
	);	

	return $menu[$menuid]['url'];
}

function getCategoryname($catid=0,$isurl=true,$iswap=false) ////////////////////// 根据栏目ID获取栏目名称
{
	$r_=cache_read('category'.$catid.'.cache.php',DIRCMS_ROOT.'data/cache_category/');
	if(!$r_ || !$catid)return '未定义';
	else{
		if($iswap)return $isurl?'<a href="wap/category.php?id='.$r_['id'].'" title="'.$r_['categoryname'].'" target="_blank">'.$r_['categoryname'].'</a>':$r_['categoryname'];
		else return $isurl?'<a href="'.$r_['url'].'" title="'.$r_['categoryname'].'" target="_blank">'.$r_['categoryname'].'</a>':$r_['categoryname'];
	}
}

function getCategoryinfo($catid=0)////////////////////// 根据栏目ID获取栏目的所有信息，返回一个数组
{
	return cache_read('category'.$catid.'.cache.php',DIRCMS_ROOT.'data/cache_category/');
}

function getAreaname($areaid=0) ////////////////////// 根据地区ID获取地区名称
{
	$r_=cache_read('area'.$areaid.'.cache.php',DIRCMS_ROOT.'data/cache/');
	return (!$r_ || !$areaid)?CITY:$r_['area'];
}

function isfinalcatid($catid)
{
	$r_=cache_read('finalcatid.cache.php',DIRCMS_ROOT.'data/cache_category/');
	return in_array($catid,$r_);
}

function getTagname($id=1)
{
	$r=cache_read('words.tag.php',TPL_ROOT.TPL_NAME.'/');
	if(!$r || !$id)return '未定义';
	else{
		$r=$r[$id];
		return $r['url']?'<a href="'.$r['url'].'" title="'.$r['name'].'" target="_blank">'.$r['name'].'</a>':$r['name'];
	}
}

function getSign($id=0)
{
	global $db;
	$id=intval($id);
	$sql="SELECT COUNT(id) as num FROM `".DB_PRE."sign` WHERE `".DB_PRE."sign`.`contentid`=$id";
	$r=$db->fetch_one($sql);
	return $r?$r['num']:0;
}

function getImages($images) // 多图字段调用 
{
	$result=$r=$t=array();
	if(!$images)return $t;
	$t=explode("\n",$images);
	if($t)foreach($t as $k => $_t)
	{
		if($_t)
		{
			$r=explode("|",$_t);
			$result[$k]['name']=$r[0];
			$result[$k]['url']=$r[1];
		}
	}
	return $result;
}

function getDownloads($downloads) // 下载地址字段调用 
{
	$result=$r=$t=array();
	if(!$downloads)return $t;
	$t=explode("\n",$downloads);
	if($t)foreach($t as $k => $_t)
	{
		if($_t)
		{
			$r=explode("|",$_t);
			$result[$k]['name']=$r[0];
			$result[$k]['url']=$r[1];
		}
	}
	return $result;
}

function getVedios($vedios) // 视频地址字段调用 
{
	$result=$r=$t=array();
	if(!$vedios)return $t;
	$t=explode("\n",$vedios);
	if($t)foreach($t as $k => $_t)
	{
		if($_t)
		{
			$r=explode("|",$_t);
			if($r[1]!='http://' && $r[1])
			{
				$result[$k]['name']=$r[0];
				$result[$k]['url']=$r[1];
			}
		}
	}
	return $result;
}

function set_cookie($var,$value='',$time=0)
{
	$time = $time > 0 ? $time : ($value == '' ? PHP_TIME - 3600 : 0);
	$secure=$_SERVER['SERVER_PORT']=='443'?true:false; /////////////////// 2010-5-24 https协议
	$var = COOKIE_PRE.$var;
	$_COOKIE[$var] = $value;
	if(is_array($value))
	{
		foreach($value as $k=>$v)
		{
			setcookie($var.'['.$k.']',$v,$time,COOKIE_PATH,COOKIE_DOMAIN,$secure);
		}
	}
	else
	{
		setcookie($var,$value,$time,COOKIE_PATH,COOKIE_DOMAIN,$secure);
	}
}

function dircms_auth($str,$operation='ENCODE',$key='')
{
	$key=$key?$key:AUTH_KEY;
	$str=$operation == 'ENCODE'?$str:base64_decode($str);
	$len=strlen($key);
	$code='';
	for($i=0; $i<strlen($str); $i++){
		$k=$i%$len;
		$code.=$str[$i]^$key[$k];
	}
	$code=$operation=='DECODE'?$code:base64_encode($code);
	return $code;
}

function get_cookie($var)
{
	$var = COOKIE_PRE.$var;
	return isset($_COOKIE[$var])?$_COOKIE[$var]:false;
}

function getpos($catid=0,$separator='&gt;')
{
	global $DIRCMS;
	$r=cache_read('category'.$catid.'.cache.php',DIRCMS_ROOT.'data/cache_category/');
	$url=' <a href="'.$r['url'].'" title="'.$r['categoryname'].'">'.$r['categoryname'].'</a> ';
	if(!$r || !$r['parentid']) 
	{
		return $url;
	}
	else
	{
		return getpos($r['parentid'],$separator).$separator.$url;
	}
}

function get_pos($catid=0,$separator='&gt;') //////// 根据当前ID获取导航
{
	global $DIRCMS;
	$pos=getpos($catid,$separator);	
	return ' <a href="'.$DIRCMS['site_url'].'" title="'.$DIRCMS['site_name'].'">首页</a> '.$separator.' '.$pos;
}

function get_fileext($file)
{
	return strtolower(substr(strrchr($file,'.'),1));
}

function getMicrotime() // 返回浮点数的 microtime()
{
	if(version_compare(PHP_VERSION,'5.0.0','ge')) return microtime(true);
	else{
		list($msec,$sec)=explode(' ',microtime());
		return ((float)$sec+(float)$msec);
	}
}

function get_rand_array_value($array) //从一个数组中取得一个随机数
{
	return $array[array_rand($array)];
}

function delete_array_value($array,$value) //删除数组中指定的值
{
	$keys=array_keys($array,$value);
	if($key)
	{
		foreach($keys as $key)unset($array[$key]);
		return true;
	}
	return false;
}

function getrandnumber($len=16) //////返回一个 长度为$len的随机字符串
{
	$len=$len>=10?$len:10; ///最小为10位
	$t=time();
	$len=($len-10)>=0?($len-10):0;
	for($i=0;$i<$len;$i++)
	{
		$t.=mt_rand(0,9);
	}
	return $t;
}

function is_ip($str)
{
	$ip = explode('.',$is_ip);
	for($i=0;$i<count($ip);$i++)
	{  
		if($ip[$i]>255)
		{  
			return (0);  
		}  
	}  
	return preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/',$gonten);  
} 

function getIp()
{
	$ip='0.0.0.0';

	if(!empty($_SERVER['HTTP_CLIENT_IP']))
	{
		return is_ip($_SERVER['HTTP_CLIENT_IP'])?$_SERVER['HTTP_CLIENT_IP']:$ip;
	}
	elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
	{
		return is_ip($_SERVER['HTTP_X_FORWARDED_FOR'])?$_SERVER['HTTP_X_FORWARDED_FOR']:$ip;
	}
	else
	{
		return is_ip($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:$ip;
	}
}

function wordstoZoneCode($cnwords) // 汉字转区位码（单字） 2010-5-12
{
	$qu=(string)(ord($cnwords[0])-160);
	$qu=strlen($qu)==1?'0'.$qu:$qu;
	$wei=(string)(ord($cnwords[1])-160);
	$wei=strlen($wei)==1?'0'.$wei:$wei;
	return $qu.$wei;
}

function zoneCodetoWords($zonecode) // 区位码转汉字（单字） 
{
	if(intval($zonecode)<1601 || intval($zonecode)>8794) return '';
	$cnwords=chr(substr($zonecode,0,2)+160).chr(substr($zonecode,2,2)+160);
	return $cnwords;
}

function zoneCodetoStr($zonecode) // 区位码转字符串 2010-5-15
{
	$tarr=explode(' ',$zonecode);
	$t_arr=array();
	foreach($tarr as $zonecode)
	{
		$tt='';
		if(!preg_match('/^[0-9]+$/',$zonecode))$tt=$zonecode;
		else
		{
			$len=strlen($zonecode);
			$str='';
			for($i=0;$i<$len;$i+=4)
			{
				$tt.=zoneCodetoWords(substr($zonecode,$i,4));
			}
		}
		$t_arr[]=$tt.' ';
	}
	return preg_replace('/(\s)+/i','\\1',trim(implode(' ',$t_arr)));
}

function getCatid($catid) //////////////////////// 2010/8/28
{
	$catid=intval($catid);
	if(is_final_catid($catid))return 'catid='.intval($catid);
	else
	{
		$r=cache_read('finalcatid.cache.php',DIRCMS_ROOT.'data/cache_category/');
		$t_catid[]=implode(',',get_childrencatid($catid));
		$catid=array_unique(explode(',',implode(',',$t_catid)));
		$catid=array_intersect($r,$catid);
		$catid=$catid?$catid:array(0);
		sort($catid);
		return 'catid IN('.implode(',',$catid).')';
	}
}

function getTypeid($typeid)
{
	$typeid=intval($typeid);
	$r=cache_read('member_type'.$typeid.'.cache.php',DIRCMS_ROOT.'data/cache/');
	if($r['parentid'])return 'typeid='.intval($typeid);
	else
	{
		$t=array($typeid);
		$r=cache_read('all_member_type.cache.php',DIRCMS_ROOT.'data/cache/');
		if($r)foreach($r as $_r)
		{
			if($_r['parentid']==$typeid)$t[]=$_r['id'];
		}
		return 'typeid IN('.implode(',',$t).')';
	}
}

function strtoZoneCode($str) // 字符串转区位码 2010-5-15
{
	$str=split_words($str);
	$t_arr=array();
	foreach($str as $t_str)
	{
		$tt='';
		if(preg_match('/^[0-9a-z]+$/i',$t_str))$tt=$t_str;
		else
		{
			$strlen=strlen($t_str);
			for($i=0;$i<$strlen;$i+=3)
			{
				$t=$t_str[$i].$t_str[$i+1].$t_str[$i+2];
				$tt.=wordstoZoneCode($t);
			}
		}
		$t_arr[]=$tt.' ';
	}
	return implode(' ',$t_arr);
}

function split_words($str) // 将句子粗略分词（中,英数字,符号分开）,返回数组 2010-5-15
{
	$trimchars= array('\r','\n','\t','`','~','!','@','#','$','%','^','&','*','(',')','-','_','+','=','|','\\','\'','"',';',':','/','?','.','>',',','<','[','{',']','}','·','～','!','＠','＃','￥','％','……','＆','×','（','）','－','——','＝','＋','＼','｜','【','｛','】','｝','‘','“','”','；','：','、','？','。','》','，','《',' ','　','▲','△','▼','▽','★','☆','◆','◇','■','□','●','○','⊙','㊣','◎','▂','▁','▃','▄','▅','▆','▇','█','▏','▎','▍','▌','▋','▊','◢','◣','◥','◤','▲','▼','♀','♂','卍','※','︻'); // 标点符号
	$prechar=0; // 0:中文 1:英文或数字
	$str=str_replace($trimchars,' ',$str);
	$len=strlen($str);
	$tstr='';
	for($i=0;$i<$len;)
	{
		if($str[$i]==' ')
		{
			$tstr.=' ';
			$i++;
		}
		elseif(ord($str[$i])>=0x81)
		{
			
			
			if($prechar==1)
			{
				$tstr.=' '.$str[$i].$str[$i+1].$str[$i+2];
			}
			else
			{
				$tstr.=$str[$i].$str[$i+1].$str[$i+2];
			}
			$i+=2;
			$prechar=0;
		}
		else
		{
			if($prechar==0)
			{
				$tstr.=' '.$str[$i];
			}
			else
			{
				$tstr.=$str[$i];
			}
			$prechar=1;
			$i++;
		}
	}
	$tstr=explode(' ',$tstr);
	foreach($tstr as $key => $value)
	{
		if(preg_match('/^[0-9]+$/',$value)||$value=='') unset($tstr[$key]);
	}
	return array_unique($tstr);
}

function trim_str($str)
{
	return preg_replace('/[\r\n\t\s]+/','',$str);
}

function make_dir($dirname) //递归创建文件夹
{	
	@chdir(DIRCMS_ROOT);
	if(file_exists($dirname))return true;
	$dirname=strtolower(preg_replace('/[^0-9a-zA-Z_\-\/]/i','',str_replace('\\','/',$dirname)));
	$dirname=explode('/',$dirname);
	$dir_name='./';
	foreach($dirname as $childdir)
	{
		$dir_name.=$childdir.'/';
		if(!file_exists($dir_name) && !empty($childdir))
		{
			@mkdir($dir_name);
			@chmod($dir_name,0777);
		}
	}
	return true;
}

function get_path($path)
{
	$path = str_replace('\\', '/', $path);
	if(substr($path,-1) != '/') $path = $path.'/';
	return $path;
}

function delete_dir($dirname)
{
	$dir = get_path($dirname);
	if(!$dir)return true;
	if(!is_dir($dir)) return false;
	$systemdirs = array('', DIRCMS_ROOT.'admin/', DIRCMS_ROOT.'admin/include/', DIRCMS_ROOT.'data/', DIRCMS_ROOT.'member/', DIRCMS_ROOT.'templates/', DIRCMS_ROOT.'images/');
	if(substr($dir, 0, 1) == '.' || in_array($dir, $systemdirs)) fatal_error("系统保护操作,删除失败!");
	$list = glob($dir.'*');
	foreach($list as $v)
	{
		is_dir($v) ? delete_dir($v) : @unlink($v);
	}
    return @rmdir($dir);
}

function delete_file($filename)  // 删除文件，可批量操作 Edited By M On 2010-5-14
{
	if(is_array($filename))
	{
		foreach($filename as $file)
		{
			delete_file($file);
		}
	}
	else
	{
		if(!file_exists($filename)) return true;
		return @unlink($filename);
	}
}

function sub_string($string, $length, $dot='')
{
	$string=trim($string);
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	$dotlen = strlen($dot);
	$maxi = $length - $dotlen - 1;
	for($i = 0; $i < $maxi; $i++)
	{
		$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
	}
	$strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}

function is_mormal($str)
{
	return preg_match('/^[0-9a-z_]+$/i',trim_str($str));
}

function is_email($email)
{
	if(!$email)return false;
	if(strlen(trim_str($email))>80)return false;
	return preg_match('/^\w+@\w+\.[0-9a-z\._\-]+$/i',trim_str($email));
}

function get_images($str) /////////////////////// 读取文章内所有图片链接，返回数组  2010-5-20
{
	preg_match_all('/<img(.+)src=[\'\"]?([^\'\"]+)[\'\"]?/i',stripslashes($str),$matches,PREG_PATTERN_ORDER);
	$r=array();
	$t=$matches[2];
	foreach($t as $_t)
	{
		$__t=get_fileext($_t);
		if($__t=='gif'||$__t=='jpg'||$__t=='jpeg'||$__t=='png')$r[]=$_t;
	}
	return $r;
}

function down_url_images($str)  //////////////////// 下载远程图片
{
	@set_time_limit(0);
	$str=stripslashes($str);
	$imgs=get_images($str);
	if($imgs)foreach($imgs as $img)
	{		
		if(substr($img,0,7)=='http://')
		{
			$file=@get_file_content($img,true);
			if($file)
			{
				$filename=date('YmdHis').rand(10000,99999).'.'.get_fileext($img);
				$fp=@fopen(DIRCMS_ROOT.'upload/image/'.$filename,'a');
				@fwrite($fp,$file);
				@fclose($fp);

				////////////////////////////////////////// 加水印 2010-5-20
				if(WATERMARK_ENABLED)
				{
					require_once(DIRCMS_ROOT.'include/image.class.php');
					$image=new image();
					$image->watermark(DIRCMS_ROOT.'upload/image/'.$filename,WATERMARK_POS,WATERMARK_FILE,WATERMARK_PCT,WATERMARK_WORDS,WATERMARK_COLOR);
				}
				$localimg[]=DIRCMS_PATH.'upload/image/'.$filename; /////////////////////// 修复一处错误 2010-5-21
			}
			else
			{
				$localimg[]=$img;
			}
		}
		else
		{
			$localimg[]=$img;
		}		
	}
	return $imgs?addslashes(str_replace($imgs,$localimg,$str)):addslashes($str);
}

function add_alt($str,$alt='') //////////////////////////////////// 替换图片alt标签 
{
	return addslashes(preg_replace('/<img(.+)(alt=[\'\"]?[^\'\"]*[\'\"]?)/i','<img\\1alt="'.$alt.'"',stripslashes($str)));
}

function is_url($url)
{
	if(strlen(trim_str($url))>200)return false;
	return preg_match('/^http:\/\/\w+?.{4,200}$/i',trim_str($url));
}

function is_phone_fax($phone)
{
	if(strlen(trim_str($phone))>80)return false;
	return preg_match('/^[0-9\-\(\)]{3,50}$/i',trim_str($phone));
}

function is_postcode($postcode)
{
	if(strlen(trim_str($postcode))>10)return false;
	return preg_match('/^[0-9\-]{4,10}$/i',trim_str($postcode));
}

function is_pwd($str)
{
	if(!$str)return false;
	if(strlen(trim_str($str))>30)return false;
	return preg_match('/^[a-z0-9_]{3,30}$/i',trim_str($str));
}

function is_username($str)
{
	if(!$str)return false;
	if(strlen(trim_str($str))>30)return false;
	return preg_match('/^[\x80-\xff_a-zA-Z0-9]{1,60}$/i',trim_str($str));
}

function get_file_content($file,$url=false) 
{
	if($url)
	{
		if(ini_get('allow_url_fopen') && function_exists('file_get_contents'))
		{
			$opts = array( 
				'http'=>array( 
					'method'=>"GET", 
					'timeout'=>30, 
				) 
			); 
			$context = stream_context_create($opts); 
			return file_get_contents($file, false, $context);
		}
		else if(ini_get('allow_url_fopen') && !function_exists('file_get_contents'))
		{
			$fp=fopen($file,'r');
			$content='';
			while(!feof($fp))
			{
				$content.=fread($fp,8192);
			}
			fclose($fp);

			return $content;
		}
		else
		{	
			if(extension_loaded('curl'))
			{
				$ch=curl_init();
				curl_setopt($ch,CURLOPT_URL,$file);
				curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
				curl_setopt($ch,CURLOPT_HEADER,0);
				$content=curl_exec($ch);
				curl_close($ch);

				return trim($content);
			}
			else
			{
				return '';
			}
		}
	}
	else
	{
		$fp=fopen($file,'r');
		$content='';
		while(!feof($fp))
		{
			$content.=fread($fp,8192);
		}
		fclose($fp);

		return trim($content);
	}
}

function strip_url($str)
{
	return preg_replace('/<a\s+[^>]+>([^>].+[^<])<\/a>/i','\\1',$str);
}

function add_url($str,$flag='true')
{
	$flag=!$flag?'false':'true';
	return preg_replace('/(https?|ftp|telnet|rtsp|mms|callto):\/\/|([0-9a-z]+\.)([a-z0-9\/\-_\+=\.~!%@\?#%&;:\$\\\(\)\|]+)/i','<a href="http://\\2\\3" target="_blank" onClick="return clickUrl(\'http://\\2\\3\',event,'.$flag.');">\\2\\3</a>',$str);
}

function member_cache($flag=false)
{
	global $db;
	$status = $db->get_one_table_status(DB_PRE.'member_cache');
	if($status['Rows'] == 0 || $flag)
	{
		@set_time_limit(0);
		$db->query("REPLACE INTO `".DB_PRE."member_cache` SELECT * FROM `".DB_PRE."member`");
		return true;
	}
	return false;
}

function getcururl()
{
	if(isset($_SERVER['REQUEST_URI']))return $_SERVER['REQUEST_URI'];
	else if(isset($_SERVER['PHP_SELF']) && isset($_SERVER['argv']))return $_SERVER['PHP_SELF'].'?'.$_SERVER['argv'][0];
	else return $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
}

function getpages($number,$page,$pagesize,$ishtml=0,$align='right',$catid=0)  //  分页函数
{
	global $DIRCMS;
	$pagenum=max(1,ceil($number/$pagesize));
	$prepage=max(($page-1),1);
	$nextpage=max(1,min(($page+1),$pagenum));
	if(!$ishtml)
	{
		$cururl=preg_replace('/([&\?]?)(page=[0-9]+)([&\?]?)/i','\\1',getcururl());
		$strlen=strlen($cururl)-1;
		$flag=(boolean)(substr(strrchr($cururl,'/'),1)); /////////////////////////// 2010-6-4 修正
		if(substr($cururl,-1,1)=='&')
		{
			$cururl=$flag?substr($cururl,0,$strlen).'&page=':substr($cururl,0,$strlen).'?page=';
		}
		elseif(substr($cururl,-1,1)=='?')
		{
			$cururl=substr($cururl,0,$strlen).'?page=';
		}
		else{
			if(strpos($cururl,'?')===false && strpos($cururl,'&')===false)$flag=false;
			$cururl=$flag?$cururl.'&page=':$cururl.'?page=';
		}
		
		return '<div align="'.$align.'">&nbsp;&nbsp共'.$number.'条记录，当前第'.$page.'/'.$pagenum.'页  &nbsp;&nbsp;
						<a href="'.$cururl.'1">首页</a>&nbsp;&nbsp;<a href="'.$cururl.$prepage.'">上一页</a>&nbsp;&nbsp;
						<a href="'.$cururl.$nextpage.'">下一页</a>&nbsp;&nbsp;
						<a href="'.$cururl.$pagenum.'">尾页</a>&nbsp;&nbsp;
						第
							<input id="go_page_number" type="text" size="4" style="height:12px; width:20px; border:1px solid #999999;" onkeyup="if(event.keyCode==13){if(document.getElementById(\'go_page_number\').value<='.$pagenum.' && document.getElementById(\'go_page_number\').value>=1 && !isNaN(document.getElementById(\'go_page_number\').value)){window.location.href=\''.$cururl.'\'+document.getElementById(\'go_page_number\').value}else{alert(\'页码为在1-'.$pagenum.'之间的整数!\');document.getElementById(\'go_page_number\').focus();return false}}" /> 
							页 &nbsp;&nbsp<img style="cursor:pointer" src="'.DIRCMS_PATH.'images/go.gif" alt="转到" width="37" height="15" onclick="if(document.getElementById(\'go_page_number\').value<='.$pagenum.' && document.getElementById(\'go_page_number\').value>=1 && !isNaN(document.getElementById(\'go_page_number\').value)){window.location.href=\''.$cururl.'\'+document.getElementById(\'go_page_number\').value}else{alert(\'页码为在1-'.$pagenum.'之间的整数!\');document.getElementById(\'go_page_number\').focus();return false}" /></div>';
	}else{
		$r=cache_read('category'.$catid.'.cache.php',DIRCMS_ROOT.'data/cache_category/');
		$cururl=$r['url'];
		return '<div align="'.$align.'">&nbsp;&nbsp共'.$number.'条记录，当前第'.$page.'/'.$pagenum.'页  &nbsp;&nbsp;
					<a href="'.$cururl.'/index.html">首页</a>&nbsp;&nbsp;
					<a href="'.$cururl.'/'.$prepage.'.html">上一页</a>&nbsp;&nbsp;
					<a href="'.$cururl.'/'.$nextpage.'.html">下一页</a>&nbsp;&nbsp;
					<a href="'.$cururl.'/'.$pagenum.'.html">尾页</a>&nbsp;&nbsp;
					第
							<input id="go_page_number" type="text" size="4" style="height:12px; width:20px; border:1px solid #999999;" onkeyup="if(event.keyCode==13){if(document.getElementById(\'go_page_number\').value<='.$pagenum.' && document.getElementById(\'go_page_number\').value>=1 && !isNaN(document.getElementById(\'go_page_number\').value)){window.location.href=\''.$DIRCMS['site_url'].$cururl.'/\'+document.getElementById(\'go_page_number\').value+\'.html\'}else{alert(\'页码为在1-'.$pagenum.'之间的整数!\');document.getElementById(\'go_page_number\').focus();return false}}" /> 
							页 &nbsp;&nbsp<img style="cursor:pointer" src="'.DIRCMS_PATH.'images/go.gif" alt="转到" width="37" height="15" onclick="if(document.getElementById(\'go_page_number\').value<='.$pagenum.' && document.getElementById(\'go_page_number\').value>=1 && !isNaN(document.getElementById(\'go_page_number\').value)){window.location.href=\''.$DIRCMS['site_url'].$cururl.'/\'+document.getElementById(\'go_page_number\').value+\'.html\'}else{alert(\'页码为在1-'.$pagenum.'之间的整数!\');document.getElementById(\'go_page_number\').focus();return false}" /></div>';
	}
}

function return_words($str) // 过滤后的字符串只适合用户名和邮箱
{
	return preg_replace('/[^a-z0-9_@\.]/i','',$str);
}
function cache_read($cachename,$path='')
{
	$cachename=str_replace('/','',$cachename);
	$cachename=str_replace('\\','',$cachename);
	$path=empty($path)?CACHE_PATH:$path;
	$cachefile=$path.$cachename;
	if(!file_exists($cachefile))return false;
	return @include $cachefile;
}

function cache_write($cachename,$array=array(),$path='')
{
	if(!is_array($array))return false;
	$path=empty($path)?CACHE_PATH:$path;
	$cachefile=$path.$cachename;
	$array="<?php\n//".date('Y-m-d H:i:s',time())."\nreturn ".var_export($array,true).";\n?>"; ///////TIME = time()
	$strlen=file_put_contents($cachefile,$array);
	@chmod($cachefile,0777);
	return $strlen;
}

function string2array($str)
{
	if($str=='') return array();
	eval("\$array = $str;");
	return $array;
}

function cache_config($cachename='common.cache.php',$array=array(),$path='')
{
	if(!is_array($array))return false;
	$path=empty($path)?CACHE_PATH:$path;
	$cachefile=$path.$cachename;
	$array="<?php\n\$DIRCMS=".var_export($array,true).";\n?>";
	$strlen=file_put_contents($cachefile,$array);
	@chmod($cachefile,0777);
	return $strlen;
}

function n_array_diff($a1,$a2) //////////// 2010/8/16
{
	if(function_exists('array_diff_key'))return array_diff_key($a1,$a2);
	else
	{
		$a1=array_flip($a1);
		$a2=array_flip($a2);
		return array_flip(array_diff($a1,$a2));
	}
}

function getchildrencatid($catid)
{
	$t_catid[]=$catid;
	$r=cache_read('parent'.$catid.'.cache.php',DIRCMS_ROOT.'data/cache_category/');
	if($r)foreach($r as $_r)
	{
		$t_catid[]=getchildrencatid($_r['id']);
	};
	return implode(',',$t_catid);
}

function get_childrencatid($catid) //////// 根据当前栏目ID获取其下面的所有子栏目,返回一个数组
{
	return explode(',',getchildrencatid($catid));
}

function cache_delete($cachename,$path='')
{
	$path=empty($path)?CACHE_PATH:$path;
	$cachefile=$path.$cachename;
	return @unlink($cachefile);
}

function create_html($file)
{
	global $DIRCMS,$LANG;
	$data=ob_get_contents();
	ob_clean();
	make_dir(dirname($file));
	$strlen=file_put_contents($file,$data);
	@chmod($file,0777);
	return $strlen;
}

function template($tlpname)
{
	$compliedfile=TPL_CACHEPATH.$tlpname.'.tlp.php';
	if(!file_exists($compliedfile) || filemtime(TPL_ROOT.TPL_NAME.'/'.$tlpname.'.html')>filemtime($compliedfile) || filemtime(TPL_ROOT.TPL_NAME.'/tag.inc.php')>filemtime($compliedfile))
	{
		require_once(DIRCMS_ROOT.'include/template.func.php');
		template_complie($tlpname);
	}
	return $compliedfile;
}

function space_tlp($path='default',$tlp='index')
{
	$compliedfile=TPL_CACHEPATH.'comtmp/'.$path.'/'.$tlp.'.tlp.php';
	if(!file_exists($compliedfile) || filemtime(DIRCMS_ROOT.'template/comtmp/'.$path.'/'.$tlp.'.html')>filemtime($compliedfile) || filemtime(TPL_ROOT.TPL_NAME.'/tag.inc.php')>filemtime($compliedfile))
	{
		require_once(DIRCMS_ROOT.'include/template.func.php');
		spacetlp_complie($path,$tlp);
	}
	return $compliedfile;
}

function get_cache_counts($sql)
{
	global $db,$T;
	$id = md5($sql);
	
	if(!isset($T['count'][$id]))
	{
		if(CACHE_COUNT_TTL)
		{
			$r=$db->fetch_one("SELECT `count`,`updatetime` FROM `".DB_PRE."counts` WHERE `id`='$id'");
			if(!$r||$r['updatetime']<TIME-CACHE_COUNT_TTL)
			{
				$r=$db->fetch_one($sql);
				$T['count'][$id] = $r['count'];
				$db->query("REPLACE INTO `".DB_PRE."counts`(`id`, `count`, `updatetime`) VALUES('$id', '".$r['count']."', '".TIME."')",true);
			}
		}
		else
		{
			$r=$db->get_one($sql);
		}
		$T['count'][$id]=$r['count'];
	}
	return $T['count'][$id];
}

function clear_tag_cache()
{
	@set_time_limit(0);
	$t=glob(DIRCMS_ROOT.'data/cache_tag/*.cache.php');
	if($t)foreach($t as $_t)
	{
		@unlink($_t);
	}
}

function dircms_addslashes($str)
{
	if(!is_array($str))return addslashes($str);
	foreach($str as $key=>$value)
	{
		$str[$key]=dircms_addslashes($value);
	}
	return $str;
}

function mysql_escapestr($str)
{
	if(!is_array($str))return mysql_escape_string($str);
	foreach($str as $key=>$value)
	{
		$str[$key]=mysql_escapestr($value);
	}
	return $str;
}

function is_final_catid($catid)
{
	$r=cache_read('finalcatid.cache.php',DIRCMS_ROOT.'data/cache_category/');
	$r=$r?$r:array();
	return in_array($catid,$r);
}

function dircms_stripslashes($str)
{
	if(!is_array($str))return stripslashes($str);
	foreach($str as $key => $value)
	{
		$str[$key]=dircms_stripslashes($value);
	}
	return $str;
}

function dircms_htmlspecialchars($str)
{
	if(!is_array($str))return htmlspecialchars($str);
	foreach($str as $key=>$value)
	{
		$str[$key]=dircms_htmlspecialchars($value);
	}
	return $str;
}


function searchoption($catid=0,$modelid=0)
{
	global $page,$DIRCMS;
	if(!$catid)global $catid;
	if(!$catid && !$modelid)return false;
	if(!$modelid)
	{
		$r=cache_read('category'.$catid.'.cache.php',DIRCMS_ROOT.'data/cache_category/');
		if(!$r)return false;
		$modelid=$r['modelid'];
	}
	unset($r);
	@extract($_REQUEST,EXTR_SKIP);
	if(!$modelid)return false;
	$t=$flag=array();
	$r=cache_read('cache_model'.$modelid.'.fields.cache.php',DIRCMS_ROOT.'data/cache_model/');
	if($r)foreach($r as $_r)
	{
		if($_r['issearch'] && in_array($_r['formtype'],array('radio','select','checkbox')))
		{
			$t[$_r['searchbyvalue']]=$_r;
			$flag[$_r['searchbyvalue']]=$_r['searchbyvalue'];
		}
	}
	if(!$t)return false;
	else
	{
		$searchoptions='';
		$aquery=array();
		foreach($t as $tkey => $_t)
		{				
			if(in_array($_t['formtype'],array('radio','select','checkbox')))
			{
				$tv=array();	
				$option=explode("\r\n",$_t['optionvalue']);
				$option=array_merge(array('|不限'),$option);
				foreach($option as $_option)
				{
					$t_option=explode('|',$_option);
					if($t_option[0]!=='0')
					{
						$text=${$_t['searchbyvalue']}!=$t_option[0]?$t_option[1]:'<span class="redbg">'.$t_option[1].'</span>';
						$aquery[$_t['searchbyvalue']]='&'.$_t['searchbyvalue'].'='.urlencode($t_option[0]);		
						foreach($flag as $fkey => $fvalue)
						{
							$aquery=array_unique($aquery);
							if(isset($_GET[$fkey]) && $fkey!=$_t['searchbyvalue'])$aquery[$fkey]='&'.$fkey.'='.urlencode($_GET[$fkey]);
						}
						$aquerystring=implode('',$aquery);
						$tv[]='<a href="'.$DIRCMS['site_url'].'search/index.php?type=content&catid='.$catid.$aquerystring.'">'.$text.'</a>';
					}
				}
				$tv=implode('&nbsp;&nbsp;',$tv);
				$searchoptions.='<b>'.$_t['fieldname'].'</b>：'.$tv.'<br />';
			}
			$i++;
		}
		return $searchoptions;
	}
}


function cmpt($a, $b)
{
	return strcmp($a["template"], $b["template"]);
}
?>