vr-shopxo-source/application/common.php

2426 lines
67 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
// +----------------------------------------------------------------------
// | ShopXO 国内领先企业级B2C免费开源电商系统
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2099 http://shopxo.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://opensource.org/licenses/mit-license.php )
// +----------------------------------------------------------------------
// | Author: Devil
// +----------------------------------------------------------------------
// 应用公共文件
/**
* 文件快速排序
* @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);
}
}
/**
* 是否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)));
}
/**
* 根据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));
$host = (count($arr) == 1) ? $arr['path'] : $arr['host'];
// 是否存在斜杠
if(stripos($host, '/') !== false)
{
$slash = explode('/', $host);
$host = $slash[0];
}
// 查看是几级域名
$data = explode('.', $host);
$n = count($data);
if(count($data) == 1)
{
return $host;
}
// 判断是否是双后缀
$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)$/';
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;
}
/**
* 文件配置数据读写
* @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)
{
// 目录不存在则创建
$config_dir = ROOT.'runtime'.DS.'data'.DS.'config_data'.DS;
\base\FileUtil::CreateDir($config_dir);
// 数据文件
$file = $config_dir.md5($key).'.php';
// 删除
if($value === null)
{
return \base\FileUtil::UnlinkFile($aim_url);
} else {
// 读内容
if($value === '')
{
$value = file_exists($file) ? require $file : $default;
if($mandatory === true)
{
if(empty($value))
{
$value = $default;
}
}
return $value;
// 写内容
} else {
// 目录是否有可写权限
if(!is_writable($config_dir))
{
return false;
}
// 存在则校验写权限
if(file_exists($file) && !is_writable($file))
{
return false;
}
// 存储内容
$content = "<?php\nreturn ".var_export($value, true).";\n?>";
return (file_put_contents($file, $content) !== false);
}
}
}
/**
* 获取参数数据
* @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)
{
static $params = null;
if($params === null)
{
$params = input();
if(empty($params))
{
$params = file_get_contents("php://input");
}
}
// 是否指定key
if(!empty($key) && is_array($params))
{
if(array_key_exists($key, $params))
{
return is_array($params[$key]) ? $params[$key] : htmlspecialchars(trim($params[$key]));
}
return $default;
}
// 未指定key则返回所有数据
return $params;
}
/**
* 当前应用平台
* @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;
}
/**
* 是否微信环境
* @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);
}
/**
* 笛卡尔积生成规格
* @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;
}
/**
* 后台管理权限校验方法
* @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);
// 管理员
$admin = \app\service\AdminService::LoginInfo();
if(!empty($admin))
{
// 不需要校验权限的方法
if(!empty($unwanted_power) && in_array($action, $unwanted_power))
{
return true;
}
// 权限
// 角色组权限列表校验
$power = \app\service\AdminPowerService::PowerData();
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 [];
}
/**
* 商品销售模式
* @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)
{
return ($site_type == -1) ? \app\service\SystemBaseService::SiteTypeValue() : $site_type;
}
/**
* 商品类型是否与站点类型一致
* @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;
}
// 系统站点类型
$common_site_type = \app\service\SystemBaseService::SiteTypeValue();
// 是否一致
if($common_site_type == $site_type)
{
return 1;
}
// 系统是否为 销售+自提,包含其中
if($common_site_type == 4 && in_array($site_type, [0, 2]))
{
return 1;
}
// 不一致
return 0;
}
/**
* 缓存安全验证次数处理
* @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验证]
* @param [int] $expire_time [过期时间默认30秒]
*/
function SecurityPreventViolence($key, $type = 1, $expire_time = 30)
{
// 安全缓存 key
$mkey = md5($key.'_security_prevent_violence');
// 清除缓存返
if($type == 0)
{
cache($mkey, null);
return true;
}
// 验证并增加次数
$count = intval(cache($mkey))+1;
$max = config('shopxo.security_prevent_violence_max');
$status = false;
if($count <= $max)
{
cache($mkey, $count, $expire_time);
$status = true;
}
// 验证达到次数限制则清除验证信息
if($count > $max)
{
cache($key, null);
cache($mkey, null);
}
return $status;
}
/**
* 获取动态表格 form 路径
* @author Devil
* @blog http://gong.gg/
* @version 1.0.0
* @date 2020-06-05
* @desc description
* @param [array] $params [输入参数]
*/
function FormModulePath($params = [])
{
// 参数变量
$path = '';
$group = request()->module();
$controller = request()->controller();
$action = request()->action();
// 是否插件调用
if($controller == 'Plugins')
{
if(!empty($params['pluginsname']))
{
// 控制器和方法默认值处理
$controller = empty($params['pluginscontrol']) ? 'index' : $params['pluginscontrol'];
$action = empty($params['pluginsaction']) ? 'index' : $params['pluginsaction'];
// 是否定义模块组
$path = '\app\plugins\\'.$params['pluginsname'].'\form\\'.$group.'\\'.ucfirst($controller);
if(!class_exists($path))
{
$path = '\app\plugins\\'.$params['pluginsname'].'\form\\'.ucfirst($controller);
}
}
} else {
$path = '\app\\'.request()->module().'\form\\'.$controller;
}
return [
'module' => $path,
'action' => $action,
];
}
/**
* 模块视图动态加载方法
* @author Devil
* @blog http://gong.gg/
* @version 1.0.0
* @date 2020-05-25
* @desc description
* @param [string] $template [视图路径]
* @param [mixed] $data [参数数据]
* @param [mixed] $params [额外参数]
*/
function ModuleInclude($template, $data = [], $params = [])
{
// 应用控制器
$module = '\app\module\ViewIncludeModule';
if(!class_exists($module))
{
return '模块视图控制器未定义['.$module.']';
}
// 调用方法
$action = 'Run';
$obj = new $module();
if(!method_exists($obj, $action))
{
return '模块视图方法未定义['.$module.'->'.$action.'()]';
}
return $obj->Run($template, $data, $params);
}
/**
* 钩子返回数据处理,是否存在错误
* @author Devil
* @blog http://gong.gg/
* @version 1.0.0
* @date 2019-12-02
* @desc description
* @param [array] $data [钩子返回的数据]
*/
function HookReturnHandle($data)
{
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);
}
/**
* 附件地址处理
* @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);
}
/**
* 路径解析指定参数
* @author Devil
* @blog http://gong.gg/
* @version 1.0.0
* @date 2019-08-06
* @desc description
* @param [string] $key [指定key]
* @param [mixed] $default [默认值]
* @param [string] $path [参数字符串 格式如: a/aa/b/bb/c/cc ]
*/
function PathToParams($key = null, $default = null, $path = '')
{
$data = $_REQUEST;
if(empty($path) && isset($_REQUEST['s']))
{
$path = $_REQUEST['s'];
}
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']);
}
if(!empty($path) && !array_key_exists($key, $data))
{
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);
$index = 0;
foreach($arr as $k=>$v)
{
if($index != $k)
{
$data[$arr[$index]] = $v;
$index = $k;
}
}
}
if($key !== null)
{
return array_key_exists($key, $data) ? $data[$key] : $default;
}
return $data;
}
/**
* 应用控制器调用
* @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;
}
/**
* 调用插件服务层方法 - 获取插件配置信息
* @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')
{
// 插件是否启用
if(app\service\PluginsService::PluginsStatus($plugins) != 1)
{
return DataReturn('插件状态异常['.$plugins.']', -1);
}
// 查看是否存在基础服务层并且定义获取基础配置方法
$plugins_class = 'app\plugins\\'.$plugins.'\service\BaseService';
if(class_exists($plugins_class) && method_exists($plugins_class, 'BaseConfig'))
{
return $plugins_class::BaseConfig();
}
// 未指定附件字段则自动去获取
$attachment = $attachment_field;
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);
}
/**
* 调用插件服务层方法 - 访问为静态
* @author Devil
* @blog http://gong.gg/
* @version 1.0.0
* @datetime 2019-07-10T22:03:48+0800
* @param [string] $plugins [插件名称]
* @param [string] $service [服务层名称]
* @param [string] $method [方法名称]
* @param [mixed] $params [参数]
*/
function CallPluginsServiceMethod($plugins, $service, $method, $params = null)
{
$plugins_class = 'app\plugins\\'.$plugins.'\service\\'.$service;
if(class_exists($plugins_class))
{
if(method_exists($plugins_class, $method))
{
// 插件是否启用
if(app\service\PluginsService::PluginsStatus($plugins) != 1)
{
return DataReturn('插件状态异常['.$plugins.']', -1);
}
// 调用方法返回数据
return $plugins_class::$method($params);
} else {
return DataReturn('类方法未定义['.$plugins.'-'.$service.'-'.$method.']', -1);
}
}
return DataReturn('类未定义['.$plugins.'-'.$service.']', -1);
}
/**
* 判断当前是否小程序环境中
* @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
// QQ小程序 miniProgram
if(stripos($_SERVER['HTTP_USER_AGENT'], 'miniProgram') !== false)
{
// 是否QQ小程序
if(stripos($_SERVER['HTTP_USER_AGENT'], 'QQ') !== false)
{
return 'qq';
}
return 'weixin';
}
// 支付宝客户端 AlipayClient
if(stripos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false)
{
return 'alipay';
}
// 百度小程序 swan-baiduboxapp
if(stripos($_SERVER['HTTP_USER_AGENT'], 'swan-baiduboxapp') !== false)
{
return 'baidu';
}
// 头条小程序 ToutiaoMicroApp
if(stripos($_SERVER['HTTP_USER_AGENT'], 'ToutiaoMicroApp') !== false)
{
return 'toutiao';
}
}
return null;
}
/**
* 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;
}
/**
* 字符串转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))
{
// 编码处理
$encode = mb_detect_encoding($str);
if($encode != 'UTF-8')
{
$str = mb_convert_encoding($str, 'UTF-8', $encode);
}
// 开始转换
for($i=0; $i<strlen($str); $i++)
{
$temp_str = dechex(ord($str[$i]));
if(isset($temp_str[1]))
{
$change_after .= $temp_str[1];
}
if(isset($temp_str[0]))
{
$change_after .= $temp_str[0];
}
}
}
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))
{
// 开始转换
$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]));
}
// 编码处理
$encode = mb_detect_encoding($str);
if($encode != 'UTF-8')
{
$str = mb_convert_encoding($str, 'UTF-8', $encode);
}
}
return $str;
}
/**
* 获取当前系统所在根路径
* @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'])));
}
}
// 服务器root没有获取到默认使用系统root_path
return (substr(ROOT_PATH, -1) == '/') ? substr(ROOT_PATH, 0, -1) : ROOT_PATH;
}
/**
* 生成随机字符串
* @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;
}
/**
* 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;
}
/**
* 金额格式化
* @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 = '.')
{
return number_format((float) $value, $decimals, $dec_point, '');
}
/**
* 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;
}
/**
* [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)
{
// 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;
}
return false;
}
/**
* [DataReturn 公共返回数据]
* @author Devil
* @blog http://gong.gg/
* @version 0.0.1
* @datetime 2016-12-07T22:03:40+0800
* @param [string] $msg [提示信息]
* @param [int] $code [状态码]
* @param [mixed] $data [数据]
* @return [json] [json数据]
*/
function DataReturn($msg = '', $code = 0, $data = '')
{
// ajax的时候success和error错误由当前方法接收
if(IS_AJAX)
{
if(isset($msg['info']))
{
// success模式下code=0, error模式下code参数-1
$result = array('msg'=>$msg['info'], 'code'=>-1, 'data'=>'');
}
}
// 默认情况下,手动调用当前方法
if(empty($result))
{
$result = array('msg'=>$msg, 'code'=>$code, 'data'=>$data);
}
// 错误情况下,防止提示信息为空
if($result['code'] != 0 && empty($result['msg']))
{
$result['msg'] = '操作失败';
}
return $result;
}
/**
* 获取当前脚本名称
* @author Devil
* @blog http://gong.gg/
* @version 1.0.0
* @date 2019-06-20
* @desc description
*/
function CurrentScriptName()
{
$name = '';
if(empty($_SERVER['SCRIPT_NAME']))
{
if(empty($_SERVER['PHP_SELF']))
{
if(!empty($_SERVER['SCRIPT_FILENAME']))
{
$name = $_SERVER['SCRIPT_FILENAME'];
}
} else {
$name = $_SERVER['PHP_SELF'];
}
} else {
$name = $_SERVER['SCRIPT_NAME'];
}
if(!empty($name))
{
$loc = strripos($name, '/');
if($loc !== false)
{
$name = substr($name, $loc+1);
}
}
return $name;
}
/**
* 生成url地址