2000) { return false; } $parts = parse_url($url); if (!is_array($parts)) { return false; } $scheme = strtolower((string) ($parts['scheme'] ?? '')); if (!in_array($scheme, ['http', 'https'], true)) { return false; } if (isset($parts['user']) || isset($parts['pass'])) { return false; } $host = strtolower(trim((string) ($parts['host'] ?? ''), '[]')); if ('' === $host) { return false; } if (in_array($host, ['localhost', '127.0.0.1', '::1', '0.0.0.0'], true)) { return false; } if (preg_match('#\.(local|localhost|internal|lan)$#i', $host)) { return false; } // 直接写 IP 的,必须是公网地址 if (filter_var($host, FILTER_VALIDATE_IP)) { if (!filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { return false; } } return true; } /** * 读一个网址的标题 / 摘要 / 日期 * * @param string $url * @return array|null ['url','title','desc','date','site'],失败返回 null */ public static function meta(string $url): ?array { $url = trim($url); if (!self::valid($url)) { return null; } $cached = self::read($url); if (null !== $cached) { return isset($cached['__failed']) ? null : $cached; } $page = self::fetch($url); if (null === $page) { self::write($url, null, self::FAIL_TTL); return null; } $info = self::parse($page['body'], self::charset($page['charset'], $page['body'])); $info['url'] = '' === $page['url'] ? $url : $page['url']; self::write($url, $info, self::TTL); return $info; } /** * 缓存目录(不可写时自动跳过缓存,不影响功能) * * @return string */ public static function cacheDir(): string { return __DIR__ . '/cache'; } /** * 清空缓存(插件停用时顺手清一下) * * @return void */ public static function flush(): void { $dir = self::cacheDir(); if (!is_dir($dir)) { return; } $files = glob($dir . '/*.json'); if (!is_array($files)) { return; } foreach ($files as $file) { @unlink($file); } } /* ------------------------------------------------------------------ * 缓存 * ------------------------------------------------------------------ */ /** * @param string $url * @return array|null 命中返回数据(失败记录返回 ['__failed' => true]),未命中返回 null */ private static function read(string $url): ?array { $file = self::path($url); if ('' === $file || !is_file($file)) { return null; } $raw = @file_get_contents($file); if (false === $raw) { return null; } $data = json_decode($raw, true); if (!is_array($data) || empty($data['expire'])) { return null; } if ((int) $data['expire'] < time()) { @unlink($file); return null; } if (empty($data['ok']) || !is_array($data['data'] ?? null)) { return ['__failed' => true]; } return $data['data']; } /** * @param string $url * @param array|null $data null 表示这次抓失败了 * @param int $ttl * @return void */ private static function write(string $url, ?array $data, int $ttl): void { $file = self::path($url); if ('' === $file) { return; } $payload = [ 'ok' => null !== $data, 'expire' => time() + $ttl, 'data' => $data, ]; @file_put_contents($file, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); } /** * @param string $url * @return string 缓存不可用时返回空串 */ private static function path(string $url): string { $dir = self::cacheDir(); if (!is_dir($dir)) { @mkdir($dir, 0755, true); } if (!is_dir($dir) || !is_writable($dir)) { return ''; } // 带版本号做键:解析规则改过之后,旧缓存里的标题不会继续被读出来 return $dir . '/' . md5(self::CACHE_VERSION . '|' . $url) . '.json'; } /* ------------------------------------------------------------------ * 抓取 * ------------------------------------------------------------------ */ /** * @param string $url * @return array|null ['body' => string, 'url' => string, 'charset' => string] */ private static function fetch(string $url): ?array { $result = function_exists('curl_init') ? self::viaCurl($url) : self::viaStream($url); if (null === $result || '' === $result['body']) { return null; } if (strlen($result['body']) > self::MAX_BYTES) { $result['body'] = substr($result['body'], 0, self::MAX_BYTES); } return $result; } /** * @param string $url * @return array|null */ private static function viaCurl(string $url): ?array { $result = self::curlRequest($url, true); // 很多 Windows / 精简环境没配 CA 证书,校验必然失败;这类环境退回不校验再试一次, // 我们只读公开页面的标题,不发送任何凭据,代价可以接受。 if (null === $result && in_array(self::$curlErrno, [35, 51, 58, 60, 77], true)) { $result = self::curlRequest($url, false); } return $result; } /** * @param string $url * @param bool $verify 是否校验证书 * @return array|null */ private static function curlRequest(string $url, bool $verify): ?array { $ch = curl_init(); if (false === $ch) { return null; } curl_setopt_array($ch, [ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 3, CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_TIMEOUT => 6, CURLOPT_USERAGENT => self::UA, CURLOPT_ENCODING => '', CURLOPT_SSL_VERIFYPEER => $verify, CURLOPT_SSL_VERIFYHOST => $verify ? 2 : 0, CURLOPT_HTTPHEADER => [ 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8', ], ]); $body = curl_exec($ch); $errno = (int) curl_errno($ch); $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); $type = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE); $final = (string) curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); self::$curlErrno = $errno; if (PHP_VERSION_ID < 80000) { curl_close($ch); } if (false === $body || 0 !== $errno || $code >= 400) { return null; } if ('' !== $type && false === stripos($type, 'html') && false === stripos($type, 'xml')) { return null; } return ['body' => (string) $body, 'url' => $final, 'charset' => $type]; } /** * 没有 curl 时的退路 * * @param string $url * @return array|null */ private static function viaStream(string $url): ?array { if (!ini_get('allow_url_fopen')) { return null; } $context = stream_context_create([ 'http' => [ 'timeout' => 6, 'follow_location' => 1, 'max_redirects' => 3, 'user_agent' => self::UA, 'ignore_errors' => true, 'header' => "Accept: text/html,application/xhtml+xml;q=0.9,*/*;q=0.8\r\n" . "Accept-Language: zh-CN,zh;q=0.9,en;q=0.8\r\n", ], 'ssl' => [ 'verify_peer' => true, 'verify_peer_name' => true, ], ]); $body = @file_get_contents($url, false, $context, 0, self::MAX_BYTES); if (false === $body || '' === $body) { return null; } $type = ''; // PHP 8.5 起弃用本地作用域 $http_response_header,改用 http_get_last_response_headers()(PHP 8.4+ 提供) $responseHeaders = function_exists('http_get_last_response_headers') ? http_get_last_response_headers() : ($http_response_header ?? null); if (is_array($responseHeaders)) { foreach ($responseHeaders as $header) { if (stripos($header, 'content-type:') === 0) { $type = trim(substr($header, 13)); } } } if ('' !== $type && false === stripos($type, 'html') && false === stripos($type, 'xml')) { return null; } return ['body' => (string) $body, 'url' => $url, 'charset' => $type]; } /* ------------------------------------------------------------------ * 解析 * ------------------------------------------------------------------ */ /** * @param string $html * @param string $charset * @return array */ private static function parse(string $html, string $charset): array { $html = self::toUtf8($html, $charset); // 注释和脚本里也可能写着
]*>(.*?)
#is', $html, $m)) { return ''; } foreach ($m[1] as $raw) { $text = self::clean(strip_tags($raw)); if (self::strLen($text) >= 24) { return $text; } } return ''; } /** * @param string $text * @return int */ private static function strLen(string $text): int { return function_exists('mb_strlen') ? mb_strlen($text, 'UTF-8') : strlen($text); } /** * @param string $text * @param int $len * @return string */ private static function cut(string $text, int $len): string { if (self::strLen($text) <= $len) { return $text; } return function_exists('mb_substr') ? mb_substr($text, 0, $len, 'UTF-8') : substr($text, 0, $len); } /** * JSON-LD 里的 datePublished * * @param string $html * @return string */ private static function jsonDate(string $html): string { if (preg_match('#["\']datePublished["\']\s*:\s*["\']([^"\']+)["\']#i', $html, $m)) { return $m[1]; } return ''; } /** * @param string $html * @return string */ private static function timeAttr(string $html): string { if (preg_match('#