<?php
/*获取客户端ip*/
function getip()
{
	if (isset($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], "unknown"))
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], "unknown")) {
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		if (stripos($ip, ',') > 0) {
			$iparr = explode(",", $ip);
			foreach ($iparr as $key => $var) {
				if ($var == '127.0.0.1') unset($iparr[$key]);
			}
			if (count($iparr > 0)) $ip = $iparr[0];
		}
	} else if (isset($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
		$ip = $_SERVER['REMOTE_ADDR'];
	else if (isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
		$ip = $_SERVER['REMOTE_ADDR'];
	else $ip = "";
	if (!filter_var($ip, FILTER_VALIDATE_IP)) $ip = "";
	return ($ip);
}
function getipport()
{
	$ipport = (int)$_SERVER['REMOTE_PORT'];
	return $ipport;
}
//是否为局域网ip
function lanip($ip)
{
	if (filter_var($ip, FILTER_VALIDATE_IP,  FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
		return false;
	} else {
		return true;
	}
}

function url_admin($a = ROUTE_A, $c = ROUTE_C, $parm = array(), $hashstr = '')
{
	global $yunyecms_admlogin;
	if ($a == '') $a = ROUTE_A;
	if ($c == '') $c = ROUTE_C;
	$a == 'init' ? $returnurl = "admin.php?c=" . $c : $returnurl = "admin.php?c=" . $c . "&a=" . $a;
	if (!empty($parm)) {
		foreach ($parm as $key => $var) {
			$returnurl = $returnurl . "&" . $key . "=" . $var;
		}
	}
	if (empty($hashstr)) {
		$hashstr = "&" . $yunyecms_admlogin["ehashname"] . "=" . $yunyecms_admlogin["ehash"];
	}
	return $returnurl . $hashstr;
}
/**
 * URL组装 支持不同URL模式
 * @param string $url URL表达式，格式：'[分组/模块/操作#锚点@域名]?参数1=值1&参数2=值2...'
 * @param string|array $vars 传入的参数，支持数组和字符串
 * @param string $suffix 伪静态后缀，默认为true表示获取配置值
 * @param boolean $redirect 是否跳转，如果设置为true则表示跳转到该URL地址
 * @param boolean $domain 是否显示域名
 * @return string
 */
function url($url = '', $vars = '', $suffix = true, $redirect = false, $domain = false)
{
	// 解析URL
	global $lang;
	$info   =  parse_url($url);
	$url    =  !empty($info['path']) ? $info['path'] : ROUTE_A;
	if (isset($info['fragment'])) { // 解析锚点
		$anchor =   $info['fragment'];
		if (false !== strpos($anchor, '?')) { // 解析参数
			list($anchor, $info['query']) = explode('?', $anchor, 2);
		}
		if (false !== strpos($anchor, '@')) { // 解析域名
			list($anchor, $host)    =   explode('@', $anchor, 2);
		}
	} elseif (false !== strpos($url, '@')) { // 解析域名
		list($url, $host)    =   explode('@', $info['path'], 2);
	}
	// 解析子域名
	if (isset($host)) {
		$domain = $host . (strpos($host, '.') ? '' : strstr($_SERVER['HTTP_HOST'], '.'));
	} elseif ($domain === true) {
		$domain = $_SERVER['HTTP_HOST'];
	}
	// 解析参数
	if (is_string($vars)) { // aaa=1&bbb=2 转换成数组
		parse_str($vars, $vars);
	} elseif (!is_array($vars)) {
		$vars = array();
	}
	if (isset($info['query'])) { // 解析地址里面参数 合并到vars
		parse_str($info['query'], $params);
		$vars = array_merge($params, $vars);
	}
	// URL组装
	$depr = URL_PATHINFO_DEPR;
	if ($url) {
		if (0 === strpos($url, '/')) { // 定义路由
			$route      =   true;
			$url        =   substr($url, 1);
			if (!empty($_GET['lang']) && (is_numeric($_GET['lang']) || ctype_alnum($_GET['lang']))) {
				$urlroutearr = explode('/', $url);
				if ($urlroutearr[0])
					$strsql = "select count(*) from `#yunyecms_lang` where `landir` ='{$urlroutearr[0]}'";
				if (!getcount($strsql)) {
					$url = $_GET['lang'] . '/' . $url;
				}
			}
			if ('/' != $depr) {
				$url    =   str_replace('/', $depr, $url);
			}
		} else {
			if (!empty($_GET['lang']) && (is_numeric($_GET['lang']) || ctype_alnum($_GET['lang']))) {
				$vars["lang"] = $_REQUEST['lang'];
			}
			if (URL_MODEL == 5) {
				$route_group = 'app';
				if (!empty($lang)) $vars["lang"] = $lang['id'];
			} else {
				$route_group = ROUTE_G;
			}
			if ('/' != $depr) { // 安全替换
				$url    =   str_replace('/', $depr, $url);
			}
			// 解析分组、模块和操作
			$url        =   trim($url, $depr);
			$path       =   explode($depr, $url);
			$var        =   array();
			if (empty($path)) {
				$var["g"] = $route_group;
				$var["m"] = ROUTE_M;
				$var["c"] = ROUTE_C;
				$var["a"] = ROUTE_A;
			} else {
				$pathsize = count($path);
				switch ($pathsize) {
					case 1:
						$var["g"] = $route_group;
						$var["m"] = ROUTE_M;
						$var["c"] = ROUTE_C;
						$var["a"] = strtolower(array_pop($path));
						break;
					case 2:
						$var["g"] = $route_group;
						$var["m"] = ROUTE_M;
						$var["c"] = strtolower(array_shift($path));
						$var["a"] = strtolower(array_shift($path));
						break;
					case 3:
						$var["g"] = $route_group;
						$var["m"] = strtolower(array_shift($path));
						$var["c"] = strtolower(array_shift($path));
						$var["a"] = strtolower(array_shift($path));
						break;
					case 4:
						$var["g"] = strtolower(array_shift($path));
						$var["m"] = strtolower(array_shift($path));
						$var["c"] = strtolower(array_shift($path));
						$var["a"] = strtolower(array_shift($path));
						break;
				}
			}
		}
	}
	if (URL_MODEL == 0) { // 普通模式URL转换
		if (isset($route)) {
			$url    =   APP_IN . '/' . rtrim($url, $depr);
		} else {
			if ($var["g"] == "app") {
				unset($var["g"]);
				if ($var["c"] == "index" && $var["a"] == 'index' && $var["m"] == 'content') {
					$var = array();
				} elseif ($var["m"] == "content" && $var["c"] == 'index') {
					unset($var["c"]);
					unset($var["m"]);
				}
			}
			$url        =   ROOT . 'index.php?' . http_build_query($var);
			if (!empty($vars)) {
				$vars   =   urldecode(http_build_query($vars));
				$url   .=   '&' . $vars;
			}
		}
	} else { // PATHINFO模式或者兼容URL模式

		if (isset($route)) {
			$url    =   APP_IN . '/' . rtrim($url, $depr);
		} else {
			$url    =   APP_IN . '/' . implode($depr, $var);
		}
		if (!empty($vars)) { // 添加参数
			foreach ($vars as $var => $val) {
				if ('' !== trim($val))   $url .= $depr . $var . $depr . urlencode($val);
			}
		}
		if ($suffix) {
			$suffix   =  $suffix === true ? URL_HTML_SUFFIX : $suffix;
			if ($pos = strpos($suffix, '|')) {
				$suffix = substr($suffix, 0, $pos);
			}
			if ($suffix && '/' != substr($url, -1)) {
				$url  .=  '.' . ltrim($suffix, '.');
			}
		}
	}
	if (isset($anchor)) {
		$url  .= '#' . $anchor;
	}
	if ($domain) {
		$url   =  (is_ssl() ? 'https://' : 'http://') . $domain . $url;
	}
	if ($redirect) // 直接跳转URL
		redirect($url);
	else
		return $url;
}

/**
 * URL组装 支持不同URL模式
 * @param string $url URL表达式，格式：'[分组/模块/操作#锚点@域名]?参数1=值1&参数2=值2...'
 * @param string|array $vars 传入的参数，支持数组和字符串
 * @param string $suffix 伪静态后缀，默认为true表示获取配置值
 * @param boolean $redirect 是否跳转，如果设置为true则表示跳转到该URL地址
 * @param boolean $domain 是否显示域名
 * @return string
 */
function url_addons($url = '', $vars = '', $suffix = true, $redirect = false, $domain = false)
{
	// 解析URL
	global $yunyecms_admlogin;
	$info   =  parse_url($url);
	$url    =  !empty($info['path']) ? $info['path'] : ROUTE_A;
	if (isset($info['fragment'])) { // 解析锚点
		$anchor =   $info['fragment'];
		if (false !== strpos($anchor, '?')) { // 解析参数
			list($anchor, $info['query']) = explode('?', $anchor, 2);
		}
		if (false !== strpos($anchor, '@')) { // 解析域名
			list($anchor, $host)    =   explode('@', $anchor, 2);
		}
	} elseif (false !== strpos($url, '@')) { // 解析域名
		list($url, $host)    =   explode('@', $info['path'], 2);
	}
	// 解析子域名
	if (isset($host)) {
		$domain = $host . (strpos($host, '.') ? '' : strstr($_SERVER['HTTP_HOST'], '.'));
	} elseif ($domain === true) {
		$domain = $_SERVER['HTTP_HOST'];
	}
	// 解析参数
	if (is_string($vars)) { // aaa=1&bbb=2 转换成数组
		parse_str($vars, $vars);
	} elseif (!is_array($vars)) {
		$vars = array();
	}
	if (isset($info['query'])) { // 解析地址里面参数 合并到vars
		parse_str($info['query'], $params);
		$vars = array_merge($params, $vars);
	}
	// URL组装
	$depr = URL_PATHINFO_DEPR;
	if ($url) {
		if (0 === strpos($url, '/')) { // 定义路由
			$route      =   true;
			$url        =   substr($url, 1);
			if (!empty($_GET['lang']) && (is_numeric($_GET['lang']) || ctype_alnum($_GET['lang']))) {
				$urlroutearr = explode('/', $url);
				if ($urlroutearr[0])
					$strsql = "select count(*) from `#yunyecms_lang` where `landir` ='{$urlroutearr[0]}'";
				if (!getcount($strsql)) {
					$url = $_GET['lang'] . '/' . $url;
				}
			}
			if ('/' != $depr) {
				$url    =   str_replace('/', $depr, $url);
			}
		} else {
			if (!empty($_GET['lang']) && (is_numeric($_GET['lang']) || ctype_alnum($_GET['lang']))) {
				$vars["lang"] = $_REQUEST['lang'];
			}
			if ('/' != $depr) { // 安全替换
				$url    =   str_replace('/', $depr, $url);
			}
			// 解析分组、模块和操作
			$url        =   trim($url, $depr);
			$path       =   explode($depr, $url);
			$var        =   array();
			if (empty($path)) {
				$var["g"] = ROUTE_G;
				$var["m"] = ROUTE_M;
				$var["c"] = ROUTE_C;
				$var["a"] = ROUTE_A;
			} else {
				$pathsize = count($path);
				switch ($pathsize) {
					case 1:
						$var["g"] = ROUTE_G;
						$var["m"] = ROUTE_M;
						$var["c"] = ROUTE_C;
						$var["a"] = strtolower(array_pop($path));
						break;
					case 2:
						$var["g"] = ROUTE_G;
						$var["m"] = ROUTE_M;
						$var["c"] = strtolower(array_shift($path));
						$var["a"] = strtolower(array_shift($path));
						break;
					case 3:
						$var["g"] = ROUTE_G;
						$var["m"] = strtolower(array_shift($path));
						$var["c"] = strtolower(array_shift($path));
						$var["a"] = strtolower(array_shift($path));
						break;
					case 4:
						$var["g"] = strtolower(array_shift($path));
						$var["m"] = strtolower(array_shift($path));
						$var["c"] = strtolower(array_shift($path));
						$var["a"] = strtolower(array_shift($path));
						break;
				}
			}
		}
	}
	if ($var["g"] == "app") {
		unset($var["g"]);
		if ($var["c"] == "index" && $var["a"] == 'index' && $var["m"] == 'content') {
			$var = array();
		} elseif ($var["m"] == "content" && $var["c"] == 'index') {
			unset($var["c"]);
			unset($var["m"]);
		}
	}
	$url        =   ROOT . 'index.php?' . http_build_query($var);
	if (!empty($vars)) {
		$vars   =   urldecode(http_build_query($vars));
		$url   .=   '&' . $vars;
	}
	if (!empty($yunyecms_admlogin)) {
		$hashstr = "&" . $yunyecms_admlogin["ehashname"] . "=" . $yunyecms_admlogin["ehash"];
		$url = $url . $hashstr;
	}
	if (isset($anchor)) {
		$url  .= '#' . $anchor;
	}
	if ($domain) {
		$url   =  (is_ssl() ? 'https://' : 'http://') . $domain . $url;
	}
	if ($redirect) // 直接跳转URL
		redirect($url);
	else
		return $url;
}

/**
 * URL重定向
 * @param string $url 重定向的URL地址
 * @param integer $time 重定向的等待时间（秒）
 * @param string $msg 重定向前的提示信息
 * @return void
 */
function redirect($url, $time = 0, $msg = '')
{
	//多行URL地址支持
	$url        = str_replace(array("\n", "\r"), '', $url);
	if (empty($msg))
		$msg    = "系统将在{$time}秒之后自动跳转到{$url}！";
	if (!headers_sent()) {
		// redirect
		if (0 === $time) {
			header('Location: ' . $url);
		} else {
			header("refresh:{$time};url={$url}");
			echo ($msg);
		}
		exit();
	} else {
		$str    = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
		if ($time != 0)
			$str .= $msg;
		exit($str);
	}
}

/**
 * 判断是否SSL协议
 * @return boolean 
 */
function is_ssl()
{
	if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
		return true;
	} elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
		return true;
	}
	return false;
}

//获取当前网址
function gethost()
{
	if ((int)$_SERVER['SERVER_PORT'] === 80) {
		$host = (is_ssl() ? 'https://' : 'http://') . $_SERVER['SERVER_NAME'];
	} else {
		$host = (is_ssl() ? 'https://' : 'http://') . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'];
	}
	return $host;
}
function getweburl($url)
{
	$url   =  gethost() . $url;
	return $url;
}
/**
 * 发送HTTP状态
 * @param integer $code 状态码
 * @return void
 */
function send_http_status($code)
{
	static $_status = array(
		// Informational 1xx
		100 => 'Continue',
		101 => 'Switching Protocols',
		// Success 2xx
		200 => 'OK',
		201 => 'Created',
		202 => 'Accepted',
		203 => 'Non-Authoritative Information',
		204 => 'No Content',
		205 => 'Reset Content',
		206 => 'Partial Content',
		// Redirection 3xx
		300 => 'Multiple Choices',
		301 => 'Moved Permanently',
		302 => 'Moved Temporarily ', // 1.1
		303 => 'See Other',
		304 => 'Not Modified',
		305 => 'Use Proxy',
		// 306 is deprecated but reserved
		307 => 'Temporary Redirect',
		// Client Error 4xx
		400 => 'Bad Request',
		401 => 'Unauthorized',
		402 => 'Payment Required',
		403 => 'Forbidden',
		404 => 'Not Found',
		405 => 'Method Not Allowed',
		406 => 'Not Acceptable',
		407 => 'Proxy Authentication Required',
		408 => 'Request Timeout',
		409 => 'Conflict',
		410 => 'Gone',
		411 => 'Length Required',
		412 => 'Precondition Failed',
		413 => 'Request Entity Too Large',
		414 => 'Request-URI Too Long',
		415 => 'Unsupported Media Type',
		416 => 'Requested Range Not Satisfiable',
		417 => 'Expectation Failed',
		// Server Error 5xx
		500 => 'Internal Server Error',
		501 => 'Not Implemented',
		502 => 'Bad Gateway',
		503 => 'Service Unavailable',
		504 => 'Gateway Timeout',
		505 => 'HTTP Version Not Supported',
		509 => 'Bandwidth Limit Exceeded'
	);
	if (isset($_status[$code])) {
		header('HTTP/1.1 ' . $code . ' ' . $_status[$code]);
		// 确保FastCGI模式下正常
		header('Status:' . $code . ' ' . $_status[$code]);
	}
}




function messagebox($msg, $reurl = 'back', $type = "info", $target = "", $msg2 = '', $time = 3000)
{
	switch ($type) {
		case "error":
			$strico = "ban";
			$strcss = "danger";
			break;
		case "success":
			$strico = "check";
			$strcss = $type;
			break;
		case "warn":
			$strico = "warning";
			$strcss = "warning";
			break;
		case "info":
			$strico = "info";
			$strcss = "info";
			break;
		default:
			$strico = $type;
			$strcss = $type;
	}
	if (defined('IN_YUNYECMSAdmin')) {
		require YUNYECMS_CORE . 'admin/tpl/message.tpl.php';
	} else {
		if (!defined('LAN')) {
			define('LAN', 'cn');
		}
		require YUNYECMS_CORE . 'app/inc/message.tpl.php';
	}
	exit;
}
function arrnull($array)
{
	if (count($array) > 0) {
		return false;
	} else {
		return true;
	}
}

function ToChinaseNum($num)
{
	$char = array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
	$dw = array("", "十", "百", "千", "万", "亿", "兆");
	$retval = "";
	$proZero = false;
	for ($i = 0; $i < strlen($num); $i++) {
		if ($i > 0) $temp = (int)(($num % pow(10, $i + 1)) / pow(10, $i));
		else $temp = (int)($num % pow(10, 1));
		if ($proZero == true && $temp == 0) continue;
		if ($temp == 0) $proZero = true;
		else $proZero = false;
		if ($proZero) {
			if ($retval == "") continue;
			$retval = $char[$temp] . $retval;
		} else $retval = $char[$temp] . $dw[$i] . $retval;
	}
	if ($retval == "一十") $retval = "十";
	return $retval;
}
/**
 * 程序执行时间
 *
 * @return	int	单位ms
 */
function execute_time()
{
	$microtime = microtime(true);
	return round($microtime - YUNYECMS_START_TIME, 3);
}

function  udecode($jsonstr)
{
	return json_decode($jsonstr, true);
}

function usetcookie($name, $value, $isadmin = 0, $expire = COOKIE_EXPIRE)
{
	$cookiepre = empty($isadmin) ? COOKIE_PRE : COOKIE_ADMINPRE;
	return setcookie($cookiepre . $name, $value, $expire, COOKIE_PATH, COOKIE_DOMAIN);
}

function ugetcookie($name, $isadmin = 0)
{
	$cookiename = empty($isadmin) ? COOKIE_PRE . $name : COOKIE_ADMINPRE . $name;
	if (!empty($_COOKIE[$cookiename])) {
		$cookie_value = $_COOKIE[$cookiename];
		if (in_array($name, array('userid', 'siteid', 'groupid', 'roleid'))) {
			if (!is_numeric($cookie_value)) {
				return false;
			}
		} elseif (in_array($name, array('username', 'nickname', 'admin_username', 'sys_lang'))) {
			$cookie_value = usafestr($cookie_value);
		}
		return $cookie_value;
	} else {
		return false;
	}
}

//文件处理函数
function fwritetext($filepath, $string)
{
	$fp = fopen($filepath, "w") or die("Unable to open file!");
	$ret = @fwrite($fp, $string);
	@fclose($fp);
	@chmod($filepath, 0777);
	return $ret;
}

function dir_list($path, $exts = '', $list = array())
{
	$path = dir_path($path);
	$files = glob($path . '*');
	foreach ($files as $v) {
		$fileext = fileext($v);
		if (!$exts || preg_match("/\.($exts)/i", $v)) {
			$list[] = $v;
			if (is_dir($v)) {
				$list = dir_list($v, $exts, $list);
			}
		}
	}
	return $list;
}
//遍历目录所有文件
function getDir($path)
{
	if (!file_exists($path)) {
		return false;
	}
	$handle = opendir($path);
	$fileItem = array();
	if ($handle) {
		while (($file = readdir($handle)) !== false) {
			$newPath = $path . DIRECTORY_SEPARATOR . $file;
			if (is_dir($newPath) && $file != '.' && $file != '..') {
				$fileItem = array_merge($fileItem, getDir($newPath));
			} else if (is_file($newPath)) {
				$fileItem[] = $newPath;
			}
		}
	}
	@closedir($handle);
	return $fileItem;
}

function fileext($filename)
{
	return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}
function dir_path($path)
{
	$path = str_replace('\\', '/', $path);
	if (substr($path, -1) != '/') $path = $path . '/';
	return $path;
}

function dir_delete($dir)
{
	$dir = dir_path($dir);
	if (!is_dir($dir)) return FALSE;
	$list = glob($dir . '*');
	foreach ((array)$list as $v) {
		is_dir($v) ? dir_delete($v) : @unlink($v);
	}
	return @rmdir($dir);
}

function file_delete($path, $real_path = 0)
{
	if (!$real_path) $path = '.' . $path;
	$path = usafepic($path);
	$dir = dirname($path);
	if (file_exists($path)) {
		@unlink($path);
		$fileempty = glob($dir . '/*');
		if (empty($fileempty)) {
			return @rmdir($dir);
		}
	} else {
		return FALSE;
	}
}

function dir_create($path, $mode = 0777)
{
	if (is_dir($path)) return TRUE;
	$ftp_enable = 0;
	$path = dir_path($path);
	$temp = explode('/', $path);
	$cur_dir = '';
	$max = count($temp) - 1;
	for ($i = 0; $i < $max; $i++) {
		$cur_dir .= $temp[$i] . '/';
		if (@is_dir($cur_dir)) continue;
		@mkdir($cur_dir, 0777, true);
		@chmod($cur_dir, 0777);
	}
	return is_dir($path);
}

function dir_copy($fromdir, $todir)
{
	$fromdir = dir_path($fromdir);
	$todir = dir_path($todir);
	if (!is_dir($fromdir)) return FALSE;
	if (!is_dir($todir)) dir_create($todir);
	$list = glob($fromdir . '*');
	if (!empty($list)) {
		foreach ($list as $v) {
			$path = $todir . basename($v);
			if (is_dir($v)) {
				dir_copy($v, $path);
			} else {
				copy($v, $path);
				@chmod($path, 0777);
			}
		}
	}
	return TRUE;
}

function getattachdir($dirpatharr)
{
	$dirs = $_SERVER['DOCUMENT_ROOT'];
	$subarr = array();
	$dirarr = explode('/', $dirpatharr);
	foreach ($dirarr as $value) {
		$dirs .= '/' . $value;
		if (smkdir($dirs)) {
			$subarr[] = $value;
		} else {
			break;
		}
	}
	return implode('/', $subarr);
}

function smkdir($dirname, $ismkindex = 1)
{
	$mkdir = false;
	if (!is_dir($dirname)) {
		if (@mkdir($dirname, 0777)) {
			if ($ismkindex) {
				@fclose(@fopen($dirname . '/index.htm', 'w'));
			}
			$mkdir = true;
		}
	} else {
		$mkdir = true;
	}
	return $mkdir;
}

function GetFileName($fileUrl, $noext = 0)
{
	if (strpos($fileUrl, "\\")) {
		$fileUrl = str_ireplace('\\', '/', $fileUrl);
	}
	$FileNamearr = yexplode('/', $fileUrl);
	$FileName = end($FileNamearr);
	if ($noext) {
		$strlength = strlen($FileName) - strlen(fileext($FileName)) - 1;
		$FileName = substr($FileName, 0, $strlength);
	}
	return $FileName;
}
//去除文件扩展名
function RemoveFileext($FileName)
{
	$strlength = strlen($FileName) - strlen(fileext($FileName)) - 1;
	$FileName = substr($FileName, 0, $strlength);
	return $FileName;
}
function ToBackslash($string)
{
	if (strpos($string, "\\") !== false) {
		$string = str_ireplace('\\', '/', $string);
	}
	return $string;
}
//获取当前模板目录默认语言风格下模板文件列表
function gettplfile($db)
{
	$tpl_dir = YUNYECMS_ROOT . "theme/";
	$cur_theme = $db->find("select `theme` from `#yunyecms_config` where `theme`<>''");
	$cur_landir = $db->getfield('landir', 1, 'lang', 'isdefault');
	$retfile = array();
	if ($cur_theme && $cur_landir) {
		$tpl_dir = YUNYECMS_ROOT . "theme/{$cur_theme["theme"]}/$cur_landir";
		chdir($tpl_dir);
		$filearr = glob('content_*.html');
		foreach ($filearr as $key => $var) {
			if (stripos($var, 'closesite')) {
				unset($filearr[$key]);
			} else {
				$filestr = RemoveFileext($filearr[$key]);
				$retfile[] = str_ireplace('content_', '', $filestr);
			}
		}
		if ($retfile) {
			return $retfile;
		} else {
			return false;
		}
	} else {
		return false;
	}
}



/**
 * 更新模板缓存
 *
 * @param $fileUrl	模板原文件路径
 * @param $localpath	编译完成后，写入文件名
 * @param $md5	编译完成后，写入文件名
 * @return $savefile 长度
 */ //文件上传函数
function Get_RemoteFile($fileUrl, $localpath, $md5 = '')
{
	$remoteFileName = GetFileName($fileUrl);
	$savefile = $localpath . $remoteFileName; // 保存目录
	if (!is_dir(dirname($savefile)))  dir_create(dirname($savefile));
	if (!file_get_contents($fileUrl, 0, null, 0, 1)) {
		return false;
	}
	//$file_nr=curl_post($fileUrl); 
	$file_nr = file_get_contents($fileUrl);
	if ($file_nr) {
		$strlen = @file_put_contents($savefile, $file_nr);
		chmod($saveDir, 0777);
		if ($strlen == false) return false;
	} else {
		return false;
	}
	if (!is_file($savefile)) {
		return false;
	}
	if ($md5) {
		if ($md5 != md5_file($savefile)) return false;
	}
	return $savefile;
}


function savelocalfile($filearr, $savepath = '', $thumb = '', $arrext = '',  $save_rule = '', $objfile = '', $havethumb = 1)
{
	if (empty($filearr) || empty($savepath)) {
		return array('error' => '请选择要上传的文件！');
	}
	$patharr = $deault = array();
	//debug 传入参数
	$filename = strip_tags($filearr['name']);
	$tmpname = str_replace('\\', '\\\\', $filearr['tmp_name']);
	//debug 文件后缀
	$ext = fileext($filename) == 'gif' ? 'jpg' : fileext($filename);
	$patharr['name'] = addslashes($filename);
	$patharr['type'] = $ext;
	$patharr['size'] = $filearr['size'];
	if ($patharr['size'] / 1024 > 20480) {
		return array('error' => '您上传的图片大小是：' . round($patharr['size'] / 1024) . '文件不超过20480KB');
	}
	//debug 文件名
	if ($objfile) {
		$newfilename = $objfile;
		$isimage = 0;
		$patharr['file'] = $patharr['thumb'] = $objfile;
	} else {
		if (empty($arrext)) $arrext = array('jpg', 'jpeg', 'gif', 'png', 'rar', 'doc', 'pdf');
		if (in_array($ext, $arrext)) {
			/* $imageinfo = @getimagesize($tmpname);
			list($width, $height, $type) = !empty($imageinfo) ? $imageinfo : array('', '', '');
			if(!in_array($type, array(1,2,3,6,13))) {
				return $deault;
			}*/
			$isimage = 1;
		} else {
			//$isimage = 0;
			//$ext = 'attach';
			return array('error' => '您上传的文件类型不对！');
		}
		//文件名称
		if (empty($save_rule)) {
			//$filemain = date('YmdHis').random(4);
			$filemain = str_replace("." . $ext, '', $filename);
		} else {
			$filemain = $save_rule;
		}
		//得到存储目录
		$dirpath = getattachdir($savepath);
		$patharr['filename'] = $filemain . '.' . $ext;
		$patharr['file'] = $dirpath . '/' . $filemain . '.' . $ext;
		$patharr['path'] = $dirpath . '/';
		//上传
		$newfilename = $patharr['file'];
	}
	if (@copy($tmpname, $newfilename)) {
	} elseif ((function_exists('move_uploaded_file') && @move_uploaded_file($tmpname, $newfilename))) {
	} elseif (@rename($tmpname, $newfilename)) {
	} else {
		return $deault;
	}
	@unlink($tmpname);
	//debug 缩略图水印
	/*	if($isimage && empty($objfile)) {
		//缩略图
		if($havethumb == 1) {
			// 如果$thumb是字符串			
			if(is_array($thumb)){
				$arrThumbWidth = explode(',',$thumb['width']);
				$arrThumbHeight = explode(',',$thumb['height']);
				foreach($arrThumbWidth as $key => $item){
					 $patharr['img_'.$item.'_'.$arrThumbHeight[$key]] = makethumb($patharr['file'],array($item,$arrThumbHeight[$key]));
				}
			}
		}
	}*/
	return $patharr;
}


//文件处理函数end
//获取指定内容中的图片路径
function  getcontentimg($content)
{
	$pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
	//$pattern2="/<[img|IMG].+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i"; 
	preg_match_all($pattern, $content, $match);
	return $match[1];
}

function udate($datetime, $flag = 0)
{
	switch ($flag) {
		case 0:
			return date("Y-m-d H:i:s", $datetime);
			break;
		case 1:
			return date("Y-m-d", $datetime);
			break;
		default:
			return date("Y-m-d H:i:s", $datetime);
	}
}



function exportExcel($expTitle, $expCellName, $expTableData)
{
	//$xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
	$xlsTitle = $expTitle;
	$fileName = date('_YmdHis'); //or $xlsTitle 文件名称可根据自己情况设定
	$fileName = $xlsTitle . date('_YmdHis'); //or $xlsTitle 文件名称可根据自己情况设定
	$cellNum = count($expCellName);
	$dataNum = count($expTableData);
	include_once YUNYECMS_CORE . 'extend' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'PHPExcel.php';
	$objPHPExcel = new PHPExcel();
	$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
	//自动换行
	$objPHPExcel->getActiveSheet()->getStyle('A:M')->getAlignment()->setWrapText(true);

	$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
	$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
	$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
	$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
	$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
	$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(30);
	$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
	$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
	$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(15);
	$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(15);
	//$objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
	// $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));  
	for ($i = 0; $i < $cellNum; $i++) {
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $expCellName[$i][1]);
	}
	// Miscellaneous glyphs, UTF-8   
	for ($i = 0; $i < $dataNum; $i++) {
		for ($j = 0; $j < $cellNum; $j++) {
			$objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 2), $expTableData[$i][$expCellName[$j][0]]);
		}
	}
	header('pragma:public');
	header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
	header("Content-Disposition:attachment;filename=$fileName.xls"); //attachment新窗口打印inline本窗口打印
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	$objWriter->save('php://output');
	exit;
}

function readexcel($filename, $encode = 'utf-8')
{
	include_once YUNYECMS_CORE . 'extend' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'PHPExcel.php';
	$objReader = PHPExcel_IOFactory::createReader('Excel5');
	$objReader->setReadDataOnly(true);
	$objPHPExcel = $objReader->load($filename);
	$objWorksheet = $objPHPExcel->getActiveSheet();
	$highestRow = $objWorksheet->getHighestRow();
	$highestColumn = $objWorksheet->getHighestColumn();
	$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
	$excelData = array();
	for ($row = 1; $row <= $highestRow; $row++) {
		for ($col = 0; $col < $highestColumnIndex; $col++) {
			$excelData[$row][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
		}
	}
	return $excelData;
}

//时间处理函数
function yytime($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 . '小时前 ' . $htime;
	} elseif ($time < 60 * 60 * 24 * 3) {
		$d = floor($time / (60 * 60 * 24));
		if ($d == 1)
			$str = '昨天 ' . $rtime;
		else
			$str = '前天 ' . $rtime;
	} else {
		$str = $rtime;
	}
	return $str;
}

//返回两个数组的交集
function yarray_intersect($subcat, $catpwerid)
{
	$newcat = array();
	foreach ($subcat as $k => $v) {
		if (!empty($catpwerid)) {
			foreach ($catpwerid as $kp => $vp) {
				if ($subcat[$k] == $catpwerid[$kp]) {
					$newcat[] = $subcat[$k];
				}
			}
		}
	}
	return $newcat;
}


/* 检查是否是微信浏览器访问 */
function is_wechat_browser()
{
	$user_agent = $_SERVER['HTTP_USER_AGENT'];
	if (strpos($user_agent, 'MicroMessenger') === false) {
		//echo '非微信浏览器禁止浏览';
		return false;
	} else {
		//echo '微信浏览器，允许访问';
		//preg_match('/.*?(MicroMessenger\/([0-9.]+))\s*/', $user_agent, $matches);
		//echo '<br>你的微信版本号为:'.$matches[2];
		return true;
	}
}


function getToday()
{
	$curtime = time();
	$today_start = strtotime(date('Y-m-d', $curtime));
	$today_end = strtotime(date('Y-m-d', $curtime)) + 86399;
	$rearr['start'] = $today_start;
	$rearr['end'] = $today_end;
	return $rearr;
}

function getYesterday()
{
	$beginYesterday = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
	$endYesterday = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
	$rearr['start'] = $beginYesterday;
	$rearr['end'] = $endYesterday;
	return $rearr;
}

function getThisweek()
{
	$curtime = time();
	$w = date("w", $curtime); //获取当前周的第几天 周日是 0 周一 到周六是 1 -6
	$d = $w ? $w - 1 : 6; //如果是周日 -6天
	$start_week = strtotime("" . date("Y-m-d") . " -" . $d . " days"); //本周开始时间
	$end_week = strtotime("" . date("Y-m-d", $start_week) . " +7 days") - 1; //本周结束时间
	$rearr['start'] = $start_week;
	$rearr['end'] = $end_week;
	return $rearr;
}

function getLastweek()
{
	$lastweek_start = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 7, date('Y'));
	$lastweek_end = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7 - 7, date('Y'));
	$rearr['start'] = $lastweek_start;
	$rearr['end'] = $lastweek_end;
	return $rearr;
}


function getThismonth()
{
	$beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
	$endThismonth = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
	$rearr['start'] = $beginThismonth;
	$rearr['end'] = $endThismonth;
	return $rearr;
}


function getLastmonth()
{
	$beginLastmonth = mktime(0, 0, 0, date("m") - 1, 1, date("Y"));
	$endLastmonth = mktime(23, 59, 59, date("m"), 0, date("Y"));
	$rearr['start'] = $beginLastmonth;
	$rearr['end'] = $endLastmonth;
	return $rearr;
}


function yexplode($separator = ',', $string)
{
	if (strpos($string, $separator) !== false) {
		return explode($separator, $string);
	} else {
		return $string;
	}
}

//处理网站语言包
function dolang($lang, $cfg)
{
	if (empty($lang["tel"])) $lang["tel"] = $cfg["tel"];
	if (empty($lang["mobile"])) $lang["mobile"] = $cfg["mobile"];
	if (empty($lang["qq"])) $lang["qq"] = $cfg["qq"];
	if (empty($lang["sitename"])) $lang["sitename"] = $cfg["sitename"];
	if (empty($lang["mail"])) $lang["mail"] = $cfg["mail"];
	if (!empty($lang['copyright'])) $lang['copyright'] = uhtmlspecialchars_decode($lang['copyright']);
	if (!empty($lang['tel'])) $lang['tel'] = yexplode(',', $lang['tel']);
	if (!empty($lang['mobile'])) $lang['mobile'] = yexplode(',', $lang['mobile']);
	if (!empty($lang['qq'])) $lang['qq'] = yexplode(',', $lang['qq']);
	if (!empty($lang['mail'])) $lang['mail'] = yexplode(',', $lang['mail']);
	$lang['weibo'] = $cfg['weibo'];
	$lang['icon'] = $cfg['icon'];
	$lang['theme'] = $cfg['theme'];
	return $lang;
}



function getSiteUrl()
{
	$currentdir = $_SERVER['REQUEST_URI'] ? $_SERVER['REQUEST_URI'] : ($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
	$currentdir = str_ireplace('\\', '/', $currentdir);
	return substr($currentdir, 0, strrpos($currentdir, '/') + 1);
}

function getserver_domain()
{
	$client_domaindomain = $_SERVER['HTTP_HOST'];
	if (stripos($_SERVER['HTTP_HOST'], ":")) {
		$client_domaindomain = substr($client_domaindomain, 0, strrpos($client_domaindomain, ':'));
	}
	return $client_domaindomain;
}

function getsofttype($type)
{
	switch ($type) {
		case 1:
			$returnstr = "Release";
			break;
		case 2:
			$returnstr = "Build ";
			break;
		default:
			$returnstr = "Release";
	}
	return $returnstr;
}

function getsofttime($type, $version_time, $build_time)
{
	switch ($type) {
		case 1:
			$returnstr = empty($version_time) ? "" : date("Y-m-d", $version_time);
			break;
		case 2:
			$returnstr = empty($build_time) ? "" : date("Y-m-d", $build_time);
			break;
		default:
			$returnstr = empty($version_time) ? "" : date("Y-m-d", $version_time);
	}
	return $returnstr;
}
function getsoftname($type, $version, $version_time, $build_time)
{
	switch ($type) {
		case 1:
			$returnstr = "Yunyecms_$version" . " ( " . date("Y-m-d", $version_time) . ")";
			break;
		case 2:
			$returnstr = empty($build_time) ? "" : "Yunyecms_{$version}_Build" . date("md", $build_time);
			break;
		default:
			$returnstr = "Yunyecms_$version" . " ( " . date("Y-m-d", $version_time) . ")";
	}
	return $returnstr;
}
function getversion($type, $version, $version_time, $build_time)
{
	switch ($type) {
		case 1:
			$returnstr = "$version" . " ( " . date("Y-m-d", $version_time) . ")";
			break;
		case 2:
			$returnstr = empty($build_time) ? "{$version}" : "{$version} (Build_" . date("md", $build_time) . ")";
			break;
		default:
			$returnstr = "$version" . " ( " . date("Y-m-d", $version_time) . ")";
	}
	return $returnstr;
}
//二维数组根据某个键排序
function sortArr($arrays, $sort_key, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC)
{
	$key_arrays = array();
	if (is_array($arrays)) {
		foreach ($arrays as $array) {
			if (is_array($array)) {
				$key_arrays[] = $array[$sort_key];
			} else {
				return false;
			}
		}
	} else {
		return false;
	}
	array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
	return $arrays;
}
//二维数组多键值排序
//$data表示二维数组，结构比如说从数据读取出来的多行表结构
//'date'表示每行里面的一个字段，通过这个字段排序,然后通过'time'字段排序
//SORT_DESC,SORT_ASC分别对应'date'，'time'两个字段的排序方式
//效果类似于数据库中order by data desc,time asc。
function my_sort($arrays, $sort_key, $sort_key1, $sort_order = SORT_ASC, $sort_order1 = SORT_DESC)
{
	$key_arrays = $key_arrays1 = array();
	if (is_array($arrays)) {
		foreach ($arrays as $array) {
			if (is_array($array)) {
				$key_arrays[] = $array[$sort_key];
				$key_arrays1[] = $array[$sort_key1];
			} else {
				return false;
			}
		}
	} else {
		return false;
	}
	array_multisort($key_arrays, $sort_order, $key_arrays1, $sort_order1, $arrays);
	return $arrays;
}
//图片处理函数
function dopic($pic)
{
	if (strlen(RD) > 0 && !empty($pic)) {
		if (stripos($pic, RD) === FALSE) $pic = RD . $pic;
	}
	return $pic;
}
//图片处理逆向函数
function revpic($pic)
{
	if (strlen(RD) > 0 && !empty($pic)) {
		if (stripos($pic, RD) >= 0 || stripos($pic, 'uploads') >= 0) $pic = str_ireplace(RD, '', $pic);
	}
	return uhtmlspecialchars($pic);
}

//内容图片处理函数
function doimgs($content)
{
	$content = uhtmlspecialchars_decode($content);
	if (strlen(RD) > 0) {
		$ct_content_img = getcontentimg($content);
		if (!empty($ct_content_img)) $ct_content_img = array_unique($ct_content_img);
		foreach ($ct_content_img as $key => $var) {
			if (stripos($var, "http") === false && stripos($var, RD) === false && !empty($var)) {
				$content = str_ireplace($var, RD . $var, $content);
			}
		}
	}
	return $content;
}

//内容图片处理函数
function remoteimgs($content, $url = "http://www.yunyecms.com")
{
	$content = uhtmlspecialchars_decode($content);
	if (strlen($url) > 0) {
		$ct_content_img = getcontentimg($content);
		foreach ($ct_content_img as $key => $var) {
			if (stripos($var, "http") === false && stripos($var, $url) === false && !empty($var)) {
				$content = str_ireplace($var, $url . $var, $content);
			}
		}
	}
	return $content;
}

//内容图片处理逆向函数 
function revimgs($content)
{
	if (strlen(RD) > 0) {
		$ct_content_img = getcontentimg($content);
		foreach ($ct_content_img as $key => $var) {
			if ((stripos($var, "http") >= 0 || stripos($var, RD) >= 0) && !empty($var)) {
				$content = str_ireplace(RD, '', $content);
			}
		}
	}
	return uhtmlspecialchars($content);
}


//将数字版本号格式化
function formatver($version)
{
	if (empty($version)) return false;
	$bigver = floor($version);
	$subver = $version - $bigver;
	$subver = $subver * 100;
	$numarr = str_split($subver);
	$subver_2 = $numarr[count($numarr) - 1];
	$subver_1 = intval($subver / 10);
	if (intval($subver_2) > 0) {
		$varsion_name = "V" . $bigver . "." . $subver_1 . "." . $subver_2;
	} else {
		$varsion_name = "V" . $bigver . "." . $subver_1;
	}
	return $varsion_name;
}

function  get_curver()
{
	$strsql = "select * from `#yunyecms_version`  where status=1 order by version_num desc,id desc limit 0,1";
	$ver = getone($strsql);
	if ($ver) {
		return $ver;
	} else {
		return false;
	}
}

// 说明：获取 _SERVER['REQUEST_URI'] 值的通用解决方案
function request_uri()
{
	if (isset($_SERVER['REQUEST_URI'])) {
		$uri = $_SERVER['REQUEST_URI'];
	} else {
		if (isset($_SERVER['argv'])) {
			$uri = $_SERVER['PHP_SELF'] . '?' . $_SERVER['argv'][0];
		} else {
			$uri = $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
		}
	}
	return $uri;
}

//url安全检测
function checkurl()
{
	$URI = request_uri();
	$REFERER = $_SERVER['HTTP_REFERER'];
	$condition_uri = stripos($URI, "script") !== false || stripos($URI, "iframe") !== false || stripos($URI, "alert") !== false || stripos($URI, "XSS") !== false || stripos($URI, "cookie") !== false || stripos($URI, "eval") !== false || stripos($URI, "onmouse") !== false;
	$condition_REFERER = stripos($REFERER, "script") !== false || stripos($REFERER, "iframe") !== false || stripos($REFERER, "alert") !== false || stripos($REFERER, "XSS") !== false || stripos($REFERER, "cookie") !== false || stripos($REFERER, "eval") !== false || stripos($REFERER, "onmouse") !== false;
	if ($condition_uri || $condition_REFERER) {
		return false;
	} else {
		return true;
	}
}

//参数检测
function check_parameter($para)
{
	$allow_para = array('g', 'm', 'c', 'a', 'orderid', 'catid', 'id');
	foreach ($para as $key => $var) {
		$para_name = strtolower($key);
		$para_value = strtolower($var);
		if (!in_array($para_name, $allow_para)) {
			redirect(ROOT . '404.html');
		}
		if (stripos($para_name, ',') !== false || stripos($para_name, '.') !== false || stripos($para_value, ',') !== false || stripos($para_value, '.') !== false) {
			redirect(ROOT . '404.html');
		}
		if ($para_name == "id" || $para_name == "catid" || $para_name == "orderid") {
			if (!is_numeric($para_value)) {
				redirect(ROOT . '404.html');
			}
		}
	}
}
