common.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. $output = $export ? var_export($content, true) : print_r($content, true);
  32. echo "<pre>{$output}</pre>";
  33. app_end();
  34. }
  35. /**
  36. * 打印调试函数 json
  37. * @param $content
  38. * @param bool $export
  39. * @throws DebugException
  40. */
  41. function pree($content, bool $export = false)
  42. {
  43. $output = $export ? var_export($content, true) : $content;
  44. throw new DebugException([], $output);
  45. }
  46. /**
  47. * 输出错误信息
  48. * @param string $message 报错信息
  49. * @param int|null $status 状态码,默认为配置文件status.error
  50. * @param array $data 附加数据
  51. * @throws BaseException
  52. */
  53. function throwError(string $message, ?int $status = null, array $data = [])
  54. {
  55. is_null($status) && $status = config('status.error');
  56. throw new BaseException(['status' => $status, 'message' => $message, 'data' => $data]);
  57. }
  58. /**
  59. * 下划线转驼峰
  60. * @param string $uncamelized_words
  61. * @param string $separator
  62. * @return string
  63. */
  64. function camelize(string $uncamelized_words, string $separator = '_'): string
  65. {
  66. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  67. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  68. }
  69. /**
  70. * 驼峰转下划线
  71. * @param string $camelCaps
  72. * @param string $separator
  73. * @return string
  74. */
  75. function uncamelize(string $camelCaps, string $separator = '_'): string
  76. {
  77. return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
  78. }
  79. /**
  80. * 生成密码hash值
  81. * @param string $password
  82. * @return string
  83. */
  84. function encryption_hash(string $password): string
  85. {
  86. return password_hash($password, PASSWORD_DEFAULT);
  87. }
  88. /**
  89. * 获取当前域名及根路径
  90. * @return string
  91. */
  92. function base_url(): string
  93. {
  94. static $baseUrl = '';
  95. if (empty($baseUrl)) {
  96. $request = Request::instance();
  97. // url协议,设置强制https或自动获取
  98. $scheme = Config::get('route')['url_force_https'] ? 'https' : $request->scheme();
  99. // url子目录
  100. $rootUrl = root_url();
  101. // 拼接完整url
  102. //$baseUrl = "{$scheme}://" . $request->host() . $rootUrl;
  103. $baseUrl = "{$scheme}://" . Config::get('app.app_domain') . $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. * 多维数组合并
  178. * @param array $array1
  179. * @param array $array2
  180. * @return array
  181. */
  182. function array_merge_multiple(array $array1, array $array2): array
  183. {
  184. $merge = $array1 + $array2;
  185. $data = [];
  186. foreach ($merge as $key => $val) {
  187. if (
  188. isset($array1[$key])
  189. && is_array($array1[$key])
  190. && isset($array2[$key])
  191. && is_array($array2[$key])
  192. ) {
  193. $data[$key] = is_assoc($array1[$key]) ? array_merge_multiple($array1[$key], $array2[$key]) : $array2[$key];
  194. } else {
  195. $data[$key] = $array2[$key] ?? $array1[$key];
  196. }
  197. }
  198. return $data;
  199. }
  200. /**
  201. * 判断是否为自定义索引数组
  202. * @param array $array
  203. * @return bool
  204. */
  205. function is_assoc(array $array): bool
  206. {
  207. if (empty($array)) return false;
  208. return array_keys($array) !== range(0, count($array) - 1);
  209. }
  210. /**
  211. * 二维数组排序
  212. * @param $arr
  213. * @param $keys
  214. * @param bool $desc
  215. * @return array
  216. */
  217. function array_sort($arr, $keys, bool $desc = false): array
  218. {
  219. $key_value = $new_array = array();
  220. foreach ($arr as $k => $v) {
  221. $key_value[$k] = $v[$keys];
  222. }
  223. if ($desc) {
  224. arsort($key_value);
  225. } else {
  226. asort($key_value);
  227. }
  228. reset($key_value);
  229. foreach ($key_value as $k => $v) {
  230. $new_array[$k] = $arr[$k];
  231. }
  232. return $new_array;
  233. }
  234. /**
  235. * 隐藏敏感字符
  236. * @param string $value
  237. * @return string
  238. */
  239. function substr_cut(string $value): string
  240. {
  241. $strlen = mb_strlen($value, 'utf-8');
  242. if ($strlen <= 1) return $value;
  243. $firstStr = mb_substr($value, 0, 1, 'utf-8');
  244. $lastStr = mb_substr($value, -1, 1, 'utf-8');
  245. return $strlen == 2 ? $firstStr . str_repeat('*', $strlen - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
  246. }
  247. /**
  248. * 获取当前系统版本号
  249. * @return mixed|null
  250. * @throws Exception
  251. */
  252. function get_version()
  253. {
  254. static $version = [];
  255. if (!empty($version)) {
  256. return $version['version'];
  257. }
  258. // 读取version.json文件
  259. $file = root_path() . '/version.json';
  260. if (!file_exists($file)) {
  261. throw new Exception('version.json not found');
  262. }
  263. // 解析json数据
  264. $version = helper::jsonDecode(file_get_contents($file));
  265. if (!is_array($version)) {
  266. throw new Exception('version cannot be decoded');
  267. }
  268. return $version['version'];
  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 == true ? 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 $value
  318. * @param int $padLength
  319. * @return string
  320. */
  321. function pad_left($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 mixed
  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 mixed
  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. * 根据指定长度截取字符串
  359. * @param $str
  360. * @param int $length
  361. * @return bool|string
  362. */
  363. function str_substr($str, int $length = 30)
  364. {
  365. if (strlen($str) > $length) {
  366. $str = mb_substr($str, 0, $length);
  367. }
  368. return $str;
  369. }
  370. /**
  371. * 结束执行
  372. */
  373. function app_end()
  374. {
  375. throw new HttpResponseException(Response::create());
  376. }
  377. /**
  378. * 当前是否为调试模式
  379. * @return bool
  380. */
  381. function is_debug(): bool
  382. {
  383. return (bool)Env::instance()->get('APP_DEBUG');
  384. }
  385. /**
  386. * 文本左斜杠转换为右斜杠
  387. * @param string $string
  388. * @return mixed
  389. */
  390. function convert_left_slash(string $string)
  391. {
  392. return str_replace('\\', '/', $string);
  393. }
  394. /**
  395. * 隐藏手机号中间四位 13012345678 -> 130****5678
  396. * @param string $mobile 手机号
  397. * @return string
  398. */
  399. function hide_mobile(string $mobile): string
  400. {
  401. return substr_replace($mobile, '****', 3, 4);
  402. }
  403. function is_email(string $email) : bool
  404. {
  405. if (preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/', $email)) {
  406. return true;
  407. }
  408. return false;
  409. }
  410. /**
  411. * 获取当前登录的商城ID
  412. * @return int $storeId
  413. */
  414. function getStoreId(): int
  415. {
  416. return 10001;
  417. }
  418. function curl_post($url, $data = [],array $header = [])
  419. {
  420. //$header[] = "Content-type: text/xml";//设置http报文头text/xml
  421. $ch = curl_init();
  422. curl_setopt($ch, CURLOPT_POST, 1);//1:post方式 0:get方式
  423. curl_setopt($ch, CURLOPT_HEADER, 0);
  424. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  425. curl_setopt($ch, CURLOPT_URL, $url);
  426. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  427. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  428. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  429. $result = curl_exec($ch);
  430. curl_close($ch);
  431. return $result;
  432. }
  433. function curl_get($url)
  434. {
  435. $header[] = "Accept: application/json";
  436. $ch = curl_init();
  437. curl_setopt($ch, CURLOPT_POST, 0);//1:post方式 0:get方式
  438. curl_setopt($ch, CURLOPT_HEADER, 0);
  439. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  440. curl_setopt($ch, CURLOPT_URL, $url);
  441. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  442. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  443. $result = curl_exec($ch);
  444. curl_close($ch);
  445. return $result;
  446. }