首页 / 教程文章 / 网络传媒WordPress柔性内容版权保护插件开发教程

网络传媒WordPress柔性内容版权保护插件开发教程

WordPress柔性内容版权保护插件开发教程

引言:为什么需要内容版权保护

在当今数字化时代,网络传媒面临着严峻的内容盗用挑战。原创文章、图片和视频被未经授权地复制、传播,给内容创作者带来巨大损失。WordPress作为最流行的内容管理系统,虽然功能强大,但在原生版权保护方面仍有不足。本教程将指导您开发一个柔性内容版权保护插件,既能有效防止内容盗用,又不会影响正常用户的浏览体验。

插件基础架构设计

1. 创建插件基本结构

首先,在WordPress的wp-content/plugins/目录下创建插件文件夹flexible-copyright-protector,并建立以下基础文件结构:

flexible-copyright-protector/
├── flexible-copyright-protector.php    # 主插件文件
├── includes/
│   ├── class-protection-engine.php    # 保护引擎核心类
│   ├── class-settings-manager.php     # 设置管理类
│   └── class-content-filter.php       # 内容过滤类
├── assets/
│   ├── css/
│   │   └── admin-styles.css           # 后台样式
│   └── js/
│       ├── frontend-scripts.js        # 前端脚本
│       └── admin-scripts.js           # 后台脚本
├── templates/
│   └── watermark-overlay.php          # 水印模板
└── uninstall.php                      # 卸载脚本

2. 主插件文件配置

<?php
/**
 * Plugin Name: Flexible Copyright Protector
 * Plugin URI: https://yourwebsite.com/flexible-copyright-protector
 * Description: 柔性内容版权保护插件,防止内容被非法复制
 * Version: 1.0.0
 * Author: 您的名字
 * License: GPL v2 or later
 * Text Domain: flexible-copyright
 */

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

// 定义插件常量
define('FCP_VERSION', '1.0.0');
define('FCP_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('FCP_PLUGIN_URL', plugin_dir_url(__FILE__));

// 自动加载类文件
spl_autoload_register(function ($class_name) {
    if (strpos($class_name, 'FCP_') === 0) {
        $file = FCP_PLUGIN_DIR . 'includes/class-' . strtolower(str_replace('_', '-', $class_name)) . '.php';
        if (file_exists($file)) {
            require_once $file;
        }
    }
});

// 初始化插件
function fcp_init_plugin() {
    // 检查WordPress版本
    if (version_compare(get_bloginfo('version'), '5.0', '<')) {
        add_action('admin_notices', function() {
            echo '<div class="notice notice-error"><p>';
            echo __('Flexible Copyright Protector 需要 WordPress 5.0 或更高版本', 'flexible-copyright');
            echo '</p></div>';
        });
        return;
    }
    
    // 实例化核心类
    $protection_engine = new FCP_Protection_Engine();
    $settings_manager = new FCP_Settings_Manager();
    $content_filter = new FCP_Content_Filter();
    
    // 初始化组件
    $protection_engine->init();
    $settings_manager->init();
    $content_filter->init();
}

add_action('plugins_loaded', 'fcp_init_plugin');

// 激活插件时的操作
register_activation_hook(__FILE__, function() {
    // 创建必要的数据库表
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();
    
    $table_name = $wpdb->prefix . 'fcp_protection_logs';
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        user_ip varchar(45) DEFAULT NULL,
        action_type varchar(50) NOT NULL,
        post_id bigint(20) DEFAULT NULL,
        user_agent text,
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY post_id (post_id),
        KEY created_at (created_at)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    
    // 设置默认选项
    $default_options = array(
        'enable_right_click_protection' => true,
        'enable_text_selection_protection' => true,
        'enable_image_drag_protection' => true,
        'watermark_opacity' => 30,
        'protection_level' => 'medium',
        'excluded_user_roles' => array('administrator'),
        'custom_css' => '',
    );
    
    add_option('fcp_settings', $default_options);
});

核心保护功能实现

3. 保护引擎开发

<?php
// includes/class-protection-engine.php

class FCP_Protection_Engine {
    
    private $settings;
    
    public function __construct() {
        $this->settings = get_option('fcp_settings', array());
    }
    
    public function init() {
        // 根据设置添加不同的保护措施
        if ($this->settings['enable_right_click_protection'] ?? false) {
            add_action('wp_footer', array($this, 'disable_right_click'));
        }
        
        if ($this->settings['enable_text_selection_protection'] ?? false) {
            add_action('wp_enqueue_scripts', array($this, 'disable_text_selection'));
        }
        
        if ($this->settings['enable_image_drag_protection'] ?? false) {
            add_action('wp_footer', array($this, 'disable_image_drag'));
        }
        
        // 添加水印功能
        add_filter('the_content', array($this, 'add_content_watermark'), 99);
    }
    
    /**
     * 禁用右键菜单
     */
    public function disable_right_click() {
        // 检查当前用户是否在排除角色列表中
        if ($this->is_user_excluded()) {
            return;
        }
        
        echo '<script type="text/javascript">
        document.addEventListener("contextmenu", function(e) {
            // 允许在某些元素上使用右键
            if (e.target.tagName === "INPUT" || 
                e.target.tagName === "TEXTAREA" ||
                e.target.closest(".allow-right-click")) {
                return;
            }
            
            e.preventDefault();
            
            // 显示版权提示
            var warning = document.createElement("div");
            warning.style.cssText = "position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,0.8);color:white;padding:20px;border-radius:5px;z-index:999999;";
            warning.innerHTML = "<h3>版权保护提示</h3><p>此内容受版权保护,请尊重原创。</p>";
            document.body.appendChild(warning);
            
            setTimeout(function() {
                document.body.removeChild(warning);
            }, 2000);
            
            // 记录日志
            fetch("' . admin_url('admin-ajax.php') . '", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                body: "action=fcp_log_action&type=right_click_attempt&post_id=" + (window.fcp_post_id || 0)
            });
        }, false);
        </script>';
    }
    
    /**
     * 禁用文本选择
     */
    public function disable_text_selection() {
        if ($this->is_user_excluded()) {
            return;
        }
        
        $protection_level = $this->settings['protection_level'] ?? 'medium';
        
        if ($protection_level === 'high') {
            // 高级保护:完全禁用选择
            $css = '
                body * {
                    -webkit-user-select: none !important;
                    -moz-user-select: none !important;
                    -ms-user-select: none !important;
                    user-select: none !important;
                }
                .allow-selection, input, textarea {
                    -webkit-user-select: text !important;
                    -moz-user-select: text !important;
                    -ms-user-select: text !important;
                    user-select: text !important;
                }
            ';
        } else {
            // 中级保护:允许选择但添加干扰
            $css = '
                body::selection {
                    background: rgba(0, 150, 255, 0.3) !important;
                }
                body::-moz-selection {
                    background: rgba(0, 150, 255, 0.3) !important;
                }
            ';
        }
        
        // 添加自定义CSS
        if (!empty($this->settings['custom_css'])) {
            $css .= $this->settings['custom_css'];
        }
        
        wp_add_inline_style('wp-block-library', $css);
    }
    
    /**
     * 添加内容水印
     */
    public function add_content_watermark($content) {
        // 只在文章页面显示水印
        if (!is_single() || $this->is_user_excluded()) {
            return $content;
        }
        
        $watermark_text = get_bloginfo('name') . ' - ' . get_permalink();
        $opacity = $this->settings['watermark_opacity'] ?? 30;
        
        // 创建水印层
        $watermark_html = '
        <div class="fcp-watermark" style="
            position: relative;
            display: inline-block;
            width: 100%;
        ">
            ' . $content . '
            <div class="fcp-watermark-overlay" style="
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                pointer-events: none;
                background: repeating-linear-gradient(
                    45deg,
                    transparent,
                    transparent 100px,
                    rgba(0, 0, 0, 0.' . $opacity . ') 100px,
                    rgba(0, 0, 0, 0.' . $opacity . ') 200px
                );
                z-index: 999;
            "></div>
            <div class="fcp-watermark-text" style="
                position: absolute;
                bottom: 10px;
                right: 10px;
                color: rgba(0, 0, 0, 0.' . ($opacity + 20) . ');
                font-size: 12px;
                pointer-events: none;
                z-index: 1000;
            ">' . esc_html($watermark_text) . '</div>
        </div>';
        
        return $watermark_html;
    }
    
    /**
     * 检查用户是否在排除列表中
     */
    private function is_user_excluded() {
        if (!is_user_logged_in()) {
            return false;
        }
        
        $user = wp_get_current_user();
        $excluded_roles = $this->settings['excluded_user_roles'] ?? array();
        
        foreach ($excluded_roles as $role) {
            if (in_array($role, $user->roles)) {
                return true;
            }
        }
        
        return false;
    }
}

4. 设置管理界面

<?php
// includes/class-settings-manager.php

class FCP_Settings_Manager {
    
    public function init() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
    }
    
    public function add_admin_menu() {
        add_options_page(
            '柔性版权保护设置',
            '版权保护',
            'manage_options',
            'flexible-copyright-protector',
            array($this, 'render_settings_page')
        );
    }
    
    public function register_settings() {
        register_setting('fcp_settings_group', 'fcp_settings', array(
            'sanitize_callback' => array($this, 'sanitize_settings')
        ));
        
        // 基本设置部分
        add_settings_section(
            'fcp_basic_settings',
            '基本保护设置',
            array($this, 'render_basic_settings_section'),
            'flexible-copyright-protector'
        );
        
        // 添加各个设置字段
        $fields = array(
            array(
                'id' => 'enable_right_click_protection',
                'title' => '禁用右键菜单',
                'callback' => 'render_checkbox_field',
                'args' => array(
                    'label' => '启用右键菜单保护'
                )
            ),
            array(
                'id' => 'enable_text_selection_protection',
                'title' => '文本选择保护',
                'callback' => 'render_checkbox_field',
                'args' => array(
                    'label' => '启用文本选择保护'
                )
            ),
            array(
                'id' => 'protection_level',
                'title' => '保护级别',
                'callback' => 'render_select_field',
                'args' => array(
                    'options' => array(
                        'low' => '低 - 基本保护',
                        'medium' => '中 - 平衡保护',
                        'high' => '高 - 最强保护'
                    )
                )
            )
        );
        
        foreach ($fields as $field) {
            add_settings_field(
                $field['id'],
                $field['title'],
                array($this, $field['callback']),
                'flexible-copyright-protector',
                'fcp_basic_settings',
                array_merge(array('id' => $field['id']), $field['args'])
            );
        }
    }
    
    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1>柔性内容版权保护设置</h1>
            <form method="post" action="options.php">
                <?php
                settings_fields('fcp_settings_group');
                do_settings_sections('flexible-copyright-protector');
                submit_button();
                ?>
            </form>
            
            <div class="fcp-stats-box" style="margin-top: 30px; padding: 20px; background: #f5f5f5; border-radius: 5px;">
                <h3>保护统计</h3>
                <?php $this->render_protection_stats(); ?>
            </div>
        </div>
        <?php
    }
    
    public function render_checkbox_field($args) {
        $options = get_option('fcp_settings');
        $checked = isset($options[$args['id']]) ? checked(1, $options[$args['id']], false) : '';
        ?>
        <input type="checkbox" 
               id="<?php echo esc_attr($args['id']); ?>" 
               name="fcp_settings[<?php echo esc_attr($args['id']); ?>]" 
               value="1" 
               <?php echo $checked; ?> />
        <label for="<?php echo esc_attr($args['id']); ?>">
            <?php echo esc_html($args['label']); ?>
        </label>
        <?php
    }
    
    public function sanitize_settings($input) {
        $sanitized = array();
        
        foreach ($input as $key => $value) {
            switch ($key) {
                case 'watermark_opacity':
                    $sanitized[$key] = absint($value);
                    if ($sanitized[$key] > 100) $sanitized[$key] = 100;
                    break;
                case 'custom_css':
                    $sanitized[$key] = wp_strip_all_tags($value);
                    break;
                default:
                    $sanitized[$key] = sanitize_text_field($value);
            }
        }
        
        return $sanitized;
    }
}

高级功能扩展

5. 智能内容指纹识别

// assets/js/frontend-scripts.js

(function($) {
    'use strict';
    
    class ContentFingerprint {
        constructor() {
            this.postId = window.fcp_post_id || 0;
            this.init();
        }
        
        init() {
            // 为内容生成唯一指纹
            this.generateFingerprint();
            
            // 监听复制事件
            this.monitorCopyEvents();
            
            // 监听打印事件
            this.monitorPrintEvents();
        }
        
        generateFingerprint() {
            const content = document.querySelector('.entry-content') || 
                           document.querySelector('.post-content') || 
                           document.body;
            
            if (!content) return;
            
            // 创建内容哈希
            const textContent = content.textContent.replace(/s+/g, ' ').trim();
            const hash = this.hashString(textContent);
            
            // 将指纹添加到页面
            const fingerprintEl = document.createElement('div');
            fingerprintEl.style.display = 'none';
            fingerprintEl.className = 'fcp-content-fingerprint';
            fingerprintEl.setAttribute('data-fingerprint', hash);
            fingerprintEl.setAttribute('data-post-id', this.postId);
            fingerprintEl.setAttribute('data-timestamp', Date.now());
            
            document.body.appendChild(fingerprintEl);
            
            // 保存到全局变量
            window.fcpFingerprint = hash;
        }
        
        hashString(str) {
            let hash = 0;
            for (let i = 0; i < str.length; i++) {
                const char = str.charCodeAt(i);
                hash = ((hash << 5) - hash) + char;
                hash = hash & hash; // 转换为32位整数
            }
            return hash.toString(36);
        }
        
        monitorCopyEvents() {
            document.addEventListener('copy', (e) => {
                // 获取选中的文本
                const selectedText = window.getSelection().toString();
                
                if (selectedText.length > 100) { // 只记录较长的复制
                    this.logAction('content_copied', {
                        textLength: selectedText.length,
                        fingerprint: window.fcpFingerprint,
                        firstChars: selectedText.substring(0, 50)
                    });
                    
                    // 添加版权信息到剪贴板
                e.clipboardData.setData('text/plain', 
                    selectedText + copyrightNotice
                );
                e.preventDefault();
                
                // 显示复制提示
                this.showNotification('复制成功,已自动添加版权信息');
            }
        });
    }
    
    monitorPrintEvents() {
        // 监听打印前事件
        window.addEventListener('beforeprint', () => {
            this.logAction('print_attempt', {
                fingerprint: window.fcpFingerprint
            });
            
            // 添加打印水印
            this.addPrintWatermark();
        });
    }
    
    logAction(actionType, extraData = {}) {
        const data = {
            action: 'fcp_log_action',
            type: actionType,
            post_id: this.postId,
            fingerprint: window.fcpFingerprint,
            ...extraData
        };
        
        // 使用navigator.sendBeacon确保日志可靠发送
        if (navigator.sendBeacon) {
            const formData = new FormData();
            Object.keys(data).forEach(key => {
                formData.append(key, data[key]);
            });
            navigator.sendBeacon(fcp_ajax.ajax_url, formData);
        } else {
            // 回退到fetch API
            fetch(fcp_ajax.ajax_url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(data)
            });
        }
    }
    
    showNotification(message) {
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #4CAF50;
            color: white;
            padding: 15px 20px;
            border-radius: 4px;
            z-index: 1000000;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            animation: slideIn 0.3s ease;
        `;
        
        notification.innerHTML = `
            <span>${message}</span>
            <button style="
                background: none;
                border: none;
                color: white;
                margin-left: 10px;
                cursor: pointer;
            " onclick="this.parentElement.remove()">×</button>
        `;
        
        document.body.appendChild(notification);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (notification.parentElement) {
                notification.remove();
            }
        }, 3000);
    }
    
    addPrintWatermark() {
        // 创建打印样式
        const printStyle = document.createElement('style');
        printStyle.setAttribute('media', 'print');
        printStyle.textContent = `
            body::before {
                content: "版权声明:本文来自${document.title},未经许可禁止转载";
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%) rotate(-45deg);
                font-size: 40px;
                color: rgba(0,0,0,0.1);
                white-space: nowrap;
                z-index: 999999;
                pointer-events: none;
            }
            
            @page {
                margin: 2cm;
                @top-center {
                    content: "${document.title} - ${window.location.href}";
                    font-size: 10pt;
                    color: #666;
                }
            }
        `;
        
        document.head.appendChild(printStyle);
    }
}

// 初始化
$(document).ready(function() {
    if (typeof fcp_ajax !== 'undefined') {
        new ContentFingerprint();
    }
});

})(jQuery);


### 6. AJAX日志处理

<?php
// 在保护引擎类中添加AJAX处理

class FCP_Protection_Engine {

// ... 之前的代码 ...

public function init() {
    // ... 之前的初始化代码 ...
    
    // 添加AJAX处理
    add_action('wp_ajax_fcp_log_action', array($this, 'handle_action_log'));
    add_action('wp_ajax_nopriv_fcp_log_action', array($this, 'handle_action_log'));
    
    // 本地化脚本
    add_action('wp_enqueue_scripts', array($this, 'localize_scripts'));
}

public function localize_scripts() {
    wp_localize_script('jquery', 'fcp_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('fcp_security_nonce')
    ));
}

public function handle_action_log() {
    // 验证nonce
    if (!isset($_POST['nonce']) || 
        !wp_verify_nonce($_POST['nonce'], 'fcp_security_nonce')) {
        wp_die('安全验证失败');
    }
    
    global $wpdb;
    $table_name = $wpdb->prefix . 'fcp_protection_logs';
    
    $data = array(
        'user_ip' => $this->get_client_ip(),
        'action_type' => sanitize_text_field($_POST['type'] ?? 'unknown'),
        'post_id' => absint($_POST['post_id'] ?? 0),
        'user_agent' => sanitize_text_field($_SERVER['HTTP_USER_AGENT'] ?? ''),
        'created_at' => current_time('mysql')
    );
    
    // 如果有额外数据,存储为meta
    $extra_data = $_POST;
    unset($extra_data['action'], $extra_data['type'], $extra_data['post_id']);
    
    $wpdb->insert($table_name, $data);
    $log_id = $wpdb->insert_id;
    
    // 存储额外数据
    if ($log_id && !empty($extra_data)) {
        foreach ($extra_data as $key => $value) {
            add_metadata('fcp_log', $log_id, 
                sanitize_key($key), 
                sanitize_text_field($value)
            );
        }
    }
    
    // 发送邮件通知(针对可疑行为)
    if (in_array($data['action_type'], ['right_click_attempt', 'print_attempt'])) {
        $this->send_alert_email($data);
    }
    
    wp_send_json_success(array('logged' => true));
}

private function get_client_ip() {
    $ip_keys = array(
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_X_CLUSTER_CLIENT_IP',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'
    );
    
    foreach ($ip_keys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                $ip = trim($ip);
                if (filter_var($ip, FILTER_VALIDATE_IP)) {
                    return $ip;
                }
            }
        }
    }
    
    return '0.0.0.0';
}

private function send_alert_email($data) {
    $admin_email = get_option('admin_email');
    $subject = '版权保护警报:检测到可疑行为';
    
    $message = "检测到可疑的版权侵犯行为:nn";
    $message .= "行为类型:{$data['action_type']}n";
    $message .= "文章ID:{$data['post_id']}n";
    $message .= "IP地址:{$data['user_ip']}n";
    $message .= "时间:{$data['created_at']}n";
    $message .= "用户代理:{$data['user_agent']}nn";
    
    $post = get_post($data['post_id']);
    if ($post) {
        $message .= "文章标题:{$post->post_title}n";
        $message .= "文章链接:" . get_permalink($post->ID) . "n";
    }
    
    $message .= "n请登录管理后台查看详细日志。";
    
    wp_mail($admin_email, $subject, $message);
}

}


## 插件优化与测试

### 7. 性能优化策略

<?php
// includes/class-optimizer.php

class FCP_Optimizer {


public static function optimize_scripts() {
    // 延迟加载非关键脚本
    add_filter('script_loader_tag', function($tag, $handle) {
        if (strpos($handle, 'fcp-') === 0 && $handle !== 'fcp-critical') {
            return str_replace(' src=', ' defer src=', $tag);
        }
        return $tag;
    }, 10, 2);
    
    // 合并CSS文件
    add_action('wp_enqueue_scripts', function() {
        wp_enqueue_style('fcp-combined', false);
        wp_add_inline_style('fcp-combined', self::get_combined_css());
    }, 99);
}

private static function get_combined_css() {
    $css_files = array(
        FCP_PLUGIN_DIR . 'assets/css/frontend.css',
        FCP_PLUGIN_DIR . 'assets/css/watermark.css'
    );
    
    $combined_css = '';
    foreach ($css_files as $file) {
        if (file_exists($file)) {
            $combined_css .= file_get_contents($file);
        }
    }
    
    // 压缩CSS
    $combined_css = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $combined_css);
    $combined_css = str_replace(array("rn", "r", "n", "t", '  ', '    ', '    '), '', $combined_css);
    
    return $combined_css;
}

public static function cache_protection_rules() {
    // 缓存保护规则到transient
    $cached_rules = get_transient('fcp_protection_rules');
    
    if (false === $cached_rules) {
        $rules = self::generate_protection_rules();
        set_transient('fcp_protection_rules', $rules, HOUR_IN_SECONDS);
        return $rules;
    }
    
    return $cached_rules;
}

private static function generate_protection_rules() {
    $settings = get_option('fcp_settings');
    $rules = array();
    
    // 生成基于角色的规则
    $user = wp_get_current_user();
    $user_roles = $user->roles;
    
    $rules['is_excluded'] = false;
    foreach ($user_roles as $role) {
        if (in_array($role, $settings['excluded_user_roles'] ?? array())) {
            $rules['is_excluded'] = true;
            break;
        }
    }
    
    // 生成页面类型规则
    $rules['is_protected_page'] = is_single() || is_page();
    
    // 生成保护级别规则
    $rules['protection_level'] = $settings['protection_level'] ?? 'medium';
    
    return $rules;
}

}


### 8. 测试与调试

<?php
// 测试功能类

class FCP_Tester {


public static function run_tests() {
    $tests = array(
        'right_click_protection' => array(
            'name' => '右键保护测试',
            'callback' => 'test_right_click'
        ),
        'text_selection' => array(
            'name' => '文本选择测试',
            'callback' => 'test_text_selection'
        ),
        'watermark_generation' => array(
            'name' => '水印生成测试',
            'callback' => 'test_watermark'
        ),
        'ajax_logging' => array(
            'name' => 'AJAX日志测试',
            'callback' => 'test_ajax_logging'
        )
    );
    
    $results = array();
    foreach ($tests as $test_id => $test) {
        $results[$test_id] = call_user_func(array(__CLASS__, $test['callback']));
    }
    
    return $results;
}

private static function test_right_click() {
    ob_start();
    ?>
    <script>
    document.addEventListener('contextmenu', function(e) {
        window.rightClickTest = 'blocked';
        e.preventDefault();
    });
    
    // 模拟右键点击
    setTimeout(function() {
        var event = new MouseEvent('contextmenu', {
            bubbles: true,
            cancelable: true
        });
        document.dispatchEvent(event);
        
        // 检查是否被阻止
        if (window.rightClickTest === 'blocked') {
            document.getElementById('right-click-result').innerHTML = 
                '<span style="color:green">✓ 右键保护正常</span>';
        } else {
            document.getElementById('right-click-result').innerHTML = 
                '<span style="color:red">✗ 右键保护失败</span>';
        }
    }, 100);
    </script>
    <div id="right-click-test">
        右键保护测试: <span id="right-click-result">测试中...</span>
    </div>
    <?php
    return ob_get_clean();
}

private static function test_ajax_logging() {
    $nonce = wp_create_nonce('fcp_test_nonce');
    
    ob_start();
    ?>
    <button onclick="testAjaxLogging()">测试AJAX日志</button>
    <div id="ajax-test-result"></div>
    
    <script>
    function testAjaxLogging() {
        fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'fcp_log_action',
                type: 'test_action',
                post_id: <?php echo get_the_ID(); ?>,
                nonce: '<?php echo $nonce; ?>'
            })
        })
        .then(response => response.json())
        .then(data => {
            document.getElementById('ajax-test-result').innerHTML = 
                data.success ? 
                '<span style="color:green">✓ AJAX日志记录成功</span>' :
                '<span style="color:red">✗ AJAX日志记录失败</span>';
        });
    }
    </script>
    <?php
    return ob_get_clean();
}

}

// 添加测试页面到管理后台
add_action('admin_menu', function() {

add_submenu_page(
    'flexible-copyright-protector',
    '插件测试',
    '功能测试',
    'manage_options',
    'fcp-test',
    function() {
        echo '<div class="wrap">';
        echo '<h1>柔性版权保护插件测试</h1>';
        echo '<p>运行以下测试以确保所有功能正常工作:</p>';
        
        $results = FCP_Tester::run_tests();
        
        foreach ($results as $test_id => $test_output) {
            echo '<div class="test-section" style="margin: 20px 0; padding: 20px; border: 1px solid #ddd;">';
            echo $test_output;
            echo '</div>';
        }
        
        echo '</div>';
    }
);

});


## 部署与维护

### 9. 安装与配置指南

1. **安装插件**:
   - 将插件文件夹上传到 `/wp-content/plugins/`
   - 在WordPress后台激活插件
   - 进入"设置" → "版权保护"进行配置

2. **推荐配置**:

// 对于新闻媒体网站
$recommended_settings = array(

   'protection_level' => 'high',
   'watermark_opacity' => 25,
   'enable_right_click_protection' => true,
   'enable_text_selection_protection' => true,
   'excluded_user_roles' => array('administrator', 'editor')

);

// 对于个人博客
$personal_settings = array(

   'protection_level' => 'medium',
   'watermark_opacity' => 15,
   'enable_right_click_protection' => false, // 更友好的设置
   'enable_text_selection_protection' => true

);


3. **性能监控**:
- 定期检查保护日志
- 监控页面加载时间影响
- 根据用户反馈调整保护级别

### 10. 常见问题解决

// 故障排除函数
class FCP_Troubleshooter {


public static function diagnose_issues() {
    $issues = array();
    
    // 检查AJAX是否工作
    if (!self::test_ajax()) {
        $issues[] = array(
            'level' => 'error',
            'message' => 'AJAX功能可能被其他插件或主题阻止',
            'solution' => '尝试禁用其他插件逐一排查'
        );
    }
    
    // 检查数据库表
    if (!self::check_database_tables()) {
        $issues[] = array(
            'level' => 'warning',
            'message' => '数据库表可能损坏',
            'solution' => '尝试重新激活插件以重建表结构'
        );
    }
    
    // 检查文件权限
    if (!self::check_file_permissions()) {
        $issues[] = array(
            'level' => 'warning',
            'message' => '插件文件权限可能不正确',
            'solution' => '确保插件目录权限为755,文件权限为644'
        );
    }
    
    return $issues;
}

private static function test_ajax() {
    $response = wp_remote_post(admin_url('admin-ajax.php'), array(
        'body' => array('action' => 'fcp_test_ajax')
    ));
    
    return !is_wp_error($response);
}

}


## 结语

通过本教程,您已经学会了如何开发一个完整的WordPress柔性内容版权保护插件。这个插件不仅提供了基本的右键禁用和文本选择保护,还实现了智能水印、内容指纹识别和详细的行为日志记录。

**关键要点总结**:

1. **柔性设计**:插件提供了多种保护级别,可以根据网站类型灵活配置
2. **用户体验**:在保护版权的同时,尽量减少对正常用户的干扰
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/6008.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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