common.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <?php
  2. // 公共助手函数
  3. use Symfony\Component\VarExporter\VarExporter;
  4. if (!function_exists('__')) {
  5. /**
  6. * 获取语言变量值
  7. * @param string $name 语言变量名
  8. * @param array $vars 动态变量值
  9. * @param string $lang 语言
  10. * @return mixed
  11. */
  12. function __($name, $vars = [], $lang = '')
  13. {
  14. if (is_numeric($name) || !$name) {
  15. return $name;
  16. }
  17. if (!is_array($vars)) {
  18. $vars = func_get_args();
  19. array_shift($vars);
  20. $lang = '';
  21. }
  22. return \think\Lang::get($name, $vars, $lang);
  23. }
  24. }
  25. if (!function_exists('format_bytes')) {
  26. /**
  27. * 将字节转换为可读文本
  28. * @param int $size 大小
  29. * @param string $delimiter 分隔符
  30. * @return string
  31. */
  32. function format_bytes($size, $delimiter = '')
  33. {
  34. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  35. for ($i = 0; $size >= 1024 && $i < 6; $i++) {
  36. $size /= 1024;
  37. }
  38. return round($size, 2) . $delimiter . $units[$i];
  39. }
  40. }
  41. if (!function_exists('datetime')) {
  42. /**
  43. * 将时间戳转换为日期时间
  44. * @param int $time 时间戳
  45. * @param string $format 日期时间格式
  46. * @return string
  47. */
  48. function datetime($time, $format = 'Y-m-d H:i:s')
  49. {
  50. $time = is_numeric($time) ? $time : strtotime($time);
  51. return date($format, $time);
  52. }
  53. }
  54. if (!function_exists('human_date')) {
  55. /**
  56. * 获取语义化时间
  57. * @param int $time 时间
  58. * @param int $local 本地时间
  59. * @return string
  60. */
  61. function human_date($time, $local = null)
  62. {
  63. return \fast\Date::human($time, $local);
  64. }
  65. }
  66. if (!function_exists('cdnurl')) {
  67. /**
  68. * 获取上传资源的CDN的地址
  69. * @param string $url 资源相对地址
  70. * @param boolean $domain 是否显示域名 或者直接传入域名
  71. * @return string
  72. */
  73. function cdnurl($url, $domain = false)
  74. {
  75. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  76. $url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
  77. if ($domain && !preg_match($regex, $url)) {
  78. $domain = is_bool($domain) ? request()->domain() : $domain;
  79. $url = $domain . $url;
  80. }
  81. return $url;
  82. }
  83. }
  84. if (!function_exists('is_really_writable')) {
  85. /**
  86. * 判断文件或文件夹是否可写
  87. * @param string $file 文件或目录
  88. * @return bool
  89. */
  90. function is_really_writable($file)
  91. {
  92. if (DIRECTORY_SEPARATOR === '/') {
  93. return is_writable($file);
  94. }
  95. if (is_dir($file)) {
  96. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  97. if (($fp = @fopen($file, 'ab')) === false) {
  98. return false;
  99. }
  100. fclose($fp);
  101. @chmod($file, 0777);
  102. @unlink($file);
  103. return true;
  104. } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
  105. return false;
  106. }
  107. fclose($fp);
  108. return true;
  109. }
  110. }
  111. if (!function_exists('rmdirs')) {
  112. /**
  113. * 删除文件夹
  114. * @param string $dirname 目录
  115. * @param bool $withself 是否删除自身
  116. * @return boolean
  117. */
  118. function rmdirs($dirname, $withself = true)
  119. {
  120. if (!is_dir($dirname)) {
  121. return false;
  122. }
  123. $files = new RecursiveIteratorIterator(
  124. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
  125. RecursiveIteratorIterator::CHILD_FIRST
  126. );
  127. foreach ($files as $fileinfo) {
  128. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  129. $todo($fileinfo->getRealPath());
  130. }
  131. if ($withself) {
  132. @rmdir($dirname);
  133. }
  134. return true;
  135. }
  136. }
  137. if (!function_exists('copydirs')) {
  138. /**
  139. * 复制文件夹
  140. * @param string $source 源文件夹
  141. * @param string $dest 目标文件夹
  142. */
  143. function copydirs($source, $dest)
  144. {
  145. if (!is_dir($dest)) {
  146. mkdir($dest, 0755, true);
  147. }
  148. foreach (
  149. $iterator = new RecursiveIteratorIterator(
  150. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  151. RecursiveIteratorIterator::SELF_FIRST
  152. ) as $item
  153. ) {
  154. if ($item->isDir()) {
  155. $sontDir = $dest . DS . $iterator->getSubPathName();
  156. if (!is_dir($sontDir)) {
  157. mkdir($sontDir, 0755, true);
  158. }
  159. } else {
  160. copy($item, $dest . DS . $iterator->getSubPathName());
  161. }
  162. }
  163. }
  164. }
  165. if (!function_exists('mb_ucfirst')) {
  166. function mb_ucfirst($string)
  167. {
  168. return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
  169. }
  170. }
  171. if (!function_exists('addtion')) {
  172. /**
  173. * 附加关联字段数据
  174. * @param array $items 数据列表
  175. * @param mixed $fields 渲染的来源字段
  176. * @return array
  177. */
  178. function addtion($items, $fields)
  179. {
  180. if (!$items || !$fields) {
  181. return $items;
  182. }
  183. $fieldsArr = [];
  184. if (!is_array($fields)) {
  185. $arr = explode(',', $fields);
  186. foreach ($arr as $k => $v) {
  187. $fieldsArr[$v] = ['field' => $v];
  188. }
  189. } else {
  190. foreach ($fields as $k => $v) {
  191. if (is_array($v)) {
  192. $v['field'] = isset($v['field']) ? $v['field'] : $k;
  193. } else {
  194. $v = ['field' => $v];
  195. }
  196. $fieldsArr[$v['field']] = $v;
  197. }
  198. }
  199. foreach ($fieldsArr as $k => &$v) {
  200. $v = is_array($v) ? $v : ['field' => $v];
  201. $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  202. $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
  203. $v['column'] = isset($v['column']) ? $v['column'] : 'name';
  204. $v['model'] = isset($v['model']) ? $v['model'] : '';
  205. $v['table'] = isset($v['table']) ? $v['table'] : '';
  206. $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
  207. }
  208. unset($v);
  209. $ids = [];
  210. $fields = array_keys($fieldsArr);
  211. foreach ($items as $k => $v) {
  212. foreach ($fields as $m => $n) {
  213. if (isset($v[$n])) {
  214. $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
  215. }
  216. }
  217. }
  218. $result = [];
  219. foreach ($fieldsArr as $k => $v) {
  220. if ($v['model']) {
  221. $model = new $v['model'];
  222. } else {
  223. $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
  224. }
  225. $primary = $v['primary'] ? $v['primary'] : $model->getPk();
  226. $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
  227. }
  228. foreach ($items as $k => &$v) {
  229. foreach ($fields as $m => $n) {
  230. if (isset($v[$n])) {
  231. $curr = array_flip(explode(',', $v[$n]));
  232. $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
  233. }
  234. }
  235. }
  236. return $items;
  237. }
  238. }
  239. if (!function_exists('var_export_short')) {
  240. /**
  241. * 返回打印数组结构
  242. * @param string $var 数组
  243. * @return string
  244. */
  245. function var_export_short($var)
  246. {
  247. return VarExporter::export($var);
  248. }
  249. }
  250. if (!function_exists('letter_avatar')) {
  251. /**
  252. * 首字母头像
  253. * @param $text
  254. * @return string
  255. */
  256. function letter_avatar($text)
  257. {
  258. $total = unpack('L', hash('adler32', $text, true))[1];
  259. $hue = $total % 360;
  260. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  261. $bg = "rgb({$r},{$g},{$b})";
  262. $color = "#ffffff";
  263. $first = mb_strtoupper(mb_substr($text, 0, 1));
  264. $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" alignment-baseline="central">' . $first . '</text></svg>');
  265. $value = 'data:image/svg+xml;base64,' . $src;
  266. return $value;
  267. }
  268. }
  269. if (!function_exists('hsv2rgb')) {
  270. function hsv2rgb($h, $s, $v)
  271. {
  272. $r = $g = $b = 0;
  273. $i = floor($h * 6);
  274. $f = $h * 6 - $i;
  275. $p = $v * (1 - $s);
  276. $q = $v * (1 - $f * $s);
  277. $t = $v * (1 - (1 - $f) * $s);
  278. switch ($i % 6) {
  279. case 0:
  280. $r = $v;
  281. $g = $t;
  282. $b = $p;
  283. break;
  284. case 1:
  285. $r = $q;
  286. $g = $v;
  287. $b = $p;
  288. break;
  289. case 2:
  290. $r = $p;
  291. $g = $v;
  292. $b = $t;
  293. break;
  294. case 3:
  295. $r = $p;
  296. $g = $q;
  297. $b = $v;
  298. break;
  299. case 4:
  300. $r = $t;
  301. $g = $p;
  302. $b = $v;
  303. break;
  304. case 5:
  305. $r = $v;
  306. $g = $p;
  307. $b = $q;
  308. break;
  309. }
  310. return [
  311. floor($r * 255),
  312. floor($g * 255),
  313. floor($b * 255)
  314. ];
  315. }
  316. }
  317. if (!function_exists('check_nav_active')) {
  318. /**
  319. * 检测会员中心导航是否高亮
  320. */
  321. function check_nav_active($url, $classname = 'active')
  322. {
  323. $auth = \app\common\library\Auth::instance();
  324. $requestUrl = $auth->getRequestUri();
  325. $url = ltrim($url, '/');
  326. return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
  327. }
  328. }
  329. if (!function_exists('check_cors_request')) {
  330. /**
  331. * 跨域检测
  332. */
  333. function check_cors_request()
  334. {
  335. if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
  336. $info = parse_url($_SERVER['HTTP_ORIGIN']);
  337. $domainArr = explode(',', config('fastadmin.cors_request_domain'));
  338. $domainArr[] = request()->host(true);
  339. if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
  340. header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
  341. } else {
  342. header('HTTP/1.1 403 Forbidden');
  343. exit;
  344. }
  345. header('Access-Control-Allow-Credentials: true');
  346. header('Access-Control-Max-Age: 86400');
  347. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  348. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
  349. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  350. }
  351. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  352. header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  353. }
  354. exit;
  355. }
  356. }
  357. }
  358. }
  359. if (!function_exists('xss_clean')) {
  360. /**
  361. * 清理XSS
  362. */
  363. function xss_clean($content, $is_image = false)
  364. {
  365. return \app\common\library\Security::instance()->xss_clean($content, $is_image);
  366. }
  367. }