<?php
if(!defined('IN_PHPQUAN'))
{
	die('Access Denied');
}
function cut_str($str, $length, $start=0)
{
	global $charset;
	if(function_exists("mb_substr")) {
	    if(mb_strlen($str, $charset) <= $length) return $str;
	    $slice = mb_substr($str, $start, $length, $charset);
	} else {
		$re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		if(count($match[0]) <= $length) return $str;
		$slice = join("",array_slice($match[0], $start, $length));
	}
	return $slice;
}
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);
    }
}
function addslashes_deep($value)
{
	if (empty($value))
	{
		return $value;
	}
	else
	{
		if(is_array($value))
		{
			foreach($value as $key => $v)
			{
				unset($value[$key]);
				if($htmlspecialchars==true)
				{
					$key=get_magic_quotes_gpc()? addslashes(stripslashes(htmlspecialchars($key,ENT_NOQUOTES))) : addslashes(htmlspecialchars($key,ENT_NOQUOTES));
				}
				else{
					$key=get_magic_quotes_gpc()? addslashes(stripslashes($key)) : addslashes($key);
				}
				if(is_array($v))
				{
					$value[$key]=addslashes_deep($v);
				}
				else
				{
					if($htmlspecialchars==true)
					{
						$value[$key]=get_magic_quotes_gpc()? addslashes(stripslashes(htmlspecialchars($v,ENT_NOQUOTES))) : addslashes(htmlspecialchars($v,ENT_NOQUOTES));
					}
					else{
						$value[$key]=get_magic_quotes_gpc()? addslashes(stripslashes($v)) : addslashes($v);
					}
				}
			}
		}
		else
		{
			if($htmlspecialchars==true)
			{
				$value=get_magic_quotes_gpc()? addslashes(stripslashes(htmlspecialchars($value,ENT_NOQUOTES))) : addslashes(htmlspecialchars($value,ENT_NOQUOTES));
			}
			else{
				$value=get_magic_quotes_gpc()? addslashes(stripslashes($value)) : addslashes($value);
			}
		}
		return $value;
	}
}
function stripslashes_deep($value)
{
	return is_array($value) ? array_map('stripslashes_deep', $value) : (isset($value) ? stripslashes($value) : null);
}
function htmlspecialchars_deep($value)
{
	return is_array($value) ? array_map('htmlspecialchars_deep', $value) : str_replace('&amp;', '&', htmlspecialchars($value, ENT_QUOTES));
}
function key_replace($array, $deep = 0) {
	foreach($array as $k=>$v) {
		if($deep && !preg_match("/^[a-z0-9_\-]{1,}$/i", $k)) {
			die('error');
		}
		if(is_array($v)) key_replace($v, 1);
	}
}
//对内容进行过滤
function safe_replace($string) {
	if(is_array($string)) {
		return array_map('safe_replace', $string);
	} else {
		if(strlen($string) < 20) return $string;
		$match = array("/&#([a-z0-9]+)([;]*)/i","/\<\!\-\-([\s\S]*?)\-\-\>/","/\/\*([\s\S]*?)\*\//","/on(mouse|exit|error|click|dblclick|key|load|unload|change|move|submit|reset|cut|copy|select|start|stop|drag|touch)/i","/s[[:space:]]*c[[:space:]]*r[[:space:]]*i[[:space:]]*p[[:space:]]*t/i","/about/i","/frame/i","/link/i","/import/i","/expression/i","/meta/i","/textarea/i","/eval/i");
		$replace = array("","","","o&#110;\\1","scrip&#116;","abou&#116;","fram&#101;","lin&#107;","impor&#116;","expressio&#110;","met&#97;","textare&#97;","eva&#108;");
		return preg_replace($match, $replace, $string);
	}
}
/**
 * sql语句过滤
 *
 * @param $string
 * @return string
 */
function sql_replace($string) {
	$match = array("/select/i","/concat/i","/char/i","/sleep/i","/union/i","/where/i","/outfile/i","/dumpfile/i","/0x([a-z0-9]{2,})/i","/select([\s\S]*?)from/i","/select([\s\*\/\-\(\+@])/i","/update([\s\*\/\-\(\+@])/i","/replace([\s\*\/\-\(\+@])/i","/delete([\s\*\/\-\(\+@])/i","/drop([\s\*\/\-\(\+@])/i","/load_file[\s]*\(/i","/substring[\s]*\(/i","/substr[\s]*\(/i","/left[\s]*\(/i","/concat[\s]*\(/i","/concat_ws[\s]*\(/i","/make_set[\s]*\(/i","/ascii[\s]*\(/i","/hex[\s]*\(/i","/ord[\s]*\(/i","/char[\s]*\(/i");
	$replace = array('selec&#116;','conca&#116;','cha&#114;','sl&#101;ep','unio&#110;','wher&#101;','outfil&#101;','dumpfil&#101;','0&#120;\\1','selec&#116;\\1from','selec&#116;\\1','updat&#101;\\1','replac&#101;\\1','delet&#101;\\1','dro&#112;\\1','load_fil&#101;(','substrin&#103;(','subst&#114;(','lef&#116;(','conca&#116;(','concat_w&#115;(','make_se&#116;(','asci&#105;(','he&#120;(','or&#100;(','cha&#114;(');
	return is_array($string) ? array_map('sql_replace', $string) : preg_replace($match, $replace, $string);
}
function keyword_replace($kw) {
	$kw = htmlspecialchars(trim(urldecode($kw)));
	if($kw) {
		if(strpos($kw, '%') !== false) return '';
		$kw = str_replace("'", '', $kw);
	}
	return $kw;
}
function random($length,$types='')
{
	if($types=='1'){
		$chars = '1234567890123456789';
	}else{
		$chars = '123456789ABCDEFGHIJ123456789KLMNPQRSTJ123456789VWXYZ123456789abcdefghijJ123456789kmnpqrstJ123456789vwxyz123456789';
	}
	$max = strlen($chars);
	mt_srand((double)microtime() * 1000000);
	for($i = 0; $i < $length; $i ++) {
		$hash .= $chars[mt_rand(0, $max)];
	}
	return $hash;
}
function is_email($email)
{
	return strlen($email) > 8 && preg_match("/^[-_+.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+([a-z]{2,4})|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email);
}
function checkupfile($file)
{
	return function_exists('is_uploaded_file') && (is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file)));
}
function fileext($filename) 
{
	return trim(substr(strrchr($filename, '.'), 1));
}
function get_ip()
{
    static $ip = NULL;
    if($ip !== NULL){return $ip;}
    if(isset($_SERVER)) {
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($arr as $ip) {
                $ip = trim($ip);
                if($ip != 'unknown') {
                    $ip = $ip;
                    break;
                }
            }
        } elseif(isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            if(isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            } else {
                $ip = '0.0.0.0';
            }
        }
    } else {
        if(getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } else {
            $ip = getenv('REMOTE_ADDR');
        }
    }
    preg_match("/[\d\.]{7,15}/", $ip, $onlineip);
    $ip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
    return $ip;
}
function chkcode($width = 60, $height = 22, $count = 4)
{
	$randnum = "";
	if(function_exists("imagecreatetruecolor") && function_exists("imagecolorallocate") && function_exists("imagestring") && function_exists("imagepng") && function_exists("imagesetpixel") && function_exists("imagefilledrectangle") && function_exists("imagerectangle")) {
		$image  = imagecreatetruecolor($width, $height);
		$swhite = imagecolorallocate($image, 255, 255, 255);
		$sblack = imagecolorallocate($image, 0, 0, 0);
		
		//建立矩形
		imagefilledrectangle($image, 0, 0, ($width -2), ($height -2), $swhite);
		imagerectangle($image, 0, 0, $width, $height, $sblack);
		
		//生成干扰像素
		for ($i = 0; $i < 20; $i++) {
			$sjamcolor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
			imagesetpixel($image, rand(0, $width), rand(0, $height), $sjamcolor);
		}
		
		//随机数字
		for ($i = 0; $i < $count; $i++) {
			$randnum .= rand(1, 9);
		}
		//将文字写入图像
		$widthx = floor($width / $count);
		for ($i = 0; $i < strlen($randnum); $i++) {
			$irandomcolor = imagecolorallocate($image, rand(50, 255), rand(50, 120), rand(50, 255));
			imagestring($image, 6, ($widthx * $i +rand(1, 3)), rand(1, 5), $randnum {$i }, $irandomcolor);
		}
		header("Pragma:no-cache");
		header("Cache-control:no-cache");
		header("Content-type: image/png");
		imagepng($image);
		imagedestroy($image);
	} else {
		header("Pragma:no-cache");
		header("Cache-control:no-cache");
		header("Content-type: image/png");
		if (!readfile("images/chkcode.png")) {return false;}
		$randnum = "2293";
	}
	return $randnum;
}
function check_code($checkcode)
{
	$chkcode = $_SESSION['chkcode'];
	if(empty($chkcode) || $chkcode != $checkcode)showmsg('验证码错误');
}
function page($file,$cat,$area,$count,$size=20,$page=1)
{
	global $tpl;
    $page = intval($page);
    if($page<1)$page = 1;
    $page_count = $count > 0 ? intval(ceil($count / $size)) : 1;
    $page_prev  = ($page > 1) ? $page - 1 : 1;
    $page_next  = ($page < $page_count) ? $page + 1 : $page_count;
	$pager['start']      = ($page-1)*$size;
    $pager['page']       = $page;
    $pager['size']       = $size;
    $pager['count']		 = $count;
    $pager['page_count'] = $page_count;
	
	switch ($file)
    {
        case 'category':
			$params = array('cid' => $cat, 'eid' => $area);
        break;
		
		case 'com';
			$params = array('catid' => $cat, 'eid' => $area, 'act'=>'list');
		break;
		case 'article';
			$params = array('iid' => $cat, 'act'=>'list');
		break;
		
		case 'help';
			$params = array('tid' => $cat, 'act'=>'list');
		break;
    }
	if($page_count <= '1') {
	    $pager['first'] = $pager['prev']  = $pager['next']  = $pager['last']  = '';
	} elseif($page_count > '1') {
		if($page == $page_count) {
			$pager['first'] = url_rewrite($file, $params, 1);
			$pager['prev']  = url_rewrite($file, $params, $page_prev);
			$pager['next']  = '';
			$pager['last']  = '';
		} elseif($page_prev == '1' && $page == '1') {
			$pager['first'] = '';
			$pager['prev']  = '';
			$pager['next']  = url_rewrite($file, $params, $page_next);
			$pager['last']  = url_rewrite($file, $params, $page_count);
		} else {
			$pager['first'] = url_rewrite($file, $params, 1);
			$pager['prev']  = url_rewrite($file, $params, $page_prev);
			$pager['next']  = url_rewrite($file, $params, $page_next);
			$pager['last']  = url_rewrite($file, $params, $page_count);
		}
	}
    return $pager;
}
function get_pager($url, $param, $count, $page = 1, $size = 10)
{
    $size = intval($size);
    if($size < 1)$size = 10;
    $page = intval($page);
    if($page < 1)$page = 1;
    $count = intval($count);
    $page_count = $count > 0 ? intval(ceil($count / $size)) : 1;
    if ($page > $page_count)$page = $page_count;
    $page_prev  = ($page > 1) ? $page - 1 : 1;
    $page_next  = ($page < $page_count) ? $page + 1 : $page_count;
    $param_url = '?';
    foreach ($param as $key => $value)$param_url .= $key . '=' . $value . '&';
    $pager['url']        = $url;
    $pager['start']      = ($page-1) * $size;
    $pager['page']       = $page;
    $pager['size']       = $size;
    $pager['count']		 = $count;
    $pager['page_count'] = $page_count;
	if($page_count <= '1') {
	    $pager['first'] = $pager['prev']  = $pager['next']  = $pager['last']  = '';
	} else {
		if($page == $page_count) {
			$pager['first'] = $url . $param_url . 'page=1';
			$pager['prev']  = $url . $param_url . 'page=' . $page_prev;
			$pager['next']  = '';
			$pager['last']  = '';
		} elseif($page_prev == '1' && $page == '1') {
			$pager['first'] = '';
			$pager['prev']  = '';
			$pager['next']  = $url . $param_url . 'page=' . $page_next;
			$pager['last']  = $url . $param_url . 'page=' . $page_count;
		} else {
			$pager['first'] = $url . $param_url . 'page=1';
			$pager['prev']  = $url . $param_url . 'page=' . $page_prev;
			$pager['next']  = $url . $param_url . 'page=' . $page_next;
			$pager['last']  = $url . $param_url . 'page=' . $page_count;
		}
	}
    return $pager;
}
//新分页page
function get_page($url, $param, $count, $page = 1, $size = 10, $param_urls='?act=json&')
{
    $size = intval($size);
    if($size < 1)$size = 10;
    $page = intval($page);
    if($page < 1)$page = 1;
    $count = intval($count);
    $page_count = $count > 0 ? intval(ceil($count / $size)) : 1;
    if ($page > $page_count)$page = $page_count;
    $page_prev  = ($page > 1) ? $page - 1 : 1;
    $page_next  = ($page < $page_count) ? $page + 1 : $page_count;
    $param_url = $param_urls;
    foreach ($param as $key => $value){
		if(!empty($value)){
			$param_url .= $key . '=' . $value . '&';
		}
	}
	$pager['url']		 = $url . $param_url;
    $pager['start']      = ($page-1) * $size;
    $pager['page']       = $page;
    $pager['size']       = $size;
    $pager['count']		 = $count;
    $pager['page_count'] = $page_count;
    return $pager;
}

function url_rewrite($app, $params, $page = 0, $size = 0)
{
	global $CFG,$_userid;
    static $rewrite = NULL;
    if($rewrite === NULL)$rewrite = intval($CFG['rewrite']);
    $args = array('aid'=> 0,'bid'=>'0','cid'=> 0,'vid'=> 0,'eid'=> '0','tid'=>'0','hid'=>'0' );
    @extract(array_merge($args, $params));
    $uri = '';
    switch($app)
    {
        case 'list':
                if($rewrite) {
                    if(!empty($page))$uri .= '-page-' . $page;
                }else{
					$uri = 'list.php?';
					if(!empty($order)) $uri .= 'order=' . $order;
					if(!empty($qcid)) $uri .= '&qcid=' . $qcid;
					if(!empty($catid)) $uri .= '&catid=' . $catid;
					if(!empty($comid)) $uri .= '&comid=' . $comid;
					if(!empty($keyword)) $uri .= '&keyword=' . $keyword;
                    if(!empty($page)) $uri .= '&page=' . $page;
                }
        break;
		case 'coms':
                if($rewrite) {
                    if(!empty($page))$uri .= '-page-' . $page;
                }else{
					$uri = 'coms.php?';
					if(!empty($order)) $uri .= 'order=' . $order;
					if(!empty($catid)) $uri .= '&catid=' . $catid;
					if(!empty($comid)) $uri .= '&comid=' . $comid;
					if(!empty($keyword)) $uri .= '&keyword=' . $keyword;
                    if(!empty($page)) $uri .= '&page=' . $page;
                }
        break;
		case 'view':
            if(empty($vid)) {
                return false;
            }else{
                $myid = !empty($_userid) ? '&myid='.$_userid : '';
				$uri = $rewrite ? 'view-' . $vid : 'view.php?id=' . $vid.$myid;
            }
        break;
		case 'com':
            if($act=='list_comment') {
                if($rewrite) {
                    if(!empty($page))$uri .= '-page-' . $page;
                }else{
					$uri = 'com.php?act=list_comment';
					if(!empty($order)) $uri .= '&order=' . $order;
					if(!empty($comid)) $uri .= '&comid=' . $comid;
                    if(!empty($page)) $uri .= '&page=' . $page;
                }
            } elseif($act=='view' && $comid) {
                if($rewrite) {
                    $uri = 'com-view-' . $comid.'';
                }else{
                    $uri = 'com.php?act=view&id=' . $comid;
                }
            }
        break;
		case 'comment':
            if($act=='list_comment') {
                if($rewrite) {
                    if(!empty($page))$uri .= '-page-' . $page;
                }else{
					$uri = 'comment.php?act=list_comment';
					if(!empty($order)) $uri .= '&order=' . $order;
					if(!empty($comid)) $uri .= '&comid=' . $comid;
                    if(!empty($page)) $uri .= '&page=' . $page;
                }
            } 
        break;
		case 'about':
            if(empty($aid)) {
                return false;
            }else{
                $uri = $rewrite ? 'about-' . $aid : 'about.php?id=' . $aid;
            }
        break;
   
        default:
            return false;
        break;
    }
    if($rewrite)$uri .= '.html';
    return $uri;
}
function iconvs($from_encoding, $to_encoding, $str_or_array)
{
	if(!is_array($str_or_array) && empty($str_or_array)) return "";
	$from_encoding = strtolower($from_encoding);
	$to_encoding = strtolower($to_encoding);
	$converarray = array();
	if($from_encoding == $to_encoding) return $str_or_array;
	if(($from_encoding == "big5" && $to_encoding == "gb2312")||($from_encoding == "gb2312" && $to_encoding == "big5")) $flag = false;
	else $flag = true;
	if(function_exists('mb_convert_encoding') && $to_encoding != 'pinyin' && $flag) {
		if(!is_array($str_or_array)) {
			return mb_convert_encoding($str_or_array, $to_encoding, $from_encoding);
		} else {
			foreach($str_or_array as $key => $val) {
				$converarray[$key] = mb_convert_encoding($val, $to_encoding, $from_encoding);
			}
			return $converarray;
		}
	} else if(function_exists('iconv') && $to_encoding != 'pinyin' &&$flag) {
		if(!is_array($str_or_array)) {
			return iconv($from_encoding, $to_encoding."//IGNORE", $str_or_array);
		} else {
			foreach($str_or_array as $key => $val) {
				$converarray[$key] = iconv($from_encoding, $to_encoding."//IGNORE", $val);
			}
			return $converarray;
		}
	} else {
		require_once PHPQUAN_ROOT."include/convert.class.php";
		$chs = new chinese();
		$charset=array("utf8","gb2312","big5","unicode","pinyin");
		if(!in_array($from_encoding,$charset)) {
			return "The codepage-".$from_encoding." is not support!";
		} else if(!in_array($to_encoding,$charset)) {
			return "The codepage-".$to_encoding." is not support!";
		} else {
			$from_encoding = strtoupper($from_encoding);
			$to_encoding = strtoupper($to_encoding);
			if(!is_array($str_or_array)) {
				return $chs->Convert($from_encoding,$to_encoding,$str_or_array);
			} else {
				foreach($str_or_array as $key => $val) {
					$converarray[$key] = $chs->Convert($from_encoding,$to_encoding,$val);
				}
				return $converarray;
			}
		}
	}
}
function enddate($date)
{
	if($date > 0) {
		if($date > time()) {
			$a = round(($date-time())/86400);
			if($a<1) $a = 1;
			$day = "剩余<font color=red>$a</font>天";
		} else {
			$day = '已过期';
		}
	} else {
		$day = '长期有效';
	}
	
	return $day;
}
function template($file)
{
	global $CFG;
	$compiledfile = PHPQUAN_ROOT.'data/compiled/'.$file.'.php';
	$tplfile = PHPQUAN_ROOT.'/templates/'.$CFG['tplname'].'/'.$file.'.htm';
	if(!file_exists($compiledfile) || @filemtime($tplfile) > @filemtime($compiledfile)) {
		template_compile($tplfile, $compiledfile);
	}
	return $compiledfile;
}
function showmsg($msg,$url='goback')
{
    include template('show');
	exit();
}
/**
 *  清除指定后缀的模板缓存或编译文件
 *
 * @access  public
 * @param  string     $type  要清除的类型
 * @param  string     $ext   需要删除的文件名，不包含后缀
 *
 * @return int        返回清除的文件个数
 */
function clear_caches($type = 'phpcache', $ext = '')
{
    $dirs = array();
    $tmp_dir = 'data';
    
    if ($type=='phpcache') {
        $dirs = array(PHPQUAN_ROOT . $tmp_dir . '/phpcache/');
    }  elseif ($type=='sqlcache') {
        $dirs = array(PHPQUAN_ROOT . $tmp_dir . '/sqlcache/');
    } elseif ($type=='compiled') {
        $dirs = array(PHPQUAN_ROOT . $tmp_dir . '/compiled/');
    }
    $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 = 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;
}
function get_cat_array()
{
	global $db, $table;
	$data = read_cache('cat_array');
	if ($data === false) {
		$sql = "select catid,catname from {$table}juan_cat order by catid ";
		$res = $db->query($sql);
		while($row=$db->fetchrow($res)) {
				$cat_array[$row['catid']][] = $row['catname'];
		}
		write_cache('cat_array', $cat_array);
	} else {
		$cat_array = $data;
	}
	return $cat_array;
}
function get_com_cat_array()
{
	global $db, $table;
	$data = read_cache('com_cat_array');
	if ($data === false) {
		$sql = "select catid,catname from {$table}com_cat order by catid ";
		$res = $db->query($sql);
		while($row=$db->fetchrow($res)) {
			$com_cat_array[$row['catid']] = $row['catname'];
		}
		write_cache('com_cat_array', $com_cat_array);
	} else {
		$com_cat_array = $data;
	}
	return $com_cat_array;
}
function get_parent_cat()
{
	global $db,$table;
	
	$data = read_cache('parent_cat');
	if ($data === false) {
		$sql = "select catid,catname from {$table}category where parentid = '0' ";
		$res = $db->query($sql);
		while($row=$db->fetchrow($res)) {
			$parent_cat[] = $row;
		}
		write_cache('parent_cat', $parent_cat);
	} else {
		$parent_cat = $data;
	}
	return $parent_cat;
}
function get_cat_list()
{
	global $db,$table;
	
	static $cats = NULL;
	if ($cats === NULL) {
		$data = read_cache('cat_list');
		if ($data === false) {
			$sql = "select * from {$table}juan_cat order by catorder asc,catid asc";
			$res = $db->getAll($sql);
			$cats = array();
			foreach ($res as $row) {
				$cats[$row['catid']]['catid']   = $row['catid'];
				$cats[$row['catid']]['catname'] = $row['catname'];
				$cats[$row['catid']]['pay'] = $row['pay'];
				$cats[$row['catid']]['red'] = $row['red'];
				$cats[$row['catid']]['bgcolor'] = $row['bgcolor'];
				$cats[$row['catid']]['catinfo'] = $row['catinfo'];
				$cats[$row['catid']]['caturl']  = url_rewrite('category',array('cid'=>$row[catid]));
			}
			write_cache('cat_list', $cats);
		} else {
			$cats = $data;
		}
	}
	return $cats;
}
function cat_options($selectid='',$catid='')
{
	$cats = get_cat_list();
	if($catd){$cats = $cats[$catid];}
	foreach((array)$cats as $cat) {
		$option .= "<option value=$cat[catid] style='color:red;'";
		$option .= ($selectid == $cat['catid']) ? " selected='selected'" : '';
		$option .= ">$cat[catname]</option>";
		if(!empty($cat['children'])) {
			foreach($cat['children'] as $chi) {
				$option .= "<option value=$chi[id]";
				$option .= ($selectid == $chi['id']) ? " selected='selected'" : '';
				$option .= ">&nbsp;&nbsp;|--$chi[name]</option>";
			}
		}
	}
	return $option;
}
function get_cat_children($catid,$type='int')
{
	$cats = get_cat_list();
	$cat_children = $cats[$catid]['children'];
	if(is_array($cat_children)) {
		if($type=='int') {
			foreach($cat_children as $child) {
				$id .= $child['id'].',';
			}
			$result = substr($id,0,-1);
		} elseif($type=='array') {
			$result = $cat_children;
		}
	} else {
		if($type=='int') {
			$result = $catid;
		} elseif($type=='array') {
			$result = '';
		}
	}
	return $result;
}
function get_cat_info($catid)
{
	global $db,$table;
	
	$data = read_cache('cat_'.$catid);
	if ($data === false) {
		$sql = "select * from {$table}juan_cat where catid='$catid' ";
		$cat_info = $db->getRow($sql);
		write_cache('cat_'.$catid, $cat_info);
	} else {
		$cat_info = $data;
	}
	return $cat_info;
}
function get_config()
{
	global $db,$table;
	$data = read_cache('webconfig');
    if ($data === false) {
		$sql = "select setname,value from {$table}config";
		$res = $db->query($sql);
		while($row=$db->fetchRow($res)) {
			$config[$row['setname']] = $row['value'];
			if($row['setname']=='qq' && $row['value']) {
				$config[$row['setname']] = explode('|', $row['value']);
			}
		}
		write_cache('webconfig', $config);
	} else {
		$config = $data;
	}
	return $config;
}
function get_configs()
{
	global $db,$table;
		$sql = "select setname,value from {$table}config";
		$res = $db->query($sql);
		while($row=$db->fetchRow($res)) {
			$config[$row['setname']] = $row['value'];
			if($row['setname']=='qq' && $row['value']) {
				$config[$row['setname']] = explode('|', $row['value']);
			}
		}
		//write_cache('webconfig', $config);
	return $config;
}
function get_juan($cat='',$area='',$num='10',$protype='',$listtype='',$len='20',$thumb='', $dateformat='y-m-d')
{
	global $db,$table;
	
	$where = "where is_check=1 and (enddate='0' or enddate >= ".time().")";
	if(!empty($cat)) {
		$where .= " and i.catid in ($cat)";
	}
	if(!empty($area)) {
		$where .= " and i.areaid in ($area)";
	}
	if($thumb=='1') {
		$where .= " and thumb != '' ";
	}
	if(!empty($protype)) {
		switch($protype) {
			case 'pro':
				$where .= " and is_pro >=".time();
			break;
			
			case 'top':
				$where .= " and is_top >=".time();
			break;
		}
	}
	if(!empty($listtype)) {
		switch($listtype) {
			case 'date':
				$order = " order by postdate desc";
			break;
			
			case 'click':
				$order = " order by click desc, id desc ";
			break;
		}
	}
	if(empty($order)) $order = "order by postdate desc";
	$limit = " LIMIT 0,$num ";
	$sql = "select i.id,i.title,i.postdate,i.thumb,i.description,i.catid,i.areaid,c.catname,a.areaname from {$table}juan as i left join {$table}juan_cat as c on i.catid = c.catid left join {$table}area as a on a.areaid = i.areaid $where $order $limit";
	$res = $db->query($sql);
	$juan = array();
	while($row=$db->fetchRow($res)) {
		$row['title']    = cut_str($row['title'], $len);
		$row['postdate'] = date($dateformat, $row['postdate']);
		$row['url']      = url_rewrite('view',array('vid'=>$row['id']));
		$juan[]          = $row;
	}
	return $juan;
}
function get_nav($navwz='')
{
	global $db,$table;
	if(!empty($navwz)){
		$sqls = "where navwz='$navwz'";
	}
	$data = read_cache('nav_'.$navwz);
    if ($data === false) {
		$sql = "select * from {$table}nav $sqls order by navorder";
		$nav = $db->getAll($sql);
		write_cache('nav_'.$navwz, $nav);
	} else {
		$nav = $data;
	}
	return $nav;
}
function template_compile($tplfile,$tplcachefile)
{
	$str = file_get_contents($tplfile);
	$str = template_parse($str);
	$strlen = file_put_contents($tplcachefile, $str);
	@chmod($tplcachefile, 0777);
	return $strlen;
}
function template_parse($tpl)
{
	$tpl = preg_replace("/([\n\r]+)\t+/s","\\1",$tpl);
	$tpl = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}",$tpl);
	$tpl = preg_replace("/\{template\s+(.+)\}/","\n<?php include template(\\1); ?>\n",$tpl);
	$tpl = preg_replace("/\{include\s+(.+)\}/","\n<?php include \\1; ?>\n",$tpl);
	$tpl = preg_replace("/\{php\s+(.+)\}/","\n<?php \\1?>\n",$tpl);
	$tpl = preg_replace("/\{if\s+(.+?)\}/","<?php if(\\1) { ?>",$tpl);
	$tpl = preg_replace("/\{else\}/","<?php } else { ?>",$tpl);
	$tpl = preg_replace("/\{elseif\s+(.+?)\}/","<?php } elseif (\\1) { ?>",$tpl);
	$tpl = preg_replace("/\{\/if\}/","<?php } ?>",$tpl);
	$tpl = preg_replace("/\{loop\s+(\S+)\s+(\S+)\}/","<?php if(is_array(\\1)) foreach(\\1 AS \\2) { ?>",$tpl);
	$tpl = preg_replace("/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}/","\n<?php if(is_array(\\1)) foreach(\\1 AS \\2 => \\3) { ?>",$tpl);
	$tpl = preg_replace("/\{\/loop\}/","\n<?php } ?>\n",$tpl);
	$tpl = preg_replace("/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\(([^{}]*)\))\}/","<?php echo \\1;?>",$tpl);
	$tpl = preg_replace("/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\(([^{}]*)\))\}/","<?php echo \\1;?>",$tpl);
	$tpl = preg_replace("/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/","<?php echo \\1;?>",$tpl);
	$tpl = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/es", "addquote('<?php echo \\1;?>')",$tpl);
	$tpl = preg_replace("/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php echo \\1;?>",$tpl);
	$tpl = "<?php if(!defined('IN_PHPQUAN'))die('Access Denied'); ?>".$tpl;
	return $tpl;
}
function addquote($var)
{
	return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
}
if (!function_exists('file_get_contents'))
{
    function file_get_contents($file)  {
        if (($fp = @fopen($file, 'rb')) === false) {
            return false;
        } else {
            $fsize = @filesize($file);
            if ($fsize) {
                $contents = fread($fp, $fsize);
            } else {
                $contents = '';
            }
            fclose($fp);
            return $contents;
        }
    }
}
if (!function_exists('file_put_contents'))
{
    define('FILE_APPEND', 'FILE_APPEND');
    function file_put_contents($file, $data, $flags = '') {
        $contents = (is_array($data)) ? implode('', $data) : $data;
        if ($flags == 'FILE_APPEND') {
            $mode = 'ab+';
        } else {
            $mode = 'wb';
        }
        if (($fp = @fopen($file, $mode)) === false) {
            return false;
        } else {
            $bytes = fwrite($fp, $contents);
            fclose($fp);
            return $bytes;
        }
    }
}
function read_cache($filename)
{
    $result = array();
    if (!empty($result[$filename])) {
        return $result[$filename];
    }
    $filepath = PHPQUAN_ROOT . 'data/phpcache/' . $filename . '.php';
    if (file_exists($filepath)) {
        include_once($filepath);
        $result[$filename] = $data;
        return $result[$filename];
    } else {
        return false;
    }
}
function write_cache($filename, $val)
{
    $filepath = PHPQUAN_ROOT . 'data/phpcache/' . $filename . '.php';
    $content  = "<?php\r\n";
    $content .= "\$data = " . var_export($val, true) . ";\r\n";
    $content .= "?>";
    file_put_contents($filepath, $content, LOCK_EX);
}
function get_url()
{
	$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
	$php_domain = $_SERVER['SERVER_NAME'];
	$php_agent = $_SERVER['HTTP_USER_AGENT'];
	$php_referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
	$php_scheme = $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_reuri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
	$php_port = $_SERVER['SERVER_PORT'] == '80' ? '' : ':'.$_SERVER['SERVER_PORT'];
	$host_url = $php_scheme . $php_domain . $php_port;
	$site_url = $host_url . substr($php_self, 0, strrpos($php_self, '/'));
	$site_url = str_replace('/install', '', $site_url);
	$site_url = str_replace('/admin', '', $site_url);
	return $site_url;
}
function get_domain($url)
{
	$pattern = "/[\w-]+\.[\w-]+\.(com|net|org|gov|cc|biz|info|cn)(\.(cn|hk))*/";
	preg_match($pattern, $url, $matches);
	if(count($matches) > 0)  {
		return $matches[0];
	} else {
		$rs = parse_url($url);
		$main_url = $rs["host"];
		if(!strcmp(long2ip(sprintf("%u",ip2long($main_url))),$main_url)) {
			return $main_url;
		} else {
			$arr = explode(".",$main_url);
			$count=count($arr);
			$endArr = array("com","net","org","3322");//com.cn  net.cn 等情况
			
			if (in_array($arr[$count-2],$endArr)) {
				$domain = $arr[$count-3].".".$arr[$count-2].".".$arr[$count-1];
			} else {
				$domain =  $arr[$count-2].".".$arr[$count-1];
			}
			return $domain;
		}
	}
}
function check_words($who=array())
{
	global $CFG;
	if(!empty($CFG['banwords'])) {
		$ban = explode('|',$CFG['banwords']);
		$count = count($ban);
		for($i=0;$i<$count;$i++){
			foreach($who as $val) {
				if(strstr($val,$ban[$i])){
					showmsg('您发布的信息中有违禁词语');
				}
			}
		}
	}
}
function CreateSmallImage( $OldImagePath, $NewImagePath, $NewWidth=154, $NewHeight=134) 
{
	// 取出原图，获得图形信息getimagesize参数说明：0(宽),1(高),2(1gif/2jpg/3png),3(width="638" height="340")
	$OldImageInfo = getimagesize($OldImagePath); 
	if ( $OldImageInfo[2] == 1 ) $OldImg = @imagecreatefromgif($OldImagePath); 
	elseif ( $OldImageInfo[2] == 2 ) $OldImg = @imagecreatefromjpeg($OldImagePath); 
	else $OldImg = @imagecreatefrompng($OldImagePath);
	// 创建图形,imagecreate参数说明：宽,高 
	$NewImg = imagecreatetruecolor( $NewWidth, $NewHeight ); 
	//创建色彩,参数：图形,red(0-255),green(0-255),blue(0-255) 
	$black = ImageColorAllocate( $NewImg, 0, 0, 0 ); //黑色 
	$white = ImageColorAllocate( $NewImg, 255, 255, 255 ); //白色 
	$red   = ImageColorAllocate( $NewImg, 255, 0, 0 ); //红色 
	$blue  = ImageColorAllocate( $NewImg, 0, 0, 255 ); //蓝色 
	$other = ImageColorAllocate( $NewImg, 0, 255, 0 );
	//新图形高宽处理 
	$WriteNewWidth = $NewHeight*($OldImageInfo[0] / $OldImageInfo[1]); //要写入的高度 
	$WriteNewHeight = $NewWidth*($OldImageInfo[1] / $OldImageInfo[0]); //要写入的宽度 
	
	//这样处理图片比例会失调，但可以填满背景
	if ($OldImageInfo[0] / $NewWidth > $org_info[1] / $NewHeight) {
		$WriteNewWidth  = $NewWidth;
		$WriteNewHeight  = $NewWidth / ($OldImageInfo[0] / $OldImageInfo[1]);
	} else {
		/* 原始图片比较高，则以高度为准 */
		$WriteNewWidth  = $NewHeight * ($OldImageInfo[0] / $OldImageInfo[1]);
		$WriteNewHeight = $NewHeight;
	}
	//以$NewHeight为基础,如果新宽小于或等于$NewWidth,则成立 
	if ( $WriteNewWidth <= $NewWidth ) {
		$WriteNewWidth = $WriteNewWidth; //用判断后的大小 
		$WriteNewHeight = $NewHeight; //用规定的大小 
		$WriteX = floor( ($NewWidth-$WriteNewWidth) / 2 ); //在新图片上写入的X位置计算 
		$WriteY = 0; 
	} else { 
		$WriteNewWidth = $NewWidth; // 用规定的大小 
		$WriteNewHeight = $WriteNewHeight; //用判断后的大小 
		$WriteX = 0; 
		$WriteY = floor( ($NewHeight-$WriteNewHeight) / 2 ); //在新图片上写入的X位置计算 
	} 
	//旧图形缩小后,写入到新图形上(复制),imagecopyresized参数说明：新旧, 新xy旧xy, 新宽高旧宽高 
	@imagecopyresampled( $NewImg, $OldImg, $WriteX, $WriteY, 0, 0, $WriteNewWidth, $WriteNewHeight, $OldImageInfo[0], $OldImageInfo[1] ); 
	//保存文件 
	@imagegif( $NewImg, $NewImagePath ); 
	//结束图形 
	@imagedestroy($NewImg); 
}
function login($username, $password)
{
	global $db,$table,$CFG;
	if (check_user($username, $password) > 0) {
		set_session($username);
		set_cookie($username,'1');
		return true;
	} else {
		set_session();
		set_cookie();
		return false;
	}
}
function check_user($username, $password = '')
{
	global $db,$table,$CFG;
	if($password == '') {
		$sql = "select userid FROM {$table}member WHERE username = '$username'";
	} else {
		$sql = "select userid FROM {$table}member WHERE username = '$username' AND password ='$password'";
	}
	return $db->getOne($sql);
}
function logout()
{
	set_session();
	set_cookie();
}
function set_session ($username='')
{
	global $db,$table,$CFG;
	if (empty($username)) {
		$_SESSION['userid']   = '';
		$_SESSION['username']  = '';
		$_SESSION['password']  = '';
	} else {
		$sql = "SELECT userid, password, email , lastlogintime , sendmailtime FROM {$table}member WHERE username='$username' LIMIT 1";
		$row = $db->getRow($sql);
		if($row) {
			$_SESSION['userid']   = $row['userid'];
			$_SESSION['username']  = $username;
			$_SESSION['password']  = $row['password'];
		}
		$time = time();
		$ip = get_ip();
		$db->query("UPDATE {$table}member SET lastlogintime='$time',lastloginip='$ip' where username = '$username' ");
	}
}
function set_cookie($username='', $remember= null )
{
	global $db,$table,$CFG;
	if (empty($username)) {
		$time = $time > 0 ? $time : (empty($username) ? $PHP_TIME - 3600 : 0);
		$port = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
		setcookie('userkey', '', $time);
	} elseif ($remember) {
		$time = time() + 3600 * 24 * 180;
		$sql = "SELECT userid, password FROM {$table}member WHERE username='$username' LIMIT 1";
		$row = $db->getRow($sql);
		if ($row) {
			setcookie('userkey',encrypt(serialize($row)),$time);
			$_COOKIE['userkey'] = encrypt(serialize($row));
		}
	}
}
//设置cookie
function set_cookie_a($var, $value = '', $time = 0) {
	global $CFG, $PHP_TIME, $CFG;
	$time = $time > 0 ? $time : (empty($value) ? $PHP_TIME - 3600 : $PHP_TIME + 3600 * 24 * $CFG['login_cookie']);
	$port = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
	return setcookie($var, $value, $time);
}
//获取cookie
function get_cookie($var) {
	return isset($_COOKIE[$var]) ? $_COOKIE[$var] : '';
}
function register($username, $password)
{
	global $db,$table,$CFG;
	if (check_user($username) > 0) {
		showmsg("用户名 $username 已经存在");
	}
	$myuserid = !empty($_COOKIE['myuserid']) ? $_COOKIE['myuserid'] : '';
	$time = time();
	$ip = get_ip();
	if($CFG['regip']>0){
		$ip_count = $db->getOne("select count(*) from {$table}member where registerip='$ip'");
		if($ip_count>$CFG['regip']) showmsg('注册失败','index.php');
	}
	$status = $CFG['reg_check'] == 1 ? 0 : 1;
	$sql = "INSERT INTO {$table}member (username,password,sex,face,gid,registertime,registerip,lastlogintime,status) VALUES ('$username','$password','$site_arr[2]','$site_arr[3]','$gid','$time','$ip','$time', '$status')";
	$res = $db->query($sql);
	$siteid = $db->insert_id();
	if($res) {
		set_session($username);
		set_cookie($username,'1');
		return true;
	} else {
		set_session();
		set_cookie();
		return false;
	}
}
function get_here($here_arr=array())
{
	$here = '<a href="'.PHPQUAN_PATH.'">首页</a>';
	foreach($here_arr as $val) {
		if(!empty($val['url']) && !empty($val['name'])) {
			$here .= ' -> <a href="'.$val['url'].'">' . $val['name'] . '</a>';
		} elseif (empty($val['url']) && !empty($val['name'])) {
			$here .= ' -> '. $val['name'];
		}
	}
	return $here;
}
//添加数据
function inserttable($tablename, $insertsqlarr, $returnid=0, $replace = false, $silent=0) 
{
	global $db,$table;
	$insertkeysql = $insertvaluesql = $comma = '';
	foreach ($insertsqlarr as $insert_key => $insert_value) {
		$insertkeysql .= $comma.'`'.$insert_key.'`';
		$insertvaluesql .= $comma.'\''.$insert_value.'\'';
		$comma = ', ';
	}
	$method = $replace?'REPLACE':'INSERT';
	$db->query($method.' INTO '.$table.$tablename.' ('.$insertkeysql.') VALUES ('.$insertvaluesql.')', $silent?'SILENT':'');
	if($returnid && !$replace) {
		return $db->insert_id();
	}
}
//更新数据
function updatetable($tablename, $setsqlarr, $wheresqlarr, $silent=0) 
{
	global $db,$table;
	$setsql = $comma = '';
	foreach ($setsqlarr as $set_key => $set_value) {
		if(is_array($set_value)) {
			$setsql .= $comma.'`'.$set_key.'`'.'='.$set_value[0];
		} else {
			$setsql .= $comma.'`'.$set_key.'`'.'=\''.$set_value.'\'';
		}
		$comma = ', ';
	}
	$where = $comma = '';
	if(empty($wheresqlarr)) {
		$where = '1';
	} elseif(is_array($wheresqlarr)) {
		foreach ($wheresqlarr as $key => $value) {
			$where .= $comma.'`'.$key.'`'.'=\''.$value.'\'';
			$comma = ' AND ';
		}
	} else {
		$where = $wheresqlarr;
	}
	$db->query('UPDATE '.$table.$tablename.' SET '.$setsql.' WHERE '.$where, $silent?'SILENT':'');
}
function html_select($name, $arr, $selectid='')
{
	$option = "<select name=\"$name\" id=\"$name\">";
	foreach($arr as $key=>$val) {
		$option .= "<option value=$key";
		$option .= ($selectid == $key) ? " selected='selected'" : '';
		$option .= ">$val</option>";
	}
	$option .= "</select>";
	return $option;
}
function member_info($data='',$type='1',$upid='')
{
	global $db,$table,$_userid;
	
	if($type=='1') {
		$userid = intval($data);
		$info = $db->getRow("select * from {$table}member where userid='$userid' ");
	} elseif($type=='2') {
		$userid = trim($data);
		$info = $db->getOne("select userid from {$table}member where userid='$userid' ");
	} elseif($type=='3') {
		$info = $db->getOne("select ".$data." from {$table}member where userid='$_userid' ");
	} elseif($type=='4') {
		$info = $db->getOne("select ".$data." from {$table}member where userid='$upid' ");
	}
	return $info;
}
function com_info($data='',$type='1',$cid='')
{
	global $db,$table,$_userid;
	
	if($type=='1') {
		$info = $db->getOne("select count(*) from {$table}com where userid='$_userid' ");
	} elseif($type=='2') {
		$info = $db->getOne("select ".$data." from {$table}com where userid='$_userid' ");
	} elseif($type=='3') {
		$userid = intval($data);
		$info = $db->getOne("select count(*) from {$table}com where userid='$userid' ");
	} elseif($type=='4') {
		$info = $db->getOne("select ".$data." from {$table}com where comid='$cid' ");
	}
	return $info;
}

function addInfo($items, $cusvalue)
{
	global $db, $table;
	if(empty($items)) return '';
	$id = inserttable('juan', $items, 1);
	if(isset($cusvalue)) {
		$juanid = $id;
        $cus_value_list = array();
        foreach((array)$cusvalue as $key => $val) {
			if(is_array($val)) {
				$cus_value = implode(",", $val);
			} else {
				$cus_value = $val;
			}
            if(!empty($cus_value)) {
                $cus_value_list[$key] = $cus_value;
            }
        }
        foreach($cus_value_list as $cusid => $cus_value) {
			$db->query("INSERT INTO {$table}cus_value (cusid, juanid, cusvalue) VALUES ('$cusid', '$juanid', '$cus_value')");
        }
    }
	return $id;
}

//判断提交是否正确
function submitcheck($var) {
	if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST[$var])) {
		if((empty($_SERVER['HTTP_REFERER']) || preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST']))) {
			return true;
		} else {
			die('post error');
		}
	} else {
		return false;
	}
}
function checkInfoUser($id, $password) {
	global $db, $table, $_userid;
	if(empty($_userid)) {
		$password = trim($password);
		$pass = $db->getOne("SELECT password FROM {$table}juan WHERE id='$id' LIMIT 1");
		if(empty($pass))showmsg('此券没有设置密码，请联系客服删除。');
		if($password != $pass)showmsg('密码错误');
	} else {
		$sql = "SELECT userid FROM {$table}juan WHERE id='$id' ";
		$infouserid = $db->getOne($sql);
		if($infouserid!=$_userid)showmsg('此券不是您发布的');
	}
	
}
/* 取得违禁词语 */
function get_censor()
{
	global $CFG;
	$censors = $banned = $banwords = array();
	
	$data = read_cache('censor');
	if ($data === false) {
		//取得数据
		$censorarr = explode("|", $CFG['banwords']);
		foreach($censorarr as $censor) {
			$censor = trim($censor);
			if(empty($censor)) continue;
			
			//处理每个词组的替换
			if(strstr($censor, '=')) {
				list($find, $replace) = explode('=', $censor);
			} else {
				$find = $censor;
				$replace = '*';
			}
			$findword = $find;
			//解析{}，替换成正则的形式
			$find = preg_replace("/\\\{(\d+)\\\}/", ".{0,\\1}", preg_quote($find, '/'));
			switch($replace) {
				case '{BANNED}':
					$banwords[] = preg_replace("/\\\{(\d+)\\\}/", "*", preg_quote($findword, '/'));
					$banned[] = $find;
					break;
				default:
					$censors['filter']['find'][] = '/'.$find.'/i';
					$censors['filter']['replace'][] = $replace;
					break;
			}
		}
		//禁止发布时包含的词语
		if($banned) {
			$censors['banned'] = '/('.implode('|', $banned).')/i';
			$censors['banword'] = implode(', ', $banwords);
		}
	
		write_cache('censor', $censors);
	} else {
		$censors = $data;
	}
	return $censors;
}
/* 
 * 验证字或替换符串中是否包含违禁词语
 * @param string $string 要验证或替换的字符串
 * @return bool
*/
function censor($string) {
	$censor = get_censor();
	if($censor) {
		//词语屏蔽
		if($censor['banned'] && preg_match($censor['banned'], $string)) {
			$string = false;
		} else {
			$string = empty($censor['filter']) ? $string : @preg_replace($censor['filter']['find'], $censor['filter']['replace'], $string);
		}
	}
	return $string;
}
/*
3-16个字符 用户名仅可使用汉字、字母、数字、中划线或下划线。
*/
function check_name($username) {
	if(strpos($username, '__') !== false || strpos($username, '--') !== false) return false; 
	return preg_match("/^[a-zA-Z0-9\x7f-\xff][a-zA-Z0-9_\x7f-\xff\-]{3,30}$/", $username);
}

function check_gid(){
	global $_gid;
	if($_gid<=0)pheader('member.php');
}
function encrypt($txt, $key = ''){
    if (empty($txt)) return $txt;
    if (empty($key)) $key = md5(MD5_KEY);
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $nh1 = rand(0,64);
    $nh2 = rand(0,64);
    $nh3 = rand(0,64);
    $ch1 = $chars{$nh1};
    $ch2 = $chars{$nh2};
    $ch3 = $chars{$nh3};
    $nhnum = $nh1 + $nh2 + $nh3;
    $knum = 0;$i = 0;
    while(isset($key{$i})) $knum +=ord($key{$i++});
    $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum%8,$knum%8 + 16);
    $txt = base64_encode(time().'_'.$txt);
    $txt = str_replace(array('+','/','='),array('-','_','.'),$txt);
    $tmp = '';
    $j=0;$k = 0;
    $tlen = strlen($txt);
    $klen = strlen($mdKey);
    for ($i=0; $i<$tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = ($nhnum+strpos($chars,$txt{$i})+ord($mdKey{$k++}))%64;
        $tmp .= $chars{$j};
    }
    $tmplen = strlen($tmp);
    $tmp = substr_replace($tmp,$ch3,$nh2 % ++$tmplen,0);
    $tmp = substr_replace($tmp,$ch2,$nh1 % ++$tmplen,0);
    $tmp = substr_replace($tmp,$ch1,$knum % ++$tmplen,0);
    return $tmp;
}
function decrypt($txt, $key = '', $ttl = 0){
    if (empty($txt)) return $txt;
    if (empty($key)) $key = md5(MD5_KEY);
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $knum = 0;$i = 0;
    $tlen = @strlen($txt);
    while(isset($key{$i})) $knum +=ord($key{$i++});
    $ch1 = @$txt{$knum % $tlen};
    $nh1 = strpos($chars,$ch1);
    $txt = @substr_replace($txt,'',$knum % $tlen--,1);
    $ch2 = @$txt{$nh1 % $tlen};
    $nh2 = @strpos($chars,$ch2);
    $txt = @substr_replace($txt,'',$nh1 % $tlen--,1);
    $ch3 = @$txt{$nh2 % $tlen};
    $nh3 = @strpos($chars,$ch3);
    $txt = @substr_replace($txt,'',$nh2 % $tlen--,1);
    $nhnum = $nh1 + $nh2 + $nh3;
    $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum % 8,$knum % 8 + 16);
    $tmp = '';
    $j=0; $k = 0;
    $tlen = @strlen($txt);
    $klen = @strlen($mdKey);
    for ($i=0; $i<$tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = strpos($chars,$txt{$i})-$nhnum - ord($mdKey{$k++});
        while ($j<0) $j+=64;
        $tmp .= $chars{$j};
    }
    $tmp = str_replace(array('-','_','.'),array('+','/','='),$tmp);
    $tmp = trim(base64_decode($tmp));
    if (preg_match("/\d{10}_/s",substr($tmp,0,11))){
        if ($ttl > 0 && (time() - substr($tmp,0,11) > $ttl)){
            $tmp = null;
        }else{
            $tmp = substr($tmp,11);
        }
    }
    return $tmp;
}

function numzh($str)
{
    $aNumber = array('０'=>'0', '１'=>'1', '２'=>'2', '３'=>'3', '４'=>'4', '５'=>'5', '６'=>'6', '７'=>'7', '８'=>'8', '９'=>'9');
    return strtr($str, $aNumber);
}
//求百分比
function get_stat($num,$allnum)
{
	$mystat = round($num/$allnum*100);
	if($mystat>0 && $mystat<=25){
		$mystat = '25';
	}elseif($mystat>25 && $mystat<=50){
		$mystat = '50';
	}elseif($mystat>50 && $mystat<=75){
		$mystat = '75';
	}elseif($mystat>=100){
		$mystat = '100';
	}else{
		$mystat = '0';
	}
	return $mystat;
}
//友好日期显示
function mdate($time) {  
    $rtime = date("m-d H:i",$time);  
    $htime = date("H:i",$time);  
    $time = time() - $time;   
    if ($time < 60) {  
        $str = '刚刚';  
    }  
    elseif ($time < 60 * 60) {  
        $min = floor($time/60);  
        $str = $min.'分钟前';  
    }  
    elseif ($time < 60 * 60 * 24) {  
        $h = floor($time/(60*60));  
        $str = $h.'小时前 ';  
    }  
    elseif ($time < 60 * 60 * 24 * 3) {  
        $d = floor($time/(60*60*24));  
        if($d==1) { 
           $str = '昨天';//.$htime;  
		}else{  
           $str = '前天';//.$htime; 
		}
    } else {  
        $str = $rtime;  
    }  
    return $str;  
}
//判断客户端
function is_mobile_request()  
{  
 $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';  
 $mobile_browser = '0';  
 if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))  
  $mobile_browser++;  
 if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false))  
  $mobile_browser++;  
 if(isset($_SERVER['HTTP_X_WAP_PROFILE']))  
  $mobile_browser++;  
 if(isset($_SERVER['HTTP_PROFILE']))  
  $mobile_browser++;  
 $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));  
 $mobile_agents = array(  
    'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',  
    'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',  
    'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',  
    'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',  
    'newt','noki','oper','palm','pana','pant','phil','play','port','prox',  
    'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',  
    'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',  
    'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',  
    'wapr','webc','winw','winw','xda','xda-'
    );  
 if(in_array($mobile_ua, $mobile_agents))  
  $mobile_browser++;  
 if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)  
  $mobile_browser++;  
 // Pre-final check to reset everything if the user is on Windows  
 if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)  
  $mobile_browser=0;  
 // But WP7 is also Windows, with a slightly different characteristic  
 if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)  
  $mobile_browser++;  
 if($mobile_browser>0)  
  return true;  
 else
  return false;
} 

function myshowmsg($msg){
    echo '<script language=JavaScript>var i = parent.layer.getFrameIndex(window.name);parent.layer.msg("'.$msg.'",{icon: 9,time:2000}, function(){parent.location.reload();});</script>';
}

function getPostArea($ip)
{
	global $charset;
	require_once PHPQUAN_ROOT . 'include/ip.class.php';
	$cha = new ip();
	$address = $cha->getaddress($ip);
	//$postarea = $address["area1"].$address["area2"];
	$postarea = $address["area1"];
	if($charset == 'utf-8') $postarea = iconvs('gb2312','utf-8', $postarea);
	return $postarea;
}
function pheader($url)
{
	Header("Location: $url");
	exit;
}
function ex_tab($str)
{
	preg_match('/([\d]{4})([\d]{4})([\d]{0,})?/', $str,$match);
	unset($match[0]);
	return implode(' ', $match);
}
?>