validate_content($content);
if (is_wp_error($validation)) {
return '
' . esc_html($validation->get_error_message()) . '
';
}
// First, ensure the content is treated as plain text
// Multiple layers of safety to prevent any code execution
// 1. Convert to UTF-8 if needed
if (!mb_check_encoding($content, 'UTF-8')) {
$content = mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content));
}
// 2. Remove any null bytes
$content = str_replace("\0", '', $content);
// 3. HTML encode everything - this is crucial for safety
$safe_content = htmlspecialchars($content, ENT_QUOTES | ENT_HTML5 | ENT_SUBSTITUTE, 'UTF-8', false);
// 4. Additional escaping for JavaScript context
$safe_content = $this->escape_for_javascript($safe_content);
// 5. Get language for syntax highlighting
$language = $this->detect_language($filename);
// 6. Prepare the code block with line numbers
$lines = explode("\n", $safe_content);
$formatted_code = $this->format_with_line_numbers($lines);
// 7. Wrap in proper HTML structure
$output = '';
$output .= '';
$output .= '
';
$output .= '
';
$output .= $formatted_code;
$output .= '
';
$output .= '
';
$output .= '
';
return $output;
}
/**
* Format code with line numbers
*/
private function format_with_line_numbers($lines) {
$output = '';
$line_count = count($lines);
$digit_count = strlen((string)$line_count);
foreach ($lines as $index => $line) {
$line_num = $index + 1;
$padded_num = str_pad($line_num, $digit_count, ' ', STR_PAD_LEFT);
$output .= '' . $padded_num . '';
$output .= '' . $line . '' . "\n";
}
return rtrim($output);
}
/**
* Additional escaping for JavaScript context
*/
private function escape_for_javascript($content) {
// Escape any remaining potentially dangerous patterns
$patterns = array(
'/