common.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. <?php
  2. // 公共助手函数
  3. use PhpOffice\PhpSpreadsheet\IOFactory;
  4. if (!function_exists('__')) {
  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. }
  17. if (!is_array($vars)) {
  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. * @param int $size 大小
  29. * @param string $delimiter 分隔符
  30. * @return string
  31. */
  32. function format_bytes($size, $delimiter = '')
  33. {
  34. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  35. for ($i = 0; $size >= 1024 && $i < 6; $i++) {
  36. $size /= 1024;
  37. }
  38. return round($size, 2) . $delimiter . $units[$i];
  39. }
  40. }
  41. if (!function_exists('datetime')) {
  42. /**
  43. * 将时间戳转换为日期时间
  44. * @param int $time 时间戳
  45. * @param string $format 日期时间格式
  46. * @return string
  47. */
  48. function datetime($time, $format = 'Y-m-d H:i:s')
  49. {
  50. $time = is_numeric($time) ? $time : strtotime($time);
  51. return date($format, $time);
  52. }
  53. }
  54. if (!function_exists('human_date')) {
  55. /**
  56. * 获取语义化时间
  57. * @param int $time 时间
  58. * @param int $local 本地时间
  59. * @return string
  60. */
  61. function human_date($time, $local = null)
  62. {
  63. return \fast\Date::human($time, $local);
  64. }
  65. }
  66. if (!function_exists('cdnurl')) {
  67. /**
  68. * 获取上传资源的CDN的地址
  69. * @param string $url 资源相对地址
  70. * @param boolean $domain 是否显示域名 或者直接传入域名
  71. * @return string
  72. */
  73. function cdnurl($url, $domain = false)
  74. {
  75. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  76. $url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
  77. if ($domain && !preg_match($regex, $url)) {
  78. $domain = is_bool($domain) ? request()->domain() : $domain;
  79. $url = $domain . $url;
  80. }
  81. return $url;
  82. }
  83. }
  84. if (!function_exists('is_really_writable')) {
  85. /**
  86. * 判断文件或文件夹是否可写
  87. * @param string $file 文件或目录
  88. * @return bool
  89. */
  90. function is_really_writable($file)
  91. {
  92. if (DIRECTORY_SEPARATOR === '/') {
  93. return is_writable($file);
  94. }
  95. if (is_dir($file)) {
  96. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  97. if (($fp = @fopen($file, 'ab')) === false) {
  98. return false;
  99. }
  100. fclose($fp);
  101. @chmod($file, 0777);
  102. @unlink($file);
  103. return true;
  104. } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
  105. return false;
  106. }
  107. fclose($fp);
  108. return true;
  109. }
  110. }
  111. if (!function_exists('rmdirs')) {
  112. /**
  113. * 删除文件夹
  114. * @param string $dirname 目录
  115. * @param bool $withself 是否删除自身
  116. * @return boolean
  117. */
  118. function rmdirs($dirname, $withself = true)
  119. {
  120. if (!is_dir($dirname)) {
  121. return false;
  122. }
  123. $files = new RecursiveIteratorIterator(
  124. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
  125. RecursiveIteratorIterator::CHILD_FIRST
  126. );
  127. foreach ($files as $fileinfo) {
  128. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  129. $todo($fileinfo->getRealPath());
  130. }
  131. if ($withself) {
  132. @rmdir($dirname);
  133. }
  134. return true;
  135. }
  136. }
  137. if (!function_exists('copydirs')) {
  138. /**
  139. * 复制文件夹
  140. * @param string $source 源文件夹
  141. * @param string $dest 目标文件夹
  142. */
  143. function copydirs($source, $dest)
  144. {
  145. if (!is_dir($dest)) {
  146. mkdir($dest, 0755, true);
  147. }
  148. foreach (
  149. $iterator = new RecursiveIteratorIterator(
  150. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  151. RecursiveIteratorIterator::SELF_FIRST
  152. ) as $item
  153. ) {
  154. if ($item->isDir()) {
  155. $sontDir = $dest . DS . $iterator->getSubPathName();
  156. if (!is_dir($sontDir)) {
  157. mkdir($sontDir, 0755, true);
  158. }
  159. } else {
  160. copy($item, $dest . DS . $iterator->getSubPathName());
  161. }
  162. }
  163. }
  164. }
  165. if (!function_exists('mb_ucfirst')) {
  166. function mb_ucfirst($string)
  167. {
  168. return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
  169. }
  170. }
  171. if (!function_exists('addtion')) {
  172. /**
  173. * 附加关联字段数据
  174. * @param array $items 数据列表
  175. * @param mixed $fields 渲染的来源字段
  176. * @return array
  177. */
  178. function addtion($items, $fields)
  179. {
  180. if (!$items || !$fields) {
  181. return $items;
  182. }
  183. $fieldsArr = [];
  184. if (!is_array($fields)) {
  185. $arr = explode(',', $fields);
  186. foreach ($arr as $k => $v) {
  187. $fieldsArr[$v] = ['field' => $v];
  188. }
  189. } else {
  190. foreach ($fields as $k => $v) {
  191. if (is_array($v)) {
  192. $v['field'] = isset($v['field']) ? $v['field'] : $k;
  193. } else {
  194. $v = ['field' => $v];
  195. }
  196. $fieldsArr[$v['field']] = $v;
  197. }
  198. }
  199. foreach ($fieldsArr as $k => &$v) {
  200. $v = is_array($v) ? $v : ['field' => $v];
  201. $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  202. $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
  203. $v['column'] = isset($v['column']) ? $v['column'] : 'name';
  204. $v['model'] = isset($v['model']) ? $v['model'] : '';
  205. $v['table'] = isset($v['table']) ? $v['table'] : '';
  206. $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
  207. }
  208. unset($v);
  209. $ids = [];
  210. $fields = array_keys($fieldsArr);
  211. foreach ($items as $k => $v) {
  212. foreach ($fields as $m => $n) {
  213. if (isset($v[$n])) {
  214. $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
  215. }
  216. }
  217. }
  218. $result = [];
  219. foreach ($fieldsArr as $k => $v) {
  220. if ($v['model']) {
  221. $model = new $v['model'];
  222. } else {
  223. $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
  224. }
  225. $primary = $v['primary'] ? $v['primary'] : $model->getPk();
  226. $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
  227. }
  228. foreach ($items as $k => &$v) {
  229. foreach ($fields as $m => $n) {
  230. if (isset($v[$n])) {
  231. $curr = array_flip(explode(',', $v[$n]));
  232. $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
  233. }
  234. }
  235. }
  236. return $items;
  237. }
  238. }
  239. if (!function_exists('var_export_short')) {
  240. /**
  241. * 返回打印数组结构
  242. * @param string $var 数组
  243. * @param string $indent 缩进字符
  244. * @return string
  245. */
  246. function var_export_short($var, $indent = "")
  247. {
  248. switch (gettype($var)) {
  249. case "string":
  250. return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
  251. case "array":
  252. $indexed = array_keys($var) === range(0, count($var) - 1);
  253. $r = [];
  254. foreach ($var as $key => $value) {
  255. $r[] = "$indent "
  256. . ($indexed ? "" : var_export_short($key) . " => ")
  257. . var_export_short($value, "$indent ");
  258. }
  259. return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
  260. case "boolean":
  261. return $var ? "TRUE" : "FALSE";
  262. default:
  263. return var_export($var, true);
  264. }
  265. }
  266. }
  267. if (!function_exists('letter_avatar')) {
  268. /**
  269. * 首字母头像
  270. * @param $text
  271. * @return string
  272. */
  273. function letter_avatar($text)
  274. {
  275. $total = unpack('L', hash('adler32', $text, true))[1];
  276. $hue = $total % 360;
  277. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  278. $bg = "rgb({$r},{$g},{$b})";
  279. $color = "#ffffff";
  280. $first = mb_strtoupper(mb_substr($text, 0, 1));
  281. $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
  282. $value = 'data:image/svg+xml;base64,' . $src;
  283. return $value;
  284. }
  285. }
  286. if (!function_exists('hsv2rgb')) {
  287. function hsv2rgb($h, $s, $v)
  288. {
  289. $r = $g = $b = 0;
  290. $i = floor($h * 6);
  291. $f = $h * 6 - $i;
  292. $p = $v * (1 - $s);
  293. $q = $v * (1 - $f * $s);
  294. $t = $v * (1 - (1 - $f) * $s);
  295. switch ($i % 6) {
  296. case 0:
  297. $r = $v;
  298. $g = $t;
  299. $b = $p;
  300. break;
  301. case 1:
  302. $r = $q;
  303. $g = $v;
  304. $b = $p;
  305. break;
  306. case 2:
  307. $r = $p;
  308. $g = $v;
  309. $b = $t;
  310. break;
  311. case 3:
  312. $r = $p;
  313. $g = $q;
  314. $b = $v;
  315. break;
  316. case 4:
  317. $r = $t;
  318. $g = $p;
  319. $b = $v;
  320. break;
  321. case 5:
  322. $r = $v;
  323. $g = $p;
  324. $b = $q;
  325. break;
  326. }
  327. return [
  328. floor($r * 255),
  329. floor($g * 255),
  330. floor($b * 255)
  331. ];
  332. }
  333. }
  334. if (!function_exists('makeNew16Uid')) {
  335. function makeNew16Uid()
  336. {
  337. return substr(md5(uniqid(rand(),1)), 8, 16);;
  338. }
  339. }
  340. if (!function_exists('read_excel')) {
  341. /**
  342. * 读取excel内容
  343. * @param $filename
  344. * @return array
  345. * @throws \PhpOffice\PhpSpreadsheet\Exception
  346. * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
  347. * @author matielong
  348. */
  349. function read_excel($filename)
  350. {
  351. //设置excel格式
  352. $reader = IOFactory::createReader('Xlsx');
  353. //载入excel文件
  354. $excel = $reader->load($filename);
  355. //读取第一张表
  356. $sheet = $excel->getSheet(0);
  357. //获取总行数
  358. $row_num = $sheet->getHighestRow();
  359. //获取总列数
  360. $col_num = $sheet->getHighestColumn();
  361. $data = []; //数组形式获取表格数据
  362. for($col='A';$col<=$col_num;$col++)
  363. {
  364. //从第二行开始,去除表头(若无表头则从第一行开始)
  365. for($row=2;$row<=$row_num;$row++)
  366. {
  367. $data[$row-2][] = $sheet->getCell($col.$row)->getValue();
  368. }
  369. }
  370. return $data;
  371. }
  372. }