首页 / 应用软件 / 开发指南,打造网站内嵌的在线代码编辑与运行环境

开发指南,打造网站内嵌的在线代码编辑与运行环境

开发指南:打造网站内嵌的在线代码编辑与运行环境

摘要

在当今数字化时代,网站功能多样化已成为吸引用户的关键因素之一。本文将详细介绍如何通过WordPress程序的二次开发,打造一个内嵌的在线代码编辑与运行环境,并实现常用互联网小工具功能。我们将从技术选型、环境搭建、核心功能实现到安全优化等方面进行全面解析,帮助开发者构建功能强大且用户友好的代码编辑平台。


一、引言:在线代码编辑环境的价值与意义

1.1 在线代码编辑器的兴起

随着云计算和Web技术的发展,在线代码编辑器逐渐成为开发者工具箱中的重要组成部分。从简单的代码片段分享到完整的集成开发环境(IDE),在线编辑器为用户提供了无需本地安装即可编写、运行和调试代码的便利。对于技术博客、教育平台或开发者社区而言,内嵌代码编辑器能极大提升用户体验和参与度。

1.2 WordPress作为开发平台的优势

WordPress作为全球最流行的内容管理系统,拥有庞大的插件生态系统和灵活的扩展能力。通过二次开发,我们可以在WordPress平台上构建专业级的代码编辑环境,同时利用其用户管理、内容发布和社区功能,打造一体化的开发者服务平台。

1.3 本文目标与结构

本文将指导读者完成以下目标:

  1. 在WordPress中集成在线代码编辑器
  2. 实现代码运行环境(支持多种编程语言)
  3. 开发常用互联网小工具(如JSON格式化、加密解密等)
  4. 确保系统的安全性与性能优化

二、技术架构与工具选型

2.1 核心编辑器选择

2.1.1 Monaco Editor

Monaco Editor是Visual Studio Code的底层编辑器,功能强大且高度可定制。它支持语法高亮、代码补全、错误检查等高级功能,是构建专业代码编辑器的理想选择。

2.1.2 CodeMirror

CodeMirror是一个轻量级的代码编辑器,易于集成且资源消耗较小。对于不需要完整IDE功能的场景,CodeMirror是一个优秀的选择。

2.1.3 Ace Editor

Ace Editor是另一个流行的在线代码编辑器,性能优异且支持多种语言模式。

推荐方案:对于需要接近桌面IDE体验的场景,我们选择Monaco Editor;对于轻量级需求,可选择CodeMirror。

2.2 代码执行环境

2.2.1 服务器端执行方案

  • Docker容器:为每种语言创建独立的Docker容器,确保环境隔离和安全
  • 语言特定沙箱:如PySandbox for Python, JS-Sandbox for JavaScript
  • 第三方API:利用如JDoodle、Runnable等在线编译API

2.2.2 客户端执行方案

  • WebAssembly:将语言运行时编译为WebAssembly,在浏览器中直接执行
  • JavaScript解释器:对于JavaScript代码,可直接在浏览器中运行

推荐方案:结合使用客户端执行(适合简单JavaScript代码)和服务器端Docker容器(支持多种语言,安全性高)。

2.3 WordPress开发框架

2.3.1 插件开发基础

  • 使用标准的WordPress插件结构
  • 遵循WordPress编码标准
  • 利用WordPress的REST API进行前后端通信

2.3.2 前端技术栈

  • React或Vue.js用于构建交互式UI组件
  • Webpack或Vite进行模块打包
  • Sass/Less用于样式管理

三、环境搭建与基础配置

3.1 开发环境准备

// WordPress插件基础结构
/*
Plugin Name: 在线代码编辑器与工具集
Plugin URI: https://yourwebsite.com/
Description: 在WordPress中嵌入在线代码编辑器和常用开发工具
Version: 1.0.0
Author: Your Name
*/

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

// 定义插件常量
define('CODE_EDITOR_VERSION', '1.0.0');
define('CODE_EDITOR_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CODE_EDITOR_PLUGIN_URL', plugin_dir_url(__FILE__));

3.2 Monaco Editor集成

// 前端初始化Monaco Editor
import * as monaco from 'monaco-editor';

class CodeEditor {
    constructor(containerId, language = 'javascript') {
        this.container = document.getElementById(containerId);
        this.language = language;
        this.editor = null;
        this.init();
    }
    
    init() {
        this.editor = monaco.editor.create(this.container, {
            value: this.getDefaultCode(),
            language: this.language,
            theme: 'vs-dark',
            fontSize: 14,
            minimap: { enabled: true },
            automaticLayout: true,
            scrollBeyondLastLine: false,
            wordWrap: 'on'
        });
    }
    
    getDefaultCode() {
        const defaults = {
            'javascript': 'console.log("Hello, World!");',
            'python': 'print("Hello, World!")',
            'html': '<!DOCTYPE html>n<html>n<head>n<title>示例</title>n</head>n<body>n<h1>Hello World</h1>n</body>n</html>',
            'css': 'body {n  font-family: Arial, sans-serif;n}',
            'php': '<?phpnecho "Hello, World!";n?>'
        };
        
        return defaults[this.language] || '// 输入你的代码';
    }
    
    getCode() {
        return this.editor.getValue();
    }
    
    setCode(code) {
        this.editor.setValue(code);
    }
    
    changeLanguage(language) {
        const model = this.editor.getModel();
        monaco.editor.setModelLanguage(model, language);
        this.language = language;
    }
}

3.3 Docker执行环境配置

# docker-compose.yml 配置示例
version: '3.8'

services:
  code-executor:
    build: ./executor
    container_name: code_executor
    restart: unless-stopped
    networks:
      - code_network
    volumes:
      - ./code-temp:/tmp/code
    environment:
      - MAX_EXECUTION_TIME=10
      - MAX_MEMORY=256m
      
  # 不同语言的执行器
  python-executor:
    image: python:3.9-slim
    container_name: python_executor
    command: tail -f /dev/null
    networks:
      - code_network
      
  node-executor:
    image: node:16-alpine
    container_name: node_executor
    command: tail -f /dev/null
    networks:
      - code_network

networks:
  code_network:
    driver: bridge

四、核心功能实现

4.1 多语言代码编辑器

// WordPress短代码实现编辑器嵌入
add_shortcode('code_editor', 'code_editor_shortcode');

function code_editor_shortcode($atts) {
    $atts = shortcode_atts(array(
        'language' => 'javascript',
        'height' => '400px',
        'theme' => 'vs-dark',
        'readonly' => false
    ), $atts);
    
    // 生成唯一ID
    $editor_id = 'code-editor-' . uniqid();
    
    // 加载必要资源
    wp_enqueue_script('monaco-editor', 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.0/min/vs/loader.min.js');
    wp_enqueue_style('code-editor-style', CODE_EDITOR_PLUGIN_URL . 'assets/css/editor.css');
    
    ob_start();
    ?>
    <div class="code-editor-container">
        <div class="editor-toolbar">
            <select class="language-selector">
                <option value="javascript" <?php selected($atts['language'], 'javascript'); ?>>JavaScript</option>
                <option value="python" <?php selected($atts['language'], 'python'); ?>>Python</option>
                <option value="html" <?php selected($atts['language'], 'html'); ?>>HTML</option>
                <option value="css" <?php selected($atts['language'], 'css'); ?>>CSS</option>
                <option value="php" <?php selected($atts['language'], 'php'); ?>>PHP</option>
                <option value="java" <?php selected($atts['language'], 'java'); ?>>Java</option>
            </select>
            <button class="run-code-btn">运行代码</button>
            <button class="save-code-btn">保存代码</button>
        </div>
        <div id="<?php echo esc_attr($editor_id); ?>" 
             class="code-editor" 
             data-language="<?php echo esc_attr($atts['language']); ?>"
             data-theme="<?php echo esc_attr($atts['theme']); ?>"
             style="height: <?php echo esc_attr($atts['height']); ?>;">
        </div>
        <div class="execution-result">
            <h4>运行结果:</h4>
            <div class="result-output"></div>
        </div>
    </div>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化编辑器
        const editorId = '<?php echo $editor_id; ?>';
        const initLanguage = '<?php echo $atts["language"]; ?>';
        
        // 配置Monaco Editor
        require.config({ paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.0/min/vs' } });
        
        require(['vs/editor/editor.main'], function() {
            const editorContainer = document.getElementById(editorId);
            const language = editorContainer.dataset.language;
            const theme = editorContainer.dataset.theme;
            
            // 创建编辑器实例
            const editor = monaco.editor.create(editorContainer, {
                value: getDefaultCode(language),
                language: language,
                theme: theme,
                fontSize: 14,
                minimap: { enabled: true },
                automaticLayout: true
            });
            
            // 存储编辑器实例供后续使用
            window.codeEditors = window.codeEditors || {};
            window.codeEditors[editorId] = editor;
            
            // 语言切换功能
            const languageSelector = editorContainer.parentElement.querySelector('.language-selector');
            languageSelector.addEventListener('change', function(e) {
                const newLanguage = e.target.value;
                const model = editor.getModel();
                monaco.editor.setModelLanguage(model, newLanguage);
                editorContainer.dataset.language = newLanguage;
            });
            
            // 运行代码功能
            const runButton = editorContainer.parentElement.querySelector('.run-code-btn');
            runButton.addEventListener('click', function() {
                const code = editor.getValue();
                const language = editorContainer.dataset.language;
                runCode(code, language, editorContainer);
            });
        });
        
        function getDefaultCode(language) {
            const defaults = {
                'javascript': 'console.log("Hello, World!");n// 尝试修改并运行这段代码',
                'python': 'print("Hello, World!")n# 尝试修改并运行这段代码',
                'html': '<!DOCTYPE html>n<html>n<head>nt<title>示例页面</title>n</head>n<body>nt<h1>Hello World!</h1>nt<p>尝试修改并运行这段HTML代码</p>n</body>n</html>',
                'css': 'body {ntfont-family: Arial, sans-serif;ntbackground-color: #f0f0f0;n}nnh1 {ntcolor: #333;n}',
                'php': '<?phpntecho "Hello, World!\n";nt// 尝试修改并运行这段PHP代码n?>',
                'java': 'public class Main {ntpublic static void main(String[] args) {nttSystem.out.println("Hello, World!");nt}n}'
            };
            
            return defaults[language] || '// 输入你的代码';
        }
        
        function runCode(code, language, container) {
            const outputArea = container.parentElement.querySelector('.result-output');
            outputArea.innerHTML = '<div class="loading">执行中...</div>';
            
            // 发送AJAX请求到WordPress后端
            fetch('<?php echo admin_url("admin-ajax.php"); ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    'action': 'execute_code',
                    'code': code,
                    'language': language,
                    'nonce': '<?php echo wp_create_nonce("code_execution_nonce"); ?>'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    outputArea.innerHTML = `<pre class="success-output">${data.data.output}</pre>`;
                } else {
                    outputArea.innerHTML = `<pre class="error-output">错误: ${data.data.error}</pre>`;
                }
            })
            .catch(error => {
                outputArea.innerHTML = `<pre class="error-output">请求失败: ${error.message}</pre>`;
            });
        }
    });
    </script>
    <?php
    
    return ob_get_clean();
}

4.2 代码执行后端处理

// WordPress AJAX处理代码执行
add_action('wp_ajax_execute_code', 'handle_code_execution');
add_action('wp_ajax_nopriv_execute_code', 'handle_code_execution');

function handle_code_execution() {
    // 验证nonce
    if (!wp_verify_nonce($_POST['nonce'], 'code_execution_nonce')) {
        wp_send_json_error(array('error' => '安全验证失败'));
        return;
    }
    
    // 获取参数
    $code = isset($_POST['code']) ? stripslashes($_POST['code']) : '';
    $language = isset($_POST['language']) ? sanitize_text_field($_POST['language']) : 'javascript';
    
    if (empty($code)) {
        wp_send_json_error(array('error' => '代码不能为空'));
        return;
    }
    
    // 根据语言选择执行方式
    $result = execute_code_safely($code, $language);
    
    if ($result['success']) {
        wp_send_json_success(array('output' => $result['output']));
    } else {
        wp_send_json_error(array('error' => $result['error']));
    }
}

function execute_code_safely($code, $language) {
    // 安全检查:防止危险代码
    $blacklisted_patterns = array(
        '/systems*(/i',
        '/execs*(/i',
        '/shell_execs*(/i',
        '/passthrus*(/i',
        '/proc_opens*(/i',
        '/popens*(/i',
        '/`.*`/',
        '/evals*(/i',
        '/includes*(/i',
        '/requires*(/i'
    );
    
    foreach ($blacklisted_patterns as $pattern) {
        if (preg_match($pattern, $code)) {
            return array(
                'success' => false,
                'error' => '代码包含不允许的操作'
            );
        }
    }
    
    // 根据语言执行代码
    switch ($language) {
        case 'javascript':
            return execute_javascript($code);
        case 'python':
            return execute_python($code);
        case 'php':
            return execute_php($code);
        case 'html':
            return execute_html($code);
        default:
            return array(
                'success' => false,
                'error' => '暂不支持该语言'
            );
    }
}

function execute_javascript($code) {
    // 对于简单JavaScript,可以在服务端使用V8JS(如果安装)
    // 或者返回给客户端执行
    // 这里我们使用一个简化的方法:返回给客户端执行的指令
    
    return array(
        'success' => true,
        'output' => 'JavaScript代码将在客户端执行。注意:出于安全考虑,某些API可能受限。'
    );
}

function execute_python($code) {
    // 使用Docker执行Python代码
    $temp_file = tempnam(sys_get_temp_dir(), 'py_');
    file_put_contents($temp_file, $code);
    
    // 使用Docker运行代码(需要Docker环境)
    $command = "docker run --rm -v " . dirname($temp_file) . ":/code python:3.9-slim python /code/" . basename($temp_file) . " 2>&1";
    $output = shell_exec("timeout 10 " . $command);
    
    // 清理临时文件
    unlink($temp_file);
    
    if ($output === null) {
        return array(
            'success' => false,
            'error' => '执行超时或出错'
        );
    }
    
    return array(
        'success' => true,
        'output' => htmlspecialchars($output)
    );
}

function execute_html($code) {
    // 对于HTML,我们可以返回一个可预览的iframe
    $html_content = $code;
    
    // 如果代码中没有完整的HTML结构,添加基本结构
    if (!preg_match('/<!DOCTYPEs+html>/i', $html_content) && !preg_match('/<html>/i', $html_content)) {
        $html_content = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>运行结果</title></head><body>' . $html_content . '</body></html>';
    }
    
    // 编码HTML内容以便安全传输
    $encoded_html = base64_encode($html_content);
    
    return array(
        'success' => true,
        'output' => '<iframe srcdoc="' . htmlspecialchars($html_content) . '" style="width:100%; height:300px; border:1px solid #ddd;"></iframe>'
    );
}

4.3 常用互联网小工具集成

// 小工具集成的短代码
add_shortcode('web_tools', 'web_tools_shortcode');

function web_tools_shortcode() {
    ob_start();

?>
<div class="web-tools-container">

<div class="tools-tabs">
    <button class="tool-tab active" data-tool="json">JSON格式化</button>
    <button class="tool-tab" data-tool="encrypt">加密/解密</button>
    <button class="tool-tab" data-tool="timestamp">时间戳转换</button>
    <button class="tool-tab" data-tool="color">颜色转换</button>
    <button class="tool-tab" data-tool="regex">正则测试</button>
    <button class="tool-tab" data-tool="qrcode">二维码生成</button>
</div>

<div class="tool-content">
    <!-- JSON格式化工具 -->
    <div class="tool-pane active" id="json-tool">
        <div class="tool-description">
            <h3>JSON格式化工具</h3>
            <p>格式化、验证和压缩JSON数据,支持JSON与XML互转</p>
        </div>
        <div class="tool-interface">
            <div class="input-area">
                <textarea id="json-input" placeholder="输入JSON字符串...">{"name": "示例", "value": 123, "items": [1, 2, 3]}</textarea>
                <div class="button-group">
                    <button id="json-format">格式化</button>
                    <button id="json-minify">压缩</button>
                    <button id="json-validate">验证</button>
                    <button id="json-clear">清空</button>
                </div>
            </div>
            <div class="output-area">
                <textarea id="json-output" readonly placeholder="格式化结果..."></textarea>
                <div class="conversion-options">
                    <button id="json-to-xml">JSON转XML</button>
                    <button id="xml-to-json">XML转JSON</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 加密解密工具 -->
    <div class="tool-pane" id="encrypt-tool">
        <div class="tool-description">
            <h3>加密/解密工具</h3>
            <p>支持Base64、MD5、SHA、AES、DES等多种加密算法</p>
        </div>
        <div class="tool-interface">
            <div class="algorithm-selector">
                <select id="encrypt-algorithm">
                    <option value="base64">Base64编码/解码</option>
                    <option value="md5">MD5哈希</option>
                    <option value="sha1">SHA-1哈希</option>
                    <option value="sha256">SHA-256哈希</option>
                    <option value="aes">AES加密/解密</option>
                    <option value="des">DES加密/解密</option>
                </select>
                <input type="text" id="encrypt-key" placeholder="加密密钥(如适用)">
            </div>
            <div class="input-area">
                <textarea id="encrypt-input" placeholder="输入要加密/解密的文本...">Hello, World!</textarea>
                <div class="button-group">
                    <button id="encrypt-action">加密</button>
                    <button id="decrypt-action">解密</button>
                </div>
            </div>
            <div class="output-area">
                <textarea id="encrypt-output" readonly placeholder="加密/解密结果..."></textarea>
            </div>
        </div>
    </div>
    
    <!-- 时间戳转换工具 -->
    <div class="tool-pane" id="timestamp-tool">
        <div class="tool-description">
            <h3>时间戳转换工具</h3>
            <p>Unix时间戳与可读日期时间相互转换,支持多种格式</p>
        </div>
        <div class="tool-interface">
            <div class="timestamp-input">
                <div class="input-group">
                    <label>Unix时间戳:</label>
                    <input type="text" id="timestamp-input" value="<?php echo time(); ?>">
                    <button id="timestamp-to-date">转换为日期</button>
                </div>
                <div class="input-group">
                    <label>日期时间:</label>
                    <input type="datetime-local" id="date-input" value="<?php echo date('Y-m-dTH:i'); ?>">
                    <button id="date-to-timestamp">转换为时间戳</button>
                </div>
            </div>
            <div class="output-area">
                <div id="timestamp-result">
                    <p><strong>当前时间戳:</strong> <span id="current-timestamp"><?php echo time(); ?></span></p>
                    <p><strong>北京时间:</strong> <span id="beijing-time"><?php echo date('Y-m-d H:i:s'); ?></span></p>
                    <p><strong>UTC时间:</strong> <span id="utc-time"><?php echo gmdate('Y-m-d H:i:s'); ?></span></p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 其他工具界面类似,此处省略详细HTML -->
</div>

</div>

<script>
document.addEventListener('DOMContentLoaded', function() {

// 工具标签切换
const toolTabs = document.querySelectorAll('.tool-tab');
const toolPanes = document.querySelectorAll('.tool-pane');

toolTabs.forEach(tab => {
    tab.addEventListener('click', function() {
        const toolName = this.dataset.tool;
        
        // 更新标签状态
        toolTabs.forEach(t => t.classList.remove('active'));
        this.classList.add('active');
        
        // 显示对应工具
        toolPanes.forEach(pane => {
            pane.classList.remove('active');
            if (pane.id === toolName + '-tool') {
                pane.classList.add('active');
            }
        });
    });
});

// JSON格式化功能
const jsonInput = document.getElementById('json-input');
const jsonOutput = document.getElementById('json-output');

document.getElementById('json-format').addEventListener('click', function() {
    try {
        const jsonObj = JSON.parse(jsonInput.value);
        jsonOutput.value = JSON.stringify(jsonObj, null, 2);
    } catch (e) {
        jsonOutput.value = 'JSON格式错误: ' + e.message;
    }
});

document.getElementById('json-minify').addEventListener('click', function() {
    try {
        const jsonObj = JSON.parse(jsonInput.value);
        jsonOutput.value = JSON.stringify(jsonObj);
    } catch (e) {
        jsonOutput.value = 'JSON格式错误: ' + e.message;
    }
});

document.getElementById('json-validate').addEventListener('click', function() {
    try {
        JSON.parse(jsonInput.value);
        jsonOutput.value = '✓ JSON格式正确';
    } catch (e) {
        jsonOutput.value = '✗ JSON格式错误: ' + e.message;
    }
});

// 加密解密功能
const encryptInput = document.getElementById('encrypt-input');
const encryptOutput = document.getElementById('encrypt-output');
const encryptAlgorithm = document.getElementById('encrypt-algorithm');

document.getElementById('encrypt-action').addEventListener('click', function() {
    const text = encryptInput.value;
    const algorithm = encryptAlgorithm.value;
    const key = document.getElementById('encrypt-key').value;
    
    // 调用WordPress后端处理加密
    fetch('<?php echo admin_url("admin-ajax.php"); ?>', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            'action': 'process_encryption',
            'text': text,
            'algorithm': algorithm,
            'key': key,
            'mode': 'encrypt',
            'nonce': '<?php echo wp_create_nonce("encryption_nonce"); ?>'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            encryptOutput.value = data.data.result;
        } else {
            encryptOutput.value = '错误: ' + data.data.error;
        }
    })
    .catch(error => {
        encryptOutput.value = '请求失败: ' + error.message;
    });
});

// 时间戳转换功能
document.getElementById('timestamp-to-date').addEventListener('click', function() {
    const timestamp = parseInt(document.getElementById('timestamp-input').value);
    if (!isNaN(timestamp)) {
        const date = new Date(timestamp * 1000);
        document.getElementById('date-input').value = 
            date.getFullYear() + '-' + 
            String(date.getMonth() + 1).padStart(2, '0') + '-' + 
            String(date.getDate()).padStart(2, '0') + 'T' + 
            String(date.getHours()).padStart(2, '0') + ':' + 
            String(date.getMinutes()).padStart(2, '0');
    }
});

// 更新时间显示
function updateTimeDisplay() {
    const now = new Date();
    document.getElementById('current-timestamp').textContent = Math.floor(now.getTime() / 1000);
    document.getElementById('beijing-time').textContent = 
        now.getFullYear() + '-' + 
        String(now.getMonth() + 1).padStart(2, '0') + '-' + 
        String(now.getDate()).padStart(2, '0') + ' ' + 
        String(now.getHours()).padStart(2, '0') + ':' + 
        String(now.getMinutes()).padStart(2, '0') + ':' + 
        String(now.getSeconds()).padStart(2, '0');
    
    const utcNow = new Date(now.toUTCString());
    document.getElementById('utc-time').textContent = 
        utcNow.getFullYear() + '-' + 
        String(utcNow.getMonth() + 1).padStart(2, '0') + '-' + 
        String(utcNow.getDate()).padStart(2, '0') + ' ' + 
        String(utcNow.getHours()).padStart(2, '0') + ':' + 
        String(utcNow.getMinutes()).padStart(2, '0') + ':' + 
        String(utcNow.getSeconds()).padStart(2, '0');
}

setInterval(updateTimeDisplay, 1000);

});
</script>

<style>
.web-tools-container {

background: #fff;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin: 20px 0;
overflow: hidden;

}

.tools-tabs {

display: flex;
background: #f5f5f5;
border-bottom: 1px solid #ddd;
flex-wrap: wrap;

}

.tool-tab {

padding: 12px 20px;
background: none;
border: none;
border-right: 1px solid #ddd;
cursor: pointer;
font-size: 14px;
transition: all 0.3s;

}

.tool-tab:hover {

background: #e9e9e9;

}

.tool-tab.active {

background: #0073aa;
color: white;

}

.tool-pane {

display: none;
padding: 20px;

}

.tool-pane.active {

display: block;

}

.tool-description {

margin-bottom: 20px;
padding-bottom: 15px;
border-bottom: 1px solid #eee;

}

.tool-description h3 {

margin: 0 0 5px 0;
color: #333;

}

.tool-description p {

margin: 0;
color: #666;
font-size: 14px;

}

.tool-interface {

display: flex;
flex-direction: column;
gap: 20px;

}

.input-area, .output-area {

display: flex;
flex-direction: column;
gap: 10px;

}

textarea {

width: 100%;
min-height: 150px;
padding: 12px;
border: 1px solid #ddd;
border-radius: 4px;
font-family: 'Consolas', 'Monaco', monospace;
font-size: 14px;
resize: vertical;

}

.button-group {

display: flex;
gap: 10px;
flex-wrap: wrap;

}

button {

padding: 8px 16px;
background: #0073aa;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: background 0.3s;

}

button:hover {

background: #005a87;

}

.algorithm-selector {

display: flex;
gap: 10px;
margin-bottom: 15px;

}

select, input[type="text"] {

padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;

}

.timestamp-input {

display: flex;
flex-direction: column;
gap: 15px;

}

.input-group {

display: flex;
align-items: center;
gap: 10px;

}

.input-group label {

min-width: 120px;
font-weight: bold;

}

timestamp-result {

background: #f9f9f9;
padding: 15px;
border-radius: 4px;
border: 1px solid #eee;

}

timestamp-result p {

margin: 8px 0;

}
</style>
<?php

return ob_get_clean();

}

// 加密解密处理函数
add_action('wp_ajax_process_encryption', 'handle_encryption_request');
add_action('wp_ajax_nopriv_process_encryption', 'handle_encryption_request');

function handle_encryption_request() {

// 验证nonce
if (!wp_verify_nonce($_POST['nonce'], 'encryption_nonce')) {
    wp_send_json_error(array('error' => '安全验证失败'));
    return;
}

$text = isset($_POST['text']) ? $_POST['text'] : '';
$algorithm = isset($_POST['algorithm']) ? sanitize_text_field($_POST['algorithm']) : 'base64';
$key = isset($_POST['key']) ? $_POST['key'] : '';
$mode = isset($_POST['mode']) ? sanitize_text_field($_POST['mode']) : 'encrypt';

if (empty($text)) {
    wp_send_json_error(array('error' => '输入文本不能为空'));
    return;
}

$result = process_encryption($text, $algorithm, $key, $mode);

if ($result['success']) {
    wp_send_json_success(array('result' => $result['output']));
} else {
    wp_send_json_error(array('error' => $result['error']));
}

}

function process_encryption($text, $algorithm, $key, $mode) {

try {
    switch ($algorithm) {
        case 'base64':
            if ($mode === 'encrypt') {
                $output = base64_encode($text);
            } else {
                $output = base64_decode($text);
                if ($output === false) {
                    throw new Exception('Base64解码失败,请检查输入');
                }
            }
            break;
            
        case 'md5':
            $output = md5($text);
            break;
            
        case 'sha1':
            $output = sha1($text);
            break;
            
        case 'sha256':
            $output = hash('sha256', $text);
            break;
            
        case 'aes':
            // 简化的AES示例(实际应用中需要更安全的实现)
            if (empty($key)) {
                throw new Exception('AES加密需要提供密钥');
            }
            if ($mode === 'encrypt') {
                $output = openssl_encrypt($text, 'AES-128-ECB', $key, 0);
            } else {
                $output = openssl_decrypt($text, 'AES-128-ECB', $key, 0);
            }
            if ($output === false) {
                throw new Exception('AES处理失败');
            }
            break;
            
        default:
            throw new Exception('不支持的算法');
    }
    
    return array(
        'success' => true,
        'output' => $output
    );
    
} catch (Exception $e) {
    return array(
        'success' => false,
        'error' => $e->getMessage()
    );
}

}


---

## 五、安全性与性能优化

### 5.1 安全防护措施

// 安全增强功能
class CodeExecutionSecurity {


// 代码执行时间限制
const MAX_EXECUTION_TIME = 10; // 秒

// 内存限制
const MAX_MEMORY_LIMIT = '256M';

// 危险函数黑名单
private static $dangerous_functions = [
    'system', 'exec', 'shell_exec', 'passthru',
    'proc_open', 'popen', 'eval', 'create_function',
    'include', 'require', 'include_once', 'require_once',
    'fopen', 'file_get_contents', 'file_put_contents',
    'unlink', 'rmdir', 'mkdir'
];

// 危险模式黑名单
private static $dangerous_patterns = [
    '/`.*`/', // 反引号执行
    '/$_(GET|POST|REQUEST|COOKIE|SERVER)/', // 超全局变量
    '/phar:///', // PHAR反序列化
    '/expect:///', // Expect包装器
    '/php://(filter|input)/', // PHP包装器
];

/**
 * 检查代码安全性
 */
public static function check_code_safety($code, $language) {
    // 检查代码长度
    if (strlen($code) > 10000) {
        return array(
            'safe' => false,
            'reason' => '代码过长(超过10000字符)'
        );
    }
    
    // 语言特定的安全检查
    switch ($language) {
        case 'php':
            return self::check_php_code($code);
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5104.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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