This commit is contained in:
Javier Casares 2026-06-08 18:01:39 +00:00
commit b6a55a7f04
27 changed files with 2221 additions and 45 deletions

View file

@ -1,4 +1,4 @@
/* global mraAdmin, mraTools */
/* global mraAdmin, mraTools, mraAlerts, mraNetworkTools */
( function ( $ ) {
'use strict';
@ -163,5 +163,39 @@
$row.prop( 'hidden', true );
$( '[data-target="' + rowId + '"]' ).text( mraAlerts.i18n.dismiss );
} );
// Network trigger buttons — Network Tools page.
if ( typeof mraNetworkTools !== 'undefined' ) {
$( document ).on( 'click', '.mra-network-trigger', function () {
var $btn = $( this );
var $status = $btn.closest( '.mra-op-card' ).find( '.mra-network-trigger-status' );
var type = $btn.data( 'type' );
$btn.prop( 'disabled', true );
$status.text( mraNetworkTools.i18n.scheduling );
$.ajax( {
url: mraNetworkTools.ajaxUrl,
type: 'POST',
data: {
action: 'mra_network_trigger_scan',
type: type,
nonce: mraNetworkTools.nonce
},
success: function ( res ) {
if ( res.success ) {
$status.text( res.data.message || mraNetworkTools.i18n.done );
} else {
$status.text( mraNetworkTools.i18n.error );
}
$btn.prop( 'disabled', false );
},
error: function () {
$status.text( mraNetworkTools.i18n.error );
$btn.prop( 'disabled', false );
}
} );
} );
}
} );
} ( jQuery ) );

View file

@ -1,5 +1,32 @@
== Changelog ==
= 1.8.1 =
_Release date: 2026-06-08_
**Fixed**
* Network Operations buttons now use standard HTML POST forms with server-side redirect (PRG pattern), replacing the AJAX approach that failed due to network admin script-loading constraints.
* Removed unreliable in-render script enqueueing for Network Tools page; operation buttons now work without JavaScript.
* JS dismiss/cancel labels on the Alerts page now use i18n strings from `wp_localize_script`.
= 1.8.0 =
_Release date: 2026-06-08_
**Added**
* **WordPress Multisite support** — plugin now declares `Network: true` and can be activated network-wide.
* **Two operating modes** configurable from Network Admin → Media Audit → Settings:
* **Per site** (default) — each site operates independently, identical to v1.7.x behaviour.
* **Central** — API credentials and filter lists are configured once in the network admin and shared across all sites. Site-level admin pages show a placeholder notice linking to the network admin panel.
* **Network admin panel** (central mode only): aggregated Audit list, Alerts list, and Tools page showing all media across all sites with a "Site" column identifying origin. Network Tools page allows triggering internal and external scans across all sites via Action Scheduler.
* **Network mirror table** `{base_prefix}mra_network_index` — lightweight denormalised index enabling fast cross-site queries without per-request `switch_to_blog()` loops. Synchronised automatically after each scan batch.
* **New site provisioning** — when the plugin is network-active, tables are automatically created for newly added sites via the `wp_initialize_site` hook.
* **Settings migration** — on first switch to central mode, existing settings from the main site are copied to the network option as a starting point.
* **Network-aware uninstall** — when `delete_on_uninstall` is set, uninstalling removes tables and options from every site in the network plus the mirror table.
* DB schema version bumped to `1.3.0`.
= 1.7.1 =
_Release date: 2026-06-02_

View file

@ -137,6 +137,10 @@ class AlertsPage {
delete_transient( 'mra_alert_count' );
self::invalidate_cache();
if ( is_multisite() && 'central' === get_site_option( 'robotstxt_mediaaudit_network_mode', 'per_site' ) ) {
\MediaRightsAudit\Core\NetworkDatabase::update_dismissal_flag( get_current_blog_id(), $attachment_id, true );
}
}
/**
@ -158,6 +162,10 @@ class AlertsPage {
delete_transient( 'mra_alert_count' );
self::invalidate_cache();
if ( is_multisite() && 'central' === get_site_option( 'robotstxt_mediaaudit_network_mode', 'per_site' ) ) {
\MediaRightsAudit\Core\NetworkDatabase::update_dismissal_flag( get_current_blog_id(), $attachment_id, false );
}
}
// -------------------------------------------------------------------------

View file

@ -222,6 +222,40 @@ class Settings {
return in_array( $raw, self::TAB_KEYS, true ) ? $raw : 'general';
}
/**
* Returns the effective settings for the current context.
*
* In Multisite central mode, reads from the shared network site option so that
* all providers and scanners pick up network-wide API credentials and filter
* lists without changing per-site DB records.
*
* @return array<string, mixed>
*/
public static function get_effective_settings(): array {
if ( is_multisite() && 'central' === get_site_option( 'robotstxt_mediaaudit_network_mode', 'per_site' ) ) {
$raw = get_site_option( 'robotstxt_mediaaudit_network_settings', array() );
} else {
$raw = get_option( self::OPTION_NAME, array() );
}
return is_array( $raw ) ? $raw : array();
}
/**
* Sanitizes a settings array for the network admin, merging against $current.
*
* Mirrors the tab-based logic of sanitize() but accepts the existing values
* as a parameter rather than reading from get_option(), so it can be used
* for both per-site and network site options.
*
* @param array<string, mixed> $input Raw POST input (must include '_tab').
* @param array<string, mixed> $current Existing option values to merge against.
*
* @return array<string, mixed>
*/
public function sanitize_for_network( array $input, array $current ): array {
return $this->sanitize_with_base( $input, $current );
}
/**
* Registers all settings, sections, and fields via the WordPress Settings API.
*
@ -367,7 +401,19 @@ class Settings {
public function sanitize( $input ): array {
$raw = get_option( self::OPTION_NAME, array() );
$current = is_array( $raw ) ? $raw : array();
$output = $current;
return $this->sanitize_with_base( $input, $current );
}
/**
* Core tab-based sanitization logic shared by sanitize() and sanitize_for_network().
*
* @param mixed $input Raw POST input.
* @param array<string, mixed> $current Existing values to merge against.
*
* @return array<string, mixed>
*/
private function sanitize_with_base( $input, array $current ): array {
$output = $current;
if ( ! is_array( $input ) ) {
return $output;
@ -430,11 +476,18 @@ class Settings {
}
/**
* Sanitises a newline-separated list of hostnames into a deduplicated array.
* Public proxy for sanitize_hostname_list(), used by Network\Settings.
*
* Accepts plain hostnames (example.com) and explicit wildcard prefixes
* (*.example.com). A plain hostname implicitly covers all its subdomains
* at match time.
* @param mixed $raw Raw textarea value.
*
* @return list<string>
*/
public function sanitize_hostname_list_public( mixed $raw ): array {
return $this->sanitize_hostname_list( $raw );
}
/**
* Sanitises a newline-separated hostname list into a deduplicated sorted array.
*
* @param mixed $raw Raw textarea value.
*

View file

@ -11,6 +11,7 @@ if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use MediaRightsAudit\Admin\Settings;
use MediaRightsAudit\Core\Database;
use MediaRightsAudit\Core\Queue\Scheduler;
use MediaRightsAudit\External\ExternalScanner;
@ -132,8 +133,7 @@ class ToolsPage {
case 'external':
ExternalScanner::queue_all_pending();
$raw_opts = get_option( 'robotstxt_mediaaudit_settings', array() );
$opts_arr = is_array( $raw_opts ) ? $raw_opts : array();
$opts_arr = Settings::get_effective_settings();
$bs_setting = $opts_arr['external_batch_size'] ?? null;
$ajax_bs = is_numeric( $bs_setting ) ? max( 1, (int) $bs_setting ) : 10;
ExternalScanner::scan_batch( $ajax_bs );

View file

@ -11,6 +11,8 @@ if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use MediaRightsAudit\Core\NetworkDatabase;
/**
* Manages all custom table creation and schema migrations.
*
@ -29,6 +31,7 @@ class Database {
self::migration_101();
self::migration_110();
self::migration_120();
self::migration_130();
}
/**
@ -57,6 +60,10 @@ class Database {
if ( version_compare( $current, '1.2.0', '<' ) ) {
self::migration_120();
}
if ( version_compare( $current, '1.3.0', '<' ) ) {
self::migration_130();
}
}
/**
@ -92,6 +99,10 @@ class Database {
// phpcs:enable WordPress.DB.DirectDatabaseQuery
delete_transient( 'mra_alert_count' );
if ( is_multisite() && 'central' === get_site_option( 'robotstxt_mediaaudit_network_mode', 'per_site' ) ) {
NetworkDatabase::clear_site( get_current_blog_id() );
}
}
// -------------------------------------------------------------------------
@ -256,4 +267,23 @@ class Database {
) {$charset_collate};"
);
}
/**
* Migration 1.3.0 — creates the network mirror table (Multisite central mode only).
*
* For single-site installs this is a no-op. The network table lives in the
* main site's DB and is managed by NetworkDatabase::create_network_table().
* This migration entry exists only to advance the per-site DB version constant.
*
* @return void
*/
private static function migration_130(): void {
if ( ! is_multisite() ) {
return;
}
if ( 'central' === get_site_option( 'robotstxt_mediaaudit_network_mode', 'per_site' ) ) {
NetworkDatabase::create_network_table();
}
}
}

View file

@ -0,0 +1,114 @@
<?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();
}
}

View file

@ -0,0 +1,261 @@
<?php
/**
* Network-level database operations for the cross-site mirror index.
*
* @package MediaRightsAudit\Core
*/
namespace MediaRightsAudit\Core;
use MediaRightsAudit\External\HostnameFilter;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Manages {base_prefix}mra_network_index, a denormalized mirror of each site's
* mra_media_index that enables fast cross-site queries in the network admin.
*
* Detailed data (top_domains JSON, raw_response) stays in per-site tables and
* is loaded on demand via switch_to_blog(). This table holds only the fields
* needed for list display, filtering, and aggregated stats.
*
* All sync methods must be called while the target site's context is active
* (switch_to_blog already called), so $wpdb->prefix resolves to per-site tables
* while $wpdb->base_prefix always resolves to the network-wide prefix.
*/
class NetworkDatabase {
/**
* Returns the fully-qualified network mirror table name.
*
* Uses base_prefix so it lives in the main site's DB regardless of active blog.
*
* @return string
*/
public static function table_name(): string {
global $wpdb;
return $wpdb->base_prefix . 'mra_network_index';
}
/**
* Creates the network mirror table using dbDelta (idempotent).
*
* @return void
*/
public static function create_network_table(): void {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table = self::table_name();
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta(
"CREATE TABLE {$table} (
site_id bigint(20) unsigned NOT NULL,
attachment_id bigint(20) unsigned NOT NULL,
site_url varchar(255) NOT NULL DEFAULT '',
file_name varchar(255) NOT NULL DEFAULT '',
file_url text NOT NULL,
mime_type varchar(100) NOT NULL DEFAULT '',
file_size bigint(20) unsigned NOT NULL DEFAULT 0,
external_status enum('pending','queued','scanned','matches','error') NOT NULL DEFAULT 'pending',
internal_scanned_at datetime DEFAULT NULL,
external_scanned_at datetime DEFAULT NULL,
has_alert tinyint(1) NOT NULL DEFAULT 0,
is_dismissed tinyint(1) NOT NULL DEFAULT 0,
updated_at datetime NOT NULL,
PRIMARY KEY (site_id, attachment_id),
KEY external_status (external_status),
KEY has_alert (has_alert)
) {$charset_collate};"
);
}
/**
* Drops the network mirror table. Used only during full network uninstall.
*
* @return void
*/
public static function drop_network_table(): void {
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$wpdb->query( "DROP TABLE IF EXISTS `{$table}`" );
}
/**
* Removes all mirror rows for a given site.
*
* Called when a site resets all its plugin data (truncate_all).
*
* @param int $site_id WordPress blog ID.
*
* @return void
*/
public static function clear_site( int $site_id ): void {
global $wpdb;
$wpdb->delete( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
self::table_name(),
array( 'site_id' => $site_id ),
array( '%d' )
);
}
/**
* Syncs the mirror table for the currently active site.
*
* Reads mra_media_index, mra_external_results (for has_alert), and
* mra_dismissed_alerts (for is_dismissed) from the current site's tables,
* then replaces all mirror rows for this site.
*
* Must be called while switch_to_blog($site_id) is active.
*
* @param int $site_id WordPress blog ID (must match the currently active blog).
*
* @return void
*/
public static function sync_site( int $site_id ): void {
global $wpdb;
$site_url = get_site_url( $site_id );
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$rows = $wpdb->get_results(
"SELECT attachment_id, file_name, file_url, mime_type, file_size,
external_status, internal_scanned_at, external_scanned_at
FROM {$wpdb->prefix}mra_media_index",
ARRAY_A
);
self::clear_site( $site_id );
if ( empty( $rows ) || ! is_array( $rows ) ) {
return;
}
$ids = array_map( 'intval', array_column( $rows, 'attachment_id' ) );
$placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
// Load top_domains per attachment to compute has_alert.
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
$domain_rows = $wpdb->get_results(
$wpdb->prepare(
"SELECT attachment_id, top_domains
FROM {$wpdb->prefix}mra_external_results
WHERE attachment_id IN ({$placeholders})",
...$ids
),
ARRAY_A
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
// Build merged domain map: attachment_id → domain → count.
$domains_by_id = array();
if ( is_array( $domain_rows ) ) {
foreach ( $domain_rows as $dr ) {
if ( ! is_array( $dr ) ) {
continue;
}
$aid = is_numeric( $dr['attachment_id'] ?? null ) ? (int) $dr['attachment_id'] : 0;
$td = is_string( $dr['top_domains'] ?? null ) ? json_decode( $dr['top_domains'], true ) : null;
if ( $aid <= 0 || ! is_array( $td ) ) {
continue;
}
if ( ! isset( $domains_by_id[ $aid ] ) ) {
$domains_by_id[ $aid ] = array();
}
foreach ( $td as $domain => $count ) {
if ( is_string( $domain ) ) {
$domains_by_id[ $aid ][ $domain ] = ( $domains_by_id[ $aid ][ $domain ] ?? 0 ) + ( is_numeric( $count ) ? (int) $count : 0 );
}
}
}
}
// Load dismissed attachment IDs.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$dismissed_col = $wpdb->get_col( "SELECT attachment_id FROM {$wpdb->prefix}mra_dismissed_alerts" );
$dismissed_ids = array();
if ( is_array( $dismissed_col ) ) {
foreach ( $dismissed_col as $did ) {
if ( is_numeric( $did ) ) {
$dismissed_ids[ (int) $did ] = true;
}
}
}
$now = current_time( 'mysql', true );
foreach ( $rows as $row ) {
if ( ! is_array( $row ) ) {
continue;
}
$aid = is_numeric( $row['attachment_id'] ?? null ) ? (int) $row['attachment_id'] : 0;
if ( $aid <= 0 ) {
continue;
}
$has_alert = HostnameFilter::has_alert_domains( $domains_by_id[ $aid ] ?? array() ) ? 1 : 0;
$is_dismissed = isset( $dismissed_ids[ $aid ] ) ? 1 : 0;
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$wpdb->query(
$wpdb->prepare(
"REPLACE INTO `{$table}`
(site_id, attachment_id, site_url, file_name, file_url, mime_type,
file_size, external_status, internal_scanned_at, external_scanned_at,
has_alert, is_dismissed, updated_at)
VALUES (%d, %d, %s, %s, %s, %s, %d, %s, %s, %s, %d, %d, %s)",
$site_id,
$aid,
$site_url,
is_string( $row['file_name'] ?? null ) ? $row['file_name'] : '',
is_string( $row['file_url'] ?? null ) ? $row['file_url'] : '',
is_string( $row['mime_type'] ?? null ) ? $row['mime_type'] : '',
is_numeric( $row['file_size'] ?? null ) ? (int) $row['file_size'] : 0,
is_string( $row['external_status'] ?? null ) ? $row['external_status'] : 'pending',
is_string( $row['internal_scanned_at'] ?? null ) && '' !== $row['internal_scanned_at'] ? $row['internal_scanned_at'] : null,
is_string( $row['external_scanned_at'] ?? null ) && '' !== $row['external_scanned_at'] ? $row['external_scanned_at'] : null,
$has_alert,
$is_dismissed,
$now
)
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
}
}
/**
* Updates the dismissal flag for a single attachment in the mirror.
*
* Lighter alternative to sync_site() when only dismissal status changes.
*
* @param int $site_id WordPress blog ID.
* @param int $attachment_id WordPress attachment ID.
* @param bool $is_dismissed Whether the alert is dismissed.
*
* @return void
*/
public static function update_dismissal_flag( int $site_id, int $attachment_id, bool $is_dismissed ): void {
global $wpdb;
$wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
self::table_name(),
array(
'is_dismissed' => $is_dismissed ? 1 : 0,
'updated_at' => current_time( 'mysql', true ),
),
array(
'site_id' => $site_id,
'attachment_id' => $attachment_id,
),
array( '%d', '%s' ),
array( '%d', '%d' )
);
}
}

View file

@ -118,6 +118,20 @@ class Plugin {
* @return void
*/
public function register_admin_pages(): void {
// In central mode, replace the full admin UI with a placeholder notice.
if ( is_multisite() && 'central' === get_site_option( 'robotstxt_mediaaudit_network_mode', 'per_site' ) ) {
add_menu_page(
__( 'Media Audit', 'robotstxt-mediaaudit' ),
__( 'Media Audit', 'robotstxt-mediaaudit' ),
'edit_others_posts',
'robotstxt-mediaaudit',
array( $this, 'render_central_mode_notice' ),
'dashicons-camera',
11
);
return;
}
$suffix = add_menu_page(
__( 'Media Audit', 'robotstxt-mediaaudit' ),
__( 'Media Audit', 'robotstxt-mediaaudit' ),
@ -233,8 +247,7 @@ class Plugin {
* @return bool
*/
private function is_provider_configured( string $slug ): bool {
$raw = get_option( Settings::OPTION_NAME, array() );
$opts = is_array( $raw ) ? $raw : array();
$opts = Settings::get_effective_settings();
if ( 'picdefense' === $slug ) {
$uid = $opts['picdefense_user_id'] ?? '';
@ -245,6 +258,33 @@ class Plugin {
return false;
}
/**
* Renders the central-mode placeholder shown on each site's admin pages.
*
* Replaces the full per-site admin UI when the network is operating in
* central mode, directing users to the network admin panel instead.
*
* @return void
*/
public function render_central_mode_notice(): void {
$network_url = network_admin_url( 'admin.php?page=robotstxt-mediaaudit-network' );
?>
<div class="wrap">
<h1><?php esc_html_e( 'Media Audit', 'robotstxt-mediaaudit' ); ?></h1>
<div class="notice notice-info" style="margin-top:1em;">
<p>
<?php esc_html_e( 'This plugin is managed at the network level. Media data for this site is collected and stored here, but viewed and managed from the Network Admin panel.', 'robotstxt-mediaaudit' ); ?>
</p>
<p>
<a href="<?php echo esc_url( $network_url ); ?>" class="button button-primary">
<?php esc_html_e( 'Go to Network Media Audit →', 'robotstxt-mediaaudit' ); ?>
</a>
</p>
</div>
</div>
<?php
}
/**
* Registers WP-CLI commands when running in CLI context.
*

View file

@ -11,6 +11,8 @@ if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use MediaRightsAudit\Admin\Settings;
/**
* Provides rate-limited scanning via a transient-based per-minute counter.
*
@ -41,8 +43,7 @@ abstract class AbstractProvider {
* @return positive-int
*/
public function rate_limit(): int {
$raw = get_option( 'robotstxt_mediaaudit_settings', array() );
$opts = is_array( $raw ) ? $raw : array();
$opts = Settings::get_effective_settings();
$val = $opts['rate_limit_per_minute'] ?? null;
return is_numeric( $val ) ? max( 1, (int) $val ) : 10;
}

View file

@ -11,6 +11,7 @@ if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use MediaRightsAudit\Admin\Settings;
use MediaRightsAudit\Core\Queue\Scheduler;
/**
@ -142,8 +143,7 @@ class ExternalScanner {
* @return void
*/
public static function process_scheduled_batch(): void {
$raw = get_option( 'robotstxt_mediaaudit_settings', array() );
$opts = is_array( $raw ) ? $raw : array();
$opts = Settings::get_effective_settings();
$bs_val = $opts['external_batch_size'] ?? null;
$batch_size = is_numeric( $bs_val ) ? max( 1, (int) $bs_val ) : 10;
@ -151,6 +151,10 @@ class ExternalScanner {
delete_transient( 'mra_alert_count' );
if ( is_multisite() && 'central' === get_site_option( 'robotstxt_mediaaudit_network_mode', 'per_site' ) ) {
\MediaRightsAudit\Core\NetworkDatabase::sync_site( get_current_blog_id() );
}
if ( self::get_pending_count() > 0 ) {
Scheduler::schedule_single( self::AS_HOOK );
}

View file

@ -126,9 +126,9 @@ class GoogleVisionProvider extends AbstractProvider {
* @return string Empty string if not configured.
*/
private function get_api_key(): string {
$raw = get_option( Settings::OPTION_NAME, array() );
$opts = is_array( $raw ) ? $raw : array();
$val = $opts['google_vision_api_key'] ?? null;
$opts = Settings::get_effective_settings();
$val = $opts['google_vision_api_key'] ?? null;
return is_string( $val ) ? trim( $val ) : '';
}

View file

@ -112,8 +112,8 @@ class PicDefenseProvider extends AbstractProvider {
* @return array{string, string} [user_id, api_key] — empty strings if not configured.
*/
private function get_credentials(): array {
$raw = get_option( Settings::OPTION_NAME, array() );
$opts = is_array( $raw ) ? $raw : array();
$opts = Settings::get_effective_settings();
$uid_val = $opts['picdefense_user_id'] ?? null;
$key_val = $opts['picdefense_api_key'] ?? null;
$user_id = is_string( $uid_val ) ? trim( $uid_val ) : '';

View file

@ -104,9 +104,9 @@ class TinEyeProvider extends AbstractProvider {
* @return string Empty string if not configured.
*/
private function get_api_key(): string {
$raw = get_option( Settings::OPTION_NAME, array() );
$opts = is_array( $raw ) ? $raw : array();
$val = $opts['tineye_api_key'] ?? null;
$opts = Settings::get_effective_settings();
$val = $opts['tineye_api_key'] ?? null;
return is_string( $val ) ? trim( $val ) : '';
}

View file

@ -159,6 +159,10 @@ class AttachmentIndexer {
public static function process_scheduled_batch(): void {
self::index_batch();
if ( is_multisite() && 'central' === get_site_option( 'robotstxt_mediaaudit_network_mode', 'per_site' ) ) {
\MediaRightsAudit\Core\NetworkDatabase::sync_site( get_current_blog_id() );
}
if ( self::get_pending_count() > 0 ) {
Scheduler::schedule_single( self::AS_HOOK );
} else {

View file

@ -450,6 +450,10 @@ class UsageScanner {
public static function process_scheduled_batch(): void {
self::scan_batch();
if ( is_multisite() && 'central' === get_site_option( 'robotstxt_mediaaudit_network_mode', 'per_site' ) ) {
\MediaRightsAudit\Core\NetworkDatabase::sync_site( get_current_blog_id() );
}
if ( self::get_pending_count() > 0 ) {
Scheduler::schedule_single( self::AS_HOOK );
}

View file

@ -0,0 +1,73 @@
<?php
/**
* Network admin aggregated Alerts page.
*
* @package MediaRightsAudit\Network
*/
namespace MediaRightsAudit\Network;
use MediaRightsAudit\Core\NetworkDatabase;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Renders the aggregated alerts view for the network admin.
*
* Shows all active (non-dismissed) alert attachments across all sites,
* ordered by site. Alert dismissal is performed at the per-site level via
* a link to the site's own Alerts page.
*/
class AlertsPage {
/**
* Renders the network Alerts page.
*
* @return void
*/
public function render(): void {
if ( ! current_user_can( 'manage_network_options' ) ) {
wp_die( esc_html__( 'You do not have permission to access this page.', 'robotstxt-mediaaudit' ) );
}
$table = new NetworkListTable( true );
$table->prepare_items();
$total_alert = $this->get_active_alert_count();
?>
<div class="wrap">
<h1>
<?php esc_html_e( 'Network Alerts', 'robotstxt-mediaaudit' ); ?>
<?php if ( $total_alert > 0 ) : ?>
<span class="title-count"><?php echo esc_html( number_format_i18n( $total_alert ) ); ?></span>
<?php endif; ?>
</h1>
<p class="description">
<?php esc_html_e( 'Active copyright-risk alerts across all sites. To dismiss an alert, visit the Alerts page on the corresponding site.', 'robotstxt-mediaaudit' ); ?>
</p>
<form method="get">
<input type="hidden" name="page" value="robotstxt-mediaaudit-network-alerts" />
<?php $table->display(); ?>
</form>
</div>
<?php
}
/**
* Returns the total count of active (non-dismissed) alerts across the network.
*
* @return int
*/
private function get_active_alert_count(): int {
global $wpdb;
$table = NetworkDatabase::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
return (int) $wpdb->get_var( "SELECT COUNT(*) FROM `{$table}` WHERE has_alert = 1 AND is_dismissed = 0" );
}
}

View file

@ -0,0 +1,102 @@
<?php
/**
* Network admin aggregated Audit page.
*
* @package MediaRightsAudit\Network
*/
namespace MediaRightsAudit\Network;
use MediaRightsAudit\Core\NetworkDatabase;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Renders the aggregated media audit list for the network admin.
*
* Queries the network mirror table to show all media across all sites with
* a "Site" column identifying the origin of each attachment.
*/
class AuditPage {
/**
* Renders the network Audit page.
*
* @return void
*/
public function render(): void {
if ( ! current_user_can( 'manage_network_options' ) ) {
wp_die( esc_html__( 'You do not have permission to access this page.', 'robotstxt-mediaaudit' ) );
}
$table = new NetworkListTable( false );
$table->prepare_items();
$stats = $this->get_network_stats();
?>
<div class="wrap">
<h1><?php esc_html_e( 'Network Media Audit', 'robotstxt-mediaaudit' ); ?></h1>
<div class="mra-stats">
<?php
$this->stat_box( $stats['total_indexed'], __( 'Total Indexed', 'robotstxt-mediaaudit' ), '' );
$this->stat_box( $stats['total_matches'], __( 'External Matches', 'robotstxt-mediaaudit' ), '' );
$this->stat_box( $stats['total_alert'], __( 'Active Alerts', 'robotstxt-mediaaudit' ), '' );
$this->stat_box( $stats['total_sites'], __( 'Sites', 'robotstxt-mediaaudit' ), '' );
?>
</div>
<form method="get">
<input type="hidden" name="page" value="robotstxt-mediaaudit-network" />
<?php $table->display(); ?>
</form>
</div>
<?php
}
/**
* Renders a single stat box.
*
* @param int $value Numeric value.
* @param string $label Short label.
* @param string $sub Optional sub-label.
*
* @return void
*/
private function stat_box( int $value, string $label, string $sub ): void {
echo '<div class="mra-stat-box">';
echo '<strong>' . esc_html( number_format_i18n( $value ) ) . '</strong>';
echo '<span>' . esc_html( $label ) . '</span>';
if ( '' !== $sub ) {
echo '<small>' . esc_html( $sub ) . '</small>';
}
echo '</div>';
}
/**
* Returns aggregate stats from the network mirror table.
*
* @return array{total_indexed: int, total_matches: int, total_alert: int, total_sites: int}
*/
private function get_network_stats(): array {
global $wpdb;
$table = NetworkDatabase::table_name();
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$total_indexed = (int) $wpdb->get_var( "SELECT COUNT(*) FROM `{$table}`" );
$total_matches = (int) $wpdb->get_var( "SELECT COUNT(*) FROM `{$table}` WHERE external_status = 'matches'" );
$total_alert = (int) $wpdb->get_var( "SELECT COUNT(*) FROM `{$table}` WHERE has_alert = 1 AND is_dismissed = 0" );
$total_sites = (int) $wpdb->get_var( "SELECT COUNT(DISTINCT site_id) FROM `{$table}`" );
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
return array(
'total_indexed' => $total_indexed,
'total_matches' => $total_matches,
'total_alert' => $total_alert,
'total_sites' => $total_sites,
);
}
}

View file

@ -0,0 +1,304 @@
<?php
/**
* WP_List_Table subclass for the cross-site media audit list.
*
* @package MediaRightsAudit\Network
*/
namespace MediaRightsAudit\Network;
use MediaRightsAudit\Core\NetworkDatabase;
use MediaRightsAudit\External\HostnameFilter;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'WP_List_Table' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}
/**
* Renders the aggregated media list in the network admin Audit page.
*
* Queries {base_prefix}mra_network_index for fast cross-site listing.
* Detailed per-attachment data is accessed on demand via per-site URLs.
* A "Site" column is added to identify which site each attachment belongs to.
*/
class NetworkListTable extends \WP_List_Table {
/**
* Rows per page.
*/
const PER_PAGE = 30;
/**
* Alerts-only filter: when true, shows only has_alert=1 rows.
*
* @var bool
*/
private bool $alerts_only;
/**
* Initialises the list table.
*
* @param bool $alerts_only Whether to filter to alert rows only.
*/
public function __construct( bool $alerts_only = false ) {
parent::__construct(
array(
'singular' => 'mra-network-attachment',
'plural' => 'mra-network-attachments',
'ajax' => false,
)
);
$this->alerts_only = $alerts_only;
}
/**
* Returns the column definitions.
*
* @return array<string, string>
*/
public function get_columns(): array {
return array(
'cb' => '<input type="checkbox" />',
'site' => __( 'Site', 'robotstxt-mediaaudit' ),
'file_name' => __( 'Filename', 'robotstxt-mediaaudit' ),
'external_status' => __( 'External Status', 'robotstxt-mediaaudit' ),
'has_alert' => __( 'Alert', 'robotstxt-mediaaudit' ),
'external_scanned_at' => __( 'Last Scanned', 'robotstxt-mediaaudit' ),
);
}
/**
* Returns sortable column definitions.
*
* @return array<string, array<int, mixed>>
*/
protected function get_sortable_columns(): array {
return array(
'site' => array( 'site_url', false ),
'file_name' => array( 'file_name', false ),
'external_status' => array( 'external_status', false ),
'external_scanned_at' => array( 'external_scanned_at', false ),
);
}
/**
* Returns bulk action definitions.
*
* @return array<string, string>
*/
protected function get_bulk_actions(): array {
return array(
'run_external_scan' => __( 'Run External Scan', 'robotstxt-mediaaudit' ),
'purge_external_data' => __( 'Purge External Data', 'robotstxt-mediaaudit' ),
);
}
/**
* Renders the checkbox column.
*
* @param array<string, mixed> $item Row data.
*
* @return string
*/
protected function column_cb( $item ): string {
$site_id = is_numeric( $item['site_id'] ?? null ) ? (int) $item['site_id'] : 0;
$aid = is_numeric( $item['attachment_id'] ?? null ) ? (int) $item['attachment_id'] : 0;
return sprintf(
'<input type="checkbox" name="mra_item[]" value="%d_%d" />',
$site_id,
$aid
);
}
/**
* Renders the Site column.
*
* @param array<string, mixed> $item Row data.
*
* @return string
*/
protected function column_site( array $item ): string {
$site_id = is_numeric( $item['site_id'] ?? null ) ? (int) $item['site_id'] : 0;
$site_url = is_string( $item['site_url'] ?? null ) ? $item['site_url'] : '';
$site_details = get_site( $site_id );
$site_name = $site_details instanceof \WP_Site ? esc_html( $site_details->blogname ) : esc_html( $site_url );
if ( $site_url ) {
$admin_url = get_admin_url( $site_id, 'admin.php?page=robotstxt-mediaaudit' );
return sprintf(
'<a href="%s" target="_blank">%s</a><br /><small>%s</small>',
esc_url( $admin_url ),
$site_name,
esc_html( $site_url )
);
}
return $site_name;
}
/**
* Renders the Filename column with a link to the per-site detail page.
*
* @param array<string, mixed> $item Row data.
*
* @return string
*/
protected function column_file_name( array $item ): string {
$site_id = is_numeric( $item['site_id'] ?? null ) ? (int) $item['site_id'] : 0;
$aid = is_numeric( $item['attachment_id'] ?? null ) ? (int) $item['attachment_id'] : 0;
$filename = is_string( $item['file_name'] ?? null ) ? $item['file_name'] : "#{$aid}";
$detail_url = get_admin_url(
$site_id,
'admin.php?page=robotstxt-mediaaudit-detail&attachment_id=' . $aid
);
return sprintf(
'<a href="%s" target="_blank">%s</a>',
esc_url( $detail_url ),
esc_html( $filename )
);
}
/**
* Renders the External Status column.
*
* @param array<string, mixed> $item Row data.
*
* @return string
*/
protected function column_external_status( array $item ): string {
$status = is_string( $item['external_status'] ?? null ) ? $item['external_status'] : 'pending';
return '<span class="mra-badge mra-status-' . esc_attr( $status ) . '">' . esc_html( ucfirst( $status ) ) . '</span>';
}
/**
* Renders the Alert column.
*
* @param array<string, mixed> $item Row data.
*
* @return string
*/
protected function column_has_alert( array $item ): string {
$has_alert = ! empty( $item['has_alert'] );
$is_dismissed = ! empty( $item['is_dismissed'] );
if ( $has_alert && $is_dismissed ) {
return '<span class="mra-badge">' . esc_html__( 'Dismissed', 'robotstxt-mediaaudit' ) . '</span>';
}
if ( $has_alert ) {
return '<span class="mra-badge mra-badge-alert">' . esc_html__( 'Alert', 'robotstxt-mediaaudit' ) . '</span>';
}
return '&mdash;';
}
/**
* Renders the Last Scanned column.
*
* @param array<string, mixed> $item Row data.
*
* @return string
*/
protected function column_external_scanned_at( array $item ): string {
$val = $item['external_scanned_at'] ?? null;
return is_string( $val ) && '' !== $val ? esc_html( $val ) : '&mdash;';
}
/**
* Default column renderer.
*
* @param array<string, mixed> $item Row data.
* @param string $column_name Column key.
*
* @return string
*/
protected function column_default( $item, $column_name ): string {
$val = $item[ $column_name ] ?? '';
return is_scalar( $val ) ? esc_html( (string) $val ) : '';
}
/**
* Queries the network mirror table and populates $this->items.
*
* @return void
*/
public function prepare_items(): void {
global $wpdb;
$table = NetworkDatabase::table_name();
$per_pg = self::PER_PAGE;
$current = $this->get_pagenum();
$offset = ( $current - 1 ) * $per_pg;
$where = array( '1=1' );
$args = array();
if ( $this->alerts_only ) {
$where[] = 'has_alert = 1 AND is_dismissed = 0';
}
// Site filter.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$site_filter = isset( $_GET['mra_site'] ) && is_numeric( $_GET['mra_site'] ) ? (int) $_GET['mra_site'] : 0;
if ( $site_filter > 0 ) {
$where[] = 'site_id = %d';
$args[] = $site_filter;
}
// Status filter.
$valid_statuses = array( 'pending', 'queued', 'scanned', 'matches', 'error' );
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$status_filter = isset( $_GET['mra_status'] ) && is_string( $_GET['mra_status'] ) ? sanitize_key( $_GET['mra_status'] ) : '';
if ( $status_filter && in_array( $status_filter, $valid_statuses, true ) ) {
$where[] = 'external_status = %s';
$args[] = $status_filter;
}
$where_sql = implode( ' AND ', $where );
// Sorting.
$valid_orderby = array( 'site_url', 'file_name', 'external_status', 'external_scanned_at' );
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$orderby_raw = isset( $_GET['orderby'] ) && is_string( $_GET['orderby'] ) ? sanitize_key( $_GET['orderby'] ) : 'site_url';
$orderby = in_array( $orderby_raw, $valid_orderby, true ) ? $orderby_raw : 'site_url';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$order_raw = isset( $_GET['order'] ) && is_string( $_GET['order'] ) ? strtoupper( sanitize_key( $_GET['order'] ) ) : 'ASC';
$order = in_array( $order_raw, array( 'ASC', 'DESC' ), true ) ? $order_raw : 'ASC';
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared
$count_sql = "SELECT COUNT(*) FROM `{$table}` WHERE {$where_sql}";
$total = empty( $args ) ? (int) $wpdb->get_var( $count_sql ) : (int) $wpdb->get_var( $wpdb->prepare( $count_sql, ...$args ) );
$data_sql = "SELECT * FROM `{$table}` WHERE {$where_sql} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d";
$query_args = array_merge( $args, array( $per_pg, $offset ) );
$this->items = (array) $wpdb->get_results( $wpdb->prepare( $data_sql, ...$query_args ), ARRAY_A );
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared
$this->set_pagination_args(
array(
'total_items' => $total,
'per_page' => $per_pg,
)
);
$this->_column_headers = array(
$this->get_columns(),
array(),
$this->get_sortable_columns(),
);
}
/**
* Renders the "no items" message.
*
* @return void
*/
public function no_items(): void {
esc_html_e( 'No media attachments found across the network.', 'robotstxt-mediaaudit' );
}
}

148
includes/Network/Plugin.php Normal file
View file

@ -0,0 +1,148 @@
<?php
/**
* Network admin bootstrap for central mode.
*
* @package MediaRightsAudit\Network
*/
namespace MediaRightsAudit\Network;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Registers network admin menu pages and hooks when the plugin operates in central mode.
*
* In per_site mode, only a lightweight network status page is registered so
* network admins can monitor per-site plugin health without managing data centrally.
*/
class Plugin {
/**
* Network Settings page handler.
*
* @var Settings
*/
private Settings $settings;
/**
* Network Audit page handler.
*
* @var AuditPage
*/
private AuditPage $audit_page;
/**
* Network Alerts page handler.
*
* @var AlertsPage
*/
private AlertsPage $alerts_page;
/**
* Network Tools page handler.
*
* @var ToolsPage
*/
private ToolsPage $tools_page;
/**
* Initialises network admin subsystem dependencies.
*/
public function __construct() {
$this->settings = new Settings();
$this->audit_page = new AuditPage();
$this->alerts_page = new AlertsPage();
$this->tools_page = new ToolsPage();
}
/**
* Registers all network admin hooks.
*
* @return void
*/
public function run(): void {
add_action( 'network_admin_menu', array( $this, 'register_network_pages' ) );
add_action( 'network_admin_edit_mra_network_settings', array( $this->settings, 'save' ) );
}
/**
* Registers network admin menu pages.
*
* In central mode: full aggregated UI (Audit, Alerts, Tools, Settings).
* In per_site mode: only a status overview page is registered.
*
* @return void
*/
public function register_network_pages(): void {
$mode = get_site_option( 'robotstxt_mediaaudit_network_mode', 'per_site' );
if ( 'central' === $mode ) {
add_menu_page(
__( 'Network Media Audit', 'robotstxt-mediaaudit' ),
__( 'Media Audit', 'robotstxt-mediaaudit' ),
'manage_network_options',
'robotstxt-mediaaudit-network',
array( $this->audit_page, 'render' ),
'dashicons-camera',
11
);
add_submenu_page(
'robotstxt-mediaaudit-network',
__( 'Network Media Audit', 'robotstxt-mediaaudit' ),
__( 'Network Audit', 'robotstxt-mediaaudit' ),
'manage_network_options',
'robotstxt-mediaaudit-network',
array( $this->audit_page, 'render' )
);
add_submenu_page(
'robotstxt-mediaaudit-network',
__( 'Network Alerts', 'robotstxt-mediaaudit' ),
__( 'Alerts', 'robotstxt-mediaaudit' ),
'manage_network_options',
'robotstxt-mediaaudit-network-alerts',
array( $this->alerts_page, 'render' )
);
$tools_suffix = add_submenu_page(
'robotstxt-mediaaudit-network',
__( 'Network Tools', 'robotstxt-mediaaudit' ),
__( 'Tools', 'robotstxt-mediaaudit' ),
'manage_network_options',
'robotstxt-mediaaudit-network-tools',
array( $this->tools_page, 'render' )
);
if ( is_string( $tools_suffix ) ) {
$this->tools_page->set_hook_suffix( $tools_suffix );
}
} else {
$status_suffix = add_menu_page(
__( 'Media Audit — Network', 'robotstxt-mediaaudit' ),
__( 'Media Audit', 'robotstxt-mediaaudit' ),
'manage_network_options',
'robotstxt-mediaaudit-network',
array( $this->tools_page, 'render_status_only' ),
'dashicons-camera',
11
);
if ( is_string( $status_suffix ) ) {
$this->tools_page->set_hook_suffix( $status_suffix );
}
}
// Settings always shown in network admin, regardless of mode.
add_submenu_page(
'robotstxt-mediaaudit-network',
__( 'Network Settings', 'robotstxt-mediaaudit' ),
__( 'Settings', 'robotstxt-mediaaudit' ),
'manage_network_options',
'robotstxt-mediaaudit-network-settings',
array( $this->settings, 'render' )
);
}
}

Some files were not shown because too many files have changed in this diff Show more