首页 / 教程文章 / WordPress文创项目柔性投资回报分析插件开发详解

WordPress文创项目柔性投资回报分析插件开发详解

WordPress文创项目柔性投资回报分析插件开发详解

引言:文创项目投资分析的特殊性

在文化创意产业蓬勃发展的今天,越来越多的投资者开始关注文创项目的投资价值。然而,文创项目与传统投资项目有着本质区别——其回报不仅体现在财务收益上,还包括品牌价值、文化影响力、社会效益等"柔性回报"。传统的投资回报率(ROI)计算方法难以全面评估这类项目的综合价值。

为此,我们开发了一款专门针对WordPress平台的文创项目柔性投资回报分析插件,帮助文创项目管理者、投资者和策展人全面评估项目价值。本文将详细介绍该插件的开发过程、功能实现和技术要点。

插件架构设计

1.1 核心功能模块

<?php
/**
 * 文创项目柔性投资回报分析插件 - 主文件
 * Plugin Name: 文创柔性投资分析器
 * Description: 用于分析文创项目柔性投资回报的WordPress插件
 * Version: 1.0.0
 * Author: 文创科技团队
 */

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

// 定义插件常量
define('CULTURAL_ROI_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('CULTURAL_ROI_PLUGIN_URL', plugin_dir_url(__FILE__));

// 主插件类
class Cultural_ROI_Analyzer {
    
    private $db; // 数据库操作对象
    private $calculation_engine; // 计算引擎
    
    public function __construct() {
        // 初始化数据库连接
        $this->init_database();
        
        // 初始化计算引擎
        $this->calculation_engine = new ROI_Calculation_Engine();
        
        // 注册WordPress钩子
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts'));
        
        // 注册短代码
        add_shortcode('cultural_roi_calculator', array($this, 'roi_calculator_shortcode'));
    }
    
    // 初始化数据库
    private function init_database() {
        global $wpdb;
        $this->db = $wpdb;
        $this->create_tables();
    }
    
    // 创建数据表
    private function create_tables() {
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        
        $charset_collate = $this->db->get_charset_collate();
        
        // 项目数据表
        $projects_table = $this->db->prefix . 'cultural_projects';
        $sql = "CREATE TABLE IF NOT EXISTS $projects_table (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            project_name varchar(255) NOT NULL,
            description text,
            initial_investment decimal(15,2) DEFAULT 0.00,
            duration_months int DEFAULT 12,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id)
        ) $charset_collate;";
        dbDelta($sql);
        
        // 回报指标表
        $metrics_table = $this->db->prefix . 'roi_metrics';
        $sql = "CREATE TABLE IF NOT EXISTS $metrics_table (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            project_id mediumint(9) NOT NULL,
            metric_type varchar(100) NOT NULL,
            metric_value decimal(10,2) NOT NULL,
            weight decimal(3,2) DEFAULT 1.00,
            recorded_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            FOREIGN KEY (project_id) REFERENCES $projects_table(id) ON DELETE CASCADE
        ) $charset_collate;";
        dbDelta($sql);
    }
    
    // 更多方法将在下文展开...
}
?>

1.2 数据库设计要点

本插件采用模块化数据库设计,主要包含以下核心表:

  • cultural_projects: 存储文创项目基本信息
  • roi_metrics: 存储各类回报指标数据
  • roi_calculations: 存储计算结果
  • metric_templates: 存储指标模板

柔性回报指标体系实现

2.1 指标分类与权重系统

<?php
/**
 * 柔性回报指标管理类
 */
class Flexible_Metrics_Manager {
    
    // 定义指标类别
    private $metric_categories = array(
        'financial' => array(
            'name' => '财务回报',
            'weight' => 0.4,
            'metrics' => array(
                'direct_revenue' => '直接收入',
                'indirect_revenue' => '间接收入',
                'cost_savings' => '成本节约'
            )
        ),
        'brand' => array(
            'name' => '品牌价值',
            'weight' => 0.25,
            'metrics' => array(
                'brand_awareness' => '品牌知名度',
                'brand_reputation' => '品牌美誉度',
                'social_media_engagement' => '社交媒体参与度'
            )
        ),
        'cultural' => array(
            'name' => '文化影响',
            'weight' => 0.2,
            'metrics' => array(
                'cultural_preservation' => '文化传承',
                'innovation_index' => '创新指数',
                'aesthetic_value' => '美学价值'
            )
        ),
        'social' => array(
            'name' => '社会效益',
            'weight' => 0.15,
            'metrics' => array(
                'community_engagement' => '社区参与',
                'education_value' => '教育价值',
                'employment_created' => '就业创造'
            )
        )
    );
    
    /**
     * 计算综合柔性回报指数
     * @param int $project_id 项目ID
     * @return array 计算结果
     */
    public function calculate_flexible_roi_index($project_id) {
        global $wpdb;
        
        $results = array(
            'category_scores' => array(),
            'total_score' => 0,
            'interpretation' => ''
        );
        
        // 获取项目所有指标数据
        $metrics_table = $wpdb->prefix . 'roi_metrics';
        $metrics = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT metric_type, metric_value, weight FROM $metrics_table WHERE project_id = %d",
                $project_id
            ),
            ARRAY_A
        );
        
        // 按类别计算得分
        foreach ($this->metric_categories as $category_id => $category) {
            $category_score = 0;
            $metric_count = 0;
            
            foreach ($metrics as $metric) {
                if (isset($category['metrics'][$metric['metric_type']])) {
                    // 标准化处理:将原始值转换为0-100分
                    $normalized_value = $this->normalize_metric_value(
                        $metric['metric_value'], 
                        $metric['metric_type']
                    );
                    
                    // 应用权重
                    $weighted_value = $normalized_value * $metric['weight'];
                    $category_score += $weighted_value;
                    $metric_count++;
                }
            }
            
            if ($metric_count > 0) {
                $category_average = $category_score / $metric_count;
                $weighted_category_score = $category_average * $category['weight'];
                
                $results['category_scores'][$category_id] = array(
                    'raw_score' => $category_average,
                    'weighted_score' => $weighted_category_score,
                    'category_name' => $category['name']
                );
                
                $results['total_score'] += $weighted_category_score;
            }
        }
        
        // 生成解读
        $results['interpretation'] = $this->generate_interpretation($results['total_score']);
        
        return $results;
    }
    
    /**
     * 标准化指标值
     */
    private function normalize_metric_value($raw_value, $metric_type) {
        // 根据指标类型应用不同的标准化方法
        $normalization_methods = array(
            'direct_revenue' => 'log_normalization',
            'brand_awareness' => 'percentage_normalization',
            'cultural_preservation' => 'expert_scoring_normalization'
        );
        
        $method = isset($normalization_methods[$metric_type]) ? 
                 $normalization_methods[$metric_type] : 'linear_normalization';
        
        return $this->$method($raw_value);
    }
    
    /**
     * 对数标准化(适用于收入类指标)
     */
    private function log_normalization($value) {
        return min(100, log10($value + 1) * 20);
    }
    
    // 更多标准化方法...
}
?>

可视化分析模块开发

3.1 图表生成与数据可视化

// assets/js/roi-visualization.js
/**
 * 文创项目ROI可视化模块
 */
class ROIVisualization {
    constructor(containerId, projectData) {
        this.container = document.getElementById(containerId);
        this.projectData = projectData;
        this.charts = {};
    }
    
    /**
     * 初始化所有图表
     */
    initVisualizations() {
        this.renderRadarChart();
        this.renderTrendChart();
        this.renderROIComparison();
        this.renderCategoryBreakdown();
    }
    
    /**
     * 渲染雷达图(综合指标分析)
     */
    renderRadarChart() {
        const ctx = document.createElement('canvas');
        ctx.id = 'roi-radar-chart';
        this.container.appendChild(ctx);
        
        const chartData = {
            labels: ['财务回报', '品牌价值', '文化影响', '社会效益', '创新指数'],
            datasets: [{
                label: '当前项目',
                data: this.projectData.categoryScores,
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                borderColor: 'rgba(54, 162, 235, 1)',
                pointBackgroundColor: 'rgba(54, 162, 235, 1)',
                pointBorderColor: '#fff',
                pointHoverBackgroundColor: '#fff',
                pointHoverBorderColor: 'rgba(54, 162, 235, 1)'
            }]
        };
        
        this.charts.radar = new Chart(ctx, {
            type: 'radar',
            data: chartData,
            options: {
                responsive: true,
                maintainAspectRatio: true,
                scale: {
                    ticks: {
                        beginAtZero: true,
                        max: 100
                    }
                },
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `${context.label}: ${context.raw.toFixed(1)}分`;
                            }
                        }
                    }
                }
            }
        });
    }
    
    /**
     * 渲染投资回报趋势图
     */
    renderTrendChart() {
        // 实现时间序列数据可视化
        const ctx = document.createElement('canvas');
        ctx.id = 'roi-trend-chart';
        this.container.appendChild(ctx);
        
        // 获取时间序列数据
        const timelineData = this.projectData.timeline || [];
        
        const chartData = {
            labels: timelineData.map(item => item.month),
            datasets: [
                {
                    label: '财务回报',
                    data: timelineData.map(item => item.financial),
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1,
                    fill: false
                },
                {
                    label: '综合柔性指数',
                    data: timelineData.map(item => item.flexible_index),
                    borderColor: 'rgb(255, 99, 132)',
                    tension: 0.1,
                    fill: false
                }
            ]
        };
        
        this.charts.trend = new Chart(ctx, {
            type: 'line',
            data: chartData,
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: '投资回报趋势分析'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '指数值'
                        }
                    }
                }
            }
        });
    }
    
    // 更多可视化方法...
}

/**
 * 初始化可视化模块
 */
document.addEventListener('DOMContentLoaded', function() {
    // 通过AJAX获取项目数据
    fetchCulturalROIData().then(data => {
        const viz = new ROIVisualization('roi-visualization-container', data);
        viz.initVisualizations();
    });
});

/**
 * 从服务器获取ROI数据
 */
async function fetchCulturalROIData() {
    try {
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                'action': 'get_cultural_roi_data',
                'project_id': document.getElementById('project-id').value,
                'nonce': culturalROI.nonce
            })
        });
        
        return await response.json();
    } catch (error) {
        console.error('获取数据失败:', error);
        return null;
    }
}

数据导入导出功能

4.1 Excel数据导入模块

<?php
/**
 * Excel数据导入处理器
 */
class Excel_Data_Importer {
    
    /**
     * 处理上传的Excel文件
     * @param string $file_path Excel文件路径
     * @param int $project_id 项目ID
     * @return array 导入结果
     */
    public function import_excel_data($file_path, $project_id) {
        require_once CULTURAL_ROI_PLUGIN_PATH . 'vendor/autoload.php';
        
        $results = array(
            'total_rows' => 0,
            'imported_rows' => 0,
            'errors' => array()
        );
        
        try {
            // 使用PhpSpreadsheet读取Excel文件
            $spreadsheet = PhpOfficePhpSpreadsheetIOFactory::load($file_path);
            $worksheet = $spreadsheet->getActiveSheet();
            
            // 获取最高行和列
            $highest_row = $worksheet->getHighestRow();
            $highest_column = $worksheet->getHighestColumn();
            
            // 定义列映射(Excel列 => 数据库字段)
            $column_mapping = array(
                'A' => 'metric_type',
                'B' => 'metric_value',
                'C' => 'weight',
                'D' => 'recorded_date'
            );
            
            // 从第二行开始读取(跳过标题行)
            for ($row = 2; $row <= $highest_row; $row++) {
                $results['total_rows']++;
                
                $row_data = array('project_id' => $project_id);
                
                // 读取每一列数据
                foreach ($column_mapping as $column => $field) {
                    $cell_value = $worksheet->getCell($column . $row)->getValue();
                    
                    // 数据清洗和验证
                    $cleaned_value = $this->clean_cell_value($cell_value, $field);
                    
                    if ($cleaned_value !== false) {
                        $row_data[$field] = $cleaned_value;
                    } else {
                        $results['errors'][] = "第{$row}行,列{$column}数据无效";
                        continue 2; // 跳过此行
                    }
                }
                
                // 插入数据库
                if ($this->insert_metric_data($row_data)) {
                    $results['imported_rows']++;
                }
            }
            
        } catch (Exception $e) {
            $results['errors'][] = '文件读取失败: ' . $e->getMessage();
        }
        
        return $results;
    }
    
    /**
     * 清洗和验证单元格数据
     */
    private function clean_cell_value($value, $field) {
        $value = trim($value);
        
        switch ($field) {
            case 'metric_value':
                // 验证是否为有效数字
                if (is_numeric($value)) {
                    return floatval($value);
                }
                break;
                
            case 'weight':
                // 权重必须在0-1之间
                $float_val = floatval($value);
                if ($float_val >= 0 && $float_val <= 1) {
                    return $float_val;
                }
                break;
                
            case 'metric_type':
                // 验证指标类型是否有效
                $valid_metrics = array('direct_revenue', 'brand_awareness', /* ... */);
                if (in_array($value, $valid_metrics)) {
                    return $value;
                }
                break;
                
            case 'recorded_date':
                // 解析日期
                $timestamp = strtotime($value);
                if ($timestamp !== false) {
                    return date('Y-m-d H:i:s', $timestamp);
                }
                break;
        }
        
        return false;
    }
    
    /**
     * 插入指标数据到数据库
     */
    private function insert_metric_data($data) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'roi_metrics';
        
        return $wpdb->insert($table_name, $data);
    }
    
    /**
     * 生成Excel模板
     */
    public function generate_excel_template() {
        require_once CULTURAL_ROI_PLUGIN_PATH . 'vendor/autoload.php';
        
        $spreadsheet = new PhpOfficePhpSpreadsheetSpreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        
        // 设置标题行
        $headers = array(
            'A1' => '指标类型',
            'B1' => '指标值',
            'C1' => '权重(0-1)',
            'D1' => '记录日期'
        );
        
        foreach ($headers as $cell => $value) {
            $sheet->setCellValue($cell, $value);
            $sheet->getStyle($cell)->getFont()->setBold(true);
        }
        
        // 设置数据验证
        $validation = $sheet->getCell('A2')->getDataValidation();
        $validation->setType(PhpOfficePhpSpreadsheetCellDataValidation::TYPE_LIST);
        $validation->setFormula1('"direct_revenue,brand_awareness,cultural_preservation,social_impact"');
        $validation->setShowDropDown(true);
        
        // 设置示例数据
        $examples = array(
            array('direct_revenue', 50000, 0.4, '2024-01-15'),
            array('brand_awareness', 75, 0.25, '2024-01-15'),
            array('cultural_preservation', 80, 0.2, '2024-01-15'),
            array('social_impact', 65, 0.15, '2024-01-15')
        );
        
        $row = 2;
        foreach ($examples as $example) {
            $sheet->setCellValue('A' . $row, $example[0]);
            $sheet->setCellValue('B' . $row, $example[1]);
            $sheet->setCellValue('C' . $row, $example[2]);
            $sheet->setCellValue('D' . $row, $example[3]);
            $row++;
        }
        
        // 自动调整列宽
        foreach (range('A', 'D') as $column) {
            $sheet->getColumnDimension($column)->setAutoSize(true);
        }
        
        // 保存文件
        $writer = new PhpOfficePhpSpreadsheetWriterXlsx($spreadsheet);
        $file_path = CULTURAL_ROI_PLUGIN_PATH . 'templates/import_template.xlsx';
        $writer->save($file_path);
        
        return $file_path;
    }
}
?>

4.2 PDF报告生成模块

<?php
/**
 * PDF报告生成器
 */
class PDF_Report_Generator {
    
    /**
     * 生成完整的投资回报分析报告
     * @param int $project_id 项目ID
     * @param array $analysis_data 分析数据
     * @return string PDF文件路径
     */
    public function generate_roi_report($project_id, $analysis_data) {
        require_once CULTURAL_ROI_PLUGIN_PATH . 'vendor/autoload.php';
        
        // 创建TCPDF实例
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        
        // 设置文档信息
        $pdf->SetCreator('文创柔性投资分析插件');
        $pdf->SetAuthor('文创科技团队');
        $pdf->SetTitle('文创项目投资回报分析报告');
        $pdf->SetSubject('柔性投资回报分析');
        
        // 设置页眉页脚
        $pdf->setHeaderData('', 0, '文创项目柔性投资回报分析报告', '生成时间: ' . date('Y-m-d H:i:s'));
        
        // 设置默认字体
        $pdf->SetFont('stsongstdlight', '', 12);
        
        // 添加封面页
        $this->add_cover_page($pdf, $analysis_data['project_info']);
        
        // 添加目录
        $pdf->AddPage();
        $this->add_table_of_contents($pdf);
        
        // 添加执行摘要
        $pdf->AddPage();
        $this->add_executive_summary($pdf, $analysis_data['summary']);
        
        // 添加详细分析
        $pdf->AddPage();
        $this->add_detailed_analysis($pdf, $analysis_data['detailed']);
        
        // 添加图表
        $pdf->AddPage();
        $this->add_charts_page($pdf, $analysis_data['charts']);
        
        // 添加建议部分
        $pdf->AddPage();
        $this->add_recommendations($pdf, $analysis_data['recommendations']);
        
        // 保存文件
        $filename = 'roi_report_' . $project_id . '_' . date('YmdHis') . '.pdf';
        $file_path = CULTURAL_ROI_PLUGIN_PATH . 'reports/' . $filename;
        $pdf->Output($file_path, 'F');
        
        return $file_path;
    }
    
    /**
     * 添加封面页
     */
    private function add_cover_page($pdf, $project_info) {
        $pdf->AddPage();
        
        // 添加标题
        $pdf->SetFont('stsongstdlight', 'B', 24);
        $pdf->Cell(0, 40, '文创项目柔性投资回报分析报告', 0, 1, 'C');
        
        // 添加项目信息
        $pdf->SetFont('stsongstdlight', '', 16);
        $pdf->Ln(20);
        $pdf->Cell(0, 10, '项目名称: ' . $project_info['name'], 0, 1, 'C');
        $pdf->Cell(0, 10, '分析期间: ' . $project_info['period'], 0, 1, 'C');
        $pdf->Cell(0, 10, '生成日期: ' . date('Y年m月d日'), 0, 1, 'C');
        
        // 添加公司logo(如果有)
        if (file_exists(CULTURAL_ROI_PLUGIN_PATH . 'assets/logo.png')) {
            $pdf->Image(CULTURAL_ROI_PLUGIN_PATH . 'assets/logo.png', 85, 180, 40, 0, 'PNG');
        }
    }
    
    /**
     * 添加目录
     */
    private function add_table_of_contents($pdf) {
        $pdf->SetFont('stsongstdlight', 'B', 18);
        $pdf->Cell(0, 10, '目录', 0, 1);
        $pdf->Ln(10);
        
        $contents = array(
            '1. 执行摘要' => 3,
            '2. 项目概况' => 4,
            '3. 分析方法论' => 5,
            '4. 柔性回报分析' => 6,
            '5. 财务指标分析' => 7,
            '6. 品牌价值评估' => 8,
            '7. 文化影响力分析' => 9,
            '8. 社会效益评估' => 10,
            '9. 综合指数与建议' => 11
        );
        
        $pdf->SetFont('stsongstdlight', '', 12);
        foreach ($contents as $title => $page) {
            $pdf->Cell(0, 8, $title . ' ................................................ ' . $page, 0, 1);
        }
    }
    
    /**
     * 添加执行摘要
     */
    private function add_executive_summary($pdf, $summary_data) {
        $pdf->SetFont('stsongstdlight', 'B', 16);
        $pdf->Cell(0, 10, '1. 执行摘要', 0, 1);
        $pdf->Ln(5);
        
        $pdf->SetFont('stsongstdlight', '', 12);
        
        // 关键指标表格
        $pdf->SetFillColor(240, 240, 240);
        $pdf->SetFont('stsongstdlight', 'B', 12);
        
        $headers = array('指标类别', '得分', '权重', '加权得分', '评级');
        $widths = array(40, 30, 30, 40, 30);
        
        // 表头
        for ($i = 0; $i < count($headers); $i++) {
            $pdf->Cell($widths[$i], 10, $headers[$i], 1, 0, 'C', true);
        }
        $pdf->Ln();
        
        // 数据行
        $pdf->SetFont('stsongstdlight', '', 11);
        foreach ($summary_data['category_scores'] as $category) {
            $pdf->Cell($widths[0], 8, $category['name'], 1);
            $pdf->Cell($widths[1], 8, number_format($category['raw_score'], 1), 1, 0, 'C');
            $pdf->Cell($widths[2], 8, number_format($category['weight'], 2), 1, 0, 'C');
            $pdf->Cell($widths[3], 8, number_format($category['weighted_score'], 1), 1, 0, 'C');
            $pdf->Cell($widths[4], 8, $this->get_rating($category['weighted_score']), 1, 0, 'C');
            $pdf->Ln();
        }
        
        // 总分行
        $pdf->SetFont('stsongstdlight', 'B', 12);
        $pdf->Cell($widths[0] + $widths[1] + $widths[2], 8, '综合柔性回报指数', 1, 0, 'R');
        $pdf->Cell($widths[3], 8, number_format($summary_data['total_score'], 1), 1, 0, 'C');
        $pdf->Cell($widths[4], 8, $this->get_rating($summary_data['total_score']), 1, 0, 'C');
        
        // 摘要文字
        $pdf->Ln(15);
        $pdf->SetFont('stsongstdlight', '', 12);
        $pdf->MultiCell(0, 6, $summary_data['interpretation'], 0, 'L');
    }
    
    /**
     * 获取评级
     */
    private function get_rating($score) {
        if ($score >= 85) return '优秀';
        if ($score >= 70) return '良好';
        if ($score >= 60) return '中等';
        if ($score >= 50) return '合格';
        return '待改进';
    }
    
    // 更多PDF生成方法...
}
?>

插件安全与优化

5.1 安全防护措施

<?php
/**
 * 安全防护模块
 */
class Security_Manager {
    
    /**
     * 验证用户权限
     * @param string $capability 所需权限
     * @return bool 是否有权限
     */
    public static function check_user_capability($capability = 'manage_options') {
        // 检查用户是否登录
        if (!is_user_logged_in()) {
            return false;
        }
        
        // 检查用户权限
        if (!current_user_can($capability)) {
            // 记录安全日志
            self::log_security_event('insufficient_permissions', array(
                'user_id' => get_current_user_id(),
                'required_cap' => $capability
            ));
            return false;
        }
        
        return true;
    }
    
    /**
     * 数据输入验证和清理
     * @param mixed $data 输入数据
     * @param string $type 数据类型
     * @return mixed 清理后的数据
     */
    public static function sanitize_input($data, $type = 'text') {
        switch ($type) {
            case 'integer':
                return intval($data);
                
            case 'float':
                return floatval($data);
                
            case 'email':
                return sanitize_email($data);
                
            case 'url':
                return esc_url_raw($data);
                
            case 'html':
                return wp_kses_post($data);
                
            case 'text':
            default:
                return sanitize_text_field($data);
        }
    }
    
    /**
     * SQL注入防护
     * @param string $query SQL查询
     * @param array $params 参数
     * @return string 安全的查询
     */
    public static function prepare_sql_query($query, $params = array()) {
        global $wpdb;
        
        if (empty($params)) {
            return $query;
        }
        
        // 使用WordPress的prepare方法
        return $wpdb->prepare($query, $params);
    }
    
    /**
     * 文件上传安全检查
     * @param array $file 上传的文件信息
     * @param array $allowed_types 允许的文件类型
     * @return array 检查结果
     */
    public static function validate_uploaded_file($file, $allowed_types = array()) {
        $result = array(
            'valid' => false,
            'message' => '',
            'file_path' => ''
        );
        
        // 检查文件上传错误
        if ($file['error'] !== UPLOAD_ERR_OK) {
            $result['message'] = '文件上传失败,错误代码: ' . $file['error'];
            return $result;
        }
        
        // 检查文件大小(限制为10MB)
        $max_size = 10 * 1024 * 1024; // 10MB
        if ($file['size'] > $max_size) {
            $result['message'] = '文件大小超过限制(最大10MB)';
            return $result;
        }
        
        // 检查文件类型
        $file_info = wp_check_filetype($file['name']);
        if (empty($file_info['ext']) || empty($file_info['type'])) {
            $result['message'] = '不支持的文件类型';
            return $result;
        }
        
        // 如果指定了允许的类型,进行验证
        if (!empty($allowed_types) && !in_array($file_info['ext'], $allowed_types)) {
            $result['message'] = '只允许上传以下文件类型: ' . implode(', ', $allowed_types);
            return $result;
        }
        
        // 生成安全的文件名
        $filename = sanitize_file_name($file['name']);
        $upload_dir = wp_upload_dir();
        $file_path = $upload_dir['path'] . '/' . $filename;
        
        // 移动文件到安全目录
        if (move_uploaded_file($file['tmp_name'], $file_path)) {
            $result['valid'] = true;
            $result['file_path'] = $file_path;
        } else {
            $result['message'] = '文件保存失败';
        }
        
        return $result;
    }
    
    /**
     * 记录安全事件
     */
    private static function log_security_event($event_type, $data = array()) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'cultural_roi_security_logs';
        
        $log_data = array(
            'event_type' => $event_type,
            'user_id' => get_current_user_id(),
            'ip_address' => self::get_client_ip(),
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'event_data' => json_encode($data),
            'created_at' => current_time('mysql')
        );
        
        $wpdb->insert($table_name, $log_data);
    }
    
    /**
     * 获取客户端IP
     */
    private static 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, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                        return $ip;
                    }
                }
            }
        }
        
        return '0.0.0.0';
    }
    
    /**
     * 生成CSRF令牌
     */
    public static function generate_nonce($action = 'cultural_roi_action') {
        return wp_create_nonce($action);
    }
    
    /**
     * 验证CSRF令牌
     */
    public static function verify_nonce($nonce, $action = 'cultural_roi_action') {
        return wp_verify_nonce($nonce, $action);
    }
}
?>

5.2 性能优化策略

<?php
/**
 * 性能优化管理器
 */
class Performance_Optimizer {
    
    private $cache_enabled = true;
    private $cache_expiration = 3600; // 1小时
    
    /**
     * 启用数据缓存
     */
    public function enable_caching($enabled = true) {
        $this->cache_enabled = $enabled;
    }
    
    /**
     * 获取缓存数据
     * @param string $key 缓存键
     * @return mixed 缓存数据
     */
    public function get_cached_data($key) {
        if (!$this->cache_enabled) {
            return false;
        }
        
        $cache_key = 'cultural_roi_' . md5($key);
        $cached = wp_cache_get($cache_key, 'cultural_roi');
        
        if ($cached !== false) {
            // 检查是否过期
            if (isset($cached['expires']) && $cached['expires'] < time()) {
                wp_cache_delete($cache_key, 'cultural_roi');
                return false;
            }
            return $cached['data'];
        }
        
        return false;
    }
    
    /**
     * 设置缓存数据
     * @param string $key 缓存键
     * @param mixed $data 缓存数据
     * @param int $expiration 过期时间(秒)
     */
    public function set_cached_data($key, $data, $expiration = null) {
        if (!$this->cache_enabled) {
            return false;
        }
        
        $cache_key = 'cultural_roi_' . md5($key);
        $expiration = $expiration ?: $this->cache_expiration;
        
        $cache_data = array(
            'data' => $data,
            'expires' => time() + $expiration,
            'created' => time()
        );
        
        return wp_cache_set($cache_key, $cache_data, 'cultural_roi', $expiration);
    }
    
    /**
     * 批量查询优化
     * @param array $project_ids 项目ID数组
     * @return array 项目数据
     */
    public function batch_get_project_data($project_ids) {
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/6015.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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