<?php

if(!defined('IN_PHPMPS'))
{
	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,$typeid='')
{
	if(empty($typeid)){
	   $chars = '0123456789ABCDEFGHIJ0123456789KLMNOPQRSTJ0123456789UVWXYZ0123456789abcdefghijJ0123456789klmnopqrstJ0123456789uvwxyz0123456789';
	}elseif($typeid=='1'){
	    $chars = '12345678998765432123456789';	
	}elseif($typeid=='2'){
		$chars = 'ACDEFGHJKMNPQRSTWXYZ';
	}elseif($typeid=='3'){
		$chars = '123456789abcdefghij123456789klmnopqrstj123456789uvwxyz123456789';
	}
	$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 encrypt($string, $password)
{
	$password = base64_encode($password);
    $count_pwd = strlen("a".$password);
    for($i = 1;$i<$count_pwd;$i++) {
		$pwd+=ord($password{$i});
    }
	$string = base64_encode($string);
    $count = strlen("a".$string);
    for($i = 0;$i<$count;$i++) {
    	$asciis.=(ord($string{$i})+$pwd)."|";
    }
    $asciis = base64_encode($asciis);
	return $asciis;
}

function decrypt($string, $password)
{
	$password = base64_encode($password);
    $count_pwd = strlen("a".$password);
    for($i = 1;$i<$count_pwd;$i++) {
    	$pwd+=ord($password{$i});
    }
    $string = base64_decode($string);
    $contents = explode("|",$string);
    $count = count($contents);
    for($i=0;$i<$count;$i++) {
    	$infos.=chr($contents[$i]-$pwd);
    }
    $asciis = base64_decode($infos);
	return $asciis;
}

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,$order='',$keyword='',$check_p='',$check_wf='',$type='normal')
{
	global $tpl,$CFG;
    $page = intval($page);
    if($page<1)$page = 1;
	$init=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 'com';
			$params = array('catid' => $cat, 'eid' => $area, 'act'=>'list', 'order'=>$order, 'keyword'=>$keyword, 'check_p'=>$check_p, 'check_wf'=>$check_wf,'type'=>$type);
			$targets = " target=icomment";
		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']  = '';
	} else {
		//
	if($page_count>10){
	  $inits     = $page>$CFG['page_num'] ? ($page-$CFG['page_num']) : $init;
	  $page_init = ($page_count-$page)>$CFG['page_num'] ? ($page+$CFG['page_num']) : $page_count;
	  if(($page+$CFG['page_num']) < $page_count){
	  $pager['page_msg']  = "...<span><a href=\"".url_rewrite($file, $params, $page_count)."\"".$targets.">".$page_count."</a></span>";
	  }
	}else{
	  $inits = $init;
	  $page_init = $page_count;
	}
		for($i=$inits;$i<=$page_init;$i++)
        {
			if($i==$page){
				$pager['numlist'].="<span class='sc'>".$i.'</span>';
			}else{
				$pager['numlist'].="<span><a href=\"".url_rewrite($file, $params, $i)."\"".$targets.">".$i."</a></span>";
		    }
        }
		//
		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)
{
    global $CFG;
	$size = intval($size);
    if($size < 1)$size = 10;
    $page = intval($page);
    if($page < 1)$page = 1;
    $count = intval($count);
	$init=1;

    $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($url=='com_comment.php'){
	$targets = " target=icomment";
	}

	if($page_count <= '1') {
	    $pager['first'] = $pager['prev']  = $pager['next']  = $pager['last']  = '';
	} else {
		//
	if($page_count>10){
	  $inits     = $page>$CFG['page_num'] ? ($page-$CFG['page_num']) : $init;
	  $page_init = ($page_count-$page)>$CFG['page_num'] ? ($page+$CFG['page_num']) : $page_count;
	  if(($page+$CFG['page_num']) < $page_count){
	  $pager['page_msg']  = "...<span><a href=\"".$url . $param_url . 'page=' .$page_count."\"".$targets.">".$page_count."</a></span>";
	  }
	}else{
	  $inits = $init;
	  $page_init = $page_count;
	}
		for($i=$inits;$i<=$page_init;$i++)
        {
			if($i==$page){
				$pager['numlist'].="<span class='sc'>".$i.'</span>';
			}else{
				$pager['numlist'].="<span><a href=\"".$url . $param_url . 'page=' .$i."\"".$targets.">".$i."</a></span>";  //target=icomment
		    }
        }
		//
		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;
}

function url_rewrite($app, $params, $page = 0, $size = 0)
{
	global $CFG;
    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 'view':
            if(empty($vid)) {
                return false;
            }else{
                $uri = $rewrite ? 'view-' . $vid : 'view.php?id=' . $vid;
            }
        break;

		case 'about':
            if(empty($aid)) {
                return false;
            }else{
                $uri = $rewrite ? 'about-' . $aid : 'about.php?id=' . $aid;
            }
        break;
		
		case 'plus_page':
            if(empty($aid)) {
                return false;
            }else{
                $uri = $rewrite ? 'pages-' . $aid : 'plus_page.php?id=' . $aid;
            }
        break;

		case 'help':
            if($act=='list') {
                if($rewrite) {
					$uri = 'help';
                    if($tid)$uri .= '-list-' . $tid;
					if($page)$uri .= '-page-' . $page;
                }else{
					$uri = 'help.php?act=list';
					if($tid)$uri .= '&typeid=' . $tid;
                    if($page)$uri .= '&page=' . $page;
                }
            } elseif($act=='view' && $hid) {
                if($rewrite) {
                    $uri = 'help-view-' . $hid;
                }else{
                    $uri = 'help.php?act=view&id=' . $hid;
                }
            }
        break;

		case 'article':
            if($act=='list') {
                if($rewrite) {
					$uri = 'article';
                    if($iid)$uri .= '-list-' . $iid;
					if($page)$uri .= '-page-' . $page;
                }else{
					$uri = 'article.php?act=list';
					if($iid)$uri .= '&typeid=' . $iid;
                    if($page)$uri .= '&page=' . $page;
                }
            } elseif($act=='view' && $aid) {
                if($rewrite) {
                    $uri = 'article-view-' . $aid.'';
                }else{
                    $uri = 'article.php?act=view&id=' . $aid;
                }
            }
        break;
		
		case 'com_comment':
		   if($rewrite) {
			   $uri = 'com-comment';
		    if(empty($comid)) {
                return false;
            }else{
                $uri = 'com_comment-' . $comid;
            }
			if(!empty($page)){
				$uri .= '-' . $page;
			}else{
				$uri .= '-0';
			}
		   }else{
			 $uri = 'com_comment.php?';
			 if(!empty($comid))$uri .= 'comid=' . $comid;
			 if(!empty($page))$uri .= '&page=' . $page; 
		   }
		break;

		case 'com':
            if($act=='list') {
                if($rewrite) {
					$uri = 'com';
					$uri = 'com';
					if(!empty($catid)){
						$uri .= '-' . $catid;
					}else{
						$uri .= '-0';
					}
					if(!empty($eid)){
						$uri .= '-' . $eid;
					}else{
						$uri .= '-0';
					}
					if(!empty($order)){
						$uri .= '-'.$order;
					}else{
						$uri .= '-new';
					}
					if(!empty($keyword)){
						$uri .= '-'.urlencode($keyword);
					}else{
						$uri .= '-0';
					}
					if(!empty($check_wf)){
						$uri .= '-'.$check_wf;
					}else{
						$uri .= '-0';
					}
					if(!empty($check_p)){
						$uri .= '-'.$check_p;
					}else{
						$uri .= '-0';
					}
					if(!empty($page)){
						$uri .= '-' . $page;
					}else{
						$uri .= '-0';
					}
				}else{
					$uri = 'com.php?act=list';
					if(!empty($catid))$uri .= '&catid=' . $catid;
					if(!empty($eid))$uri .= '&area=' . $eid;
					if(!empty($order))$uri .= '&order=' . $order;
					if(!empty($keyword))$uri .= '&keyword=' . $keyword;
					if(!empty($check_wf))$uri .= '&check_wf=' . $check_wf;
					if(!empty($check_p))$uri .= '&check_p=' . $check_p;
					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;
   
        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 PHPMPS_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 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(PHPMPS_ROOT . $tmp_dir . '/phpcache/');
    }  elseif ($type=='sqlcache') {
        $dirs = array(PHPMPS_ROOT . $tmp_dir . '/sqlcache/');
    } elseif ($type=='compiled') {
        $dirs = array(PHPMPS_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_area_array()
{
	global $db, $table;
	$data = read_cache('area_array');
	if ($data === false) {
		$sql = "select areaid,areaname from {$table}area order by areaid ";
		$res = $db->query($sql);
		while($row=$db->fetchrow($res)) {
			$area_array[$row['areaid']] = $row['areaname'];
		}
		write_cache('area_array', $area_array);
	} else {
		$area_array = $data;
	}
	return $area_array;
}

function get_parent_area()
{
	global $db,$table;
	
	$data = read_cache('parent_area');
	if ($data === false) {
		$sql = "select areaid,areaname from {$table}area where parentid = '0' ";
		$res = $db->query($sql);
		while($row=$db->fetchrow($res)) {
			$parent_area[] = $row;
		}
		write_cache('parent_area', $parent_area);
	} else {
		$parent_area = $data;
	}
	return $parent_area;
}

function get_area_list()
{
	global $db,$table;
	
	static $areas = NULL;
	if ($areas === NULL) {
		$data = read_cache('area_list');
		if ($data === false) {
			$sql = "select a.areaid, a.areaname, a.areaorder as catorder,b.areaid as childid, b.areaname as childname, b.areaorder as chiorder from {$table}area as a left join {$table}area as b on b.parentid = a.areaid where a.parentid = '$area' order by catorder,a.areaid,chiorder asC"; 
			$res = $db->getAll($sql);

			$areas = array();
			foreach ($res as $row) {
				$areas[$row['areaid']]['areaid']   = $row['areaid'];
				$areas[$row['areaid']]['areaname'] = $row['areaname'];
				$areas[$row['areaid']]['url']  = url_rewrite('category',array('eid'=>$row[areaid]));

				if($row['childid'] != NULL) {
					$areas[$row['areaid']]['children'][$row['childid']]['id']   = $row['childid'];
					$areas[$row['areaid']]['children'][$row['childid']]['name'] = $row['childname'];
					$areas[$row['areaid']]['children'][$row['childid']]['url']  = url_rewrite('category',array('eid'=>$row[childid]));
				}
			}
			write_cache('area_list', $areas);
		} else {
			$areas = $data;
		}
	}
	return $areas;
}

function area_options($selectid='')
{
	$area = get_area_list();
	foreach($area as $area) {
		$option .= "<option value=$area[areaid] style='color:red;'";
		$option .= ($selectid == $area['areaid']) ? " selected='selected'" : '';
		$option .= ">$area[areaname]</option>";

		if(!empty($area['children'])) {
			foreach($area['children'] as $chi) {
				$option .= "<option value=$chi[id]";
				$option .= ($selectid == $chi['id']) ? " selected='selected'" : '';
				$option .= ">&nbsp;&nbsp;|--$chi[name]</option>";
			}
		}
	}
	return $option;
}
function area_options3($selectid='')
{
	$area = get_area_list();
	foreach($area as $area) {
		$option .= "<option value=$area[areaid]_$area[areaname]";
		$option .= ($selectid == $area['areaid']) ? " selected='selected'" : '';
		$option .= ">$area[areaname]</option>";
	}
	return $option;
}
function area_options_zl($selectid='')
{
	$area = get_area_list();
	foreach($area as $area) {
		/*$option .= "<option value=$area[areaid] style='color:red;'";
		$option .= ($selectid == $area['areaid']) ? " selected='selected'" : '';
		$option .= ">$area[areaname]</option>";*/

		if(!empty($area['children']) && $area['areaid'] == $_COOKIE['cityid']) {
			foreach($area['children'] as $chi) {
				$option .= "<option value=$chi[id]";
				$option .= ($selectid == $chi['id']) ? " selected='selected'" : '';
				$option .= ">$chi[name]</option>";
			}
		}
	}
	return $option;
}

function get_area_children($areaid,$type='int')
{
	$areas = get_area_list();
	$area_children = $areas[$areaid]['children'];
	if(is_array($area_children)) {
		if($type=='int') {
			if(is_array($area_children)) {
				foreach($area_children as $child) {
					$id .= $child['id'].',';
				}
			}
			$result = substr($id,0,-1);
		} elseif($type=='array') {
			$result = $area_children;
		}
	} else {
		if($type=='int') {
			$result = $areaid;
		} elseif($type=='array') {
			$result = '';
		}
	}
	return $result;
	
}

function get_area_info($areaid)
{
	global $db,$table;
	
	$data = read_cache('area_'.$areaid);
	if ($data === false) {
		$sql = "select * from {$table}area where areaid='$areaid' ";
		$area_info = $db->getRow($sql);
		write_cache('area_'.$areaid, $area_info);
	} else {
		$area_info = $data;
	}
	return $area_info;
}

function get_nav()
{
	global $db,$table;
	
	$data = read_cache('nav');
    if ($data === false) {
		$sql = "select * from {$table}nav order by navorder";
		$nav = $db->getAll($sql);
		write_cache('nav', $nav);
	} else {
		$nav = $data;
	}
	return $nav;
}



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 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 onlyarea($postarea)
{
	global $db,$table,$CFG;

	if(!empty($CFG['onlyarea'])) {
		$onlyarea = explode('|', $CFG['onlyarea']);
		foreach($onlyarea as $val) {
			if(strstr($postarea, $val)) $count++;
		}
	}
}

function getPostArea($ip)
{
	global $charset;
	return $postarea;
}

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;

	if (empty($username)) {
		$time = time() - 3600;
		setcookie("userid", '', $time);            
		setcookie("password", '', $time);

	} elseif ($remember) {
		$time = time() + 3600 * 24 * 15;

		setcookie("username", $username, $time);
		$sql = "SELECT userid, password FROM {$table}member WHERE username='$username' LIMIT 1";
		$row = $db->getRow($sql);
		if ($row) {
			setcookie("userid", $row['userid'], $time);
			setcookie("password", $row['password'], $time);
		}
	}
}

function get_here($here_arr=array())
{
	$here = '<a href="'.PHPMPS_PATH.'" class="f99">首页</a>';
	foreach($here_arr as $val) {
		if(!empty($val['url']) && !empty($val['name'])) {
			$here .= ' <span class="song fb5">></span> <a href="'.$val['url'].'" class="f99">' . $val['name'] . '</a>';
		} elseif (empty($val['url']) && !empty($val['name'])) {
			$here .= ' <span class="song fb5">></span> '. $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')
{
	global $db,$table,$_userid;
	
	if($type=='1') {
		$userid = intval($data);
		$info = $db->getRow("select * from {$table}member where userid='$userid' ");
	} elseif($type=='2') {
		$username = trim($data);
		$info = $db->getRow("select * from {$table}member where username='$username' ");
	} elseif($type=='3') {
		$data = trim($data);
		$info = $db->getRow("select ".$data." from {$table}member where userid='$_userid' ");
	} elseif($type=='4') {
		$data = trim($data);
		$info = $db->getRow("select * from {$table}member where cardnum='$data' ");
	}
	return $info;
}

function send_pwd_email($userid, $username, $email, $code)
{
    if (empty($userid) || empty($username) || empty($email) || empty($code)) {
        header("Location: member.php?act=get_password\n");
        exit;
    }
    $reset_email = PHPMPS_PATH . 'member.php?act=get_password&userid=' . $userid . '&code=' . $code;

	$send_date = date('Y-m-d', time());
	$content = "{$username}您好！<br><br>您已经进行了密码重置的操作，请点击以下链接(或者复制到您的浏览器):<br><br><a href=".$reset_email." target=\"_blank\">".$reset_email."</a><br><br>以确认您的新密码重置操作！<br><br>".$send_date;
	require_once PHPMPS_ROOT.'include/mail.inc.php';
    if (sendmail($email, $CFG['webname'].'-密码找回邮件', $content)) {
        return true;
    } else {
        return false;
    }
}

function get_pay_setting()
{
	global $db,$table;
	$data = read_cache('pay_setting');
	if($data === false) {
		$sql = "select * from {$table}payment order by id";
		$res = $db->query($sql);
		while($row = $db->fetchrow($res)) {
			$pay[$row['paycenter']] = $row;
		}
		write_cache('pay_setting', $pay);
	} else {
		$pay = $data;
	}
	return $pay;
}

function get_about()
{
	global $db,$table;
	$sql = "SELECT id,title FROM {$table}about WHERE is_show=1 ORDER BY id ASC";
	$res = $db->query($sql);
	while($row = $db->fetchrow($res)) {
		$row['url'] = url_rewrite('about', array('aid'=>$row['id']));
		$abouts[] = $row;
	}
	return $abouts;
}

function getUserGlod($userid)
{
	global $db, $table;
	$sql = "SELECT glod FROM {$table}member WHERE userid='$userid'";
	$glod = $db->getOne($sql);
	return $glod;
}

function getCreditTimes($username, $type)
{
	global $db, $table;
	$credit_times = $db->getOne("SELECT COUNT(*) FROM {$table}pay_exchange WHERE username='$_username' AND addtime>".mktime(0,0,0)." AND note='$type' ");
	return $credit_times;
}

function get_new_comment($num='5')
{
	global $db,$table;
	$areaid = intval($_COOKIE['cityid']);
	if($_COOKIE['cityid']) {
	$area_info = get_area_info($areaid);
	//if(empty($area_info)) showmsg('地区暂未开通，请选择其他地区','plus_city.php');
	$area_parent = $area_info['parentid'];
	if(empty($area_parent)) {
		$area_row = get_area_children($areaid,'array');
		$areas = get_area_children($areaid);
		if(!empty($areas)) $areas .= ','.$areaid;
	} else {
		//如果有父分类，取得他所有的子分类
		$area_row = get_area_children($area_parent, 'array');
		/* 生成搜索 */
		$areas = $areaid;
	}
	    $area_sql = " and areaid in ($areas) ";

    }//
	$sql = "select c.*,i.comname,i.thumb,i.comid from (SELECT * FROM {$table}com_comment ORDER BY postdate DESC) as c left join {$table}com as i on i.comid=c.comid where c.is_check=1 $area_sql group by c.comid order by c.postdate desc limit $num";
	$res = $db->query($sql);
	while($row=$db->fetchrow($res)) {
		$row['comname'] = $row['comname'];
		$row['face'] = empty($row['face']) ? $CFG['thumbs'] : $row['face'];
		$row['content'] = cut_str($row['content'],'100').'...';
		$row['username'] = $row['username']?$row['username']:'本站网友';
		$row['url']      = url_rewrite('com',array('act'=>'view','comid'=>$row['comid']));
		$row['postdate'] = mdate($row['postdate']);
		$row['star'] = number_format(($row['cm_pz']+$row['cm_fw']+$row['cm_hj'])/3,1);
		$comments[] = $row;
	}
	return $comments;
}

function get_index_help($num='5',$typeid='')
{
	global $db,$table;
	if(!empty($typeid)) {
		$where .= " AND typeid in ($typeid)";
	}
	$sql = "select id,title from {$table}help where is_index=1 $where order by listorder asc limit $num ";
	$helps = $db->getAll($sql);
	$result = array();
	foreach((array)$helps as $row) {
		$row['url'] = url_rewrite('help',array('act'=>'view','hid'=>$row['id']));
		$result[] = $row;
	}
	return $result;
}

function get_index_com($num='4',$type='1')
{
	global $db,$table;
	$areaid = intval($_COOKIE['cityid']);
	if($_COOKIE['cityid']) {
	$area_info = get_area_info($areaid);
	//if(empty($area_info)) showmsg('地区暂未开通，请选择其他地区','plus_city.php');
	$area_parent = $area_info['parentid'];
	if(empty($area_parent)) {
		$area_row = get_area_children($areaid,'array');
		$areas = get_area_children($areaid);
		if(!empty($areas)) $areas .= ','.$areaid;
	} else {
		//如果有父分类，取得他所有的子分类
		$area_row = get_area_children($area_parent, 'array');
		/* 生成搜索 */
		$areas = $areaid;
	}
	    $area_sql = " and areaid in ($areas) ";

}//
	if($type=='1'){
	//$order = array('comid', 'addtime', 'click', '');
	$sql = "select a.comid as acomid,a.comname,a.thumb,a.is_check,a.postdate,c.* from {$table}com as a left join {$table}com_config as c  on a.comid=c.comid where a.is_check=1 $area_sql group by a.comid order by postdate desc limit $num";
	$res = $db->query($sql);
	while($row=$db->fetchrow($res)) {
		$row['jifens']     = explode('|',$row['jf_bl']);
		$row['url'] = url_rewrite('com', array('act'=>'view', 'comid'=>$row['acomid']));
		$coms[] = $row;
	}
	}elseif($type=='2'){
	$sql = "select a.comid,a.comname,a.is_check,a.thumb,((sum(b.cm_pz)+sum(b.cm_fw)+sum(b.cm_hj))/3/count(b.comid)) as sum_cm,count(b.comid) as ccid from {$table}com a,{$table}com_comment b where b.is_check=1 and a.comid=b.comid $area_sql group by a.comid order by sum_cm DESC limit $num";
	$res = $db->query($sql);
	while($row=$db->fetchrow($res)) {
		$row['sname'] = cut_str($row['comname'],13);
		$row['sum_cm']    = $row['sum_cm']!=0 ? number_format($row['sum_cm'],1) : '<span class="f99">0.0</span>';
		$row['url'] = url_rewrite('com', array('act'=>'view', 'comid'=>$row['comid']));
		$coms[] = $row;
	}	
	}
	return $coms;
}

function get_index_article($num='5',$type='')
{
	global $db,$table,$CFG;
	$areaid = intval($_COOKIE['cityid']);
	if($_COOKIE['cityid']) {
	$area_info = get_area_info($areaid);
	//if(empty($area_info)) showmsg('地区暂未开通，请选择其他地区','plus_city.php');
	$area_parent = $area_info['parentid'];
	if(empty($area_parent)) {
		$area_row = get_area_children($areaid,'array');
		$areas = get_area_children($areaid);
		if(!empty($areas)) $areas .= ','.$areaid;
	} else {
		//如果有父分类，取得他所有的子分类
		$area_row = get_area_children($area_parent, 'array');
		/* 生成搜索 */
		$areas = $areaid;
	}
	    $area_sql = " and a.areaid in ($areas) ";

}//
	if(!empty($typeid)) {
		$where .= " AND c.typeid in ($typeid)";
	}
	$sql = "select a.*,c.typename,c.typeid from {$table}article as a left join {$table}type as c on a.typeid=c.typeid where  is_index=1 $where $area_sql order by id desc limit $num";
	$res = $db->query($sql);
	while($row=$db->fetchrow($res)) {
		$row['ctitle'] = cut_str($row['title'], 20);
		$row['addtime'] = date('m-d', $row['addtime']);
		$row['url'] = url_rewrite('article', array('aid'=>$row['id'],'act'=>'view'));
		$data[] = $row;
	}
	return $data;
}

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 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;
}

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,16}$/", $username);
}

function chkcom($comid)
{
	global $db,$table,$_userid;
	$comid = intval($comid);
	$comuserid = $db->getOne("select userid from {$table}com where comid='$comid' ");
    if(!$comuserid)showmsg('您还未添加店铺，为你转向店铺添加页！','postcom.php');
	if($comuserid!=$_userid)showmsg('此店铺不是您发布的，您不能修改！');
}
function numzh($str)
{
    $aNumber = array('０'=>0, '１'=>1, '２'=>2, '３'=>3, '４'=>4, '５'=>5, '６'=>6, '７'=>7, '８'=>8, '９'=>9);
    return strtr($str, $aNumber);
}
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 com_info($data,$comid='',$type='1')
{
	global $db,$table,$_userid;
	
	if($type=='1') {
		$data = trim($data);
		$com_info = $db->getRow("select ".$data." from {$table}com where comid='$comid' ");
	}elseif($type=='2') {
		$data = intval($data);
		$com_info = $db->getOne("select userid from {$table}com where comid='$data' ");
	}elseif($type=='3') {
		$data = trim($data);
		$com_info = $db->getOne("select ".$data." from {$table}com where userid='$_userid' ");
	}elseif($type=='4') {
		$data = trim($data);
		$com_info = $db->getRow("select ".$data." from {$table}com where keycode='$comid' ");
	}
	return $com_info;
}
function SendSMS($SMS_sign,$SMS_tpl,$SMS_text,$SMS_phone,$note='',$comid='',$userid='')
{
	global $db,$table,$CFG;
	require_once PHPMPS_ROOT . 'include/sms.class.php';
	$time = time();
	if(!empty($SMS_phone)){
	$config = array(
	  'appkey' => $CFG['sms_alidayu_appkey'],
	  'secret' => $CFG['sms_alidayu_secret']
    );
    $sms = new SMS($config);
    $param = array(
	  'sign' => $SMS_sign,//短信签名
	  'template' => $SMS_tpl,//短信模板
	  'param' => $SMS_text,//短信内容
	  'phone' => $SMS_phone //接受短信的号码
    );
    $ret = $sms->send($param);
    $retname = objtoarr($ret);
    if($retname['result']['success']==true || $retname['result']['success']==1){
		$res = '0';
	}else{
		$res = '1';
	}
	$db->query("INSERT INTO {$table}com_sms (`phone`,`userid`,`comid`,`note`,`sendtime`,`star`) VALUES('$SMS_phone','$userid','$comid','$note','$time','$res')");
	}
}
//将stdClass Object转为普通数组
function objtoarr($obj){
	$ret = array();
	foreach($obj as $key =>$value){
		if(gettype($value) == 'array' || gettype($value) == 'object'){
			$ret[$key] = objtoarr($value);
		}
		else{
			$ret[$key] = $value;
		}
	}
	return $ret;
}

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 template_compiel($tplfile,$tplcachefile)
{
	$str = file_get_contents($tplfile);
	$str = template_parse($str);
	$strlen = file_put_contents($tplcachefile, $str);
	@chmod($tplcachefile, 0777);
	return $strlen;
}
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 template($file)
{
	global $CFG;
	$compiledfile = PHPMPS_ROOT.'data/compiled/'.$file.'.php';
	//$tplfile = PHPMPS_ROOT.'/templates/'.$CFG['tplname'].'/'.$file.'.htm';
	$tplfile = PHPMPS_ROOT.'templates/'.$CFG['tplname'].'/'.$CFG['tpl2name'].'/'.$file.'.htm';
	if(!file_exists($compiledfile) || @filemtime($tplfile) > @filemtime($compiledfile)) {
		template_compile($tplfile, $compiledfile);
	}
	return $compiledfile;
}
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_PHPMPS'))die('Access Denied'); ?>".$tpl;
	return $tpl;
}
function read_cache($filename)
{
    $result = array();
    if (!empty($result[$filename])) {
        return $result[$filename];
    }
    $filepath = PHPMPS_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 = PHPMPS_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);
}
?>