Skip to content

Commit

Permalink
expanded support for multisites, testing out new custom commands
Browse files Browse the repository at this point in the history
  • Loading branch information
miriamgoldman committed Feb 12, 2025
1 parent 6bf1128 commit 7f9f1d6
Show file tree
Hide file tree
Showing 3 changed files with 106 additions and 64 deletions.
95 changes: 71 additions & 24 deletions src/classes/class-fastly-media-regen-admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,52 @@ class FastlyMediaRegenAdmin
public function __construct()
{
add_action('admin_menu', [$this, 'add_admin_page']);
add_action('network_admin_menu', [$this, 'add_network_admin_page']);
add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
add_action('wp_ajax_fastly_media_regen', [$this, 'handle_ajax_request']);
}

/**
* Adds the admin page under Tools.
* Adds the admin page in the correct location.
*/
public function add_admin_page()
{
add_submenu_page(
'tools.php',
if (is_multisite()) {
return; // Only add in the network admin if multisite
}

add_menu_page(
'Fastly Media Regen',
'Fastly Media Regen',
'manage_options',
'fastly-media-regen',
[$this, 'render_admin_page']
[$this, 'render_admin_page'],
'dashicons-images-alt2', // Media-related Dashicon
25
);
}

/**
* Adds the network admin menu for multisite installations.
*/
public function add_network_admin_page()
{
if (!is_multisite()) {
return; // Only add in network admin if multisite
}

if (!current_user_can('manage_network')) {
return; // Restrict to super admins
}

add_menu_page(
'Fastly Media Regen',
'Fastly Media Regen',
'manage_network',
'fastly-media-regen',
[$this, 'render_admin_page'],
'dashicons-images-alt2', // Media-related Dashicon
25
);
}

Expand All @@ -33,7 +63,7 @@ public function add_admin_page()
*/
public function enqueue_scripts($hook)
{
if ($hook !== 'tools_page_fastly-media-regen') {
if ($hook !== 'toplevel_page_fastly-media-regen' && $hook !== 'settings_page_fastly-media-regen') {
return;
}

Expand All @@ -47,7 +77,10 @@ public function enqueue_scripts($hook)

wp_localize_script('fastly-media-regen-js', 'fastlyMediaRegen', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('fastly_media_regen_nonce')
'nonce' => wp_create_nonce('fastly_media_regen_nonce'),
'site_url' => get_site_url(),
'is_multisite' => is_multisite(),
'sites' => is_multisite() ? get_sites(['fields' => 'id,url']) : []
]);
}

Expand All @@ -60,6 +93,18 @@ public function render_admin_page()
<div class="wrap">
<h1>Fastly Media Regeneration</h1>
<p>Click the button below to regenerate all images.</p>
<?php if (is_multisite()) : ?>
<label for="fastly-media-regen-sites">Select Subsites:</label>
<select id="fastly-media-regen-sites" name="selected_sites" multiple style="width:100%;">
<?php foreach (get_sites(['fields' => 'ids']) as $site_id) : ?>
<?php $site_details = get_blog_details($site_id); ?>
<option value="<?php echo esc_attr($site_id); ?>">
<?php echo "(" . $site_id . ") " . esc_html($site_details->blogname . ' (' . $site_details->siteurl . ')'); ?>
</option>
<?php endforeach; ?>
</select>
<br>
<?php endif; ?>
<button id="fastly-media-regen-btn" class="button button-primary">Regenerate Media</button>
<p>&nbsp;</p>
<p><strong>Output:</strong></p>
Expand All @@ -71,28 +116,30 @@ public function render_admin_page()
/**
* Handles AJAX request to run the regeneration.
*/
/**
* Handles AJAX request to run the regeneration.
*/
public function handle_ajax_request()
{
check_ajax_referer('fastly_media_regen_nonce', 'nonce');
public function handle_ajax_request()
{
check_ajax_referer('fastly_media_regen_nonce', 'nonce');

if (!current_user_can('manage_options')) {
wp_send_json_error('Unauthorized', 403);
}
$selected_sites = isset($_POST['selected_sites']) ? array_map('intval', $_POST['selected_sites']) : [];
$output = "";

// Run WP-CLI command via shell_exec (Make sure WP-CLI is available in system path)
$command = 'wp fastlyio media regenerate --allow-root 2>&1';
$output = shell_exec($command);
if (is_multisite() && !empty($selected_sites)) {
foreach ($selected_sites as $site_id) {
$command = 'wp fastlyio media regenerate --blogid=' . $site_id . ' 2>&1';
$output .= "\nRunning on Site ID: $site_id\n" . shell_exec($command);
}
} else {
$command = 'wp fastlyio media regenerate';
$command .= ' 2>&1';
$output = shell_exec($command);
}

if (!$output) {
wp_send_json_error(['message' => 'WP-CLI command failed to execute.']);
} else {
wp_send_json_success(['output' => $output]);
if (!$output) {
wp_send_json_error(['message' => 'WP-CLI command failed to execute.']);
} else {
wp_send_json_success(['output' => $output]);
}
}
}

}

new FastlyMediaRegenAdmin();
72 changes: 33 additions & 39 deletions src/classes/class-fastly-media-regen.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

use WP_CLI;
use WP_CLI_Command;
use WP_CLI\Utils;


if (!class_exists('WP_CLI')) {
return;
Expand All @@ -25,6 +27,8 @@ class FastlyMediaRegen extends WP_CLI_Command
* [--verbose]
* : Show detailed output.
*
* [--<field>=<value>]
* : Allow unlimited number of associative parameters.
* ## EXAMPLES
*
* wp media regenerate
Expand All @@ -33,9 +37,28 @@ class FastlyMediaRegen extends WP_CLI_Command
* @param array $args Positional arguments (attachment IDs or empty).
* @param array $assoc_args Associative arguments.
*/
public function regenerate($args, $assoc_args)
public function regenerate( $args, $assoc_args )
{
$verbose = isset($assoc_args['verbose']);
$site = $assoc_args['blogid'];
$url_flag = '';

if ( $site ) {
if ( is_numeric( $site ) ) {
$blog_id = intval( $site );
$site_url = get_site_url( $blog_id );
} else {
$site_url = esc_url_raw( $site );
}

if ( !empty( $site_url ) ) {
WP_CLI::log( "Regenerating media for site: {$site_url}" );
$url_flag = ' --url=' . escapeshellarg( $site_url );
} else {
WP_CLI::error( "Invalid site parameter: {$site}. Must be either blog ID or site URL." );
return;
}
}


// Get media IDs from args or default to all attachments
$attachment_ids = !empty($args) ? array_map('intval', $args) : $this->get_all_attachment_ids();
Expand All @@ -46,60 +69,32 @@ public function regenerate($args, $assoc_args)
}

$filtered_ids = [];
foreach ($attachment_ids as $attachment_id) {
if ($this->has_image_meta($attachment_id)) {
// Output metadata before regenerating
$this->output_metadata($attachment_id, $verbose);
foreach ( $attachment_ids as $attachment_id ) {
if ( $this->has_image_meta( $attachment_id ) ) {
$filtered_ids[] = $attachment_id;
}
}

if (!empty($filtered_ids)) {
if ( !empty( $filtered_ids ) ) {
// Call the original `wp media regenerate` command only on filtered images
WP_CLI::runcommand('media regenerate ' . implode(' ', $filtered_ids) . ($verbose ? ' --verbose' : ''));
WP_CLI::runcommand( 'media regenerate ' . implode(' ', $filtered_ids) . $url_flag . ($verbose ? ' --verbose' : '' ));
} else {
WP_CLI::warning('No valid images with image_meta found for regeneration.');
WP_CLI::warning( 'No valid images found for regeneration.' );
}
}


/**
* Outputs media metadata.
*
* @param int $attachment_id The attachment ID.
* @param bool $verbose Whether to show detailed output.
*/
private function output_metadata($attachment_id, $verbose)
{
$metadata = wp_get_attachment_metadata($attachment_id);
$mime_type = get_post_mime_type($attachment_id);

if (!$metadata) {
WP_CLI::warning("No metadata found for attachment ID: $attachment_id");
return;
}

WP_CLI::log("Metadata for Attachment ID: $attachment_id");
WP_CLI::log("MIME Type: " . ($mime_type ?: 'Unknown'));

if (isset($metadata['image_meta'])) {
WP_CLI::log("Image metadata found. Proceeding with regeneration.");
} else {
WP_CLI::log("No image meta data is present. The mime type is " . $mime_type . " This is likely not an image, skipping regeneration.");
}

}

/**
* Checks if an attachment has image_meta.
*
* @param int $attachment_id The attachment ID.
* @return bool True if image_meta is present, false otherwise.
*/
private function has_image_meta($attachment_id)
private function has_image_meta( $attachment_id )
{
$metadata = wp_get_attachment_metadata($attachment_id);
return isset($metadata['image_meta']);
return isset( $metadata['image_meta'] );
}

/**
Expand All @@ -118,5 +113,4 @@ private function get_all_attachment_ids()
}
}

// Register the command, overriding `wp media regenerate`
WP_CLI::add_command('fastlyio media', __NAMESPACE__ . '\\FastlyMediaRegen');
WP_CLI::add_command( 'fastlyio media', __NAMESPACE__ . '\\FastlyMediaRegen' );
3 changes: 2 additions & 1 deletion src/js/fastly-media-regen.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ jQuery(document).ready(function ($) {
type: 'POST',
data: {
action: 'fastly_media_regen',
nonce: fastlyMediaRegen.nonce
nonce: fastlyMediaRegen.nonce,
selected_sites: $('#fastly-media-regen-sites').val()
},
success: function (response) {
if (response.success) {
Expand Down

0 comments on commit 7f9f1d6

Please sign in to comment.