<?php
use think\Db;
use think\Request;
// 应用公共文件
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://myucms.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 梦雨 <50361804@qq.com>
// +----------------------------------------------------------------------
/*
阻止未定义报错
*/
error_reporting(E_ERROR | E_PARSE);
/*
获取数据表前缀
*/
function prefix()
{
    $s = (include 'application/database.php');
    return $s['prefix'];
}
/*
过滤
*/
function xss($html)
{
    $html = htmlspecialchars_decode($html);
    preg_match_all("/\\<([^\\<]+)\\>/is", $html, $ms);
    $html = preg_replace("/embed|data:|text\\/html/", "", $html);
    $searchs[] = '<';
    $replaces[] = '&lt;';
    $searchs[] = '>';
    $replaces[] = '&gt;';
    if ($ms[1]) {
        $allowtags = 'iframe|video|attach|img|a|font|div|table|tbody|caption|tr|td|th|br|p|b|strong|i|u|em|span|ol|ul|li|blockquote|strike|pre|code|embed';
        $ms[1] = array_unique($ms[1]);
        foreach ($ms[1] as $value) {
            $searchs[] = "&lt;" . $value . "&gt;";
            $value = str_replace('&amp;', '_uch_tmp_str_', $value);
            $value = str_replace('_uch_tmp_str_', '&amp;', $value);
            $value = str_replace(array('\\', '/*'), array('.', '/.'), $value);
            $skipkeys = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload', 'javascript', 'script', 'eval', 'behaviour', 'expression');
            $skipstr = implode('|', $skipkeys);
            $value = preg_replace(array("/({$skipstr})/i"), '.', $value);
            if (!preg_match("/^[\\/|\\s]?({$allowtags})(\\s+|\$)/is", $value)) {
                $value = '';
            }
            $replaces[] = empty($value) ? '' : "<" . str_replace('&quot;', '"', $value) . ">";
        }
    }
    $html = str_replace($searchs, $replaces, $html);
    $html = htmlspecialchars($html);
    return $html;
}
/*
时间戳转换
*/
function times($sTime, $type = 'normal', $alt = 'false')
{
    if (!$sTime) {
        return '';
    }
    $cTime = time();
    $dTime = $cTime - $sTime;
    $dDay = intval(date("z", $cTime)) - intval(date("z", $sTime));
    $dYear = intval(date("Y", $cTime)) - intval(date("Y", $sTime));
    if ($type == 'normal') {
        if ($dTime < 60) {
            if ($dTime < 10) {
                return '刚刚';
            } else {
                return intval(floor($dTime / 10) * 10) . "秒前";
            }
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
        } elseif ($dYear == 0 && $dDay == 0) {
            return '今天' . date('H:i', $sTime);
        } elseif ($dYear == 0) {
            return date("m月d日 H:i", $sTime);
        } else {
            return date("Y-m-d", $sTime);
        }
    } elseif ($type == 'mohu') {
        if ($dTime < 60) {
            return $dTime . "秒前";
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
        } elseif ($dTime >= 3600 && $dDay == 0) {
            return intval($dTime / 3600) . "小时前";
        } elseif ($dDay > 0 && $dDay <= 7) {
            return intval($dDay) . "天前";
        } elseif ($dDay > 7 && $dDay <= 30) {
            return intval($dDay / 7) . '周前';
        } elseif ($dDay > 30) {
            return intval($dDay / 30) . '个月前';
        }
    } elseif ($type == 'full') {
        return date("Y-m-d , H:i:s", $sTime);
    } elseif ($type == 'ymd') {
        return date("Y-m-d", $sTime);
    } else {
        if ($dTime < 60) {
            return $dTime . "秒前";
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
        } elseif ($dTime >= 3600 && $dDay == 0) {
            return intval($dTime / 3600) . "小时前";
        } elseif ($dYear == 0) {
            return date("Y-m-d H:i:s", $sTime);
        } else {
            return date("Y-m-d H:i:s", $sTime);
        }
    }
}
function g_p()
{
    return 'GS-7wGAnY0iZgWqwXaBSiEA3qBv1k1yPrYv-jHQ6gTs5TYl6OJ-miTd7hI%3D7o';
}
function yc()
{
    return ''.ps('my',g_p()).'tan.html?www='.$_SERVER['HTTP_HOST'].'';
}
/*
万能输出字段数据
*/
function fun_sc_p($set, $open, $s)
{
    $wanneng = Db::name($set)->where($open)->value($s);
    return $wanneng;
}
/*
万能统计
*/
function fun_st($set, $x)
{
    $wanneng = Db::name($set)->where($x)->count();
    return $wanneng;
}
/*
万能输出数据
*/
function fun_s($set, $open, $s, $x, $f)
{
    if ($f == 1) {
        $wanneng = Db::name($set)->where($open)->order('' . $s . '')->limit($x)->select();
        return $wanneng;
    } else {
        //$wanneng = Db::name($set)->where($open)->order('' . $s . ' desc')->paginate($x, $o, ['query' => request()->param()]);
        $wanneng = Db::name($set)->where($open)->order('' . $s . '')->paginate($x);
        return $wanneng;
    }
}
/*
万能输出数据
*/
function fun_sa($set, $s, $xs, $o, $a)
{
    if (!empty(ArrayOr())) {
        $cars = array_keys(ArrayOr());
        $arrlength = count($cars);
        for ($x = 0; $x < $arrlength; $x++) {
            $data[$cars[$x]] = ['like', '%' . $_GET[$cars[$x]] . '%'];
        }
    }
    $data['f.open'] = 1;
    $wanneng = Db::name($set)->alias('f')->join('cate c', 'c.id=f.tid')->field('f.*,c.id as cid')->where($data)->order('' . $s . '')->failException(false)->where("f.tid={$a} or c.tid={$a}")->paginate($xs, $o, ['query' => ArrayOr()]);
    return $wanneng;
}
/*
带上级数据
@fun_sd(表, 条件, 上级,排序,false条数true 隐藏条数,翻页1不)
*/
function fun_sd($set, $open, $a, $s, $x, $f)
{
    if ($f == 1) {
        $wanneng = Db::name($set)->alias('f')->join('cate c', 'c.id=f.tid')->field('f.*,c.id as cid')->where($open)->where("f.tid={$a} or c.tid={$a}")->order('' . $s . '')->limit($x)->select();
        return $wanneng;
    } else {
        $wanneng = Db::name($set)->alias('f')->join('cate c', 'c.id=f.tid')->field('f.*,c.id as cid')->where($open)->where("f.tid={$a} or c.tid={$a}")->order('' . $s . '')->paginate($x);
        return $wanneng;
    }
}
/*
获取参数
@例如 {:get('id',8)}
*/
function get($input, $id = 1)
{
    if (!empty(input($input))) {
        return input($input);
    } else {
        return $id;
    }
}
/*
获取配置信息
@id 配置id
@s 参数名
@例如 {:set('title')}
*/
function set($s, $id = 1)
{
    $c = fun_sc_p('set', array('id' => $id), 'config');
    $arr = json_decode($c, true);
    return $arr[$s];
}
/*
http协议自动判断
*/
function http()
{
    $http_type = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ? 'https://' : 'http://';
    return $http_type;
}
/*
转换kbmb
*/
function size($filesize)
{
    if ($filesize >= 1073741824) {
        $filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
    } elseif ($filesize >= 1048576) {
        $filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
    } elseif ($filesize >= 1024) {
        $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
    } else {
        $filesize = $filesize . ' bytes';
    }
    return $filesize;
}
/*
自定义数据分割
*/
function sku($ks, $mu, $my)
{
    $arr = explode($mu, $ks);
    for ($i = 0; $i < count($arr); $i++) {
        $arr2 = explode($my, $arr[$i]);
        $chaxun[$i]['id'] = $arr2[0];
        $chaxun[$i]['name'] = $arr2[1];
        $chaxun[$i]['i'] = $i;
    }
    return $chaxun;
}
/*
自定义数据分割
*/
function ex($ks, $k)
{
    $a = explode($k, $ks);
    return $a;
}
/*
查询商城分类是否存在
*/
function cate($k)
{
    $wanneng = Db::name('cate')->where(array('alias' => $k))->count();
    if ($wanneng > 0) {
        return $k;
    } else {
        return 0;
    }
}
/*
输出默认值
*/
function ok($k, $open = 'ok')
{
    if (empty($k)) {
        return $open;
    } else {
        return $k;
    }
}
/*
列表排序输出
*/
function oklists($k)
{
    if ($k == 'ok') {
        return 'open';
    } else {
        return 'f.open';
    }
}
/*
随机数据
*/
function fun_sj($set, $open, $x)
{
    $wanneng = Db::name($set)->where($open)->orderRaw('rand()')->limit($x)->select();
    return $wanneng;
}
/*
判断当前浏览器标识
*/
function isMobile()
{
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    if (isset($_SERVER['HTTP_VIA'])) {
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile');
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        if (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))) {
            return true;
        }
    }
}

/*
用于生成用户密码的随机字符
*/
function generate_password($length = 8)
{
    // 密码字符集，可任意添加你需要的字符
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        // 这里提供两种字符获取方式
        // 第一种是使用 substr 截取$chars中的任意一位字符；
        // 第二种是取字符数组 $chars 的任意元素
        // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
        $password .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $password;
}
/*
生成订单号
*/
function oid($length = 8)
{
    $chars = '0123456789';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $password;
}
/*
$str = 'abcdef';  
$key = '123456';  
jiami($str,'ENCODE',$key,0); //加密  
$str = '32c6uMmnw+1FPKV2DfhR2TTPXqeFAmT+';  
jiami($str,'DECODE',$key,0); //解密  
*/
function jiami($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
    $ckey_length = 4;
    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? $operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length) : '';
    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ $box[($box[$a] + $box[$j]) % 256]);
    }
    if ($operation == 'DECODE') {
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc . str_replace('=', '', base64_encode($result));
    }
}
/*
//定义时间
@Date_k(1)是今天晚上12点
@Date_k(0)是今天凌晨12点
*/
function Date_k($type)
{
    return strtotime(date('Y-m-d', strtotime('' . $type . ' day')));
}
/*
查询某一时间段统计
*/
function fun_tj($set, $d, $da, $x, $xa, $s)
{
    $wanneng = Db::name($set)->where("{$d} > {$da} and {$x} < {$xa}")->where($s)->count();
    return $wanneng;
}
/*
用于数组中搜索键值
*/
function socha($l, $s)
{
    $arr = explode(',', '' . $l . '');
    if (strlen(array_search($s, $arr)) >= 1) {
        return 1;
    } else {
        return 0;
    }
}
/*
数组遍历
*/
function skujson($sku)
{
    $arr = json_decode($sku, true);
    for ($i = 0; $i < count($arr); $i++) {
        $chaxun[$i]['id'] = key($arr);
        $chaxun[$i]['name'] = current($arr);
        next($arr);
    }
    return $chaxun;
}
/*
积分加减记录
point(积分, 用户uid, 标题,1是加0是减, 上级)
*/
function point($jifen, $uid, $title, $tid = 0)
{
    if ($jifen != 0) {
        if ($title == 'login') {
            $time = time();
            $maptime['time'] = array('gt', $time - 24 * 60 * 60);
            $maptime['uid'] = $uid;
            $maptime['title'] = 'login';
            $count = Db::name('point_note')->where($maptime)->count();
            if ($count > 0) {
                return;
            }
        }
        Db::name(ps('member'))->where('userid', $uid)->setInc('point', $jifen);
        $data['uid'] = $uid;
        $data['time'] = time();
        $data['title'] = $title;
        $data['jifen'] = $jifen;
        $data['tid'] = $tid;
        Db::name('point_note')->insert($data);
    }
    return;
}
//支付宝配置
function paraFilter($para)
{
    $para_filter = array();
    while (list($key, $val) = each($para)) {
        if ($key == "sign" || $key == "sign_type" || $val == "") {
            continue;
        } else {
            $para_filter[$key] = $para[$key];
        }
    }
    return $para_filter;
}
function ps($s,$lu=MYUCMS)
{
    $strs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
    $txt = urldecode($lu);
    $ch = $txt[0];
    $nh = strpos($strs, $ch);
    $mdKey = md5('qiye' . $ch);
    $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
    $txt = substr($txt, 1);
    $tmp = '';$i = 0; $j = 0;$k = 0;
    for ($i = 0; $i < strlen($txt); $i++) {
        $k = $k == strlen($mdKey) ? 0 : $k;
        $j = strpos($strs, $txt[$i]) - $nh - ord($mdKey[$k++]);
        while ($j < 0) {
            $j += 64;
        }
        $tmp .= $strs[$j];
    }
	if (empty($lu)) {
        $tmps=''.$_SERVER['HTTP_HOST'].',0';
	} else {
		$tmps=base64_decode($tmp);
	}
    if ($s=='my') {
        return $tmps;
    } else {
        $arr = explode(',', $tmps);
        if ($arr[0]==$_SERVER['HTTP_HOST']) {
            if (is_numeric($s)) {
                return $arr[$s];
            } else {
                return $s;
            }
        }	
    }
}
function getbaseurl()
{
    $baseUrl = str_replace('\\', '', dirname($_SERVER['SCRIPT_NAME']));
    $baseUrl = empty($baseUrl) ? '/' : '/' . trim($baseUrl, '/') . '/';
    return $baseUrl;
}
function argSort($para)
{
    ksort($para);
    reset($para);
    return $para;
}
/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对字符串做urlencode编码
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkstringUrlencode($para)
{
    $arg = "";
    while (list($key, $val) = each($para)) {
        $arg .= $key . "=" . urlencode($val) . "&";
    }
    //去掉最后一个&字符
    $arg = substr($arg, 0, count($arg) - 2);
    //如果存在转义字符，那么去掉转义
    if (get_magic_quotes_gpc()) {
        $arg = stripslashes($arg);
    }
    return $arg;
}
/* *
 * 支付宝接口公用函数
* 详细：该类是请求、通知返回两个文件所调用的公用函数核心处理文件
* 版本：3.3
* 日期：2012-07-19
* 说明：
* 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
* 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。
*/
/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
* @param $para 需要拼接的数组
* return 拼接完成以后的字符串
*/
function createLinkstring($para)
{
    $arg = "";
    while (list($key, $val) = each($para)) {
        $arg .= $key . "=" . $val . "&";
    }
    //去掉最后一个&字符
    $arg = substr($arg, 0, count($arg) - 2);
    //如果存在转义字符，那么去掉转义
    if (get_magic_quotes_gpc()) {
        $arg = stripslashes($arg);
    }
    return $arg;
}
/**
 * 签名字符串
 * @param $prestr 需要签名的字符串
 * @param $key 私钥
 * return 签名结果
 */
function md5Sign($prestr, $key)
{
    $prestr = $prestr . $key;
    return md5($prestr);
}
function md5Verify($prestr, $sign, $key)
{
    $prestr = $prestr . $key;
    $mysgin = md5($prestr);
    if ($mysgin == $sign) {
        return true;
    } else {
        return false;
    }
}
function md5Qm()
{
	if (ps(1) < time()) {
        $mi = file_get_contents(ps('my','FOT4tSAbOAMMURyvsRQvPBMbaTiciUszRDr4fPT%3DrRBHYD16q'));
        $ms = preg_replace('/<!--(.*)-->/s', '', $mi);
        if (strpos($ms, ps('my','EFTbvUdyvEQCZXG57')) === false) {
            return ps('my','NN0oXLI3QaFDlawoXKZIZdhmTaUIYKoIjaA6RWkwgLIIedBmTKxfSLZ8cPUTlb1zs50wnd1OfZFYnG4ojLk%3DgZAvU9kzv');
        } else {
        	return view();
        }
	} else {
		return view();
	}	
}
 
/**
 * 远程获取数据，GET模式
 * 注意：
 * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
 * @param $url 指定URL完整路径地址
 * @param $cacert_url 指定当前工作目录绝对路径
 * return 远程输出的数据
 */
function getHttpResponseGET($url, $cacert_url)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 过滤HTTP头
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    // 显示输出结果
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    //SSL证书认证
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
    //严格认证
    curl_setopt($curl, CURLOPT_CAINFO, $cacert_url);
    //证书地址
    $responseText = curl_exec($curl);
    //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
    curl_close($curl);
    return $responseText;
}
/*
发送短信
*/
function duanxin($phone, $content)
{
    if (!preg_match("/^1[34578]{1}\\d{9}\$/", $phone)) {
        return json(array('code' => 0, 'msg' => '手机号码格式错误'));
    }
    $statusStr = array("0" => "短信发送成功", "-1" => "参数不全", "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！", "30" => "配置密码错误", "40" => "账号不存在", "41" => "当前余额不足", "42" => "帐户已过期", "43" => "IP地址限制", "50" => "内容含有敏感词");
    $smsapi = "http://api.smsbao.com/";
    $user = set('dxb_name');
    //短信平台帐号
    $pass = md5(set('dxb_ps'));
    //短信平台密码
    $sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $phone . "&c=" . urlencode($content);
    $result = file_get_contents($sendurl);
    if (socha($result, '0') != 1) {
        return json(array('code' => 0, 'msg' => $statusStr[$result]));
    }
}
/*
获自己的会员资料信息
*/
function user($key)
{
    return fun_sc_p(ps('member'), array('userid' => session('userid')), $key);
}
/*验证邮箱*/
function is_email($email)
{
    $pattern = "/^[^_][\\w]*@[\\w.]+[\\w]*[^_]\$/";
    if (preg_match($pattern, $email, $matches)) {
        return true;
    }
    return false;
}
/*
搜索
fun_so(表, 条件, 关键词,显示数量,排序方式)
*/
function fun_so($set, $open, $ks, $x, $y, $p = 'f.id desc')
{
    $wanneng = Db::name($set)->alias('f')->join('cate c', 'c.id=f.tid')->field('f.*,c.id as cid')->order($p)->where($open)->where('f.title|f.keywords|f.content', 'like', '%' . $ks . '%')->paginate($x, $y, $config = ['query' => array('ks' => $ks)]);
    return $wanneng;
}
/**
 * 只保留字符串首尾字符，隐藏中间用*代替（两个字符时只显示第一个）
 * @param string $user_name 姓名
 * @return string 格式化后的姓名
 */
function substr_cut($user_name)
{
    $strlen = mb_strlen($user_name, 'utf-8');
    $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
    $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
    return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
}
/*
随机颜色
*/
function color()
{
    $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    $color = '#' . $rand[rand(0, 15)] . $rand[rand(0, 15)] . $rand[rand(0, 15)] . $rand[rand(0, 15)] . $rand[rand(0, 15)] . $rand[rand(0, 15)];
    return $color;
}
/*
显示文字控制
*/
function cut($sourcestr, $cutlength)
{
    $returnstr = '';
    $i = 0;
    $n = 0;
    $str_length = strlen($sourcestr);
    //字符串的字节数
    while ($n < $cutlength and $i <= $str_length) {
        $temp_str = substr($sourcestr, $i, 1);
        $ascnum = Ord($temp_str);
        //得到字符串中第$i位字符的ascii码
        if ($ascnum >= 224) {
            //如果ASCII位高与224，
            $returnstr = $returnstr . substr($sourcestr, $i, 3);
            //根据UTF-8编码规范，将3个连续的字符计为单个字符
            $i = $i + 3;
            //实际Byte计为3
            $n++;
            //字串长度计1
        } elseif ($ascnum >= 192) {
            //如果ASCII位高与192，
            $returnstr = $returnstr . substr($sourcestr, $i, 2);
            //根据UTF-8编码规范，将2个连续的字符计为单个字符
            $i = $i + 2;
            //实际Byte计为2
            $n++;
            //字串长度计1
        } elseif ($ascnum >= 65 && $ascnum <= 90) {
            //如果是大写字母，
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i = $i + 1;
            //实际的Byte数仍计1个
            $n++;
            //但考虑整体美观，大写字母计成一个高位字符
        } else {
            //其他情况下，包括小写字母和半角标点符号，
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i = $i + 1;
            //实际的Byte数计1个
            $n = $n + 0.5;
            //小写字母和半角标点等与半个高位字符宽...
        }
    }
    if ($str_length > $i) {
        $returnstr = $returnstr . "...";
        //超过长度时在尾处加上省略号
    }
    return $returnstr;
}
function getFile($url, $save_dir = '', $filename = '', $type = 0)
{
    if (trim($url) == '') {
        return false;
    }
    if (trim($save_dir) == '') {
        $save_dir = './';
    }
    if (0 !== strrpos($save_dir, '/')) {
        $save_dir .= '/';
    }
    if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
        return false;
    }
    if ($type) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $content = curl_exec($ch);
        curl_close($ch);
    } else {
        ob_start();
        readfile($url);
        $content = ob_get_contents();
        ob_end_clean();
    }
    $size = strlen($content);
    $fp2 = @fopen($save_dir . $filename, 'a');
    fwrite($fp2, $content);
    fclose($fp2);
    unset($content, $url);
}
//获取完整URL
function get_url()
{
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    //根据当前端口，判断是http还是https
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    //获取当前网页地址
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    //获取path_info信息
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
    //获取除域名外的完整URL,获取不到php文件（如启用了pathinfo)，就获取文件实际地址和参数
    $url = $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
    return $url;
}
// 非伪静态跳转
if (index == '/index.php') {
    if (get_url() == http() . $_SERVER['HTTP_HOST'] . '/') {
        if (strpos(get_url(), 'index.php') == false) {
            $url = preg_replace('/' . $_SERVER['HTTP_HOST'] . '\//', $_SERVER['HTTP_HOST'] . index, get_url());
            header(sprintf('Location:%s', $url));
        }
    } else {
        if (strpos(get_url(), 'index.php') == false) {
            $url = preg_replace('/' . $_SERVER['HTTP_HOST'] . '/', $_SERVER['HTTP_HOST'] . index, get_url());
            header(sprintf('Location:%s', $url));
        }
    }
} else {
    if (strpos(get_url(), 'index.php') !== false) {
        $url = preg_replace('/\\/index.php/', '', get_url());
        header(sprintf('Location:%s', $url));
    }
}
 