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); // 注释和脚本里也可能写着 ,先整段清掉 $flat = preg_replace('#<!--.*?-->#s', ' ', $html) ?? $html; $flat = preg_replace('#<(script|style|noscript|svg)\b[^>]*>.*?</\1>#is', ' ', $flat) ?? $flat; $site = self::clean(self::metaOf($flat, ['og:site_name', 'application-name'])); $title = self::titleOf($flat, $site); $desc = self::metaOf($flat, ['og:description', 'twitter:description', 'description']); if ('' === $desc) { $desc = self::firstPara($flat); } $desc = self::clean($desc); $desc = self::cut($desc, 600); $date = self::metaOf($flat, [ 'article:published_time', 'article:modified_time', 'og:updated_time', 'pubdate', 'publishdate', ]); if ('' === $date) { $date = self::jsonDate($flat); } if ('' === $date) { $date = self::timeAttr($flat); } return [ 'title' => $title, 'desc' => $desc, 'date' => self::dateOf($date), 'site' => $site, ]; } /** * 取文章标题 * * <title> 往往是「文章标题 | 站点名 - 一句话介绍」,直接拿来当引用标题会拖一长串, * 所以按 og:title → 正文 h1 → <title> 的顺序取,前两个基本就是文章标题本身; * 很多站点连 og:title 都拼成「文章标题 - 站名」(页面又常缺 og:site_name), * 这时以正文 h1 为基准把后缀整段切掉;退到 <title> 时再把站名和后面的介绍切掉。 * * @param string $html * @param string $site * @return string */ private static function titleOf(string $html, string $site): string { $og = self::clean(self::metaOf($html, ['og:title', 'twitter:title'])); $h1 = self::clean(self::firstHeading($html)); if ('' !== $og && $og !== $site) { $og = self::withoutSite($og, $site); // og:title 拼了站名后缀时,h1 就是干净的文章标题,拿它切尾巴 $og = self::stripKnownTail($og, $h1); if ('' !== $og) { return $og; } } if ('' !== $h1 && $h1 !== $site) { return self::withoutSite($h1, $site); } return self::fromTagTitle(self::clean(self::tagText($html, 'title')), $site); } /** * 参照干净标题把候选标题尾部拼的站名整段切掉 * * og:title / <title> 常被站点拼成「文章标题 - 站名」,而正文 h1 一般就是 * 干净的文章标题:候选标题以 h1 开头、后面紧跟分隔符时,剩下那段必然是 * 站名之类的附属信息,整段去掉,只留文章标题。 * * @param string $title 候选标题(可能带站名后缀) * @param string $reference 正文里的干净标题(h1),可为空 * @return string */ private static function stripKnownTail(string $title, string $reference): string { if ('' === $reference || '' === $title) { return $title; } // 参照标题太短(4 字以内)不可靠,切错不如不切 if (self::strLen($reference) < 4 || self::strLen($title) <= self::strLen($reference)) { return $title; } if (!self::strStartsWith($title, $reference)) { return $title; } $tail = function_exists('mb_substr') ? mb_substr($title, self::strLen($reference), null, 'UTF-8') : substr($title, strlen($reference)); // 后面紧跟分隔符(可能连着几个)才认定是站名后缀; // 标题本身就写到 h1 结尾、没有后缀的,原样返回 if (preg_match('#^\s*[-–—||·•_/»]+#u', $tail)) { return $reference; } return $title; } /** * @param string $haystack * @param string $needle * @return bool haystack 是否以 needle 开头 */ private static function strStartsWith(string $haystack, string $needle): bool { if ('' === $needle || self::strLen($haystack) < self::strLen($needle)) { return false; } if (function_exists('mb_strpos')) { return 0 === mb_strpos($haystack, $needle, 0, 'UTF-8'); } return 0 === strpos($haystack, $needle); } /** * 第一个 h1 的文字(文章页里通常就是标题本身) * * @param string $html * @return string */ private static function firstHeading(string $html): string { if (!preg_match_all('#<h1\b[^>]*>(.*?)</h1>#is', $html, $m)) { return ''; } foreach ($m[1] as $raw) { $text = self::clean($raw); if ('' !== $text) { return $text; } } return ''; } /** * 去掉标题里拼的站名 * * 只处理「站名在首尾、且有分隔符」这一种,正文标题里自带的破折号不动。 * * @param string $title * @param string $site * @return string */ private static function withoutSite(string $title, string $site): string { if ('' === $site || '' === $title) { return $title; } $quoted = preg_quote($site, '#'); $sep = '\s*[-–—||·•_/»]\s*'; $title = preg_replace('#\s*[-–—||·•_/»]\s*' . $quoted . '\s*$#iu', '', $title) ?? $title; $title = preg_replace('#^' . $quoted . '\s*[-–—||·•_/»]\s*#iu', '', $title) ?? $title; $title = preg_replace('#^' . $sep . '#u', '', $title) ?? $title; $title = preg_replace('#' . $sep . '$#u', '', $title) ?? $title; return trim($title); } /** * <title> 兜底:「文章标题 - 站名 - 一句话介绍」只留第一段 * * 第一段太短(比如「归档 - 某站」)就整条保留,免得把栏目名当成标题切掉。 * * @param string $title * @param string $site * @return string */ private static function fromTagTitle(string $title, string $site): string { $title = self::withoutSite($title, $site); if ('' === $title) { return ''; } $parts = preg_split('#\s*[-–—||·•_/»]+\s*#u', $title) ?: []; $parts = array_values(array_filter($parts, function ($part) { return '' !== trim($part); })); if (count($parts) < 2) { return $title; } $first = trim($parts[0]); return self::strLen($first) >= 6 ? $first : $title; } /** * 按属性名找 <meta content> * * 有的站点写成 <meta content="..." property="og:title">,属性顺序不固定, * 所以整条标签拿出来再分别取,不能靠一个正则硬套。 * * @param string $html * @param array $keys 小写的属性名,按优先级排列 * @return string */ private static function metaOf(string $html, array $keys): string { if (!preg_match_all('#<meta\b[^>]*>#i', $html, $tags)) { return ''; } $map = []; foreach ($tags[0] as $tag) { if (!preg_match('#\b(?:property|name|itemprop)\s*=\s*["\']([^"\']+)["\']#i', $tag, $key)) { continue; } $name = strtolower(trim($key[1])); if (!in_array($name, $keys, true) || isset($map[$name])) { continue; } if (preg_match('#\bcontent\s*=\s*(["\'])(.*?)\1#is', $tag, $value)) { $value = trim($value[2]); if ('' !== $value) { $map[$name] = $value; } } } foreach ($keys as $name) { if (isset($map[$name])) { return $map[$name]; } } return ''; } /** * @param string $html * @param string $tag * @return string */ private static function tagText(string $html, string $tag): string { if (!preg_match('#<' . $tag . '\b[^>]*>(.*?)</' . $tag . '>#is', $html, $m)) { return ''; } return trim(strip_tags($m[1])); } /** * 正文第一段够长的文字 * * @param string $html * @return string */ private static function firstPara(string $html): string { if (!preg_match_all('#<p\b[^>]*>(.*?)</p>#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('#<time\b[^>]*\bdatetime\s*=\s*["\']([^"\']+)["\']#i', $html, $m)) { return $m[1]; } return ''; } /** * 各种时间写法统一成 Y-m-d,明显不合理的丢掉 * * @param string $raw * @return string */ private static function dateOf(string $raw): string { $raw = trim($raw); if ('' === $raw) { return ''; } $ts = strtotime($raw); if (false === $ts || $ts < 315532800 || $ts > time() + 86400 * 365) { return ''; } return date('Y-m-d', $ts); } /** * 从响应头或页面里找编码 * * @param string $header * @param string $body * @return string */ private static function charset(string $header, string $body): string { if (preg_match('#charset\s*=\s*["\']?([\w-]+)#i', $header, $m)) { return strtolower($m[1]); } if (preg_match('#<meta[^>]+charset\s*=\s*["\']?([\w-]+)#i', substr($body, 0, 4096), $m)) { return strtolower($m[1]); } return 'utf-8'; } /** * @param string $html * @param string $charset * @return string */ private static function toUtf8(string $html, string $charset): string { $charset = strtolower($charset); if (in_array($charset, ['utf-8', 'utf8', ''], true) || !function_exists('mb_convert_encoding')) { return $html; } try { $converted = @mb_convert_encoding($html, 'UTF-8', $charset); } catch (\Throwable $e) { return $html; } return is_string($converted) && '' !== $converted ? $converted : $html; } /** * 去标签、解实体、收空白 * * @param string $text * @return string */ private static function clean(string $text): string { $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8'); $text = strip_tags($text); $text = preg_replace('/\s+/u', ' ', $text) ?? $text; return trim($text); } }