v1.0.0
This commit is contained in:
commit
6708bbb67f
43 changed files with 8342 additions and 0 deletions
705
includes/Admin/AuditPage.php
Normal file
705
includes/Admin/AuditPage.php
Normal file
|
|
@ -0,0 +1,705 @@
|
|||
<?php
|
||||
/**
|
||||
* Admin page controller for the Media Audit list view.
|
||||
*
|
||||
* @package MediaRightsAudit\Admin
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\Admin;
|
||||
|
||||
use MediaRightsAudit\External\ExternalScanner;
|
||||
use MediaRightsAudit\External\ResultsConsolidator;
|
||||
use MediaRightsAudit\Internal\AttachmentIndexer;
|
||||
use MediaRightsAudit\Internal\UsageScanner;
|
||||
|
||||
/**
|
||||
* Registers and renders the main Media Audit admin page.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Enqueue CSS/JS on the plugin's admin pages.
|
||||
* - Render the page: dashboard stats + WP_List_Table.
|
||||
* - Handle CSV bulk-action export (before page output).
|
||||
* - Serve AJAX usage-detail modal content.
|
||||
*/
|
||||
class AuditPage {
|
||||
|
||||
/**
|
||||
* Hook suffix assigned to the main menu page (populated on admin_menu).
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $hook_suffix = '';
|
||||
|
||||
/**
|
||||
* Registers all hooks owned by this controller.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_hooks(): void {
|
||||
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
|
||||
add_action( 'wp_ajax_mra_usage_details', array( $this, 'ajax_usage_details' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the hook suffix so asset enqueuing can limit to this page.
|
||||
*
|
||||
* @param string $suffix Hook suffix from add_menu_page / add_submenu_page.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function set_hook_suffix( string $suffix ): void {
|
||||
$this->hook_suffix = $suffix;
|
||||
add_action( 'load-' . $suffix, array( $this, 'handle_load' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires before the admin header is sent, allowing headers to be set.
|
||||
*
|
||||
* Handles bulk actions that need to modify headers (CSV export) or redirect
|
||||
* (run_external_scan, purge_external_data) before any HTML output begins.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_load(): void {
|
||||
$action = $this->get_current_bulk_action();
|
||||
|
||||
if ( 'export_csv' === $action ) {
|
||||
$this->handle_export_csv();
|
||||
} elseif ( 'run_external_scan' === $action ) {
|
||||
$this->handle_run_external_scan();
|
||||
} elseif ( 'purge_external_data' === $action ) {
|
||||
$this->handle_purge_external_data();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueues CSS and JS only on the Media Audit admin page.
|
||||
*
|
||||
* @param string $hook_suffix Current admin page hook suffix.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function enqueue_assets( string $hook_suffix ): void {
|
||||
if ( '' !== $this->hook_suffix && $hook_suffix !== $this->hook_suffix ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$base = ROBOTSTXT_MEDIAAUDIT_PLUGIN_URL . 'assets/';
|
||||
$ver = ROBOTSTXT_MEDIAAUDIT_VERSION;
|
||||
|
||||
wp_enqueue_style(
|
||||
'mra-admin',
|
||||
$base . 'css/media-audit-admin.css',
|
||||
array(),
|
||||
$ver
|
||||
);
|
||||
|
||||
wp_enqueue_script(
|
||||
'mra-admin',
|
||||
$base . 'js/media-audit-admin.js',
|
||||
array( 'jquery' ),
|
||||
$ver,
|
||||
true
|
||||
);
|
||||
|
||||
wp_localize_script(
|
||||
'mra-admin',
|
||||
'mraAdmin',
|
||||
array(
|
||||
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
|
||||
'nonce' => wp_create_nonce( 'mra_usage_details' ),
|
||||
'i18n' => array(
|
||||
'loading' => __( 'Loading…', 'robotstxt-mediaaudit' ),
|
||||
'errorLoading' => __( 'Error loading details.', 'robotstxt-mediaaudit' ),
|
||||
'noUsages' => __( 'This image is not used in any post.', 'robotstxt-mediaaudit' ),
|
||||
'detailsTitle' => __( 'Usage Details', 'robotstxt-mediaaudit' ),
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the full Media Audit admin page.
|
||||
*
|
||||
* Bulk actions (CSV export, external scan, purge) are intercepted earlier in
|
||||
* handle_load() via the load-{hook_suffix} action, before any HTML is sent.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render(): void {
|
||||
if ( ! current_user_can( 'edit_posts' ) ) {
|
||||
wp_die( esc_html__( 'You do not have permission to access this page.', 'robotstxt-mediaaudit' ) );
|
||||
}
|
||||
|
||||
$table = new MediaListTable();
|
||||
$table->prepare_items();
|
||||
|
||||
echo '<div class="wrap">';
|
||||
echo '<h1>' . esc_html__( 'Media Audit', 'robotstxt-mediaaudit' ) . '</h1>';
|
||||
|
||||
$this->render_dashboard_stats();
|
||||
|
||||
echo '<form method="get">';
|
||||
echo '<input type="hidden" name="page" value="robotstxt-mediaaudit" />';
|
||||
$table->search_box( __( 'Search', 'robotstxt-mediaaudit' ), 'mra-search' );
|
||||
$table->display();
|
||||
echo '</form>';
|
||||
|
||||
// Modal overlay (hidden by default, opened via JS).
|
||||
echo '<div id="mra-modal-overlay" class="mra-modal-overlay" role="dialog" aria-modal="true" aria-labelledby="mra-modal-title">';
|
||||
echo ' <div class="mra-modal">';
|
||||
echo ' <div class="mra-modal-header">';
|
||||
echo ' <h3 id="mra-modal-title" class="mra-modal-title">' . esc_html__( 'Usage Details', 'robotstxt-mediaaudit' ) . '</h3>';
|
||||
echo ' <button type="button" class="mra-modal-close" aria-label="' . esc_attr__( 'Close', 'robotstxt-mediaaudit' ) . '">×</button>';
|
||||
echo ' </div>';
|
||||
echo ' <div class="mra-modal-body"></div>';
|
||||
echo ' </div>';
|
||||
echo '</div>';
|
||||
|
||||
echo '</div>'; // .wrap
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX handler: returns formatted HTML for the usage-detail modal.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function ajax_usage_details(): void {
|
||||
check_ajax_referer( 'mra_usage_details', 'nonce' );
|
||||
|
||||
if ( ! current_user_can( 'edit_posts' ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'robotstxt-mediaaudit' ) ) );
|
||||
}
|
||||
|
||||
$attachment_id = isset( $_POST['attachment_id'] ) && is_string( $_POST['attachment_id'] ) ? (int) sanitize_text_field( wp_unslash( $_POST['attachment_id'] ) ) : 0;
|
||||
if ( $attachment_id <= 0 ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Invalid attachment ID.', 'robotstxt-mediaaudit' ) ) );
|
||||
}
|
||||
|
||||
$usages = MediaListTable::fetch_usages( array( $attachment_id ) );
|
||||
$title = get_the_title( $attachment_id );
|
||||
|
||||
// Build usage section.
|
||||
$context_labels = array(
|
||||
'featured' => __( 'Featured Image', 'robotstxt-mediaaudit' ),
|
||||
'content' => __( 'Post Content', 'robotstxt-mediaaudit' ),
|
||||
'meta' => __( 'Custom Field', 'robotstxt-mediaaudit' ),
|
||||
);
|
||||
|
||||
if ( empty( $usages ) ) {
|
||||
$usage_html = '<p>' . esc_html__( 'This image is not used in any post.', 'robotstxt-mediaaudit' ) . '</p>';
|
||||
} else {
|
||||
$usage_html = '<table class="widefat mra-usages-table">';
|
||||
$usage_html .= '<thead><tr>';
|
||||
$usage_html .= '<th>' . esc_html__( 'Post', 'robotstxt-mediaaudit' ) . '</th>';
|
||||
$usage_html .= '<th>' . esc_html__( 'Type', 'robotstxt-mediaaudit' ) . '</th>';
|
||||
$usage_html .= '<th>' . esc_html__( 'Context', 'robotstxt-mediaaudit' ) . '</th>';
|
||||
$usage_html .= '<th>' . esc_html__( 'Status', 'robotstxt-mediaaudit' ) . '</th>';
|
||||
$usage_html .= '</tr></thead><tbody>';
|
||||
|
||||
foreach ( $usages as $u ) {
|
||||
$pid_val = $u['post_id'] ?? null;
|
||||
$post_id = is_numeric( $pid_val ) ? (int) $pid_val : 0;
|
||||
$t_raw = $u['post_title'] ?? '';
|
||||
$post_title = is_string( $t_raw ) && '' !== $t_raw ? $t_raw : sprintf( '#%d', $post_id );
|
||||
$pt_val = $u['post_type'] ?? null;
|
||||
$post_type = is_string( $pt_val ) ? $pt_val : '';
|
||||
$ctx_val = $u['context'] ?? null;
|
||||
$context = is_string( $ctx_val ) ? $ctx_val : '';
|
||||
$status_val = $u['post_status'] ?? null;
|
||||
$status = is_string( $status_val ) ? $status_val : '';
|
||||
$mk_val = $u['meta_key'] ?? null;
|
||||
$meta_key = is_string( $mk_val ) ? $mk_val : '';
|
||||
|
||||
$ctx_label = isset( $context_labels[ $context ] ) ? $context_labels[ $context ] : esc_html( $context );
|
||||
if ( '' !== $meta_key ) {
|
||||
$ctx_label .= ' <code>' . esc_html( $meta_key ) . '</code>';
|
||||
}
|
||||
|
||||
$edit_link = get_edit_post_link( $post_id );
|
||||
$post_cell = $edit_link
|
||||
? sprintf( '<a href="%s">%s</a>', esc_url( $edit_link ), esc_html( $post_title ) )
|
||||
: esc_html( $post_title );
|
||||
|
||||
$usage_html .= '<tr>';
|
||||
$usage_html .= '<td>' . $post_cell . '</td>';
|
||||
$usage_html .= '<td>' . esc_html( $post_type ) . '</td>';
|
||||
$usage_html .= '<td>' . $ctx_label . '</td>';
|
||||
$usage_html .= '<td>' . esc_html( $status ) . '</td>';
|
||||
$usage_html .= '</tr>';
|
||||
}
|
||||
|
||||
$usage_html .= '</tbody></table>';
|
||||
}
|
||||
|
||||
// Build external results section.
|
||||
$external_html = $this->build_external_results_html( $attachment_id );
|
||||
|
||||
// Combine sections; add headings only when both sections are present.
|
||||
if ( '' !== $external_html ) {
|
||||
$html = '<h4 class="mra-section-heading">' . esc_html__( 'Internal Usage', 'robotstxt-mediaaudit' ) . '</h4>';
|
||||
$html .= $usage_html;
|
||||
$html .= $external_html;
|
||||
} else {
|
||||
$html = $usage_html;
|
||||
}
|
||||
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'title' => esc_html( $title ? $title : sprintf( '#%d', $attachment_id ) ),
|
||||
'html' => $html,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the HTML for the external scan results section of the detail modal.
|
||||
*
|
||||
* Returns an empty string when no external scan data exists for the attachment.
|
||||
*
|
||||
* @param int $attachment_id WordPress attachment ID.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function build_external_results_html( int $attachment_id ): string {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$rows = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT provider, match_count, top_domains, created_at
|
||||
FROM {$wpdb->prefix}mra_external_results
|
||||
WHERE attachment_id = %d
|
||||
ORDER BY provider ASC",
|
||||
$attachment_id
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
|
||||
if ( empty( $rows ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$provider_names = array(
|
||||
'google_vision' => 'Google Cloud Vision',
|
||||
'tineye' => 'TinEye',
|
||||
);
|
||||
|
||||
$html = '<h4 class="mra-section-heading">' . esc_html__( 'External Scan Results', 'robotstxt-mediaaudit' ) . '</h4>';
|
||||
|
||||
foreach ( $rows as $row ) {
|
||||
if ( ! is_array( $row ) ) {
|
||||
continue;
|
||||
}
|
||||
$slug_val = $row['provider'] ?? null;
|
||||
$slug = is_string( $slug_val ) ? $slug_val : '';
|
||||
$name = isset( $provider_names[ $slug ] ) ? $provider_names[ $slug ] : ucwords( str_replace( '_', ' ', $slug ) );
|
||||
$mc_val = $row['match_count'] ?? null;
|
||||
$match_count = is_numeric( $mc_val ) ? (int) $mc_val : 0;
|
||||
$at_val = $row['created_at'] ?? null;
|
||||
$scanned_at = is_string( $at_val ) ? $at_val : '';
|
||||
$td_val = $row['top_domains'] ?? null;
|
||||
$td_raw = is_string( $td_val ) ? json_decode( $td_val, true ) : null;
|
||||
$domains = is_array( $td_raw ) ? $td_raw : array();
|
||||
|
||||
$html .= '<div class="mra-provider-result">';
|
||||
$html .= '<strong>' . esc_html( $name ) . '</strong> — ';
|
||||
|
||||
if ( $match_count > 0 ) {
|
||||
$html .= esc_html(
|
||||
sprintf(
|
||||
/* translators: %d: number of external matches */
|
||||
_n( '%d match', '%d matches', $match_count, 'robotstxt-mediaaudit' ),
|
||||
$match_count
|
||||
)
|
||||
);
|
||||
} else {
|
||||
$html .= esc_html__( 'No matches', 'robotstxt-mediaaudit' );
|
||||
}
|
||||
|
||||
if ( '' !== $scanned_at ) {
|
||||
$html .= ' <small>' . esc_html( $scanned_at ) . '</small>';
|
||||
}
|
||||
$html .= '</div>';
|
||||
|
||||
if ( ! empty( $domains ) ) {
|
||||
$html .= '<table class="widefat mra-domains-table">';
|
||||
$html .= '<thead><tr>';
|
||||
$html .= '<th>' . esc_html__( 'Domain', 'robotstxt-mediaaudit' ) . '</th>';
|
||||
$html .= '<th>' . esc_html__( 'Occurrences', 'robotstxt-mediaaudit' ) . '</th>';
|
||||
$html .= '</tr></thead><tbody>';
|
||||
foreach ( $domains as $domain => $count ) {
|
||||
if ( ! is_string( $domain ) ) {
|
||||
continue;
|
||||
}
|
||||
$html .= sprintf(
|
||||
'<tr><td>%s</td><td>%s</td></tr>',
|
||||
esc_html( $domain ),
|
||||
esc_html( (string) ( is_numeric( $count ) ? (int) $count : 0 ) )
|
||||
);
|
||||
}
|
||||
$html .= '</tbody></table>';
|
||||
}
|
||||
}
|
||||
|
||||
// Consensus section: only when multiple providers have results.
|
||||
if ( count( $rows ) > 1 ) {
|
||||
$consensus = ResultsConsolidator::get_consensus_domains( $attachment_id );
|
||||
if ( ! empty( $consensus ) ) {
|
||||
$html .= '<div class="mra-consensus">';
|
||||
$html .= '<strong>' . esc_html__( 'Consensus Domains', 'robotstxt-mediaaudit' ) . '</strong>';
|
||||
$html .= '<ul class="mra-usage-list">';
|
||||
foreach ( $consensus as $domain => $count ) {
|
||||
$html .= '<li>' . esc_html( $domain ) . ' <small>(' . esc_html(
|
||||
sprintf(
|
||||
/* translators: %d: number of providers that agree */
|
||||
_n( '%d provider', '%d providers', $count, 'robotstxt-mediaaudit' ),
|
||||
$count
|
||||
)
|
||||
) . ')</small></li>';
|
||||
}
|
||||
$html .= '</ul></div>';
|
||||
}
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Private helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Renders the dashboard stats strip.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function render_dashboard_stats(): void {
|
||||
$stats = self::get_dashboard_stats();
|
||||
|
||||
$scanned_pct = $stats['total_indexed'] > 0
|
||||
? round( $stats['total_scanned'] / $stats['total_indexed'] * 100 )
|
||||
: 0;
|
||||
|
||||
echo '<div class="mra-stats">';
|
||||
|
||||
$this->stat_box(
|
||||
$stats['total_indexed'],
|
||||
__( 'In Index', 'robotstxt-mediaaudit' ),
|
||||
$stats['pending_index'] > 0
|
||||
? sprintf(
|
||||
/* translators: %d: count of images not yet indexed */
|
||||
__( '%d not yet indexed', 'robotstxt-mediaaudit' ),
|
||||
$stats['pending_index']
|
||||
)
|
||||
: __( 'All indexed', 'robotstxt-mediaaudit' )
|
||||
);
|
||||
|
||||
$this->stat_box(
|
||||
$stats['total_scanned'],
|
||||
__( 'Scanned', 'robotstxt-mediaaudit' ),
|
||||
sprintf(
|
||||
/* translators: %d: percentage */
|
||||
__( '%d%% of index', 'robotstxt-mediaaudit' ),
|
||||
$scanned_pct
|
||||
)
|
||||
);
|
||||
|
||||
$this->stat_box(
|
||||
$stats['total_used'],
|
||||
__( 'Used', 'robotstxt-mediaaudit' ),
|
||||
''
|
||||
);
|
||||
|
||||
$this->stat_box(
|
||||
$stats['total_unused'],
|
||||
__( 'Unused', 'robotstxt-mediaaudit' ),
|
||||
''
|
||||
);
|
||||
|
||||
if ( $stats['total_matches'] > 0 ) {
|
||||
$this->stat_box(
|
||||
$stats['total_matches'],
|
||||
__( 'External Matches', 'robotstxt-mediaaudit' ),
|
||||
''
|
||||
);
|
||||
}
|
||||
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs a single stat box.
|
||||
*
|
||||
* @param int $value Main number.
|
||||
* @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>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs CSV for selected attachment IDs and terminates the request.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function handle_export_csv(): void {
|
||||
check_admin_referer( 'bulk-mra-attachments' );
|
||||
|
||||
if ( ! current_user_can( 'edit_posts' ) ) {
|
||||
wp_die( esc_html__( 'Insufficient permissions.', 'robotstxt-mediaaudit' ) );
|
||||
}
|
||||
|
||||
$ids = $this->collect_attachment_ids();
|
||||
$rows = $this->build_csv_rows( $ids );
|
||||
|
||||
$filename = 'media-audit-' . gmdate( 'Y-m-d' ) . '.csv';
|
||||
|
||||
header( 'Content-Type: text/csv; charset=utf-8' );
|
||||
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
|
||||
header( 'Pragma: no-cache' );
|
||||
|
||||
$out = fopen( 'php://output', 'w' );
|
||||
if ( false === $out ) {
|
||||
wp_die( esc_html__( 'Could not open output stream.', 'robotstxt-mediaaudit' ) );
|
||||
}
|
||||
|
||||
// BOM for Excel UTF-8 compatibility.
|
||||
fwrite( $out, "\xEF\xBB\xBF" ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
|
||||
|
||||
fputcsv(
|
||||
$out,
|
||||
array(
|
||||
__( 'Attachment ID', 'robotstxt-mediaaudit' ),
|
||||
__( 'Filename', 'robotstxt-mediaaudit' ),
|
||||
__( 'File URL', 'robotstxt-mediaaudit' ),
|
||||
__( 'MIME Type', 'robotstxt-mediaaudit' ),
|
||||
__( 'File Size (bytes)', 'robotstxt-mediaaudit' ),
|
||||
__( 'External Status', 'robotstxt-mediaaudit' ),
|
||||
__( 'Usage Count', 'robotstxt-mediaaudit' ),
|
||||
__( 'Used In (post titles)', 'robotstxt-mediaaudit' ),
|
||||
)
|
||||
);
|
||||
|
||||
foreach ( $rows as $row ) {
|
||||
fputcsv( $out, $row );
|
||||
}
|
||||
|
||||
fclose( $out ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queues selected attachments for external scanning and redirects.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function handle_run_external_scan(): void {
|
||||
check_admin_referer( 'bulk-mra-attachments' );
|
||||
|
||||
if ( ! current_user_can( 'edit_posts' ) ) {
|
||||
wp_die( esc_html__( 'Insufficient permissions.', 'robotstxt-mediaaudit' ) );
|
||||
}
|
||||
|
||||
$ids = $this->collect_attachment_ids();
|
||||
|
||||
if ( ! empty( $ids ) ) {
|
||||
ExternalScanner::queue_attachments( $ids );
|
||||
} else {
|
||||
ExternalScanner::schedule();
|
||||
}
|
||||
|
||||
wp_safe_redirect(
|
||||
add_query_arg(
|
||||
array(
|
||||
'page' => 'robotstxt-mediaaudit',
|
||||
'mra_notice' => 'scan_scheduled',
|
||||
),
|
||||
admin_url( 'admin.php' )
|
||||
)
|
||||
);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Purges external scan data for selected attachments and redirects.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function handle_purge_external_data(): void {
|
||||
check_admin_referer( 'bulk-mra-attachments' );
|
||||
|
||||
if ( ! current_user_can( 'edit_posts' ) ) {
|
||||
wp_die( esc_html__( 'Insufficient permissions.', 'robotstxt-mediaaudit' ) );
|
||||
}
|
||||
|
||||
$ids = $this->collect_attachment_ids();
|
||||
|
||||
if ( ! empty( $ids ) ) {
|
||||
ExternalScanner::purge( $ids );
|
||||
}
|
||||
|
||||
wp_safe_redirect(
|
||||
add_query_arg(
|
||||
array(
|
||||
'page' => 'robotstxt-mediaaudit',
|
||||
'mra_notice' => 'purge_done',
|
||||
),
|
||||
admin_url( 'admin.php' )
|
||||
)
|
||||
);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects and sanitises attachment IDs from the current bulk action POST data.
|
||||
*
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private function collect_attachment_ids(): array {
|
||||
$ids = array();
|
||||
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Missing,WordPress.Security.NonceVerification.Recommended -- nonce verified by all callers.
|
||||
if ( isset( $_REQUEST['attachment_id'] ) && is_array( $_REQUEST['attachment_id'] ) ) {
|
||||
foreach ( $_REQUEST['attachment_id'] as $raw ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
|
||||
$id = is_numeric( $raw ) ? (int) $raw : 0;
|
||||
if ( $id > 0 ) {
|
||||
$ids[] = $id;
|
||||
}
|
||||
}
|
||||
}
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Missing,WordPress.Security.NonceVerification.Recommended
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds CSV data rows for the given attachment IDs.
|
||||
*
|
||||
* If $ids is empty, exports all indexed attachments.
|
||||
*
|
||||
* @param array<int, int> $ids Attachment IDs to export (empty = all).
|
||||
*
|
||||
* @return array<int, array<int, string>>
|
||||
*/
|
||||
private function build_csv_rows( array $ids ): array {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
|
||||
if ( empty( $ids ) ) {
|
||||
$index_rows = $wpdb->get_results(
|
||||
"SELECT * FROM {$wpdb->prefix}mra_media_index ORDER BY attachment_id ASC",
|
||||
ARRAY_A
|
||||
);
|
||||
} else {
|
||||
$placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
$index_rows = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT * FROM {$wpdb->prefix}mra_media_index WHERE attachment_id IN ({$placeholders}) ORDER BY attachment_id ASC",
|
||||
...$ids
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
}
|
||||
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
|
||||
if ( ! $index_rows ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$page_ids = array_map(
|
||||
static function ( $v ) {
|
||||
return (int) $v;
|
||||
},
|
||||
array_column( $index_rows, 'attachment_id' )
|
||||
);
|
||||
$usages = MediaListTable::fetch_usages( $page_ids );
|
||||
|
||||
$usage_titles = array();
|
||||
foreach ( $usages as $u ) {
|
||||
$aid_val = $u['attachment_id'] ?? null;
|
||||
$aid = is_numeric( $aid_val ) ? (int) $aid_val : 0;
|
||||
$t_raw = $u['post_title'] ?? '';
|
||||
$pid_raw = $u['post_id'] ?? null;
|
||||
$title = is_string( $t_raw ) && '' !== $t_raw ? $t_raw : sprintf( '#%d', is_numeric( $pid_raw ) ? (int) $pid_raw : 0 );
|
||||
|
||||
$usage_titles[ $aid ][] = $title;
|
||||
}
|
||||
|
||||
$output = array();
|
||||
foreach ( $index_rows as $r ) {
|
||||
$aid = (int) ( $r['attachment_id'] ?? 0 );
|
||||
$titles = isset( $usage_titles[ $aid ] ) ? implode( '; ', $usage_titles[ $aid ] ) : '';
|
||||
|
||||
$fn_raw = $r['file_name'] ?? '';
|
||||
$url_raw = $r['file_url'] ?? '';
|
||||
$mt_raw = $r['mime_type'] ?? '';
|
||||
$fs_raw = $r['file_size'] ?? '';
|
||||
$es_raw = $r['external_status'] ?? '';
|
||||
|
||||
$output[] = array(
|
||||
(string) $aid,
|
||||
is_string( $fn_raw ) ? $fn_raw : '',
|
||||
is_string( $url_raw ) ? $url_raw : '',
|
||||
is_string( $mt_raw ) ? $mt_raw : '',
|
||||
is_string( $fs_raw ) ? $fs_raw : '',
|
||||
is_string( $es_raw ) ? $es_raw : '',
|
||||
(string) count( $usage_titles[ $aid ] ?? array() ),
|
||||
$titles,
|
||||
);
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the active bulk action from the form submission.
|
||||
*
|
||||
* @return string Action name, or '' if none.
|
||||
*/
|
||||
private function get_current_bulk_action(): string {
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Missing,WordPress.Security.NonceVerification.Recommended
|
||||
$action = isset( $_REQUEST['action'] ) && is_string( $_REQUEST['action'] ) ? sanitize_key( wp_unslash( $_REQUEST['action'] ) ) : '';
|
||||
if ( '-1' === $action ) {
|
||||
$action = isset( $_REQUEST['action2'] ) && is_string( $_REQUEST['action2'] ) ? sanitize_key( wp_unslash( $_REQUEST['action2'] ) ) : '';
|
||||
}
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Missing,WordPress.Security.NonceVerification.Recommended
|
||||
return $action;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries and returns dashboard statistics.
|
||||
*
|
||||
* @return array{total_indexed: int, total_scanned: int, total_used: int, total_unused: int, total_matches: int, pending_index: int}
|
||||
*/
|
||||
private static function get_dashboard_stats(): array {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery
|
||||
$total_indexed = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}mra_media_index" );
|
||||
$total_scanned = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}mra_media_index WHERE internal_scanned_at IS NOT NULL" );
|
||||
$total_used = (int) $wpdb->get_var( "SELECT COUNT(DISTINCT attachment_id) FROM {$wpdb->prefix}mra_media_usage" );
|
||||
$total_matches = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}mra_media_index WHERE external_status = 'matches'" );
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery
|
||||
|
||||
return array(
|
||||
'total_indexed' => $total_indexed,
|
||||
'total_scanned' => $total_scanned,
|
||||
'total_used' => $total_used,
|
||||
'total_unused' => max( 0, $total_indexed - $total_used ),
|
||||
'total_matches' => $total_matches,
|
||||
'pending_index' => AttachmentIndexer::get_pending_count(),
|
||||
);
|
||||
}
|
||||
}
|
||||
570
includes/Admin/MediaListTable.php
Normal file
570
includes/Admin/MediaListTable.php
Normal file
|
|
@ -0,0 +1,570 @@
|
|||
<?php
|
||||
/**
|
||||
* WP_List_Table subclass for the Media Audit list.
|
||||
*
|
||||
* @package MediaRightsAudit\Admin
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\Admin;
|
||||
|
||||
if ( ! class_exists( 'WP_List_Table' ) ) {
|
||||
require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the indexed media library with usage data.
|
||||
*
|
||||
* Columns: thumbnail, filename, attachment_id, usage_count, usages, external_status.
|
||||
*/
|
||||
class MediaListTable extends \WP_List_Table {
|
||||
|
||||
/**
|
||||
* Allowed values for the external_status column.
|
||||
*/
|
||||
const EXTERNAL_STATUSES = array( 'pending', 'queued', 'scanned', 'matches', 'error' );
|
||||
|
||||
/**
|
||||
* Initialises the list table with singular/plural labels and AJAX support.
|
||||
*/
|
||||
public function __construct() {
|
||||
parent::__construct(
|
||||
array(
|
||||
'singular' => 'mra-attachment',
|
||||
'plural' => 'mra-attachments',
|
||||
'ajax' => false,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// WP_List_Table interface
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns all column headers.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function get_columns() {
|
||||
return array(
|
||||
'cb' => '<input type="checkbox" />',
|
||||
'thumbnail' => __( 'Thumbnail', 'robotstxt-mediaaudit' ),
|
||||
'filename' => __( 'Filename', 'robotstxt-mediaaudit' ),
|
||||
'attachment_id' => __( 'ID', 'robotstxt-mediaaudit' ),
|
||||
'usage_count' => __( 'Usage Count', 'robotstxt-mediaaudit' ),
|
||||
'usages' => __( 'Usages', 'robotstxt-mediaaudit' ),
|
||||
'external_status' => __( 'External Status', 'robotstxt-mediaaudit' ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns sortable columns.
|
||||
*
|
||||
* @return array<string, array<int, mixed>>
|
||||
*/
|
||||
protected function get_sortable_columns() {
|
||||
return array(
|
||||
'attachment_id' => array( 'attachment_id', true ),
|
||||
'usage_count' => array( 'usage_count', false ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns bulk actions.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function get_bulk_actions() {
|
||||
return array(
|
||||
'run_external_scan' => __( 'Run External Scan', 'robotstxt-mediaaudit' ),
|
||||
'purge_external_data' => __( 'Purge External Data', 'robotstxt-mediaaudit' ),
|
||||
'export_csv' => __( 'Export CSV', 'robotstxt-mediaaudit' ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback renderer for unrecognised columns.
|
||||
*
|
||||
* @param array<string, mixed> $item Row data.
|
||||
* @param string $column_name Column slug.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function column_default( $item, $column_name ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the checkbox column.
|
||||
*
|
||||
* @param array<string, mixed> $item Row data.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function column_cb( $item ) {
|
||||
$aid = $item['attachment_id'];
|
||||
return sprintf(
|
||||
'<input type="checkbox" name="attachment_id[]" value="%d" />',
|
||||
is_numeric( $aid ) ? (int) $aid : 0
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a 40×40 thumbnail linked to the attachment.
|
||||
*
|
||||
* @param array<string, mixed> $item Row data.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function column_thumbnail( $item ) {
|
||||
$aid_val = $item['attachment_id'];
|
||||
$url_val = $item['file_url'];
|
||||
$id = is_numeric( $aid_val ) ? (int) $aid_val : 0;
|
||||
$url = esc_url( is_string( $url_val ) ? $url_val : '' );
|
||||
|
||||
$thumb = wp_get_attachment_image(
|
||||
$id,
|
||||
array( 40, 40 ),
|
||||
false,
|
||||
array( 'class' => 'mra-thumb' )
|
||||
);
|
||||
|
||||
if ( ! $thumb ) {
|
||||
$thumb = '<span class="dashicons dashicons-format-image" style="font-size:40px;line-height:1;"></span>';
|
||||
}
|
||||
|
||||
return sprintf( '<a href="%s" target="_blank">%s</a>', $url, $thumb );
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the filename column with a link to the original file.
|
||||
*
|
||||
* @param array<string, mixed> $item Row data.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function column_filename( $item ) {
|
||||
$aid_val = $item['attachment_id'];
|
||||
$fn_val = $item['file_name'];
|
||||
$url_val = $item['file_url'];
|
||||
$id = is_numeric( $aid_val ) ? (int) $aid_val : 0;
|
||||
$filename = esc_html( is_string( $fn_val ) ? $fn_val : '' );
|
||||
$url = esc_url( is_string( $url_val ) ? $url_val : '' );
|
||||
|
||||
$title = sprintf(
|
||||
'<a href="%s" target="_blank">%s</a>',
|
||||
$url,
|
||||
( '' !== $filename ? $filename : '—' )
|
||||
);
|
||||
|
||||
$raw_edit_link = get_edit_post_link( $id );
|
||||
$actions = array(
|
||||
'edit' => sprintf(
|
||||
'<a href="%s">%s</a>',
|
||||
esc_url( is_string( $raw_edit_link ) ? $raw_edit_link : '' ),
|
||||
__( 'Edit', 'robotstxt-mediaaudit' )
|
||||
),
|
||||
'view_details' => sprintf(
|
||||
'<a href="#" class="mra-view-details" data-id="%d">%s</a>',
|
||||
$id,
|
||||
__( 'View Details', 'robotstxt-mediaaudit' )
|
||||
),
|
||||
);
|
||||
|
||||
return $title . $this->row_actions( $actions );
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the attachment ID column.
|
||||
*
|
||||
* @param array<string, mixed> $item Row data.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function column_attachment_id( $item ) {
|
||||
$aid_val = $item['attachment_id'];
|
||||
return esc_html( (string) ( is_numeric( $aid_val ) ? (int) $aid_val : 0 ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the usage count column.
|
||||
*
|
||||
* @param array<string, mixed> $item Row data.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function column_usage_count( $item ) {
|
||||
$cnt_val = $item['usage_count'];
|
||||
$count = is_numeric( $cnt_val ) ? (int) $cnt_val : 0;
|
||||
if ( 0 === $count ) {
|
||||
return '<span style="color:#999">' . esc_html__( 'Unused', 'robotstxt-mediaaudit' ) . '</span>';
|
||||
}
|
||||
return esc_html( (string) $count );
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the usages column with inline post links (max 3) and a modal link for more.
|
||||
*
|
||||
* @param array<string, mixed> $item Row data.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function column_usages( $item ) {
|
||||
$aid_val = $item['attachment_id'];
|
||||
$cnt_val = $item['usage_count'];
|
||||
$id = is_numeric( $aid_val ) ? (int) $aid_val : 0;
|
||||
$count = is_numeric( $cnt_val ) ? (int) $cnt_val : 0;
|
||||
|
||||
if ( 0 === $count ) {
|
||||
return '—';
|
||||
}
|
||||
|
||||
$usages = isset( $item['usages_data'] ) && is_array( $item['usages_data'] )
|
||||
? $item['usages_data']
|
||||
: array();
|
||||
|
||||
$shown = array_slice( $usages, 0, 3 );
|
||||
$html = '<ul class="mra-usage-list">';
|
||||
foreach ( $shown as $u ) {
|
||||
if ( ! is_array( $u ) ) {
|
||||
continue;
|
||||
}
|
||||
$pid_raw = $u['post_id'] ?? 0;
|
||||
$post_id = is_numeric( $pid_raw ) ? (int) $pid_raw : 0;
|
||||
$t = $u['post_title'] ?? '';
|
||||
$raw_title = is_string( $t ) ? $t : '';
|
||||
$post_title = esc_html( '' !== $raw_title ? $raw_title : __( '(no title)', 'robotstxt-mediaaudit' ) );
|
||||
$edit_link = get_edit_post_link( $post_id );
|
||||
if ( $edit_link ) {
|
||||
$html .= sprintf( '<li><a href="%s">%s</a></li>', esc_url( $edit_link ), $post_title );
|
||||
} else {
|
||||
$html .= '<li>' . $post_title . '</li>';
|
||||
}
|
||||
}
|
||||
|
||||
if ( $count > 3 ) {
|
||||
$html .= sprintf(
|
||||
'<li><a href="#" class="mra-view-details" data-id="%d">%s</a></li>',
|
||||
$id,
|
||||
sprintf(
|
||||
/* translators: %d: number of additional usages */
|
||||
esc_html__( '+ %d more…', 'robotstxt-mediaaudit' ),
|
||||
$count - 3
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$html .= '</ul>';
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the external status badge.
|
||||
*
|
||||
* @param array<string, mixed> $item Row data.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function column_external_status( $item ) {
|
||||
$es_val = $item['external_status'];
|
||||
$status = is_string( $es_val ) ? $es_val : '';
|
||||
|
||||
$labels = array(
|
||||
'pending' => __( 'Pending', 'robotstxt-mediaaudit' ),
|
||||
'queued' => __( 'Queued', 'robotstxt-mediaaudit' ),
|
||||
'scanned' => __( 'Scanned', 'robotstxt-mediaaudit' ),
|
||||
'matches' => __( 'Matches Found', 'robotstxt-mediaaudit' ),
|
||||
'error' => __( 'Error', 'robotstxt-mediaaudit' ),
|
||||
);
|
||||
|
||||
$label = isset( $labels[ $status ] ) ? $labels[ $status ] : ucfirst( $status );
|
||||
|
||||
$out = sprintf(
|
||||
'<span class="mra-badge mra-badge-%s">%s</span>',
|
||||
esc_attr( $status ),
|
||||
esc_html( $label )
|
||||
);
|
||||
|
||||
if ( 'matches' === $status ) {
|
||||
$mc_val = $item['total_match_count'] ?? null;
|
||||
$match_count = is_numeric( $mc_val ) ? (int) $mc_val : 0;
|
||||
if ( $match_count > 0 ) {
|
||||
$out .= sprintf(
|
||||
' <span class="mra-badge mra-badge-match-count">%s</span>',
|
||||
esc_html( number_format_i18n( $match_count ) )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if ( in_array( $status, array( 'scanned', 'matches' ), true ) ) {
|
||||
$aid_val = $item['attachment_id'];
|
||||
$aid = is_numeric( $aid_val ) ? (int) $aid_val : 0;
|
||||
$out .= sprintf(
|
||||
' <a href="#" class="mra-view-details" data-id="%d">%s</a>',
|
||||
$aid,
|
||||
esc_html__( 'View Results', 'robotstxt-mediaaudit' )
|
||||
);
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders filter controls above the table.
|
||||
*
|
||||
* @param string $which 'top' or 'bottom'.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function extra_tablenav( $which ) {
|
||||
if ( 'top' !== $which ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Recommended
|
||||
$current_status = isset( $_REQUEST['mra_external_status'] ) && is_string( $_REQUEST['mra_external_status'] ) ? sanitize_key( wp_unslash( $_REQUEST['mra_external_status'] ) ) : '';
|
||||
$current_post_type = isset( $_REQUEST['mra_post_type'] ) && is_string( $_REQUEST['mra_post_type'] ) ? sanitize_key( wp_unslash( $_REQUEST['mra_post_type'] ) ) : '';
|
||||
$show_unused = ! empty( $_REQUEST['mra_unused'] );
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Recommended
|
||||
|
||||
$post_types = self::get_used_post_types();
|
||||
|
||||
echo '<div class="alignleft actions mra-filters">';
|
||||
|
||||
// External status filter.
|
||||
echo '<select name="mra_external_status">';
|
||||
echo '<option value="">' . esc_html__( 'All statuses', 'robotstxt-mediaaudit' ) . '</option>';
|
||||
foreach ( self::EXTERNAL_STATUSES as $s ) {
|
||||
printf(
|
||||
'<option value="%s"%s>%s</option>',
|
||||
esc_attr( $s ),
|
||||
selected( $current_status, $s, false ),
|
||||
esc_html( ucfirst( $s ) )
|
||||
);
|
||||
}
|
||||
echo '</select>';
|
||||
|
||||
// Post type filter.
|
||||
if ( $post_types ) {
|
||||
echo '<select name="mra_post_type">';
|
||||
echo '<option value="">' . esc_html__( 'All post types', 'robotstxt-mediaaudit' ) . '</option>';
|
||||
foreach ( $post_types as $pt ) {
|
||||
printf(
|
||||
'<option value="%s"%s>%s</option>',
|
||||
esc_attr( $pt ),
|
||||
selected( $current_post_type, $pt, false ),
|
||||
esc_html( $pt )
|
||||
);
|
||||
}
|
||||
echo '</select>';
|
||||
}
|
||||
|
||||
// Unused toggle.
|
||||
echo '<label style="margin-left:8px">';
|
||||
echo '<input type="checkbox" name="mra_unused" value="1"' . checked( $show_unused, true, false ) . ' /> ';
|
||||
echo esc_html__( 'Unused only', 'robotstxt-mediaaudit' );
|
||||
echo '</label>';
|
||||
|
||||
submit_button( __( 'Filter', 'robotstxt-mediaaudit' ), 'button', 'mra_filter', false );
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Message shown when the index is empty.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function no_items() {
|
||||
esc_html_e( 'No indexed attachments found. Run wp mra scan-internal to populate the index.', 'robotstxt-mediaaudit' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries the database and sets $this->items.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function prepare_items() {
|
||||
global $wpdb;
|
||||
|
||||
$per_page = 20;
|
||||
$paged = $this->get_pagenum();
|
||||
$offset = ( $paged - 1 ) * $per_page;
|
||||
|
||||
// Sorting.
|
||||
$allowed_orderby = array( 'attachment_id', 'usage_count' );
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Recommended
|
||||
$orderby_raw = isset( $_REQUEST['orderby'] ) && is_string( $_REQUEST['orderby'] ) ? sanitize_key( wp_unslash( $_REQUEST['orderby'] ) ) : '';
|
||||
$orderby = in_array( $orderby_raw, $allowed_orderby, true ) ? $orderby_raw : 'attachment_id';
|
||||
$order_raw = strtoupper( isset( $_REQUEST['order'] ) && is_string( $_REQUEST['order'] ) ? sanitize_key( wp_unslash( $_REQUEST['order'] ) ) : '' );
|
||||
$order = ( 'DESC' === $order_raw ) ? 'DESC' : 'ASC';
|
||||
|
||||
// Filters.
|
||||
$search = isset( $_REQUEST['s'] ) && is_string( $_REQUEST['s'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) : '';
|
||||
$external_status = isset( $_REQUEST['mra_external_status'] ) && is_string( $_REQUEST['mra_external_status'] ) ? sanitize_key( wp_unslash( $_REQUEST['mra_external_status'] ) ) : '';
|
||||
$filter_post_type = isset( $_REQUEST['mra_post_type'] ) && is_string( $_REQUEST['mra_post_type'] ) ? sanitize_key( wp_unslash( $_REQUEST['mra_post_type'] ) ) : '';
|
||||
$show_unused = ! empty( $_REQUEST['mra_unused'] );
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Recommended
|
||||
|
||||
if ( ! in_array( $external_status, self::EXTERNAL_STATUSES, true ) ) {
|
||||
$external_status = '';
|
||||
}
|
||||
|
||||
// Build WHERE clause.
|
||||
$where_parts = array( '1=1' );
|
||||
$prepare_args = array();
|
||||
|
||||
if ( '' !== $search ) {
|
||||
$where_parts[] = 'i.file_name LIKE %s';
|
||||
$prepare_args[] = '%' . $wpdb->esc_like( $search ) . '%';
|
||||
}
|
||||
|
||||
if ( '' !== $external_status ) {
|
||||
$where_parts[] = 'i.external_status = %s';
|
||||
$prepare_args[] = $external_status;
|
||||
}
|
||||
|
||||
if ( '' !== $filter_post_type ) {
|
||||
$where_parts[] = 'EXISTS (SELECT 1 FROM ' . $wpdb->prefix . 'mra_media_usage mu WHERE mu.attachment_id = i.attachment_id AND mu.post_type = %s)';
|
||||
$prepare_args[] = $filter_post_type;
|
||||
}
|
||||
|
||||
if ( $show_unused ) {
|
||||
$where_parts[] = 'NOT EXISTS (SELECT 1 FROM ' . $wpdb->prefix . 'mra_media_usage mu WHERE mu.attachment_id = i.attachment_id)';
|
||||
}
|
||||
|
||||
$where = implode( ' AND ', $where_parts );
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared
|
||||
|
||||
if ( 'usage_count' === $orderby ) {
|
||||
$order_sql = "(SELECT COUNT(*) FROM {$wpdb->prefix}mra_media_usage mu WHERE mu.attachment_id = i.attachment_id) {$order}";
|
||||
} else {
|
||||
$order_sql = "i.attachment_id {$order}";
|
||||
}
|
||||
|
||||
$count_sql = "SELECT COUNT(*) FROM {$wpdb->prefix}mra_media_index i WHERE {$where}";
|
||||
$items_sql = "SELECT i.*,
|
||||
(SELECT COUNT(*) FROM {$wpdb->prefix}mra_media_usage mu WHERE mu.attachment_id = i.attachment_id) AS usage_count,
|
||||
(SELECT COALESCE(SUM(er.match_count), 0) FROM {$wpdb->prefix}mra_external_results er WHERE er.attachment_id = i.attachment_id) AS total_match_count
|
||||
FROM {$wpdb->prefix}mra_media_index i
|
||||
WHERE {$where}
|
||||
ORDER BY {$order_sql}
|
||||
LIMIT %d OFFSET %d";
|
||||
|
||||
$count_prepared = empty( $prepare_args )
|
||||
? $count_sql
|
||||
: $wpdb->prepare( $count_sql, ...$prepare_args );
|
||||
|
||||
$items_prepared = $wpdb->prepare(
|
||||
$items_sql,
|
||||
...array_merge( $prepare_args, array( $per_page, $offset ) )
|
||||
);
|
||||
|
||||
$total = (int) $wpdb->get_var( $count_prepared );
|
||||
$rows = $wpdb->get_results( $items_prepared, ARRAY_A );
|
||||
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared
|
||||
|
||||
if ( ! $rows ) {
|
||||
$this->items = array();
|
||||
} else {
|
||||
// Bulk-load usages for this page (avoid N+1).
|
||||
$ids = array_map( 'intval', array_column( $rows, 'attachment_id' ) );
|
||||
$usages = self::fetch_usages( $ids );
|
||||
$usage_by = array();
|
||||
foreach ( $usages as $u ) {
|
||||
$uid_val = $u['attachment_id'] ?? null;
|
||||
$uid = is_numeric( $uid_val ) ? (int) $uid_val : 0;
|
||||
$usage_by[ $uid ][] = $u;
|
||||
}
|
||||
|
||||
foreach ( $rows as &$row ) {
|
||||
$rid_val = $row['attachment_id'] ?? null;
|
||||
$rid = is_numeric( $rid_val ) ? (int) $rid_val : 0;
|
||||
$row['usages_data'] = $usage_by[ $rid ] ?? array();
|
||||
}
|
||||
unset( $row );
|
||||
|
||||
$this->items = $rows;
|
||||
}
|
||||
|
||||
$this->_column_headers = array(
|
||||
$this->get_columns(),
|
||||
array(),
|
||||
$this->get_sortable_columns(),
|
||||
'filename',
|
||||
);
|
||||
|
||||
$this->set_pagination_args(
|
||||
array(
|
||||
'total_items' => $total,
|
||||
'total_pages' => (int) ceil( $total / $per_page ),
|
||||
'per_page' => $per_page,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Public query helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Fetches usage rows for a set of attachment IDs in one query.
|
||||
*
|
||||
* @param array<int, int> $attachment_ids Attachment IDs to look up.
|
||||
*
|
||||
* @return list<array<array-key, mixed>>
|
||||
*/
|
||||
public static function fetch_usages( array $attachment_ids ): array {
|
||||
global $wpdb;
|
||||
|
||||
if ( empty( $attachment_ids ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$placeholders = implode( ',', array_fill( 0, count( $attachment_ids ), '%d' ) );
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
$rows = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT u.attachment_id, u.post_id, u.post_type, u.context, u.meta_key,
|
||||
p.post_title, p.post_status
|
||||
FROM {$wpdb->prefix}mra_media_usage u
|
||||
JOIN {$wpdb->posts} p ON u.post_id = p.ID
|
||||
WHERE u.attachment_id IN ({$placeholders})
|
||||
ORDER BY u.attachment_id ASC, u.post_id ASC",
|
||||
...$attachment_ids
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
|
||||
return $rows ?? array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns distinct post types that have at least one usage record.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function get_used_post_types(): array {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
$rows = $wpdb->get_col(
|
||||
"SELECT DISTINCT post_type FROM {$wpdb->prefix}mra_media_usage ORDER BY post_type ASC"
|
||||
);
|
||||
|
||||
if ( ! is_array( $rows ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$types = array();
|
||||
foreach ( $rows as $r ) {
|
||||
if ( is_string( $r ) ) {
|
||||
$types[] = $r;
|
||||
}
|
||||
}
|
||||
return $types;
|
||||
}
|
||||
}
|
||||
340
includes/Admin/Settings.php
Normal file
340
includes/Admin/Settings.php
Normal file
|
|
@ -0,0 +1,340 @@
|
|||
<?php
|
||||
/**
|
||||
* Settings page handler.
|
||||
*
|
||||
* @package MediaRightsAudit\Admin
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\Admin;
|
||||
|
||||
/**
|
||||
* Registers and renders the plugin Settings page.
|
||||
*
|
||||
* Settings are stored in a single option array: robotstxt_mediaaudit_settings.
|
||||
*/
|
||||
class Settings {
|
||||
|
||||
/**
|
||||
* WordPress Settings API option group name.
|
||||
*/
|
||||
const OPTION_GROUP = 'robotstxt_mediaaudit';
|
||||
|
||||
/**
|
||||
* Option name in the database.
|
||||
*/
|
||||
const OPTION_NAME = 'robotstxt_mediaaudit_settings';
|
||||
|
||||
/**
|
||||
* Registers all settings, sections, and fields via the WordPress Settings API.
|
||||
*
|
||||
* Hooked to admin_init.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register(): void {
|
||||
register_setting(
|
||||
self::OPTION_GROUP,
|
||||
self::OPTION_NAME,
|
||||
array(
|
||||
'type' => 'array',
|
||||
'sanitize_callback' => array( $this, 'sanitize' ),
|
||||
'default' => array(),
|
||||
)
|
||||
);
|
||||
|
||||
add_settings_section(
|
||||
'mra_general',
|
||||
__( 'General', 'robotstxt-mediaaudit' ),
|
||||
'__return_false',
|
||||
'robotstxt-mediaaudit-settings'
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
'delete_on_uninstall',
|
||||
__( 'Delete data on uninstall', 'robotstxt-mediaaudit' ),
|
||||
array( $this, 'field_delete_on_uninstall' ),
|
||||
'robotstxt-mediaaudit-settings',
|
||||
'mra_general'
|
||||
);
|
||||
|
||||
add_settings_section(
|
||||
'mra_api_credentials',
|
||||
__( 'API Credentials', 'robotstxt-mediaaudit' ),
|
||||
'__return_false',
|
||||
'robotstxt-mediaaudit-settings'
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
'google_vision_api_key',
|
||||
__( 'Google Cloud Vision API Key', 'robotstxt-mediaaudit' ),
|
||||
array( $this, 'field_google_vision_api_key' ),
|
||||
'robotstxt-mediaaudit-settings',
|
||||
'mra_api_credentials'
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
'tineye_api_key',
|
||||
__( 'TinEye API Key', 'robotstxt-mediaaudit' ),
|
||||
array( $this, 'field_tineye_api_key' ),
|
||||
'robotstxt-mediaaudit-settings',
|
||||
'mra_api_credentials'
|
||||
);
|
||||
|
||||
add_settings_section(
|
||||
'mra_external_scanning',
|
||||
__( 'External Scanning', 'robotstxt-mediaaudit' ),
|
||||
'__return_false',
|
||||
'robotstxt-mediaaudit-settings'
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
'external_batch_size',
|
||||
__( 'Batch Size', 'robotstxt-mediaaudit' ),
|
||||
array( $this, 'field_external_batch_size' ),
|
||||
'robotstxt-mediaaudit-settings',
|
||||
'mra_external_scanning'
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
'rate_limit_per_minute',
|
||||
__( 'Rate Limit (requests/min)', 'robotstxt-mediaaudit' ),
|
||||
array( $this, 'field_rate_limit_per_minute' ),
|
||||
'robotstxt-mediaaudit-settings',
|
||||
'mra_external_scanning'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitises the settings array on save.
|
||||
*
|
||||
* @param mixed $input Raw POST input.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function sanitize( $input ): array {
|
||||
$output = array();
|
||||
|
||||
if ( ! is_array( $input ) ) {
|
||||
return $output;
|
||||
}
|
||||
|
||||
$output['delete_on_uninstall'] = ! empty( $input['delete_on_uninstall'] );
|
||||
|
||||
$key_val = $input['google_vision_api_key'] ?? null;
|
||||
$output['google_vision_api_key'] = is_string( $key_val ) ? sanitize_text_field( $key_val ) : '';
|
||||
|
||||
$tineye_val = $input['tineye_api_key'] ?? null;
|
||||
$output['tineye_api_key'] = is_string( $tineye_val ) ? sanitize_text_field( $tineye_val ) : '';
|
||||
|
||||
$batch_val = $input['external_batch_size'] ?? null;
|
||||
$batch = is_numeric( $batch_val ) ? (int) $batch_val : 10;
|
||||
$output['external_batch_size'] = max( 1, min( 100, $batch ) );
|
||||
|
||||
$rl_val = $input['rate_limit_per_minute'] ?? null;
|
||||
$rl = is_numeric( $rl_val ) ? (int) $rl_val : 10;
|
||||
$output['rate_limit_per_minute'] = max( 1, min( 60, $rl ) );
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the "Delete data on uninstall" checkbox field.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function field_delete_on_uninstall(): void {
|
||||
$options = (array) get_option( self::OPTION_NAME, array() );
|
||||
$checked = ! empty( $options['delete_on_uninstall'] );
|
||||
?>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="<?php echo esc_attr( self::OPTION_NAME ); ?>[delete_on_uninstall]"
|
||||
value="1"
|
||||
<?php checked( $checked ); ?>
|
||||
/>
|
||||
<?php esc_html_e( 'Remove all plugin data (tables and options) when the plugin is uninstalled.', 'robotstxt-mediaaudit' ); ?>
|
||||
</label>
|
||||
<p class="description">
|
||||
<?php esc_html_e( 'By default, data is preserved after uninstall. Enable this only if you want a clean removal.', 'robotstxt-mediaaudit' ); ?>
|
||||
</p>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the Google Cloud Vision API key field.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function field_google_vision_api_key(): void {
|
||||
$options = (array) get_option( self::OPTION_NAME, array() );
|
||||
$val = $options['google_vision_api_key'] ?? '';
|
||||
$value = is_string( $val ) ? $val : '';
|
||||
?>
|
||||
<input
|
||||
type="text"
|
||||
id="google_vision_api_key"
|
||||
name="<?php echo esc_attr( self::OPTION_NAME ); ?>[google_vision_api_key]"
|
||||
value="<?php echo esc_attr( $value ); ?>"
|
||||
class="regular-text"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<p class="description">
|
||||
<?php esc_html_e( 'Required for Google Cloud Vision Web Detection. Obtain from the Google Cloud Console.', 'robotstxt-mediaaudit' ); ?>
|
||||
—
|
||||
<a href="https://cloud.google.com/vision/pricing" target="_blank" rel="noopener noreferrer">
|
||||
<?php esc_html_e( 'View pricing', 'robotstxt-mediaaudit' ); ?>
|
||||
</a>
|
||||
</p>
|
||||
<table class="mra-pricing-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><?php esc_html_e( 'Monthly requests', 'robotstxt-mediaaudit' ); ?></th>
|
||||
<th><?php esc_html_e( 'Price per 1,000', 'robotstxt-mediaaudit' ); ?></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><?php esc_html_e( 'First 1,000', 'robotstxt-mediaaudit' ); ?></td>
|
||||
<td><?php esc_html_e( 'Free', 'robotstxt-mediaaudit' ); ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1,001 – 5,000,000</td>
|
||||
<td>$1.50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>5,000,001+</td>
|
||||
<td>$0.60</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the TinEye API key field.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function field_tineye_api_key(): void {
|
||||
$options = (array) get_option( self::OPTION_NAME, array() );
|
||||
$val = $options['tineye_api_key'] ?? '';
|
||||
$value = is_string( $val ) ? $val : '';
|
||||
?>
|
||||
<input
|
||||
type="text"
|
||||
id="tineye_api_key"
|
||||
name="<?php echo esc_attr( self::OPTION_NAME ); ?>[tineye_api_key]"
|
||||
value="<?php echo esc_attr( $value ); ?>"
|
||||
class="regular-text"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<p class="description">
|
||||
<?php esc_html_e( 'Required for TinEye reverse image search. Obtain from your TinEye Commercial account.', 'robotstxt-mediaaudit' ); ?>
|
||||
—
|
||||
<a href="https://services.tineye.com/TinEyeAPI" target="_blank" rel="noopener noreferrer">
|
||||
<?php esc_html_e( 'View pricing', 'robotstxt-mediaaudit' ); ?>
|
||||
</a>
|
||||
</p>
|
||||
<table class="mra-pricing-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><?php esc_html_e( 'Bundle', 'robotstxt-mediaaudit' ); ?></th>
|
||||
<th><?php esc_html_e( 'Searches', 'robotstxt-mediaaudit' ); ?></th>
|
||||
<th><?php esc_html_e( 'Price', 'robotstxt-mediaaudit' ); ?></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><?php esc_html_e( 'Starter', 'robotstxt-mediaaudit' ); ?></td>
|
||||
<td>500</td>
|
||||
<td>$50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><?php esc_html_e( 'Standard', 'robotstxt-mediaaudit' ); ?></td>
|
||||
<td>5,000</td>
|
||||
<td>$200</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><?php esc_html_e( 'Professional', 'robotstxt-mediaaudit' ); ?></td>
|
||||
<td>25,000</td>
|
||||
<td>$600</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the external batch size field.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function field_external_batch_size(): void {
|
||||
$options = (array) get_option( self::OPTION_NAME, array() );
|
||||
$raw = $options['external_batch_size'] ?? 10;
|
||||
$value = is_numeric( $raw ) ? (int) $raw : 10;
|
||||
?>
|
||||
<input
|
||||
type="number"
|
||||
id="external_batch_size"
|
||||
name="<?php echo esc_attr( self::OPTION_NAME ); ?>[external_batch_size]"
|
||||
value="<?php echo esc_attr( (string) $value ); ?>"
|
||||
min="1"
|
||||
max="100"
|
||||
class="small-text"
|
||||
/>
|
||||
<p class="description">
|
||||
<?php esc_html_e( 'Number of images to scan per scheduled batch (1–100). Default: 10.', 'robotstxt-mediaaudit' ); ?>
|
||||
</p>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the per-minute rate limit field.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function field_rate_limit_per_minute(): void {
|
||||
$options = (array) get_option( self::OPTION_NAME, array() );
|
||||
$raw = $options['rate_limit_per_minute'] ?? 10;
|
||||
$value = is_numeric( $raw ) ? (int) $raw : 10;
|
||||
?>
|
||||
<input
|
||||
type="number"
|
||||
id="rate_limit_per_minute"
|
||||
name="<?php echo esc_attr( self::OPTION_NAME ); ?>[rate_limit_per_minute]"
|
||||
value="<?php echo esc_attr( (string) $value ); ?>"
|
||||
min="1"
|
||||
max="60"
|
||||
class="small-text"
|
||||
/>
|
||||
<p class="description">
|
||||
<?php esc_html_e( 'Maximum API requests per minute per provider (1–60). Default: 10.', 'robotstxt-mediaaudit' ); ?>
|
||||
</p>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the Settings admin page.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render(): void {
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_die( esc_html__( 'You do not have permission to access this page.', 'robotstxt-mediaaudit' ) );
|
||||
}
|
||||
?>
|
||||
<div class="wrap">
|
||||
<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
|
||||
<form method="post" action="options.php">
|
||||
<?php
|
||||
settings_fields( self::OPTION_GROUP );
|
||||
do_settings_sections( 'robotstxt-mediaaudit-settings' );
|
||||
submit_button();
|
||||
?>
|
||||
</form>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
}
|
||||
239
includes/CLI/Command.php
Normal file
239
includes/CLI/Command.php
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
<?php
|
||||
/**
|
||||
* WP-CLI command handler.
|
||||
*
|
||||
* @package MediaRightsAudit\CLI
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\CLI;
|
||||
|
||||
use MediaRightsAudit\Core\Database;
|
||||
use MediaRightsAudit\External\ExternalScanner;
|
||||
use MediaRightsAudit\Internal\AttachmentIndexer;
|
||||
use MediaRightsAudit\Internal\UsageScanner;
|
||||
|
||||
/**
|
||||
* WP-CLI commands for Media Audit.
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # Install or repair database tables.
|
||||
* $ wp mra install
|
||||
*
|
||||
* @package MediaRightsAudit\CLI
|
||||
*/
|
||||
class Command {
|
||||
|
||||
/**
|
||||
* Creates or repairs the plugin database tables.
|
||||
*
|
||||
* Safe to run multiple times. Uses dbDelta internally so existing tables
|
||||
* are only altered when the schema has changed.
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* $ wp mra install
|
||||
* Success: Media Audit tables ready. DB version: 1.0.0
|
||||
*
|
||||
* @subcommand install
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function install(): void {
|
||||
Database::create_tables();
|
||||
update_option( 'robotstxt_mediaaudit_db_version', ROBOTSTXT_MEDIAAUDIT_DB_VERSION );
|
||||
|
||||
\WP_CLI::success(
|
||||
sprintf(
|
||||
/* translators: %s: DB version number */
|
||||
__( 'Media Audit tables ready. DB version: %s', 'robotstxt-mediaaudit' ),
|
||||
ROBOTSTXT_MEDIAAUDIT_DB_VERSION
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the current plugin and schema versions.
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* $ wp mra status
|
||||
*
|
||||
* @subcommand status
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function status(): void {
|
||||
$raw = get_option( 'robotstxt_mediaaudit_db_version', 'not installed' );
|
||||
$stored = is_string( $raw ) ? $raw : 'not installed';
|
||||
|
||||
\WP_CLI::line(
|
||||
sprintf(
|
||||
/* translators: %s: plugin version */
|
||||
__( 'Plugin version : %s', 'robotstxt-mediaaudit' ),
|
||||
ROBOTSTXT_MEDIAAUDIT_VERSION
|
||||
)
|
||||
);
|
||||
\WP_CLI::line(
|
||||
sprintf(
|
||||
/* translators: %s: DB version number */
|
||||
__( 'DB version : %s', 'robotstxt-mediaaudit' ),
|
||||
$stored
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scans the media library for internal attachment usage.
|
||||
*
|
||||
* Runs indexing and usage scanning in a loop until all attachments are processed.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* [--batch=<size>]
|
||||
* : Number of attachments to process per iteration.
|
||||
* ---
|
||||
* default: 50
|
||||
* ---
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* $ wp mra scan-internal
|
||||
* $ wp mra scan-internal --batch=100
|
||||
*
|
||||
* @subcommand scan-internal
|
||||
*
|
||||
* @param array<string> $args Positional arguments (unused).
|
||||
* @param array<string> $assoc_args Named arguments.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function scan_internal( array $args, array $assoc_args ): void {
|
||||
$batch_size = isset( $assoc_args['batch'] ) ? intval( $assoc_args['batch'] ) : 50;
|
||||
if ( $batch_size < 1 ) {
|
||||
$batch_size = 50;
|
||||
}
|
||||
|
||||
// --- Indexing phase ---
|
||||
\WP_CLI::log( __( 'Indexing attachments…', 'robotstxt-mediaaudit' ) );
|
||||
$total_indexed = 0;
|
||||
|
||||
do {
|
||||
$indexed = AttachmentIndexer::index_batch( $batch_size );
|
||||
$total_indexed += $indexed;
|
||||
$pending = AttachmentIndexer::get_pending_count();
|
||||
|
||||
if ( $indexed > 0 ) {
|
||||
\WP_CLI::log(
|
||||
sprintf(
|
||||
/* translators: 1: newly indexed count, 2: remaining count */
|
||||
__( 'Indexed %1$d (%2$d remaining)', 'robotstxt-mediaaudit' ),
|
||||
$indexed,
|
||||
$pending
|
||||
)
|
||||
);
|
||||
}
|
||||
} while ( $indexed > 0 && $pending > 0 );
|
||||
|
||||
\WP_CLI::success(
|
||||
sprintf(
|
||||
/* translators: %d: total indexed count */
|
||||
__( 'Indexing complete. %d attachments in index.', 'robotstxt-mediaaudit' ),
|
||||
AttachmentIndexer::get_indexed_count()
|
||||
)
|
||||
);
|
||||
|
||||
// --- Usage scanning phase ---
|
||||
\WP_CLI::log( __( 'Scanning usage…', 'robotstxt-mediaaudit' ) );
|
||||
$total_scanned = 0;
|
||||
|
||||
do {
|
||||
$scanned = UsageScanner::scan_batch( $batch_size );
|
||||
$total_scanned += $scanned;
|
||||
$pending = UsageScanner::get_pending_count();
|
||||
|
||||
if ( $scanned > 0 ) {
|
||||
\WP_CLI::log(
|
||||
sprintf(
|
||||
/* translators: 1: scanned count, 2: remaining count */
|
||||
__( 'Scanned %1$d (%2$d remaining)', 'robotstxt-mediaaudit' ),
|
||||
$scanned,
|
||||
$pending
|
||||
)
|
||||
);
|
||||
}
|
||||
} while ( $scanned > 0 && $pending > 0 );
|
||||
|
||||
\WP_CLI::success(
|
||||
sprintf(
|
||||
/* translators: %d: total scanned count */
|
||||
__( 'Scan complete. %d attachments scanned.', 'robotstxt-mediaaudit' ),
|
||||
$total_scanned
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs external reverse-image-search scans via all configured providers.
|
||||
*
|
||||
* Promotes any 'pending' attachments to 'queued' before scanning, then
|
||||
* processes all queued items synchronously. Requires API keys to be configured.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* [--batch=<size>]
|
||||
* : Number of attachments to process per iteration.
|
||||
* ---
|
||||
* default: 10
|
||||
* ---
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* $ wp mra scan-external
|
||||
* $ wp mra scan-external --batch=5
|
||||
*
|
||||
* @subcommand scan-external
|
||||
*
|
||||
* @param array<string> $args Positional arguments (unused).
|
||||
* @param array<string> $assoc_args Named arguments.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function scan_external( array $args, array $assoc_args ): void {
|
||||
$batch_size = isset( $assoc_args['batch'] ) ? (int) $assoc_args['batch'] : 10;
|
||||
if ( $batch_size < 1 ) {
|
||||
$batch_size = 10;
|
||||
}
|
||||
|
||||
\WP_CLI::log( __( 'Running external scans…', 'robotstxt-mediaaudit' ) );
|
||||
|
||||
ExternalScanner::queue_all_pending();
|
||||
|
||||
$total_scanned = 0;
|
||||
|
||||
do {
|
||||
$scanned = ExternalScanner::scan_batch( $batch_size );
|
||||
$total_scanned += $scanned;
|
||||
$pending = ExternalScanner::get_pending_count();
|
||||
|
||||
if ( $scanned > 0 ) {
|
||||
\WP_CLI::log(
|
||||
sprintf(
|
||||
/* translators: 1: scanned count, 2: remaining count */
|
||||
__( 'Scanned %1$d (%2$d remaining)', 'robotstxt-mediaaudit' ),
|
||||
$scanned,
|
||||
$pending
|
||||
)
|
||||
);
|
||||
}
|
||||
} while ( $scanned > 0 && $pending > 0 );
|
||||
|
||||
\WP_CLI::success(
|
||||
sprintf(
|
||||
/* translators: %d: total scanned count */
|
||||
__( 'External scan complete. %d attachments processed.', 'robotstxt-mediaaudit' ),
|
||||
$total_scanned
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
25
includes/Core/Activator.php
Normal file
25
includes/Core/Activator.php
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<?php
|
||||
/**
|
||||
* Fired during plugin activation.
|
||||
*
|
||||
* @package MediaRightsAudit\Core
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\Core;
|
||||
|
||||
/**
|
||||
* Handles tasks that run once when the plugin is activated.
|
||||
*/
|
||||
class Activator {
|
||||
|
||||
/**
|
||||
* Creates database tables and seeds the initial DB version.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function activate(): void {
|
||||
Database::create_tables();
|
||||
update_option( 'robotstxt_mediaaudit_db_version', ROBOTSTXT_MEDIAAUDIT_DB_VERSION );
|
||||
flush_rewrite_rules();
|
||||
}
|
||||
}
|
||||
141
includes/Core/Database.php
Normal file
141
includes/Core/Database.php
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
<?php
|
||||
/**
|
||||
* Database schema creation and versioned migrations.
|
||||
*
|
||||
* @package MediaRightsAudit\Core
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\Core;
|
||||
|
||||
/**
|
||||
* Manages all custom table creation and schema migrations.
|
||||
*
|
||||
* Migration methods are idempotent: they rely on dbDelta's ALTER TABLE
|
||||
* diffing and can be run multiple times without side effects.
|
||||
*/
|
||||
class Database {
|
||||
|
||||
/**
|
||||
* Creates all tables. Called on plugin activation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function create_tables(): void {
|
||||
self::migration_100();
|
||||
self::migration_101();
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies any pending migrations based on the currently installed schema version.
|
||||
*
|
||||
* Called on admin_init by Plugin::check_db_version().
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function run_migrations(): void {
|
||||
$raw = get_option( 'robotstxt_mediaaudit_db_version', '0.0.0' );
|
||||
$current = is_string( $raw ) ? $raw : '0.0.0';
|
||||
|
||||
if ( version_compare( $current, '1.0.0', '<' ) ) {
|
||||
self::migration_100();
|
||||
}
|
||||
|
||||
if ( version_compare( $current, '1.0.1', '<' ) ) {
|
||||
self::migration_101();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops all plugin tables. Used by uninstall.php.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function drop_tables(): void {
|
||||
global $wpdb;
|
||||
$wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}mra_external_results`" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
$wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}mra_media_usage`" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
$wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}mra_media_index`" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Migrations
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Migration 1.0.0 — creates the initial three tables.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function migration_100(): void {
|
||||
global $wpdb;
|
||||
|
||||
$charset_collate = $wpdb->get_charset_collate();
|
||||
|
||||
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
|
||||
|
||||
dbDelta(
|
||||
"CREATE TABLE {$wpdb->prefix}mra_media_index (
|
||||
attachment_id bigint(20) unsigned NOT NULL,
|
||||
file_url text NOT NULL,
|
||||
file_name varchar(255) NOT NULL DEFAULT '',
|
||||
mime_type varchar(100) NOT NULL DEFAULT '',
|
||||
file_size bigint(20) unsigned NOT NULL DEFAULT 0,
|
||||
internal_scanned_at datetime DEFAULT NULL,
|
||||
external_status enum('pending','queued','scanned','matches','error') NOT NULL DEFAULT 'pending',
|
||||
external_scanned_at datetime DEFAULT NULL,
|
||||
created_at datetime NOT NULL,
|
||||
PRIMARY KEY (attachment_id),
|
||||
KEY external_status (external_status)
|
||||
) {$charset_collate};"
|
||||
);
|
||||
|
||||
dbDelta(
|
||||
"CREATE TABLE {$wpdb->prefix}mra_media_usage (
|
||||
usage_id bigint(20) unsigned NOT NULL auto_increment,
|
||||
attachment_id bigint(20) unsigned NOT NULL,
|
||||
post_id bigint(20) unsigned NOT NULL,
|
||||
post_type varchar(20) NOT NULL DEFAULT '',
|
||||
context enum('featured','content','meta') NOT NULL DEFAULT 'featured',
|
||||
meta_key varchar(255) DEFAULT NULL,
|
||||
created_at datetime NOT NULL,
|
||||
PRIMARY KEY (usage_id),
|
||||
KEY attachment_id (attachment_id),
|
||||
KEY post_id (post_id)
|
||||
) {$charset_collate};"
|
||||
);
|
||||
|
||||
dbDelta(
|
||||
"CREATE TABLE {$wpdb->prefix}mra_external_results (
|
||||
result_id bigint(20) unsigned NOT NULL auto_increment,
|
||||
attachment_id bigint(20) unsigned NOT NULL,
|
||||
provider enum('google_vision','tineye') NOT NULL,
|
||||
raw_response json DEFAULT NULL,
|
||||
match_count int(10) unsigned NOT NULL DEFAULT 0,
|
||||
top_domains json DEFAULT NULL,
|
||||
created_at datetime NOT NULL,
|
||||
PRIMARY KEY (result_id),
|
||||
UNIQUE KEY attachment_provider (attachment_id,provider)
|
||||
) {$charset_collate};"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Migration 1.0.1 — adds 'queued' to the external_status ENUM.
|
||||
*
|
||||
* Uses ALTER TABLE directly because dbDelta cannot modify ENUM column definitions.
|
||||
* Safe to re-run: MariaDB/MySQL treats an identical MODIFY as a no-op.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function migration_101(): void {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.DirectDatabaseQuery.SchemaChange
|
||||
$wpdb->query(
|
||||
"ALTER TABLE `{$wpdb->prefix}mra_media_index`
|
||||
MODIFY COLUMN external_status
|
||||
enum('pending','queued','scanned','matches','error') NOT NULL DEFAULT 'pending'"
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.DirectDatabaseQuery.SchemaChange
|
||||
}
|
||||
}
|
||||
28
includes/Core/Deactivator.php
Normal file
28
includes/Core/Deactivator.php
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
/**
|
||||
* Fired during plugin deactivation.
|
||||
*
|
||||
* @package MediaRightsAudit\Core
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\Core;
|
||||
|
||||
use MediaRightsAudit\Core\Queue\Scheduler;
|
||||
|
||||
/**
|
||||
* Handles tasks that run once when the plugin is deactivated.
|
||||
*/
|
||||
class Deactivator {
|
||||
|
||||
/**
|
||||
* Cancels all pending scheduled actions and flushes rewrite rules.
|
||||
*
|
||||
* Database tables and stored data are intentionally preserved.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function deactivate(): void {
|
||||
Scheduler::cancel_all();
|
||||
flush_rewrite_rules();
|
||||
}
|
||||
}
|
||||
165
includes/Core/Plugin.php
Normal file
165
includes/Core/Plugin.php
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
<?php
|
||||
/**
|
||||
* Core plugin bootstrap class.
|
||||
*
|
||||
* @package MediaRightsAudit\Core
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\Core;
|
||||
|
||||
use MediaRightsAudit\Admin\AuditPage;
|
||||
use MediaRightsAudit\Admin\Settings;
|
||||
use MediaRightsAudit\CLI\Command;
|
||||
use MediaRightsAudit\External\AbstractProvider;
|
||||
use MediaRightsAudit\External\ExternalScanner;
|
||||
use MediaRightsAudit\External\GoogleVisionProvider;
|
||||
use MediaRightsAudit\External\TinEyeProvider;
|
||||
use MediaRightsAudit\Internal\AttachmentIndexer;
|
||||
use MediaRightsAudit\Internal\UsageScanner;
|
||||
use MediaRightsAudit\Privacy\DataEraser;
|
||||
use MediaRightsAudit\Privacy\DataExporter;
|
||||
|
||||
/**
|
||||
* Registers all hooks and initialises the plugin subsystems.
|
||||
*/
|
||||
class Plugin {
|
||||
|
||||
/**
|
||||
* Settings page handler.
|
||||
*
|
||||
* @var Settings
|
||||
*/
|
||||
private Settings $settings;
|
||||
|
||||
/**
|
||||
* Audit list page controller.
|
||||
*
|
||||
* @var AuditPage
|
||||
*/
|
||||
private AuditPage $audit_page;
|
||||
|
||||
/**
|
||||
* Initialises dependencies.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->settings = new Settings();
|
||||
$this->audit_page = new AuditPage();
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches all WordPress hooks.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function run(): void {
|
||||
add_action( 'init', array( $this, 'load_textdomain' ) );
|
||||
add_action( 'admin_menu', array( $this, 'register_admin_pages' ) );
|
||||
add_action( 'admin_init', array( $this->settings, 'register' ) );
|
||||
add_action( 'admin_init', array( $this, 'check_db_version' ) );
|
||||
add_action( AttachmentIndexer::AS_HOOK, array( AttachmentIndexer::class, 'process_scheduled_batch' ) );
|
||||
add_action( UsageScanner::AS_HOOK, array( UsageScanner::class, 'process_scheduled_batch' ) );
|
||||
add_action( ExternalScanner::AS_HOOK, array( ExternalScanner::class, 'process_scheduled_batch' ) );
|
||||
add_filter( 'mra/external/providers', array( $this, 'register_providers' ) );
|
||||
add_filter( 'wp_privacy_personal_data_exporters', array( DataExporter::class, 'register' ) );
|
||||
add_filter( 'wp_privacy_personal_data_erasers', array( DataEraser::class, 'register' ) );
|
||||
$this->audit_page->register_hooks();
|
||||
$this->register_cli_commands();
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the plugin text domain.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function load_textdomain(): void {
|
||||
load_plugin_textdomain(
|
||||
'robotstxt-mediaaudit',
|
||||
false,
|
||||
dirname( plugin_basename( ROBOTSTXT_MEDIAAUDIT_PLUGIN_FILE ) ) . '/languages'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers admin menu pages.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_admin_pages(): void {
|
||||
$suffix = add_menu_page(
|
||||
__( 'Media Audit', 'robotstxt-mediaaudit' ),
|
||||
__( 'Media Audit', 'robotstxt-mediaaudit' ),
|
||||
'edit_others_posts',
|
||||
'robotstxt-mediaaudit',
|
||||
array( $this->audit_page, 'render' ),
|
||||
'dashicons-camera',
|
||||
60
|
||||
);
|
||||
|
||||
$this->audit_page->set_hook_suffix( $suffix );
|
||||
|
||||
// Rename the auto-created first submenu entry.
|
||||
add_submenu_page(
|
||||
'robotstxt-mediaaudit',
|
||||
__( 'Media Audit', 'robotstxt-mediaaudit' ),
|
||||
__( 'Media Audit', 'robotstxt-mediaaudit' ),
|
||||
'edit_others_posts',
|
||||
'robotstxt-mediaaudit',
|
||||
array( $this->audit_page, 'render' )
|
||||
);
|
||||
|
||||
add_submenu_page(
|
||||
'robotstxt-mediaaudit',
|
||||
__( 'Settings', 'robotstxt-mediaaudit' ),
|
||||
__( 'Settings', 'robotstxt-mediaaudit' ),
|
||||
'manage_options',
|
||||
'robotstxt-mediaaudit-settings',
|
||||
array( $this->settings, 'render' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs pending DB migrations when the stored schema version is behind the constant.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function check_db_version(): void {
|
||||
$raw = get_option( 'robotstxt_mediaaudit_db_version', '0.0.0' );
|
||||
$stored = is_string( $raw ) ? $raw : '0.0.0';
|
||||
if ( ROBOTSTXT_MEDIAAUDIT_DB_VERSION !== $stored ) {
|
||||
Database::run_migrations();
|
||||
update_option( 'robotstxt_mediaaudit_db_version', ROBOTSTXT_MEDIAAUDIT_DB_VERSION );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers built-in external providers via the mra/external/providers filter.
|
||||
*
|
||||
* @param mixed $providers Accumulated provider list.
|
||||
*
|
||||
* @return array<\MediaRightsAudit\External\AbstractProvider>
|
||||
*/
|
||||
public function register_providers( $providers ): array {
|
||||
$list = array();
|
||||
if ( is_array( $providers ) ) {
|
||||
foreach ( $providers as $p ) {
|
||||
if ( $p instanceof AbstractProvider ) {
|
||||
$list[] = $p;
|
||||
}
|
||||
}
|
||||
}
|
||||
$list[] = new GoogleVisionProvider();
|
||||
$list[] = new TinEyeProvider();
|
||||
return $list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers WP-CLI commands when running in CLI context.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register_cli_commands(): void {
|
||||
if ( defined( 'WP_CLI' ) && WP_CLI ) {
|
||||
\WP_CLI::add_command( 'mra', Command::class );
|
||||
}
|
||||
}
|
||||
}
|
||||
77
includes/Core/Queue/Scheduler.php
Normal file
77
includes/Core/Queue/Scheduler.php
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
<?php
|
||||
/**
|
||||
* Action Scheduler wrapper.
|
||||
*
|
||||
* @package MediaRightsAudit\Core\Queue
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\Core\Queue;
|
||||
|
||||
/**
|
||||
* Thin wrapper around Action Scheduler that namespaces all jobs under a single group.
|
||||
*
|
||||
* Action Scheduler is declared as a required plugin (Requires Plugins: action-scheduler)
|
||||
* so its functions are always available at runtime. The is_available() guard is kept
|
||||
* for defensive unit-test scenarios only.
|
||||
*/
|
||||
class Scheduler {
|
||||
|
||||
/**
|
||||
* Action Scheduler group for all plugin jobs.
|
||||
*/
|
||||
const GROUP = 'robotstxt-mediaaudit';
|
||||
|
||||
/**
|
||||
* Returns true when Action Scheduler functions are available.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_available(): bool {
|
||||
return function_exists( 'as_schedule_single_action' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules a single action to run after the given delay.
|
||||
*
|
||||
* @param string $hook Action hook name.
|
||||
* @param array<mixed> $args Arguments passed to the hook.
|
||||
* @param int $delay Seconds from now (default 0 = immediate).
|
||||
*
|
||||
* @return int|null Action Scheduler action ID, or null if unavailable.
|
||||
*/
|
||||
public static function schedule_single( string $hook, array $args = array(), int $delay = 0 ): ?int {
|
||||
if ( ! self::is_available() ) {
|
||||
return null;
|
||||
}
|
||||
return as_schedule_single_action( time() + $delay, $hook, $args, self::GROUP );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a pending (not-yet-run) action exists for this hook.
|
||||
*
|
||||
* @param string $hook Action hook name.
|
||||
* @param array<mixed> $args Arguments to match.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function has_pending( string $hook, array $args = array() ): bool {
|
||||
if ( ! self::is_available() ) {
|
||||
return false;
|
||||
}
|
||||
return as_has_scheduled_action( $hook, $args, self::GROUP );
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels all pending plugin actions across all hooks.
|
||||
*
|
||||
* Called on plugin deactivation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function cancel_all(): void {
|
||||
if ( ! self::is_available() ) {
|
||||
return;
|
||||
}
|
||||
as_unschedule_all_actions( '', array(), self::GROUP );
|
||||
}
|
||||
}
|
||||
128
includes/External/AbstractProvider.php
vendored
Normal file
128
includes/External/AbstractProvider.php
vendored
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
<?php
|
||||
/**
|
||||
* Base class for all external reverse-image-search providers.
|
||||
*
|
||||
* @package MediaRightsAudit\External
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\External;
|
||||
|
||||
/**
|
||||
* Provides rate-limited scanning via a transient-based per-minute counter.
|
||||
*
|
||||
* Subclasses implement do_scan() with the provider-specific HTTP call.
|
||||
* The public scan() wrapper enforces the rate limit before delegating.
|
||||
*/
|
||||
abstract class AbstractProvider {
|
||||
|
||||
/**
|
||||
* Machine-readable provider identifier stored in mra_external_results.provider.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
abstract public function provider_slug(): string;
|
||||
|
||||
/**
|
||||
* Human-readable provider display name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
abstract public function provider_name(): string;
|
||||
|
||||
/**
|
||||
* Maximum API requests allowed per minute for this provider.
|
||||
*
|
||||
* Subclasses may override to read a per-provider setting.
|
||||
*
|
||||
* @return positive-int
|
||||
*/
|
||||
public function rate_limit(): int {
|
||||
return 10;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the provider-specific scan and returns a result.
|
||||
*
|
||||
* @param int $attachment_id WordPress attachment ID.
|
||||
* @param string $file_url Public URL of the image to analyse.
|
||||
*
|
||||
* @return ScanResult
|
||||
*
|
||||
* @throws \RuntimeException On HTTP or parse errors.
|
||||
*/
|
||||
abstract protected function do_scan( int $attachment_id, string $file_url ): ScanResult;
|
||||
|
||||
/**
|
||||
* Scans an image URL after checking the per-minute rate limit.
|
||||
*
|
||||
* @param int $attachment_id WordPress attachment ID.
|
||||
* @param string $file_url Public URL of the image to analyse.
|
||||
*
|
||||
* @return ScanResult
|
||||
*
|
||||
* @throws \RuntimeException When rate limit is exceeded or the scan fails.
|
||||
*/
|
||||
final public function scan( int $attachment_id, string $file_url ): ScanResult {
|
||||
$this->enforce_rate_limit();
|
||||
return $this->do_scan( $attachment_id, $file_url );
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a domain → count map from a list of URL-bearing items.
|
||||
*
|
||||
* Each item must be an array with a string 'url' key. Items missing the key
|
||||
* or whose host cannot be parsed are silently skipped.
|
||||
*
|
||||
* @param array<mixed> $items URL-bearing items (e.g. pages or backlink objects).
|
||||
*
|
||||
* @return array<string, int> Domain → occurrence count, sorted descending, max 10.
|
||||
*/
|
||||
protected function extract_top_domains( array $items ): array {
|
||||
$counts = array();
|
||||
|
||||
foreach ( $items as $item ) {
|
||||
if ( ! is_array( $item ) ) {
|
||||
continue;
|
||||
}
|
||||
$url_val = $item['url'] ?? null;
|
||||
if ( ! is_string( $url_val ) || '' === $url_val ) {
|
||||
continue;
|
||||
}
|
||||
$host = wp_parse_url( $url_val, PHP_URL_HOST );
|
||||
if ( ! is_string( $host ) || '' === $host ) {
|
||||
continue;
|
||||
}
|
||||
$counts[ $host ] = ( $counts[ $host ] ?? 0 ) + 1;
|
||||
}
|
||||
|
||||
arsort( $counts );
|
||||
return array_slice( $counts, 0, 10, true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks and increments the per-minute request counter via transients.
|
||||
*
|
||||
* Throws if the counter has reached the configured limit.
|
||||
*
|
||||
* @throws \RuntimeException When the rate limit for the current minute is exhausted.
|
||||
*/
|
||||
private function enforce_rate_limit(): void {
|
||||
$key = 'mra_rl_' . $this->provider_slug() . '_' . gmdate( 'YmdHi' );
|
||||
$raw = get_transient( $key );
|
||||
$current = is_numeric( $raw ) ? (int) $raw : 0;
|
||||
|
||||
if ( $current >= $this->rate_limit() ) {
|
||||
// phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped
|
||||
throw new \RuntimeException(
|
||||
sprintf(
|
||||
'Rate limit of %d req/min exceeded for provider "%s".',
|
||||
$this->rate_limit(),
|
||||
$this->provider_slug()
|
||||
)
|
||||
);
|
||||
// phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped
|
||||
}
|
||||
|
||||
set_transient( $key, $current + 1, 90 );
|
||||
}
|
||||
}
|
||||
334
includes/External/ExternalScanner.php
vendored
Normal file
334
includes/External/ExternalScanner.php
vendored
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
<?php
|
||||
/**
|
||||
* External scan batch processor.
|
||||
*
|
||||
* @package MediaRightsAudit\External
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\External;
|
||||
|
||||
use MediaRightsAudit\Core\Queue\Scheduler;
|
||||
|
||||
/**
|
||||
* Processes the external scan queue: runs each pending attachment through
|
||||
* all active providers and stores results in mra_external_results.
|
||||
*
|
||||
* Active providers are resolved at runtime via the mra/external/providers filter.
|
||||
* Scanning is triggered manually by an administrator (Run External Scan bulk action
|
||||
* or wp mra scan-external CLI) — never automatically, to control API costs.
|
||||
*
|
||||
* Extension hook: mra/external/providers — filter to register additional providers.
|
||||
*/
|
||||
class ExternalScanner {
|
||||
|
||||
/**
|
||||
* Action Scheduler hook name for background external scanning.
|
||||
*/
|
||||
const AS_HOOK = 'mra_external_scan_batch';
|
||||
|
||||
/**
|
||||
* Scans one batch of pending attachments with all active providers.
|
||||
*
|
||||
* @param int $batch_size Maximum number of attachments to process.
|
||||
*
|
||||
* @return int Number of attachments attempted.
|
||||
*/
|
||||
public static function scan_batch( int $batch_size = 10 ): int {
|
||||
global $wpdb;
|
||||
|
||||
$providers = self::get_active_providers();
|
||||
if ( empty( $providers ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$rows = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT attachment_id, file_url
|
||||
FROM {$wpdb->prefix}mra_media_index
|
||||
WHERE external_status = 'queued'
|
||||
ORDER BY attachment_id ASC
|
||||
LIMIT %d",
|
||||
$batch_size
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
|
||||
if ( ! $rows ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
foreach ( $rows as $row ) {
|
||||
$aid_val = $row['attachment_id'] ?? null;
|
||||
$url_val = $row['file_url'] ?? null;
|
||||
$aid = is_numeric( $aid_val ) ? (int) $aid_val : 0;
|
||||
$url = is_string( $url_val ) ? $url_val : '';
|
||||
|
||||
if ( $aid <= 0 || '' === $url ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
self::process_attachment( $aid, $url, $providers );
|
||||
}
|
||||
|
||||
return count( $rows );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the count of attachments still waiting for external scanning.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function get_pending_count(): int {
|
||||
global $wpdb;
|
||||
|
||||
$result = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
"SELECT COUNT(*) FROM {$wpdb->prefix}mra_media_index WHERE external_status = 'queued'"
|
||||
);
|
||||
|
||||
return is_numeric( $result ) ? (int) $result : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes one scheduled batch and re-queues if more remain.
|
||||
*
|
||||
* Called by Action Scheduler via the mra_external_scan_batch hook.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function process_scheduled_batch(): void {
|
||||
self::scan_batch();
|
||||
|
||||
if ( self::get_pending_count() > 0 ) {
|
||||
Scheduler::schedule_single( self::AS_HOOK );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Promotes all attachments with external_status = 'pending' to 'queued'.
|
||||
*
|
||||
* Does not schedule an Action Scheduler action. Useful in CLI context where
|
||||
* processing runs synchronously in a loop rather than via background jobs.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function queue_all_pending(): void {
|
||||
global $wpdb;
|
||||
|
||||
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
"UPDATE {$wpdb->prefix}mra_media_index
|
||||
SET external_status = 'queued'
|
||||
WHERE external_status = 'pending'"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks all pending attachments as queued and schedules a background scan batch.
|
||||
*
|
||||
* Moves every attachment with external_status = 'pending' to 'queued' so the
|
||||
* status change is visible immediately in the admin list. Only schedules the
|
||||
* Action Scheduler action if there are now queued items and no batch is already running.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function schedule(): void {
|
||||
global $wpdb;
|
||||
|
||||
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
"UPDATE {$wpdb->prefix}mra_media_index
|
||||
SET external_status = 'queued'
|
||||
WHERE external_status = 'pending'"
|
||||
);
|
||||
|
||||
if ( self::get_pending_count() > 0 && ! Scheduler::has_pending( self::AS_HOOK ) ) {
|
||||
Scheduler::schedule_single( self::AS_HOOK );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks specific attachments as pending and schedules a scan batch.
|
||||
*
|
||||
* Idempotent: already-pending attachments are left unchanged;
|
||||
* previously-scanned or error attachments are reset to pending.
|
||||
*
|
||||
* @param array<int, int> $attachment_ids Attachment IDs to queue. Must be non-empty.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function queue_attachments( array $attachment_ids ): void {
|
||||
if ( empty( $attachment_ids ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
global $wpdb;
|
||||
|
||||
$ids = array_map( 'intval', $attachment_ids );
|
||||
$placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
$wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"UPDATE {$wpdb->prefix}mra_media_index
|
||||
SET external_status = 'queued', external_scanned_at = NULL
|
||||
WHERE attachment_id IN ({$placeholders})
|
||||
AND external_status != 'queued'",
|
||||
...$ids
|
||||
)
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
|
||||
// Schedule directly — do not call schedule() which would also mark all 'pending' items.
|
||||
if ( ! Scheduler::has_pending( self::AS_HOOK ) ) {
|
||||
Scheduler::schedule_single( self::AS_HOOK );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes external scan results and resets status to pending for given IDs.
|
||||
*
|
||||
* @param array<int, int> $attachment_ids Attachment IDs to purge.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function purge( array $attachment_ids ): void {
|
||||
if ( empty( $attachment_ids ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
global $wpdb;
|
||||
|
||||
$ids = array_map( 'intval', $attachment_ids );
|
||||
$placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
$wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"DELETE FROM {$wpdb->prefix}mra_external_results
|
||||
WHERE attachment_id IN ({$placeholders})",
|
||||
...$ids
|
||||
)
|
||||
);
|
||||
|
||||
$wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"UPDATE {$wpdb->prefix}mra_media_index
|
||||
SET external_status = 'pending', external_scanned_at = NULL
|
||||
WHERE attachment_id IN ({$placeholders})",
|
||||
...$ids
|
||||
)
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Private helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Scans a single attachment with all providers and updates the index.
|
||||
*
|
||||
* @param int $attachment_id WordPress attachment ID.
|
||||
* @param string $file_url Public URL of the image.
|
||||
* @param array<AbstractProvider> $providers Resolved provider list.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function process_attachment( int $attachment_id, string $file_url, array $providers ): void {
|
||||
global $wpdb;
|
||||
|
||||
$any_success = false;
|
||||
$any_match = false;
|
||||
|
||||
foreach ( $providers as $provider ) {
|
||||
try {
|
||||
$result = $provider->scan( $attachment_id, $file_url );
|
||||
self::save_result( $attachment_id, $provider->provider_slug(), $result );
|
||||
$any_success = true;
|
||||
if ( $result->match_count() > 0 ) {
|
||||
$any_match = true;
|
||||
}
|
||||
} catch ( \RuntimeException $e ) {
|
||||
if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
|
||||
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
error_log(
|
||||
sprintf(
|
||||
'[MRA] %s scan failed for attachment %d: %s',
|
||||
$provider->provider_slug(),
|
||||
$attachment_id,
|
||||
$e->getMessage()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! $any_success ) {
|
||||
$new_status = 'error';
|
||||
} elseif ( $any_match ) {
|
||||
$new_status = 'matches';
|
||||
} else {
|
||||
$new_status = 'scanned';
|
||||
}
|
||||
|
||||
$wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
$wpdb->prefix . 'mra_media_index',
|
||||
array(
|
||||
'external_status' => $new_status,
|
||||
'external_scanned_at' => current_time( 'mysql', true ),
|
||||
),
|
||||
array( 'attachment_id' => $attachment_id ),
|
||||
array( '%s', '%s' ),
|
||||
array( '%d' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists a provider's scan result (upsert via REPLACE INTO).
|
||||
*
|
||||
* @param int $attachment_id WordPress attachment ID.
|
||||
* @param string $provider_slug Provider machine-readable slug.
|
||||
* @param ScanResult $result Scan result to store.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function save_result( int $attachment_id, string $provider_slug, ScanResult $result ): void {
|
||||
global $wpdb;
|
||||
|
||||
$raw_json = wp_json_encode( $result->raw_response() );
|
||||
$domains_json = wp_json_encode( $result->top_domains() );
|
||||
|
||||
$wpdb->replace( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
$wpdb->prefix . 'mra_external_results',
|
||||
array(
|
||||
'attachment_id' => $attachment_id,
|
||||
'provider' => $provider_slug,
|
||||
'raw_response' => ( false !== $raw_json ) ? $raw_json : '{}',
|
||||
'match_count' => $result->match_count(),
|
||||
'top_domains' => ( false !== $domains_json ) ? $domains_json : '{}',
|
||||
'created_at' => current_time( 'mysql', true ),
|
||||
),
|
||||
array( '%d', '%s', '%s', '%d', '%s', '%s' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves active providers from the mra/external/providers filter.
|
||||
*
|
||||
* @return array<AbstractProvider>
|
||||
*/
|
||||
private static function get_active_providers(): array {
|
||||
$raw = apply_filters( 'mra/external/providers', array() ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
|
||||
$providers = array();
|
||||
|
||||
if ( is_array( $raw ) ) {
|
||||
foreach ( $raw as $p ) {
|
||||
if ( $p instanceof AbstractProvider ) {
|
||||
$providers[] = $p;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $providers;
|
||||
}
|
||||
}
|
||||
177
includes/External/GoogleVisionProvider.php
vendored
Normal file
177
includes/External/GoogleVisionProvider.php
vendored
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
<?php
|
||||
/**
|
||||
* Google Cloud Vision Web Detection provider.
|
||||
*
|
||||
* @package MediaRightsAudit\External
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\External;
|
||||
|
||||
use MediaRightsAudit\Admin\Settings;
|
||||
|
||||
/**
|
||||
* Sends images to the Google Cloud Vision API (WEB_DETECTION feature) and
|
||||
* normalises the response into a ScanResult.
|
||||
*
|
||||
* Reads the API key from the plugin settings (google_vision_api_key).
|
||||
* Supports public-URL image submissions; for private/staging sites the
|
||||
* file_url may not be publicly accessible — a warning is surfaced via
|
||||
* the scan error message in that case.
|
||||
*/
|
||||
class GoogleVisionProvider extends AbstractProvider {
|
||||
|
||||
/**
|
||||
* Google Vision API endpoint (without key).
|
||||
*/
|
||||
const ENDPOINT = 'https://vision.googleapis.com/v1/images:annotate';
|
||||
|
||||
/**
|
||||
* Returns the machine-readable provider identifier.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function provider_slug(): string {
|
||||
return 'google_vision';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human-readable provider display name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function provider_name(): string {
|
||||
return __( 'Google Cloud Vision', 'robotstxt-mediaaudit' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the image to Google Cloud Vision Web Detection and returns a ScanResult.
|
||||
*
|
||||
* @param int $attachment_id WordPress attachment ID.
|
||||
* @param string $file_url Public URL of the image.
|
||||
*
|
||||
* @return ScanResult
|
||||
*
|
||||
* @throws \RuntimeException On configuration, HTTP, or parse errors.
|
||||
*/
|
||||
protected function do_scan( int $attachment_id, string $file_url ): ScanResult {
|
||||
$api_key = $this->get_api_key();
|
||||
if ( '' === $api_key ) {
|
||||
throw new \RuntimeException( 'Google Vision API key is not configured.' );
|
||||
}
|
||||
|
||||
$body = wp_json_encode(
|
||||
array(
|
||||
'requests' => array(
|
||||
array(
|
||||
'image' => array( 'source' => array( 'imageUri' => $file_url ) ),
|
||||
'features' => array(
|
||||
array(
|
||||
'type' => 'WEB_DETECTION',
|
||||
'maxResults' => 100,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
);
|
||||
|
||||
if ( false === $body ) {
|
||||
throw new \RuntimeException( 'Failed to encode Google Vision request body.' );
|
||||
}
|
||||
|
||||
$response = wp_remote_post(
|
||||
self::ENDPOINT,
|
||||
array(
|
||||
'headers' => array(
|
||||
'Content-Type' => 'application/json; charset=utf-8',
|
||||
'X-Goog-Api-Key' => $api_key,
|
||||
),
|
||||
'body' => $body,
|
||||
'timeout' => 30,
|
||||
)
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
throw new \RuntimeException( $response->get_error_message() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
|
||||
}
|
||||
|
||||
$http_code = (int) wp_remote_retrieve_response_code( $response );
|
||||
if ( 200 !== $http_code ) {
|
||||
throw new \RuntimeException(
|
||||
sprintf( 'Google Vision API returned HTTP %d.', $http_code ) // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
|
||||
);
|
||||
}
|
||||
|
||||
$raw_body = wp_remote_retrieve_body( $response );
|
||||
$decoded = json_decode( $raw_body, true );
|
||||
|
||||
if ( ! is_array( $decoded ) ) {
|
||||
throw new \RuntimeException( 'Failed to parse Google Vision API response.' );
|
||||
}
|
||||
|
||||
return $this->parse_response( $decoded );
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Private helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Reads the Google Vision API key from plugin settings.
|
||||
*
|
||||
* @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;
|
||||
return is_string( $val ) ? trim( $val ) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the decoded Vision API response into a ScanResult.
|
||||
*
|
||||
* @param array<mixed, mixed> $decoded json_decode()'d API response.
|
||||
*
|
||||
* @return ScanResult
|
||||
*/
|
||||
private function parse_response( array $decoded ): ScanResult {
|
||||
$web_detection = $this->extract_web_detection( $decoded );
|
||||
|
||||
$pages_raw = $web_detection['pagesWithMatchingImages'] ?? null;
|
||||
$pages = is_array( $pages_raw ) ? $pages_raw : array();
|
||||
|
||||
$full_raw = $web_detection['fullMatchingImages'] ?? null;
|
||||
$full = is_array( $full_raw ) ? $full_raw : array();
|
||||
|
||||
$partial_raw = $web_detection['partialMatchingImages'] ?? null;
|
||||
$partial = is_array( $partial_raw ) ? $partial_raw : array();
|
||||
|
||||
$match_count = count( $pages ) + count( $full );
|
||||
$top_domains = $this->extract_top_domains( array_merge( $pages, $full, $partial ) );
|
||||
|
||||
return new ScanResult( $match_count, $top_domains, $decoded );
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the webDetection sub-object from the full API response.
|
||||
*
|
||||
* @param array<mixed, mixed> $decoded Full decoded API response.
|
||||
*
|
||||
* @return array<mixed, mixed>
|
||||
*/
|
||||
private function extract_web_detection( array $decoded ): array {
|
||||
$responses_raw = $decoded['responses'] ?? null;
|
||||
if ( ! is_array( $responses_raw ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$first = reset( $responses_raw );
|
||||
if ( ! is_array( $first ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$wd = $first['webDetection'] ?? null;
|
||||
return is_array( $wd ) ? $wd : array();
|
||||
}
|
||||
}
|
||||
99
includes/External/ResultsConsolidator.php
vendored
Normal file
99
includes/External/ResultsConsolidator.php
vendored
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
<?php
|
||||
/**
|
||||
* Cross-provider result consolidation.
|
||||
*
|
||||
* @package MediaRightsAudit\External
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\External;
|
||||
|
||||
/**
|
||||
* Aggregates external scan results across multiple providers to surface
|
||||
* domains that appear in more than one provider's findings (consensus signals).
|
||||
*
|
||||
* Consensus detection provides stronger copyright-risk signals: a domain
|
||||
* independently found by both Google Vision and TinEye is more likely to be
|
||||
* a genuine unauthorised copy than one found by a single provider.
|
||||
*/
|
||||
class ResultsConsolidator {
|
||||
|
||||
/**
|
||||
* Returns domains confirmed by results from at least $min_providers distinct providers.
|
||||
*
|
||||
* Reads top_domains JSON stored in mra_external_results for the given attachment
|
||||
* and counts how many providers reported each domain. Only domains meeting the
|
||||
* threshold are returned, sorted descending by provider-agreement count.
|
||||
*
|
||||
* @param int $attachment_id WordPress attachment ID.
|
||||
* @param int $min_providers Minimum number of providers that must agree (default: 2).
|
||||
*
|
||||
* @return array<string, int> Domain → agreeing-provider count, sorted descending.
|
||||
*/
|
||||
public static function get_consensus_domains( int $attachment_id, int $min_providers = 2 ): array {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$rows = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT provider, top_domains FROM {$wpdb->prefix}mra_external_results WHERE attachment_id = %d",
|
||||
$attachment_id
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
|
||||
if ( ! $rows ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return self::aggregate_consensus( $rows, $min_providers );
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes consensus domains from an array of provider result rows.
|
||||
*
|
||||
* Each row must contain 'provider' (string) and 'top_domains' (JSON string
|
||||
* mapping domain → count). Designed to be called directly in unit tests
|
||||
* by passing mock row data.
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $rows Provider result rows.
|
||||
* @param int $min_providers Minimum provider agreement.
|
||||
*
|
||||
* @return array<string, int> Domain → agreeing-provider count, sorted descending.
|
||||
*/
|
||||
public static function aggregate_consensus( array $rows, int $min_providers = 2 ): array {
|
||||
$domain_to_providers = array();
|
||||
|
||||
foreach ( $rows as $row ) {
|
||||
$provider_val = $row['provider'] ?? null;
|
||||
$provider = is_string( $provider_val ) ? $provider_val : '';
|
||||
if ( '' === $provider ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$domains_val = $row['top_domains'] ?? null;
|
||||
$domains_raw = is_string( $domains_val ) ? json_decode( $domains_val, true ) : null;
|
||||
$domains = is_array( $domains_raw ) ? $domains_raw : array();
|
||||
|
||||
foreach ( $domains as $domain => $count ) {
|
||||
if ( ! is_string( $domain ) ) {
|
||||
continue;
|
||||
}
|
||||
if ( ! isset( $domain_to_providers[ $domain ] ) ) {
|
||||
$domain_to_providers[ $domain ] = array();
|
||||
}
|
||||
$domain_to_providers[ $domain ][ $provider ] = true;
|
||||
}
|
||||
}
|
||||
|
||||
$consensus = array();
|
||||
foreach ( $domain_to_providers as $domain => $providers_map ) {
|
||||
$provider_count = count( $providers_map );
|
||||
if ( $provider_count >= $min_providers ) {
|
||||
$consensus[ $domain ] = $provider_count;
|
||||
}
|
||||
}
|
||||
|
||||
arsort( $consensus );
|
||||
return $consensus;
|
||||
}
|
||||
}
|
||||
75
includes/External/ScanResult.php
vendored
Normal file
75
includes/External/ScanResult.php
vendored
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
<?php
|
||||
/**
|
||||
* Value object representing the outcome of one external provider scan.
|
||||
*
|
||||
* @package MediaRightsAudit\External
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\External;
|
||||
|
||||
/**
|
||||
* Immutable result returned by AbstractProvider::scan().
|
||||
*/
|
||||
class ScanResult {
|
||||
|
||||
/**
|
||||
* Number of pages / images where the attachment was found.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private int $match_count;
|
||||
|
||||
/**
|
||||
* Top domains where matches were found (domain → occurrence count), max 10.
|
||||
*
|
||||
* @var array<string, int>
|
||||
*/
|
||||
private array $top_domains;
|
||||
|
||||
/**
|
||||
* Full decoded API response for storage.
|
||||
*
|
||||
* @var array<mixed, mixed>
|
||||
*/
|
||||
private array $raw_response;
|
||||
|
||||
/**
|
||||
* Constructs a new scan result.
|
||||
*
|
||||
* @param int $match_count Number of pages or images found.
|
||||
* @param array<string, int> $top_domains Domain → count map.
|
||||
* @param array<mixed, mixed> $raw_response Full decoded API payload.
|
||||
*/
|
||||
public function __construct( int $match_count, array $top_domains, array $raw_response ) {
|
||||
$this->match_count = $match_count;
|
||||
$this->top_domains = $top_domains;
|
||||
$this->raw_response = $raw_response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of matching pages or images found.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function match_count(): int {
|
||||
return $this->match_count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the top-domain occurrence map (domain → count), max 10 entries.
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public function top_domains(): array {
|
||||
return $this->top_domains;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the full decoded API response payload.
|
||||
*
|
||||
* @return array<mixed, mixed>
|
||||
*/
|
||||
public function raw_response(): array {
|
||||
return $this->raw_response;
|
||||
}
|
||||
}
|
||||
151
includes/External/TinEyeProvider.php
vendored
Normal file
151
includes/External/TinEyeProvider.php
vendored
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
<?php
|
||||
/**
|
||||
* TinEye reverse image search provider.
|
||||
*
|
||||
* @package MediaRightsAudit\External
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\External;
|
||||
|
||||
use MediaRightsAudit\Admin\Settings;
|
||||
|
||||
/**
|
||||
* Submits images to the TinEye Commercial API and normalises the response
|
||||
* into a ScanResult.
|
||||
*
|
||||
* Uses URL-based image submission (GET request with image_url parameter).
|
||||
* Reads the API key from the plugin settings (tineye_api_key).
|
||||
* Match count reflects the number of distinct matching images found;
|
||||
* top domains are extracted from the backlink URLs of all matches.
|
||||
*/
|
||||
class TinEyeProvider extends AbstractProvider {
|
||||
|
||||
/**
|
||||
* TinEye Commercial API search endpoint.
|
||||
*/
|
||||
const ENDPOINT = 'https://api.tineye.com/rest/search/';
|
||||
|
||||
/**
|
||||
* Returns the machine-readable provider identifier.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function provider_slug(): string {
|
||||
return 'tineye';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human-readable provider display name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function provider_name(): string {
|
||||
return 'TinEye';
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits the image URL to TinEye and returns a ScanResult.
|
||||
*
|
||||
* @param int $attachment_id WordPress attachment ID.
|
||||
* @param string $file_url Public URL of the image.
|
||||
*
|
||||
* @return ScanResult
|
||||
*
|
||||
* @throws \RuntimeException On configuration, HTTP, or parse errors.
|
||||
*/
|
||||
protected function do_scan( int $attachment_id, string $file_url ): ScanResult {
|
||||
$api_key = $this->get_api_key();
|
||||
if ( '' === $api_key ) {
|
||||
throw new \RuntimeException( 'TinEye API key is not configured.' );
|
||||
}
|
||||
|
||||
$url = add_query_arg(
|
||||
array(
|
||||
'api_key' => $api_key,
|
||||
'image_url' => $file_url,
|
||||
),
|
||||
self::ENDPOINT
|
||||
);
|
||||
|
||||
$response = wp_remote_get( $url, array( 'timeout' => 30 ) );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
throw new \RuntimeException( $response->get_error_message() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
|
||||
}
|
||||
|
||||
$http_code = (int) wp_remote_retrieve_response_code( $response );
|
||||
if ( 200 !== $http_code ) {
|
||||
throw new \RuntimeException(
|
||||
sprintf( 'TinEye API returned HTTP %d.', $http_code ) // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
|
||||
);
|
||||
}
|
||||
|
||||
$raw_body = wp_remote_retrieve_body( $response );
|
||||
$decoded = json_decode( $raw_body, true );
|
||||
|
||||
if ( ! is_array( $decoded ) ) {
|
||||
throw new \RuntimeException( 'Failed to parse TinEye API response.' );
|
||||
}
|
||||
|
||||
return $this->parse_response( $decoded );
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Private helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Reads the TinEye API key from plugin settings.
|
||||
*
|
||||
* @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;
|
||||
return is_string( $val ) ? trim( $val ) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a decoded TinEye API response into a ScanResult.
|
||||
*
|
||||
* Navigates results.matches, extracts backlink page URLs to build the
|
||||
* domain-frequency map, and counts distinct image matches.
|
||||
*
|
||||
* @param array<mixed, mixed> $decoded json_decode()'d API response.
|
||||
*
|
||||
* @return ScanResult
|
||||
*/
|
||||
private function parse_response( array $decoded ): ScanResult {
|
||||
$results_raw = $decoded['results'] ?? null;
|
||||
$results = is_array( $results_raw ) ? $results_raw : array();
|
||||
|
||||
$matches_raw = $results['matches'] ?? null;
|
||||
$matches = is_array( $matches_raw ) ? $matches_raw : array();
|
||||
|
||||
$backlink_items = array();
|
||||
foreach ( $matches as $match ) {
|
||||
if ( ! is_array( $match ) ) {
|
||||
continue;
|
||||
}
|
||||
$bls_raw = $match['backlinks'] ?? null;
|
||||
if ( ! is_array( $bls_raw ) ) {
|
||||
continue;
|
||||
}
|
||||
foreach ( $bls_raw as $bl ) {
|
||||
if ( ! is_array( $bl ) ) {
|
||||
continue;
|
||||
}
|
||||
$url_val = $bl['url'] ?? null;
|
||||
if ( is_string( $url_val ) && '' !== $url_val ) {
|
||||
$backlink_items[] = array( 'url' => $url_val );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$match_count = count( $matches );
|
||||
$top_domains = $this->extract_top_domains( $backlink_items );
|
||||
|
||||
return new ScanResult( $match_count, $top_domains, $decoded );
|
||||
}
|
||||
}
|
||||
175
includes/Internal/AttachmentIndexer.php
Normal file
175
includes/Internal/AttachmentIndexer.php
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
<?php
|
||||
/**
|
||||
* Indexes image attachments into mra_media_index.
|
||||
*
|
||||
* @package MediaRightsAudit\Internal
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\Internal;
|
||||
|
||||
use MediaRightsAudit\Core\Queue\Scheduler;
|
||||
|
||||
/**
|
||||
* Populates mra_media_index with one row per image attachment.
|
||||
*
|
||||
* Processing order: oldest-first (ASC by attachment ID).
|
||||
* Idempotent: safely re-runnable; existing rows are never overwritten.
|
||||
*/
|
||||
class AttachmentIndexer {
|
||||
|
||||
/**
|
||||
* Action Scheduler hook name for background indexing.
|
||||
*/
|
||||
const AS_HOOK = 'mra_internal_index_batch';
|
||||
|
||||
/**
|
||||
* Indexes one batch of not-yet-indexed image attachments.
|
||||
*
|
||||
* @param int $batch_size Maximum number of attachments to process.
|
||||
*
|
||||
* @return int Number of attachments newly added to the index.
|
||||
*/
|
||||
public static function index_batch( int $batch_size = 50 ): int {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery
|
||||
$rows = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT p.ID, p.guid, p.post_mime_type
|
||||
FROM {$wpdb->posts} p
|
||||
LEFT JOIN {$wpdb->prefix}mra_media_index i ON p.ID = i.attachment_id
|
||||
WHERE p.post_type = 'attachment'
|
||||
AND p.post_mime_type LIKE %s
|
||||
AND p.post_status != 'trash'
|
||||
AND i.attachment_id IS NULL
|
||||
ORDER BY p.ID ASC
|
||||
LIMIT %d",
|
||||
'image/%',
|
||||
$batch_size
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery
|
||||
|
||||
if ( ! $rows ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Prime postmeta cache so get_attached_file() and wp_get_attachment_url() are fast.
|
||||
$ids = array_map( 'intval', array_column( $rows, 'ID' ) );
|
||||
update_meta_cache( 'post', $ids );
|
||||
|
||||
$now = current_time( 'mysql', true );
|
||||
$count = 0;
|
||||
|
||||
foreach ( $rows as $row ) {
|
||||
$attachment_id = intval( $row['ID'] );
|
||||
$guid = strval( $row['guid'] );
|
||||
$mime_type = strval( $row['post_mime_type'] );
|
||||
|
||||
$file_url = wp_get_attachment_url( $attachment_id );
|
||||
$file_url = $file_url ? $file_url : $guid;
|
||||
$file_path = get_attached_file( $attachment_id );
|
||||
$file_size = ( $file_path && file_exists( $file_path ) )
|
||||
? intval( filesize( $file_path ) )
|
||||
: 0;
|
||||
|
||||
$inserted = $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
$wpdb->prefix . 'mra_media_index',
|
||||
array(
|
||||
'attachment_id' => $attachment_id,
|
||||
'file_url' => $file_url,
|
||||
'file_name' => self::extract_filename( $file_url ),
|
||||
'mime_type' => $mime_type,
|
||||
'file_size' => $file_size,
|
||||
'created_at' => $now,
|
||||
),
|
||||
array( '%d', '%s', '%s', '%s', '%d', '%s' )
|
||||
);
|
||||
|
||||
if ( false !== $inserted ) {
|
||||
++$count;
|
||||
}
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the bare filename from a URL.
|
||||
*
|
||||
* Uses PHP's parse_url() so this method is testable without WordPress.
|
||||
*
|
||||
* @param string $url Absolute or relative URL.
|
||||
*
|
||||
* @return string Filename, or the original string if parsing fails.
|
||||
*/
|
||||
public static function extract_filename( string $url ): string {
|
||||
$path = parse_url( $url, PHP_URL_PATH ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url
|
||||
return is_string( $path ) ? basename( $path ) : basename( $url );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of image attachments not yet in the index.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function get_pending_count(): int {
|
||||
global $wpdb;
|
||||
|
||||
$result = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
"SELECT COUNT(p.ID)
|
||||
FROM {$wpdb->posts} p
|
||||
LEFT JOIN {$wpdb->prefix}mra_media_index i ON p.ID = i.attachment_id
|
||||
WHERE p.post_type = 'attachment'
|
||||
AND p.post_mime_type LIKE 'image/%'
|
||||
AND p.post_status != 'trash'
|
||||
AND i.attachment_id IS NULL"
|
||||
);
|
||||
|
||||
return intval( $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of attachments currently in the index.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function get_indexed_count(): int {
|
||||
global $wpdb;
|
||||
|
||||
$result = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
"SELECT COUNT(*) FROM {$wpdb->prefix}mra_media_index"
|
||||
);
|
||||
|
||||
return intval( $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes one scheduled batch and re-queues or hands off to UsageScanner.
|
||||
*
|
||||
* Called by Action Scheduler via the mra_internal_index_batch hook.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function process_scheduled_batch(): void {
|
||||
self::index_batch();
|
||||
|
||||
if ( self::get_pending_count() > 0 ) {
|
||||
Scheduler::schedule_single( self::AS_HOOK );
|
||||
} else {
|
||||
Scheduler::schedule_single( UsageScanner::AS_HOOK );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueues a background indexing job if one is not already pending.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function schedule(): void {
|
||||
if ( ! Scheduler::has_pending( self::AS_HOOK ) ) {
|
||||
Scheduler::schedule_single( self::AS_HOOK );
|
||||
}
|
||||
}
|
||||
}
|
||||
464
includes/Internal/UsageScanner.php
Normal file
464
includes/Internal/UsageScanner.php
Normal file
|
|
@ -0,0 +1,464 @@
|
|||
<?php
|
||||
/**
|
||||
* Scans where each indexed attachment is used across the site.
|
||||
*
|
||||
* @package MediaRightsAudit\Internal
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\Internal;
|
||||
|
||||
use MediaRightsAudit\Core\Queue\Scheduler;
|
||||
|
||||
/**
|
||||
* Populates mra_media_usage with one row per attachment–post reference.
|
||||
*
|
||||
* Three context types are detected:
|
||||
* - featured : the post uses this attachment as its featured image (_thumbnail_id).
|
||||
* - content : the attachment ID appears in post_content (block editor class wp-image-{id}).
|
||||
* - meta : a custom field value contains the attachment filename.
|
||||
*
|
||||
* Scanning is idempotent: existing usage rows are deleted before each attachment's scan.
|
||||
*
|
||||
* Extension hooks:
|
||||
* - mra/internal/scanner/post_types filter to override scanned post types.
|
||||
* - mra/internal/scanner/meta_keys filter to add private meta keys to the meta scan.
|
||||
*/
|
||||
class UsageScanner {
|
||||
|
||||
/**
|
||||
* Action Scheduler hook name for background scanning.
|
||||
*/
|
||||
const AS_HOOK = 'mra_internal_scan_batch';
|
||||
|
||||
/**
|
||||
* Scans one batch of indexed-but-unscanned attachments for usage.
|
||||
*
|
||||
* @param int $batch_size Maximum number of attachments to scan per call.
|
||||
*
|
||||
* @return int Number of attachments scanned.
|
||||
*/
|
||||
public static function scan_batch( int $batch_size = 50 ): int {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery
|
||||
$rows = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT attachment_id, file_url
|
||||
FROM {$wpdb->prefix}mra_media_index
|
||||
WHERE internal_scanned_at IS NULL
|
||||
ORDER BY attachment_id ASC
|
||||
LIMIT %d",
|
||||
$batch_size
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery
|
||||
|
||||
if ( ! $rows ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
foreach ( $rows as $row ) {
|
||||
self::scan_attachment(
|
||||
intval( $row['attachment_id'] ),
|
||||
strval( $row['file_url'] )
|
||||
);
|
||||
}
|
||||
|
||||
return count( $rows );
|
||||
}
|
||||
|
||||
/**
|
||||
* Scans a single attachment for usage and marks it as scanned.
|
||||
*
|
||||
* Deletes existing mra_media_usage rows first (idempotent).
|
||||
*
|
||||
* @param int $attachment_id WordPress attachment ID.
|
||||
* @param string $file_url Canonical URL of the original file.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function scan_attachment( int $attachment_id, string $file_url ): void {
|
||||
global $wpdb;
|
||||
|
||||
$wpdb->delete( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
$wpdb->prefix . 'mra_media_usage',
|
||||
array( 'attachment_id' => $attachment_id ),
|
||||
array( '%d' )
|
||||
);
|
||||
|
||||
self::scan_featured( $attachment_id );
|
||||
self::scan_content( $attachment_id );
|
||||
self::scan_meta( $attachment_id, $file_url );
|
||||
|
||||
$wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
$wpdb->prefix . 'mra_media_index',
|
||||
array( 'internal_scanned_at' => current_time( 'mysql', true ) ),
|
||||
array( 'attachment_id' => $attachment_id ),
|
||||
array( '%s' ),
|
||||
array( '%d' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds posts that use this attachment as a featured image.
|
||||
*
|
||||
* @param int $attachment_id Attachment ID to search for.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function scan_featured( int $attachment_id ): void {
|
||||
global $wpdb;
|
||||
|
||||
$raw_types = apply_filters( 'mra/internal/scanner/post_types', get_post_types( array( 'public' => true ) ) ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
|
||||
$post_types = array();
|
||||
if ( is_array( $raw_types ) ) {
|
||||
foreach ( $raw_types as $type ) {
|
||||
if ( is_string( $type ) ) {
|
||||
$post_types[] = $type;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( empty( $post_types ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$placeholders = implode( ',', array_fill( 0, count( $post_types ), '%s' ) );
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$results = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT pm.post_id, p.post_type
|
||||
FROM {$wpdb->postmeta} pm
|
||||
INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
|
||||
WHERE pm.meta_key = '_thumbnail_id'
|
||||
AND pm.meta_value = %d
|
||||
AND p.post_status NOT IN ('trash','auto-draft')
|
||||
AND p.post_type IN ({$placeholders})",
|
||||
array_merge( array( $attachment_id ), $post_types )
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
|
||||
if ( ! $results ) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ( $results as $row ) {
|
||||
self::insert_usage(
|
||||
$attachment_id,
|
||||
intval( $row['post_id'] ),
|
||||
strval( $row['post_type'] ),
|
||||
'featured'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds posts whose post_content references this attachment.
|
||||
*
|
||||
* Detects the block-editor class `wp-image-{id}` written by Gutenberg.
|
||||
*
|
||||
* @param int $attachment_id Attachment ID to search for.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function scan_content( int $attachment_id ): void {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
$results = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT ID, post_type
|
||||
FROM {$wpdb->posts}
|
||||
WHERE post_content LIKE %s
|
||||
AND post_status NOT IN ('trash','auto-draft')
|
||||
AND post_type NOT IN ('attachment','revision')",
|
||||
'%wp-image-' . $attachment_id . '%'
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
|
||||
if ( ! $results ) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ( $results as $row ) {
|
||||
self::insert_usage(
|
||||
$attachment_id,
|
||||
intval( $row['ID'] ),
|
||||
strval( $row['post_type'] ),
|
||||
'content'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds custom field values that reference this attachment by filename.
|
||||
*
|
||||
* Scans non-private meta keys by default. Supports basic serialized values (ACF, etc.).
|
||||
* The mra/internal/scanner/meta_keys filter can add private (underscore-prefixed) keys.
|
||||
*
|
||||
* @param int $attachment_id Attachment ID.
|
||||
* @param string $file_url Canonical URL, used to extract the filename for matching.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function scan_meta( int $attachment_id, string $file_url ): void {
|
||||
global $wpdb;
|
||||
|
||||
$filename = self::url_basename( $file_url );
|
||||
if ( '' === $filename ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$like = '%' . $wpdb->esc_like( $filename ) . '%';
|
||||
|
||||
// esc_like('_') returns '\' + '_'; appending '%' produces the LIKE pattern '\_%'
|
||||
// which matches any meta_key beginning with a literal underscore.
|
||||
$meta_key_like = $wpdb->esc_like( '_' ) . '%';
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery.slow_db_query_meta_key
|
||||
$results = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT pm.post_id, p.post_type, pm.meta_key, pm.meta_value
|
||||
FROM {$wpdb->postmeta} pm
|
||||
INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
|
||||
WHERE pm.meta_key NOT LIKE %s
|
||||
AND pm.meta_value LIKE %s
|
||||
AND p.post_status NOT IN ('trash','auto-draft')
|
||||
AND p.post_type NOT IN ('attachment','revision')",
|
||||
$meta_key_like,
|
||||
$like
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery.slow_db_query_meta_key
|
||||
|
||||
$raw_extra_keys = apply_filters( 'mra/internal/scanner/meta_keys', array() ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
|
||||
$extra_keys = array();
|
||||
if ( is_array( $raw_extra_keys ) ) {
|
||||
foreach ( $raw_extra_keys as $key ) {
|
||||
if ( is_string( $key ) ) {
|
||||
$extra_keys[] = $key;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( $extra_keys ) {
|
||||
$placeholders = implode( ',', array_fill( 0, count( $extra_keys ), '%s' ) );
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.SlowDBQuery.slow_db_query_meta_key
|
||||
$extra_results = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT pm.post_id, p.post_type, pm.meta_key, pm.meta_value
|
||||
FROM {$wpdb->postmeta} pm
|
||||
INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
|
||||
WHERE pm.meta_key IN ({$placeholders})
|
||||
AND pm.meta_value LIKE %s
|
||||
AND p.post_status NOT IN ('trash','auto-draft')
|
||||
AND p.post_type NOT IN ('attachment','revision')",
|
||||
array_merge( $extra_keys, array( $like ) )
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.SlowDBQuery.slow_db_query_meta_key
|
||||
|
||||
$results = $results
|
||||
? array_merge( $results, (array) $extra_results )
|
||||
: (array) $extra_results;
|
||||
}
|
||||
|
||||
if ( ! $results ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Deduplicate by post_id + meta_key.
|
||||
$seen = array();
|
||||
foreach ( $results as $row ) {
|
||||
$post_id = intval( $row['post_id'] );
|
||||
$meta_key = strval( $row['meta_key'] );
|
||||
$key = $post_id . '|' . $meta_key;
|
||||
|
||||
if ( isset( $seen[ $key ] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Verify match survives unserialisation (handles ACF arrays, etc.).
|
||||
$meta_value = strval( $row['meta_value'] );
|
||||
$values = self::flatten_meta_value( $meta_value );
|
||||
$matched = false;
|
||||
foreach ( $values as $v ) {
|
||||
if ( false !== strpos( $v, $filename ) ) {
|
||||
$matched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ( $matched ) {
|
||||
$seen[ $key ] = true;
|
||||
self::insert_usage(
|
||||
$attachment_id,
|
||||
$post_id,
|
||||
strval( $row['post_type'] ),
|
||||
'meta',
|
||||
$meta_key
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts a single usage record.
|
||||
*
|
||||
* @param int $attachment_id Attachment ID.
|
||||
* @param int $post_id Post that references the attachment.
|
||||
* @param string $post_type Post type.
|
||||
* @param string $context 'featured', 'content', or 'meta'.
|
||||
* @param string|null $meta_key Meta key; only populated when context is 'meta'.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function insert_usage(
|
||||
int $attachment_id,
|
||||
int $post_id,
|
||||
string $post_type,
|
||||
string $context,
|
||||
?string $meta_key = null
|
||||
): void {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery.slow_db_query_meta_key
|
||||
$wpdb->insert(
|
||||
$wpdb->prefix . 'mra_media_usage',
|
||||
array(
|
||||
'attachment_id' => $attachment_id,
|
||||
'post_id' => $post_id,
|
||||
'post_type' => $post_type,
|
||||
'context' => $context,
|
||||
'meta_key' => $meta_key,
|
||||
'created_at' => current_time( 'mysql', true ),
|
||||
),
|
||||
array( '%d', '%d', '%s', '%s', '%s', '%s' )
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery.slow_db_query_meta_key
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Public helpers (also used in tests)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Extracts attachment IDs referenced in post content via the wp-image-{id} class.
|
||||
*
|
||||
* Pure PHP — no WordPress dependency; safe to call in unit tests.
|
||||
*
|
||||
* @param string $content Post content string.
|
||||
*
|
||||
* @return array<int> Unique attachment IDs found.
|
||||
*/
|
||||
public static function extract_attachment_ids_from_content( string $content ): array {
|
||||
if ( ! preg_match_all( '/wp-image-(\d+)/', $content, $matches ) ) {
|
||||
return array();
|
||||
}
|
||||
return array_values( array_unique( array_map( 'intval', $matches[1] ) ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Flattens a meta value (including serialized arrays) to a list of strings.
|
||||
*
|
||||
* Pure PHP — no WordPress dependency; safe to call in unit tests.
|
||||
*
|
||||
* @param mixed $value Raw meta value.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function flatten_meta_value( $value ): array {
|
||||
if ( is_string( $value ) ) {
|
||||
// All PHP serialized strings (except the literal "N;") have ':' as the second character.
|
||||
if ( 'N;' === $value || ( strlen( $value ) >= 2 && ':' === $value[1] ) ) {
|
||||
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize
|
||||
$unserialized = unserialize( $value, array( 'allowed_classes' => false ) );
|
||||
if ( false !== $unserialized && is_array( $unserialized ) ) {
|
||||
return self::flatten_meta_value( $unserialized );
|
||||
}
|
||||
}
|
||||
return array( $value );
|
||||
}
|
||||
|
||||
if ( is_array( $value ) ) {
|
||||
$flat = array();
|
||||
foreach ( $value as $item ) {
|
||||
foreach ( self::flatten_meta_value( $item ) as $s ) {
|
||||
$flat[] = $s;
|
||||
}
|
||||
}
|
||||
return $flat;
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the filename component of a URL.
|
||||
*
|
||||
* Pure PHP — no WordPress dependency; safe to call in unit tests.
|
||||
*
|
||||
* @param string $url Full URL.
|
||||
*
|
||||
* @return string Filename, or empty string on failure.
|
||||
*/
|
||||
public static function url_basename( string $url ): string {
|
||||
$path = parse_url( $url, PHP_URL_PATH ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url
|
||||
return is_string( $path ) ? basename( $path ) : '';
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Scheduling helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns the number of indexed attachments not yet usage-scanned.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function get_pending_count(): int {
|
||||
global $wpdb;
|
||||
|
||||
$result = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
|
||||
"SELECT COUNT(*)
|
||||
FROM {$wpdb->prefix}mra_media_index
|
||||
WHERE internal_scanned_at IS NULL"
|
||||
);
|
||||
|
||||
return intval( $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes one scheduled batch and re-queues if more attachments remain.
|
||||
*
|
||||
* Called by Action Scheduler via the mra_internal_scan_batch hook.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function process_scheduled_batch(): void {
|
||||
self::scan_batch();
|
||||
|
||||
if ( self::get_pending_count() > 0 ) {
|
||||
Scheduler::schedule_single( self::AS_HOOK );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueues a background scan job if one is not already pending.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function schedule(): void {
|
||||
if ( ! Scheduler::has_pending( self::AS_HOOK ) ) {
|
||||
Scheduler::schedule_single( self::AS_HOOK );
|
||||
}
|
||||
}
|
||||
}
|
||||
160
includes/Privacy/DataEraser.php
Normal file
160
includes/Privacy/DataEraser.php
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
<?php
|
||||
/**
|
||||
* GDPR personal data eraser.
|
||||
*
|
||||
* @package MediaRightsAudit\Privacy
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\Privacy;
|
||||
|
||||
/**
|
||||
* Erases Media Audit data for a given user via the WordPress privacy tools.
|
||||
*
|
||||
* Registered via the wp_privacy_personal_data_erasers filter. Removes all rows
|
||||
* from mra_media_index, mra_media_usage, and mra_external_results that belong
|
||||
* to attachments uploaded by the requested user.
|
||||
*
|
||||
* Erasure is a hard delete: once removed, the data cannot be recovered. The
|
||||
* attachment itself (wp_posts row) is not touched — only plugin-specific data.
|
||||
*/
|
||||
class DataEraser {
|
||||
|
||||
/**
|
||||
* Registers this eraser with the WordPress privacy API.
|
||||
*
|
||||
* Hooked to wp_privacy_personal_data_erasers.
|
||||
*
|
||||
* @param array<string, mixed> $erasers Accumulated eraser list.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function register( array $erasers ): array {
|
||||
$erasers['robotstxt-mediaaudit'] = array(
|
||||
'eraser_friendly_name' => __( 'Media Audit', 'robotstxt-mediaaudit' ),
|
||||
'callback' => array( self::class, 'erase' ),
|
||||
);
|
||||
return $erasers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Erases Media Audit data for the user identified by $email_address.
|
||||
*
|
||||
* @param string $email_address User e-mail address.
|
||||
* @param int $page Pagination page (unused; all data erased in one pass).
|
||||
*
|
||||
* @return array{items_removed: int, items_retained: int, messages: array<mixed>, done: bool}
|
||||
*/
|
||||
public static function erase( string $email_address, int $page = 1 ): array { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- required by WP privacy API signature
|
||||
$user = get_user_by( 'email', $email_address );
|
||||
if ( ! $user instanceof \WP_User ) {
|
||||
return self::done_response( 0 );
|
||||
}
|
||||
|
||||
$attachment_ids = self::get_attachment_ids( $user->ID );
|
||||
if ( empty( $attachment_ids ) ) {
|
||||
return self::done_response( 0 );
|
||||
}
|
||||
|
||||
$removed = self::delete_plugin_data( $attachment_ids );
|
||||
|
||||
return self::done_response( $removed );
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Private helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Builds a standard "done" response array.
|
||||
*
|
||||
* @param int $removed Number of records removed.
|
||||
*
|
||||
* @return array{items_removed: int, items_retained: int, messages: array<mixed>, done: bool}
|
||||
*/
|
||||
private static function done_response( int $removed ): array {
|
||||
return array(
|
||||
'items_removed' => $removed,
|
||||
'items_retained' => 0,
|
||||
'messages' => array(),
|
||||
'done' => true,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all indexed attachment IDs for a given user (no pagination).
|
||||
*
|
||||
* @param int $user_id WordPress user ID.
|
||||
*
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private static function get_attachment_ids( int $user_id ): array {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$raw = $wpdb->get_col(
|
||||
$wpdb->prepare(
|
||||
"SELECT p.ID
|
||||
FROM {$wpdb->posts} p
|
||||
INNER JOIN {$wpdb->prefix}mra_media_index mi ON p.ID = mi.attachment_id
|
||||
WHERE p.post_type = 'attachment'
|
||||
AND p.post_author = %d
|
||||
ORDER BY p.ID ASC",
|
||||
$user_id
|
||||
)
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
|
||||
if ( ! is_array( $raw ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return array_map( static fn ( mixed $v ): int => is_numeric( $v ) ? (int) $v : 0, $raw );
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all plugin data rows for the given attachment IDs.
|
||||
*
|
||||
* Removes records from mra_external_results, mra_media_usage, and
|
||||
* mra_media_index. Returns the total number of affected rows.
|
||||
*
|
||||
* @param array<int, int> $ids Attachment IDs to delete.
|
||||
*
|
||||
* @return int Total rows deleted across all three tables.
|
||||
*/
|
||||
private static function delete_plugin_data( array $ids ): int {
|
||||
global $wpdb;
|
||||
|
||||
$placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
$removed = 0;
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
|
||||
$wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"DELETE FROM {$wpdb->prefix}mra_external_results WHERE attachment_id IN ({$placeholders})",
|
||||
...$ids
|
||||
)
|
||||
);
|
||||
$removed += (int) $wpdb->rows_affected;
|
||||
|
||||
$wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"DELETE FROM {$wpdb->prefix}mra_media_usage WHERE attachment_id IN ({$placeholders})",
|
||||
...$ids
|
||||
)
|
||||
);
|
||||
$removed += (int) $wpdb->rows_affected;
|
||||
|
||||
$wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"DELETE FROM {$wpdb->prefix}mra_media_index WHERE attachment_id IN ({$placeholders})",
|
||||
...$ids
|
||||
)
|
||||
);
|
||||
$removed += (int) $wpdb->rows_affected;
|
||||
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
|
||||
return $removed;
|
||||
}
|
||||
}
|
||||
316
includes/Privacy/DataExporter.php
Normal file
316
includes/Privacy/DataExporter.php
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
<?php
|
||||
/**
|
||||
* GDPR personal data exporter.
|
||||
*
|
||||
* @package MediaRightsAudit\Privacy
|
||||
*/
|
||||
|
||||
namespace MediaRightsAudit\Privacy;
|
||||
|
||||
/**
|
||||
* Exports Media Audit data for a given user via the WordPress privacy tools.
|
||||
*
|
||||
* Registered via the wp_privacy_personal_data_exporters filter. Exports rows
|
||||
* from mra_media_index and mra_external_results for all attachments uploaded
|
||||
* by the requested user. Results are paginated at 20 attachments per page.
|
||||
*/
|
||||
class DataExporter {
|
||||
|
||||
/**
|
||||
* Group ID for media index export items.
|
||||
*/
|
||||
const GROUP_INDEX = 'mra-media-index';
|
||||
|
||||
/**
|
||||
* Group ID for external results export items.
|
||||
*/
|
||||
const GROUP_RESULTS = 'mra-external-results';
|
||||
|
||||
/**
|
||||
* Number of attachments processed per export page.
|
||||
*/
|
||||
const PER_PAGE = 20;
|
||||
|
||||
/**
|
||||
* Registers this exporter with the WordPress privacy API.
|
||||
*
|
||||
* Hooked to wp_privacy_personal_data_exporters.
|
||||
*
|
||||
* @param array<string, mixed> $exporters Accumulated exporter list.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function register( array $exporters ): array {
|
||||
$exporters['robotstxt-mediaaudit'] = array(
|
||||
'exporter_friendly_name' => __( 'Media Audit', 'robotstxt-mediaaudit' ),
|
||||
'callback' => array( self::class, 'export' ),
|
||||
);
|
||||
return $exporters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports Media Audit data for the user identified by $email_address.
|
||||
*
|
||||
* @param string $email_address User e-mail address.
|
||||
* @param int $page Current pagination page (1-based).
|
||||
*
|
||||
* @return array{data: array<mixed>, done: bool}
|
||||
*/
|
||||
public static function export( string $email_address, int $page = 1 ): array {
|
||||
$user = get_user_by( 'email', $email_address );
|
||||
if ( ! $user instanceof \WP_User ) {
|
||||
return array(
|
||||
'data' => array(),
|
||||
'done' => true,
|
||||
);
|
||||
}
|
||||
|
||||
$offset = ( $page - 1 ) * self::PER_PAGE;
|
||||
$attachment_ids = self::get_attachment_ids( $user->ID, $offset, self::PER_PAGE );
|
||||
|
||||
if ( empty( $attachment_ids ) ) {
|
||||
return array(
|
||||
'data' => array(),
|
||||
'done' => true,
|
||||
);
|
||||
}
|
||||
|
||||
$data = array();
|
||||
|
||||
foreach ( self::get_index_rows( $attachment_ids ) as $row ) {
|
||||
if ( ! is_array( $row ) ) {
|
||||
continue;
|
||||
}
|
||||
$aid_val = $row['attachment_id'] ?? null;
|
||||
$aid = is_numeric( $aid_val ) ? (int) $aid_val : 0;
|
||||
$data[] = array(
|
||||
'group_id' => self::GROUP_INDEX,
|
||||
'group_label' => __( 'Media Audit – Indexed Files', 'robotstxt-mediaaudit' ),
|
||||
'item_id' => 'mra-index-' . $aid,
|
||||
'data' => self::format_index_row( $row, $aid ),
|
||||
);
|
||||
}
|
||||
|
||||
foreach ( self::get_result_rows( $attachment_ids ) as $row ) {
|
||||
if ( ! is_array( $row ) ) {
|
||||
continue;
|
||||
}
|
||||
$aid_val = $row['attachment_id'] ?? null;
|
||||
$aid = is_numeric( $aid_val ) ? (int) $aid_val : 0;
|
||||
$provider_val = $row['provider'] ?? null;
|
||||
$provider = is_string( $provider_val ) ? $provider_val : '';
|
||||
$data[] = array(
|
||||
'group_id' => self::GROUP_RESULTS,
|
||||
'group_label' => __( 'Media Audit – External Scan Results', 'robotstxt-mediaaudit' ),
|
||||
'item_id' => 'mra-result-' . $aid . '-' . $provider,
|
||||
'data' => self::format_result_row( $row, $aid, $provider ),
|
||||
);
|
||||
}
|
||||
|
||||
$total = self::count_attachments( $user->ID );
|
||||
$done = ( $page * self::PER_PAGE ) >= $total;
|
||||
|
||||
return array(
|
||||
'data' => $data,
|
||||
'done' => $done,
|
||||
);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Private helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns attachment IDs from the plugin index for a given user, paginated.
|
||||
*
|
||||
* @param int $user_id WordPress user ID.
|
||||
* @param int $offset Number of rows to skip.
|
||||
* @param int $limit Maximum number of rows to return.
|
||||
*
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private static function get_attachment_ids( int $user_id, int $offset, int $limit ): array {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$raw = $wpdb->get_col(
|
||||
$wpdb->prepare(
|
||||
"SELECT p.ID
|
||||
FROM {$wpdb->posts} p
|
||||
INNER JOIN {$wpdb->prefix}mra_media_index mi ON p.ID = mi.attachment_id
|
||||
WHERE p.post_type = 'attachment'
|
||||
AND p.post_author = %d
|
||||
ORDER BY p.ID ASC
|
||||
LIMIT %d OFFSET %d",
|
||||
$user_id,
|
||||
$limit,
|
||||
$offset
|
||||
)
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
|
||||
if ( ! is_array( $raw ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return array_map( static fn ( mixed $v ): int => is_numeric( $v ) ? (int) $v : 0, $raw );
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts all indexed attachments for a given user.
|
||||
*
|
||||
* @param int $user_id WordPress user ID.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
private static function count_attachments( int $user_id ): int {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$result = $wpdb->get_var(
|
||||
$wpdb->prepare(
|
||||
"SELECT COUNT(*)
|
||||
FROM {$wpdb->posts} p
|
||||
INNER JOIN {$wpdb->prefix}mra_media_index mi ON p.ID = mi.attachment_id
|
||||
WHERE p.post_type = 'attachment'
|
||||
AND p.post_author = %d",
|
||||
$user_id
|
||||
)
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
|
||||
return is_numeric( $result ) ? (int) $result : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches index rows for the given attachment IDs.
|
||||
*
|
||||
* @param array<int, int> $ids Attachment IDs.
|
||||
*
|
||||
* @return array<mixed>
|
||||
*/
|
||||
private static function get_index_rows( array $ids ): array {
|
||||
global $wpdb;
|
||||
|
||||
$placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
$rows = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT attachment_id, file_name, file_url, mime_type, external_status,
|
||||
internal_scanned_at, external_scanned_at
|
||||
FROM {$wpdb->prefix}mra_media_index
|
||||
WHERE attachment_id IN ({$placeholders})",
|
||||
...$ids
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
|
||||
return is_array( $rows ) ? $rows : array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches external result rows for the given attachment IDs.
|
||||
*
|
||||
* @param array<int, int> $ids Attachment IDs.
|
||||
*
|
||||
* @return array<mixed>
|
||||
*/
|
||||
private static function get_result_rows( array $ids ): array {
|
||||
global $wpdb;
|
||||
|
||||
$placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
$rows = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT attachment_id, provider, match_count, created_at
|
||||
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
|
||||
|
||||
return is_array( $rows ) ? $rows : array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a mra_media_index row into WordPress privacy export data items.
|
||||
*
|
||||
* @param array<mixed, mixed> $row DB row.
|
||||
* @param int $aid Attachment ID.
|
||||
*
|
||||
* @return array<int, array<string, string>>
|
||||
*/
|
||||
private static function format_index_row( array $row, int $aid ): array {
|
||||
$file_name = is_string( $row['file_name'] ?? null ) ? $row['file_name'] : '';
|
||||
$file_url = is_string( $row['file_url'] ?? null ) ? $row['file_url'] : '';
|
||||
$status = is_string( $row['external_status'] ?? null ) ? $row['external_status'] : '';
|
||||
$int_at = is_string( $row['internal_scanned_at'] ?? null ) ? $row['internal_scanned_at'] : '';
|
||||
$ext_at = is_string( $row['external_scanned_at'] ?? null ) ? $row['external_scanned_at'] : '';
|
||||
|
||||
return array(
|
||||
array(
|
||||
'name' => __( 'Attachment ID', 'robotstxt-mediaaudit' ),
|
||||
'value' => (string) $aid,
|
||||
),
|
||||
array(
|
||||
'name' => __( 'Filename', 'robotstxt-mediaaudit' ),
|
||||
'value' => $file_name,
|
||||
),
|
||||
array(
|
||||
'name' => __( 'File URL', 'robotstxt-mediaaudit' ),
|
||||
'value' => $file_url,
|
||||
),
|
||||
array(
|
||||
'name' => __( 'External Scan Status', 'robotstxt-mediaaudit' ),
|
||||
'value' => $status,
|
||||
),
|
||||
array(
|
||||
'name' => __( 'Last Scanned (internal)', 'robotstxt-mediaaudit' ),
|
||||
'value' => $int_at,
|
||||
),
|
||||
array(
|
||||
'name' => __( 'Last Scanned (external)', 'robotstxt-mediaaudit' ),
|
||||
'value' => $ext_at,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a mra_external_results row into WordPress privacy export data items.
|
||||
*
|
||||
* @param array<mixed, mixed> $row DB row.
|
||||
* @param int $aid Attachment ID.
|
||||
* @param string $provider Provider slug.
|
||||
*
|
||||
* @return array<int, array<string, string>>
|
||||
*/
|
||||
private static function format_result_row( array $row, int $aid, string $provider ): array {
|
||||
$mc_val = $row['match_count'] ?? null;
|
||||
$match_count = is_numeric( $mc_val ) ? (int) $mc_val : 0;
|
||||
$created_at = is_string( $row['created_at'] ?? null ) ? $row['created_at'] : '';
|
||||
|
||||
return array(
|
||||
array(
|
||||
'name' => __( 'Attachment ID', 'robotstxt-mediaaudit' ),
|
||||
'value' => (string) $aid,
|
||||
),
|
||||
array(
|
||||
'name' => __( 'Provider', 'robotstxt-mediaaudit' ),
|
||||
'value' => $provider,
|
||||
),
|
||||
array(
|
||||
'name' => __( 'Match Count', 'robotstxt-mediaaudit' ),
|
||||
'value' => (string) $match_count,
|
||||
),
|
||||
array(
|
||||
'name' => __( 'Scanned At', 'robotstxt-mediaaudit' ),
|
||||
'value' => $created_at,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue