Helpers.php 12 KB

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