木漏茶室源码下载中心
整站 PHP 源码:可浏览文件、复制路径、下载单文件或打包 ZIP。
发布版本 v6.25.231
升级后自动生成独立源码包,下载中心只发送这份冻结包
已排除 config.php / 用户数据 / 上传文件 / 升级备份
COMMUNITY DEPLOYMENTS
已经跑起来的木漏茶室
从源码下载中心下载、完成安装并回传验证的站外站点。每个站点只计 1 次部署下载量;已记录站点会实时读取名称、版本、Logo 与在线状态,本机、内网和证书异常站点无法完成回传。
实时检测
2
个站点已部署
木
木漏茶室
mlcs.xnn.lol · v6.25.232
访问 ↗
2026.11.21
在线
木
木漏茶室
mlcs.nbnb.mom · v6.25.231
访问 ↗
2026.11.20
在线
已展示全部 2 个站点。
inc/source_deploy.php
57.1 KB · 发布包 v6.25.231
<?php
/**
* 源码部署统计:站外站点完成安装后回传,下载中心验证并展示。
*
* 下载中心生成完整源码 ZIP 时,会额外写入 inc/deploy_origin.php。
* 站外站点安装完成后读取该文件,把站点地址、名称、版本回传给下载中心;
* 下载中心再访问目标站点的 api.php?action=deploy_verify 验证部署真实性,
* 只有验证通过的站点才计入“部署下载量”并展示。
*/
if (!function_exists('source_deploy_root')) {
function source_deploy_root()
{
if (defined('APP_ROOT')) { return APP_ROOT; }
if (defined('ROOT')) { return ROOT; }
return dirname(__DIR__);
}
}
if (!function_exists('source_deploy_data_dir')) {
function source_deploy_data_dir()
{
$dir = source_deploy_root() . '/data';
if (!is_dir($dir)) { @mkdir($dir, 0775, true); }
return $dir;
}
}
if (!function_exists('source_deploy_secret')) {
function source_deploy_secret()
{
$file = source_deploy_data_dir() . '/source_deploy_secret.txt';
if (is_file($file)) {
$secret = trim((string) @file_get_contents($file));
if (strlen($secret) >= 32) { return $secret; }
}
$secret = bin2hex(random_bytes(32));
if (@file_put_contents($file, $secret, LOCK_EX) === false) {
throw new Exception('无法创建源码部署标识,请检查 data 目录权限');
}
@chmod($file, 0600);
return $secret;
}
}
if (!function_exists('source_deploy_token')) {
function source_deploy_token()
{
return hash_hmac('sha256', 'komorebi-source-deploy-v1', source_deploy_secret());
}
}
if (!function_exists('source_deploy_superadmin_email')) {
function source_deploy_superadmin_email()
{
try {
$row = DB::one('SELECT email FROM ' . DB::table('users') . " WHERE role = 'superadmin' AND email <> '' ORDER BY id ASC LIMIT 1");
$email = strtolower(trim((string) ($row['email'] ?? '')));
if ($email !== '') { return $email; }
} catch (Throwable $e) {
// 数据库尚未安装或查询失败时回退到当前用户。
}
$user = function_exists('current_user') ? current_user() : null;
if (is_array($user) && !empty($user['email'])) {
return strtolower(trim((string) $user['email']));
}
return '';
}
}
if (!function_exists('source_deploy_current_url')) {
function source_deploy_current_url()
{
$forwarded = strtolower(trim((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')));
$cf = json_decode((string) ($_SERVER['HTTP_CF_VISITOR'] ?? ''), true);
$https = (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off')
|| strpos($forwarded, 'https') !== false
|| strtolower((string) ($_SERVER['HTTP_X_FORWARDED_SSL'] ?? '')) === 'on'
|| (is_array($cf) && strtolower((string) ($cf['scheme'] ?? '')) === 'https')
|| (int) ($_SERVER['SERVER_PORT'] ?? 0) === 443;
$scheme = $https ? 'https' : 'http';
$host = trim((string) ($_SERVER['HTTP_HOST'] ?? 'localhost'));
if ($host === '' || strpos($host, '/') !== false || strpos($host, '\\') !== false) {
$host = 'localhost';
}
$script = (string) ($_SERVER['SCRIPT_NAME'] ?? '/index.php');
if ($script === '' || $script[0] !== '/') {
$script = '/index.php';
}
$dir = rtrim(str_replace('\\', '/', dirname($script)), '/');
return $scheme . '://' . $host . ($dir === '' ? '/' : $dir . '/');
}
}
if (!function_exists('source_deploy_origin_path')) {
function source_deploy_origin_path()
{
return source_deploy_root() . '/inc/deploy_origin.php';
}
}
if (!function_exists('source_deploy_origin')) {
function source_deploy_origin()
{
static $loaded = false;
static $origin = null;
if ($loaded) { return $origin; }
$loaded = true;
$file = source_deploy_origin_path();
if (!is_file($file)) { return null; }
$data = @include $file;
if (!is_array($data) || empty($data['source']) || empty($data['token'])) {
return null;
}
$origin = [
'source' => rtrim((string) $data['source'], '/') . '/',
'token' => (string) $data['token'],
'version' => (string) ($data['version'] ?? ''),
'issued_at' => (int) ($data['issued_at'] ?? 0),
];
return $origin;
}
}
if (!function_exists('source_deploy_scheme_alternate')) {
function source_deploy_scheme_alternate($url)
{
$url = trim((string) $url);
if (preg_match('#^https://#i', $url)) {
return preg_replace('#^https://#i', 'http://', $url);
}
if (preg_match('#^http://#i', $url)) {
return preg_replace('#^http://#i', 'https://', $url);
}
return '';
}
}
if (!function_exists('source_deploy_origin_urls')) {
function source_deploy_origin_urls()
{
$origin = source_deploy_origin();
if (!$origin) { return []; }
$urls = [rtrim((string) $origin['source'], '/') . '/'];
$alt = source_deploy_scheme_alternate($urls[0]);
if ($alt !== '') { $urls[] = rtrim($alt, '/') . '/'; }
return array_values(array_unique($urls));
}
}
if (!function_exists('source_deploy_https_cert_ok')) {
function source_deploy_https_cert_ok($url)
{
$parts = parse_url((string) $url);
if (!is_array($parts) || strtolower((string) ($parts['scheme'] ?? '')) !== 'https') {
return true;
}
$host = (string) ($parts['host'] ?? '');
$port = (int) ($parts['port'] ?? 443);
if ($host === '') { return false; }
if (in_array(strtolower($host), ['localhost', '127.0.0.1', '::1'], true)) { return false; }
$ctx = stream_context_create([
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
'SNI_enabled' => true,
'peer_name' => $host,
],
]);
$errno = 0;
$errstr = '';
$fp = @stream_socket_client('tls://' . $host . ':' . $port, $errno, $errstr, 3, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) { return false; }
fclose($fp);
return true;
}
}
if (!function_exists('source_deploy_origin_manifest')) {
function source_deploy_origin_manifest()
{
$source = source_deploy_current_url();
// 源站 HTTPS 证书失效时,完整包写入 HTTP 备用地址,避免安装站点继承坏证书;
// 运行期回传仍会同时尝试 HTTP/HTTPS 两种协议。
if (!source_deploy_https_cert_ok($source)) {
$alternate = source_deploy_scheme_alternate($source);
if ($alternate !== '') { $source = $alternate; }
}
return [
'source' => $source,
'token' => source_deploy_token(),
'version' => defined('APP_VERSION') ? APP_VERSION : '',
'issued_at' => time(),
];
}
}
if (!function_exists('source_deploy_is_external')) {
function source_deploy_is_external()
{
return source_deploy_origin() !== null;
}
}
if (!function_exists('source_deploy_post_json')) {
function source_deploy_post_json($url, array $payload, $timeout = 6)
{
$body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($body === false) { return [0, '', 'JSON 编码失败']; }
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Accept: application/json'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => (int) $timeout,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_USERAGENT => 'Komorebi-Source-Deploy/1.0',
]);
$raw = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = (string) curl_error($ch);
curl_close($ch);
return [$code, $raw === false ? '' : (string) $raw, $err];
}
$ctx = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\nAccept: application/json\r\n",
'content' => $body,
'timeout' => (int) $timeout,
'ignore_errors' => true,
'user_agent' => 'Komorebi-Source-Deploy/1.0',
],
]);
$raw = @file_get_contents($url, false, $ctx);
$code = 0;
if (isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $m)) {
$code = (int) $m[1];
}
return [$code, $raw === false ? '' : (string) $raw, $raw === false ? '请求失败' : ''];
}
}
if (!function_exists('source_deploy_state_file')) {
function source_deploy_state_file()
{
return source_deploy_data_dir() . '/source_deploy_report.json';
}
}
if (!function_exists('source_deploy_read_state')) {
function source_deploy_read_state()
{
$file = source_deploy_state_file();
$state = is_file($file) ? json_decode((string) @file_get_contents($file), true) : null;
return is_array($state) ? $state : [];
}
}
if (!function_exists('source_deploy_write_state')) {
function source_deploy_write_state(array $state)
{
@file_put_contents(source_deploy_state_file(), json_encode($state, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT), LOCK_EX);
}
}
if (!function_exists('source_deploy_report')) {
function source_deploy_report($siteName = '')
{
$origin = source_deploy_origin();
if (!$origin) { return ['ok' => false, 'message' => '当前站点不是从源码下载中心安装的']; }
$siteName = trim((string) $siteName);
if ($siteName === '' && function_exists('setting')) { $siteName = (string) setting('site_name', '木漏茶室'); }
if ($siteName === '') { $siteName = '木漏茶室'; }
$payload = [
'site_url' => source_deploy_current_url(),
'site_name' => mb_substr($siteName, 0, 80, 'UTF-8'),
'version' => defined('APP_VERSION') ? APP_VERSION : ($origin['version'] ?? ''),
'token' => $origin['token'],
'superadmin_email' => source_deploy_superadmin_email(),
'installed_at' => time(),
];
$bases = source_deploy_origin_urls();
if (!$bases) { $bases = [rtrim((string) $origin['source'], '/') . '/']; }
$state = ['at' => time(), 'attempt_at' => time(), 'ok' => false, 'message' => '连接下载中心失败'];
$lastError = '连接下载中心失败';
foreach ($bases as $base) {
$endpoint = $base . 'index.php?page=source&act=deploy_register';
$result = source_deploy_post_json($endpoint, $payload, 6);
$json = json_decode($result[1], true);
if (is_array($json) && !empty($json['ok'])) {
$state['ok'] = true;
$state['message'] = '部署已记录';
$state['site_url'] = (string) ($json['site_url'] ?? $payload['site_url']);
$state['count'] = (int) ($json['count'] ?? 0);
$state['email'] = (string) ($payload['superadmin_email'] ?? '');
$state['endpoint'] = $endpoint;
break;
}
if (is_array($json) && !empty($json['msg'])) {
$lastError = (string) $json['msg'];
} elseif ($result[2] !== '') {
$lastError = (string) $result[2];
} elseif ((int) $result[0] >= 300) {
$lastError = 'HTTP ' . (int) $result[0];
}
$state['endpoint'] = $endpoint;
}
if (!$state['ok']) { $state['message'] = $lastError; }
source_deploy_write_state($state);
return $state;
}
}
if (!function_exists('source_deploy_install_report')) {
function source_deploy_install_report($siteName = '')
{
return source_deploy_report($siteName);
}
}
if (!function_exists('source_deploy_bootstrap')) {
function source_deploy_bootstrap()
{
$origin = source_deploy_origin();
if (!$origin) { return; }
$state = source_deploy_read_state();
$lastOk = (int) ($state['at'] ?? 0);
$lastAttempt = (int) ($state['attempt_at'] ?? 0);
$currentEmail = source_deploy_superadmin_email();
$stateEmail = strtolower(trim((string) ($state['email'] ?? '')));
$emailChanged = $currentEmail !== '' && $currentEmail !== $stateEmail;
if (!$emailChanged && !empty($state['ok']) && $lastOk > 0 && (time() - $lastOk) < 7 * 86400) { return; }
if (!$emailChanged && $lastAttempt > 0 && (time() - $lastAttempt) < 3600) { return; }
// 放在响应结束后再回传;FPM 环境用 fastcgi_finish_request 避免拖慢访问。
register_shutdown_function(function () {
@ignore_user_abort(true);
if (function_exists('fastcgi_finish_request')) { @fastcgi_finish_request(); }
try { source_deploy_report(''); } catch (Throwable $e) { /* 部署回传失败不阻塞站点 */ }
});
}
}
if (!function_exists('source_deploy_host_is_public')) {
function source_deploy_host_is_public($host)
{
$host = strtolower(rtrim((string) $host, '.'));
if ($host === '' || strpos($host, '..') !== false) { return false; }
if (filter_var($host, FILTER_VALIDATE_IP)) {
return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
}
if (!preg_match('/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/', $host) || strpos($host, '.') === false) {
return false;
}
$ip = gethostbyname($host);
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
}
}
if (!function_exists('source_deploy_normalize_url')) {
function source_deploy_normalize_url($url)
{
$url = trim((string) $url);
$parts = parse_url($url);
if (!is_array($parts) || empty($parts['scheme']) || empty($parts['host'])) { return ''; }
$scheme = strtolower((string) $parts['scheme']);
if (!in_array($scheme, ['http', 'https'], true)) { return ''; }
if (!empty($parts['user']) || !empty($parts['pass']) || !empty($parts['query']) || !empty($parts['fragment'])) { return ''; }
$host = strtolower(rtrim((string) $parts['host'], '.'));
if (!source_deploy_host_is_public($host)) { return ''; }
$port = (int) ($parts['port'] ?? ($scheme === 'https' ? 443 : 80));
if (!in_array($port, [80, 443], true)) { return ''; }
$path = (string) ($parts['path'] ?? '/');
if ($path === '' || $path[0] !== '/') { $path = '/' . $path; }
if (substr($path, -1) !== '/') { $path .= '/'; }
return $scheme . '://' . $host . (($port !== ($scheme === 'https' ? 443 : 80)) ? ':' . $port : '') . $path;
}
}
if (!function_exists('source_deploy_logo_kind')) {
function source_deploy_logo_kind($url, $hint = '')
{
if ($hint === 'video' || $hint === 'image') { return $hint; }
$ext = strtolower(pathinfo((string) parse_url((string) $url, PHP_URL_PATH), PATHINFO_EXTENSION));
return in_array($ext, ['mp4', 'webm', 'ogv', 'ogg', 'm4v', 'mov'], true) ? 'video' : 'image';
}
}
if (!function_exists('source_deploy_public_logo_info')) {
function source_deploy_public_logo_info()
{
$logo = function_exists('setting') ? (string) setting('site_logo', 'assets/img/logo.svg') : 'assets/img/logo.svg';
if ($logo === '') { $logo = 'assets/img/logo.svg'; }
$type = source_deploy_logo_kind($logo, function_exists('site_logo_is_video') && site_logo_is_video($logo) ? 'video' : '');
if (preg_match('#^https?://#i', $logo)) {
$url = $logo;
} elseif (function_exists('full_url')) {
$url = full_url($logo);
} else {
$url = $logo;
}
return [
'url' => filter_var($url, FILTER_VALIDATE_URL) ? $url : '',
'type' => $type,
];
}
}
if (!function_exists('source_deploy_public_logo_url')) {
function source_deploy_public_logo_url()
{
$info = source_deploy_public_logo_info();
return (string) ($info['url'] ?? '');
}
}
if (!function_exists('source_deploy_public_payload')) {
function source_deploy_public_payload()
{
$logo = source_deploy_public_logo_info();
return [
'ok' => true,
'installed' => true,
'site_name' => function_exists('setting') ? (string) setting('site_name', '木漏茶室') : '木漏茶室',
'version' => defined('APP_VERSION') ? APP_VERSION : '',
'logo_url' => (string) ($logo['url'] ?? ''),
'logo_type' => (string) ($logo['type'] ?? 'image'),
'checked_at' => time(),
];
}
}
if (!function_exists('source_deploy_absolute_url')) {
function source_deploy_absolute_url($base, $ref)
{
$ref = trim(html_entity_decode((string) $ref, ENT_QUOTES | ENT_HTML5, 'UTF-8'));
if ($ref === '') { return ''; }
if (preg_match('#^https?://#i', $ref)) { return $ref; }
$parts = parse_url((string) $base);
if (!is_array($parts) || empty($parts['scheme']) || empty($parts['host'])) { return ''; }
$origin = strtolower((string) $parts['scheme']) . '://' . (string) $parts['host'];
if (!empty($parts['port'])) { $origin .= ':' . (int) $parts['port']; }
if (strpos($ref, '//') === 0) { return strtolower((string) $parts['scheme']) . ':' . $ref; }
if ($ref[0] === '/') { return $origin . $ref; }
$dir = str_replace('\\', '/', dirname((string) ($parts['path'] ?? '/')));
if ($dir === '.' || $dir === '/') { $dir = ''; }
return $origin . rtrim($dir, '/') . '/' . $ref;
}
}
if (!function_exists('source_deploy_normalize_logo_url')) {
function source_deploy_normalize_logo_url($url, $siteUrl = '')
{
if ($url === '' && $siteUrl !== '') {
$url = rtrim((string) $siteUrl, '/') . '/assets/img/logo.svg';
}
$url = source_deploy_absolute_url($siteUrl, $url);
$parts = parse_url($url);
if (!is_array($parts) || empty($parts['scheme']) || empty($parts['host'])) { return ''; }
$scheme = strtolower((string) $parts['scheme']);
if (!in_array($scheme, ['http', 'https'], true)) { return ''; }
if (!empty($parts['user']) || !empty($parts['pass'])) { return ''; }
$host = strtolower(rtrim((string) $parts['host'], '.'));
if (!source_deploy_host_is_public($host)) { return ''; }
$port = (int) ($parts['port'] ?? ($scheme === 'https' ? 443 : 80));
if (!in_array($port, [80, 443], true)) { return ''; }
$path = (string) ($parts['path'] ?? '/');
if ($path === '' || $path[0] !== '/') { $path = '/' . $path; }
if (strlen($path) > 1600) { return ''; }
return $scheme . '://' . $host . (($port !== ($scheme === 'https' ? 443 : 80)) ? ':' . $port : '') . $path
. (!empty($parts['query']) ? '?' . $parts['query'] : '');
}
}
if (!function_exists('source_deploy_http_get')) {
function source_deploy_http_get($url, $timeout = 4, $maxBytes = 2097152, $allowInsecure = false)
{
$parts = parse_url((string) $url);
if (!is_array($parts) || empty($parts['scheme']) || empty($parts['host'])) { return null; }
$scheme = strtolower((string) $parts['scheme']);
if (!in_array($scheme, ['http', 'https'], true) || !empty($parts['user']) || !empty($parts['pass'])) { return null; }
$host = strtolower(rtrim((string) $parts['host'], '.'));
if (!source_deploy_host_is_public($host)) { return null; }
$port = (int) ($parts['port'] ?? ($scheme === 'https' ? 443 : 80));
if (!in_array($port, [80, 443], true)) { return null; }
$ip = filter_var($host, FILTER_VALIDATE_IP) ? $host : gethostbyname($host);
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { return null; }
if (!function_exists('curl_init')) { return null; }
$ch = curl_init($url);
$options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => (int) $timeout,
CURLOPT_SSL_VERIFYPEER => $allowInsecure ? false : true,
CURLOPT_SSL_VERIFYHOST => $allowInsecure ? 0 : 2,
CURLOPT_ENCODING => '',
CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
CURLOPT_USERAGENT => 'Komorebi-Source-Deploy/1.0',
];
if (!filter_var($host, FILTER_VALIDATE_IP)) {
$options[CURLOPT_RESOLVE] = [$host . ':' . $port . ':' . $ip];
}
curl_setopt_array($ch, $options);
$raw = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$final = (string) curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$err = (string) curl_error($ch);
curl_close($ch);
if ($raw === false || strlen((string) $raw) > (int) $maxBytes) { return null; }
return ['code' => $code, 'body' => (string) $raw, 'url' => $final, 'err' => $err];
}
}
if (!function_exists('source_deploy_parse_home_info')) {
function source_deploy_parse_home_info($html, $siteUrl)
{
$name = '';
if (preg_match('/<meta[^>]+property\s*=\s*["\']og:site_name["\'][^>]+content\s*=\s*["\']([^"\']+)/i', (string) $html, $m)) {
$name = trim(html_entity_decode($m[1], ENT_QUOTES, 'UTF-8'));
}
if ($name === '' && preg_match('/<title[^>]*>(.*?)<\/title>/is', (string) $html, $m)) {
$name = trim(html_entity_decode(strip_tags($m[1]), ENT_QUOTES, 'UTF-8'));
$name = trim(preg_split('/\s*[·||-]\s*/u', $name)[0] ?? $name);
}
$version = '';
if (preg_match('/v?\s*(\d{1,2}\.\d{1,2}\.\d{1,3})/i', (string) $html, $m)) {
$version = $m[1];
}
$logo = source_deploy_parse_home_logo_info((string) $html, $siteUrl);
return [
'site_name' => mb_substr($name, 0, 80, 'UTF-8'),
'version' => $version,
'logo_url' => (string) ($logo['url'] ?? ''),
'logo_type' => (string) ($logo['type'] ?? 'image'),
];
}
}
if (!function_exists('source_deploy_parse_home_logo_info')) {
function source_deploy_parse_home_logo_info($html, $siteUrl)
{
$html = (string) $html;
$candidates = [];
// 优先读取站点前台实际渲染的 Logo,避免只依赖 og:image 或 favicon。
if (preg_match('/<video[^>]*class\s*=\s*["\'][^"\']*site-logo[^"\']*["\'][^>]*>[\s\S]{0,800}?<source[^>]+src\s*=\s*["\']([^"\']+)/i', $html, $m)) {
$candidates[] = [$m[1], 'video'];
}
if (preg_match('/<img[^>]*class\s*=\s*["\'][^"\']*site-logo[^"\']*["\'][^>]*>/i', $html, $tag)) {
if (preg_match('/src\s*=\s*["\']([^"\']+)/i', $tag[0], $m)) { $candidates[] = [$m[1], 'image']; }
}
if (preg_match('/<img[^>]*src\s*=\s*["\']([^"\']+)["\'][^>]*class\s*=\s*["\'][^"\']*site-logo[^"\']*["\']/i', $html, $m)) {
$candidates[] = [$m[1], 'image'];
}
$patterns = [
['/<meta[^>]+property\s*=\s*["\']og:image["\'][^>]+content\s*=\s*["\']([^"\']+)/i', 'image'],
['/<meta[^>]+content\s*=\s*["\']([^"\']+)["\'][^>]+property\s*=\s*["\']og:image["\']/i', 'image'],
['/<link[^>]+rel\s*=\s*["\'][^"\']*(?:apple-touch-icon|icon)[^"\']*["\'][^>]+href\s*=\s*["\']([^"\']+)/i', 'image'],
['/<link[^>]+href\s*=\s*["\']([^"\']+)["\'][^>]+rel\s*=\s*["\'][^"\']*(?:apple-touch-icon|icon)[^"\']*["\']/i', 'image'],
];
foreach ($patterns as $pattern) {
if (preg_match($pattern[0], $html, $m)) { $candidates[] = [$m[1], $pattern[1]]; }
}
foreach ($candidates as $candidate) {
$logo = source_deploy_normalize_logo_url($candidate[0], $siteUrl);
if ($logo !== '') {
return ['url' => $logo, 'type' => source_deploy_logo_kind($logo, $candidate[1])];
}
}
return [
'url' => source_deploy_normalize_logo_url('', $siteUrl),
'type' => 'image',
];
}
}
if (!function_exists('source_deploy_parse_home_logo')) {
function source_deploy_parse_home_logo($html, $siteUrl)
{
$info = source_deploy_parse_home_logo_info($html, $siteUrl);
return (string) ($info['url'] ?? '');
}
}
if (!function_exists('source_deploy_logo_dir')) {
function source_deploy_logo_dir()
{
$dir = source_deploy_data_dir() . '/source_deploy_logos';
if (!is_dir($dir)) { @mkdir($dir, 0775, true); }
return $dir;
}
}
if (!function_exists('source_deploy_cache_logo')) {
function source_deploy_cache_logo($key, $siteUrl, $logoUrl)
{
$key = preg_replace('/[^a-f0-9]/', '', (string) $key);
if (strlen($key) !== 24 || $logoUrl === '') { return null; }
$logoUrl = source_deploy_normalize_logo_url($logoUrl, $siteUrl);
if ($logoUrl === '') { return null; }
$response = source_deploy_http_get($logoUrl, 8, 12582912);
if (!$response && preg_match('#^https://#i', $logoUrl)) {
$response = source_deploy_http_get(preg_replace('#^https://#i', 'http://', $logoUrl), 8, 12582912);
}
if (!$response && preg_match('#^https://#i', $logoUrl)) {
// 部分虚拟主机证书链异常,浏览器能打开但服务端严格校验失败;仅对公开 Logo 做一次降级缓存。
$response = source_deploy_http_get($logoUrl, 8, 12582912, true);
}
if (!$response || (int) $response['code'] !== 200 || $response['body'] === '') { return null; }
$body = (string) $response['body'];
if (strlen($body) > 12582912) { return null; }
$mime = '';
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = strtolower((string) finfo_buffer($finfo, $body));
finfo_close($finfo);
}
$ext = '';
$map = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp',
'video/mp4' => 'mp4', 'video/webm' => 'webm', 'video/ogg' => 'ogv'];
if (isset($map[$mime])) {
$ext = $map[$mime];
} elseif ($mime === 'image/svg+xml') {
$trim = ltrim($body);
if (strpos($trim, '<svg') !== false || strpos($trim, '<?xml') === 0) { $ext = 'svg'; }
} else {
$size = @getimagesize('data://image/*;base64,' . base64_encode($body));
if (is_array($size) && !empty($size[2])) {
$extMap = [IMAGETYPE_PNG => 'png', IMAGETYPE_JPEG => 'jpg', IMAGETYPE_GIF => 'gif', IMAGETYPE_WEBP => 'webp'];
$ext = $extMap[$size[2]] ?? '';
if ($ext !== '') { $mime = image_type_to_mime_type($size[2]); }
}
}
if ($ext === '') {
$trim = ltrim($body);
if (strpos($trim, '<svg') !== false || strpos($trim, '<?xml') === 0) {
$ext = 'svg';
$mime = 'image/svg+xml';
} elseif (strncmp($body, "\x1aE\xdf\xa3", 4) === 0) {
$ext = 'webm';
$mime = 'video/webm';
} elseif (strpos(substr($body, 0, 32), 'ftyp') !== false) {
$ext = 'mp4';
$mime = 'video/mp4';
} elseif (strpos(substr($body, 0, 32), 'OggS') !== false) {
$ext = 'ogv';
$mime = 'video/ogg';
}
}
if ($ext === '') { return null; }
$dir = source_deploy_logo_dir();
foreach (glob($dir . '/' . $key . '.*') ?: [] as $old) { @unlink($old); }
$file = $key . '.' . $ext;
if (@file_put_contents($dir . '/' . $file, $body, LOCK_EX) === false) { return null; }
@chmod($dir . '/' . $file, 0644);
return [
'file' => $file,
'mime' => $mime !== '' ? $mime : (in_array($ext, ['mp4', 'webm', 'ogv'], true) ? ($ext === 'ogv' ? 'video/ogg' : 'video/' . $ext) : 'image/' . ($ext === 'jpg' ? 'jpeg' : $ext)),
'url' => $logoUrl,
'type' => in_array($ext, ['mp4', 'webm', 'ogv'], true) ? 'video' : 'image',
'at' => time(),
];
}
}
if (!function_exists('source_deploy_logo_src')) {
function source_deploy_logo_src(array $site)
{
$key = (string) ($site['key'] ?? '');
$file = (string) ($site['logo_file'] ?? '');
if ($key !== '' && $file !== '') {
$path = source_deploy_logo_dir() . '/' . basename($file);
if (is_file($path)) {
return function_exists('page_url')
? page_url('source', ['act' => 'deploy_logo', 'key' => $key, 'v' => filemtime($path)])
: '';
}
}
return (string) ($site['logo_url'] ?? '');
}
}
if (!function_exists('source_deploy_live_probe')) {
function source_deploy_live_probe($siteUrl)
{
$siteUrl = source_deploy_normalize_url($siteUrl);
if ($siteUrl === '') {
return ['status' => 'offline', 'checked_at' => time(), 'logo_url' => '', 'site_name' => '', 'version' => ''];
}
$api = rtrim($siteUrl, '/') . '/api.php?action=deploy_public';
$response = source_deploy_http_get($api, 4, 262144);
$certIssue = false;
if (!$response) {
$alternate = source_deploy_scheme_alternate($api);
if ($alternate !== '') {
$response = source_deploy_http_get($alternate, 4, 262144);
$certIssue = $response !== null;
}
}
if (!$response && preg_match('#^https://#i', $api)) {
// 证书异常时仍读取公开的站名 / 版本 / Logo,状态继续标记为“证书异常”。
$response = source_deploy_http_get($api, 4, 262144, true);
if ($response) { $certIssue = true; }
}
$info = [];
if ($response && (int) $response['code'] === 200) {
$json = json_decode((string) $response['body'], true);
if (is_array($json) && !empty($json['ok'])) {
$info = [
'site_name' => mb_substr(trim((string) ($json['site_name'] ?? '')), 0, 80, 'UTF-8'),
'version' => preg_replace('/[^0-9A-Za-z._-]/', '', (string) ($json['version'] ?? '')),
'logo_url' => source_deploy_normalize_logo_url((string) ($json['logo_url'] ?? ''), $siteUrl),
'logo_type' => source_deploy_logo_kind((string) ($json['logo_url'] ?? ''), (string) ($json['logo_type'] ?? '')),
];
}
}
if (!$info) {
$response = source_deploy_http_get($siteUrl, 5, 2097152);
if (!$response) {
$alternate = source_deploy_scheme_alternate($siteUrl);
if ($alternate !== '') {
$response = source_deploy_http_get($alternate, 5, 2097152);
$certIssue = $response !== null;
}
}
if (!$response && preg_match('#^https://#i', $siteUrl)) {
$response = source_deploy_http_get($siteUrl, 5, 2097152, true);
if ($response) { $certIssue = true; }
}
if ($response && (int) $response['code'] >= 200 && (int) $response['code'] < 400) {
$info = source_deploy_parse_home_info((string) $response['body'], $siteUrl);
}
}
if (!$info) {
return ['status' => 'offline', 'checked_at' => time(), 'logo_url' => '', 'logo_type' => 'image', 'site_name' => '', 'version' => ''];
}
return [
'status' => $certIssue ? 'cert' : 'online',
'checked_at' => time(),
'logo_url' => (string) ($info['logo_url'] ?? ''),
'logo_type' => (string) ($info['logo_type'] ?? source_deploy_logo_kind((string) ($info['logo_url'] ?? ''))),
'site_name' => (string) ($info['site_name'] ?? ''),
'version' => (string) ($info['version'] ?? ''),
];
}
}
if (!function_exists('source_deploy_refresh_sites')) {
function source_deploy_refresh_sites($force = false)
{
$file = source_deployments_file();
$data = is_file($file) ? json_decode((string) @file_get_contents($file), true) : null;
if (!is_array($data) || empty($data['sites']) || !is_array($data['sites'])) { return []; }
$now = time();
if (!$force && (int) ($data['refresh_at'] ?? 0) > 0 && ($now - (int) $data['refresh_at']) < 90) {
return source_deployments();
}
$changed = false;
$checked = 0;
foreach ($data['sites'] as $key => $site) {
if (!$force && (int) ($site['checked_at'] ?? 0) > 0 && ($now - (int) $site['checked_at']) < 120) { continue; }
if ($checked >= 12) { break; }
$checked++;
$probe = source_deploy_live_probe((string) ($site['site_url'] ?? ''));
$site['status'] = (string) ($probe['status'] ?? 'unknown');
$site['checked_at'] = (int) ($probe['checked_at'] ?? $now);
if (!empty($probe['logo_url'])) {
$site['logo_url'] = (string) $probe['logo_url'];
$site['logo_type'] = (string) ($probe['logo_type'] ?? source_deploy_logo_kind((string) $probe['logo_url']));
$cached = source_deploy_cache_logo((string) $key, (string) ($site['site_url'] ?? ''), (string) $probe['logo_url']);
if (is_array($cached)) {
$site['logo_file'] = (string) ($cached['file'] ?? '');
$site['logo_mime'] = (string) ($cached['mime'] ?? '');
$site['logo_type'] = (string) ($cached['type'] ?? $site['logo_type']);
$site['logo_at'] = (int) ($cached['at'] ?? time());
}
}
if (!empty($probe['site_name'])) { $site['site_name'] = (string) $probe['site_name']; }
if (!empty($probe['version'])) { $site['version'] = (string) $probe['version']; }
$data['sites'][$key] = $site;
$changed = true;
}
if ($changed) {
$data['refresh_at'] = $now;
$data['updated_at'] = $now;
@file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT), LOCK_EX);
}
return source_deployments();
}
}
if (!function_exists('source_deploy_remote_cache_file')) {
function source_deploy_remote_cache_file()
{
return source_deploy_data_dir() . '/source_deploy_remote_cache.json';
}
}
if (!function_exists('source_deploy_site_canonical')) {
function source_deploy_site_canonical($url)
{
$parts = parse_url((string) $url);
if (!is_array($parts) || empty($parts['host'])) { return ''; }
$host = strtolower(rtrim((string) $parts['host'], '.'));
$path = '/' . trim((string) ($parts['path'] ?? '/'), '/');
return $host . rtrim($path, '/');
}
}
if (!function_exists('source_deploy_remote_site')) {
function source_deploy_remote_site($url, array $row = [], $base = '')
{
$url = source_deploy_normalize_url($url);
if ($url === '') { return null; }
$status = (string) ($row['status'] ?? 'unknown');
if (!in_array($status, ['online', 'cert', 'offline', 'unknown'], true)) { $status = 'unknown'; }
$logo = (string) ($row['logo_src'] ?? '');
if ($logo !== '' && $logo[0] === '/' && $base !== '') {
$logo = rtrim($base, '/') . $logo;
}
if ($logo === '') { $logo = (string) ($row['logo_url'] ?? ''); }
return [
'key' => 'remote-' . substr(hash('sha256', source_deploy_site_canonical($url)), 0, 20),
'site_url' => $url,
'site_name' => mb_substr(trim((string) ($row['site_name'] ?? '')), 0, 80, 'UTF-8'),
'version' => preg_replace('/[^0-9A-Za-z._-]/', '', (string) ($row['version'] ?? '')),
'logo_url' => $logo,
'logo_src' => $logo,
'logo_type' => source_deploy_logo_kind($logo, (string) ($row['logo_type'] ?? '')),
'status' => $status,
'checked_at' => (int) ($row['checked_at'] ?? time()),
'verified_at' => (int) ($row['verified_at'] ?? time()),
'remote' => true,
];
}
}
if (!function_exists('source_deploy_parse_center_html')) {
function source_deploy_parse_center_html($html, $base)
{
if (!class_exists('DOMDocument')) { return []; }
$doc = new DOMDocument();
$old = libxml_use_internal_errors(true);
@$doc->loadHTML((string) $html);
libxml_clear_errors();
libxml_use_internal_errors($old);
$xp = new DOMXPath($doc);
$sites = [];
foreach ($xp->query('//a[contains(concat(" ", normalize-space(@class), " "), " source-deploy-card ")]') as $card) {
$href = (string) $card->getAttribute('href');
$row = [];
foreach ([
'site_name' => './/*[@data-deploy-name]',
'version' => './/*[@data-deploy-version]',
'status' => './/*[@data-deploy-status-text]',
'date' => './/*[@data-deploy-date]',
] as $field => $query) {
$node = $xp->query($query, $card)->item(0);
if ($node) { $row[$field] = trim((string) $node->textContent); }
}
$logoNode = $xp->query('.//*[@data-deploy-logo]', $card)->item(0);
if ($logoNode) {
$row['logo_src'] = source_deploy_absolute_url($base, (string) $logoNode->getAttribute('src'));
$row['logo_type'] = strtolower($logoNode->nodeName) === 'video' ? 'video' : 'image';
if ($row['logo_src'] === '' && strtolower($logoNode->nodeName) === 'video') {
$sourceNode = $xp->query('.//source', $logoNode)->item(0);
if ($sourceNode) { $row['logo_src'] = source_deploy_absolute_url($base, (string) $sourceNode->getAttribute('src')); }
}
}
$status = (string) ($row['status'] ?? '');
$row['status'] = strpos($status, '在线') !== false ? 'online' : (strpos($status, '证书') !== false ? 'cert' : (strpos($status, '离线') !== false ? 'offline' : 'unknown'));
$row['version'] = preg_replace('/^v/i', '', (string) ($row['version'] ?? ''));
$date = trim((string) ($row['date'] ?? ''));
if ($date !== '' && preg_match('/^\d{4}\.\d{2}\.\d{2}$/', $date)) {
$row['verified_at'] = strtotime(str_replace('.', '-', $date)) ?: time();
}
$site = source_deploy_remote_site($href, $row, $base);
if ($site) { $sites[] = $site; }
}
return $sites;
}
}
if (!function_exists('source_deploy_remote_fetch')) {
function source_deploy_remote_fetch($base)
{
$base = rtrim((string) $base, '/') . '/';
$bases = [$base];
$alternate = source_deploy_scheme_alternate($base);
if ($alternate !== '') { $bases[] = rtrim($alternate, '/') . '/'; }
foreach ($bases as $baseUrl) {
foreach (['index.php?page=source&act=deploy_list', 'index.php?page=source&act=deploy_feed'] as $path) {
$response = source_deploy_http_get($baseUrl . $path, 5, 262144);
if (!$response || (int) $response['code'] !== 200) { continue; }
$json = json_decode((string) $response['body'], true);
if (!is_array($json) || empty($json['ok']) || empty($json['sites']) || !is_array($json['sites'])) { continue; }
$sites = [];
foreach ($json['sites'] as $row) {
if (!is_array($row)) { continue; }
$site = source_deploy_remote_site((string) ($row['site_url'] ?? ''), $row, $baseUrl);
if ($site) { $sites[$site['key']] = $site; }
}
if ($sites) { return array_values($sites); }
}
$response = source_deploy_http_get($baseUrl . 'index.php?page=source', 5, 1048576);
if ($response && (int) $response['code'] === 200) {
$sites = source_deploy_parse_center_html((string) $response['body'], $baseUrl);
if ($sites) { return $sites; }
}
}
return [];
}
}
if (!function_exists('source_deploy_peer_centers')) {
function source_deploy_peer_centers()
{
$centers = source_deploy_origin_urls();
$file = source_deploy_data_dir() . '/source_centers.txt';
if (is_file($file)) {
foreach (preg_split('/\r\n|\r|\n/', (string) @file_get_contents($file)) as $line) {
$line = trim($line);
if ($line !== '' && $line[0] !== '#') { $centers[] = $line; }
}
}
$out = [];
$current = source_deploy_site_canonical(source_deploy_current_url());
foreach ($centers as $center) {
$center = source_deploy_normalize_url($center);
if ($center === '') { continue; }
if (source_deploy_site_canonical($center) === $current) { continue; }
$key = source_deploy_site_canonical($center);
if ($key !== '' && !isset($out[$key])) {
$out[$key] = rtrim($center, '/') . '/';
}
}
return array_values($out);
}
}
if (!function_exists('source_deploy_remote_sites')) {
function source_deploy_remote_sites($force = false)
{
$file = source_deploy_remote_cache_file();
$cache = is_file($file) ? json_decode((string) @file_get_contents($file), true) : null;
if (!$force && is_array($cache) && (int) ($cache['at'] ?? 0) > 0 && (time() - (int) $cache['at']) < 180) {
return is_array($cache['sites'] ?? null) ? $cache['sites'] : [];
}
$centers = source_deploy_peer_centers();
if (!$centers) { return is_array($cache['sites'] ?? null) ? $cache['sites'] : []; }
$sites = [];
foreach ($centers as $center) {
$rows = source_deploy_remote_fetch($center);
foreach ($rows as $row) {
if (!is_array($row)) { continue; }
$key = source_deploy_site_canonical((string) ($row['site_url'] ?? ''));
if ($key !== '') { $sites[$key] = $row; }
}
// 把来源下载中心本身也作为一台已运行站点展示,避免只显示“被它记录”的站点。
$centerKey = source_deploy_site_canonical($center);
if ($centerKey !== '' && !isset($sites[$centerKey])) {
$probe = source_deploy_live_probe($center);
$centerSite = source_deploy_remote_site($center, [
'site_name' => (string) ($probe['site_name'] ?? ''),
'version' => (string) ($probe['version'] ?? ''),
'logo_src' => (string) ($probe['logo_url'] ?? ''),
'status' => (string) ($probe['status'] ?? 'unknown'),
'checked_at' => (int) ($probe['checked_at'] ?? time()),
'verified_at' => time(),
], $center);
if ($centerSite) { $sites[$centerKey] = $centerSite; }
}
}
$sites = array_values($sites);
@file_put_contents($file, json_encode(['at' => time(), 'sites' => $sites], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT), LOCK_EX);
return $sites;
}
}
if (!function_exists('source_deploy_self_site')) {
function source_deploy_self_site()
{
$url = source_deploy_normalize_url(source_deploy_current_url());
if ($url === '') { return null; }
$name = function_exists('setting') ? (string) setting('site_name', '木漏茶室') : '木漏茶室';
$logo = source_deploy_public_logo_info();
return [
'key' => 'self-' . substr(hash('sha256', source_deploy_site_canonical($url)), 0, 20),
'site_url' => $url,
'site_name' => $name !== '' ? $name : '木漏茶室',
'version' => defined('APP_VERSION') ? APP_VERSION : '',
'logo_url' => (string) ($logo['url'] ?? ''),
'logo_src' => (string) ($logo['url'] ?? ''),
'logo_type' => (string) ($logo['type'] ?? 'image'),
'status' => 'online',
'checked_at' => time(),
'verified_at' => time(),
'self' => true,
];
}
}
if (!function_exists('source_deploy_all_sites')) {
function source_deploy_all_sites($force = false)
{
$local = source_deploy_refresh_sites($force);
$remote = source_deploy_remote_sites($force);
$now = time();
$probed = 0;
foreach ($remote as $i => $site) {
$siteUrl = (string) ($site['site_url'] ?? '');
if ($siteUrl === '' || (int) ($site['checked_at'] ?? 0) > $now - 120 || $probed >= 20) { continue; }
$probe = source_deploy_live_probe($siteUrl);
if ($probe) {
$remote[$i]['status'] = (string) ($probe['status'] ?? $remote[$i]['status']);
$remote[$i]['checked_at'] = (int) ($probe['checked_at'] ?? $now);
if (!empty($probe['site_name'])) { $remote[$i]['site_name'] = (string) $probe['site_name']; }
if (!empty($probe['version'])) { $remote[$i]['version'] = (string) $probe['version']; }
if (!empty($probe['logo_url'])) {
$remote[$i]['logo_url'] = $remote[$i]['logo_src'] = (string) $probe['logo_url'];
$remote[$i]['logo_type'] = (string) ($probe['logo_type'] ?? source_deploy_logo_kind((string) $probe['logo_url']));
}
}
$probed++;
}
$all = [];
$seen = [];
foreach (array_merge($local, $remote) as $site) {
if (!is_array($site)) { continue; }
$key = source_deploy_site_canonical((string) ($site['site_url'] ?? ''));
if ($key === '' || isset($seen[$key])) { continue; }
$seen[$key] = true;
$all[] = $site;
}
$self = source_deploy_self_site();
if ($self) {
$key = source_deploy_site_canonical($self['site_url']);
if ($key !== '' && !isset($seen[$key])) { $all[] = $self; }
}
usort($all, function ($a, $b) {
return (int) ($b['verified_at'] ?? 0) <=> (int) ($a['verified_at'] ?? 0);
});
return $all;
}
}
if (!function_exists('source_deploy_probe_site')) {
function source_deploy_probe_site($siteUrl, $token)
{
$siteUrl = source_deploy_normalize_url($siteUrl);
if ($siteUrl === '') { return null; }
$parts = parse_url($siteUrl);
$host = (string) ($parts['host'] ?? '');
$port = (int) ($parts['port'] ?? (($parts['scheme'] ?? '') === 'https' ? 443 : 80));
$ip = filter_var($host, FILTER_VALIDATE_IP) ? $host : gethostbyname($host);
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { return null; }
$probe = rtrim($siteUrl, '/') . '/api.php?action=deploy_verify&token=' . urlencode($token);
if (!function_exists('curl_init')) { return null; }
$ch = curl_init($probe);
$options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 8,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
CURLOPT_USERAGENT => 'Komorebi-Source-Deploy-Verify/1.0',
];
if (!filter_var($host, FILTER_VALIDATE_IP)) {
$options[CURLOPT_RESOLVE] = [$host . ':' . $port . ':' . $ip];
}
curl_setopt_array($ch, $options);
$raw = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($raw === false || $code >= 400 || strlen((string) $raw) > 65536) { return null; }
$json = json_decode((string) $raw, true);
if (!is_array($json) || empty($json['ok']) || empty($json['token'])) { return null; }
if (!hash_equals((string) $token, (string) $json['token'])) { return null; }
return [
'site_name' => mb_substr(trim((string) ($json['site_name'] ?? '木漏茶室')), 0, 80, 'UTF-8'),
'version' => preg_replace('/[^0-9A-Za-z._-]/', '', (string) ($json['version'] ?? '')),
'superadmin_email' => strtolower(trim((string) ($json['superadmin_email'] ?? ''))),
'logo_url' => source_deploy_normalize_logo_url((string) ($json['logo_url'] ?? ''), $siteUrl),
'logo_type' => source_deploy_logo_kind((string) ($json['logo_url'] ?? ''), (string) ($json['logo_type'] ?? '')),
'site_url' => $siteUrl,
];
}
}
if (!function_exists('source_deploy_rate_allow')) {
function source_deploy_rate_allow($ip)
{
$ip = trim((string) $ip);
if ($ip === '') { return false; }
$file = source_deploy_data_dir() . '/source_deploy_rate.json';
$fp = @fopen($file, 'c+');
if (!$fp) { return true; }
@flock($fp, LOCK_EX);
$raw = stream_get_contents($fp);
$data = json_decode((string) $raw, true);
if (!is_array($data)) { $data = []; }
$now = time();
$bucket = $data[$ip] ?? ['start' => $now, 'count' => 0];
if (($now - (int) ($bucket['start'] ?? 0)) > 3600) { $bucket = ['start' => $now, 'count' => 0]; }
$bucket['count'] = (int) ($bucket['count'] ?? 0) + 1;
$data[$ip] = $bucket;
foreach ($data as $key => $row) {
if (($now - (int) ($row['start'] ?? 0)) > 7200) { unset($data[$key]); }
}
rewind($fp);
ftruncate($fp, 0);
fwrite($fp, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
fflush($fp);
@flock($fp, LOCK_UN);
fclose($fp);
return $bucket['count'] <= 10;
}
}
if (!function_exists('source_deployments_file')) {
function source_deployments_file()
{
return source_deploy_data_dir() . '/source_deployments.json';
}
}
if (!function_exists('source_deploy_record')) {
function source_deploy_record(array $probe, $token, &$isNew = null, &$emailChanged = null)
{
$file = source_deployments_file();
$fp = @fopen($file, 'c+');
if (!$fp) { throw new Exception('无法写入部署统计,请检查 data 目录权限'); }
@flock($fp, LOCK_EX);
$raw = stream_get_contents($fp);
$data = json_decode((string) $raw, true);
if (!is_array($data) || empty($data['sites']) || !is_array($data['sites'])) {
$data = ['sites' => [], 'updated_at' => time()];
}
$siteUrl = rtrim((string) $probe['site_url'], '/') . '/';
$key = substr(hash('sha256', strtolower($siteUrl)), 0, 24);
$old = $data['sites'][$key] ?? [];
$isNew = !$old;
$newEmail = strtolower(trim((string) ($probe['superadmin_email'] ?? '')));
$oldEmail = strtolower(trim((string) ($old['superadmin_email'] ?? '')));
$emailChanged = $newEmail !== '' && $newEmail !== $oldEmail;
if (!$old && count($data['sites']) >= 500) {
@flock($fp, LOCK_UN);
fclose($fp);
throw new Exception('部署站点数量已达上限,请联系管理员清理');
}
$logoUrl = (string) ($probe['logo_url'] ?? '');
if ($logoUrl === '') { $logoUrl = (string) ($old['logo_url'] ?? ''); }
$data['sites'][$key] = [
'site_url' => $siteUrl,
'site_name' => (string) ($probe['site_name'] ?? '木漏茶室'),
'version' => (string) ($probe['version'] ?? ''),
'superadmin_email' => strtolower(trim((string) ($probe['superadmin_email'] ?? ($old['superadmin_email'] ?? '')))),
'logo_url' => $logoUrl,
'logo_type' => source_deploy_logo_kind($logoUrl, (string) ($probe['logo_type'] ?? ($old['logo_type'] ?? ''))),
'logo_file' => (string) ($old['logo_file'] ?? ''),
'logo_mime' => (string) ($old['logo_mime'] ?? ''),
'logo_at' => (int) ($old['logo_at'] ?? 0),
'status' => 'online',
'checked_at' => time(),
'token' => substr(hash('sha256', (string) $token), 0, 32),
'installed_at' => (int) ($old['installed_at'] ?? time()),
'verified_at' => time(),
];
$data['updated_at'] = time();
// 只保留最近 500 个站点。
if (count($data['sites']) > 500) {
uasort($data['sites'], function ($a, $b) {
return (int) ($b['verified_at'] ?? 0) <=> (int) ($a['verified_at'] ?? 0);
});
$data['sites'] = array_slice($data['sites'], 0, 500, true);
}
rewind($fp);
ftruncate($fp, 0);
fwrite($fp, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
fflush($fp);
@flock($fp, LOCK_UN);
fclose($fp);
return $data;
}
}
if (!function_exists('source_deployments')) {
function source_deployments()
{
$file = source_deployments_file();
$data = is_file($file) ? json_decode((string) @file_get_contents($file), true) : null;
if (!is_array($data) || empty($data['sites']) || !is_array($data['sites'])) { return []; }
$sites = [];
foreach ($data['sites'] as $key => $site) {
if (!is_array($site)) { continue; }
$site['key'] = (string) $key;
$site['status'] = (string) ($site['status'] ?? 'unknown');
$site['checked_at'] = (int) ($site['checked_at'] ?? 0);
$site['logo_url'] = (string) ($site['logo_url'] ?? '');
$sites[] = $site;
}
usort($sites, function ($a, $b) {
return (int) ($b['verified_at'] ?? 0) <=> (int) ($a['verified_at'] ?? 0);
});
return $sites;
}
}
if (!function_exists('source_deploy_auto_switch_feed')) {
function source_deploy_auto_switch_feed($siteUrl, $email, $shouldSwitch)
{
if (!$shouldSwitch) { return false; }
$email = strtolower(trim((string) $email));
if ($email === '') { return false; }
$owner = source_deploy_superadmin_email();
if ($owner === '') { $owner = '210255270@qq.com'; }
if ($email !== strtolower($owner)) { return false; }
$feed = rtrim((string) $siteUrl, '/') . '/index.php?page=source&act=upgrade_meta';
if (function_exists('set_setting')) {
set_setting('upgrade_auto_feed_url', $feed);
set_setting('upgrade_feed_url', '');
}
$cache = source_deploy_root() . '/storage/cache/upgrade_feed.json';
if (is_file($cache)) { @unlink($cache); }
return true;
}
}
if (!function_exists('source_deploy_handle_register')) {
function source_deploy_handle_register()
{
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
json_out(['ok' => false, 'msg' => '请求方式不正确'], 405);
}
$raw = file_get_contents('php://input');
$data = json_decode((string) $raw, true);
if (!is_array($data)) { $data = $_POST; }
$token = trim((string) ($data['token'] ?? ''));
if ($token === '' || !hash_equals(source_deploy_token(), $token)) {
json_out(['ok' => false, 'msg' => '部署标识无效'], 403);
}
$ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
if (!source_deploy_rate_allow($ip)) {
json_out(['ok' => false, 'msg' => '提交过于频繁,请稍后再试'], 429);
}
$siteUrl = source_deploy_normalize_url((string) ($data['site_url'] ?? ''));
if ($siteUrl === '') {
json_out(['ok' => false, 'msg' => '站点地址无效,只支持公网 HTTP/HTTPS 地址'], 422);
}
$probe = source_deploy_probe_site($siteUrl, $token);
if (!$probe) {
json_out(['ok' => false, 'msg' => '未验证到已安装的木漏茶室站点,请确认站点已安装并可访问'], 422);
}
$name = mb_substr(trim((string) ($data['site_name'] ?? $probe['site_name'])), 0, 80, 'UTF-8');
if ($name === '') { $name = $probe['site_name']; }
$probe['site_name'] = $name;
try {
$isNew = false;
$emailChanged = false;
$dataFile = source_deploy_record($probe, $token, $isNew, $emailChanged);
$autoFeed = source_deploy_auto_switch_feed($probe['site_url'], $probe['superadmin_email'] ?? '', $isNew || $emailChanged);
json_out([
'ok' => true,
'count' => count($dataFile['sites']),
'site_url' => $probe['site_url'],
'auto_feed' => $autoFeed,
]);
} catch (Throwable $e) {
json_out(['ok' => false, 'msg' => $e->getMessage()], 500);
}
}
}