common.php 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. <?php
  2. // 公共助手函数
  3. use Symfony\Component\VarExporter\VarExporter;
  4. use think\Db;
  5. use think\exception\HttpResponseException;
  6. use think\Response;
  7. if (!function_exists('__')) {
  8. /**
  9. * 获取语言变量值
  10. * @param string $name 语言变量名
  11. * @param array $vars 动态变量值
  12. * @param string $lang 语言
  13. * @return mixed
  14. */
  15. function __($name, $vars = [], $lang = '')
  16. {
  17. if (is_numeric($name) || !$name) {
  18. return $name;
  19. }
  20. if (!is_array($vars)) {
  21. $vars = func_get_args();
  22. array_shift($vars);
  23. $lang = '';
  24. }
  25. return \think\Lang::get($name, $vars, $lang);
  26. }
  27. }
  28. if (!function_exists('format_bytes')) {
  29. /**
  30. * 将字节转换为可读文本
  31. * @param int $size 大小
  32. * @param string $delimiter 分隔符
  33. * @param int $precision 小数位数
  34. * @return string
  35. */
  36. function format_bytes($size, $delimiter = '', $precision = 2)
  37. {
  38. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  39. for ($i = 0; $size >= 1024 && $i < 6; $i++) {
  40. $size /= 1024;
  41. }
  42. return round($size, $precision) . $delimiter . $units[$i];
  43. }
  44. }
  45. if (!function_exists('datetime')) {
  46. /**
  47. * 将时间戳转换为日期时间
  48. * @param int $time 时间戳
  49. * @param string $format 日期时间格式
  50. * @return string
  51. */
  52. function datetime($time, $format = 'Y-m-d H:i:s')
  53. {
  54. $time = is_numeric($time) ? $time : strtotime($time);
  55. return date($format, $time);
  56. }
  57. }
  58. if (!function_exists('human_date')) {
  59. /**
  60. * 获取语义化时间
  61. * @param int $time 时间
  62. * @param int $local 本地时间
  63. * @return string
  64. */
  65. function human_date($time, $local = null)
  66. {
  67. return \fast\Date::human($time, $local);
  68. }
  69. }
  70. if (!function_exists('cdnurl')) {
  71. /**
  72. * 获取上传资源的CDN的地址
  73. * @param string $url 资源相对地址
  74. * @param boolean $domain 是否显示域名 或者直接传入域名
  75. * @return string
  76. */
  77. function cdnurl($url, $domain = false)
  78. {
  79. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  80. $cdnurl = \think\Config::get('upload.cdnurl');
  81. $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
  82. if ($domain && !preg_match($regex, $url)) {
  83. $domain = is_bool($domain) ? request()->domain() : $domain;
  84. $url = $domain . $url;
  85. }
  86. return $url;
  87. }
  88. }
  89. if (!function_exists('is_really_writable')) {
  90. /**
  91. * 判断文件或文件夹是否可写
  92. * @param string $file 文件或目录
  93. * @return bool
  94. */
  95. function is_really_writable($file)
  96. {
  97. if (DIRECTORY_SEPARATOR === '/') {
  98. return is_writable($file);
  99. }
  100. if (is_dir($file)) {
  101. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  102. if (($fp = @fopen($file, 'ab')) === false) {
  103. return false;
  104. }
  105. fclose($fp);
  106. @chmod($file, 0777);
  107. @unlink($file);
  108. return true;
  109. } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
  110. return false;
  111. }
  112. fclose($fp);
  113. return true;
  114. }
  115. }
  116. if (!function_exists('rmdirs')) {
  117. /**
  118. * 删除文件夹
  119. * @param string $dirname 目录
  120. * @param bool $withself 是否删除自身
  121. * @return boolean
  122. */
  123. function rmdirs($dirname, $withself = true)
  124. {
  125. if (!is_dir($dirname)) {
  126. return false;
  127. }
  128. $files = new RecursiveIteratorIterator(
  129. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
  130. RecursiveIteratorIterator::CHILD_FIRST
  131. );
  132. foreach ($files as $fileinfo) {
  133. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  134. $todo($fileinfo->getRealPath());
  135. }
  136. if ($withself) {
  137. @rmdir($dirname);
  138. }
  139. return true;
  140. }
  141. }
  142. if (!function_exists('copydirs')) {
  143. /**
  144. * 复制文件夹
  145. * @param string $source 源文件夹
  146. * @param string $dest 目标文件夹
  147. */
  148. function copydirs($source, $dest)
  149. {
  150. if (!is_dir($dest)) {
  151. mkdir($dest, 0755, true);
  152. }
  153. foreach (
  154. $iterator = new RecursiveIteratorIterator(
  155. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  156. RecursiveIteratorIterator::SELF_FIRST
  157. ) as $item
  158. ) {
  159. if ($item->isDir()) {
  160. $sontDir = $dest . DS . $iterator->getSubPathName();
  161. if (!is_dir($sontDir)) {
  162. mkdir($sontDir, 0755, true);
  163. }
  164. } else {
  165. copy($item, $dest . DS . $iterator->getSubPathName());
  166. }
  167. }
  168. }
  169. }
  170. if (!function_exists('mb_ucfirst')) {
  171. function mb_ucfirst($string)
  172. {
  173. return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
  174. }
  175. }
  176. if (!function_exists('addtion')) {
  177. /**
  178. * 附加关联字段数据
  179. * @param array $items 数据列表
  180. * @param mixed $fields 渲染的来源字段
  181. * @return array
  182. */
  183. function addtion($items, $fields)
  184. {
  185. if (!$items || !$fields) {
  186. return $items;
  187. }
  188. $fieldsArr = [];
  189. if (!is_array($fields)) {
  190. $arr = explode(',', $fields);
  191. foreach ($arr as $k => $v) {
  192. $fieldsArr[$v] = ['field' => $v];
  193. }
  194. } else {
  195. foreach ($fields as $k => $v) {
  196. if (is_array($v)) {
  197. $v['field'] = isset($v['field']) ? $v['field'] : $k;
  198. } else {
  199. $v = ['field' => $v];
  200. }
  201. $fieldsArr[$v['field']] = $v;
  202. }
  203. }
  204. foreach ($fieldsArr as $k => &$v) {
  205. $v = is_array($v) ? $v : ['field' => $v];
  206. $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  207. $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
  208. $v['column'] = isset($v['column']) ? $v['column'] : 'name';
  209. $v['model'] = isset($v['model']) ? $v['model'] : '';
  210. $v['table'] = isset($v['table']) ? $v['table'] : '';
  211. $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
  212. }
  213. unset($v);
  214. $ids = [];
  215. $fields = array_keys($fieldsArr);
  216. foreach ($items as $k => $v) {
  217. foreach ($fields as $m => $n) {
  218. if (isset($v[$n])) {
  219. $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
  220. }
  221. }
  222. }
  223. $result = [];
  224. foreach ($fieldsArr as $k => $v) {
  225. if ($v['model']) {
  226. $model = new $v['model'];
  227. } else {
  228. $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
  229. }
  230. $primary = $v['primary'] ? $v['primary'] : $model->getPk();
  231. $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
  232. }
  233. foreach ($items as $k => &$v) {
  234. foreach ($fields as $m => $n) {
  235. if (isset($v[$n])) {
  236. $curr = array_flip(explode(',', $v[$n]));
  237. $linedata = array_intersect_key($result[$n], $curr);
  238. $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
  239. }
  240. }
  241. }
  242. return $items;
  243. }
  244. }
  245. if (!function_exists('var_export_short')) {
  246. /**
  247. * 使用短标签打印或返回数组结构
  248. * @param mixed $data
  249. * @param boolean $return 是否返回数据
  250. * @return string
  251. */
  252. function var_export_short($data, $return = true)
  253. {
  254. return var_export($data, $return);
  255. $replaced = [];
  256. $count = 0;
  257. //判断是否是对象
  258. if (is_resource($data) || is_object($data)) {
  259. return var_export($data, $return);
  260. }
  261. //判断是否有特殊的键名
  262. $specialKey = false;
  263. array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
  264. if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
  265. $specialKey = true;
  266. }
  267. });
  268. if ($specialKey) {
  269. return var_export($data, $return);
  270. }
  271. array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
  272. if (is_object($value) || is_resource($value)) {
  273. $replaced[$count] = var_export($value, true);
  274. $value = "##<{$count}>##";
  275. } else {
  276. if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
  277. $index = array_search($value, $replaced);
  278. if ($index === false) {
  279. $replaced[$count] = var_export($value, true);
  280. $value = "##<{$count}>##";
  281. } else {
  282. $value = "##<{$index}>##";
  283. }
  284. }
  285. }
  286. $count++;
  287. });
  288. $dump = var_export($data, true);
  289. $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
  290. $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
  291. $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
  292. $dump = preg_replace('#\)$#', "]", $dump); //End
  293. if ($replaced) {
  294. $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
  295. return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
  296. }, $dump);
  297. }
  298. if ($return === true) {
  299. return $dump;
  300. } else {
  301. echo $dump;
  302. }
  303. }
  304. }
  305. if (!function_exists('letter_avatar')) {
  306. /**
  307. * 首字母头像
  308. * @param $text
  309. * @return string
  310. */
  311. function letter_avatar($text)
  312. {
  313. $total = unpack('L', hash('adler32', $text, true))[1];
  314. $hue = $total % 360;
  315. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  316. $bg = "rgb({$r},{$g},{$b})";
  317. $color = "#ffffff";
  318. $first = mb_strtoupper(mb_substr($text, 0, 1));
  319. $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
  320. $value = 'data:image/svg+xml;base64,' . $src;
  321. return $value;
  322. }
  323. }
  324. if (!function_exists('hsv2rgb')) {
  325. function hsv2rgb($h, $s, $v)
  326. {
  327. $r = $g = $b = 0;
  328. $i = floor($h * 6);
  329. $f = $h * 6 - $i;
  330. $p = $v * (1 - $s);
  331. $q = $v * (1 - $f * $s);
  332. $t = $v * (1 - (1 - $f) * $s);
  333. switch ($i % 6) {
  334. case 0:
  335. $r = $v;
  336. $g = $t;
  337. $b = $p;
  338. break;
  339. case 1:
  340. $r = $q;
  341. $g = $v;
  342. $b = $p;
  343. break;
  344. case 2:
  345. $r = $p;
  346. $g = $v;
  347. $b = $t;
  348. break;
  349. case 3:
  350. $r = $p;
  351. $g = $q;
  352. $b = $v;
  353. break;
  354. case 4:
  355. $r = $t;
  356. $g = $p;
  357. $b = $v;
  358. break;
  359. case 5:
  360. $r = $v;
  361. $g = $p;
  362. $b = $q;
  363. break;
  364. }
  365. return [
  366. floor($r * 255),
  367. floor($g * 255),
  368. floor($b * 255)
  369. ];
  370. }
  371. }
  372. if (!function_exists('check_nav_active')) {
  373. /**
  374. * 检测会员中心导航是否高亮
  375. */
  376. function check_nav_active($url, $classname = 'active')
  377. {
  378. $auth = \app\common\library\Auth::instance();
  379. $requestUrl = $auth->getRequestUri();
  380. $url = ltrim($url, '/');
  381. return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
  382. }
  383. }
  384. if (!function_exists('check_cors_request')) {
  385. /**
  386. * 跨域检测
  387. */
  388. function check_cors_request()
  389. {
  390. if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
  391. $info = parse_url($_SERVER['HTTP_ORIGIN']);
  392. $domainArr = explode(',', config('fastadmin.cors_request_domain'));
  393. $domainArr[] = request()->host(true);
  394. if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
  395. header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
  396. } else {
  397. $response = Response::create('跨域检测无效', 'html', 403);
  398. throw new HttpResponseException($response);
  399. }
  400. header('Access-Control-Allow-Credentials: true');
  401. header('Access-Control-Max-Age: 86400');
  402. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  403. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
  404. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  405. }
  406. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  407. header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  408. }
  409. $response = Response::create('', 'html');
  410. throw new HttpResponseException($response);
  411. }
  412. }
  413. }
  414. }
  415. if (!function_exists('xss_clean')) {
  416. /**
  417. * 清理XSS
  418. */
  419. function xss_clean($content, $is_image = false)
  420. {
  421. return \app\common\library\Security::instance()->xss_clean($content, $is_image);
  422. }
  423. }
  424. if (!function_exists('check_ip_allowed')) {
  425. /**
  426. * 检测IP是否允许
  427. * @param string $ip IP地址
  428. */
  429. function check_ip_allowed($ip = null)
  430. {
  431. $ip = is_null($ip) ? request()->ip() : $ip;
  432. $forbiddenipArr = config('site.forbiddenip');
  433. $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
  434. $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
  435. if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
  436. $response = Response::create('请求无权访问', 'html', 403);
  437. throw new HttpResponseException($response);
  438. }
  439. }
  440. }
  441. if (!function_exists('build_suffix_image')) {
  442. /**
  443. * 生成文件后缀图片
  444. * @param string $suffix 后缀
  445. * @param null $background
  446. * @return string
  447. */
  448. function build_suffix_image($suffix, $background = null)
  449. {
  450. $suffix = mb_substr(strtoupper($suffix), 0, 4);
  451. $total = unpack('L', hash('adler32', $suffix, true))[1];
  452. $hue = $total % 360;
  453. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  454. $background = $background ? $background : "rgb({$r},{$g},{$b})";
  455. $icon = <<<EOT
  456. <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
  457. <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
  458. <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
  459. <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
  460. <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
  461. <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
  462. <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
  463. </svg>
  464. EOT;
  465. return $icon;
  466. }
  467. }
  468. //我的
  469. //结果集信息里,生日转换年龄
  470. function list_birthday_age($list){
  471. if(!$list || empty($list)){
  472. return $list;
  473. }
  474. foreach($list as $vo => $info){
  475. $list[$vo]['age'] = birthtime_to_age($info['birthday']);
  476. }
  477. return $list;
  478. }
  479. //结果集信息里,多个字段需要增加domain_cdnurl
  480. function list_domain_image($list,$field){
  481. if(!$list || empty($list)){
  482. return $list;
  483. }
  484. foreach($list as $vo => $info){
  485. $list[$vo] = info_domain_image($info,$field);
  486. }
  487. return $list;
  488. }
  489. //单条信息里,多个字段需要增加domain_cdnurl
  490. //支持image,images
  491. function info_domain_image($data,$field){
  492. if(!$data || empty($data)){
  493. return $data;
  494. }
  495. foreach($data as $key => $val){
  496. if(in_array($key,$field)){
  497. $data[$key] = one_domain_image($val);
  498. }
  499. }
  500. return $data;
  501. }
  502. //支持单个字段,需要增加domain_cdnurl
  503. //支持image,images
  504. function one_domain_image($one){
  505. if(!$one){
  506. return $one;
  507. }
  508. if(strpos($one,',')){
  509. //逗号隔开的多个图片
  510. $one = explode(',',$one);
  511. foreach($one as $k => $v){
  512. $one[$k] = localpath_to_netpath($v);
  513. }
  514. //$one = implode(',',$one);
  515. }else{
  516. $one = localpath_to_netpath($one);
  517. }
  518. return $one;
  519. }
  520. //本地地址转换为网络地址
  521. function localpath_to_netpath($path)
  522. {
  523. if (empty($path)) {
  524. return '';
  525. } elseif (strrpos($path, 'http') !== false) {
  526. return $path;
  527. } else {
  528. return config('upload.cdnurl') . str_replace("\\", "/", $path);
  529. }
  530. }
  531. //秒 转换 日月分
  532. function Sec2Time($time){
  533. if(is_numeric($time)){
  534. $value = array(
  535. 'years' => 0, 'days' => 0, 'hours' => 0,
  536. 'minutes' => 0, 'seconds' => 0,
  537. );
  538. /*if($time >= 31556926){
  539. $value['years'] = floor($time/31556926);
  540. $time = ($time%31556926);
  541. }*/
  542. if($time >= 86400){
  543. $value['days'] = floor($time/86400);
  544. $time = ($time%86400);
  545. }
  546. if($time >= 3600){
  547. $value['hours'] = floor($time/3600);
  548. $time = ($time%3600);
  549. }
  550. if($time >= 60){
  551. $value['minutes'] = floor($time/60);
  552. $time = ($time%60);
  553. }
  554. $value['seconds'] = floor($time);
  555. //return (array) $value;
  556. //$t=$value['years'] .'年'. $value['days'] .'天'.' '. $value['hours'] .'小时'. $value['minutes'] .'分'.$value['seconds'].'秒';
  557. $t = $value['days'] .'天' . $value['hours'] .'小时'. $value['minutes'] .'分';
  558. return $t;
  559. }else{
  560. return '0天';
  561. }
  562. }
  563. //生日转年龄
  564. function birthtime_to_age($birthtime){
  565. // $birthtime = strtotime('1990-11-06');
  566. if(!$birthtime){
  567. return 0;
  568. }
  569. list($y1,$m1,$d1) = explode("-",date("Y-m-d",$birthtime));
  570. list($y2,$m2,$d2) = explode("-",date("Y-m-d",time()));
  571. $age = $y2 - $y1;
  572. if((int)($m2.$d2) < (int)($m1.$d1))
  573. {$age -= 1;}
  574. if($age < 0){
  575. $age = 0;
  576. }
  577. return $age;
  578. }
  579. if(!function_exists('mk_dir')) {
  580. /**
  581. * 新建目录
  582. */
  583. function mk_dir($dir, $mode = 0770, $tmp = true)
  584. {
  585. $mode = 0770;
  586. if(is_file($dir)) {
  587. //有同名文件
  588. return false;
  589. } else {
  590. if(!is_dir($dir)) { //目录不存在
  591. $dir_up = dirname($dir); //上级目录
  592. if(!is_dir($dir_up)) {
  593. //上级不存在
  594. $rs = @mk_dir($dir_up);
  595. if(!$rs) return false;
  596. }
  597. $rs = @mkdir($dir, $mode); //新建
  598. if(!$rs) return false;
  599. $rs = @chmod($dir, $mode); //改权限
  600. if(!$rs) return false;
  601. }
  602. return true;
  603. }
  604. }
  605. }
  606. /**
  607. * 在线支付日志
  608. */
  609. function filePut($info,$text='notify.txt'){
  610. if(is_array($info)) {
  611. $info = json_encode($info, JSON_UNESCAPED_UNICODE);
  612. }
  613. if(!file_exist(RUNTIME_PATH.'paylog/')) {
  614. mk_dir(RUNTIME_PATH.'paylog/');
  615. }
  616. $file = RUNTIME_PATH.'paylog/'.$text;
  617. touch_file($file);
  618. file_put_contents($file, "\r\n".date('Y-m-d H:i:s').' '.$info, FILE_APPEND);
  619. }
  620. if(!function_exists('touch_file')) {
  621. /**
  622. * 新建文件
  623. */
  624. function touch_file($file = '')
  625. {
  626. if($file) {
  627. if(!file_exists($file)) {
  628. @touch($file);
  629. @chmod($file, 0770);
  630. }
  631. }
  632. }
  633. }
  634. if(!function_exists('file_exist')) {
  635. /**
  636. * 检测文件是否存在
  637. * @param $file
  638. * @return string
  639. */
  640. function file_exist($file)
  641. {
  642. if(false === strpos($file, 'http')) { //本地文件
  643. if(0 === strpos($file, '/upload')) {
  644. $file = '.'.$file;
  645. }
  646. return file_exists($file);
  647. } else { //网络文件
  648. $ch = curl_init();
  649. curl_setopt($ch, CURLOPT_URL, $file);
  650. curl_setopt($ch, CURLOPT_TIMEOUT, 2);
  651. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  652. curl_exec($ch);
  653. $status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
  654. curl_close($ch);
  655. if(in_array(substr($status, 0, 1), [2, 3])) {
  656. return true;
  657. } else {
  658. return false;
  659. }
  660. }
  661. }
  662. }
  663. /**
  664. * 发起HTTPS请求
  665. */
  666. function curl_post($url, $data, $header = '', $timeOut = 0)
  667. {
  668. //初始化curl
  669. $ch = curl_init();
  670. //参数设置
  671. curl_setopt($ch, CURLOPT_URL, $url);
  672. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  673. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  674. curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
  675. curl_setopt($ch, CURLOPT_HEADER, 0);
  676. curl_setopt($ch, CURLOPT_POST, 1);
  677. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  678. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  679. if($header != '') {
  680. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  681. }
  682. $result = curl_exec($ch);
  683. //连接失败
  684. if($result == FALSE) {
  685. //\think\Log::record('[ CURL ] ERROR ' . curl_error($ch)."\n".var_export(debug_backtrace(), true)."\n", 'error');
  686. }
  687. curl_close($ch);
  688. return $result;
  689. }
  690. /**
  691. * 发起HTTP GET请求
  692. */
  693. function curl_get($url)
  694. {
  695. $oCurl = curl_init();
  696. if(stripos($url, "https://") !== FALSE) {
  697. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  698. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  699. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  700. }
  701. curl_setopt($oCurl, CURLOPT_TIMEOUT, 3);
  702. curl_setopt($oCurl, CURLOPT_URL, $url);
  703. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
  704. $sContent = curl_exec($oCurl);
  705. $aStatus = curl_getinfo($oCurl);
  706. $error = curl_error($oCurl);
  707. curl_close($oCurl);
  708. if($error) {
  709. $sContent = file_get_contents($url);
  710. return $sContent;
  711. }
  712. if(intval($aStatus["http_code"]) == 200) {
  713. return $sContent;
  714. } else {
  715. return false;
  716. }
  717. }
  718. //创建订单号
  719. function createUniqueNo($prifix = 'P',$id = 0)
  720. {
  721. $s = 0;
  722. $ms = 0;
  723. list($ms, $s) = explode(' ', microtime());
  724. $ms = substr($ms, 2, 6); //获取微妙
  725. $rt = $prifix.date('ymdHis', $s).$ms.rand(10, 99).$id; //年月日时分秒.用户id对10取余.微秒
  726. return $rt;
  727. }
  728. //下载远程图片 到指定目录
  729. function downloadfile($file_url, $path = '', $save_file_name = '')
  730. {
  731. $basepath = '/uploaded/';
  732. if ($path) {
  733. $basepath = $basepath . $path . '/';
  734. }
  735. $basepath = $basepath . date('Ymd');
  736. $dir_path = ROOT_PATH . '/public' . $basepath;
  737. if (!is_dir($dir_path)) {
  738. mkdir($dir_path, 0777, true);
  739. }
  740. $ch = curl_init();
  741. curl_setopt($ch, CURLOPT_URL, $file_url);
  742. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  743. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  744. $file = curl_exec($ch);
  745. curl_close($ch);
  746. //传入保存文件的名称
  747. $filename = $save_file_name ?: pathinfo($file_url, PATHINFO_BASENAME);
  748. $resource = fopen($dir_path. '/'. $filename, 'a');
  749. fwrite($resource, $file);
  750. fclose($resource);
  751. return $dir_path . '/' . $filename;
  752. }
  753. //获取视频时长
  754. function get_video_seconds($netpath = ''){
  755. $local_url = downloadfile($netpath,'video','');
  756. $playtime = 0;
  757. Vendor('getid3.getid3.getid3');
  758. $getID3 = new \getID3();
  759. $fileinfo = $getID3->analyze($local_url);
  760. if(isset($fileinfo['playtime_seconds'])){
  761. $playtime = (int)$fileinfo['playtime_seconds'];
  762. }
  763. return $playtime;
  764. }
  765. //post接收参数中心,只接非必须
  766. function request_post_hub($field_array = [],$required = [],$noempty = []){
  767. if(empty($field_array)){
  768. return [];
  769. }
  770. $data = [];
  771. foreach($field_array as $key => $field){
  772. //接收
  773. if(!request()->has($field,'post')){
  774. continue;
  775. }
  776. $newone = request()->post($field);
  777. //追加
  778. $data[$field] = $newone;
  779. }
  780. //必传
  781. if(!empty($required)){
  782. foreach($required as $k => $mustone){
  783. if(!isset($data[$mustone])){
  784. return $mustone.' required';
  785. }
  786. }
  787. }
  788. //必传,且不能空
  789. if(!empty($noempty)){
  790. foreach($noempty as $havekey => $haveone){
  791. if(!isset($data[$havekey]) || empty($data[$havekey])){
  792. return $haveone.' 必填';
  793. }
  794. }
  795. }
  796. return $data;
  797. }
  798. if(!function_exists('getAccessToken')) {
  799. /**
  800. * 获取access_token
  801. * @return string
  802. */
  803. function getAccessToken()
  804. {
  805. $accessToken = cache('access_token');
  806. if (!$accessToken) {
  807. $config = \think\Config::get('user_wxMiniProgram');
  808. $appId = isset($config['appid']) ? $config['appid'] : '';
  809. $appSecret = isset($config['secret']) ? $config['secret'] : '';
  810. $getAccountTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
  811. $accessTokenRes = httpRequest($getAccountTokenUrl, 'GET');
  812. $accessTokenData = json_decode($accessTokenRes,true);
  813. $accessToken = isset($accessTokenData['access_token']) ? $accessTokenData['access_token'] : '';
  814. if (!empty($accessToken)) {
  815. cache('access_token',$accessToken,['expire'=>7100]);
  816. }
  817. }
  818. return $accessToken;
  819. }
  820. }
  821. if (!function_exists('getDistance')) {
  822. /**
  823. * 根据坐标计算距离
  824. */
  825. function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=false, $decimal=0,$hasUnit=false){
  826. $EARTH_RADIUS = 6370.996; // 地球半径系数
  827. $PI = 3.1415926;
  828. $FLAT = 180.0;
  829. $radLat1 = $latitude1 * $PI / $FLAT;
  830. $radLat2 = $latitude2 * $PI / $FLAT;
  831. $radLng1 = $longitude1 * $PI / $FLAT;
  832. $radLng2 = $longitude2 * $PI / $FLAT;
  833. $a = $radLat1 - $radLat2;
  834. $b = $radLng1 - $radLng2;
  835. $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
  836. $distance = $distance * $EARTH_RADIUS * 1000;
  837. if($unit){//转换成km
  838. $distance = $distance / 1000;
  839. }
  840. if ($hasUnit) {//是否需要待单位
  841. $unitStr = 'm';
  842. if ($distance/1000 >= 1) {
  843. $distance = $distance/1000;
  844. $unitStr = 'km';
  845. }
  846. return round($distance, $decimal).$unitStr;
  847. }
  848. return round($distance, $decimal);
  849. }
  850. }
  851. /**
  852. * 文章时间友好化
  853. * @param null $time 添加时间,时间戳
  854. * @return string
  855. */
  856. if (!function_exists('weixinDate')) {
  857. function weixinDate($time = null)
  858. {
  859. if (!$time) {
  860. return '';
  861. }
  862. // 获取当前时间戳
  863. $cTime = time();
  864. $date = date('Y.m.d', $time);
  865. $xyh = intval(($cTime - $time) / 24 / 3600);
  866. // 获取当前时间戳与$time的差
  867. $dTime = $cTime - $time;
  868. if ($dTime < 1) {
  869. return '刚刚';
  870. } elseif ($dTime < 60) {
  871. return intval($dTime) . "秒前";
  872. } elseif ($dTime < 3600) {
  873. return intval($dTime / 60) . "分钟前";
  874. } elseif ($dTime >= 3600 && $xyh < 1) {
  875. return intval($dTime / 3600) . "小时前";
  876. } elseif ($xyh > 365) {
  877. // 如果时间大于1年,返回具体日期
  878. return $date;
  879. } elseif ($xyh == 1) {
  880. return "昨天";
  881. } elseif ($xyh >= 2 && $xyh <= 13) {
  882. return intval($xyh) . "天前";
  883. } elseif ($xyh > 13 && $xyh <= 60) {
  884. return intval($xyh / 7) . "周前";
  885. } elseif ($xyh > 60) {
  886. return intval($xyh / 30) . "月前";
  887. }
  888. }
  889. }
  890. if(!function_exists('build_qrcode')) {
  891. /**
  892. * 生成二维码
  893. * @param string $url 二维码的内容
  894. * @param string $logo 二维码中间的LOGO
  895. * @param string $save_dir 保存路径
  896. * @return bool|string
  897. */
  898. function build_qrcode($url, $logo, $save_dir,$fileName='') {
  899. require_once("../vendor/phpqrcode/phpqrcode.php");
  900. $QRcode = new \QRcode();
  901. $value = $url; //二维码内容
  902. $errorCorrectionLevel = 'H'; //容错级别
  903. $matrixPointSize = 7; //生成图片大小
  904. //生成二维码图片
  905. if(!is_dir($save_dir)) {
  906. mkdir($save_dir,0766,true);
  907. }
  908. $filename = $save_dir.time().rand(10000,99999).'.png';
  909. if (!empty($fileName)) {
  910. $filename = $fileName.'png';
  911. }
  912. $QRcode::png($value,$filename, $errorCorrectionLevel, $matrixPointSize, 2);
  913. $QR = $filename; //已经生成的原始二维码图片文件
  914. $QR = imagecreatefromstring(file_get_contents($QR)); //目标图象连接资源。
  915. if ($logo) { //LOGO是否存在
  916. $logo = imagecreatefromstring(file_get_contents($logo)); //源图象连接资源。
  917. //将真彩色图像logo变成调色板图像
  918. if (imageistruecolor($logo)) imagetruecolortopalette($logo, false, 65535);
  919. $QR_width = imagesx($QR); //二维码图片宽度
  920. //$QR_height = imagesy($QR); //二维码图片高度
  921. $logo_width = imagesx($logo); //logo图片宽度
  922. $logo_height = imagesy($logo); //logo图片高度
  923. $logo_qr_width = $QR_width / 4; //组合之后logo的宽度(占二维码的1/4)
  924. $scale = $logo_width/$logo_qr_width; //logo的宽度缩放比(本身宽度/组合后的宽度)
  925. $logo_qr_height = $logo_height/$scale; //组合之后logo的高度
  926. $from_width = ($QR_width - $logo_qr_width) / 2; //组合之后logo左上角所在坐标点
  927. //重新组合图片并调整大小
  928. imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);
  929. imagedestroy($logo);
  930. }
  931. //输出图片
  932. $res = imagepng($QR, $filename);
  933. imagedestroy($QR);
  934. if($res === false) {
  935. return $res;
  936. }
  937. return $filename;
  938. }
  939. }
  940. if(!function_exists('getProvince')) {
  941. /**
  942. * 获取省市区名称
  943. * @return bool|string
  944. */
  945. function getProvince($params=[]) {
  946. $provinceId = isset($params['province_id']) ? $params['province_id'] : 0;
  947. $cityId = isset($params['city_id']) ? $params['city_id'] : 0;
  948. $areaId = isset($params['area_id']) ? $params['area_id'] : 0;
  949. $address = isset($params['address']) ? $params['address'] : '';
  950. $areaWhere['id'] = ['in',[$provinceId,$cityId,$areaId]];
  951. $areaData = Db::name('shopro_area')->where($areaWhere)->column('id,name');
  952. $params['province_name'] = isset($areaData[$provinceId]) ? $areaData[$provinceId] : '';
  953. $params['city_name'] = isset($areaData[$cityId]) ? $areaData[$cityId] : '';
  954. $params['area_name'] = isset($areaData[$areaId]) ? $areaData[$areaId] : '';
  955. $params['full_address'] = $params['province_name'].$params['city_name'].$params['area_name'].$address;
  956. return $params;
  957. }
  958. }