common.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. <?php
  2. // 公共助手函数
  3. use think\exception\HttpResponseException;
  4. use think\Response;
  5. use think\Session;
  6. if (!function_exists('__')) {
  7. /**
  8. * 获取语言变量值
  9. * @param string $name 语言变量名
  10. * @param array $vars 动态变量值
  11. * @param string $lang 语言
  12. * @return mixed
  13. */
  14. function __($name, $vars = [], $lang = '')
  15. {
  16. if (is_numeric($name) || !$name) {
  17. return $name;
  18. }
  19. if (!is_array($vars)) {
  20. $vars = func_get_args();
  21. array_shift($vars);
  22. $lang = '';
  23. }
  24. return \think\Lang::get($name, $vars, $lang);
  25. }
  26. }
  27. if (!function_exists('mask_email')) {
  28. /**
  29. * 邮箱脱敏:保留本地部分前三位,其余用 * 代替,域名完整保留
  30. * 例:14906570@qq.com → 149***@qq.com
  31. */
  32. function mask_email($email)
  33. {
  34. $email = trim((string)$email);
  35. if ($email === '') {
  36. return '';
  37. }
  38. $at = strpos($email, '@');
  39. if ($at === false) {
  40. if (mb_strlen($email, 'UTF-8') <= 3) {
  41. return $email;
  42. }
  43. return mb_substr($email, 0, 3, 'UTF-8') . '***';
  44. }
  45. $local = mb_substr($email, 0, $at, 'UTF-8');
  46. $domain = mb_substr($email, $at + 1, null, 'UTF-8');
  47. if (mb_strlen($local, 'UTF-8') <= 3) {
  48. return $local . '@' . $domain;
  49. }
  50. return mb_substr($local, 0, 3, 'UTF-8') . '***@' . $domain;
  51. }
  52. }
  53. if (!function_exists('mask_phone')) {
  54. /**
  55. * 手机号脱敏:前三位 + 星号 + 后四位
  56. * 例:18981046362 → 189****6362
  57. */
  58. function mask_phone($phone)
  59. {
  60. $phone = preg_replace('/\s+/', '', trim((string)$phone));
  61. if ($phone === '') {
  62. return '';
  63. }
  64. $len = strlen($phone);
  65. if ($len <= 7) {
  66. if ($len <= 3) {
  67. return $phone;
  68. }
  69. return substr($phone, 0, 3) . str_repeat('*', $len - 3);
  70. }
  71. return substr($phone, 0, 3) . str_repeat('*', $len - 7) . substr($phone, -4);
  72. }
  73. }
  74. if (!function_exists('format_bytes')) {
  75. /**
  76. * 将字节转换为可读文本
  77. * @param int $size 大小
  78. * @param string $delimiter 分隔符
  79. * @param int $precision 小数位数
  80. * @return string
  81. */
  82. function format_bytes($size, $delimiter = '', $precision = 2)
  83. {
  84. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  85. for ($i = 0; $size >= 1024 && $i < 6; $i++) {
  86. $size /= 1024;
  87. }
  88. return round($size, $precision) . $delimiter . $units[$i];
  89. }
  90. }
  91. if (!function_exists('datetime')) {
  92. /**
  93. * 将时间戳转换为日期时间
  94. * @param int $time 时间戳
  95. * @param string $format 日期时间格式
  96. * @return string
  97. */
  98. function datetime($time, $format = 'Y-m-d H:i:s')
  99. {
  100. $time = is_numeric($time) ? $time : strtotime($time);
  101. return date($format, $time);
  102. }
  103. }
  104. if (!function_exists('human_date')) {
  105. /**
  106. * 获取语义化时间
  107. * @param int $time 时间
  108. * @param int $local 本地时间
  109. * @return string
  110. */
  111. function human_date($time, $local = null)
  112. {
  113. return \fast\Date::human($time, $local);
  114. }
  115. }
  116. if (!function_exists('cdnurl')) {
  117. /**
  118. * 获取上传资源的CDN的地址
  119. * @param string $url 资源相对地址
  120. * @param boolean $domain 是否显示域名 或者直接传入域名
  121. * @return string
  122. */
  123. function cdnurl($url, $domain = false)
  124. {
  125. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  126. $cdnurl = \think\Config::get('upload.cdnurl');
  127. if (is_bool($domain) || stripos($cdnurl, '/') === 0) {
  128. $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
  129. }
  130. if ($domain && !preg_match($regex, $url)) {
  131. $domain = is_bool($domain) ? request()->domain() : $domain;
  132. $url = $domain . $url;
  133. }
  134. return $url;
  135. }
  136. }
  137. if (!function_exists('is_really_writable')) {
  138. /**
  139. * 判断文件或文件夹是否可写
  140. * @param string $file 文件或目录
  141. * @return bool
  142. */
  143. function is_really_writable($file)
  144. {
  145. if (DIRECTORY_SEPARATOR === '/') {
  146. return is_writable($file);
  147. }
  148. if (is_dir($file)) {
  149. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  150. if (($fp = @fopen($file, 'ab')) === false) {
  151. return false;
  152. }
  153. fclose($fp);
  154. @chmod($file, 0777);
  155. @unlink($file);
  156. return true;
  157. } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
  158. return false;
  159. }
  160. fclose($fp);
  161. return true;
  162. }
  163. }
  164. if (!function_exists('rmdirs')) {
  165. /**
  166. * 删除文件夹
  167. * @param string $dirname 目录
  168. * @param bool $withself 是否删除自身
  169. * @return boolean
  170. */
  171. function rmdirs($dirname, $withself = true)
  172. {
  173. if (!is_dir($dirname)) {
  174. return false;
  175. }
  176. $files = new RecursiveIteratorIterator(
  177. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
  178. RecursiveIteratorIterator::CHILD_FIRST
  179. );
  180. foreach ($files as $fileinfo) {
  181. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  182. $todo($fileinfo->getRealPath());
  183. }
  184. if ($withself) {
  185. @rmdir($dirname);
  186. }
  187. return true;
  188. }
  189. }
  190. if (!function_exists('copydirs')) {
  191. /**
  192. * 复制文件夹
  193. * @param string $source 源文件夹
  194. * @param string $dest 目标文件夹
  195. */
  196. function copydirs($source, $dest)
  197. {
  198. if (!is_dir($dest)) {
  199. mkdir($dest, 0755, true);
  200. }
  201. foreach (
  202. $iterator = new RecursiveIteratorIterator(
  203. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  204. RecursiveIteratorIterator::SELF_FIRST
  205. ) as $item
  206. ) {
  207. if ($item->isDir()) {
  208. $sontDir = $dest . DS . $iterator->getSubPathName();
  209. if (!is_dir($sontDir)) {
  210. mkdir($sontDir, 0755, true);
  211. }
  212. } else {
  213. copy($item, $dest . DS . $iterator->getSubPathName());
  214. }
  215. }
  216. }
  217. }
  218. if (!function_exists('mb_ucfirst')) {
  219. function mb_ucfirst($string)
  220. {
  221. return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
  222. }
  223. }
  224. if (!function_exists('addtion')) {
  225. /**
  226. * 附加关联字段数据
  227. * @param array $items 数据列表
  228. * @param mixed $fields 渲染的来源字段
  229. * @return array
  230. */
  231. function addtion($items, $fields)
  232. {
  233. if (!$items || !$fields) {
  234. return $items;
  235. }
  236. $fieldsArr = [];
  237. if (!is_array($fields)) {
  238. $arr = explode(',', $fields);
  239. foreach ($arr as $k => $v) {
  240. $fieldsArr[$v] = ['field' => $v];
  241. }
  242. } else {
  243. foreach ($fields as $k => $v) {
  244. if (is_array($v)) {
  245. $v['field'] = $v['field'] ?? $k;
  246. } else {
  247. $v = ['field' => $v];
  248. }
  249. $fieldsArr[$v['field']] = $v;
  250. }
  251. }
  252. foreach ($fieldsArr as $k => &$v) {
  253. $v = is_array($v) ? $v : ['field' => $v];
  254. $v['display'] = $v['display'] ?? str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  255. $v['primary'] = $v['primary'] ?? '';
  256. $v['column'] = $v['column'] ?? 'name';
  257. $v['model'] = $v['model'] ?? '';
  258. $v['table'] = $v['table'] ?? '';
  259. $v['name'] = $v['name'] ?? str_replace(['_ids', '_id'], '', $v['field']);
  260. }
  261. unset($v);
  262. $ids = [];
  263. $fields = array_keys($fieldsArr);
  264. foreach ($items as $k => $v) {
  265. foreach ($fields as $m => $n) {
  266. if (isset($v[$n])) {
  267. $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
  268. }
  269. }
  270. }
  271. $result = [];
  272. foreach ($fieldsArr as $k => $v) {
  273. if ($v['model']) {
  274. $model = new $v['model'];
  275. } else {
  276. $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
  277. }
  278. $primary = $v['primary'] ? $v['primary'] : $model->getPk();
  279. $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
  280. }
  281. foreach ($items as $k => &$v) {
  282. foreach ($fields as $m => $n) {
  283. if (isset($v[$n])) {
  284. $curr = array_flip(explode(',', $v[$n]));
  285. $linedata = array_intersect_key($result[$n], $curr);
  286. $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
  287. }
  288. }
  289. }
  290. return $items;
  291. }
  292. }
  293. if (!function_exists('var_export_short')) {
  294. /**
  295. * 使用短标签打印或返回数组结构
  296. * @param mixed $data
  297. * @param boolean $return 是否返回数据
  298. * @return string
  299. */
  300. function var_export_short($data, $return = true)
  301. {
  302. return var_export($data, $return);
  303. $replaced = [];
  304. $count = 0;
  305. //判断是否是对象
  306. if (is_resource($data) || is_object($data)) {
  307. return var_export($data, $return);
  308. }
  309. //判断是否有特殊的键名
  310. $specialKey = false;
  311. array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
  312. if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
  313. $specialKey = true;
  314. }
  315. });
  316. if ($specialKey) {
  317. return var_export($data, $return);
  318. }
  319. array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
  320. if (is_object($value) || is_resource($value)) {
  321. $replaced[$count] = var_export($value, true);
  322. $value = "##<{$count}>##";
  323. } else {
  324. if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
  325. $index = array_search($value, $replaced);
  326. if ($index === false) {
  327. $replaced[$count] = var_export($value, true);
  328. $value = "##<{$count}>##";
  329. } else {
  330. $value = "##<{$index}>##";
  331. }
  332. }
  333. }
  334. $count++;
  335. });
  336. $dump = var_export($data, true);
  337. $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
  338. $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
  339. $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
  340. $dump = preg_replace('#\)$#', "]", $dump); //End
  341. if ($replaced) {
  342. $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
  343. return $replaced[$matches[1]] ?? "''";
  344. }, $dump);
  345. }
  346. if ($return === true) {
  347. return $dump;
  348. } else {
  349. echo $dump;
  350. }
  351. }
  352. }
  353. if (!function_exists('letter_avatar')) {
  354. /**
  355. * 首字母头像
  356. * @param $text
  357. * @return string
  358. */
  359. function letter_avatar($text)
  360. {
  361. $total = unpack('L', hash('adler32', $text, true))[1];
  362. $hue = $total % 360;
  363. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  364. $bg = "rgb({$r},{$g},{$b})";
  365. $color = "#ffffff";
  366. $first = mb_strtoupper(mb_substr($text, 0, 1));
  367. $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>');
  368. $value = 'data:image/svg+xml;base64,' . $src;
  369. return $value;
  370. }
  371. }
  372. if (!function_exists('hsv2rgb')) {
  373. function hsv2rgb($h, $s, $v)
  374. {
  375. $r = $g = $b = 0;
  376. $i = floor($h * 6);
  377. $f = $h * 6 - $i;
  378. $p = $v * (1 - $s);
  379. $q = $v * (1 - $f * $s);
  380. $t = $v * (1 - (1 - $f) * $s);
  381. switch ($i % 6) {
  382. case 0:
  383. $r = $v;
  384. $g = $t;
  385. $b = $p;
  386. break;
  387. case 1:
  388. $r = $q;
  389. $g = $v;
  390. $b = $p;
  391. break;
  392. case 2:
  393. $r = $p;
  394. $g = $v;
  395. $b = $t;
  396. break;
  397. case 3:
  398. $r = $p;
  399. $g = $q;
  400. $b = $v;
  401. break;
  402. case 4:
  403. $r = $t;
  404. $g = $p;
  405. $b = $v;
  406. break;
  407. case 5:
  408. $r = $v;
  409. $g = $p;
  410. $b = $q;
  411. break;
  412. }
  413. return [
  414. floor($r * 255),
  415. floor($g * 255),
  416. floor($b * 255)
  417. ];
  418. }
  419. }
  420. if (!function_exists('check_nav_active')) {
  421. /**
  422. * 检测会员中心导航是否高亮
  423. */
  424. function check_nav_active($url, $classname = 'active')
  425. {
  426. $auth = \app\common\library\Auth::instance();
  427. $requestUrl = $auth->getRequestUri();
  428. $url = ltrim($url, '/');
  429. return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
  430. }
  431. }
  432. if (!function_exists('check_cors_request')) {
  433. /**
  434. * 跨域检测
  435. */
  436. function check_cors_request()
  437. {
  438. if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] && config('fastadmin.cors_request_domain')) {
  439. $info = parse_url($_SERVER['HTTP_ORIGIN']);
  440. $domainArr = explode(',', config('fastadmin.cors_request_domain'));
  441. $domainArr[] = request()->host(true);
  442. if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
  443. header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
  444. } else {
  445. $response = Response::create('跨域检测无效', 'html', 403);
  446. throw new HttpResponseException($response);
  447. }
  448. header('Access-Control-Allow-Credentials: true');
  449. header('Access-Control-Max-Age: 86400');
  450. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  451. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
  452. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  453. }
  454. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  455. header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  456. }
  457. $response = Response::create('', 'html');
  458. throw new HttpResponseException($response);
  459. }
  460. }
  461. }
  462. }
  463. if (!function_exists('xss_clean')) {
  464. /**
  465. * 清理XSS
  466. */
  467. function xss_clean($content, $is_image = false)
  468. {
  469. return \app\common\library\Security::instance()->xss_clean($content, $is_image);
  470. }
  471. }
  472. if (!function_exists('url_clean')) {
  473. /**
  474. * 清理URL
  475. */
  476. function url_clean($url)
  477. {
  478. if (!check_url_allowed($url)) {
  479. return '';
  480. }
  481. return xss_clean($url);
  482. }
  483. }
  484. if (!function_exists('check_ip_allowed')) {
  485. /**
  486. * 检测IP是否允许
  487. * @param string $ip IP地址
  488. */
  489. function check_ip_allowed($ip = null)
  490. {
  491. $ip = is_null($ip) ? request()->ip() : $ip;
  492. $forbiddenipArr = config('site.forbiddenip');
  493. $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
  494. $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
  495. if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
  496. $response = Response::create('请求无权访问', 'html', 403);
  497. throw new HttpResponseException($response);
  498. }
  499. }
  500. }
  501. if (!function_exists('check_url_allowed')) {
  502. /**
  503. * 检测URL是否允许
  504. * @param string $url URL
  505. * @return bool
  506. */
  507. function check_url_allowed($url = '')
  508. {
  509. //允许的主机列表
  510. $allowedHostArr = [
  511. strtolower(request()->host())
  512. ];
  513. if (empty($url)) {
  514. return true;
  515. }
  516. //如果是站内相对链接则允许
  517. if (preg_match("/^[\/a-z][a-z0-9][a-z0-9\.\/]+((\?|#).*)?\$/i", $url) && substr($url, 0, 2) !== '//') {
  518. return true;
  519. }
  520. //如果是站外链接则需要判断HOST是否允许
  521. if (preg_match("/((http[s]?:\/\/)+(?>[a-z\-0-9]{2,}\.){1,}[a-z]{2,8})(?:\s|\/)/i", $url)) {
  522. $chkHost = parse_url(strtolower($url), PHP_URL_HOST);
  523. if ($chkHost && in_array($chkHost, $allowedHostArr)) {
  524. return true;
  525. }
  526. }
  527. return false;
  528. }
  529. }
  530. if (!function_exists('build_suffix_image')) {
  531. /**
  532. * 生成文件后缀图片
  533. * @param string $suffix 后缀
  534. * @param null $background
  535. * @return string
  536. */
  537. function build_suffix_image($suffix, $background = null)
  538. {
  539. $suffix = mb_substr(strtoupper($suffix), 0, 4);
  540. $total = unpack('L', hash('adler32', $suffix, true))[1];
  541. $hue = $total % 360;
  542. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  543. $background = $background ? $background : "rgb({$r},{$g},{$b})";
  544. $icon = <<<EOT
  545. <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">
  546. <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"/>
  547. <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
  548. <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
  549. <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"/>
  550. <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
  551. <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>
  552. </svg>
  553. EOT;
  554. return $icon;
  555. }
  556. }
  557. //获取Session缓存数据
  558. function getSessionData($key,$expire_time){
  559. $seseeion_key = md5($key);
  560. $seseeion_key_time = $seseeion_key.'_ctime';
  561. $seseeion_key_data = $seseeion_key.'_data';
  562. $seseeion_time = Session::get($seseeion_key_time);
  563. $seseeion_data = Session::get($seseeion_key_data);
  564. if($seseeion_time && $seseeion_data
  565. && ( time() - $seseeion_time <= $expire_time) ){
  566. //返回缓存数据
  567. $res = json_decode($seseeion_data,true);
  568. return $res;
  569. }
  570. return [];
  571. }
  572. //设置Session缓存数据
  573. function setSessionData($key,$data){
  574. $seseeion_key = md5($key);
  575. $seseeion_key_time = $seseeion_key.'_ctime';
  576. $seseeion_key_data = $seseeion_key.'_data';
  577. Session::set($seseeion_key_time,time());
  578. if(is_array($data)){
  579. $data = json_encode($data,320);
  580. }
  581. Session::set($seseeion_key_data,$data);
  582. return $data;
  583. }
  584. //=================大屏定义算法公式=======================================
  585. //只查看公斤单位数据
  586. function gongjin($info)
  587. {
  588. if ($info['cUnit'] == '公斤') {
  589. return floatval($info['nAmount']);
  590. } else {
  591. return 0;
  592. }
  593. }
  594. //只查看令单位数据)
  595. function ling($info)
  596. {
  597. if($info['cUnit'] == '令' && floatval($info['nhss']) > 0){
  598. return round($info['nAmount']/$info['nhss'],3);
  599. }else{
  600. return 0;
  601. }
  602. }
  603. //个别统一转换为(吨)单位
  604. function todun($info)
  605. {
  606. $dun = 0;
  607. if($info['cUnit'] == '令' && floatval($info['nhss']) > 0){
  608. $dun = round($info['nAmount']/$info['nhss'],3);
  609. }
  610. else if($info['cUnit'] == '张' && floatval($info['nhss']) > 0){
  611. $dun = round($info['nAmount']/500/$info['nhss'],3);
  612. }
  613. else if($info['cUnit'] == '公斤' && floatval($info['nhss']) > 0){
  614. $dun = round(floatval($info['nAmount'])/1000,3) ;
  615. }else if($info['cUnit'] == '米'){
  616. $dun = 0;
  617. }else if($info['cUnit'] == '张'){
  618. $dun = 0;
  619. }
  620. return $dun;
  621. }
  622. //个别统一转换为(公斤)单位
  623. function togongjin($info)
  624. {
  625. if($info['cUnit'] == '令' && floatval($info['nhss']) > 0){
  626. return round($info['nAmount']/$info['nhss'],3);
  627. }
  628. else if($info['cUnit'] == '张' && floatval($info['nhss']) > 0){
  629. return round($info['nAmount']/500/$info['nhss'],3);
  630. }
  631. else if($info['cUnit'] == '公斤'){
  632. return floatval($info['nAmount']);
  633. }
  634. return 0;
  635. }
  636. //获取转换为 单位万
  637. function gettowan($num){
  638. return intval($num/10000);
  639. }
  640. //分类信息——如有新增分类可添加 getCateName方法也要加
  641. function getcateinfo(){
  642. return [
  643. '有光双面铜版纸',
  644. '本白双胶纸',
  645. '特种纸',
  646. '彩画纸',
  647. '轻涂纸',
  648. '亚光双面铜版纸',
  649. '轻型纸',
  650. '白卡纸',
  651. '全灰板',
  652. '纯质纸',
  653. '高白双胶纸',
  654. '纯雅纸'
  655. ];
  656. }
  657. //各类纸张归类
  658. function getCateName($name){
  659. if(strpos($name,'有光双面铜版纸') !== false){
  660. return '有光双面铜版纸';
  661. }
  662. else if(strpos($name,'本白双胶纸') !== false){
  663. return '本白双胶纸';
  664. }
  665. else if(strpos($name,'特种纸') !== false){
  666. return '特种纸';
  667. }
  668. else if(strpos($name,'彩画纸') !== false){
  669. return '彩画纸';
  670. }
  671. else if(strpos($name,'轻涂纸') !== false){
  672. return '轻涂纸';
  673. }
  674. else if(strpos($name,'亚光双面铜版纸') !== false){
  675. return '亚光双面铜版纸';
  676. }
  677. else if(strpos($name,'轻型纸') !== false){
  678. return '轻型纸';
  679. }
  680. else if(strpos($name,'白卡纸') !== false){
  681. return '白卡纸';
  682. }
  683. else if(strpos($name,'高白双胶纸') !== false){
  684. return '高白双胶纸';
  685. }
  686. else if(strpos($name,'纯质纸') !== false){
  687. return '纯质纸';
  688. }
  689. else if(strpos($name,'全灰板') !== false){
  690. return '全灰板';
  691. }
  692. else if(strpos($name,'纯雅纸') !== false){
  693. return '纯雅纸';
  694. }
  695. return '未归类';
  696. }
  697. //判断名称分类
  698. function pdcateinfobyczgmc($czgmc){
  699. if(!$czgmc || empty($czgmc)){
  700. return '';
  701. }
  702. //getcateinfo自定义函数查询显示的固定分类
  703. $cateinfo = getcateinfo();
  704. if(in_array($czgmc,$cateinfo)){
  705. return $czgmc;
  706. }
  707. //
  708. foreach($cateinfo as $value){
  709. if(strpos($czgmc,$value) !== false){
  710. return $value;
  711. }
  712. }
  713. return '';
  714. }
  715. //补分类信息
  716. function bucateinfo($info=[])
  717. {
  718. $arr = getcateinfo();
  719. $tmp = [];
  720. foreach($arr as $value){
  721. if(!isset($info[$value]) ){
  722. $tmp[$value] = 0;
  723. }else{
  724. $tmp[$value] = $info[$value];
  725. }
  726. }
  727. return $tmp;
  728. }
  729. //获取今年年份信息
  730. function getYearInfo()
  731. {
  732. $y = [];
  733. $year= date('Y');
  734. for($i=1;$i<=12;$i++)
  735. {
  736. if($i < 10){
  737. $y[] = $year.'0'.$i;
  738. }
  739. else{
  740. $y[] = $year.$i;
  741. }
  742. }
  743. return $y;
  744. }
  745. //获取今年年月份
  746. function gettimeinfo($type=0){
  747. $start_time = date('Y-01-01').' 00:00:00';
  748. if($type == 1){
  749. return date('Y-m-d',strtotime($start_time .' + 1 year -1 day')) .' 23:59:59';
  750. }
  751. return $start_time;
  752. }
  753. //获取去年月份
  754. function getLastYear($type = 0) {
  755. $start_time = date('Y-01-01', strtotime('-1 year')) . ' 00:00:00';
  756. if ($type == 1) {
  757. return date('Y-m-d', strtotime($start_time . ' + 1 year -1 day')) . ' 23:59:59';
  758. }
  759. return $start_time;
  760. }
  761. //获取前年月份
  762. function getPreviousYear($type = 0) {
  763. $start_time = date('Y-01-01', strtotime('-2 years')) . ' 00:00:00';
  764. if ($type == 1) {
  765. return date('Y-m-d', strtotime($start_time . ' + 1 year -1 day')) . ' 23:59:59';
  766. }
  767. return $start_time;
  768. }
  769. //获取前年月份
  770. function getPreviousQYear($type = 0) {
  771. $start_time = date('Y-01-01', strtotime('-3 years')) . ' 00:00:00';
  772. if ($type == 1) {
  773. return date('Y-m-d', strtotime($start_time . ' + 1 year -1 day')) . ' 23:59:59';
  774. }
  775. return $start_time;
  776. }
  777. //规格字段处理
  778. function change($info){
  779. $infosize = $info['size'];
  780. if(!$infosize || empty($infosize)){
  781. return 0;
  782. }
  783. $infosize2 = explode('*',$info['size']);
  784. if(count($infosize2) >= 3){
  785. return 0;
  786. }
  787. $flag = false;
  788. foreach ($infosize2 as $size){
  789. if(!is_numeric($size)){
  790. $flag = true;break;
  791. }
  792. }
  793. if($flag){
  794. return 0;
  795. }
  796. $sizer = 1;
  797. foreach ($infosize2 as $size){
  798. $sizer = $sizer * $size;
  799. }
  800. return $sizer;
  801. }
  802. //保留3位数
  803. function toround($num){
  804. return sprintf("%.3f", $num);
  805. // return round($num,3);
  806. }
  807. //保留2位数
  808. function two_toround($num){
  809. return sprintf("%.2f", $num);
  810. // return round($num,3);
  811. }
  812. //采购平台数据库————采购量重量转换单位(吨)
  813. function cgl_weight($info){
  814. $infosize = floatval($info['size']);
  815. if(!$infosize){return 0;}
  816. $info['unit']= trim($info['unit']);
  817. $dun = 0;
  818. if($info['unit'] == '令' ){
  819. $dun = $info['number'] * 500 * $info['weight'] * pow(10, -12);
  820. }
  821. else if($info['unit'] == '张'){
  822. $dun = $info['number'] * $info['weight'] * pow(10, -12);
  823. }else if($info['unit'] == '米'){
  824. $dun = 0;
  825. }
  826. if($dun >= 0){
  827. $infosize = explode('*',$info['size']);
  828. foreach ($infosize as $size){
  829. $dun = $dun * floatval($size);
  830. }
  831. }
  832. if($info['unit'] == '吨'){
  833. $dun = $info['dunwei'];
  834. }
  835. return $dun;
  836. }
  837. //采购平台数据库————采购量重量转换单位(均价)
  838. function cgl_price($info){
  839. $infosize = floatval($info['size']);
  840. if(!$infosize){return 0;}
  841. $info['unit']= trim($info['unit']);
  842. $dun = 0;
  843. if($info['unit'] == '令' ){
  844. $dun = $info['number'] / 500 / $info['weight'];
  845. }
  846. else if($info['unit'] == '张' ){
  847. $dun = $info['number'] / $info['weight'] ;
  848. }else if($info['unit'] == '米'){
  849. $dun = 0;
  850. }
  851. if($dun >= 0){
  852. $infosize = explode('*',$info['size']);
  853. foreach ($infosize as $size){
  854. $dun = $dun / floatval($size);
  855. }
  856. }
  857. if($info['unit'] == '吨'){
  858. $dun = $info['price'];
  859. }
  860. $dun = $dun * pow(10, 12);
  861. return $dun;
  862. }
  863. //令 = 数量/吨折令
  864. //张 = 数量/吨折令/500
  865. //公斤 =数量/1000
  866. //米=0
  867. //吨折令 = 0 单位为:令/ 20、张/ 1.5 、
  868. //转换单位吨
  869. function erp_price($info){
  870. $info['unit']= trim($info['unit']);
  871. $dun = 0;
  872. if($info['unit'] == '令' ){
  873. if($info['nhss'] == 0){
  874. $dun = $info['number'] / 20;
  875. }else{
  876. $dun = $info['number'] / $info['nhss'];
  877. }
  878. }else if($info['unit'] == '张'){
  879. if($info['nhss'] == 0){
  880. $dun = $info['number'] / 1.5 / 500;
  881. }else{
  882. $dun = $info['number'] / $info['nhss'] / 500;
  883. }
  884. }else if($info['unit'] == '公斤'){
  885. $dun = $info['number'] / 1000;
  886. }else if($info['unit'] == '米'){
  887. $dun = 0;
  888. }
  889. return $dun;
  890. }
  891. //连接 Redis
  892. function redis(){
  893. $redis = new \Redis();
  894. // $redis->connect($this->redis_config['host'], $this->redis_config['port'], $this->redis_config['timeout']);
  895. $redis->connect('127.0.0.1','6379',16400,'');
  896. return $redis;
  897. }