<?php
use think\Db;
use think\Request;
use Think\Config;
use think\Cookie;
use think\Session;
use PHPMailer\PHPMailer;
use WordAnalysis\Analysis;
// 应用公共文件
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://mifenlei.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 梦雨 <50361804@qq.com>
// +----------------------------------------------------------------------
/*
阻止未定义报错
*/
error_reporting(E_ERROR | E_PARSE);
/**
 * 获取数据表前缀
 * @return [type] [description]
 */
function prefix()
{
    $s = (include 'mifenlei/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($posttime){
$now = time(); 
$end = 86400*10; 
$dif = $now - $posttime;
    if($dif <= 3600){ 
        return '<span style="color:red">'.ceil($dif/60).'分钟前</span>'; 
    }else if($dif >3600 && $dif<86400){ 
        return ceil($dif/3600).'小时前'; 
    }else if( $dif >86400 && $dif < $end){ 
        return ceil($dif/86400).'天前'; 
    }else{
        return date('m-d',$posttime);
    }       

}
function zh_time($time)
{
    $d = floor($time / (3600*24));
    $h = floor(($time % (3600*24)) / 3600);
    $m = floor((($time % (3600*24)) % 3600) / 60);
    if($d>'0'){
        echo $d.'天'.$h.'小时'.$m.'分';
    }else{
        if($h!='0'){
            echo $h.'小时'.$m.'分';
        }else{
            echo $m.'分';
        }
    }
}
function g_p()
{
    return 'JNc3yH2JsdAfhDVmqbAepC1qrNgfpDFC2NR7jGBqndQLgIBqndQLgIBp9';
}
function yc()
{
    return ''.ps('my',g_p()).'tan.html?www='.$_SERVER['HTTP_HOST'].'';
}
/*
万能输出字段数据
*/
function fun_sc_p($set, $open, $s,$desc='1')
{
    if ($desc==1) {
        $wanneng = Db::name($set)->where($open)->value($s);
    } else {
        $wanneng = Db::name($set)->where($open)->order('' . $desc . '')->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 (isMobile()!=true) {
        $true=false;
    } else {
        $true=true;
    }
    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,$true);
        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;
}
/**
 * 带上级数据
 * @param  [type] $set  表
 * @param  [type] $open 条件
 * @param  [type] $a    上级
 * @param  [type] $s    排查
 * @param  [type] $x    false条数true 隐藏条数
 * @param  [type] $f    翻页1不
 * @return [type] @fun_sd(表, 条件, 上级,排序,false条数true 隐藏条数,翻页1不)
 * 
 */
function fun_sd($set, $open, $a, $s, $x, $f, $cate='cate')
{
    if ($f == 1) {
        if ($a) {
            $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();
        } else {
            $wanneng = Db::name($set)->alias('f')->join($cate.' c', 'c.id=f.tid')->field('f.*,c.id as cid')->where($open)->limit($x)->select();
        }
        return $wanneng;
    } else {
        if ($a) {
            $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);
        } else {
            $wanneng = Db::name($set)->alias('f')->join($cate.' c', 'c.id=f.tid')->field('f.*,c.id as cid')->where($open)->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];
}
/**
 * 获取功能设置的信息
 * @param  [type] $name [description]
 * @return [type]       [description]
 */
function set_s($name,$id='set')
{
    $url = file_get_contents('mifenlei/extra/'.$id.'.txt');
    $arr = json_decode($url, true);
    return $arr[$name];
}
/**
 * 获模板的配置信息
 * @param  [type] $name [description]
 * @return [type]       [description]
 */
function mi($name)
{
    if (input('wap')=='muban') {
        if (isMobile()==true) {
            $url = file_get_contents('template/'.muban().'/set.txt');
        } else {
            $url = file_get_contents('template/'.input('id').'/set.txt');
        }
    } else {
        $url = file_get_contents('template/'.muban().'/set.txt');
    }
    $arr = json_decode($url, true);
    return $arr[$name];
}
/*
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 == '登陆') {
            $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=MIFENLEI)
{
    $strs = APP_MI;
    $txt = urldecode($lu);
    $ch = $txt[0];
    $nh = strpos($strs, $ch);
    $mdKey = md5('mi' . $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);
	}
	$arr = explode(',', $tmps);
    if ($s=='my') {
        return $tmps;
    } else if ($s==1) {
        return $arr[0];
    } else if ($s==2) {
        return $arr[1];
    } else {    
        if (strpos($_SERVER['HTTP_HOST'],$arr[0]) !== false) {
            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(2) < time()) {
        $mi = file_get_contents(ps('my','GGuOZF9vNaw8u').muban().'/'.ps('my','MHqCyeGVi9kRifbzA'));
        if (strpos($mi, ps('my','OfWjoJYozIZlhZ69r')) !== false) {
        	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;
}
/**
 * 搜索
 * @param  [type]  $set  [description]
 * @param  [type]  $open [description]
 * @param  [type]  $ks   [description]
 * @param  string  $x    [description]
 * @param  string  $so   [description]
 * @param  string  $p    [description]
 * @param  boolean $y    [description]
 * @return [type]        [description]
 */
function fun_so($set, $open, $ks, $x = '10', $so = 'title-content', $p = 'id desc', $y = false)
{
    $so = preg_replace("/-/","|", $so);
    if (empty($ks)) {
        $wanneng = Db::name($set)->order($p)->where($open)->paginate($x, $y);
    } else {
        $wanneng = Db::name($set)->order($p)->where($open)->where($so, '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, $dian='...')
{
    $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 . $dian;
        //超过长度时在尾处加上省略号
    }
    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);
}
/**
 * 当数据为空定义的显示数据
 * @param  [type] $s 要显示的数据
 * @param  string $v 数据为空显示的自定义数据
 * @return [type]    [description]
 */
function dingyi($s, $v = '1')
{
    if (empty($s)) {
        return $v;
    } else {
        return $s;
    }
}
/**
 * 获取cate_m的数据
 * @param  [type] $id [description]
 * @param  [type] $s  [description]
 * @return [type]     [description]
 */
function fun_cate_m($id, $s)
{
    $wanneng = Db::name('cate_m')->where(array('id' => $id))->value($s);
    return $wanneng;
}
function fun_cate_diqu($id, $s)
{
    $wanneng = Db::name('cate_diqu')->where(array('id' => $id))->value($s);
    return $wanneng;
}
/*
输出用户数据
$uid==用户
$s==字段数据
*/
function fun_u($uid, $s)
{
    $wanneng = Db::name('member')->where(array('userid' => $uid))->value($s);
    return $wanneng;
}
function fun_cate($id, $s)
{
    $wanneng = Db::name('cate')->where(array('id' => $id))->value($s);
    return $wanneng;
}
/**
 * 执行sql
 * @param  [type] $sql [description]
 * @return [type]      [description]
 */
function sql($sql)
{
    $db_config = array();
    $db_config['prefix'] = Config::get('database.prefix');
    $sql_array = preg_split("/;[\r\n]+/", str_replace('my_', $db_config['prefix'], $sql));
    foreach ($sql_array as $k => $v) {
        if (!empty($v)) {
            return Db::query($v);
        }
    }
}
/**
 * [m description]
 * @return [type] [description]
 */
function m()
{
    return '/template/'.muban().'/public';
}
function u()
{
    return '/mifenlei/index/view/public';
}
// 指定字符随机输出1个
function mi_sj($c)
{
    $a = explode(',', $c);
    shuffle($a);
    $b=array_slice($a,0,$n); 
    return $b[0];
}
// 模型数组分割
function json_model($s)
{
    $cars = explode("\n", $s);
    return array_merge($cars);
}
// 获取json值
function json_model_v($s,$v)
{
    $arr = json_decode($s, true);
    return $arr[$v]; 
}
/**
 * 循环删除目录和文件函数
 * @param  [type] $dir_name [description]
 * @return [type]           [description]
 */
function deleteun($dir_name)
{
    $result = false;
    if (is_dir($dir_name)) {
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        deleteun($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }
    return $result;
}
/**
 * 广告简写
 * @param  [type] $id [description]
 * @return [type]     [description]
 */
function ad($id)
{
    $time = time();
    $wanneng = Db::name('ad')->where(array('alias' => muban(), 'tid' => $id))->where("times > {$time}")->select();
    foreach ($wanneng as $html) {
        echo $html['config'];
    }
}
/**
 * 获取model的数据
 * @param  [type] $id [description]
 * @param  [type] $s  [description]
 * @return [type]     [description]
 */
function fun_model($id, $s)
{
    $wanneng = Db::name('model')->where(array('name' => $id))->value($s);
    return $wanneng;
}
function fun_shangjia($id, $s)
{
    $wanneng = Db::name('shangjia')->where(array('id' => $id))->value($s);
    return $wanneng;
}
/**
 * [muban description]
 * @return [type] [description]
 */
function muban()
{
    if (Cookie('muban')) {
        if(is_dir('./template/'.Cookie('muban'))){
            return Cookie('muban');
        } else {
            return 'mifenlei';
        }
    }
    $include = (include 'mifenlei/extra/template.php');
    if (isMobile()!=true) {
        if (jiami($include['name'],'DECODE','mifenlei',0) == set('muban')) {
            if (set('muban')) {
                return set('muban');
            } else {
                return 'mifenlei';
            }
        } else {
            return 'mifenlei';
        }
    } else {
        return jiami($include['wap'],'DECODE','mifenlei',0);
    }
}
/**
 * 获取文件目录列表,该方法返回数组
 * @param  [type] $dir [description]
 * @param  string $id  [description]
 * @return [type]      [description]
 */
function getDir($dir, $id = '')
{
    $dirArray[] = NULL;
    if (!file_exists($dir)) {
        return array();
    }
    if (false != ($handle = opendir($dir))) {
        $i = 0;
        while (false !== ($file = readdir($handle))) {
            if ($id == 1) {
                //去掉"“.”、“..”以及带“.xxx”后缀的文件
                if ($file != "." && $file != ".." && !strpos($file, ".")) {
                    $dirArray[$i] = $file;
                    $i++;
                }
            } else {
                if ($id == 2) {
                    //获取带后缀的文件
                    if (strpos($file, ".")) {
                        $dirArray[$i] = $file;
                        $i++;
                    }
                } else {
                    $dirArray[$i] = $file;
                    $i++;
                }
            }
        }
        //关闭句柄
        closedir($handle);
    }
    return $dirArray;
}
/**
 * 获取模板配置
 * @param  [type] $url [description]
 * @param  [type] $id  [description]
 * @return [type]      [description]
 */
function m_config($url, $id)
{
    $include = (include 'template/' . $url . '/config.php');
    return $include[$id];
}
/**
 * [get_config description]
 * @return [type] [description]
 */
function get_config($mn,$id)
{
    $include = (include 'mifenlei/extra/'.$mn.'.php');
    return $include[$id];

}
/**
 * 获取内容的图片信息
 * @param  [type] $content [description]
 * @param  string $order   [description]
 * @return [type]          [description]
 */
function getImgList($content, $order = 'ALL')
{
    $html_string = htmlspecialchars_decode($content);
    $pattern = "/<[img|IMG].*?src=[\\'|\"](.*?(?:[\\.gif|\\.jpg|\\.png]))[\\'|\"].*?[\\/]?>/";
    preg_match_all($pattern, $html_string, $match);
    if (isset($match[1]) && !empty($match[1])) {
        if ($order === 'ALL') {
            return $match[1];
        }
        if (is_numeric($order) && isset($match[1][$order])) {
            return $match[1][$order];
        }
    }
    return [];
}
/**
 * 提取存文本介绍
 * @param  [type] $content [description]
 * @param  string $cut     [description]
 * @return [type]          [description]
 */
function cut_c($content, $cut = '200')
{
    $content = preg_replace('/\\"/i', '', str_replace(PHP_EOL, '', $content));
    $content = preg_replace("/\\'/i", "", str_replace(PHP_EOL, "", $content));
    $content = preg_replace("/ /", "", $content);
    $content = preg_replace( "/<style[\s\S]*?<\/style>/i", "", $content);
    $content = preg_replace( "/<script[\s\S]*?<\/script>/i", "", $content);
    $content = preg_replace('/\s/','',preg_replace("/[[:punct:]]/",'',strip_tags(html_entity_decode($content,ENT_QUOTES,'UTF-8'))));
    return cut(strip_tags($content), $cut);
}


/**
 * 提取中文
 * @param  [type] $str [description]
 * @return [type]      [description]
 */
function zw($str)
{
    preg_match_all('/[\\x{4e00}-\\x{9fff}]+/u', $str, $matches);
    //把匹配到的数组连接为字符串
    $str = implode('', $matches[0]);
    return $str;
}
/**
 * 获取关键字
 * @param  [type]  $content [description]
 * @param  integer $s       [description]
 * @return [type]           [description]
 */
function ks($content, $s = 20)
{
    return Analysis::getKeywords($content, $s);
}
/**
 * 获取内容作为封面
 * @梦雨50361804
 */
function pic($content = '', $t = '')
{
    $html_string = $content;
    $pattern = "/<[img|IMG].*?src=[\\'|\"](.*?(?:[\\.gif|\\.jpg|\\.png|\\.GIF|\\.JPG|\\.PNG]))[\\'|\"].*?[\\/]?>/";
    preg_match_all($pattern, $html_string, $matchContent);
    if (isset($matchContent[1][0])) {
        $item['news_pic'] = $matchContent[1][0];
    } else {
        if (empty($t)) {
            $item['news_pic'] = '/public/img/default.jpg';
        } else {
            $item['news_pic'] = $t;
        }
    }
    return $item['news_pic'];
}
function jiacs()
{
    $url = preg_replace("/(.*?)\\?/s", "?", $_SERVER['REQUEST_URI']);
    $urlS = preg_replace("/page(.*)/s", "", $url);
    if (strpos($_SERVER['REQUEST_URI'], '?') !== false) {
        if (strpos($_SERVER['REQUEST_URI'], 'page') !== false) {
            return substr($urlS,0,strlen($urlS)-1);
        } else {
            return $urlS;
        }
    } else {
        return ;
    }
}
/**
 * 获取完整URL
 * @return [type] [description]
 */
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;
}
/**
 * 图片检查是否是木马
 * @param  [type] $img [description]
 * @return [type]      [description]
 */
function checkHex($img)
{
    $status = 0;
    //文件没问题
    if (file_exists($img)) {
        $resource = fopen($img, 'rb');
        $fileSize = filesize($img);
        fseek($resource, 0);
        if ($fileSize > 512) {
            // 取头和尾
            $hexCode = bin2hex(fread($resource, 512));
            fseek($resource, $fileSize - 512);
            $hexCode .= bin2hex(fread($resource, 512));
        } else {
            // 取全部
            $hexCode = bin2hex(fread($resource, $fileSize));
        }
        fclose($resource);
        /* 匹配16进制中的 <% ( ) %> */
        /* 匹配16进制中的 <? ( ) ?> */
        /* 匹配16进制中的 <script | /script> 大小写亦可 */
        if (preg_match("/(3c25.*?28.*?29.*?253e)|(3c3f.*?28.*?29.*?3f3e)|(3C534352495054)|(2F5343524950543E)|(3C736372697074)|(2F7363726970743E)/is", $hexCode)) {
            $status = 5;
            //文件有毒
        }
    } else {
        $status = -1;
        //文件没有上传
    }
    return $status;
}
/**
 * 邮件发送
 * @param  [type] $tomail  邮箱
 * @param  string $subject 标题
 * @param  string $body    内容
 * @return [type]          [description]
 */
function send_mail($tomail, $subject = '', $body = '')
{
    $mail = new PHPMailer(true);
    //实例化PHPMailer对象
    $mail->CharSet = 'UTF-8';
    //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();
    // 设定使用SMTP服务
    $mail->SMTPDebug = 0;
    // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
    $mail->SMTPAuth = true;
    // 启用 SMTP 验证功能
    $mail->SMTPSecure = 'ssl';
    // 使用安全协议
    $mail->Host = set('mailHost');
    // SMTP 服务器
    $mail->Port = set('mailPort');
    // SMTP服务器的端口号
    $mail->Username = set('mailUsername');
    // SMTP服务器用户名
    $mail->Password = set('mailPassword');
    // SMTP服务器密码
    $mail->SetFrom('' . set('mailUsername') . '', '' . set('title') . '');
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($tomail);
    return $mail->Send() ? true : $mail->ErrorInfo;
}
// 添加短信记录
function yanzhengma($code, $phone, $content, $fl,$time)
{
    //发送短信
    $data['ma'] = $code;
    $data['phone'] = $phone;
    $data['content'] = $content;
    $data['open'] = 1;
    $data['ip'] = $_SERVER["REMOTE_ADDR"];
    $data['time'] = time();
    $data['fl'] = $fl;
    $data['times'] = $time;
    Db::name('yanzhengma')->insert($data);
}
// 自动登录
if (!Session::get('userid')) {
    if (fun_sc_p(ps('member'), array('key' => Cookie::get('mima')), 'key')) {
        Session::set('userid',fun_sc_p(ps('member'), array('key' =>Cookie::get('mima')), 'userid'));
    }
}
// 验证身份号码是否正确
function is_idcard($id)
{
    $id = strtoupper($id);
    $regx = "/(^\\d{15}\$)|(^\\d{17}([0-9]|X)\$)/";
    $arr_split = array();
    if (!preg_match($regx, $id)) {
        return FALSE;
    }
    if (15 == strlen($id)) {
        //检查15位
        $regx = "/^(\\d{6})+(\\d{2})+(\\d{2})+(\\d{2})+(\\d{3})\$/";
        @preg_match($regx, $id, $arr_split);
        //检查生日日期是否正确
        $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
        if (!strtotime($dtm_birth)) {
            return FALSE;
        } else {
            return TRUE;
        }
    } else {
        //检查18位
        $regx = "/^(\\d{6})+(\\d{4})+(\\d{2})+(\\d{2})+(\\d{3})([0-9]|X)\$/";
        @preg_match($regx, $id, $arr_split);
        $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
        if (!strtotime($dtm_birth)) {
            //检查生日日期是否正确
            return FALSE;
        } else {
            //检验18位身份证的校验码是否正确。
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            $sign = 0;
            for ($i = 0; $i < 17; $i++) {
                $b = (int) $id[$i];
                $w = $arr_int[$i];
                $sign += $b * $w;
            }
            $n = $sign % 11;
            $val_num = $arr_ch[$n];
            if ($val_num != substr($id, 17, 1)) {
                return FALSE;
            } else {
                return TRUE;
            }
        }
    }
}
/**
 * [信息列表专用数据调用]
 * @param  string $array    [条件]
 * @param  string $desc     [排序]
 * @param  string $sl       [显示的数量]
 * @param  string $zd       [要搜索的字段例如jiage-lianjiue]
 * @param  string $ks       [同时搜索的字段]
 * @param  string $shangxia [以上一下的字段]
 * @return [type]           [数据]
 */
function html($array=array() , $desc='settop desc , times desc' , $sl='20', $zd='', $ks = 'title-content-phone-username',$shangxia=''){
    if (isMobile()!=true) {
        $true=false;
    } else {
        $true=true;
    }
    if ($zd) {
        $cars = explode("-", $zd);
        $arrlength = count($cars);
        for ($x = 0; $x < $arrlength; $x++) {
            $data[$cars[$x]] = ['like', '%' . $_GET[$cars[$x]] . '%'];
            $data_1[$cars[$x]] = $_GET[$cars[$x]];
        }
    }
    $ks = preg_replace("/-/","|", $ks);
    $d = Db::name('cate_diqu')->where(array('id' => input('diqu')))->find();
    $data[$ks] = ['like', '%' . input('ks') . '%'];
    if ($shangxia) {
        $cars=explode("-",input($shangxia));
        if (strpos(input($shangxia), '以上') !== false) {
            $data[$shangxia] = ['>', input($shangxia)];
        } elseif(strpos(input($shangxia), '以下') !== false) {
            $data[$shangxia] = ['<', input($shangxia)];
        } else {
            $data[$shangxia] = ['between',''.findNum($cars[0]).','.findNum($cars[1]).''];
        }
        $data_1[$shangxia] = input($shangxia);
    }
    $data_1['ks'] = input('ks');
    if (input('diqu')==0) {
        // 全部
        $data['open']=1;
        if (input('c')) {
            $data['tid']=input('c');
        }
        $html=Db::name(input('m'))
        ->where($data)
        ->where($array)
        ->order($desc)
        ->paginate($sl,$true, ['query' => $data_1]);
    } else {
        // 条件
        $data['f.open']=1;
        if (input('c')) {
            $data['f.tid']=input('c');
        }
        $html=Db::name(input('m'))
        ->alias('f')
        ->join('cate_diqu'.' c', 'c.id=f.sid')
        ->field('f.*,c.id as cid')
        ->where($data)
        ->where($array)
        ->where("c.tid=".$d['id']." or f.sid=".$d['id'])
        ->order($desc)
        ->paginate($sl,$true, ['query' => $data_1]);
    }
    return $html;
}
/**
 * [shangjia description]
 * @param  array  $array [条件]
 * @param  string $desc  [排序]
 * @param  string $sl    [数量]
 * @param  string $ks    [搜索的字段]
 * @return [type]        [description]
 */
function shangjia($array=array() , $desc='settop desc , times desc' , $sl='20', $ks = 'title-dizhi-phone'){
    if (isMobile()!=true) {
        $true=false;
    } else {
        $true=true;
    }
    $ks = preg_replace("/-/","|", $ks);
    $d = Db::name('cate_diqu')->where(array('id' => input('diqu')))->find();
    $data[$ks] = ['like', '%' . input('ks') . '%'];
    $data_1['ks'] = input('ks');
    if (input('c')) {
        $c = Db::name('cate_shangjia')->where(array('id' => input('c')))->find();
    } 
    if (input('diqu')) {
        $d = Db::name('cate_diqu')->where(array('id' => input('diqu')))->find();
    } 
    if (input('diqu') && input('c')) {
        // 全部条件
        $data['f.open']=1;
        $html=Db::name('shangjia') 
        ->alias('f')
        ->join('cate_diqu'.' c', 'c.id=f.sid')
        ->join('cate_shangjia'.' t', 't.id=f.tid')
        ->field('f.*')
        ->where($data)
        ->where($array)
        ->where("c.tid=".$d['id']." or f.sid=".$d['id'])
        ->where("t.tid=".$c['id']." or f.tid=".$c['id'])
        ->order($desc)
        ->paginate($sl,$trut, ['query' => $data_1]);
    } elseif(input('diqu')) {
        // 条件地区
        $data['f.open']=1;
        $html=Db::name('shangjia') 
        ->alias('f')
        ->join('cate_diqu'.' c', 'c.id=f.sid')
        ->field('f.*')
        ->where($data)
        ->where($array)
        ->where("c.tid=".$d['id']." or f.sid=".$d['id'])
        ->order($desc)
        ->paginate($sl,$true, ['query' => $data_1]);
    } elseif(input('c')) {
        // 条件分类
        $data['f.open']=1;
        $html=Db::name('shangjia') 
        ->alias('f')
        ->join('cate_shangjia'.' t', 't.id=f.tid')
        ->field('f.*')
        ->where($data)
        ->where($array)
        ->where("t.tid=".$c['id']." or f.tid=".$c['id'])
        ->order($desc)
        ->paginate($sl,$true, ['query' => $data_1]);

    } else {
        // 全部
        $data['open']=1;
        $html=Db::name('shangjia')
        ->where($data)
        ->where($array)
        ->order($desc)
        ->paginate($sl,$true, ['query' => $data_1]);
    }
    return $html;
}
/**
 * [info description]
 * @param  array  $array [description]
 * @param  string $desc  [description]
 * @param  string $sl    [description]
 * @param  string $ks    [description]
 * @return [type]        [description]
 */
function info($array=array() , $desc='settop desc , times desc' , $sl='20', $ks = 'title'){
    if (isMobile()!=true) {
        $true=false;
    } else {
        $true=true;
    }
    if (input('alias')) {
        $c = Db::name('cate')->where(array('alias' => input('alias')))->find();
    } 
    $ks = preg_replace("/-/","|", $ks);
    $data[$ks] = ['like', '%' . input('ks') . '%'];
    $data_1['ks'] = input('ks');
    if (input('alias')) {
        // 条件
        $data['f.open']=1;
        $html=Db::name('article') 
        ->alias('f')
        ->join('cate'.' t', 't.id=f.tid')
        ->field('f.*')
        ->where($data)
        ->where($array)
        ->where("t.tid=".$c['id']." or f.tid=".$c['id'])
        ->order($desc)
        ->paginate($sl,$true, ['query' => $data_1]);

    } else {
        // 全部
        $data['open']=1;
        $html=Db::name('article')
        ->where($data)
        ->where($array)
        ->order($desc)
        ->paginate($sl,$true, ['query' => $data_1]);
    }
    return $html;
}

/**
* 目录列表
* 
* @param   string $dir      路径
* @param   int       $parentid  父id
* @param   array  $dirs     传入的目录
* @return  array  返回目录列表
*/
function dir_tree($dir, $parentid = 0, $dirs = array())
{
    global $id;
    if ($parentid == 0) {
        $id = 0;
    }
    $list = glob($dir . '*');
    foreach ($list as $v) {
        if (is_dir($v)) {
            $id++;
            $dirs[$id] = array('id' => $id, 'parentid' => $parentid, 'name' => basename($v), 'dir' => $v . '/');
            // $dirs = dir_tree($v . '/', $id, $dirs);
        }
    }
    return $dirs;
}
/**
 * 删除文件及文件下方的文件
 * $dir 地址
 */
function deldir($dir)
{
    //先删除目录下的文件：
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {
            $fullpath = $dir . "/" . $file;
            if (!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                deldir($fullpath);
            }
        }
    }
    closedir($dh);
    //删除当前文件夹：
    if (rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}
/**
 * 二维数组根据某个字段排序
 * @param array $array 要排序的数组
 * @param string $keys   要排序的键字段
 * @param string $sort  排序类型  SORT_ASC     SORT_DESC 
 * @return array 排序后的数组
 */
function arraySort($array, $keys, $sort = SORT_DESC)
{
    $last_names = array_column($array, $keys);
    array_multisort($last_names, $sort, $array);
    return $array;
}
/**
 * 查询所有模型数据
 * @param  integer $getdata  1是默认数据 其他是分页数据
 * @param  integer $where 条件
 * @param  integer $page  每页显示的数量
 * @param  string  $field 显示的字段
 * @param  string  $keys  排序的字段
 * @param  [type]  $sort  排序类型  SORT_ASC     SORT_DESC 
 * @return [type]         [description] 1,'open=1',10,'id,title,model,tid,times,time,uid,view,zan,pic','view'
 */
function quanbu($getdata = 1, $where = 'open=1', $page = 20, $field = 'id,title,tid,times,time,uid,view,sid,settop,m', $keys = 'times', $sort = SORT_DESC)
{
    $wanneng = Db::name('model')->where('open', 1)->select();
 
    foreach ($wanneng as $html) {
        $sql .= $union_all . "(select {$field} from my_{$html['name']} where {$where} order by {$keys} )";
        $union_all = " UNION ALL ";
    }
    if (get('pages', 1) == 1) {
        $p = '0';
    } else {
        $p = (get('pages', 0) - 1) * $page;
    }
    $data = arraySort(sql($sql), $keys, $sort);
    if ($getdata == 1) {
        $da = array_slice($data, 0, $page);
        return dingyi($da, array());
    } elseif ($getdata == 2) {
        $da = array_slice($data, $p, $page);
        return dingyi($da, array());
    } else {
        $da = array_slice($data, $p, $page);
        return array('count' => count($data), 'show' => $page, 'data' => $da);
    }
}
/**
 * 自动显示分页
 * @param  [type] $data page_close数据
 * @param  string $show 是否显示统计
 * @return [type]       [description]
 */
function page($data, $show = '')
{
    $count = $data['count'];
    //记录总条数
    @($page_size = $data['show']);
    //每页显示条数
    @($page_all = ceil($count / $page_size));
    //总页数
    @($page = $_GET['pages'] ? $_GET['pages'] : 1);
    //当前页数
    @($page_up = $page - 1 > 1 ? $page - 1 : 1);
    //上一页
    @($page_next = $page + 1 > $page_all ? $page_all : $page + 1);
    //下一页
    @($key = ($page - 1) * $page_size);
    if (empty(strpos(get_url(), '?'))) {
        $url = get_url() . '?pages';
    } else {
        if (empty($_GET['pages'])) {
            $url = get_url() . '&pages';
        } else {
            $url = preg_replace("/pages(.*)/is", "pages", get_url());
        }
    }
    echo '<style> .page {padding-top: 10px;}.page a {padding: 5px 8px;margin: 0 8px 8px 0;display: inline-block; background: #f1f1f1;color: #444;font-size: 12px; border-radius: 2px;text-decoration: none;}</style>';
    if ($show == 1) {
        @($page_next = $page + 1);
        //下一页
        echo "<div align='center' class='page'><a \r\n\r\nhref='" . $url . "=1'>首页 </a><a href='" . $url . "=\r\n\r\n{$page_up}'> 上一页 </a><a href='" . $url . "={$page_next}\r\n\r\n'> 下一页 </a></div>";
    } else {
        if ($count == 0) {
            return;
        }
        if ($page_all != 1 && !empty($data)) {
            echo "<div align='center' class='page'><a \r\n\r\nhref='" . $url . "=1'>首页 </a><a href='" . $url . "=\r\n\r\n{$page_up}'> 上一页 </a><a href='" . $url . "={$page_next}\r\n\r\n'> 下一页 </a><a \r\n\r\nhref='" . $url . "={$page_all}'>尾页</a><span> 第 {$page}/{$page_all}页 </span></div>";
        }
    }
}


// 非伪静态跳转
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));
        }
    }
}
 /**
 * 格式化数字
 */
function float_number($number){
    $length = strlen($number);  //数字长度
    if($length > 8){ //亿单位
        $str = substr_replace(strstr($number,substr($number,-7),' '),'.',-1,0)."亿";
    }elseif($length >4){ //万单位
        //截取前俩为
        $str = substr_replace(strstr($number,substr($number,-3),' '),'.',-1,0)."万";
    }else{
        return $number;
    }
    return $str;
}
// 统计所有模型的浏览量DE和
function model_he($where = 'open>0',$field = 'view', $keys = 'view', $sort = SORT_DESC)
{
    $wanneng = Db::name('model')->where('open', 1)->select();
    foreach ($wanneng as $html) {
        $sql .= $union_all . "(select {$field} from my_{$html['name']} where {$where} order by {$keys} )";
        $union_all = " UNION ALL ";
    }
    $data = array_sum(array_map(create_function('$val', 'return $val["view"];'), sql($sql)));
    return $data;
}