<?php
/**
 * Name: Email Obfuscator
 * Description: Protect email addresses from spam bots by encoding them in HTML entities or JavaScript to prevent harvesting while keeping emails clickable for visitors
 * Category: Content
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Contact Email Protection",
 *     "description": "Hide email addresses from spam bots on contact pages while keeping them clickable for legitimate visitors."
 *   },
 *   {
 *     "title": "Team Directory",
 *     "description": "Protect dozens of staff email addresses on team page from being harvested by automated scrapers."
 *   },
 *   {
 *     "title": "Service Provider Info",
 *     "description": "Obfuscate support@ and sales@ email addresses displayed throughout site to reduce spam volume."
 *   }
 * ]
 * Added: 2025-06-24
 * Tags: email, spam, protection, obfuscation, security
 * WhereToFind: {
 *   "location": "Frontend (Page Source)",
 *   "url": "/",
 *   "instructions": "View page source - email addresses will be encoded, not plain text",
 *   "newTab": true
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardEmailObfuscator {

    public function __construct() {
        add_filter('the_content', [$this, 'obfuscate_email_addresses'], 999);
        add_filter('the_excerpt', [$this, 'obfuscate_email_addresses'], 999);
        add_filter('widget_text', [$this, 'obfuscate_email_addresses'], 999);
        add_filter('comment_text', [$this, 'obfuscate_email_addresses'], 999);
    }

    /**
     * Obfuscate email addresses in content
     */
    public function obfuscate_email_addresses($content) {
        // Skip if empty or in admin
        if (empty($content) || is_admin()) {
            return $content;
        }

        // Pattern to match email addresses
        $pattern = '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/';

        $content = preg_replace_callback($pattern, function($matches) {
            $email = $matches[1];
            $encoded = '';

            // Encode each character as HTML entity
            for ($i = 0; $i < strlen($email); $i++) {
                $encoded .= '&#' . ord($email[$i]) . ';';
            }

            return $encoded;
        }, $content);

        return $content;
    }

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return [
            'options' => [],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
}

$switchboard_instance = new SwitchboardEmailObfuscator();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
