Helpers.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. <?php
  2. use Illuminate\Http\UploadedFile;
  3. use Modules\Common\Support\Upload\Uploader;
  4. use PhpOffice\PhpSpreadsheet\IOFactory;
  5. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  6. use Modules\Common\Support\Trace\CustomizeLogger;
  7. use PHPMailer\PHPMailer\PHPMailer;
  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. * 输出到浏览器(需要设置header头)
  131. * @param string $fileName 文件名
  132. * @param string $fileType 文件类型
  133. */
  134. function excelBrowserExport($fileName, $fileType) {
  135. //文件名称校验
  136. if(!$fileName) {
  137. trigger_error('文件名不能为空', E_USER_ERROR);
  138. }
  139. //Excel文件类型校验
  140. $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];
  141. if(!in_array($fileType, $type)) {
  142. trigger_error('未知文件类型', E_USER_ERROR);
  143. }
  144. if($fileType == 'Excel2007' || $fileType == 'Xlsx') {
  145. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  146. header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
  147. header('Cache-Control: max-age=0');
  148. } else { //Excel5
  149. header('Content-Type: application/vnd.ms-excel');
  150. header('Content-Disposition: attachment;filename="'.$fileName.'.xls"');
  151. header('Cache-Control: max-age=0');
  152. }
  153. }
  154. /**
  155. * 导出excel
  156. * @param $header 第一行,表头
  157. * <pre>
  158. * ['书名', 'bid', '版权方']
  159. * </pre>
  160. * @param $datas 表内容,和表头一一对应
  161. * <pre>
  162. * [
  163. * ['aa', 1, 'bb'],
  164. * ['aa', 1, 'bb'],
  165. * ....
  166. * ['aa', 1, 'bb'],
  167. * ['aa', 1, 'bb'],
  168. * ]
  169. * </pre>
  170. * @param $fileName 导出文件名
  171. * @param string $fileType
  172. * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
  173. */
  174. function exportExcelXslx($header, $datas, $fileName, $fileType = 'Xlsx') {
  175. $spreadsheet = new Spreadsheet();
  176. $worksheet = $spreadsheet->getActiveSheet();
  177. // $worksheet->setTitle('数据中心');
  178. foreach ($header as $key => $value) {
  179. $worksheet->setCellValue([$key+1, 1], $value);
  180. }
  181. $row = 2; //从第二行开始
  182. foreach ($datas as $item) {
  183. $column = 1;
  184. foreach ($item as $value) {
  185. $worksheet->setCellValue([$column, $row], $value);
  186. $column++;
  187. }
  188. $row++;
  189. }
  190. $writer = IOFactory::createWriter($spreadsheet, $fileType); //按照指定格式生成Excel文件
  191. excelBrowserExport($fileName, $fileType);
  192. $writer->save('php://output');
  193. }
  194. /**
  195. * 发送邮件
  196. * @param $to_email 收件人
  197. * <pre>
  198. * [
  199. * ['address' => 'aa@bb.com', 'name' => 'aa'],
  200. * ......,
  201. * ['address' => 'aa@bb.com', 'name' => 'aa'],
  202. * ]
  203. * </pre>
  204. * @param $param
  205. * <pre>
  206. * [
  207. * 'subject' => "xxxxxx" , // 标题
  208. * 'body' => 'xxxx', // 邮件内容,如果内容需要换行,使用 <br>
  209. * ]
  210. * </pre>
  211. * @param string $accessory
  212. */
  213. function sendEmail($to_email, $param, $accessory = '')
  214. {
  215. $mail = new PHPMailer(true);// Passing `true` enables exceptions
  216. $mail->CharSet = 'UTF-8';//'UTF-8';
  217. try {
  218. $mail->SMTPDebug = 0; // Enable verbose debug output
  219. $mail->isSMTP(); // Set mailer to use SMTP
  220. $mail->Host = 'smtp.exmail.qq.com'; //$mail->Host = 'smtp.126.com'; Specify main and backup SMTP servers
  221. $mail->SMTPAuth = true; // Enable SMTP authentication
  222. $mail->Username = 'sendemail01@zkanshu.com'; //$mail->Username = 'tushengxiang@126.com'; // SMTP username
  223. $mail->Password = '5jBekvU2jJ2Ketue'; // SMTP password
  224. $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
  225. $mail->Port = 465; // TCP port to connect to
  226. //Recipients
  227. $mail->setFrom('sendemail01@zkanshu.com', 'System');
  228. $mail->addAddress($to_email[0]['address'], $to_email[0]['name']);
  229. array_shift($to_email);
  230. foreach ($to_email as $item) {
  231. $mail->addCC($item['address'], $item['name']); // Add a recipient
  232. }
  233. //Attachments
  234. if ($accessory) $mail->addAttachment($accessory);// Add attachments
  235. $mail->isHTML(true);
  236. $mail->Subject = $param['subject'];
  237. $mail->Body = $param['body'];
  238. $mail->send();
  239. } catch (\Exception $e) {
  240. \Log::warning('发送邮件失败:' . $mail->ErrorInfo, $e->getTrace());
  241. }
  242. }
  243. /**
  244. * 获取日志对象
  245. * @param $fileName 保存日志的名称
  246. * @param string $logLevel 日志等级
  247. * @param int $logDays 日志保留的天数
  248. * @return \Psr\Log\LoggerInterface
  249. */
  250. function myLog($fileName, $logLevel='info', $logDays = 7) :\Psr\Log\LoggerInterface{
  251. return CustomizeLogger::getLogger($fileName, $logLevel, $logDays);
  252. }
  253. if (!function_exists('get_date')) {
  254. /**
  255. * 获取时间
  256. * @param mixed $time
  257. * @param mixed $format
  258. * @return false|string
  259. */
  260. function get_date($time = 0, $format = "Y-m-d H:i:s")
  261. {
  262. $time = intval($time);
  263. if ($time <= 0) {
  264. $time = time();
  265. }
  266. return date($format, $time);
  267. }
  268. }
  269. /**
  270. * 华为obs文件上传
  271. * @param UploadedFile $file
  272. * @return array
  273. */
  274. function huaweiObsUpload(UploadedFile $file) {
  275. $uploader = new Uploader();
  276. $uploader->setDriver('HuaweiOBS');
  277. return $uploader->upload($file);
  278. }
  279. if (!function_exists("random")) {
  280. /**
  281. * [random 生成随机字符串]
  282. * @wzq
  283. * @DtuateTime 2020-09-08
  284. * @param [type] $length [长度]
  285. * @param mixed $numeric [是否仅是数字]
  286. * @return string [type] [string]
  287. * @version v1
  288. */
  289. function random($length, $numeric = false): string
  290. {
  291. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  292. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  293. if ($numeric) {
  294. $hash = '';
  295. } else {
  296. $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
  297. $length--;
  298. }
  299. $max = strlen($seed) - 1;
  300. for ($i = 0; $i < $length; $i++) {
  301. $hash .= $seed[mt_rand(0, $max)] ?? "";
  302. }
  303. return $hash;
  304. }
  305. }
  306. if(!function_exists('getMiniProgramTableName')){
  307. /**
  308. * 获取小程序表名 表名前添加前缀:wechat_miniprogram_ 或者 douyin_miniprogram_
  309. * name: getMiniProgramTableName
  310. * @param int $from 来源 1 微信小程序
  311. * @param string $name 表名
  312. * @return string
  313. * date 2023/05/19 09:18
  314. */
  315. function getMiniProgramTableName(int $from, string $name): string
  316. {
  317. return sprintf('%s_%s', [
  318. '1' => 'wechat_miniprogram',
  319. '2' => 'douyin_miniprogram'
  320. ][$from],$name);
  321. }
  322. }
  323. if (!function_exists('getProp')){
  324. /**
  325. * 获取对象或数组的属性值
  326. * @param $param
  327. * @param $key
  328. * @param string $default
  329. * @return mixed|string
  330. */
  331. function getProp($param, $key, $default = '')
  332. {
  333. $result = $default;
  334. if (is_object($param) && isset($param->$key)) {
  335. $result = $param->$key;
  336. }
  337. if (is_array($param) && isset($param[$key])) {
  338. $result = $param[$key];
  339. }
  340. return $result;
  341. }
  342. }