common.php 11 KB

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