common.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. <?php
  2. // 公共助手函数
  3. if (!function_exists('__'))
  4. {
  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. if (!is_array($vars))
  17. {
  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. * 将字节转换为可读文本
  29. * @param int $size 大小
  30. * @param string $delimiter 分隔符
  31. * @return string
  32. */
  33. function format_bytes($size, $delimiter = '')
  34. {
  35. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  36. for ($i = 0; $size >= 1024 && $i < 6; $i++)
  37. $size /= 1024;
  38. return round($size, 2) . $delimiter . $units[$i];
  39. }
  40. }
  41. if (!function_exists('datetime'))
  42. {
  43. /**
  44. * 将时间戳转换为日期时间
  45. * @param int $time 时间戳
  46. * @param string $format 日期时间格式
  47. * @return string
  48. */
  49. function datetime($time, $format = 'Y-m-d H:i:s')
  50. {
  51. $time = is_numeric($time) ? $time : strtotime($time);
  52. return date($format, $time);
  53. }
  54. }
  55. if (!function_exists('human_date'))
  56. {
  57. /**
  58. * 获取语义化时间
  59. * @param int $time 时间
  60. * @param int $local 本地时间
  61. * @return string
  62. */
  63. function human_date($time, $local = null)
  64. {
  65. return \fast\Date::human($time, $local);
  66. }
  67. }
  68. if (!function_exists('cdnurl'))
  69. {
  70. /**
  71. * 获取上传资源的CDN的地址
  72. * @param string $url 资源相对地址
  73. * @return string
  74. */
  75. function cdnurl($url)
  76. {
  77. return preg_match("/^https?:\/\/(.*)/i", $url) ? $url : think\Config::get('upload.cdnurl') . $url;
  78. }
  79. }
  80. if (!function_exists('getCurrentDomain'))
  81. {
  82. /**
  83. * 获取用户当前域名
  84. * @param int $channel_id 渠道ID
  85. * @param string $redirect 跳转地址
  86. * @param array|string $params 参数
  87. * @param bool $isUseMenuDomain
  88. * @return string
  89. */
  90. function getCurrentDomain($channel_id,$redirect = null,$params = [],$isUseMenuDomain = false){
  91. \think\Log::info('GetCurrentDomain: Channel_id:'.$channel_id.' Redirect:'.$redirect.' Params:'.(is_array($params)? var_export($params,true):$params));
  92. if (!$channel_id) {
  93. return '';
  94. }
  95. try{
  96. $webParams = [];
  97. $webSitePath = '';
  98. $scheme = \think\Config::get('site.scheme');
  99. if (empty($scheme)) {
  100. //库里拉取
  101. $site = model("Config")->getConfigSiteArr();
  102. $scheme = $site['scheme'];
  103. }
  104. $adminConfig = \app\main\service\AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($channel_id);
  105. if($isUseMenuDomain && isset($adminConfig['menuophost']) && !empty($adminConfig['menuophost'])){
  106. $webSite = $scheme.'://'.($adminConfig['appid'] ?? '').'.'.$adminConfig['menuophost'];
  107. }else{
  108. $webSite = $scheme.'://'.($adminConfig['appid'] ?? '').'.'.$adminConfig['ophost_host'];
  109. }
  110. if($redirect){
  111. $pathParams = parse_url($redirect);
  112. //添加路径
  113. if(isset($pathParams['path']) && $pathParams['path']){
  114. $webSitePath = $pathParams['path'];
  115. }
  116. //检查路径是否有参数
  117. if(isset($pathParams['query']) && $pathParams['query']){
  118. $pathQuery = explode('&',$pathParams['query']);
  119. if($pathQuery){
  120. foreach($pathQuery as $val){
  121. $temp = explode('=',$val);
  122. $webParams[$temp[0]] = $temp[1] ?? '';
  123. }
  124. }
  125. }
  126. }
  127. if($params){
  128. if(is_array($params)){
  129. $webParams = array_merge($webParams,$params);
  130. }
  131. if(is_string($params)){
  132. //检查参数
  133. $pathParams = parse_url($params);
  134. if(isset($pathParams['query']) && $pathParams['query']){
  135. $pathQuery = explode('&',$pathParams['query']);
  136. if($pathQuery){
  137. foreach($pathQuery as $val){
  138. $temp = explode('=',$val);
  139. $webParams[$temp[0]] = $temp[1] ?? '';
  140. }
  141. }
  142. }
  143. }
  144. }
  145. //拼接路径
  146. if(empty($webSitePath)){
  147. $webSitePath = '/';
  148. }
  149. $webSite = $webSite . $webSitePath;
  150. //拼接参数
  151. if($webParams){
  152. $webSite = $webSite .'?'.http_build_query($webParams);
  153. }
  154. \think\Log::info('GetCurrentDomain: URI:'.$webSite);
  155. return $webSite;
  156. }catch (\Exception $e){
  157. \think\Log::error('GetCurrentDomain Error:'.$e->getMessage());
  158. }
  159. return '';
  160. }
  161. }
  162. if (!function_exists('getCurrentOphost'))
  163. {
  164. function getCurrentOphost(){
  165. $domain = get_host_no_port();
  166. $hostArr = explode('.', $domain);
  167. array_shift($hostArr);
  168. return implode('.', $hostArr);
  169. }
  170. }
  171. if (!function_exists('is_really_writable'))
  172. {
  173. /**
  174. * 判断文件或文件夹是否可写
  175. * @param string $file 文件或目录
  176. * @return bool
  177. */
  178. function is_really_writable($file)
  179. {
  180. if (DIRECTORY_SEPARATOR === '/')
  181. {
  182. return is_writable($file);
  183. }
  184. if (is_dir($file))
  185. {
  186. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  187. if (($fp = @fopen($file, 'ab')) === FALSE)
  188. {
  189. return FALSE;
  190. }
  191. fclose($fp);
  192. @chmod($file, 0777);
  193. @unlink($file);
  194. return TRUE;
  195. }
  196. elseif (!is_file($file) OR ( $fp = @fopen($file, 'ab')) === FALSE)
  197. {
  198. return FALSE;
  199. }
  200. fclose($fp);
  201. return TRUE;
  202. }
  203. }
  204. if (!function_exists('rmdirs'))
  205. {
  206. /**
  207. * 删除文件夹
  208. * @param string $dirname 目录
  209. * @param bool $withself 是否删除自身
  210. * @return boolean
  211. */
  212. function rmdirs($dirname, $withself = true)
  213. {
  214. if (!is_dir($dirname))
  215. return false;
  216. $files = new RecursiveIteratorIterator(
  217. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
  218. );
  219. foreach ($files as $fileinfo)
  220. {
  221. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  222. $todo($fileinfo->getRealPath());
  223. }
  224. if ($withself)
  225. {
  226. @rmdir($dirname);
  227. }
  228. return true;
  229. }
  230. }
  231. if (!function_exists('copydirs'))
  232. {
  233. /**
  234. * 复制文件夹
  235. * @param string $source 源文件夹
  236. * @param string $dest 目标文件夹
  237. */
  238. function copydirs($source, $dest)
  239. {
  240. if (!is_dir($dest))
  241. {
  242. mkdir($dest, 0755);
  243. }
  244. foreach (
  245. $iterator = new RecursiveIteratorIterator(
  246. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item
  247. )
  248. {
  249. if ($item->isDir())
  250. {
  251. $sontDir = $dest . DS . $iterator->getSubPathName();
  252. if (!is_dir($sontDir))
  253. {
  254. mkdir($sontDir);
  255. }
  256. }
  257. else
  258. {
  259. copy($item, $dest . DS . $iterator->getSubPathName());
  260. }
  261. }
  262. }
  263. }
  264. if (!function_exists('mb_ucfirst'))
  265. {
  266. function mb_ucfirst($string)
  267. {
  268. return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
  269. }
  270. }
  271. if (!function_exists('addtion'))
  272. {
  273. /**
  274. * 附加关联字段数据
  275. * @param array $items 数据列表
  276. * @param mixed $fields 渲染的来源字段
  277. * @return array
  278. */
  279. function addtion($items, $fields)
  280. {
  281. if (!$items || !$fields)
  282. return $items;
  283. $fieldsArr = [];
  284. if (!is_array($fields))
  285. {
  286. $arr = explode(',', $fields);
  287. foreach ($arr as $k => $v)
  288. {
  289. $fieldsArr[$v] = ['field' => $v];
  290. }
  291. }
  292. else
  293. {
  294. foreach ($fields as $k => $v)
  295. {
  296. if (is_array($v))
  297. {
  298. $v['field'] = isset($v['field']) ? $v['field'] : $k;
  299. }
  300. else
  301. {
  302. $v = ['field' => $v];
  303. }
  304. $fieldsArr[$v['field']] = $v;
  305. }
  306. }
  307. foreach ($fieldsArr as $k => &$v)
  308. {
  309. $v = is_array($v) ? $v : ['field' => $v];
  310. $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  311. $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
  312. $v['column'] = isset($v['column']) ? $v['column'] : 'name';
  313. $v['model'] = isset($v['model']) ? $v['model'] : '';
  314. $v['table'] = isset($v['table']) ? $v['table'] : '';
  315. $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
  316. }
  317. unset($v);
  318. $ids = [];
  319. $fields = array_keys($fieldsArr);
  320. foreach ($items as $k => $v)
  321. {
  322. foreach ($fields as $m => $n)
  323. {
  324. if (isset($v[$n]))
  325. {
  326. $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
  327. }
  328. }
  329. }
  330. $result = [];
  331. foreach ($fieldsArr as $k => $v)
  332. {
  333. if ($v['model'])
  334. {
  335. $model = new $v['model'];
  336. }
  337. else
  338. {
  339. $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
  340. }
  341. $primary = $v['primary'] ? $v['primary'] : $model->getPk();
  342. $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
  343. }
  344. foreach ($items as $k => &$v)
  345. {
  346. foreach ($fields as $m => $n)
  347. {
  348. if (isset($v[$n]))
  349. {
  350. $curr = array_flip(explode(',', $v[$n]));
  351. $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
  352. }
  353. }
  354. }
  355. return $items;
  356. }
  357. }
  358. if(!function_exists('formatNumber'))
  359. {
  360. /**
  361. * 格式化书籍字数
  362. */
  363. function formatNumber($string)
  364. {
  365. if(stristr($string,'万')){
  366. return $string;
  367. }
  368. $num = intval($string);
  369. if($num > 10000){
  370. $num = intval($string)/10000;
  371. return round($num,2).'万';
  372. }else{
  373. return $string;
  374. }
  375. }
  376. }
  377. if(!function_exists('replaceShortDomain'))
  378. {
  379. /**
  380. * 使用渠道商/代理商绑定的短链接域名替换默认短链接域名
  381. *
  382. * @author liues@dianzhong.com
  383. * @date 2018-08-16 16:18:23
  384. * @param string $source 默认短链接地址,如:
  385. * @param string $short_id 短链接域名
  386. * @return string
  387. */
  388. function replaceShortDomain($source, $short_id)
  389. {
  390. $host = model('ShortDomain')->getHostById($short_id);
  391. $source = empty($host) ? $source : sprintf("%s%s", $host, parse_url($source, PHP_URL_PATH));
  392. return $source;
  393. }
  394. }
  395. //下划线转驼峰
  396. if(!function_exists('camelizeArr')){
  397. function camelizeArr(array $arr)
  398. {
  399. if(is_array($arr)){
  400. $newArr = [];
  401. foreach ($arr as $key=>$value){
  402. if ($value instanceof \think\Model) {
  403. $value = $value->toArray();
  404. }
  405. $newKey = camelize($key);
  406. if(is_array($value)){
  407. $newArr[$newKey] = camelizeArr($value);
  408. }else{
  409. $newArr[$newKey] = $value;
  410. }
  411. }
  412. return $newArr;
  413. }
  414. return $arr;
  415. }
  416. }
  417. //下划线转驼峰
  418. if(!function_exists('camelize')){
  419. function camelize($uncamelized_words,$separator='_')
  420. {
  421. $uncamelized_words = $separator. str_replace($separator, " ", strtolower($uncamelized_words));
  422. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
  423. }
  424. }