robotstxt-mediaaudit/includes/Core/NetworkActivator.php
2026-06-08 18:01:39 +00:00

114 lines
2.6 KiB
PHP

<?php
/**
* Handles network-wide activation and deactivation in WordPress Multisite.
*
* @package MediaRightsAudit\Core
*/
namespace MediaRightsAudit\Core;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Manages network-level activation, deactivation, and new-site provisioning.
*
* On network activation, iterates all active sites and runs Activator::activate()
* in each site's context. On new site creation, provisions tables automatically
* when the plugin is network-active.
*/
class NetworkActivator {
/**
* Runs on network-wide plugin activation.
*
* Creates the shared network mirror table, seeds the network mode option
* (default: per_site), and runs per-site activation for every active site.
*
* @return void
*/
public static function network_activate(): void {
if ( ! is_multisite() ) {
return;
}
NetworkDatabase::create_network_table();
if ( false === get_site_option( 'robotstxt_mediaaudit_network_mode' ) ) {
add_site_option( 'robotstxt_mediaaudit_network_mode', 'per_site' );
}
foreach ( self::get_active_site_ids() as $site_id ) {
switch_to_blog( $site_id );
Activator::activate();
restore_current_blog();
}
}
/**
* Runs on network-wide plugin deactivation.
*
* Cancels all scheduled Action Scheduler jobs on every site. Tables and
* data are preserved (deactivation is reversible).
*
* @return void
*/
public static function network_deactivate(): void {
if ( ! is_multisite() ) {
return;
}
foreach ( self::get_active_site_ids() as $site_id ) {
switch_to_blog( $site_id );
Deactivator::deactivate();
restore_current_blog();
}
}
/**
* Provisions plugin tables for a newly created site when the plugin is network-active.
*
* Hooked to wp_initialize_site (WordPress 5.1+).
*
* @param \WP_Site $new_site The newly created site object.
*
* @return void
*/
public static function on_new_site( \WP_Site $new_site ): void {
if ( ! is_multisite() ) {
return;
}
if ( ! is_plugin_active_for_network( plugin_basename( ROBOTSTXT_MEDIAAUDIT_PLUGIN_FILE ) ) ) {
return;
}
switch_to_blog( (int) $new_site->blog_id );
Activator::activate();
restore_current_blog();
}
/**
* Returns an array of active site IDs on this network.
*
* @return array<int>
*/
public static function get_active_site_ids(): array {
if ( ! is_multisite() ) {
return array( get_current_blog_id() );
}
$sites = get_sites(
array(
'fields' => 'ids',
'number' => 0,
'archived' => 0,
'deleted' => 0,
'spam' => 0,
)
);
return is_array( $sites ) ? array_map( 'intval', $sites ) : array();
}
}