common.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2025 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. /**
  13. * 应用公共函数库文件
  14. */
  15. use think\Response;
  16. use think\facade\Env;
  17. use think\facade\Log;
  18. use think\facade\Config;
  19. use think\facade\Request;
  20. use cores\exception\BaseException;
  21. use cores\exception\DebugException;
  22. use think\exception\HttpResponseException;
  23. /**
  24. * 打印调试函数 html
  25. * @param $content
  26. * @param bool $export
  27. */
  28. function pre($content, bool $export = false)
  29. {
  30. $output = $export ? var_export($content, true) : print_r($content, true);
  31. echo "<pre>{$output}</pre>";
  32. app_end();
  33. }
  34. /**
  35. * 打印调试函数 json
  36. * @param $content
  37. * @param bool $export
  38. * @throws DebugException
  39. */
  40. function pree($content, bool $export = false)
  41. {
  42. $output = $export ? var_export($content, true) : $content;
  43. throw new DebugException([], $output);
  44. }
  45. /**
  46. * 打印调试函数 输出在终端
  47. * 只有debug模式下输出
  48. * @param $content
  49. * @return void
  50. */
  51. function tre($content)
  52. {
  53. // if (is_debug()) {
  54. $output = print_r($content, true);
  55. echo "$output\n";
  56. // }
  57. }
  58. /**
  59. * 输出错误信息
  60. * @param string $message 报错信息
  61. * @param int|null $status 状态码,默认为配置文件status.error
  62. * @param array $data 附加数据
  63. * @throws BaseException
  64. */
  65. function throwError(string $message, ?int $status = null, array $data = [])
  66. {
  67. is_null($status) && $status = config('status.error');
  68. $data = \array_merge(['isPrompt' => true], $data);
  69. throw new BaseException(compact('status', 'message', 'data'));
  70. }
  71. /**
  72. * 下划线转驼峰
  73. * @param string $str
  74. * @param string $separator
  75. * @return string
  76. */
  77. function camelize(string $str, string $separator = '_'): string
  78. {
  79. $str = ucwords(str_replace($separator, ' ', $str));
  80. $str = str_replace(' ', '', $str);
  81. return lcfirst($str);
  82. }
  83. /**
  84. * 驼峰转下划线
  85. * @param string $camelCaps
  86. * @param string $separator
  87. * @return string
  88. */
  89. function uncamelize(string $camelCaps, string $separator = '_'): string
  90. {
  91. return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
  92. }
  93. /**
  94. * 生成密码hash值
  95. * @param string $password
  96. * @return string
  97. */
  98. function encryption_hash(string $password): string
  99. {
  100. return password_hash($password, PASSWORD_DEFAULT);
  101. }
  102. /**
  103. * 获取当前域名及根路径
  104. * @return string
  105. */
  106. function base_url(): string
  107. {
  108. static $baseUrl = '';
  109. if (empty($baseUrl)) {
  110. $request = Request::instance();
  111. // url协议,设置强制https或自动获取
  112. $scheme = Config::get('route')['url_force_https'] ? 'https' : $request->scheme();
  113. // url子目录
  114. $rootUrl = root_url();
  115. // 拼接完整url
  116. $baseUrl = "{$scheme}://" . $request->host() . $rootUrl;
  117. }
  118. return $baseUrl;
  119. }
  120. /**
  121. * 获取当前url的子目录路径
  122. * @return string
  123. */
  124. function root_url(): string
  125. {
  126. static $rootUrl = '';
  127. if (empty($rootUrl)) {
  128. $request = Request::instance();
  129. $subUrl = str_replace('\\', '/', dirname($request->baseFile()));
  130. $rootUrl = $subUrl . ($subUrl === '/' ? '' : '/');
  131. }
  132. return $rootUrl;
  133. }
  134. /**
  135. * 获取当前uploads目录访问地址
  136. * @return string
  137. */
  138. function uploads_url(): string
  139. {
  140. return base_url() . 'uploads/';
  141. }
  142. /**
  143. * 获取当前temp目录访问地址
  144. * @return string
  145. */
  146. function temp_url(): string
  147. {
  148. return base_url() . 'temp/';
  149. }
  150. /**
  151. * 获取当前的应用名称
  152. * @return mixed
  153. */
  154. function app_name()
  155. {
  156. return app('http')->getName();
  157. }
  158. /**
  159. * 获取web根目录
  160. * @return string
  161. */
  162. function web_path(): string
  163. {
  164. static $webPath = '';
  165. if (empty($webPath)) {
  166. $request = Request::instance();
  167. $webPath = dirname($request->server('SCRIPT_FILENAME')) . DIRECTORY_SEPARATOR;
  168. }
  169. return $webPath;
  170. }
  171. /**
  172. * 获取data目录路径
  173. * @return string
  174. */
  175. function data_path(): string
  176. {
  177. return config('filesystem.disks.data.root') . DIRECTORY_SEPARATOR;
  178. }
  179. /**
  180. * 获取runtime根目录路径
  181. * @return string
  182. */
  183. function runtime_root_path(): string
  184. {
  185. // return dirname(runtime_path()) . DIRECTORY_SEPARATOR;
  186. return root_path() . 'runtime' . DIRECTORY_SEPARATOR;
  187. }
  188. /**
  189. * 写入日志 (使用tp自带驱动记录到runtime目录中)
  190. * @param mixed $value
  191. * @param string $type
  192. */
  193. function log_record($value, string $type = 'info')
  194. {
  195. $content = is_string($value) ? $value : print_r($value, true);
  196. Log::record($content, $type);
  197. }
  198. /**
  199. * 重组缓存数据(多维)
  200. * @param $data1
  201. * @param $data2
  202. * @return array
  203. */
  204. function resetOptions($data1, $data2): array
  205. {
  206. $data = [];
  207. foreach ($data1 + $data2 as $key => $val) {
  208. $data[$key] = (isset($data1[$key]) && is_array($data1[$key]) && isset($data2[$key]) && is_array($data2[$key]))
  209. ? (is_assoc($data1[$key]) ? \resetOptions($data1[$key], $data2[$key]) : $data2[$key])
  210. : $data2[$key] ?? $data1[$key];
  211. }
  212. return $data;
  213. }
  214. /**
  215. * 判断是否为自定义索引数组
  216. * @param array $array
  217. * @return bool
  218. */
  219. function is_assoc(array $array): bool
  220. {
  221. if (empty($array)) return false;
  222. return array_keys($array) !== range(0, count($array) - 1);
  223. }
  224. /**
  225. * 二维数组排序
  226. * @param $arr
  227. * @param $keys
  228. * @param bool $desc
  229. * @return array
  230. */
  231. function array_sort($arr, $keys, bool $desc): array
  232. {
  233. $key_value = $new_array = array();
  234. foreach ($arr as $k => $v) {
  235. $key_value[$k] = $v[$keys];
  236. }
  237. if ($desc) {
  238. arsort($key_value);
  239. } else {
  240. asort($key_value);
  241. }
  242. reset($key_value);
  243. foreach ($key_value as $k => $v) {
  244. $new_array[$k] = $arr[$k];
  245. }
  246. return $new_array;
  247. }
  248. /**
  249. * 隐藏敏感字符
  250. * @param $value
  251. * @return string
  252. */
  253. function substr_cut($value): string
  254. {
  255. $strlen = mb_strlen($value, 'utf-8');
  256. if ($strlen <= 1) return $value;
  257. $firstStr = mb_substr($value, 0, 1, 'utf-8');
  258. $lastStr = mb_substr($value, -1, 1, 'utf-8');
  259. return $strlen == 2 ? $firstStr . str_repeat('*', $strlen - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
  260. }
  261. /**
  262. * 获取当前系统版本号
  263. * @return string
  264. * @throws BaseException
  265. */
  266. function get_version(): string
  267. {
  268. return \cores\library\Version::getVersion();
  269. }
  270. /**
  271. * 获取全局唯一标识符
  272. * @param bool $trim
  273. * @return string
  274. */
  275. function get_guid_v4(bool $trim = true): string
  276. {
  277. // Windows
  278. if (function_exists('com_create_guid') === true) {
  279. $charid = com_create_guid();
  280. return $trim ? trim($charid, '{}') : $charid;
  281. }
  282. // OSX/Linux
  283. if (function_exists('openssl_random_pseudo_bytes') === true) {
  284. $data = openssl_random_pseudo_bytes(16);
  285. $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
  286. $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
  287. return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  288. }
  289. // Fallback (PHP 4.2+)
  290. mt_srand(intval((double)microtime() * 10000));
  291. $charid = strtolower(md5(uniqid((string)rand(), true)));
  292. $hyphen = chr(45); // "-"
  293. $lbrace = $trim ? "" : chr(123); // "{"
  294. $rbrace = $trim ? "" : chr(125); // "}"
  295. return $lbrace .
  296. substr($charid, 0, 8) . $hyphen .
  297. substr($charid, 8, 4) . $hyphen .
  298. substr($charid, 12, 4) . $hyphen .
  299. substr($charid, 16, 4) . $hyphen .
  300. substr($charid, 20, 12) .
  301. $rbrace;
  302. }
  303. /**
  304. * 时间戳转换日期
  305. * @param int|string $timeStamp 时间戳
  306. * @param bool $withTime 是否关联时间
  307. * @return false|string
  308. */
  309. function format_time($timeStamp, bool $withTime = true)
  310. {
  311. $format = 'Y-m-d';
  312. $withTime && $format .= ' H:i:s';
  313. return $timeStamp ? date($format, $timeStamp) : '';
  314. }
  315. /**
  316. * 左侧填充0
  317. * @param string $value
  318. * @param int $padLength
  319. * @return string
  320. */
  321. function pad_left(string $value, int $padLength = 2): string
  322. {
  323. return str_pad($value, $padLength, '0', STR_PAD_LEFT);
  324. }
  325. /**
  326. * 重写trim方法 (解决int类型过滤后后变为string类型)
  327. * @param $str
  328. * @return string|void
  329. */
  330. function my_trim($str)
  331. {
  332. return is_string($str) ? trim($str) : $str;
  333. }
  334. /**
  335. * 重写htmlspecialchars方法 (解决int类型过滤后后变为string类型)
  336. * @param $string
  337. * @return string|void
  338. */
  339. function my_htmlspecialchars($string)
  340. {
  341. return is_string($string) ? htmlspecialchars($string, ENT_COMPAT) : $string;
  342. }
  343. /**
  344. * 过滤emoji表情
  345. * @param $text
  346. * @return null|string|string[]
  347. */
  348. function filter_emoji($text)
  349. {
  350. if (!is_string($text)) {
  351. return $text;
  352. }
  353. // 此处的preg_replace用于过滤emoji表情
  354. // 如需支持emoji表情, 需将mysql的编码改为utf8mb4
  355. return preg_replace('/[\xf0-\xf7].{3}/', '', $text);
  356. }
  357. /**
  358. * 过滤int类型的数组
  359. * @param array $data
  360. * @return array
  361. */
  362. function filter_array_int(array $data): array
  363. {
  364. return array_filter(array_map(fn($val) => (int)$val, $data));
  365. }
  366. /**
  367. * 分割int类型的数组
  368. * @param array $data
  369. * @param string $separator
  370. * @return string
  371. */
  372. function implode_int(array $data, string $separator = ','): string
  373. {
  374. return implode($separator, filter_array_int($data));
  375. }
  376. /**
  377. * 根据指定长度截取字符串
  378. * @param $str
  379. * @param int $length
  380. * @return bool|string
  381. */
  382. function str_substr($str, int $length = 30)
  383. {
  384. if (strlen($str) > $length) {
  385. $str = mb_substr($str, 0, $length);
  386. }
  387. return $str;
  388. }
  389. /**
  390. * 结束执行
  391. */
  392. function app_end()
  393. {
  394. if (\request()->isCli()) {
  395. exit(PHP_EOL);
  396. }
  397. throw new HttpResponseException(Response::create());
  398. }
  399. /**
  400. * 当前是否为调试模式
  401. * @return bool
  402. */
  403. function is_debug(): bool
  404. {
  405. return (bool)Env::instance()->get('APP_DEBUG');
  406. }
  407. /**
  408. * 文本左斜杠转换为右斜杠
  409. * @param string $string
  410. * @return string
  411. */
  412. function convert_left_slash(string $string): string
  413. {
  414. return str_replace('\\', '/', $string);
  415. }
  416. /**
  417. * 隐藏手机号中间四位 13012345678 -> 130****5678
  418. * @param string $mobile 手机号
  419. * @return string
  420. */
  421. function hide_mobile(string $mobile): string
  422. {
  423. return substr_replace($mobile, '****', 3, 4);
  424. }
  425. /**
  426. * 获取当前登录的商城ID
  427. * @return int $storeId
  428. */
  429. function getStoreId(): int
  430. {
  431. return 10001;
  432. }
  433. /**
  434. * 验证字符串是否为域名
  435. * @param string $domain
  436. * @return bool
  437. */
  438. function is_valid_domain(string $domain): bool
  439. {
  440. $pattern = '/^([a-z0-9]+([a-z0-9-]*(?:[a-z0-9]+))?\.)?[a-z0-9]+([a-z0-9-]*(?:[a-z0-9]+))?(\.us|\.tv|\.org\.cn|\.org|\.net\.cn|\.net|\.mobi|\.me|\.la|\.info|\.hk|\.gov\.cn|\.edu|\.com\.cn|\.com|\.co\.jp|\.co|\.cn|\.cc|\.biz)$/i';
  441. return !empty($domain) && strpos($domain, '--') === false && preg_match($pattern, $domain);
  442. }