common.php 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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. $more = strpos($key,'images');
  498. $data[$key] = one_domain_image($val,$more);
  499. }
  500. }
  501. return $data;
  502. }
  503. //支持单个字段,需要增加domain_cdnurl
  504. //支持image,images
  505. function one_domain_image($one,$more = false){
  506. if(!$one){
  507. return $one;
  508. }
  509. if(strpos($one,',') || $more !== false){
  510. //逗号隔开的多个图片
  511. $one = explode(',',$one);
  512. foreach($one as $k => $v){
  513. $one[$k] = localpath_to_netpath($v);
  514. }
  515. //$one = implode(',',$one);
  516. }else{
  517. $one = localpath_to_netpath($one);
  518. }
  519. return $one;
  520. }
  521. //本地地址转换为网络地址
  522. function localpath_to_netpath($path)
  523. {
  524. if (empty($path)) {
  525. return '';
  526. } elseif (strrpos($path, 'http') !== false) {
  527. return $path;
  528. } else {
  529. return config('upload.cdnurl') . str_replace("\\", "/", $path);
  530. }
  531. }
  532. //秒 转换 日月分
  533. function Sec2Time($time){
  534. if(is_numeric($time)){
  535. $value = array(
  536. 'years' => 0, 'days' => 0, 'hours' => 0,
  537. 'minutes' => 0, 'seconds' => 0,
  538. );
  539. /*if($time >= 31556926){
  540. $value['years'] = floor($time/31556926);
  541. $time = ($time%31556926);
  542. }*/
  543. if($time >= 86400){
  544. $value['days'] = floor($time/86400);
  545. $time = ($time%86400);
  546. }
  547. if($time >= 3600){
  548. $value['hours'] = floor($time/3600);
  549. $time = ($time%3600);
  550. }
  551. if($time >= 60){
  552. $value['minutes'] = floor($time/60);
  553. $time = ($time%60);
  554. }
  555. $value['seconds'] = floor($time);
  556. //return (array) $value;
  557. //$t=$value['years'] .'年'. $value['days'] .'天'.' '. $value['hours'] .'小时'. $value['minutes'] .'分'.$value['seconds'].'秒';
  558. $t = $value['days'] .'天' . $value['hours'] .'小时'. $value['minutes'] .'分';
  559. return $t;
  560. }else{
  561. return '0天';
  562. }
  563. }
  564. //生日转年龄
  565. function birthtime_to_age($birthtime){
  566. // $birthtime = strtotime('1990-11-06');
  567. if(!$birthtime){
  568. return 0;
  569. }
  570. list($y1,$m1,$d1) = explode("-",date("Y-m-d",$birthtime));
  571. list($y2,$m2,$d2) = explode("-",date("Y-m-d",time()));
  572. $age = $y2 - $y1;
  573. if((int)($m2.$d2) < (int)($m1.$d1))
  574. {$age -= 1;}
  575. if($age < 0){
  576. $age = 0;
  577. }
  578. return $age;
  579. }
  580. if(!function_exists('mk_dir')) {
  581. /**
  582. * 新建目录
  583. */
  584. function mk_dir($dir, $mode = 0770, $tmp = true)
  585. {
  586. $mode = 0770;
  587. if(is_file($dir)) {
  588. //有同名文件
  589. return false;
  590. } else {
  591. if(!is_dir($dir)) { //目录不存在
  592. $dir_up = dirname($dir); //上级目录
  593. if(!is_dir($dir_up)) {
  594. //上级不存在
  595. $rs = @mk_dir($dir_up);
  596. if(!$rs) return false;
  597. }
  598. $rs = @mkdir($dir, $mode); //新建
  599. if(!$rs) return false;
  600. $rs = @chmod($dir, $mode); //改权限
  601. if(!$rs) return false;
  602. }
  603. return true;
  604. }
  605. }
  606. }
  607. /**
  608. * 在线支付日志
  609. */
  610. function filePut($info,$text='notify.txt'){
  611. if(is_array($info)) {
  612. $info = json_encode($info, JSON_UNESCAPED_UNICODE);
  613. }
  614. if(!file_exist(RUNTIME_PATH.'paylog/')) {
  615. mk_dir(RUNTIME_PATH.'paylog/');
  616. }
  617. $file = RUNTIME_PATH.'paylog/'.$text;
  618. touch_file($file);
  619. file_put_contents($file, "\r\n".date('Y-m-d H:i:s').' '.$info, FILE_APPEND);
  620. }
  621. if(!function_exists('touch_file')) {
  622. /**
  623. * 新建文件
  624. */
  625. function touch_file($file = '')
  626. {
  627. if($file) {
  628. if(!file_exists($file)) {
  629. @touch($file);
  630. @chmod($file, 0770);
  631. }
  632. }
  633. }
  634. }
  635. if(!function_exists('file_exist')) {
  636. /**
  637. * 检测文件是否存在
  638. * @param $file
  639. * @return string
  640. */
  641. function file_exist($file)
  642. {
  643. if(false === strpos($file, 'http')) { //本地文件
  644. if(0 === strpos($file, '/upload')) {
  645. $file = '.'.$file;
  646. }
  647. return file_exists($file);
  648. } else { //网络文件
  649. $ch = curl_init();
  650. curl_setopt($ch, CURLOPT_URL, $file);
  651. curl_setopt($ch, CURLOPT_TIMEOUT, 2);
  652. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  653. curl_exec($ch);
  654. $status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
  655. curl_close($ch);
  656. if(in_array(substr($status, 0, 1), [2, 3])) {
  657. return true;
  658. } else {
  659. return false;
  660. }
  661. }
  662. }
  663. }
  664. /**
  665. * 发起HTTPS请求
  666. */
  667. function curl_post($url, $data, $header = '', $timeOut = 0)
  668. {
  669. //初始化curl
  670. $ch = curl_init();
  671. //参数设置
  672. curl_setopt($ch, CURLOPT_URL, $url);
  673. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  674. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  675. curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
  676. curl_setopt($ch, CURLOPT_HEADER, 0);
  677. curl_setopt($ch, CURLOPT_POST, 1);
  678. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  679. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  680. if($header != '') {
  681. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  682. }
  683. $result = curl_exec($ch);
  684. //连接失败
  685. if($result == FALSE) {
  686. //\think\Log::record('[ CURL ] ERROR ' . curl_error($ch)."\n".var_export(debug_backtrace(), true)."\n", 'error');
  687. }
  688. curl_close($ch);
  689. return $result;
  690. }
  691. /**
  692. * 发起HTTP GET请求
  693. */
  694. function curl_get($url)
  695. {
  696. $oCurl = curl_init();
  697. if(stripos($url, "https://") !== FALSE) {
  698. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  699. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  700. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  701. }
  702. curl_setopt($oCurl, CURLOPT_TIMEOUT, 3);
  703. curl_setopt($oCurl, CURLOPT_URL, $url);
  704. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
  705. $sContent = curl_exec($oCurl);
  706. $aStatus = curl_getinfo($oCurl);
  707. $error = curl_error($oCurl);
  708. curl_close($oCurl);
  709. if($error) {
  710. $sContent = file_get_contents($url);
  711. return $sContent;
  712. }
  713. if(intval($aStatus["http_code"]) == 200) {
  714. return $sContent;
  715. } else {
  716. return false;
  717. }
  718. }
  719. //创建订单号
  720. function createUniqueNo($prifix = 'P',$id = 0)
  721. {
  722. $s = 0;
  723. $ms = 0;
  724. list($ms, $s) = explode(' ', microtime());
  725. $ms = substr($ms, 2, 6); //获取微妙
  726. $rt = $prifix.date('ymdHis', $s).$ms.rand(10, 99).$id; //年月日时分秒.用户id对10取余.微秒
  727. return $rt;
  728. }
  729. //下载远程图片 到指定目录
  730. function downloadfile($file_url, $path = '', $save_file_name = '')
  731. {
  732. $basepath = '/uploaded/';
  733. if ($path) {
  734. $basepath = $basepath . $path . '/';
  735. }
  736. $basepath = $basepath . date('Ymd');
  737. $dir_path = ROOT_PATH . '/public' . $basepath;
  738. if (!is_dir($dir_path)) {
  739. mkdir($dir_path, 0777, true);
  740. }
  741. $ch = curl_init();
  742. curl_setopt($ch, CURLOPT_URL, $file_url);
  743. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  744. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  745. $file = curl_exec($ch);
  746. curl_close($ch);
  747. //传入保存文件的名称
  748. $filename = $save_file_name ?: pathinfo($file_url, PATHINFO_BASENAME);
  749. $resource = fopen($dir_path. '/'. $filename, 'a');
  750. fwrite($resource, $file);
  751. fclose($resource);
  752. return $dir_path . '/' . $filename;
  753. }
  754. //获取视频时长
  755. function get_video_seconds($netpath = ''){
  756. $local_url = downloadfile($netpath,'video','');
  757. $playtime = 0;
  758. Vendor('getid3.getid3.getid3');
  759. $getID3 = new \getID3();
  760. $fileinfo = $getID3->analyze($local_url);
  761. if(isset($fileinfo['playtime_seconds'])){
  762. $playtime = (int)$fileinfo['playtime_seconds'];
  763. }
  764. return $playtime;
  765. }
  766. //post接收参数中心,只接非必须
  767. function request_post_hub($field_array = [],$required = [],$noempty = []){
  768. if(empty($field_array)){
  769. return [];
  770. }
  771. $data = [];
  772. foreach($field_array as $key => $field){
  773. //接收
  774. if(!request()->has($field,'post')){
  775. continue;
  776. }
  777. $newone = request()->post($field);
  778. //追加
  779. $data[$field] = $newone;
  780. }
  781. //必传
  782. if(!empty($required)){
  783. foreach($required as $k => $mustone){
  784. if(!isset($data[$mustone])){
  785. return $mustone.' required';
  786. }
  787. }
  788. }
  789. //必传,且不能空
  790. if(!empty($noempty)){
  791. foreach($noempty as $havekey => $haveone){
  792. if(!isset($data[$havekey]) || empty($data[$havekey])){
  793. return $haveone.' 必填';
  794. }
  795. }
  796. }
  797. return $data;
  798. }
  799. if(!function_exists('getAccessToken')) {
  800. /**
  801. * 获取access_token
  802. * @return string
  803. */
  804. function getAccessToken()
  805. {
  806. $accessToken = cache('access_token');
  807. if (!$accessToken) {
  808. $config = \think\Config::get('user_wxMiniProgram');
  809. $appId = isset($config['appid']) ? $config['appid'] : '';
  810. $appSecret = isset($config['secret']) ? $config['secret'] : '';
  811. $getAccountTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
  812. $accessTokenRes = httpRequest($getAccountTokenUrl, 'GET');
  813. $accessTokenData = json_decode($accessTokenRes,true);
  814. $accessToken = isset($accessTokenData['access_token']) ? $accessTokenData['access_token'] : '';
  815. if (!empty($accessToken)) {
  816. cache('access_token',$accessToken,['expire'=>7100]);
  817. }
  818. }
  819. return $accessToken;
  820. }
  821. }
  822. if (!function_exists('getDistance')) {
  823. /**
  824. * 根据坐标计算距离
  825. */
  826. function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=false, $decimal=0,$hasUnit=false){
  827. $EARTH_RADIUS = 6370.996; // 地球半径系数
  828. $PI = 3.1415926;
  829. $FLAT = 180.0;
  830. $radLat1 = $latitude1 * $PI / $FLAT;
  831. $radLat2 = $latitude2 * $PI / $FLAT;
  832. $radLng1 = $longitude1 * $PI / $FLAT;
  833. $radLng2 = $longitude2 * $PI / $FLAT;
  834. $a = $radLat1 - $radLat2;
  835. $b = $radLng1 - $radLng2;
  836. $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
  837. $distance = $distance * $EARTH_RADIUS * 1000;
  838. if($unit){//转换成km
  839. $distance = $distance / 1000;
  840. }
  841. if ($hasUnit) {//是否需要待单位
  842. $unitStr = 'm';
  843. if ($distance/1000 >= 1) {
  844. $distance = $distance/1000;
  845. $unitStr = 'km';
  846. }
  847. return round($distance, $decimal).$unitStr;
  848. }
  849. return round($distance, $decimal);
  850. }
  851. }
  852. /**
  853. * 文章时间友好化
  854. * @param null $time 添加时间,时间戳
  855. * @return string
  856. */
  857. if (!function_exists('weixinDate')) {
  858. function weixinDate($time = null)
  859. {
  860. if (!$time) {
  861. return '';
  862. }
  863. // 获取当前时间戳
  864. $cTime = time();
  865. $date = date('Y.m.d', $time);
  866. $xyh = intval(($cTime - $time) / 24 / 3600);
  867. // 获取当前时间戳与$time的差
  868. $dTime = $cTime - $time;
  869. if ($dTime < 1) {
  870. return '刚刚';
  871. } elseif ($dTime < 60) {
  872. return intval($dTime) . "秒前";
  873. } elseif ($dTime < 3600) {
  874. return intval($dTime / 60) . "分钟前";
  875. } elseif ($dTime >= 3600 && $xyh < 1) {
  876. return intval($dTime / 3600) . "小时前";
  877. } elseif ($xyh > 365) {
  878. // 如果时间大于1年,返回具体日期
  879. return $date;
  880. } elseif ($xyh == 1) {
  881. return "昨天";
  882. } elseif ($xyh >= 2 && $xyh <= 13) {
  883. return intval($xyh) . "天前";
  884. } elseif ($xyh > 13 && $xyh <= 60) {
  885. return intval($xyh / 7) . "周前";
  886. } elseif ($xyh > 60) {
  887. return intval($xyh / 30) . "月前";
  888. }
  889. }
  890. }
  891. if(!function_exists('build_qrcode')) {
  892. /**
  893. * 生成二维码
  894. * @param string $url 二维码的内容
  895. * @param string $logo 二维码中间的LOGO
  896. * @param string $save_dir 保存路径
  897. * @return bool|string
  898. */
  899. function build_qrcode($url, $logo, $save_dir,$fileName='') {
  900. require_once("../vendor/phpqrcode/phpqrcode.php");
  901. $QRcode = new \QRcode();
  902. $value = $url; //二维码内容
  903. $errorCorrectionLevel = 'H'; //容错级别
  904. $matrixPointSize = 7; //生成图片大小
  905. //生成二维码图片
  906. if(!is_dir($save_dir)) {
  907. mkdir($save_dir,0766,true);
  908. }
  909. $filename = $save_dir.time().rand(10000,99999).'.png';
  910. if (!empty($fileName)) {
  911. $filename = $save_dir.$fileName.'.png';
  912. }
  913. $QRcode::png($value,$filename, $errorCorrectionLevel, $matrixPointSize, 2);
  914. $QR = $filename; //已经生成的原始二维码图片文件
  915. $QR = imagecreatefromstring(file_get_contents($QR)); //目标图象连接资源。
  916. if ($logo) { //LOGO是否存在
  917. $logo = imagecreatefromstring(file_get_contents($logo)); //源图象连接资源。
  918. //将真彩色图像logo变成调色板图像
  919. if (imageistruecolor($logo)) imagetruecolortopalette($logo, false, 65535);
  920. $QR_width = imagesx($QR); //二维码图片宽度
  921. //$QR_height = imagesy($QR); //二维码图片高度
  922. $logo_width = imagesx($logo); //logo图片宽度
  923. $logo_height = imagesy($logo); //logo图片高度
  924. $logo_qr_width = $QR_width / 4; //组合之后logo的宽度(占二维码的1/4)
  925. $scale = $logo_width/$logo_qr_width; //logo的宽度缩放比(本身宽度/组合后的宽度)
  926. $logo_qr_height = $logo_height/$scale; //组合之后logo的高度
  927. $from_width = ($QR_width - $logo_qr_width) / 2; //组合之后logo左上角所在坐标点
  928. //重新组合图片并调整大小
  929. imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);
  930. imagedestroy($logo);
  931. }
  932. //输出图片
  933. $res = imagepng($QR, $filename);
  934. imagedestroy($QR);
  935. if($res === false) {
  936. return $res;
  937. }
  938. return $filename;
  939. }
  940. }
  941. if(!function_exists('getProvince')) {
  942. /**
  943. * 获取省市区名称
  944. * @return bool|string
  945. */
  946. function getProvince($params=[]) {
  947. $provinceId = isset($params['province_id']) ? $params['province_id'] : 0;
  948. $cityId = isset($params['city_id']) ? $params['city_id'] : 0;
  949. $areaId = isset($params['area_id']) ? $params['area_id'] : 0;
  950. $address = isset($params['address']) ? $params['address'] : '';
  951. $areaWhere['id'] = ['in',[$provinceId,$cityId,$areaId]];
  952. $areaData = Db::name('shopro_area')->where($areaWhere)->column('id,name');
  953. $params['province_name'] = isset($areaData[$provinceId]) ? $areaData[$provinceId] : '';
  954. $params['city_name'] = isset($areaData[$cityId]) ? $areaData[$cityId] : '';
  955. $params['area_name'] = isset($areaData[$areaId]) ? $areaData[$areaId] : '';
  956. $params['full_address'] = $params['province_name'].$params['city_name'].$params['area_name'].$address;
  957. return $params;
  958. }
  959. }
  960. if(!function_exists('httpRequest')) {
  961. /**
  962. * CURL请求
  963. * @param $url 请求url地址
  964. * @param $method 请求方法 get post
  965. * @param null $postfields post数据数组
  966. * @param array $headers 请求header信息
  967. * @param bool|false $debug 调试开启 默认false
  968. * @return mixed
  969. */
  970. function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false)
  971. {
  972. $method = strtoupper($method);
  973. $ci = curl_init();
  974. /* Curl settings */
  975. curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  976. curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
  977. curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
  978. curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
  979. curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
  980. switch ($method) {
  981. case "POST":
  982. curl_setopt($ci, CURLOPT_POST, true);
  983. if (!empty($postfields)) {
  984. $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
  985. curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
  986. }
  987. break;
  988. default:
  989. curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
  990. break;
  991. }
  992. $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
  993. curl_setopt($ci, CURLOPT_URL, $url);
  994. if ($ssl) {
  995. curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
  996. curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
  997. }
  998. //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
  999. //curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
  1000. curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
  1001. curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
  1002. curl_setopt($ci, CURLINFO_HEADER_OUT, true);
  1003. /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
  1004. $response = curl_exec($ci);
  1005. $requestinfo = curl_getinfo($ci);
  1006. $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
  1007. if ($debug) {
  1008. echo "=====post data======\r\n";
  1009. var_dump($postfields);
  1010. echo "=====info===== \r\n";
  1011. print_r($requestinfo);
  1012. echo "=====response=====\r\n";
  1013. print_r($response);
  1014. }
  1015. curl_close($ci);
  1016. return $response;
  1017. //return array($http_code, $response,$requestinfo);
  1018. }
  1019. }
  1020. if(!function_exists('is_mobile')) {
  1021. /**
  1022. * 手机格式验证
  1023. * @param string $mobile 验证的手机号码
  1024. * @return boolean
  1025. */
  1026. function is_mobile($mobile)
  1027. {
  1028. if (!empty($mobile)) {
  1029. return preg_match('/^1[3|4|5|6|7|8|9][0-9]\d{8}$/', $mobile);
  1030. }
  1031. return false;
  1032. }
  1033. }
  1034. if (!function_exists('httpurllocal')) {
  1035. /**
  1036. * 判断当前url是否为全路径,并返回全路径
  1037. */
  1038. function httpurllocal($path) {
  1039. if(!$path) return $path;
  1040. $host = $_SERVER["REQUEST_SCHEME"]."://".$_SERVER["HTTP_HOST"];
  1041. // 获取当前域名
  1042. if(strpos($path,'http://') === false && strpos($path,'https://') === false) {
  1043. $url = $host.$path;
  1044. } else {
  1045. $url = $path;
  1046. }
  1047. return $url;
  1048. }
  1049. }