Helper.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. <?php
  2. use lwmf\base\Logger;
  3. class Helper
  4. {
  5. /**
  6. * 将数组转为cmodel对象
  7. *
  8. * @param array $arr
  9. * @return object
  10. */
  11. public static function arrayToModel($arr)
  12. {
  13. $arr = (array)$arr;
  14. $model = new \DynamicModel();
  15. $model->setAttributes($arr);
  16. return $model;
  17. }
  18. /**
  19. * 将数据库中获取的对象数组转为数组
  20. * @param array $arr
  21. * @return array
  22. */
  23. public static function objectToArray(array $arr, $column = '')
  24. {
  25. $ret = [];
  26. if (!empty($arr)) {
  27. foreach ($arr as $item) {
  28. if ($column) {
  29. $ret[$item->$column] = $item->attributes;
  30. } else {
  31. $ret[] = $item->attributes;
  32. }
  33. }
  34. }
  35. return $ret;
  36. }
  37. /**
  38. * 获取图片完整路径
  39. * @param $imageUrl
  40. * @param string $default
  41. *
  42. * @return string
  43. * @author lizhi <1458705589@qq.com>
  44. * @date 2021/5/11
  45. */
  46. public static function getImageUrl($imageUrl, string $default = '', $params = []): string
  47. {
  48. if (empty($imageUrl)) {
  49. return $default;
  50. }
  51. if (str_contains($imageUrl, 'http')) {
  52. return $imageUrl;
  53. }
  54. $imageUrl = IMAGEDOMAIN . '/' . ltrim($imageUrl, '/');
  55. if (self::getArrParam($params, 'from_type', 'string') == 'console') {
  56. // 把后端用到图片的地方,加个后缀,类似!max200 !width600这种
  57. $imageUrl .= '!max200';
  58. }
  59. return $imageUrl;
  60. }
  61. public static function time_tran($time)
  62. {
  63. $text = '请选择正确的时间!';
  64. if(!$time){
  65. return $text;
  66. }
  67. $current = time();
  68. $t = $current - $time;
  69. $retArr = array('刚刚','秒前','分钟前','小时前','天前','月前','年前');
  70. switch($t){
  71. case $t < 0://时间大于当前时间,返回格式化时间
  72. $text = date('Y-m-d',$time);
  73. break;
  74. case $t == 0://刚刚
  75. $text = $retArr[0];
  76. break;
  77. case $t < 60:// 几秒前
  78. $text = $t.$retArr[1];
  79. break;
  80. case $t < 3600://几分钟前
  81. $text = floor($t / 60).$retArr[2];
  82. break;
  83. case $t < 86400://几小时前
  84. $text = floor($t / 3600).$retArr[3];
  85. break;
  86. case $t < 2592000: //几天前
  87. $text = floor($t / 86400).$retArr[4];
  88. break;
  89. case $t < 31536000: //几个月前
  90. $text = floor($t / 2592000).$retArr[5];
  91. break;
  92. default : //几年前
  93. $text = floor($t / 31536000).$retArr[6];
  94. }
  95. return $text;
  96. }
  97. public static function getPostString($key, $default = null)
  98. {
  99. return self::getArrParam($_POST, $key, 'string', $default);
  100. }
  101. public static function getPostInt($key, $default = 0)
  102. {
  103. return self::getArrParam($_POST, $key, 'int', $default);
  104. }
  105. public static function getGetString($key, $default = null)
  106. {
  107. return self::getArrParam($_GET, $key, 'string', $default);
  108. }
  109. public static function getGetDate($key, $default = null)
  110. {
  111. return self::getArrParam($_GET, $key, 'date', $default);
  112. }
  113. public static function getPostDatetime($key, $default = null)
  114. {
  115. return self::getArrParam($_POST, $key, 'datetime', $default);
  116. }
  117. public static function getGetDatetime($key, $default = null)
  118. {
  119. return self::getArrParam($_GET, $key, 'datetime', $default);
  120. }
  121. public static function getPostDate($key, $default = null)
  122. {
  123. return self::getArrParam($_POST, $key, 'date', $default);
  124. }
  125. public static function getGetInt($key, $default = 0)
  126. {
  127. return self::getArrParam($_GET, $key, 'int', $default);
  128. }
  129. /**
  130. * 从数组中获取字段
  131. */
  132. public static function getArrParam($arr, $name, $type = 'string', $default = null)
  133. {
  134. if (isset($arr[$name])) {
  135. $param = $arr[$name];
  136. return self::formatByType($param, $type, $default);
  137. }
  138. return $default;
  139. }
  140. /**
  141. * @param string $name 从数组中获取字段,并进行安全处理 多维数组示例 area.name
  142. * @see self::formatByType()
  143. */
  144. public static function getByKey($arr, $name, $type = '', $default = null)
  145. {
  146. $nameArr = array_filter(explode('.', $name));
  147. if (count($nameArr) == 1) {
  148. if (!isset($arr[$name])) {
  149. return $default;
  150. } else {
  151. $param = $arr[$name];
  152. }
  153. } else if (count($nameArr) == 2) {
  154. if (!isset($arr[$nameArr[0]][$nameArr[1]])) {
  155. return $default;
  156. } else {
  157. $param = $arr[$nameArr[0]][$nameArr[1]];
  158. }
  159. } else {
  160. return $default;
  161. }
  162. return self::formatByType($param, $type, $default);
  163. }
  164. /**
  165. * 格式化数据
  166. * @param mixed $param
  167. * @param string $type 数据类型,将元素处理成这样的数据类型
  168. - string 字符串
  169. - int 数字
  170. - float float数字
  171. - date 日期
  172. - datetime 日期时间
  173. - array_string 包含字符串的数组
  174. - array_float 包含float的数组
  175. - array_int 包含int的数组
  176. * @param mixed $default
  177. * @return mixed
  178. */
  179. public static function formatByType($param, $type, $default)
  180. {
  181. if ($type == 'string') {
  182. $param = addslashes(trim($param));
  183. }
  184. elseif ($type == 'int') {
  185. $param = intval($param);
  186. }
  187. elseif ($type == 'float') {
  188. $param = floatval($param);
  189. }
  190. elseif ($type == 'date') {
  191. if (!empty($param)) {
  192. $param = date('Y-m-d', strtotime($param));
  193. } else {
  194. $param = $default;
  195. }
  196. }
  197. elseif ($type == 'datetime') {
  198. if (!empty($param)) {
  199. $param = date('Y-m-d H:i:s', strtotime($param));
  200. } else {
  201. $param = $default;
  202. }
  203. }
  204. elseif ($type == 'array_string') {
  205. if (!empty($param)) {
  206. foreach ($param as $key => &$item) {
  207. $item = addslashes(trim($item));
  208. }
  209. }
  210. }
  211. elseif ($type == 'array_float') {
  212. if (!empty($param)) {
  213. foreach ($param as $key => &$item) {
  214. $item = floatval($item);
  215. }
  216. }
  217. }
  218. elseif ($type == 'array_int') {
  219. if (!empty($param)) {
  220. foreach ($param as $key => &$item) {
  221. $item = intval($item);
  222. }
  223. }
  224. }
  225. return $param;
  226. }
  227. /**
  228. * 获取date格式的日期间隔
  229. */
  230. public static function intervalDays($date1, $date2)
  231. {
  232. $d = @(strtotime($date2) - strtotime($date1)) / (3600 * 24);
  233. return $d;
  234. }
  235. /**
  236. * 获取一个对象中的某个字段,返回数组
  237. * @param array $arr 通过查询返回的数组
  238. * @param string $column 字段名
  239. */
  240. public static function getObjectColumn(array $arr, $column = 'id')
  241. {
  242. $ret = [];
  243. if (!empty($arr)) {
  244. foreach ($arr as $key => $item) {
  245. $attributes = $item->attributes;
  246. isset($attributes[$column]) && $ret[] = $attributes[$column];
  247. }
  248. }
  249. return $ret;
  250. }
  251. public static function concatArray($arr1, $arr2)
  252. {
  253. foreach ($arr2 as $item) {
  254. if (!in_array($item, $arr1)) {
  255. $arr1[] = $item;
  256. }
  257. }
  258. return $arr1;
  259. }
  260. public static function toJson($code = 200, $data = [], $msg = '请求成功')
  261. {
  262. @header("Content-Type: text/json; charset=UTF-8");
  263. echo json_encode([
  264. 'code' => $code,
  265. 'msg' => $msg,
  266. 'data' => $data
  267. ]);
  268. \Yii::app()->end();
  269. }
  270. public static function imageUpload($imagepath, $uploadpath)
  271. {
  272. try {
  273. // 腾讯云
  274. $region = 'ap-shanghai'; // 用户的 region,已创建桶归属的 region 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket
  275. $cosClient = new \Qcloud\Cos\Client(
  276. array(
  277. 'region' => $region,
  278. // 'scheme' => 'https', //协议头部,默认为 http
  279. 'credentials'=> array(
  280. 'secretId' => 'AKIDviIeLyQluythLAykSJ6oXH91upgR6iT8' ,
  281. 'secretKey' => 'tobSCsOn7yc6ToBSWegaM9rVGyiR6f95'
  282. )
  283. )
  284. );
  285. $bucket = 'lewaimai-image-1251685925';
  286. $file = fopen($imagepath, "rb");
  287. if ($file) {
  288. $result = $cosClient->putObject(['Bucket' => $bucket, 'Key' => $uploadpath, 'Body' => $file]);
  289. }
  290. } catch(Exception $e) {
  291. throw $e;
  292. }
  293. }
  294. public static function error($msg, $code = 400, $data = [])
  295. {
  296. self::toJson($code, $data, $msg);
  297. }
  298. public static function ok($data = [], $msg = '操作成功', $code = 200)
  299. {
  300. self::toJson($code, $data, $msg);
  301. }
  302. public static function commonError($_msg = '', $_code = 500, $_data = [])
  303. {
  304. return self::commonReturn($_data, $_msg, $_code);
  305. }
  306. public static function commonReturn($_data = [], $_msg = '', $_code = 200)
  307. {
  308. return [
  309. 'code' => $_code,
  310. 'msg' => $_msg,
  311. 'data' => $_data
  312. ];
  313. }
  314. //php防注入和XSS攻击通用过滤
  315. public static function safeFilter (&$arr)
  316. {
  317. $ra=Array('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/','/script/','/javascript/','/vbscript/','/expression/','/applet/'
  318. ,'/meta/','/xml/','/blink/','/link/','/style/','/embed/','/object/','/frame/','/layer/','/title/','/bgsound/'
  319. ,'/base/','/onload/','/onunload/','/onchange/','/onsubmit/','/onreset/','/onselect/','/onblur/','/onfocus/',
  320. '/onabort/','/onkeydown/','/onkeypress/','/onkeyup/','/onclick/','/ondblclick/','/onmousedown/','/onmousemove/'
  321. ,'/onmouseout/','/onmouseover/','/onmouseup/','/onunload/');
  322. if (is_array($arr))
  323. {
  324. foreach ($arr as $key => $value)
  325. {
  326. if (!is_array($value))
  327. {
  328. if (!get_magic_quotes_gpc()) //不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。
  329. {
  330. $value = addslashes($value); //给单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符)
  331. #加上反斜线转义
  332. }
  333. $value = preg_replace($ra,'',$value); //删除非打印字符,粗暴式过滤xss可疑字符串
  334. // $arr[$key] = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体
  335. }
  336. else
  337. {
  338. self::SafeFilter($arr[$key]);
  339. }
  340. }
  341. }
  342. return $arr;
  343. }
  344. public static function getSign($data)
  345. {
  346. return md5($data . "145709480B89EE59E3F4D43A56C355F2");
  347. }
  348. /**
  349. * 将二维数组转化为对象数组
  350. * @param array $arr
  351. * @return array
  352. */
  353. public static function arrayToObjects(array $arr)
  354. {
  355. $ret = [];
  356. foreach ($arr as $item) {
  357. $ret[] = (object)$item;
  358. }
  359. return $ret;
  360. }
  361. /**
  362. * 异步批量get请求
  363. *
  364. * @param array $nodes 格式: 'key' => ['url', 'data'] key是标识key,url是请求host,data是post传递的数据
  365. * @param integer $timeOut 超时时间
  366. * @return void
  367. */
  368. public static function multiGet($nodes, $options = [] ,$timeOut = 5)
  369. {
  370. $mh = curl_multi_init();
  371. $curl_arr = [];
  372. // 将请求放入curl中
  373. foreach ($nodes as $key => $node) {
  374. if (!is_array($node)) {
  375. continue;
  376. }
  377. $ch = curl_init();
  378. $url = $node['url'] . (strpos($node['url'], '?') === FALSE ? '?' : '');
  379. if (isset($node['data'])) {
  380. $url .= http_build_query($node['data']);
  381. }
  382. curl_setopt($ch, CURLOPT_URL, $url);
  383. // 其他的参数按照 function GET($url, $get = array(), array $options = array()) 来
  384. curl_setopt($ch, CURLOPT_HEADER, 0);
  385. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
  386. curl_setopt($ch, CURLOPT_TIMEOUT, 15);
  387. curl_setopt($ch, CURLOPT_SSLVERSION, 1);
  388. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  389. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  390. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  391. // 超时时间
  392. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeOut);
  393. foreach ($options as $k => $v) {
  394. curl_setopt($ch, $k, $v);
  395. }
  396. $curl_arr[$key] = $ch;
  397. curl_multi_add_handle($mh, $curl_arr[$key]);
  398. }
  399. // 发送请求
  400. $running = null;
  401. do {
  402. usleep(10000);
  403. curl_multi_exec($mh, $running);
  404. } while ($running > 0);
  405. // 获取请求数据,并删除请求
  406. $ret = [];
  407. foreach ($nodes as $key => $node) {
  408. $ret[$key] = curl_multi_getcontent($curl_arr[$key]);
  409. curl_multi_remove_handle($mh, $curl_arr[$key]);
  410. }
  411. curl_multi_close($mh);
  412. return $ret;
  413. }
  414. /**
  415. * array_column 一样用法
  416. */
  417. public static function arrayColumn($array, $column_key, $index_key = null): array
  418. {
  419. return $array && $array['datas'] ? array_column($array['datas'], $column_key, $index_key) : [];
  420. }
  421. }