<?php
if(!defined('PCFINAL')) exit('Request Error!');

function sql_query($sql){
	global $conn;
	if (function_exists('mysqli_close')) {
		return mysqli_query($conn,$sql);
	} else {
		return mysql_query($sql);
	}
}
function sql_fetch_array ($result){
	if (function_exists('mysqli_close')) {
		return mysqli_fetch_array($result);
	} else {
		return mysql_fetch_array($result);
	}
}
function sql_num_rows ($result){
	if (function_exists('mysqli_close')) {
		return mysqli_num_rows($result);
	} else {
		return mysql_num_rows($result);
	}
}
function sql_insert_id(){
	global $conn;
	if (function_exists('mysqli_close')) {
		return mysqli_insert_id($conn);
	} else {
		return mysql_insert_id();
	}
}



if (!empty($_GET)){
	$_GET = addslashes_deep($_GET);
}
if (!empty($_POST)){
	$_POST = addslashes_deep($_POST);
}
$_COOKIE = addslashes_deep($_COOKIE);
$_REQUEST = addslashes_deep($_REQUEST);


function addslashes_deep($value) {
	if (empty($value)) {
		return $value;
	} else {
		return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
	}
}

//提示后返回
function alert_back($str) {
	die('<script type="text/javascript">alert("'.$str.'");window.history.back();</script>');
}

//提示后跳转
function alert_href($str, $rul) {
	die('<script type="text/javascript">alert("'.$str.'");window.location.href="'.$rul.'"</script>');
}

//空值返回
function null_back($str, $rul) {
	if ($str == '') {
		alert_back($rul);
	}
}

//非数字返回
function non_numeric_back($str, $alert_srt) {
	if (!is_numeric($str) || $str < 0) {
		alert_back($alert_srt);
	}
}

//分页初始化
//参数说明：1分页参数。2.每页显示多少。3.一共多少。
function page_handle($parameter, $size, $sum) {
	if (isset($_GET[$parameter])) {
		$page_num = $_GET[$parameter];
		if (empty($page_num) || $page_num < 1 || !is_numeric($page_num)) {
			$page_num = 1;
		} else {
			$page_num = intval($page_num);
		}
	} else {
		$page_num = 1;
	}
	if ($sum == 0) {
		$page_sum = 1;
	} else {
		$page_sum = ceil($sum / $size);
	}
	if ($page_num > $page_sum) {
		$page_num = $page_sum;
	}
	$from_num = ($page_num - 1) * $size;
	$tmp = array();
	$tmp[0] = $from_num;
	$tmp[1] = $size;
	$tmp[2] = $page_sum;
	$tmp[3] = $page_num;
	$tmp[4] = $parameter;
	return $tmp;
}

//返回翻页条
//参数说明：1.总页数。2.当前页。3.分页参数。4.分页半径。
function page_show($sum, $current, $parameter, $length) {
	$page_sum = $sum;
	$page_current = $current;
	$page_parameter = $parameter;
	$page_len = $length;
	$page_start = 0;
	$page_end = 0;
	$page_start = $page_current - $page_len;
	if ($page_start <= 0) {
		$page_start = 1;
		$page_end = $page_start + $page_end;
	}
	$page_end = $page_current + $page_len;
	if ($page_end > $page_sum) {
		$page_end = $page_sum;
	}
	$page_link = $_SERVER['REQUEST_URI'];
	$tmp_arr = parse_url($page_link);
	if (isset($tmp_arr['query'])){
		$url = $tmp_arr['path'];
		$query = $tmp_arr['query'];
		parse_str($query, $arr);
		unset($arr[$page_parameter]);
		if (count($arr) != 0){
			$page_link = $url.'?'.http_build_query($arr).'&';
		}else{
			$page_link = $url.'?';
		}
	}else{
		$page_link = $page_link.'?';
	}
	$page_back = '';
	$page_home = '';
	$page_list = '';
	$page_last = '';
	$page_next = '';
	$tmp = '<div class="page_show">';
	if ($page_current > $page_len + 1) {
		$page_home = '<a href="'.$page_link.$page_parameter.'=1" title="首页">1...</a>';
	}
	if ($page_current == 1) {
		$page_back = '';
	} else {
		$page_back = '<a href="'.$page_link.$page_parameter.'='.($page_current - 1).'" title="上一页"><<</a>';
	}
	for ($i = $page_start; $i <= $page_end; $i++) {
		if ($i == $page_current) {
			$page_list = $page_list.'<a href="javascript:void(0)" class="page_current">'.$i.'</a>';
		} else {
			$page_list = $page_list.'<a href="'.$page_link.$page_parameter.'='.$i.'" title="第'.$i.'页">'.$i.'</a>';
		}
	}
	if ($page_current < $page_sum - $page_len) {
		$page_last = '<a href="'.$page_link.$page_parameter.'='.$page_sum.'" title="尾页">...'.$page_sum.'</a>';
	}
	if ($page_current == $page_sum) {
		$page_next = '';
	} else {
		$page_next = '<a href="'.$page_link.$page_parameter.'='.($page_current + 1).'" title="下一页">>></a>';
	}
	$tmp = $tmp.$page_back.$page_home.$page_list.$page_last.$page_next.'</div>';
	return $tmp;
}
//$sum, $current, $parameter, $length
function page_shows($sum, $current, $parameter, $length) {
	$page_sum = $sum;
	$page_current = $current;
	$page_parameter = $parameter;
	$page_len = $length;
	$page_start = 0;
	$page_end = 0;
	$page_start = $page_current - $page_len;
	if ($page_start <= 0) {
		$page_start = 1;
		$page_end = $page_start + $page_end;
	}
	$page_end = $page_current + $page_len;
	if ($page_end > $page_sum) {
		$page_end = $page_sum;
	}

	$page_back = '';
	$page_home = '';
	$page_list = '';
	$page_last = '';
	$page_next = '';
	$tmp = '<div class="page_show">';
	if ($page_current > $page_len + 1) {
		$page_home = '<a href="'.$page_parameter.'1.html" title="首页">1...</a>';
	}
	if ($page_current == 1) {
		$page_back = '';
	} else {
		$page_back = '<a href="'.$page_parameter.($page_current - 1).'.html" title="上一页"><<</a>';
	}
	for ($i = $page_start; $i <= $page_end; $i++) {
		if ($i == $page_current) {
			$page_list = $page_list.'<a href="javascript:void(0)" class="page_current">'.$i.'</a>';
		} else {
			$page_list = $page_list.'<a href="'.$page_parameter.$i.'.html" title="第'.$i.'页">'.$i.'</a>';
		}
	}
	if ($page_current < $page_sum - $page_len) {
		$page_last = '<a href="'.$page_parameter.$page_sum.'.html" title="尾页">...'.$page_sum.'</a>';
	}
	if ($page_current == $page_sum) {
		$page_next = '';
	} else {
		$page_next = '<a href="'.$page_parameter.($page_current + 1).'.html" title="下一页">>></a>';
	}
	$tmp = $tmp.$page_back.$page_home.$page_list.$page_last.$page_next.'</div>';
	return $tmp;
}

function url_encode($str) {
	$src = array('/', '+', '=');
	$dist = array('_a', '_b', '_c');
	$old = base64_encode($str);
	$new = str_replace($src, $dist, $old);
	return $new;
}

function url_decode($str) {
	$src = array('_a', '_b', '_c');
	$dist = array('/', '+', '=');
	$old = str_replace($src, $dist, $str);
	$new = base64_decode($old);
	return $new;
}

//截断字符串
function cut_str($str, $len = 10, $etc = '...') {
	$restr = '';
	$i = 0;
	$n = 0.0;
	$strlen = strlen($str);
	while (($n < $len) and ($i < $strlen)) {
		$temp_str = substr($str, $i, 1);
		$ascnum = ord($temp_str);
		if ($ascnum >= 252) {
			$restr = $restr . substr($str, $i, 6);
			$i = $i + 6;
			$n++;
		} else if ($ascnum >= 248) {
			$restr = $restr . substr($str, $i, 5);
			$i = $i + 5;
			$n++;
		} else if ($ascnum >= 240) {
			$restr = $restr . substr($str, $i, 4);
			$i = $i + 4;
			$n++;
		} else if ($ascnum >= 224) {
			$restr = $restr . substr($str, $i, 3);
			$i = $i + 3;
			$n++;
		} else if ($ascnum >= 192) {
			$restr = $restr . substr($str, $i, 2);
			$i = $i + 2;
			$n++;
		}
		else if ($ascnum >= 65 and $ascnum <= 90 and $ascnum != 73) {
			$restr = $restr . substr($str, $i, 1);
			$i = $i + 1;
			$n++;
		}
		else if (!(array_search($ascnum, array(37,38,64,109,119)) === FALSE)) {
			$restr = $restr . substr($str, $i, 1);
			$i = $i + 1;
			$n++;
		}
		else {
			$restr = $restr . substr($str, $i, 1);
			$i = $i + 1;
			$n = $n + 0.5;
		}
	}
	if ($i < $strlen) {
		$restr = $restr . $etc;
	}
	return $restr;
}

/**
 * @from extend.php
 * 过滤xss攻击
 * @param str $val
 * @return mixed
 */
function remove_xss($val) {
	// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
	// this prevents some character re-spacing such as <java\0script>
	// note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
	$val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

	// straight replacements, the user should never need these since they're normal characters
	// this prevents like <IMG SRC=@avascript:alert('XSS')>
	$search = 'abcdefghijklmnopqrstuvwxyz';
	$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$search .= '1234567890!@#$%^&*()';
	$search .= '~`";:?+/={}[]-_|\'\\';
	for ($i = 0; $i < strlen($search); $i++) {
		// ;? matches the ;, which is optional
		// 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

		// @ @ search for the hex values
		$val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
		// @ @ 0{0,7} matches '0' zero to seven times
		$val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
	}

	// now the only remaining whitespace attacks are \t, \n, and \r
	$ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script',
	              'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
	$ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut',
	         'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate',
	         'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut',
	         'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend',
	         'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange',
	         'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete',
	         'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover',
	         'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange','onreadystatechange',
	         'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted',
	         'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
	$ra = array_merge($ra1, $ra2);

	$found = true; // keep replacing as long as the previous round replaced something
	while ($found == true) {
		$val_before = $val;
		for ($i = 0; $i < sizeof($ra); $i++) {
			$pattern = '/';
			for ($j = 0; $j < strlen($ra[$i]); $j++) {
				if ($j > 0) {
					$pattern .= '(';
					$pattern .= '(&#[xX]0{0,8}([9ab]);)';
					$pattern .= '|';
					$pattern .= '|(&#0{0,8}([9|10|13]);)';
					$pattern .= ')*';
				}
				$pattern .= $ra[$i][$j];
			}
			$pattern .= '/i';
			$replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
			$val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
			if ($val_before == $val) {
				// no replacements were made, so exit the loop
				$found = false;
			}
		}
	}
	return $val;
}

//获取当前页面的url

function get_url() {
	$pageURL = 'http://';
	if ($_SERVER["SERVER_PORT"] != "80") {
		$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
	} else {
		$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
	}
	return $pageURL;
}
//获取当前页面的文件名

function file_self () {
	$url = $_SERVER['PHP_SELF'];
	$arr = explode( '/' , $url );
	$filename = $arr[count($arr)-1];
	return $filename;
}


//获取IP
function get_ip() {
	static $ip = NULL;
	if ($ip !== NULL) return $ip;
	if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
		$pos = array_search('unknown', $arr);
		if (false !== $pos) unset($arr[$pos]);
		$ip = trim($arr[0]);
	} else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} else if (isset($_SERVER['REMOTE_ADDR'])) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	//IP地址合法验证
	$ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';
	return $ip;
}

//清理html
function clear_html($str) {
	$str = strip_tags($str);
	$str = trim($str);
	$str = preg_replace('/\s(?=\s)/', '', $str);
	$str = preg_replace('/[\n\r\t]/', ' ', $str);
	return $str;
}

//获取随机字符

function random_str($length = 6, $type = '') {
	$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	if ($type == 'num') {
		$chars = '0123456789';
	}
	$random_str = '';
	for ($i = 0; $i < $length; $i++) {
		$random_str.= $chars[mt_rand(0, strlen($chars) - 1) ];
	}
	return $random_str;
}



//将数组转换成供insert用的字符串
function arrtoinsert($arr){
	$key = '';
	$value = '';
	foreach($arr as $k=>$v){
		$tmp_key[] = '`'.$k.'`';
		$tmp_value[] = '"'.$v.'"';
	}
	$key .= implode(',',$tmp_key);
	$value .= implode(',',$tmp_value);
	$tmp[0] = $key;
	$tmp[1] = $value;
	return $tmp;
}

//将数组转换成供update用的字符串
function arrtoupdate($arr){
	$tmp = '';
	$s = '';
	foreach($arr as $k=>$v){
		$tmp .= $s.'`'.$k.'` = "'.$v.'"';
		$s = ',';
	}
	return $tmp;
}
?>
