Helper.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. <?php
  2. namespace PhpLife\Frame;
  3. use PhpLife\App\Admin\Config\Proxy;
  4. use PhpLife\Library\Webp;
  5. class Helper
  6. {
  7. /*
  8. * 检测链接是否是SSL连接
  9. * @return bool
  10. */
  11. public static function isSSL()
  12. {
  13. if (!isset($_SERVER['HTTPS']))
  14. return false;
  15. if ($_SERVER['HTTPS'] === 1) { //Apache
  16. return true;
  17. } elseif ($_SERVER['HTTPS'] === 'on') { //IIS
  18. return true;
  19. } elseif ($_SERVER['SERVER_PORT'] == 443) { //其他
  20. return true;
  21. }
  22. return false;
  23. }
  24. /**
  25. * 随机数生成器
  26. */
  27. public static function random()
  28. {
  29. return md5(microtime() . rand() . uniqid() . $_SERVER['REMOTE_ADDR']);
  30. }
  31. /**
  32. * 简单验证email
  33. * @param $email
  34. * @return bool
  35. */
  36. public static function validateEmail($email)
  37. {
  38. $email = trim($email);
  39. if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) {
  40. return False;
  41. }
  42. return True;
  43. }
  44. /**
  45. * 检查文件是否存在
  46. * @todo 检查content-Type和文件大小
  47. * @param $url
  48. * @param string $extension
  49. * @param bool $checkHeader 检查头信息
  50. * @return bool
  51. */
  52. public static function validateFile($url, $extension = '', $checkHeader = false)
  53. {
  54. if (!$url) {
  55. return false;
  56. }
  57. $urlInfo = parse_url($url);
  58. if ($urlInfo['scheme'] !== 'http' && $urlInfo['scheme'] !== 'https') {
  59. return false;
  60. }
  61. // 检查后缀
  62. if ($extension) {
  63. $pathInfo = pathinfo($url);
  64. if ($pathInfo['extension'] != trim($extension, '.')) {
  65. return false;
  66. }
  67. }
  68. // 检查Http头信息
  69. if ($checkHeader) {
  70. $result = get_headers($url);
  71. $httpCode = explode(' ', $result[0]);
  72. $httpCode = $httpCode[1];
  73. if ($httpCode != 200) {
  74. return false;
  75. }
  76. }
  77. return true;
  78. }
  79. /**
  80. * 对象转换
  81. * @param object $target
  82. * @param object $source
  83. * @return object
  84. */
  85. public static function objectMerge($target, $source)
  86. {
  87. if (!is_object($target)) {
  88. return null;
  89. }
  90. $result = clone $target;
  91. $source = (array)$source;
  92. foreach ($source as $k => $v) {
  93. $result->{$k} = $v;
  94. }
  95. return $result;
  96. }
  97. /**
  98. * 去除首尾全角及半角空格,多个空格合并为一个
  99. * @param type $str
  100. * @return string
  101. */
  102. public static function trimAndMerge($str)
  103. {
  104. $str = preg_replace('/( | )+/', ' ', $str);
  105. return trim(preg_replace("/^ +| +$/ ", " ", $str));
  106. }
  107. /**
  108. * 去除首尾空格,包含全角空格
  109. */
  110. public static function trim($str)
  111. {
  112. //$str = trim($str,"  \t\n\r\0\x0B");
  113. $str = mb_ereg_replace('(^( | )+|( | )+$)', '', $str);
  114. return $str;
  115. }
  116. /**
  117. * 转换为友好时间
  118. * @param int|string $timestamp
  119. * @return string
  120. */
  121. public static function convertToFriendlyTime($timestamp)
  122. {
  123. if (!is_numeric($timestamp)) {
  124. $timestamp = strtotime($timestamp);
  125. }
  126. $now = time();
  127. $interval = abs($now - $timestamp);
  128. $today = strtotime(date("Ymd"));
  129. $tomorrow = strtotime(date("Ymd", $now + 86400));
  130. $thisYear = strtotime(date("Y-01-01 00:00"));
  131. if ($interval < 60) {
  132. if ($interval < 10) {
  133. $interval = 10;
  134. }
  135. $string = $interval . "秒前";
  136. } else if ($interval < 3600) {
  137. $string = floor($interval / 60) . '分钟前';
  138. } else if ($today < $timestamp AND $timestamp < $tomorrow) {
  139. $string = '今天' . date('H:i', $timestamp);
  140. } else if ($thisYear < $timestamp) {
  141. $string = date('n月j日', $timestamp);
  142. } else {
  143. $string = date('Y-m-d', $timestamp);
  144. }
  145. return $string;
  146. }
  147. /**
  148. * 写入ini文件
  149. * @param type $path
  150. * @param type $data
  151. * @return type
  152. */
  153. public static function writeIniFile($path, $data)
  154. {
  155. $content = null;
  156. foreach ($data as $key => $item) {
  157. if (is_array($item)) {
  158. $content .= "\n[{$key}]\n";
  159. foreach ($item as $k => $v) {
  160. if (is_numeric($v) || is_bool($v)) {
  161. $v = '"' . $v . '"';
  162. }
  163. $content .= "{$k} = {$v}\n";
  164. }
  165. } else {
  166. if (is_numeric($item) || is_bool($item)) {
  167. $item = '"' . $item . '"';
  168. }
  169. $content .= "{$key} = {$item}\n";
  170. }
  171. }
  172. return file_put_contents($path, $content);
  173. }
  174. public static function checkField($input, $fileds)
  175. {
  176. $input = (array)$input;
  177. $output = array();
  178. foreach ($input as $k => $v) {
  179. if (in_array($k, $fileds)) {
  180. $output[$k] = $v;
  181. }
  182. }
  183. return $output;
  184. }
  185. /**
  186. * 递归合并数组,兼容 数字类型
  187. * @param array $target
  188. * @param mixed $source
  189. * @return array
  190. * @author daniel@danielsmedegaardbuus.dk
  191. * http://www.php.net/manual/zh/function.array-merge-recursive.php
  192. */
  193. public static function arrayMerge(&$target, &$source)
  194. {
  195. if (empty($target) OR !is_array($target)) {
  196. $target = array();
  197. }
  198. if (empty($source) OR !is_array($source)) {
  199. $source = array();
  200. }
  201. $merged = $target;
  202. foreach ($source as $key => &$value) {
  203. if (is_array($value) && isset($merged [$key]) && is_array($merged [$key])) {
  204. $merged [$key] = self::arrayMerge($merged [$key], $value);
  205. } else if (is_object($value) AND is_object($merged[$key])) {
  206. $value = (array)$value;
  207. foreach ($value as $k => $v) {
  208. $merged [$key]->{$k} = $v;
  209. }
  210. } else {
  211. $merged [$key] = $value;
  212. }
  213. }
  214. return $merged;
  215. }
  216. /**
  217. * 链接添加a标签
  218. * @param string $content
  219. * @return string
  220. */
  221. public static function urlAddHref($string)
  222. {
  223. preg_match_all('@(https?://([-\w\.]+)+(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)?)@', $string, $matches, PREG_SET_ORDER);
  224. foreach ($matches as $matche) {
  225. $url = $matche [0];
  226. }
  227. if ($url) {
  228. $newUrl = '<a href = "' . $url . '">' . $url . '</a>';
  229. $string = str_replace($url, $newUrl, $string);
  230. }
  231. return $string;
  232. }
  233. /**
  234. * 计算字符串长度,汉字按两个字符
  235. * @param string $str
  236. * @return int
  237. */
  238. public static function strlenUtf8($str)
  239. {
  240. $length = strlen(preg_replace('/[u4e00-u9fa5 ]/', '', $str));
  241. if ($length) {
  242. return strlen($str) - $length + intval($length / 3) * 2;
  243. } else {
  244. return strlen($str);
  245. }
  246. }
  247. public static function makeSemiangle($str)
  248. {
  249. if (!isset($str[0])) {
  250. return null;
  251. }
  252. $arr = array(
  253. '0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4',
  254. '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9',
  255. 'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E',
  256. 'F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J',
  257. 'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O',
  258. 'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T',
  259. 'U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y',
  260. 'Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd',
  261. 'e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i',
  262. 'j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n',
  263. 'o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's',
  264. 't' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x',
  265. 'y' => 'y', 'z' => 'z',
  266. '(' => '(', ')' => ')', '〔' => '[', '〕' => ']', '【' => '[',
  267. '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
  268. '‘' => '[', '’' => ']', '{' => '{', '}' => '}', '《' => '<',
  269. '》' => '>', '%' => '%', '+' => '+', '—' => '-', '-' => '-',
  270. '~' => '-', ':' => ':', '。' => '.', '、' => ',', ',' => '.',
  271. ';' => ',', '?' => '?', '!' => '!', '…' => '-', '‖' => '|',
  272. '”' => '"', '’' => '`', '‘' => '`', '|' => '|', '〃' => '"',
  273. ' ' => ' ', '@' => '@', '、' => '.',);
  274. return strtr($str, $arr);
  275. }
  276. /**
  277. * 获取子串,替换全角 汉字2字符,英文1字符,数字判断
  278. */
  279. public static function getUtf8SubStr($str, $len)
  280. {
  281. $str = self::makeSemiangle($str);
  282. return self::getRawUtf8SubStr($str, $len);
  283. }
  284. /**
  285. * 获取子串,不替换全角
  286. */
  287. public static function getRawUtf8SubStr($str, $len)
  288. {
  289. if ((strlen($str) + mb_strlen($str, 'UTF8')) / 2 <= $len) {
  290. return $str;
  291. } else {
  292. $temp_len = 0;
  293. $temp_str = '';
  294. for ($i = 0; $i < mb_strlen($str, 'UTF-8'); $i++) {
  295. if ($temp_len < $len) {
  296. $tmp = mb_substr($str, $i, 1, 'UTF-8');
  297. $temp_str .= $tmp;
  298. $temp_len += ((strlen($tmp) + mb_strlen($tmp, 'UTF-8')) / 2);
  299. }
  300. }
  301. return $temp_str;
  302. }
  303. }
  304. /**
  305. * 从一个数组里面取出以指定key为中心的偏移, 九宫格
  306. */
  307. public static function getCenterFromList($list, $key, $length = 9)
  308. {
  309. $list = array_values($list);
  310. $list = array_unique($list);
  311. $ids = array_flip($list);
  312. $current = $ids[$key];
  313. $total = count($list);
  314. $first = $current - $length > 0 ? $current - $length : 0;
  315. $last = $current + $length < $total - 1 ? $current + $length : $total - 1;
  316. $limit = $last - $first + 1;
  317. return array_slice($list, $first, $limit);
  318. }
  319. public static function safeHtmlEncodeString($str)
  320. {
  321. $str = htmlspecialchars_decode($str);
  322. return htmlspecialchars($str);
  323. }
  324. /**
  325. * 删除数据中指定的值
  326. * @param max $val
  327. * @param array $array
  328. */
  329. public static function delArrayValue($val, $array)
  330. {
  331. $key = array_search($val, $array);
  332. if ($key !== false) {
  333. unset($array[$key]);
  334. }
  335. return array_values($array);
  336. }
  337. public static function strcut($str, $length, $etc = '...')
  338. {
  339. $result = '';
  340. $str = html_entity_decode(trim(strip_tags($str)), ENT_QUOTES, 'UTF-8');
  341. $strlen = strlen($str);
  342. for ($i = 0; (($i < $strlen) && ($length > 0)); $i++) {
  343. $number = strpos(str_pad(decbin(ord(substr($str, $i, 1))), 8, '0', STR_PAD_LEFT), '0');
  344. if ($number) {
  345. if ($length < 1.0) {
  346. break;
  347. }
  348. $result .= substr($str, $i, $number);
  349. $length -= 1.0;
  350. $i += $number - 1;
  351. } else {
  352. $result .= substr($str, $i, 1);
  353. $length -= 0.5;
  354. }
  355. }
  356. $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
  357. if ($i < $strlen) {
  358. $result .= $etc;
  359. }
  360. return $result;
  361. }
  362. /**
  363. * 递归调整文件属性
  364. */
  365. public static function chmod($path, $filemode = 0755)
  366. {
  367. if (!is_dir($path)) {
  368. return chmod($path, $filemode);
  369. }
  370. $dh = opendir($path);
  371. while (($file = readdir($dh)) !== false) {
  372. if ($file != '.' && $file != '..') {
  373. $fullpath = $path . '/' . $file;
  374. if (is_link($fullpath)) {
  375. return false;
  376. } elseif (!is_dir($fullpath) && !chmod($fullpath, $filemode)) {
  377. return false;
  378. } elseif (!self::chmod($fullpath, $filemode)) {
  379. return false;
  380. }
  381. }
  382. }
  383. closedir($dh);
  384. return chmod($path, $filemode);
  385. }
  386. /**
  387. * 获取服务器IP
  388. * @param bool $toLong 是否返回整形
  389. * @return string
  390. */
  391. public static function getServerIp($toLong = false)
  392. {
  393. if (isset($_SERVER['SERVER_ADDR'])) {
  394. $ip = $_SERVER['SERVER_ADDR'];
  395. } else {
  396. $domain = gethostname();
  397. $ip = gethostbyname($domain);
  398. }
  399. if ($toLong) {
  400. $ip = ip2long($ip);
  401. }
  402. return $ip;
  403. }
  404. /**
  405. * 获取客户端Ip
  406. * @param bool $toLong 是否返回整形
  407. * @return string|int
  408. */
  409. public static function getClientIp($toLong = false)
  410. {
  411. $ip = '';
  412. if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && $_SERVER["HTTP_X_FORWARDED_FOR"]) {
  413. $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  414. } elseif (isset($_SERVER["HTTP_CLIENT_IP"]) && $_SERVER["HTTP_CLIENT_IP"]) {
  415. $ip = $_SERVER["HTTP_CLIENT_IP"];
  416. } elseif (isset($_SERVER["REMOTE_ADDR"]) && $_SERVER["REMOTE_ADDR"]) {
  417. $ip = $_SERVER["REMOTE_ADDR"];
  418. }
  419. $pos = strpos($ip, ',');
  420. if ($pos) {
  421. $ip = substr($ip, 0, $pos);
  422. }
  423. $ip = trim($ip);
  424. if ($toLong) {
  425. $ip = ip2long($ip);
  426. }
  427. return $ip;
  428. }
  429. /**
  430. * 获取截取后的文字
  431. * 英文汉字均算做一个长度
  432. */
  433. public static function getUtf8ShortCut($content, $length)
  434. {
  435. $shortCut = mb_substr($content, 0, $length, 'UTF-8');
  436. $shortCut = strcmp($shortCut, $content) == 0 ? $shortCut : $shortCut . '...';
  437. return $shortCut;
  438. }
  439. /**
  440. * 检查是否有http
  441. * @param type $str
  442. * @return type
  443. */
  444. public static function httpLinkChecker($str)
  445. {
  446. $reg = '/^https?/i';
  447. if (preg_match($reg, $str)) {
  448. return $str;
  449. } else {
  450. return 'http://' . $str;
  451. }
  452. }
  453. /**
  454. * 获取进程运行时间
  455. */
  456. public static function getPidTime($pid)
  457. {
  458. $i_pinfo = file_get_contents('/proc/' . $pid . '/stat');
  459. $args = explode(" ", $i_pinfo);
  460. $start_time = $args[21];
  461. $m_pinfo = file_get_contents('/proc/stat');
  462. $args = explode("\n", $m_pinfo);
  463. foreach ($args as $line) {
  464. $v = trim($line);
  465. if (strpos($line, "btime") !== false) {
  466. $args_1 = explode(" ", $v);
  467. $uptime = $args_1[1];
  468. break;
  469. }
  470. }
  471. if ($uptime == '' || $start_time == '') {
  472. return 0;
  473. }
  474. return (int)microtime(true) - (int)($uptime + $start_time / 100);
  475. }
  476. /**
  477. * 过滤标点符号
  478. * @param type $content
  479. * @return type
  480. */
  481. public static function strap($content)
  482. {
  483. $content = trim($content);
  484. $content = strip_tags($content);
  485. $content = preg_replace("/(&[a-zA-Z]{0,4};)/u", ' ', $content);
  486. $content = preg_replace("/([^a-zA-Z0-9\x{4e00}-\x{9fa5}]+)/u", ' ', $content);
  487. $content = trim($content);
  488. return $content;
  489. }
  490. public static function html2text($str)
  491. {
  492. $str = preg_replace("/<style .*?<\/style>/is", "", $str);
  493. $str = preg_replace("/<script .*?<\/script>/is", "", $str);
  494. $str = preg_replace("/<br \s*\/?\/>/i", "\n", $str);
  495. $str = preg_replace("/<\/?p>/i", "\n\n", $str);
  496. $str = preg_replace("/<\/?td>/i", "\n", $str);
  497. $str = preg_replace("/<\/?div>/i", "\n", $str);
  498. $str = preg_replace("/<\/?blockquote>/i", "\n", $str);
  499. $str = preg_replace("/<\/?li>/i", "\n", $str);
  500. $str = preg_replace("/\&nbsp\;/i", " ", $str);
  501. $str = preg_replace("/\&nbsp/i", " ", $str);
  502. $str = preg_replace("/\&amp\;/i", "&", $str);
  503. $str = preg_replace("/\&amp/i", "&", $str);
  504. $str = preg_replace("/\&lt\;/i", "<", $str);
  505. $str = preg_replace("/\&lt/i", "<", $str);
  506. $str = preg_replace("/\&ldquo\;/i", '"', $str);
  507. $str = preg_replace("/\&ldquo/i", '"', $str);
  508. $str = preg_replace("/\&lsquo\;/i", "'", $str);
  509. $str = preg_replace("/\&lsquo/i", "'", $str);
  510. $str = preg_replace("/\&rsquo\;/i", "'", $str);
  511. $str = preg_replace("/\&rsquo/i", "'", $str);
  512. $str = preg_replace("/\&gt\;/i", ">", $str);
  513. $str = preg_replace("/\&gt/i", ">", $str);
  514. $str = preg_replace("/\&rdquo\;/i", '"', $str);
  515. $str = preg_replace("/\&rdquo/i", '"', $str);
  516. $str = strip_tags($str);
  517. $str = preg_replace("/(\n\s*\n)+/is", "\n", $str);
  518. return $str;
  519. }
  520. public static function convertStringToUtf8($string)
  521. {
  522. $string = urldecode($string);
  523. $encoding = mb_detect_encoding($string, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
  524. $string = mb_convert_encoding($string, 'UTF-8', $encoding);
  525. return $string;
  526. }
  527. /**
  528. * utf8多字节编码文字折行
  529. * @param $text
  530. * @param int $length
  531. * @return string
  532. */
  533. public static function wordwrapUtf8($text, $length = 75)
  534. {
  535. $result = array();
  536. $len = mb_strlen($text, 'UTF-8');
  537. $step = ceil($len / $length);
  538. for ($i = 0; $i < $step; $i++) {
  539. $result[] = mb_substr($text, $length * $i, $length, "UTF-8");
  540. }
  541. return implode("\n", $result);
  542. }
  543. /**
  544. * 从 $argv 中解析合并参数, 兼容一下情况:
  545. * 无前缀, 被解析成索引数组
  546. * 单前缀(只能是单字母, 后面可以直接跟value, 也可以空格后面跟着value,二者不能混用), 被解析成关联数组
  547. * 双前缀形式(可以是单字母也可以是多字母,后面必需跟着 '='), 被解析成关联数组
  548. * 如果不确定, 请自行打印结果查看是否正确
  549. * @example : php index.php first -s 'second' --third='third'
  550. * @return array('first', 's' => 'second', 'third' => 'third')
  551. */
  552. public static function getArguments()
  553. {
  554. $arguments = $_SERVER['argv'];
  555. for ($i = 0; $i < $_SERVER['argc']; $i++) {
  556. if (!isset($arguments[$i][0])) {
  557. continue;
  558. }
  559. //判断第一位是否是 '-'
  560. if (substr($arguments[$i], 0, 1) != '-') {
  561. continue;
  562. }
  563. //判断第二位是否是 '-'
  564. if (substr($arguments[$i], 1, 1) != '-') {
  565. if (strlen($arguments[$i]) == 2) {
  566. $key = substr($arguments[$i], 1);
  567. $value = $arguments[$i + 1];
  568. $arguments[$key] = trim($value);
  569. unset($arguments[$i]);
  570. unset($arguments[$i + 1]);
  571. } elseif (strlen($arguments[$i]) > 2) {
  572. $key = substr($arguments[$i], 1, 1);
  573. $value = substr($arguments[$i], 2);
  574. $arguments[$key] = trim($value);
  575. unset($arguments[$i]);
  576. } else {
  577. //do nothing;
  578. }
  579. } else {
  580. $value = substr($arguments[$i], 2);
  581. $value = explode('=', $value, 2);
  582. $arguments[$value[0]] = trim($value[1]);
  583. unset($arguments[$i]);
  584. }
  585. }
  586. return $arguments;
  587. }
  588. /**
  589. * 尝试解析字符串,如果解析失败则返回原值
  590. * @param $string
  591. * @return string | array
  592. */
  593. public static function jsonDecode($string)
  594. {
  595. if (!$string) {
  596. return $string;
  597. }
  598. $result = json_decode($string, true);
  599. if ($result) {
  600. $string = $result;
  601. }
  602. return $string;
  603. }
  604. /**
  605. * 获取数组分片, 从指定列表中获取指定元素之后的若干个切片
  606. * @param $idList
  607. * @param $lastId
  608. * @param $count
  609. * @return array
  610. */
  611. public static function getSlice($idList, $lastId = 0, $count = 20)
  612. {
  613. $result = array();
  614. if (!$idList || ($lastId && !in_array($lastId, $idList))) {
  615. return $result;
  616. }
  617. if ($lastId) {
  618. $position = array_search($lastId, $idList) + 1;
  619. } else {
  620. $position = 0;
  621. }
  622. $result = array_slice($idList, $position, $count);
  623. return $result;
  624. }
  625. /**
  626. * 创建目录
  627. * @param unknown $dir
  628. * @param number $mode
  629. */
  630. public static function mkdir($dir, $mode = 0755)
  631. {
  632. if (!is_dir($dir)) {
  633. $temp = explode('/', $dir);
  634. $cur_dir = '';
  635. for ($i = 0; $i < count($temp); $i++) {
  636. $cur_dir .= $temp[$i] . '/';
  637. if (!is_dir($cur_dir)) {
  638. @mkdir($cur_dir, 0777);
  639. @chmod($cur_dir, $mode);
  640. }
  641. }
  642. }
  643. }
  644. /**
  645. * 下载图片
  646. *
  647. * @param unknown $imgUrl
  648. * @return string
  649. */
  650. public static function downImg($imgUrl,$suffix=NULL)
  651. {
  652. $suffix = $suffix?:strtolower(substr(strrchr($imgUrl, '.'), 1));
  653. if (strlen($suffix)>5){
  654. $suffix="jpg";
  655. }
  656. if ($suffix==""){
  657. $suffix="jpg";
  658. }
  659. $new_name = "makeup/images/".date("Y-m")."/img_" . uniqid() . rand(1, 1000) . "." . $suffix;
  660. $path = "/www/api.test.meitu.com/" . $new_name;
  661. if (!is_dir("/www/api.test.meitu.com/makeup/images/".date("Y-m")."/")){
  662. Helper::mkdir("/www/api.test.meitu.com/makeup/images/".date("Y-m")."/");
  663. }
  664. $file=self::getContent($imgUrl);
  665. $i=0;
  666. while ($file==""&&$i<3){
  667. $file=self::getContent($imgUrl);
  668. Logger::setLog(null,'下载图片失败。原图:'.$imgUrl,'down_img_error');
  669. $i++;
  670. }
  671. if ($file==""){
  672. return "";
  673. }
  674. file_put_contents($path, $file);
  675. Webp::tranPic2Webp($path);//转换成webp图片
  676. $push = "/www/api.mgr.meitu.com/cdn/push.sh";
  677. push($push, $new_name);
  678. push($push, $new_name.'.webp');
  679. return "/".$new_name;
  680. }
  681. public static function getContent($url){
  682. $curlHandle = curl_init();
  683. curl_setopt($curlHandle, CURLOPT_URL, $url);
  684. curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, 0); // 让CURL支持HTTPS访问
  685. curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
  686. curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT, 30);
  687. if (strpos($url,"https")!==false){
  688. curl_setopt($curlHandle, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  689. curl_setopt($curlHandle, CURLOPT_PROXY, Proxy::getData("host"));
  690. curl_setopt($curlHandle, CURLOPT_PROXYPORT, Proxy::getData('port'));
  691. curl_setopt($curlHandle, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
  692. curl_setopt($curlHandle, CURLOPT_PROXYUSERPWD, Proxy::getData('user').":".Proxy::getData('password'));
  693. }
  694. curl_setopt($curlHandle, CURLOPT_TIMEOUT, 30);
  695. $file = curl_exec($curlHandle);
  696. curl_close($curlHandle);
  697. return $file;
  698. }
  699. }