首页 / 应用软件 / 手把手教程,为WordPress实现智能化的网站内容版权检测与保护工具

手把手教程,为WordPress实现智能化的网站内容版权检测与保护工具

手把手教程:为WordPress实现智能化的网站内容版权检测与保护工具

引言:数字时代的内容版权挑战

在当今数字化时代,内容创作已成为网站运营的核心。无论是个人博客、企业官网还是电子商务平台,原创内容都是吸引流量、建立品牌权威的关键要素。然而,随着互联网信息的快速传播,内容盗用、抄袭和未经授权的转载问题日益严重。根据最新统计,超过60%的网站管理员表示曾遭遇过内容被盗用的情况,这直接影响了原创者的权益和网站的SEO表现。

WordPress作为全球最流行的内容管理系统,占据了互联网近43%的网站份额。虽然WordPress拥有丰富的插件生态系统,但在内容版权保护方面,大多数现有解决方案要么功能有限,要么需要高昂的订阅费用。本文将手把手指导您通过WordPress代码二次开发,实现一个智能化的网站内容版权检测与保护工具,让您的原创内容得到更好的保护。

第一章:理解WordPress内容保护的基本原理

1.1 WordPress内容盗用的常见形式

在开始开发之前,我们需要了解内容盗用的主要形式:

  • 直接复制粘贴:用户通过浏览器右键复制或查看源代码获取内容
  • RSS订阅盗用:通过网站的RSS源批量抓取内容
  • 爬虫程序抓取:使用自动化脚本抓取网站内容
  • 截图盗用:对内容进行截图后重新发布

1.2 现有版权保护方法的局限性

当前常见的WordPress版权保护方法包括:

  • 禁用右键功能:简单但用户体验差,且技术用户可轻松绕过
  • 添加水印:适用于图片,但对文本内容无效
  • 使用JavaScript干扰:可以防止简单复制,但无法阻止源代码查看
  • 法律声明:仅有威慑作用,缺乏实际保护能力

1.3 智能化版权保护的核心思路

我们将要开发的工具基于以下核心思路:

  1. 内容指纹技术:为每篇文章生成唯一数字指纹
  2. 智能监控系统:定期搜索互联网上的相似内容
  3. 动态防护机制:根据访问者行为动态调整保护策略
  4. 版权声明自动化:自动在内容中嵌入版权信息

第二章:开发环境准备与基础架构设计

2.1 开发环境配置

首先,确保您具备以下开发环境:

  • WordPress安装(建议5.6以上版本)
  • PHP开发环境(7.4以上版本)
  • 代码编辑器(VS Code、PHPStorm等)
  • 本地或测试服务器环境

2.2 创建插件基础结构

在WordPress的wp-content/plugins/目录下创建新文件夹smart-content-protector,并建立以下基础文件结构:

smart-content-protector/
├── smart-content-protector.php      # 主插件文件
├── includes/
│   ├── class-content-fingerprint.php   # 内容指纹生成类
│   ├── class-content-monitor.php       # 内容监控类
│   ├── class-protection-engine.php     # 保护引擎类
│   └── class-settings-manager.php      # 设置管理类
├── admin/
│   ├── css/
│   │   └── admin-style.css             # 后台样式
│   ├── js/
│   │   └── admin-script.js             # 后台脚本
│   └── class-admin-interface.php       # 后台界面类
├── public/
│   ├── css/
│   │   └── public-style.css            # 前端样式
│   ├── js/
│   │   └── public-script.js            # 前端脚本
│   └── class-public-handler.php        # 前端处理类
├── assets/                             # 静态资源
└── uninstall.php                       # 插件卸载处理

2.3 主插件文件配置

编辑smart-content-protector.php文件,添加插件基本信息:

<?php
/**
 * Plugin Name: Smart Content Protector
 * Plugin URI: https://yourwebsite.com/smart-content-protector
 * Description: 智能化的WordPress网站内容版权检测与保护工具
 * Version: 1.0.0
 * Author: Your Name
 * License: GPL v2 or later
 * Text Domain: smart-content-protector
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 定义插件常量
define('SCP_VERSION', '1.0.0');
define('SCP_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('SCP_PLUGIN_URL', plugin_dir_url(__FILE__));
define('SCP_PLUGIN_BASENAME', plugin_basename(__FILE__));

// 自动加载类文件
spl_autoload_register(function ($class_name) {
    $prefix = 'SCP_';
    $base_dir = SCP_PLUGIN_DIR . 'includes/';
    
    $len = strlen($prefix);
    if (strncmp($prefix, $class_name, $len) !== 0) {
        return;
    }
    
    $relative_class = substr($class_name, $len);
    $file = $base_dir . 'class-' . str_replace('_', '-', strtolower($relative_class)) . '.php';
    
    if (file_exists($file)) {
        require $file;
    }
});

// 初始化插件
function scp_init_plugin() {
    // 检查WordPress版本
    if (version_compare(get_bloginfo('version'), '5.6', '<')) {
        add_action('admin_notices', function() {
            echo '<div class="notice notice-error"><p>';
            echo __('Smart Content Protector需要WordPress 5.6或更高版本。', 'smart-content-protector');
            echo '</p></div>';
        });
        return;
    }
    
    // 初始化核心类
    $content_fingerprint = new SCP_Content_Fingerprint();
    $content_monitor = new SCP_Content_Monitor();
    $protection_engine = new SCP_Protection_Engine();
    $settings_manager = new SCP_Settings_Manager();
    
    // 根据环境加载前端或后台
    if (is_admin()) {
        require_once SCP_PLUGIN_DIR . 'admin/class-admin-interface.php';
        new SCP_Admin_Interface($settings_manager);
    } else {
        require_once SCP_PLUGIN_DIR . 'public/class-public-handler.php';
        new SCP_Public_Handler($protection_engine);
    }
}

add_action('plugins_loaded', 'scp_init_plugin');

// 激活插件时的操作
register_activation_hook(__FILE__, 'scp_activate_plugin');
function scp_activate_plugin() {
    // 创建必要的数据库表
    scp_create_database_tables();
    
    // 设置默认选项
    $default_options = array(
        'protection_level' => 'medium',
        'auto_monitor' => true,
        'monitor_frequency' => 'weekly',
        'watermark_text' => '本文来自{site_name},原文链接:{post_url}',
        'disable_right_click' => false,
        'enable_fingerprint' => true,
        'search_engines' => array('google', 'bing'),
    );
    
    add_option('scp_settings', $default_options);
    
    // 安排定期监控任务
    if (!wp_next_scheduled('scp_daily_monitor')) {
        wp_schedule_event(time(), 'daily', 'scp_daily_monitor');
    }
}

// 停用插件时的操作
register_deactivation_hook(__FILE__, 'scp_deactivate_plugin');
function scp_deactivate_plugin() {
    // 清除定时任务
    wp_clear_scheduled_hook('scp_daily_monitor');
}

// 创建数据库表
function scp_create_database_tables() {
    global $wpdb;
    
    $charset_collate = $wpdb->get_charset_collate();
    $table_name = $wpdb->prefix . 'scp_content_fingerprints';
    
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        post_id bigint(20) NOT NULL,
        fingerprint varchar(64) NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY post_id (post_id),
        KEY fingerprint (fingerprint)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    
    // 创建侵权记录表
    $infringement_table = $wpdb->prefix . 'scp_infringements';
    
    $sql = "CREATE TABLE IF NOT EXISTS $infringement_table (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        post_id bigint(20) NOT NULL,
        infringing_url varchar(500) NOT NULL,
        similarity_score float NOT NULL,
        detected_at datetime DEFAULT CURRENT_TIMESTAMP,
        status varchar(20) DEFAULT 'pending',
        action_taken varchar(50) DEFAULT NULL,
        PRIMARY KEY (id),
        KEY post_id (post_id),
        KEY status (status)
    ) $charset_collate;";
    
    dbDelta($sql);
}

第三章:实现内容指纹生成系统

3.1 内容指纹算法设计

编辑includes/class-content-fingerprint.php文件:

<?php
class SCP_Content_Fingerprint {
    
    private $hash_algo = 'sha256';
    
    public function __construct() {
        add_action('save_post', array($this, 'generate_post_fingerprint'), 10, 3);
        add_action('scp_daily_monitor', array($this, 'update_all_fingerprints'));
    }
    
    /**
     * 为文章生成内容指纹
     */
    public function generate_post_fingerprint($post_id, $post, $update) {
        // 跳过自动保存和修订
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        if (wp_is_post_revision($post_id)) {
            return;
        }
        
        // 只处理已发布的文章
        if ($post->post_status !== 'publish') {
            return;
        }
        
        // 获取文章内容
        $content = $this->extract_content_for_fingerprint($post);
        
        // 生成指纹
        $fingerprint = $this->calculate_fingerprint($content);
        
        // 保存到数据库
        $this->save_fingerprint($post_id, $fingerprint);
        
        return $fingerprint;
    }
    
    /**
     * 提取用于生成指纹的内容
     */
    private function extract_content_for_fingerprint($post) {
        $content = '';
        
        // 添加标题
        $content .= strip_tags($post->post_title) . "n";
        
        // 添加正文内容(去除HTML标签)
        $post_content = strip_tags($post->post_content);
        $post_content = preg_replace('/s+/', ' ', $post_content);
        $content .= $post_content . "n";
        
        // 添加前300个字符作为特征(即使内容被部分修改也能检测)
        $content .= substr($post_content, 0, 300);
        
        // 添加文章摘要(如果有)
        if (!empty($post->post_excerpt)) {
            $content .= strip_tags($post->post_excerpt) . "n";
        }
        
        return $content;
    }
    
    /**
     * 计算内容指纹
     */
    private function calculate_fingerprint($content) {
        // 标准化内容:转换为小写,移除多余空格和标点
        $normalized = $this->normalize_content($content);
        
        // 使用simhash算法生成指纹(更适合文本相似度检测)
        $fingerprint = $this->simhash($normalized);
        
        return $fingerprint;
    }
    
    /**
     * 内容标准化处理
     */
    private function normalize_content($content) {
        // 转换为小写
        $content = mb_strtolower($content, 'UTF-8');
        
        // 移除所有标点符号和特殊字符
        $content = preg_replace('/[^p{L}p{N}s]/u', ' ', $content);
        
        // 将多个空格合并为一个
        $content = preg_replace('/s+/', ' ', $content);
        
        // 移除停用词(常见但无实际意义的词)
        $stop_words = $this->get_stop_words();
        $words = explode(' ', $content);
        $words = array_diff($words, $stop_words);
        
        return implode(' ', $words);
    }
    
    /**
     * 获取停用词列表
     */
    private function get_stop_words() {
        // 中文常见停用词
        $chinese_stop_words = array(
            '的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这'
        );
        
        // 英文常见停用词
        $english_stop_words = array(
            'a', 'an', 'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were', 'be', 'been', 'being'
        );
        
        return array_merge($chinese_stop_words, $english_stop_words);
    }
    
    /**
     * SimHash算法实现
     */
    private function simhash($content) {
        $features = array();
        $words = explode(' ', $content);
        
        // 统计词频
        $word_counts = array_count_values($words);
        
        // 初始化特征向量(64位)
        $vector = array_fill(0, 64, 0);
        
        foreach ($word_counts as $word => $count) {
            // 为每个词生成hash
            $hash = hexdec(substr(md5($word), 0, 16));
            
            for ($i = 0; $i < 64; $i++) {
                // 检查hash的每一位
                $bit = ($hash >> $i) & 1;
                if ($bit == 1) {
                    $vector[$i] += $count;
                } else {
                    $vector[$i] -= $count;
                }
            }
        }
        
        // 生成最终的fingerprint
        $fingerprint = 0;
        for ($i = 0; $i < 64; $i++) {
            if ($vector[$i] > 0) {
                $fingerprint |= (1 << $i);
            }
        }
        
        return dechex($fingerprint);
    }
    
    /**
     * 保存指纹到数据库
     */
    private function save_fingerprint($post_id, $fingerprint) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'scp_content_fingerprints';
        
        // 检查是否已存在记录
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM $table_name WHERE post_id = %d",
            $post_id
        ));
        
        if ($existing) {
            // 更新现有记录
            $wpdb->update(
                $table_name,
                array('fingerprint' => $fingerprint),
                array('post_id' => $post_id),
                array('%s'),
                array('%d')
            );
        } else {
            // 插入新记录
            $wpdb->insert(
                $table_name,
                array(
                    'post_id' => $post_id,
                    'fingerprint' => $fingerprint
                ),
                array('%d', '%s')
            );
        }
    }
    
    /**
     * 更新所有文章的指纹
     */
    public function update_all_fingerprints() {
        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => -1,
        );
        
        $posts = get_posts($args);
        
        foreach ($posts as $post) {
            $this->generate_post_fingerprint($post->ID, $post, true);
        }
    }
    
    /**
     * 计算两个指纹的相似度
     */
    public function calculate_similarity($fingerprint1, $fingerprint2) {
        // 将十六进制转换为二进制
        $bin1 = hex2bin(str_pad($fingerprint1, 16, '0', STR_PAD_LEFT));
        $bin2 = hex2bin(str_pad($fingerprint2, 16, '0', STR_PAD_LEFT));
        
        // 计算海明距离
        $hamming_distance = 0;
        for ($i = 0; $i < strlen($bin1); $i++) {
            $xor = ord($bin1[$i]) ^ ord($bin2[$i]);
            while ($xor) {
                $hamming_distance += $xor & 1;
                $xor >>= 1;
            }
        }
        
        // 转换为相似度百分比
        $max_distance = strlen($bin1) * 8;
        $similarity = 100 * (1 - $hamming_distance / $max_distance);
        
        return round($similarity, 2);
    }
}

第四章:构建智能内容监控系统

4.1 监控系统设计

编辑includes/class-content-monitor.php文件:

<?php
class SCP_Content_Monitor {
    
    private $search_engines = array();
    private $api_keys = array();
    
    public function __construct() {
        $settings = get_option('scp_settings', array());
        $this->search_engines = isset($settings['search_engines']) ? $settings['search_engines'] : array('google');
        
        // 设置API密钥(实际使用时需要从设置中获取)
        $this->api_keys = array(
            'google' => defined('SCP_GOOGLE_API_KEY') ? SCP_GOOGLE_API_KEY : '',

_API_KEY') ? SCP_BING_API_KEY : ''

    );
    
    add_action('scp_daily_monitor', array($this, 'run_daily_monitoring'));
    add_action('scp_manual_monitor', array($this, 'monitor_specific_post'));
}

/**
 * 执行每日监控任务
 */
public function run_daily_monitoring() {
    // 获取最近30天内发布的文章
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'date_query' => array(
            array(
                'after' => '30 days ago',
            )
        ),
        'posts_per_page' => 20, // 每天监控20篇文章,避免API限制
    );
    
    $posts = get_posts($args);
    
    foreach ($posts as $post) {
        $this->monitor_post($post);
        // 避免请求过于频繁
        sleep(2);
    }
    
    // 记录监控日志
    $this->log_monitoring_result(count($posts));
}

/**
 * 监控特定文章
 */
public function monitor_specific_post($post_id) {
    $post = get_post($post_id);
    if ($post && $post->post_status === 'publish') {
        return $this->monitor_post($post);
    }
    return false;
}

/**
 * 监控单篇文章
 */
private function monitor_post($post) {
    $results = array();
    
    // 生成搜索查询
    $search_queries = $this->generate_search_queries($post);
    
    foreach ($this->search_engines as $engine) {
        if (method_exists($this, "search_with_{$engine}")) {
            foreach ($search_queries as $query) {
                $engine_results = call_user_func(
                    array($this, "search_with_{$engine}"),
                    $query,
                    $post->ID
                );
                
                if (!empty($engine_results)) {
                    $results = array_merge($results, $engine_results);
                }
            }
        }
    }
    
    // 分析结果并保存侵权记录
    if (!empty($results)) {
        $this->analyze_and_save_results($results, $post->ID);
    }
    
    return $results;
}

/**
 * 生成搜索查询
 */
private function generate_search_queries($post) {
    $queries = array();
    
    // 提取文章标题中的关键词
    $title = strip_tags($post->post_title);
    $title_words = explode(' ', preg_replace('/[^p{L}p{N}s]/u', ' ', $title));
    $title_words = array_filter($title_words, function($word) {
        return mb_strlen($word, 'UTF-8') > 1;
    });
    
    // 使用标题中的前5个词作为查询
    if (count($title_words) > 0) {
        $title_query = implode(' ', array_slice($title_words, 0, 5));
        $queries[] = $title_query;
    }
    
    // 提取文章中的独特短语(连续3-5个词)
    $content = strip_tags($post->post_content);
    $content = preg_replace('/s+/', ' ', $content);
    $words = explode(' ', $content);
    
    // 生成独特短语
    $phrases = array();
    for ($i = 0; $i < count($words) - 3; $i++) {
        $phrase = implode(' ', array_slice($words, $i, 4));
        if (strlen($phrase) > 15 && strlen($phrase) < 50) {
            $phrases[] = $phrase;
        }
    }
    
    // 选择最独特的3个短语
    $unique_phrases = $this->select_unique_phrases($phrases);
    $queries = array_merge($queries, array_slice($unique_phrases, 0, 3));
    
    // 添加包含网站名称的查询
    $site_name = get_bloginfo('name');
    if (!empty($site_name) && !empty($title_query)) {
        $queries[] = ""{$title_query}" "{$site_name}"";
    }
    
    return array_unique($queries);
}

/**
 * 选择独特短语
 */
private function select_unique_phrases($phrases) {
    // 简单的独特性评分:基于词频和长度
    $scored_phrases = array();
    
    foreach ($phrases as $phrase) {
        $score = 0;
        
        // 长度适中得分高
        $length = strlen($phrase);
        if ($length > 20 && $length < 40) {
            $score += 3;
        } elseif ($length >= 40 && $length < 60) {
            $score += 2;
        }
        
        // 包含较少常见词得分高
        $common_words = array('的', '了', '在', '是', '和', '就', '不', '人', '都');
        $phrase_words = explode(' ', $phrase);
        $common_count = count(array_intersect($phrase_words, $common_words));
        $score += max(0, 5 - $common_count);
        
        $scored_phrases[$phrase] = $score;
    }
    
    arsort($scored_phrases);
    return array_keys($scored_phrases);
}

/**
 * 使用Google搜索
 */
private function search_with_google($query, $post_id) {
    $api_key = $this->api_keys['google'];
    $search_engine_id = defined('SCP_GOOGLE_CSE_ID') ? SCP_GOOGLE_CSE_ID : '';
    
    if (empty($api_key) || empty($search_engine_id)) {
        // 如果没有API密钥,使用简单的HTTP请求模拟搜索
        return $this->search_with_google_public($query, $post_id);
    }
    
    $url = 'https://www.googleapis.com/customsearch/v1';
    $params = array(
        'key' => $api_key,
        'cx' => $search_engine_id,
        'q' => $query,
        'num' => 10,
        'fields' => 'items(link,title,snippet)'
    );
    
    $response = wp_remote_get(add_query_arg($params, $url));
    
    if (is_wp_error($response)) {
        return array();
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    $results = array();
    if (isset($data['items'])) {
        foreach ($data['items'] as $item) {
            // 排除自己的网站
            if (strpos($item['link'], home_url()) !== false) {
                continue;
            }
            
            $results[] = array(
                'url' => $item['link'],
                'title' => $item['title'],
                'snippet' => $item['snippet'],
                'engine' => 'google',
                'query' => $query
            );
        }
    }
    
    return $results;
}

/**
 * 使用公开的Google搜索(无API)
 */
private function search_with_google_public($query, $post_id) {
    // 注意:这种方法可能违反Google的服务条款,仅作为示例
    // 实际使用时建议使用官方API
    
    $url = 'https://www.google.com/search';
    $params = array(
        'q' => $query,
        'num' => 10
    );
    
    $response = wp_remote_get(add_query_arg($params, $url), array(
        'headers' => array(
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        )
    ));
    
    if (is_wp_error($response)) {
        return array();
    }
    
    $body = wp_remote_retrieve_body($response);
    
    // 简单的HTML解析提取结果
    $results = array();
    if (preg_match_all('/<div class="g">(.*?)</div></div></div>/s', $body, $matches)) {
        foreach ($matches[1] as $match) {
            if (preg_match('/<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>/', $match, $link_match)) {
                $url = $link_match[1];
                $title = strip_tags($link_match[2]);
                
                // 排除自己的网站
                if (strpos($url, home_url()) !== false) {
                    continue;
                }
                
                // 提取摘要
                $snippet = '';
                if (preg_match('/<div[^>]*class="[^"]*VwiC3b[^"]*"[^>]*>(.*?)</div>/', $match, $snippet_match)) {
                    $snippet = strip_tags($snippet_match[1]);
                }
                
                $results[] = array(
                    'url' => $url,
                    'title' => $title,
                    'snippet' => $snippet,
                    'engine' => 'google_public',
                    'query' => $query
                );
            }
        }
    }
    
    return $results;
}

/**
 * 使用Bing搜索
 */
private function search_with_bing($query, $post_id) {
    $api_key = $this->api_keys['bing'];
    
    if (empty($api_key)) {
        return array();
    }
    
    $url = 'https://api.bing.microsoft.com/v7.0/search';
    $params = array(
        'q' => $query,
        'count' => 10,
        'responseFilter' => 'Webpages'
    );
    
    $response = wp_remote_get(add_query_arg($params, $url), array(
        'headers' => array(
            'Ocp-Apim-Subscription-Key' => $api_key
        )
    ));
    
    if (is_wp_error($response)) {
        return array();
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    $results = array();
    if (isset($data['webPages']['value'])) {
        foreach ($data['webPages']['value'] as $item) {
            // 排除自己的网站
            if (strpos($item['url'], home_url()) !== false) {
                continue;
            }
            
            $results[] = array(
                'url' => $item['url'],
                'title' => $item['name'],
                'snippet' => $item['snippet'],
                'engine' => 'bing',
                'query' => $query
            );
        }
    }
    
    return $results;
}

/**
 * 分析并保存结果
 */
private function analyze_and_save_results($results, $post_id) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'scp_infringements';
    
    $post_content = get_post_field('post_content', $post_id);
    $post_content_plain = strip_tags($post_content);
    
    foreach ($results as $result) {
        // 获取疑似侵权页面的内容
        $infringing_content = $this->fetch_page_content($result['url']);
        
        if (empty($infringing_content)) {
            continue;
        }
        
        // 计算相似度
        $similarity = $this->calculate_content_similarity(
            $post_content_plain,
            $infringing_content
        );
        
        // 如果相似度超过阈值,保存记录
        $threshold = 70; // 70%相似度阈值
        if ($similarity >= $threshold) {
            // 检查是否已存在记录
            $existing = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM $table_name 
                WHERE post_id = %d AND infringing_url = %s",
                $post_id,
                $result['url']
            ));
            
            if (!$existing) {
                $wpdb->insert(
                    $table_name,
                    array(
                        'post_id' => $post_id,
                        'infringing_url' => $result['url'],
                        'similarity_score' => $similarity,
                        'detected_at' => current_time('mysql'),
                        'status' => 'pending'
                    ),
                    array('%d', '%s', '%f', '%s', '%s')
                );
                
                // 发送通知
                $this->send_infringement_notification($post_id, $result['url'], $similarity);
            }
        }
    }
}

/**
 * 获取页面内容
 */
private function fetch_page_content($url) {
    $response = wp_remote_get($url, array(
        'timeout' => 10,
        'headers' => array(
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        )
    ));
    
    if (is_wp_error($response)) {
        return '';
    }
    
    $body = wp_remote_retrieve_body($response);
    
    // 提取正文内容
    $content = '';
    
    // 尝试多种方法提取正文
    if (preg_match('/<body[^>]*>(.*?)</body>/s', $body, $matches)) {
        $body_content = $matches[1];
        
        // 移除脚本和样式
        $body_content = preg_replace('/<script[^>]*>.*?</script>/s', '', $body_content);
        $body_content = preg_replace('/<style[^>]*>.*?</style>/s', '', $body_content);
        
        // 提取文本
        $content = strip_tags($body_content);
        $content = preg_replace('/s+/', ' ', $content);
        $content = trim($content);
    }
    
    return $content;
}

/**
 * 计算内容相似度
 */
private function calculate_content_similarity($content1, $content2) {
    // 使用文本相似度算法
    $similarity = 0;
    
    // 方法1:基于共享词的比例
    $words1 = $this->extract_significant_words($content1);
    $words2 = $this->extract_significant_words($content2);
    
    $common_words = array_intersect($words1, $words2);
    $total_unique_words = count(array_unique(array_merge($words1, $words2)));
    
    if ($total_unique_words > 0) {
        $similarity = (count($common_words) / $total_unique_words) * 100;
    }
    
    // 方法2:检查长字符串匹配
    $long_strings1 = $this->extract_long_strings($content1);
    $long_strings2 = $this->extract_long_strings($content2);
    
    $string_similarity = 0;
    foreach ($long_strings1 as $str1) {
        foreach ($long_strings2 as $str2) {
            similar_text($str1, $str2, $percent);
            if ($percent > 80) { // 80%相似的长字符串
                $string_similarity = max($string_similarity, $percent);
            }
        }
    }
    
    // 取两种方法的较高值
    $similarity = max($similarity, $string_similarity);
    
    return min(100, round($similarity, 2));
}

/**
 * 提取重要词汇
 */
private function extract_significant_words($content, $min_length = 2) {
    $content = mb_strtolower($content, 'UTF-8');
    $content = preg_replace('/[^p{L}p{N}s]/u', ' ', $content);
    $words = explode(' ', $content);
    
    // 过滤短词和停用词
    $stop_words = $this->get_stop_words();
    $words = array_filter($words, function($word) use ($min_length, $stop_words) {
        return mb_strlen($word, 'UTF-8') >= $min_length && 
               !in_array($word, $stop_words);
    });
    
    return array_values($words);
}

/**
 * 提取长字符串
 */
private function extract_long_strings($content, $min_length = 20) {
    $sentences = preg_split('/[。.!??]/u', $content);
    $long_strings = array();
    
    foreach ($sentences as $sentence) {
        $sentence = trim($sentence);
        if (mb_strlen($sentence, 'UTF-8') >= $min_length) {
            $long_strings[] = $sentence;
        }
    }
    
    return $long_strings;
}

/**
 * 发送侵权通知
 */
private function send_infringement_notification($post_id, $infringing_url, $similarity) {
    $admin_email = get_option('admin_email');
    $post_title = get_the_title($post_id);
    $post_url = get_permalink($post_id);
    
    $subject = sprintf(
        __('[内容侵权警报] 文章 "%s" 可能被抄袭', 'smart-content-protector'),
        $post_title
    );
    
    $message = sprintf(
        __('检测到可能的内容侵权:

您的文章:%s
文章链接:%s

疑似侵权页面:%s
相似度:%.2f%%

请登录WordPress后台查看详细信息并采取相应措施。

Smart Content Protector
%s', 'smart-content-protector'),

        $post_title,
        $post_url,
        $infringing_url,
        $similarity,
        home_url()
    );
    
    wp_mail($admin_email, $subject, $message);
}

/**
 * 记录监控日志
 */
private function log_monitoring_result($posts_monitored) {
    $log_entry = sprintf(
        '[%s] 监控完成,检查了 %d 篇文章',
        current_time('mysql'),
        $posts_monitored
    );
    
    // 保存到选项
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5210.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

工作时间:周一至周五,9:00-17:30,节假日休息
返回顶部