文章目录
-
- 在当今数字化时代,WordPress作为全球最受欢迎的内容管理系统,驱动着超过40%的网站。然而,随着其普及度的提升,WordPress网站也成为了黑客攻击的主要目标。据统计,每天有超过9万个WordPress网站遭受各种形式的网络攻击。与此同时,用户对网站功能的需求也日益多样化,不再满足于基本的内容发布,而是期望网站能够集成各种实用工具,提升用户体验。 本教程将深入探讨如何通过WordPress代码二次开发,实现两个关键目标:一是集成专业级网站安全扫描与漏洞检测工具,构建主动防御体系;二是开发常用互联网小工具,增强网站功能性。我们将从理论基础到实践操作,从安全原理到代码实现,全面解析这一综合解决方案。
-
- WordPress面临的安全威胁多种多样,主要包括: SQL注入攻击:通过恶意SQL代码操纵数据库 跨站脚本攻击(XSS):在网页中注入恶意脚本 跨站请求伪造(CSRF):诱使用户执行非本意的操作 文件包含漏洞:利用文件包含功能执行恶意代码 暴力破解攻击:尝试大量密码组合获取访问权限 主题和插件漏洞:第三方代码中的安全缺陷 根据Wordfence安全报告,2023年针对WordPress的攻击尝试比前一年增加了150%,其中插件和主题漏洞占比高达56%。这些数据凸显了加强WordPress安全防护的紧迫性。
- 传统的WordPress安全方案通常包括: 基础安全插件安装 定期手动更新 简单的防火墙配置 然而,这些方法存在明显不足: 被动防御:多数方案只在攻击发生后响应 检测能力有限:难以发现复杂或新型攻击 误报率高:可能将正常流量误判为攻击 性能影响:某些安全插件显著降低网站速度
- 集成专业安全扫描与漏洞检测工具能够: 实现主动安全监测:定期自动扫描,提前发现潜在风险 深度漏洞检测:使用专业算法识别复杂安全漏洞 实时威胁情报:基于全球攻击数据提供预警 最小性能影响:优化代码减少对网站速度的影响 定制化报告:根据网站特点生成针对性安全建议
-
- 我们将设计一个模块化的安全系统,包含以下核心组件: // 安全系统主类结构 class WP_Security_Scanner { private $scanner_modules = array(); private $vulnerability_db; private $reporting_system; public function __construct() { $this->init_modules(); $this->load_vulnerability_database(); $this->setup_reporting(); } private function init_modules() { // 初始化各扫描模块 $this->scanner_modules = array( 'file_integrity' => new File_Integrity_Scanner(), 'malware_detection' => new Malware_Scanner(), 'vulnerability_scan' => new Vulnerability_Scanner(), 'brute_force_protection' => new Brute_Force_Protector() ); } }
- 文件完整性监控是检测未经授权文件更改的关键技术: class File_Integrity_Scanner { private $baseline_hashes = array(); public function create_baseline() { $wp_files = $this->get_wordpress_files(); foreach ($wp_files as $file) { if ($this->is_scannable_file($file)) { $this->baseline_hashes[$file] = array( 'hash' => md5_file($file), 'size' => filesize($file), 'modified' => filemtime($file) ); } } $this->save_baseline(); } public function run_integrity_check() { $current_hashes = array(); $alerts = array(); foreach ($this->baseline_hashes as $file => $baseline_data) { if (!file_exists($file)) { $alerts[] = "文件删除警告: {$file}"; continue; } $current_hash = md5_file($file); if ($current_hash !== $baseline_data['hash']) { $alerts[] = "文件篡改检测: {$file}"; $this->analyze_file_changes($file, $baseline_data['hash'], $current_hash); } } return $alerts; } }
- 漏洞扫描引擎需要结合本地检测和外部漏洞数据库: class Vulnerability_Scanner { private $vulnerability_sources = array( 'wpvulndb' => 'https://wpvulndb.com/api/v3/', 'nvd' => 'https://services.nvd.nist.gov/rest/json/cves/1.0' ); public function scan_plugins_themes() { $vulnerabilities = array(); // 扫描已安装插件 $plugins = get_plugins(); foreach ($plugins as $plugin_path => $plugin_data) { $plugin_slug = dirname($plugin_path); $plugin_version = $plugin_data['Version']; $plugin_vulns = $this->check_plugin_vulnerabilities($plugin_slug, $plugin_version); if (!empty($plugin_vulns)) { $vulnerabilities['plugins'][$plugin_slug] = $plugin_vulns; } } // 扫描当前主题 $theme = wp_get_theme(); $theme_vulns = $this->check_theme_vulnerabilities($theme->get('TextDomain'), $theme->get('Version')); if (!empty($theme_vulns)) { $vulnerabilities['theme'] = $theme_vulns; } return $vulnerabilities; } private function check_plugin_vulnerabilities($slug, $version) { // 查询漏洞数据库 $api_url = $this->vulnerability_sources['wpvulndb'] . "plugins/{$slug}"; $response = wp_remote_get($api_url); if (is_wp_error($response)) { return false; } $data = json_decode(wp_remote_retrieve_body($response), true); $relevant_vulns = array(); if (isset($data[$slug]['vulnerabilities'])) { foreach ($data[$slug]['vulnerabilities'] as $vuln) { if ($this->is_version_affected($version, $vuln['fixed_in'])) { $relevant_vulns[] = array( 'id' => $vuln['id'], 'title' => $vuln['title'], 'cvss_score' => $vuln['cvss']['score'], 'fixed_in' => $vuln['fixed_in'] ); } } } return $relevant_vulns; } }
- 恶意代码检测需要结合特征码检测和行为分析: class Malware_Scanner { private $malware_signatures = array( 'base64_decode' => '/base64_decodes*([^)]*)/', 'eval' => '/evals*([^)]*)/', 'shell_exec' => '/shell_execs*([^)]*)/', 'suspicious_url' => '/(https?://[^s<>"']*.(php|exe|bat|sh))/i' ); private $suspicious_patterns = array( 'obfuscated_code' => '/$(?:w+)s*=s*$(?:w+)s*.s*$(?:w+)/', 'long_string' => '/"[^"]{200,}"/' ); public function scan_directory($directory) { $malware_findings = array(); $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($directory) ); foreach ($files as $file) { if ($file->isDir()) continue; if ($this->is_php_file($file)) { $content = file_get_contents($file->getPathname()); $file_findings = $this->analyze_file_content($content, $file->getPathname()); if (!empty($file_findings)) { $malware_findings[$file->getPathname()] = $file_findings; } } } return $malware_findings; } private function analyze_file_content($content, $filename) { $findings = array(); // 检查已知恶意代码特征 foreach ($this->malware_signatures as $type => $pattern) { if (preg_match_all($pattern, $content, $matches)) { $findings[$type] = $matches[0]; } } // 检查可疑代码模式 foreach ($this->suspicious_patterns as $pattern_name => $pattern) { if (preg_match_all($pattern, $content, $matches)) { $findings[$pattern_name] = count($matches[0]); } } // 检查文件权限 $perms = substr(sprintf('%o', fileperms($filename)), -4); if ($perms == '0777') { $findings['insecure_permissions'] = $perms; } return $findings; } }
- class Security_Reporter { private $report_types = array('daily', 'weekly', 'immediate'); private $notification_methods = array('email', 'dashboard', 'webhook'); public function generate_report($scan_results, $report_type = 'daily') { $report = array( 'timestamp' => current_time('timestamp'), 'scan_summary' => array( 'total_checks' => 0, 'issues_found' => 0, 'critical_issues' => 0 ), 'detailed_findings' => array(), 'recommendations' => array() ); // 汇总扫描结果 foreach ($scan_results as $module => $results) { $report['scan_summary']['total_checks']++; if (!empty($results)) { $report['scan_summary']['issues_found']++; $report['detailed_findings'][$module] = $results; // 生成建议 $report['recommendations'] = array_merge( $report['recommendations'], $this->generate_recommendations($module, $results) ); } } // 确定报告严重级别 $report['severity'] = $this->calculate_severity($report); return $report; } public function send_alerts($report) { if ($report['severity'] >= 7) { // 高严重级别 $this->send_immediate_alert($report); } // 发送定期报告 if ($this->is_time_for_report('daily')) { $this->send_email_report($report, 'daily'); } // 更新仪表板小工具 $this->update_dashboard_widget($report); } }
-
- 我们将创建一个可扩展的小工具框架: class WP_Toolkit_Framework { private $tools = array(); private $tool_categories = array( 'utility' => '实用工具', 'seo' => 'SEO工具', 'security' => '安全工具', 'development' => '开发工具' ); public function register_tool($tool_slug, $tool_config) { $defaults = array( 'name' => '', 'description' => '', 'category' => 'utility', 'callback' => null, 'settings' => array(), 'shortcode' => '' ); $config = wp_parse_args($tool_config, $defaults); $this->tools[$tool_slug] = $config; // 注册短代码 if (!empty($config['shortcode'])) { add_shortcode($config['shortcode'], array($this, 'render_tool')); } } public function render_tool($atts, $content = null, $tag = '') { $atts = shortcode_atts(array('tool' => ''), $atts, $tag); if (empty($atts['tool']) || !isset($this->tools[$atts['tool']])) { return '<p>工具未找到</p>'; } $tool = $this->tools[$atts['tool']]; ob_start(); ?> <div class="wp-toolkit-tool" id="tool-<?php echo esc_attr($atts['tool']); ?>"> <div class="tool-header"> <h3><?php echo esc_html($tool['name']); ?></h3> <p class="tool-description"><?php echo esc_html($tool['description']); ?></p> </div> <div class="tool-content"> <?php call_user_func($tool['callback'], $atts); ?> </div> </div> <?php return ob_get_clean(); } }
- class Password_Strength_Tool { public function init() { add_shortcode('password_strength_checker', array($this, 'render_checker')); add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts')); } public function render_checker() { ob_start(); ?> <div class="password-strength-checker"> <h3>密码强度检测</h3> <div class="input-group"> <input type="password" id="password-input" placeholder="输入密码进行强度检测" class="form-control"> <button id="toggle-visibility" class="btn btn-secondary"> 显示/隐藏 </button> </div> <div class="strength-meter"> <div class="strength-bar"></div> <div class="strength-labels"> <span class="strength-label" data-level="0">非常弱</span> <span class="strength-label" data-level="1">弱</span> <span class="strength-label" data-level="2">中等</span> <span class="strength-label" data-level="3">强</span> <span class="strength-label" data-level="4">非常强</span> </div> </div> <div class="password-feedback"> <h4>改进建议:</h4> <ul id="password-suggestions"></ul> </div> <div class="password-statistics"> <h4>密码统计:</h4> <p>长度: <span id="password-length">0</span> 字符</p> <p>熵值: <span id="password-entropy">0</span> bits</p> <p>破解时间: <span id="crack-time">立即</span></p> </div> </div> <?php return ob_get_clean(); } public function enqueue_scripts() { wp_enqueue_script('password-strength-js', plugin_dir_url(__FILE__) . 'js/password-strength.js', array('jquery'), '1.0', true); wp_enqueue_style('password-strength-css', plugin_dir_url(__FILE__) . 'css/password-strength.css'); } }
- class Website_Performance_Tool { public function performance_test($url = '') { if (empty($url)) { $url = home_url(); } $results = array( 'load_time' => 0, 'page_size' => 0, 'requests' => 0, 'performance_score' => 0, 'recommendations' => array() ); // 使用WordPress HTTP API进行测试 $start_time = microtime(true); $response = wp_remote_get($url, array( 'timeout' => 30, 'sslverify' => false )); $end_time = microtime(true); if (!is_wp_error($response)) { $results['load_time'] = round(($end_time - $start_time) * 1000, 2); $results['page_size'] = strlen($response['body']) / 1024; // 分析HTML内容 $results = $this->analyze_html_content($response['body'], $results); // 计算性能分数 $results['performance_score'] = $this->calculate_score($results); // 生成建议 $results['recommendations'] = $this->generate_recommendations($results); } return $results; } private function analyze_html_content($html, $results) { // 解析DOM $dom = new DOMDocument(); @$dom->loadHTML($html); // 统计资源请求 $scripts = $dom->getElementsByTagName('script'); $stylesheets = $dom->getElementsByTagName('link'); $images = $dom->getElementsByTagName('img'); $results['requests'] = $scripts->length + $stylesheets->length + $images->length;
- class SEO_Analyzer_Tool { public function analyze_page($url = '') { if (empty($url)) { $url = get_permalink(); } $analysis = array( 'basic' => array(), 'on_page' => array(), 'technical' => array(), 'score' => 0 ); $response = wp_remote_get($url); if (!is_wp_error($response)) { $html = wp_remote_retrieve_body($response); $headers = wp_remote_retrieve_headers($response); // 基础分析 $analysis['basic'] = $this->basic_analysis($html, $headers); // 页面SEO分析 $analysis['on_page'] = $this->on_page_analysis($html); // 技术SEO分析 $analysis['technical'] = $this->technical_analysis($html, $headers); // 计算总分 $analysis['score'] = $this->calculate_seo_score($analysis); } return $analysis; } private function on_page_analysis($html) { $dom = new DOMDocument(); @$dom->loadHTML($html); $analysis = array( 'title' => array( 'value' => '', 'length' => 0, 'score' => 0 ), 'meta_description' => array( 'value' => '', 'length' => 0, 'score' => 0 ), 'headings' => array(), 'images' => array( 'total' => 0, 'with_alt' => 0 ), 'keywords' => array() ); // 分析标题标签 $title_tags = $dom->getElementsByTagName('title'); if ($title_tags->length > 0) { $title = $title_tags->item(0)->nodeValue; $analysis['title']['value'] = $title; $analysis['title']['length'] = mb_strlen($title); $analysis['title']['score'] = $this->evaluate_title($title); } // 分析meta描述 $meta_tags = $dom->getElementsByTagName('meta'); foreach ($meta_tags as $meta) { if ($meta->getAttribute('name') == 'description') { $description = $meta->getAttribute('content'); $analysis['meta_description']['value'] = $description; $analysis['meta_description']['length'] = mb_strlen($description); $analysis['meta_description']['score'] = $this->evaluate_description($description); } } // 分析标题结构 for ($i = 1; $i <= 6; $i++) { $h_tags = $dom->getElementsByTagName('h' . $i); $analysis['headings']['h' . $i] = array( 'count' => $h_tags->length, 'titles' => array() ); foreach ($h_tags as $h_tag) { $analysis['headings']['h' . $i]['titles'][] = $h_tag->nodeValue; } } return $analysis; } public function render_seo_tool() { ob_start(); ?> <div class="seo-analyzer-tool"> <div class="seo-input-section"> <input type="url" id="seo-analysis-url" placeholder="输入要分析的URL" value="<?php echo esc_url(home_url()); ?>"> <button id="run-seo-analysis" class="btn btn-primary"> 分析SEO </button> </div> <div class="seo-results-container"> <div class="seo-score-card"> <div class="score-circle" id="seo-score-circle"> <span class="score-value">0</span> </div> <h4>SEO总分</h4> </div> <div class="seo-details"> <div class="seo-section" id="basic-seo"> <h4>基础SEO</h4> <div class="seo-metrics"></div> </div> <div class="seo-section" id="on-page-seo"> <h4>页面SEO</h4> <div class="seo-metrics"></div> </div> <div class="seo-section" id="technical-seo"> <h4>技术SEO</h4> <div class="seo-metrics"></div> </div> </div> <div class="seo-recommendations"> <h4>改进建议</h4> <ul id="seo-suggestions"></ul> </div> </div> </div> <?php return ob_get_clean(); } }
- class QR_Code_Generator { private $qr_library_path; public function __construct() { // 引入QR码生成库 require_once plugin_dir_path(__FILE__) . 'libs/phpqrcode/qrlib.php'; } public function generate_qr_code($data, $options = array()) { $defaults = array( 'size' => 10, 'margin' => 4, 'level' => 'L', // L, M, Q, H 'foreground' => array(0, 0, 0), 'background' => array(255, 255, 255), 'logo' => false, 'format' => 'png' ); $options = wp_parse_args($options, $defaults); // 创建临时文件 $temp_dir = wp_upload_dir()['basedir'] . '/qrcodes/'; if (!file_exists($temp_dir)) { wp_mkdir_p($temp_dir); } $filename = 'qr_' . md5(serialize($data) . serialize($options)) . '.png'; $filepath = $temp_dir . $filename; // 生成QR码 QRcode::png($data, $filepath, $options['level'], $options['size'], $options['margin']); // 添加Logo(如果指定) if ($options['logo'] && file_exists($options['logo'])) { $this->add_logo_to_qr($filepath, $options['logo']); } // 颜色调整 if ($options['foreground'] != array(0, 0, 0) || $options['background'] != array(255, 255, 255)) { $this->recolor_qr($filepath, $options['foreground'], $options['background']); } return array( 'url' => wp_upload_dir()['baseurl'] . '/qrcodes/' . $filename, 'path' => $filepath, 'filename' => $filename ); } public function render_generator_ui() { ob_start(); ?> <div class="qr-code-generator"> <div class="generator-form"> <div class="form-group"> <label for="qr-data">内容/URL:</label> <textarea id="qr-data" rows="3" placeholder="输入要编码的内容或URL"></textarea> </div> <div class="form-group"> <label for="qr-size">尺寸:</label> <select id="qr-size"> <option value="5">小 (200x200)</option> <option value="10" selected>中 (400x400)</option> <option value="15">大 (600x600)</option> <option value="20">超大 (800x800)</option> </select> </div> <div class="form-group"> <label for="qr-error-correction">容错级别:</label> <select id="qr-error-correction"> <option value="L">低 (7%)</option> <option value="M" selected>中 (15%)</option> <option value="Q">高 (25%)</option> <option value="Q">极高 (30%)</option> </select> </div> <div class="form-group"> <label>前景色:</label> <input type="color" id="qr-foreground-color" value="#000000"> </div> <div class="form-group"> <label>背景色:</label> <input type="color" id="qr-background-color" value="#ffffff"> </div> <div class="form-group"> <label for="qr-logo">添加Logo:</label> <input type="file" id="qr-logo" accept="image/*"> </div> <button id="generate-qr" class="btn btn-primary"> 生成QR码 </button> </div> <div class="qr-preview-container"> <div class="qr-preview" id="qr-preview"> <p>QR码预览将显示在这里</p> </div> <div class="qr-actions"> <button id="download-qr" class="btn btn-secondary" disabled> 下载PNG </button> <button id="copy-qr-link" class="btn btn-secondary" disabled> 复制链接 </button> <button id="share-qr" class="btn btn-secondary" disabled> 分享 </button> </div> <div class="qr-info"> <h4>QR码信息:</h4> <p>版本: <span id="qr-version">-</span></p> <p>数据容量: <span id="qr-capacity">-</span></p> <p>纠错级别: <span id="qr-ecc-level">-</span></p> </div> </div> </div> <?php return ob_get_clean(); } }
-
- class Toolkit_Admin_Interface { public function __construct() { add_action('admin_menu', array($this, 'add_admin_menu')); add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets')); } public function add_admin_menu() { add_menu_page( '网站工具包', '网站工具包', 'manage_options', 'wp-toolkit', array($this, 'render_admin_page'), 'dashicons-admin-tools', 30 ); // 添加子菜单 add_submenu_page( 'wp-toolkit', '安全扫描', '安全扫描', 'manage_options', 'wp-toolkit-security', array($this, 'render_security_page') ); add_submenu_page( 'wp-toolkit', '工具集', '工具集', 'manage_options', 'wp-toolkit-tools', array($this, 'render_tools_page') ); add_submenu_page( 'wp-toolkit', '设置', '设置', 'manage_options', 'wp-toolkit-settings', array($this, 'render_settings_page') ); } public function render_admin_page() { ?> <div class="wrap wp-toolkit-dashboard"> <h1>网站工具包仪表板</h1> <div class="dashboard-widgets"> <div class="widget security-status"> <h3>安全状态</h3> <div class="widget-content"> <?php $this->display_security_status(); ?> </div> </div> <div class="widget quick-tools"> <h3>快速工具</h3> <div class="widget-content"> <?php $this->display_quick_tools(); ?> </div> </div> <div class="widget recent-scans"> <h3>最近扫描</h3> <div class="widget-content"> <?php $this->display_recent_scans(); ?> </div> </div> <div class="widget system-info"> <h3>系统信息</h3> <div class="widget-content"> <?php $this->display_system_info(); ?> </div> </div> </div> <div class="dashboard-main"> <div class="activity-log"> <h3>活动日志</h3> <div class="log-entries"> <?php $this->display_activity_log(); ?> </div> </div> </div> </div> <?php } public function render_security_page() { $scanner = new WP_Security_Scanner(); $scan_results = $scanner->run_full_scan(); ?> <div class="wrap wp-toolkit-security"> <h1>安全扫描中心</h1> <div class="security-controls"> <button class="button button-primary" id="run-full-scan"> 运行完整扫描 </button> <button class="button button-secondary" id="run-quick-scan"> 快速扫描 </button> <button class="button" id="schedule-scan"> 计划扫描 </button> </div> <div class="scan-results"> <div class="results-summary"> <h3>扫描摘要</h3> <div class="summary-cards"> <?php $this->display_scan_summary($scan_results); ?> </div> </div> <div class="detailed-results"> <h3>详细结果</h3> <div class="results-tabs"> <ul class="tab-nav"> <li class="active" data-tab="vulnerabilities">漏洞</li> <li data-tab="malware">恶意软件</li> <li data-tab="file-changes">文件变更</li> <li data-tab="security-headers">安全头</li> </ul> <div class="tab-content"> <?php $this->display_detailed_results($scan_results); ?> </div> </div> </div> </div> </div> <?php } }
- class Toolkit_Performance_Optimizer { private $cache_enabled = true; private $cache_expiry = 3600; // 1小时 public function __construct() { add_action('init', array($this, 'init_cache_system')); add_action('save_post', array($this, 'clear_post_cache')); add_action('switch_theme', array($this, 'clear_theme_cache')); } public function init_cache_system() { // 创建缓存目录 $cache_dir = WP_CONTENT_DIR . '/cache/wp-toolkit/'; if (!file_exists($cache_dir)) { wp_mkdir_p($cache_dir); } // 添加缓存清理计划任务 if (!wp_next_scheduled('wp_toolkit_clear_expired_cache')) { wp_schedule_event(time(), 'hourly', 'wp_toolkit_clear_expired_cache'); } add_action('wp_toolkit_clear_expired_cache', array($this, 'clear_expired_cache')); } public function get_cached_data($key, $callback, $expiry = null) { if (!$this->cache_enabled) { return call_user_func($callback); } $cache_key = 'wp_toolkit_' . md5($key); $cached = get_transient($cache_key); if ($cached !== false) { return $cached; } $data = call_user_func($callback); if ($expiry === null) { $expiry = $this->cache_expiry; } set_transient($cache_key, $data, $expiry); // 同时保存到文件缓存作为备份 $this->save_to_file_cache($key, $data); return $data; } private function save_to_file_cache($key, $data) { $cache_file = WP_CONTENT_DIR . '/cache/wp-toolkit/' . md5($key) . '.cache'; $cache_data = array( 'timestamp' => time(), 'data' => $data, 'key' => $key ); file_put_contents($cache_file, serialize($cache_data)); } public function optimize_database() { global $wpdb; $optimizations = array(); // 清理修订版本 $revisions = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'revision'" ); if ($revisions > 50) { $wpdb->query( "DELETE FROM $wpdb->posts WHERE post_type = 'revision' AND post_modified < DATE_SUB(NOW(), INTERVAL 30 DAY)" ); $optimizations[] = "清理了旧的文章修订版本"; } // 清理自动草稿 $wpdb->query( "DELETE FROM $wpdb->posts WHERE post_status = 'auto-draft' AND post_date < DATE_SUB(NOW(), INTERVAL 7 DAY)" ); // 优化数据库表 $tables = $wpdb->get_col("SHOW TABLES"); foreach ($tables as $table) { $wpdb->query("OPTIMIZE TABLE $table"); } $optimizations[] = "优化了所有数据库表"; return $optimizations; } }
- class Toolkit_API { private $api_version = 'v1';
在当今数字化时代,WordPress作为全球最受欢迎的内容管理系统,驱动着超过40%的网站。然而,随着其普及度的提升,WordPress网站也成为了黑客攻击的主要目标。据统计,每天有超过9万个WordPress网站遭受各种形式的网络攻击。与此同时,用户对网站功能的需求也日益多样化,不再满足于基本的内容发布,而是期望网站能够集成各种实用工具,提升用户体验。
本教程将深入探讨如何通过WordPress代码二次开发,实现两个关键目标:一是集成专业级网站安全扫描与漏洞检测工具,构建主动防御体系;二是开发常用互联网小工具,增强网站功能性。我们将从理论基础到实践操作,从安全原理到代码实现,全面解析这一综合解决方案。
WordPress面临的安全威胁多种多样,主要包括:
- SQL注入攻击:通过恶意SQL代码操纵数据库
- 跨站脚本攻击(XSS):在网页中注入恶意脚本
- 跨站请求伪造(CSRF):诱使用户执行非本意的操作
- 文件包含漏洞:利用文件包含功能执行恶意代码
- 暴力破解攻击:尝试大量密码组合获取访问权限
- 主题和插件漏洞:第三方代码中的安全缺陷
根据Wordfence安全报告,2023年针对WordPress的攻击尝试比前一年增加了150%,其中插件和主题漏洞占比高达56%。这些数据凸显了加强WordPress安全防护的紧迫性。
传统的WordPress安全方案通常包括:
- 基础安全插件安装
- 定期手动更新
- 简单的防火墙配置
然而,这些方法存在明显不足:
- 被动防御:多数方案只在攻击发生后响应
- 检测能力有限:难以发现复杂或新型攻击
- 误报率高:可能将正常流量误判为攻击
- 性能影响:某些安全插件显著降低网站速度
集成专业安全扫描与漏洞检测工具能够:
- 实现主动安全监测:定期自动扫描,提前发现潜在风险
- 深度漏洞检测:使用专业算法识别复杂安全漏洞
- 实时威胁情报:基于全球攻击数据提供预警
- 最小性能影响:优化代码减少对网站速度的影响
- 定制化报告:根据网站特点生成针对性安全建议
我们将设计一个模块化的安全系统,包含以下核心组件:
// 安全系统主类结构
class WP_Security_Scanner {
private $scanner_modules = array();
private $vulnerability_db;
private $reporting_system;
public function __construct() {
$this->init_modules();
$this->load_vulnerability_database();
$this->setup_reporting();
}
private function init_modules() {
// 初始化各扫描模块
$this->scanner_modules = array(
'file_integrity' => new File_Integrity_Scanner(),
'malware_detection' => new Malware_Scanner(),
'vulnerability_scan' => new Vulnerability_Scanner(),
'brute_force_protection' => new Brute_Force_Protector()
);
}
}
文件完整性监控是检测未经授权文件更改的关键技术:
class File_Integrity_Scanner {
private $baseline_hashes = array();
public function create_baseline() {
$wp_files = $this->get_wordpress_files();
foreach ($wp_files as $file) {
if ($this->is_scannable_file($file)) {
$this->baseline_hashes[$file] = array(
'hash' => md5_file($file),
'size' => filesize($file),
'modified' => filemtime($file)
);
}
}
$this->save_baseline();
}
public function run_integrity_check() {
$current_hashes = array();
$alerts = array();
foreach ($this->baseline_hashes as $file => $baseline_data) {
if (!file_exists($file)) {
$alerts[] = "文件删除警告: {$file}";
continue;
}
$current_hash = md5_file($file);
if ($current_hash !== $baseline_data['hash']) {
$alerts[] = "文件篡改检测: {$file}";
$this->analyze_file_changes($file, $baseline_data['hash'], $current_hash);
}
}
return $alerts;
}
}
漏洞扫描引擎需要结合本地检测和外部漏洞数据库:
class Vulnerability_Scanner {
private $vulnerability_sources = array(
'wpvulndb' => 'https://wpvulndb.com/api/v3/',
'nvd' => 'https://services.nvd.nist.gov/rest/json/cves/1.0'
);
public function scan_plugins_themes() {
$vulnerabilities = array();
// 扫描已安装插件
$plugins = get_plugins();
foreach ($plugins as $plugin_path => $plugin_data) {
$plugin_slug = dirname($plugin_path);
$plugin_version = $plugin_data['Version'];
$plugin_vulns = $this->check_plugin_vulnerabilities($plugin_slug, $plugin_version);
if (!empty($plugin_vulns)) {
$vulnerabilities['plugins'][$plugin_slug] = $plugin_vulns;
}
}
// 扫描当前主题
$theme = wp_get_theme();
$theme_vulns = $this->check_theme_vulnerabilities($theme->get('TextDomain'), $theme->get('Version'));
if (!empty($theme_vulns)) {
$vulnerabilities['theme'] = $theme_vulns;
}
return $vulnerabilities;
}
private function check_plugin_vulnerabilities($slug, $version) {
// 查询漏洞数据库
$api_url = $this->vulnerability_sources['wpvulndb'] . "plugins/{$slug}";
$response = wp_remote_get($api_url);
if (is_wp_error($response)) {
return false;
}
$data = json_decode(wp_remote_retrieve_body($response), true);
$relevant_vulns = array();
if (isset($data[$slug]['vulnerabilities'])) {
foreach ($data[$slug]['vulnerabilities'] as $vuln) {
if ($this->is_version_affected($version, $vuln['fixed_in'])) {
$relevant_vulns[] = array(
'id' => $vuln['id'],
'title' => $vuln['title'],
'cvss_score' => $vuln['cvss']['score'],
'fixed_in' => $vuln['fixed_in']
);
}
}
}
return $relevant_vulns;
}
}
恶意代码检测需要结合特征码检测和行为分析:
class Malware_Scanner {
private $malware_signatures = array(
'base64_decode' => '/base64_decodes*([^)]*)/',
'eval' => '/evals*([^)]*)/',
'shell_exec' => '/shell_execs*([^)]*)/',
'suspicious_url' => '/(https?://[^s<>"']*.(php|exe|bat|sh))/i'
);
private $suspicious_patterns = array(
'obfuscated_code' => '/$(?:w+)s*=s*$(?:w+)s*.s*$(?:w+)/',
'long_string' => '/"[^"]{200,}"/'
);
public function scan_directory($directory) {
$malware_findings = array();
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory)
);
foreach ($files as $file) {
if ($file->isDir()) continue;
if ($this->is_php_file($file)) {
$content = file_get_contents($file->getPathname());
$file_findings = $this->analyze_file_content($content, $file->getPathname());
if (!empty($file_findings)) {
$malware_findings[$file->getPathname()] = $file_findings;
}
}
}
return $malware_findings;
}
private function analyze_file_content($content, $filename) {
$findings = array();
// 检查已知恶意代码特征
foreach ($this->malware_signatures as $type => $pattern) {
if (preg_match_all($pattern, $content, $matches)) {
$findings[$type] = $matches[0];
}
}
// 检查可疑代码模式
foreach ($this->suspicious_patterns as $pattern_name => $pattern) {
if (preg_match_all($pattern, $content, $matches)) {
$findings[$pattern_name] = count($matches[0]);
}
}
// 检查文件权限
$perms = substr(sprintf('%o', fileperms($filename)), -4);
if ($perms == '0777') {
$findings['insecure_permissions'] = $perms;
}
return $findings;
}
}
class Security_Reporter {
private $report_types = array('daily', 'weekly', 'immediate');
private $notification_methods = array('email', 'dashboard', 'webhook');
public function generate_report($scan_results, $report_type = 'daily') {
$report = array(
'timestamp' => current_time('timestamp'),
'scan_summary' => array(
'total_checks' => 0,
'issues_found' => 0,
'critical_issues' => 0
),
'detailed_findings' => array(),
'recommendations' => array()
);
// 汇总扫描结果
foreach ($scan_results as $module => $results) {
$report['scan_summary']['total_checks']++;
if (!empty($results)) {
$report['scan_summary']['issues_found']++;
$report['detailed_findings'][$module] = $results;
// 生成建议
$report['recommendations'] = array_merge(
$report['recommendations'],
$this->generate_recommendations($module, $results)
);
}
}
// 确定报告严重级别
$report['severity'] = $this->calculate_severity($report);
return $report;
}
public function send_alerts($report) {
if ($report['severity'] >= 7) { // 高严重级别
$this->send_immediate_alert($report);
}
// 发送定期报告
if ($this->is_time_for_report('daily')) {
$this->send_email_report($report, 'daily');
}
// 更新仪表板小工具
$this->update_dashboard_widget($report);
}
}
class Security_Reporter {
private $report_types = array('daily', 'weekly', 'immediate');
private $notification_methods = array('email', 'dashboard', 'webhook');
public function generate_report($scan_results, $report_type = 'daily') {
$report = array(
'timestamp' => current_time('timestamp'),
'scan_summary' => array(
'total_checks' => 0,
'issues_found' => 0,
'critical_issues' => 0
),
'detailed_findings' => array(),
'recommendations' => array()
);
// 汇总扫描结果
foreach ($scan_results as $module => $results) {
$report['scan_summary']['total_checks']++;
if (!empty($results)) {
$report['scan_summary']['issues_found']++;
$report['detailed_findings'][$module] = $results;
// 生成建议
$report['recommendations'] = array_merge(
$report['recommendations'],
$this->generate_recommendations($module, $results)
);
}
}
// 确定报告严重级别
$report['severity'] = $this->calculate_severity($report);
return $report;
}
public function send_alerts($report) {
if ($report['severity'] >= 7) { // 高严重级别
$this->send_immediate_alert($report);
}
// 发送定期报告
if ($this->is_time_for_report('daily')) {
$this->send_email_report($report, 'daily');
}
// 更新仪表板小工具
$this->update_dashboard_widget($report);
}
}
我们将创建一个可扩展的小工具框架:
class WP_Toolkit_Framework {
private $tools = array();
private $tool_categories = array(
'utility' => '实用工具',
'seo' => 'SEO工具',
'security' => '安全工具',
'development' => '开发工具'
);
public function register_tool($tool_slug, $tool_config) {
$defaults = array(
'name' => '',
'description' => '',
'category' => 'utility',
'callback' => null,
'settings' => array(),
'shortcode' => ''
);
$config = wp_parse_args($tool_config, $defaults);
$this->tools[$tool_slug] = $config;
// 注册短代码
if (!empty($config['shortcode'])) {
add_shortcode($config['shortcode'], array($this, 'render_tool'));
}
}
public function render_tool($atts, $content = null, $tag = '') {
$atts = shortcode_atts(array('tool' => ''), $atts, $tag);
if (empty($atts['tool']) || !isset($this->tools[$atts['tool']])) {
return '<p>工具未找到</p>';
}
$tool = $this->tools[$atts['tool']];
ob_start();
?>
<div class="wp-toolkit-tool" id="tool-<?php echo esc_attr($atts['tool']); ?>">
<div class="tool-header">
<h3><?php echo esc_html($tool['name']); ?></h3>
<p class="tool-description"><?php echo esc_html($tool['description']); ?></p>
</div>
<div class="tool-content">
<?php call_user_func($tool['callback'], $atts); ?>
</div>
</div>
<?php
return ob_get_clean();
}
}
class Password_Strength_Tool {
public function init() {
add_shortcode('password_strength_checker', array($this, 'render_checker'));
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
}
public function render_checker() {
ob_start();
?>
<div class="password-strength-checker">
<h3>密码强度检测</h3>
<div class="input-group">
<input type="password" id="password-input"
placeholder="输入密码进行强度检测"
class="form-control">
<button id="toggle-visibility" class="btn btn-secondary">
显示/隐藏
</button>
</div>
<div class="strength-meter">
<div class="strength-bar"></div>
<div class="strength-labels">
<span class="strength-label" data-level="0">非常弱</span>
<span class="strength-label" data-level="1">弱</span>
<span class="strength-label" data-level="2">中等</span>
<span class="strength-label" data-level="3">强</span>
<span class="strength-label" data-level="4">非常强</span>
</div>
</div>
<div class="password-feedback">
<h4>改进建议:</h4>
<ul id="password-suggestions"></ul>
</div>
<div class="password-statistics">
<h4>密码统计:</h4>
<p>长度: <span id="password-length">0</span> 字符</p>
<p>熵值: <span id="password-entropy">0</span> bits</p>
<p>破解时间: <span id="crack-time">立即</span></p>
</div>
</div>
<?php
return ob_get_clean();
}
public function enqueue_scripts() {
wp_enqueue_script('password-strength-js',
plugin_dir_url(__FILE__) . 'js/password-strength.js',
array('jquery'), '1.0', true);
wp_enqueue_style('password-strength-css',
plugin_dir_url(__FILE__) . 'css/password-strength.css');
}
}
class Password_Strength_Tool {
public function init() {
add_shortcode('password_strength_checker', array($this, 'render_checker'));
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
}
public function render_checker() {
ob_start();
?>
<div class="password-strength-checker">
<h3>密码强度检测</h3>
<div class="input-group">
<input type="password" id="password-input"
placeholder="输入密码进行强度检测"
class="form-control">
<button id="toggle-visibility" class="btn btn-secondary">
显示/隐藏
</button>
</div>
<div class="strength-meter">
<div class="strength-bar"></div>
<div class="strength-labels">
<span class="strength-label" data-level="0">非常弱</span>
<span class="strength-label" data-level="1">弱</span>
<span class="strength-label" data-level="2">中等</span>
<span class="strength-label" data-level="3">强</span>
<span class="strength-label" data-level="4">非常强</span>
</div>
</div>
<div class="password-feedback">
<h4>改进建议:</h4>
<ul id="password-suggestions"></ul>
</div>
<div class="password-statistics">
<h4>密码统计:</h4>
<p>长度: <span id="password-length">0</span> 字符</p>
<p>熵值: <span id="password-entropy">0</span> bits</p>
<p>破解时间: <span id="crack-time">立即</span></p>
</div>
</div>
<?php
return ob_get_clean();
}
public function enqueue_scripts() {
wp_enqueue_script('password-strength-js',
plugin_dir_url(__FILE__) . 'js/password-strength.js',
array('jquery'), '1.0', true);
wp_enqueue_style('password-strength-css',
plugin_dir_url(__FILE__) . 'css/password-strength.css');
}
}
class Website_Performance_Tool {
public function performance_test($url = '') {
if (empty($url)) {
$url = home_url();
}
$results = array(
'load_time' => 0,
'page_size' => 0,
'requests' => 0,
'performance_score' => 0,
'recommendations' => array()
);
// 使用WordPress HTTP API进行测试
$start_time = microtime(true);
$response = wp_remote_get($url, array(
'timeout' => 30,
'sslverify' => false
));
$end_time = microtime(true);
if (!is_wp_error($response)) {
$results['load_time'] = round(($end_time - $start_time) * 1000, 2);
$results['page_size'] = strlen($response['body']) / 1024;
// 分析HTML内容
$results = $this->analyze_html_content($response['body'], $results);
// 计算性能分数
$results['performance_score'] = $this->calculate_score($results);
// 生成建议
$results['recommendations'] = $this->generate_recommendations($results);
}
return $results;
}
private function analyze_html_content($html, $results) {
// 解析DOM
$dom = new DOMDocument();
@$dom->loadHTML($html);
// 统计资源请求
$scripts = $dom->getElementsByTagName('script');
$stylesheets = $dom->getElementsByTagName('link');
$images = $dom->getElementsByTagName('img');
$results['requests'] = $scripts->length + $stylesheets->length + $images->length;
class Website_Performance_Tool {
public function performance_test($url = '') {
if (empty($url)) {
$url = home_url();
}
$results = array(
'load_time' => 0,
'page_size' => 0,
'requests' => 0,
'performance_score' => 0,
'recommendations' => array()
);
// 使用WordPress HTTP API进行测试
$start_time = microtime(true);
$response = wp_remote_get($url, array(
'timeout' => 30,
'sslverify' => false
));
$end_time = microtime(true);
if (!is_wp_error($response)) {
$results['load_time'] = round(($end_time - $start_time) * 1000, 2);
$results['page_size'] = strlen($response['body']) / 1024;
// 分析HTML内容
$results = $this->analyze_html_content($response['body'], $results);
// 计算性能分数
$results['performance_score'] = $this->calculate_score($results);
// 生成建议
$results['recommendations'] = $this->generate_recommendations($results);
}
return $results;
}
private function analyze_html_content($html, $results) {
// 解析DOM
$dom = new DOMDocument();
@$dom->loadHTML($html);
// 统计资源请求
$scripts = $dom->getElementsByTagName('script');
$stylesheets = $dom->getElementsByTagName('link');
$images = $dom->getElementsByTagName('img');
$results['requests'] = $scripts->length + $stylesheets->length + $images->length;
class SEO_Analyzer_Tool {
public function analyze_page($url = '') {
if (empty($url)) {
$url = get_permalink();
}
$analysis = array(
'basic' => array(),
'on_page' => array(),
'technical' => array(),
'score' => 0
);
$response = wp_remote_get($url);
if (!is_wp_error($response)) {
$html = wp_remote_retrieve_body($response);
$headers = wp_remote_retrieve_headers($response);
// 基础分析
$analysis['basic'] = $this->basic_analysis($html, $headers);
// 页面SEO分析
$analysis['on_page'] = $this->on_page_analysis($html);
// 技术SEO分析
$analysis['technical'] = $this->technical_analysis($html, $headers);
// 计算总分
$analysis['score'] = $this->calculate_seo_score($analysis);
}
return $analysis;
}
private function on_page_analysis($html) {
$dom = new DOMDocument();
@$dom->loadHTML($html);
$analysis = array(
'title' => array(
'value' => '',
'length' => 0,
'score' => 0
),
'meta_description' => array(
'value' => '',
'length' => 0,
'score' => 0
),
'headings' => array(),
'images' => array(
'total' => 0,
'with_alt' => 0
),
'keywords' => array()
);
// 分析标题标签
$title_tags = $dom->getElementsByTagName('title');
if ($title_tags->length > 0) {
$title = $title_tags->item(0)->nodeValue;
$analysis['title']['value'] = $title;
$analysis['title']['length'] = mb_strlen($title);
$analysis['title']['score'] = $this->evaluate_title($title);
}
// 分析meta描述
$meta_tags = $dom->getElementsByTagName('meta');
foreach ($meta_tags as $meta) {
if ($meta->getAttribute('name') == 'description') {
$description = $meta->getAttribute('content');
$analysis['meta_description']['value'] = $description;
$analysis['meta_description']['length'] = mb_strlen($description);
$analysis['meta_description']['score'] = $this->evaluate_description($description);
}
}
// 分析标题结构
for ($i = 1; $i <= 6; $i++) {
$h_tags = $dom->getElementsByTagName('h' . $i);
$analysis['headings']['h' . $i] = array(
'count' => $h_tags->length,
'titles' => array()
);
foreach ($h_tags as $h_tag) {
$analysis['headings']['h' . $i]['titles'][] = $h_tag->nodeValue;
}
}
return $analysis;
}
public function render_seo_tool() {
ob_start();
?>
<div class="seo-analyzer-tool">
<div class="seo-input-section">
<input type="url" id="seo-analysis-url"
placeholder="输入要分析的URL"
value="<?php echo esc_url(home_url()); ?>">
<button id="run-seo-analysis" class="btn btn-primary">
分析SEO
</button>
</div>
<div class="seo-results-container">
<div class="seo-score-card">
<div class="score-circle" id="seo-score-circle">
<span class="score-value">0</span>
</div>
<h4>SEO总分</h4>
</div>
<div class="seo-details">
<div class="seo-section" id="basic-seo">
<h4>基础SEO</h4>
<div class="seo-metrics"></div>
</div>
<div class="seo-section" id="on-page-seo">
<h4>页面SEO</h4>
<div class="seo-metrics"></div>
</div>
<div class="seo-section" id="technical-seo">
<h4>技术SEO</h4>
<div class="seo-metrics"></div>
</div>
</div>
<div class="seo-recommendations">
<h4>改进建议</h4>
<ul id="seo-suggestions"></ul>
</div>
</div>
</div>
<?php
return ob_get_clean();
}
}
class SEO_Analyzer_Tool {
public function analyze_page($url = '') {
if (empty($url)) {
$url = get_permalink();
}
$analysis = array(
'basic' => array(),
'on_page' => array(),
'technical' => array(),
'score' => 0
);
$response = wp_remote_get($url);
if (!is_wp_error($response)) {
$html = wp_remote_retrieve_body($response);
$headers = wp_remote_retrieve_headers($response);
// 基础分析
$analysis['basic'] = $this->basic_analysis($html, $headers);
// 页面SEO分析
$analysis['on_page'] = $this->on_page_analysis($html);
// 技术SEO分析
$analysis['technical'] = $this->technical_analysis($html, $headers);
// 计算总分
$analysis['score'] = $this->calculate_seo_score($analysis);
}
return $analysis;
}
private function on_page_analysis($html) {
$dom = new DOMDocument();
@$dom->loadHTML($html);
$analysis = array(
'title' => array(
'value' => '',
'length' => 0,
'score' => 0
),
'meta_description' => array(
'value' => '',
'length' => 0,
'score' => 0
),
'headings' => array(),
'images' => array(
'total' => 0,
'with_alt' => 0
),
'keywords' => array()
);
// 分析标题标签
$title_tags = $dom->getElementsByTagName('title');
if ($title_tags->length > 0) {
$title = $title_tags->item(0)->nodeValue;
$analysis['title']['value'] = $title;
$analysis['title']['length'] = mb_strlen($title);
$analysis['title']['score'] = $this->evaluate_title($title);
}
// 分析meta描述
$meta_tags = $dom->getElementsByTagName('meta');
foreach ($meta_tags as $meta) {
if ($meta->getAttribute('name') == 'description') {
$description = $meta->getAttribute('content');
$analysis['meta_description']['value'] = $description;
$analysis['meta_description']['length'] = mb_strlen($description);
$analysis['meta_description']['score'] = $this->evaluate_description($description);
}
}
// 分析标题结构
for ($i = 1; $i <= 6; $i++) {
$h_tags = $dom->getElementsByTagName('h' . $i);
$analysis['headings']['h' . $i] = array(
'count' => $h_tags->length,
'titles' => array()
);
foreach ($h_tags as $h_tag) {
$analysis['headings']['h' . $i]['titles'][] = $h_tag->nodeValue;
}
}
return $analysis;
}
public function render_seo_tool() {
ob_start();
?>
<div class="seo-analyzer-tool">
<div class="seo-input-section">
<input type="url" id="seo-analysis-url"
placeholder="输入要分析的URL"
value="<?php echo esc_url(home_url()); ?>">
<button id="run-seo-analysis" class="btn btn-primary">
分析SEO
</button>
</div>
<div class="seo-results-container">
<div class="seo-score-card">
<div class="score-circle" id="seo-score-circle">
<span class="score-value">0</span>
</div>
<h4>SEO总分</h4>
</div>
<div class="seo-details">
<div class="seo-section" id="basic-seo">
<h4>基础SEO</h4>
<div class="seo-metrics"></div>
</div>
<div class="seo-section" id="on-page-seo">
<h4>页面SEO</h4>
<div class="seo-metrics"></div>
</div>
<div class="seo-section" id="technical-seo">
<h4>技术SEO</h4>
<div class="seo-metrics"></div>
</div>
</div>
<div class="seo-recommendations">
<h4>改进建议</h4>
<ul id="seo-suggestions"></ul>
</div>
</div>
</div>
<?php
return ob_get_clean();
}
}
class QR_Code_Generator {
private $qr_library_path;
public function __construct() {
// 引入QR码生成库
require_once plugin_dir_path(__FILE__) . 'libs/phpqrcode/qrlib.php';
}
public function generate_qr_code($data, $options = array()) {
$defaults = array(
'size' => 10,
'margin' => 4,
'level' => 'L', // L, M, Q, H
'foreground' => array(0, 0, 0),
'background' => array(255, 255, 255),
'logo' => false,
'format' => 'png'
);
$options = wp_parse_args($options, $defaults);
// 创建临时文件
$temp_dir = wp_upload_dir()['basedir'] . '/qrcodes/';
if (!file_exists($temp_dir)) {
wp_mkdir_p($temp_dir);
}
$filename = 'qr_' . md5(serialize($data) . serialize($options)) . '.png';
$filepath = $temp_dir . $filename;
// 生成QR码
QRcode::png($data, $filepath, $options['level'], $options['size'], $options['margin']);
// 添加Logo(如果指定)
if ($options['logo'] && file_exists($options['logo'])) {
$this->add_logo_to_qr($filepath, $options['logo']);
}
// 颜色调整
if ($options['foreground'] != array(0, 0, 0) || $options['background'] != array(255, 255, 255)) {
$this->recolor_qr($filepath, $options['foreground'], $options['background']);
}
return array(
'url' => wp_upload_dir()['baseurl'] . '/qrcodes/' . $filename,
'path' => $filepath,
'filename' => $filename
);
}
public function render_generator_ui() {
ob_start();
?>
<div class="qr-code-generator">
<div class="generator-form">
<div class="form-group">
<label for="qr-data">内容/URL:</label>
<textarea id="qr-data" rows="3"
placeholder="输入要编码的内容或URL"></textarea>
</div>
<div class="form-group">
<label for="qr-size">尺寸:</label>
<select id="qr-size">
<option value="5">小 (200x200)</option>
<option value="10" selected>中 (400x400)</option>
<option value="15">大 (600x600)</option>
<option value="20">超大 (800x800)</option>
</select>
</div>
<div class="form-group">
<label for="qr-error-correction">容错级别:</label>
<select id="qr-error-correction">
<option value="L">低 (7%)</option>
<option value="M" selected>中 (15%)</option>
<option value="Q">高 (25%)</option>
<option value="Q">极高 (30%)</option>
</select>
</div>
<div class="form-group">
<label>前景色:</label>
<input type="color" id="qr-foreground-color" value="#000000">
</div>
<div class="form-group">
<label>背景色:</label>
<input type="color" id="qr-background-color" value="#ffffff">
</div>
<div class="form-group">
<label for="qr-logo">添加Logo:</label>
<input type="file" id="qr-logo" accept="image/*">
</div>
<button id="generate-qr" class="btn btn-primary">
生成QR码
</button>
</div>
<div class="qr-preview-container">
<div class="qr-preview" id="qr-preview">
<p>QR码预览将显示在这里</p>
</div>
<div class="qr-actions">
<button id="download-qr" class="btn btn-secondary" disabled>
下载PNG
</button>
<button id="copy-qr-link" class="btn btn-secondary" disabled>
复制链接
</button>
<button id="share-qr" class="btn btn-secondary" disabled>
分享
</button>
</div>
<div class="qr-info">
<h4>QR码信息:</h4>
<p>版本: <span id="qr-version">-</span></p>
<p>数据容量: <span id="qr-capacity">-</span></p>
<p>纠错级别: <span id="qr-ecc-level">-</span></p>
</div>
</div>
</div>
<?php
return ob_get_clean();
}
}
class QR_Code_Generator {
private $qr_library_path;
public function __construct() {
// 引入QR码生成库
require_once plugin_dir_path(__FILE__) . 'libs/phpqrcode/qrlib.php';
}
public function generate_qr_code($data, $options = array()) {
$defaults = array(
'size' => 10,
'margin' => 4,
'level' => 'L', // L, M, Q, H
'foreground' => array(0, 0, 0),
'background' => array(255, 255, 255),
'logo' => false,
'format' => 'png'
);
$options = wp_parse_args($options, $defaults);
// 创建临时文件
$temp_dir = wp_upload_dir()['basedir'] . '/qrcodes/';
if (!file_exists($temp_dir)) {
wp_mkdir_p($temp_dir);
}
$filename = 'qr_' . md5(serialize($data) . serialize($options)) . '.png';
$filepath = $temp_dir . $filename;
// 生成QR码
QRcode::png($data, $filepath, $options['level'], $options['size'], $options['margin']);
// 添加Logo(如果指定)
if ($options['logo'] && file_exists($options['logo'])) {
$this->add_logo_to_qr($filepath, $options['logo']);
}
// 颜色调整
if ($options['foreground'] != array(0, 0, 0) || $options['background'] != array(255, 255, 255)) {
$this->recolor_qr($filepath, $options['foreground'], $options['background']);
}
return array(
'url' => wp_upload_dir()['baseurl'] . '/qrcodes/' . $filename,
'path' => $filepath,
'filename' => $filename
);
}
public function render_generator_ui() {
ob_start();
?>
<div class="qr-code-generator">
<div class="generator-form">
<div class="form-group">
<label for="qr-data">内容/URL:</label>
<textarea id="qr-data" rows="3"
placeholder="输入要编码的内容或URL"></textarea>
</div>
<div class="form-group">
<label for="qr-size">尺寸:</label>
<select id="qr-size">
<option value="5">小 (200x200)</option>
<option value="10" selected>中 (400x400)</option>
<option value="15">大 (600x600)</option>
<option value="20">超大 (800x800)</option>
</select>
</div>
<div class="form-group">
<label for="qr-error-correction">容错级别:</label>
<select id="qr-error-correction">
<option value="L">低 (7%)</option>
<option value="M" selected>中 (15%)</option>
<option value="Q">高 (25%)</option>
<option value="Q">极高 (30%)</option>
</select>
</div>
<div class="form-group">
<label>前景色:</label>
<input type="color" id="qr-foreground-color" value="#000000">
</div>
<div class="form-group">
<label>背景色:</label>
<input type="color" id="qr-background-color" value="#ffffff">
</div>
<div class="form-group">
<label for="qr-logo">添加Logo:</label>
<input type="file" id="qr-logo" accept="image/*">
</div>
<button id="generate-qr" class="btn btn-primary">
生成QR码
</button>
</div>
<div class="qr-preview-container">
<div class="qr-preview" id="qr-preview">
<p>QR码预览将显示在这里</p>
</div>
<div class="qr-actions">
<button id="download-qr" class="btn btn-secondary" disabled>
下载PNG
</button>
<button id="copy-qr-link" class="btn btn-secondary" disabled>
复制链接
</button>
<button id="share-qr" class="btn btn-secondary" disabled>
分享
</button>
</div>
<div class="qr-info">
<h4>QR码信息:</h4>
<p>版本: <span id="qr-version">-</span></p>
<p>数据容量: <span id="qr-capacity">-</span></p>
<p>纠错级别: <span id="qr-ecc-level">-</span></p>
</div>
</div>
</div>
<?php
return ob_get_clean();
}
}
class Toolkit_Admin_Interface {
public function __construct() {
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
}
public function add_admin_menu() {
add_menu_page(
'网站工具包',
'网站工具包',
'manage_options',
'wp-toolkit',
array($this, 'render_admin_page'),
'dashicons-admin-tools',
30
);
// 添加子菜单
add_submenu_page(
'wp-toolkit',
'安全扫描',
'安全扫描',
'manage_options',
'wp-toolkit-security',
array($this, 'render_security_page')
);
add_submenu_page(
'wp-toolkit',
'工具集',
'工具集',
'manage_options',
'wp-toolkit-tools',
array($this, 'render_tools_page')
);
add_submenu_page(
'wp-toolkit',
'设置',
'设置',
'manage_options',
'wp-toolkit-settings',
array($this, 'render_settings_page')
);
}
public function render_admin_page() {
?>
<div class="wrap wp-toolkit-dashboard">
<h1>网站工具包仪表板</h1>
<div class="dashboard-widgets">
<div class="widget security-status">
<h3>安全状态</h3>
<div class="widget-content">
<?php $this->display_security_status(); ?>
</div>
</div>
<div class="widget quick-tools">
<h3>快速工具</h3>
<div class="widget-content">
<?php $this->display_quick_tools(); ?>
</div>
</div>
<div class="widget recent-scans">
<h3>最近扫描</h3>
<div class="widget-content">
<?php $this->display_recent_scans(); ?>
</div>
</div>
<div class="widget system-info">
<h3>系统信息</h3>
<div class="widget-content">
<?php $this->display_system_info(); ?>
</div>
</div>
</div>
<div class="dashboard-main">
<div class="activity-log">
<h3>活动日志</h3>
<div class="log-entries">
<?php $this->display_activity_log(); ?>
</div>
</div>
</div>
</div>
<?php
}
public function render_security_page() {
$scanner = new WP_Security_Scanner();
$scan_results = $scanner->run_full_scan();
?>
<div class="wrap wp-toolkit-security">
<h1>安全扫描中心</h1>
<div class="security-controls">
<button class="button button-primary" id="run-full-scan">
运行完整扫描
</button>
<button class="button button-secondary" id="run-quick-scan">
快速扫描
</button>
<button class="button" id="schedule-scan">
计划扫描
</button>
</div>
<div class="scan-results">
<div class="results-summary">
<h3>扫描摘要</h3>
<div class="summary-cards">
<?php $this->display_scan_summary($scan_results); ?>
</div>
</div>
<div class="detailed-results">
<h3>详细结果</h3>
<div class="results-tabs">
<ul class="tab-nav">
<li class="active" data-tab="vulnerabilities">漏洞</li>
<li data-tab="malware">恶意软件</li>
<li data-tab="file-changes">文件变更</li>
<li data-tab="security-headers">安全头</li>
</ul>
<div class="tab-content">
<?php $this->display_detailed_results($scan_results); ?>
</div>
</div>
</div>
</div>
</div>
<?php
}
}
class Toolkit_Admin_Interface {
public function __construct() {
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
}
public function add_admin_menu() {
add_menu_page(
'网站工具包',
'网站工具包',
'manage_options',
'wp-toolkit',
array($this, 'render_admin_page'),
'dashicons-admin-tools',
30
);
// 添加子菜单
add_submenu_page(
'wp-toolkit',
'安全扫描',
'安全扫描',
'manage_options',
'wp-toolkit-security',
array($this, 'render_security_page')
);
add_submenu_page(
'wp-toolkit',
'工具集',
'工具集',
'manage_options',
'wp-toolkit-tools',
array($this, 'render_tools_page')
);
add_submenu_page(
'wp-toolkit',
'设置',
'设置',
'manage_options',
'wp-toolkit-settings',
array($this, 'render_settings_page')
);
}
public function render_admin_page() {
?>
<div class="wrap wp-toolkit-dashboard">
<h1>网站工具包仪表板</h1>
<div class="dashboard-widgets">
<div class="widget security-status">
<h3>安全状态</h3>
<div class="widget-content">
<?php $this->display_security_status(); ?>
</div>
</div>
<div class="widget quick-tools">
<h3>快速工具</h3>
<div class="widget-content">
<?php $this->display_quick_tools(); ?>
</div>
</div>
<div class="widget recent-scans">
<h3>最近扫描</h3>
<div class="widget-content">
<?php $this->display_recent_scans(); ?>
</div>
</div>
<div class="widget system-info">
<h3>系统信息</h3>
<div class="widget-content">
<?php $this->display_system_info(); ?>
</div>
</div>
</div>
<div class="dashboard-main">
<div class="activity-log">
<h3>活动日志</h3>
<div class="log-entries">
<?php $this->display_activity_log(); ?>
</div>
</div>
</div>
</div>
<?php
}
public function render_security_page() {
$scanner = new WP_Security_Scanner();
$scan_results = $scanner->run_full_scan();
?>
<div class="wrap wp-toolkit-security">
<h1>安全扫描中心</h1>
<div class="security-controls">
<button class="button button-primary" id="run-full-scan">
运行完整扫描
</button>
<button class="button button-secondary" id="run-quick-scan">
快速扫描
</button>
<button class="button" id="schedule-scan">
计划扫描
</button>
</div>
<div class="scan-results">
<div class="results-summary">
<h3>扫描摘要</h3>
<div class="summary-cards">
<?php $this->display_scan_summary($scan_results); ?>
</div>
</div>
<div class="detailed-results">
<h3>详细结果</h3>
<div class="results-tabs">
<ul class="tab-nav">
<li class="active" data-tab="vulnerabilities">漏洞</li>
<li data-tab="malware">恶意软件</li>
<li data-tab="file-changes">文件变更</li>
<li data-tab="security-headers">安全头</li>
</ul>
<div class="tab-content">
<?php $this->display_detailed_results($scan_results); ?>
</div>
</div>
</div>
</div>
</div>
<?php
}
}
class Toolkit_Performance_Optimizer {
private $cache_enabled = true;
private $cache_expiry = 3600; // 1小时
public function __construct() {
add_action('init', array($this, 'init_cache_system'));
add_action('save_post', array($this, 'clear_post_cache'));
add_action('switch_theme', array($this, 'clear_theme_cache'));
}
public function init_cache_system() {
// 创建缓存目录
$cache_dir = WP_CONTENT_DIR . '/cache/wp-toolkit/';
if (!file_exists($cache_dir)) {
wp_mkdir_p($cache_dir);
}
// 添加缓存清理计划任务
if (!wp_next_scheduled('wp_toolkit_clear_expired_cache')) {
wp_schedule_event(time(), 'hourly', 'wp_toolkit_clear_expired_cache');
}
add_action('wp_toolkit_clear_expired_cache', array($this, 'clear_expired_cache'));
}
public function get_cached_data($key, $callback, $expiry = null) {
if (!$this->cache_enabled) {
return call_user_func($callback);
}
$cache_key = 'wp_toolkit_' . md5($key);
$cached = get_transient($cache_key);
if ($cached !== false) {
return $cached;
}
$data = call_user_func($callback);
if ($expiry === null) {
$expiry = $this->cache_expiry;
}
set_transient($cache_key, $data, $expiry);
// 同时保存到文件缓存作为备份
$this->save_to_file_cache($key, $data);
return $data;
}
private function save_to_file_cache($key, $data) {
$cache_file = WP_CONTENT_DIR . '/cache/wp-toolkit/' . md5($key) . '.cache';
$cache_data = array(
'timestamp' => time(),
'data' => $data,
'key' => $key
);
file_put_contents($cache_file, serialize($cache_data));
}
public function optimize_database() {
global $wpdb;
$optimizations = array();
// 清理修订版本
$revisions = $wpdb->get_var(
"SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'revision'"
);
if ($revisions > 50) {
$wpdb->query(
"DELETE FROM $wpdb->posts
WHERE post_type = 'revision'
AND post_modified < DATE_SUB(NOW(), INTERVAL 30 DAY)"
);
$optimizations[] = "清理了旧的文章修订版本";
}
// 清理自动草稿
$wpdb->query(
"DELETE FROM $wpdb->posts
WHERE post_status = 'auto-draft'
AND post_date < DATE_SUB(NOW(), INTERVAL 7 DAY)"
);
// 优化数据库表
$tables = $wpdb->get_col("SHOW TABLES");
foreach ($tables as $table) {
$wpdb->query("OPTIMIZE TABLE $table");
}
$optimizations[] = "优化了所有数据库表";
return $optimizations;
}
}
class Toolkit_Performance_Optimizer {
private $cache_enabled = true;
private $cache_expiry = 3600; // 1小时
public function __construct() {
add_action('init', array($this, 'init_cache_system'));
add_action('save_post', array($this, 'clear_post_cache'));
add_action('switch_theme', array($this, 'clear_theme_cache'));
}
public function init_cache_system() {
// 创建缓存目录
$cache_dir = WP_CONTENT_DIR . '/cache/wp-toolkit/';
if (!file_exists($cache_dir)) {
wp_mkdir_p($cache_dir);
}
// 添加缓存清理计划任务
if (!wp_next_scheduled('wp_toolkit_clear_expired_cache')) {
wp_schedule_event(time(), 'hourly', 'wp_toolkit_clear_expired_cache');
}
add_action('wp_toolkit_clear_expired_cache', array($this, 'clear_expired_cache'));
}
public function get_cached_data($key, $callback, $expiry = null) {
if (!$this->cache_enabled) {
return call_user_func($callback);
}
$cache_key = 'wp_toolkit_' . md5($key);
$cached = get_transient($cache_key);
if ($cached !== false) {
return $cached;
}
$data = call_user_func($callback);
if ($expiry === null) {
$expiry = $this->cache_expiry;
}
set_transient($cache_key, $data, $expiry);
// 同时保存到文件缓存作为备份
$this->save_to_file_cache($key, $data);
return $data;
}
private function save_to_file_cache($key, $data) {
$cache_file = WP_CONTENT_DIR . '/cache/wp-toolkit/' . md5($key) . '.cache';
$cache_data = array(
'timestamp' => time(),
'data' => $data,
'key' => $key
);
file_put_contents($cache_file, serialize($cache_data));
}
public function optimize_database() {
global $wpdb;
$optimizations = array();
// 清理修订版本
$revisions = $wpdb->get_var(
"SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'revision'"
);
if ($revisions > 50) {
$wpdb->query(
"DELETE FROM $wpdb->posts
WHERE post_type = 'revision'
AND post_modified < DATE_SUB(NOW(), INTERVAL 30 DAY)"
);
$optimizations[] = "清理了旧的文章修订版本";
}
// 清理自动草稿
$wpdb->query(
"DELETE FROM $wpdb->posts
WHERE post_status = 'auto-draft'
AND post_date < DATE_SUB(NOW(), INTERVAL 7 DAY)"
);
// 优化数据库表
$tables = $wpdb->get_col("SHOW TABLES");
foreach ($tables as $table) {
$wpdb->query("OPTIMIZE TABLE $table");
}
$optimizations[] = "优化了所有数据库表";
return $optimizations;
}
}
class Toolkit_API {
private $api_version = 'v1';
class Toolkit_API {
private $api_version = 'v1';


