<?php
use think\Db;
use think\Request;
use PHPMailer\PHPMailer;
use Think\Config;
use QL\QueryList;
use org\Http;
use WordAnalysis\Analysis;
use app\index\Hook;
use think\Hook as thinkHook;
// 应用公共文件
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021 http://115cms.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 作者@梦雨 <50361804@qq.com>
// +----------------------------------------------------------------------
error_reporting(E_ERROR | E_PARSE);
/**
 * 钩子名称
 */
function hook($name , $array = array())
{
    $cars = explode(',', fun_sc_p('hook', array('name'=>$name), 'addons'));
    $arrlength=count($cars);
    for($x=0;$x<$arrlength;$x++)
    {
        Hook::call($cars[$x], $name ,$array);
    }
}
/**
 * 输出插件配置值 $name=插件标识 $s=配置的值
 * @param  [type] $u [description]
 * @param  [type] $s [description]
 * @return [type]    [description]
 */
function addons($u, $s)
{
    $c = fun_sc_p('addons', array('name' => $u), 'config');
    $arr = json_decode($c, true);
    return $arr[$s];
}
/**
 * 获取数据表前缀
 * @return [type] [description]
 */
function prefix()
{
    $s = (include 'app/database.php');
    return $s['prefix'];
}
/**
 * 过滤
 * @param  [type] $html [description]
 * @return [type]       [description]
 */
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;
}
/**
 * 过滤
 * @param  [type] $val [description]
 * @return [type]      [description]
 */
function remove_xss($val)
{
    $val = preg_replace('/([\\x00-\\x08,\\x0b-\\x0c,\\x0e-\\x19])/', '', $val);
    $search = 'abcdefghijklmnopqrstuvwxyz';
    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $search .= '1234567890!@#$%^&*()';
    $search .= '~`";:?+/={}[]-_|\'\\';
    for ($i = 0; $i < strlen($search); $i++) {
        $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val);
        // with a ;
        $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val);
        // with a ;
    }
    $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
    $ra2 = 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');
    $ra = array_merge($ra1, $ra2);
    $found = true;
    while ($found == true) {
        $val_before = $val;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = '/';
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= '(';
                    $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                    $pattern .= '|';
                    $pattern .= '|(&#0{0,8}([9|10|13]);)';
                    $pattern .= ')*';
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= '/i';
            $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2);
            $val = preg_replace($pattern, $replacement, $val);
            if ($val_before == $val) {
                $found = false;
            }
        }
    }
    return $val;
}
/**
 * [getUserInfo description]
 * @param  Request $request [description]
 * @param  [type]  $userId  [description]
 * @return [type]           [description]
 */
function getUserInfo(Request $request, $userId)
{
    // 根据$userId获取用户信息
    return $info;
}
/**
 * 时间戳转换
 * @param  [type] $sTime [description]
 * @param  string $type  [description]
 * @param  string $alt   [description]
 * @return [type]        [description]
 */
function times($sTime, $type = '1', $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 == '1') {
        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 == '2') {
        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 == '3') {
        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);
        }
    }
}
/**
 * 万能输出字段数据
 * @param  [type] $set  [description]
 * @param  [type] $open [description]
 * @param  [type] $s    [description]
 * @return [type]       [description]
 */
function fun_sc_p($set, $open, $s)
{
    $wanneng = Db::name($set)->where($open)->value($s);
    return $wanneng;
}
/**
 * 获取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;
}
/**
 * 获取cate的数据
 * @param  [type] $id [description]
 * @param  [type] $s  [description]
 * @return [type]     [description]
 */
function fun_cate($id, $s)
{
    $wanneng = Db::name('cate')->where(array('id' => $id))->value($s);
    return $wanneng;
}
/**
 * 获取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;
}
/**
 * 万能统计
 * @param  [type] $set [description]
 * @param  [type] $x   [description]
 * @return [type]      [description]
 */
function fun_st($set, $x)
{
    $wanneng = Db::name($set)->strict(false)->where($x)->count();
    return $wanneng;
}
/**
 * 万能输出数据
 * @param  [type] $set  [description]
 * @param  [type] $open [description]
 * @param  [type] $s    [description]
 * @param  [type] $x    [description]
 * @param  [type] $f    [description]
 * @return [type]       [description]
 */
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;
    }
}
/**
 * 万能输出数据
 * @param  [type] $set [description]
 * @param  [type] $s   [description]
 * @param  [type] $xs  [description]
 * @param  [type] $o   [description]
 * @return [type]      [description]
 */
function fun_sa($set, $s, $xs, $o)
{
    if (!empty(ArrayOr())) {
        $cars = array_keys(ArrayOr());
        $arrlength = count($cars);
        for ($x = 0; $x < $arrlength; $x++) {
            $data[$cars[$x]] = ['like', '%' . $_GET[$cars[$x]] . '%'];
        }
    }
    $data['open'] = 1;
    $wanneng = Db::name($set)->where($data)->order('' . $s . '')->failException(false)->paginate($xs, $o, ['query' => ArrayOr()]);
    return $wanneng;
}
/**
 * 提取数字
 * @param  string $str [description]
 * @return [type]      [description]
 */
function findNum($str = '')
{
    $str = trim($str);
    if (empty($str)) {
        return '';
    }
    $temp = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
    $result = '';
    for ($i = 0; $i < strlen($str); $i++) {
        if (in_array($str[$i], $temp)) {
            $result .= $str[$i];
        }
    }
    return $result;
}
/**
 * 查询
 * @param  [type] $set   表
 * @param  [type] $array 条件
 * @param  [type] $s     排序方式
 * @param  [type] $xs    悬赏的数据
 * @param  [type] $o     false或者真true
 * @param  string $guoji 搜索的分类,隔开
 * @param  string $sx    搜索区间字段
 * @param  string $ks    搜索的字段
 * @return [type]        [description]
 */
function fun_sw($set, $array, $s, $xs, $o, $guoji = '', $sx = '', $ks = 'title|content')
{
    $data[$ks] = ['like', '%' . input('title') . '%'];
    $arr = explode(',', $guoji);
    for ($i = 0; $i < count($arr); $i++) {
        $data[$arr[$i]] = ['=', $arr[$i]];
        $data_1[$arr[$i]] = $arr[$i];
    }
    if ($sx) {
        $cars = explode("-", $sx);
        if (strpos($sx, '以上') !== false) {
            $data['rmb'] = ['>', $sx];
        } elseif (strpos($sx, '以下') !== false) {
            $data['rmb'] = ['<', $sx];
        } else {
            $data['rmb'] = ['between', '' . findNum($cars[0]) . ',' . findNum($cars[1]) . ''];
        }
    }
    $data['open'] = 1;
    $wanneng = Db::name($set)->where($data)->where($array)->order('' . $s . '')->failException(false)->paginate($xs, $o, ['query' => $data_1]);
    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;
    }
}
/**
 * 上月 本月近15天近30天数据
 * @param  [type] $set  [description]
 * @param  [type] $open [description]
 * @param  [type] $d    [description]
 * @param  [type] $x    [description]
 * @param  [type] $s    [description]
 * @param  [type] $o    [description]
 * @return [type]       [description]
 */
function fun_sdx($set, $open, $d, $x, $s, $o)
{
    $wanneng = Db::name($set)->where($open)->where("time > {$d} and time < {$x}")->order('' . $s . '')->limit($o)->select();
    return $wanneng;
}
/**
 * 过滤任何标签
 * @param  [type] $str [description]
 * @return [type]      [description]
 */
function pre($str)
{
    $new = preg_replace("/<.*?>|<\\/>/is", "", $str);
    return $new;
}
/**
 * 随机获取数组
 * @param  [type] $ks [description]
 * @return [type]     [description]
 */
function sjsz($ks)
{
    $a = explode(",", $ks);
    $key = array_rand($a, 1);
    return $a[$key];
}
/**
 * 获取参数
 * @param  [type]  $input [description]
 * @param  integer $id    [description]
 * @return [type]         [description]
 */
function get($input, $id = 1)
{
    if (is_numeric(input($input)) === true || !empty(input($input))) {
        return pre(input($input));
    } else {
        return $id;
    }
}
/**
 * 获取配置信息
 * @param [type]  参数名
 * @param integer $id 配置id
 */
function set($s, $id = 1)
{
    $c = fun_sc_p('set', array('id' => $id), 'config');
    $arr = json_decode($c, true);
    return $arr[$s];
}
define('CMS', set('sq'));
/**
 * http协议自动判断
 * @return [type] [description]
 */
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
 * @param  [type] $filesize [description]
 * @return [type]           [description]
 */
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;
}
/**
 * 自定义数据分割
 * @param  [type] $ks [description]
 * @param  [type] $mu [description]
 * @param  [type] $my [description]
 * @return [type]     [description]
 */
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;
}
/**
 * 自定义数据分割
 * @param  [type] $ks [description]
 * @param  [type] $k  [description]
 * @return [type]     [description]
 */
function ex($ks, $k)
{
    $a = explode($k, $ks);
    return $a;
}
/**
 * 查询商城分类是否存在
 * @param  [type] $k [description]
 * @return [type]    [description]
 */
function cate($k)
{
    $wanneng = Db::name('cate')->where(array('alias' => $k))->count();
    if ($wanneng > 0) {
        return $k;
    } else {
        return 0;
    }
}
/**
 * 输出默认值
 * @param  [type] $k    [description]
 * @param  string $open [description]
 * @return [type]       [description]
 */
function ok($k, $open = 'ok')
{
    if (empty($k)) {
        return $open;
    } else {
        return $k;
    }
}
/**
 * 随机数据
 * @param  [type] $set  [description]
 * @param  [type] $open [description]
 * @param  [type] $x    [description]
 * @return [type]       [description]
 */
function fun_sj($set, $open, $x)
{
    $wanneng = Db::name($set)->where($open)->orderRaw('rand()')->limit($x)->select();
    return $wanneng;
}
/**
 * 随机栏目下推荐
 * @param  [type] $set  [description]
 * @param  [type] $open [description]
 * @param  [type] $a    [description]
 * @param  [type] $x    [description]
 * @return [type]       [description]
 */
function fun_sj_id($set, $open, $a, $x)
{
    $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}")->orderRaw('rand()')->limit($x)->select();
    return $wanneng;
}
/**
 * 判断当前浏览器标识
 * @return boolean [description]
 */
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;
        }
    }
}
/**
 * 用于生成用户密码的随机字符
 * @param  integer $length [description]
 * @return [type]          [description]
 */
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;
}
/**
 * 生成订单号
 * @param  integer $length [description]
 * @return [type]          [description]
 */
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')));
}
/**
 * 查询某一时间段统计
 * @param  [type] $set [description]
 * @param  [type] $d   [description]
 * @param  [type] $da  [description]
 * @param  [type] $x   [description]
 * @param  [type] $xa  [description]
 * @param  [type] $s   [description]
 * @return [type]      [description]
 */
function fun_tj($set, $d, $da, $x, $xa, $s)
{
    $wanneng = Db::name($set)->where("{$d} > {$da} and {$x} < {$xa}")->where($s)->count();
    return $wanneng;
}
/**
 * 用于数组中搜索键值
 * @param  [type] $l [description]
 * @param  [type] $s [description]
 * @return [type]    [description]
 */
function socha($l, $s)
{
    $arr = explode(',', '' . $l . '');
    if (strlen(array_search($s, $arr)) >= 1) {
        return 1;
    } else {
        return 0;
    }
}
/**
 * 数组遍历
 * @param  [type] $sku [description]
 * @return [type]      [description]
 */
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;
}
/**
 * 积分加减记录
 * @param  [type]  $jifen 积分
 * @param  [type]  $uid   用户id
 * @param  [type]  $title 命名
 * @param  integer $tid   上级
 * @return [type]         [description]
 */
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'] = '登录';
            $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;
}
/**
 * 支付宝配置
 * @param  [type] $para [description]
 * @return [type]       [description]
 */
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;
}
/**
 * [ps description]
 * @param  [type] $s  [description]
 * @param  [type] $lu [description]
 * @return [type]     [description]
 */
function ps($s, $lu = CMS)
{
    $strs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
    $txt = urldecode($lu);
    $ch = $txt[0];
    $nh = strpos($strs, $ch);
    $mdKey = md5('gj' . $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];
    }
    $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{
        return $s;
    }
}
/**
 * [getbaseurl description]
 * @return [type] [description]
 */
function getbaseurl()
{
    $baseUrl = str_replace('\\', '', dirname($_SERVER['SCRIPT_NAME']));
    $baseUrl = empty($baseUrl) ? '/' : '/' . trim($baseUrl, '/') . '/';
    return $baseUrl;
}
/**
 * [argSort description]
 * @param  [type] $para [description]
 * @return [type]       [description]
 */
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;
}

/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
* @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);
}
/**
 * [md5Verify description]
 * @param  [type] $prestr [description]
 * @param  [type] $sign   [description]
 * @param  [type] $key    [description]
 * @return [type]         [description]
 */
function md5Verify($prestr, $sign, $key)
{
    $prestr = $prestr . $key;
    $mysgin = md5($prestr);
    if ($mysgin == $sign) {
        return true;
    } else {
        return false;
    }
}
/**
 * 远程获取数据，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;
}
/**
 * 发送短信
 * @param  [type] $phone   电话号码
 * @param  [type] $content 内容
 * @return [type]          [description]
 */
function duanxin($phone, $content)
{
    if (!preg_match("/^1[34578]{1}\\d{9}\$/", $phone)) {
        exit('{"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) {
        exit('{"code":0,"msg":"' . $statusStr[$result] . '"}');
    }
}
/**
 * 获自己的会员资料信息
 * @param  [type] $key [description]
 * @return [type]      [description]
 */
function user($key)
{
    return fun_sc_p(ps('member'), array('userid' => session('userid')), $key);
}
/**
 * 验证邮箱
 * @param  [type]  $email [description]
 * @return boolean        [description]
 */
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)
{
    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;
}
/**
 * 随机颜色
 * @param  string $t [description]
 * @return [type]    [description]
 */
function color($t = '')
{
    $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)] . $t;
    return $color;
}
/**
 * 显示文字控制
 * @param  [type] $sourcestr [description]
 * @param  [type] $cutlength [description]
 * @return [type]            [description]
 */
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;
}
/**
 * 提取存文本介绍
 * @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);
    return cut(strip_tags($content), $cut);
}
/**
 * [getFile description]
 * @param  [type]  $url      [description]
 * @param  string  $save_dir [description]
 * @param  string  $filename [description]
 * @param  integer $type     [description]
 * @return [type]            [description]
 */
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
 * @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;
}
/**
 * 非伪静态跳转
 */
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));
        }
    }
}
/**
 * 获取内容作为封面
 * @梦雨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)) {
            $arr = explode(',', set('rand', 1));
            $rand = array_rand($arr, 1);
            $item['news_pic'] = '' . http() . '' . $_SERVER['HTTP_HOST'] . '/public/img/cover/' . $rand . '.jpg';
        } else {
            $item['news_pic'] = $t;
        }
    }
    return $item['news_pic'];
}
/**
 * 获取内容纯文本
 * @param  [type] $str [description]
 * @return [type]      [description]
 */
function htmltext($str)
{
    $str = preg_replace("/<style .*?<\\/style>/is", "", $str);
    $str = preg_replace("/<script .*?<\\/script>/is", "", $str);
    $str = preg_replace("/<p .*?<\\/p>/is", "", $str);
    $str = preg_replace("/<br \\s*\\/>/i", "", $str);
    $str = preg_replace("/<\\/?p>/i", "", $str);
    $str = preg_replace("/<\\/?td>/i", "", $str);
    $str = preg_replace("/<\\/?div>/i", "", $str);
    $str = preg_replace("/<\\/?ul>/i", "", $str);
    $str = preg_replace("/<\\/?span>/i", "", $str);
    $str = preg_replace("/<\\/?li>/i", "", $str);
    $str = preg_replace("/ /i", " ", $str);
    $str = preg_replace("/ /i", " ", $str);
    $str = preg_replace("/&/i", "&", $str);
    $str = preg_replace("/&/i", "&", $str);
    $str = preg_replace("/</i", "<", $str);
    $str = preg_replace("/</i", "<", $str);
    $str = preg_replace("/“/i", '"', $str);
    $str = preg_replace("/&ldquo/i", '"', $str);
    $str = preg_replace("/‘/i", "'", $str);
    $str = preg_replace("/&lsquo/i", "'", $str);
    $str = preg_replace("/'/i", "'", $str);
    $str = preg_replace("/&rsquo/i", "'", $str);
    $str = preg_replace("/>/i", ">", $str);
    $str = preg_replace("/>/i", ">", $str);
    $str = preg_replace("/”/i", '"', $str);
    $str = preg_replace("/&rdquo/i", '"', $str);
    $str = strip_tags($str);
    $str = html_entity_decode($str, ENT_QUOTES, "utf-8");
    $str = preg_replace("/&#.*?;/i", "", $str);
    return $str;
}
/**
 * 获取内容的图片信息
 * @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] $ks [description]
 * @return [type]     [description]
 */
function exps($ks)
{
    $a = explode(",", $ks);
    return $a;
}
/**
 * 邮件发送
 * @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;
}
/**
 * [fun_a description]
 * @param  [type] $v [description]
 * @param  [type] $s [description]
 * @return [type]    [description]
 */
function fun_a($v, $s)
{
    $wanneng = Db::name('html')->where(array('id' => $v))->value($s);
    return $wanneng;
}
/**
 * 相关数据查询
 * @param  [type] $set [description]
 * @param  [type] $so  [description]
 * @param  [type] $ks  [description]
 * @param  [type] $map [description]
 * @param  [type] $x   [description]
 * @return [type]      [description]
 */
function fun_ks($set, $so, $ks, $map, $x)
{
    $data[$so] = ['like', '%' . $ks . '%'];
    $wanneng = Db::name($set)->where($data)->where($map)->orderRaw('rand()')->limit($x)->select();
    return $wanneng;
}
/**
$code 状态码
$count 数量
$message 提示信息
$data 数据
*/
function getjson($code, $count, $message = '', $data = array())
{
    if (!is_numeric($code)) {
        return '';
    }
    $result = array('code' => $code, 'msg' => $message, 'data' => $data);
    echo json_encode($result);
    exit;
}
/*
输出用户数据
$uid==用户
$s==字段数据
*/
function fun_u($uid, $s)
{
    $wanneng = Db::name('member')->where(array('userid' => $uid))->value($s);
    return $wanneng;
}
/**
 * 消息记录xiaoxi
 * @param  [type] $uid     用户id
 * @param  [type] $cid     发送给
 * @param  [type] $content 内容
 * @return [type]          [description]
 */
function xiaoxi($uid, $cid, $content)
{
    $data['uid'] = $uid;
    //用户
    $data['cid'] = $cid;
    //类别
    $data['open'] = 0;
    $data['content'] = $content;
    $_data['uid'] = $uid;
    //用户
    $_data['cid'] = $cid;
    //类别
    $_data['open'] = 0;
    $_data['content'] = $content;
    $_data['times'] = time();
    //查询是否存在数据 存在就更新不存在添加
    if ($wanneng = Db::name('xiaoxi')->where($data)->count() != 0) {
        //存在更新
        Db::name('xiaoxi')->where($data)->update($_data);
    } else {
        //不存在添加
        $_data['time'] = time();
        Db::name('xiaoxi')->data($_data)->insert();
    }
}
/*
自定义数据分割例如
{volist name=":vo($c.content,PHP_EOL,'$')" id="v"}
{$v.id}-{$v.name}<br>
{/volist}
*/
function vo($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]['urls'] = $i;
    }
    return $chaxun;
}
/**
 * [guoji_vo description]
 * @param  [type] $ks [description]
 * @return [type]     [description]
 */
function guoji_vo($ks)
{
    $arr = explode('|', $ks);
    for ($i = 0; $i < count($arr); $i++) {
        $arr2 = explode(',', $arr[$i]);
        $chaxun[$i]['id'] = $arr2[0];
        $chaxun[$i]['name'] = $arr2[1];
    }
    return $chaxun;
}
/**
 * [expz description]
 * @param  [type] $ks [description]
 * @param  [type] $k  [description]
 * @return [type]     [description]
 */
function expz($ks, $k)
{
    $a = explode($k, $ks);
    return $a;
}
/**
 * 格式化数字
 */
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;
}
/**
 * [ArrayOr description]
 */
function ArrayOr()
{
    $url = preg_replace("/(.*?)\\?/s", "", $_SERVER['REQUEST_URI']);
    $urlS = preg_replace("/page(.*)/s", "", $url);
    $check = strpos($urlS, '=');
    if ($check !== false) {
        parse_str($urlS, $get);
        return $get;
    } else {
    }
}
/**
 * 当数据为空定义的显示数据
 * @param  [type] $s 要显示的数据
 * @param  string $v 数据为空显示的自定义数据
 * @return [type]    [description]
 */
function dingyi($s, $v = '1')
{
    if (empty($s)) {
        return $v;
    } else {
        return $s;
    }
}
/**
 * 判断输入的是否是网址
 * @param  [type] $url [description]
 * @return [type]      [description]
 */
function check_url($url)
{
    //  if(!preg_match('/http:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$url)){
    if (!preg_match('/\\.[\\w.]+[\\w\\/]*[\\w.]*\\??[\\w=&\\+\\%]*/is', $url)) {
        return false;
    }
    return true;
}
/**
 * 二维数组根据某个字段排序
 * @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;
}
/**
 * 执行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);
        }
    }
}
/**
 * 查询所有模型数据
 * @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 page_close($m, $getdata = 1, $where = 'open=1', $page = 10, $field = 'id,title,tid,times,time,uid,view', $keys = 'id', $sort = SORT_DESC)
{
    $cars = explode(',', $m);
    $arrlength = count($cars);
    for ($x = 0; $x < $arrlength; $x++) {
        $sql .= $union_all . "(select {$field} from my_{$cars[$x]} 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>";
        }
    }
}
/**
 * 提取中文
 * @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 = 10)
{
    return Analysis::getKeywords($content, $s);
}
/**
 * 任意获取页面数据
 * @param [type] $url  获取的链接
 * @param [type] $id   选择器 class 和id的容器
 * @param [type] $pr1   需要替换的字符
 * @param [type] $pr2   替换成的字符
 * @param string $html 获取页面的类型 html是包含标签 text是纯文本 href是链接 src是图片地址
 */
function Query($url, $id, $html = 'html', $pr1 = '', $pr2 = '')
{
    $rules = array('html' => array($id, $html));
    $data = QueryList::Query($url, $rules)->data;
    if (!$pr1) {
        return $data[0]['html'];
    } else {
        return preg_replace(explode("|", $pr1), explode("|", $pr2), $data[0]['html']);
    }
}
/**
 * 内容图片本地化
 * @param  [type] $content [description]
 * @return [type]          [description]
 */
function getCurContent($content)
{
    //匹配图片地址
    preg_match_all('/(http.+\\.(jpg|gif|bmp|bnp|png))/i', $content, $img_array);
    //移除重复的Url
    $img_array = array_unique($img_array[0]);
    if ($img_array != '') {
        $imgUrl = DS . 'uploads' . DS . date("Ymd") . DS;
        $imgPath = ROOT_PATH . $imgUrl;
        $htd = new Http();
        foreach ($img_array as $key => $value) {
            //获取hash
            $md5 = strtolower($htd->getHash($value, true));
            $filemode = Db::name('file');
            $n = $filemode->where('md5', $md5)->find();
            $realpath = '';
            if (empty($n)) {
                $itype = substr(strrchr($value, '.'), 1);
                $milliSecondN = md5(microtime(true));
                $rndFileName = $imgPath . $milliSecondN . '.' . $itype;
                $fileurl = $imgUrl . $milliSecondN . '.' . $itype;
                $rs = $htd->http_down($value, $rndFileName);
                //抓取成功
                if ($rs) {
                    $path = str_replace("\\", "/", $fileurl);
                    $realpath = WEB_URL . $path;
                    //写入数据库
                    $data['sha1'] = sha1($rndFileName);
                    $data['md5'] = md5($rndFileName);
                    $data['create_time'] = time();
                    $data['size'] = filesize($rndFileName);
                    $data['name'] = $milliSecondN . '.' . $itype;
                    $data['ext'] = $itype;
                    $data['uid'] = 1;
                    $data['savepath'] = $realpath;
                    $data['savename'] = $milliSecondN . '.' . $itype;
                    Db::name('file')->insert($data);
                }
            } else {
                $realpath = $n['savepath'];
            }
            $content = str_replace($value, $realpath, $content);
        }
    }
    return $content;
}
/**
 * 获取文件目录列表,该方法返回数组
 * @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   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;
}
/**
 * 获取当前启动的路径
 * @param  [type] $dir [description]
 * @return [type]      [description]
 */
function get_tpl($dir)
{
    return APP_PATH.$dir;
}
/**
 * 获取插件基本信息
 * @param  [type] $info [description]
 * @param  [type] $id   [description]
 * @return [type]       [description]
 */
function h_config($info, $id)
{
    $class='app\\'.$info.'\\'.$info;
    $addons = new $class();
    $config = $addons->info;
    return $config[$id];
}
/**
 * 获取插件的配置数据信息
 * @param  [type] $info [description]
 * @return [type]       [description]
 */
function admin_config($info)
{
    $class='app\\'.$info.'\\'.$info;
    $addons = new $class();
    $config = $addons->admin;
    return $config;
}
/**
 * 获取插件的配置详情数据
 * @param  [type] $info [description]
 * @param  [type] $id   [description]
 * @return [type]       [description]
 */
function a_config($info, $id)
{
    $class='app\\'.$info.'\\'.$info;
    $addons = new $class();
    $config = $addons->admin;
    return $config[$id];
}
/**
 * 获取模板配置
 * @param  [type] $url [description]
 * @param  [type] $id  [description]
 * @return [type]      [description]
 */
function m_config($url, $id)
{
    $include = (include 'app/template/' . $url . '/config.php');
    return $include[$id];
}
/**
 * 获取当前模板自定义路由
 * @return [type] [description]
 */
function mbny()
{
    $s = (include 'app/template/' . config('template.name') . '/config.php');
    $a = explode(",", $s['route']);
    return $a;
}
/**
 * [muban description]
 * @return [type] [description]
 */
function muban()
{
    if (Cookie('muban')) {
        if(is_dir('./app/template/'.Cookie('muban'))){
            return Cookie('muban');
        } else {
            return 'guojicms';
        }
    }
    $include = (include 'app/extra/template.php');
    if (isMobile()!=true) {
        if (jiami($include['name'],'DECODE','guojicms',0) == set('muban')) {
            return set('muban');
        } else {
            return 'guojicms';
        }
    } else {
        return jiami($include['wap'],'DECODE','guojicms',0);
    }
}
/**
 * [get_config description]
 * @return [type] [description]
 */
function get_config($mn,$id)
{
    $include = (include 'app/extra/'.$mn.'.php');
    return $include[$id];

}
/**
 * [m description]
 * @return [type] [description]
 */
function m()
{
    return '/app/template/'.muban().'/public';
}
/**
 * 获取当前模板的设置信息set.html
 * @param  [type] $name [description]
 * @return [type]       [description]
 */
function guoji($name)
{
    $url = file_get_contents('app/template/' . muban() . '/set.txt');
    $arr = json_decode($url, true);
    return $arr[$name];
}
/**
 * 获取任意模板配置config.php
 * @param  [type] $id   [description]
 * @param  [type] $name [description]
 * @return [type]       [description]
 */
function config_m($id, $name)
{
    $s = (include 'app/template/' . $id . '/config.php');
    return $s[$name];
}
/**
 * 循环删除目录和文件函数
 * @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'];
    }
}
/**
 * 获取插件类的类名
 * @param $name 插件名
 * @param string $type 返回命名空间类型
 * @param string $class 当前类名
 * @return string
 */
function get_addon_class($name = '', $class = null)
{
    $name = \think\Loader::parseName($name);
    $class = \think\Loader::parseName(is_null($class) ? $name : $class, 0);
    return $namespace = "addons\\" . $name . "\\" . $class;
}
/**
 * 删除文件及文件下方的文件
 * $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  [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] $img [description]
 * @return [type]      [description]
 */
function rand_ks($img,$reg=',')
{
    $my_array = explode($reg, $img);
    shuffle($my_array);
    return $my_array;
}
// 模型数组分割
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]; 
}