common.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. <?php
  2. // 公共助手函数
  3. use Symfony\Component\VarExporter\VarExporter;
  4. use think\exception\HttpResponseException;
  5. use think\Response;
  6. if (!function_exists('__')) {
  7. /**
  8. * 获取语言变量值
  9. * @param string $name 语言变量名
  10. * @param array $vars 动态变量值
  11. * @param string $lang 语言
  12. * @return mixed
  13. */
  14. function __($name, $vars = [], $lang = '')
  15. {
  16. if (is_numeric($name) || !$name) {
  17. return $name;
  18. }
  19. if (!is_array($vars)) {
  20. $vars = func_get_args();
  21. array_shift($vars);
  22. $lang = '';
  23. }
  24. return \think\Lang::get($name, $vars, $lang);
  25. }
  26. }
  27. if (!function_exists('format_bytes')) {
  28. /**
  29. * 将字节转换为可读文本
  30. * @param int $size 大小
  31. * @param string $delimiter 分隔符
  32. * @param int $precision 小数位数
  33. * @return string
  34. */
  35. function format_bytes($size, $delimiter = '', $precision = 2)
  36. {
  37. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  38. for ($i = 0; $size >= 1024 && $i < 6; $i++) {
  39. $size /= 1024;
  40. }
  41. return round($size, $precision) . $delimiter . $units[$i];
  42. }
  43. }
  44. if (!function_exists('datetime')) {
  45. /**
  46. * 将时间戳转换为日期时间
  47. * @param int $time 时间戳
  48. * @param string $format 日期时间格式
  49. * @return string
  50. */
  51. function datetime($time, $format = 'Y-m-d H:i:s')
  52. {
  53. $time = is_numeric($time) ? $time : strtotime($time);
  54. return date($format, $time);
  55. }
  56. }
  57. if (!function_exists('human_date')) {
  58. /**
  59. * 获取语义化时间
  60. * @param int $time 时间
  61. * @param int $local 本地时间
  62. * @return string
  63. */
  64. function human_date($time, $local = null)
  65. {
  66. return \fast\Date::human($time, $local);
  67. }
  68. }
  69. if (!function_exists('cdnurl')) {
  70. /**
  71. * 获取上传资源的CDN的地址
  72. * @param string $url 资源相对地址
  73. * @param boolean $domain 是否显示域名 或者直接传入域名
  74. * @return string
  75. */
  76. function cdnurl($url, $domain = false)
  77. {
  78. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  79. $cdnurl = \think\Config::get('upload.cdnurl');
  80. $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
  81. if ($domain && !preg_match($regex, $url)) {
  82. $domain = is_bool($domain) ? request()->domain() : $domain;
  83. $url = $domain . $url;
  84. }
  85. return $url;
  86. }
  87. }
  88. if (!function_exists('is_really_writable')) {
  89. /**
  90. * 判断文件或文件夹是否可写
  91. * @param string $file 文件或目录
  92. * @return bool
  93. */
  94. function is_really_writable($file)
  95. {
  96. if (DIRECTORY_SEPARATOR === '/') {
  97. return is_writable($file);
  98. }
  99. if (is_dir($file)) {
  100. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  101. if (($fp = @fopen($file, 'ab')) === false) {
  102. return false;
  103. }
  104. fclose($fp);
  105. @chmod($file, 0777);
  106. @unlink($file);
  107. return true;
  108. } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
  109. return false;
  110. }
  111. fclose($fp);
  112. return true;
  113. }
  114. }
  115. if (!function_exists('rmdirs')) {
  116. /**
  117. * 删除文件夹
  118. * @param string $dirname 目录
  119. * @param bool $withself 是否删除自身
  120. * @return boolean
  121. */
  122. function rmdirs($dirname, $withself = true)
  123. {
  124. if (!is_dir($dirname)) {
  125. return false;
  126. }
  127. $files = new RecursiveIteratorIterator(
  128. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
  129. RecursiveIteratorIterator::CHILD_FIRST
  130. );
  131. foreach ($files as $fileinfo) {
  132. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  133. $todo($fileinfo->getRealPath());
  134. }
  135. if ($withself) {
  136. @rmdir($dirname);
  137. }
  138. return true;
  139. }
  140. }
  141. if (!function_exists('copydirs')) {
  142. /**
  143. * 复制文件夹
  144. * @param string $source 源文件夹
  145. * @param string $dest 目标文件夹
  146. */
  147. function copydirs($source, $dest)
  148. {
  149. if (!is_dir($dest)) {
  150. mkdir($dest, 0755, true);
  151. }
  152. foreach (
  153. $iterator = new RecursiveIteratorIterator(
  154. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  155. RecursiveIteratorIterator::SELF_FIRST
  156. ) as $item
  157. ) {
  158. if ($item->isDir()) {
  159. $sontDir = $dest . DS . $iterator->getSubPathName();
  160. if (!is_dir($sontDir)) {
  161. mkdir($sontDir, 0755, true);
  162. }
  163. } else {
  164. copy($item, $dest . DS . $iterator->getSubPathName());
  165. }
  166. }
  167. }
  168. }
  169. if (!function_exists('mb_ucfirst')) {
  170. function mb_ucfirst($string)
  171. {
  172. return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
  173. }
  174. }
  175. if (!function_exists('addtion')) {
  176. /**
  177. * 附加关联字段数据
  178. * @param array $items 数据列表
  179. * @param mixed $fields 渲染的来源字段
  180. * @return array
  181. */
  182. function addtion($items, $fields)
  183. {
  184. if (!$items || !$fields) {
  185. return $items;
  186. }
  187. $fieldsArr = [];
  188. if (!is_array($fields)) {
  189. $arr = explode(',', $fields);
  190. foreach ($arr as $k => $v) {
  191. $fieldsArr[$v] = ['field' => $v];
  192. }
  193. } else {
  194. foreach ($fields as $k => $v) {
  195. if (is_array($v)) {
  196. $v['field'] = isset($v['field']) ? $v['field'] : $k;
  197. } else {
  198. $v = ['field' => $v];
  199. }
  200. $fieldsArr[$v['field']] = $v;
  201. }
  202. }
  203. foreach ($fieldsArr as $k => &$v) {
  204. $v = is_array($v) ? $v : ['field' => $v];
  205. $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  206. $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
  207. $v['column'] = isset($v['column']) ? $v['column'] : 'name';
  208. $v['model'] = isset($v['model']) ? $v['model'] : '';
  209. $v['table'] = isset($v['table']) ? $v['table'] : '';
  210. $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
  211. }
  212. unset($v);
  213. $ids = [];
  214. $fields = array_keys($fieldsArr);
  215. foreach ($items as $k => $v) {
  216. foreach ($fields as $m => $n) {
  217. if (isset($v[$n])) {
  218. $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
  219. }
  220. }
  221. }
  222. $result = [];
  223. foreach ($fieldsArr as $k => $v) {
  224. if ($v['model']) {
  225. $model = new $v['model'];
  226. } else {
  227. $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
  228. }
  229. $primary = $v['primary'] ? $v['primary'] : $model->getPk();
  230. $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
  231. }
  232. foreach ($items as $k => &$v) {
  233. foreach ($fields as $m => $n) {
  234. if (isset($v[$n])) {
  235. $curr = array_flip(explode(',', $v[$n]));
  236. $linedata = array_intersect_key($result[$n], $curr);
  237. $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
  238. }
  239. }
  240. }
  241. return $items;
  242. }
  243. }
  244. if (!function_exists('var_export_short')) {
  245. /**
  246. * 使用短标签打印或返回数组结构
  247. * @param mixed $data
  248. * @param boolean $return 是否返回数据
  249. * @return string
  250. */
  251. function var_export_short($data, $return = true)
  252. {
  253. return var_export($data, $return);
  254. $replaced = [];
  255. $count = 0;
  256. //判断是否是对象
  257. if (is_resource($data) || is_object($data)) {
  258. return var_export($data, $return);
  259. }
  260. //判断是否有特殊的键名
  261. $specialKey = false;
  262. array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
  263. if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
  264. $specialKey = true;
  265. }
  266. });
  267. if ($specialKey) {
  268. return var_export($data, $return);
  269. }
  270. array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
  271. if (is_object($value) || is_resource($value)) {
  272. $replaced[$count] = var_export($value, true);
  273. $value = "##<{$count}>##";
  274. } else {
  275. if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
  276. $index = array_search($value, $replaced);
  277. if ($index === false) {
  278. $replaced[$count] = var_export($value, true);
  279. $value = "##<{$count}>##";
  280. } else {
  281. $value = "##<{$index}>##";
  282. }
  283. }
  284. }
  285. $count++;
  286. });
  287. $dump = var_export($data, true);
  288. $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
  289. $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
  290. $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
  291. $dump = preg_replace('#\)$#', "]", $dump); //End
  292. if ($replaced) {
  293. $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
  294. return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
  295. }, $dump);
  296. }
  297. if ($return === true) {
  298. return $dump;
  299. } else {
  300. echo $dump;
  301. }
  302. }
  303. }
  304. if (!function_exists('letter_avatar')) {
  305. /**
  306. * 首字母头像
  307. * @param $text
  308. * @return string
  309. */
  310. function letter_avatar($text)
  311. {
  312. $total = unpack('L', hash('adler32', $text, true))[1];
  313. $hue = $total % 360;
  314. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  315. $bg = "rgb({$r},{$g},{$b})";
  316. $color = "#ffffff";
  317. $first = mb_strtoupper(mb_substr($text, 0, 1));
  318. $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" dominant-baseline="central">' . $first . '</text></svg>');
  319. $value = 'data:image/svg+xml;base64,' . $src;
  320. return $value;
  321. }
  322. }
  323. if (!function_exists('hsv2rgb')) {
  324. function hsv2rgb($h, $s, $v)
  325. {
  326. $r = $g = $b = 0;
  327. $i = floor($h * 6);
  328. $f = $h * 6 - $i;
  329. $p = $v * (1 - $s);
  330. $q = $v * (1 - $f * $s);
  331. $t = $v * (1 - (1 - $f) * $s);
  332. switch ($i % 6) {
  333. case 0:
  334. $r = $v;
  335. $g = $t;
  336. $b = $p;
  337. break;
  338. case 1:
  339. $r = $q;
  340. $g = $v;
  341. $b = $p;
  342. break;
  343. case 2:
  344. $r = $p;
  345. $g = $v;
  346. $b = $t;
  347. break;
  348. case 3:
  349. $r = $p;
  350. $g = $q;
  351. $b = $v;
  352. break;
  353. case 4:
  354. $r = $t;
  355. $g = $p;
  356. $b = $v;
  357. break;
  358. case 5:
  359. $r = $v;
  360. $g = $p;
  361. $b = $q;
  362. break;
  363. }
  364. return [
  365. floor($r * 255),
  366. floor($g * 255),
  367. floor($b * 255)
  368. ];
  369. }
  370. }
  371. if (!function_exists('check_nav_active')) {
  372. /**
  373. * 检测会员中心导航是否高亮
  374. */
  375. function check_nav_active($url, $classname = 'active')
  376. {
  377. $auth = \app\common\library\Auth::instance();
  378. $requestUrl = $auth->getRequestUri();
  379. $url = ltrim($url, '/');
  380. return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
  381. }
  382. }
  383. if (!function_exists('check_cors_request')) {
  384. /**
  385. * 跨域检测
  386. */
  387. function check_cors_request()
  388. {
  389. if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
  390. $info = parse_url($_SERVER['HTTP_ORIGIN']);
  391. $domainArr = explode(',', config('fastadmin.cors_request_domain'));
  392. $domainArr[] = request()->host(true);
  393. if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
  394. header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
  395. } else {
  396. $response = Response::create('跨域检测无效', 'html', 403);
  397. throw new HttpResponseException($response);
  398. }
  399. header('Access-Control-Allow-Credentials: true');
  400. header('Access-Control-Max-Age: 86400');
  401. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  402. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
  403. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  404. }
  405. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  406. header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  407. }
  408. $response = Response::create('', 'html');
  409. throw new HttpResponseException($response);
  410. }
  411. }
  412. }
  413. }
  414. if (!function_exists('xss_clean')) {
  415. /**
  416. * 清理XSS
  417. */
  418. function xss_clean($content, $is_image = false)
  419. {
  420. return \app\common\library\Security::instance()->xss_clean($content, $is_image);
  421. }
  422. }
  423. if (!function_exists('check_ip_allowed')) {
  424. /**
  425. * 检测IP是否允许
  426. * @param string $ip IP地址
  427. */
  428. function check_ip_allowed($ip = null)
  429. {
  430. $ip = is_null($ip) ? request()->ip() : $ip;
  431. $forbiddenipArr = config('site.forbiddenip');
  432. $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
  433. $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
  434. if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
  435. $response = Response::create('请求无权访问', 'html', 403);
  436. throw new HttpResponseException($response);
  437. }
  438. }
  439. }
  440. if (!function_exists('build_suffix_image')) {
  441. /**
  442. * 生成文件后缀图片
  443. * @param string $suffix 后缀
  444. * @param null $background
  445. * @return string
  446. */
  447. function build_suffix_image($suffix, $background = null)
  448. {
  449. $suffix = mb_substr(strtoupper($suffix), 0, 4);
  450. $total = unpack('L', hash('adler32', $suffix, true))[1];
  451. $hue = $total % 360;
  452. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  453. $background = $background ? $background : "rgb({$r},{$g},{$b})";
  454. $icon = <<<EOT
  455. <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
  456. <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
  457. <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
  458. <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
  459. <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
  460. <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
  461. <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
  462. </svg>
  463. EOT;
  464. return $icon;
  465. }
  466. }
  467. //我的
  468. //结果集信息里,生日转换年龄
  469. function list_birthday_age($list){
  470. if(!$list || empty($list)){
  471. return $list;
  472. }
  473. foreach($list as $vo => $info){
  474. $list[$vo]['age'] = birthtime_to_age($info['birthday']);
  475. }
  476. return $list;
  477. }
  478. //结果集信息里,多个字段需要增加domain_cdnurl
  479. function list_domain_image($list,$field){
  480. if(!$list || empty($list)){
  481. return $list;
  482. }
  483. foreach($list as $vo => $info){
  484. $list[$vo] = info_domain_image($info,$field);
  485. }
  486. return $list;
  487. }
  488. //单条信息里,多个字段需要增加domain_cdnurl
  489. //支持image,images
  490. function info_domain_image($data,$field){
  491. if(!$data || empty($data)){
  492. return $data;
  493. }
  494. foreach($data as $key => $val){
  495. if(in_array($key,$field)){
  496. $more = strpos($key,'images');
  497. $data[$key] = one_domain_image($val,$more);
  498. }
  499. }
  500. return $data;
  501. }
  502. //支持单个字段,需要增加domain_cdnurl
  503. //支持image,images
  504. function one_domain_image($one,$more = false){
  505. if(!$one){
  506. return $one;
  507. }
  508. if(strpos($one,',') || $more !== false){
  509. //逗号隔开的多个图片
  510. $one = explode(',',$one);
  511. foreach($one as $k => $v){
  512. $one[$k] = localpath_to_netpath($v);
  513. }
  514. // $one = implode(',',$one);
  515. }else{
  516. $one = localpath_to_netpath($one);
  517. }
  518. return $one;
  519. }
  520. //本地地址转换为网络地址
  521. function localpath_to_netpath($path)
  522. {
  523. if (empty($path)) {
  524. return '';
  525. } elseif (strrpos($path, 'http') !== false) {
  526. return $path;
  527. } else {
  528. return config('domain_cdnurl') . str_replace("\\", "/", $path);
  529. }
  530. }
  531. //秒 转换 日月分
  532. function Sec2Time($time){
  533. if(is_numeric($time)){
  534. $value = array(
  535. 'years' => 0, 'days' => 0, 'hours' => 0,
  536. 'minutes' => 0, 'seconds' => 0,
  537. );
  538. /*if($time >= 31556926){
  539. $value['years'] = floor($time/31556926);
  540. $time = ($time%31556926);
  541. }*/
  542. if($time >= 86400){
  543. $value['days'] = floor($time/86400);
  544. $time = ($time%86400);
  545. }
  546. if($time >= 3600){
  547. $value['hours'] = floor($time/3600);
  548. $time = ($time%3600);
  549. }
  550. if($time >= 60){
  551. $value['minutes'] = floor($time/60);
  552. $time = ($time%60);
  553. }
  554. $value['seconds'] = floor($time);
  555. //return (array) $value;
  556. //$t=$value['years'] .'年'. $value['days'] .'天'.' '. $value['hours'] .'小时'. $value['minutes'] .'分'.$value['seconds'].'秒';
  557. $t = $value['days'] .'天' . $value['hours'] .'小时'. $value['minutes'] .'分';
  558. return $t;
  559. }else{
  560. return '0天';
  561. }
  562. }
  563. //生日转年龄
  564. function birthtime_to_age($birthtime){
  565. // $birthtime = strtotime('1990-11-06');
  566. if(!$birthtime){
  567. return 0;
  568. }
  569. list($y1,$m1,$d1) = explode("-",date("Y-m-d",$birthtime));
  570. list($y2,$m2,$d2) = explode("-",date("Y-m-d",time()));
  571. $age = $y2 - $y1;
  572. if((int)($m2.$d2) < (int)($m1.$d1))
  573. {$age -= 1;}
  574. if($age < 0){
  575. $age = 0;
  576. }
  577. return $age;
  578. }
  579. if(!function_exists('mk_dir')) {
  580. /**
  581. * 新建目录
  582. */
  583. function mk_dir($dir, $mode = 0770, $tmp = true)
  584. {
  585. $mode = 0770;
  586. if(is_file($dir)) {
  587. //有同名文件
  588. return false;
  589. } else {
  590. if(!is_dir($dir)) { //目录不存在
  591. $dir_up = dirname($dir); //上级目录
  592. if(!is_dir($dir_up)) {
  593. //上级不存在
  594. $rs = @mk_dir($dir_up);
  595. if(!$rs) return false;
  596. }
  597. $rs = @mkdir($dir, $mode); //新建
  598. if(!$rs) return false;
  599. $rs = @chmod($dir, $mode); //改权限
  600. if(!$rs) return false;
  601. }
  602. return true;
  603. }
  604. }
  605. }
  606. /**
  607. * 在线支付日志
  608. */
  609. function filePut($info,$text='notify.txt'){
  610. if(is_array($info)) {
  611. $info = json_encode($info, JSON_UNESCAPED_UNICODE);
  612. }
  613. if(!file_exist(RUNTIME_PATH.'paylog/')) {
  614. mk_dir(RUNTIME_PATH.'paylog/');
  615. }
  616. $file = RUNTIME_PATH.'paylog/'.$text;
  617. touch_file($file);
  618. file_put_contents($file, "\r\n".date('Y-m-d H:i:s').' '.$info, FILE_APPEND);
  619. }
  620. if(!function_exists('touch_file')) {
  621. /**
  622. * 新建文件
  623. */
  624. function touch_file($file = '')
  625. {
  626. if($file) {
  627. if(!file_exists($file)) {
  628. @touch($file);
  629. @chmod($file, 0770);
  630. }
  631. }
  632. }
  633. }
  634. if(!function_exists('file_exist')) {
  635. /**
  636. * 检测文件是否存在
  637. * @param $file
  638. * @return string
  639. */
  640. function file_exist($file)
  641. {
  642. if(false === strpos($file, 'http')) { //本地文件
  643. if(0 === strpos($file, '/upload')) {
  644. $file = '.'.$file;
  645. }
  646. return file_exists($file);
  647. } else { //网络文件
  648. $ch = curl_init();
  649. curl_setopt($ch, CURLOPT_URL, $file);
  650. curl_setopt($ch, CURLOPT_TIMEOUT, 2);
  651. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  652. curl_exec($ch);
  653. $status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
  654. curl_close($ch);
  655. if(in_array(substr($status, 0, 1), [2, 3])) {
  656. return true;
  657. } else {
  658. return false;
  659. }
  660. }
  661. }
  662. }
  663. /**
  664. * 发起HTTPS请求
  665. */
  666. function curl_post($url, $data, $header = '', $timeOut = 0)
  667. {
  668. //初始化curl
  669. $ch = curl_init();
  670. //参数设置
  671. curl_setopt($ch, CURLOPT_URL, $url);
  672. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  673. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  674. curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
  675. curl_setopt($ch, CURLOPT_HEADER, 0);
  676. curl_setopt($ch, CURLOPT_POST, 1);
  677. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  678. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  679. if($header != '') {
  680. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  681. }
  682. $result = curl_exec($ch);
  683. //连接失败
  684. if($result == FALSE) {
  685. //\think\Log::record('[ CURL ] ERROR ' . curl_error($ch)."\n".var_export(debug_backtrace(), true)."\n", 'error');
  686. }
  687. curl_close($ch);
  688. return $result;
  689. }
  690. /**
  691. * 发起HTTP GET请求
  692. */
  693. function curl_get($url)
  694. {
  695. $oCurl = curl_init();
  696. if(stripos($url, "https://") !== FALSE) {
  697. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  698. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  699. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  700. }
  701. curl_setopt($oCurl, CURLOPT_TIMEOUT, 3);
  702. curl_setopt($oCurl, CURLOPT_URL, $url);
  703. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
  704. $sContent = curl_exec($oCurl);
  705. $aStatus = curl_getinfo($oCurl);
  706. $error = curl_error($oCurl);
  707. curl_close($oCurl);
  708. if($error) {
  709. $sContent = file_get_contents($url);
  710. return $sContent;
  711. }
  712. if(intval($aStatus["http_code"]) == 200) {
  713. return $sContent;
  714. } else {
  715. return false;
  716. }
  717. }
  718. //创建订单号
  719. function createUniqueNo($prifix = 'P',$id = 0)
  720. {
  721. $s = 0;
  722. $ms = 0;
  723. list($ms, $s) = explode(' ', microtime());
  724. $ms = substr($ms, 2, 6); //获取微妙
  725. $rt = $prifix.date('ymdHis', $s).$ms.rand(10, 99).$id; //年月日时分秒.用户id对10取余.微秒
  726. return $rt;
  727. }
  728. //下载远程图片 到指定目录
  729. function downloadfile($file_url, $path = '', $save_file_name = '')
  730. {
  731. $basepath = '/uploaded/';
  732. if ($path) {
  733. $basepath = $basepath . $path . '/';
  734. }
  735. $basepath = $basepath . date('Ymd');
  736. $dir_path = ROOT_PATH . '/public' . $basepath;
  737. if (!is_dir($dir_path)) {
  738. mkdir($dir_path, 0777, true);
  739. }
  740. $ch = curl_init();
  741. curl_setopt($ch, CURLOPT_URL, $file_url);
  742. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  743. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  744. $file = curl_exec($ch);
  745. curl_close($ch);
  746. //传入保存文件的名称
  747. $filename = $save_file_name ?: pathinfo($file_url, PATHINFO_BASENAME);
  748. $resource = fopen($dir_path. '/'. $filename, 'a');
  749. fwrite($resource, $file);
  750. fclose($resource);
  751. return $dir_path . '/' . $filename;
  752. }
  753. //获取视频时长
  754. function get_video_seconds($netpath = ''){
  755. $local_url = downloadfile($netpath,'video','');
  756. $playtime = 0;
  757. Vendor('getid3.getid3.getid3');
  758. $getID3 = new \getID3();
  759. $fileinfo = $getID3->analyze($local_url);
  760. if(isset($fileinfo['playtime_seconds'])){
  761. $playtime = (int)$fileinfo['playtime_seconds'];
  762. }
  763. return $playtime;
  764. }
  765. //post接收参数中心,只接非必须
  766. function request_post_hub($field_array = [],$required = [],$noempty = []){
  767. if(empty($field_array)){
  768. return [];
  769. }
  770. $data = [];
  771. foreach($field_array as $key => $field){
  772. //接收
  773. if(!request()->has($field,'post')){
  774. continue;
  775. }
  776. $newone = request()->post($field);
  777. //追加
  778. $data[$field] = $newone;
  779. }
  780. //必传
  781. if(!empty($required)){
  782. foreach($required as $k => $mustone){
  783. if(!isset($data[$mustone])){
  784. return $mustone.' required';
  785. }
  786. }
  787. }
  788. //必传,且不能空
  789. if(!empty($noempty)){
  790. foreach($noempty as $havekey => $haveone){
  791. if(!isset($data[$havekey]) || empty($data[$havekey])){
  792. return $haveone.' 必填';
  793. }
  794. }
  795. }
  796. return $data;
  797. }