<?php
/**
* 通用函数库
* @author moufer<moufer@163.com>
* @copyright (C)2001-2007 Moufersoft
* @version $Id: global.func.php 25 2008-08-24 17:31 $
*/
!defined('IN_MUDDER') && exit('Access Denied');

function add_slashes($string) {
    if(is_array($string))
        foreach($string as $key => $val) $string[$key] = add_slashes($val); 
    else
        $string = is_string($string) ? addslashes($string) : $string;
    return $string;
}

function add_cs_lashes($string) {
    return $string ? addcslashes($string, '\'\\') : '';
}

function authcode($string, $operation = 'DECODE') {
    $string = $operation == 'DECODE' ? base64_decode($string) : base64_encode($string);
    return $string;
}

function new_intval($number) {
    if(is_array($number))
        foreach($number as $key => $val) $number[$key] = new_intval($val); 
    else
        return intval($number);
    return $number;
}

function strip_slashes($string) {
    if(is_array($string))
        foreach($string as $key => $val) $string[$key] = strip_slashes($val); 
    else
        $string = is_string($string) ? stripslashes($string) : $string;
    return $string;
}

function html_special_chars($string) {
    if(is_array($string))
        foreach($string as $key => $val) $string[$key] = html_special_chars($val); 
    else
        $string = is_string($string) ? htmlspecialchars($string, ENT_QUOTES) : $string;
    return $string;
}

function html_special_chars_ex($string) {
    if(is_array($string))
        foreach($string as $key => $val) $string[$key] = html_special_chars_ex($val); 
    else
        $string = is_string($string) ? htmlspecialchars(trim(stripslashes($string)), ENT_QUOTES) : $string;
    return $string;
}

function strip_sql($string) {
	global $pattern_arr, $replace_arr;
	return is_array($string) ? array_map('strip_sql', $string) : preg_replace($pattern_arr, $replace_arr, $string);
}

function strip_order($string) {
    $string = preg_replace('/.?select.+from.+/i', '', $string);
    $string = preg_replace("/.?delete.+from.+/i", "", $string);
    $string = preg_replace("/.?update.+set.+/i", "", $string);
    $string = preg_replace("/.?select.+union.+/i", "", $string);

    return $string;
}

function strip_textarea($string) {
    $search_arr = array(" ","\t");
    $replace_arr = array("&nbsp;","&nbsp;&nbsp;&nbsp;&nbsp;");
    return nl2br(str_replace($search_arr, $replace_arr, html_special_chars($string)));
}

function unite_textarea($string) {
    return trim(preg_replace("/\s*(\r\n|\n\r|\n|\r)\s*/", "\r\n", $string));
}

function nl_textarea($string) {
    return trim(preg_replace("/(\r\n|\n\r|\n|\r)/", "\r\n", $string));
}

function strip_safe($string) {
	$search_arr = array("/(javascript|jscript|js|vbscript|vbs|about):/i","/on(mouse|exit|error|click|dblclick|key|load|unload|change|move|submit|reset|cut|copy|select|start|stop)/i","/<script([^>]*)>/i","/<iframe([^>]*)>/i","/<frame([^>]*)>/i","/<link([^>]*)>/i","/@import/i");
	$replace_arr = array("\\1\n:","on\n\\1","&lt;script\\1&gt;","&lt;iframe\\1&gt;","&lt;frame\\1&gt;","&lt;link\\1&gt;","@\nimport");
	$string = preg_replace($search_arr, $replace_arr, $string);
	$string = str_replace("&#", "&\n#", $string);
	return $string;
}

function sql_quote($value) { 
    $value = stripslashes($value); 
    //check if this function exists 
    if(function_exists("mysql_real_escape_string")) { 
        $value = mysql_real_escape_string($value);
    } else {
        //for PHP version < 4.3.0 use addslashes
        $value = addslashes($value);
    }
    return $value;
}

function set_cookie($var, $value, $life = 0, $prefix = 1) {
	global $timestamp, $cookiepre, $cookiepath, $cookiedomain, $_SERVER;
	$life = $life ? ($timestamp + $life) : 0;
	$secure = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
	$var = ($prefix ? $cookiepre : '').$var;
	return setcookie($var, $value, $life, $cookiepath, $cookiedomain, $secure);
}

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

function del_cookie($var, $prefix = 1) {
    global $cookiepre;
    if(is_array($var)){
        foreach($var as $val) set_cookie($val, '', -360000, $prefix);
    } else {
        set_cookie($var, '', -360000, $prefix);
    }
}

function clear_cookie() {
    del_cookie(array("uid", "username", "email", "hash", "logintime", "remembertime", "seccode"));
}

// 根据制定数组生成唯一标识
function cacheIdentifier($params) {
    return substr(md5(serialize($params)),0,8);
}

// 检测缓存的生命周期
function check_cache($cachefile, $life = -1) {
    global $timestamp;
    if(file_exists($cachefile)) {
        return $life < 0 || $timestamp - @filemtime($cachefile) < $life;
    } else {
        return false;
    }
}

// 读取缓存
function read_cache($cachefile, $mode = 'i') {
    if(!file_exists($cachefile)) return false;
    return $mode == 'i' ? include $cachefile : file_get_contents($cachefile);
}

// 写入缓存
function write_cache($cachename, $cachedata = '', $extra = '', $mod='', $cachedir = '') {
    global $timestamp;

    $cachedir = $cachedir ? MUDDER_ROOT . $cachedir : MUDDER_CACHEDIR;
    if(!$extra) {
        $filename = 'cache_'.$cachename.'.php';
    } elseif($extra == 'js') {
        $filename = $cachename.'.js';
    }
    if(!is_dir($cachedir)) {
        @mkdir($cachedir, 0777);
    }
    $cachefile = $cachedir.$filename;
    if($fp = @fopen($cachefile, 'wb')) {
        if(!$extra && !$mod) {
            @fwrite($fp, "<?php\r\n//Mudder cache file\r\n//Created on ".date('Y-m-d H:i:s', $timestamp)."\r\n\r\n!defined('IN_MUDDER') && exit('Access Denied');\r\n\r\n".$cachedata."\r\n\r\n?>");
        } elseif($extra == 'js') {
            @fwrite($fp, "//Mudder cache file\r\n//Created on ".date('Y-m-d H:i:s', $timestamp)."\r\n\r\n".$cachedata."\r\n");
        } elseif($mod == 'return') {
            @fwrite($fp, "<?php \r\n!defined('IN_MUDDER') && exit('Access Denied');\r\nreturn $cachedata; \r\n?>");
        }
        @fclose($fp);
        @chmod($cachefile, 0777);
    } else {
        echo 'Can not write to '.$cachename.' cache files, please check directory ./data/cache/ .';
        exit;
    }
}

function arrayeval($array, $level = 0) {

	if(!is_array($array)) {
		return "'".$array."'";
	}
	if(is_array($array) && function_exists('var_export')) {
		return var_export($array, true);
	}
	$space = '';
	for($i = 0; $i <= $level; $i++) {
		$space .= "\t";
	}
	$evaluate = "array (\n\r";
	$comma = $space;
	if(is_array($array)) {
		foreach($array as $key => $val) {
			$key = is_string($key) ? '\''.add_cs_lashes($key).'\'' : $key;
			$val = !is_array($val) && (!preg_match("/^\-?[0-9]\d*$/", $val) || strlen($val) > 12) ? '\''.add_cs_lashes($val, '\'\\').'\'' : $val;
			if(is_array($val)) {
				$evaluate .= "$comma$key => ".arrayeval($val, $level + 1);
			} else {
				$evaluate .= "$comma$key => $val";
			}
			$comma = ",\n\r$space";
		}
	}
	$evaluate .= "\n\r$space)";
	return $evaluate;
}

// 数据调用
function datacall($callid) {
    global $_datacall,$_modules;
    $query = $_datacall[$callid];
    if(empty($query)) return '';
    if(empty($_modules[$query['module']])) return '';
    if($query['calltype']=='sql') {
        $fun = 'datacall_sql';
    } else {
        $fun = 'query_'.$query['fun'];
    }
    $s_var = $query['var'];
    if(empty($s_var)) return '';
    $var = '_QUERY['."\$_datacall['$callid']['var']".']';
    $array = "\$_datacall['$callid']['expression']";
    $restr = "{eval \$$var = $fun($callid,$array);}\r\n";
    $restr .= "{if !empty(\$$var)}\r\n";
    $restr .= "{template \$_datacall['$callid']['tplname'],'1_datacall','./templates/datacall'}\r\n";
    $restr .= "{else}\r\n";
    $restr .= "{template \$_datacall['$callid']['empty_tplname'],'1_datacall','./templates/datacall'}\r\n";
    $restr .= "{/if}\r\n";
    return $restr;
}

// SQL的数据调用
function datacall_sql($callid,$params) {
    global $db,$dbpre,$_config;

    $params = parseGlobal($params);
    $cachename = sprintf("%d_%s", $callid,cacheIdentifier($params));
    $cachefile = MUDDER_ROOT.$_config['datacall_dir'].'cache_'.$cachename.'.php';

    if(file_exists($cachefile) && check_cache($cachefile, $params['cachetime'])) {
        return read_cache($cachefile);
    }
    $result = array();
    $params['from'] = str_replace("{dbpre}", $dbpre, $params['from']);
    $params['where'] = !trim($params['where']) ? '1=1' : $params['where'];
    $params['orderby'] = !trim($params['orderby']) ? '' : " ORDER BY ".$params['orderby'];
    $sql = "SELECT " . $params['select'] . " FROM " . $params['from'] . " WHERE " . $params['where'] . " " . $params['other'] . $params['orderby'] . " LIMIT " . $params['limit'];

    $query = $db->query($sql);
    while($row=$db->fetch_array($query)) {
        $result[] = $row;
    }

    $db->free_result($query);
    if($params['cachetime'] > 0) {
        write_cache($cachename, arrayeval($result), '', 'return', $_config['datacall_dir']);
    }
    return $result;
}

// 从数组的表达式中取出一个变量字符，应用为全局变量，并返回这个变量的值
function parseGlobal(& $params) {
    if(!is_array($params)||count($params)==0) return $params;
    $gbls = array();
    foreach($params as $key => $val) {
        $match = array();
        if(preg_match_all('/\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+)\}/i', $val, $match)) {
            foreach($match[1] as $_val) {
                if(!in_array($_val, $gbls)) {
                    global $$_val;
                    $gbls[] = $_val;
                    $params[$key] = str_replace('{$'.$_val.'}', $$_val, $params[$key]);
                }
            }
        }
    }
    unset($match,$gbls,$val,$key);
    return $params;
}

function log_read() {
    // do nothing
}

function log_write($file, $log) {
	global $timestamp, $_DCACHE;
	$yearmonth = gmdate('Ym', $timestamp);
	$logdir = MUDDER_ROOT.'./cache/logs/';
	$logfile = $logdir.$yearmonth.'_'.$file.'.php';
	if(@filesize($logfile) > 2048000) {
		$dir = opendir($logdir);
		$length = strlen($file);
		$maxid = $id = 0;
		while($entry = readdir($dir)) {
			if(strexists($entry, $yearmonth.'_'.$file)) {
				$id = intval(substr($entry, $length + 8, -4));
				$id > $maxid && $maxid = $id;
			}
		}
		closedir($dir);

		$logfilebak = $logdir.$yearmonth.'_'.$file.'_'.($maxid + 1).'.php';
		@rename($logfile, $logfilebak);
	}
	if($fp = @fopen($logfile, 'a')) {
		@flock($fp, 2);
		$log = is_array($log) ? $log : array($log);
		foreach($log as $tmp) {
			fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>'), '', $tmp)."\n");
		}
		fclose($fp);
	}
}

function trimmed_title($text, $limit=12, $ext='') {
    if ($limit) {
        $val = csubstr($text, 0, $limit);
        return $val[1] ? $val[0].$ext : $val[0];
    } else {
        return $text;
    }
}

function csubstr($text, $start=0, $limit=12) {
    global $charset;
    if (function_exists('mb_substr')) {
        $more = (mb_strlen($text, $charset) > $limit) ? true : false;
        $text = mb_substr($text, 0, $limit, $charset);
        return array($text, $more);
    } elseif (function_exists('iconv_substr')) {
        $more = (iconv_strlen($text) > $limit) ? true : false;
        $text = iconv_substr($text, 0, $limit, $charset);
        return array($text, $more);
    } elseif (strtolower($charset) == "utf-8") {
        preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $text, $ar);
        if(func_num_args() >= 3) {
            if (count($ar[0])>$limit) {
                $more = true;
                $text = join("",array_slice($ar[0],0,$limit))."...";
            } else {
                $more = false;
                $text = join("",array_slice($ar[0],0,$limit));
            }
        } else {
            $more = false;
            $text = join("",array_slice($ar[0],0));
        }
        return array($text, $more);
    } else {
        $fStart = 0;
        $fStart = $fStart * 2; 
        $limit = $limit * 2; 
        $strlen = strlen($text); 
		for ( $i = 0; $i < $strlen; $i++ ) { 
            if ($i >= $fStart && $i < ($fStart + $limit ) ) { 
                if (ord(substr($text, $i, 1)) > 129) $tmpstr .= substr($text, $i, 2); 
                else $tmpstr .= substr($text, $i, 1); 
            } 
            if (ord(substr($text, $i, 1)) > 129 ) $i++; 
        } 
        $more = strlen($tmpstr) < $strlen; 
        return array($tmpstr, $more);
    }
}

function newdate($date, $format='Y-m-d') {
    global $timestamp;
    $date == 'NOW'||!$date ? $timestamp : $date;
    $date = is_numeric($date) ? $date : (!$date ? $timestamp : strtotime($date));
    $date = ($date == -1 || !$date) ? $timestamp : $date;
    if($format != 'w2style') {
        return date($format, $date);
    } else {
        $tm = $timestamp - $date;
        $num = 0;
        if($tm < 60) {
            $num = $tm;
            $unit = '秒钟';
        } elseif($tm < 3600) {
            $num = floor($tm / 60);
            $unit = '分钟';
        } elseif($tm < 3600*24) {
            $num = floor($tm / 3600);
            $unit = '小时';
        } elseif($tm < 3600*24*30) {
            $num = floor($tm / (3600*24));
            $unit = '天';
        } elseif($tm < 3600*24*30*365) {
            $num = floor($tm / (3600*24*30));
            $unit = '月';
        }
        return $num > 0 ? $num.$unit.'前' : date('Y-m-d', $date);
    }
}

function isemail($email) {
    return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

function formhash($uid, $username, $password) {
    global $_config;
    return substr(md5($_config['authkey'].$uid.$username.$password), 8, 8);
}

function cdc2dbc($number){
    $search_arr = array('０','１','２','３','４','５','６','７','８','９');
    $replace_arr = array('0','1','2','3','4','5','6','7','8','9');
    return str_replace($search_arr, $replace_arr, $number);
}

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last) {
        case 'g':
             $val *= 1024;
        case 'm':
             $val *= 1024;
        case 'k':
             $val *= 1024;
    }
    return $val;
}

function string_length($string, $min, $max) {
    return strlen($string) >= $min && strlen($string) <= $max;
}

function filter_htmltag($string) {
    return preg_replace("/(<\/?[a-zA-Z0-9\s\/]+>)/is", "", $string);
}

function strposex($haystack, $needle, $offset = 0) {
    return !(strpos($haystack, $needle, $offset) === false);
}

function random($length) {
	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
	$hash = '';
	$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	$max = strlen($chars) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $chars[mt_rand(0, $max)];
	}
	return $hash;
}

function multi($num, $perpage, $curpage, $mpurl, $anchor = '') {
    $multipage = '';
    $mpurl .= strpos($mpurl, '?') ? '&amp;' : '?';
    if($num > $perpage) {
        $page = 10;
        $offset = 5;
        $pages = @ceil($num / $perpage);
        if($page > $pages) {
            $from = 1;
            $to = $pages;
        } else {
            $from = $curpage - $offset;
            $to = $curpage + $page - $offset - 1;
            if($from < 1) {
                $to = $curpage + 1 - $from;
                $from = 1;
                if(($to - $from) < $page && ($to - $from) < $pages) {
                    $to = $page;
                }
            } elseif($to > $pages) {
                $from = $curpage - $pages + $to;
                $to = $pages;
                if(($to - $from) < $page && ($to - $from) < $pages) {
                    $from = $pages - $page + 1;
                }
            }
        }
        $multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'page=1'.$anchor.'" class="p_redirect">&lt;&lt;</a>' : '').($curpage > 1 ? '<a href="'.$mpurl.'page='.($curpage - 1).$anchor.'" class="p_redirect">&lt;</a>' : '');
        for($i = $from; $i <= $to; $i++) {
            $multipage .= $i == $curpage ? '<span class="p_curpage">'.$i.'</span>' : '<a href="'.$mpurl.'page='.$i.$anchor.'" class="p_num">'.$i.'</a>';
        }
        $multipage .= ($curpage < $pages ? '<a href="'.$mpurl.'page='.($curpage + 1).$anchor.'" class="p_redirect">&gt;</a>' : '').($to < $pages ? '<a href="'.$mpurl.'page='.$pages.$anchor.'"class="p_redirect">&gt;&gt;</a>' : '');
        $multipage = $multipage ? '<div class="p_bar"><span class="p_info">'.$num.'</span>'.$multipage.'</div>' : '';
    }
    return $multipage;
}

function template($file, $templateid='', $tpldir='') {
    global $_config, $template_dir, $template_url;

    $templateid = ($templateid) ? $templateid : ($_config['templateid'] ? $_config['templateid'] : '1');
    $tpldir = ($tpldir) ? $tpldir : ($template_dir ? $template_dir : './templates/main/default');
    $tpldir = substr($tpldir,-1,1) == '/' ? substr($tpldir,0,-1) : $tpldir;

    $cachedir = './data/templates';
    $ext = empty($_config['tplext']) ? '.htm' : $_config['tplext'];
    
    $tplfile = MUDDER_ROOT.$tpldir.'/'.$file.$ext;
    $objfile = MUDDER_ROOT.$cachedir.'/'.$templateid.'_'.$file.'.tpl.php';

    if(!file_exists($tplfile) || (@filemtime($tplfile) > @filemtime($objfile))) {
        require_once MUDDER_ROOT.'./include/template.func.php';
        parse_template($file, $templateid, $tpldir, $cachedir, $ext);
    }
    return $objfile;
}

function template_plugin($file) {
    global $pluginmodule;
    $pluginmodule['directory'] = './plugins/'.$pluginmodule['directory'].'templates';
    return template($file, "1_plugin_{$pluginmodule['module']}" ,$pluginmodule['directory']);
}

function spacestyle($file, $space_styleid, $styledir = '') {
    global $_config, $_templates;

    $space_styleid = array_key_exists($space_styleid, $_templates['space']) ? $space_styleid : ($_config['space_styleid'] ? $_config['space_styleid'] : '2');

    $styledir = $styledir ? $styledir : ($_templates['space'][$space_styleid]['directory'] ? $_templates['space'][$space_styleid]['directory'] : './templates/space/default');
    $styledir = substr($styledir,-1,1) == '/' ? substr($styledir,0,-1) : $styledir;

    $cachedir = './data/templates';
    $space_styleid = 'space_'.$space_styleid;

    $ext = empty($_config['tplext']) ? '.htm' : $_config['tplext'];

    $stylefile = MUDDER_ROOT.$styledir.'/'.$file.$ext;
    $objfile = MUDDER_ROOT.$cachedir.'/'.$space_styleid.'_'.$file.'.tpl.php';
    if(!file_exists($objfile) || (@filemtime($stylefile) > @filemtime($objfile))) {
        require_once MUDDER_ROOT.'./include/template.func.php';
        parse_template($file, $space_styleid, $styledir, $cachedir, $ext);
    }
    return $objfile;
}

function itemstyle($file, $item_styleid) {
    global $_config, $_templates, $itemstyle_url;

    $styledir = $_templates['item'][$item_styleid]['directory'];
    $styledir = substr($styledir,-1,1) == '/' ? substr($styledir,0,-1) : $styledir;

    $cachedir = './data/templates';
    $item_styleid = 'item_'.$item_styleid;

    $ext = empty($_config['tplext']) ? '.htm' : $_config['tplext'];

    $stylefile = MUDDER_ROOT.$styledir.'/'.$file.$ext;
    $objfile = MUDDER_ROOT.$cachedir.'/'.$item_styleid.'_'.$file.'.tpl.php';
    
    if(!file_exists($objfile) || (@filemtime($stylefile) > @filemtime($objfile))) {
        require_once MUDDER_ROOT.'./include/template.func.php';
        parse_template($file, $item_styleid, $styledir, $cachedir, $ext);
    }
    return $objfile;
}

function output() {
    global $_config, $_rewrite, $_modules, $MOD;
    $output = ob_get_contents();
    ob_end_clean();
    require_once MUDDER_ROOT.'./include/rewrite.inc.php';
    $_config['gzipcompress'] ? @ob_start('ob_gzhandler') : ob_start();
    echo $output;
    exit;
}

function footer($templateid='', $tpldir='', $extra='') {
    global $db, $mudder_starttime, $_config, $_VERSION, $no_body;
    if($_config['debug']){
        $mtime = explode(' ', microtime());
        $totaltime = number_format(($mtime[1] + $mtime[0] - $mudder_starttime), 6);
        $gzip = $_config['gzipcompress'] ? 'enabled' : 'disabled';
        $sitedebug = 'Processed in '.$totaltime.' second(s), '.$db->query_num.' queries, Gzip '.$gzip;
    }
    if($extra == 'space') {
        require_once spacestyle('footer', $templateid, $tpldir);
    } elseif($extra == 'item') {
        require_once itemstyle('footer', $templateid, $tpldir);
    } else {
        require_once template('modoer_footer', $templateid, $tpldir);
    }
    output();
}

function redirect($msg, $url = 'javascript:history.go(-1);', $min = '3') {
    global $_config, $template_url, $charset;
    require_once template('redirect');
    output();
}

//ajax 提示框
function dialog($caption, $msg, $extra = '') {
    global $_config,$forward;
    $caption = html_special_chars(trim($caption));
    $msg = trim($msg);
    $search = array('"',"\r\n","\r","\n","\n\r");
    $replace = array('\\"',"{LF}","{LF}","{LF}","{LF}");
    echo '{ caption:"'.$caption.'",message:'.'"'.str_replace($search,$replace,$msg).'"';
    if($extra == 'login') {
        $url = $_config['siteurl'].'member/login.php?forward='.$forward;
        echo ',extra:"'.$extra.'",url:"'.$url.'" }';
        //require_once template('dlg_login_msg');
    } elseif($extra == 'myDialog') {
        echo ',extra:"myDialog" }';
    } else {
        echo '}';
    }
    output();
}

// $rewrite是否使用$rewrite功能，false强制不使用，true按系统默认模式 // 未实现
function location($url, $rewrite = true) {
    global $_config;
    header('Location:' . $url);
}

function check_submit($var, $allowget = 0) {
    if(empty($GLOBALS[$var])) return false;
    if($allowget || ($_SERVER['REQUEST_METHOD'] == 'POST' && (empty($_SERVER['HTTP_REFERER']) ||
			preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])))) {
        return true;
    } else {
        if(defined('IN_ADMIN') && SCRIPTNAV == 'admincp') {
            cpmsg('无效的提交行为！');
        } else {
            redirect('无效的提交行为！');
        }
	}
}

function diex($msg) {
    global $_config;
    include MUDDER_ROOT.'./include/diex.php';
    exit(0);
}

function check_ipaccess($checkip, $accessips) {
    if($accessips && is_array($accessips)) {
        return in_array($checkip, $accessips);
    } else {
        return false;
    }
}

// 有效的表keyId数字
function validKey($id) {
    return is_numeric($id) and $id > 0;
}

function upexpleve($subject, $action = 'update') {
    global $_expleve, $db, $dbpre, $user;
    $exp_type = array(
        'reg',
        'addshop',
        'updateshop',
        'addreview',
        'addrespond',
        'addpicture',
        'deletereview',
        'deleterespond',
        'deletepicture',
    );
    if(in_array($subject, $exp_type)) {
        $uppoint = intval(addslashes($_expleve[$subject]['point']));
        $upcoin = intval(addslashes($_expleve[$subject]['coin']));
        $set = "`point`=`point`+$uppoint, `coin`=`coin`+$upcoin";
        $uid = intval($user->uid);
        $sql = "UPDATE {$dbpre}members SET $set WHERE uid='$uid'";
        if($action == 'sqlstr') return $sql;
        elseif($action == 'sqlset') return $set;
        elseif($action == 'update' && $uppoint != 0 && $upcoin != 0) $db->update($sql);
    }
}

function dblimit($page, $offset) {
    if(!$offset || $offset < 1) $offset = 10;
    return array((($page-1) * $offset),$offset);
}

function get_limit($page, $offset) {
    if(!$offset || $offset < 1) $offset = 10;
    return (($page-1) * $offset).', '.$offset;
}

function get_face($face) {
    global $_config;
    $face = html_special_chars(stripslashes($face));
    if(strpos($face, '|')){
        $param = implode('|', $face);
        $path = $_config['siteurl'].'images/faces/'.$param[1];
    }else{
        $path = $_config['siteurl'].'images/faces/'.$face;
    }
    return $path;
}

// size => source, small, big
function get_picture($folder, $filename, $size='source') {
    global $_config;
    $prefix_arr = array(
        'source' => '',
        'small' => 's_',
        'big' => 'g_'
    );
    $size = array_key_exists($size, $prefix_arr) ? $size : 'source';
    return $_config['siteurl'].'uploads/pictures/'.$folder.'/'.$prefix_arr[$size].$filename;
}

function get_userrank($point) {
    global $_userranks, $_usergroups;
    if($_userranks) foreach($_userranks as $rank) {
        if($point >= $rank['point']){
            return $rank['rankname'];
        }
    } else {
        return 'unknowable';
    }
    return 'member';
}

function get_item_suitplace($panelcode) {
    global $_panel_config;
    return $_panel_config[$panelcode]['suitplaces'];
}

function get_item_review($panelcode) {
    global $_panel_config;
    return $_panel_config[$panelcode]['review'];
}

function vp($var) {
    echo "<div style=\"border:1px solid #ddd;background:#F7F7F7;padding:5px 10px;\">\r\n";
    echo "<pre style=\"font-family:Arial,Vrinda;font-size:14px;\">\r\n";
    var_dump($var);
    echo "\r\n</pre>\r\n";
    echo "</div>";
}
function pr($var) {
    echo "<div style=\"border:1px solid #ddd;background:#F7F7F7;padding:5px 10px;\">\r\n";
    echo "<pre style=\"font-family:Arial,Vrinda;font-size:14px;\">\r\n";
    print_r($var);
    echo "\r\n</pre>\r\n";
    echo "</div>";
}
?>