common.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Laravel框架 [ Laravel ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 南京Laravel研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: wesmiler <12345678@qq.com>
  10. // +----------------------------------------------------------------------
  11. // 此文件为系统框架核心公共函数文件,为了系统的稳定与安全,未经允许不得擅自改动
  12. if (!function_exists('array_sort')) {
  13. /**
  14. * 数组排序
  15. * @param array $arr 数据源
  16. * @param $keys KEY
  17. * @param bool $desc 排序方式(默认:asc)
  18. * @return array 返回结果
  19. * @author wesmiler
  20. * @date 2019/5/23
  21. */
  22. function array_sort($arr, $keys, $desc = false)
  23. {
  24. $key_value = $new_array = array();
  25. foreach ($arr as $k => $v) {
  26. $key_value[$k] = $v[$keys];
  27. }
  28. if ($desc) {
  29. arsort($key_value);
  30. } else {
  31. asort($key_value);
  32. }
  33. reset($key_value);
  34. foreach ($key_value as $k => $v) {
  35. $new_array[$k] = $arr[$k];
  36. }
  37. return $new_array;
  38. }
  39. }
  40. if (!function_exists('xml2array')) {
  41. /**
  42. * xml转数组
  43. * @param $xml xml文本
  44. * @return string
  45. * @author wesmiler
  46. * @date 2019/6/6
  47. */
  48. function xml2array(&$xml)
  49. {
  50. $xml = "<xml>";
  51. foreach ($xml as $key => $val) {
  52. if (is_numeric($val)) {
  53. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  54. } else {
  55. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  56. }
  57. }
  58. $xml .= "</xml>";
  59. return $xml;
  60. }
  61. }
  62. if (!function_exists('array2xml')) {
  63. /**
  64. * 数组转xml
  65. * @param $arr 原始数据(数组)
  66. * @param bool $ignore 是否忽视true或fasle
  67. * @param int $level 级别(默认:1)
  68. * @return string 返回结果
  69. * @author wesmiler
  70. * @date 2019/6/6
  71. */
  72. function array2xml($arr, $ignore = true, $level = 1)
  73. {
  74. $s = $level == 1 ? "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<root>\r\n" : '';
  75. $space = str_repeat("\t", $level);
  76. foreach ($arr as $k => $v) {
  77. if (!is_array($v)) {
  78. $s .= $space . "<item id=\"$k\">" . ($ignore ? '<![CDATA[' : '') . $v . ($ignore ? ']]>' : '')
  79. . "</item>\r\n";
  80. } else {
  81. $s .= $space . "<item id=\"$k\">\r\n" . array2xml($v, $ignore, $level + 1) . $space . "</item>\r\n";
  82. }
  83. }
  84. $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
  85. return $level == 1 ? $s . "</root>" : $s;
  86. }
  87. }
  88. if (!function_exists('array_merge_multiple')) {
  89. /**
  90. * 多为数组合并
  91. * @param array $array1 数组1
  92. * @param array $array2 数组2
  93. * @return array 返回合并后的数组
  94. * @author wesmiler
  95. * @date 2019/6/6
  96. */
  97. function array_merge_multiple($array1, $array2)
  98. {
  99. $merge = $array1 + $array2;
  100. $data = [];
  101. foreach ($merge as $key => $val) {
  102. if (isset($array1[$key])
  103. && is_array($array1[$key])
  104. && isset($array2[$key])
  105. && is_array($array2[$key])
  106. ) {
  107. $data[$key] = array_merge_multiple($array1[$key], $array2[$key]);
  108. } else {
  109. $data[$key] = isset($array2[$key]) ? $array2[$key] : $array1[$key];
  110. }
  111. }
  112. return $data;
  113. }
  114. }
  115. if (!function_exists('array_key_value')) {
  116. /**
  117. * 获取数组中某个字段的所有值
  118. * @param array $arr 数据源
  119. * @param string $name 字段名
  120. * @return array 返回结果
  121. * @author wesmiler
  122. * @date 2019/6/6
  123. */
  124. function array_key_value($arr, $name = "")
  125. {
  126. $result = [];
  127. if ($arr) {
  128. foreach ($arr as $key => $val) {
  129. if ($name) {
  130. $result[] = $val[$name];
  131. } else {
  132. $result[] = $key;
  133. }
  134. }
  135. }
  136. $result = array_unique($result);
  137. return $result;
  138. }
  139. }
  140. if (!function_exists('curl_url')) {
  141. /**
  142. * 获取当前访问的完整地址
  143. * @return string 返回结果
  144. * @author wesmiler
  145. * @date 2019/6/6
  146. */
  147. function curl_url()
  148. {
  149. $page_url = 'http';
  150. if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] === 'on') {
  151. $page_url .= "s";
  152. }
  153. $page_url .= "://";
  154. if ($_SERVER["SERVER_PORT"] != "80") {
  155. $page_url .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
  156. } else {
  157. $page_url .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
  158. }
  159. return $page_url;
  160. }
  161. }
  162. if (!function_exists('curl_get')) {
  163. /**
  164. * curl请求(GET)
  165. * @param $url 请求地址
  166. * @param array $data 请求参数
  167. * @return bool|string 返回结果
  168. * @author wesmiler
  169. * @date 2019/6/5
  170. */
  171. function curl_get($url, $data = [])
  172. {
  173. if (!empty($data)) {
  174. $url = $url . '?' . http_build_query($data);
  175. }
  176. // 初始化
  177. $ch = curl_init();
  178. // 设置抓取的url
  179. curl_setopt($ch, CURLOPT_URL, $url);
  180. // 设置头文件的信息作为数据流输出
  181. curl_setopt($ch, CURLOPT_HEADER, false);
  182. // 是否要求返回数据
  183. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  184. // 是否检测服务器的证书是否由正规浏览器认证过的授权CA颁发的
  185. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  186. // 执行命令
  187. $result = curl_exec($ch);
  188. // 关闭URL请求(释放句柄)
  189. curl_close($ch);
  190. return $result;
  191. }
  192. }
  193. if (!function_exists('curl_post')) {
  194. /**
  195. * curl请求(POST)
  196. * @param $url 请求地址
  197. * @param array $data 请求参数
  198. * @return bool|string 返回结果
  199. * @author wesmiler
  200. * @date 2019/6/5
  201. */
  202. function curl_post($url, $data = [])
  203. {
  204. // 初始化
  205. $ch = curl_init();
  206. // 设置post方式提交
  207. curl_setopt($ch, CURLOPT_POST, 1);
  208. // 设置头文件的信息作为数据流输出
  209. curl_setopt($ch, CURLOPT_HEADER, 0);
  210. // 是否要求返回数据
  211. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  212. // 设置抓取的url
  213. curl_setopt($ch, CURLOPT_URL, $url);
  214. // 提交的数据
  215. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  216. // 是否检测服务器的证书是否由正规浏览器认证过的授权CA颁发的
  217. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  218. // 执行命令
  219. $result = curl_exec($ch);
  220. // 关闭URL请求(释放句柄)
  221. curl_close($ch);
  222. return $result;
  223. }
  224. }
  225. if (!function_exists('curl_request')) {
  226. /**
  227. * curl请求(支持get和post)
  228. * @param $url 请求地址
  229. * @param array $data 请求参数
  230. * @param string $type 请求类型(默认:post)
  231. * @param bool $https 是否https请求true或false
  232. * @return bool|string 返回请求结果
  233. * @author wesmiler
  234. * @date 2019/6/6
  235. */
  236. function curl_request($url, $data = [], $type = 'post', $timeout=10, $https = false)
  237. {
  238. // 初始化
  239. $ch = curl_init();
  240. curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  241. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
  242. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  243. // 设置超时时间
  244. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  245. // 是否要求返回数据
  246. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  247. if ($https) {
  248. // 对认证证书来源的检查
  249. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  250. // 从证书中检查SSL加密算法是否存在
  251. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  252. }
  253. if (strtolower($type) == 'post') {
  254. // 设置post方式提交
  255. curl_setopt($ch, CURLOPT_POST, true);
  256. // 提交的数据
  257. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  258. } elseif (!empty($data) && is_array($data)) {
  259. // get网络请求
  260. $url = $url . '?' . http_build_query($data);
  261. }
  262. // 设置抓取的url
  263. curl_setopt($ch, CURLOPT_URL, $url);
  264. // 执行命令
  265. $result = curl_exec($ch);
  266. if ($result === false) {
  267. return false;
  268. }
  269. // 关闭URL请求(释放句柄)
  270. curl_close($ch);
  271. return $result;
  272. }
  273. }
  274. if (!function_exists('httpRequest')) {
  275. /**
  276. *
  277. * 接口请求
  278. * @author wesmiler
  279. * @param $url 接口地址
  280. * @param $data
  281. * @param $type
  282. * @param int $timeout
  283. * @return mixed
  284. */
  285. function httpRequest($url, $data = '', $type = 'post', $cookie = '', $timeout = 60)
  286. {
  287. try {
  288. set_time_limit($timeout);
  289. $data = $data && is_array($data) ? http_build_query($data) : $data;
  290. $url = strtolower($type) == 'get' ? $url . (strpos($url, '?') === false ? '?' : '&') . $data : $url;
  291. $ch = curl_init($url);
  292. if (!empty($cookie)) {
  293. curl_setopt($ch, CURLOPT_COOKIE, $cookie);
  294. }
  295. if($type =='post'){
  296. curl_setopt($ch, CURLOPT_POST, 1);
  297. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  298. }
  299. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //禁止 cURL 验证对等证书
  300. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //是否检测服务器的域名与证书上的是否一致
  301. curl_setopt($ch, CURLOPT_HEADER, 0);
  302. curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
  303. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  304. curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
  305. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  306. $ret = curl_exec($ch);
  307. curl_close($ch);
  308. if (!preg_match("/^{/", $ret)) {
  309. return ['code' => 'err', 'msg' => $ret];
  310. }
  311. $ret = $ret ? json_decode($ret, true) : ['code' => 'err', 'msg' => 'unknow error'];
  312. } catch (\Exception $exception) {
  313. $ret = ['code' => 'error', 'msg' => 'request error'];
  314. }
  315. return $ret;
  316. }
  317. }
  318. if (!function_exists('datetime')) {
  319. /**
  320. * 格式化日期函数
  321. * @param $time 时间戳
  322. * @param string $format 输出日期格式
  323. * @return string 返回格式化的日期
  324. * @author wesmiler
  325. * @date 2019/5/23
  326. */
  327. function datetime($time, $format = 'Y-m-d H:i:s')
  328. {
  329. $time = is_numeric($time) ? $time : strtotime($time);
  330. return date($format, $time);
  331. }
  332. }
  333. if (!function_exists('data_auth_sign')) {
  334. /**
  335. * 数据签名认证
  336. * @param $data 数据源
  337. * @return string
  338. * @author wesmiler
  339. * @date 2019/6/6
  340. */
  341. function data_auth_sign($data)
  342. {
  343. // 数据类型检测
  344. if (!is_array($data)) {
  345. $data = (array)$data;
  346. }
  347. // 排序
  348. ksort($data);
  349. // url编码并生成query字符串
  350. $code = http_build_query($data);
  351. // 生成签名
  352. $sign = sha1($code);
  353. return $sign;
  354. }
  355. }
  356. if (!function_exists('decrypt')) {
  357. /**
  358. * DES解密
  359. * @param string $str 解密字符串
  360. * @param string $key 解密KEY
  361. * @return mixed
  362. * @author wesmiler
  363. * @date 2019/6/6
  364. */
  365. function decrypt($str, $key = 'p@ssw0rd')
  366. {
  367. $str = base64_decode($str);
  368. $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
  369. $block = mcrypt_get_block_size('des', 'ecb');
  370. $pad = ord($str[($len = strlen($str)) - 1]);
  371. if ($pad && $pad < $block && preg_match('/' . chr($pad) . '{' . $pad . '}$/', $str)) {
  372. $str = substr($str, 0, strlen($str) - $pad);
  373. }
  374. return unserialize($str);
  375. }
  376. }
  377. if (!function_exists('encrypt')) {
  378. /**
  379. *
  380. * @param string $str 加密字符串
  381. * @param string $key 加密KEY
  382. * @return string
  383. * @author wesmiler
  384. * @date 2019/6/6
  385. */
  386. function encrypt($str, $key = 'p@ssw0rd')
  387. {
  388. $prep_code = serialize($str);
  389. $block = mcrypt_get_block_size('des', 'ecb');
  390. if (($pad = $block - (strlen($prep_code) % $block)) < $block) {
  391. $prep_code .= str_repeat(chr($pad), $pad);
  392. }
  393. $encrypt = mcrypt_encrypt(MCRYPT_DES, $key, $prep_code, MCRYPT_MODE_ECB);
  394. return base64_encode($encrypt);
  395. }
  396. }
  397. if (!function_exists('export_excel')) {
  398. /**
  399. * 导出Excel文件
  400. * @param string $file_name 文件名
  401. * @param array $title 标题
  402. * @param array $data 数据源
  403. * @author wesmiler
  404. * @date 2019/6/6
  405. */
  406. function export_excel($file_name, $title = [], $data = [])
  407. {
  408. // 默认支持最大512M
  409. ini_set('memory_limit', '512M');
  410. ini_set('max_execution_time', 0);
  411. ob_end_clean();
  412. ob_start();
  413. header("Content-Type: text/csv");
  414. header("Content-Disposition:filename=" . $file_name);
  415. $fp = fopen('php://output', 'w');
  416. // 转码 防止乱码(比如微信昵称)
  417. fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
  418. fputcsv($fp, $title);
  419. $index = 0;
  420. foreach ($data as $item) {
  421. if ($index == 1000) {
  422. $index = 0;
  423. ob_flush();
  424. flush();
  425. }
  426. $index++;
  427. fputcsv($fp, $item);
  428. }
  429. ob_flush();
  430. flush();
  431. ob_end_clean();
  432. }
  433. }
  434. if (!function_exists('ecm_define')) {
  435. /**
  436. * 定义常量(读取数组或引用文件)
  437. * @param $value 数据源
  438. * @return bool
  439. * @author wesmiler
  440. * @date 2019/6/6
  441. */
  442. function ecm_define($value)
  443. {
  444. if (is_string($value)) {
  445. /* 导入数组 */
  446. $value = include($value);
  447. }
  448. if (!is_array($value)) {
  449. /* 不是数组,无法定义 */
  450. return false;
  451. }
  452. foreach ($value as $key => $val) {
  453. if (is_string($val) || is_numeric($val) || is_bool($val) || is_null($val)) {
  454. // 判断是否已定义过,否则进行定义
  455. defined(strtoupper($key)) or define(strtoupper($key), $val);
  456. }
  457. }
  458. }
  459. }
  460. if (!function_exists('format_time')) {
  461. /**
  462. * 格式化时间段
  463. * @param int $time 时间戳
  464. * @return string 输出格式化时间
  465. * @author wesmiler
  466. * @date 2019/5/23
  467. */
  468. function format_time($time)
  469. {
  470. $interval = time() - $time;
  471. $format = array(
  472. '31536000' => '年',
  473. '2592000' => '个月',
  474. '604800' => '星期',
  475. '86400' => '天',
  476. '3600' => '小时',
  477. '60' => '分钟',
  478. '1' => '秒',
  479. );
  480. foreach ($format as $key => $val) {
  481. $match = floor($interval / (int)$key);
  482. if (0 != $match) {
  483. return $match . $val . '前';
  484. }
  485. }
  486. return date('Y-m-d', $time);
  487. }
  488. }
  489. if (!function_exists('format_bytes')) {
  490. /**
  491. * 将字节转换为可读文本
  492. * @param int $size 字节大小
  493. * @param string $delimiter 分隔符
  494. * @return string 返回结果
  495. * @author wesmiler
  496. * @date 2019/5/23
  497. */
  498. function format_bytes($size, $delimiter = '')
  499. {
  500. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  501. for ($i = 0; $size >= 1024 && $i < 6; $i++) {
  502. $size /= 1024;
  503. }
  504. return round($size, 2) . $delimiter . $units[$i];
  505. }
  506. }
  507. if (!function_exists('format_yuan')) {
  508. /**
  509. * 以分为单位的金额转换成元
  510. * @param int $money 金额
  511. * @return string 返回格式化的金额
  512. * @author wesmiler
  513. * @date 2019/5/23
  514. */
  515. function format_yuan($money = 0)
  516. {
  517. if ($money > 0) {
  518. return number_format($money / 100, 2, ".", "");
  519. }
  520. return "0.00";
  521. }
  522. }
  523. if(!function_exists('makeUniqueCode')){
  524. /**
  525. * 生成邀请码
  526. * @param int $len 长度
  527. * @return false|string
  528. */
  529. function makeUniqueCode($str='',$len=6){
  530. return substr(base_convert(md5(uniqid(md5(microtime(true).$str),true)), 16, 10), 0, $len);
  531. }
  532. }
  533. if (!function_exists('format_cent')) {
  534. /**
  535. * 以元为单位的金额转化成分
  536. * @param $money 金额
  537. * @return string 返回格式化的金额
  538. * @author wesmiler
  539. * @date 2019/5/23
  540. */
  541. function format_cent($money)
  542. {
  543. return (string)($money * 100);
  544. }
  545. }
  546. if (!function_exists('format_bank_card')) {
  547. /**
  548. * 银行卡格式转换
  549. * @param string $card_no 银行卡号
  550. * @param bool $is_format 是否格式化
  551. * @return string 输出结果
  552. * @author wesmiler
  553. * @date 2019/5/23
  554. */
  555. function format_bank_card($card_no, $is_format = true)
  556. {
  557. if ($is_format) {
  558. // 截取银行卡号前4位
  559. $prefix = substr($card_no, 0, 4);
  560. // 截取银行卡号后4位
  561. $suffix = substr($card_no, -4, 4);
  562. $format_card_no = $prefix . " **** **** **** " . $suffix;
  563. } else {
  564. // 4的意思就是每4个为一组
  565. $arr = str_split($card_no, 4);
  566. $format_card_no = implode(' ', $arr);
  567. }
  568. return $format_card_no;
  569. }
  570. }
  571. if (!function_exists('format_mobile')) {
  572. /**
  573. * 格式化手机号码
  574. * @param string $mobile 手机号码
  575. * @return string 返回结果
  576. * @author wesmiler
  577. * @date 2019/5/23
  578. */
  579. function format_mobile($mobile)
  580. {
  581. return substr($mobile, 0, 5) . "****" . substr($mobile, 9, 2);
  582. }
  583. }
  584. if (!function_exists('get_random_code')) {
  585. /**
  586. * 获取指定位数的随机码
  587. * @param int $num 随机码长度
  588. * @return string 返回字符串
  589. * @author wesmiler
  590. * @date 2019/5/23
  591. */
  592. function get_random_code($num = 12)
  593. {
  594. $codeSeeds = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  595. $codeSeeds .= "abcdefghijklmnopqrstuvwxyz";
  596. $codeSeeds .= "0123456789_";
  597. $len = strlen($codeSeeds);
  598. $code = "";
  599. for ($i = 0; $i < $num; $i++) {
  600. $rand = rand(0, $len - 1);
  601. $code .= $codeSeeds[$rand];
  602. }
  603. return $code;
  604. }
  605. }
  606. if (!function_exists('get_password')) {
  607. /**
  608. * 获取双MD5加密密码
  609. * @param string $password 加密字符串
  610. * @return string 输出MD5加密字符串
  611. * @author wesmiler
  612. * @date 2019/5/23
  613. */
  614. function get_password($password)
  615. {
  616. return md5(md5($password));
  617. }
  618. }
  619. if (!function_exists('get_order_num')) {
  620. /**
  621. * 生成订单号
  622. * @param string $prefix 订单前缀(如:JD-)
  623. * @return string 输出订单号字符串
  624. * @author wesmiler
  625. * @date 2019/5/23
  626. */
  627. function get_order_num($prefix = '')
  628. {
  629. $micro = substr(microtime(), 2, 3);
  630. return $prefix . date("YmdHis") . $micro . rand(100000, 999999);
  631. }
  632. }
  633. if (!function_exists('getter')) {
  634. /**
  635. * 获取数组的下标值
  636. * @param array $data 数据源
  637. * @param string $field 字段名称
  638. * @param string $default 默认值
  639. * @return mixed|string 返回结果
  640. * @author wesmiler
  641. * @date 2019/5/23
  642. */
  643. function getter($data, $field, $default = '')
  644. {
  645. $result = $default;
  646. if (isset($data[$field])) {
  647. $result = $data[$field];
  648. }
  649. return $result;
  650. }
  651. }
  652. if (!function_exists('get_zodiac_sign')) {
  653. /**
  654. * 根据月、日获取星座
  655. * @param $month 月份
  656. * @param $day 日期
  657. * @return string 返回结果
  658. * @author wesmiler
  659. * @date 2019/5/23
  660. */
  661. function get_zodiac_sign($month, $day)
  662. {
  663. // 检查参数有效性
  664. if ($month < 1 || $month > 12 || $day < 1 || $day > 31) {
  665. return false;
  666. }
  667. // 星座名称以及开始日期
  668. $signs = array(
  669. array("20" => "水瓶座"),
  670. array("19" => "双鱼座"),
  671. array("21" => "白羊座"),
  672. array("20" => "金牛座"),
  673. array("21" => "双子座"),
  674. array("22" => "巨蟹座"),
  675. array("23" => "狮子座"),
  676. array("23" => "处女座"),
  677. array("23" => "天秤座"),
  678. array("24" => "天蝎座"),
  679. array("22" => "射手座"),
  680. array("22" => "摩羯座")
  681. );
  682. list($sign_start, $sign_name) = each($signs[(int)$month - 1]);
  683. if ($day < $sign_start) {
  684. list($sign_start, $sign_name) = each($signs[($month - 2 < 0) ? $month = 11 : $month -= 2]);
  685. }
  686. return $sign_name;
  687. }
  688. }
  689. if (!function_exists('get_image_url')) {
  690. /**
  691. * 获取图片地址
  692. * @param $image_url 图片地址
  693. * @return string 返回图片网络地址
  694. * @author wesmiler
  695. * @date 2019/6/6
  696. */
  697. function get_image_url($image_url)
  698. {
  699. return strpos($image_url,'http') === false? IMG_URL . $image_url : $image_url;
  700. }
  701. }
  702. if (!function_exists('get_file_url')) {
  703. /**
  704. * 获取文件地址
  705. * @param $file_url 文件地址
  706. * @return string 返回图片网络地址
  707. * @author wesmiler
  708. * @date 2019/6/6
  709. */
  710. function get_file_url($file_url)
  711. {
  712. return strpos($file_url,'http') === false? IMG_URL . $file_url : $file_url;
  713. }
  714. }
  715. if (!function_exists('get_hash')) {
  716. /**
  717. * 获取HASH值
  718. * @return string 返回hash字符串
  719. * @author wesmiler
  720. * @date 2019/6/6
  721. */
  722. function get_hash()
  723. {
  724. $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()+-';
  725. $random = $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)]
  726. . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)];
  727. $content = uniqid() . $random;
  728. return sha1($content);
  729. }
  730. }
  731. if (!function_exists('get_server_ip')) {
  732. /**
  733. * 获取服务端IP地址
  734. * @return string 返回IP地址
  735. * @author wesmiler
  736. * @date 2019/6/6
  737. */
  738. function get_server_ip()
  739. {
  740. if (isset($_SERVER)) {
  741. if ($_SERVER['SERVER_ADDR']) {
  742. $server_ip = $_SERVER['SERVER_ADDR'];
  743. } else {
  744. $server_ip = $_SERVER['LOCAL_ADDR'];
  745. }
  746. } else {
  747. $server_ip = getenv('SERVER_ADDR');
  748. }
  749. return $server_ip;
  750. }
  751. }
  752. if (!function_exists('get_client_ip')) {
  753. /**
  754. * 获取客户端IP地址
  755. * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
  756. * @param bool $adv 否进行高级模式获取(有可能被伪装)
  757. * @return mixed 返回IP
  758. * @author wesmiler
  759. * @date 2019/5/23
  760. */
  761. function get_client_ip($type = 0, $adv = false)
  762. {
  763. $type = $type ? 1 : 0;
  764. static $ip = null;
  765. if ($ip !== null) {
  766. return $ip[$type];
  767. }
  768. if ($adv) {
  769. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  770. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  771. $pos = array_search('unknown', $arr);
  772. if (false !== $pos) {
  773. unset($arr[$pos]);
  774. }
  775. $ip = trim($arr[0]);
  776. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  777. $ip = $_SERVER['HTTP_CLIENT_IP'];
  778. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  779. $ip = $_SERVER['REMOTE_ADDR'];
  780. }
  781. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  782. $ip = $_SERVER['REMOTE_ADDR'];
  783. }
  784. // IP地址合法验证
  785. $long = sprintf("%u", ip2long($ip));
  786. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  787. return $ip[$type];
  788. }
  789. }
  790. if (!function_exists('formatName')) {
  791. /**
  792. * 格式化账号
  793. * @param $name
  794. */
  795. function formatName($name)
  796. {
  797. return substr($name, 0, 2) . '****' . substr($name, -3, 3);
  798. }
  799. }
  800. if (!function_exists('moneyFormat')) {
  801. /**
  802. * 金钱格式化小数点
  803. * @param $money
  804. * @param int $decimal 小数点位数,默认系统配置2位
  805. * @return float
  806. */
  807. function moneyFormat($money, $decimal = null)
  808. {
  809. $formatConfig = [];
  810. $charset = !empty($formatConfig['charset']) ? trim($formatConfig['charset']) : 'utf-8';
  811. if ($decimal === null) {
  812. $decimal = isset($formatConfig['moneyDecimal']) ? intval($formatConfig['moneyDecimal']) : 2;
  813. }
  814. $money = round($money, $decimal + 1);
  815. $data = explode('.', $money);
  816. $money = isset($data[0]) ? $data[0] : 0;
  817. $float = isset($data[1]) ? $data[1] : '';
  818. $len = $float ? mb_strlen($float, $charset) : 0;
  819. $decimal = $decimal >= 0 ? intval($decimal) : 2;
  820. $num1 = isset($data[1]) ? $data[1] : '';
  821. $float = $len >= $decimal ? mb_substr($num1, 0, $decimal, $charset) : $float . str_repeat('0', $decimal - $len);
  822. $money = $money . '.' . $float;
  823. return number_format($money, $decimal, '.', '');
  824. }
  825. }
  826. if (!function_exists('get_guid_v4')) {
  827. /**
  828. * 获取唯一性GUID
  829. * @param bool $trim 是否去除{}
  830. * @return string 返回GUID字符串
  831. * @author wesmiler
  832. * @date 2019/6/6
  833. */
  834. function get_guid_v4($trim = true)
  835. {
  836. // Windows
  837. if (function_exists('com_create_guid') === true) {
  838. $charid = com_create_guid();
  839. return $trim == true ? trim($charid, '{}') : $charid;
  840. }
  841. // OSX/Linux
  842. if (function_exists('openssl_random_pseudo_bytes') === true) {
  843. $data = openssl_random_pseudo_bytes(16);
  844. $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
  845. $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
  846. return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  847. }
  848. // Fallback (PHP 4.2+)
  849. mt_srand((double)microtime() * 10000);
  850. $charid = strtolower(md5(uniqid(rand(), true)));
  851. $hyphen = chr(45); // "-"
  852. $lbrace = $trim ? "" : chr(123); // "{"
  853. $rbrace = $trim ? "" : chr(125); // "}"
  854. $guidv4 = $lbrace .
  855. substr($charid, 0, 8) . $hyphen .
  856. substr($charid, 8, 4) . $hyphen .
  857. substr($charid, 12, 4) . $hyphen .
  858. substr($charid, 16, 4) . $hyphen .
  859. substr($charid, 20, 12) .
  860. $rbrace;
  861. return $guidv4;
  862. }
  863. }
  864. if (!function_exists('is_email')) {
  865. /**
  866. * 判断是否为邮箱
  867. * @param string $str 邮箱
  868. * @return false 返回结果true或false
  869. * @author wesmiler
  870. * @date 2019/5/23
  871. */
  872. function is_email($str)
  873. {
  874. return preg_match('/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/', $str);
  875. }
  876. }
  877. if (!function_exists('is_mobile')) {
  878. /**
  879. * 判断是否为手机号
  880. * @param string $num 手机号码
  881. * @return false 返回结果true或false
  882. * @author wesmiler
  883. * @date 2019/5/23
  884. */
  885. function is_mobile($num)
  886. {
  887. return preg_match('/^1(3|4|5|7|8)\d{9}$/', $num);
  888. }
  889. }
  890. if (!function_exists('is_zipcode')) {
  891. /**
  892. * 验证邮编是否正确
  893. * @param string $code 邮编
  894. * @return false 返回结果true或false
  895. * @author wesmiler
  896. * @date 2019/5/23
  897. */
  898. function is_zipcode($code)
  899. {
  900. return preg_match('/^[1-9][0-9]{5}$/', $code);
  901. }
  902. }
  903. if (!function_exists('is_idcard')) {
  904. /**
  905. * 验证身份证是否正确
  906. * @param string $idno 身份证号
  907. * @return bool 返回结果true或false
  908. * @author wesmiler
  909. * @date 2019/5/23
  910. */
  911. function is_idcard($idno)
  912. {
  913. $idno = strtoupper($idno);
  914. $regx = '/(^\d{15}$)|(^\d{17}([0-9]|X)$)/';
  915. $arr_split = array();
  916. if (!preg_match($regx, $idno)) {
  917. return false;
  918. }
  919. // 检查15位
  920. if (15 == strlen($idno)) {
  921. $regx = '/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/';
  922. @preg_match($regx, $idno, $arr_split);
  923. $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
  924. if (!strtotime($dtm_birth)) {
  925. return false;
  926. } else {
  927. return true;
  928. }
  929. } else {
  930. // 检查18位
  931. $regx = '/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/';
  932. @preg_match($regx, $idno, $arr_split);
  933. $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
  934. // 检查生日日期是否正确
  935. if (!strtotime($dtm_birth)) {
  936. return false;
  937. } else {
  938. // 检验18位身份证的校验码是否正确。
  939. // 校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
  940. $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
  941. $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
  942. $sign = 0;
  943. for ($i = 0; $i < 17; $i++) {
  944. $b = (int)$idno{$i};
  945. $w = $arr_int[$i];
  946. $sign += $b * $w;
  947. }
  948. $n = $sign % 11;
  949. $val_num = $arr_ch[$n];
  950. if ($val_num != substr($idno, 17, 1)) {
  951. return false;
  952. } else {
  953. return true;
  954. }
  955. }
  956. }
  957. }
  958. }
  959. if (!function_exists('is_empty')) {
  960. /**
  961. * 判断是否为空
  962. * @param $value 参数值
  963. * @return bool 返回结果true或false
  964. * @author wesmiler
  965. * @date 2019/6/5
  966. */
  967. function is_empty($value)
  968. {
  969. // 判断是否存在该值
  970. if (!isset($value)) {
  971. return true;
  972. }
  973. // 判断是否为empty
  974. if (empty($value)) {
  975. return true;
  976. }
  977. // 判断是否为null
  978. if ($value === null) {
  979. return true;
  980. }
  981. // 判断是否为空字符串
  982. if (trim($value) === '') {
  983. return true;
  984. }
  985. // 默认返回false
  986. return false;
  987. }
  988. }
  989. if (!function_exists('mkdirs')) {
  990. /**
  991. * 递归创建目录
  992. * @param string $dir 需要创建的目录路径
  993. * @param int $mode 权限值
  994. * @return bool 返回结果true或false
  995. * @author wesmiler
  996. * @date 2019/6/6
  997. */
  998. function mkdirs($dir, $mode = 0777)
  999. {
  1000. if (is_dir($dir) || mkdir($dir, $mode, true)) {
  1001. return true;
  1002. }
  1003. if (!mkdirs(dirname($dir), $mode)) {
  1004. return false;
  1005. }
  1006. return mkdir($dir, $mode, true);
  1007. }
  1008. }
  1009. if (!function_exists('rmdirs')) {
  1010. /**
  1011. * 删除文件夹
  1012. * @param string $dir 文件夹路径
  1013. * @param bool $rmself 是否删除本身true或false
  1014. * @return bool 返回删除结果
  1015. * @author wesmiler
  1016. * @date 2019/6/6
  1017. */
  1018. function rmdirs($dir, $rmself = true)
  1019. {
  1020. if (!is_dir($dir)) {
  1021. return false;
  1022. }
  1023. $files = new RecursiveIteratorIterator(
  1024. new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
  1025. RecursiveIteratorIterator::CHILD_FIRST
  1026. );
  1027. foreach ($files as $file) {
  1028. $todo = ($file->isDir() ? 'rmdir' : 'unlink');
  1029. $todo($file->getRealPath());
  1030. }
  1031. if ($rmself) {
  1032. @rmdir($dir);
  1033. }
  1034. return true;
  1035. }
  1036. }
  1037. if (!function_exists('copydirs')) {
  1038. /**
  1039. * 复制文件夹
  1040. * @param string $source 原文件夹路径
  1041. * @param string $dest 目的文件夹路径
  1042. * @author wesmiler
  1043. * @date 2019/6/6
  1044. */
  1045. function copydirs($source, $dest)
  1046. {
  1047. if (!is_dir($dest)) {
  1048. mkdir($dest, 0755, true);
  1049. }
  1050. $iterator = new RecursiveIteratorIterator(
  1051. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  1052. RecursiveIteratorIterator::SELF_FIRST
  1053. );
  1054. foreach ($iterator as $item) {
  1055. if ($item->isDir()) {
  1056. $sent_dir = $dest . "/" . $iterator->getSubPathName();
  1057. if (!is_dir($sent_dir)) {
  1058. mkdir($sent_dir, 0755, true);
  1059. }
  1060. } else {
  1061. copy($item, $dest . "/" . $iterator->getSubPathName());
  1062. }
  1063. }
  1064. }
  1065. }
  1066. if (!function_exists('message')) {
  1067. /**
  1068. * 消息数组
  1069. * @param string $msg 提示文字
  1070. * @param bool $success 是否成功true或false
  1071. * @param array $data 结果数据
  1072. * @param int $code 编码
  1073. * @return array 返回结果
  1074. * @author wesmiler
  1075. * @date 2019/5/28
  1076. */
  1077. function message($msg = "操作成功", $success = true, $data = [], $code = 0)
  1078. {
  1079. $msg = is_int($msg)? lang($msg, 'api') : $msg;
  1080. $result = ['success' => $success, 'msg' => $msg, 'data' => $data];
  1081. if ($success) {
  1082. $result['code'] = 0;
  1083. } else {
  1084. $result['code'] = $code ? $code : -1;
  1085. }
  1086. return $result;
  1087. }
  1088. }
  1089. if (!function_exists('getValidatorError')) {
  1090. /**
  1091. * 错误验证
  1092. * @param $error
  1093. * @return mixed
  1094. */
  1095. function getValidatorError($validator)
  1096. {
  1097. $errors = $validator->errors()->all();
  1098. return isset($errors[0]) ? $errors[0] : 'validator error';
  1099. }
  1100. }
  1101. if (!function_exists('lang')) {
  1102. /**
  1103. * 语言转换
  1104. * @param $value
  1105. * @return array|\Illuminate\Contracts\Translation\Translator|null|string
  1106. */
  1107. function lang($value, $app = 'api')
  1108. {
  1109. $value = $app ? $app . '.' . $value : $value;
  1110. return trim(trans($value), $app . '.');
  1111. }
  1112. }
  1113. if (!function_exists('num2rmb')) {
  1114. /**
  1115. * 数字金额转大写
  1116. * @param float $num 金额
  1117. * @return string 返回大写金额
  1118. * @author wesmiler
  1119. * @date 2019/6/6
  1120. */
  1121. function num2rmb($num)
  1122. {
  1123. $c1 = "零壹贰叁肆伍陆柒捌玖";
  1124. $c2 = "分角元拾佰仟万拾佰仟亿";
  1125. $num = round($num, 2);
  1126. $num = $num * 100;
  1127. if (strlen($num) > 10) {
  1128. return "oh,sorry,the number is too long!";
  1129. }
  1130. $i = 0;
  1131. $c = "";
  1132. while (1) {
  1133. if ($i == 0) {
  1134. $n = substr($num, strlen($num) - 1, 1);
  1135. } else {
  1136. $n = $num % 10;
  1137. }
  1138. $p1 = substr($c1, 3 * $n, 3);
  1139. $p2 = substr($c2, 3 * $i, 3);
  1140. if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
  1141. $c = $p1 . $p2 . $c;
  1142. } else {
  1143. $c = $p1 . $c;
  1144. }
  1145. $i = $i + 1;
  1146. $num = $num / 10;
  1147. $num = (int)$num;
  1148. if ($num == 0) {
  1149. break;
  1150. }
  1151. }
  1152. $j = 0;
  1153. $slen = strlen($c);
  1154. while ($j < $slen) {
  1155. $m = substr($c, $j, 6);
  1156. if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
  1157. $left = substr($c, 0, $j);
  1158. $right = substr($c, $j + 3);
  1159. $c = $left . $right;
  1160. $j = $j - 3;
  1161. $slen = $slen - 3;
  1162. }
  1163. $j = $j + 3;
  1164. }
  1165. if (substr($c, strlen($c) - 3, 3) == '零') {
  1166. $c = substr($c, 0, strlen($c) - 3);
  1167. } // if there is a '0' on the end , chop it out
  1168. return $c . "整";
  1169. }
  1170. }
  1171. if (!function_exists('object_array')) {
  1172. /**
  1173. * 对象转数组
  1174. * @param $object 对象
  1175. * @return mixed 返回结果
  1176. * @author wesmiler
  1177. * @date 2019/5/23
  1178. */
  1179. function object_array($object)
  1180. {
  1181. //先编码成json字符串,再解码成数组
  1182. return json_decode(json_encode($object), true);
  1183. }
  1184. }
  1185. if (!function_exists('parse_attr')) {
  1186. /**
  1187. * 配置值解析成数组
  1188. * @param string $value 参数值
  1189. * @return array 返回结果
  1190. * @author wesmiler
  1191. * @date 2019/6/6
  1192. */
  1193. function parse_attr($value = '')
  1194. {
  1195. if (is_array($value)) {
  1196. return $value;
  1197. }
  1198. $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
  1199. if (strpos($value, ':')) {
  1200. $value = array();
  1201. foreach ($array as $val) {
  1202. list($k, $v) = explode(':', $val);
  1203. $value[$k] = $v;
  1204. }
  1205. } else {
  1206. $value = $array;
  1207. }
  1208. return $value;
  1209. }
  1210. }
  1211. if (!function_exists('strip_html_tags')) {
  1212. /**
  1213. * 去除HTML标签、图像等 仅保留文本
  1214. * @param string $str 字符串
  1215. * @param int $length 长度
  1216. * @return string 返回结果
  1217. * @author wesmiler
  1218. * @date 2019/5/23
  1219. */
  1220. function strip_html_tags($str, $length = 0)
  1221. {
  1222. // 把一些预定义的 HTML 实体转换为字符
  1223. $str = htmlspecialchars_decode($str);
  1224. // 将空格替换成空
  1225. $str = str_replace("&nbsp;", "", $str);
  1226. // 函数剥去字符串中的 HTML、XML 以及 PHP 的标签,获取纯文本内容
  1227. $str = strip_tags($str);
  1228. $str = str_replace(array("\n", "\r\n", "\r"), ' ', $str);
  1229. $preg = '/<script[\s\S]*?<\/script>/i';
  1230. // 剥离JS代码
  1231. $str = preg_replace($preg, "", $str, -1);
  1232. if ($length == 2) {
  1233. // 返回字符串中的前100字符串长度的字符
  1234. $str = mb_substr($str, 0, $length, "utf-8");
  1235. }
  1236. return $str;
  1237. }
  1238. }
  1239. if (!function_exists('sub_str')) {
  1240. /**
  1241. * 字符串截取
  1242. * @param string $str 需要截取的字符串
  1243. * @param int $start 开始位置
  1244. * @param int $length 截取长度
  1245. * @param bool $suffix 截断显示字符
  1246. * @param string $charset 编码格式
  1247. * @return string 返回结果
  1248. * @author wesmiler
  1249. * @date 2019/5/23
  1250. */
  1251. function sub_str($str, $start = 0, $length = 10, $suffix = true, $charset = "utf-8")
  1252. {
  1253. if (function_exists("mb_substr")) {
  1254. $slice = mb_substr($str, $start, $length, $charset);
  1255. } elseif (function_exists('iconv_substr')) {
  1256. $slice = iconv_substr($str, $start, $length, $charset);
  1257. } else {
  1258. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  1259. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  1260. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  1261. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  1262. preg_match_all($re[$charset], $str, $match);
  1263. $slice = join("", array_slice($match[0], $start, $length));
  1264. }
  1265. $omit = mb_strlen($str) >= $length ? '...' : '';
  1266. return $suffix ? $slice . $omit : $slice;
  1267. }
  1268. }
  1269. if (!function_exists('save_image')) {
  1270. /**
  1271. * 保存图片
  1272. * @param string $img_url 网络图片地址
  1273. * @param string $save_dir 图片保存目录
  1274. * @return string 返回路径
  1275. * @author wesmiler
  1276. * @date 2019/5/23
  1277. */
  1278. function save_image($img_url, $save_dir = '/')
  1279. {
  1280. if (!$img_url) {
  1281. return false;
  1282. }
  1283. $save_dir = trim($save_dir, "/");
  1284. $imgExt = pathinfo($img_url, PATHINFO_EXTENSION);
  1285. // 是否是本站图片
  1286. if (strpos($img_url, IMG_URL) !== false) {
  1287. // 是否是临时文件
  1288. if (strpos($img_url, 'temp') === false) {
  1289. return str_replace(IMG_URL, "", $img_url);
  1290. }
  1291. $new_path = create_image_path($save_dir, $imgExt);
  1292. $old_path = str_replace(IMG_URL, ATTACHMENT_PATH, $img_url);
  1293. if (!file_exists($old_path)) {
  1294. return false;
  1295. }
  1296. rename($old_path, ATTACHMENT_PATH . $new_path);
  1297. return $new_path;
  1298. } else {
  1299. // 保存远程图片
  1300. $new_path = save_remote_image($img_url, $save_dir);
  1301. }
  1302. return $new_path;
  1303. }
  1304. }
  1305. if (!function_exists('create_image_path')) {
  1306. /**
  1307. * 创建图片存储目录
  1308. * @param string $save_dir 存储目录
  1309. * @param string $image_ext 图片后缀
  1310. * @param string $image_root 图片存储根目录路径
  1311. * @return string 返回文件目录
  1312. * @author wesmiler
  1313. * @date 2019/5/23
  1314. */
  1315. function create_image_path($save_dir = "", $image_ext = "", $image_root = IMG_PATH)
  1316. {
  1317. $image_dir = date("/Ymd/");
  1318. if ($image_dir) {
  1319. $image_dir = ($save_dir ? "/" : '') . $save_dir . $image_dir;
  1320. }
  1321. // 未指定后缀默认使用JPG
  1322. if (!$image_ext) {
  1323. $image_ext = "jpg";
  1324. }
  1325. $image_path = $image_root . $image_dir;
  1326. if (!is_dir($image_path)) {
  1327. // 创建目录并赋予权限
  1328. mkdir($image_path, 0777, true);
  1329. }
  1330. $file_name = substr(md5(time() . rand(0, 999999)), 8, 16) . rand(100, 999) . ".{$image_ext}";
  1331. $file_path = str_replace(ATTACHMENT_PATH, "", IMG_PATH) . $image_dir . $file_name;
  1332. return $file_path;
  1333. }
  1334. }
  1335. if (!function_exists('save_remote_image')) {
  1336. /**
  1337. * 保存网络图片到本地
  1338. * @param string $img_url 网络图片地址
  1339. * @param string $save_dir 保存目录
  1340. * @return bool|string 图片路径
  1341. * @author wesmiler
  1342. * @date 2019/5/23
  1343. */
  1344. function save_remote_image($img_url, $save_dir = '/')
  1345. {
  1346. $content = file_get_contents($img_url);
  1347. if (!$content) {
  1348. return false;
  1349. }
  1350. if ($content{0} . $content{1} == "\xff\xd8") {
  1351. $image_ext = 'jpg';
  1352. } elseif ($content{0} . $content{1} . $content{2} == "\x47\x49\x46") {
  1353. $image_ext = 'gif';
  1354. } elseif ($content{0} . $content{1} . $content{2} == "\x89\x50\x4e") {
  1355. $image_ext = 'png';
  1356. } else {
  1357. // 不是有效图片
  1358. return false;
  1359. }
  1360. $save_path = create_image_path($save_dir, $image_ext);
  1361. return file_put_contents(IMG_PATH . $save_path, $content) ? $save_path : false;
  1362. }
  1363. }
  1364. if (!function_exists('save_image_content')) {
  1365. /**
  1366. * 富文本信息处理
  1367. * @param string $content 富文本内容
  1368. * @param bool $title 标题
  1369. * @param string $path 图片存储路径
  1370. * @return bool|int 返回结果
  1371. * @author wesmiler
  1372. * @date 2020-04-21
  1373. */
  1374. function save_image_content(&$content, $title = false, $path = 'article')
  1375. {
  1376. // 图片处理
  1377. preg_match_all("/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i", str_ireplace("\\", "", $content), $match);
  1378. if ($match[1]) {
  1379. foreach ($match[1] as $id => $val) {
  1380. $save_image = save_image($val, $path);
  1381. if ($save_image) {
  1382. $content = str_replace($val, "[IMG_URL]" . $save_image, $content);
  1383. }
  1384. }
  1385. }
  1386. // 视频处理
  1387. preg_match_all("/<embed .*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i", str_ireplace("\\", "", $content), $match2);
  1388. if ($match2[1]) {
  1389. foreach ($match2[1] as $vo) {
  1390. $save_video = save_image($vo, $path);
  1391. if ($save_video) {
  1392. $content = str_replace($vo, "[IMG_URL]" . str_replace(ATTACHMENT_PATH, "", IMG_PATH) . $save_video, $content);
  1393. }
  1394. }
  1395. }
  1396. // 提示标签替换
  1397. if ((strpos($content, 'alt=\"\"') !== false) && $title) {
  1398. $content = str_replace('alt=\"\"', 'alt=\"' . $title . '\"', $content);
  1399. }
  1400. return true;
  1401. }
  1402. }
  1403. if (!function_exists('upload_image')) {
  1404. /**
  1405. * 上传图片
  1406. * @param $request 网络请求
  1407. * @param string $form_name 文件表单名
  1408. * @return array 返回结果
  1409. * @author wesmiler
  1410. * @date 2019/5/23
  1411. */
  1412. function upload_image($request, $form_name = 'file')
  1413. {
  1414. // 检测请求中是否包含name=$form_name的上传文件
  1415. if (!$request->hasFile($form_name)) {
  1416. return message("请上传文件", false);
  1417. }
  1418. // 文件对象
  1419. $file = $request->file($form_name);
  1420. // 判断图片上传是否错误
  1421. if (!$file->isValid()) {
  1422. // 文件上传失败
  1423. return message("上传文件验证失败", false);
  1424. }
  1425. // 文件原名
  1426. $original_name = $file->getClientOriginalName();
  1427. // 文件扩展名(文件后缀)
  1428. $ext = $file->getClientOriginalExtension();
  1429. // 临时文件的绝对路径
  1430. $real_path = $file->getRealPath();
  1431. // 文件类型
  1432. $type = $file->getClientMimeType();
  1433. // 文件大小
  1434. $size = $file->getSize();
  1435. // 文件大小校验
  1436. if ($size > 5 * 1024 * 1024) {
  1437. return message("文件大小超过了5M", false);
  1438. }
  1439. // 文件后缀校验
  1440. $ext_arr = array('jpg', 'jpeg', 'png', 'gif');
  1441. if (!in_array($ext, $ext_arr)) {
  1442. return message("文件格式不正确", false);
  1443. }
  1444. // 文件路径
  1445. $file_dir = UPLOAD_TEMP_PATH . "/" . date('Ymd');
  1446. // 检测文件路径是否存在,不存在则创建
  1447. if (!file_exists($file_dir)) {
  1448. mkdir($file_dir, 0777, true);
  1449. }
  1450. // 文件名称
  1451. $file_name = uniqid() . '.' . $ext;
  1452. // 重命名保存
  1453. $path = $file->move($file_dir, $file_name);
  1454. // 文件临时路径
  1455. $file_path = str_replace(ATTACHMENT_PATH, '', $file_dir) . '/' . $file_name;
  1456. // 返回结果
  1457. $result = [
  1458. 'img_original_name' => $original_name,
  1459. 'img_ext' => $ext,
  1460. 'img_real_path' => $real_path,
  1461. 'img_type' => $type,
  1462. 'img_size' => $size,
  1463. 'img_name' => $file_name,
  1464. 'img_path' => $file_path,
  1465. ];
  1466. return message(MESSAGE_OK, true, $result);
  1467. }
  1468. }
  1469. if (!function_exists('upload_file')) {
  1470. /**
  1471. * 上传文件
  1472. * @param $request 网络请求
  1473. * @param string $form_name 文件表单名
  1474. * @return array 返回结果
  1475. * @author wesmiler
  1476. * @date 2019/5/23
  1477. */
  1478. function upload_file($request, $form_name = 'file')
  1479. {
  1480. // 检测请求中是否包含上传的文件
  1481. if (!$request->hasFile($form_name)) {
  1482. return message("请上传文件", false);
  1483. }
  1484. // 文件对象
  1485. $file = $request->file($form_name);
  1486. // 判断图片上传是否错误
  1487. if (!$file->isValid()) {
  1488. // 文件上传失败
  1489. return message("上传文件验证失败", false);
  1490. }
  1491. // 文件原名
  1492. $original_name = $file->getClientOriginalName();
  1493. // 文件扩展名(文件后缀)
  1494. $ext = $file->getClientOriginalExtension();
  1495. // 临时文件的绝对路径
  1496. $real_path = $file->getRealPath();
  1497. // 文件类型
  1498. $type = $file->getClientMimeType();
  1499. // 文件大小
  1500. $size = $file->getSize();
  1501. // 文件大小校验(MAX=5M)
  1502. $file_max_size = 50 * 1024 * 1024;
  1503. if ($size > $file_max_size) {
  1504. return message("您上传的文件过大,最大值为" . $file_max_size / 1024 / 1024 . "MB", false);
  1505. }
  1506. // 允许上传的文件后缀
  1507. $file_exts = array('xls', 'xlsx', 'csv','mp3','mp4','WMA','MPEG');
  1508. if (!in_array($ext, $file_exts)) {
  1509. return message("文件格式不正确", false);
  1510. }
  1511. // 文件路径
  1512. $file_dir = UPLOAD_FILE_PATH . "/" . date('Ymd');
  1513. // 检测文件路径是否存在,不存在则创建
  1514. if (!file_exists($file_dir)) {
  1515. mkdir($file_dir, 0777, true);
  1516. }
  1517. // 文件名称
  1518. $file_name = uniqid() . '.' . $ext;
  1519. // 重命名保存
  1520. $path = $file->move($file_dir, $file_name);
  1521. // 文件临时路径
  1522. $file_path = str_replace(ATTACHMENT_PATH, '', $file_dir) . '/' . $file_name;
  1523. // 返回结果
  1524. $result = [
  1525. 'file_original_name' => $original_name,
  1526. 'file_ext' => $ext,
  1527. 'file_real_path' => $real_path,
  1528. 'file_type' => $type,
  1529. 'file_size' => $size,
  1530. 'file_name' => $file_name,
  1531. 'file_path' => $file_path,
  1532. ];
  1533. return message(MESSAGE_OK, true, $result);
  1534. }
  1535. }
  1536. if (!function_exists('widget')) {
  1537. /**
  1538. * 加载系统组件,传入的名字会以目录和类名区别
  1539. * 如Home.Common就代表Widget目录下的Home/Common.php这个widget。
  1540. * @param $widgetName 组件名称
  1541. * @return bool|mixed
  1542. * @author wesmiler
  1543. * @date 2019/5/23
  1544. */
  1545. function widget($widgetName)
  1546. {
  1547. $widgetNameEx = explode('.', $widgetName);
  1548. if (!isset($widgetNameEx[1])) {
  1549. return false;
  1550. }
  1551. $widgetClass = 'App\\Widget\\' . $widgetNameEx[0] . '\\' . $widgetNameEx[1];
  1552. if (app()->bound($widgetName)) {
  1553. return app()->make($widgetName);
  1554. }
  1555. app()->singleton($widgetName, function () use ($widgetClass) {
  1556. return new $widgetClass();
  1557. });
  1558. return app()->make($widgetName);
  1559. }
  1560. }