Plugin Updates

This commit is contained in:
Tony Volpe
2024-03-19 15:33:31 +00:00
parent ff5b56dc44
commit 3a70a6e4bf
317 changed files with 8178 additions and 2933 deletions

View File

@@ -5,6 +5,11 @@
* @package WP-Background-Processing
*/
// phpcs:disable Generic.Commenting.DocComment.MissingShort
/** @noinspection PhpIllegalPsrClassPathInspection */
/** @noinspection AutoloadingIssuesInspection */
// phpcs:disable Generic.Commenting.DocComment.MissingShort
/**
* Abstract Imagify_WP_Async_Request class.
*
@@ -51,7 +56,7 @@ abstract class Imagify_WP_Async_Request {
protected $data = array();
/**
* Initiate new async request
* Initiate new async request.
*/
public function __construct() {
$this->identifier = $this->prefix . '_' . $this->action;
@@ -61,7 +66,7 @@ abstract class Imagify_WP_Async_Request {
}
/**
* Set data used during the request
* Set data used during the request.
*
* @param array $data Data.
*
@@ -74,9 +79,9 @@ abstract class Imagify_WP_Async_Request {
}
/**
* Dispatch the async request
* Dispatch the async request.
*
* @return array|WP_Error
* @return array|WP_Error|false HTTP Response array, WP_Error on failure, or false if not attempted.
*/
public function dispatch() {
$url = add_query_arg( $this->get_query_args(), $this->get_query_url() );
@@ -86,7 +91,7 @@ abstract class Imagify_WP_Async_Request {
}
/**
* Get query args
* Get query args.
*
* @return array
*/
@@ -109,7 +114,7 @@ abstract class Imagify_WP_Async_Request {
}
/**
* Get query URL
* Get query URL.
*
* @return string
*/
@@ -129,7 +134,7 @@ abstract class Imagify_WP_Async_Request {
}
/**
* Get post args
* Get post args.
*
* @return array
*/
@@ -139,11 +144,11 @@ abstract class Imagify_WP_Async_Request {
}
$args = array(
'timeout' => 0.01,
'timeout' => 5,
'blocking' => false,
'body' => $this->data,
'cookies' => $_COOKIE,
'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
'cookies' => $_COOKIE, // Passing cookies ensures request is performed as initiating user.
'sslverify' => apply_filters( 'https_local_ssl_verify', false ), // Local requests, fine to pass false.
);
/**
@@ -155,27 +160,49 @@ abstract class Imagify_WP_Async_Request {
}
/**
* Maybe handle
* Maybe handle a dispatched request.
*
* Check for correct nonce and pass to handler.
*
* @return void|mixed
*/
public function maybe_handle() {
// Don't lock up other requests while processing
// Don't lock up other requests while processing.
session_write_close();
check_ajax_referer( $this->identifier, 'nonce' );
$this->handle();
wp_die();
return $this->maybe_wp_die();
}
/**
* Handle
* Should the process exit with wp_die?
*
* @param mixed $return What to return if filter says don't die, default is null.
*
* @return void|mixed
* @noinspection ForgottenDebugOutputInspection
*/
protected function maybe_wp_die( $return = null ) {
/**
* Should wp_die be used?
*
* @return bool
*/
if ( apply_filters( $this->identifier . '_wp_die', true ) ) {
wp_die();
}
return $return;
}
/**
* Handle a dispatched request.
*
* Override this method to perform any actions required
* during the async request.
*/
abstract protected function handle();
}

View File

@@ -5,6 +5,11 @@
* @package WP-Background-Processing
*/
// phpcs:disable Generic.Commenting.DocComment.MissingShort
/** @noinspection PhpIllegalPsrClassPathInspection */
/** @noinspection AutoloadingIssuesInspection */
// phpcs:disable Generic.Commenting.DocComment.MissingShort
/**
* Abstract Imagify_WP_Background_Process class.
*
@@ -36,7 +41,7 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
/**
* Cron_hook_identifier
*
* @var mixed
* @var string
* @access protected
*/
protected $cron_hook_identifier;
@@ -44,13 +49,27 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
/**
* Cron_interval_identifier
*
* @var mixed
* @var string
* @access protected
*/
protected $cron_interval_identifier;
/**
* Initiate new background process
* The status set when process is cancelling.
*
* @var int
*/
const STATUS_CANCELLED = 1;
/**
* The status set when process is paused or pausing.
*
* @var int;
*/
const STATUS_PAUSED = 2;
/**
* Initiate new background process.
*/
public function __construct() {
parent::__construct();
@@ -59,16 +78,22 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
$this->cron_interval_identifier = $this->identifier . '_cron_interval';
add_action( $this->cron_hook_identifier, array( $this, 'handle_cron_healthcheck' ) );
// phpcs:ignore WordPress.WP.CronInterval.ChangeDetected
add_filter( 'cron_schedules', array( $this, 'schedule_cron_healthcheck' ) );
}
/**
* Dispatch
* Schedule the cron healthcheck and dispatch an async request to start processing the queue.
*
* @access public
* @return void
* @return array|WP_Error|false HTTP Response array, WP_Error on failure, or false if not attempted.
*/
public function dispatch() {
if ( $this->is_processing() ) {
// Process already running.
return false;
}
// Schedule the cron healthcheck.
$this->schedule_event();
@@ -77,7 +102,9 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
}
/**
* Push to queue
* Push to the queue.
*
* Note, save must be called in order to persist queued items to a batch for processing.
*
* @param mixed $data Data.
*
@@ -90,7 +117,7 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
}
/**
* Save queue
* Save the queued items for future processing.
*
* @return $this
*/
@@ -101,11 +128,14 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
update_site_option( $key, $this->data );
}
// Clean out data so that new data isn't prepended with closed session's data.
$this->data = array();
return $this;
}
/**
* Update queue
* Update a batch's queued items.
*
* @param string $key Key.
* @param array $data Data.
@@ -121,7 +151,7 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
}
/**
* Delete queue
* Delete a batch of queued items.
*
* @param string $key Key.
*
@@ -134,83 +164,209 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
}
/**
* Generate key
* Delete entire job queue.
*/
public function delete_all() {
$batches = $this->get_batches();
foreach ( $batches as $batch ) {
$this->delete( $batch->key );
}
delete_site_option( $this->get_status_key() );
$this->cancelled();
}
/**
* Cancel job on next batch.
*/
public function cancel() {
update_site_option( $this->get_status_key(), self::STATUS_CANCELLED );
// Just in case the job was paused at the time.
$this->dispatch();
}
/**
* Has the process been cancelled?
*
* @return bool
*/
public function is_cancelled() {
$status = get_site_option( $this->get_status_key(), 0 );
return absint( $status ) === self::STATUS_CANCELLED;
}
/**
* Called when background process has been cancelled.
*/
protected function cancelled() {
do_action( $this->identifier . '_cancelled' );
}
/**
* Pause job on next batch.
*/
public function pause() {
update_site_option( $this->get_status_key(), self::STATUS_PAUSED );
}
/**
* Is the job paused?
*
* @return bool
*/
public function is_paused() {
$status = get_site_option( $this->get_status_key(), 0 );
return absint( $status ) === self::STATUS_PAUSED;
}
/**
* Called when background process has been paused.
*/
protected function paused() {
do_action( $this->identifier . '_paused' );
}
/**
* Resume job.
*/
public function resume() {
delete_site_option( $this->get_status_key() );
$this->schedule_event();
$this->dispatch();
$this->resumed();
}
/**
* Called when background process has been resumed.
*/
protected function resumed() {
do_action( $this->identifier . '_resumed' );
}
/**
* Is queued?
*
* @return bool
*/
public function is_queued() {
return ! $this->is_queue_empty();
}
/**
* Is the tool currently active, e.g. starting, working, paused or cleaning up?
*
* @return bool
*/
public function is_active() {
return $this->is_queued() || $this->is_processing() || $this->is_paused() || $this->is_cancelled();
}
/**
* Generate key for a batch.
*
* Generates a unique key based on microtime. Queue items are
* given a unique key so that they can be merged upon save.
*
* @param int $length Length.
* @param int $length Optional max length to trim key to, defaults to 64 characters.
* @param string $key Optional string to append to identifier before hash, defaults to "batch".
*
* @return string
*/
protected function generate_key( $length = 64 ) {
$unique = md5( microtime() . rand() );
$prepend = $this->identifier . '_batch_';
protected function generate_key( $length = 64, $key = 'batch' ) {
$unique = md5( microtime() . wp_rand() );
$prepend = $this->identifier . '_' . $key . '_';
return substr( $prepend . $unique, 0, $length );
}
/**
* Maybe process queue
* Get the status key.
*
* @return string
*/
protected function get_status_key() {
return $this->identifier . '_status';
}
/**
* Maybe process a batch of queued items.
*
* Checks whether data exists within the queue and that
* the process is not already running.
*/
public function maybe_handle() {
// Don't lock up other requests while processing
// Don't lock up other requests while processing.
session_write_close();
if ( $this->is_process_running() ) {
if ( $this->is_processing() ) {
// Background process already running.
wp_die();
return $this->maybe_wp_die();
}
if ( $this->is_cancelled() ) {
$this->clear_scheduled_event();
$this->delete_all();
return $this->maybe_wp_die();
}
if ( $this->is_paused() ) {
$this->clear_scheduled_event();
$this->paused();
return $this->maybe_wp_die();
}
if ( $this->is_queue_empty() ) {
// No data to process.
wp_die();
return $this->maybe_wp_die();
}
check_ajax_referer( $this->identifier, 'nonce' );
$this->handle();
wp_die();
return $this->maybe_wp_die();
}
/**
* Is queue empty
* Is queue empty?
*
* @return bool
* @noinspection IsEmptyFunctionUsageInspection
*/
protected function is_queue_empty() {
global $wpdb;
$table = $wpdb->options;
$column = 'option_name';
if ( is_multisite() ) {
$table = $wpdb->sitemeta;
$column = 'meta_key';
}
$key = $wpdb->esc_like( $this->identifier . '_batch_' ) . '%';
$count = $wpdb->get_var( $wpdb->prepare( "
SELECT COUNT(*)
FROM {$table}
WHERE {$column} LIKE %s
", $key ) );
return ( $count > 0 ) ? false : true;
return empty( $this->get_batch() );
}
/**
* Is process running
* Is process running?
*
* Check whether the current process is already running
* in a background process.
*
* @return bool
*
* @deprecated 1.1.0 Superseded.
* @see is_processing()
* @noinspection PhpUnused
*/
protected function is_process_running() {
return $this->is_processing();
}
/**
* Is the background process currently running?
*
* @return bool
*/
public function is_processing() {
if ( get_site_transient( $this->identifier . '_process_lock' ) ) {
// Process already running.
return true;
@@ -220,7 +376,7 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
}
/**
* Lock process
* Lock process.
*
* Lock the process so that multiple instances can't run simultaneously.
* Override if applicable, but the duration should be greater than that
@@ -236,7 +392,7 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
}
/**
* Unlock process
* Unlock process.
*
* Unlock the process so that other instances can spawn.
*
@@ -249,13 +405,34 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
}
/**
* Get batch
* Get batch.
*
* @return stdClass Return the first batch from the queue
* @return stdClass Return the first batch of queued items.
*/
protected function get_batch() {
return array_reduce(
$this->get_batches( 1 ),
static function ( $carry, $batch ) {
return $batch;
},
array()
);
}
/**
* Get batches.
*
* @param int $limit Number of batches to return, defaults to all.
*
* @return array of stdClass
*/
public function get_batches( $limit = 0 ) {
global $wpdb;
if ( empty( $limit ) || ! is_int( $limit ) ) {
$limit = 0;
}
$table = $wpdb->options;
$column = 'option_name';
$key_column = 'option_id';
@@ -270,30 +447,68 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
$key = $wpdb->esc_like( $this->identifier . '_batch_' ) . '%';
$query = $wpdb->get_row( $wpdb->prepare( "
$sql = '
SELECT *
FROM {$table}
WHERE {$column} LIKE %s
ORDER BY {$key_column} ASC
LIMIT 1
", $key ) );
FROM ' . $table . '
WHERE ' . $column . ' LIKE %s
ORDER BY ' . $key_column . '
';
$batch = new stdClass();
$batch->key = $query->$column;
$batch->data = maybe_unserialize( $query->$value_column );
$args = array( $key );
return $batch;
if ( ! empty( $limit ) ) {
$sql .= ' LIMIT %d';
$args[] = $limit;
}
$items = $wpdb->get_results( $wpdb->prepare( $sql, $args ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$batches = array();
if ( ! empty( $items ) ) {
$batches = array_map(
static function ( $item ) use ( $column, $value_column ) {
$batch = new stdClass();
$batch->key = $item->{$column};
$batch->data = maybe_unserialize( $item->{$value_column} );
return $batch;
},
$items
);
}
return $batches;
}
/**
* Handle
* Handle a dispatched request.
*
* Pass each queue item to the task handler, while remaining
* within server memory and time limit constraints.
*
* @noinspection DisconnectedForeachInstructionInspection
*/
protected function handle() {
$this->lock_process();
/**
* Number of seconds to sleep between batches. Defaults to 0 seconds, minimum 0.
*
* @param int $seconds
*/
$throttle_seconds = max(
0,
apply_filters(
$this->identifier . '_seconds_between_batches',
apply_filters(
$this->prefix . '_seconds_between_batches',
0
)
)
);
do {
$batch = $this->get_batch();
@@ -306,19 +521,25 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
unset( $batch->data[ $key ] );
}
if ( $this->time_exceeded() || $this->memory_exceeded() ) {
// Batch limits reached.
// Keep the batch up to date while processing it.
if ( ! empty( $batch->data ) ) {
$this->update( $batch->key, $batch->data );
}
// Let the server breathe a little.
sleep( $throttle_seconds );
// Batch limits reached, or pause or cancel request.
if ( $this->time_exceeded() || $this->memory_exceeded() || $this->is_paused() || $this->is_cancelled() ) {
break;
}
}
// Update or delete current batch.
if ( ! empty( $batch->data ) ) {
$this->update( $batch->key, $batch->data );
} else {
// Delete current batch if fully processed.
if ( empty( $batch->data ) ) {
$this->delete( $batch->key );
}
} while ( ! $this->time_exceeded() && ! $this->memory_exceeded() && ! $this->is_queue_empty() );
} while ( ! $this->time_exceeded() && ! $this->memory_exceeded() && ! $this->is_queue_empty() && ! $this->is_paused() && ! $this->is_cancelled() );
$this->unlock_process();
@@ -329,11 +550,11 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
$this->complete();
}
wp_die();
return $this->maybe_wp_die();
}
/**
* Memory exceeded
* Memory exceeded?
*
* Ensures the batch process never exceeds 90%
* of the maximum WordPress memory.
@@ -353,7 +574,7 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
}
/**
* Get memory limit
* Get memory limit in bytes.
*
* @return int
*/
@@ -365,7 +586,7 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
$memory_limit = '128M';
}
if ( ! $memory_limit || - 1 === intval( $memory_limit ) ) {
if ( ! $memory_limit || -1 === (int) $memory_limit ) {
// Unlimited, set to 32GB.
$memory_limit = '32000M';
}
@@ -374,7 +595,7 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
}
/**
* Time exceeded.
* Time limit exceeded?
*
* Ensures the batch never exceeds a sensible time limit.
* A timeout limit of 30s is common on shared hosting.
@@ -385,7 +606,10 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
$finish = $this->start_time + apply_filters( $this->identifier . '_default_time_limit', 20 ); // 20 seconds
$return = false;
if ( time() >= $finish ) {
if (
! ( defined( 'WP_CLI' ) && WP_CLI ) &&
time() >= $finish
) {
$return = true;
}
@@ -393,18 +617,29 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
}
/**
* Complete.
* Complete processing.
*
* Override if applicable, but ensure that the below actions are
* performed, or, call parent::complete().
*/
protected function complete() {
// Unschedule the cron healthcheck.
delete_site_option( $this->get_status_key() );
// Remove the cron healthcheck job from the cron schedule.
$this->clear_scheduled_event();
$this->completed();
}
/**
* Schedule cron healthcheck
* Called when background process has completed.
*/
protected function completed() {
do_action( $this->identifier . '_completed' );
}
/**
* Schedule the cron healthcheck job.
*
* @access public
*
@@ -413,29 +648,35 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
* @return mixed
*/
public function schedule_cron_healthcheck( $schedules ) {
$interval = apply_filters( $this->identifier . '_cron_interval', 5 );
$interval = apply_filters( $this->cron_interval_identifier, 5 );
if ( property_exists( $this, 'cron_interval' ) ) {
$interval = apply_filters( $this->identifier . '_cron_interval', $this->cron_interval );
$interval = apply_filters( $this->cron_interval_identifier, $this->cron_interval );
}
// Adds every 5 minutes to the existing schedules.
$schedules[ $this->identifier . '_cron_interval' ] = array(
if ( 1 === $interval ) {
$display = __( 'Every Minute' );
} else {
$display = sprintf( __( 'Every %d Minutes' ), $interval );
}
// Adds an "Every NNN Minute(s)" schedule to the existing cron schedules.
$schedules[ $this->cron_interval_identifier ] = array(
'interval' => MINUTE_IN_SECONDS * $interval,
'display' => sprintf( __( 'Every %d Minutes' ), $interval ),
'display' => $display,
);
return $schedules;
}
/**
* Handle cron healthcheck
* Handle cron healthcheck event.
*
* Restart the background process if not already running
* and data exists in the queue.
*/
public function handle_cron_healthcheck() {
if ( $this->is_process_running() ) {
if ( $this->is_processing() ) {
// Background process already running.
exit;
}
@@ -446,13 +687,11 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
exit;
}
$this->handle();
exit;
$this->dispatch();
}
/**
* Schedule event
* Schedule the cron healthcheck event.
*/
protected function schedule_event() {
if ( ! wp_next_scheduled( $this->cron_hook_identifier ) ) {
@@ -461,7 +700,7 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
}
/**
* Clear scheduled event
* Clear scheduled cron healthcheck event.
*/
protected function clear_scheduled_event() {
$timestamp = wp_next_scheduled( $this->cron_hook_identifier );
@@ -472,24 +711,20 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
}
/**
* Cancel Process
* Cancel the background process.
*
* Stop processing queue items, clear cronjob and delete batch.
* Stop processing queue items, clear cron job and delete batch.
*
* @deprecated 1.1.0 Superseded.
* @see cancel()
* @noinspection PhpUnused
*/
public function cancel_process() {
if ( ! $this->is_queue_empty() ) {
$batch = $this->get_batch();
$this->delete( $batch->key );
wp_clear_scheduled_hook( $this->cron_hook_identifier );
}
$this->cancel();
}
/**
* Task
* Perform task with queued item.
*
* Override this method to perform any actions required on each
* queue item. Return the modified item for further processing
@@ -501,5 +736,4 @@ abstract class Imagify_WP_Background_Process extends Imagify_WP_Async_Request {
* @return mixed
*/
abstract protected function task( $item );
}
}

View File

@@ -0,0 +1,135 @@
<?php
namespace Imagify\EventManagement;
/**
* The event manager manages events using the WordPress plugin API.
*
* @since 3.1
* @author Carl Alexander <contact@carlalexander.ca>
*/
class EventManager {
/**
* Adds a callback to a specific hook of the WordPress plugin API.
*
* @uses add_filter()
*
* @param string $hook_name Name of the hook.
* @param callable $callback Callback function.
* @param int $priority Priority.
* @param int $accepted_args Number of arguments.
*/
public function add_callback( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) {
add_filter( $hook_name, $callback, $priority, $accepted_args );
}
/**
* Add an event subscriber.
*
* The event manager registers all the hooks that the given subscriber
* wants to register with the WordPress Plugin API.
*
* @param SubscriberInterface $subscriber SubscriberInterface implementation.
*/
public function add_subscriber( SubscriberInterface $subscriber ) {
if ( $subscriber instanceof EventManagerAwareSubscriberInterface ) {
$subscriber->set_event_manager( $this );
}
$events = $subscriber->get_subscribed_events();
if ( empty( $events ) ) {
return;
}
foreach ( $subscriber->get_subscribed_events() as $hook_name => $parameters ) {
$this->add_subscriber_callback( $subscriber, $hook_name, $parameters );
}
}
/**
* Checks the WordPress plugin API to see if the given hook has
* the given callback. The priority of the callback will be returned
* or false. If no callback is given will return true or false if
* there's any callbacks registered to the hook.
*
* @uses has_filter()
*
* @param string $hook_name Hook name.
* @param mixed $callback Callback.
*
* @return bool|int
*/
public function has_callback( $hook_name, $callback = false ) {
return has_filter( $hook_name, $callback );
}
/**
* Removes the given callback from the given hook. The WordPress plugin API only
* removes the hook if the callback and priority match a registered hook.
*
* @uses remove_filter()
*
* @param string $hook_name Hook name.
* @param callable $callback Callback.
* @param int $priority Priority.
*
* @return bool
*/
public function remove_callback( $hook_name, $callback, $priority = 10 ) {
return remove_filter( $hook_name, $callback, $priority );
}
/**
* Remove an event subscriber.
*
* The event manager removes all the hooks that the given subscriber
* wants to register with the WordPress Plugin API.
*
* @param SubscriberInterface $subscriber SubscriberInterface implementation.
*/
public function remove_subscriber( SubscriberInterface $subscriber ) {
foreach ( $subscriber->get_subscribed_events() as $hook_name => $parameters ) {
$this->remove_subscriber_callback( $subscriber, $hook_name, $parameters );
}
}
/**
* Adds the given subscriber's callback to a specific hook
* of the WordPress plugin API.
*
* @param SubscriberInterface $subscriber SubscriberInterface implementation.
* @param string $hook_name Hook name.
* @param mixed $parameters Parameters, can be a string, an array or a multidimensional array.
*/
private function add_subscriber_callback( SubscriberInterface $subscriber, $hook_name, $parameters ) {
if ( is_string( $parameters ) ) {
$this->add_callback( $hook_name, [ $subscriber, $parameters ] );
} elseif ( is_array( $parameters ) && count( $parameters ) !== count( $parameters, COUNT_RECURSIVE ) ) {
foreach ( $parameters as $parameter ) {
$this->add_subscriber_callback( $subscriber, $hook_name, $parameter );
}
} elseif ( is_array( $parameters ) && isset( $parameters[0] ) ) {
$this->add_callback( $hook_name, [ $subscriber, $parameters[0] ], isset( $parameters[1] ) ? $parameters[1] : 10, isset( $parameters[2] ) ? $parameters[2] : 1 );
}
}
/**
* Removes the given subscriber's callback to a specific hook
* of the WordPress plugin API.
*
* @param SubscriberInterface $subscriber SubscriberInterface implementation.
* @param string $hook_name Hook name.
* @param mixed $parameters Parameters, can be a string, an array or a multidimensional array.
*/
private function remove_subscriber_callback( SubscriberInterface $subscriber, $hook_name, $parameters ) {
if ( is_string( $parameters ) ) {
$this->remove_callback( $hook_name, [ $subscriber, $parameters ] );
} elseif ( is_array( $parameters ) && count( $parameters ) !== count( $parameters, COUNT_RECURSIVE ) ) {
foreach ( $parameters as $parameter ) {
$this->remove_subscriber_callback( $subscriber, $hook_name, $parameter );
}
} elseif ( is_array( $parameters ) && isset( $parameters[0] ) ) {
$this->remove_callback( $hook_name, [ $subscriber, $parameters[0] ], isset( $parameters[1] ) ? $parameters[1] : 10 );
}
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace Imagify\EventManagement;
interface EventManagerAwareSubscriberInterface extends SubscriberInterface {
/**
* Set the WordPress event manager for the subscriber.
*
* @since 3.1
* @author Remy Perona
*
* @param EventManager $event_manager EventManager instance.
*/
public function set_event_manager( EventManager $event_manager );
}

View File

@@ -0,0 +1,32 @@
<?php
namespace Imagify\EventManagement;
/**
* A Subscriber knows what specific WordPress events it wants to listen to.
*
* When an EventManager adds a Subscriber, it gets all the WordPress events that
* it wants to listen to. It then adds the subscriber as a listener for each of them.
*
* @author Carl Alexander <contact@carlalexander.ca>
*/
interface SubscriberInterface {
/**
* Returns an array of events that this subscriber wants to listen to.
*
* The array key is the event name. The value can be:
*
* * The method name
* * An array with the method name and priority
* * An array with the method name, priority and number of accepted arguments
*
* For instance:
*
* * array('hook_name' => 'method_name')
* * array('hook_name' => array('method_name', $priority))
* * array('hook_name' => array('method_name', $priority, $accepted_args))
* * array('hook_name' => array(array('method_name_1', $priority_1, $accepted_args_1)), array('method_name_2', $priority_2, $accepted_args_2)))
*
* @return array
*/
public static function get_subscribed_events();
}

View File

@@ -27,8 +27,8 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
'imagify_manual_optimize',
'imagify_manual_reoptimize',
'imagify_optimize_missing_sizes',
'imagify_generate_webp_versions',
'imagify_delete_webp_versions',
'imagify_generate_nextgen_versions',
'imagify_delete_nextgen_versions',
'imagify_restore',
// Custom folders optimization.
'imagify_optimize_file',
@@ -194,7 +194,7 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
}
/**
* Generate WebP images if they are missing.
* Generate next-gen images if they are missing.
*
* @since 1.9
*
@@ -202,12 +202,12 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
* @param string $context The context.
* @return bool|WP_Error True if successfully launched. A \WP_Error instance on failure.
*/
protected function generate_webp_versions( $media_id, $context ) {
return imagify_get_optimization_process( $media_id, $context )->generate_webp_versions();
protected function generate_nextgen_versions( $media_id, $context ) {
return imagify_get_optimization_process( $media_id, $context )->generate_nextgen_versions();
}
/**
* Delete WebP images for media that are "already_optimize".
* Delete Next gen images for media that are "already_optimize".
*
* @since 1.9.6
*
@@ -215,7 +215,7 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
* @param string $context The context.
* @return bool|WP_Error True if successfully launched. A \WP_Error instance on failure.
*/
protected function delete_webp_versions( $media_id, $context ) {
protected function delete_nextgen_versions( $media_id, $context ) {
$process = imagify_get_optimization_process( $media_id, $context );
if ( ! $process->is_valid() ) {
@@ -228,15 +228,15 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
return new WP_Error( 'not_already_optimized', __( 'This media does not have the right optimization status.', 'imagify' ) );
}
if ( ! $process->has_webp() ) {
if ( ! $process->has_next_gen() ) {
return true;
}
$data->delete_optimization_data();
$deleted = $process->delete_webp_files();
$deleted = $process->delete_nextgen_files( false, true );
if ( is_wp_error( $deleted ) ) {
return new WP_Error( 'webp_not_deleted', __( 'Previous WebP files could not be deleted.', 'imagify' ) );
return new WP_Error( 'nextgen_not_deleted', __( 'Previous next-gen files could not be deleted.', 'imagify' ) );
}
return true;
@@ -359,11 +359,11 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
}
/**
* Generate WebP images if they are missing.
* Generate next-gen images if they are missing.
*
* @since 1.9
*/
public function imagify_generate_webp_versions_callback() {
public function imagify_generate_nextgen_versions_callback() {
$context = $this->get_context();
$media_id = $this->get_media_id();
@@ -371,13 +371,13 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
imagify_die( __( 'Invalid request', 'imagify' ) );
}
imagify_check_nonce( 'imagify-generate-webp-versions-' . $media_id . '-' . $context );
imagify_check_nonce( 'imagify-generate-nextgen-versions-' . $media_id . '-' . $context );
if ( ! imagify_get_context( $context )->current_user_can( 'manual-optimize', $media_id ) ) {
imagify_die();
}
$result = $this->generate_webp_versions( $media_id, $context );
$result = $this->generate_nextgen_versions( $media_id, $context );
imagify_maybe_redirect( is_wp_error( $result ) ? $result : false );
@@ -392,11 +392,11 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
}
/**
* Generate WebP images if they are missing.
* Generate next-gen images if they are missing.
*
* @since 1.9.6
*/
public function imagify_delete_webp_versions_callback() {
public function imagify_delete_nextgen_versions_callback() {
$context = $this->get_context();
$media_id = $this->get_media_id();
@@ -404,13 +404,13 @@ class Imagify_Admin_Ajax_Post extends Imagify_Admin_Ajax_Post_Deprecated {
imagify_die( __( 'Invalid request', 'imagify' ) );
}
imagify_check_nonce( 'imagify-delete-webp-versions-' . $media_id . '-' . $context );
imagify_check_nonce( 'imagify-delete-nextgen-versions-' . $media_id . '-' . $context );
if ( ! imagify_get_context( $context )->current_user_can( 'manual-restore', $media_id ) ) {
imagify_die();
}
$result = $this->delete_webp_versions( $media_id, $context );
$result = $this->delete_nextgen_versions( $media_id, $context );
imagify_maybe_redirect( is_wp_error( $result ) ? $result : false );

View File

@@ -606,11 +606,11 @@ class Imagify_Files_List_Table extends WP_List_Table {
</li>
<?php
if ( $item->process->get_media()->is_image() ) {
$has_webp = $item->process->has_webp() ? __( 'Yes', 'imagify' ) : __( 'No', 'imagify' );
$has_nextgen = $item->process->has_next_gen() ? __( 'Yes', 'imagify' ) : __( 'No', 'imagify' );
?>
<li class="imagify-data-item">
<span class="data"><?php esc_html_e( 'WebP generated:', 'imagify' ); ?></span>
<strong class="data-value"><?php echo esc_html( $has_webp ); ?></strong>
<span class="data"><?php esc_html_e( 'Next-Gen generated:', 'imagify' ); ?></span>
<strong class="data-value"><?php echo esc_html( $has_nextgen ); ?></strong>
</li>
<?php
}
@@ -700,8 +700,8 @@ class Imagify_Files_List_Table extends WP_List_Table {
$this->optimize_button( $item );
$this->retry_button( $item );
$this->reoptimize_buttons( $item );
$this->generate_webp_versions_button( $item );
$this->delete_webp_versions_button( $item );
$this->generate_nextgen_versions_button( $item );
$this->delete_nextgen_versions_button( $item );
$this->restore_button( $item );
}
@@ -806,14 +806,14 @@ class Imagify_Files_List_Table extends WP_List_Table {
}
/**
* Prints a button to generate WebP versions if they are missing.
* Prints a button to generate Next gen versions if they are missing.
*
* @since 1.7
*
* @param object $item The current item. It must contain at least a $process property.
*/
protected function generate_webp_versions_button( $item ) {
$button = get_imagify_attachment_generate_webp_versions_link( $item->process );
protected function generate_nextgen_versions_button( $item ) {
$button = get_imagify_attachment_generate_nextgen_versions_link( $item->process );
if ( $button ) {
echo $button . '<br/>';
@@ -821,14 +821,14 @@ class Imagify_Files_List_Table extends WP_List_Table {
}
/**
* Prints a button to delete WebP versions when the status is "already_optimized".
* Prints a button to delete next-gen versions when the status is "already_optimized".
*
* @since 1.9.6
*
* @param object $item The current item. It must contain at least a $process property.
*/
protected function delete_webp_versions_button( $item ) {
$button = get_imagify_attachment_delete_webp_versions_link( $item->process );
protected function delete_nextgen_versions_button( $item ) {
$button = get_imagify_attachment_delete_nextgen_versions_link( $item->process );
if ( $button ) {
echo $button . '<br/>';

View File

@@ -27,20 +27,23 @@ class Imagify_Options extends Imagify_Abstract_Options {
* @since 1.7
*/
protected $default_values = [
'api_key' => '',
'optimization_level' => 2,
'lossless' => 0,
'auto_optimize' => 0,
'backup' => 0,
'resize_larger' => 0,
'resize_larger_w' => 0,
'convert_to_webp' => 0,
'api_key' => '',
'optimization_level' => 2,
'lossless' => 0,
'auto_optimize' => 0,
'backup' => 0,
'resize_larger' => 0,
'resize_larger_w' => 0,
'display_nextgen' => 0,
'display_nextgen_method' => 'picture',
'display_webp' => 0,
'display_webp_method' => 'picture',
'cdn_url' => '',
'disallowed-sizes' => [],
'admin_bar_menu' => 0,
'partner_links' => 0,
'cdn_url' => '',
'disallowed-sizes' => [],
'admin_bar_menu' => 0,
'partner_links' => 0,
'convert_to_avif' => 0,
'convert_to_webp' => 0,
];
/**
@@ -54,7 +57,6 @@ class Imagify_Options extends Imagify_Abstract_Options {
'optimization_level' => 2,
'auto_optimize' => 1,
'backup' => 1,
'convert_to_webp' => 1,
'admin_bar_menu' => 1,
'partner_links' => 1,
];
@@ -131,10 +133,12 @@ class Imagify_Options extends Imagify_Abstract_Options {
case 'lossless':
case 'resize_larger':
case 'convert_to_webp':
case 'display_nextgen':
case 'display_webp':
case 'admin_bar_menu':
case 'partner_links':
return 1;
case 'convert_to_avif':
return empty( $value ) ? 0 : 1;
case 'resize_larger_w':
if ( $value <= 0 ) {
@@ -159,6 +163,7 @@ class Imagify_Options extends Imagify_Abstract_Options {
$value = array_map( 'sanitize_text_field', $value );
return array_fill_keys( $value, 1 );
case 'display_nextgen_method':
case 'display_webp_method':
$values = [
'picture' => 1,
@@ -172,7 +177,7 @@ class Imagify_Options extends Imagify_Abstract_Options {
return $reset_values[ $key ];
case 'cdn_url':
$cdn_source = \Imagify\Webp\Picture\Display::get_instance()->get_cdn_source( $value );
$cdn_source = apply_filters( 'imagify_cdn_source_url', $value );
if ( 'option' !== $cdn_source['source'] ) {
/**
@@ -202,11 +207,6 @@ class Imagify_Options extends Imagify_Abstract_Options {
unset( $values['resize_larger'], $values['resize_larger_w'] );
}
// Don't display wepb if conversion is disabled.
if ( empty( $values['convert_to_webp'] ) ) {
unset( $values['convert_to_webp'], $values['display_webp'] );
}
return $values;
}
}