<?php
/**
 * Content helper to safely render admin-authored HTML with an allowlist of tags/attributes.
 * This avoids showing raw HTML text while still preventing most unsafe markup.
 */

if (!function_exists('sanitize_rich_content')) {
    /**
     * Allow a safe subset of HTML. Extend as needed.
     *
     * @param string $html
     * @return string sanitized HTML
     */
    function sanitize_rich_content($html)
    {
        if (!is_string($html) || $html === '') {
            return '';
        }

        // Allowed tags (no scripts, iframes, styles)
        $allowed_tags = '<p><br><br/><strong><b><em><i><u><s><ul><ol><li><blockquote><code><pre>' .
                        '<h1><h2><h3><h4><h5><h6>' .
                        '<a><img><hr><span><div>' .
                        '<table><thead><tbody><tr><th><td>';

        // Strip disallowed tags first
        $clean = strip_tags($html, $allowed_tags);

        // Basic attribute allowlist: href/src/alt/title/target/rel for a/img, class/style limited
        // Remove event handlers and javascript: URLs
        $clean = preg_replace('/\son[a-z]+\s*=\s*"[^"]*"/i', '', $clean); // on*="..."
        $clean = preg_replace("/\son[a-z]+\s*=\s*'[^']*'/i", '', $clean); // on*='...'
        $clean = preg_replace('/\sstyle\s*=\s*"[^"]*"/i', ' ', $clean);   // drop inline styles (optional)
        $clean = preg_replace("/\sstyle\s*=\s*'[^']*'/i", ' ', $clean);

        // Disallow javascript: in href/src
        $clean = preg_replace('/(href|src)\s*=\s*"\s*javascript:[^"]*"/i', '$1="#"', $clean);
        $clean = preg_replace("/(href|src)\s*=\s*'\s*javascript:[^']*'/i", '$1="#"', $clean);

        return $clean;
    }
}
