global.fun.php
<?php
/*
* 所有公共函数文件
*/
/*
* 序列化
*/
function _serialize($obj){
return base64_encode(gzcompress(serialize($obj)));
}
/*
* 反序列化
*/
function _unserialize($txt){
return unserialize(gzuncompress(base64_decode($txt)));
}
/*
* 获取彩票信息
*/
function getcaipiao(){
// include('/system/libs/model.class.php');
$model = new model();
$file = './memory/ssc.txt';
if (!is_file($file) || time()-filemtime($file) >= 600 ||
file_get_contents($file) == '||' || file_get_contents($file) == '') {
$ssc = json_decode(file_get_contents('http://f.apiplus.cn/cqssc-1.json'), true);
$ssc = $ssc['data'][0];
$ssc_str = $ssc['opentime'].'|'.preg_replace("/^(\d{8})(\d{3})$/", "$1-$2", $ssc['expect']).'|'.str_replace(',', '', $ssc['opencode']).'|'.$ssc['opentimestamp'];
$date = preg_replace("/^(\d{8})(\d{3})$/", "$1-$2", $ssc['expect']);
$haoma = str_replace(',', '', $ssc['opencode']);
$time = $ssc['opentimestamp'];
$result = $model->Query("select id from `@#_shishi_1` where time = '$time'");
if (!$result) {
$model->Query("INSERT INTO `@#_shishi_1`(`qishu`,`haoma`,`time`) VALUES ('$date','$haoma','$time')");
}
file_put_contents($file, $ssc_str, LOCK_EX);
$open_unix_time = $ssc['opentimestamp'] / 1000;
$touch_time = $open_unix_time + floor((time() - $open_unix_time) / 600) * 600;
touch($file, $touch_time);
} else {
$ssc_str = file_get_contents($file);
}
return $ssc_str;
}
//生成日志文件
function putContent($text,$param){
file_put_contents(G_APP_PATH."system\modules\LOG\'".$text.'.txt', $param,FILE_APPEND);
}
//判断变量值是否为空
function isnull($param){
$param = $param!=null?$param:'';
return $param;
}
// 获取文件夹大小
function getDirSize($dir)
{
$handle = opendir($dir);
while (false!==($FolderOrFile = readdir($handle)))
{
if($FolderOrFile != "." && $FolderOrFile != "..")
{
if(is_dir("$dir/$FolderOrFile"))
{
$sizeResult += getDirSize("$dir/$FolderOrFile");
}
else
{
$sizeResult += filesize("$dir/$FolderOrFile");
}
}
}
closedir($handle);
return $sizeResult;
}
function getnull($arr){
if(is_array($arr)){
foreach($arr as $key=>$val){
if(is_array($val)){
$arr[$key] = getnull($val);
}else{
$arr[$key] = is_null($arr[$key])?'':$arr[$key];
$arr[$key] = is_string($arr[$key])?$arr[$key]:"{$arr[$key]}";
}
}
} else {
$arr = $arr == null?'':$arr;
$arr = is_string($arr)?$arr:"$arr";
}
return $arr;
}
/**
* PHP 版本判断
*
**/
function is_php($version = '5.0.0'){
static $_is_php;
$version = (string)$version;
if ( ! isset($_is_php[$version]))
{
$_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE;
}
return $_is_php[$version];
}
//判断用户存在
function isUsername($username,$uid){
// include('/system/libs/model.class.php')
if ($uid) {
$where = "`username` = '$username' and `uid` != '$uid'";
} else {
$where = "`username` = '$username'";
}
$model = new model();
$result = $model -> GetOne("select uid from `@#_member` where $where");
return $result;
}
//判断手机号码是否注册
function isMobile($mobile,$uid){
$model = new model();
$result = $model->GetOne("select uid from `@#_member` where `mobile` = '$mobile' and `uid` != '$uid'");
return $result;
}
/**
* ajax封装类
*
**/
function ajaxRetrun($code,$msg='',$data=array(),$count='',$number='',$is_room='',$title=''){
$result=array(
'code'=>$code,
'msg'=>$msg,
'data'=>$data,
'count'=>$count,
'number'=>$number,
'is_room'=>$is_room,
'title'=>$title
);
$arr = json_encode($result);
echo str_replace('\/', '/', $arr);
exit;
}
function ajaxBack($code,$msg='',$data=array(),$count=''){
$result=array(
'code'=>$code,
'msg'=>$msg,
'data'=>$data,
'count'=>$count
);
$arr = json_encode($result);
echo str_replace('\/', '/', $arr);
exit;
}
function zhaunhuan($arr){
if(is_array($arr)){
foreach($arr as $key=>$val){
if (is_array($val)) {
$arr[$key] = zhaunhuan($val);
} else {
$arr[$key] = urlencode($val);
}
}
}else{
$arr = urlencode($arr);
}
return $arr;
}
function returnAjax($code,$msg,$data=array(),$count=''){
$result=array(
'code'=>$code,
'msg'=>$msg,
'data'=>$data,
'count'=>$count
);
$data = zhaunhuan($result);
$arr = urldecode(json_encode($data));
// $search = "#\\\u([0-9a-f]+)#ie";
// $replace = "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))";
// $ar = preg_replace($search, $replace, $arr);
echo str_replace('\/', '/', $arr);
exit;
}
/**
* 返回经addslashes处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function new_addslashes($string){
if(!is_array($string)) return addslashes($string);
foreach($string as $key => $val) $string[$key] = new_addslashes($val);
return $string;
}
/*数组转字符串*/
function Array2String($Array){
if(!$Array)return false;
$Return='';
$NullValue="^^^";
foreach ($Array as $Key => $Value) {
if(is_array($Value))
$ReturnValue='^^array^'.Array2String($Value);
else
$ReturnValue=(strlen($Value)>0)?$Value:$NullValue;
$Return.=urlencode(base64_encode($Key)) . '|' . urlencode(base64_encode($ReturnValue)).'||';
}
return urlencode(substr($Return,0,-2));
}
/*字符串转数组*/
function String2Array($String){
if(NULL==$String)return false;
$Return=array();
$String=urldecode($String);
$TempArray=explode('||',$String);
$NullValue=urlencode(base64_encode("^^^"));
foreach ($TempArray as $TempValue) {
list($Key,$Value)=explode('|',$TempValue);
$DecodedKey=base64_decode(urldecode($Key));
if($Value!=$NullValue) {
$ReturnValue=base64_decode(urldecode($Value));
if(substr($ReturnValue,0,8)=='^^array^')
$ReturnValue=String2Array(substr($ReturnValue,8));
$Return[$DecodedKey]=$ReturnValue;
}
else
$Return[$DecodedKey]=NULL;
}
return $Return;
}
/*字符过滤url*/
function safe_replace($string) {
$string = str_replace('%20','',$string);
$string = str_replace('%27','',$string);
$string = str_replace('%2527','',$string);
$string = str_replace('*','',$string);
$string = str_replace('"','"',$string);
$string = str_replace("'",'',$string);
$string = str_replace('"','',$string);
$string = str_replace(';','',$string);
$string = str_replace('<','<',$string);
$string = str_replace('>','>',$string);
$string = str_replace("{",'',$string);
$string = str_replace('}','',$string);
$string = str_replace('\\','',$string);
return $string;
}
/*获取页面完整url*/
function get_web_url() {
$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
$php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}
/*获取网站当前地址*/
function get_home_url() {
$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
$path=explode('/',safe_replace($_SERVER['SCRIPT_NAME']));
if(count($path)==3){
return $sys_protocal.$_SERVER['HTTP_HOST'].'/'.$path[1];
}
if(count($path)==2){
return $sys_protocal.$_SERVER['HTTP_HOST'];
}
}
/*HTML安全过滤*/
function _htmtocode($content) {
$content = str_replace('%','%‎',$content);
$content = str_replace("<", "<", $content);
$content = str_replace(">", ">", $content);
$content = str_replace("\n", "<br/>", $content);
$content = str_replace(" ", " ", $content);
$content = str_replace('"', """, $content);
$content = str_replace("'", "'", $content);
$content = str_replace("$", "$", $content);
$content = str_replace('}','‏}',$content);
return $content;
}
/*手机号码验证*/
function _checkmobile($mobilephone=''){
if(strlen($mobilephone)!=11){ return false; }
if(preg_match("/^13[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|14[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$|17[0|7|6|8]{1}[0-9]{8}$/",$mobilephone)){
return true;
}else{
return false;
}
}
/*邮箱验证*/
function _checkemail($email=''){
if(mb_strlen($email)<5){
return false;
}
$res="/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/";
if(preg_match($res,$email)){
return true;
}else{
return false;
}
}
/*加密解密 ENCODE 加密 DECODE 解密*/
function _encrypt($string, $operation = 'ENCODE', $key = '', $expiry = 0){
if($operation == 'DECODE') {
$string = str_replace('_', '/', $string);
}
$key_length = 4;
if(defined("G_BANBEN_NUMBER")){
$key = md5($key != '' ? $key : System::load_sys_config("code","code"));
}else{
$key = md5($key != '' ? $key : G_WEB_PATH);
}
$fixedkey = md5($key);
$egiskeys = md5(substr($fixedkey, 16, 16));
$runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
$keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
$string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));
$i = 0; $result = '';
$string_length = strlen($string);
for ($i = 0; $i < $string_length; $i++){
$result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
}
if($operation == 'ENCODE') {
$retstrs = str_replace('=', '', base64_encode($result));
$retstrs = str_replace('/', '_', $retstrs);
return $runtokey.$retstrs;
} else {
if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
return substr($result, 26);
} else {
return '';
}
}
}
function _getcookie($name){
if(empty($name)){return false;}
if(isset($_COOKIE[$name])){
return $_COOKIE[$name];
}else{
return false;
}
}
function _setcookie($name,$value,$time=0,$path='/',$domain=''){
if(empty($name)){return false;}
$_COOKIE[$name]=$value; //及时生效
$s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
if(!$time){
return setcookie($name,$value,0,$path,$domain,$s);
}else{
return setcookie($name,$value,time()+$time,$path,$domain,$s);
}
}
/*
*获取字符串长度
*一个汉字2个字节,字符1个字节
*/
function _strlen($str=''){
if(empty($str)){
return 0;
}
if(!_is_utf8($str)){
$str=iconv("GBK","UTF-8",$str);
}
return ceil((strlen($str)+mb_strlen($str,'utf-8'))/2);
}
/*
* 调用模板函数
* $module 模板目录
* $template 模板文件名,
* $StyleTheme 模板方案目录,为空为默认目录
*/
function templates($module = '', $template = '',$StyleTheme=''){
if(empty($StyleTheme)){$style=G_STYLE.DIRECTORY_SEPARATOR.G_STYLE_HTML;}
else{
$templates=System::load_sys_config('templates',$style);
$style=$templates['dir'].DIRECTORY_SEPARATOR.$templates['html'];
}
$FileTpl = G_CACHES.'caches_template'.DIRECTORY_SEPARATOR.dirname($style).DIRECTORY_SEPARATOR.md5($module.'.'.$template).'.tpl.php';
$FileHtml = G_TEMPLATES.$style.DIRECTORY_SEPARATOR.$module.'.'.$template.'.html';
if(file_exists($FileHtml)){
if (file_exists($FileTpl) && @filemtime($FileTpl) >= @filemtime($FileHtml)) {
return $FileTpl;
} else {
$template_cache=&System::load_sys_class('template_cache');
if(!is_dir(dirname(dirname($FileTpl)))){
mkdir(dirname(dirname($FileTpl)),0777, true)or die("Not Dir");
chmod(dirname(dirname($FileTpl)),0777);
}
if(!is_dir(dirname($FileTpl))){
mkdir(dirname($FileTpl), 0777, true)or die("Not Dir");
chmod(dirname($FileTpl),0777);
}
$PutFileTpl=$template_cache->template_init($FileTpl,$FileHtml,$module,$template);
if($PutFileTpl)
return $FileTpl;
else
_error('template message','The "'.$module.'.'.$template .'" template file does not exist');
}
}
_error('template message','The "'.$module.'.'.$template .'" template file does not exist');
}
/**
* 字符截取 支持UTF8/GBK
* @param $string
* @param $length
* @param $dot
*/
function _strcut($string, $length,$dot = '...') {
$string = trim($string);
if($length && strlen($string) > $length) {
//截断字符
$wordscut = '';
if(strtolower(G_CHARSET) == 'utf-8') {
//utf8编码
$n = 0;
$tn = 0;
$noc = 0;
while ($n < strlen($string)) {
$t = ord($string[$n]);
if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1;
$n++;
$noc++;
} elseif(194 <= $t && $t <= 223) {
$tn = 2;
$n += 2;
$noc += 2;
} elseif(224 <= $t && $t < 239) {
$tn = 3;
$n += 3;
$noc += 2;
} elseif(240 <= $t && $t <= 247) {
$tn = 4;
$n += 4;
$noc += 2;
} elseif(248 <= $t && $t <= 251) {
$tn = 5;
$n += 5;
$noc += 2;
} elseif($t == 252 || $t == 253) {
$tn = 6;
$n += 6;
$noc += 2;
} else {
$n++;
}
if ($noc >= $length) {
break;
}
}
if ($noc > $length) {
$n -= $tn;
}
$wordscut = substr($string, 0, $n);
} else {
for($i = 0; $i < $length - 1; $i++) {
if(ord($string[$i]) > 127) {
$wordscut .= $string[$i].$string[$i + 1];
$i++;
} else {
$wordscut .= $string[$i];
}
}
}
$string = $wordscut.$dot;
}
return trim($string);
}
/*获取客户端ip*/
function _get_ip(){
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'];
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 = "";
return ($ip);
}
/* 获取ip + 地址*/
function _get_ip_dizhi($ip=null){
$opts = array(
'http'=>array(
'method'=>"GET",
'timeout'=>5,)
);
$context = stream_context_create($opts);
if($ip){
$ipmac = $ip;
}else{
$ipmac=_get_ip();
if(strpos($ipmac,"127.0.0.") === true)return '';
}
$url_ip='http://ip.taobao.com/service/getIpInfo.php?ip='.$ipmac;
$str = @file_get_contents($url_ip, false, $context);
if(!$str) return "";
$json=json_decode($str,true);
if($json['code']==0){
$json['data']['region'] = addslashes(_htmtocode($json['data']['region']));
$json['data']['city'] = addslashes(_htmtocode($json['data']['city']));
$ipcity= $json['data']['region'].$json['data']['city'];
$ip= $ipcity.','.$ipmac;
}else{
$ip="";
}
return $ip;
}
/**
* 判断字符串是否为utf8编码,英文和半角字符返回ture
* @param $string
* @return bool
*/
function _is_utf8($string) {
return preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $string);
}
/**
* 发送电子邮件
* @email 也可以是一个二维数组,包含邮件和用户名信息
**/
function _sendemail($email,$username=null,$title='',$content='',$yes='',$no=''){
System::load_sys_class("email",'sys',"no");
$config=System::load_sys_config('email');
if(!$username)$username="";
if(!$yes)$yes="发送成功,如果没有收到,请到垃圾箱查看,\n请把".$config['fromName']."设置为信任,方便以后接收邮件";
if(!$no)$no="发送失败,请重新点击发送";
if(!_checkemail($email)){return false;}
email::config($config);
if(is_array($email)){
email::adduser($email);
}else{
email::adduser($email,$username);
}
$if=email::send($title,$content);
if($if){
return $yes;
}else{
return $no;
}
}
/*
* 发送短信
**/
function _sendmobile($mobiles='',$content=''){
$mobiles=str_replace(",",',',$mobiles);
$mobiles=str_replace(" ",'',$mobiles);
$mobiles=trim($mobiles," ");
$mobiles=trim($mobiles,",");
$sends=System::load_sys_class('sendmobile');
$config=array();
$config['mobile']=$mobiles;
$config['content']= $content;
$config['ext']='';
$config['stime']='';
$config['rrid']='';
$cok=$sends->init($config);
if(!$cok){
return array('-1','配置不正确!');
}
$sends->send();
$sendarr=array($sends->error,$sends->v);
return $sendarr;
}
/**
*
* 页面执行时间统计
*
*/
function get_end_time(){
$EndTime=explode(" ",microtime());
$StartTime=explode(" ",G_START_TIME);
return intval($EndTime[1]-$StartTime[1])+($EndTime[0]-$StartTime[0]).'/S';
}
/*
*
* 页面内存消耗统计
*/
function get_end_memory(){
$memory=memory_get_usage();
$memory=$memory/1024;
return round($memory,2).'/KB';
}
/**
* message 输出自定义错误页面
* $str 错误信息
* $url 返回页面的地址, 默认返回上一页
* $time 返回时间,默认3秒后返回
* $config 其他参数配置.类型为数组 $config['titlebg']='#549bd9',$config['title']='#fff',
*/
/*
* 系统消息提示
**/
function _message($string=null,$defurl=null,$time=2,$config=null){
if(empty($defurl)){
//$defurl=G_HTTP_REFERER;
$defurl = ":js:";
//if(empty($defurl))$defurl=WEB_PATH;
}
// if(defined("G_IN_ADMIN")){
// if(empty($config)){
// $config = array("titlebg"=>"#549bd9","title"=>"#fff");
// }
// $str_url_two=array("url"=>WEB_PATH.'/'.G_ADMIN_DIR,"text"=>"返回后台首页");
// }else{
$str_url_two=array("url"=>G_WEB_PATH,"text"=>"返回首页");
// }
$time=intval($time);if($time<2){$time=2;}
include templates("system","message");
exit;
}
function _messageadmin($string=null,$defurl=null,$time=2,$config=null){
if(empty($defurl)){
//$defurl=G_HTTP_REFERER;
$defurl = ":js:";
//if(empty($defurl))$defurl=WEB_PATH;
}
// if(defined("G_IN_ADMIN")){
// if(empty($config)){
// $config = array("titlebg"=>"#549bd9","title"=>"#fff");
// }
// $str_url_two=array("url"=>WEB_PATH.'/'.G_ADMIN_DIR,"text"=>"返回后台首页");
// }else{
// $str_url_two=array("url"=>G_WEB_PATH,"text"=>"返回首页");
// }
$time=intval($time);if($time<2){$time=2;}
include templates("system","messageadmin");
exit;
}
/*
* 手机错误消息提示
**/
function _messagemobile($string=null,$defurl=null,$time=2,$config=null){
if(empty($defurl)){
$defurl=G_HTTP_REFERER;
if(empty($defurl))$defurl=WEB_PATH;
}
if(empty($config)){
if(ROUTE_M==System::load_sys_config("system","admindir")){
$config=array();
$config['titlebg']='#549bd9';$config['title']='#fff';
}
}
$time=intval($time);if($time<2){$time=2;}
include templates("mobile/system","message");
exit;
}
/*
* 手机错误消息提示
**/
function _messagemobileyes($string=null,$defurl=null,$time=2,$config=null){
if(empty($defurl)){
$defurl=G_HTTP_REFERER;
if(empty($defurl))$defurl=WEB_PATH;
}
if(empty($config)){
if(ROUTE_M==System::load_sys_config("system","admindir")){
$config=array();
$config['titlebg']='#549bd9';$config['title']='#fff';
}
}
$time=intval($time);if($time<2){$time=2;}
include templates("mobile/system","messageyes");
exit;
}
/**
* message 输出自定义错误页面
* $str 错误信息
* $url 返回页面的地址, 默认返回上一页
* $time 返回时间,默认3秒后返回
*/
function _error($title,$content){
if(empty($title)){$title='404 Page Not Found';}
if(empty($content)){$content='The page you requested was not found.';}
echo '<!DOCTYPE html><html lang="en"><head><title>'.$title.'</title><style type="text/css">::selection{ background-color: #E13300; color: white; }
::moz-selection{ background-color: #E13300; color: white; }::webkit-selection{ background-color: #E13300; color: white; }
body { background-color: #fff; margin: 40px; font: 13px/20px normal Helvetica, Arial, sans-serif; color: #4F5155;}
a { color: #003399; background-color: transparent; font-weight: normal;}
h1 { color: #444; background-color: transparent; border-bottom: 1px solid #D0D0D0; font-size: 19px; font-weight: normal;
margin: 0 0 14px 0; padding: 14px 15px 10px 15px;}
code { font-family: Consolas, Monaco, Courier New, Courier, monospace; font-size: 12px;
background-color: #f9f9f9; border: 1px solid #D0D0D0; color: #002166; display: block; margin: 14px 0 14px 0; padding: 12px 10px 12px 10px;}
#container { margin: 10px; border: 1px solid #D0D0D0; -webkit-box-shadow: 0 0 8px #D0D0D0;}
p { margin: 12px 15px 12px 15px;}</style><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>
<body> <div id="container"> <h1>'.$title.'</h1> <p>'.$content.'</p></div></body></html>';
exit;
}
/**
* IE浏览器判断
*/
function _is_ie() {
$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
if(strpos($useragent, 'msie ') !== false) return true;
return false;
}
function _is_mobile() {
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte");
$is_mobile = false;
foreach ($mobile_agents as $device) {
if (stristr($user_agent, $device)) {
$is_mobile = true;
break;
}
}
return $is_mobile;
}
//查询公共页脚信息
function _footer(){
$model=new model();
$biaoti=$model->GetList("select cateid,name from `@#_category` where `model` = '3' limit 4");
foreach($biaoti as $key=>$val){
$article = $model->GetList("select `id`,`title` from `@#_article` where `cateid` = '$val[cateid]' limit 4");
$biaoti[$key]['article'] = $article;
}
return $biaoti;
}
//查询页脚的文章
function _foot(){
$model = new model();
$cateid = $model->GetOne("select cateid from `@#_category` where `name` = '页脚文章'");
$article = $model->GetList("select `id`,`title` from `@#_article` where `cateid` = '$cateid[cateid]'");
return $article;
}
/* PHP解析错误处理 */
function _error_handler(){
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set("display_errors","OFF"); //错误报告提示关闭
ini_set("error_log",G_CACHES."error.".date("Y-m-d").".logs"); //写错误日志的地址
}
/* $n 字符串长度,返回一个数组*/
function _getcode($n=10){
$num=intval($n) ? intval($n) : 10;
if($num>44)
$codestr=base64_encode(md5(time()).md5(time()));
else
$codestr=base64_encode(md5(time()));
$temp=array();
$temp['code']=substr($codestr,0,$num);
$temp['time']=time();
return $temp;
}
/* 获取系统变量 */
function _cfg($name=''){
return System::load_sys_config('system',$name);
}
/* 安装系统函数 */
function hook_mysql_install($message=''){
if(file_exists(G_APP_PATH.'install')){
echo "<script>";
echo "window.location.href='".G_WEB_PATH."/install'";
echo "</script>";
}else{
_error("数据库连接不成功,请检查配置!",$message);
}
exit;
}
/* 网络操作函数 */
function _g_triggerRequest($url,$io=false,$post_data = array(), $cookie = array()){
$method = empty($post_data) ? 'GET' : 'POST';
$url_array = parse_url($url);
$port = isset($url_array['port'])? $url_array['port'] : 80;
if(function_exists('fsockopen')){
$fp = @fsockopen($url_array['host'], $port, $errno, $errstr, 30);
}elseif(function_exists('pfsockopen')){
$fp = @pfsockopen($url_array['host'], $port, $errno, $errstr, 30);
}elseif(function_exists('stream_socket_client')){
$fp = @stream_socket_client($url_array['host'].':'.$port,$errno,$errstr,30);
} else {
$fp = false;
}
if(!$fp){
return false;
}
$url_array['query'] = isset($url_array['query']) ? $url_array['query'] : '';
$getPath = $url_array['path'] ."?". $url_array['query'];
$header = $method . " " . $getPath." ";
$header .= "HTTP/1.1\r\n";
$header .= "Host: ".$url_array['host']."\r\n"; //HTTP 1.1 Host域不能省略
$header .= "Pragma: no-cache\r\n";
/*
//以下头信息域可以省略
$header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13 \r\n";
$header .= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,q=0.5 \r\n";
$header .= "Accept-Language: en-us,en;q=0.5 ";
$header .= "Accept-Encoding: gzip,deflate\r\n";
*/
if(!empty($cookie)){
$_cookie_s = strval(NULL);
foreach($cookie as $k => $v){
$_cookie_s .= $k."=".$v."; ";
}
$_cookie_s = rtrim($_cookie_s,"; ");
$cookie_str = "Cookie: " . base64_encode($_cookie_s) ." \r\n"; //传递Cookie
$header .= $cookie_str;
}
$post_str = '';
if(!empty($post_data)){
$_post = strval(NULL);
foreach($post_data as $k => $v){
$_post .= $k."=".urlencode($v)."&";
}
$_post = rtrim($_post,"&");
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";//POST数据
$header .= "Content-Length: ". strlen($_post) ." \r\n";//POST数据的长度
$post_str = $_post."\r\n"; //传递POST数据
}
$header .= "Connection: Close\r\n\r\n";
$header .= $post_str;
fwrite($fp,$header);
if($io){
while (!feof($fp)){
echo fgets($fp,1024);
}
}
fclose($fp);
//echo $header;
return true;
}
/**
* 短时间显示, 几分钟前,几秒前...
**/
function _put_time($time = 0,$test=''){
if(empty($time)){return $test;}
$time = substr($time,0,10);
$ttime = time() - $time;
if($ttime <= 0 || $ttime < 60){
return '几秒前';
}
if($ttime > 60 && $ttime <120){
return '1分钟前';
}
$i = floor($ttime / 60); //分
$h = floor($ttime / 60 / 60); //时
$d = floor($ttime / 86400); //天
$m = floor($ttime / 2592000); //月
$y = floor($ttime / 60 / 60 / 24 / 365); //年
if($i < 30){
return $i.'分钟前';
}
if($i > 30 && $i < 60){
return '一小时内';
}
if($h>=1 && $h < 24){
return $h.'小时前';
}
if($d>=1 && $d < 30){
return $d.'天前';
}
if($m>=1 && $m < 12){
return $m.'个月前';
}
if($y){
return $y.'年前';
}
return "";
}
/*
获取栏目信息
*/
function get_category($cid){
if(empty($cid)){
return '';
}
$db = System::load_sys_class("model");
$info = $db->GetOne("SELECT name FROM `@#_category` where `cateid` = '$cid' limit 1");
if($info){
return $info['name'];
}else{
return '';
}
}
/*
_session_start
*/
function _session_start(){
if(!isset($_SESSION)){ session_start();}
}
/*
_session_destroy
*/
function _session_destroy(){
if(isset($_SESSION)){session_destroy();}
}
/*
xml to array
*/
function _xml_to_array($xml){
$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
if(preg_match_all($reg, $xml, $matches)){
$count = count($matches[0]);
for($i = 0; $i < $count; $i++){
$subxml= $matches[2][$i];
$key = $matches[1][$i];
if(preg_match( $reg, $subxml )){
$arr[$key] = _xml_to_array( $subxml );
}else{
$arr[$key] = $subxml;
}
}
}
return $arr;
}
function get_regions($type = 0, $parent = 0)
{
$db = System::load_sys_class("model");
$sql = "SELECT id, name FROM `@#_district` WHERE level = '$type' AND upid = '$parent'";
return $db->GetList($sql);
}
/**
* 获得地区列表(all by zhangfl 需优化)
*
* @access public
* @param integer $cat_id 分类编号
* @return array
*/
function get_region_tree(){
$db = System::load_sys_class("model");
$parent_id = 1;
/*
判断当前分类中全是是否是底级分类,
如果是取出底级分类上级分类,
如果不是取当前分类及其下的子分类
*/
$sql = "SELECT count(*) FROM `@#_district` WHERE level = '$parent_id'";
if ($db->GetCount($sql))
{
/* 获取当前分类及其子分类 */
$sql = 'SELECT id, name, upid ' .
"FROM `@#_district` WHERE level = '$parent_id'";
$res = $db->GetList($sql);
foreach ($res AS $row)
{
$cat_arr[$row['id']]['id'] = $row['id'];
$cat_arr[$row['id']]['name'] = $row['name'];
if (isset($row['id']) != NULL)
{
$cat_arr[$row['id']]['region_id'] = get_child_tree_region($row['id']);
}
}
}
if(isset($cat_arr))
{
return $cat_arr;
}
}
function get_child_tree_region($tree_id = 0)
{
$db = System::load_sys_class("model");
$three_arr = array();
$sql = "SELECT count(*) FROM `@#_district` WHERE upid = '$tree_id'";
if ($db->GetCount($sql) || $tree_id == 0)
{
$child_sql = 'SELECT id, name, upid,level ' .
"FROM `@#_district` WHERE upid = '$tree_id'";
$res = $db->GetList($child_sql);
foreach ($res AS $row)
{
$three_arr[$row['id']]['id'] = $row['id'];
$three_arr[$row['id']]['name'] = $row['name'];
if (isset($row['id']) != NULL && $row['level'] <= 2)
{
$three_arr[$row['id']]['region_id'] = get_child_tree_region($row['id']);
}
}
}
return $three_arr;
}
function _check_send_mobile($mobile,$day,$type,$code=0){
$mb=_checkmobile($mobile);
if(!$mb) return false;
$st=strtotime(date("Y-m-d 00:00:00"));
$en=strtotime(date("Y-m-d 23:59:59"));
$db = System::load_sys_class("model");
if($day==1){
$sql="select count(*) from `@#_sms_records` where `mobile`=$mobile and `sendtime`>=$st and `sendtime`<=$en";
if($db->GetCount($sql)>=10){
return false;
}
}
$sql="select sendtime from `@#_sms_records` where `mobile`=$mobile and `sendtime`>=$st and `sendtime`<=$en order by `id` desc limit 1 ";
$rs=$db->GetOne($sql);
$times=time();
$tl=System::load_sys_config('setting',mobile_limit_time);
if(!empty($rs['sendtime'])){
$cha=$times-$rs['sendtime'];
if($cha<=$tl){
return false;
}else{
if($code==0){
$sql="insert into `@#_sms_records` (mobile,type,sendtime) values('$mobile','$type','$times')";
}else{
$sql="insert into `@#_sms_records` (mobile,type,sendtime,code) values('$mobile','$type','$times','$code')";
}
$query=$db->Query($sql);
return true;
}
}else{
if($code==0){
$sql="insert into `@#_sms_records` (mobile,type,sendtime) values('$mobile','$type','$times')";
}else{
$sql="insert into `@#_sms_records` (mobile,type,sendtime,code) values('$mobile','$type','$times','$code')";
}
$query=$db->Query($sql);
return true;
}
}
global.fun.php的更多相关文章
- 全局变量:global与$GLOBALS的区别和使用
今天在写框架的时候想把SaeMySQL初始化之后作为全局变量使用.但是后来发现PHP中的全局变量和Java或者OC中的全局变量还是有较大区别的.下面记录一下php里面的global的使用相关注意事项. ...
- [翻译]ES 提案: global
Jordan Harband 的 ECMAScript 提案“global”现在处于第三阶段.该提案提供了一种新的用于访问全局对象的标准方式. 全局对象的引用 下面是常用的几种引用全局对象的方式: 全 ...
- PHP中的全局变量global和$GLOBALS的区别
1.global Global的作用是定义全局变量,但是这个全局变量不是应用于整个网站,而是应用于当前页面,包括include或require的所有文件. 但是在函数体内定义的global变量,函数体 ...
- python中list作为全局变量无需global声明的原因
发现一个问题. python中list变量作为全局变量时,在函数中可以直接修改. 而普通变量则需要先在函数中global声明,否则会报错. 例如: a = 1 def fun(): global a ...
- Global Translator
Global Translator插件可以把已经通过翻译服务翻译好的内容生成对应语种的“静态”页面,或者说“缓存”起来,这样在一段时间内(可设置)想访问该语种的这 个页面的访客,就可以在不调用翻译服务 ...
- python 中使用 global 引发了莫名其妙的问题
哪里出问题了 python 中,使用 global 会将全局变量设为本函数可用.同时,在函数内部访问变量会先本地再全局. 在嵌套函数中,使用 global 会产生不合常理的行为. 上代码: In [9 ...
- Mysql命令show global status求根溯源
近来,发现好多公司对mysql的性能监控是通过show global status实现的,因此对于这个命令想要探究一番,看他是否是实时更新的. 在此之前,我们必须搞明白mysql对于这个命令的执行过程 ...
- Global eval. What are the options?
David Flanagan最近写了一个关于全局eval的简单表达式,可以用一行式子表示: var geval = this.execScript || eval; 尽管看起来很简短,但是跨浏览器的兼 ...
- 解决EP拒绝访问注册表Global键的的问题
问题描述 打开EP站点时出现如下Error: Message: An unhandled error has occurred. To view details about this error, ...
- python中global 和 nonlocal 的作用域
python引用变量的顺序: 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量 . 一 global global关键字用来在函数或其他局部作用域 ...
随机推荐
- Asp.Net中的HttpWebRequest类与HttpWebResponse类
相关博文:https://www.cnblogs.com/xu-yi/p/10061342.html 相关博文:https://www.cnblogs.com/zoujinhua/p/11313396 ...
- 移植 inetd
inetd 的选择及获取 Busybox1.1.3 提供了 inetd 支持.如果读者使用的是较低版本的不提供 inetd 的 Busybox,那么可以考虑使 用 netkit 套件来提供网络服务.强 ...
- Luogu P2827 蚯蚓(模拟)
P2827 蚯蚓 题意 题目描述 本题中,我们将用符号\(\lfloor c\rfloor\)表示对\(c\)向下取整,例如:\(\lfloor 3.0\rfloor =\lfloor 3.1\rfl ...
- C#可扩展编程之MEF(五):MEF高级进阶
好久没有写博客了,今天抽空继续写MEF系列的文章.有园友提出这种系列的文章要做个目录,看起来方便,所以就抽空做了一个,放到每篇文章的最后. 前面四篇讲了MEF的基础知识,学完了前四篇,MEF中比较 ...
- Docker系列(十):Kubernetes集群入门
kubenetes安装 官网:https://github.com/kubernetes/kubernetes/blob/release-1.0/docs/getting-started- guide ...
- HTML 颜色表示
三种表示方法 1 颜色单词 : blue green red pink 2 10进制表示: RGB(255, 10, 0) 3 16进制表示: #FF0000(红) #00FF00(绿)
- IDEA中Git的使用(多人合作)
首先我们要简单知道github跟Git的区别.git是版本控制工具, github是一个面向开源及私有软件项目的托管平台,也是程序员交流的地方. 接下来就开始讲怎么多人一起开发. 首先我们先拥有git ...
- Java +支付宝 +接入
说下业务场景, 公司之前的支付宝业务是PHP对接的现在改成 Java ,在接入出现不同的问题.之前PHP用的是老的移动支付, 现在Java的新接口 , 需要签约. 跟运维沟通好几次, 说签约不了, 只 ...
- java基础之完数判断
完数: 完全数(Perfect number),又称完美数或完备数,是一些特殊的自然数.它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身.如果一个数恰好等于它的因子之和,则称该 ...
- C++【stack/queue】用法和例子
Stack的常用基本操作: s.push() // 压栈 s.emplace() // 插入,相当于push(目前掌握的唯一区别是emplace可以自行调用构造函数,push不行) s.empty() ...