Helpers.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. <?php
  2. use Illuminate\Http\UploadedFile;
  3. use Illuminate\Support\Facades\DB;
  4. use Modules\Common\Support\Trace\TraceContext;
  5. use Modules\Common\Support\Upload\Uploader;
  6. use PhpOffice\PhpSpreadsheet\IOFactory;
  7. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  8. use Modules\Common\Support\Trace\CustomizeLogger;
  9. use PHPMailer\PHPMailer\PHPMailer;
  10. use Illuminate\Support\Str;
  11. use Illuminate\Support\Facades\Http;
  12. if(!function_exists("str_decode")){
  13. /**
  14. * 字符解密
  15. * name: str_decode
  16. * @param $str
  17. * @return int
  18. * date 2022/09/27 11:38
  19. */
  20. function str_decode($str){
  21. $decode = Hashids::decode($str);
  22. $decode = is_array($decode) ? array_shift($decode) : $decode;
  23. if(empty($decodeBid)){
  24. myLog("StrDecodeError")->info("str : {$str}, decode : ".var_export($decode,true));
  25. }
  26. return intval($decode);
  27. }
  28. }
  29. if (!function_exists('str_encode')){
  30. /***
  31. * 字符加密
  32. * name: str_decode
  33. * @param mixed $str
  34. * @return mixed
  35. * date 2022/09/27 11:38
  36. */
  37. function str_encode($str)
  38. {
  39. return Hashids::encode($str);
  40. }
  41. }
  42. if (!function_exists('is_empty')){
  43. /**
  44. * 判断数据是否为空
  45. * name: is_empty
  46. * @param $data
  47. * @return bool 空返回true 非空返回false
  48. * date 2022/11/18 11:39
  49. */
  50. function is_empty($data): bool
  51. {
  52. if (is_object($data)){
  53. if (method_exists($data,'isEmpty')){
  54. return $data->isEmpty();
  55. }
  56. return empty(get_object_vars($data));
  57. }
  58. return empty($data);
  59. }
  60. }
  61. if (!function_exists('column_str')) {
  62. /**
  63. * 列转化
  64. * @param $key
  65. * @return string
  66. */
  67. function column_str($key)
  68. {
  69. $array = array(
  70. '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',
  71. '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',
  72. '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',
  73. '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',
  74. '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',
  75. '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'
  76. );
  77. return $array[$key];
  78. }
  79. }
  80. if (!function_exists('column')) {
  81. /**
  82. * Excel 列转化
  83. * @param $key
  84. * @param mixed $columns
  85. * @return string
  86. */
  87. function column($key, $columns = 1)
  88. {
  89. return column_str($key) . $columns;
  90. }
  91. }
  92. if (!function_exists('export')) {
  93. /***
  94. * @param mixed $list 导出的数据
  95. * @param mixed $params 标题设置
  96. * @throws PHPExcel_Exception
  97. * @throws PHPExcel_Reader_Exception
  98. */
  99. function export($list, $params = array())
  100. {
  101. if (PHP_SAPI == 'cli') {
  102. die('This example should only be run from a Web Browser');
  103. }
  104. $excel = new \PHPExcel();
  105. $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");
  106. $sheet = $excel->setActiveSheetIndex(0);
  107. $rowNum = 1;
  108. foreach ($params['columns'] as $key => $column) {
  109. $sheet->setCellValue(column($key, $rowNum), $column['title']);
  110. if (!empty($column['width'])) {
  111. $sheet->getColumnDimension(column_str($key))->setWidth($column['width']);
  112. }
  113. }
  114. $rowNum++;
  115. $len = count($params['columns']);;
  116. foreach ($list as $row) {
  117. for ($i = 0; $i < $len; $i++) {
  118. $value = $row[$params['columns'][$i]['field']] ?? '';
  119. $sheet->setCellValue(column($i, $rowNum), $value);
  120. }
  121. $rowNum++;
  122. }
  123. $excel->getActiveSheet()->setTitle($params['title']);
  124. $filename = urlencode($params['title'] . '-' . date('Y-m-d H:i', time()));
  125. ob_end_clean();
  126. header('Content-Type: application/octet-stream');
  127. header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
  128. header('Cache-Control: max-age=0');
  129. $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
  130. $writer->save("php://output");
  131. }
  132. }
  133. /**
  134. * 输出到浏览器(需要设置header头)
  135. * @param string $fileName 文件名
  136. * @param string $fileType 文件类型
  137. */
  138. function excelBrowserExport($fileName, $fileType) {
  139. //文件名称校验
  140. if(!$fileName) {
  141. trigger_error('文件名不能为空', E_USER_ERROR);
  142. }
  143. //Excel文件类型校验
  144. $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];
  145. if(!in_array($fileType, $type)) {
  146. trigger_error('未知文件类型', E_USER_ERROR);
  147. }
  148. if($fileType == 'Excel2007' || $fileType == 'Xlsx') {
  149. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  150. header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
  151. header('Cache-Control: max-age=0');
  152. } else { //Excel5
  153. header('Content-Type: application/vnd.ms-excel');
  154. header('Content-Disposition: attachment;filename="'.$fileName.'.xls"');
  155. header('Cache-Control: max-age=0');
  156. }
  157. }
  158. /**
  159. * 导出excel
  160. * @param $header 第一行,表头
  161. * <pre>
  162. * ['书名', 'bid', '版权方']
  163. * </pre>
  164. * @param $datas 表内容,和表头一一对应
  165. * <pre>
  166. * [
  167. * ['aa', 1, 'bb'],
  168. * ['aa', 1, 'bb'],
  169. * ....
  170. * ['aa', 1, 'bb'],
  171. * ['aa', 1, 'bb'],
  172. * ]
  173. * </pre>
  174. * @param $fileName 导出文件名
  175. * @param string $fileType
  176. * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
  177. */
  178. function exportExcelXslx($header, $datas, $fileName, $fileType = 'Xlsx') {
  179. $spreadsheet = new Spreadsheet();
  180. $worksheet = $spreadsheet->getActiveSheet();
  181. // $worksheet->setTitle('数据中心');
  182. foreach ($header as $key => $value) {
  183. $worksheet->setCellValue([$key+1, 1], $value);
  184. }
  185. $row = 2; //从第二行开始
  186. foreach ($datas as $item) {
  187. $column = 1;
  188. foreach ($item as $value) {
  189. $worksheet->setCellValue([$column, $row], $value);
  190. $column++;
  191. }
  192. $row++;
  193. }
  194. $writer = IOFactory::createWriter($spreadsheet, $fileType); //按照指定格式生成Excel文件
  195. excelBrowserExport($fileName, $fileType);
  196. $writer->save('php://output');
  197. }
  198. /**
  199. * 发送邮件
  200. * @param $to_email 收件人
  201. * <pre>
  202. * [
  203. * ['address' => 'aa@bb.com', 'name' => 'aa'],
  204. * ......,
  205. * ['address' => 'aa@bb.com', 'name' => 'aa'],
  206. * ]
  207. * </pre>
  208. * @param $param
  209. * <pre>
  210. * [
  211. * 'subject' => "xxxxxx" , // 标题
  212. * 'body' => 'xxxx', // 邮件内容,如果内容需要换行,使用 <br>
  213. * ]
  214. * </pre>
  215. * @param string $accessory
  216. */
  217. function sendEmail($to_email, $param, $accessory = '')
  218. {
  219. $mail = new PHPMailer(true);// Passing `true` enables exceptions
  220. $mail->CharSet = 'UTF-8';//'UTF-8';
  221. try {
  222. $mail->SMTPDebug = 0; // Enable verbose debug output
  223. $mail->isSMTP(); // Set mailer to use SMTP
  224. $mail->Host = 'smtp.exmail.qq.com'; //$mail->Host = 'smtp.126.com'; Specify main and backup SMTP servers
  225. $mail->SMTPAuth = true; // Enable SMTP authentication
  226. $mail->Username = 'sendemail01@zkanshu.com'; //$mail->Username = 'tushengxiang@126.com'; // SMTP username
  227. $mail->Password = '5jBekvU2jJ2Ketue'; // SMTP password
  228. $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
  229. $mail->Port = 465; // TCP port to connect to
  230. //Recipients
  231. $mail->setFrom('sendemail01@zkanshu.com', 'System');
  232. $mail->addAddress($to_email[0]['address'], $to_email[0]['name']);
  233. array_shift($to_email);
  234. foreach ($to_email as $item) {
  235. $mail->addCC($item['address'], $item['name']); // Add a recipient
  236. }
  237. //Attachments
  238. if ($accessory) $mail->addAttachment($accessory);// Add attachments
  239. $mail->isHTML(true);
  240. $mail->Subject = $param['subject'];
  241. $mail->Body = $param['body'];
  242. $mail->send();
  243. } catch (\Exception $e) {
  244. \Log::warning('发送邮件失败:' . $mail->ErrorInfo, $e->getTrace());
  245. }
  246. }
  247. /**
  248. * 获取日志对象
  249. * @param $fileName 保存日志的名称
  250. * @param string $logLevel 日志等级
  251. * @param int $logDays 日志保留的天数
  252. * @return \Psr\Log\LoggerInterface
  253. */
  254. function myLog($fileName, $logLevel='info', $logDays = 7) :\Psr\Log\LoggerInterface{
  255. return CustomizeLogger::getLogger($fileName, $logLevel, $logDays);
  256. }
  257. if (!function_exists('get_date')) {
  258. /**
  259. * 获取时间
  260. * @param mixed $time
  261. * @param mixed $format
  262. * @return false|string
  263. */
  264. function get_date($time = 0, $format = "Y-m-d H:i:s")
  265. {
  266. $time = intval($time);
  267. if ($time <= 0) {
  268. $time = time();
  269. }
  270. return date($format, $time);
  271. }
  272. }
  273. /**
  274. * 华为obs文件上传
  275. * @param UploadedFile $file
  276. * @return array
  277. */
  278. function huaweiObsUpload(UploadedFile $file) {
  279. $uploader = new Uploader();
  280. $uploader->setDriver('HuaweiOBS');
  281. return $uploader->upload($file);
  282. }
  283. if (!function_exists("random")) {
  284. /**
  285. * [random 生成随机字符串]
  286. * @wzq
  287. * @DtuateTime 2020-09-08
  288. * @param [type] $length [长度]
  289. * @param mixed $numeric [是否仅是数字]
  290. * @return string [type] [string]
  291. * @version v1
  292. */
  293. function random($length, $numeric = false): string
  294. {
  295. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  296. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  297. if ($numeric) {
  298. $hash = '';
  299. } else {
  300. $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
  301. $length--;
  302. }
  303. $max = strlen($seed) - 1;
  304. for ($i = 0; $i < $length; $i++) {
  305. $hash .= $seed[mt_rand(0, $max)] ?? "";
  306. }
  307. return $hash;
  308. }
  309. }
  310. if(!function_exists('getMiniProgramTableName')){
  311. /**
  312. * 获取小程序表名 表名前添加前缀:wechat_miniprogram_ 或者 douyin_miniprogram_
  313. * name: getMiniProgramTableName
  314. * @param int $from 来源 1 微信小程序
  315. * @param string $name 表名
  316. * @return string
  317. * date 2023/05/19 09:18
  318. */
  319. function getMiniProgramTableName(int $from, string $name): string
  320. {
  321. return sprintf('%s_%s', [
  322. '1' => 'wechat_miniprogram',
  323. '2' => 'douyin_miniprogram'
  324. ][$from],$name);
  325. }
  326. }
  327. if (!function_exists('getProp')){
  328. /**
  329. * 获取对象或数组的属性值
  330. * @param $param
  331. * @param $key
  332. * @param string $default
  333. * @return mixed|string
  334. */
  335. function getProp($param, $key, $default = '')
  336. {
  337. $result = $default;
  338. if (is_object($param) && isset($param->$key)) {
  339. $result = $param->$key;
  340. }
  341. if (is_array($param) && isset($param[$key])) {
  342. $result = $param[$key];
  343. }
  344. return $result;
  345. }
  346. }
  347. /**
  348. * 打印sql
  349. */
  350. if (!function_exists('print_sql')) {
  351. function print_sql ()
  352. {
  353. DB::listen(function ($sql) {
  354. $singleSql = $sql->sql;
  355. if ($sql->bindings) {
  356. foreach ($sql->bindings as $replace) {
  357. $value = is_numeric($replace) ? $replace : "'" . $replace . "'";
  358. $singleSql = preg_replace('/\?/', $value, $singleSql, 1);
  359. }
  360. }
  361. myLog('sql-query')->info($singleSql);
  362. });
  363. }
  364. }
  365. if(!function_exists('getTraceContext')) {
  366. /**
  367. * @return TraceContext
  368. */
  369. function getTraceContext() {
  370. return app(TraceContext::class);
  371. }
  372. }
  373. /**
  374. * 钉钉报警
  375. *
  376. * @param \Throwable $exception
  377. * @return void
  378. */
  379. function dingTalkAlertException(\Throwable $exception)
  380. {
  381. $code = $exception->getCode();
  382. if($code >0){
  383. return ;
  384. }
  385. $url = 'https://oapi.dingtalk.com/robot/send?access_token=07829435258bf07c5f0b0a0a84c50c4bebc15e585b3040ad43c5e94e213a9bba';
  386. $key = 'SEC74f8117d06ae59a7edde24cd9706334dbdd09b5d5734522f060272bdfbfb1abd';
  387. $timestamp = time()*1000;
  388. $string = $timestamp . "\n" . $key;
  389. $sign = hash_hmac('sha256',$string,$key,true);
  390. $sign = urlencode(base64_encode($sign));
  391. $url .= '&'.http_build_query(['timestamp'=>$timestamp,'sign'=>$sign]);
  392. $class_name = get_class($exception);
  393. $app_path = base_path();
  394. $trace = $exception->getTraceAsString();
  395. $trace_list = preg_split('/\n/',$trace);
  396. $error = '- '.$exception->getFile().':'.$exception->getLine()."\n";
  397. foreach($trace_list as $item){
  398. if( !Str::contains($item,'vendor')){
  399. $error .= '- '.trim(preg_replace('/^(\#\d+)/','',$item))."\n";
  400. }
  401. }
  402. $hostname = gethostname();
  403. $ip = '';
  404. $ssh = getenv('SSH_CONNECTION');
  405. if($ssh){
  406. $ssh_list = explode(' ',$ssh);
  407. $ip = isset($ssh_list[2]) ? $ssh_list[2]:'';
  408. }
  409. if(!$ip){
  410. $ip = trim( shell_exec("ifconfig eth0 |grep 'inet ' 2>/dev/null |awk '{print $2}' ") );
  411. }
  412. $result = [
  413. 'message'=>$exception->getMessage(),
  414. 'class_name'=>$class_name,
  415. 'app_path'=>$app_path,
  416. 'error'=>$error,
  417. 'hostname'=>$hostname.' - '.$ip
  418. ];
  419. try{
  420. $response = Http::post($url,[
  421. 'msgtype' => 'markdown',
  422. 'markdown' => [
  423. 'title'=>basename (base_path()).'异常',
  424. 'text' => sprintf("### 错误信息: \n%s\n ### 异常详情: \n%s\n### 项目路径: \n%s\n\n ### 主机名:\n%s\n",
  425. $result['class_name'].':'.$result['message'],$result['error'],$result['app_path'],$result['hostname'])
  426. ]
  427. ]);
  428. }catch(\Exception $e){
  429. }
  430. }