common.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. // 应用公共文件
  3. use think\facade\Db;
  4. use think\facade\Lang;
  5. use think\Response;
  6. use think\facade\Config;
  7. use app\admin\model\Config as configModel;
  8. use think\exception\HttpResponseException;
  9. use Symfony\Component\HttpFoundation\IpUtils;
  10. use think\db\exception\DbException;
  11. use think\db\exception\DataNotFoundException;
  12. use think\db\exception\ModelNotFoundException;
  13. if (!function_exists('path_is_writable')) {
  14. /**
  15. * 检查目录/文件是否可写
  16. * @param $path
  17. * @return bool
  18. */
  19. function path_is_writable($path): bool
  20. {
  21. if (DIRECTORY_SEPARATOR == '/' && !@ini_get('safe_mode')) {
  22. return is_writable($path);
  23. }
  24. if (is_dir($path)) {
  25. $path = rtrim($path, '/') . '/' . md5(mt_rand(1, 100) . mt_rand(1, 100));
  26. if (($fp = @fopen($path, 'ab')) === false) {
  27. return false;
  28. }
  29. fclose($fp);
  30. @chmod($path, 0777);
  31. @unlink($path);
  32. return true;
  33. } elseif (!is_file($path) || ($fp = @fopen($path, 'ab')) === false) {
  34. return false;
  35. }
  36. fclose($fp);
  37. return true;
  38. }
  39. }
  40. if (!function_exists('deldir')) {
  41. /**
  42. * 删除文件夹
  43. * @param string $dirname 目录
  44. * @param bool $delself 是否删除自身
  45. * @return boolean
  46. */
  47. function deldir(string $dirname, bool $delself = true): bool
  48. {
  49. if (!is_dir($dirname)) {
  50. return false;
  51. }
  52. $files = new RecursiveIteratorIterator(
  53. new RecursiveDirectoryIterator($dirname, FilesystemIterator::SKIP_DOTS),
  54. RecursiveIteratorIterator::CHILD_FIRST
  55. );
  56. foreach ($files as $fileinfo) {
  57. if ($fileinfo->isDir()) {
  58. deldir($fileinfo->getRealPath());
  59. } else {
  60. @unlink($fileinfo->getRealPath());
  61. }
  62. }
  63. if ($delself) {
  64. @rmdir($dirname);
  65. }
  66. return true;
  67. }
  68. }
  69. if (!function_exists('del_empty_dir')) {
  70. /**
  71. * 删除一个路径下的所有相对空文件夹(删除此路径中的所有空文件夹)
  72. * @param string $path 相对于根目录的文件夹路径,如 c:BuildAdmin/a/b/
  73. * @return void
  74. */
  75. function del_empty_dir(string $path)
  76. {
  77. $path = str_replace(root_path(), '', rtrim(path_transform($path), DIRECTORY_SEPARATOR));
  78. $path = array_filter(explode(DIRECTORY_SEPARATOR, $path));
  79. for ($i = count($path) - 1; $i >= 0; $i--) {
  80. $dirPath = root_path() . implode(DIRECTORY_SEPARATOR, $path);
  81. if (!is_dir($dirPath)) {
  82. unset($path[$i]);
  83. continue;
  84. }
  85. if (dir_is_empty($dirPath)) {
  86. deldir($dirPath);
  87. unset($path[$i]);
  88. } else {
  89. break;
  90. }
  91. }
  92. }
  93. }
  94. if (!function_exists('dir_is_empty')) {
  95. function dir_is_empty(string $dir): bool
  96. {
  97. $handle = opendir($dir);
  98. while (false !== ($entry = readdir($handle))) {
  99. if ($entry != "." && $entry != "..") {
  100. closedir($handle);
  101. return false;
  102. }
  103. }
  104. closedir($handle);
  105. return true;
  106. }
  107. }
  108. if (!function_exists('__')) {
  109. /**
  110. * 语言翻译
  111. * @param string $name 被翻译字符
  112. * @param array $vars 替换字符数组
  113. * @param string $lang 翻译语言
  114. * @return string
  115. */
  116. function __(string $name, array $vars = [], string $lang = '')
  117. {
  118. if (is_numeric($name) || !$name) {
  119. return $name;
  120. }
  121. return Lang::get($name, $vars, $lang);
  122. }
  123. }
  124. if (!function_exists('get_sys_config')) {
  125. /**
  126. * 获取站点的系统配置,不传递参数则获取所有配置项
  127. * @param string $name 变量名
  128. * @param string $group 变量分组,传递此参数来获取某个分组的所有配置项
  129. * @param bool $reduct 是否开启简洁模式,简洁模式下,获取多项配置时只返回配置的键值对
  130. * @return string | array
  131. * @throws DataNotFoundException
  132. * @throws DbException
  133. * @throws ModelNotFoundException
  134. */
  135. function get_sys_config(string $name = '', string $group = '', bool $reduct = true)
  136. {
  137. if ($name) {
  138. // 直接使用->value('value')不能使用到模型的类型格式化
  139. $config = configModel::cache($name, null, configModel::$cacheTag)->where('name', $name)->find();
  140. if ($config) $config = $config['value'];
  141. } else {
  142. if ($group) {
  143. $temp = configModel::cache('group' . $group, null, configModel::$cacheTag)->where('group', $group)->select()->toArray();
  144. } else {
  145. $temp = configModel::cache('sys_config_all', null, configModel::$cacheTag)->order('weigh desc')->select()->toArray();
  146. }
  147. if ($reduct) {
  148. $config = [];
  149. foreach ($temp as $item) {
  150. $config[$item['name']] = $item['value'];
  151. }
  152. } else {
  153. $config = $temp;
  154. }
  155. }
  156. return $config;
  157. }
  158. }
  159. if (!function_exists('get_route_remark')) {
  160. /**
  161. * 获取当前路由后台菜单规则的备注信息
  162. * @return string
  163. */
  164. function get_route_remark()
  165. {
  166. $controllername = request()->controller(true);
  167. $actionname = request()->action(true);
  168. $path = str_replace('.', '/', $controllername);
  169. $remark = Db::name('menu_rule')
  170. ->where('name', $path)
  171. ->whereOr('name', $path . '/' . $actionname)
  172. ->value('remark');
  173. return __((string)$remark);
  174. }
  175. }
  176. if (!function_exists('full_url')) {
  177. /**
  178. * 获取资源完整url地址
  179. * @param string $relativeUrl 资源相对地址 不传入则获取域名
  180. * @param boolean $domain 是否携带域名 或者直接传入域名
  181. * @return string
  182. */
  183. function full_url(string $relativeUrl = '', bool $domain = true, $default = '')
  184. {
  185. $cdnUrl = Config::get('buildadmin.cdn_url');
  186. if (!$cdnUrl) $cdnUrl = request()->upload['cdn'] ?? request()->domain();
  187. if ($domain === true) {
  188. $domain = $cdnUrl;
  189. } elseif ($domain === false) {
  190. $domain = '';
  191. }
  192. $relativeUrl = $relativeUrl ?: $default;
  193. if (!$relativeUrl) return $domain;
  194. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  195. if (preg_match('/^http(s)?:\/\//', $relativeUrl) || preg_match($regex, $relativeUrl) || $domain === false) {
  196. return $relativeUrl;
  197. }
  198. return $domain . $relativeUrl;
  199. }
  200. }
  201. if (!function_exists('encrypt_password')) {
  202. /**
  203. * 加密密码
  204. */
  205. function encrypt_password($password, $salt = '', $encrypt = 'md5')
  206. {
  207. return $encrypt($encrypt($password) . $salt);
  208. }
  209. }
  210. if (!function_exists('str_attr_to_array')) {
  211. /**
  212. * 将字符串属性列表转为数组
  213. * @param string $attr 属性,一行一个,无需引号,比如:class=input-class
  214. * @return array
  215. */
  216. function str_attr_to_array(string $attr): array
  217. {
  218. if (!$attr) return [];
  219. $attr = explode("\n", trim(str_replace("\r\n", "\n", $attr)));
  220. $attrTemp = [];
  221. foreach ($attr as $item) {
  222. $item = explode('=', $item);
  223. if (!empty($item[0]) && isset($item[1])) {
  224. $attrVal = $item[1];
  225. if ($item[1] === 'false' || $item[1] === 'true') {
  226. $attrVal = !($item[1] === 'false');
  227. } elseif (is_numeric($item[1])) {
  228. $attrVal = (float)$item[1];
  229. }
  230. if (strpos($item[0], '.')) {
  231. $attrKey = explode('.', $item[0]);
  232. if (!empty($attrKey[0]) && !empty($attrKey[1])) {
  233. $attrTemp[$attrKey[0]][$attrKey[1]] = $attrVal;
  234. continue;
  235. }
  236. }
  237. $attrTemp[$item[0]] = $attrVal;
  238. }
  239. }
  240. return $attrTemp;
  241. }
  242. }
  243. if (!function_exists('action_in_arr')) {
  244. /**
  245. * 检测一个方法是否在传递的数组内
  246. * @param array $arr
  247. * @return bool
  248. */
  249. function action_in_arr(array $arr = []): bool
  250. {
  251. $arr = is_array($arr) ? $arr : explode(',', $arr);
  252. if (!$arr) {
  253. return false;
  254. }
  255. $arr = array_map('strtolower', $arr);
  256. if (in_array(strtolower(request()->action()), $arr) || in_array('*', $arr)) {
  257. return true;
  258. }
  259. return false;
  260. }
  261. }
  262. if (!function_exists('build_suffix_svg')) {
  263. /**
  264. * 构建文件后缀的svg图片
  265. * @param string $suffix 文件后缀
  266. * @param string|null $background 背景颜色,如:rgb(255,255,255)
  267. * @return string
  268. */
  269. function build_suffix_svg(string $suffix = 'file', string $background = null): string
  270. {
  271. $suffix = mb_substr(strtoupper($suffix), 0, 4);
  272. $total = unpack('L', hash('adler32', $suffix, true))[1];
  273. $hue = $total % 360;
  274. [$r, $g, $b] = hsv2rgb($hue / 360, 0.3, 0.9);
  275. $background = $background ?: "rgb($r,$g,$b)";
  276. return '<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">
  277. <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"/>
  278. <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
  279. <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
  280. <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"/>
  281. <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
  282. <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>
  283. </svg>';
  284. }
  285. }
  286. if (!function_exists('get_area')) {
  287. function get_area()
  288. {
  289. $province = request()->param('province', '');
  290. $city = request()->param('city', '');
  291. $where = ['pid' => 0, 'level' => 1];
  292. if ($province !== '') {
  293. $where['pid'] = $province;
  294. $where['level'] = 2;
  295. if ($city !== '') {
  296. $where['pid'] = $city;
  297. $where['level'] = 3;
  298. }
  299. }
  300. return Db::name('area')->where($where)->field('id as value,name as label')->select();
  301. }
  302. }
  303. if (!function_exists('hsv2rgb')) {
  304. function hsv2rgb($h, $s, $v): array
  305. {
  306. $r = $g = $b = 0;
  307. $i = floor($h * 6);
  308. $f = $h * 6 - $i;
  309. $p = $v * (1 - $s);
  310. $q = $v * (1 - $f * $s);
  311. $t = $v * (1 - (1 - $f) * $s);
  312. switch ($i % 6) {
  313. case 0:
  314. $r = $v;
  315. $g = $t;
  316. $b = $p;
  317. break;
  318. case 1:
  319. $r = $q;
  320. $g = $v;
  321. $b = $p;
  322. break;
  323. case 2:
  324. $r = $p;
  325. $g = $v;
  326. $b = $t;
  327. break;
  328. case 3:
  329. $r = $p;
  330. $g = $q;
  331. $b = $v;
  332. break;
  333. case 4:
  334. $r = $t;
  335. $g = $p;
  336. $b = $v;
  337. break;
  338. case 5:
  339. $r = $v;
  340. $g = $p;
  341. $b = $q;
  342. break;
  343. }
  344. return [
  345. floor($r * 255),
  346. floor($g * 255),
  347. floor($b * 255)
  348. ];
  349. }
  350. }
  351. if (!function_exists('ip_check')) {
  352. function ip_check($ip = null)
  353. {
  354. $ip = is_null($ip) ? request()->ip() : $ip;
  355. $noAccess = get_sys_config('no_access_ip');
  356. $noAccess = !$noAccess ? [] : array_filter(explode("\n", str_replace("\r\n", "\n", $noAccess)));
  357. if ($noAccess && IpUtils::checkIp($ip, $noAccess)) {
  358. $response = Response::create(['msg' => 'No permission request'], 'json', 403);
  359. throw new HttpResponseException($response);
  360. }
  361. }
  362. }
  363. if (!function_exists('set_timezone')) {
  364. function set_timezone($timezone = null)
  365. {
  366. $defaultTimezone = Config::get('app.default_timezone');
  367. $timezone = is_null($timezone) ? get_sys_config('time_zone') : $timezone;
  368. if ($timezone && $defaultTimezone != $timezone) {
  369. Config::set([
  370. 'app.default_timezone' => $timezone
  371. ]);
  372. date_default_timezone_set($timezone);
  373. }
  374. }
  375. }
  376. if (!function_exists('path_transform')) {
  377. function path_transform(string $path)
  378. {
  379. return str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
  380. }
  381. }
  382. if (!function_exists('get_upload_config')) {
  383. function get_upload_config()
  384. {
  385. $uploadConfig = Config::get('upload');
  386. $uploadConfig['maxsize'] = file_unit_to_byte($uploadConfig['maxsize']);
  387. $upload = request()->upload;
  388. if (!$upload) {
  389. $uploadConfig['mode'] = 'local';
  390. return $uploadConfig;
  391. }
  392. unset($upload['cdn']);
  393. return array_merge($upload, $uploadConfig);
  394. }
  395. }
  396. if (!function_exists('file_unit_to_byte')) {
  397. /**
  398. * 将一个文件单位转为字节
  399. * @param string $unit 将b、kb、m、mb、g、gb的单位转为 byte
  400. */
  401. function file_unit_to_byte(string $unit): int
  402. {
  403. preg_match('/([0-9\.]+)(\w+)/', $unit, $matches);
  404. if (!$matches) {
  405. return 0;
  406. }
  407. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  408. return (int)($matches[1] * pow(1024, $typeDict[strtolower($matches[2])] ?? 0));
  409. }
  410. }