文章目录[隐藏]
WordPress文创IP授权柔性管理插件开发指南
引言:文创IP授权管理的挑战与机遇
在数字文创产业蓬勃发展的今天,IP授权管理成为文创企业面临的核心挑战之一。传统的授权管理方式往往缺乏灵活性,难以适应快速变化的市场需求。本文将详细介绍如何开发一款WordPress文创IP授权柔性管理插件,帮助文创企业实现授权流程的数字化、自动化与柔性化管理。
插件架构设计
核心功能模块规划
我们的插件将包含以下核心模块:
- IP资源管理模块
- 授权协议管理模块
- 授权申请与审批流程模块
- 使用情况跟踪模块
- 数据分析与报告模块
数据库表结构设计
<?php
/**
* 创建插件所需的数据库表
* 这段代码应该放在插件的激活钩子中执行
*/
function ip_license_create_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
// IP资源表
$ip_resources_table = $wpdb->prefix . 'ip_resources';
$sql1 = "CREATE TABLE IF NOT EXISTS $ip_resources_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
title varchar(200) NOT NULL,
description text,
ip_type varchar(50) DEFAULT 'character', -- IP类型:character, story, design等
status varchar(20) DEFAULT 'active', -- 状态:active, inactive, archived
thumbnail_url varchar(500),
created_at datetime DEFAULT CURRENT_TIMESTAMP,
updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) $charset_collate;";
// 授权协议表
$license_agreements_table = $wpdb->prefix . 'license_agreements';
$sql2 = "CREATE TABLE IF NOT EXISTS $license_agreements_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
resource_id mediumint(9) NOT NULL,
agreement_name varchar(200) NOT NULL,
terms text NOT NULL, -- 授权条款
license_type varchar(50) DEFAULT 'exclusive', -- 授权类型:exclusive, non-exclusive
duration_days int DEFAULT 365, -- 授权期限(天)
fee_structure text, -- 费用结构(JSON格式)
allowed_usage text, -- 允许的使用范围(JSON格式)
restrictions text, -- 限制条件(JSON格式)
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
FOREIGN KEY (resource_id) REFERENCES $ip_resources_table(id) ON DELETE CASCADE
) $charset_collate;";
// 授权申请记录表
$license_applications_table = $wpdb->prefix . 'license_applications';
$sql3 = "CREATE TABLE IF NOT EXISTS $license_applications_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
agreement_id mediumint(9) NOT NULL,
applicant_name varchar(200) NOT NULL,
applicant_email varchar(200) NOT NULL,
company_name varchar(200),
usage_plan text NOT NULL, -- 使用计划描述
status varchar(20) DEFAULT 'pending', -- 状态:pending, approved, rejected, expired
approved_by bigint(20), -- 审批人用户ID
approved_at datetime,
expires_at datetime,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
FOREIGN KEY (agreement_id) REFERENCES $license_agreements_table(id) ON DELETE CASCADE,
FOREIGN KEY (approved_by) REFERENCES {$wpdb->prefix}users(ID) ON DELETE SET NULL
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql1);
dbDelta($sql2);
dbDelta($sql3);
}
?>
核心功能实现
IP资源管理模块
<?php
/**
* IP资源管理类
* 负责IP资源的CRUD操作
*/
class IP_Resource_Manager {
/**
* 添加新的IP资源
* @param array $resource_data 资源数据
* @return int|false 成功返回资源ID,失败返回false
*/
public function add_resource($resource_data) {
global $wpdb;
$table_name = $wpdb->prefix . 'ip_resources';
// 数据验证
if (empty($resource_data['title'])) {
return false;
}
// 准备插入数据
$data = array(
'title' => sanitize_text_field($resource_data['title']),
'description' => wp_kses_post($resource_data['description']),
'ip_type' => sanitize_text_field($resource_data['ip_type']),
'status' => 'active',
'thumbnail_url' => esc_url_raw($resource_data['thumbnail_url'])
);
// 插入数据库
$result = $wpdb->insert($table_name, $data);
if ($result) {
return $wpdb->insert_id;
}
return false;
}
/**
* 获取IP资源列表
* @param array $args 查询参数
* @return array 资源列表
*/
public function get_resources($args = array()) {
global $wpdb;
$table_name = $wpdb->prefix . 'ip_resources';
$defaults = array(
'page' => 1,
'per_page' => 10,
'status' => 'active',
'ip_type' => ''
);
$args = wp_parse_args($args, $defaults);
$where = "WHERE status = '" . esc_sql($args['status']) . "'";
if (!empty($args['ip_type'])) {
$where .= " AND ip_type = '" . esc_sql($args['ip_type']) . "'";
}
$offset = ($args['page'] - 1) * $args['per_page'];
$sql = $wpdb->prepare(
"SELECT * FROM $table_name
$where
ORDER BY created_at DESC
LIMIT %d OFFSET %d",
$args['per_page'],
$offset
);
return $wpdb->get_results($sql, ARRAY_A);
}
}
?>
柔性授权协议生成器
<?php
/**
* 柔性授权协议生成器
* 支持动态生成不同条件的授权协议
*/
class Flexible_License_Generator {
/**
* 生成授权协议
* @param int $resource_id IP资源ID
* @param array $parameters 授权参数
* @return int|false 协议ID或false
*/
public function generate_agreement($resource_id, $parameters) {
global $wpdb;
$table_name = $wpdb->prefix . 'license_agreements';
// 验证资源存在
$resource_exists = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(*) FROM {$wpdb->prefix}ip_resources WHERE id = %d",
$resource_id
)
);
if (!$resource_exists) {
return false;
}
// 根据参数生成协议名称
$agreement_name = $this->generate_agreement_name($parameters);
// 生成授权条款
$terms = $this->generate_terms($parameters);
// 生成费用结构
$fee_structure = $this->generate_fee_structure($parameters);
// 准备数据
$data = array(
'resource_id' => $resource_id,
'agreement_name' => $agreement_name,
'terms' => $terms,
'license_type' => $parameters['license_type'],
'duration_days' => $parameters['duration_days'],
'fee_structure' => json_encode($fee_structure),
'allowed_usage' => json_encode($parameters['allowed_usage']),
'restrictions' => json_encode($parameters['restrictions'])
);
// 插入数据库
$result = $wpdb->insert($table_name, $data);
if ($result) {
return $wpdb->insert_id;
}
return false;
}
/**
* 生成协议名称
* @param array $parameters 授权参数
* @return string 协议名称
*/
private function generate_agreement_name($parameters) {
$type_map = array(
'exclusive' => '独家授权',
'non-exclusive' => '非独家授权',
'regional' => '区域授权'
);
$type = isset($type_map[$parameters['license_type']]) ?
$type_map[$parameters['license_type']] : '通用授权';
$duration = $parameters['duration_days'] >= 365 ?
'长期' : ($parameters['duration_days'] . '天');
return sprintf('%s协议 - %s期限', $type, $duration);
}
/**
* 生成授权条款
* @param array $parameters 授权参数
* @return string 授权条款HTML
*/
private function generate_terms($parameters) {
$terms_template = '
<div class="license-terms">
<h3>授权条款</h3>
<p><strong>授权类型:</strong>%s</p>
<p><strong>授权期限:</strong>%d天</p>
<p><strong>允许使用范围:</strong>%s</p>
<p><strong>限制条件:</strong>%s</p>
<p><strong>费用结构:</strong>%s</p>
<p>本协议自双方确认之日起生效,解释权归版权方所有。</p>
</div>';
return sprintf(
$terms_template,
$parameters['license_type'],
$parameters['duration_days'],
implode('、', $parameters['allowed_usage']),
implode(';', $parameters['restrictions']),
$this->format_fee_structure($parameters['fee_structure'])
);
}
}
?>
前端用户界面
授权申请表单
<?php
/**
* 授权申请表单短码
* 用法:[ip_license_application_form agreement_id="1"]
*/
function ip_license_application_form_shortcode($atts) {
$atts = shortcode_atts(array(
'agreement_id' => 0
), $atts);
if (!$atts['agreement_id']) {
return '<p>错误:未指定授权协议</p>';
}
ob_start();
?>
<div class="ip-license-application-form">
<h3>文创IP授权申请</h3>
<form id="ip-license-application" method="post">
<?php wp_nonce_field('submit_license_application', 'license_nonce'); ?>
<input type="hidden" name="agreement_id" value="<?php echo esc_attr($atts['agreement_id']); ?>">
<div class="form-group">
<label for="applicant_name">申请人姓名 *</label>
<input type="text" id="applicant_name" name="applicant_name" required>
</div>
<div class="form-group">
<label for="applicant_email">电子邮箱 *</label>
<input type="email" id="applicant_email" name="applicant_email" required>
</div>
<div class="form-group">
<label for="company_name">公司/机构名称</label>
<input type="text" id="company_name" name="company_name">
</div>
<div class="form-group">
<label for="usage_plan">使用计划描述 *</label>
<textarea id="usage_plan" name="usage_plan" rows="5" required
placeholder="请详细描述您计划如何使用该IP,包括产品类型、预计产量、销售渠道等信息"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit_application">提交申请</button>
</div>
</form>
</div>
<script>
jQuery(document).ready(function($) {
$('#ip-license-application').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: formData + '&action=submit_license_application',
beforeSend: function() {
$('.form-group button').prop('disabled', true).text('提交中...');
},
success: function(response) {
if (response.success) {
$('#ip-license-application').html(
'<div class="success-message">' +
'<h4>申请提交成功!</h4>' +
'<p>您的申请编号是:' + response.data.application_id + '</p>' +
'<p>我们将在3个工作日内审核您的申请,并通过邮件通知您结果。</p>' +
'</div>'
);
} else {
alert('提交失败:' + response.data.message);
$('.form-group button').prop('disabled', false).text('提交申请');
}
}
});
});
});
</script>
<?php
return ob_get_clean();
}
add_shortcode('ip_license_application_form', 'ip_license_application_form_shortcode');
?>
管理后台界面
授权审批面板
<?php
/**
* 添加授权管理菜单
*/
function ip_license_admin_menu() {
add_menu_page(
'文创IP授权管理',
'IP授权',
'manage_options',
'ip-license-manager',
'ip_license_admin_page',
'dashicons-media-document',
30
);
add_submenu_page(
'ip-license-manager',
'授权申请审批',
'申请审批',
'manage_options',
'ip-license-applications',
'ip_license_applications_page'
);
add_submenu_page(
'ip-license-manager',
'IP资源管理',
'IP资源',
'manage_options',
'ip-resource-manager',
'ip_resource_manager_page'
);
}
add_action('admin_menu', 'ip_license_admin_menu');
/**
* 授权申请审批页面
*/
function ip_license_applications_page() {
global $wpdb;
$table_name = $wpdb->prefix . 'license_applications';
// 处理审批操作
if (isset($_POST['approve_application']) && check_admin_referer('approve_application')) {
$application_id = intval($_POST['application_id']);
$action = sanitize_text_field($_POST['action_type']);
$data = array('status' => $action);
if ($action == 'approved') {
$data['approved_by'] = get_current_user_id();
$data['approved_at'] = current_time('mysql');
// 设置过期时间
$agreement = $wpdb->get_row($wpdb->prepare(
"SELECT la.duration_days FROM $table_name la
JOIN {$wpdb->prefix}license_agreements a ON la.agreement_id = a.id
WHERE la.id = %d",
$application_id
));
if ($agreement) {
$expires_at = date('Y-m-d H:i:s',
strtotime("+{$agreement->duration_days} days"));
$data['expires_at'] = $expires_at;
}
}
$wpdb->update(
$table_name,
$data,
array('id' => $application_id)
);
echo '<div class="notice notice-success"><p>申请已' .
($action == 'approved' ? '批准' : '拒绝') . '</p></div>';
}
// 获取待审批申请
$pending_applications = $wpdb->get_results(
"SELECT la.*, a.agreement_name, r.title as resource_title
FROM $table_name la
JOIN {$wpdb->prefix}license_agreements a ON la.agreement_id = a.id
JOIN {$wpdb->prefix}ip_resources r ON a.resource_id = r.id
WHERE la.status = 'pending'
ORDER BY la.created_at DESC"
);
?>
<div class="wrap">
<h1>授权申请审批</h1>
<?php if (empty($pending_applications)): ?>
<p>暂无待审批的申请。</p>
<?php else: ?>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>申请ID</th>
<th>IP资源</th>
<th>协议名称</th>
<th>申请人</th>
<th>申请时间</th>
<th>使用计划</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach ($pending_applications as $app): ?>
<tr>
<td><?php echo $app->id; ?></td>
<td><?php echo esc_html($app->resource_title); ?></td>
<td><?php echo esc_html($app->agreement_name); ?></td>
<td>
<?php echo esc_html($app->applicant_name); ?><br>
<small><?php echo esc_html($app->applicant_email); ?></small>
</td>
<td><?php echo date('Y-m-d H:i', strtotime($app->created_at)); ?></td>
<td><?php echo wp_trim_words($app->usage_plan, 20); ?></td>
<td>
<form method="post" style="display: inline;">
<?php wp_nonce_field('approve_application'); ?>
<input type="hidden" name="application_id" value="<?php echo $app->id; ?>">
<input type="hidden" name="action_type" value="approved">
<button type="submit" name="approve_application" class="button button-primary">批准</button>
</form>
<form method="post" style="display: inline;">
<?php wp_nonce_field('approve_application'); ?>
<input type="hidden" name="application_id" value="<?php echo $app->id; ?>">
<input type="hidden" name="action_type" value="rejected">
<button type="submit" name="approve_application" class="button button-secondary">拒绝</button>
</form>
<a href="#" class="button view-details" data-id="<?php echo $app->id; ?>">详情</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<script>
jQuery(document).ready(function($) {
$('.view-details').on('click', function(e) {
e.preventDefault();
var appId = $(this).data('id');
// 这里可以添加查看详情的模态框逻辑
alert('申请ID ' + appId + ' 的详细信息功能待实现');
});
});
</script>
<?php
}
?>
## 柔性管理功能实现
### 动态授权条件调整
<?php
/**
- 动态授权条件调整器
- 允许根据实际情况调整已授权协议的条件
*/
class Dynamic_License_Adjuster {
/**
* 调整授权条件
* @param int $application_id 授权申请ID
* @param array $adjustments 调整参数
* @return bool 是否成功
*/
public function adjust_license_terms($application_id, $adjustments) {
global $wpdb;
// 获取当前授权信息
$application = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM {$wpdb->prefix}license_applications WHERE id = %d",
$application_id
));
if (!$application || $application->status != 'approved') {
return false;
}
// 记录调整历史
$this->log_adjustment_history($application_id, $adjustments);
// 根据调整类型执行相应操作
if (isset($adjustments['extend_duration'])) {
$this->extend_license_duration($application_id, $adjustments['extend_duration']);
}
if (isset($adjustments['modify_usage'])) {
$this->modify_usage_scope($application_id, $adjustments['modify_usage']);
}
if (isset($adjustments['adjust_fee'])) {
$this->adjust_license_fee($application_id, $adjustments['adjust_fee']);
}
return true;
}
/**
* 延长授权期限
* @param int $application_id 授权申请ID
* @param int $additional_days 延长的天数
*/
private function extend_license_duration($application_id, $additional_days) {
global $wpdb;
$current_expiry = $wpdb->get_var($wpdb->prepare(
"SELECT expires_at FROM {$wpdb->prefix}license_applications WHERE id = %d",
$application_id
));
if ($current_expiry) {
$new_expiry = date('Y-m-d H:i:s',
strtotime($current_expiry . " + $additional_days days"));
$wpdb->update(
$wpdb->prefix . 'license_applications',
array('expires_at' => $new_expiry),
array('id' => $application_id)
);
}
}
/**
* 记录调整历史
* @param int $application_id 授权申请ID
* @param array $adjustments 调整参数
*/
private function log_adjustment_history($application_id, $adjustments) {
global $wpdb;
$history_table = $wpdb->prefix . 'license_adjustment_history';
$data = array(
'application_id' => $application_id,
'adjustment_type' => json_encode(array_keys($adjustments)),
'adjustment_details' => json_encode($adjustments),
'adjusted_by' => get_current_user_id(),
'adjusted_at' => current_time('mysql')
);
$wpdb->insert($history_table, $data);
}
}
?>
### 智能授权推荐引擎
<?php
/**
- 智能授权推荐引擎
- 根据用户需求推荐最合适的授权方案
*/
class Smart_License_Recommender {
/**
* 推荐授权方案
* @param array $user_requirements 用户需求
* @return array 推荐方案
*/
public function recommend_license($user_requirements) {
$recommendations = array();
// 分析用户需求
$requirements = $this->analyze_requirements($user_requirements);
// 获取可用的授权协议
$available_agreements = $this->get_available_agreements();
// 计算匹配度
foreach ($available_agreements as $agreement) {
$score = $this->calculate_match_score($agreement, $requirements);
if ($score > 0.6) { // 匹配度阈值
$recommendations[] = array(
'agreement' => $agreement,
'match_score' => $score,
'reason' => $this->generate_recommendation_reason($agreement, $requirements)
);
}
}
// 按匹配度排序
usort($recommendations, function($a, $b) {
return $b['match_score'] <=> $a['match_score'];
});
return array_slice($recommendations, 0, 3); // 返回前3个推荐
}
/**
* 计算匹配度分数
* @param object $agreement 授权协议
* @param array $requirements 用户需求
* @return float 匹配度分数(0-1)
*/
private function calculate_match_score($agreement, $requirements) {
$score = 0;
$total_weight = 0;
// 授权类型匹配
if ($agreement->license_type == $requirements['preferred_type']) {
$score += 0.3;
}
$total_weight += 0.3;
// 使用范围匹配
$agreement_usage = json_decode($agreement->allowed_usage, true);
$usage_match = count(array_intersect($requirements['usage_types'], $agreement_usage)) /
max(count($requirements['usage_types']), 1);
$score += $usage_match * 0.4;
$total_weight += 0.4;
// 预算匹配
$fee_structure = json_decode($agreement->fee_structure, true);
if ($this->is_budget_compatible($fee_structure, $requirements['budget'])) {
$score += 0.3;
}
$total_weight += 0.3;
return $total_weight > 0 ? $score / $total_weight : 0;
}
/**
* 生成推荐理由
* @param object $agreement 授权协议
* @param array $requirements 用户需求
* @return string 推荐理由
*/
private function generate_recommendation_reason($agreement, $requirements) {
$reasons = array();
if ($agreement->license_type == $requirements['preferred_type']) {
$reasons[] = "符合您期望的" . $this->get_type_name($agreement->license_type) . "类型";
}
$agreement_usage = json_decode($agreement->allowed_usage, true);
$common_usage = array_intersect($requirements['usage_types'], $agreement_usage);
if (!empty($common_usage)) {
$reasons[] = "支持您需要的" . implode('、', $common_usage) . "使用场景";
}
$fee_structure = json_decode($agreement->fee_structure, true);
if (isset($fee_structure['type']) && $fee_structure['type'] == 'royalty') {
$reasons[] = "采用分成模式,降低前期成本";
}
return implode(';', $reasons);
}
}
?>
## 插件部署与配置
### 安装与激活设置
<?php
/**
- 插件激活时的初始化操作
*/
register_activation_hook(__FILE__, 'ip_license_plugin_activate');
function ip_license_plugin_activate() {
// 创建数据库表
ip_license_create_tables();
// 创建必要的目录
$upload_dir = wp_upload_dir();
$plugin_dir = $upload_dir['basedir'] . '/ip-license-docs/';
if (!file_exists($plugin_dir)) {
wp_mkdir_p($plugin_dir);
}
// 设置默认选项
$default_options = array(
'auto_approve_threshold' => 3, // 自动审批阈值
'default_license_duration' => 365,
'notification_emails' => get_option('admin_email'),
'enable_smart_recommendation' => true,
'allow_license_adjustment' => true
);
add_option('ip_license_settings', $default_options);
// 添加用户角色和能力
$this->add_license_manager_role();
}
/**
- 添加授权管理员角色
*/
private function add_license_manager_role() {
add_role('license_manager', '授权管理员', array(
'read' => true,
'manage_ip_licenses' => true,
'approve_licenses' => true,
'edit_license_terms' => true
));
// 给管理员添加权限
$admin_role = get_role('administrator');
if ($admin_role) {
$admin_role->add_cap('manage_ip_licenses');
$admin_role->add_cap('approve_licenses');
$admin_role->add_cap('edit_license_terms');
}
}
?>
### 配置页面
<?php
/**
- 插件设置页面
*/
function ip_license_settings_page() {
if (!current_user_can('manage_options')) {
return;
}
$settings = get_option('ip_license_settings', array());
// 保存设置
if (isset($_POST['submit_settings'])) {
check_admin_referer('ip_license_settings');
$new_settings = array(
'auto_approve_threshold' => intval($_POST['auto_approve_threshold']),
'default_license_duration' => intval($_POST['default_license_duration']),
'notification_emails' => sanitize_textarea_field($_POST['notification_emails']),
'enable_smart_recommendation' => isset($_POST['enable_smart_recommendation']),
'allow_license_adjustment' => isset($_POST['allow_license_adjustment']),
'license_templates' => array_map('sanitize_text_field', $_POST['license_templates'])
);
update_option('ip_license_settings', $new_settings);
echo '<div class="notice notice-success"><p>设置已保存</p></div>';
$settings = $new_settings;
}
?>
<div class="wrap">
<h1>文创IP授权插件设置</h1>
<form method="post">
<?php wp_nonce_field('ip_license_settings'); ?>
<table class="form-table">
<tr>
<th scope="row">自动审批阈值</th>
<td>
<input type="number" name="auto_approve_threshold"
value="<?php echo esc_attr($settings['auto_approve_threshold']); ?>"
min="0" max="10">
<p class="description">用户信用评分达到此值时自动批准申请</p>
</td>
</tr>
<tr>
<th scope="row">默认授权期限(天)</th>
<td>
<input type="number" name="default_license_duration"
value="<?php echo esc_attr($settings['default_license_duration']); ?>"
min="30" max="3650">
</td>
</tr>
<tr>
<th scope="row">通知邮箱</th>
<td>
<textarea name="notification_emails" rows="3" style="width: 300px;">
<?php echo esc_textarea($settings['notification_emails']); ?>
</textarea>
<p class="description">多个邮箱用逗号分隔</p>
</td>
</tr>
<tr>
<th scope="row">智能功能</th>
<td>
<label>
<input type="checkbox" name="enable_smart_recommendation"
<?php checked($settings['enable_smart_recommendation']); ?>>
启用智能授权推荐
</label><br>
<label>
<input type="checkbox" name="allow_license_adjustment"
<?php checked($settings['allow_license_adjustment']); ?>>
允许动态调整授权条件
</label>
</td>
</tr>
<tr>
<th scope="row">授权模板</th>
<td>
<div id="license-templates">
<?php
$templates = isset($settings['license_templates']) ?
$settings['license_templates'] : array('基础授权', '商业授权', '独家授权');
foreach ($templates as $index => $template): ?>
<div class="template-item">
<input type="text" name="license_templates[]"
value="<?php echo esc_attr($template); ?>"
style="width: 200px; margin-bottom: 5px;">
<button type="button" class="button remove-template">删除</button>
</div>
<?php endforeach; ?>
</div>
<button type="button" id="add-template" class="button">添加模板</button>
</td>
</tr>
</table>
<p class="submit">
<input type="submit" name="submit_settings" class="button-primary" value="保存设置">
</p>
</form>
</div>
<script>
jQuery(document).ready(function($) {
// 添加模板
$('#add-template').on('click', function() {
$('#license-templates').append(
'<div class="template-item">' +
'<input type="text" name="license_templates[]" value="" style="width: 200px; margin-bottom: 5px;">' +
'<button type="button" class="button remove-template">删除</button>' +
'</div>'
);
});
// 删除模板
$(document).on('click', '.remove-template', function() {
$(this).closest('.template-item').remove();
});
});
</script>
<?php
}
?>
## 安全与性能优化
### 数据安全保护
<?php
/**
- 数据加密处理类
*/
class License_Data_Encryptor {
private $encryption_key;
public function __construct() {
$this->encryption_key = $this->get_encryption_key();
}
/**
* 获取加密密钥
* @return string 加密密钥
*/
private function get_encryption_key() {
$key = get_option('ip_license_encryption_key');
if (!$key) {
$key = $this->generate_encryption_key();
update_option('ip_license_encryption_key', $key);
}
return $key;
}
/**
* 生成加密密钥
* @return string 生成的密钥
*/
private function generate_encryption_key() {
if (function_exists('random_bytes')) {
return bin2hex(random_bytes(32));
} elseif (function_exists('openssl_random_pseudo_bytes')) {
return bin2hex(openssl_random_pseudo_bytes(32));
}
// 备用方案
return md5(uniqid(mt_rand(), true) . microtime(true));
}
/**
* 加密敏感数据
* @param string $data 原始数据
* @return string 加密后的数据
*/
public function encrypt($data) {
$method = 'AES-256-CBC';
$iv_length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_length);
$encrypted = openssl_encrypt(
$data,
$method,
$this->encryption_key,
OPENSSL_RAW_DATA,
$iv
);
return base64_encode($iv . $encrypted);
}
/**
* 解密数据
* @param string $encrypted_data 加密数据
* @return string|false 解密后的数据或false
*/
public function decrypt($encrypted_data) {
$data = base64_decode($encrypted_data);
$method = 'AES-256-CBC';
$iv_length = openssl_cipher_iv_length($method);
$iv = substr($data, 0, $iv_length);
$encrypted = substr($data, $iv_length);
return openssl_decrypt(
$encrypted,
$method,
$this->encryption_key,
OPENSSL_RAW_DATA,
$iv
);
}
}
/**
- 敏感数据处理器
*/
class Sensitive_Data_Handler {
private $encryptor;
public function __construct() {
$this->encryptor = new License_Data_Encryptor();
}
/**
* 保存敏感数据
* @param array $data 包含敏感数据的数据数组
* @return array 处理
