common.php 73.5 KB
Newer Older
D
v1.2.0  
devil_gong 已提交
1 2 3 4
<?php
// +----------------------------------------------------------------------
// | ShopXO 国内领先企业级B2C免费开源电商系统
// +----------------------------------------------------------------------
D
2.0  
Devil 已提交
5
// | Copyright (c) 2011~2099 http://shopxo.net All rights reserved.
D
v1.2.0  
devil_gong 已提交
6
// +----------------------------------------------------------------------
D
2.0  
Devil 已提交
7
// | Licensed ( https://opensource.org/licenses/mit-license.php )
D
v1.2.0  
devil_gong 已提交
8 9 10 11 12
// +----------------------------------------------------------------------
// | Author: Devil
// +----------------------------------------------------------------------

// 应用公共文件
D
devil_gong 已提交
13

D
Devil 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
/**
 * session管理
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-17
 * @desc    description
 * @param   [string]         $name    [session名称]
 * @param   [mixed]          $value   [session值]
 */
function MySession($name = '', $value = '')
{
    return session($name, $value);
}

/**
 * 缓存管理
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-17
 * @desc    description
 * @param   [string]         $name    [缓存名称]
 * @param   [mixed]          $value   [缓存值]
 * @param   [mixed]          $options [缓存参数]
 * @param   [string]         $tag     [缓存标签]
 */
function MyCache($name = null, $value = '', $options = null, $tag = null)
{
    return cache($name, $value, $options, $tag);
}

/**
 * 环境变量配置
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-17
 * @desc    description
 * @param   [string]          $key [key名称、支持.连接子数据,比如 shopxo.hello]
 * @param   [mixed]           $val [默认值]
 */
function MyEnv($key, $val = null)
{
    return env($key, $val);
}

/**
 * 配置读取
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-17
 * @desc    description
 * @param   [string]          $key [key名称、支持.连接子数据,比如 shopxo.hello ]
 */
function MyConfig($key)
{
    return config($key);
}

/**
 * 重定向
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-16
 * @desc    description
 * @param   [string]          $url      [url地址 或 模块地址]
 * @param   [boolean]         $is_exit  [是否需要结束运行、默认 false]
 */
function MyRedirect($url, $is_exit = false)
{
    if(!IsUrl($url))
    {
        $url = MyUrl($url);
    }
    if($is_exit)
    {
        exit(header('location:'.$url));
    } else {
        return redirect($url);
    }
}

/**
 * 钩子事件定义
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-16
 * @desc    description
 * @param   [string]          $key    [钩子名称]
 * @param   [array]           $params [输入参数]
 */
function MyEventTrigger($key, $params = [])
{
    return event($key, $params);
}

/**
 * 视图赋值
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-16
 * @desc    description
D
Devil 已提交
121
 * @param   [string|array]    $data   [key名称|批量赋值(数组)]
D
Devil 已提交
122 123
 * @param   [mixed]           $value [数据值]
 */
D
Devil 已提交
124
function MyViewAssign($data, $value = '')
D
Devil 已提交
125
{
D
Devil 已提交
126
    \think\facade\View::assign($data, $value);
D
Devil 已提交
127 128 129 130 131 132 133 134 135 136
}

/**
 * 视图调用
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-16
 * @desc    description
 * @param   [string]          $view   [视图地址]
D
Devil 已提交
137
 * @param   [array]           $data   [模板变量]
D
Devil 已提交
138
 */
D
Devil 已提交
139
function MyView($view = '', $data = [])
D
Devil 已提交
140
{
D
Devil 已提交
141
    return \think\facade\View::fetch($view, $data);
D
Devil 已提交
142 143 144 145 146 147 148 149 150 151 152 153
}

/**
 * 当前请求模块组名
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-16
 * @desc    description
 */
function RequestModule()
{
D
Devil 已提交
154
    return strtolower(app('http')->getName());
D
Devil 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
}

/**
 * 当前请求控制器名
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-16
 * @desc    description
 */
function RequestController()
{
    return strtolower(request()->controller());
}

/**
 * 当前请求方法名
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-16
 * @desc    description
 */
function RequestAction()
{
    return strtolower(request()->action());
}

D
Devil 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
/**
 * 获取链接http状态码
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-09
 * @desc    description
 * @param   [string]      $url     [链接地址]
 * @param   [int]         $timeout [超时时间(秒)]
 */
function GetHttpCode($url, $timeout = 5)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
D
Devil 已提交
200 201
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
D
Devil 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $code;
}

/**
 * 判断是否是url地址
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-09
 * @desc    description
 * @param   [string]          $value [地址值]
 */
D
Devil 已提交
218 219
function IsUrl($value)
{
D
Devil 已提交
220
    return in_array(substr($value, 0, 6), ['http:/', 'https:']);
D
Devil 已提交
221 222
}

D
Devil 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
/**
 * 文件快速排序
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-03-09
 * @desc    description
 * @param  [array] $data [需要排序的数据(选择一个基准元素,将待排序分成小和打两罐部分,以此类推递归的排序划分两罐部分)]
 * @param  [array]       [数组字段]
 * @return [array]       [排序好的数据,从小到大排序]
 */
function ArrayQuickSort($data, $field)
{
    if(!empty($data) && is_array($data))
    {
        $len = count($data);
        if($len <= 1) return $data;

        $base = $data[0];
        $left_array = array();
        $right_array = array();
        for($i=1; $i<$len; $i++)
        {
            if($base[$field] > $data[$i][$field])
            {
                $left_array[] = $data[$i];
            } else {
                $right_array[] = $data[$i];
            }
        }
        if(!empty($left_array)) $left_array = ArrayQuickSort($left_array, $field);
        if(!empty($right_array)) $right_array = ArrayQuickSort($right_array, $field);

        return array_merge($left_array, array($base), $right_array);
    }
}

260 261 262 263 264 265 266 267 268 269 270 271 272 273
/**
 * 是否base64加密的字符串
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-02-28
 * @desc    description
 * @param   [string]          $str [base加密的字符串]
 */
function IsBase64($str)
{
    $str = urldecode($str);
    return ($str == base64_encode(base64_decode($str)));
}
D
Devil 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287

/**
 * 根据url地址解析顶级域名
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-02-25
 * @desc    description
 * @param   [string]          $url [url地址]
 */
function GetUrlHost($url)
{
    // 地址解析
    $arr = parse_url(strtolower($url));
D
Devil 已提交
288 289 290 291 292
    $host = (count($arr) == 1) ? $arr['path'] : (empty($arr['host']) ? '' : $arr['host']);
    if(empty($host))
    {
        return $url;
    }
D
Devil 已提交
293 294 295 296 297 298 299 300 301 302 303

    // 是否存在斜杠
    if(stripos($host, '/') !== false)
    {
        $slash = explode('/', $host);
        $host = $slash[0];
    }

    // 查看是几级域名
    $data = explode('.', $host);
    $n = count($data);
304 305 306 307
    if(count($data) == 1)
    {
        return $host;
    }
D
Devil 已提交
308 309

    // 判断是否是双后缀
D
Devil 已提交
310
    $preg = '/[\w].+\.(com|net|org|gov|ac|bj|sh|tj|cq|he|sn|sx|nm|ln|jl|hl|js|zj|ah|fj|jx|sd|ha|hb|hn|gd|gx|hi|sc|gz|yn|gs|qh|nx|xj|tw|hk|mo|xz|edu|ge|dev|co)\.(cn|nz)$/';
D
Devil 已提交
311 312 313 314 315 316 317 318 319 320 321
    if(($n > 2) && preg_match($preg, $host))
    {
        // 双后缀取后3位
        $host = $data[$n-3].'.'.$data[$n-2].'.'.$data[$n-1];
    } else {
        // 非双后缀取后两位
        $host = $data[$n-2].'.'.$data[$n-1];
    }
    return $host;
}

D
devil 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
/**
 * 文件配置数据读写
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-11-13
 * @desc    description
 * @param   [string]          $key      [数据缓存可以]
 * @param   [mixed]           $value    [数据值(空字符串:读, null:删除, 其他:写)]
 * @param   [mixed]           $default  [默认值]
 * @param   [boolean]         $mandatory[是否强制判断数据值(空字符串|null|0)视为空]
 * @return  [mixed]                     [缓存不存在:null, 则缓存数据]
 */
function MyFileConfig($key, $value = '', $default = null, $mandatory = false)
{
337
    static $fileConfigCache = [];
D
devil 已提交
338 339 340 341 342
    // 目录不存在则创建
    $config_dir = ROOT.'runtime'.DS.'data'.DS.'config_data'.DS;
    \base\FileUtil::CreateDir($config_dir);

    // 数据文件
D
Devil 已提交
343
    $file = $config_dir.md5($key).'.txt';
D
devil 已提交
344 345 346 347

    // 删除
    if($value === null)
    {
靳陆陆 已提交
348
        return \base\FileUtil::UnlinkFile($file);
D
devil 已提交
349 350 351 352
    } else {
        // 读内容
        if($value === '')
        {
353 354 355 356
            $value = $fileConfigCache[$file] ?? '';
            if ($value) {
                return $value;
            }
D
Devil 已提交
357
            $value = file_exists($file) ? unserialize(file_get_contents($file)) : $default;
D
devil 已提交
358 359 360 361 362 363 364
            if($mandatory === true)
            {
                if(empty($value))
                {
                    $value = $default;
                }
            }
365
            $fileConfigCache[$file] = $value;
D
devil 已提交
366 367 368
            return $value;
        // 写内容
        } else {
369
            $fileConfigCache[$file] = $value;
D
devil 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382
            // 目录是否有可写权限
            if(!is_writable($config_dir))
            {
                return false;
            }

            // 存在则校验写权限
            if(file_exists($file) && !is_writable($file))
            {
                return false;
            }

            // 存储内容
D
Devil 已提交
383
            return (file_put_contents($file, serialize($value)) !== false);
D
devil 已提交
384 385 386 387
        }
    }
}

D
devil 已提交
388 389 390 391 392 393 394 395 396 397 398 399
/**
 * 获取参数数据
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-09-23
 * @desc    description
 * @param   [string]          $key     [参数key]
 * @param   [string]          $default [默认值]
 */
function MyInput($key = null, $default = null)
{
D
devil 已提交
400 401
    static $params = null;
    if($params === null)
D
devil 已提交
402
    {
D
devil 已提交
403 404 405 406 407
        $params = input();
        if(empty($params))
        {
            $params = file_get_contents("php://input");
        }
D
devil 已提交
408 409 410
    }

    // 是否指定key
D
devil 已提交
411
    if(!empty($key) && is_array($params))
D
devil 已提交
412
    {
D
devil 已提交
413
        if(array_key_exists($key, $params)) 
D
devil 已提交
414
        {
D
devil 已提交
415
            return is_array($params[$key]) ? $params[$key] : htmlspecialchars(trim($params[$key]));
D
devil 已提交
416 417 418 419 420
        }
        return $default;
    }

    // 未指定key则返回所有数据
D
devil 已提交
421
    return $params;
D
devil 已提交
422 423
}

D
devil 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
/**
 * 当前应用平台
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-09-11
 * @desc    description
 */
function ApplicationClientType()
{
    // 平台
    $platform = APPLICATION_CLIENT_TYPE;

    // web端手机访问
    if($platform == 'pc' && IsMobile())
    {
        $platform = 'h5';
    }
    return $platform;
}

D
devil 已提交
445 446 447 448 449 450 451 452 453 454 455 456 457 458
/**
 * 是否微信环境
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-08-26
 * @desc    description
 * @return  [boolean] [否false, 是true]
 */
function IsWeixinEnv()
{
    return (!empty($_SERVER['HTTP_USER_AGENT']) && stripos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false);
}

D
优化  
Devil 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
/**
 * 是否微信环境
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-08-26
 * @desc    description
 * @return  [boolean] [否false, 是true]
 */
function IsDingdingEnv()
{
    return (!empty($_SERVER['HTTP_USER_AGENT']) && stripos($_SERVER['HTTP_USER_AGENT'], 'DingTalk') !== false);
}

/**
 * 是否QQ环境
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-08-26
 * @desc    description
 * @return  [boolean] [否false, 是true]
 */
function IsQQEnv()
{
D
Devil 已提交
484
    return (!empty($_SERVER['HTTP_USER_AGENT']) && stripos($_SERVER['HTTP_USER_AGENT'], 'QQ/') !== false);
D
优化  
Devil 已提交
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
}

/**
 * 是否支付宝环境
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-08-26
 * @desc    description
 * @return  [boolean] [否false, 是true]
 */
function IsAlipayEnv()
{
    return (!empty($_SERVER['HTTP_USER_AGENT']) && stripos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false);
}

/**
 * 是否新浪微博环境
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-08-26
 * @desc    description
 * @return  [boolean] [否false, 是true]
 */
function IsWeiboEnv()
{
    return (!empty($_SERVER['HTTP_USER_AGENT']) && stripos($_SERVER['HTTP_USER_AGENT'], 'Weibo') !== false);
}

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
/**
 * 笛卡尔积生成规格
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-07-15
 * @desc    description
 * @param   [array]          $arr1 [要进行笛卡尔积的二维数组]
 * @param   [array]          $arr2 [最终实现的笛卡尔积组合,可不传]
 */
function SpecCartesian($arr1, $arr2 = [])
{
    $result = [];
    if(!empty($arr1))
    {
        // 去除第一个元素
        $first = array_splice($arr1, 0, 1);

        // 判断是否是第一次进行拼接
        if(count($arr2) > 0)
        {
            foreach($arr2 as $v)
            {
                foreach($first[0] as $vs)
                {
                    $result[] = $v.','.$vs;
                }
            }
        } else {
            foreach($first[0] as $vs)
            {
                $result[] = $vs;
            }
        }

        // 递归进行拼接
        if(count($arr1) > 0)
        {
            $result = SpecCartesian($arr1, $result);
        }
    }
    return $result;
}

D
devil 已提交
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
/**
 * 后台管理权限校验方法
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-07-12
 * @desc    description
 * @param   [string]          $controller     [控制器(默认读取当前)]
 * @param   [string]          $action         [方法(默认读取当前)]
 * @param   [array]           $unwanted_power [不校验权限的方法(默认空)]
 */
function AdminIsPower($controller = null, $action = null, $unwanted_power = [])
{
    // 控制器/方法
    $controller = strtolower(empty($controller) ? request()->controller() : $controller);
    $action = strtolower(empty($action) ? request()->action() : $action);

    // 管理员
577
    $admin = \app\service\AdminService::LoginInfo();
D
devil 已提交
578 579 580 581 582 583 584 585 586 587
    if(!empty($admin))
    {
        // 不需要校验权限的方法
        if(!empty($unwanted_power) && in_array($action, $unwanted_power))
        {
            return true;
        }

        // 权限
        // 角色组权限列表校验
588
        $power = \app\service\AdminPowerService::PowerData();
D
devil 已提交
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
        if(!empty($power) && is_array($power) && in_array($controller.'_'.$action, $power))
        {
            return true;
        }
    }

    return false;
}

/**
 * 获取数组字段名称
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-07-12
 * @desc    description
 * @param   [array]          $data [数组(一维或二维数组)]
 */
function ArrayKeys($data)
{
    if(is_array($data))
    {
        // 是否二维数组
        if(isset($data[0]) && is_array($data[0]))
        {
            return array_keys($data[0]);
        }

        // 一维数组
        return array_keys($data);
    }
    return [];
}

D
devil 已提交
623 624 625 626 627 628 629 630 631 632 633 634
/**
 * 商品销售模式
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-07-02
 * @desc    description
 * @param   [int]          $site_type [商品类型]
 * @return  [int]                     [销售模式]
 */
function GoodsSalesModelType($site_type)
{
D
Devil 已提交
635
    return ($site_type == -1) ? \app\service\SystemBaseService::SiteTypeValue() : $site_type;
D
devil 已提交
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
}

/**
 * 商品类型是否与站点类型一致
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-07-02
 * @desc    description
 * @param   [int]          $site_type [商品类型]
 * @return  [int]                     [一致 1 | 不一致 0]
 */
function IsGoodsSiteTypeConsistent($site_type)
{
    // 是否已设置
    if($site_type == -1)
    {
        return 1;
    }

    // 系统站点类型
D
Devil 已提交
657
    $common_site_type = \app\service\SystemBaseService::SiteTypeValue();
D
devil 已提交
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673

    // 是否一致
    if($common_site_type == $site_type)
    {
        return 1;
    }

    // 系统是否为 销售+自提,包含其中
    if($common_site_type == 4 && in_array($site_type, [0, 2]))
    {
        return 1;
    }

    // 不一致
    return 0;
}
D
devil 已提交
674 675 676 677 678 679 680 681 682 683

/**
 * 缓存安全验证次数处理
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-06-03
 * @desc    description
 * @param   [string]          $key          [缓存 key]
 * @param   [int]             $type         [操作类型(0清除, 1验证)]
D
devil 已提交
684
 * @param   [int]             $expire_time  [过期时间(默认30秒)]
D
devil 已提交
685 686 687 688 689 690 691 692 693
 */
function SecurityPreventViolence($key, $type = 1, $expire_time = 30)
{
    // 安全缓存 key
    $mkey = md5($key.'_security_prevent_violence');

    // 清除缓存返
    if($type == 0)
    {
D
Devil 已提交
694
        MyCache($mkey, null);
D
devil 已提交
695 696 697 698
        return true;
    }

    // 验证并增加次数
D
Devil 已提交
699 700
    $count = intval(MyCache($mkey))+1;
    $max = MyConfig('shopxo.security_prevent_violence_max');
D
devil 已提交
701 702 703
    $status = false;
    if($count <= $max)
    {
D
Devil 已提交
704
        MyCache($mkey, $count, $expire_time);
D
devil 已提交
705 706 707 708 709 710
        $status = true;
    }

    // 验证达到次数限制则清除验证信息
    if($count > $max)
    {
D
Devil 已提交
711 712
        MyCache($key, null);
        MyCache($mkey, null);
D
devil 已提交
713 714 715 716 717
    }

    return $status;
}

D
devil 已提交
718
/**
D
devil 已提交
719
 * 获取动态表格 form 路径
D
devil 已提交
720 721 722
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
D
devil 已提交
723
 * @date    2020-06-05
D
devil 已提交
724
 * @desc    description
D
devil 已提交
725
 * @param   [array]           $params [输入参数]
D
devil 已提交
726
 */
D
devil 已提交
727
function FormModulePath($params = [])
D
devil 已提交
728
{
D
devil 已提交
729 730
    // 参数变量
    $path = '';
D
Devil 已提交
731 732 733
    $group = RequestModule();
    $controller = RequestController();
    $action = RequestAction();
D
devil 已提交
734

D
devil 已提交
735
    // 是否插件调用
D
Devil 已提交
736
    if($controller == 'plugins')
D
devil 已提交
737
    {
D
Devil 已提交
738
        if(!empty($params['pluginsname']))
D
devil 已提交
739
        {
D
Devil 已提交
740 741 742
            // 控制器和方法默认值处理
            $controller = empty($params['pluginscontrol']) ? 'index' : $params['pluginscontrol'];
            $action = empty($params['pluginsaction']) ? 'index' : $params['pluginsaction'];
D
Devil 已提交
743 744 745 746 747 748 749

            // 是否定义模块组
            $path = '\app\plugins\\'.$params['pluginsname'].'\form\\'.$group.'\\'.ucfirst($controller);
            if(!class_exists($path))
            {
                $path = '\app\plugins\\'.$params['pluginsname'].'\form\\'.ucfirst($controller);
            }
D
devil 已提交
750 751
        }
    } else {
D
Devil 已提交
752
        $path = '\app\\'.$group.'\form\\'.ucfirst($controller);
D
devil 已提交
753 754
    }

D
devil 已提交
755 756 757 758
    return [
        'module'    => $path,
        'action'    => $action,
    ];
D
devil 已提交
759 760
}

D
devil 已提交
761 762 763 764 765 766 767 768
/**
 * 模块视图动态加载方法
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-05-25
 * @desc    description
 * @param   [string]          $template [视图路径]
769 770
 * @param   [mixed]           $data     [参数数据]
 * @param   [mixed]           $params   [额外参数]
D
devil 已提交
771
 */
772
function ModuleInclude($template, $data = [], $params = [])
D
devil 已提交
773 774
{
    // 应用控制器
D
devil 已提交
775
    $module = '\app\module\ViewIncludeModule';
D
devil 已提交
776 777 778 779 780 781 782 783 784 785 786 787 788
    if(!class_exists($module))
    {
        return '模块视图控制器未定义['.$module.']';
    }

    // 调用方法
    $action = 'Run';
    $obj = new $module();
    if(!method_exists($obj, $action))
    {
        return '模块视图方法未定义['.$module.'->'.$action.'()]';
    }

789
    return $obj->Run($template, $data, $params);
D
devil 已提交
790 791
}

D
devil_gong 已提交
792 793 794 795 796 797 798 799 800
/**
 * 钩子返回数据处理,是否存在错误
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2019-12-02
 * @desc    description
 * @param   [array]          $data [钩子返回的数据]
 */
D
Devil 已提交
801
function EventReturnHandle($data)
D
devil_gong 已提交
802 803 804 805 806 807 808 809 810 811 812 813 814 815
{
    if(!empty($data) && is_array($data))
    {
        foreach($data as $v)
        {
            if(is_array($v) && isset($v['code']) && $v['code'] != 0)
            {
                return $v;
            }
        }
    }
    return DataReturn('无钩子信息', 0);
}

D
devil_gong 已提交
816 817 818 819 820 821 822 823 824 825 826 827 828 829
/**
 * 附件地址处理
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2019-10-16
 * @desc    用于页面展示处理,非绝对路径的情况下自动加上http
 * @param   [string]          $value [附件地址]
 */
function AttachmentPathViewHandle($value)
{
    return app\service\ResourcesService::AttachmentPathViewHandle($value);
}

D
devil_gong 已提交
830 831 832 833 834 835 836 837 838
/**
 * 路径解析指定参数
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2019-08-06
 * @desc    description
 * @param   [string]            $key        [指定key]
 * @param   [mixed]             $default    [默认值]
G
gongfuxiang 已提交
839
 * @param   [string]            $path       [参数字符串 格式如: a/aa/b/bb/c/cc ]
D
devil_gong 已提交
840
 */
G
gongfuxiang 已提交
841
function PathToParams($key = null, $default = null, $path = '')
D
devil_gong 已提交
842
{
D
devil_gong 已提交
843
    $data = $_REQUEST;
G
gongfuxiang 已提交
844 845 846 847
    if(empty($path) && isset($_REQUEST['s']))
    {
        $path = $_REQUEST['s'];
    }
D
devil 已提交
848 849 850 851 852
    if(empty($path))
    {
        $path = !empty($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : (empty($_SERVER['REDIRECT_URL']) ? (empty($_SERVER['REQUEST_URI']) ? (empty($_SERVER['PATH_TRANSLATED']) ? '' : $_SERVER['PATH_TRANSLATED']) : $_SERVER['REQUEST_URI']) : $_SERVER['REDIRECT_URL']);
    }

D
devil_gong 已提交
853
    if(!empty($path) && !array_key_exists($key, $data))
D
devil_gong 已提交
854 855 856 857 858 859 860 861 862 863 864 865
    {
        if(substr($path, 0, 1) == '/')
        {
            $path = mb_substr($path, 1, mb_strlen($path, 'utf-8')-1, 'utf-8');
        }
        $position = strrpos($path, '.');
        if($position !== false)
        {
            $path = mb_substr($path, 0, $position, 'utf-8');
        }
        $arr = explode('/', $path);

D
devil_gong 已提交
866
        
D
devil_gong 已提交
867 868 869 870 871 872 873 874 875 876
        $index = 0;
        foreach($arr as $k=>$v)
        {
            if($index != $k)
            {
                $data[$arr[$index]] = $v;
                $index = $k;
            }
        }
    }
D
devil 已提交
877

D
devil_gong 已提交
878 879 880 881 882
    if($key !== null)
    {
        return array_key_exists($key, $data) ? $data[$key] : $default;
    }
    return $data;
D
devil_gong 已提交
883 884
}

885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
/**
 * 应用控制器调用
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  1.0.0
 * @date     2020-01-02
 * @param    [string]          $plugins        [应用标记]
 * @param    [string]          $control        [应用控制器]
 * @param    [string]          $action         [应用方法]
 * @param    [string]          $group          [应用组(admin, index, api)]
 * @param    [array]           $params         [输入参数]
 * @param    [int]             $is_ret_data    [是否直接返回data数据]
 */
function PluginsControlCall($plugins, $control, $action, $group = 'index', $params = [], $is_ret_data = 0)
{
    $ret =  app\service\PluginsService::PluginsControlCall($plugins, $control, $action, $group, $params);
    return ($is_ret_data == 1) ? $ret['data'] : $ret;
}

D
devil_gong 已提交
904
/**
D
devil 已提交
905
 * 调用插件服务层方法 - 获取插件配置信息
D
devil_gong 已提交
906 907 908 909 910 911 912 913 914 915 916
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  1.0.0
 * @datetime 2019-10-16T22:03:48+0800
 * @param    [string]          $plugins             [插件名称]
 * @param    [array]           $attachment_field    [自定义附件字段]
 * @param    [string]          $service_name        [附件定义的服务层类名]
 * @param    [string]          $attachment_property [附件属性名称]
 */
function CallPluginsData($plugins, $attachment_field = [], $service_name = '', $attachment_property = 'base_config_attachment_field')
{
D
devil_gong 已提交
917 918 919 920 921 922
    // 插件是否启用
    if(app\service\PluginsService::PluginsStatus($plugins) != 1)
    {
        return DataReturn('插件状态异常['.$plugins.']', -1);
    }

D
devil 已提交
923 924 925 926 927 928 929
    // 查看是否存在基础服务层并且定义获取基础配置方法
    $plugins_class = 'app\plugins\\'.$plugins.'\service\BaseService';
    if(class_exists($plugins_class) && method_exists($plugins_class, 'BaseConfig'))
    {
        return $plugins_class::BaseConfig();
    }

D
devil_gong 已提交
930
    // 未指定附件字段则自动去获取
D
devil 已提交
931
    $attachment = $attachment_field;
D
devil_gong 已提交
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
    if(empty($attachment_field) && !empty($attachment_property))
    {
        // 类自定义或者默认两个类
        $service_all = empty($service_name) ? ['BaseService', 'Service'] : [$service_name];
        foreach($service_all as $service)
        {
            // 服务层获取附件属性
            $plugins_class = 'app\plugins\\'.$plugins.'\service\\'.$service;
            if(class_exists($plugins_class) && property_exists($plugins_class, $attachment_property))
            {
                $attachment = $plugins_class::${$attachment_property};
                break;
            }
        }
    }

    // 获取配置信息
    return app\service\PluginsService::PluginsData($plugins, $attachment);
}

G
gongfuxiang 已提交
952
/**
D
devil 已提交
953
 * 调用插件服务层方法 - 访问为静态
G
gongfuxiang 已提交
954 955 956 957
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  1.0.0
 * @datetime 2019-07-10T22:03:48+0800
G
gongfuxiang 已提交
958 959 960
 * @param    [string]          $plugins   [插件名称]
 * @param    [string]          $service   [服务层名称]
 * @param    [string]          $method    [方法名称]
G
gongfuxiang 已提交
961
 * @param    [mixed]           $params    [参数]
G
gongfuxiang 已提交
962
 */
G
gongfuxiang 已提交
963
function CallPluginsServiceMethod($plugins, $service, $method, $params = null)
G
gongfuxiang 已提交
964
{
G
gongfuxiang 已提交
965
    $plugins_class = 'app\plugins\\'.$plugins.'\service\\'.$service;
G
gongfuxiang 已提交
966 967
    if(class_exists($plugins_class))
    {
D
devil_gong 已提交
968 969
        if(method_exists($plugins_class, $method))
        {
D
devil_gong 已提交
970 971 972 973 974 975 976
            // 插件是否启用
            if(app\service\PluginsService::PluginsStatus($plugins) != 1)
            {
                return DataReturn('插件状态异常['.$plugins.']', -1);
            }

            // 调用方法返回数据
D
devil_gong 已提交
977 978 979 980
            return $plugins_class::$method($params);
        } else {
            return DataReturn('类方法未定义['.$plugins.'-'.$service.'-'.$method.']', -1);
        }
G
gongfuxiang 已提交
981
    }
D
devil_gong 已提交
982
    return DataReturn('类未定义['.$plugins.'-'.$service.']', -1);
G
gongfuxiang 已提交
983 984
}

G
gongfuxiang 已提交
985 986 987 988 989 990 991 992 993 994 995 996
/**
 * 判断当前是否小程序环境中
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  1.0.0
 * @datetime 2019-06-29T22:21:44+0800
 */
function MiniAppEnv()
{
    if(!empty($_SERVER['HTTP_USER_AGENT']))
    {
        // 微信小程序 miniProgram
D
devil_gong 已提交
997
        // QQ小程序 miniProgram
G
gongfuxiang 已提交
998 999
        if(stripos($_SERVER['HTTP_USER_AGENT'], 'miniProgram') !== false)
        {
D
devil_gong 已提交
1000 1001 1002 1003 1004
            // 是否QQ小程序
            if(stripos($_SERVER['HTTP_USER_AGENT'], 'QQ') !== false)
            {
                return 'qq';
            }
G
gongfuxiang 已提交
1005 1006 1007 1008 1009 1010 1011 1012
            return 'weixin';
        }

        // 支付宝客户端 AlipayClient
        if(stripos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false)
        {
            return 'alipay';
        }
G
gongfuxiang 已提交
1013

D
devil_gong 已提交
1014
        // 百度小程序 swan-baiduboxapp
G
gongfuxiang 已提交
1015 1016 1017 1018
        if(stripos($_SERVER['HTTP_USER_AGENT'], 'swan-baiduboxapp') !== false)
        {
            return 'baidu';
        }
D
devil_gong 已提交
1019 1020 1021 1022 1023 1024

        // 头条小程序 ToutiaoMicroApp
        if(stripos($_SERVER['HTTP_USER_AGENT'], 'ToutiaoMicroApp') !== false)
        {
            return 'toutiao';
        }
G
gongfuxiang 已提交
1025 1026 1027 1028
    }
    return null;
}

G
gongfuxiang 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
/**
 * RGB 转 十六进制
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  1.0.0
 * @datetime 2019-06-08T18:38:16+0800
 * @param    [string]        $rgb [reg颜色值]
 */
function RgbToHex($rgb)
{
    $regexp = "/^rgb\(([0-9]{0,3})\,\s*([0-9]{0,3})\,\s*([0-9]{0,3})\)/";
    preg_match($regexp, $rgb, $match);
    $re = array_shift($match);
    $hex_color = "#";
    $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
    for ($i = 0; $i < 3; $i++)
    {
        $r = null;
        $c = $match[$i];
        $hex_array = [];
        while ($c > 16)
        {
            $r = $c % 16;
            $c = ($c / 16) >> 0;
            array_push($hex_array, $hex[$r]);
        }
        array_push($hex_array, $hex[$c]);
        $ret = array_reverse($hex_array);
        $item = implode('', $ret);
        $item = str_pad($item, 2, '0', STR_PAD_LEFT);
        $hex_color .= $item;
    }
    return $hex_color;
}

/**
 * 十六进制 转 RGB
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  1.0.0
 * @datetime 2019-06-08T18:33:45+0800
 * @param    [string]        $hex_color [十六进制颜色值]
 */
function HexToRgb($hex_color) {
    $color = str_replace('#', '', $hex_color);
    if(strlen($color) > 3)
    {
        $rgb = [
            'r' => hexdec(substr($color, 0, 2)),
            'g' => hexdec(substr($color, 2, 2)),
            'b' => hexdec(substr($color, 4, 2))
        ];
    } else {
        $color = $hex_color;
        $r = substr($color, 0, 1) . substr($color, 0, 1);
        $g = substr($color, 1, 1) . substr($color, 1, 1);
        $b = substr($color, 2, 1) . substr($color, 2, 1);
        $rgb = [
            'r' => hexdec($r),
            'g' => hexdec($g),
            'b' => hexdec($b)
        ];
    }
    return $rgb;
}

G
gongfuxiang 已提交
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
/**
 * 字符串转ascii
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  1.0.0
 * @datetime 2019-06-02T01:13:47+0800
 * @param    [string]          $str [字符串]
 * @return   [string]               [转换后的ascii]
 */
function StrToAscii($str)
{
    $change_after = '';
    if(!empty($str))
    {
D
Devil 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
        // 编码处理
        $encode = mb_detect_encoding($str);
        if($encode != 'UTF-8')
        {
            $str = mb_convert_encoding($str, 'UTF-8', $encode);
        }

        // 开始转换
        for($i=0; $i<strlen($str); $i++)
        {
G
gongfuxiang 已提交
1119
            $temp_str = dechex(ord($str[$i]));
D
devil_gong 已提交
1120 1121 1122 1123 1124 1125 1126 1127
            if(isset($temp_str[1]))
            {
                $change_after .= $temp_str[1];
            }
            if(isset($temp_str[0]))
            {
                $change_after .= $temp_str[0];
            }
G
gongfuxiang 已提交
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
        }
    }
    return strtoupper($change_after);
}


/**
 * ascii转字符串
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  1.0.0
 * @datetime 2019-06-02T01:14:04+0800
 * @param    [string]       $ascii [ascii]
 * @return   [string]              [转换后的字符串]
 */
function AsciiToStr($ascii)
{
    $str = '';
    if(!empty($ascii))
    {
D
Devil 已提交
1148
        // 开始转换
G
gongfuxiang 已提交
1149 1150 1151 1152 1153
        $asc_arr = str_split(strtolower($ascii), 2);
        for($i=0; $i<count($asc_arr); $i++)
        {
            $str .= chr(hexdec($asc_arr[$i][1].$asc_arr[$i][0]));
        }
D
Devil 已提交
1154 1155 1156 1157 1158 1159 1160

        // 编码处理
        $encode = mb_detect_encoding($str);
        if($encode != 'UTF-8')
        {
            $str = mb_convert_encoding($str, 'UTF-8', $encode);
        }
G
gongfuxiang 已提交
1161
    }
D
Devil 已提交
1162
    return $str;
G
gongfuxiang 已提交
1163 1164
}

D
devil_gong 已提交
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
/**
 * 获取当前系统所在根路径
 * @author   Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2019-04-09
 * @desc    description
 */
function GetDocumentRoot()
{
    // 当前所在的文档根目录
    if(!empty($_SERVER['DOCUMENT_ROOT']))
    {
        return $_SERVER['DOCUMENT_ROOT'];
    }

    // 处理iis服务器DOCUMENT_ROOT路径为空
    if(!empty($_SERVER['PHP_SELF']))
    {
        // 当前执行程序的绝对路径及文件名
        if(!empty($_SERVER['SCRIPT_FILENAME']))
        {
            return str_replace('\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0 -strlen($_SERVER['PHP_SELF'])));
        }

        // 当前所在绝对路径
        if(!empty($_SERVER['PATH_TRANSLATED']))
        {
            return str_replace('\\', '/', substr(str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']), 0, 0 -strlen($_SERVER['PHP_SELF'])));
        }
    }
D
devil_gong 已提交
1196 1197 1198

    // 服务器root没有获取到默认使用系统root_path
    return (substr(ROOT_PATH, -1) == '/') ? substr(ROOT_PATH, 0, -1) : ROOT_PATH;
D
devil_gong 已提交
1199 1200
}

D
devil_gong 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
/**
 * 生成随机字符串
 * @author   Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2019-04-04
 * @desc    description
 * @param   [int]          $length [长度 默认6]
 */
function RandomString($length = 6)
{
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
    $pattern_length = strlen($pattern)-1;
    $output = '';
    for($i=0; $i<$length; $i++)   
    {
        $output .= $pattern[mt_rand(0, $pattern_length)];
    }
    return $output;
}

D
devil_gong 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
/**
 * each函数
 * @author   Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2019-02-26
 * @desc    description
 * @param   [array]          &$data [输入参数]
 */
function FunEach(&$data)
{
    if(!is_array($data))
    {
        return false;
    }

    $res = [];
    $key = key($data);
    if($key !== null)
    {
        next($data); 
        $res[1] = $res['value'] = $data[$key];
        $res[0] = $res['key'] = $key;
    } else {
        $res = false;
    }
    return $res;
}

D
devil_gong 已提交
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
/**
 * 金额格式化
 * @author   Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2019-02-20
 * @desc    description
 * @param   [float]         $value     [金额]
 * @param   [int]           $decimals  [保留的位数]
 * @param   [string]        $dec_point [保留小数分隔符]
 */
function PriceNumberFormat($value, $decimals = 2, $dec_point = '.')
{
D
Devil 已提交
1264
    return number_format((float) $value, $decimals, $dec_point, '');
D
devil_gong 已提交
1265 1266
}

D
devil_gong 已提交
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
/**
 * json带格式输出
 * @author   Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2019-02-13
 * @desc    description
 * @param   [array]          $data   [数据]
 * @param   [string]         $indent [缩进字符,默认4个空格 ]
 */
function JsonFormat($data, $indent = null)
{
    // json encode  
    $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  
    // 缩进处理  
    $ret = '';
    $pos = 0;
    $length = strlen($data);
    $indent = isset($indent)? $indent : '    ';
    $newline = "\n";
    $prevchar = '';
    $outofquotes = true;
  
    for($i=0; $i<=$length; $i++)
    {
        $char = substr($data, $i, 1);
  
        if($char == '"' && $prevchar != '\\')
        {
            $outofquotes = !$outofquotes;  
        } elseif(($char == '}' || $char == ']') && $outofquotes)
        {
            $ret .= $newline;
            $pos--;
            for($j=0; $j<$pos; $j++)
            {
                $ret .= $indent;
            }
        }
  
        $ret .= $char;  

        if(($char == ',' || $char == '{' || $char == '[') && $outofquotes)
        {
            $ret .= $newline;
            if($char == '{' || $char == '[')
            {
                $pos++;
            }
  
            for($j=0; $j<$pos; $j++)
            {
                $ret .= $indent;
            }
        }
  
        $prevchar = $char;
    }
  
    return $ret;  
}
D
v1.2.0  
devil_gong 已提交
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361

/**
 * [FileSizeByteToUnit 文件大小转常用单位]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  1.0.0
 * @datetime 2018-11-28T01:05:29+0800
 * @param    [int]                   $bit [字节数]
 */
function FileSizeByteToUnit($bit)
{
    //单位每增大1024,则单位数组向后移动一位表示相应的单位
    $type = array('Bytes','KB','MB','GB','TB');
    for($i = 0; $bit >= 1024; $i++)
    {
        $bit/=1024;
    }

    //floor是取整函数,为了防止出现一串的小数,这里取了两位小数
    return (floor($bit*100)/100).$type[$i];
}

/**
 * 异步调用方法
 * @author   Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2018-06-11
 * @desc    异步运行url地址方法
 * @param   [string]          $url [url地址 支持get参数]
 */
function SyncJob($url, $port = 80, $time = 30)
{
D
Devil 已提交
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
    // curl
    if(function_exists('curl_init'))
    {
        CurlGet($url, 1);
        return true;

    // fsockopen
    } elseif(function_exists('fsockopen'))
    {
        $url_str = str_replace(array('http://', 'https://'), '', $url);
        $location = strpos($url_str, '/');
        $host = substr($url_str, 0, $location);
        $fp = fsockopen($host, $port, $errno, $errstr, $time);
        if($fp)
        {
            $out = "GET ".str_replace($host, '', $url_str)." HTTP/1.1\r\n";
            $out .= "Host: ".$host."\r\n";
            $out .= "Content-type: application/x-www-form-urlencoded\r\n";
            $out .= "Connection: Close\r\n\r\n";
            fputs($fp, $out);
            fclose($fp);
        }
        return true;
D
v1.2.0  
devil_gong 已提交
1385
    }
D
Devil 已提交
1386
    return false;
D
v1.2.0  
devil_gong 已提交
1387 1388 1389
}

/**
D
Devil 已提交
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
 * 公共返回数据
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2021-07-16
 * @desc    description
 * @param   [string]       $msg  [提示信息]
 * @param   [int]          $code [状态码]
 * @param   [mixed]        $data [数据]
 * @return  [json]               [json数据]
D
v1.2.0  
devil_gong 已提交
1400 1401
 */
function DataReturn($msg = '', $code = 0, $data = '')
D
Devil 已提交
1402
{    
D
v1.2.0  
devil_gong 已提交
1403
    // 默认情况下,手动调用当前方法
D
Devil 已提交
1404
    $result = ['msg'=>$msg, 'code'=>$code, 'data'=>$data];
D
v1.2.0  
devil_gong 已提交
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414

    // 错误情况下,防止提示信息为空
    if($result['code'] != 0 && empty($result['msg']))
    {
        $result['msg'] = '操作失败';
    }

    return $result;
}

D
devil_gong 已提交
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
/**
 * 获取当前脚本名称
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2019-06-20
 * @desc    description
 */
function CurrentScriptName()
{
    $name = '';
D
devil_gong 已提交
1426
    if(empty($_SERVER['SCRIPT_NAME']))
D
devil_gong 已提交
1427
    {
D
devil_gong 已提交
1428
        if(empty($_SERVER['PHP_SELF']))
D
devil_gong 已提交
1429
        {
D
devil_gong 已提交
1430
            if(!empty($_SERVER['SCRIPT_FILENAME']))
D
devil_gong 已提交
1431
            {
D
devil_gong 已提交
1432
                $name = $_SERVER['SCRIPT_FILENAME'];
D
devil_gong 已提交
1433
            }
D
devil_gong 已提交
1434 1435
        } else {
            $name = $_SERVER['PHP_SELF'];
D
devil_gong 已提交
1436 1437 1438 1439
        }
    } else {
        $name = $_SERVER['SCRIPT_NAME'];
    }
D
devil_gong 已提交
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450

    if(!empty($name))
    {
        $loc = strripos($name, '/');
        if($loc !== false)
        {
            $name = substr($name, $loc+1);
        } 
    }

    return $name;
D
devil_gong 已提交
1451
}
D
v1.2.0  
devil_gong 已提交
1452 1453 1454 1455 1456 1457 1458 1459

/**
 * 生成url地址
 * @author   Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2018-06-12
 * @desc    description
1460 1461
 * @param   string          $path      [路径地址]
 * @param   array           $params    [参数]
D
v1.2.0  
devil_gong 已提交
1462
 */
D
Devil 已提交
1463
function MyUrl($path, $params = [])
D
v1.2.0  
devil_gong 已提交
1464
{
D
Devil 已提交
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
    // 当前脚本名称
    $script_name = CurrentScriptName();

    // url模式
    $url_model = MyC('home_seo_url_model', 0);

    // 模块组状态
    $is_api = (substr($path, 0, 4) == 'api/');
    $is_admin = (substr($path, 0, 6) == 'admin/');
    $is_index = (substr($path, 0, 6) == 'index/');
    $is_install = (substr($path, 0, 8) == 'install/');

D
devil_gong 已提交
1477
    // 调用框架生成url
D
v1.2.0  
devil_gong 已提交
1478 1479
    $url = url($path, $params, true, true);

D
Devil 已提交
1480 1481
    // 非 admin 则使用配置后缀
    if(!$is_admin && !$is_install)
D
v1.2.0  
devil_gong 已提交
1482
    {
D
Devil 已提交
1483
        $url = $url->suffix(MyFileConfig('home_seo_url_html_suffix', '', 'html', true));
D
v1.2.0  
devil_gong 已提交
1484 1485
    }

D
Devil 已提交
1486 1487 1488 1489 1490 1491 1492 1493
    // 转 url字符串
    $url = (string) $url;

    // 去除组名称
    $join = ($script_name != 'index.php' || $url_model == 0) ? '?s=' : '/';
    $len = $is_api ? 4 : ($is_install ? 8 : 6);
    $url = str_replace('/'.$path, $join.substr($path, $len), $url);

D
Devil 已提交
1494 1495
    // 避免非当前目录生成url索引错误
    if($script_name != 'index.php' && $is_index)
1496
    {
D
Devil 已提交
1497
        if($url_model == 0)
D
Devil 已提交
1498
        {
D
Devil 已提交
1499
            // 替换索引为 index.php
D
Devil 已提交
1500
            $url = str_replace($script_name, 'index.php', $url);
D
Devil 已提交
1501
        } else {
D
Devil 已提交
1502 1503
            // 去除入口和?s=
            $url = str_replace([$script_name.'?s=', '/'.$script_name], '', $url);
D
Devil 已提交
1504
        }
1505
    }
D
Devil 已提交
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
    // 替换索引为 api.php
    if($script_name != 'api.php' && $is_api)
    {
        $url = str_replace($script_name, 'api.php', $url);
    }
    // 替换索引为 install.php
    if($script_name != 'install.php' && $is_install)
    {
        $url = str_replace($script_name, 'install.php', $url);
    }
1516

D
Devil 已提交
1517 1518 1519 1520 1521
    // 前端则去除 index.php
    $url = str_replace('/index.php', '', $url);

    // 是否根目录访问项目
    if(defined('IS_ROOT_ACCESS'))
D
devil_gong 已提交
1522
    {
D
Devil 已提交
1523
        $url = str_replace('public/', '', $url);
D
devil_gong 已提交
1524 1525
    }

D
Devil 已提交
1526 1527
    // tp框架url方法是否识别到https
    if(__MY_HTTP__ == 'https' && substr($url, 0, 5) != 'https')
1528
    {
D
Devil 已提交
1529
        $url = 'https'.mb_substr($url, 4, null, 'utf-8');
1530 1531
    }

D
v1.2.0  
devil_gong 已提交
1532 1533 1534
    return $url;
}

1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
/**
 * 生成url地址 - 应用前端
 * @author   Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2018-06-12
 * @desc    description
 * @param   string          $plugins_name      [应用名称]
 * @param   string          $plugins_control   [应用控制器]
 * @param   string          $plugins_action    [应用方法]
 * @param   array           $params            [参数]
 */
D
devil 已提交
1547
function PluginsHomeUrl($plugins_name, $plugins_control = '', $plugins_action = '', $params = [])
1548
{
D
devil 已提交
1549
    // 控制器和方法都为index的时候置空、缩短url地址
D
Devil 已提交
1550
    if($plugins_control == 'index' && $plugins_action == 'index' && empty($params))
D
devil 已提交
1551 1552 1553 1554 1555 1556
    {
        $plugins_control = '';
        $plugins_action = '';
    }

    // 插件基础参数
D
devil_gong 已提交
1557 1558 1559 1560 1561
    $plugins = [
        'pluginsname'       => $plugins_name,
        'pluginscontrol'    => $plugins_control,
        'pluginsaction'     => $plugins_action,
    ];
D
Devil 已提交
1562 1563
    $path = 'index/plugins/index';
    return MyUrl($path, $plugins+$params);
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
}

/**
 * 生成url地址 - 应用后端
 * @author   Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2018-06-12
 * @desc    description
 * @param   string          $plugins_name      [应用名称]
 * @param   string          $plugins_control   [应用控制器]
 * @param   string          $plugins_action    [应用方法]
 * @param   array           $params            [参数]
 */
D
devil 已提交
1578
function PluginsAdminUrl($plugins_name, $plugins_control, $plugins_action, $params = [])
1579
{
D
Devil 已提交
1580
    // 插件基础参数
D
devil_gong 已提交
1581 1582 1583 1584 1585
    $plugins = [
        'pluginsname'       => $plugins_name,
        'pluginscontrol'    => $plugins_control,
        'pluginsaction'     => $plugins_action,
    ];
D
Devil 已提交
1586 1587
    $path = 'admin/plugins/index';
    return MyUrl($path, $plugins+$params);
1588 1589
}

D
v1.2.0  
devil_gong 已提交
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
/**
 * [PriceBeautify 金额美化]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  1.0.0
 * @datetime 2018-04-12T16:54:51+0800
 * @param    [float]                  $price   [金额]
 * @param    [mixed]                  $default [默认值]
 */
function PriceBeautify($price = 0, $default = null)
{
    if(empty($price))
    {
        return $default;
    }

    $price = str_replace('.00', '', $price);
D
Devil 已提交
1607
    if(strpos($price, '.') !== false)
D
v1.2.0  
devil_gong 已提交
1608 1609 1610 1611
    {
        if(substr($price, -1) == 0)
        {
            $price = substr($price, 0, -1);
D
Devil 已提交
1612 1613 1614 1615 1616
        }
        if(substr($price, -1) == '.')
        {
            $price = substr($price, 0, -1);
        }
D
v1.2.0  
devil_gong 已提交
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
    }
    return $price;
}

/**
 * [FileUploadError 文件上传错误校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2017-04-12T17:21:51+0800
 * @param    [string]     $name [表单name]
 * @param    [int]        $index[多文件索引]
 * @return   [mixed]            [true | 错误信息]
 */
function FileUploadError($name, $index = false)
{
    // 是否存在该name表单
    if($index === false)
    {
        if(empty($_FILES[$name]))
        {
            return '请选择需要上传的文件';
        }
    } else {
        if(empty($_FILES[$name]['name'][$index]))
        {
            return '请选择需要上传的文件';
        }
    }

    // 是否正常
    $error = null;
    if($index === false)
    {
        if($_FILES[$name]['error'] == 0)
        {
            return true;
        }
        $error = $_FILES[$name]['error'];
    } else {
        if($_FILES[$name]['error'][$index] == 0)
        {
            return true;
        }
        $error = $_FILES[$name]['error'][$index];
    }

    // 错误码对应的错误信息
    $file_error_list = lang('common_file_upload_error_list');
    if(isset($file_error_list[$error]))
    {
        return $file_error_list[$error];
    }
    return '未知错误'.'[file error '.$error.']';
}

/**
 * [LangValueKeyFlip 公共数据翻转]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2017-04-07T11:32:02+0800
 * @param    [array]       $data        [需要翻转的数据]
 * @param    [mixed]       $default     [默认值]
 * @param    [string]      $value_field [value值字段名称]
 * @param    [string]      $name_field  [name值字段名称]
 * @return   [array]                    [翻转后的数据]
 */
function LangValueKeyFlip($data, $default = false, $value_field = 'id', $name_field = 'name')
{
    $result = array();
    if(!empty($data) && is_array($data))
    {
        foreach($data as $k=>$v)
        {
            $result[$v[$name_field]] = $v[$value_field];
            if(isset($v['checked']) && $v['checked'] == true)
            {
                $result['default'] = $v[$value_field];
            }
        }
    }
    if($default !== false)
    {
        $result['default'] = $default;
    }
    return $result;
}

/**
 * [ScienceNumToString 科学数字转换成原始的数字]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2017-04-06T17:21:51+0800
 * @param    [int]   $num [科学数字]
 * @return   [string]     [数据原始的值]
 */
function ScienceNumToString($num)
{
    if(stripos($num, 'e') === false) return $num;

    // 出现科学计数法,还原成字符串 
    $num = trim(preg_replace('/[=\'"]/','',$num,1),'"');
    $result = ''; 
    while($num > 0)
    { 
        $v = $num-floor($num/10)*10; 
        $num = floor($num/10); 
        $result   =   $v.$result; 
    }
    return $result; 
}

/**
 * [GetClientIP 客户端ip地址]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2017-02-09T12:53:13+0800
 * @param    [boolean]        $long [是否将ip转成整数]
 * @return   [string|int]           [ip地址|ip地址整数]
 */
function GetClientIP($long = false)
{
D
devil 已提交
1742
    $onlineip = '';
D
v1.2.0  
devil_gong 已提交
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown'))
    { 
        $onlineip = getenv('HTTP_CLIENT_IP'); 
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown'))
    {
        $onlineip = getenv('HTTP_X_FORWARDED_FOR'); 
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown'))
    {
        $onlineip = getenv('REMOTE_ADDR'); 
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
    {
        $onlineip = $_SERVER['REMOTE_ADDR']; 
    } 
    if($long)
    {
        $onlineip = sprintf("%u", ip2long($onlineip));
    }
    return $onlineip;
}

/**
 * [UrlParamJoin url参数拼接]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2017-01-09T23:33:44+0800
 * @param    [array]      $param [url参数一维数组]
 * @return   [string]            [url参数字符串]
 */
function UrlParamJoin($param)
{
    $string = '';
    if(!empty($param) && is_array($param))
    {
        foreach($param as $k=>$v)
        {
            if(is_string($v))
            {
                $string .= $k.'='.$v.'&';
            }
        }
        if(!empty($string))
        {
D
Devil 已提交
1786 1787
            $join = (MyC('home_seo_url_model', 0) == 0) ? '&' : '?';
            $string = $join.substr($string, 0, -1);
D
v1.2.0  
devil_gong 已提交
1788 1789 1790 1791 1792 1793
        }
    }
    return $string;
}

/**
D
devil 已提交
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
 * 读取站点配置信息
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-09-13
 * @desc    description
 * @param   [string]    $key           [索引名称]
 * @param   [mixed]     $default       [默认值]
 * @param   [boolean]   $mandatory     [是否强制校验值,默认false]
 * @return  [mixed]                    [配置信息值,没找到返回null]
D
v1.2.0  
devil_gong 已提交
1804 1805 1806
 */
function MyC($key, $default = null, $mandatory = false)
{
D
Devil 已提交
1807
    $data = MyCache($key);
D
v1.2.0  
devil_gong 已提交
1808 1809
    if($mandatory === true)
    {
D
devil 已提交
1810
        return empty($data) ? $default : $data;
D
v1.2.0  
devil_gong 已提交
1811
    }
D
devil 已提交
1812
    return ($data === null) ? $default : $data;
D
v1.2.0  
devil_gong 已提交
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
}

/**
 * [EmptyDir 清空目录下所有文件]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-21T19:25:57+0800
 * @param    [string]    $dir_path [目录地址]
 * @return   [boolean]             [成功true, 失败false]
 */
function EmptyDir($dir_path)
{
    if(is_dir($dir_path))
    {
        $dn = @opendir($dir_path);
        if($dn !== false)
        {
            while(false !== ($file = readdir($dn)))
            {
                if($file != '.' && $file != '..')
                {
                    if(!unlink($dir_path.$file))
                    {
                        return false;
                    }
                }
            }
        } else {
            return false;
        }
    }
    return true;
}

/**
 * [Utf8Strlen 计算符串长度(中英文一致)]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-13T21:34:09+0800
 * @param    [string]      $string [需要计算的字符串]
 * @return   [int]                 [字符长度]
 */
function Utf8Strlen($string = null)
{
    preg_match_all("/./us", $string, $match);
    return count($match[0]);
}

/**
 * [IsMobile 是否是手机访问]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-05T10:52:20+0800
 * @return  [boolean] [手机访问true, 则false]
 */
function IsMobile()
{
    /* 如果有HTTP_X_WAP_PROFILE则一定是移动设备 */
    if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
    
    /* 此条摘自TPM智能切换模板引擎,适合TPM开发 */
    if(isset($_SERVER['HTTP_CLIENT']) && 'PhoneClient' == $_SERVER['HTTP_CLIENT']) return true;
    
    /* 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息 */
    if(isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], 'wap') !== false) return true;
    
    /* 判断手机发送的客户端标志,兼容性有待提高 */
    if(isset($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array(
            'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipad','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
        );
        /* 从HTTP_USER_AGENT中查找手机浏览器的关键字 */
        if(preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }

    /* 协议法,因为有可能不准确,放到最后判断 */
    if(isset($_SERVER['HTTP_ACCEPT']))
    {
        /* 如果只支持wml并且不支持html那一定是移动设备 */
        /* 如果支持wml和html但是wml在html之前则是移动设备 */
        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;
}


/**
D
devil 已提交
1906
 * 校验json数据是否合法
D
v1.2.0  
devil_gong 已提交
1907 1908 1909 1910 1911 1912 1913
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $jsonstr [需要校验的json字符串]
 * @return   [boolean] [合法true, 则false]
 */
D
devil 已提交
1914
function IsJson($jsonstr)
D
v1.2.0  
devil_gong 已提交
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
{
    if(PHP_VERSION > 5.3)
    {
        json_decode($jsonstr);
        return (json_last_error() == JSON_ERROR_NONE);
    } else {
        return is_null(json_decode($jsonstr)) ? false : true;
    }
}

D
devil 已提交
1925 1926 1927 1928 1929 1930 1931
/**
 * 请求get,支持本地文件
 * @author  Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2020-08-07
 * @desc    description
D
Devil 已提交
1932 1933
 * @param   [string]          $value        [本地文件路径或者远程url地址]
 * @param   [int]             $timeout      [超时时间(默认10秒)]
D
devil 已提交
1934
 */
D
Devil 已提交
1935
function RequestGet($value, $timeout = 10)
D
devil 已提交
1936 1937 1938 1939 1940 1941 1942
{
    // 远程
    if(substr($value, 0, 4) == 'http')
    {
        // 是否有curl模块
        if(function_exists('curl_init'))
        {
D
Devil 已提交
1943
            return CurlGet($value, $timeout);
D
devil 已提交
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
        }
        return file_get_contents($value);
    }

    // 本地文件
    return file_exists($value) ? file_get_contents($value) : '';
}

/**
 * curl模拟get请求
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  1.0.0
 * @datetime 2018-01-03T19:21:38+0800
D
Devil 已提交
1958 1959 1960
 * @param    [string]           $url        [url地址]
 * @param    [int]              $timeout    [超时时间(默认10秒)]
 * @return   [array]                        [返回数据]
D
devil 已提交
1961
 */
D
Devil 已提交
1962
function CurlGet($url, $timeout = 10)
D
devil 已提交
1963
{
D
devil 已提交
1964 1965
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
D
Devil 已提交
1966
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
D
devil 已提交
1967 1968 1969
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
D
Devil 已提交
1970
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
D
devil 已提交
1971 1972 1973 1974
    curl_setopt($ch, CURLOPT_URL, $url);

    $result = curl_exec($ch);
    curl_close($ch);
D
devil 已提交
1975 1976 1977
    return $result;
}

D
v1.2.0  
devil_gong 已提交
1978
/**
D
devil 已提交
1979
 * curl模拟post
D
v1.2.0  
devil_gong 已提交
1980 1981 1982 1983
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
D
devil 已提交
1984 1985 1986
 * @param    [string]   $url        [请求地址]
 * @param    [array]    $post       [发送的post数据]
 * @param    [boolean]  $is_json    [是否使用 json 数据发送]
D
Devil 已提交
1987
 * @param    [int]      $timeout    [超时时间]
D
devil 已提交
1988
 * @return   [mixed]                [请求返回的数据]
D
v1.2.0  
devil_gong 已提交
1989
 */
D
Devil 已提交
1990
function CurlPost($url, $post, $is_json = false, $timeout = 30)
D
v1.2.0  
devil_gong 已提交
1991
{
D
devil 已提交
1992
    $ch = curl_init();
D
Devil 已提交
1993
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
D
devil 已提交
1994 1995 1996
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
D
devil 已提交
1997
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
D
devil 已提交
1998 1999
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
D
Devil 已提交
2000
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
D
devil 已提交
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
    curl_setopt($ch, CURLOPT_URL, $url);

    // 是否 json
    if($is_json)
    {
        $data_string = json_encode($post);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json; charset=utf-8",
                "Content-Length: " . strlen($data_string)
            )
        );
    } else {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
D
优化  
Devil 已提交
2016
                "Content-Type: application/x-www-form-urlencoded; charset=utf-8",
D
devil 已提交
2017 2018 2019 2020 2021
                "cache-control: no-cache"
            )
        );
    }

D
devil 已提交
2022
    // 返回结果
D
v1.2.0  
devil_gong 已提交
2023
    $result = curl_exec($ch);
D
devil 已提交
2024 2025 2026 2027 2028 2029 2030 2031 2032
    if($result !== false)
    {
        curl_close($ch);
        return $result;
    } else { 
        $error = curl_errno($ch);
        curl_close($ch);
        return "curl出错,错误码:$error";
    }
D
v1.2.0  
devil_gong 已提交
2033 2034 2035
}

/**
D
devil 已提交
2036
 * fsockopen方式
D
v1.2.0  
devil_gong 已提交
2037 2038 2039 2040 2041 2042 2043
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $url  [url地址]
 * @param    [string] $data [发送参数]
 */
D
devil 已提交
2044
function FsockopenPost($url, $data = '')
D
v1.2.0  
devil_gong 已提交
2045 2046 2047 2048 2049 2050
{
    $row = parse_MyUrl($url);
    $host = $row['host'];
    $port = isset($row['port']) ? $row['port'] : 80;
    $file = $row['path'];
    $post = '';
D
devil_gong 已提交
2051
    while (list($k,$v) = FunEach($data)) 
D
v1.2.0  
devil_gong 已提交
2052 2053 2054 2055 2056 2057
    {
        if(isset($k) && isset($v)) $post .= rawurlencode($k)."=".rawurlencode($v)."&"; //转URL标准码
    }
    $post = substr( $post , 0 , -1 );
    $len = strlen($post);
    $fp = @fsockopen( $host ,$port, $errno, $errstr, 10);
D
devil_gong 已提交
2058
    if(!$fp) {
D
v1.2.0  
devil_gong 已提交
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
        return "$errstr ($errno)\n";
    } else {
        $receive = '';
        $out = "POST $file HTTP/1.0\r\n";
        $out .= "Host: $host\r\n";
        $out .= "Content-type: application/x-www-form-urlencoded\r\n";
        $out .= "Connection: Close\r\n";
        $out .= "Content-Length: $len\r\n\r\n";
        $out .= $post;    
        fwrite($fp, $out);
        while (!feof($fp)) {
          $receive .= fgets($fp, 128);
        }
        fclose($fp);
        $receive = explode("\r\n\r\n",$receive);
        unset($receive[0]);
        return implode("",$receive);
    }
}

/**
D
devil 已提交
2080
 * xml转数组
D
v1.2.0  
devil_gong 已提交
2081 2082 2083 2084 2085 2086 2087
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [xml] $xmlstring [xml数据]
 * @return   [array]          [array数组]
 */
D
devil 已提交
2088
function XmlArray($xmlstring) {
D
v1.2.0  
devil_gong 已提交
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
    return json_decode(json_encode((array) simplexml_load_string($xmlstring)), true);
}


/**
 * [CheckMobile 手机号码格式校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [int] $mobile [手机号码]
 * @return   [boolean]     [正确true,失败false]
 */
function CheckMobile($mobile)
{
    return (preg_match('/'.lang('common_regex_mobile').'/', $mobile) == 1) ? true : false;
}

/**
 * [CheckTel 电话号码格式校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $tel    [电话号码]
 * @return   [boolean]        [正确true,失败false]
 */
function CheckTel($tel)
{
    return (preg_match('/'.lang('common_regex_tel').'/', $tel) == 1) ? true : false;
}

/**
 * [CheckEmail 电子邮箱格式校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $email  [电子邮箱]
 * @return   [boolean]        [正确true,失败false]
 */
function CheckEmail($email)
{
    return (preg_match('/'.lang('common_regex_email').'/', $email) == 1) ? true : false;
}

/**
 * [CheckIdCard 身份证号码格式校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $number [身份证号码]
 * @return   [boolean]        [正确true,失败false]
 */
function CheckIdCard($number)
{
    return (preg_match('/'.lang('common_regex_id_card').'/', $number) == 1) ? true : false;
}

/**
 * [CheckPrice 价格格式校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [float]  $price  [价格]
 * @return   [boolean]        [正确true,失败false]
 */
function CheckPrice($price)
{
    return (preg_match('/'.lang('common_regex_price').'/', $price) == 1) ? true : false;
}


/**
 * [CheckIp ip校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $ip [ip]
 */
function CheckIp($ip)
{
    return (preg_match('/'.lang('common_regex_ip').'/', $ip) == 1) ? true : false;
}

/**
 * [CheckUrl url校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $url [url地址]
 */
function CheckUrl($url)
{
    return (preg_match('/'.lang('common_regex_url').'/', $url) == 1) ? true : false;
}

D
Devil 已提交
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
/**
 * [CheckVersion 版本号校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $ver [版本]
 */
function CheckVersion($ver)
{
    return (preg_match('/'.lang('common_regex_version').'/', $ver) == 1) ? true : false;
}

D
v1.2.0  
devil_gong 已提交
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
/**
 * [CheckUserName 用户名校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $string [用户名]
 * @return   [boolean]        [成功true, 失败false]
 */
function CheckUserName($string)
{
    return (preg_match('/'.lang('common_regex_username').'/', $string) == 1) ? true : false;
}

/**
 * [CheckSort 排序值校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [int] $value  [数据值]
 * @return   [boolean]     [成功true, 失败false]
 */
function CheckSort($value)
{
    $temp = intval($value);
    return ($temp >= 0 && $temp <= 255);
}

/**
 * [CheckColor 颜色值校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $value [数据值]
 */
function CheckColor($value)
{
    return (preg_match('/'.lang('common_regex_color').'/', $value) == 1) ? true : false;
}

/**
 * [CheckLoginPwd 密码格式校验]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $string [登录密码]
 * @return   [boolean]        [正确true, 错误false]
 */
function CheckLoginPwd($string)
{
    return (preg_match('/'.lang('common_regex_pwd').'/', $string) == 1) ? true : false;
}

/**
 * [IsExistRemoteImage 检测一张网络图片是否存在]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $url [图片地址]
 * @return   [boolean]     [存在true, 则false]
 */
function IsExistRemoteImage($url)
{
    if(!empty($url))
    {
        $content = get_headers($url, 1);
        if(!empty($content[0]))
        {
            return preg_match('/200/',$content[0]);
        }
    }
    return false;
}

/**
 * [GetNumberCode 随机数生成生成]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [int] $length [生成位数]
 * @return   [int]         [生成的随机数]
 */
function GetNumberCode($length = 6)
{
    $code = '';
    for($i=0; $i<intval($length); $i++) $code .= rand(0, 9);
    return $code;
}

/**
 * [LoginPwdEncryption 登录密码加密]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $pwd  [需要加密的密码]
 * @param    [string] $salt [配合密码加密的随机数]
 * @return   [string]       [加密后的密码]
 */
function LoginPwdEncryption($pwd, $salt)
{
    return md5($salt.trim($pwd));
}

/**
 * [PwdPayEncryption 支付密码加密]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string] $pwd  [需要加密的密码]
 * @param    [string] $salt [配合密码加密的随机数]
 * @return   [string]       [加密后的密码]
 */
function PwdPayEncryption($pwd, $salt)
{
    return md5(md5(trim($pwd).$salt));
}

/**
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * [PwdStrength 密码强度校验]
 * @param    [string] $pwd [需要校验的密码]
 * @return   [int]         [密码强度值0~10]
 */
function PwdStrength($pwd)
{ 
    $score = 0; 
    if(preg_match("/[0-9]+/", $pwd)) $score ++; 
    if(preg_match("/[0-9]{3,}/", $pwd)) $score ++;
    if(preg_match("/[a-z]+/", $pwd)) $score ++;
    if(preg_match("/[a-z]{3,}/", $pwd)) $score ++;
    if(preg_match("/[A-Z]+/", $pwd)) $score ++;
    if(preg_match("/[A-Z]{3,}/", $pwd)) $score ++;
    if(preg_match("/[_|\-|+|=|*|!|@|#|$|%|^|&|(|)]+/", $pwd)) $score += 2;
    if(preg_match("/[_|\-|+|=|*|!|@|#|$|%|^|&|(|)]{3,}/", $pwd)) $score ++ ;
    if(strlen($pwd) >= 10) $score ++;
    return $score;
}
 
/**
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 *  $lng = '116.655540';
 *  $lat = '39.910980';
 *  $squares = returnSquarePoint($lng, $lat);
 *       
 *  print_r($squares);
 *  $info_sql = "select id,locateinfo,lat,lng from `lbs_info` where lat<>0 and lat>{$squares['right-bottom']['lat']} and lat<{$squares['left-top']['lat']} and lng>{$squares['left-top']['lng']} and lng<{$squares['right-bottom']['lng']} ";
 *  计算某个经纬度的周围某段距离的正方形的四个点
 *
 *  param lng float 经度
 *  param lat float 纬度
 *  param Distance float 该点所在圆的半径,该圆与此正方形内切,默认值为0.5千米
 *  return array 正方形的四个点的经纬度坐标
 */
function ReturnSquarePoint($lng, $lat, $Distance = 1.2)
{
    /* 地球半径,平均半径为6371km */
    $Radius = 6371;

    $d_lng =  2 * asin(sin($Distance / (2 * $Radius)) / cos(deg2rad($lat)));
    $d_lng = rad2deg($d_lng);

    $d_lat = $Distance/$Radius;
    $d_lat = rad2deg($d_lat);

    return array(
        'left-top'=>array('lat'=>$lat + $d_lat,'lng'=>$lng-$d_lng),
        'right-top'=>array('lat'=>$lat + $d_lat, 'lng'=>$lng + $d_lng),
        'left-bottom'=>array('lat'=>$lat - $d_lat, 'lng'=>$lng - $d_lng),
        'right-bottom'=>array('lat'=>$lat - $d_lat, 'lng'=>$lng + $d_lng)
    );
}

/**
 * [Authcode 明文或密文]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-03T21:58:54+0800
 * @param    [string]  $string    [明文或密文]
 * @param    [string]  $operation [加密ENCODE, 解密DECODE]
 * @param    [string]  $key       [密钥]
 * @param    [integer] $expiry    [密钥有效期]
 * @return   [string]             [加密或解密后的数据]
 */
function Authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    // 动态密匙长度,相同的明文会生成不同密文就是依靠动态密匙
    // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。
    // 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方
    // 当此值为 0 时,则不产生随机密钥
    $ckey_length = 4;
  
    // 密匙
    // $GLOBALS['discuz_auth_key'] 这里可以根据自己的需要修改
    $key = md5($key ? $key : 'devil'); 
  
    // 密匙a会参与加解密
    $keya = md5(substr($key, 0, 16));
    // 密匙b会用来做数据完整性验证
    $keyb = md5(substr($key, 16, 16));
    // 密匙c用于变化生成的密文
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
    // 参与运算的密匙
    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);
    // 明文,前10位用来保存时间戳,解密时验证数据有效性,10到26位用来保存$keyb(密匙b),解密时会通过这个密匙验证数据完整性
    // 如果是解码的话,会从第$ckey_length位开始,因为密文前$ckey_length位保存 动态密匙,以保证解密正确
    $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') {
        // substr($result, 0, 10) == 0 验证数据有效性
        // substr($result, 0, 10) - time() > 0 验证数据有效性
        // substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16) 验证数据完整性
        // 验证数据有效性,请看未加密明文的格式
        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 {
        // 把动态密匙保存在密文里,这也是为什么同样的明文,生产不同密文后能解密的原因
        // 因为加密后的密文可能是一些特殊字符,复制过程可能会丢失,所以用base64编码
        return $keyc.str_replace('=', '', base64_encode($result));
    }
}

/**
 * [ParamsChecked 参数校验方法]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  1.0.0
 * @datetime 2017-12-12T15:26:13+0800
 * @param    [array]                   $data   [原始数据]
 * @param    [array]                   $params [校验数据]
 * @return   [boolean|string]                  [成功true, 失败 错误信息]
 */
function ParamsChecked($data, $params)
{
D
devil_gong 已提交
2477
    if(empty($params) || !is_array($data) || !is_array($params))
D
v1.2.0  
devil_gong 已提交
2478 2479 2480 2481 2482 2483
    {
        return '内部调用参数配置有误';
    }

    foreach ($params as $v)
    {
D
devil_gong 已提交
2484
        if(empty($v['key_name']) || empty($v['error_msg']))
D
v1.2.0  
devil_gong 已提交
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
        {
            return '内部调用参数配置有误';
        }

        // 是否需要验证
        $is_checked = true;

        // 数据或字段存在则验证
        // 1 数据存在则验证
        // 2 字段存在则验证
        if(isset($v['is_checked']))
        {
            if($v['is_checked'] == 1)
            {
                if(empty($data[$v['key_name']]))
                {
                    $is_checked = false;
                }
            } else if($v['is_checked'] == 2)
            {
                if(!isset($data[$v['key_name']]))
                {
                    $is_checked = false;
                }
            }
        }

        // 是否需要验证
        if($is_checked === false)
        {
            continue;
        }

D
devil_gong 已提交
2518 2519 2520
        // 数据类型,默认字符串类型
        $data_type = empty($v['data_type']) ? 'string' : $v['data_type'];

D
v1.2.0  
devil_gong 已提交
2521 2522 2523 2524 2525 2526
        // 验证规则,默认isset
        $checked_type = isset($v['checked_type']) ? $v['checked_type'] : 'isset';
        switch($checked_type)
        {
            // 是否存在
            case 'isset' :
D
devil 已提交
2527
                if(!array_key_exists($v['key_name'], $data))
D
v1.2.0  
devil_gong 已提交
2528 2529 2530 2531 2532 2533 2534
                {
                    return $v['error_msg'];
                }
                break;

            // 是否为空
            case 'empty' :
D
devil_gong 已提交
2535
                if(empty($data[$v['key_name']]))
D
v1.2.0  
devil_gong 已提交
2536 2537 2538 2539 2540 2541 2542
                {
                    return $v['error_msg'];
                }
                break;

            // 是否存在于验证数组中
            case 'in' :
D
devil_gong 已提交
2543
                if(empty($v['checked_data']) || !is_array($v['checked_data']))
D
v1.2.0  
devil_gong 已提交
2544 2545 2546
                {
                    return '内部调用参数配置有误';
                }
D
devil_gong 已提交
2547
                if(!isset($data[$v['key_name']]) || !in_array($data[$v['key_name']], $v['checked_data']))
D
v1.2.0  
devil_gong 已提交
2548 2549 2550 2551 2552 2553 2554
                {
                    return $v['error_msg'];
                }
                break;

            // 是否为数组
            case 'is_array' :
D
devil_gong 已提交
2555
                if(!isset($data[$v['key_name']]) || !is_array($data[$v['key_name']]))
D
v1.2.0  
devil_gong 已提交
2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
                {
                    return $v['error_msg'];
                }
                break;

            // 长度
            case 'length' :
                if(!isset($v['checked_data']))
                {
                    return '长度规则值未定义';
                }
                if(!is_string($v['checked_data']))
                {
                    return '内部调用参数配置有误';
                }
                if(!isset($data[$v['key_name']]))
                {
                    return $v['error_msg'];
                }
D
devil_gong 已提交
2575 2576 2577 2578 2579 2580
                if($data_type == 'array')
                {
                    $length = count($data[$v['key_name']]);
                } else {
                    $length = mb_strlen($data[$v['key_name']], 'utf-8');
                }
D
v1.2.0  
devil_gong 已提交
2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
                $rule = explode(',', $v['checked_data']);
                if(count($rule) == 1)
                {
                    if($length > intval($rule[0]))
                    {
                        return $v['error_msg'];
                    }
                } else {
                    if($length < intval($rule[0]) || $length > intval($rule[1]))
                    {
                        return $v['error_msg'];
                    }
                }
                break;

            // 自定义函数
            case 'fun' :
D
devil_gong 已提交
2598
                if(empty($v['checked_data']) || !function_exists($v['checked_data']))
D
v1.2.0  
devil_gong 已提交
2599 2600 2601 2602
                {
                    return '验证函数为空或函数未定义';
                }
                $fun = $v['checked_data'];
D
devil_gong 已提交
2603
                if(!isset($data[$v['key_name']]) || !$fun($data[$v['key_name']]))
D
v1.2.0  
devil_gong 已提交
2604 2605 2606 2607
                {
                    return $v['error_msg'];
                }
                break;
D
devil_gong 已提交
2608 2609 2610

            // 最小
            case 'min' :
D
devil_gong 已提交
2611
                if(!isset($v['checked_data']))
D
devil_gong 已提交
2612 2613 2614
                {
                    return '验证最小值未定义';
                }
D
devil_gong 已提交
2615
                if(!isset($data[$v['key_name']]) || $data[$v['key_name']] < $v['checked_data'])
D
devil_gong 已提交
2616 2617 2618 2619 2620 2621 2622
                {
                    return $v['error_msg'];
                }
                break;

            // 最大
            case 'max' :
D
devil_gong 已提交
2623
                if(!isset($v['checked_data']))
D
devil_gong 已提交
2624 2625 2626
                {
                    return '验证最大值未定义';
                }
D
devil_gong 已提交
2627 2628 2629 2630 2631 2632
                if(!isset($data[$v['key_name']]) || $data[$v['key_name']] > $v['checked_data'])
                {
                    return $v['error_msg'];
                }
                break;

D
devil_gong 已提交
2633 2634
            // 相等
            case 'eq' :
D
devil 已提交
2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646
                if(!isset($v['checked_data']))
                {
                    return '验证相等未定义';
                }
                if(!isset($data[$v['key_name']]) || $data[$v['key_name']] == $v['checked_data'])
                {
                    return $v['error_msg'];
                }
                break;

            // 不相等
            case 'neq' :
D
devil_gong 已提交
2647 2648 2649 2650
                if(!isset($v['checked_data']))
                {
                    return '验证相等未定义';
                }
D
devil 已提交
2651
                if(!isset($data[$v['key_name']]) || $data[$v['key_name']] != $v['checked_data'])
D
devil_gong 已提交
2652 2653 2654 2655 2656
                {
                    return $v['error_msg'];
                }
                break;

D
devil_gong 已提交
2657 2658 2659 2660 2661 2662 2663 2664
            // 数据库唯一
            case 'unique' :
                if(!isset($v['checked_data']))
                {
                    return '验证唯一表参数未定义';
                }
                if(empty($data[$v['key_name']]))
                {
D
devil 已提交
2665
                    return str_replace('{$var}', 'unique验证', $v['error_msg']);
D
devil_gong 已提交
2666
                }
D
Devil 已提交
2667
                $temp = \think\facade\Db::name($v['checked_data'])->where([$v['key_name']=>$data[$v['key_name']]])->find();
D
devil_gong 已提交
2668
                if(!empty($temp))
D
devil_gong 已提交
2669
                {
D
devil 已提交
2670 2671 2672
                    // 错误数据变量替换
                    $error_msg = str_replace('{$var}', $data[$v['key_name']], $v['error_msg']);

D
devil 已提交
2673 2674 2675 2676 2677
                    // 是否需要排除当前操作数据
                    if(isset($v['checked_key']))
                    {
                        if(empty($data[$v['checked_key']]) || (isset($temp[$v['checked_key']]) && $temp[$v['checked_key']] != $data[$v['checked_key']]))
                        {
D
devil 已提交
2678
                            return $error_msg;
D
devil 已提交
2679 2680
                        }
                    } else {
D
devil 已提交
2681
                        return $error_msg;
D
devil 已提交
2682
                    }
D
devil_gong 已提交
2683 2684
                }
                break;
D
v1.2.0  
devil_gong 已提交
2685 2686 2687 2688 2689
        }
    }
    return true;
}
?>