Helpers.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <?php
  2. use App\Service\Util\Support\Trace\CustomizeLogger;
  3. use Illuminate\Http\UploadedFile;
  4. use Modules\Common\Support\Upload\Uploader;
  5. use PHPMailer\PHPMailer\PHPMailer;
  6. use Illuminate\Support\Str;
  7. use Illuminate\Support\Facades\Http;
  8. if(!function_exists("str_decode")){
  9. /**
  10. * 字符解密
  11. * name: str_decode
  12. * @param $str
  13. * @return int
  14. * date 2022/09/27 11:38
  15. */
  16. function str_decode($str){
  17. $decode = Hashids::decode($str);
  18. $decode = is_array($decode) ? array_shift($decode) : $decode;
  19. if(empty($decodeBid)){
  20. myLog("StrDecodeError")->info("str : {$str}, decode : ".var_export($decode,true));
  21. }
  22. return intval($decode);
  23. }
  24. }
  25. if (!function_exists('str_encode')){
  26. /***
  27. * 字符加密
  28. * name: str_decode
  29. * @param mixed $str
  30. * @return mixed
  31. * date 2022/09/27 11:38
  32. */
  33. function str_encode($str)
  34. {
  35. return Hashids::encode($str);
  36. }
  37. }
  38. if (!function_exists('is_empty')){
  39. /**
  40. * 判断数据是否为空
  41. * name: is_empty
  42. * @param $data
  43. * @return bool 空返回true 非空返回false
  44. * date 2022/11/18 11:39
  45. */
  46. function is_empty($data): bool
  47. {
  48. if (is_object($data)){
  49. if (method_exists($data,'isEmpty')){
  50. return $data->isEmpty();
  51. }
  52. return empty(get_object_vars($data));
  53. }
  54. return empty($data);
  55. }
  56. }
  57. if (!function_exists('column_str')) {
  58. /**
  59. * 列转化
  60. * @param $key
  61. * @return string
  62. */
  63. function column_str($key)
  64. {
  65. $array = array(
  66. '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',
  67. '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',
  68. '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',
  69. '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',
  70. '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',
  71. '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'
  72. );
  73. return $array[$key];
  74. }
  75. }
  76. if (!function_exists('column')) {
  77. /**
  78. * Excel 列转化
  79. * @param $key
  80. * @param mixed $columns
  81. * @return string
  82. */
  83. function column($key, $columns = 1)
  84. {
  85. return column_str($key) . $columns;
  86. }
  87. }
  88. if (!function_exists('export')) {
  89. /***
  90. * @param mixed $list 导出的数据
  91. * @param mixed $params 标题设置
  92. * @throws PHPExcel_Exception
  93. * @throws PHPExcel_Reader_Exception
  94. */
  95. function export($list, $params = array())
  96. {
  97. if (PHP_SAPI == 'cli') {
  98. die('This example should only be run from a Web Browser');
  99. }
  100. $excel = new \PHPExcel();
  101. $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");
  102. $sheet = $excel->setActiveSheetIndex(0);
  103. $rowNum = 1;
  104. foreach ($params['columns'] as $key => $column) {
  105. $sheet->setCellValue(column($key, $rowNum), $column['title']);
  106. if (!empty($column['width'])) {
  107. $sheet->getColumnDimension(column_str($key))->setWidth($column['width']);
  108. }
  109. }
  110. $rowNum++;
  111. $len = count($params['columns']);;
  112. foreach ($list as $row) {
  113. for ($i = 0; $i < $len; $i++) {
  114. $value = $row[$params['columns'][$i]['field']] ?? '';
  115. $sheet->setCellValue(column($i, $rowNum), $value);
  116. }
  117. $rowNum++;
  118. }
  119. $excel->getActiveSheet()->setTitle($params['title']);
  120. $filename = urlencode($params['title'] . '-' . date('Y-m-d H:i', time()));
  121. ob_end_clean();
  122. header('Content-Type: application/octet-stream');
  123. header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
  124. header('Cache-Control: max-age=0');
  125. $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
  126. $writer->save("php://output");
  127. }
  128. }
  129. /**
  130. * 发送邮件
  131. * @param $to_email 收件人
  132. * <pre>
  133. * [
  134. * ['address' => 'aa@bb.com', 'name' => 'aa'],
  135. * ......,
  136. * ['address' => 'aa@bb.com', 'name' => 'aa'],
  137. * ]
  138. * </pre>
  139. * @param $param
  140. * <pre>
  141. * [
  142. * 'subject' => "xxxxxx" , // 标题
  143. * 'body' => 'xxxx', // 邮件内容,如果内容需要换行,使用 <br>
  144. * ]
  145. * </pre>
  146. * @param string $accessory
  147. */
  148. function sendEmail($to_email, $param, $accessory = '')
  149. {
  150. $mail = new PHPMailer(true);// Passing `true` enables exceptions
  151. $mail->CharSet = 'UTF-8';//'UTF-8';
  152. try {
  153. $mail->SMTPDebug = 0; // Enable verbose debug output
  154. $mail->isSMTP(); // Set mailer to use SMTP
  155. $mail->Host = 'smtp.exmail.qq.com'; //$mail->Host = 'smtp.126.com'; Specify main and backup SMTP servers
  156. $mail->SMTPAuth = true; // Enable SMTP authentication
  157. $mail->Username = 'sendemail01@zkanshu.com'; //$mail->Username = 'tushengxiang@126.com'; // SMTP username
  158. $mail->Password = '5jBekvU2jJ2Ketue'; // SMTP password
  159. $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
  160. $mail->Port = 465; // TCP port to connect to
  161. //Recipients
  162. $mail->setFrom('sendemail01@zkanshu.com', 'System');
  163. $mail->addAddress($to_email[0]['address'], $to_email[0]['name']);
  164. array_shift($to_email);
  165. foreach ($to_email as $item) {
  166. $mail->addCC($item['address'], $item['name']); // Add a recipient
  167. }
  168. //Attachments
  169. if ($accessory) $mail->addAttachment($accessory);// Add attachments
  170. $mail->isHTML(true);
  171. $mail->Subject = $param['subject'];
  172. $mail->Body = $param['body'];
  173. $mail->send();
  174. } catch (\Exception $e) {
  175. \Log::warning('发送邮件失败:' . $mail->ErrorInfo, $e->getTrace());
  176. }
  177. }
  178. /**
  179. * 获取日志对象
  180. * @param $fileName 保存日志的名称
  181. * @param string $logLevel 日志等级
  182. * @param int $logDays 日志保留的天数
  183. * @return \Psr\Log\LoggerInterface
  184. */
  185. function myLog($fileName, $logLevel='info', $logDays = 7) :\Psr\Log\LoggerInterface{
  186. return CustomizeLogger::getLogger($fileName, $logLevel, $logDays);
  187. }
  188. if (!function_exists('get_date')) {
  189. /**
  190. * 获取时间
  191. * @param mixed $time
  192. * @param mixed $format
  193. * @return false|string
  194. */
  195. function get_date($time = 0, $format = "Y-m-d H:i:s")
  196. {
  197. $time = intval($time);
  198. if ($time <= 0) {
  199. $time = time();
  200. }
  201. return date($format, $time);
  202. }
  203. }
  204. /**
  205. * 华为obs文件上传
  206. * @param UploadedFile $file
  207. * @return array
  208. */
  209. function huaweiObsUpload(UploadedFile $file) {
  210. $uploader = new Uploader();
  211. $uploader->setDriver('HuaweiOBS');
  212. return $uploader->upload($file);
  213. }
  214. if (!function_exists("random")) {
  215. /**
  216. * [random 生成随机字符串]
  217. * @wzq
  218. * @DtuateTime 2020-09-08
  219. * @param [type] $length [长度]
  220. * @param mixed $numeric [是否仅是数字]
  221. * @return string [type] [string]
  222. * @version v1
  223. */
  224. function random($length, $numeric = false): string
  225. {
  226. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  227. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  228. if ($numeric) {
  229. $hash = '';
  230. } else {
  231. $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
  232. $length--;
  233. }
  234. $max = strlen($seed) - 1;
  235. for ($i = 0; $i < $length; $i++) {
  236. $hash .= $seed[mt_rand(0, $max)] ?? "";
  237. }
  238. return $hash;
  239. }
  240. }
  241. function dingTalkAlertException(\Throwable $exception)
  242. {
  243. $code = $exception->getCode();
  244. if($code >0){
  245. return ;
  246. }
  247. $url = 'https://oapi.dingtalk.com/robot/send?access_token=07829435258bf07c5f0b0a0a84c50c4bebc15e585b3040ad43c5e94e213a9bba';
  248. $key = 'SEC74f8117d06ae59a7edde24cd9706334dbdd09b5d5734522f060272bdfbfb1abd';
  249. $timestamp = time()*1000;
  250. $string = $timestamp . "\n" . $key;
  251. $sign = hash_hmac('sha256',$string,$key,true);
  252. $sign = urlencode(base64_encode($sign));
  253. $url .= '&'.http_build_query(['timestamp'=>$timestamp,'sign'=>$sign]);
  254. $class_name = get_class($exception);
  255. $app_path = app_path();
  256. $trace = $exception->getTraceAsString();
  257. $trace_list = preg_split('/\n/',$trace);
  258. $error = '';
  259. foreach($trace_list as $item){
  260. if( Str::contains($item,$app_path)){
  261. $error .= '- '.trim(preg_replace('/^(\#\d+)/','',$item))."\n";
  262. }
  263. }
  264. $hostname = gethostname();
  265. $ip = '';
  266. $ssh = getenv('SSH_CONNECTION');
  267. if($ssh){
  268. $ssh_list = explode(' ',$ssh);
  269. $ip = isset($ssh_list[2]) ? $ssh_list[2]:'';
  270. }
  271. $result = [
  272. 'message'=>$exception->getMessage(),
  273. 'class_name'=>$class_name,
  274. 'app_path'=>$app_path,
  275. 'error'=>$error,
  276. 'hostname'=>$hostname.' - '.$ip
  277. ];
  278. try{
  279. $response = Http::post($url,[
  280. 'msgtype' => 'markdown',
  281. 'markdown' => [
  282. 'title'=>basename (base_path()).'异常',
  283. 'text' => sprintf("### 错误信息: \n%s\n ### 异常详情: \n%s\n### 项目路径: \n%s\n\n ### 主机名:\n%s\n",
  284. $result['class_name'].':'.$result['message'],$result['error'],$result['app_path'],$result['hostname'])
  285. ]
  286. ]);
  287. }catch(\Exception $e){
  288. }
  289. }