= 224) {
//如果ASCII位高与224,
$returnstr = $returnstr . substr($sourcestr, $i, 3); //根据UTF-8编码规范,将3个连续的字符计为单个字符
$i = $i + 3; //实际Byte计为3
$n++; //字串长度计1
} elseif ($ascnum >= 192) {
//如果ASCII位高与192,
$returnstr = $returnstr . substr($sourcestr, $i, 2); //根据UTF-8编码规范,将2个连续的字符计为单个字符
$i = $i + 2; //实际Byte计为2
$n++; //字串长度计1
} elseif ($ascnum >= 65 && $ascnum <= 90) {
//如果是大写字母,
$returnstr = $returnstr . substr($sourcestr, $i, 1);
$i = $i + 1; //实际的Byte数仍计1个
$n++; //但考虑整体美观,大写字母计成一个高位字符
} else {
//其他情况下,包括小写字母和半角标点符号,
$returnstr = $returnstr . substr($sourcestr, $i, 1);
$i = $i + 1; //实际的Byte数计1个
$n = $n + 0.5; //小写字母和半角标点等与半个高位字符宽...
}
}
if ($str_length > strlen($returnstr)) {
$returnstr = $returnstr . $dot; //超过长度时在尾处加上省略号
}
return $returnstr;
}
}
if (!function_exists('parse_attr')) {
/**
* 解析配置
* @param string $value 配置值
* @return array|string
*/
function parse_attr(string $value = '')
{
$array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
if (strpos($value, ':')) {
$value = [];
foreach ($array as $val) {
[$k, $v] = explode(':', $val);
$value[$k] = $v;
}
} else {
$value = $array;
}
return $value;
}
}
if (!function_exists('time_format')) {
/**
* 时间戳格式化
* @param int|null $timestamp
* @param int $type
* @return string 完整的时间显示
*/
function time_format(?int $timestamp = null, int $type = 0)
{
if ($timestamp == 0) {
return '';
}
$types = ['Y-m-d H:i:s', 'Y-m-d H:i', 'Y-m-d'];
$timestamp = $timestamp === null ? $_SERVER['REQUEST_TIME'] : intval($timestamp);
return date($types[$type], $timestamp);
}
}
if (!function_exists('human_date')) {
/**
* 获取语义化时间
* @param int $time 时间
* @param int $local 本地时间
* @return string
*/
function human_date($time, $local = null)
{
return \util\Date::human($time, $local);
}
}
if (!function_exists('format_bytes')) {
/**
* 格式化字节大小
* @param float|int $size 字节数
* @param string $delimiter 数字和单位分隔符
* @return string 格式化后的带单位的大小
*/
function format_bytes(float | int $size, string $delimiter = ''): string
{
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
for ($i = 0; $size >= 1024 && $i < 5; $i++) {
$size /= 1024;
}
return round($size, 2) . $delimiter . $units[$i];
}
}
if (!function_exists('to_guid_string')) {
/**
* 根据PHP各种类型变量生成唯一标识号
* @param mixed $mix 变量
* @return string
*/
function to_guid_string(mixed $mix): string
{
if (is_object($mix)) {
return spl_object_hash($mix);
} elseif (is_resource($mix)) {
$mix = get_resource_type($mix) . strval($mix);
} else {
$mix = serialize($mix);
}
return md5($mix);
}
}
if (!function_exists('encrypt_password')) {
/**
* 对用户的密码进行加密
* @param string $password 明文密码
* @param string $encrypt 传入加密串,在修改密码时做认证
* @param string $fun 加密函数
* @return array|mixed
*/
function encrypt_password(string $password, string $encrypt = '', string $fun = 'md5'): mixed
{
$pwd = [];
$pwd['encrypt'] = $encrypt ?: genRandomString();
$pwd['password'] = $fun($fun($password) . $pwd['encrypt']);
return $encrypt ? $pwd['password'] : $pwd;
}
}
if (!function_exists('genRandomString')) {
/**
* 产生一个指定长度的随机字符串,并返回给用户
* @param int $len 产生字符串的长度
* @return string 随机字符串
*/
function genRandomString(int $len = 6): string
{
$chars = [
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
"3", "4", "5", "6", "7", "8", "9",
];
$charsLen = count($chars) - 1;
// 将数组打乱
shuffle($chars);
$output = "";
for ($i = 0; $i < $len; $i++) {
$output .= $chars[mt_rand(0, $charsLen)];
}
return $output;
}
}
if (!function_exists('http_down')) {
/**
* 下载远程文件,默认保存在temp下
* @param string $url 网址
* @param string $filename 保存文件名
* @param integer $timeout 过期时间
* @return string 本地文件名
*/
function http_down($url, $filename = "", $timeout = 60)
{
if (empty($filename)) {
$filename = public_path() . 'temp' . DS . pathinfo($url, PATHINFO_BASENAME);
}
$path = dirname($filename);
if (!is_dir($path) && !mkdir($path, 0755, true)) {
return false;
}
$url = str_replace(" ", "%20", $url);
if (function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
// curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if ('https' == substr($url, 0, 5)) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
$temp = curl_exec($ch);
if (file_put_contents($filename, $temp) && !curl_error($ch)) {
return $filename;
} else {
return false;
}
} else {
$opts = [
"http" => [
"method" => "GET",
"header" => "",
"timeout" => $timeout,
],
];
$context = stream_context_create($opts);
if (@copy($url, $filename, $context)) {
//$http_response_header
return $filename;
} else {
return false;
}
}
}
}
if (!function_exists('safe_replace')) {
/**
* 安全过滤函数
* @param $string
* @return string
*/
function safe_replace($string)
{
$string = str_replace('%20', '', $string);
$string = str_replace('%27', '', $string);
$string = str_replace('%2527', '', $string);
$string = str_replace('*', '', $string);
$string = str_replace('"', '"', $string);
$string = str_replace("'", '', $string);
$string = str_replace('"', '', $string);
$string = str_replace(';', '', $string);
$string = str_replace('<', '<', $string);
$string = str_replace('>', '>', $string);
$string = str_replace("{", '', $string);
$string = str_replace('}', '', $string);
$string = str_replace('\\', '', $string);
return $string;
}
}
if (!function_exists('sys_auth')) {
/**
* 字符串加密、解密函数
* @param string $string
* @param string $operation ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE,
* @param string $key 密钥:数字、字母、下划线
* @param int $expiry 过期时间
* @return string
*/
function sys_auth(string $string, string $operation = 'ENCODE', string $key = '', int $expiry = 0): string
{
$ckey_length = 4;
$key = md5($key != '' ? $key : Config::get('yzn.data_auth_key'));
$keya = md5(substr($key, 0, 16));
$keyb = md5(substr($key, 16, 16));
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
$cryptkey = $keya . md5($keya . $keyc);
$key_length = strlen($cryptkey);
$string = $operation == 'DECODE' ? base64_decode(strtr(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 = [];
for ($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
}
for ($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
for ($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if ($operation == 'DECODE') {
if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
return substr($result, 26);
} else {
return '';
}
} else {
return $keyc . rtrim(strtr(base64_encode($result), '+/', '-_'), '=');
}
}
}
if (!function_exists('hsv2rgb')) {
function hsv2rgb($h, $s, $v): array
{
$r = $g = $b = 0;
$i = floor($h * 6);
$f = $h * 6 - $i;
$p = $v * (1 - $s);
$q = $v * (1 - $f * $s);
$t = $v * (1 - (1 - $f) * $s);
switch ($i % 6) {
case 0:
$r = $v;
$g = $t;
$b = $p;
break;
case 1:
$r = $q;
$g = $v;
$b = $p;
break;
case 2:
$r = $p;
$g = $v;
$b = $t;
break;
case 3:
$r = $p;
$g = $q;
$b = $v;
break;
case 4:
$r = $t;
$g = $p;
$b = $v;
break;
case 5:
$r = $v;
$g = $p;
$b = $q;
break;
}
return [
floor($r * 255),
floor($g * 255),
floor($b * 255),
];
}
}
if (!function_exists('letter_avatar')) {
/**
* 首字母头像
* @param string $text
* @return string
*/
function letter_avatar(string $text): string
{
$total = unpack('L', hash('adler32', $text, true))[1];
$hue = $total % 360;
[$r, $g, $b] = hsv2rgb($hue / 360, 0.3, 0.9);
$bg = "rgb({$r},{$g},{$b})";
$color = "#ffffff";
$first = mb_strtoupper(mb_substr($text, 0, 1));
$src = base64_encode('');
return 'data:image/svg+xml;base64,' . $src;
}
}
if (!function_exists('build_suffix_image')) {
/**
* 生成文件后缀图片
* @param string $suffix 后缀
* @param ?string $background 背景颜色
* @return string
*/
function build_suffix_image(string $suffix, ?string $background = null): string
{
$suffix = mb_substr(strtoupper($suffix), 0, 4);
$total = unpack('L', hash('adler32', $suffix, true))[1];
$hue = $total % 360;
[$r, $g, $b] = hsv2rgb($hue / 360, 0.3, 0.9);
$background = $background ?: "rgb({$r},{$g},{$b})";
return <<
{$suffix}
EOT;
}
}
if (!function_exists('xss_clean')) {
/**
* 清理XSS
* @param array|string $content
* @param bool $is_image
* @return bool|string|string[]
*/
function xss_clean(array | string $content, bool $is_image = false)
{
return \app\common\library\Security::instance()->xss_clean($content, $is_image);
}
}
if (!function_exists('url_clean')) {
/**
* 清理URL
*/
function url_clean($url)
{
if (!check_url_allowed($url)) {
return '';
}
return xss_clean($url);
}
}
if (!function_exists('check_url_allowed')) {
/**
* 检测URL是否允许范围内
* @param string $url
* @return bool
*/
function check_url_allowed(string $url = ''): bool
{
//允许的主机列表
$allowedHostArr = [
strtolower(request()->host()),
];
if (empty($url)) {
return true;
}
//如果是站内相对链接则允许
if (preg_match("/^[\/a-z][a-z0-9][a-z0-9\.\/]+((\?|#).*)?\$/i", $url) && substr($url, 0, 2) !== '//') {
return true;
}
//如果是站外链接则需要判断HOST是否允许
if (preg_match("/((http[s]?:\/\/)+(?>[a-z\-0-9]{2,}\.){1,}[a-z]{2,8})(?:\s|\/)/i", $url)) {
$chkHost = parse_url(strtolower($url), PHP_URL_HOST);
if ($chkHost && in_array($chkHost, $allowedHostArr)) {
return true;
}
}
return false;
}
}
if (!function_exists('check_nav_active')) {
/**
* 检测会员中心导航是否高亮
*/
function check_nav_active($url, $classname = 'layui-this')
{
$auth = \app\common\library\Auth::instance();
$requestUrl = $auth->getRequestUri();
$url = ltrim($url, '/');
return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
}
}
if (!function_exists('var_export_short')) {
/**
* 使用短标签打印或返回数组结构
* @param mixed $data
* @param boolean $return 是否返回数据
* @return string
*/
function var_export_short($data, $return = true)
{
return var_export($data, $return);
$replaced = [];
$count = 0;
//判断是否是对象
if (is_resource($data) || is_object($data)) {
return var_export($data, $return);
}
//判断是否有特殊的键名
$specialKey = false;
array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
$specialKey = true;
}
});
if ($specialKey) {
return var_export($data, $return);
}
array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
if (is_object($value) || is_resource($value)) {
$replaced[$count] = var_export($value, true);
$value = "##<{$count}>##";
} else {
if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
$index = array_search($value, $replaced);
if ($index === false) {
$replaced[$count] = var_export($value, true);
$value = "##<{$count}>##";
} else {
$value = "##<{$index}>##";
}
}
}
$count++;
});
$dump = var_export($data, true);
$dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
$dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
$dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
$dump = preg_replace('#\)$#', "]", $dump); //End
if ($replaced) {
$dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
}, $dump);
}
if ($return === true) {
return $dump;
} else {
echo $dump;
}
}
}