<?php
/**
 * Name: Open External Links in New Tab
 * Description: Force all external links to automatically open in new browser tab to keep visitors on your site while they explore external resources and references
 * Category: Content
 * Icon: -
  * UseCases: [
 *   {
 *     "title": "Better User Experience",
 *     "description": "Keep visitors on your site by opening external links in new tabs automatically, so they don\'t lose their place."
 *   },
 *   {
 *     "title": "SEO Benefits",
 *     "description": "Reduce bounce rate by keeping your content accessible while users explore external resources in separate tabs."
 *   }
 * ]
 * Added: 2025-06-20
 * Tags: links, external, new-tab, target-blank, seo
 * WhereToFind: {
 *   "location": "Frontend (Posts/Pages)",
 *   "url": "/",
 *   "instructions": "Click any external link - should open in new tab",
 *   "newTab": true
 * }
 */

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

class SwitchboardExternalLinksNewTab {

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

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return [
            'options' => [],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
    
    public function add_target_blank($content) {
        $home_url = home_url();
        
        $content = preg_replace_callback(
            '/<a\s+([^>]*href=["\']([^"\']+)["\'][^>]*)>/i',
            function($matches) use ($home_url) {
                $full_tag = $matches[0];
                $url = $matches[2];
                
                // Skip if already has target
                if (stripos($full_tag, 'target=') !== false) {
                    return $full_tag;
                }
                
                // Check if external
                if (strpos($url, $home_url) === false && 
                    strpos($url, 'http') === 0) {
                    return str_replace('<a ', '<a target="_blank" rel="noopener noreferrer" ', $full_tag);
                }
                
                return $full_tag;
            },
            $content
        );
        
        return $content;
    }
}

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