首页 / 应用软件 / 手把手教学,为WordPress集成智能化的网站内容合规性检查工具

手把手教学,为WordPress集成智能化的网站内容合规性检查工具

手把手教学:为WordPress集成智能化的网站内容合规性检查工具

引言:内容合规性检查在数字时代的重要性

在当今数字化时代,网站内容合规性已成为网站运营者不可忽视的重要议题。随着全球各地对网络内容监管的加强,从数据隐私保护到版权管理,从敏感信息过滤到行业规范遵守,网站内容合规性检查已成为确保网站安全运营、避免法律风险的关键环节。

对于使用WordPress构建的网站而言,作为全球最流行的内容管理系统,它承载着互联网上超过40%的网站内容。然而,WordPress本身并未内置全面的内容合规性检查功能,这给网站管理员带来了不小的挑战。手动检查每一条发布的内容不仅耗时耗力,而且容易遗漏潜在问题。

本文将详细介绍如何通过WordPress代码二次开发,集成智能化的网站内容合规性检查工具,帮助网站管理员自动化完成内容审核,确保网站内容符合法律法规和行业标准。

第一部分:理解WordPress内容合规性检查的核心需求

1.1 内容合规性的多维度考量

网站内容合规性检查涉及多个维度,主要包括:

  • 法律法规合规性:确保内容不违反国家法律法规,不包含违法信息
  • 版权合规性:检查内容是否侵犯他人知识产权
  • 敏感信息过滤:识别并处理个人隐私信息、商业秘密等敏感内容
  • 行业特定规范:根据不同行业要求检查内容合规性(如医疗、金融等行业)
  • 平台政策遵守:确保内容符合社交媒体平台、搜索引擎等的要求

1.2 WordPress内容发布流程分析

要有效集成合规性检查工具,首先需要理解WordPress的内容发布流程:

  1. 内容创建与编辑阶段
  2. 预览与保存草稿阶段
  3. 发布与更新阶段
  4. 已发布内容的定期检查阶段

理想的合规性检查工具应在这些关键节点介入,提供实时或批量的内容检查功能。

1.3 现有解决方案的局限性

目前市场上有一些WordPress合规性检查插件,但它们往往存在以下问题:

  • 功能单一,无法满足多维度检查需求
  • 缺乏智能化,误报率较高
  • 定制化程度低,难以适应特定行业需求
  • 性能影响较大,拖慢网站速度
  • 数据隐私保护不足,可能将内容发送到第三方服务器

因此,通过代码二次开发实现定制化的合规性检查工具,成为许多专业网站的选择。

第二部分:构建WordPress合规性检查工具的技术基础

2.1 WordPress插件开发基础

在开始开发合规性检查工具之前,需要掌握以下WordPress开发基础知识:

  • WordPress插件结构:了解插件文件组织方式、主文件编写规范
  • 动作钩子(Action Hooks)和过滤器钩子(Filter Hooks):这是WordPress扩展功能的核心机制
  • 自定义数据库表:用于存储检查结果和历史记录
  • WordPress REST API:为前后端交互提供接口
  • 安全性最佳实践:包括数据验证、权限检查、非ce验证等

2.2 合规性检查的技术实现方案

合规性检查可以通过以下技术方案实现:

  1. 本地规则引擎:基于正则表达式和关键词库的规则匹配
  2. 机器学习模型:使用预训练的NLP模型识别敏感内容
  3. 第三方API集成:调用专业合规性检查服务的API
  4. 混合方案:结合本地规则和云端智能检查

考虑到性能和数据隐私,我们建议采用混合方案,将基础检查放在本地,复杂分析通过API完成。

2.3 开发环境搭建

开始开发前,需要准备以下环境:

  • 本地WordPress开发环境(推荐使用Local by Flywheel或Docker)
  • 代码编辑器(VS Code、PHPStorm等)
  • 版本控制系统(Git)
  • PHP 7.4+和MySQL 5.6+
  • 必要的调试工具(Query Monitor、Debug Bar等)

第三部分:手把手创建WordPress合规性检查插件

3.1 插件基础结构创建

首先,创建插件的基本文件结构:

wp-content/plugins/content-compliance-checker/
├── content-compliance-checker.php      # 主插件文件
├── includes/
│   ├── class-compliance-checker.php    # 主功能类
│   ├── class-rule-engine.php           # 规则引擎类
│   ├── class-api-handler.php           # API处理器类
│   └── class-db-manager.php            # 数据库管理类
├── admin/
│   ├── css/
│   │   └── admin-style.css             # 后台样式
│   ├── js/
│   │   └── admin-script.js             # 后台脚本
│   └── partials/
│       └── admin-display.php           # 后台界面
├── public/
│   ├── css/
│   │   └── public-style.css            # 前台样式
│   └── js/
│       └── public-script.js            # 前台脚本
├── assets/
│   └── images/                         # 图片资源
└── languages/                          # 国际化文件

3.2 主插件文件编写

创建主插件文件content-compliance-checker.php

<?php
/**
 * Plugin Name: 内容合规性检查工具
 * Plugin URI:  https://yourwebsite.com/content-compliance-checker
 * Description: 智能化的WordPress网站内容合规性检查工具
 * Version:     1.0.0
 * Author:      你的名字
 * License:     GPL v2 or later
 * Text Domain: content-compliance-checker
 */

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

// 定义插件常量
define('CCC_VERSION', '1.0.0');
define('CCC_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CCC_PLUGIN_URL', plugin_dir_url(__FILE__));
define('CCC_PLUGIN_BASENAME', plugin_basename(__FILE__));

// 自动加载类文件
spl_autoload_register(function ($class_name) {
    $prefix = 'CCC_';
    $base_dir = CCC_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_once $file;
    }
});

// 初始化插件
function ccc_init_plugin() {
    // 检查WordPress版本
    if (version_compare(get_bloginfo('version'), '5.0', '<')) {
        add_action('admin_notices', function() {
            echo '<div class="notice notice-error"><p>';
            echo __('内容合规性检查工具需要WordPress 5.0或更高版本。', 'content-compliance-checker');
            echo '</p></div>';
        });
        return;
    }
    
    // 实例化主类
    $compliance_checker = new CCC_Compliance_Checker();
    $compliance_checker->init();
}

add_action('plugins_loaded', 'ccc_init_plugin');

// 激活和停用钩子
register_activation_hook(__FILE__, 'ccc_activate_plugin');
register_deactivation_hook(__FILE__, 'ccc_deactivate_plugin');

function ccc_activate_plugin() {
    require_once CCC_PLUGIN_DIR . 'includes/class-db-manager.php';
    CCC_DB_Manager::create_tables();
    
    // 设置默认选项
    $default_options = array(
        'enable_auto_check' => true,
        'check_on_publish' => true,
        'check_on_update' => true,
        'check_on_draft' => false,
        'block_on_violation' => true,
        'notify_admin' => true,
        'sensitivity_level' => 'medium',
        'api_key' => '',
        'api_service' => 'local',
    );
    
    add_option('ccc_settings', $default_options);
    
    // 创建默认规则
    ccc_create_default_rules();
}

function ccc_deactivate_plugin() {
    // 清理临时数据
    wp_clear_scheduled_hook('ccc_daily_compliance_check');
}

function ccc_create_default_rules() {
    $default_rules = array(
        array(
            'rule_name' => '敏感词检测',
            'rule_type' => 'keyword',
            'rule_pattern' => '赌博|毒品|色情|暴力|恐怖主义',
            'rule_action' => 'block',
            'rule_priority' => 10,
            'is_active' => 1
        ),
        array(
            'rule_name' => '电话号码检测',
            'rule_type' => 'regex',
            'rule_pattern' => '/bd{3}[-.]?d{3}[-.]?d{4}b/',
            'rule_action' => 'flag',
            'rule_priority' => 5,
            'is_active' => 1
        ),
        array(
            'rule_name' => '邮箱地址检测',
            'rule_type' => 'regex',
            'rule_pattern' => '/b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}b/',
            'rule_action' => 'flag',
            'rule_priority' => 5,
            'is_active' => 1
        )
    );
    
    $existing_rules = get_option('ccc_rules', array());
    if (empty($existing_rules)) {
        update_option('ccc_rules', $default_rules);
    }
}

3.3 主功能类实现

创建includes/class-compliance-checker.php

<?php
class CCC_Compliance_Checker {
    
    private $rule_engine;
    private $api_handler;
    private $db_manager;
    
    public function __construct() {
        $this->rule_engine = new CCC_Rule_Engine();
        $this->api_handler = new CCC_API_Handler();
        $this->db_manager = new CCC_DB_Manager();
    }
    
    public function init() {
        // 添加内容检查钩子
        add_filter('wp_insert_post_data', array($this, 'check_post_content'), 99, 2);
        add_action('save_post', array($this, 'check_post_on_save'), 10, 3);
        add_action('publish_post', array($this, 'check_post_on_publish'), 10, 2);
        
        // 添加上传文件检查
        add_filter('wp_handle_upload_prefilter', array($this, 'check_uploaded_file'));
        
        // 添加评论检查
        add_filter('preprocess_comment', array($this, 'check_comment_content'));
        
        // 添加后台管理界面
        if (is_admin()) {
            add_action('admin_menu', array($this, 'add_admin_menu'));
            add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
            add_action('add_meta_boxes', array($this, 'add_compliance_meta_box'));
        }
        
        // 添加定期检查任务
        add_action('ccc_daily_compliance_check', array($this, 'run_daily_compliance_check'));
        
        if (!wp_next_scheduled('ccc_daily_compliance_check')) {
            wp_schedule_event(time(), 'daily', 'ccc_daily_compliance_check');
        }
        
        // 初始化REST API端点
        add_action('rest_api_init', array($this, 'register_rest_routes'));
    }
    
    public function check_post_content($data, $postarr) {
        $settings = get_option('ccc_settings');
        
        // 检查是否启用自动检查
        if (!$settings['enable_auto_check']) {
            return $data;
        }
        
        // 检查草稿(如果设置允许)
        if ($data['post_status'] === 'draft' && !$settings['check_on_draft']) {
            return $data;
        }
        
        $post_id = isset($postarr['ID']) ? $postarr['ID'] : 0;
        $content_to_check = $data['post_content'] . ' ' . $data['post_title'];
        
        // 执行合规性检查
        $result = $this->perform_compliance_check($content_to_check, $post_id);
        
        if ($result['has_violation']) {
            if ($settings['block_on_violation']) {
                // 阻止发布并显示错误
                add_filter('redirect_post_location', function($location) use ($result) {
                    return add_query_arg('ccc_error', urlencode($result['message']), $location);
                });
                
                // 将文章状态改为草稿
                $data['post_status'] = 'draft';
            }
            
            // 记录违规
            $this->db_manager->log_violation(array(
                'post_id' => $post_id,
                'violation_type' => $result['violation_type'],
                'violation_details' => json_encode($result['violations']),
                'check_date' => current_time('mysql')
            ));
            
            // 发送通知(如果启用)
            if ($settings['notify_admin']) {
                $this->send_notification($post_id, $result);
            }
        }
        
        return $data;
    }
    
    public function check_post_on_save($post_id, $post, $update) {
        // 跳过自动保存和修订
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        if (wp_is_post_revision($post_id)) {
            return;
        }
        
        // 检查用户权限
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        $settings = get_option('ccc_settings');
        
        // 检查更新(如果设置允许)
        if ($update && !$settings['check_on_update']) {
            return;
        }
        
        // 如果文章已发布,执行额外检查
        if ($post->post_status === 'publish') {
            $this->perform_compliance_check($post->post_content . ' ' . $post->post_title, $post_id);
        }
    }
    
    public function check_post_on_publish($post_id, $post) {
        $settings = get_option('ccc_settings');
        
        if (!$settings['check_on_publish']) {
            return;
        }
        
        $result = $this->perform_compliance_check($post->post_content . ' ' . $post->post_title, $post_id);
        
        if ($result['has_violation']) {
            // 记录发布时的违规
            update_post_meta($post_id, '_ccc_publish_violation', $result);
        }
    }
    
    public function check_uploaded_file($file) {
        $settings = get_option('ccc_settings');
        
        if (!$settings['enable_auto_check']) {
            return $file;
        }
        
        // 检查文件类型
        $allowed_types = array('jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx');
        $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if (!in_array($file_ext, $allowed_types)) {
            $file['error'] = '不支持的文件类型。只允许上传:' . implode(', ', $allowed_types);
            return $file;
        }
        
        // 检查文件内容(如果是图片,可以检查EXIF数据等)
        if (in_array($file_ext, array('jpg', 'jpeg', 'png', 'gif'))) {
            // 这里可以添加图片内容检查逻辑
            // 例如检查图片是否包含敏感内容
        }
        
        return $file;
    }
    
    public function check_comment_content($commentdata) {
        $settings = get_option('ccc_settings');
        
        if (!$settings['enable_auto_check']) {
            return $commentdata;
        }
        
        $content_to_check = $commentdata['comment_content'];
        $result = $this->perform_compliance_check($content_to_check, 0, 'comment');
        
        if ($result['has_violation']) {
            if ($settings['block_on_violation']) {
                wp_die(__('您的评论包含不合规内容,无法提交。', 'content-compliance-checker'));
            } else {
                // 标记评论为待审核
                $commentdata['comment_approved'] = 0;
                add_comment_meta($commentdata['comment_ID'], '_ccc_flagged', true, true);
            }
        }
        
        return $commentdata;
    }
    
    private function perform_compliance_check($content, $post_id = 0, $content_type = 'post') {
        $result = array(
            'has_violation' => false,
            'violation_type' => '',
            'violations' => array(),
            'message' => ''
        );
        
        // 1. 使用本地规则引擎检查
        $rule_violations = $this->rule_engine->check_content($content);
        
        if (!empty($rule_violations)) {
            $result['has_violation'] = true;
            $result['violation_type'] = 'rule_violation';
            $result['violations'] = array_merge($result['violations'], $rule_violations);
        }
        
        // 2. 使用API检查(如果配置了API)
        $settings = get_option('ccc_settings');
        
        if (!empty($settings['api_key']) && $settings['api_service'] !== 'local') {
            $api_result = $this->api_handler->check_content($content, $content_type);
            
            if ($api_result['has_violation']) {
                $result['has_violation'] = true;
                $result['violation_type'] = $api_result['violation_type'];
                $result['violations'] = array_merge($result['violations'], $api_result['violations']);
            }
        }
        
        // 3. 生成用户友好的消息
        if ($result['has_violation']) {
            $violation_count = count($result['violations']);
            $result['message'] = sprintf(
                __('内容包含%d处不合规问题:', 'content-compliance-checker'),

$violation_count

        );
        
        foreach ($result['violations'] as $violation) {
            $result['message'] .= "n- " . $violation['description'];
        }
    }
    
    // 4. 记录检查结果
    $this->db_manager->log_check_result(array(
        'post_id' => $post_id,
        'content_type' => $content_type,
        'check_result' => json_encode($result),
        'check_date' => current_time('mysql')
    ));
    
    return $result;
}

private function send_notification($post_id, $check_result) {
    $admin_email = get_option('admin_email');
    $post_title = get_the_title($post_id);
    $post_edit_url = admin_url('post.php?post=' . $post_id . '&action=edit');
    
    $subject = sprintf(__('[合规性警报] 文章 "%s" 包含不合规内容', 'content-compliance-checker'), $post_title);
    
    $message = sprintf(__('文章 "%s" 在发布时检测到不合规内容。', 'content-compliance-checker'), $post_title) . "nn";
    $message .= __('检测到的问题:', 'content-compliance-checker') . "n";
    
    foreach ($check_result['violations'] as $violation) {
        $message .= '- ' . $violation['description'] . "n";
    }
    
    $message .= "n" . __('文章编辑链接:', 'content-compliance-checker') . "n";
    $message .= $post_edit_url . "nn";
    $message .= __('此邮件由内容合规性检查工具自动发送。', 'content-compliance-checker');
    
    wp_mail($admin_email, $subject, $message);
}

public function add_admin_menu() {
    add_menu_page(
        __('内容合规性检查', 'content-compliance-checker'),
        __('合规性检查', 'content-compliance-checker'),
        'manage_options',
        'ccc-dashboard',
        array($this, 'display_dashboard_page'),
        'dashicons-shield',
        30
    );
    
    add_submenu_page(
        'ccc-dashboard',
        __('合规性设置', 'content-compliance-checker'),
        __('设置', 'content-compliance-checker'),
        'manage_options',
        'ccc-settings',
        array($this, 'display_settings_page')
    );
    
    add_submenu_page(
        'ccc-dashboard',
        __('检查规则', 'content-compliance-checker'),
        __('规则管理', 'content-compliance-checker'),
        'manage_options',
        'ccc-rules',
        array($this, 'display_rules_page')
    );
    
    add_submenu_page(
        'ccc-dashboard',
        __('检查记录', 'content-compliance-checker'),
        __('检查记录', 'content-compliance-checker'),
        'manage_options',
        'ccc-logs',
        array($this, 'display_logs_page')
    );
    
    add_submenu_page(
        'ccc-dashboard',
        __('批量检查', 'content-compliance-checker'),
        __('批量检查', 'content-compliance-checker'),
        'manage_options',
        'ccc-bulk-check',
        array($this, 'display_bulk_check_page')
    );
}

public function display_dashboard_page() {
    include CCC_PLUGIN_DIR . 'admin/partials/dashboard.php';
}

public function display_settings_page() {
    include CCC_PLUGIN_DIR . 'admin/partials/settings.php';
}

public function display_rules_page() {
    include CCC_PLUGIN_DIR . 'admin/partials/rules.php';
}

public function display_logs_page() {
    include CCC_PLUGIN_DIR . 'admin/partials/logs.php';
}

public function display_bulk_check_page() {
    include CCC_PLUGIN_DIR . 'admin/partials/bulk-check.php';
}

public function enqueue_admin_scripts($hook) {
    if (strpos($hook, 'ccc-') === false) {
        return;
    }
    
    wp_enqueue_style(
        'ccc-admin-style',
        CCC_PLUGIN_URL . 'admin/css/admin-style.css',
        array(),
        CCC_VERSION
    );
    
    wp_enqueue_script(
        'ccc-admin-script',
        CCC_PLUGIN_URL . 'admin/js/admin-script.js',
        array('jquery', 'wp-util'),
        CCC_VERSION,
        true
    );
    
    wp_localize_script('ccc-admin-script', 'ccc_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('ccc_ajax_nonce')
    ));
}

public function add_compliance_meta_box() {
    $post_types = get_post_types(array('public' => true), 'names');
    
    foreach ($post_types as $post_type) {
        add_meta_box(
            'ccc-compliance-meta-box',
            __('内容合规性检查', 'content-compliance-checker'),
            array($this, 'render_compliance_meta_box'),
            $post_type,
            'side',
            'high'
        );
    }
}

public function render_compliance_meta_box($post) {
    $check_results = $this->db_manager->get_post_check_results($post->ID);
    
    echo '<div id="ccc-compliance-status">';
    
    if (empty($check_results)) {
        echo '<p>' . __('尚未检查此内容。', 'content-compliance-checker') . '</p>';
        echo '<button type="button" class="button button-secondary" id="ccc-check-now">' . __('立即检查', 'content-compliance-checker') . '</button>';
    } else {
        $latest_result = end($check_results);
        $result_data = json_decode($latest_result->check_result, true);
        
        if ($result_data['has_violation']) {
            echo '<div class="ccc-alert ccc-alert-error">';
            echo '<p><strong>' . __('检测到不合规内容', 'content-compliance-checker') . '</strong></p>';
            echo '<ul>';
            foreach ($result_data['violations'] as $violation) {
                echo '<li>' . esc_html($violation['description']) . '</li>';
            }
            echo '</ul>';
            echo '</div>';
        } else {
            echo '<div class="ccc-alert ccc-alert-success">';
            echo '<p><strong>' . __('内容合规', 'content-compliance-checker') . '</strong></p>';
            echo '<p>' . sprintf(__('最后检查时间:%s', 'content-compliance-checker'), $latest_result->check_date) . '</p>';
            echo '</div>';
        }
        
        echo '<button type="button" class="button button-secondary" id="ccc-recheck-now">' . __('重新检查', 'content-compliance-checker') . '</button>';
    }
    
    echo '</div>';
}

public function run_daily_compliance_check() {
    // 获取所有已发布的文章
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'fields' => 'ids'
    );
    
    $post_ids = get_posts($args);
    
    foreach ($post_ids as $post_id) {
        $post = get_post($post_id);
        $this->perform_compliance_check($post->post_content . ' ' . $post->post_title, $post_id);
    }
    
    // 记录批量检查完成
    $this->db_manager->log_bulk_check(array(
        'check_type' => 'daily',
        'items_checked' => count($post_ids),
        'check_date' => current_time('mysql')
    ));
}

public function register_rest_routes() {
    register_rest_route('ccc/v1', '/check-content', array(
        'methods' => 'POST',
        'callback' => array($this, 'rest_check_content'),
        'permission_callback' => function() {
            return current_user_can('edit_posts');
        },
        'args' => array(
            'content' => array(
                'required' => true,
                'validate_callback' => function($param) {
                    return is_string($param) && !empty($param);
                }
            ),
            'content_type' => array(
                'required' => false,
                'default' => 'post'
            )
        )
    ));
    
    register_rest_route('ccc/v1', '/get-stats', array(
        'methods' => 'GET',
        'callback' => array($this, 'rest_get_stats'),
        'permission_callback' => function() {
            return current_user_can('manage_options');
        }
    ));
}

public function rest_check_content($request) {
    $content = $request->get_param('content');
    $content_type = $request->get_param('content_type');
    
    $result = $this->perform_compliance_check($content, 0, $content_type);
    
    return rest_ensure_response($result);
}

public function rest_get_stats() {
    $stats = $this->db_manager->get_compliance_stats();
    
    return rest_ensure_response($stats);
}

}


### 3.4 规则引擎类实现

创建`includes/class-rule-engine.php`:

<?php
class CCC_Rule_Engine {


private $rules;

public function __construct() {
    $this->load_rules();
}

private function load_rules() {
    $this->rules = get_option('ccc_rules', array());
    
    // 按优先级排序
    usort($this->rules, function($a, $b) {
        return $b['rule_priority'] - $a['rule_priority'];
    });
}

public function check_content($content) {
    $violations = array();
    
    foreach ($this->rules as $rule) {
        if (!$rule['is_active']) {
            continue;
        }
        
        $matches = $this->apply_rule($rule, $content);
        
        if (!empty($matches)) {
            $violations[] = array(
                'rule_id' => $rule['rule_id'] ?? uniqid(),
                'rule_name' => $rule['rule_name'],
                'rule_type' => $rule['rule_type'],
                'matches' => $matches,
                'description' => $this->generate_violation_description($rule, $matches)
            );
        }
    }
    
    return $violations;
}

private function apply_rule($rule, $content) {
    $matches = array();
    
    switch ($rule['rule_type']) {
        case 'keyword':
            $keywords = explode('|', $rule['rule_pattern']);
            foreach ($keywords as $keyword) {
                $keyword = trim($keyword);
                if (stripos($content, $keyword) !== false) {
                    $matches[] = array(
                        'type' => 'keyword',
                        'value' => $keyword,
                        'position' => stripos($content, $keyword)
                    );
                }
            }
            break;
            
        case 'regex':
            if (@preg_match_all($rule['rule_pattern'], $content, $regex_matches, PREG_OFFSET_CAPTURE)) {
                foreach ($regex_matches[0] as $match) {
                    $matches[] = array(
                        'type' => 'regex',
                        'value' => $match[0],
                        'position' => $match[1]
                    );
                }
            }
            break;
            
        case 'ml':
            // 机器学习规则 - 可以集成TensorFlow PHP或调用外部API
            // 这里是一个简单的实现示例
            $sentiment = $this->analyze_sentiment($content);
            if ($sentiment['score'] < -0.5) { // 非常负面的情绪
                $matches[] = array(
                    'type' => 'sentiment',
                    'value' => $sentiment['label'],
                    'score' => $sentiment['score']
                );
            }
            break;
    }
    
    return $matches;
}

private function analyze_sentiment($text) {
    // 简化的情感分析
    $negative_words = array('糟糕', '差劲', '讨厌', '恶心', '垃圾', '骗子', '诈骗');
    $positive_words = array('优秀', '很好', '喜欢', '满意', '推荐', '超值', '完美');
    
    $negative_count = 0;
    $positive_count = 0;
    $total_words = str_word_count($text);
    
    if ($total_words === 0) {
        return array('label' => '中性', 'score' => 0);
    }
    
    foreach ($negative_words as $word) {
        $negative_count += substr_count($text, $word);
    }
    
    foreach ($positive_words as $word) {
        $positive_count += substr_count($text, $word);
    }
    
    $score = ($positive_count - $negative_count) / max(1, $total_words);
    
    if ($score > 0.1) {
        $label = '积极';
    } elseif ($score < -0.1) {
        $label = '消极';
    } else {
        $label = '中性';
    }
    
    return array('label' => $label, 'score' => $score);
}

private function generate_violation_description($rule, $matches) {
    $description = sprintf(__('违反规则 "%s"', 'content-compliance-checker'), $rule['rule_name']);
    
    if (count($matches) <= 3) {
        $description .= ':';
        $match_values = array();
        foreach ($matches as $match) {
            $match_values[] = $match['value'];
        }
        $description .= implode('、', array_unique($match_values));
    } else {
        $description .= sprintf(__('(发现%d处匹配)', 'content-compliance-checker'), count($matches));
    }
    
    return $description;
}

public function add_rule($rule_data) {
    $rule_id = uniqid();
    $rule_data['rule_id'] = $rule_id;
    $rule_data['is_active'] = $rule_data['is_active'] ?? 1;
    
    $this->rules[] = $rule_data;
    $this->save_rules();
    
    return $rule_id;
}

public function update_rule($rule_id, $rule_data) {
    foreach ($this->rules as &$rule) {
        if ($rule['rule_id'] === $rule_id) {
            $rule = array_merge($rule, $rule_data);
            $this->save_rules();
            return true;
        }
    }
    
    return false;
}

public function delete_rule($rule_id) {
    $this->rules = array_filter($this->rules, function($rule) use ($rule_id) {
        return $rule['rule_id'] !== $rule_id;
    });
    
    $this->save_rules();
    return true;
}

public function get_rules() {
    return $this->rules;
}

public function get_rule($rule_id) {
    foreach ($this->rules as $rule) {
        if ($rule['rule_id'] === $rule_id) {
            return $rule;
        }
    }
    
    return null;
}

private function save_rules() {
    update_option('ccc_rules', $this->rules);
}

}


### 3.5 API处理器类实现

创建`includes/class-api-handler.php`:

<?php
class CCC_API_Handler {


private $api_services = array(
    'google_safe_browsing' => array(
        'name' => 'Google Safe Browsing',
        'endpoint' => 'https://safebrowsing.googleapis.com/v4/threatMatches:find',
        'requires_key' => true
    ),
    'microsoft_presidio' => array(
        'name' => 'Microsoft Presidio',
        'endpoint' => 'https://presidio.azurewebsites.net/analyze',
        'requires_key' => false
    ),
    'openai_moderation' => array(
        'name' => 'OpenAI Moderation',
        'endpoint' => 'https://api.openai.com/v1/moderations',
        'requires_key' => true
    )
);

public function check_content($content, $content_type = 'post') {
    $settings = get_option('ccc_settings');
    $api_service = $settings['api_service'];
    $api_key = $settings['api_key'];
    
    if ($api_service === 'local' || empty($api_key)) {
        return array('has_violation' => false, 'violations' => array());
    }
    
    if (!isset($this->api_services[$api_service])) {
        return array(
            'has_violation' => false,
            'violations' => array(),
            'error' => '未知的API服务'
        );
    }
    
    $service_config = $this->api_services[$api_service];
    
    try {
        switch ($api_service) {
            case 'google_safe_browsing':
                return $this->check_google_safe_browsing($content, $api_key);
                
            case 'openai_moderation':
                return $this->check_openai_moderation($content, $api_key);
                
            case 'microsoft_presidio':
                return $this->check_microsoft_presidio($content);
                
            default:
                return array('has_violation' => false, 'violations' => array());
        }
    } catch (Exception $e) {
        error_log('合规性检查API错误:' . $e->getMessage());
        return array(
            'has_violation' => false,
            'violations' => array(),
            'error' => 'API检查失败:' . $e->getMessage()
        );
    }
}

private function check_google_safe_browsing($content, $api_key) {
    $urls = $this->extract_urls($content);
    
    if (empty($urls)) {
        return array('has_violation' => false, 'violations' => array());
    }
    
    $client_id = 'wordpress-compliance-checker';
    $client_version = '1.0';
    
    $threat_entries = array();
    foreach ($urls as $url) {
        $threat_entries[] = array('url' => $url);
    }
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5156.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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