<?php

/*
  PHP version 5
  Copyright (c) 2002-2018 ECISP.CN、EarcLink.COM
  警告：这不是一个免费的软件，请在许可范围内使用，请尊重知识产权，侵权必究，举报有奖
  作者：黄祥云 E-mail:6326420@qq.com  QQ:6326420 TEL:18665655030
  ESPCMS官网介绍：http://www.ecisp.cn	企业建站：http://www.earclink.cn
 */

use application\ESPCMS_Core;

function espcms_out($str) {
	if (is_array($str)) {
		print_r($str);
	} else {
		echo $str;
	}
}

function espcms_magic_quotes() {
	if (get_magic_quotes_gpc()) {
		$_GET = stripslashes_deep($_GET);
		$_POST = stripslashes_deep($_POST);
		$_COOKIE = stripslashes_deep($_COOKIE);
	}
	$_GET = add_magic_quotes($_GET);
	$_POST = add_magic_quotes($_POST);
	$_COOKIE = add_magic_quotes($_COOKIE);
	$_SERVER = add_magic_quotes($_SERVER);
	$_REQUEST = array_merge($_GET, $_POST);
}

function stripslashes_deep($value) {
	if (is_array($value)) {
		$value = array_map('stripslashes_deep', $value);
	} elseif (is_object($value)) {
		$vars = get_object_vars($value);
		foreach ($vars as $key => $data) {
			$value->{$key} = stripslashes_deep($data);
		}
	} elseif (is_string($value)) {
		$value = stripslashes($value);
	}
	return $value;
}

function add_magic_quotes($array) {
	foreach ((array) $array as $k => $v) {
		if (is_array($v)) {
			$array[$k] = add_magic_quotes($v);
		} else {
			$array[$k] = addslashes($v);
		}
	}
	return $array;
}

function espcms_action_url($action) {
	if (empty($action)) {
		return false;
	}
	$action_array_ex = explode('/', $action);
	if (!is_array($action_array_ex) || count($action_array_ex) != 2) {
		return false;
	}
	$action_array = array('module' => $action_array_ex[0], 'method' => $action_array_ex[1]);
	return $action_array;
}

function espcms_server_url($type = false) {
	$server_url = false;
	switch ($type) {
		case 'HTTP_REFERER':
			$server_url = $_SERVER['HTTP_REFERER'];
			break;
	}
	return $server_url;
}

function espcms_host($urlkey = null, $ishttp = true) {
	global $espcms_command;
	$http_type = $espcms_command['IS_HTTPS'] == 'https' ? 'https://' : 'http://';
	$pathurl_array = array();
	$pathurl_array['URL'] = $ishttp ? $http_type . $_SERVER['HTTP_HOST'] : $_SERVER['HTTP_HOST'];
	$pathurl_array['WWW_RT'] = $_SERVER['HTTP_HOST'];
	$pathurl_array['AP'] = $ishttp ? $http_type . $_SERVER['HTTP_HOST'] . substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/')) . '/' : $_SERVER['HTTP_HOST'] . substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/')) . '/';
	$pathurl_array['RT'] = str_replace('index.php', '', $_SERVER['PHP_SELF']);
	$pathurl_array['AP_K'] = $ishttp ? $http_type . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] : $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
	$pathurl_array['RT_K'] = $_SERVER['PHP_SELF'];
	if (ESPCMS_WEB_TYPE == 'WAP' && defined('ESPCMS_WEB_TYPE')) {
		return !$urlkey ? $pathurl_array : $pathurl_array[$urlkey];
	} else {
		return !$urlkey ? $pathurl_array : $pathurl_array[$urlkey];
	}
}

function espcms_combine_url($baseURL, $keysArr = array(), $left_str = '?') {
	if (!is_array($keysArr) || count($keysArr) <= 0) {
		return $baseURL;
	}
	$combined = $baseURL . $left_str;
	$valueArr = array();
	foreach ($keysArr as $key => $val) {
		if ($val) {
			$val = ($key == 'app' || $key == 'act') && ACTAPPCODE ? urlencode(espcms_encrypt($val, ESPCMS_ENCRYPT_CODE)) : $val;
			$valueArr[] = "$key=$val";
		}
	}
	$keyStr = implode("&", $valueArr);
	$combined .= ($keyStr);
	return $combined;
}

function espcms_add_self_url($add_url_key = array()) {
	if (!is_array($add_url_key) || count($add_url_key) <= 0) {
		return false;
	}
	$url_self = espcms_host(AP_K);
	$url_slef_key = $_SERVER['QUERY_STRING'];
	$url_key = array();
	if ($url_slef_key) {
		$url_slef_key_array = explode('&', $url_slef_key);
		if (is_array($url_slef_key_array)) {
			foreach ($url_slef_key_array as $value) {
				$url_key_value = explode('=', $value);
				$url_key_value[1] = ($url_key_value[0] == 'app' || $url_key_value[0] == 'act') && ACTAPPCODE ? espcms_decrypt(urldecode($url_key_value[1]), ESPCMS_ENCRYPT_CODE) : $url_key_value[1];
				$url_key[$url_key_value[0]] = $url_key_value[1];
			}
		}
	}
	foreach ($add_url_key as $key => $value) {
		$url_key[$key] = $value;
	}
	$new_url_sel = espcms_combine_url($url_self, $url_key);
	return $new_url_sel;
}

function linkOut($action_key = array()) {
	if (!is_array($action_key)) {
		return false;
	}
	$url = espcms_host('AP_K');
	$link = espcms_combine_url($url, $action_key);
	return $link;
}

function espcms_url_out($action_key = array(), $is_rewrite = false, $lng = false, $type_path = false) {
	global $espcms_command;
	if (!is_array($action_key)) {
		return false;
	}
	$url = $espcms_command['HTTP_PATHTYPE'] && !$type_path ? espcms_host('RT') : espcms_host('AP');
	if (ESPCMS_ISADMIN && defined('ESPCMS_ISADMIN')) {
		$url = str_replace(ESPCMS_ADMIN_DIRNAME . '/', '', $url);
	}
	if (ESPCMS_WEB_LAN && defined('ESPCMS_WEB_LAN')) {
		$lng_code = ESPCMS_WEB_LAN;
	} else {
		$lng_code = ESPCMS_CREAT && defined('ESPCMS_CREAT') ? ESPCMS_CREAT : $lng;
	}
	if ($lng_code) {
		$lan_read = ESPCMS_Core::get_lan_view($lng_code);
		$lan_dirname = $lan_read['ispack'] && $lan_read['packname'] ? $lan_read['packname'] : $lan_read['lng'];
		$creat_html_dir = $espcms_command['FILE_HTMLDIR'] && $espcms_command['IS_HTMLDIR'] ? $espcms_command['FILE_HTMLDIR'] : '';
		$url = str_replace($creat_html_dir . $lan_dirname . '/', '', $url);
		$file_path = $espcms_command['HOME_LNG'] == $lng_code ? '' : $creat_html_dir . $lan_dirname . '/';
		if (ESPCMS_WEB_TYPE == 'WAP' && defined('ESPCMS_WEB_TYPE')) {
			$url = !$is_rewrite ? $url . 'index.php' : $url;
		} else {
			$url = !$is_rewrite ? $url . $file_path . 'index.php' : $url . $file_path;
		}
	}
	if (ESPCMS_ISADMIN && defined('ESPCMS_ISADMIN') && !$lng_code) {
		$url = $url . 'index.php';
	}
	if ($is_rewrite) {
		$action_url = implode('/', $action_key);
		$link = $url . $action_url;
	} else {
		$link = espcms_combine_url($url, $action_key);
	}
	return $link;
}

function espcms_url_html_out($action_key = array(), $lng = false, $end_oblink = true, $is_html_extension = false) {
	global $espcms_command;
	if (ESPCMS_WEB_LAN && defined('ESPCMS_WEB_LAN')) {
		$lng_code = ESPCMS_WEB_LAN;
	} else {
		$lng_code = ESPCMS_CREAT && defined('ESPCMS_CREAT') ? ESPCMS_CREAT : $lng;
	}
	$lan_read = ESPCMS_Core::get_lan_view($lng_code);
	$lan_dirname = $lan_read['ispack'] && $lan_read['packname'] ? $lan_read['packname'] : $lan_read['lng'];
	$url = $espcms_command['HTTP_PATHTYPE'] ? espcms_host('RT') : espcms_host('AP');
	if (ESPCMS_ISADMIN && defined('ESPCMS_ISADMIN')) {
		$url = str_replace(ESPCMS_ADMIN_DIRNAME . '/', '', $url);
	}
	if ($espcms_command['FILE_HTMLDIR'] && $espcms_command['IS_HTMLDIR']) {
		$creat_html_dir = $espcms_command['FILE_HTMLDIR'];
	}
	if (!$espcms_command['IS_ALONELNG']) {
		$lan_path = $espcms_command['HOME_LNG'] == $lng_code ? '' : $lan_dirname . '/';
	} else {
		$lan_path = $lan_dirname . '/';
	}
	$url = str_replace($creat_html_dir . $lan_dirname . '/', '', $url);
	if (is_array($action_key)) {
		$action_url = implode('/', $action_key);
	}
	if (!$is_html_extension) {
		$link = $end_oblink ? $url . $creat_html_dir . $lan_path . $action_url . '/' : $url . $creat_html_dir . $lan_path . $action_url;
	} else {
		$link = $url . $creat_html_dir . $lan_path . $action_url . '.html';
	}
	return $link;
}

function espcms_find_array_key($array = array(), $string = null, $field = null, $refield = null) {
	if (!is_array($array) || count($array) < 1) {
		return false;
	}
	foreach ($array as $key => $value) {
		if ($value[$field] == $string) {
			$rkey = $refield ? $value[$refield] : $key;
		}
	}
	return $rkey;
}

function espcms_array_findkey($array = array(), $field = false) {
	if (!is_array($array) || count($array) < 1) {
		return false;
	}
	$key_array = array();
	foreach ($array as $key => $value) {
		$key_array[] = $value[$field];
	}
	return $key_array;
}

function espcms_array_getvalue($var = array()) {
	if (!is_array($var)) {
		return false;
	}
	$valarray = array();
	foreach ($var as $key => $value) {
		$val = explode(':', $value);
		$valarray[$val[0]] = $val[1];
	}
	return $valarray;
}

function espcms_array_onedim($array = array(), $array_key = false) {
	if (!is_array($array) || count($array) <= 0 || !$array_key) {
		return false;
	}
	$one_array = array();
	foreach ($array as $value) {
		if ($value[$array_key]) {
			$one_array[] = $value[$array_key];
		}
	}
	return is_array($one_array) && count($one_array) ? $one_array : false;
}

function espcms_val_array_key($value = false) {
	if (!$value) {
		return false;
	}
	$value_array = explode(',', $value);
	if (!is_array($value_array)) {
		return false;
	}
	$return_array = array();
	foreach ($value_array as $value_key) {
		$val = explode('-', $value_key);
		if (!$val[0] || !$val[1]) {
			continue;
		}
		$return_array[$val[0]] = $val[1];
	}
	return $return_array;
}

function espcms_array_keytokey($array = array(), $key1 = false, $key2 = false, $key3 = false) {
	if (!is_array($array) || !$key1 || !$key2) {
		return false;
	}
	$return_array = array();
	foreach ($array as $val) {
		$key_name = $val[$key1];
		$key_value = $val[$key2];
		$key_value2 = $val[$key3];
		if ($key_value2) {
			$return_array[$key_name][$key_value] = $key_value2;
		} else {
			$return_array[$key_name] = $key_value;
		}
	}
	return $return_array;
}

function espcms_replace_arraytostr($formatval, $array = array()) {
	if (!is_array($array) || count($array) <= 0) {
		return false;
	}
	foreach ($array as $key => $value) {
		$formatval = str_replace($key, $value, $formatval);
	}
	return $formatval;
}

function token($token_px = false) {
	$token_name = $token_px ? $token_px . '_' . cache_id() : cache_id();
	$token_key = md5(random(12) . random(8, true));
	if (!espcms_set_session($token_name, $token_key)) {
		espcms_set_cookie($token_name, $token_key);
	}
	return array('token_name' => $token_name, 'token_key' => $token_key);
}

function is_token($tokenname, $tokenkey) {
	if (!$tokenkey || !$tokenname) {
		return false;
	}
	if (espcms_get_session($tokenname)) {
		$tokenkey_value = espcms_get_session($tokenname);
		espcms_del_session($tokenname);
	} else {
		$tokenkey_value = $_COOKIE[$tokenname];
		unset($_COOKIE[$tokenname]);
	}
	$return = $tokenkey != $tokenkey_value ? false : true;
	return $return;
}

function cache_id() {
	$url = espcms_host('URL');
	$SELF = $url . request_url();
	$cache_id = md5($SELF);
	return $cache_id;
}

function random_code($len1 = 10, $len2 = 8) {
	$key = md5(random($len1) . random($len2, true));
	return $key;
}

function request_url() {
	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;
}

function random($length = 6, $numeric = false) {
	PHP_VERSION < '4.2.0' && mt_srand((double) microtime() * 1000000);
	if ($numeric) {
		$hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for ($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}

function treelist($text, $fontline = '─') {
	if (empty($text) || $text == 1) {
		return false;
	}
	$result = null;
	for ($i = 0; $i < $text; $i++) {
		$result .= $fontline;
	}
	return $result;
}

function real_remote_ip($iplong = false) {
	$remoteip = getenv('REMOTE_ADDR');
	if (!$remoteip) {
		return $remoteip;
	} elseif (!empty($_SERVER['REMOTE_ADDR'])) {
		$remoteip = $_SERVER['REMOTE_ADDR'];
	} else {
		$remoteip = '0.0.0.0';
	}
	return $iplong ? ip2long($remoteip) : $remoteip;
}

function real_server_ip($iplong = false) {
	$serverip = getenv('SERVER_ADDR');
	if (!$serverip) {
		return $serverip;
	} elseif (!empty($_SERVER['SERVER_ADDR'])) {
		$serverip = $_SERVER['SERVER_ADDR'];
	} else {
		$serverip = '0.0.0.0';
	}
	return $iplong ? ip2long($serverip) : $serverip;
}

function ip_shift($str, $type = 1) {
	if (empty($str)) {
		return 0;
	} else {
		if ($type) {
			$ip = ip2long($str);
		} else {
			$ip = long2ip($str);
		}
	}
	return $ip;
}

function espcms_set_cookie($key, $value, $time = 0) {
	if (empty($key)) {
		return false;
	}
	$cookeitime = $time ? time() + $time : 0;
	$path = ESPCMS_ADMIN_PATH;
	$domain = espcms_host('RT', false);
	return setcookie($key, $value, $cookeitime, '/', '', ($_SERVER['SERVER_PORT'] == 443 ? 1 : 0));
}

function espcms_set_session($key, $value) {
	if (empty($key)) {
		return false;
	}
	$sessionSavePath = ESPCMS_PATH . ESPCMS_DATA_DIR . '\session';
	if (espcms_is_dir_writeable($sessionSavePath)) {
		session_save_path($sessionSavePath);
	}
	if (!espcms_get_auto_start()) {
		@session_start();
	}
	$_SESSION[$key] = $value;
	if ($_SESSION[$key]) {
		return session_id();
	} else {
		return false;
	}
}

function espcms_get_session($key) {
	if (empty($key)) {
		return false;
	}
	$sessionSavePath = ESPCMS_PATH . ESPCMS_DATA_DIR . '\session';
	if (espcms_is_dir_writeable($sessionSavePath)) {
		session_save_path($sessionSavePath);
	}
	if (!espcms_get_auto_start()) {
		@session_start();
	}
	if ($_SESSION[$key]) {
		$value = $_SESSION[$key];
		if (session_id() !== '' && !espcms_get_auto_start()) {
			@session_write_close();
		}
		return $value;
	} else {
		return false;
	}
}

function espcms_get_auto_start() {
	$auto_start = ini_get('session.auto_start');
	if ($auto_start) {
		return true;
	} else {
		return false;
	}
}

function espcms_del_session($key) {
	if (empty($key)) {
		return false;
	}
	$sessionSavePath = ESPCMS_PATH . ESPCMS_DATA_DIR . '\session';
	if (espcms_is_dir_writeable($sessionSavePath)) {
		session_save_path($sessionSavePath);
	}
	if (!espcms_get_auto_start()) {
		@session_start();
	}
	unset($_SESSION[$key]);
	if ($_SESSION[$key]) {
		return true;
	} else {
		return false;
	}
}

function espcms_encrypt($data, $key) {
	if (!$key || !$data) {
		return $data;
	}
	return base64_encode(
		mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, serialize($data), MCRYPT_MODE_CBC, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")
	);
}

function espcms_decrypt($data, $key) {
	if (!$key || !$data) {
		return $data;
	}
	$decode = base64_decode($data);
	$str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $decode, MCRYPT_MODE_CBC, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
	return unserialize($str);
}

function espcms_ismoney($value, $matches = "/^(([0-9]\d{0,20})|0)(\.\d{1,3})?$/i") {
	if (!preg_match($matches, $value)) {
		return false;
	} else {
		return true;
	}
}

function espcms_istime($value, $matches = "/^[\d]{4}\-[\d]{1,2}\-[\d]{1,2} [\d]{1,2}:[\d]{1,2}:[\d]{1,2}$/i") {
	if (!preg_match($matches, $value)) {
		return false;
	} else {
		return true;
	}
}

function espcms_istime_long($value, $matches = "/^[\d]{4}\-[\d]{1,2}\-[\d]{1,2} [\d]{1,2}:[\d]{1,2}$/i") {
	if (!preg_match($matches, $value)) {
		return false;
	} else {
		return true;
	}
}

function espcms_islongfig($value, $matches = "/^[\d]+(,[\d]+)*$/i") {
	if (!preg_match($matches, $value)) {
		return false;
	} else {
		return true;
	}
}

function espcms_isdata($value, $matches = "/^[\d]{4}\-[\d]{1,2}\-[\d]{1,2}$/i") {
	if (!preg_match($matches, $value)) {
		return false;
	} else {
		return true;
	}
}

function espcms_ismatches($value, $matches = "/^[0-9]+$/i") {
	if (!preg_match($matches, $value)) {
		return false;
	} else {
		return true;
	}
}

function espcms_array_ismatches($array, $matches = "/^[0-9]+$/i") {
	if (!is_array($array) || count($array) <= 0) {
		return false;
	}
	foreach ($array as $value) {
		if (!espcms_ismatches($value, $matches)) {
			return false;
		}
	}
	return true;
}

function espcms_isemail($value, $matches = "/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/i") {
	if (!preg_match($matches, $value)) {
		return false;
	} else {
		return true;
	}
}

function espcms_isurl($value, $matches = "/^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+$/i") {
	if (!preg_match($matches, $value)) {
		return false;
	} else {
		return true;
	}
}

function espcms_ismoblie($value, $matches = "/^1[0-9]{10}$/i") {
	if (!preg_match($matches, $value)) {
		return false;
	} else {
		return true;
	}
}

function espcms_isact($value, $matches = "/^[\w]+\/[\w]+\/[\w]+$/i") {
	if (!preg_match($matches, $value)) {
		return false;
	} else {
		return true;
	}
}

function espcms_isip($value, $matches = "/^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/i") {
	if (!preg_match($matches, $value)) {
		return false;
	} else {
		return true;
	}
}

function espcms_timeformat($time, $type = 3, $font = '-', $ddstr = '') {
	if (!$time) {
		return false;
	}
	switch ($type) {
		case 1:
			$format = date('H:i:s', $time);
			break;
		case 2:
			$format = date('Y' . $font . 'm' . $font . 'd', $time);
			break;
		case 3:
			$format = date('Y' . $font . 'm' . $font . 'd H:i:s', $time);
			break;
		case 4:
			$format = date('Y' . $font . 'm' . $font . 'd H:i', $time);
			break;
		case 5:
			$format = date('m' . $font . 'd H:i', $time);
			break;
		case 6:
			$format = date('m' . $font . 'd', $time);
			break;
		case 7:
			$format = date('Y' . $font . 'm', $time);
			break;
		case 8:
			$format = date('y' . $font . 'm' . $font . 'd H:i:s', $time);
			break;
		case 9:
			$format = date('y' . $font . 'm' . $font . 'd H:i', $time);
			break;
		case 10:
			$format = date('m', $time);
			break;
		case 11:
			$format = date('d', $time);
			break;
		case 12:
			$format = date('Y', $time);
			break;
		case 13:
			$format = date($ddstr, $time);
			break;
	}
	return $format;
}

function espcms_gtimeformat($time, $type = 3, $isgmt = true) {
	if (!$time) {
		return false;
	}
	switch ($type) {
		case 1:
			$format = gmdate('H:i:s', $time);
			break;
		case 2:
			$format = gmdate('l d F Y', $time);
			break;
		case 3:
			$format = gmdate("l d F Y H:i:s", $time);
			break;
		case 4:
			$format = gmdate("l d F", $time);
			break;
		case 5:
			$format = gmdate('l', $time);
			break;
		case 6:
			$format = gmdate('d', $time);
			break;
		case 7:
			$format = gmdate('F', $time);
			break;
		case 8:
			$format = gmdate('Y', $time);
			break;
	}
	return $isgmt ? $format . " GMT" : $format;
}

function espcms_format_money($money, $len = 2, $sign = '￥') {
	if (!preg_match("/^(0|[1-9][0-9]{0,9})(\.[0-9]*)?$/i", $money)) {
		return false;
	}
	$len = empty($len) || !espcms_ismatches($len) ? 2 : $len;
	$money = empty($money) ? 0 : round($money, $len);
	$money_array = explode('.', $money);
	$int_money = $money_array[0];
	$decimal = $money_array[1] ? (strlen($money_array[1]) == 1 ? $money_array[1] . '0' : $money_array[1]) : '00';
	$tmp_money = strrev($int_money);
	$strlen = strlen($tmp_money);
	for ($i = 3; $i < $strlen; $i += 3) {
		$format_money .= substr($tmp_money, 0, 3) . ',';
		$tmp_money = substr($tmp_money, 3);
	}
	$format_money .= $tmp_money;
	$format_money = strrev($format_money);
	return $sign . $format_money . '.' . $decimal;
}

function espcms_week($time, $type = 'cn', $weekEm = true) {
	$time = empty($time) ? time() : ((strstr($time, ':') || strstr($time, '-')) ? strtotime($time) : $time);
	if ($type == 'cn') {
		$weekInt = date('w', $time);
		$weekInt_em = $weekEm ? espcms_lan_pack('public_pack-espcms_lable_week_name') : '';
		switch ($weekInt) {
			case 0:
				$weekInt = $weekInt_em . espcms_lan_pack('public_pack-espcms_lable_week_0');
				break;
			case 1:
				$weekInt = $weekInt_em . espcms_lan_pack('public_pack-espcms_lable_week_1');
				break;
			case 2:
				$weekInt = $weekInt_em . espcms_lan_pack('public_pack-espcms_lable_week_2');
				break;
			case 3:
				$weekInt = $weekInt_em . espcms_lan_pack('public_pack-espcms_lable_week_3');
				break;
			case 4:
				$weekInt = $weekInt_em . espcms_lan_pack('public_pack-espcms_lable_week_4');
				break;
			case 5:
				$weekInt = $weekInt_em . espcms_lan_pack('public_pack-espcms_lable_week_5');
				break;
			case 6:
				$weekInt = $weekInt_em . espcms_lan_pack('public_pack-espcms_lable_week_6');
				break;
		}
	} else {
		$weekInt = date('l', $time);
	}
	return $weekInt;
}

function espcms_get_timemessage($timenow = 0) {
	$timenow = empty($timenow) ? time() : $timenow;
	$timekey = date('G', $timenow);
	if ($timekey == 24) {
		$str = espcms_lan_pack('public_pack-espcms_time_cn_morentime');
	} elseif ($timekey >= 0 && $timekey < 5) {
		$str = espcms_lan_pack('public_pack-espcms_time_cn_morentime');
	} elseif ($timekey >= 5 && $timekey < 12) {
		$str = espcms_lan_pack('public_pack-espcms_time_cn_morning');
	} elseif ($timekey >= 12 && $timekey < 14) {
		$str = espcms_lan_pack('public_pack-espcms_time_cn_noon');
	} elseif ($timekey >= 14 && $timekey < 19) {
		$str = espcms_lan_pack('public_pack-espcms_time_cn_pm');
	} elseif ($timekey >= 19 && $timekey < 24) {
		$str = espcms_lan_pack('public_pack-espcms_time_cn_night');
	}
	return $str;
}

function unArrayEmpty($array) {
	if (!is_array($array) || count($array) < 1) {
		return false;
	}
	foreach ($array as $key => $value) {
		if (empty($value)) {
			unset($array[$key]);
		}
	}
	return $array;
}

function unArrayValue($array, $val) {
	if (!is_array($array) || count($array) < 1 || !$val) {
		return false;
	}
	foreach ($array as $key => $value) {
		if ($value == $val) {
			unset($array[$key]);
		}
	}
	return $array;
}

function espcms_guid($opt = true) {
	if (function_exists('com_create_guid')) {
		if ($opt) {
			return com_create_guid();
		} else {
			return trim(com_create_guid(), '{}');
		}
	} else {
		mt_srand((double) microtime() * 10000);
		$charid = strtoupper(md5(uniqid(rand(), true)));
		$hyphen = chr(45);
		$left_curly = $opt ? chr(123) : "";
		$right_curly = $opt ? chr(125) : "";
		$uuid = $left_curly
			. substr($charid, 0, 8) . $hyphen
			. substr($charid, 8, 4) . $hyphen
			. substr($charid, 12, 4) . $hyphen
			. substr($charid, 16, 4) . $hyphen
			. substr($charid, 20, 12)
			. $right_curly;
		return $uuid;
	}
}

function espcms_is_dir_writeable($dir) {
	$writeable = false;
	if (is_dir($dir)) {
		if ($fp = @fopen("$dir/test.txt", 'w')) {
			@fclose($fp);
			@unlink("$dir/test.txt");
			$writeable = true;
		} else {
			$writeable = false;
		}
	}
	return $writeable;
}

function format_size($size, $type = 0) {
	if (!espcms_ismatches($size)) {
		return false;
	}
	if ($size < 1024) {
		$size_BKM = (string) $size . ' B';
	} elseif ($size < (1024 * 1024)) {
		$size_BKM = number_format((double) ($size / 1024), 1) . ' KB';
	} else {
		$size_BKM = number_format((double) ($size / (1024 * 1024)), 1) . ' MB';
	}
	return $size_BKM;
}

function zoom($picfile, $dstW = 200, $dstH = 200, $iszoom = 1, $bgcolor = null) {
	global $espcms_command;
	if (!$picfile) {
		return false;
	}
	if (file_exists(ESPCMS_FILE_ROOT . 'espcms_public/ESPCMS_zoompic.php')) {
		require_once(ESPCMS_FILE_ROOT . 'espcms_public/ESPCMS_zoompic.php');
	} else {
		return false;
	}
	$bgcolor = empty($bgcolor) || !preg_match("/^#[a-zA-Z0-9]{3,6}$/i", $bgcolor) ? '#ffffff' : $bgcolor;
	$photo_dir = ESPCMS_FILE_ROOT . 'espcms_datacache/dbpic/';
	$url = $espcms_command['HTTP_PATHTYPE'] ? espcms_host('RT') : espcms_host('AP');
	if (ESPCMS_WEB_TYPE == 'WAP' && defined('ESPCMS_WEB_TYPE')) {
		$url = str_replace('wap/', '', $url);
	}
	if (ESPCMS_ISADMIN && defined('ESPCMS_ISADMIN')) {
		$url = str_replace(ESPCMS_ADMIN_DIRNAME . '/', '', $url);
	}
	if (ESPCMS_WEB_LAN && defined('ESPCMS_WEB_LAN')) {
		$lng_code = ESPCMS_WEB_LAN;
	} else {
		$lng_code = ESPCMS_CREAT && defined('ESPCMS_CREAT') ? ESPCMS_CREAT : $lng;
	}
	if ($lng_code) {
		$lan_read = ESPCMS_Core::get_lan_view($lng_code);
		$lan_dirname = $lan_read['ispack'] && $lan_read['packname'] ? $lan_read['packname'] : $lan_read['lng'];
		$creat_html_dir = $espcms_command['FILE_HTMLDIR'] && $espcms_command['IS_HTMLDIR'] ? $espcms_command['FILE_HTMLDIR'] : '';
		$url = str_replace($creat_html_dir . $lan_dirname . '/', '', $url);
	}
	$photo_dir_url = $url . 'espcms_datacache/dbpic/';
	$picfile = realpath(ESPCMS_FILE_ROOT . $picfile);
	if (!file_exists($picfile) && !is_file($picfile)) {
		return false;
	}
	$mime = ESPCMS_zoompic::getMimeType($picfile);
	$zoom_pic_path = $photo_dir . $dstW . '_' . $dstH . '_' . md5($picfile . $bgcolor . $iszoom) . '.' . $mime;
	if (is_file($zoom_pic_path)) {
		return $photo_dir_url . basename($zoom_pic_path);
	}
	$zoompic = new ESPCMS_zoompic();
	$newpicname = $zoompic->imagecreat($dstW, $dstH, $bgcolor, $picfile, $zoom_pic_path, $iszoom);
	return $photo_dir_url . basename($newpicname);
}

function espcms_cuthtml($sourcestr, $cutlength = 20, $lenstr = '', $allow = '') {
	$sourcestr = html_entity_decode($sourcestr);
	$sourcestr = preg_replace('/\n|\r/i', '', $sourcestr);
	$sourcestr = trim($sourcestr);
	$sourcestr = strip_tags($sourcestr, $allow);
	$returnstr = espcms_cutstr($sourcestr, $cutlength, $lenstr);
	return $returnstr;
}

function espcms_cutstr($sourcestr, $cutlength = 20, $lenstr = '', $x3 = 0) {
	global $CFG;
	$returnstr = '';
	$cutlength = $cutlength * 2;
	if (preg_match('/<font\s*color=[^>]+/', $sourcestr)) {
		preg_match_all('/(<font\s*color=[^>]+>)([^<]*)(<\/font>)/', $sourcestr, $fonttext);
		$sourcestrold = $sourcestr;
		$sourcestr = $fonttext[2][0];
	}
	if ($cutlength <= 0 || $cutlength >= strlen($sourcestr)) {
		return $sourcestrold ? $sourcestrold : $sourcestr;
	}
	$arr = str_split($sourcestr);
	$len = count($arr);
	$w = 0;
	$cutlength *= 10;
	$x1 = 11;
	$x2 = 16;
	$x3 = $x3 === 0 ? ($CFG['cf3'] > 0 ? $CFG['cf3'] * 10 : $x3 = 21) : $x3 * 10;
	$x4 = $x3;
	for ($i = 0; $i < $len; $i++) {
		if ($w >= $cutlength) {
			$e = $lenstr;
			break;
		}
		$c = ord($arr[$i]);
		if ($c <= 127) {
			$w += $x1;
		} elseif ($c >= 192 && $c <= 223) {
			$w += $x2;
			$i += 1;
		} elseif ($c >= 224 && $c <= 239) {
			$w += $x3;
			$i += 2;
		} elseif ($c >= 240 && $c <= 247) {
			$w += $x4;
			$i += 3;
		}
	}
	$returnstr = implode('', array_slice($arr, 0, $i)) . $e;
	$returnstr = $fonttext[1][0] . $returnstr . $fonttext[3][0];
	return $returnstr;
}

function espcms_text_to_html($txt, $is_preg = true) {
	if (empty($txt)) {
		return false;
	}
	$txt = htmlspecialchars($txt);
	if ($is_preg) {
		$txt = preg_replace("/\r\n/isU", "<br/>", $txt);
		$txt = preg_replace("/\r/isU", "<br/>", $txt);
		$txt = preg_replace("/\n/isU", "<br/>", $txt);
	} else {
		preg_replace("/[\n]{1,}/isU", "<br/>", $txt);
	}
	return $txt;
}

function espcms_find_in_set($val = false, $explode_str = false) {
	if (empty($val) || empty($explode_str)) {
		return false;
	}
	$explode_str_array = explode(',', $explode_str);
	return is_array($explode_str_array) ? in_array($val, $explode_str_array) : false;
}

function espcms_style($title = false, $style = false) {
	if (!$title || !$style) {
		return false;
	}
	$style_font = "<span style=\"$style\">$title</span>";
	return $style_font;
}

function espcms_random($style_str = false) {
	if (!$style_str) {
		return $style_str;
	}
	$time = time();
	$replace_array = array();
	$replace_array['[Y]'] = date('y', $time);
	$replace_array['[M]'] = date('m', $time);
	$replace_array['[D]'] = date('d', $time);
	$replace_array['[H]'] = date('H', $time);
	$replace_array['[I]'] = date('i', $time);
	$replace_array['[S]'] = date('s', $time);
	if (preg_match("/\[R\]|\[R\,([1-4]){1}\]/i", $style_str, $matches)) {
		$rand_len = !empty($matches[1]) && espcms_ismatches($matches[1]) ? $matches[1] : 4;
		switch ($rand_len) {
			case 1:
				$rand_str = mt_rand(1, 9);
				break;
			case 2:
				$rand_str = mt_rand(10, 99);
				break;
			case 3:
				$rand_str = mt_rand(100, 999);
				break;
			case 4:
				$rand_str = mt_rand(1000, 9999);
				break;
		}
		$replace_array[$matches[0]] = $rand_str;
	}
	foreach ($replace_array as $key => $value) {
		$style_str = str_replace($key, $value, $style_str);
	}
	return $style_str;
}

function espcms_h2t($text = false, $type = false) {
	if ($type) {
		$text = stripslashes($text);
	}
	$text = htmlspecialchars_decode($text);
	$text = str_replace("\r\n", "\n", $text);
	$text = str_replace("<br/>\n", "\n", $text);
	$text = str_replace("<br/>", "\n", $text);
	return $text;
}

function espcms_t2h($txt = false, $is_preg = true) {
	$txt = htmlspecialchars($txt);
	if ($is_preg) {
		$txt = preg_replace("/\r\n/isU", "<br/>", $txt);
		$txt = preg_replace("/\r/isU", "<br/>", $txt);
		$txt = preg_replace("/\n/isU", "<br/>", $txt);
	} else {
		preg_replace("/[\n]{1,}/isU", "<br/>", $txt);
	}
	return $txt;
}

function espcms_ip($str, $type = 1) {
	if (empty($str)) {
		return 0;
	} else {
		if ($type == 2) {
			$ip = preg_match("/^[-\d]+$/i", $str) ? long2ip($str) : $str;
		}
		if ($type == 1) {
			$ip = preg_match("/^((25[0-5]|2[0-4]\\d|[1]{1}\\d{1}\\d{1}|[1-9]{1}\\d{1}|\\d{1})($|(?!\\.$)\\.)){4}$/i", $str) ? ip2long($str) : $str;
		}
	}
	return $ip;
}

function espcms_array_to_xml($arr) {
	$xml = "<xml>";
	foreach ($arr as $key => $val) {
		if (is_numeric($val)) {
			$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
		} else {
			$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
		}
	}
	$xml .= "</xml>";
	return $xml;
}

function espcms_curl_get($url) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	$result = curl_exec($ch);
	curl_close($ch);
	return $result;
}

function espcms_curl_post($url = '', $postData = '', $options = array()) {
	if (is_array($postData)) {
		$postData = http_build_query($postData);
	}
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
	curl_setopt($ch, CURLOPT_TIMEOUT, 60);
	if (!empty($options)) {
		curl_setopt_array($ch, $options);
	}
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	$data = curl_exec($ch);
	if (curl_errno($ch)) {
		return false;
	}
	curl_close($ch);
	return $data;
}

function espcms_postdb($url, $data = '') {
	$row = parse_url($url);
	$host = $row['host'];
	$port = $row['port'] ? $row['port'] : 80;
	$file = $row['path'];
	while (list($k, $v) = each($data)) {
		$post .= rawurlencode($k) . "=" . rawurlencode($v) . "&"; //转URL标准码
	}
	$post = substr($post, 0, -1);
	$len = strlen($post);
	$fp = @fsockopen($host, $port, $errno, $errstr, 10);
	if (!$fp) {
		return "$errstr ($errno)\n";
	} else {
		$receive = '';
		$out = "POST $file HTTP/1.1\r\n";
		$out .= "Host: $host\r\n";
		$out .= "Content-type: application/x-www-form-urlencoded\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Content-Length: $len\r\n\r\n";
		$out .= $post;
		fwrite($fp, $out);
		while (!feof($fp)) {
			$receive .= fgets($fp, 128);
		}
		fclose($fp);
		$receive = explode("\r\n\r\n", $receive);
		unset($receive[0]);
		return implode("", $receive);
	}
}

function espcms_sort_terms($a, $b) {
	if (strlen($a) == strlen($b)) {
		return 0;
	}
	return (strlen($a) < strlen($b)) ? 1 : -1;
}

function get_htmlfilename($readfiletemplates, $filetext = array(), $protectval = null) {
	if ($protectval != 'dirname') {
		$readfiletemplates = str_replace('{dirname}', $filetext['dirname'], $readfiletemplates);
	}
	if ($protectval != 'tid') {
		$readfiletemplates = str_replace('{tid}', $filetext['tid'], $readfiletemplates);
	}
	if ($protectval != 'sid') {
		$readfiletemplates = str_replace('{sid}', $filetext['sid'], $readfiletemplates);
	}
	if ($protectval != 'did') {
		$readfiletemplates = str_replace('{did}', $filetext['did'], $readfiletemplates);
	}
	if ($protectval != 'pageid') {
		$readfiletemplates = str_replace('{pageid}', $filetext['pageid'], $readfiletemplates);
	}
	if ($protectval != 'datetime') {
		$readfiletemplates = str_replace('{datetime}', $filetext['datetime'], $readfiletemplates);
	}
	if ($protectval != 'data') {
		$readfiletemplates = str_replace('{data}', $filetext['data'], $readfiletemplates);
	}
	if ($protectval != 'y') {
		$readfiletemplates = str_replace('{y}', $filetext['y'], $readfiletemplates);
	}
	if ($protectval != 'm') {
		$readfiletemplates = str_replace('{m}', $filetext['m'], $readfiletemplates);
	}
	if ($protectval != 'd') {
		$readfiletemplates = str_replace('{d}', $filetext['d'], $readfiletemplates);
	}
	if ($protectval != 's') {
		$readfiletemplates = str_replace('{s}', $filetext['s'], $readfiletemplates);
	}
	return $readfiletemplates;
}

function format_array_replace_string($formatval, $replace_array = array()) {
	if (!is_array($replace_array) || count($replace_array) <= 0) {
		return false;
	}
	foreach ($replace_array as $key => $value) {
		$formatval = str_replace($key, $value, $formatval);
	}
	return $formatval;
}

function espcms_long_array($array = array(), $cut_str = '/', $link_str = ',') {
	if (!$array) {
		return false;
	}
	if (is_array($array) && count($array) > 0) {
		$array = array_unique($array);
		if (count($array) <= 0 || !espcms_array_ismatches($array)) {
			return false;
		}
		$new_long = implode($link_str, $array);
	} else {
		$str_array = explode($cut_str, $array);
		if (is_array($str_array) && count($str_array) > 0) {
			$str_array = array_unique($str_array);
			if (count($str_array) <= 0 || !espcms_array_ismatches($str_array)) {
				return false;
			}
			$new_long = implode($link_str, $str_array);
		} else {
			return false;
		}
	}
	return $new_long;
}

function espcms_screening_key($content = false, $badword = false, $is_filter = false) {
	if (!$badword || !$content) {
		return false;
	}
	if ($is_filter) {
		$badword_array = explode(',', $badword);
		if (!is_array($badword_array)) {
			return false;
		}
		$badword_key = array_combine($badword_array, array_fill(0, count($badword_array), '*'));
		$str = strtr($content, $badword_key);
		return $str;
	} else {
		$badword_array = explode(',', $badword);
		$blacklist = "/" . implode("|", $badword_array) . "/i";
		$reutrn = preg_match($blacklist, $content, $matches);
		return $reutrn;
	}
}

function dump_escape_string($str) {
	global $espcms_link_db;
	return $espcms_link_db->db_real_escape_string($str);
}

function dump_null_string($str) {
	if (!isset($str) || is_null($str)) {
		$str = 'NULL';
	}
	return $str;
}

function remove_comment($var) {
	return (substr($var, 0, 2) != '--');
}

function cutstr($sourcestr, $cutlength = 20, $lenstr = '', $x3 = 0) {
	return espcms_cutstr($sourcestr, $cutlength, $lenstr, $x3);
}

function cuthtml($sourcestr, $cutlength = 20, $lenstr = '', $allow = '') {
	return espcms_cuthtml($sourcestr, $cutlength, $lenstr, $allow);
}

function timeformat($time, $type = 3, $font = '-', $ddstr = '') {
	return espcms_timeformat($time, $type, $font, $ddstr);
}

function espcms_htmlcode($text, $type = 'hc') {
	if (!is_array($text)) {
		$text = $type == 'hc' ? htmlspecialchars($text) : htmlspecialchars_decode($text);
	}
	return $text;
}

function htmlcode($text, $type = 'hc') {
	if (!is_array($text)) {
		$text = $type == 'hc' ? htmlspecialchars($text) : htmlspecialchars_decode($text);
	}
	return $text;
}

function str_replace_limit($search, $replace, $subject, $limit = -1) {
	if (is_array($search)) {
		foreach ($search as $k => $v) {
			$search[$k] = '`' . preg_quote($search[$k], '`') . '`';
		}
	} else {
		$search = '`' . preg_quote($search, '`') . '`';
	}
	return preg_replace($search, $replace, $subject, $limit);
}

function check_str($string) {
	$result = false;
	$var = filter_keyword($string);
	if (!empty($var)) {
		if (!get_magic_quotes_gpc()) {
			$var = addslashes($string);
		}
		$var = str_replace("%", "\%", $var);
		$var = nl2br($var);
		$var = htmlspecialchars($var);
		$result = $var;
	}
	return $result;
}

function filter_keyword($string) {
	$keyword = 'select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|and|union|order|or|into|load_file|outfile';
	$arr = explode('|', $keyword);
	$result = str_ireplace($arr, '', $string);
	return $result;
}

function is_weixin() {
	if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
		return true;
	}
	return false;
}
