常用封装之一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 = 0; $msg = $data === true ? '保存成功' : '请求成功'; 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'] = 3; // $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('ApiErrorException')) { function ApiErrorException(string $message = '', int $code = 10000, int $http_status = 200) { throw new \exception\ApiErrorException($message, $code, $http_status); } } if (!function_exists('list_to_son')) { function list_to_son($list, $index = 'id', $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, $index, $parentIndex, $val[$index], $level + 1, $strRepeat, $tree); } } return $tree; } } /** * 根据子类id查找出所有父级分类信息 * */ if (!function_exists('get_parent_list')) { function get_parent_list($list, $id, $parentIndex = 'parent_id', &$arr = []) { foreach ($list as $val) { if ($val['id'] == $id) { //父级分类id等于所查找的id $arr[] = $val; if ($val[$parentIndex] > 0) { get_parent_list($list, $val[$parentIndex], $parentIndex, $arr); } } } return $arr; } } /** * @param $string `字符串,明文或密文 * @param string $operation `DECODE表示解密,其它表示加密 * @param string $key `密匙 * @param int $expiry `密文有效期 * @return false|string */ if (!function_exists('encrypt')) { function encrypt($string, $operation = 'DECODE', $key = '123456', $expiry = 0) { // 动态密匙长度,相同的明文会生成不同密文就是依靠动态密匙 $ckey_length = 4; // 密匙 $key = md5($key); // 密匙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') { // 验证数据有效性,请看未加密明文的格式 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)); } } } /** * 系统设置 * * @Description * @example * @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('config')->where("inc_type", $param[0])->select(); if ($res) { foreach ($res as $k => $val) { $config[$val['name']] = $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('config')->where("inc_type", $param[0])->select(); if ($result) { $temp = []; foreach ($result as $val) { $temp[$val['name']] = $val['value']; } foreach ($value as $k => $v) { $v = trim($v); $newArr = array('name' => $k, 'value' => is_array($v) ? json_encode($v) : $v, 'inc_type' => $param[0]); if (!isset($temp[$k])) { Db::name('config')->insert($newArr); //新key数据插入数据库 } else { if ($v != $temp[$k]) Db::name('config')->where("name", $k)->save($newArr); //缓存key存在且值有变更新此项 } } //更新后的数据库记录 $newRes = Db::name('config')->where("inc_type", $param[0])->select(); foreach ($newRes as $rs) { $newData[$rs['name']] = $rs['value']; } } else { foreach ($value as $k => $v) { $newArr[] = array('name' => $k, 'value' => trim($v), 'inc_type' => $param[0]); } Db::name('config')->insertAll($newArr); $newData = $value; } return Cache::tag('config')->set(config('cache.prefix.config') . $param[0], $newData); } } /** * week 转换为普通日期 周的最后一天 */ if (!function_exists('weekToDate')) { function weekToDate($oW) { $oW = explode("-", $oW); //拆分o-W周 为年和周数 $year = $oW[0]; //年 $week = $oW[1]; //周数 //年初1月1是星期几,0-6,0是周日,1-6是周一到周六 $weekYearBegin = date("w", strtotime($year . "-01-01")); //年初1月1是第几周,可能是该年第一周:01,也可能是上年最后一周:52 $WYearBegin = date("W", strtotime($year . "-01-01")); //该年的第一周 if ($WYearBegin == "01") { //需要计算的周的最后一天(星期天),距离年初1月1有多少天 $days = (7 - $weekYearBegin) % 7 + (int)($week - $WYearBegin) * 7; } else { //上年的最后一周 //需要计算的周的最后一天(星期天),距离年初1月1有多少天 $days = (7 - $weekYearBegin) % 7 + (int)($week) * 7; } //因为是求最后一天(星期天),所以一定落在该年($year),或者下一年,而不会落在上一年 用$year +n days $lastDayOfW = date("Y-m-d", strtotime($year . "-01-01 +" . $days . " days")); return $lastDayOfW; } } /** * 后台系统导航栏 */ if (!function_exists('SystemNav')) { function SystemNav($uid, string $module = 'console') { $auth = app('auth')->getAuthIds($uid); $where = [ ['module', '=', $module], ['type', '=', 1], ['status', '=', 1], ]; $auth !== true && $where[] = ['id', 'in', $auth]; $nav = Cache::get(config('cache.prefix.nav') . $uid); if (empty($nav)) { $nav = Db::name('node') ->field('id, name as title, pid, web_url as path, icon as ico') ->where($where) ->order('sort asc, id asc') ->select() ->toArray(); $nav = list2tree($nav, 'id', 'pid', 'child'); Cache::tag('group')->set(config('cache.prefix.nav') . $uid, $nav); } return $nav; } } /** * 后台系统权限节点 */ if (!function_exists('SystemNode')) { function SystemNode($uid, $module = '', $pid = 0) { $auth = app('auth')->getAuthIds($uid); $where = [ ['status', '=', 1], ]; if ($auth !== true) { $where[] = ['id', 'in', $auth]; } switch ($module) { case 'work': $where[] = ['module', '=', $module]; break; case 'console': $where[] = ['module', '=', $module]; break; } $auth = Db::name('node')->field('id, name as title, pid')->where($where)->order('sort asc, id asc')->select()->toArray(); $auth = list2tree($auth, 'id', 'pid', 'children', $pid); return $auth; } } function formatting_date($date) { $temp = substr($date, 4, strlen($date)); $month = $day = ''; if (substr($temp, 0, 1) == 0) { //如果月份为单位数 $month = "0" . substr($temp, 1, 1); } else { $month = substr($temp, 0, 2);; } if (substr($temp, 2, 1) == 0) { //如果天数为单位数 $day = "0" . substr($temp, strlen($temp) - 1, 1); } else { $day = substr($temp, strlen($temp) - 2, 2);; } return substr($date, 0, 4) . '-' . $month . '-' . $day; //年月日拼接 } /** * 获取当前权限可查看的报告状态 */ if (!function_exists('MonitoringAuth')) { function MonitoringAuth($auth) { $ids = []; $node = app('auth')->getAuthIds(request()->uid); if ($node === true) { return true; } foreach ($auth as $key => $val) { if (array_intersect($val, $node)) { $ids[] = $key; } } return $ids; } } /** * 工作台权限判断 * @param integer $auth_id * @return bool */ function WorkAuth(int $auth_id, ?int $user_id = null): bool { // 调试开启 // return true; static $auths; if (is_null($user_id)) { $user_id = request()->uid; } if (!isset($auths[$user_id])) { $auths[$user_id] = app('auth')->getAuthIds($user_id); } if ($auths[$user_id] === true) { return true; } return in_array($auth_id, $auths[$user_id]); } /** * 获取当前权限可查看的报告状态 */ if (!function_exists('MessagePush')) { function MessagePush($reportId, $toId, $title, $businessType = 1, $type = \app\api\model\MessageCommon::MESSAGE_TYPE_REPORT) { if (!is_array($toId)) { $toId = [$toId]; } if (is_array($toId)) { $report = \app\api\model\MonitoringReport::where('id', $reportId)->find(); $model = new \app\api\model\Admin(); $date = date('Y年m月d日 H:i'); $wechat_todo_path = request()->domain() . '/wechat/mission'; $wechat_config = config('wechat'); $remark = ''; $report_expire_info = $report['StatusExpireText']; $report_expire_info && $remark .= '任务' . $report_expire_info . ',请尽快进行处理'; foreach ($toId as $admin_id) { $admin_id = intval($admin_id); // 添加系统消息 \app\api\model\MessageCommon::addMessage([ 'admin_id' => $admin_id, 'type' => $type, 'business_type' => $businessType, 'business_tag' => $reportId, 'message_status' => 0, 'title' => $title, 'create_time' => time() ]); // 微信推送消息 if (env('APP_ENV', 'live') != 'dev') { try { $user = $model->info($admin_id); if (!empty($user['wx_open_id'])) { \sdk\wechat\api\Wechat::message($wechat_config)->sendTemplateMessage([ 'touser' => $user['wx_open_id'], // 用户的openid 'template_id' => 'WX5PQPRuEPJGRt9oJm1yqiAhuJz-7oK0APjzzIYoJ_c', 'url' => $wechat_todo_path, 'data' => [ 'first' => ['value' => '您有新的任务待处理'], 'keyword1' => ['value' => $title], 'keyword2' => ['value' => $report['number']], 'keyword3' => ['value' => $date], // 操作时间 'keyword4' => ['value' => \app\api\model\MessageCommon::$message_type[$type] ?? ''], // 流程摘要 'remark' => ['value' => $remark], // 消息最后备注 ] ]); } } catch (Exception $e) { Log::write([ 'report_id' => $reportId, 'message' => $e->getMessage() ], 'alert'); } } } } } } /** * 获取报告权限用户 */ if (!function_exists('MonitoringAuthUser')) { function MonitoringAuthUser($node, $param = []) { $checkAuth = function ($users) use ($node) { $list = []; foreach ($users as $val) { if ($val['user_auth'] === true) { $list[] = $val['admin_id']; } else { if (is_array($node)) { if (array_intersect($node, $val['user_auth'])) { $list[] = $val['admin_id']; } } else { if (in_array($node, $val['user_auth'])) { $list[] = $val['admin_id']; } } } } return $list; }; $where = [ ['role', '=', 2], ['status', '=', 1], ]; if (is_array($param) || is_string($param)) { if (!empty($param)) { $where[] = ['dept_id', 'in', $param]; } $user = (new \app\api\model\Admin())->field('admin_id')->where($where)->append(['user_auth'])->select()->toArray(); } elseif (is_callable($param)) { $user = (new \app\api\model\Admin())->field('admin_id')->where($where)->where($param)->append(['user_auth'])->select()->toArray(); } return $checkAuth($user); } } /** * 报告状态 */ if (!function_exists('MonitoringStatus')) { function MonitoringStatus() { $reportStatus = Cache::get('report_status'); if (empty($reportStatus)) { $reportStatus = Db::name('monitoring_status')->field('id, name, expire')->select()->toArray(); Cache::set('report_status', $reportStatus, 7200); } return $reportStatus; } } /** * 部门单位 */ if (!function_exists('GovDepartment')) { function GovDepartment() { $GovDepartment = Db::name('gov_department')->field('id, name, pid, bpid')->order('sort asc, id desc')->select()->toArray(); return $GovDepartment; } } if (!function_exists('getReportSpic')) { function getReportSpic($spic) { return 'http://' . env('DOMAIN.DATA_CENTER') . '/' . $spic; } } /** * 生成唯一标志 */ if (!function_exists('uuid')) { function uuid() { if (function_exists('uuid_create')) { $uuid = str_replace('-', '', uuid_create()); } else { $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): bool { return password_verify($password, $hash); } } // GCJ-02(火星,高德) 坐标转换成 BD-09(百度) 坐标//@param lng 火星经度//@param lat 火星纬度 function gaoDeToBaidu($lng, $lat) { $x_pi = 3.14159265358979324 * 3000.0 / 180.0; $x = $lng; $y = $lat; $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi); $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi); $data['lng'] = $z * cos($theta) + 0.0065; $data['lat'] = $z * sin($theta) + 0.006; return $data; } // BD-09(百度) 坐标转换成 GCJ-02(火星,高德) 坐标//@param lng 火星经度//@param lat 火星纬度 function baiduToGaoDe($lng, $lat) { $x_pi = 3.14159265358979324 * 3000.0 / 180.0; $x = $lng - 0.0065; $y = $lat - 0.006; $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi); $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi); $data['lng'] = $z * cos($theta); $data['lat'] = $z * sin($theta); return $data; } // BD-09(百度) 坐标转换成 wgs84 坐标//@param gg_lon 火星经度//@param gg_lat 火星纬度 function baiduToWgs84($bd_lon, $bd_lat) { //定义一些常量 $PI = 3.1415926535897932384626; $a = 6378245.0; $ee = 0.00669342162296594323; //百度坐标系 (BD-09) 与 火星坐标系 (GCJ-02)的转换 $x_pi = 3.14159265358979324 * 3000.0 / 180.0; $x = $bd_lon - 0.0065; $y = $bd_lat - 0.006; $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi); $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi); $lng = $z * cos($theta) + 0.0065; $lat = $z * sin($theta) + 0.006; //GCJ02 转换为 WGS84 $dlat = transformlat($lng - 105.0, $lat - 35.0); $dlng = transformlng($lng - 105.0, $lat - 35.0); $radlat = $lat / 180.0 * $PI; $magic = sin($radlat); $magic = 1 - $ee * $magic * $magic; $sqrtmagic = sqrt($magic); $dlat = ($dlat * 180.0) / (($a * (1 - $ee)) / ($magic * $sqrtmagic) * $PI); $dlng = ($dlng * 180.0) / ($a / $sqrtmagic * cos($radlat) * $PI); $mglat = $lat + $dlat; $mglng = $lng + $dlng; return [$lng * 2 - $mglng, $lat * 2 - $mglat]; } function transformlat($lng, $lat) { //定义一些常量 $PI = 3.1415926535897932384626; $ret = -100.0 + 2.0 * $lng + 3.0 * $lat + 0.2 * $lat * $lat + 0.1 * $lng * $lat + 0.2 * sqrt(abs($lng)); $ret += (20.0 * sin(6.0 * $lng * $PI) + 20.0 * sin(2.0 * $lng * $PI)) * 2.0 / 3.0; $ret += (20.0 * sin($lat * $PI) + 40.0 * sin($lat / 3.0 * $PI)) * 2.0 / 3.0; $ret += (160.0 * sin($lat / 12.0 * $PI) + 320 * sin($lat * $PI / 30.0)) * 2.0 / 3.0; return $ret; } function transformlng($lng, $lat) { //定义一些常量 $PI = 3.1415926535897932384626; $ret = 300.0 + $lng + 2.0 * $lat + 0.1 * $lng * $lng + 0.1 * $lng * $lat + 0.1 * sqrt(abs($lng)); $ret += (20.0 * sin(6.0 * $lng * $PI) + 20.0 * sin(2.0 * $lng * $PI)) * 2.0 / 3.0; $ret += (20.0 * sin($lng * $PI) + 40.0 * sin($lng / 3.0 * $PI)) * 2.0 / 3.0; $ret += (150.0 * sin($lng / 12.0 * $PI) + 300.0 * sin($lng / 30.0 * $PI)) * 2.0 / 3.0; return $ret; } /** * WGS84转GCj02(北斗转高德) * @param lng * @param lat * @returns {*[]} */ function WGS84ToGCJ02($lng, $lat) { $PI = 3.1415926535897932384626; $a = 6378245.0; $ee = 0.00669342162296594323; if (out_of_china($lng, $lat)) { return [$lng, $lat]; } else { $dlat = transformlat($lng - 105.0, $lat - 35.0); $dlng = transformlng($lng - 105.0, $lat - 35.0); $radlat = $lat / 180.0 * $PI; $magic = sin($radlat); $magic = 1 - $ee * $magic * $magic; $sqrtmagic = sqrt($magic); $dlat = ($dlat * 180.0) / (($a * (1 - $ee)) / ($magic * $sqrtmagic) * $PI); $dlng = ($dlng * 180.0) / ($a / $sqrtmagic * cos($radlat) * $PI); $mglat = $lat + $dlat; $mglng = $lng + $dlng; return [$mglng, $mglat]; } } /** * 多个坐标点获取中心坐标 */ function getPointCenter($data = []) { if (!is_array($data)) return FALSE; $num_coords = count($data); $X = 0.0; $Y = 0.0; $Z = 0.0; foreach ($data as $coord) { $lon = deg2rad($coord[0]); $lat = deg2rad($coord[1]); $a = cos($lat) * cos($lon); $b = cos($lat) * sin($lon); $c = sin($lat); $X += $a; $Y += $b; $Z += $c; } $X /= $num_coords; $Y /= $num_coords; $Z /= $num_coords; $lon = atan2($Y, $X); $hyp = sqrt($X * $X + $Y * $Y); $lat = atan2($Z, $hyp); return [rad2deg($lon), rad2deg($lat)]; } /** * 判断是否在国内,不在国内则不做偏移 * @param $lng * @param $lat * @returns {boolean} */ function out_of_china($lng, $lat) { return ($lng < 72.004 || $lng > 137.8347) || (($lat < 0.8293 || $lat > 55.8271) || false); } function qrcode_path(string $txt) { return request()->domain() . '/api/auth/qr?txt=' . sencrypt($txt); } function sredirect(string $url, int $http_status = 302) { throw new \think\exception\HttpResponseException(\think\Response::create($url, 'redirect', $http_status)); } if (!function_exists('sendMail')) { function sendMail($recipients, string $subject = null, string $body = '', array $ext = []) { static $_mail, $_setting; // $config = config('mail'); empty($_setting) && $_setting = Db::name('Config')->column('value', 'name'); $config = [ 'host' => $_setting['email_host'], 'from_email' => $_setting['from_email'] ?? '', 'username' => $_setting['email_smtp_user'] ?? '', 'password' => $_setting['email_smtp_pass'] ?? '', 'port' => $_setting['email_port'] ?? 587, 'from_name' => $_setting['from_name'] ?? '****', ]; $sn = md5(serialize($config)); try { $sender = $ext['sender'] ?? $config['from_name']; $attachment = $ext['attachment'] ?? null; if (!isset($_mail[$sn])) { $_mail[$sn] = new \sdk\PHPMailer\PHPMailer(true); //Server settings $_mail[$sn]->SMTPDebug = \sdk\PHPMailer\SMTP::DEBUG_CLIENT; // Enable verbose debug output $_mail[$sn]->Debugoutput = 'error_log'; // Enable verbose debug output $_mail[$sn]->isSMTP(); // Send using SMTP $_mail[$sn]->Host = $config['host']; // Set the SMTP server to send through $_mail[$sn]->SMTPAuth = true; // Enable SMTP authentication $_mail[$sn]->Username = $config['username']; $_mail[$sn]->Password = $config['password']; $_mail[$sn]->SMTPSecure = $config['port'] == 587 ? \sdk\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS : \sdk\PHPMailer\PHPMailer::ENCRYPTION_SMTPS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged $_mail[$sn]->Port = $config['port']; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above $_mail[$sn]->XMailer = 'Server Copyright CC Ltd.'; # 标识邮件头 } $_mail[$sn]->setFrom($config['from_email'], $sender); if (is_array($recipients)) { if (empty($recipients['address'])) { throw new Exception('adddress is null'); } foreach ($recipients['address'] as $address => $nickname) { $_mail[$sn]->addAddress($address, $nickname); } if (!empty($recipients['cc']) && is_array($recipients['cc'])) { foreach ($recipients['cc'] as $address => $nickname) { $_mail[$sn]->addCC($address, $nickname); } } if (!empty($recipients['bcc']) && is_array($recipients['bcc'])) { foreach ($recipients['cc'] as $address => $nickname) { $_mail[$sn]->addBCC($address, $nickname); } } } elseif (is_string($recipients)) { $_mail[$sn]->addAddress($recipients); } else { throw new Exception('adddress is null'); } if (is_array($attachment)) { foreach ($attachment as $filename => $alias) { $alias ? $_mail[$sn]->addAttachment($filename, $alias) : $_mail[$sn]->addAttachment($filename); } } elseif (is_string($attachment)) { $_mail[$sn]->addAttachment($attachment); } $_mail[$sn]->isHTML(true); // Set email format to HTML $_mail[$sn]->Subject = $subject ?? '无主题'; $_mail[$sn]->Body = $body; return $_mail[$sn]->send(); } catch (Exception $e) { \think\facade\Log::record($e->getMessage()); return false; } } }
作者:糖粿
来源:博客园
转载请注明原文链接:https://www.cnblogs.com/silen0119/p/15128344.html
声援博主: 如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。