常用封装之二common.php
<?php use think\facade\Db; use think\facade\Cache; use think\facade\Log; // 应用公共文件 if (!function_exists('JsonMessage')) { function JsonMessage($data = [], $http_status = 200, string $url = '') { // header('Content-Type:application/json'); $result = []; is_null($data) && $data = '无数据'; if (is_string($data)) { list($code, $msg) = explode('#', strpos($data, '#') ? (string) $data : '10000#' . $data); } else { $code = 200; $msg = '请求成功'; if (is_string($http_status)) { $msg = $http_status; $http_status = 200; } if (is_numeric($data)) { if ($data > 0) { $msg = "成功更新{$data}条数据"; } else { $msg = "无数据更新"; } $data = []; } elseif ($data instanceof \think\Paginator) { $data = $data->toArray(); $data = [ 'total' => $data['total'], 'limit' => $data['per_page'], 'page' => $data['current_page'], 'data' => $data['data'], ]; } if (isset($data['total'])) { $result = $data; } else { $result['data'] = $data === true ? [] : $data; } } if (!empty($url)) { $result['wait'] = 2; $result['url'] = $url; } $json = array_merge(['code' => intval($code), 'msg' => $msg], $result); return \think\Response::create( $json, input('?get.callback') ? 'jsonp' : 'json', $http_status )->options([ 'json_encode_param' => JSON_UNESCAPED_UNICODE | JSON_BIGINT_AS_STRING ]); } } if (!function_exists('JsonSuccess')) { function JsonSuccess(string $message = 'success', string $url = '') { return JsonMessage([], $message, $url); } } if (!function_exists('JsonError')) { function JsonError(string $message = '操作失败') { return JsonMessage($message); } } /** * 手动抛出json异常 */ if (!function_exists('ErrorException')) { function ErrorException(string $message = '', int $code = 10000, int $http_status = 200) { throw new \app\admin\ErrorException($message, $code, $http_status); } } if (!function_exists('NotFoundException')) { function NotFoundException(string $message = '', int $code = 10000, int $http_status = 200) { throw new \app\home\NotFoundException($message, $code, $http_status); } } /** * 生成唯一标志 */ if (!function_exists('uuid')) { function uuid() { $chars = md5(uniqid(mt_rand(), true)); $uuid = substr($chars, 0, 8) . substr($chars, 8, 4) . substr($chars, 12, 4) . substr($chars, 16, 4) . substr($chars, 20, 12); return $uuid; } } if (!function_exists('filter_words')) { function filter_words($str) { $farr = array( "/<(\\/?)(script|i?frame|style|html|body|title|link|meta|object|\\?|\\%)([^>]*?)>/isU", "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU", "/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|dump/is" ); $str = preg_replace($farr, '', $str); return $str; } } /** * 密码hash加密 */ // if (!function_exists('passwordHash')) { // function passwordHash(string $password) // { // return password_hash($password, PASSWORD_DEFAULT); // } // } // if (!function_exists('passwordCheck')) { // function passwordCheck(string $password, string $hash) // { // return password_verify($password, $hash); // } // } function pwd2hash(string $pwd) { return md5($pwd . md5($pwd)); } function pwdverify(string $passwd = null, string $hash = null) { try { $pwd_salt = session('pwd_salt'); if (!$pwd_salt || !is_string($pwd_salt)) { throw new Exception('pwd_salt is null.'); } if ($hash !== md5($passwd . $pwd_salt)) { throw new Exception('pwdword is error.'); } session('pwd_salt', null); return true; } catch (\Exception $e) { session('pwd_salt', null); return false; } } function pwdsalt(string $salt = null) { if (is_null($salt)) { $salt = sha1(random_bytes(10)); session('pwd_salt', $salt); return $salt; } $sess_salt = session('pwd_salt'); if (!$sess_salt) { return false; } return $sess_salt == $salt; } /** * code hash */ if (!function_exists('code_hash')) { function code_hash() { if ($hash = session('code.hash')) { return $hash; } $hash = sha1(mt_rand(1000000, 9999999)); session('code.hash', $hash); return $hash; } } if (!function_exists('code_check')) { function code_check(string $hash) { $code = session('code.hash'); session('code.hash', null); if (!empty($code) && $code === $hash) { return true; } else { return false; } } } if (!function_exists('code_check')) { function captcha_check(string $code) { if (!session('captcha')) { return false; } $key = session('captcha.key'); $code = mb_strtolower($code, 'UTF-8'); $res = password_verify($code, $key); if ($res) { session('captcha', null); } return $res; } } /** * 无限极分类 - 数组结构 * @param $list [ 分类数组 ] * @param $parentIndex [ 父类index ] * @param int $pid [ 顶级ID ] * @param int $level [ 等级 ] * @return array */ if (!function_exists('list_to_son')) { function list_to_son($list, $parentIndex = 'parent_id', $pid = 0, $level = 0, $strRepeat = '- -', &$tree = []) { foreach ($list as $key => $val) { if ($val[$parentIndex] == $pid) { $val['level'] = $level; $val['html'] = $level == 0 ? '' : str_repeat($strRepeat . ' ', $level); $tree[] = $val; list_to_son($list, $parentIndex, $val['id'], $level + 1, $strRepeat, $tree); } } return $tree; } } /** * 无限极分类 - 树状结构 * @param $items [ 分类数组 ] * @param $parentIndex [ 父类index ] * @return array */ if (!function_exists('list_to_tree')) { function list_to_tree($list, $pid = 0, $parentIndex = 'parent_id', $child = 'child') { $tree = []; foreach ($list as $key => $val) { if ($val[$parentIndex] == $pid) { unset($list[$key]); if (!empty($list)) { $children = list_to_tree($list, $val['id'], $parentIndex); if (!empty($children)) { $val[$child] = $children; } } $tree[] = $val; } } return $tree; } } /** * 根据子类id查找出所有父级分类信息 * */ if (!function_exists('get_parent_list')) { function get_parent_list($list, $id, $parentIndex = 'parent_id') { static $arr = []; foreach ($list as $val) { if ($val['id'] == $id) { //父级分类id等于所查找的id $arr[] = $val; if ($val[$parentIndex] > 0) { get_parent_list($list, $val[$parentIndex]); } } } return $arr; } } /** * 对查询结果集进行排序 * @access public * @param array $list 查询结果 * @param string $field 排序的字段名 * @param array $sortby 排序类型 * asc正向排序 desc逆向排序 nat自然排序 * @return array */ if (!function_exists('list_sort_by')) { function list_sort_by($list, $field, $sortby = 'asc') { if (is_array($list)) { $refer = $resultSet = array(); foreach ($list as $i => $data) { $refer[$i] = &$data[$field]; } switch ($sortby) { case 'asc': // 正向排序 asort($refer); break; case 'desc': // 逆向排序 arsort($refer); break; case 'nat': // 自然排序 natcasesort($refer); break; } foreach ($refer as $key => $val) { $resultSet[] = &$list[$key]; } return $resultSet; } return false; } } /** * 浏览器判断 */ if (!function_exists('is_mobile')) { function is_mobile() { if (isset($_SERVER['HTTP_USER_AGENT'])) { $clientKeywords = [ 'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile' ]; // 从HTTP_USER_AGENT中查找手机浏览器的关键字 if (preg_match("/(" . implode('|', $clientKeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) { return true; } } if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) { return true; } if (isset($_SERVER['HTTP_VIA'])) { return true; } return false; } } /** * 获取图片访问路径 */ if (!function_exists('image_url')) { function image_url(string $path) { $driver = ['image' => 'image', 'oss' => 'oss']; $name = explode(':', $path); if (!empty($driver[$name[0]])) { try { $url = app('filesystem')->disk($driver[$name[0]])->getUrl($name[1]); } catch (Exception $e) { $url = ''; } } return !empty($url) ? $url : $path; } } if (!function_exists('thumb_img')) { function thumb_img(string $path, $src = null) { $name = explode(':', $path); $temp = !empty($name[1]) ? $name[1] : $name[0]; $disk = app('filesystem')->disk('thumb'); if ($disk->has($temp)) { return $disk->getUrl($temp); } //生成缩略图 try { if (is_null($src)) { $src = image_url($path); } new app\http\service\skylar\ResizeImage($src, 200, 200, $temp); return $disk->getUrl($temp); } catch (\Exception $e) { Log::record(['file' => $e->getFile(), 'line' => $e->getLine(), 'msg' => $e->getMessage()], 'notice'); return $e->getMessage(); } } } if (!function_exists('cms_redirect')) { function cms_redirect(string $url) { throw new \think\exception\HttpResponseException(\think\Response::create($url, 'redirect', 302)); } } /** * 系统配置 * @param $key */ // if (!function_exists('setting')) { // function setting(string $key) // { // return \app\model\SystemSetting::Setting($key); // } // } /** * 系统设置 * * @Description * @example * @author uftd@qq.com * @date 2020-12-23 * @param string $key * @param array $value * @return void */ function SystemSetting(string $key, array $value = []) { $param = explode('.', $key); if (empty($value)) { $config = Cache::get(config('cache.prefix.config') . $param[0]); //直接获取缓存文件 if (empty($config)) { //缓存文件不存在就读取数据库 $res = Db::name('system_setting')->where("group", $param[0])->select(); if ($res) { foreach ($res as $k => $val) { $config[$val['key']] = $val['value']; } Cache::tag('config')->set(config('cache.prefix.config') . $param[0], $config); } } if (count($param) > 1) { return $config[$param[1]] ?? ''; } else { return $config ?? []; } } else { //更新缓存 $result = Db::name('system_setting')->where("group", $param[0])->select(); if ($result) { $temp = []; foreach ($result as $val) { $temp[$val['key']] = $val['value']; } foreach ($value as $k => $v) { $v = trim($v); $newArr = array('key' => $k, 'value' => is_array($v) ? json_encode($v) : $v, 'group' => $param[0]); if (!isset($temp[$k])) { Db::name('system_setting')->insert($newArr); //新key数据插入数据库 } else { if ($v != $temp[$k]) Db::name('system_setting')->where("key", $k)->save($newArr); //缓存key存在且值有变更新此项 } } //更新后的数据库记录 $newRes = Db::name('system_setting')->where("group", $param[0])->select(); foreach ($newRes as $rs) { $newData[$rs['key']] = $rs['value']; } } else { foreach ($value as $k => $v) { $newArr[] = array('key' => $k, 'value' => trim($v), 'group' => $param[0]); } Db::name('system_setting')->insertAll($newArr); $newData = $value; } return Cache::tag('config')->set(config('cache.prefix.config') . $param[0], $newData); } } function SkyAuth(int $auth_id, int $user_id = null) { $auth = null; if (is_null($user_id)) { /** * 从session拿,以后要改 */ $user = session('user'); $auth = !empty($user['auth_node']['node']) ? $user['auth_node']['node'] : []; if ($auth === 'all') { return true; } } if (!is_array($auth)) { return false; } return in_array($auth_id, $auth); }
作者:糖粿
来源:博客园
转载请注明原文链接:https://www.cnblogs.com/silen0119/p/16139059.html
声援博主: 如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。