<?php
/**
 * Name: Disable REST API
 * Description: Disable WordPress REST API access for non-authenticated users to enhance security and prevent unauthorized data access while keeping it available for logged users
 * Category: Security
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Prevent Data Scraping",
 *     "description": "Block public REST API access to prevent bots from harvesting all your posts, users, and content data via /wp-json endpoints."
 *   },
 *   {
 *     "title": "Reduce Attack Surface",
 *     "description": "Disable REST API for non-logged-in users to eliminate potential vulnerability exploitation vectors."
 *   },
 *   {
 *     "title": "Membership Site Protection",
 *     "description": "Prevent unauthorized access to member content or user data exposed through REST API endpoints."
 *   }
 * ]
 * WhereToFind: {
 *   "location": "Works automatically",
 *   "url": "",
 *   "instructions": "REST API blocked for non-authenticated users",
 *   "newTab": false
 * }
 * Added: 2025-08-14
 * Tags: rest-api, api, security, disable, authentication
 */

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

class SwitchboardDisableRestApi {

    public function __construct() {
        // Disable REST API for non-authenticated users
        add_filter('rest_authentication_errors', [$this, 'restrict_rest_api']);

        // Remove REST API links from head (for non-logged-in users)
        remove_action('wp_head', 'rest_output_link_wp_head', 10);
        remove_action('template_redirect', 'rest_output_link_header', 11);
        remove_action('xmlrpc_rsd_apis', 'rest_output_rsd');
    }

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

    public function restrict_rest_api($result) {
        // Only block if user is not logged in
        if (!is_user_logged_in()) {
            return new WP_Error(
                'rest_disabled',
                esc_html__('REST API is disabled for non-authenticated users.', 'wpswitchboard'),
                ['status' => 401]
            );
        }
        return $result;
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardDisableRestApi();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
