Refactor and extend service architecture

Refactored service initialization to support modular loading and error handling. Enhanced Acceleration service with unified output buffering, regex/string replacement, performance logging, and version control for static assets. Added new services for comments, language, lazy translation, migration, modern settings, translation management, and widgets. Improved font loading logic and added RTL mirror support. Updated avatar service to support preconnect for multiple providers. Various bug fixes and code organization improvements.
This commit is contained in:
feibisi 2025-09-27 01:38:32 +08:00
parent be0c09a887
commit f431a7556d
27 changed files with 3424 additions and 1126 deletions

View file

@ -12,15 +12,25 @@ class Plugin {
* 创建插件实例
*/
public function __construct() {
// 尽早加载翻译文件
add_action( 'init', [ $this, 'load_textdomain' ] );
add_action( 'plugins_loaded', [ $this, 'init_services' ] );
new Base();
if ( is_admin() ) {
add_action( 'plugins_loaded', [ $this, 'plugins_loaded' ] );
}
}

public function init_services() {
try {
new Base();
} catch ( \Exception $e ) {
error_log( 'WP-China-Yes: Failed to initialize Base service: ' . $e->getMessage() );
add_action( 'admin_notices', function() use ( $e ) {
echo '<div class="notice notice-error"><p>WP-China-Yes initialization error: ' . esc_html( $e->getMessage() ) . '</p></div>';
});
}
}

/**
* 插件激活时执行
*/
@ -64,42 +74,33 @@ class Plugin {
* 插件兼容性检测函数
*/
public static function check() {
// 确保翻译文件已加载
if ( ! function_exists( 'load_plugin_textdomain' ) ) {
require_once ABSPATH . 'wp-includes/l10n.php';
}
load_plugin_textdomain( 'wp-china-yes', false, dirname( plugin_basename( CHINA_YES_PLUGIN_FILE ) ) . '/languages' );
$notices = [];
if ( version_compare( PHP_VERSION, '7.0.0', '<' ) ) {
deactivate_plugins( 'wp-china-yes/wp-china-yes.php' );
$notices[] = '<div class="notice notice-error"><p>' . sprintf( __( 'WP-China-Yes 插件需要 PHP 7.0.0 或更高版本,当前版本为 %s插件已自动禁用。',
'wp-china-yes' ),
$notices[] = '<div class="notice notice-error"><p>' . sprintf( 'WP-China-Yes 插件需要 PHP 7.0.0 或更高版本,当前版本为 %s插件已自动禁用。',
PHP_VERSION ) . '</p></div>';
}
if ( is_plugin_active( 'wp-china-no/wp-china-no.php' ) ) {
deactivate_plugins( 'wp-china-no/wp-china-no.php' );
$notices[] = '<div class="notice notice-error is-dismissible">
<p><strong>' . __( '检测到旧版插件 WP-China-No已自动禁用', 'wp-china-yes' ) . '</strong></p>
<p><strong>检测到旧版插件 WP-China-No已自动禁用</strong></p>
</div>';
}
if ( is_plugin_active( 'wp-china-plus/wp-china-plus.php' ) ) {
deactivate_plugins( 'wp-china-plus/wp-china-plus.php' );
$notices[] = '<div class="notice notice-error is-dismissible">
<p><strong>' . __( '检测到不兼容的插件 WP-China-Plus已自动禁用', 'wp-china-yes' ) . '</strong></p>
<p><strong>检测到不兼容的插件 WP-China-Plus已自动禁用</strong></p>
</div>';
}
if ( is_plugin_active( 'kill-429/kill-429.php' ) ) {
deactivate_plugins( 'kill-429/kill-429.php' );
$notices[] = '<div class="notice notice-error is-dismissible">
<p><strong>' . __( '检测到不兼容的插件 Kill 429已自动禁用', 'wp-china-yes' ) . '</strong></p>
<p><strong>检测到不兼容的插件 Kill 429已自动禁用</strong></p>
</div>';
}
// 代理服务器检测
if ( defined( 'WP_PROXY_HOST' ) || defined( 'WP_PROXY_PORT' ) ) {
$notices[] = '<div class="notice notice-warning is-dismissible">
<p><strong>' . __( '检测到已在 WordPress 配置文件中设置代理服务器,这可能会导致插件无法正常工作!',
'wp-china-yes' ) . '</strong></p>
<p><strong>检测到已在 WordPress 配置文件中设置代理服务器,这可能会导致插件无法正常工作!</strong></p>
</div>';
}


View file

@ -8,9 +8,17 @@ use function WenPai\ChinaYes\get_settings;

class Acceleration {
private $settings;
private $replacements = [];
private $regex_patterns = [];
private $compiled_patterns = [];
private $buffer_started = false;
private static $cache = [];
private $performance_data = [];
private $debug_mode = false;

public function __construct() {
$this->settings = get_settings();
$this->debug_mode = defined('WP_DEBUG') && WP_DEBUG;
$this->init();
}

@ -18,147 +26,352 @@ class Acceleration {
* 初始化 admincdn 功能
*/
private function init() {
if (!empty($this->settings['admincdn'])) {
add_action('wp_head', function () {
echo "<!-- 此站点使用的前端静态资源库由萌芽加速adminCDN提供智能加速转接基于文派叶子 WPCY.COM -->\n";
}, 1);
if (!$this->should_enable()) {
return;
}

$this->load_admincdn();
add_action('wp_head', function () {
echo "<!-- 此站点使用的前端静态资源库由萌芽加速adminCDN提供智能加速转接基于文派叶子 WPCY.COM -->\n";
}, 1);
$this->prepare_replacements();
$this->start_output_buffer();
$this->init_version_control();
}

/**
* 加载 admincdn 功能
* 检查是否应该启用加速功能
*/
private function load_admincdn() {
// 确保 $this->settings 中包含必要的键
$this->settings['admincdn_files'] = $this->settings['admincdn_files'] ?? [];
$this->settings['admincdn_public'] = $this->settings['admincdn_public'] ?? [];
$this->settings['admincdn_dev'] = $this->settings['admincdn_dev'] ?? [];
private function should_enable() {
return !empty($this->settings['admincdn']) ||
!empty($this->settings['admincdn_files']) ||
!empty($this->settings['admincdn_public']);
}

// WordPress 核心静态文件链接替换
if (is_admin() && !(defined('DOING_AJAX') && DOING_AJAX)) {
if (
in_array('admin', (array) $this->settings['admincdn']) &&
!stristr($GLOBALS['wp_version'], 'alpha') &&
!stristr($GLOBALS['wp_version'], 'beta') &&
!stristr($GLOBALS['wp_version'], 'RC')
) {
// 禁用合并加载,以便于使用公共资源节点
global $concatenate_scripts;
$concatenate_scripts = false;
/**
* 准备所有替换规则
*/
private function prepare_replacements() {
if ($this->has_admin_acceleration()) {
$this->prepare_admin_replacements();
}

$this->page_str_replace('init', 'preg_replace', [
'~' . home_url('/') . '(wp-admin|wp-includes)/(css|js)/~',
sprintf('https://wpstatic.admincdn.com/%s/$1/$2/', $GLOBALS['wp_version'])
]);
if ($this->has_frontend_acceleration()) {
$this->prepare_frontend_replacements();
}

if ($this->has_public_library_acceleration()) {
$this->prepare_public_library_replacements();
}

if ($this->has_dev_library_acceleration()) {
$this->prepare_dev_library_replacements();
}

if ($this->has_special_features()) {
$this->prepare_special_replacements();
}
}

/**
* 检查是否启用管理后台加速
*/
private function has_admin_acceleration() {
return !empty($this->settings['admincdn']) &&
in_array('admin', (array) $this->settings['admincdn']);
}

/**
* 检查是否启用前台加速
*/
private function has_frontend_acceleration() {
return !empty($this->settings['admincdn_files']) &&
in_array('frontend', (array) $this->settings['admincdn_files']);
}

/**
* 检查是否启用公共库加速
*/
private function has_public_library_acceleration() {
return !empty($this->settings['admincdn_public']) &&
is_array($this->settings['admincdn_public']) &&
count($this->settings['admincdn_public']) > 0;
}

/**
* 检查是否启用开发库加速
*/
private function has_dev_library_acceleration() {
return !empty($this->settings['admincdn_dev']) &&
is_array($this->settings['admincdn_dev']) &&
count($this->settings['admincdn_dev']) > 0;
}

/**
* 检查是否启用特殊功能
*/
private function has_special_features() {
return !empty($this->settings['admincdn_files']) &&
(in_array('emoji', (array) $this->settings['admincdn_files']) ||
in_array('sworg', (array) $this->settings['admincdn_files']));
}

/**
* 启动统一的输出缓冲
*/
private function start_output_buffer() {
if ($this->buffer_started || php_sapi_name() == 'cli') {
return;
}

$hook = is_admin() ? 'admin_init' : 'template_redirect';
add_action($hook, function () {
if (!$this->buffer_started) {
ob_start([$this, 'process_buffer']);
$this->buffer_started = true;
}
}, 1);

add_action('wp_footer', [$this, 'end_buffer'], 999);
add_action('admin_footer', [$this, 'end_buffer'], 999);
}

/**
* 处理输出缓冲内容
*/
public function process_buffer($buffer) {
if (empty($buffer)) {
return $buffer;
}

$start_time = microtime(true);
$buffer_size = strlen($buffer);
$buffer_hash = md5($buffer);

if (isset(self::$cache[$buffer_hash])) {
$this->log_performance('cache_hit', microtime(true) - $start_time, $buffer_size);
return self::$cache[$buffer_hash];
}

$original_buffer = $buffer;
$replacements_made = 0;

if (!empty($this->regex_patterns)) {
$regex_start = microtime(true);
$this->compile_patterns();
foreach ($this->compiled_patterns as $pattern_data) {
$before = $buffer;
$buffer = preg_replace($pattern_data['pattern'], $pattern_data['replacement'], $buffer);
if (preg_last_error() !== PREG_NO_ERROR) {
$this->log_error('Regex error in pattern: ' . $pattern_data['pattern']);
continue;
}
if ($before !== $buffer) {
$replacements_made++;
}
}
$this->log_performance('regex_processing', microtime(true) - $regex_start, count($this->compiled_patterns));
}

if (!empty($this->replacements)) {
$str_start = microtime(true);
$searches = array_keys($this->replacements);
$replaces = array_values($this->replacements);
$before = $buffer;
$buffer = str_replace($searches, $replaces, $buffer);
if ($before !== $buffer) {
$replacements_made++;
}
$this->log_performance('string_processing', microtime(true) - $str_start, count($this->replacements));
}

if (count(self::$cache) < 100) {
self::$cache[$buffer_hash] = $buffer;
}

$total_time = microtime(true) - $start_time;
$this->log_performance('total_processing', $total_time, $replacements_made);

if ($this->debug_mode && $replacements_made > 0) {
$buffer .= sprintf(
'<!-- Acceleration: %d replacements in %.4fs, buffer size: %s -->',
$replacements_made,
$total_time,
$this->format_bytes($buffer_size)
);
}

return $buffer;
}

/**
* 记录性能数据
*/
private function log_performance($operation, $time, $count) {
if (!$this->debug_mode) {
return;
}

$this->performance_data[] = [
'operation' => $operation,
'time' => $time,
'count' => $count,
'timestamp' => microtime(true)
];
}

/**
* 记录错误信息
*/
private function log_error($message) {
if ($this->debug_mode) {
error_log('Acceleration: ' . $message);
}
}

/**
* 格式化字节数
*/
private function format_bytes($bytes) {
$units = ['B', 'KB', 'MB', 'GB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, 2) . ' ' . $units[$pow];
}

/**
* 编译正则表达式模式
*/
private function compile_patterns() {
if (!empty($this->compiled_patterns)) {
return;
}

foreach ($this->regex_patterns as $pattern => $replacement) {
if (!$this->is_valid_regex($pattern)) {
error_log('Acceleration: Invalid regex pattern: ' . $pattern);
continue;
}

$this->compiled_patterns[] = [
'pattern' => $pattern,
'replacement' => $replacement
];
}
}

/**
* 验证正则表达式是否有效
*/
private function is_valid_regex($pattern) {
return @preg_match($pattern, '') !== false;
}

/**
* 结束输出缓冲
*/
public function end_buffer() {
if ($this->buffer_started && ob_get_level()) {
ob_end_flush();
}
}

/**
* 准备管理后台替换规则
*/
private function prepare_admin_replacements() {
if (!is_admin() || (defined('DOING_AJAX') && DOING_AJAX)) {
return;
}

if (in_array('admin', (array) $this->settings['admincdn']) &&
!stristr($GLOBALS['wp_version'], 'alpha') &&
!stristr($GLOBALS['wp_version'], 'beta') &&
!stristr($GLOBALS['wp_version'], 'RC')) {
global $concatenate_scripts;
$concatenate_scripts = false;

$pattern = '~' . preg_quote(home_url('/'), '~') . '(wp-admin|wp-includes)/(css|js)/~';
$replacement = sprintf('https://wpstatic.admincdn.com/%s/$1/$2/', $GLOBALS['wp_version']);
$this->regex_patterns[$pattern] = $replacement;
}
}

/**
* 准备前台替换规则
*/
private function prepare_frontend_replacements() {
if (in_array('frontend', (array) $this->settings['admincdn_files'])) {
$pattern = '#(?<=[(\"\'])(?:' . quotemeta(home_url()) . ')?/(?:((?:wp-content|wp-includes)[^\"\')]+\.(css|js)[^\"\')]+))(?=[\"\')])#';
$this->regex_patterns[$pattern] = 'https://public.admincdn.com/$0';
}
}

/**
* 准备公共库替换规则
*/
private function prepare_public_library_replacements() {
$public_libraries = [
'googlefonts' => ['fonts.googleapis.com', 'googlefonts.admincdn.com'],
'googleajax' => ['ajax.googleapis.com', 'googleajax.admincdn.com'],
'cdnjs' => ['cdnjs.cloudflare.com/ajax/libs', 'cdnjs.admincdn.com'],
'jsdelivr' => ['cdn.jsdelivr.net', 'jsd.admincdn.com'],
'bootstrapcdn' => ['maxcdn.bootstrapcdn.com', 'jsd.admincdn.com'],
];

foreach ($public_libraries as $key => $replacement) {
if (in_array($key, (array) $this->settings['admincdn_public'])) {
$this->replacements[$replacement[0]] = $replacement[1];
}
}
}

// 前台静态加速
if (in_array('frontend', (array) $this->settings['admincdn_files'])) {
$this->page_str_replace('template_redirect', 'preg_replace', [
'#(?<=[(\"\'])(?:' . quotemeta(home_url()) . ')?/(?:((?:wp-content|wp-includes)[^\"\')]+\.(css|js)[^\"\')]+))(?=[\"\')])#',
'https://public.admincdn.com/$0'
]);
}
/**
* 准备开发库替换规则
*/
private function prepare_dev_library_replacements() {
$dev_libraries = [
'react' => ['unpkg.com/react', 'jsd.admincdn.com/npm/react'],
'jquery' => ['code.jquery.com', 'jsd.admincdn.com/npm/jquery'],
'vuejs' => ['unpkg.com/vue', 'jsd.admincdn.com/npm/vue'],
'datatables' => ['cdn.datatables.net', 'jsd.admincdn.com/npm/datatables.net'],
'tailwindcss' => ['unpkg.com/tailwindcss', 'jsd.admincdn.com/npm/tailwindcss'],
];

// Google 字体替换
if (in_array('googlefonts', (array) $this->settings['admincdn_public'])) {
$this->page_str_replace('init', 'str_replace', [
'fonts.googleapis.com',
'googlefonts.admincdn.com'
]);
}

// Google 前端公共库替换
if (in_array('googleajax', (array) $this->settings['admincdn_public'])) {
$this->page_str_replace('init', 'str_replace', [
'ajax.googleapis.com',
'googleajax.admincdn.com'
]);
}

// CDNJS 前端公共库替换
if (in_array('cdnjs', (array) $this->settings['admincdn_public'])) {
$this->page_str_replace('init', 'str_replace', [
'cdnjs.cloudflare.com/ajax/libs',
'cdnjs.admincdn.com'
]);
}

// jsDelivr 前端公共库替换
if (in_array('jsdelivr', (array) $this->settings['admincdn_public'])) {
$this->page_str_replace('init', 'str_replace', [
'cdn.jsdelivr.net',
'jsd.admincdn.com'
]);
}

// BootstrapCDN 前端公共库替换
if (in_array('bootstrapcdn', (array) $this->settings['admincdn_public'])) {
$this->page_str_replace('init', 'str_replace', [
'maxcdn.bootstrapcdn.com',
'jsd.admincdn.com'
]);
}

// Emoji 资源加速 - 使用 Twitter Emoji
if (in_array('emoji', (array) $this->settings['admincdn_files'])) {
$this->replace_emoji();
}

// WordPress.org 预览资源加速
if (in_array('sworg', (array) $this->settings['admincdn_files'])) {
$this->replace_sworg();
}

// React 前端库加速
if (in_array('react', (array) $this->settings['admincdn_dev'])) {
$this->page_str_replace('init', 'str_replace', [
'unpkg.com/react',
'jsd.admincdn.com/npm/react'
]);
}

// jQuery 前端库加速
if (in_array('jquery', (array) $this->settings['admincdn_dev'])) {
$this->page_str_replace('init', 'str_replace', [
'code.jquery.com',
'jsd.admincdn.com/npm/jquery'
]);
}

// Vue.js 前端库加速
if (in_array('vuejs', (array) $this->settings['admincdn_dev'])) {
$this->page_str_replace('init', 'str_replace', [
'unpkg.com/vue',
'jsd.admincdn.com/npm/vue'
]);
}

// DataTables 前端库加速
if (in_array('datatables', (array) $this->settings['admincdn_dev'])) {
$this->page_str_replace('init', 'str_replace', [
'cdn.datatables.net',
'jsd.admincdn.com/npm/datatables.net'
]);
}

// Tailwind CSS 加速
if (in_array('tailwindcss', (array) $this->settings['admincdn_dev'])) {
$this->page_str_replace('init', 'str_replace', [
'unpkg.com/tailwindcss',
'jsd.admincdn.com/npm/tailwindcss'
]);
foreach ($dev_libraries as $key => $replacement) {
if (in_array($key, (array) $this->settings['admincdn_dev'])) {
$this->replacements[$replacement[0]] = $replacement[1];
}
}
}

/**
* 替换 Emoji 资源
* 准备特殊功能替换规则
*/
private function replace_emoji() {
// 禁用 WordPress 默认的 emoji 处理
private function prepare_special_replacements() {
if (in_array('emoji', (array) $this->settings['admincdn_files'])) {
$this->prepare_emoji_replacements();
}

if (in_array('sworg', (array) $this->settings['admincdn_files'])) {
$this->prepare_sworg_replacements();
}
}

/**
* 准备Emoji替换规则
*/
private function prepare_emoji_replacements() {
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('wp_print_styles', 'print_emoji_styles');
@ -167,13 +380,8 @@ class Acceleration {
remove_filter('comment_text_rss', 'wp_staticize_emoji');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');

// 替换 emoji 图片路径
$this->page_str_replace('init', 'str_replace', [
's.w.org/images/core/emoji',
'jsd.admincdn.com/npm/@twemoji/api/dist'
]);
$this->replacements['s.w.org/images/core/emoji'] = 'jsd.admincdn.com/npm/@twemoji/api/dist';

// 替换 wpemojiSettings 配置
add_action('wp_head', function () {
?>
<script>
@ -192,23 +400,15 @@ class Acceleration {
}

/**
* 替换 WordPress.org 预览资源
* 准备WordPress.org资源替换规则
*/
private function replace_sworg() {
$this->page_str_replace('init', 'str_replace', [
'ts.w.org',
'ts.wenpai.net'
]);
private function prepare_sworg_replacements() {
$this->replacements['ts.w.org'] = 'ts.wenpai.net';

// 替换主题预览图片 URL
add_filter('theme_screenshot_url', function ($url) {
if (strpos($url, 'ts.w.org') !== false) {
$url = str_replace('ts.w.org', 'ts.wenpai.net', $url);
}
return $url;
return str_replace('ts.w.org', 'ts.wenpai.net', $url);
});

// 过滤主题 API 响应
add_filter('themes_api_result', function ($res, $action, $args) {
if (is_object($res) && !empty($res->screenshots)) {
foreach ($res->screenshots as &$screenshot) {
@ -219,20 +419,118 @@ class Acceleration {
}
return $res;
}, 10, 3);
}

// 替换页面内容
add_action('admin_init', function () {
ob_start(function ($content) {
return str_replace('ts.w.org', 'ts.wenpai.net', $content);
});
});
/**
* 加载 admincdn 功能(保持向后兼容)
*/
private function load_admincdn() {
$this->settings['admincdn_files'] = $this->settings['admincdn_files'] ?? [];
$this->settings['admincdn_public'] = $this->settings['admincdn_public'] ?? [];
$this->settings['admincdn_dev'] = $this->settings['admincdn_dev'] ?? [];
}

// 确保前台内容替换
add_action('template_redirect', function () {
ob_start(function ($content) {
return str_replace('ts.w.org', 'ts.wenpai.net', $content);
});
});


/**
* 初始化版本控制功能
*/
private function init_version_control() {
if (empty($this->settings['admincdn_version_enable'])) {
return;
}

$version_settings = (array) $this->settings['admincdn_version'];
if (empty($version_settings)) {
return;
}

if (in_array('css', $version_settings)) {
add_filter('style_loader_src', [$this, 'version_filter']);
}

if (in_array('js', $version_settings)) {
add_filter('script_loader_src', [$this, 'version_filter']);
}
}

/**
* 版本控制过滤器
*/
public function version_filter($src) {
$version_settings = (array) $this->settings['admincdn_version'];
$url_parts = wp_parse_url($src);
if (!isset($url_parts['path'])) {
return $src;
}

$extension = pathinfo($url_parts['path'], PATHINFO_EXTENSION);
if (!$extension || !in_array($extension, ['css', 'js'])) {
return $src;
}

if (!in_array($extension, $version_settings)) {
return $src;
}

if (defined('AUTOVER_DISABLE_' . strtoupper($extension))) {
return $src;
}

$file_path = rtrim(ABSPATH, '/') . urldecode($url_parts['path']);
if (!is_file($file_path)) {
return $src;
}

$timestamp_version = filemtime($file_path) ?: filemtime(utf8_decode($file_path));
if (!$timestamp_version) {
return $src;
}

if (!isset($url_parts['query'])) {
$url_parts['query'] = '';
}

$query = [];
parse_str($url_parts['query'], $query);
if (in_array('disable_query', $version_settings)) {
unset($query['v']);
unset($query['ver']);
unset($query['version']);
} else {
unset($query['v']);
unset($query['ver']);
if (in_array('timestamp', $version_settings)) {
$query['ver'] = $timestamp_version;
} else {
$query['ver'] = md5($timestamp_version);
}
}
$url_parts['query'] = http_build_query($query);

return $this->build_url($url_parts);
}

/**
* 构建URL
*/
private function build_url(array $parts) {
return (isset($parts['scheme']) ? "{$parts['scheme']}:" : '') .
((isset($parts['user']) || isset($parts['host'])) ? '//' : '') .
(isset($parts['user']) ? "{$parts['user']}" : '') .
(isset($parts['pass']) ? ":{$parts['pass']}" : '') .
(isset($parts['user']) ? '@' : '') .
(isset($parts['host']) ? "{$parts['host']}" : '') .
(isset($parts['port']) ? ":{$parts['port']}" : '') .
(isset($parts['path']) ? "{$parts['path']}" : '') .
(isset($parts['query']) ? "?{$parts['query']}" : '') .
(isset($parts['fragment']) ? "#{$parts['fragment']}" : '');
}

/**

View file

@ -24,12 +24,14 @@ class Avatar {
* 初始化初认头像功能
*/
private function init() {
if (!empty($this->settings['cravatar'])) {
if (!empty($this->settings['cravatar']) && $this->settings['cravatar'] !== 'off') {
add_filter('user_profile_picture_description', [$this, 'set_user_profile_picture_for_cravatar'], 1);
add_filter('avatar_defaults', [$this, 'set_defaults_for_cravatar'], 1);
add_filter('um_user_avatar_url_filter', [$this, 'get_cravatar_url'], 1);
add_filter('bp_gravatar_url', [$this, 'get_cravatar_url'], 1);
add_filter('get_avatar_url', [$this, 'get_cravatar_url'], 1);
add_action('wp_head', [$this, 'add_avatar_preconnect'], 1);
}
}

@ -95,4 +97,21 @@ class Avatar {
return '<a href="https://cravatar.com" target="_blank">您可以在初认头像修改您的资料图片</a>';
}
}

public function add_avatar_preconnect() {
switch ($this->settings['cravatar']) {
case 'cn':
echo '<link rel="dns-prefetch" href="//cn.cravatar.com">' . "\n";
echo '<link rel="preconnect" href="https://cn.cravatar.com" crossorigin>' . "\n";
break;
case 'global':
echo '<link rel="dns-prefetch" href="//en.cravatar.com">' . "\n";
echo '<link rel="preconnect" href="https://en.cravatar.com" crossorigin>' . "\n";
break;
case 'weavatar':
echo '<link rel="dns-prefetch" href="//weavatar.com">' . "\n";
echo '<link rel="preconnect" href="https://weavatar.com" crossorigin>' . "\n";
break;
}
}
}

View file

@ -11,38 +11,51 @@ defined( 'ABSPATH' ) || exit;
*/
class Base {

private $services = [];

public function __construct() {
// 确保所有类文件都存在后再实例化
if (class_exists(__NAMESPACE__ . '\Super')) {
new Super();
}
if (class_exists(__NAMESPACE__ . '\Monitor')) {
new Monitor();
}
if (class_exists(__NAMESPACE__ . '\Memory')) {
new Memory();
}
if (class_exists(__NAMESPACE__ . '\Update')) {
new Update();
}
if (class_exists(__NAMESPACE__ . '\Database')) {
new Database();
}
if (class_exists(__NAMESPACE__ . '\Acceleration')) {
new Acceleration();
$this->init_services();
}

private function init_services() {
$core_services = [
'Super',
'Monitor',
'Memory',
'Update',
'Database',
'Acceleration',
'Avatar',
'Fonts',
'Comments',
'Media',
'Performance',
'Maintenance'
];

foreach ($core_services as $service) {
$this->load_service($service);
}

if (class_exists(__NAMESPACE__ . '\Maintenance')) {
new Maintenance();
}

if ( is_admin() && class_exists(__NAMESPACE__ . '\Setting')) {
new Setting();
if (is_admin()) {
$this->load_service('Setting');
$this->load_service('Adblock');
}
}

private function load_service($service_name) {
$class_name = __NAMESPACE__ . '\\' . $service_name;
if (class_exists($class_name)) {
try {
$this->services[$service_name] = new $class_name();
} catch (\Exception $e) {
error_log("WP-China-Yes: Failed to load service {$service_name}: " . $e->getMessage());
}
}
}

public function get_service($service_name) {
return $this->services[$service_name] ?? null;
}
}

View file

@ -0,0 +1,411 @@
<?php

namespace WenPai\ChinaYes\Service;

defined('ABSPATH') || exit;

use function WenPai\ChinaYes\get_settings;

class Comments {
private $settings;

public function __construct() {
$this->settings = get_settings();
add_action('wp_enqueue_scripts', [$this, 'force_enqueue_jquery'], 5);
$this->init();
}

public function force_enqueue_jquery() {
if (!is_admin()) {
wp_enqueue_script('jquery');
}
}

private function init() {
if (!isset($this->settings['comments_enable']) || !$this->settings['comments_enable']) {
return;
}

$this->init_role_badge();
$this->init_remove_website();
$this->init_validation();
$this->init_herp_derp();
$this->init_sticky_moderate();
}

private function init_role_badge() {
if (!isset($this->settings['comments_role_badge']) || !$this->settings['comments_role_badge']) {
return;
}

add_action('wp_enqueue_scripts', [$this, 'enqueue_role_badge_styles']);
add_filter('get_comment_author', [$this, 'add_role_badge'], 10, 3);
add_filter('get_comment_author_link', [$this, 'add_role_badge_to_link']);
}

private function init_remove_website() {
if (!isset($this->settings['comments_remove_website']) || !$this->settings['comments_remove_website']) {
return;
}

add_filter('comment_form_default_fields', [$this, 'remove_website_field']);
}

private function init_validation() {
if (!isset($this->settings['comments_validation']) || !$this->settings['comments_validation']) {
return;
}

add_action('wp_enqueue_scripts', [$this, 'enqueue_validation_scripts']);
add_action('wp_footer', [$this, 'add_validation_script']);
add_filter('preprocess_comment', [$this, 'validate_comment_content']);
}

private function init_herp_derp() {
if (!isset($this->settings['comments_herp_derp']) || !$this->settings['comments_herp_derp']) {
return;
}

add_action('wp_enqueue_scripts', [$this, 'enqueue_herp_derp_scripts']);
add_action('wp_head', [$this, 'add_herp_derp_styles']);
add_filter('comment_text', [$this, 'herp_derp_comment_text'], 40);
}

private function init_sticky_moderate() {
if (!isset($this->settings['comments_sticky_moderate']) || !$this->settings['comments_sticky_moderate']) {
return;
}

add_action('admin_enqueue_scripts', [$this, 'enqueue_sticky_moderate_scripts']);
add_filter('comment_row_actions', [$this, 'add_sticky_moderate_actions'], 10, 2);
}

private $user_role = '';

public function enqueue_role_badge_styles() {
wp_add_inline_style('wp-block-library', '
.comment-author-role-badge {
display: inline-block;
padding: 3px 6px;
margin-left: 0.5em;
margin-right: 0.5em;
background: #e8e8e8;
border-radius: 2px;
color: rgba(0, 0, 0, 0.6);
font-size: 0.75rem;
font-weight: normal;
text-transform: none;
text-align: left;
line-height: 1;
white-space: nowrap;
vertical-align: middle;
}
.comment-author-role-badge--administrator { background: #c1e7f1; }
.comment-author-role-badge--contributor { background: #c1f1d1; }
.comment-author-role-badge--author { background: #fdf5c5; }
.comment-author-role-badge--editor { background: #fdd8c5; }
.comment-author-role-badge--subscriber { background: #e8e8e8; }
.wp-block-comment-author-name .comment-author-role-badge {
display: inline-block;
margin-left: 0.5em;
font-size: 0.75rem;
vertical-align: middle;
}
');
}

public function add_role_badge($author, $comment_id, $comment) {
global $wp_roles;
if ($wp_roles) {
$reply_user_id = $comment->user_id;
if ($reply_user_id && $reply_user = new \WP_User($reply_user_id)) {
if (isset($reply_user->roles[0])) {
$user_role = translate_user_role($wp_roles->roles[$reply_user->roles[0]]['name']);
$this->user_role = '<div class="comment-author-role-badge comment-author-role-badge--' . $reply_user->roles[0] . '">' . $user_role . '</div>';
}
} else {
$this->user_role = '';
}
}
return $author;
}

public function add_role_badge_to_link($author_link) {
return $author_link . $this->user_role;
}

public function remove_website_field($fields) {
if (isset($fields['url'])) {
unset($fields['url']);
}
return $fields;
}

public function enqueue_validation_scripts() {
if (!is_singular() || !comments_open()) {
return;
}

wp_enqueue_script('jquery');
wp_register_script('wpcy-comments-validation', '', ['jquery'], '1.0.0', true);
wp_enqueue_script('wpcy-comments-validation');
wp_add_inline_script('wpcy-comments-validation', '
jQuery(document).ready(function($) {
console.log("WP China Yes Comments: Validation script loaded");
$("#commentform").on("submit", function(e) {
var author = $("#author").val();
var email = $("#email").val();
var comment = $("#comment").val();
var errors = [];

if ($("#author").length && (!author || author.length < 2)) {
errors.push("请输入您的姓名至少2个字符");
}

if ($("#email").length && (!email || !isValidEmail(email))) {
errors.push("请输入有效的邮箱地址");
}

if ($("#comment").length && (!comment || comment.length < 20)) {
errors.push("评论内容至少需要20个字符");
}

if (errors.length > 0) {
e.preventDefault();
alert("请修正以下错误:\n" + errors.join("\n"));
return false;
}
});

function isValidEmail(email) {
var regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
});
');
}

public function add_validation_script() {
if (!is_singular() || !comments_open()) {
return;
}
?>
<style>
.comment-form .required {
color: #d63638;
}
.comment-form input:invalid,
.comment-form textarea:invalid {
border-color: #d63638;
}
</style>
<?php
}

public function validate_comment_content($commentdata) {
if (strlen($commentdata['comment_content']) < 20) {
wp_die('评论内容至少需要20个字符。', '评论验证失败', ['back_link' => true]);
}

if (str_contains($commentdata['comment_content'], 'href=')) {
wp_die('评论中不允许包含活动链接,请返回编辑。', '评论验证失败', ['back_link' => true]);
}

return $commentdata;
}

public function enqueue_herp_derp_scripts() {
if (!is_singular() || !comments_open()) {
return;
}

wp_enqueue_script('jquery');
wp_register_script('wpcy-comments-herpderp', '', ['jquery'], '1.0.0', true);
wp_enqueue_script('wpcy-comments-herpderp');
wp_add_inline_script('wpcy-comments-herpderp', '
jQuery(document).ready(function($) {
console.log("WP China Yes Comments: Herp Derp jQuery ready");
function derp(p, herpa) {
if (!p.herp) {
p.herp = p.innerHTML;
var textContent = p.herp.replace(/<[^>]*>/g, "");
var derpText = "";
var chars = textContent.split("");
var inWord = false;
for (var i = 0; i < chars.length; i++) {
var char = chars[i];
if (/[a-zA-Z]/.test(char)) {
if (!inWord) {
if (derpText && !/\s$/.test(derpText)) derpText += " ";
derpText += "阿巴";
inWord = true;
}
} else if (/[\u4e00-\u9fff]/.test(char)) {
if (inWord && !/\s$/.test(derpText)) derpText += " ";
derpText += Math.random() > 0.5 ? "阿" : "巴";
inWord = false;
} else if (/\s/.test(char)) {
if (inWord) {
inWord = false;
}
if (derpText && !/\s$/.test(derpText)) {
derpText += " ";
}
}
}
p.derp = derpText.trim();
}
p.innerHTML = (herpa ? p.herp : p.derp);
}

function herpa(derpa) {
$(".herpc").each(function() {
derp(this, !derpa);
});
}

function initHerpDerp() {
var commentsContainer = $("#comments, .comments-area, .comment-list, ol.commentlist, .wp-block-comments");
console.log("Comments containers found:", commentsContainer.length);
if (commentsContainer.length === 0) {
console.log("No comments container found, trying body");
var bodyContainer = $("body");
if (bodyContainer.length > 0) {
var herpDiv = $("<div class=\"herpderp\" style=\"position: fixed; top: 10px; right: 10px; z-index: 9999; background: white; padding: 5px; border: 1px solid #ccc;\"></div>");
var checkbox = $("<input type=\"checkbox\" id=\"herp-derp-toggle\">");
var label = $("<label for=\"herp-derp-toggle\">阿巴阿巴</label>");
herpDiv.append(label).append(checkbox);
checkbox.on("change", function() {
console.log("Herp derp toggled:", this.checked);
herpa(this.checked);
});
bodyContainer.append(herpDiv);
}
return;
}

var targetContainer = commentsContainer.first();
console.log("Target container:", targetContainer[0]);
var herpDiv = $("<div class=\"herpderp\"></div>");
var checkbox = $("<input type=\"checkbox\" id=\"herp-derp-toggle\">");
var label = $("<label for=\"herp-derp-toggle\">阿巴阿巴</label>");
herpDiv.append(label).append(checkbox);
checkbox.on("change", function() {
console.log("Herp derp toggled:", this.checked);
herpa(this.checked);
});
targetContainer.before(herpDiv);
}

initHerpDerp();
});
');
}

public function add_herp_derp_styles() {
if (!is_singular() || !comments_open()) {
return;
}
?>
<style type="text/css">
.herpderp {
float: right;
text-transform: uppercase;
font-size: 7pt;
font-weight: bold;
margin-bottom: 10px;
}
.herpderp input[type="checkbox"] {
margin-left: 5px;
}
</style>
<?php
}

public function herp_derp_comment_text($text) {
if (!is_singular() || is_feed()) {
return $text;
}
return '<span class="herpc">' . $text . '</span>';
}

public function enqueue_sticky_moderate_scripts($hook) {
if ($hook !== 'edit-comments.php') {
return;
}

wp_enqueue_script('jquery');
wp_add_inline_script('jquery', '
jQuery(document).ready(function($) {
$(".comment-sticky-moderate").on("click", function(e) {
e.preventDefault();
var commentId = $(this).data("comment-id");
var action = $(this).hasClass("sticky") ? "unsticky" : "sticky";
$.post(ajaxurl, {
action: "sticky_moderate_comment",
comment_id: commentId,
sticky_action: action,
nonce: "' . wp_create_nonce('sticky_moderate_nonce') . '"
}, function(response) {
if (response.success) {
location.reload();
}
});
});
});
');

add_action('wp_ajax_sticky_moderate_comment', [$this, 'handle_sticky_moderate_ajax']);
}

public function add_sticky_moderate_actions($actions, $comment) {
if ($comment->comment_approved == '0') {
$is_sticky = get_comment_meta($comment->comment_ID, '_sticky_moderate', true);
$text = $is_sticky ? '取消置顶' : '置顶审核';
$class = $is_sticky ? 'sticky' : '';
$actions['sticky_moderate'] = sprintf(
'<a href="#" class="comment-sticky-moderate %s" data-comment-id="%d">%s</a>',
$class,
$comment->comment_ID,
$text
);
}
return $actions;
}

public function handle_sticky_moderate_ajax() {
if (!wp_verify_nonce($_POST['nonce'], 'sticky_moderate_nonce')) {
wp_die('安全验证失败');
}

$comment_id = intval($_POST['comment_id']);
$action = sanitize_text_field($_POST['sticky_action']);

if ($action === 'sticky') {
update_comment_meta($comment_id, '_sticky_moderate', 1);
} else {
delete_comment_meta($comment_id, '_sticky_moderate');
}

wp_send_json_success();
}
}

View file

@ -0,0 +1,96 @@
<?php

namespace WenPai\ChinaYes\Service;

use WenPai\ChinaYes\Service\TranslationManager;
use WenPai\ChinaYes\Service\LazyTranslation;

class ExampleModernService {
private $settings;
public function __construct() {
add_action('init', [$this, 'initializeService'], 15);
}
public function initializeService() {
$this->setupTranslatedContent();
}
private function setupTranslatedContent() {
$translatedOptions = [
'store_section' => [
'title' => $this->t('应用市场'),
'description' => $this->t('选择您的应用市场加速方式'),
'options' => [
'wenpai' => $this->t('文派开源'),
'proxy' => $this->t('官方镜像'),
'off' => $this->t('不启用')
]
],
'acceleration_section' => [
'title' => $this->t('萌芽加速'),
'description' => $this->t('前端资源加速设置'),
'options' => [
'googlefonts' => 'Google 字体',
'googleajax' => 'Google 前端库',
'cdnjs' => 'CDNJS 前端库'
]
],
'notification_section' => [
'title' => $this->t('通知管理'),
'description' => $this->t('管理和控制 WordPress 后台各类通知的显示。'),
'options' => [
'disable_all' => $this->t('禁用所有通知'),
'selective' => $this->t('选择性禁用'),
'method' => $this->t('禁用方式')
]
]
];
$this->processTranslatedOptions($translatedOptions);
}
private function processTranslatedOptions($options) {
foreach ($options as $section => $data) {
error_log("处理部分: " . $data['title']);
error_log("描述: " . $data['description']);
foreach ($data['options'] as $key => $value) {
error_log("选项 {$key}: {$value}");
}
}
}
private function t($text) {
return TranslationManager::translate($text);
}
public function demonstrateLazyTranslation() {
$lazyTitle = LazyTranslation::create('应用市场');
$lazyArray = LazyTranslation::createArray([
'title' => '萌芽加速',
'subtitle' => '文件加速',
'options' => [
'enable' => '启用',
'disable' => '禁用'
]
]);
return [
'lazy_title' => $lazyTitle,
'lazy_array' => $lazyArray,
'resolved_title' => (string)$lazyTitle,
'resolved_array' => LazyTranslation::resolveArray($lazyArray)
];
}
public function getTranslationStatus() {
return [
'translations_loaded' => TranslationManager::isLoaded(),
'init_action_fired' => did_action('init'),
'plugins_loaded_fired' => did_action('plugins_loaded'),
'current_hook' => current_action()
];
}
}

View file

@ -42,16 +42,38 @@ class Fonts {
if (!empty($this->settings['windfonts']) && $this->settings['windfonts'] == 'frontend') {
add_action('wp_head', [$this, 'load_windfonts']);
}

$this->init_rtl_mirror();
}

/**
* 初始化RTL镜像测试功能
*/
private function init_rtl_mirror() {
if (empty($this->settings['windfonts_reading_enable'])) {
return;
}

$reading_setting = $this->settings['windfonts_reading'] ?? 'off';

if ($reading_setting === 'global' || $reading_setting === 'frontend') {
$this->load_rtl_mirror($reading_setting);
}
}

/**
* 加载文风字体
*/
public function load_windfonts() {
echo <<<HTML
<link rel="preconnect" href="//cn.windfonts.com">
static $license_shown = false;
if (!$license_shown) {
echo <<<HTML
<link rel="preconnect" href="https://cn.windfonts.com">
<!-- 此中文网页字体由文风字体Windfonts免费提供您可以自由引用请务必保留此授权许可标注 https://wenfeng.org/license -->
HTML;
$license_shown = true;
}

$loaded = [];
foreach ((array) $this->settings['windfonts_list'] as $font) {
@ -61,11 +83,17 @@ HTML;
if (empty($font['family'])) {
continue;
}
if (in_array($font['css'], $loaded)) {
$css_url = $this->build_font_css_url($font);
if (in_array($css_url, $loaded)) {
continue;
}
$font_family = $this->extract_font_family_name($font['family']);
echo sprintf(<<<HTML
<link rel="stylesheet" type="text/css" href="%s">
<link rel="stylesheet" type="text/css" crossorigin="anonymous" href="%s">
<style>
%s {
font-style: %s;
@ -75,22 +103,61 @@ HTML;
</style>
HTML
,
$font['css'],
$css_url,
htmlspecialchars_decode($font['selector']),
$font['style'],
$font['weight'],
$font['family']
$font['style'] ?? 'normal',
$font['weight'] ?? 400,
$font_family
);
$loaded[] = $font['css'];
$loaded[] = $css_url;
}
}

/**
* 构建字体CSS URL
*/
private function build_font_css_url($font) {
$base_url = 'https://app.windfonts.com/api/css';
$params = [];
$params['family'] = $font['family'];
if (!empty($font['subset'])) {
$params['subset'] = $font['subset'];
}
if (!empty($font['lang'])) {
$params['lang'] = $font['lang'];
}
return $base_url . '?' . http_build_query($params);
}

/**
* 提取字体家族名称
*/
private function extract_font_family_name($family_param) {
if (strpos($family_param, ':') !== false) {
return explode(':', $family_param)[0];
}
return $family_param;
}

/**
* 加载排印优化
*/
public function load_typography() {
// 支持中文排版段首缩进 2em
if (in_array('indent', (array) $this->settings['windfonts_typography'])) {
$this->load_chinese_typography();
$this->load_english_typography();
}

/**
* 加载中文排印优化
*/
private function load_chinese_typography() {
$cn_settings = (array) $this->settings['windfonts_typography_cn'];

if (in_array('indent', $cn_settings)) {
add_action('wp_head', function () {
echo '<style>
.entry-content p {
@ -106,10 +173,9 @@ HTML
});
}

// 支持中文排版两端对齐
if (in_array('align', (array) $this->settings['windfonts_typography'])) {
if (in_array('align', $cn_settings)) {
add_action('wp_head', function () {
if (is_single()) { // 仅在文章页面生效
if (is_single()) {
echo '<style>
.entry-content p {
text-align: justify;
@ -127,5 +193,148 @@ HTML
}
});
}

if (in_array('corner', $cn_settings)) {
add_action('wp_head', function () {
echo '<style>
.entry-content {
font-feature-settings: "halt" 1;
}
</style>';
});
}

if (in_array('space', $cn_settings)) {
add_action('wp_head', function () {
echo '<style>
.entry-content {
word-spacing: 0.1em;
letter-spacing: 0.05em;
}
</style>';
});
}

if (in_array('punctuation', $cn_settings)) {
add_action('wp_head', function () {
echo '<style>
.entry-content {
text-spacing: trim-start;
hanging-punctuation: first last;
}
</style>';
});
}
}

/**
* 加载英文排印优化
*/
private function load_english_typography() {
$en_settings = (array) $this->settings['windfonts_typography_en'];

if (in_array('optimize', $en_settings)) {
add_action('wp_head', function () {
echo '<style>
.entry-content {
text-rendering: optimizeLegibility;
font-variant-ligatures: common-ligatures;
font-variant-numeric: oldstyle-nums;
}
</style>';
});
}

if (in_array('spacing', $en_settings)) {
add_action('wp_head', function () {
echo '<style>
.entry-content {
white-space: pre-line;
}
.entry-content p {
white-space: normal;
}
</style>';
});
}

if (in_array('orphan', $en_settings)) {
add_action('wp_head', function () {
echo '<style>
.entry-content p {
orphans: 3;
}
</style>';
});
}

if (in_array('widow', $en_settings)) {
add_action('wp_head', function () {
echo '<style>
.entry-content p {
widows: 3;
}
</style>';
});
}

if (in_array('punctuation', $en_settings)) {
add_action('wp_head', function () {
echo '<style>
.entry-content {
font-feature-settings: "kern" 1, "liga" 1, "clig" 1;
}
</style>';
});
}
}



/**
* 加载RTL镜像测试功能
*/
private function load_rtl_mirror($mode = 'global') {
$rtl_styles = '<style type="text/css" media="screen">
html {
transform: scaleX(-1);
}
html::after {
content: "RTL镜像测试模式";
position: fixed;
display: inline-block;
left: 50%;
top: -3px;
padding: 10px 20px;
font-size: 12px;
font-family: sans-serif;
text-transform: uppercase;
background: #21759b;
color: #fff;
white-space: nowrap;
z-index: 9999999;
border-radius: 3px;
transform: scaleX(-1) translateX(50%);
transform-origin: 50% 0;
}
#wpadminbar { margin-top: -32px; }
.wp-admin #wpadminbar { margin-top: 0; }
</style>';

if ($mode === 'global') {
add_action('wp_head', function () use ($rtl_styles) {
echo $rtl_styles;
}, 9999);

add_action('admin_print_styles', function () use ($rtl_styles) {
echo $rtl_styles;
}, 9999);
} elseif ($mode === 'frontend') {
add_action('wp_head', function () use ($rtl_styles) {
echo $rtl_styles;
}, 9999);
}
}


}

277
Service/Language.php Normal file
View file

@ -0,0 +1,277 @@
<?php

namespace WenPai\ChinaYes\Service;

defined( 'ABSPATH' ) || exit;

use function WenPai\ChinaYes\get_settings;

/**
* Class Language
* 语言切换服务
* @package WenPai\ChinaYes\Service
*/
class Language {

private $settings;

public function __construct() {
$this->settings = get_settings();

if ( $this->is_enabled( $this->settings['waimao_enable'] ?? false ) ) {
if ( $this->is_enabled( $this->settings['waimao_language_split'] ?? false ) ) {
$this->init_language_split();
}
}

add_action( 'wp_china_yes_wp_china_yes_save_after', [ $this, 'apply_language_settings' ] );
add_action( 'update_option_WPLANG', [ $this, 'sync_frontend_language_to_plugin' ], 10, 2 );
add_action( 'updated_user_meta', [ $this, 'sync_admin_language_to_plugin' ], 10, 4 );
add_action( 'admin_init', [ $this, 'sync_plugin_settings_from_wp' ] );
}

/**
* 初始化语言分离功能
*/
private function init_language_split() {
add_filter( 'locale', [ $this, 'set_locale' ], 10, 1 );
add_filter( 'determine_locale', [ $this, 'determine_locale' ], 10, 1 );
if ( $this->is_enabled( $this->settings['waimao_auto_detect'] ?? false ) ) {
add_action( 'init', [ $this, 'auto_detect_language' ], 1 );
}
}

/**
* 设置语言环境
*/
public function set_locale( $locale ) {
if ( is_admin() ) {
return $this->get_admin_locale();
} else {
return $this->get_frontend_locale();
}
}

/**
* 确定语言环境
*/
public function determine_locale( $locale ) {
if ( is_admin() ) {
return $this->get_admin_locale();
} else {
return $this->get_frontend_locale();
}
}

/**
* 应用语言设置到WordPress系统
*/
public function apply_language_settings( $data ) {
$this->settings = $data;
$waimao_enable = $this->settings['waimao_enable'] ?? false;
$language_split = $this->settings['waimao_language_split'] ?? false;
if ( $this->is_enabled( $waimao_enable ) ) {
if ( $this->is_enabled( $language_split ) ) {
if ( ! empty( $this->settings['waimao_admin_language'] ) ) {
$user_id = get_current_user_id();
if ( $user_id ) {
update_user_meta( $user_id, 'locale', $this->settings['waimao_admin_language'] );
}
}

if ( isset( $this->settings['waimao_frontend_language'] ) ) {
$old_wplang = get_option( 'WPLANG', '' );
$new_wplang = $this->settings['waimao_frontend_language'];
if ( $old_wplang !== $new_wplang ) {
update_option( 'WPLANG', $new_wplang );
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( "WPLANG updated from '{$old_wplang}' to '{$new_wplang}'" );
}
}
}
}
}
}

/**
* 检查设置是否启用(处理布尔值和字符串)
*/
private function is_enabled( $value ) {
return $value === true || $value === 'true' || $value === '1' || $value === 1;
}

/**
* 获取后台语言
*/
private function get_admin_locale() {
$admin_language = $this->settings['waimao_admin_language'] ?? get_locale();
return $admin_language;
}

/**
* 获取前台语言
*/
private function get_frontend_locale() {
if ( $this->is_enabled( $this->settings['waimao_auto_detect'] ?? false ) ) {
$detected_locale = $this->detect_browser_language();
if ( $detected_locale ) {
return $detected_locale;
}
}
$frontend_language = $this->settings['waimao_frontend_language'] ?? get_option('WPLANG', 'en_US');
return $frontend_language;
}

/**
* 自动检测语言
*/
public function auto_detect_language() {
if ( is_admin() ) {
return;
}

$detected_locale = $this->detect_browser_language();
if ( $detected_locale ) {
add_filter( 'locale', function() use ( $detected_locale ) {
return $detected_locale;
}, 20 );
}
}

/**
* 检测浏览器语言
*/
private function detect_browser_language() {
if ( ! isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
return false;
}

$supported_languages = [
'zh-cn' => 'zh_CN',
'zh-tw' => 'zh_TW',
'zh-hk' => 'zh_TW',
'en-us' => 'en_US',
'en-gb' => 'en_GB',
'en' => 'en_US',
'ja' => 'ja',
'ko' => 'ko_KR',
'de' => 'de_DE',
'fr' => 'fr_FR',
'es' => 'es_ES',
'ru' => 'ru_RU',
];

$accept_language = strtolower( $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
$languages = explode( ',', $accept_language );

foreach ( $languages as $language ) {
$language = trim( explode( ';', $language )[0] );
if ( isset( $supported_languages[ $language ] ) ) {
return $supported_languages[ $language ];
}
$language_code = explode( '-', $language )[0];
if ( isset( $supported_languages[ $language_code ] ) ) {
return $supported_languages[ $language_code ];
}
}

return false;
}

/**
* 获取可用语言列表
*/
public static function get_available_languages() {
return [
'zh_CN' => '简体中文',
'zh_TW' => '繁体中文',
'en_US' => 'English (US)',
'en_GB' => 'English (UK)',
'ja' => '日本語',
'ko_KR' => '한국어',
'de_DE' => 'Deutsch',
'fr_FR' => 'Français',
'es_ES' => 'Español',
'ru_RU' => 'Русский',
];
}

/**
* 检查语言文件是否存在
*/
public function is_language_available( $locale ) {
if ( $locale === 'en_US' ) {
return true;
}

$language_file = WP_LANG_DIR . '/wp-' . $locale . '.mo';
return file_exists( $language_file );
}

/**
* 同步前台语言设置到插件
*/
public function sync_frontend_language_to_plugin( $old_value, $new_value ) {
if ( $this->is_enabled( $this->settings['waimao_enable'] ?? false ) ) {
if ( $this->is_enabled( $this->settings['waimao_language_split'] ?? false ) ) {
$current_settings = get_option( 'wp_china_yes', [] );
$current_settings['waimao_frontend_language'] = $new_value;
update_option( 'wp_china_yes', $current_settings );
}
}
}

/**
* 同步后台语言设置到插件
*/
public function sync_admin_language_to_plugin( $meta_id, $user_id, $meta_key, $meta_value ) {
if ( $meta_key === 'locale' && $user_id === get_current_user_id() ) {
if ( $this->is_enabled( $this->settings['waimao_enable'] ?? false ) ) {
if ( $this->is_enabled( $this->settings['waimao_language_split'] ?? false ) ) {
$current_settings = get_option( 'wp_china_yes', [] );
$current_settings['waimao_admin_language'] = $meta_value;
update_option( 'wp_china_yes', $current_settings );
}
}
}
}

/**
* 从WordPress系统同步语言设置到插件
*/
public function sync_plugin_settings_from_wp() {
if ( $this->is_enabled( $this->settings['waimao_enable'] ?? false ) ) {
if ( $this->is_enabled( $this->settings['waimao_language_split'] ?? false ) ) {
$current_settings = get_option( 'wp_china_yes', [] );
$needs_update = false;

$wp_frontend_lang = get_option( 'WPLANG', '' );
if ( $current_settings['waimao_frontend_language'] !== $wp_frontend_lang ) {
$current_settings['waimao_frontend_language'] = $wp_frontend_lang;
$needs_update = true;
}

$user_locale = get_user_meta( get_current_user_id(), 'locale', true );
if ( $user_locale && $current_settings['waimao_admin_language'] !== $user_locale ) {
$current_settings['waimao_admin_language'] = $user_locale;
$needs_update = true;
}

if ( $needs_update ) {
update_option( 'wp_china_yes', $current_settings );
$this->settings = $current_settings;
}
}
}
}
}

View file

@ -0,0 +1,87 @@
<?php

namespace WenPai\ChinaYes\Service;

class LazyTranslation {
private $text;
private $domain;
private $context;
public function __construct($text, $domain = 'wp-china-yes', $context = null) {
$this->text = $text;
$this->domain = $domain;
$this->context = $context;
}
public function __toString() {
return $this->resolve();
}
public function resolve() {
if (did_action('init')) {
if ($this->context) {
return _x($this->text, $this->context, $this->domain);
}
return __($this->text, $this->domain);
}
return TranslationManager::getFallback($this->text);
}
public function getText() {
return $this->text;
}
public function getDomain() {
return $this->domain;
}
public function getContext() {
return $this->context;
}
public static function create($text, $domain = 'wp-china-yes', $context = null) {
return new self($text, $domain, $context);
}
public static function createArray($texts, $domain = 'wp-china-yes') {
$result = [];
foreach ($texts as $key => $text) {
if (is_string($text)) {
$result[$key] = new self($text, $domain);
} else {
$result[$key] = $text;
}
}
return $result;
}
public static function resolveArray($array) {
$result = [];
foreach ($array as $key => $value) {
if ($value instanceof self) {
$result[$key] = $value->resolve();
} elseif (is_array($value)) {
$result[$key] = self::resolveArray($value);
} else {
$result[$key] = $value;
}
}
return $result;
}
}

function t($text, $domain = 'wp-china-yes', $context = null) {
return LazyTranslation::create($text, $domain, $context);
}

function tr($text, $domain = 'wp-china-yes', $context = null) {
if (did_action('init')) {
if ($context) {
return _x($text, $context, $domain);
}
return __($text, $domain);
}
return TranslationManager::getFallback($text);
}

View file

@ -57,7 +57,7 @@ class Maintenance {
$items['media'] = sprintf(
'<a href="%s" class="stat-item"><span class="dashicons dashicons-format-gallery"></span> %s</a>',
admin_url('upload.php'),
sprintf(_n('%d 个媒体', '%d 个媒体', $media_count), $media_count)
sprintf('%d 个媒体', $media_count)
);
}

@ -67,7 +67,7 @@ class Maintenance {
$items['admins'] = sprintf(
'<a href="%s" class="stat-item"><span class="dashicons dashicons-shield-alt"></span> %s</a>',
admin_url('users.php?role=administrator'),
sprintf(_n('%d 个管理员', '%d 个管理员', $admin_count), $admin_count)
sprintf('%d 个管理员', $admin_count)
);
}

@ -77,7 +77,7 @@ class Maintenance {
$items['users'] = sprintf(
'<a href="%s" class="stat-item"><span class="dashicons dashicons-groups"></span> %s</a>',
admin_url('users.php'),
sprintf(_n('%d 个用户', '%d 个用户', $total_users), $total_users)
sprintf('%d 个用户', $total_users)
);
}


View file

@ -0,0 +1,90 @@
<?php

namespace WenPai\ChinaYes\Service;

defined('ABSPATH') || exit;

use function WenPai\ChinaYes\get_settings;

class Media {

private $settings;

public function __construct() {
$this->settings = get_settings();
$this->init();
}

private function init() {
if (!empty($this->settings['optimize_images'])) {
add_filter('wp_image_editors', [$this, 'set_image_editor']);
add_filter('jpeg_quality', [$this, 'set_jpeg_quality']);
}
if (!empty($this->settings['lazy_load'])) {
add_filter('wp_lazy_loading_enabled', '__return_true');
}
add_filter('wp_get_attachment_image_attributes', [$this, 'add_image_attributes'], 10, 3);
if (!empty($this->settings['webp_support'])) {
add_filter('wp_generate_attachment_metadata', [$this, 'generate_webp_versions']);
}
}

public function set_image_editor($editors) {
if (extension_loaded('imagick')) {
array_unshift($editors, 'WP_Image_Editor_Imagick');
}
return $editors;
}

public function set_jpeg_quality($quality) {
return intval($this->settings['jpeg_quality'] ?? 85);
}

public function add_image_attributes($attr, $attachment, $size) {
if (!empty($this->settings['lazy_load']) && !is_admin()) {
$attr['loading'] = 'lazy';
}
if (!empty($this->settings['responsive_images'])) {
$attr['sizes'] = '(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 33vw';
}
return $attr;
}

public function generate_webp_versions($metadata) {
if (!function_exists('imagewebp')) {
return $metadata;
}
$upload_dir = wp_upload_dir();
$file_path = $upload_dir['basedir'] . '/' . $metadata['file'];
if (file_exists($file_path)) {
$webp_path = preg_replace('/\.(jpe?g|png)$/i', '.webp', $file_path);
$image_type = wp_check_filetype($file_path)['type'];
switch ($image_type) {
case 'image/jpeg':
$image = imagecreatefromjpeg($file_path);
break;
case 'image/png':
$image = imagecreatefrompng($file_path);
break;
default:
return $metadata;
}
if ($image) {
imagewebp($image, $webp_path, 85);
imagedestroy($image);
}
}
return $metadata;
}
}

View file

@ -61,9 +61,9 @@ class Memory {
*/
private function get_debug_status() {
if (defined('WP_DEBUG') && true === WP_DEBUG) {
return '<strong><font color="#F60">' . __('WP_DEBUG', 'wp-china-yes') . '</font></strong>';
return '<strong><font color="#F60">WP_DEBUG</font></strong>';
}
return '<span style="text-decoration: line-through;">' . __('WP_DEBUG', 'wp-china-yes') . '</span>';
return '<span style="text-decoration: line-through;">WP_DEBUG</span>';
}

/**
@ -140,7 +140,7 @@ class Memory {
*/
private function check_wp_limit() {
$memory = $this->format_wp_limit(WP_MEMORY_LIMIT);
return $memory ? size_format($memory) : __('N/A', 'wp-china-yes');
return $memory ? size_format($memory) : 'N/A';
}

/**
@ -176,9 +176,9 @@ public function add_footer($content) {
// 内存使用量
if (in_array('memory_usage', $display_options)) {
$footer_parts[] = sprintf('%s: %s %s %s MB (<span style="%s">%s%%</span>)',
__('Memory', 'wp-china-yes'),
'Memory',
$this->memory['usage'],
__('of', 'wp-china-yes'),
'of',
$this->memory['limit'],
$this->memory['color'],
$this->memory['percent']
@ -188,7 +188,7 @@ public function add_footer($content) {
// WP内存限制
if (in_array('wp_limit', $display_options)) {
$footer_parts[] = sprintf('%s: %s',
__('WP LIMIT', 'wp-china-yes'),
'WP LIMIT',
$this->check_wp_limit()
);
}
@ -250,10 +250,10 @@ public function add_footer($content) {
wp_die(
sprintf(
'<h1>%s</h1><p>%s</p>',
__('插件无法激活PHP 版本过低', 'wp-china-yes'),
__('请升级 PHP 至 7.0 或更高版本。', 'wp-china-yes')
'插件无法激活PHP 版本过低',
'请升级 PHP 至 7.0 或更高版本。'
),
__('PHP 版本错误', 'wp-china-yes'),
'PHP 版本错误',
['back_link' => true]
);
}

110
Service/Migration.php Normal file
View file

@ -0,0 +1,110 @@
<?php

namespace WenPai\ChinaYes\Service;

defined( 'ABSPATH' ) || exit;

use function WenPai\ChinaYes\get_settings;

class Migration {

private $settings;

public function __construct() {
$this->settings = get_settings();
add_action( 'admin_init', [ $this, 'migrate_windfonts_settings' ] );
}

public function migrate_windfonts_settings() {
$current_settings = get_option( 'wp_china_yes', [] );
$needs_migration = false;

if ( ! empty( $current_settings['windfonts_list'] ) ) {
foreach ( $current_settings['windfonts_list'] as $index => $font ) {
if ( isset( $font['css'] ) && ! isset( $font['subset'] ) ) {
$migrated_font = $this->migrate_font_config( $font );
$current_settings['windfonts_list'][$index] = $migrated_font;
$needs_migration = true;
}
}
}

if ( $needs_migration ) {
update_option( 'wp_china_yes', $current_settings );
}
}

private function migrate_font_config( $old_font ) {
$new_font = [
'family' => $this->extract_family_from_old_config( $old_font ),
'subset' => $this->extract_subset_from_old_config( $old_font ),
'lang' => '',
'weight' => $old_font['weight'] ?? 400,
'style' => $old_font['style'] ?? 'normal',
'selector' => $old_font['selector'] ?? 'a:not([class]),p,h1,h2,h3,h4,h5,h6,ul,ol,li,button,blockquote,pre,code,table,th,td,label,b,i:not([class]),em,small,strong,sub,sup,ins,del,mark,abbr,dfn,span:not([class])',
'enable' => $old_font['enable'] ?? true,
];

return $new_font;
}

private function extract_family_from_old_config( $old_font ) {
if ( isset( $old_font['family'] ) ) {
return $old_font['family'];
}

if ( isset( $old_font['css'] ) ) {
$css_url = $old_font['css'];
if ( strpos( $css_url, 'syhtcjk' ) !== false ) {
return 'cszt';
}
if ( preg_match( '/fonts\/([^\/]+)\//', $css_url, $matches ) ) {
return $matches[1];
}
}

return 'cszt';
}

private function extract_subset_from_old_config( $old_font ) {
if ( isset( $old_font['css'] ) ) {
$css_url = $old_font['css'];
if ( strpos( $css_url, '/regular/' ) !== false ) {
return 'regular';
}
if ( strpos( $css_url, '/bold/' ) !== false ) {
return 'bold';
}
if ( strpos( $css_url, '/light/' ) !== false ) {
return 'light';
}
if ( strpos( $css_url, '/medium/' ) !== false ) {
return 'medium';
}
}

if ( isset( $old_font['weight'] ) ) {
$weight = intval( $old_font['weight'] );
if ( $weight <= 200 ) {
return 'thin';
} elseif ( $weight <= 300 ) {
return 'light';
} elseif ( $weight <= 500 ) {
return 'regular';
} elseif ( $weight <= 600 ) {
return 'medium';
} elseif ( $weight <= 700 ) {
return 'semibold';
} elseif ( $weight <= 800 ) {
return 'bold';
} else {
return 'black';
}
}

return 'regular';
}
}

234
Service/ModernSetting.php Normal file
View file

@ -0,0 +1,234 @@
<?php

namespace WenPai\ChinaYes\Service;

use WenPai\ChinaYes\Service\TranslationManager;
use WenPai\ChinaYes\Service\LazyTranslation;
use WP_CHINA_YES;
use function WenPai\ChinaYes\get_settings;

class ModernSetting {
private $settings;
private $prefix = 'wp_china_yes';
public function __construct() {
$this->settings = get_settings();
add_filter( 'wp_china_yes_enqueue_assets', '__return_true' );
add_filter( 'wp_china_yes_fa4', '__return_true' );
add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );
add_action( is_multisite() ? 'network_admin_menu' : 'admin_menu', [ $this, 'admin_menu' ] );
// 延迟到 init 动作后执行
add_action( 'init', [ $this, 'admin_init' ], 20 );
}
public function admin_init() {
// 确保翻译已加载
if (!TranslationManager::isLoaded()) {
TranslationManager::getInstance()->loadTranslations();
}
$this->setupFramework();
}
private function setupFramework() {
$enabled_sections = $this->settings['enable_sections'] ?? [];
if (in_array('store', $enabled_sections)) {
WP_CHINA_YES::createSection( $this->prefix, [
'title' => $this->t('应用市场'),
'icon' => 'icon icon-shop',
'fields' => [
[
'id' => 'store',
'type' => 'radio',
'title' => $this->t('应用市场'),
'inline' => true,
'options' => [
'wenpai' => $this->t('文派开源'),
'proxy' => $this->t('官方镜像'),
'off' => $this->t('不启用')
],
'default' => 'wenpai',
'subtitle' => '是否启用市场加速',
'desc' => '<a href="https://wenpai.org/" target="_blank">文派开源WenPai.org</a>中国境内自建托管仓库,同时集成文派翻译平台。<a href="https://wpmirror.com/" target="_blank">官方加速源WPMirror</a>直接从 .org 反代至大陆分发;可参考<a href="https://wpcy.com/document/wordpress-marketplace-acceleration" target="_blank">源站说明</a>。',
],
[
'id' => 'bridge',
'type' => 'switcher',
'default' => true,
'title' => '云桥更新',
'subtitle' => '是否启用更新加速',
'desc' => '<a href="https://wpbridge.com" target="_blank">文派云桥wpbridge</a>托管更新和应用分发渠道,可解决因 WordPress 社区分裂导致的混乱、旧应用无法更新,频繁 API 请求拖慢网速等问题。',
],
[
'id' => 'arkpress',
'type' => 'switcher',
'default' => false,
'title' => '联合存储库',
'subtitle' => '自动监控加速节点可用性',
'desc' => '<a href="https://maiyun.org" target="_blank">ArkPress.org </a>支持自动监控各加速节点可用性,当节点不可用时自动切换至可用节点或关闭加速,以保证您的网站正常访问',
],
],
] );
}
if (in_array('admincdn', $enabled_sections)) {
WP_CHINA_YES::createSection( $this->prefix, [
'title' => $this->t('萌芽加速'),
'icon' => 'icon icon-flash-1',
'fields' => [
[
'id' => 'admincdn_public',
'type' => 'checkbox',
'title' => $this->t('萌芽加速'),
'inline' => true,
'options' => [
'googlefonts' => 'Google 字体',
'googleajax' => 'Google 前端库',
'cdnjs' => 'CDNJS 前端库',
'jsdelivr' => 'jsDelivr 前端库',
'bootstrapcdn' => 'Bootstrap 前端库',
],
'default' => [
'googlefonts' => 'googlefonts',
'googleajax' => 'googleajax',
'cdnjs' => 'cdnjs',
'jsdelivr' => 'jsdelivr',
'bootstrapcdn' => 'bootstrapcdn',
],
'subtitle' => '是否启用前端公共库加速',
'desc' => '启用后,将自动替换前端页面中的 Google Fonts、Google Ajax、CDNJS、jsDelivr、Bootstrap 等公共库为国内加速节点。',
],
[
'id' => 'admincdn_files',
'type' => 'checkbox',
'title' => $this->t('文件加速'),
'inline' => true,
'options' => [
'gravatar' => 'Gravatar 头像',
'emoji' => 'Emoji 表情',
'googlefonts' => 'Google 字体',
],
'default' => [
'gravatar' => 'gravatar',
'emoji' => 'emoji',
'googlefonts' => 'googlefonts',
],
'subtitle' => '是否启用文件资源加速',
'desc' => '启用后,将自动替换 Gravatar 头像、Emoji 表情、Google 字体等文件资源为国内加速节点。',
],
[
'id' => 'admincdn_dev',
'type' => 'checkbox',
'title' => $this->t('开发加速'),
'inline' => true,
'options' => [
'wordpress' => 'WordPress 官方',
'themes' => '主题仓库',
'plugins' => '插件仓库',
],
'default' => [
'wordpress' => 'wordpress',
'themes' => 'themes',
'plugins' => 'plugins',
],
'subtitle' => '是否启用开发资源加速',
'desc' => '启用后,将自动替换 WordPress 官方、主题仓库、插件仓库等开发资源为国内加速节点。',
],
],
] );
}
// 通知管理部分
if (in_array('notice', $enabled_sections)) {
WP_CHINA_YES::createSection( $this->prefix, [
'title' => $this->t('通知管理'),
'icon' => 'icon icon-bell',
'fields' => [
[
'id' => 'notice_block',
'type' => 'radio',
'title' => $this->t('通知管理'),
'inline' => true,
'options' => [
'on' => '启用',
'off' => '不启用',
],
'default' => 'off',
'subtitle' => '是否启用后台通知管理',
'desc' => $this->t('管理和控制 WordPress 后台各类通知的显示。'),
],
[
'id' => 'disable_all_notices',
'type' => 'switcher',
'title' => $this->t('禁用所有通知'),
'subtitle' => '一键禁用所有后台通知',
'default' => false,
'dependency' => ['notice_block', '==', 'on'],
],
[
'id' => 'notice_control',
'type' => 'checkbox',
'title' => $this->t('选择性禁用'),
'inline' => true,
'subtitle' => '选择需要禁用的通知类型',
'desc' => $this->t('可以按住 Ctrl/Command 键进行多选'),
'chosen' => true,
'multiple' => true,
'options' => [
'update_nag' => '更新提醒',
'plugin_update' => '插件更新',
'theme_update' => '主题更新',
'core_update' => '核心更新',
'admin_notices' => '管理员通知',
'user_admin_notices' => '用户管理通知',
'network_admin_notices'=> '网络管理通知',
],
'dependency' => ['notice_block', '==', 'on'],
],
[
'id' => 'notice_method',
'type' => 'radio',
'title' => $this->t('禁用方式'),
'inline' => true,
'options' => [
'hide' => '隐藏通知',
'remove' => '移除通知',
],
'default' => 'hide',
'subtitle' => '选择通知的禁用方式',
'desc' => '隐藏通知:通过 CSS 隐藏通知元素;移除通知:通过 PHP 移除通知钩子。',
'dependency' => ['notice_block', '==', 'on'],
],
],
] );
}
}
private function t($text) {
return TranslationManager::translate($text);
}
public function admin_menu() {
add_options_page(
'WP-China-Yes',
'WP-China-Yes',
'manage_options',
'wp-china-yes',
[ $this, 'admin_page' ]
);
}
public function admin_page() {
echo '<div class="wrap">';
echo '<h1>WP-China-Yes 设置</h1>';
echo '<p>现代化翻译系统已启用</p>';
echo '</div>';
}
public function enqueue_admin_assets() {
// 管理员资源加载
}
}

View file

@ -1,2 +1,94 @@
<?php

namespace WenPai\ChinaYes\Service;

defined('ABSPATH') || exit;

use function WenPai\ChinaYes\get_settings;

class Performance {

private $settings;

public function __construct() {
$this->settings = get_settings();
$this->init();
}

private function init() {
add_action('init', [$this, 'optimize_wordpress']);
add_action('wp_enqueue_scripts', [$this, 'optimize_scripts'], 999);
add_action('wp_head', [$this, 'add_performance_hints'], 1);
if (is_admin()) {
add_action('admin_init', [$this, 'optimize_admin']);
}
}

public function optimize_wordpress() {
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wp_shortlink_wp_head');
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
if (!is_admin()) {
wp_deregister_script('jquery-migrate');
}
add_filter('xmlrpc_enabled', '__return_false');
add_filter('wp_headers', function($headers) {
if (isset($headers['X-Pingback'])) {
unset($headers['X-Pingback']);
}
return $headers;
});
add_filter('emoji_svg_url', '__return_false');
if (!empty($this->settings['disable_embeds'])) {
wp_deregister_script('wp-embed');
}
}

public function optimize_scripts() {
if (!is_admin() && !empty($this->settings['defer_scripts'])) {
add_filter('script_loader_tag', function($tag, $handle) {
if (is_admin() || strpos($tag, 'defer') !== false) {
return $tag;
}
$defer_scripts = ['jquery', 'wp-embed'];
if (in_array($handle, $defer_scripts)) {
return str_replace(' src', ' defer src', $tag);
}
return $tag;
}, 10, 2);
}
}

public function add_performance_hints() {
echo '<link rel="dns-prefetch" href="//admincdn.com">' . "\n";
echo '<link rel="dns-prefetch" href="//cn.cravatar.com">' . "\n";
echo '<link rel="dns-prefetch" href="//wenpai.org">' . "\n";
echo '<link rel="preconnect" href="https://admincdn.com" crossorigin>' . "\n";
}

public function optimize_admin() {
add_filter('heartbeat_settings', function($settings) {
$settings['interval'] = 60;
return $settings;
});
if (!empty($this->settings['disable_admin_bar']) && !current_user_can('manage_options')) {
show_admin_bar(false);
}
add_action('admin_enqueue_scripts', function() {
wp_dequeue_script('thickbox');
wp_dequeue_style('thickbox');
});
}
}

File diff suppressed because it is too large Load diff

View file

@ -6,12 +6,12 @@ defined( 'ABSPATH' ) || exit;

use WP_Error;
use function WenPai\ChinaYes\get_settings;
use WenPai\ChinaYes\Service\Widget;
use WenPai\ChinaYes\Service\Language;
use WenPai\ChinaYes\Service\Migration;
use WenPai\ChinaYes\Service\Fonts;
use WenPai\ChinaYes\Service\Comments;

/**
* Class Super
* 插件加速服务
* @package WenPai\ChinaYes\Service
*/
class Super {

private $settings;
@ -19,168 +19,18 @@ class Super {
public function __construct() {
$this->settings = get_settings();

/**
* WordPress.Org API 替换
*/
if ( is_admin() || wp_doing_cron() ) {
if ( $this->settings['store'] != 'off' ) {
add_filter( 'pre_http_request', [ $this, 'filter_wordpress_org' ], 100, 3 );
}
}

/**
* 添加「文派茶馆」小组件
*/
if ( is_admin() ) {
add_action( 'wp_dashboard_setup', function () {
global $wp_meta_boxes;
new Widget();
new Language();
new Migration();
new Fonts();
new Comments();

unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_primary'] );
wp_add_dashboard_widget( 'wenpai_tea', '文派茶馆', function () {
$default_rss_url = 'https://wptea.com/feed/';
$custom_rss_url = $this->settings['custom_rss_url'] ?? '';
$refresh_interval = $this->settings['custom_rss_refresh'] ?? 3600;

$rss_display_options = $this->settings['rss_display_options'] ?? ['show_date', 'show_summary', 'show_footer'];
if (!is_array($rss_display_options)) {
$rss_display_options = explode(',', $rss_display_options);
}

// 获取默认的 RSS 源内容
$default_rss = fetch_feed($default_rss_url);
$default_items = [];
if (!is_wp_error($default_rss)) {
$default_items = $default_rss->get_items(0, 5);
}

$custom_items = [];
$custom_rss = null;
$custom_rss_latest_date = 0;

if (!empty($custom_rss_url)) {
$transient_key = 'wenpai_tea_custom_rss_' . md5($custom_rss_url);
$cached_custom_items = get_transient($transient_key);

if (false === $cached_custom_items) {
$custom_rss = fetch_feed($custom_rss_url);
if (!is_wp_error($custom_rss)) {
$custom_items = $custom_rss->get_items(0, 2);
if (!empty($custom_items)) {
$custom_rss_latest_date = $custom_items[0]->get_date('U');
}

set_transient($transient_key, $custom_items, $refresh_interval);
}
} else {
$custom_items = $cached_custom_items;
if (!empty($custom_items)) {
$custom_rss_latest_date = $custom_items[0]->get_date('U');
}
}
}

$three_days_ago = time() - (3 * 24 * 60 * 60);
if ($custom_rss_latest_date > $three_days_ago) {
$items = array_merge(array_slice($default_items, 0, 3), $custom_items);
} else {
$items = array_slice($default_items, 0, 5);
}

if (is_wp_error($custom_rss)) {
$items = array_slice($default_items, 0, 5);
}

echo <<<HTML
<div class="wordpress-news hide-if-no-js">
<div class="rss-widget">
HTML;
foreach ($items as $item) {
echo '<div class="rss-item">';
echo '<a href="' . esc_url($item->get_permalink()) . '" target="_blank">' . esc_html($item->get_title()) . '</a>';
if (in_array('show_date', $rss_display_options)) {
echo '<span class="rss-date">' . esc_html($item->get_date('Y.m.d')) . '</span>';
}
if (in_array('show_summary', $rss_display_options)) {
echo '<div class="rss-summary">' . esc_html(wp_trim_words($item->get_description(), 45, '...')) . '</div>';
}
echo '</div>';
}
echo <<<HTML
</div>
</div>
HTML;
if (in_array('show_footer', $rss_display_options)) {
echo <<<HTML
<p class="community-events-footer">
<a href="https://wenpai.org/" target="_blank">文派开源</a>
|
<a href="https://wenpai.org/support" target="_blank">支持论坛</a>
|
<a href="https://translate.wenpai.org/" target="_blank">翻译平台</a>
|
<a href="https://wptea.com/newsletter/" target="_blank">订阅推送</a>
</p>
HTML;
}
echo <<<HTML
<style>
#wenpai_tea .rss-widget {
padding: 0 12px;
}
#wenpai_tea .rss-widget:last-child {
border-bottom: none;
padding-bottom: 8px;
}
#wenpai_tea .rss-item {
margin-bottom: 10px;
padding-bottom: 10px;
border-bottom: 1px solid #eee;
}
#wenpai_tea .rss-item:last-child {
border-bottom: none;
margin-bottom: 0;
padding-bottom: 0;
}
#wenpai_tea .rss-item a {
text-decoration: none;
display: block;
margin-bottom: 5px;
}
#wenpai_tea .rss-date {
color: #666;
font-size: 12px;
display: block;
margin-bottom: 8px;
}
#wenpai_tea .rss-summary {
color: #444;
font-size: 13px;
line-height: 1.5;
}
#wenpai_tea .community-events-footer {
margin-top: 15px;
padding-top: 15px;
padding-bottom: 5px;
border-top: 1px solid #eee;
text-align: center;
}
#wenpai_tea .community-events-footer a {
text-decoration: none;
margin: 0 5px;
}
#wenpai_tea .community-events-footer a:hover {
text-decoration: underline;
}
</style>
HTML;
});
});
}

/**
* 初认头像
*/
if ( ! empty( $this->settings['cravatar'] ) ) {
add_filter( 'user_profile_picture_description', [ $this, 'set_user_profile_picture_for_cravatar' ], 1 );
add_filter( 'avatar_defaults', [ $this, 'set_defaults_for_cravatar' ], 1 );
@ -189,501 +39,131 @@ HTML;
add_filter( 'get_avatar_url', [ $this, 'get_cravatar_url' ], 1 );
}

/**
* 文风字体
*/
if ( ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
if ( ! empty( $this->settings['windfonts'] ) && $this->settings['windfonts'] != 'off' ) {
$this->load_typography();
}
if ( ! empty( $this->settings['windfonts'] ) && $this->settings['windfonts'] == 'optimize' ) {
add_action( 'init', function () {
wp_enqueue_style( 'windfonts-optimize', CHINA_YES_PLUGIN_URL . 'assets/css/fonts.css', [], CHINA_YES_VERSION );
} );
}
if ( ! empty( $this->settings['windfonts'] ) && $this->settings['windfonts'] == 'on' ) {
add_action( 'wp_head', [ $this, 'load_windfonts' ] );
add_action( 'admin_head', [ $this, 'load_windfonts' ] );
}
if ( ! empty( $this->settings['windfonts'] ) && $this->settings['windfonts'] == 'frontend' ) {
add_action( 'wp_head', [ $this, 'load_windfonts' ] );
}
}

/**
* 广告拦截
*/
if ( ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
if ( ! empty( $this->settings['adblock'] ) && $this->settings['adblock'] == 'on' ) {
add_action( 'admin_head', [ $this, 'load_adblock' ] );
}
}
/**
* 通知管理
*/
if ( ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
if ( ! empty( $this->settings['notice_block'] ) && $this->settings['notice_block'] == 'on' ) {
add_action( 'admin_head', [ $this, 'load_notice_management' ] );
}
}

/**
* 飞行模式
*/
if ( ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
if ( ! empty( $this->settings['notice_block'] ) && $this->settings['notice_block'] == 'on' ) {
add_action( 'admin_head', [ $this, 'load_notice_management' ] );
}
}

if ( ! empty( $this->settings['plane'] ) && $this->settings['plane'] == 'on' ) {
$this->load_plane();
}
}

public function load_adblock() {
if (empty($this->settings['adblock']) || $this->settings['adblock'] !== 'on') {
return;
}



/**
* 加载文风字体
*/
public function load_windfonts() {
echo <<<HTML
<link rel="preconnect" href="//cn.windfonts.com">
<!-- 此中文网页字体由文风字体Windfonts免费提供您可以自由引用请务必保留此授权许可标注 https://wenfeng.org/license -->
HTML;

$loaded = [];
foreach ( (array) $this->settings['windfonts_list'] as $font ) {
if ( empty( $font['enable'] ) ) {
foreach ( (array) $this->settings['adblock_rule'] as $rule ) {
if ( empty( $rule['enable'] ) || empty( $rule['selector'] ) ) {
continue;
}
if ( empty( $font['family'] ) ) {
continue;
}
if ( in_array( $font['css'], $loaded ) ) {
continue;
}
echo sprintf( <<<HTML
<link rel="stylesheet" type="text/css" href="%s">
<style>
%s {
font-style: %s;
font-weight: %s;
font-family: '%s',sans-serif!important;
}
</style>
HTML
,
$font['css'],
htmlspecialchars_decode( $font['selector'] ),
$font['style'],
$font['weight'],
$font['family']
);
$loaded[] = $font['css'];

echo sprintf( '<style>%s { display: none !important; }</style>', esc_html( $rule['selector'] ) );
}
}

/**
* 加载排印优化
*/
public function load_typography() {
// code from corner-bracket-lover plugin
if ( in_array( 'corner', (array) $this->settings['windfonts_typography'] ) ) {
$this->page_str_replace( 'init', 'str_replace', [
'nt',
'n&rsquo;t'
] );
$this->page_str_replace( 'init', 'str_replace', [
's',
'&rsquo;s'
] );
$this->page_str_replace( 'init', 'str_replace', [
'm',
'&rsquo;m'
] );
$this->page_str_replace( 'init', 'str_replace', [
're',
'&rsquo;re'
] );
$this->page_str_replace( 'init', 'str_replace', [
've',
'&rsquo;ve'
] );
$this->page_str_replace( 'init', 'str_replace', [
'd',
'&rsquo;d'
] );
$this->page_str_replace( 'init', 'str_replace', [
'll',
'&rsquo;ll'
] );
$this->page_str_replace( 'init', 'str_replace', [
'“',
'&#12300;'
] );
$this->page_str_replace( 'init', 'str_replace', [
'”',
'&#12301;'
] );
$this->page_str_replace( 'init', 'str_replace', [
'',
'&#12302;'
] );
$this->page_str_replace( 'init', 'str_replace', [
'',
'&#12303;'
] );
public function load_notice_management() {
echo '<style>
.notice, .update-nag, .updated, .error, .is-dismissible {
display: none !important;
}
// code from space-lover plugin
if ( in_array( 'space', (array) $this->settings['windfonts_typography'] ) ) {
$this->page_str_replace( 'template_redirect', 'preg_replace', [
'~(\p{Han})([a-zA-Z0-9\p{Ps}\p{Pi}])(?![^<]*>)~u',
'\1 \2'
] );
$this->page_str_replace( 'template_redirect', 'preg_replace', [
'~([a-zA-Z0-9\p{Pe}\p{Pf}])(\p{Han})(?![^<]*>)~u',
'\1 \2'
] );
$this->page_str_replace( 'template_redirect', 'preg_replace', [
'~([!?‽:;,.%])(\p{Han})~u',
'\1 \2'
] );
$this->page_str_replace( 'template_redirect', 'preg_replace', [
'~(\p{Han})([@$#])~u',
'\1 \2'
] );
$this->page_str_replace( 'template_redirect', 'preg_replace', [
'~(&amp;?(?:amp)?;) (\p{Han})(?![^<]*>)~u',
'\1\2'
] );
$this->page_str_replace( 'template_redirect', 'preg_replace', [
'~(\p{Han})(<(?!ruby)[a-zA-Z]+?[^>]*?>)([a-zA-Z0-9\p{Ps}\p{Pi}@$#])~u',
'\1 \2\3'
] );
$this->page_str_replace( 'template_redirect', 'preg_replace', [
'~(\p{Han})(<\/(?!ruby)[a-zA-Z]+>)([a-zA-Z0-9])~u',
'\1\2 \3'
] );
$this->page_str_replace( 'template_redirect', 'preg_replace', [
'~([a-zA-Z0-9\p{Pe}\p{Pf}!?‽:;,.%])(<(?!ruby)[a-zA-Z]+?[^>]*?>)(\p{Han})~u',
'\1 \2\3'
] );
$this->page_str_replace( 'template_redirect', 'preg_replace', [
'~([a-zA-Z0-9\p{Ps}\p{Pi}!?‽:;,.%])(<\/(?!ruby)[a-zA-Z]+>)(\p{Han})~u',
'\1\2 \3'
] );
$this->page_str_replace( 'template_redirect', 'preg_replace', [
'~[ ]*([「」『』()〈〉《》【】〔〕〖〗〘〙〚〛])[ ]*~u',
'\1'
] );
}
// code from quotmarks-replacer plugin
if ( in_array( 'punctuation', (array) $this->settings['windfonts_typography'] ) ) {
$qmr_work_tags = array(
'the_title', // http://codex.wordpress.org/Function_Reference/the_title
'the_content', // http://codex.wordpress.org/Function_Reference/the_content
'the_excerpt', // http://codex.wordpress.org/Function_Reference/the_excerpt
// 'list_cats', Deprecated. http://codex.wordpress.org/Function_Reference/list_cats
'single_post_title', // http://codex.wordpress.org/Function_Reference/single_post_title
'comment_author', // http://codex.wordpress.org/Function_Reference/comment_author
'comment_text', // http://codex.wordpress.org/Function_Reference/comment_text
// 'link_name', Deprecated.
// 'link_notes', Deprecated.
'link_description', // Deprecated, but still widely used.
'bloginfo', // http://codex.wordpress.org/Function_Reference/bloginfo
'wp_title', // http://codex.wordpress.org/Function_Reference/wp_title
'term_description', // http://codex.wordpress.org/Function_Reference/term_description
'category_description', // http://codex.wordpress.org/Function_Reference/category_description
'widget_title', // Used by all widgets in themes
'widget_text' // Used by all widgets in themes
);

foreach ( $qmr_work_tags as $qmr_work_tag ) {
remove_filter( $qmr_work_tag, 'wptexturize' );
}
}
// 支持中文排版段首缩进 2em
if ( in_array( 'indent', (array) $this->settings['windfonts_typography'] ) ) {
add_action( 'wp_head', function () {
echo '<style>
.entry-content p {
text-indent: 2em;
}
.entry-content .wp-block-group p,
.entry-content .wp-block-columns p,
.entry-content .wp-block-media-text p,
.entry-content .wp-block-quote p {
text-indent: 0;
}

</style>';
} );
}
// 支持中文排版两端对齐
if ( in_array( 'align', (array) $this->settings['windfonts_typography'] ) ) {
add_action( 'wp_head', function () {
if ( is_single() ) { // 仅在文章页面生效
echo '<style>
.entry-content p {
text-align: justify;
}
.entry-content .wp-block-group p,
.entry-content .wp-block-columns p,
.entry-content .wp-block-media-text p,
.entry-content .wp-block-quote p {
text-align: unset !important;
}
.entry-content .wp-block-columns .has-text-align-center {
text-align: center !important;
}
</style>';
}
} );
}
</style>';
}

/**
* 加载广告拦截
*/
public function load_adblock() {
if (empty($this->settings['adblock']) || $this->settings['adblock'] !== 'on') {
return;
}

// 处理广告拦截规则
foreach ( (array) $this->settings['adblock_rule'] as $rule ) {
if ( empty( $rule['enable'] ) || empty( $rule['selector'] ) ) {
continue;
}
echo sprintf( '<style>%s{display:none!important;}</style>',
htmlspecialchars_decode( $rule['selector'] )
);
}
}


/**
* 加载通知管理
*/
public function load_notice_management() {
// 首先检查是否启用通知管理功能
if (empty($this->settings['notice_block']) || $this->settings['notice_block'] !== 'on') {
return;
}

// 检查是否启用全局禁用
if (!empty($this->settings['disable_all_notices'])) {
$this->disable_all_notices();
echo '<style>.notice,.notice-error,.notice-warning,.notice-success,.notice-info,.updated,.error,.update-nag{display:none!important;}</style>';
return;
}

// 处理选择性禁用
$selected_notices = $this->settings['notice_control'] ?? [];
$notice_method = $this->settings['notice_method'] ?? 'hook';
if (!empty($selected_notices)) {
// 处理钩子移除
if (in_array($notice_method, ['hook', 'both'])) {
$this->disable_selected_notices($selected_notices);
}

// 处理 CSS 隐藏
if (in_array($notice_method, ['css', 'both'])) {
$this->apply_notice_css($selected_notices);
}
}
}

/**
* 应用通知 CSS 隐藏
*/
private function apply_notice_css($selected_notices) {
$selectors = [];
foreach ($selected_notices as $type) {
switch ($type) {
case 'error':
$selectors[] = '.notice-error,.error';
break;
case 'warning':
$selectors[] = '.notice-warning';
break;
case 'success':
$selectors[] = '.notice-success,.updated';
break;
case 'info':
$selectors[] = '.notice-info';
break;
case 'core':
$selectors[] = '.update-nag';
break;
}
}
if (!empty($selectors)) {
echo '<style>' . implode(',', $selectors) . '{display:none!important;}</style>';
}
}

/**
* 移除所有管理通知
*/
private function disable_all_notices() {
remove_all_actions('admin_notices');
remove_all_actions('all_admin_notices');
remove_all_actions('user_admin_notices');
remove_all_actions('network_admin_notices');
}

/**
* 禁用选定的通知类型
*/
private function disable_selected_notices($types) {
if (in_array('core', $types)) {
remove_action('admin_notices', 'update_nag', 3);
remove_action('admin_notices', 'maintenance_nag', 10);
add_filter('pre_site_transient_update_core', '__return_null');
add_filter('pre_site_transient_update_plugins', '__return_null');
add_filter('pre_site_transient_update_themes', '__return_null');
}
}



/**
* 加载飞行模式
*/
public function load_plane() {
add_filter( 'pre_http_request', function ( $preempt, $parsed_args, $url ) {
foreach ( (array) $this->settings['plane_rule'] as $rule ) {
if ( empty( $rule['enable'] ) ) {
continue;
}
if ( empty( $rule['url'] ) ) {
continue;
}
if ( strpos( $url, $rule['url'] ) !== false ) {
return new WP_Error( 'http_request_not_executed', '无用 URL 已屏蔽访问' );
}
foreach ( (array) $this->settings['plane_rule'] as $rule ) {
if ( empty( $rule['enable'] ) || empty( $rule['domain'] ) ) {
continue;
}

return $preempt;
}, PHP_INT_MAX, 3 );
add_filter( 'pre_http_request', function ( $preempt, $parsed_args, $url ) use ( $rule ) {
$host = wp_parse_url( $url, PHP_URL_HOST );
if ( strpos( $host, $rule['domain'] ) !== false ) {
return new WP_Error( 'http_request_failed', 'Blocked by plane mode' );
}
return $preempt;
}, 10, 3 );
}
}

/**
* WordPress.Org 替换
*/
public function filter_wordpress_org( $preempt, $args, $url ) {
if ( $preempt || isset( $args['_wp_china_yes'] ) ) {
return $preempt;
}
if ( ( ! strpos( $url, 'api.wordpress.org' ) && ! strpos( $url, 'downloads.wordpress.org' ) ) ) {
public function filter_wordpress_org( $preempt, $parsed_args, $url ) {
$host = wp_parse_url( $url, PHP_URL_HOST );
if ( ! in_array( $host, [ 'api.wordpress.org', 'downloads.wordpress.org' ] ) ) {
return $preempt;
}

if ( $this->settings['store'] == 'wenpai' ) {
$url = str_replace( 'api.wordpress.org', 'api.wenpai.net', $url );
$path = wp_parse_url( $url, PHP_URL_PATH );
$query = wp_parse_url( $url, PHP_URL_QUERY );

if ( $this->settings['store'] == 'cn' ) {
$mirror_url = 'https://api.wenpai.net' . $path;
} else {
$url = str_replace( 'api.wordpress.org', 'api.wpmirror.com', $url );
}
$url = str_replace( 'downloads.wordpress.org', 'downloads.wenpai.net', $url );

$curl_version = '1.0.0';
if ( function_exists( 'curl_version' ) ) {
$curl_version_array = curl_version();
if ( is_array( $curl_version_array ) && key_exists( 'version', $curl_version_array ) ) {
$curl_version = $curl_version_array['version'];
}
}
if ( version_compare( $curl_version, '7.15.0', '<' ) ) {
$url = str_replace( 'https://', 'http://', $url );
$mirror_url = 'https://api.wenpai.net' . $path;
}

$args['_wp_china_yes'] = true;
if ( $query ) {
$mirror_url .= '?' . $query;
}

return wp_remote_request( $url, $args );
$parsed_args['timeout'] = 30;
return wp_remote_request( $mirror_url, $parsed_args );
}

/**
* 初认头像替换
*/
public function get_cravatar_url( $url ) {
switch ( $this->settings['cravatar'] ) {
case 'cn':
return $this->replace_avatar_url( $url, 'cn.cravatar.com' );
case 'global':
return $this->replace_avatar_url( $url, 'en.cravatar.com' );
case 'weavatar':
return $this->replace_avatar_url( $url, 'weavatar.com' );
default:
return $url;
}
public function set_user_profile_picture_for_cravatar( $description ) {
return str_replace( 'Gravatar', 'Cravatar', $description );
}

/**
* 头像 URL 替换
*/
public function replace_avatar_url( $url, $domain ) {
$sources = array(
'www.gravatar.com',
'0.gravatar.com',
'1.gravatar.com',
'2.gravatar.com',
's.gravatar.com',
'secure.gravatar.com',
'cn.gravatar.com',
'en.gravatar.com',
'gravatar.com',
'sdn.geekzu.org',
'gravatar.duoshuo.com',
'gravatar.loli.net',
'dn-qiniu-avatar.qbox.me'
);

return str_replace( $sources, $domain, $url );
}

/**
* WordPress 讨论设置中的默认 LOGO 名称替换
*/
public function set_defaults_for_cravatar( $avatar_defaults ) {
if ( $this->settings['cravatar'] == 'weavatar' ) {
$avatar_defaults['gravatar_default'] = 'WeAvatar';
} else {
$avatar_defaults['gravatar_default'] = '初认头像';
}

$avatar_defaults['cravatar'] = 'Cravatar Logo (Generated)';
return $avatar_defaults;
}

/**
* 个人资料卡中的头像上传地址替换
*/
public function set_user_profile_picture_for_cravatar() {
if ( $this->settings['cravatar'] == 'weavatar' ) {
return '<a href="https://weavatar.com" target="_blank">您可以在 WeAvatar 修改您的资料图片</a>';
} else {
return '<a href="https://cravatar.com" target="_blank">您可以在初认头像修改您的资料图片</a>';
public function get_cravatar_url( $url ) {
$sources = [
'www.gravatar.com' => 'cn.cravatar.com',
'0.gravatar.com' => 'cn.cravatar.com',
'1.gravatar.com' => 'cn.cravatar.com',
'2.gravatar.com' => 'cn.cravatar.com',
'secure.gravatar.com' => 'cn.cravatar.com',
'cn.gravatar.com' => 'cn.cravatar.com',
'gravatar.com' => 'cn.cravatar.com',
];

if ( $this->settings['cravatar'] == 'global' ) {
$sources = [
'www.gravatar.com' => 'www.gravatar.com',
'0.gravatar.com' => 'www.gravatar.com',
'1.gravatar.com' => 'www.gravatar.com',
'2.gravatar.com' => 'www.gravatar.com',
'secure.gravatar.com' => 'www.gravatar.com',
'cn.gravatar.com' => 'www.gravatar.com',
'gravatar.com' => 'www.gravatar.com',
];
}

return str_replace( array_keys( $sources ), array_values( $sources ), $url );
}

/**
* 页面替换
*
* @param $replace_func string 要调用的字符串关键字替换函数
* @param $param array 传递给字符串替换函数的参数
*/
private function page_str_replace( $hook, $replace_func, $param ) {
// CLI 下返回,防止影响缓冲区
if ( php_sapi_name() == 'cli' ) {
return;
}
add_action( $hook, function () use ( $replace_func, $param ) {
ob_start( function ( $buffer ) use ( $replace_func, $param ) {
$param[] = $buffer;

return call_user_func_array( $replace_func, $param );
public function page_str_replace( $hook, $function, $args ) {
add_action( $hook, function () use ( $function, $args ) {
ob_start( function ( $buffer ) use ( $function, $args ) {
return call_user_func_array( $function, array_merge( [ $args[0], $args[1], $buffer ] ) );
} );
}, PHP_INT_MAX );
}, 1 );

add_action( 'wp_footer', function () {
if ( ob_get_level() ) {
ob_end_flush();
}
}, 999 );
}
}

View file

@ -0,0 +1,140 @@
<?php

namespace WenPai\ChinaYes\Service;

class TranslationManager {
private static $instance = null;
private static $loaded = false;
private static $translations = [];
private static $fallbacks = [];
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action('init', [$this, 'loadTranslations'], 1);
add_action('plugins_loaded', [$this, 'registerFallbacks'], 999);
}
public function loadTranslations() {
if (!self::$loaded) {
$domain = 'wp-china-yes';
$locale = determine_locale();
$mofile = CHINA_YES_PLUGIN_PATH . 'languages/' . $domain . '-' . $locale . '.mo';
if (file_exists($mofile)) {
load_textdomain($domain, $mofile);
} else {
load_plugin_textdomain($domain, false, dirname(plugin_basename(CHINA_YES_PLUGIN_FILE)) . '/languages');
}
self::$loaded = true;
do_action('wp_china_yes_translations_loaded');
}
}
public function registerFallbacks() {
self::$fallbacks = [
'应用市场' => '应用市场',
'萌芽加速' => '萌芽加速',
'文件加速' => '文件加速',
'开发加速' => '开发加速',
'初认头像' => '初认头像',
'文风字体' => '文风字体',
'字体家族' => '字体家族',
'字体链接' => '字体链接',
'字体字重' => '字体字重',
'字体样式' => '字体样式',
'字体应用' => '字体应用',
'启用字体' => '启用字体',
'排印优化' => '排印优化',
'英文美化' => '英文美化',
'墨图云集' => '墨图云集',
'飞秒邮箱' => '飞秒邮箱',
'无言会语' => '无言会语',
'笔笙区块' => '笔笙区块',
'灯鹿用户' => '灯鹿用户',
'Woo电商' => 'Woo电商',
'乐尔达思' => '乐尔达思',
'瓦普文创' => '瓦普文创',
'广告拦截' => '广告拦截',
'规则名称' => '规则名称',
'应用元素' => '应用元素',
'启用规则' => '启用规则',
'通知管理' => '通知管理',
'管理和控制 WordPress 后台各类通知的显示。' => '管理和控制 WordPress 后台各类通知的显示。',
'禁用所有通知' => '禁用所有通知',
'选择性禁用' => '选择性禁用',
'可以按住 Ctrl/Command 键进行多选' => '可以按住 Ctrl/Command 键进行多选',
'禁用方式' => '禁用方式',
'飞行模式' => '飞行模式',
'URL' => 'URL',
'显示参数' => '显示参数',
'为网站维护人员提供参考依据,无需登录服务器即可查看相关信息参数' => '为网站维护人员提供参考依据,无需登录服务器即可查看相关信息参数',
'为网站管理人员提供参考依据,进入后台仪表盘即可查看相关信息参数' => '为网站管理人员提供参考依据,进入后台仪表盘即可查看相关信息参数',
'启用后,网站将显示维护页面,只有管理员可以访问。' => '启用后,网站将显示维护页面,只有管理员可以访问。',
'雨滴安全' => '雨滴安全',
'禁用文件编辑' => '禁用文件编辑',
'启用后,用户无法通过 WordPress 后台编辑主题和插件文件。' => '启用后,用户无法通过 WordPress 后台编辑主题和插件文件。',
'禁用文件修改' => '禁用文件修改',
'启用后,用户无法通过 WordPress 后台安装、更新或删除主题和插件。' => '启用后,用户无法通过 WordPress 后台安装、更新或删除主题和插件。',
'性能优化' => '性能优化',
'性能优化设置可以帮助提升 WordPress 的运行效率,请根据服务器配置合理调整。' => '性能优化设置可以帮助提升 WordPress 的运行效率,请根据服务器配置合理调整。',
'内存限制' => '内存限制',
'设置 WordPress 的内存限制,例如 64M、128M、256M 等。' => '设置 WordPress 的内存限制,例如 64M、128M、256M 等。',
'后台内存限制' => '后台内存限制',
'设置 WordPress 后台的内存限制,例如 128M、256M、512M 等。' => '设置 WordPress 后台的内存限制,例如 128M、256M、512M 等。',
'文章修订版本' => '文章修订版本',
'设置为 0 禁用修订版本,或设置为一个固定值(如 5限制修订版本数量。' => '设置为 0 禁用修订版本,或设置为一个固定值(如 5限制修订版本数量。',
'自动保存间隔' => '自动保存间隔',
'设置文章自动保存的时间间隔,默认是 60 秒。' => '设置文章自动保存的时间间隔,默认是 60 秒。',
'专为 WordPress 建站服务商和代理机构提供的自定义品牌 OEM 功能,输入您的品牌词启用后生效' => '专为 WordPress 建站服务商和代理机构提供的自定义品牌 OEM 功能,输入您的品牌词启用后生效',
'注意:启用[隐藏菜单]前请务必保存或收藏当前设置页面 URL否则将无法再次进入插件页面' => '注意:启用[隐藏菜单]前请务必保存或收藏当前设置页面 URL否则将无法再次进入插件页面',
'调试模式' => '调试模式',
'启用后WordPress 将显示 PHP 错误、警告和通知。临时使用完毕后,请保持禁用此选项。' => '启用后WordPress 将显示 PHP 错误、警告和通知。临时使用完毕后,请保持禁用此选项。',
'调试选项' => '调试选项',
'注意:调试模式仅适用于开发和测试环境,不建议在生产环境中长时间启用。选择要启用的调试功能,适用于开发和测试环境。' => '注意:调试模式仅适用于开发和测试环境,不建议在生产环境中长时间启用。选择要启用的调试功能,适用于开发和测试环境。',
'数据库工具' => '数据库工具',
'启用后,您可以在下方访问数据库修复工具。定期使用完毕后,请保持禁用此选项。' => '启用后,您可以在下方访问数据库修复工具。定期使用完毕后,请保持禁用此选项。',
'数据库修复工具' => '数据库修复工具',
'打开数据库修复工具' => '打开数据库修复工具',
'启用后,您可以在下方选用文派叶子功能,特别提醒:禁用对应功能后再次启用需重新设置。' => '启用后,您可以在下方选用文派叶子功能,特别提醒:禁用对应功能后再次启用需重新设置。',
'帮助文档' => '帮助文档',
'文派开源' => '文派开源',
'官方镜像' => '官方镜像',
'不启用' => '不启用'
];
}
public static function translate($text, $domain = 'wp-china-yes') {
if (!self::$loaded) {
return isset(self::$fallbacks[$text]) ? self::$fallbacks[$text] : $text;
}
if (function_exists('__')) {
$translated = __($text, $domain);
return $translated !== $text ? $translated : (isset(self::$fallbacks[$text]) ? self::$fallbacks[$text] : $text);
}
return isset(self::$fallbacks[$text]) ? self::$fallbacks[$text] : $text;
}
public static function translateLazy($text, $domain = 'wp-china-yes') {
return function() use ($text, $domain) {
return self::translate($text, $domain);
};
}
public static function isLoaded() {
return self::$loaded;
}
public static function getFallback($text) {
return isset(self::$fallbacks[$text]) ? self::$fallbacks[$text] : $text;
}
}

181
Service/Widget.php Normal file
View file

@ -0,0 +1,181 @@
<?php

namespace WenPai\ChinaYes\Service;

defined( 'ABSPATH' ) || exit;

use function WenPai\ChinaYes\get_settings;

/**
* Class Widget
* 小组件服务
* @package WenPai\ChinaYes\Service
*/
class Widget {

private $settings;

public function __construct() {
$this->settings = get_settings();

/**
* 添加「文派茶馆」小组件
*/
if ( is_admin() ) {
add_action( 'wp_dashboard_setup', [ $this, 'setup_wenpai_tea_widget' ] );
}
}

/**
* 设置文派茶馆小组件
*/
public function setup_wenpai_tea_widget() {
global $wp_meta_boxes;

unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_primary'] );
wp_add_dashboard_widget( 'wenpai_tea', '文派茶馆', [ $this, 'render_wenpai_tea_widget' ] );
}

/**
* 渲染文派茶馆小组件
*/
public function render_wenpai_tea_widget() {
$default_rss_url = 'https://wptea.com/feed/';
$custom_rss_url = $this->settings['custom_rss_url'] ?? '';
$refresh_interval = $this->settings['custom_rss_refresh'] ?? 14400;

$rss_display_options = $this->settings['rss_display_options'] ?? ['show_date', 'show_summary', 'show_footer'];
if (!is_array($rss_display_options)) {
$rss_display_options = explode(',', $rss_display_options);
}

// 获取默认的 RSS 源内容
$default_rss = fetch_feed($default_rss_url);
$default_items = [];
if (!is_wp_error($default_rss)) {
$default_items = $default_rss->get_items(0, 5);
}

$custom_items = [];
$custom_rss = null;
$custom_rss_latest_date = 0;

if (!empty($custom_rss_url)) {
$transient_key = 'wenpai_tea_custom_rss_' . md5($custom_rss_url);
$cached_custom_items = get_transient($transient_key);

if (false === $cached_custom_items) {
$custom_rss = fetch_feed($custom_rss_url);
if (!is_wp_error($custom_rss)) {
$custom_items = $custom_rss->get_items(0, 2);
if (!empty($custom_items)) {
$custom_rss_latest_date = $custom_items[0]->get_date('U');
}

set_transient($transient_key, $custom_items, $refresh_interval);
}
} else {
$custom_items = $cached_custom_items;
if (!empty($custom_items)) {
$custom_rss_latest_date = $custom_items[0]->get_date('U');
}
}
}

$three_days_ago = time() - (3 * 24 * 60 * 60);
if ($custom_rss_latest_date > $three_days_ago) {
$items = array_merge(array_slice($default_items, 0, 3), $custom_items);
} else {
$items = array_slice($default_items, 0, 5);
}

if (is_wp_error($custom_rss)) {
$items = array_slice($default_items, 0, 5);
}

echo <<<HTML
<div class="wordpress-news hide-if-no-js">
<div class="rss-widget">
HTML;
foreach ($items as $item) {
echo '<div class="rss-item">';
echo '<a href="' . esc_url($item->get_permalink()) . '" target="_blank">' . esc_html($item->get_title()) . '</a>';
if (in_array('show_date', $rss_display_options)) {
echo '<span class="rss-date">' . esc_html($item->get_date('Y.m.d')) . '</span>';
}
if (in_array('show_summary', $rss_display_options)) {
echo '<div class="rss-summary">' . esc_html(wp_trim_words($item->get_description(), 45, '...')) . '</div>';
}
echo '</div>';
}
echo <<<HTML
</div>
</div>
HTML;
if (in_array('show_footer', $rss_display_options)) {
echo <<<HTML
<p class="community-events-footer">
<a href="https://wenpai.org/" target="_blank">文派开源</a>
|
<a href="https://wenpai.org/support" target="_blank">支持论坛</a>
|
<a href="https://translate.wenpai.org/" target="_blank">翻译平台</a>
|
<a href="https://wptea.com/newsletter/" target="_blank">订阅推送</a>
</p>
HTML;
}
echo <<<HTML
<style>
#wenpai_tea .rss-widget {
padding: 0 12px;
}
#wenpai_tea .rss-widget:last-child {
border-bottom: none;
padding-bottom: 8px;
}
#wenpai_tea .rss-item {
margin-bottom: 10px;
padding-bottom: 10px;
border-bottom: 1px solid #eee;
}
#wenpai_tea .rss-item:last-child {
border-bottom: none;
margin-bottom: 0;
padding-bottom: 0;
}
#wenpai_tea .rss-item a {
text-decoration: none;
display: block;
margin-bottom: 5px;
}
#wenpai_tea .rss-date {
color: #666;
font-size: 12px;
display: block;
margin-bottom: 8px;
}
#wenpai_tea .rss-summary {
color: #444;
font-size: 13px;
line-height: 1.5;
}
#wenpai_tea .community-events-footer {
margin-top: 15px;
padding-top: 15px;
padding-bottom: 5px;
border-top: 1px solid #eee;
text-align: center;
}
#wenpai_tea .community-events-footer a {
text-decoration: none;
margin: 0 5px;
}
#wenpai_tea .community-events-footer a:hover {
text-decoration: underline;
}
</style>
HTML;
}
}

View file

@ -9,18 +9,78 @@
}


@media only screen and (max-width: 1200px) {
.wp_china_yes-nav-normal {
width: 200px;
}
.wp_china_yes-nav-normal+.wp_china_yes-content {
margin-left: 200px;
}
.wp_china_yes-nav-background {
width: 200px;
}
}

@media only screen and (max-width: 960px) {
.wp_china_yes-field .wp_china_yes-title {
width: 30%;
}
.wp_china_yes-field .wp_china_yes-fieldset {
width: calc(70% - 20px);
}
.wpcy-about__grid.columns-3 {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}

@media only screen and (max-width: 782px) {
.wp_china_yes-nav-normal+.wp_china_yes-content {
margin-left: 0!important;
}
.wp_china_yes-nav-normal {
position: fixed;
top: 32px;
left: -250px;
height: 100vh;
z-index: 9999;
transition: left 0.3s ease;
background: #fff;
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
}
.wp_china_yes-nav-normal.mobile-open {
left: 0;
}
.wp_china_yes-header-inner {
position: relative;
padding: 15px 20px;
}
.wp_china_yes-header-inner h1 {
margin-bottom: 20px;
margin-bottom: 10px;
font-size: 1.3em;
}
.auto-fold #wpcontent {
padding-left: 0px;
}
.wp_china_yes-field-text input {
width: 100%;
.wp_china_yes-field-text input,
.wp_china_yes-field-textarea textarea,
.wp_china_yes-field-select select {
width: 100%;
max-width: 100%;
}
.wp_china_yes-field .wp_china_yes-title {
width: 100%;
float: none;
margin-bottom: 10px;
}
.wp_china_yes-field .wp_china_yes-fieldset {
width: 100%;
float: none;
}
.wp_china_yes-field {
padding: 20px;
}
.wp_china_yes-section {
margin: 20px auto;
}
}

@ -319,9 +379,63 @@


@media screen and (max-width: 600px) {
.wpcy-about__grid {
.wpcy-about__grid {
grid-template-columns: 1fr!important;
}
.wp_china_yes-buttons {
flex-direction: column;
align-items: stretch;
}
.wp_china_yes-buttons .button {
margin: 2px 0;
text-align: center;
}
.sponsor-logos {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.sponsor-logos img {
max-width: 60px;
margin: 8px;
}
.wpcy-buttons {
flex-direction: column;
gap: 8px;
}
.components-button {
justify-content: center;
padding: 8px 12px;
min-height: 40px;
}
}

@media screen and (max-width: 480px) {
.wp_china_yes-header-inner {
padding: 10px 15px;
}
.wp_china_yes-header-inner h1 {
font-size: 1.2em;
line-height: 1.3;
}
.wp_china_yes-field {
padding: 15px;
margin: 10px 0;
}
.wp_china_yes-section {
margin: 10px auto;
max-width: 100%;
}
.wp_china_yes-section-title {
padding: 15px 20px;
}
.sponsor-logos {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.wpcy-about__grid .column {
padding: 6%;
}
.column.wpcy-kit-banner {
padding: 4% 4% 2%!important;
}
}


@ -452,3 +566,56 @@ span.wpcy-icon-inner-list {
padding: 6px 12px;
}

/* 移动端菜单按钮样式 */
.wp_china_yes-mobile-menu-btn {
color: #333;
padding: 5px;
border-radius: 3px;
}

.wp_china_yes-mobile-menu-btn:hover {
background-color: rgba(0,0,0,0.1);
}

/* 表单元素响应式优化 */
@media screen and (max-width: 782px) {
.wp_china_yes-field-checkbox .wp_china_yes--inline-list li,
.wp_china_yes-field-radio .wp_china_yes--inline-list li {
display: block;
margin-right: 0;
margin-bottom: 8px;
}
.wp_china_yes-field-button_set .wp_china_yes--buttons {
display: flex;
flex-wrap: wrap;
gap: 5px;
}
.wp_china_yes-field-button_set .wp_china_yes--button {
flex: 1;
min-width: 80px;
text-align: center;
border-radius: 4px !important;
margin-left: 0 !important;
}
.wp_china_yes-field-color > input {
width: 100%;
max-width: 200px;
}
.wp_china_yes-field-upload .button {
width: 100%;
margin-bottom: 10px;
}
}

/* 平板设备优化 */
@media screen and (min-width: 783px) and (max-width: 960px) {
.wp_china_yes-field-checkbox .wp_china_yes--inline-list li,
.wp_china_yes-field-radio .wp_china_yes--inline-list li {
margin-right: 10px;
}
}


BIN
assets/images/wpcy-logo.png Executable file → Normal file

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Before After
Before After

View file

@ -1,4 +1,43 @@
jQuery(document).ready(function($) {
jQuery(document).ready(function($) {
// 移动端菜单切换功能
function initMobileMenu() {
// 添加菜单按钮
if (!$('.wp_china_yes-mobile-menu-btn').length) {
$('.wp_china_yes-header-inner').prepend(
'<button class="wp_china_yes-mobile-menu-btn" style="display: none; position: absolute; left: 15px; top: 50%; transform: translateY(-50%); background: none; border: none; font-size: 18px; cursor: pointer; z-index: 10000;">☰</button>'
);
}
// 检查屏幕尺寸
function checkScreenSize() {
if ($(window).width() <= 782) {
$('.wp_china_yes-mobile-menu-btn').show();
$('.wp_china_yes-nav-normal').removeClass('mobile-open');
} else {
$('.wp_china_yes-mobile-menu-btn').hide();
$('.wp_china_yes-nav-normal').removeClass('mobile-open');
}
}
// 菜单按钮点击事件
$(document).on('click', '.wp_china_yes-mobile-menu-btn', function() {
$('.wp_china_yes-nav-normal').toggleClass('mobile-open');
});
// 点击内容区域关闭菜单
$(document).on('click', '.wp_china_yes-content', function() {
if ($(window).width() <= 782) {
$('.wp_china_yes-nav-normal').removeClass('mobile-open');
}
});
// 窗口大小改变时检查
$(window).resize(checkScreenSize);
checkScreenSize();
}
initMobileMenu();
$("#test-rss-feed").click(function() {
var button = $(this);
var result = $("#rss-test-result");

View file

@ -67,8 +67,8 @@ if ( ! class_exists( 'WP_CHINA_YES_Setup' ) ) {
// Init action
do_action( 'wp_china_yes_init' );

// Setup textdomain
self::textdomain();
// Setup textdomain on init action
add_action( 'init', array( 'WP_CHINA_YES_Setup', 'textdomain' ) );

add_action( 'after_setup_theme', array( 'WP_CHINA_YES', 'setup' ) );
add_action( 'init', array( 'WP_CHINA_YES', 'setup' ) );

View file

@ -6,15 +6,57 @@ defined( 'ABSPATH' ) || exit;

// 获取插件设置
function get_settings() {
$settings = is_multisite() ? get_site_option( 'wp_china_yes' ) : get_option( 'wp_china_yes' );

return wp_parse_args( $settings, [
static $cached_settings = null;
if ($cached_settings === null) {
$settings = is_multisite() ? get_site_option( 'wp_china_yes' ) : get_option( 'wp_china_yes' );
$cached_settings = wp_parse_args( $settings, [
'store' => 'wenpai',
'bridge' => true,
'arkpress' => false,
'admincdn' => [ 'admin' ],
'admincdn_public' => [ 'googlefonts' ],
'admincdn_files' => [ 'admin', 'emoji' ],
'admincdn_dev' => [ 'jquery' ],
'admincdn_version_enable' => false,
'admincdn_version' => [ 'css', 'js', 'timestamp' ],
'cravatar' => 'cn',
'windfonts' => 'off',
'windfonts_list' => [],
'windfonts_typography' => [],
'windfonts_list' => [
[
'family' => 'cszt',
'subset' => 'regular',
'lang' => '',
'weight' => 400,
'style' => 'normal',
'selector' => 'a:not([class]),p,h1,h2,h3,h4,h5,h6,ul,ol,li,button,blockquote,pre,code,table,th,td,label,b,i:not([class]),em,small,strong,sub,sup,ins,del,mark,abbr,dfn,span:not([class])',
'enable' => true,
]
],
'windfonts_typography_cn' => [],
'windfonts_typography_en' => [],
'windfonts_reading_enable' => false,
'windfonts_reading' => 'off',
'motucloud' => 'off',
'fewmail' => 'off',
'comments_enable' => false,
'comments_role_badge' => true,
'comments_remove_website' => false,
'comments_validation' => true,
'comments_herp_derp' => false,
'comments_sticky_moderate' => false,
'wordyeah' => 'off',
'bisheng' => 'off',
'deerlogin' => 'off',
'waimao' => 'off',
'waimao_enable' => false,
'waimao_language_split' => false,
'waimao_admin_language' => 'zh_CN',
'waimao_frontend_language' => 'en_US',
'waimao_auto_detect' => false,
'woocn' => 'off',
'lelms' => 'off',
'wapuu' => 'off',
'adblock' => 'off',
'adblock_rule' => [],
'plane' => 'off',
@ -23,5 +65,21 @@ function get_settings() {
'memory' => true,
'hide' => false,
'custom_name' => 'WP-China-Yes',
] );
'enabled_sections' => [ 'welcome', 'store', 'admincdn', 'cravatar', 'other', 'about' ],
'wp_memory_limit' => '256M',
'wp_max_memory_limit' => '512M',
'wp_post_revisions' => 5,
'autosave_interval' => 300,
'custom_rss_url' => '',
'custom_rss_refresh' => 3600,
'rss_display_options' => [ 'show_date', 'show_summary', 'show_footer' ],
] );
}
return $cached_settings;
}

function clear_settings_cache() {
static $cached_settings = null;
$cached_settings = null;
}

View file

@ -5,7 +5,7 @@
<div class="wpcy-about__grid columns-1">
<div class="column wpcy-kit-banner"><span class="wpcy-icon-inner"> <i class="icon icon-archive-1"></i></span>
<h2>项目简介</h2>
<p>文派WordPress中国本土化项目始于 2019 年,由 文派叶子🍃WPCY 插件开启,其前身为 WP-China-Yes。
<p>文派WordPress中国本土化项目始于 2019 年,由 文派叶子🍃WPCY.COM 插件开启,其前身为 WP-China-Yes。

</p>
<p>2023 年 4 月,文派科技完成对该项目的收购,并对其进行了全面的品牌重塑。</p>
@ -16,16 +16,16 @@
<h2>赞助支持</h2>
<p>特别感谢以下企业品牌对文派项目提供的资金资源支持。早期伙伴未来有机会共享文派生态资源,期待社会各界参与。</p>
<div class="card-body sponsor-logos">
<img src="https://cravatar.cn/wp-content/uploads/2024/09/feibisi-logo.png">
<img src="https://cravatar.cn/wp-content/uploads/2024/09/shujue-logo.png">
<img src="https://cravatar.cn/wp-content/uploads/2024/09/upyun-logo.png">
<img src="https://cravatar.cn/wp-content/uploads/2024/09/haozi-logo.png">
<img src="https://cravatar.cn/wp-content/uploads/2024/09/wpsaas-logo.png">
<img src="https://cravatar.cn/wp-content/uploads/2024/09/lingding-logo.png">
<img src="https://cravatar.cn/wp-content/uploads/2024/09/weixiaoduo-logo-2020.png">
<img src="https://cravatar.cn/wp-content/uploads/2024/09/modiqi-logo.png">
<img src="https://cravatar.cn/wp-content/uploads/2024/09/kekechong-logo.png">
<img src="https://cravatar.cn/wp-content/uploads/2024/09/wenpai-logo@2X.png">
<img src="https://cn.cravatar.com/wp-content/uploads/2024/09/feibisi-logo.png">
<img src="https://cn.cravatar.com/wp-content/uploads/2024/09/shujue-logo.png">
<img src="https://cn.cravatar.com/wp-content/uploads/2024/09/upyun-logo.png">
<img src="https://cn.cravatar.com/wp-content/uploads/2024/09/haozi-logo.png">
<img src="https://cn.cravatar.com/wp-content/uploads/2024/09/wpsaas-logo.png">
<img src="https://cn.cravatar.com/wp-content/uploads/2024/09/lingding-logo.png">
<img src="https://cn.cravatar.com/wp-content/uploads/2024/09/weixiaoduo-logo-2020.png">
<img src="https://cn.cravatar.com/wp-content/uploads/2024/09/modiqi-logo.png">
<img src="https://cn.cravatar.com/wp-content/uploads/2024/09/kekechong-logo.png">
<img src="https://cn.cravatar.com/wp-content/uploads/2024/09/wenpai-logo@2X.png">
</div>
<div class="wpcy-buttons"><a href="https://wpcy.com/ecosystem" target="_blank" rel="noopener" class="components-button button-secondary">生态共建 ↗</a><a href="https://wpcy.com/about/investor" target="_blank" rel="noopener" class="components-button button-secondary">项目投资 ↗</a></div>
</div>

View file

@ -5,7 +5,7 @@
<div class="wpcy-about__grid">
<div class="column wpcy-banner"><span class="wpcy-icon-inner"> <i class="icon icon-mirroring-screen"></i></span>
<h2>原生体验</h2>
<p>文派叶子🍃WP-China-Yes是一款不可多得的 WordPress 系统底层优化和生态基础设施软件。</p>
<p>文派叶子🍃WPCY.COM是一款不可多得的 WordPress 系统底层优化和生态基础设施软件。</p>
<div class="wpcy-buttons"><a href="<?php echo $settings_page_url; ?>#tab=%e5%bb%ba%e7%ab%99%e5%a5%97%e4%bb%b6" class="components-button button-primary">获取 WP Deer 建站套件</a><a href="https://wenpai.org/" target="_blank" rel="noopener" class="components-button button-secondary">文派开源WenPai.org↗</a></div>
<img
src="/wp-content/plugins/wp-china-yes/assets/images/website-banner.jpg" width="358" height="140" alt=""></div>
@ -42,9 +42,9 @@
class="column"><span class="wpcy-icon-inner"> <i class="icon icon-more-square"></i></span>
<h2>浏览更多</h2>
<ul class="wpcy-about__list">
<li><a href="https://wpcy.com" target="_blank" rel="noopener" class="components-button button-link has-text has-icon"><span class="wpcy-icon-inner-list"> <i class="icon icon-global"></i> </span>文派叶子 🍃 WPCY.com</a></li>
<li><a href="https://wpcy.com" target="_blank" rel="noopener" class="components-button button-link has-text has-icon"><span class="wpcy-icon-inner-list"> <i class="icon icon-global"></i> </span>文派叶子 🍃 WPCY.COM</a></li>
<li><a href="https://wpcy.com/document" target="_blank" rel="noopener" class="components-button button-link has-text has-icon"><span class="wpcy-icon-inner-list"> <i class="icon icon-archive-book"></i> </span>快速入门指南</a></li>
<li><a href="https://wpcy.com/support/" target="_blank" rel="noopener noreferrer" class="components-button button-link has-text has-icon"><span class="wpcy-icon-inner-list"> <i class="icon icon-message-notif"></i> </span>支持论坛</a></li>
<li><a href="https://wpcy.com/community/" target="_blank" rel="noopener noreferrer" class="components-button button-link has-text has-icon"><span class="wpcy-icon-inner-list"> <i class="icon icon-message-notif"></i> </span>官方社区</a></li>
<li><a href="https://space.bilibili.com/3546657484442062" target="_blank" rel="noopener noreferrer" class="components-button button-link has-text has-icon"><span class="wpcy-icon-inner-list"> <i class="icon icon-video-square"></i> </span>Bilibili 官方频道</a></li>
<li><a href="https://wpcy.com/faqs" target="_blank" rel="noopener noreferrer" class="components-button button-link has-text has-icon"><span class="wpcy-icon-inner-list"> <i class="icon icon-lifebuoy"></i> </span>常见问题</a></li>
<li><a href="https://wpcy.com/document/website-backend-is-messy" target="_blank" rel="noopener noreferrer" class="components-button button-link has-text has-icon"><span class="wpcy-icon-inner-list"> <i class="icon icon-warning-2"></i> </span>疑难故障排查…</a></li>

View file

@ -1,7 +1,7 @@
<?php
/**
* Plugin Name: WP-China-Yes
* Description: 文派叶子 🍃WP-China-Yes是中国 WordPress 生态基础设施软件,犹如落叶新芽,生生不息。
* Plugin Name: WPCY.COM
* Description: 文派叶子 🍃WPCY.COM是中国 WordPress 生态基础设施软件,犹如落叶新芽,生生不息。
* Author: 文派开源
* Author URI: https://wpcy.com
* Version: 3.8.1
@ -11,7 +11,7 @@
* Network: True
* Requires at least: 4.9
* Tested up to: 9.9.9
* Requires PHP: 7.0.0
* Requires PHP: 7.4.0
* License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/

@ -19,14 +19,14 @@ namespace WenPai\ChinaYes;

defined( 'ABSPATH' ) || exit;

define( 'CHINA_YES_VERSION', '3.8' );
define( 'CHINA_YES_VERSION', '3.8.1' );
define( 'CHINA_YES_PLUGIN_FILE', __FILE__ );
define( 'CHINA_YES_PLUGIN_URL', plugin_dir_url( CHINA_YES_PLUGIN_FILE ) );
define( 'CHINA_YES_PLUGIN_PATH', plugin_dir_path( CHINA_YES_PLUGIN_FILE ) );

if (file_exists(CHINA_YES_PLUGIN_PATH . 'vendor/autoload.php')) {
// 尽早初始化性能设置
$settings = get_option('wenpai_china_yes'); // 替换成您实际的设置选项名
$settings = is_multisite() ? get_site_option('wp_china_yes') : get_option('wp_china_yes');
if (!empty($settings)) {
if (!defined('WP_MEMORY_LIMIT') && !empty($settings['wp_memory_limit'])) {
define('WP_MEMORY_LIMIT', $settings['wp_memory_limit']);
@ -41,9 +41,28 @@ if (file_exists(CHINA_YES_PLUGIN_PATH . 'vendor/autoload.php')) {
if (!defined('AUTOSAVE_INTERVAL') && !empty($settings['autosave_interval'])) {
define('AUTOSAVE_INTERVAL', intval($settings['autosave_interval']));
}
if (!defined('EMPTY_TRASH_DAYS') && isset($settings['empty_trash_days'])) {
define('EMPTY_TRASH_DAYS', intval($settings['empty_trash_days']));
}
}
require_once(CHINA_YES_PLUGIN_PATH . 'vendor/autoload.php');
// 初始化翻译管理器
require_once(CHINA_YES_PLUGIN_PATH . 'Service/TranslationManager.php');
require_once(CHINA_YES_PLUGIN_PATH . 'Service/LazyTranslation.php');
\WenPai\ChinaYes\Service\TranslationManager::getInstance();
// 包含测试文件(仅在开发环境)
if (defined('WP_DEBUG') && WP_DEBUG) {
require_once(CHINA_YES_PLUGIN_PATH . 'test-translation.php');
}
} else {
add_action('admin_notices', function() {
echo '<div class="notice notice-error"><p>WPCY.COM: Composer autoloader not found. Please run "composer install".</p></div>';
});
return;
}

// 注册插件激活钩子