123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335 |
- <?php
- use App\Service\Util\Support\Trace\CustomizeLogger;
- use Illuminate\Http\UploadedFile;
- use Modules\Common\Support\Upload\Uploader;
- use PHPMailer\PHPMailer\PHPMailer;
- use Illuminate\Support\Str;
- use Illuminate\Support\Facades\Http;
- if(!function_exists("str_decode")){
- /**
- * 字符解密
- * name: str_decode
- * @param $str
- * @return int
- * date 2022/09/27 11:38
- */
- function str_decode($str){
- $decode = Hashids::decode($str);
- $decode = is_array($decode) ? array_shift($decode) : $decode;
- if(empty($decodeBid)){
- myLog("StrDecodeError")->info("str : {$str}, decode : ".var_export($decode,true));
- }
- return intval($decode);
- }
- }
- if (!function_exists('str_encode')){
- /***
- * 字符加密
- * name: str_decode
- * @param mixed $str
- * @return mixed
- * date 2022/09/27 11:38
- */
- function str_encode($str)
- {
- return Hashids::encode($str);
- }
- }
- if (!function_exists('is_empty')){
- /**
- * 判断数据是否为空
- * name: is_empty
- * @param $data
- * @return bool 空返回true 非空返回false
- * date 2022/11/18 11:39
- */
- function is_empty($data): bool
- {
- if (is_object($data)){
- if (method_exists($data,'isEmpty')){
- return $data->isEmpty();
- }
- return empty(get_object_vars($data));
- }
- return empty($data);
- }
- }
- if (!function_exists('column_str')) {
- /**
- * 列转化
- * @param $key
- * @return string
- */
- function column_str($key)
- {
- $array = array(
- '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',
- 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ',
- 'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ',
- 'CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CI', 'CJ', 'CK', 'CL', 'CM', 'CN', 'CO', 'CP', 'CQ', 'CR', 'CS', 'CT', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ',
- 'DA', 'DB', 'DC', 'DD', 'DE', 'DF', 'DG', 'DH', 'DI', 'DJ', 'DK', 'DL', 'DM', 'DN', 'DO', 'DP', 'DQ', 'DR', 'DS', 'DT', 'DU', 'DV', 'DW', 'DX', 'DY', 'DZ',
- 'EA', 'EB', 'EC', 'ED', 'EE', 'EF', 'EG', 'EH', 'EI', 'EJ', 'EK', 'EL', 'EM', 'EN', 'EO', 'EP', 'EQ', 'ER', 'ES', 'ET', 'EU', 'EV', 'EW', 'EX', 'EY', 'EZ'
- );
- return $array[$key];
- }
- }
- if (!function_exists('column')) {
- /**
- * Excel 列转化
- * @param $key
- * @param mixed $columns
- * @return string
- */
- function column($key, $columns = 1)
- {
- return column_str($key) . $columns;
- }
- }
- if (!function_exists('export')) {
- /***
- * @param mixed $list 导出的数据
- * @param mixed $params 标题设置
- * @throws PHPExcel_Exception
- * @throws PHPExcel_Reader_Exception
- */
- function export($list, $params = array())
- {
- if (PHP_SAPI == 'cli') {
- die('This example should only be run from a Web Browser');
- }
- $excel = new \PHPExcel();
- $excel->getProperties()->setCreator("植宇")->setLastModifiedBy("植宇")->setTitle("Office 2007 XLSX Test Document")->setSubject("Office 2007 XLSX Test Document")->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")->setKeywords("office 2007 openxml php")->setCategory("report file");
- $sheet = $excel->setActiveSheetIndex(0);
- $rowNum = 1;
- foreach ($params['columns'] as $key => $column) {
- $sheet->setCellValue(column($key, $rowNum), $column['title']);
- if (!empty($column['width'])) {
- $sheet->getColumnDimension(column_str($key))->setWidth($column['width']);
- }
- }
- $rowNum++;
- $len = count($params['columns']);;
- foreach ($list as $row) {
- for ($i = 0; $i < $len; $i++) {
- $value = $row[$params['columns'][$i]['field']] ?? '';
- $sheet->setCellValue(column($i, $rowNum), $value);
- }
- $rowNum++;
- }
- $excel->getActiveSheet()->setTitle($params['title']);
- $filename = urlencode($params['title'] . '-' . date('Y-m-d H:i', time()));
- ob_end_clean();
- header('Content-Type: application/octet-stream');
- header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
- header('Cache-Control: max-age=0');
- $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
- $writer->save("php://output");
- }
- }
- /**
- * 发送邮件
- * @param $to_email 收件人
- * <pre>
- * [
- * ['address' => 'aa@bb.com', 'name' => 'aa'],
- * ......,
- * ['address' => 'aa@bb.com', 'name' => 'aa'],
- * ]
- * </pre>
- * @param $param
- * <pre>
- * [
- * 'subject' => "xxxxxx" , // 标题
- * 'body' => 'xxxx', // 邮件内容,如果内容需要换行,使用 <br>
- * ]
- * </pre>
- * @param string $accessory
- */
- function sendEmail($to_email, $param, $accessory = '')
- {
- $mail = new PHPMailer(true);// Passing `true` enables exceptions
- $mail->CharSet = 'UTF-8';//'UTF-8';
- try {
- $mail->SMTPDebug = 0; // Enable verbose debug output
- $mail->isSMTP(); // Set mailer to use SMTP
- $mail->Host = 'smtp.exmail.qq.com'; //$mail->Host = 'smtp.126.com'; Specify main and backup SMTP servers
- $mail->SMTPAuth = true; // Enable SMTP authentication
- $mail->Username = 'sendemail01@zkanshu.com'; //$mail->Username = 'tushengxiang@126.com'; // SMTP username
- $mail->Password = '5jBekvU2jJ2Ketue'; // SMTP password
- $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
- $mail->Port = 465; // TCP port to connect to
- //Recipients
- $mail->setFrom('sendemail01@zkanshu.com', 'System');
- $mail->addAddress($to_email[0]['address'], $to_email[0]['name']);
- array_shift($to_email);
- foreach ($to_email as $item) {
- $mail->addCC($item['address'], $item['name']); // Add a recipient
- }
- //Attachments
- if ($accessory) $mail->addAttachment($accessory);// Add attachments
- $mail->isHTML(true);
- $mail->Subject = $param['subject'];
- $mail->Body = $param['body'];
- $mail->send();
- } catch (\Exception $e) {
- \Log::warning('发送邮件失败:' . $mail->ErrorInfo, $e->getTrace());
- }
- }
- /**
- * 获取日志对象
- * @param $fileName 保存日志的名称
- * @param string $logLevel 日志等级
- * @param int $logDays 日志保留的天数
- * @return \Psr\Log\LoggerInterface
- */
- function myLog($fileName, $logLevel='info', $logDays = 7) :\Psr\Log\LoggerInterface{
- return CustomizeLogger::getLogger($fileName, $logLevel, $logDays);
- }
- if (!function_exists('get_date')) {
- /**
- * 获取时间
- * @param mixed $time
- * @param mixed $format
- * @return false|string
- */
- function get_date($time = 0, $format = "Y-m-d H:i:s")
- {
- $time = intval($time);
- if ($time <= 0) {
- $time = time();
- }
- return date($format, $time);
- }
- }
- /**
- * 华为obs文件上传
- * @param UploadedFile $file
- * @return array
- */
- function huaweiObsUpload(UploadedFile $file) {
- $uploader = new Uploader();
- $uploader->setDriver('HuaweiOBS');
- return $uploader->upload($file);
- }
- if (!function_exists("random")) {
- /**
- * [random 生成随机字符串]
- * @wzq
- * @DtuateTime 2020-09-08
- * @param [type] $length [长度]
- * @param mixed $numeric [是否仅是数字]
- * @return string [type] [string]
- * @version v1
- */
- function random($length, $numeric = false): string
- {
- $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
- $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
- if ($numeric) {
- $hash = '';
- } else {
- $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
- $length--;
- }
- $max = strlen($seed) - 1;
- for ($i = 0; $i < $length; $i++) {
- $hash .= $seed[mt_rand(0, $max)] ?? "";
- }
- return $hash;
- }
- }
- function dingTalkAlertException(\Throwable $exception)
- {
- $code = $exception->getCode();
- if($code >0){
- return ;
- }
- $url = 'https://oapi.dingtalk.com/robot/send?access_token=07829435258bf07c5f0b0a0a84c50c4bebc15e585b3040ad43c5e94e213a9bba';
- $key = 'SEC74f8117d06ae59a7edde24cd9706334dbdd09b5d5734522f060272bdfbfb1abd';
- $timestamp = time()*1000;
- $string = $timestamp . "\n" . $key;
- $sign = hash_hmac('sha256',$string,$key,true);
- $sign = urlencode(base64_encode($sign));
- $url .= '&'.http_build_query(['timestamp'=>$timestamp,'sign'=>$sign]);
- $class_name = get_class($exception);
- $app_path = app_path();
- $trace = $exception->getTraceAsString();
- $trace_list = preg_split('/\n/',$trace);
- $error = '- '.$exception->getFile().':'.$exception->getLine()."\n";
- foreach($trace_list as $item){
- if( Str::contains($item,$app_path)){
- $error .= '- '.trim(preg_replace('/^(\#\d+)/','',$item))."\n";
- }
- }
- $hostname = gethostname();
- $ip = '';
- $ssh = getenv('SSH_CONNECTION');
- if($ssh){
- $ssh_list = explode(' ',$ssh);
- $ip = isset($ssh_list[2]) ? $ssh_list[2]:'';
- }
- if(!$ip){
- $ip = trim( shell_exec(" eth0 |grep 'inet ' 2>/dev/null |awk '{print $2}' ") );
- }
- $result = [
- 'message'=>$exception->getMessage(),
- 'class_name'=>$class_name,
- 'app_path'=>$app_path,
- 'error'=>$error,
- 'hostname'=>$hostname.' - '.$ip
- ];
- try{
- $response = Http::post($url,[
- 'msgtype' => 'markdown',
- 'markdown' => [
- 'title'=>basename (base_path()).'异常',
- 'text' => sprintf("### 错误信息: \n%s\n ### 异常详情: \n%s\n### 项目路径: \n%s\n\n ### 主机名:\n%s\n",
- $result['class_name'].':'.$result['message'],$result['error'],$result['app_path'],$result['hostname'])
- ]
- ]);
- }catch(\Exception $e){
- }
-
- }
|