Helper.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. <?php
  2. use lwmf\base\Logger;
  3. class Helper
  4. {
  5. const PARAM_KEY_TYPE = [
  6. 'string' => 'string', // 字符串
  7. 'int' => 'int', // 数字
  8. 'float' => 'float', // float数字
  9. 'date' => 'date', // 日期
  10. 'datetime' => 'datetime', // 日期时间
  11. 'array_string' => 'array_string', // 包含字符串的数组
  12. 'array_float' => 'array_float', // 包含float的数组
  13. 'array_int' => 'array_int', // 包含int的数组
  14. ];
  15. /**
  16. * 检查字符串中是否含有任何一个子串
  17. * @param $str
  18. * @param array $arr
  19. * @param bool $case 是否区分大小写 0-否
  20. * @return bool
  21. */
  22. public static function hasAnyString($str, array $arr, bool $case = false): bool
  23. {
  24. foreach ($arr as $v) {
  25. if (!$case && stripos($str, $v) !== false) {
  26. return true;
  27. } elseif ($case && str_contains($str, $v)) {
  28. return true;
  29. }
  30. }
  31. return false;
  32. }
  33. /**
  34. * 获取图片完整路径
  35. * @param $imageUrl
  36. * @param string $default
  37. *
  38. * @return string
  39. * @author lizhi <1458705589@qq.com>
  40. * @date 2021/5/11
  41. */
  42. public static function getImageUrl($imageUrl, string $default = '', $params = []): string
  43. {
  44. if (empty($imageUrl)) {
  45. return $default;
  46. }
  47. if (str_contains($imageUrl, 'http')) {
  48. return $imageUrl;
  49. }
  50. $imageUrl = IMAGEDOMAIN . '/' . ltrim($imageUrl, '/');
  51. if (self::getArrParam($params, 'from_type', 'string') == 'console') {
  52. // 把后端用到图片的地方,加个后缀,类似!max200 !width600这种
  53. $imageUrl .= '!max200';
  54. }
  55. return $imageUrl;
  56. }
  57. /**
  58. * 格式化处理 imgs 字段
  59. * @param string|null $data
  60. * @param string $separator
  61. * @return array
  62. */
  63. public static function formatImgFiled(?string $data, string $separator = ','): array
  64. {
  65. if (!$data) {
  66. return [];
  67. }
  68. $data = array_filter(explode($separator, $data));
  69. return array_map(function ($img) {
  70. return Helper::getImageUrl($img);
  71. }, $data);
  72. }
  73. public static function time_tran($time)
  74. {
  75. $text = '请选择正确的时间!';
  76. if(!$time){
  77. return $text;
  78. }
  79. $current = time();
  80. $t = $current - $time;
  81. $retArr = array('刚刚','秒前','分钟前','小时前','天前','月前','年前');
  82. switch($t){
  83. case $t < 0://时间大于当前时间,返回格式化时间
  84. $text = date('Y-m-d',$time);
  85. break;
  86. case $t == 0://刚刚
  87. $text = $retArr[0];
  88. break;
  89. case $t < 60:// 几秒前
  90. $text = $t.$retArr[1];
  91. break;
  92. case $t < 3600://几分钟前
  93. $text = floor($t / 60).$retArr[2];
  94. break;
  95. case $t < 86400://几小时前
  96. $text = floor($t / 3600).$retArr[3];
  97. break;
  98. case $t < 2592000: //几天前
  99. $text = floor($t / 86400).$retArr[4];
  100. break;
  101. case $t < 31536000: //几个月前
  102. $text = floor($t / 2592000).$retArr[5];
  103. break;
  104. default : //几年前
  105. $text = floor($t / 31536000).$retArr[6];
  106. }
  107. return $text;
  108. }
  109. /**
  110. * 检查数组是否指定键都存在 true-都在
  111. * - checkEmptyKey(['num' => 1], ['num']) => true
  112. * - checkEmptyKey(['num' => 1], ['id']) => false
  113. * - checkEmptyKey(['num' => 0], ['num']) => false
  114. * - checkEmptyKey(['num' => 0], ['num'], ['num') => true
  115. *
  116. * @param array $data
  117. * @param $keys
  118. * @param array $allowEmpty 允许为空的字段
  119. *
  120. * @return bool true-通过检查
  121. * @author lizhi <1458705589@qq.com>
  122. * @date 2021/6/18
  123. */
  124. public static function checkEmptyKey($data, $keys, array $allowEmpty = [])
  125. {
  126. if (is_array($keys)) {
  127. foreach ($keys as $item) {
  128. if (!isset($data[$item]) || (!in_array($item, $allowEmpty) && empty($data[$item]))) {
  129. return false;
  130. }
  131. }
  132. } elseif (!isset($data[$keys]) || (!in_array($keys, $allowEmpty) && empty($data[$keys]))) {
  133. return false;
  134. }
  135. return true;
  136. }
  137. public static function getPostString($key, $default = null)
  138. {
  139. return self::getArrParam($_POST, $key, 'string', $default);
  140. }
  141. public static function getPostFloat($key, $default = null)
  142. {
  143. return self::getArrParam($_POST, $key, 'float', $default);
  144. }
  145. public static function getGetFloat($key, $default = null)
  146. {
  147. return self::getArrParam($_GET, $key, 'float', $default);
  148. }
  149. public static function isPhone(?string $phone)
  150. {
  151. return $phone && preg_match('/^1[3456789]\d{9}$/', $phone);
  152. }
  153. public static function getPostInt($key, $default = 0)
  154. {
  155. return self::getArrParam($_POST, $key, 'int', $default);
  156. }
  157. public static function getGetString($key, $default = null)
  158. {
  159. return self::getArrParam($_GET, $key, 'string', $default);
  160. }
  161. public static function getGetDate($key, $default = null)
  162. {
  163. return self::getArrParam($_GET, $key, 'date', $default);
  164. }
  165. public static function getPostDatetime($key, $default = null)
  166. {
  167. return self::getArrParam($_POST, $key, 'datetime', $default);
  168. }
  169. public static function getGetDatetime($key, $default = null)
  170. {
  171. return self::getArrParam($_GET, $key, 'datetime', $default);
  172. }
  173. public static function getPostDate($key, $default = null)
  174. {
  175. return self::getArrParam($_POST, $key, 'date', $default);
  176. }
  177. public static function getGetInt($key, $default = 0)
  178. {
  179. return self::getArrParam($_GET, $key, 'int', $default);
  180. }
  181. /**
  182. * 从数组中获取字段
  183. */
  184. public static function getArrParam($arr, $name, $type = 'string', $default = null)
  185. {
  186. if (isset($arr[$name])) {
  187. $param = $arr[$name];
  188. return self::formatByType($param, $type, $default);
  189. }
  190. return $default;
  191. }
  192. /**
  193. * @param string $name 从数组中获取字段,并进行安全处理 多维数组示例 area.name
  194. * @see self::formatByType()
  195. */
  196. public static function getByKey($arr, $name, $type = '', $default = null)
  197. {
  198. $nameArr = array_filter(explode('.', $name));
  199. if (count($nameArr) == 1) {
  200. if (!isset($arr[$name])) {
  201. return $default;
  202. } else {
  203. $param = $arr[$name];
  204. }
  205. } else if (count($nameArr) == 2) {
  206. if (!isset($arr[$nameArr[0]][$nameArr[1]])) {
  207. return $default;
  208. } else {
  209. $param = $arr[$nameArr[0]][$nameArr[1]];
  210. }
  211. } else {
  212. return $default;
  213. }
  214. return self::formatByType($param, $type, $default);
  215. }
  216. /**
  217. * 格式化数据
  218. * @param mixed $param
  219. * @param string $type 数据类型,将元素处理成这样的数据类型
  220. - string 字符串
  221. - int 数字
  222. - float float数字
  223. - date 日期
  224. - datetime 日期时间
  225. - array_string 包含字符串的数组
  226. - array_float 包含float的数组
  227. - array_int 包含int的数组
  228. * @param mixed $default
  229. * @return mixed
  230. */
  231. public static function formatByType($param, $type, $default)
  232. {
  233. if ($type == 'string') {
  234. $param = addslashes(trim($param));
  235. }
  236. elseif ($type == 'int') {
  237. $param = intval($param);
  238. }
  239. elseif ($type == 'float') {
  240. $param = floatval($param);
  241. }
  242. elseif ($type == 'date') {
  243. if (!empty($param)) {
  244. $param = date('Y-m-d', strtotime($param));
  245. } else {
  246. $param = $default;
  247. }
  248. }
  249. elseif ($type == 'datetime') {
  250. if (!empty($param)) {
  251. $param = date('Y-m-d H:i:s', strtotime($param));
  252. } else {
  253. $param = $default;
  254. }
  255. }
  256. elseif ($type == 'array_string') {
  257. if (!empty($param)) {
  258. foreach ($param as $key => &$item) {
  259. $item = addslashes(trim($item));
  260. }
  261. }
  262. }
  263. elseif ($type == 'array_float') {
  264. if (!empty($param)) {
  265. foreach ($param as $key => &$item) {
  266. $item = floatval($item);
  267. }
  268. }
  269. }
  270. elseif ($type == 'array_int') {
  271. if (!empty($param)) {
  272. foreach ($param as $key => &$item) {
  273. $item = intval($item);
  274. }
  275. }
  276. }
  277. return $param;
  278. }
  279. /**
  280. * 获取date格式的日期间隔
  281. */
  282. public static function intervalDays($date1, $date2)
  283. {
  284. $d = @(strtotime($date2) - strtotime($date1)) / (3600 * 24);
  285. return $d;
  286. }
  287. /**
  288. * 获取一个对象中的某个字段,返回数组
  289. * @param array $arr 通过查询返回的数组
  290. * @param string $column 字段名
  291. */
  292. public static function getObjectColumn(array $arr, $column = 'id')
  293. {
  294. $ret = [];
  295. if (!empty($arr)) {
  296. foreach ($arr as $key => $item) {
  297. $attributes = $item->attributes;
  298. isset($attributes[$column]) && $ret[] = $attributes[$column];
  299. }
  300. }
  301. return $ret;
  302. }
  303. public static function concatArray($arr1, $arr2)
  304. {
  305. foreach ($arr2 as $item) {
  306. if (!in_array($item, $arr1)) {
  307. $arr1[] = $item;
  308. }
  309. }
  310. return $arr1;
  311. }
  312. public static function toJson($code = 200, $data = [], $msg = '请求成功')
  313. {
  314. @header("Content-Type: text/json; charset=UTF-8");
  315. echo json_encode([
  316. 'code' => $code,
  317. 'msg' => $msg,
  318. 'data' => $data
  319. ]);
  320. \Yii::app()->end();
  321. }
  322. public static function error($msg, $code = 400, $data = [])
  323. {
  324. self::toJson($code, $data, $msg);
  325. }
  326. public static function ok($data = [], $msg = '操作成功', $code = 200)
  327. {
  328. self::toJson($code, $data, $msg);
  329. }
  330. public static function success($data = [], $msg = '操作成功', $code = 200)
  331. {
  332. self::toJson($code, $data, $msg);
  333. }
  334. public static function commonError($_msg = '', $_code = 500, $_data = [])
  335. {
  336. return self::commonReturn($_data, $_msg, $_code);
  337. }
  338. public static function commonReturn($_data = [], $_msg = '', $_code = 200)
  339. {
  340. return [
  341. 'code' => $_code,
  342. 'msg' => $_msg,
  343. 'data' => $_data
  344. ];
  345. }
  346. public static function dealCommonResult($res, $exit = true)
  347. {
  348. if ($exit || $res['code'] != 200) {
  349. Helper::toJson($res['code'], $res['data'], $res['msg']);
  350. }
  351. }
  352. public static function getRandomString($length = 20)
  353. {
  354. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  355. $str = "";
  356. for ($i = 0; $i < $length; $i++) {
  357. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  358. }
  359. return $str;
  360. }
  361. //php防注入和XSS攻击通用过滤
  362. public static function safeFilter (&$arr)
  363. {
  364. $ra=Array('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/','/script/','/javascript/','/vbscript/','/expression/','/applet/'
  365. ,'/meta/','/xml/','/blink/','/link/','/style/','/embed/','/object/','/frame/','/layer/','/title/','/bgsound/'
  366. ,'/base/','/onload/','/onunload/','/onchange/','/onsubmit/','/onreset/','/onselect/','/onblur/','/onfocus/',
  367. '/onabort/','/onkeydown/','/onkeypress/','/onkeyup/','/onclick/','/ondblclick/','/onmousedown/','/onmousemove/'
  368. ,'/onmouseout/','/onmouseover/','/onmouseup/','/onunload/');
  369. if (is_array($arr))
  370. {
  371. foreach ($arr as $key => $value)
  372. {
  373. if (!is_array($value))
  374. {
  375. if (!get_magic_quotes_gpc()) //不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。
  376. {
  377. $value = addslashes($value); //给单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符)
  378. #加上反斜线转义
  379. }
  380. $value = preg_replace($ra,'',$value); //删除非打印字符,粗暴式过滤xss可疑字符串
  381. // $arr[$key] = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体
  382. }
  383. else
  384. {
  385. self::SafeFilter($arr[$key]);
  386. }
  387. }
  388. }
  389. return $arr;
  390. }
  391. public static function getSign($data)
  392. {
  393. return md5($data . "145709480B89EE59E3F4D43A56C355F2");
  394. }
  395. /**
  396. * 将二维数组转化为对象数组
  397. * @param array $arr
  398. * @return array
  399. */
  400. public static function arrayToObjects(array $arr)
  401. {
  402. $ret = [];
  403. foreach ($arr as $item) {
  404. $ret[] = (object)$item;
  405. }
  406. return $ret;
  407. }
  408. /**
  409. * 异步批量get请求
  410. *
  411. * @param array $nodes 格式: 'key' => ['url', 'data'] key是标识key,url是请求host,data是post传递的数据
  412. * @param integer $timeOut 超时时间
  413. * @return void
  414. */
  415. public static function multiGet($nodes, $options = [] ,$timeOut = 5)
  416. {
  417. $mh = curl_multi_init();
  418. $curl_arr = [];
  419. // 将请求放入curl中
  420. foreach ($nodes as $key => $node) {
  421. if (!is_array($node)) {
  422. continue;
  423. }
  424. $ch = curl_init();
  425. $url = $node['url'] . (strpos($node['url'], '?') === FALSE ? '?' : '');
  426. if (isset($node['data'])) {
  427. $url .= http_build_query($node['data']);
  428. }
  429. curl_setopt($ch, CURLOPT_URL, $url);
  430. // 其他的参数按照 function GET($url, $get = array(), array $options = array()) 来
  431. curl_setopt($ch, CURLOPT_HEADER, 0);
  432. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
  433. curl_setopt($ch, CURLOPT_TIMEOUT, 15);
  434. curl_setopt($ch, CURLOPT_SSLVERSION, 1);
  435. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  436. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  437. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  438. // 超时时间
  439. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeOut);
  440. foreach ($options as $k => $v) {
  441. curl_setopt($ch, $k, $v);
  442. }
  443. $curl_arr[$key] = $ch;
  444. curl_multi_add_handle($mh, $curl_arr[$key]);
  445. }
  446. // 发送请求
  447. $running = null;
  448. do {
  449. usleep(10000);
  450. curl_multi_exec($mh, $running);
  451. } while ($running > 0);
  452. // 获取请求数据,并删除请求
  453. $ret = [];
  454. foreach ($nodes as $key => $node) {
  455. $ret[$key] = curl_multi_getcontent($curl_arr[$key]);
  456. curl_multi_remove_handle($mh, $curl_arr[$key]);
  457. }
  458. curl_multi_close($mh);
  459. return $ret;
  460. }
  461. /**
  462. * array_column 一样用法
  463. */
  464. public static function arrayColumn($array, $column_key, $index_key = null): array
  465. {
  466. return $array && $array['records'] ? array_column($array['records'], $column_key, $index_key) : [];
  467. }
  468. /**
  469. * @param int $ipNum 每日ip次数限制
  470. * @param string $phone 手机号
  471. * @param int $phoneNum 每日单个手机号次数限制
  472. * @return array
  473. */
  474. public static function limitSmsSend(int $ipNum = 10, string $phone = '', int $phoneNum = 3):array
  475. {
  476. if ($ipNum > 0) {
  477. $ip = self::getUserHostIp();
  478. $key = 'limit_ip:' . date('Ymd') . '_' . $ip;
  479. if (RedisInstance::getInstance()->incr($key, 1, 86400) > $ipNum) {
  480. return Helper::commonError('今日短信次数超过限制i');
  481. }
  482. }
  483. if ($phone && $phoneNum > 0) {
  484. $key = 'limit_phone:' . date('Ymd') . '_' . $phone;
  485. if (RedisInstance::getInstance()->incr($key, 1, 86400) > $phoneNum) {
  486. return Helper::commonError('今日短信次数超过限制p');
  487. }
  488. }
  489. return Helper::commonReturn();
  490. }
  491. /**
  492. * 获取代理模式用户真实访问IP
  493. * 获取阿里云用户真实访问IP
  494. */
  495. public static function getUserHostIp()
  496. {
  497. if (isset($_SERVER['HTTP_X_ORIGINAL_FORWARDED_FOR']))
  498. {
  499. $ips = isset($_SERVER["HTTP_X_ORIGINAL_FORWARDED_FOR"]) ? explode(',', $_SERVER["HTTP_X_ORIGINAL_FORWARDED_FOR"]) : '';
  500. }
  501. else
  502. {
  503. $ips = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? explode(',', $_SERVER["HTTP_X_FORWARDED_FOR"]) : '';
  504. }
  505. if (isset($ips[0]))
  506. {
  507. $ip = $ips[0];
  508. }
  509. else
  510. {
  511. $ip = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : '';
  512. }
  513. return $ip ? $ip : '127.0.0.1';
  514. }
  515. public static function imageUpload($imagepath, $uploadpath)
  516. {
  517. try {
  518. $cosClient = new \Qcloud\Cos\Client(
  519. array(
  520. 'region' => 'ap-shanghai',
  521. // 'scheme' => 'https', //协议头部,默认为 http
  522. 'credentials'=> array(
  523. 'secretId' => 'AKIDviIeLyQluythLAykSJ6oXH91upgR6iT8' ,
  524. 'secretKey' => 'tobSCsOn7yc6ToBSWegaM9rVGyiR6f95'
  525. )
  526. )
  527. );
  528. $file = fopen($imagepath, "rb");
  529. if (!$file) {
  530. throw new Exception("读取图片失败");
  531. }
  532. $cosClient->putObject(['Bucket' => 'lewaimai-image-1251685925', 'Key' => $uploadpath, 'Body' => $file]);
  533. return Helper::commonReturn();
  534. } catch(Exception $e) {
  535. return Helper::commonError($e->getMessage());
  536. }
  537. }
  538. public static function imageDelete($path)
  539. {
  540. try {
  541. $cosClient = new \Qcloud\Cos\Client(
  542. array(
  543. 'region' => 'ap-shanghai',
  544. // 'scheme' => 'https', //协议头部,默认为 http
  545. 'credentials'=> array(
  546. 'secretId' => 'AKIDviIeLyQluythLAykSJ6oXH91upgR6iT8' ,
  547. 'secretKey' => 'tobSCsOn7yc6ToBSWegaM9rVGyiR6f95'
  548. )
  549. )
  550. );
  551. $cosClient->deleteObject(['Bucket' => 'lewaimai-image-1251685925', 'Key' => $path]);
  552. return Helper::commonReturn();
  553. } catch(Exception $e) {
  554. return Helper::commonError($e->getMessage());
  555. }
  556. }
  557. }