Cleaning repo & changes on readME
This commit is contained in:
+23
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation;
|
||||
|
||||
use ImageOptimization\Classes\Basic_Enum;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
final class Async_Operation_Hook extends Basic_Enum {
|
||||
public const OPTIMIZE_SINGLE = 'image-optimization/optimize/single';
|
||||
public const OPTIMIZE_ON_UPLOAD = 'image-optimization/optimize/upload';
|
||||
public const OPTIMIZE_BULK = 'image-optimization/optimize/bulk';
|
||||
public const REOPTIMIZE_SINGLE = 'image-optimization/reoptimize/single';
|
||||
public const REOPTIMIZE_BULK = 'image-optimization/reoptimize/bulk';
|
||||
public const REMOVE_MANY_BACKUPS = 'image-optimization/backup/remove-many';
|
||||
public const RESTORE_SINGLE_IMAGE = 'image-optimization/restore/single';
|
||||
public const RESTORE_MANY_IMAGES = 'image-optimization/restore/restore-many';
|
||||
public const CALCULATE_OPTIMIZATION_STATS = 'image-optimization/optimization-stats/calculate';
|
||||
public const DB_MIGRATION = 'image-optimization/database/migration';
|
||||
public const STUCK_OPERATION_CLEANUP = 'image-optimization/cleanup/stuck-operation';
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation;
|
||||
|
||||
use DateTime;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Async_Operation_Item {
|
||||
private int $id;
|
||||
private string $hook;
|
||||
private string $status;
|
||||
private array $args;
|
||||
private string $queue;
|
||||
private DateTime $date;
|
||||
private array $logs;
|
||||
|
||||
public function get_id(): int {
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function set_id( int $id ): Async_Operation_Item {
|
||||
$this->id = $id;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_hook(): string {
|
||||
return $this->hook;
|
||||
}
|
||||
|
||||
public function set_hook( string $hook ): Async_Operation_Item {
|
||||
$this->hook = $hook;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_status(): string {
|
||||
return $this->status;
|
||||
}
|
||||
|
||||
public function set_status( string $status ): Async_Operation_Item {
|
||||
$this->status = $status;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_args(): array {
|
||||
return $this->args;
|
||||
}
|
||||
|
||||
public function set_args( array $args ): Async_Operation_Item {
|
||||
$this->args = $args;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_date(): DateTime {
|
||||
return $this->date;
|
||||
}
|
||||
|
||||
public function set_date( DateTime $date ): Async_Operation_Item {
|
||||
$this->date = $date;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_queue(): string {
|
||||
return $this->queue;
|
||||
}
|
||||
|
||||
public function set_queue( string $queue ): Async_Operation_Item {
|
||||
$this->queue = $queue;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_logs(): array {
|
||||
return $this->logs;
|
||||
}
|
||||
|
||||
public function set_logs( array $logs ): Async_Operation_Item {
|
||||
$this->logs = $logs;
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation;
|
||||
|
||||
use ImageOptimization\Classes\Basic_Enum;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
final class Async_Operation_Queue extends Basic_Enum {
|
||||
public const OPTIMIZE = 'image-optimization/optimize';
|
||||
public const BACKUP = 'image-optimization/backup';
|
||||
public const RESTORE = 'image-optimization/restore';
|
||||
public const STATS = 'image-optimization/stats';
|
||||
public const MIGRATION = 'image-optimization/migration';
|
||||
public const CLEANUP = 'image-optimization/cleanup';
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation;
|
||||
|
||||
use ActionScheduler;
|
||||
use ImageOptimization\Classes\Async_Operation\{
|
||||
Exceptions\Async_Operation_Exception,
|
||||
Interfaces\Operation_Query_Interface
|
||||
};
|
||||
use ImageOptimization\Classes\Logger;
|
||||
use Throwable;
|
||||
use TypeError;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Async_Operation {
|
||||
public const OPERATION_STATUS_NOT_STARTED = 'not-started';
|
||||
public const OPERATION_STATUS_COMPLETE = 'complete';
|
||||
public const OPERATION_STATUS_PENDING = 'pending';
|
||||
public const OPERATION_STATUS_RUNNING = 'in-progress';
|
||||
public const OPERATION_STATUS_FAILED = 'failed';
|
||||
public const OPERATION_STATUS_CANCELED = 'canceled';
|
||||
|
||||
/**
|
||||
* @throws Async_Operation_Exception
|
||||
*/
|
||||
public static function create( string $hook, array $args, string $queue, int $priority = 10, $unique = false ): int {
|
||||
self::check_library_is_registered();
|
||||
|
||||
if ( ! in_array( $hook, Async_Operation_Hook::get_values(), true ) ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, "Hook $hook is not a part of Async_Operation_Hook values" );
|
||||
|
||||
throw new TypeError( "Hook $hook is not a part of Async_Operation_Hook values" );
|
||||
}
|
||||
|
||||
if ( ! in_array( $queue, Async_Operation_Queue::get_values(), true ) ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, "Queue $queue is not a part of Async_Operation_Queue values" );
|
||||
|
||||
throw new TypeError( "Queue $queue is not a part of Async_Operation_Queue values" );
|
||||
}
|
||||
|
||||
return as_enqueue_async_action(
|
||||
$hook,
|
||||
$args,
|
||||
$queue,
|
||||
$unique,
|
||||
$priority
|
||||
);
|
||||
}
|
||||
|
||||
public static function create_recurring( int $timestamp, int $interval_in_seconds, string $hook, array $args, string $queue, int $priority = 10, $unique = false ): int {
|
||||
self::check_library_is_registered();
|
||||
|
||||
if ( ! in_array( $hook, Async_Operation_Hook::get_values(), true ) ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, "Hook $hook is not a part of Async_Operation_Hook values" );
|
||||
|
||||
throw new TypeError( "Hook $hook is not a part of Async_Operation_Hook values" );
|
||||
}
|
||||
|
||||
if ( ! in_array( $queue, Async_Operation_Queue::get_values(), true ) ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, "Queue $queue is not a part of Async_Operation_Queue values" );
|
||||
|
||||
throw new TypeError( "Queue $queue is not a part of Async_Operation_Queue values" );
|
||||
}
|
||||
|
||||
return as_schedule_recurring_action(
|
||||
$timestamp,
|
||||
$interval_in_seconds,
|
||||
$hook,
|
||||
$args,
|
||||
$queue,
|
||||
$unique,
|
||||
$priority
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Operation_Query_Interface $query
|
||||
*
|
||||
* @return Async_Operation_Item[]|int[]
|
||||
* @throws Async_Operation_Exception
|
||||
*/
|
||||
public static function get( Operation_Query_Interface $query ): array {
|
||||
self::check_library_is_registered();
|
||||
|
||||
$actions = [];
|
||||
|
||||
$store = ActionScheduler::store();
|
||||
$logger = ActionScheduler::logger();
|
||||
|
||||
$action_ids = $store->query_actions( $query->get_query() );
|
||||
|
||||
if ( 'ids' === $query->get_return_type() ) {
|
||||
return $action_ids ?? [];
|
||||
}
|
||||
|
||||
foreach ( $action_ids as $action_id ) {
|
||||
try {
|
||||
$action = $store->fetch_action( $action_id );
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"Unable to fetch an action `$action_id`. Reason: " . $t->getMessage()
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( is_a( $action, 'ActionScheduler_NullAction' ) ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_WARN,
|
||||
'ActionScheduler_NullAction found'
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$item = new Async_Operation_Item();
|
||||
|
||||
$actions[] = $item->set_id( $action_id )
|
||||
->set_hook( $action->get_hook() )
|
||||
->set_status( $store->get_status( $action_id ) )
|
||||
->set_args( $action->get_args() )
|
||||
->set_queue( $action->get_group() )
|
||||
->set_date( $store->get_date( $action_id ) )
|
||||
->set_logs( $logger->get_logs( $action_id ) );
|
||||
}
|
||||
|
||||
return $actions;
|
||||
}
|
||||
|
||||
public static function get_by_id( int $action_id ): ?Async_Operation_Item {
|
||||
self::check_library_is_registered();
|
||||
|
||||
$store = ActionScheduler::store();
|
||||
$logger = ActionScheduler::logger();
|
||||
|
||||
try {
|
||||
$action = $store->fetch_action( $action_id );
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"Unable to fetch an action `$action_id`. Reason: " . $t->getMessage()
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if ( is_a( $action, 'ActionScheduler_NullAction' ) ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_WARN,
|
||||
'ActionScheduler_NullAction found'
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return ( new Async_Operation_Item() )
|
||||
->set_id( $action_id )
|
||||
->set_hook( $action->get_hook() )
|
||||
->set_status( $store->get_status( $action_id ) )
|
||||
->set_args( $action->get_args() )
|
||||
->set_queue( $action->get_group() )
|
||||
->set_date( $store->get_date( $action_id ) )
|
||||
->set_logs( $logger->get_logs( $action_id ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Async_Operation_Exception
|
||||
*/
|
||||
public static function cancel( int $operation_id ): void {
|
||||
self::check_library_is_registered();
|
||||
|
||||
$store = ActionScheduler::store();
|
||||
|
||||
$store->cancel_action( $operation_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Async_Operation_Exception
|
||||
*/
|
||||
public static function remove( array $operation_ids ): void {
|
||||
self::check_library_is_registered();
|
||||
|
||||
$store = ActionScheduler::store();
|
||||
|
||||
foreach ( $operation_ids as $operation_id ) {
|
||||
$store->delete_action( $operation_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Async_Operation_Exception
|
||||
*/
|
||||
private static function check_library_is_registered(): void {
|
||||
if ( ! ActionScheduler::is_initialized() ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
'ActionScheduler is not initialised though its method was called'
|
||||
);
|
||||
|
||||
throw new Async_Operation_Exception();
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Async_Operation_Exception extends Exception {
|
||||
protected $message = 'Async operation library is not loaded';
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation\Interfaces;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
interface Operation_Query_Interface {
|
||||
public function get_query(): array;
|
||||
public function get_return_type(): string;
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation\Queries;
|
||||
|
||||
use ImageOptimization\Classes\Async_Operation\{
|
||||
Async_Operation_Hook,
|
||||
Async_Operation_Queue,
|
||||
Interfaces\Operation_Query_Interface,
|
||||
};
|
||||
use TypeError;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Optimization_Operation_Query implements Operation_Query_Interface {
|
||||
private array $query;
|
||||
|
||||
public function set_hook( string $hook ): self {
|
||||
if ( ! in_array( $hook, Async_Operation_Hook::get_values(), true ) ) {
|
||||
throw new TypeError( "Hook $hook is not a part of Async_Operation_Hook values" );
|
||||
}
|
||||
|
||||
$this->query['hook'] = $hook;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|array $status
|
||||
* @return $this
|
||||
*/
|
||||
public function set_status( $status ): self {
|
||||
$this->query['status'] = $status;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_image_id( int $image_id ): self {
|
||||
if ( empty( $this->query['args'] ) ) {
|
||||
$this->query['args'] = [];
|
||||
}
|
||||
|
||||
$this->query['args']['attachment_id'] = $image_id;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_bulk_operation_id( string $operation_id ): self {
|
||||
if ( empty( $this->query['args'] ) ) {
|
||||
$this->query['args'] = [];
|
||||
}
|
||||
|
||||
$this->query['args']['operation_id'] = $operation_id;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_limit( int $limit ): self {
|
||||
$this->query['per_page'] = $limit;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_return_type(): string {
|
||||
return $this->query['_return_type'];
|
||||
}
|
||||
|
||||
public function return_ids(): self {
|
||||
$this->query['_return_type'] = 'ids';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_query(): array {
|
||||
return $this->query;
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->query = [
|
||||
'group' => Async_Operation_Queue::OPTIMIZE,
|
||||
'per_page' => 10,
|
||||
'orderby' => 'date',
|
||||
'order' => 'DESC',
|
||||
'partial_args_matching' => 'json',
|
||||
'_return_type' => 'object',
|
||||
];
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation\Queries;
|
||||
|
||||
use ImageOptimization\Classes\Async_Operation\Async_Operation_Hook;
|
||||
use ImageOptimization\Classes\Async_Operation\Async_Operation_Queue;
|
||||
use ImageOptimization\Classes\Async_Operation\Interfaces\Operation_Query_Interface;
|
||||
use TypeError;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Operation_Query implements Operation_Query_Interface {
|
||||
private array $query;
|
||||
|
||||
public function set_hook( string $hook ): self {
|
||||
if ( ! in_array( $hook, Async_Operation_Hook::get_values(), true ) ) {
|
||||
throw new TypeError( "Hook $hook is not a part of Async_Operation_Hook values" );
|
||||
}
|
||||
|
||||
$this->query['hook'] = $hook;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_queue( string $queue ): self {
|
||||
if ( ! in_array( $queue, Async_Operation_Queue::get_values(), true ) ) {
|
||||
throw new TypeError( "Queue $queue is not a part of Async_Operation_Queue values" );
|
||||
}
|
||||
|
||||
$this->query['group'] = $queue;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|array $status
|
||||
* @return $this
|
||||
*/
|
||||
public function set_status( $status ): self {
|
||||
$this->query['status'] = $status;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_image_id( int $image_id ): self {
|
||||
$this->query['args']['attachment_id'] = $image_id;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_limit( int $limit ): self {
|
||||
$this->query['per_page'] = $limit;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_return_type(): string {
|
||||
return $this->query['_return_type'];
|
||||
}
|
||||
|
||||
public function return_ids(): self {
|
||||
$this->query['_return_type'] = 'ids';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_query(): array {
|
||||
$clone = $this->query;
|
||||
|
||||
if ( empty( $clone['args'] ) ) {
|
||||
unset( $clone['args'] );
|
||||
}
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->query = [
|
||||
'args' => [],
|
||||
'per_page' => 10,
|
||||
'orderby' => 'date',
|
||||
'order' => 'DESC',
|
||||
'_return_type' => 'object',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
use ReflectionClass;
|
||||
use ReflectionException;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
abstract class Basic_Enum {
|
||||
private static array $entries = [];
|
||||
|
||||
/**
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
public static function get_values(): array {
|
||||
return array_values( self::get_entries() );
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
protected static function get_entries(): array {
|
||||
$caller = get_called_class();
|
||||
|
||||
if ( ! array_key_exists( $caller, self::$entries ) ) {
|
||||
$reflect = new ReflectionClass( $caller );
|
||||
self::$entries[ $caller ] = $reflect->getConstants();
|
||||
}
|
||||
|
||||
return self::$entries[ $caller ];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Client;
|
||||
|
||||
use Exception;
|
||||
use ImageOptimization\Classes\Exceptions\Quota_Exceeded_Error;
|
||||
use ImageOptimization\Modules\Optimization\Classes\Exceptions\Bulk_Token_Expired_Error;
|
||||
use ImageOptimization\Modules\Optimization\Classes\Exceptions\Image_Already_Optimized_Error;
|
||||
use Throwable;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Client_Response {
|
||||
private array $known_errors;
|
||||
/**
|
||||
* @var mixed
|
||||
*/
|
||||
private $response;
|
||||
|
||||
/**
|
||||
* @throws Throwable|Quota_Exceeded_Error|Bulk_Token_Expired_Error|Image_Already_Optimized_Error
|
||||
*/
|
||||
public function handle() {
|
||||
if ( ! is_wp_error( $this->response ) ) {
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
$message = $this->response->get_error_message();
|
||||
|
||||
if ( isset( $this->known_errors[ $message ] ) ) {
|
||||
throw $this->known_errors[ $message ];
|
||||
}
|
||||
|
||||
throw new Exception( $message );
|
||||
}
|
||||
|
||||
public function __construct( $response ) {
|
||||
$this->known_errors = [
|
||||
'user reached limit' => new Quota_Exceeded_Error( esc_html__( 'Plan quota reached', 'image-optimization' ) ),
|
||||
'Bulk token expired' => new Bulk_Token_Expired_Error( esc_html__( 'Bulk token expired', 'image-optimization' ) ),
|
||||
'Image already optimized' => new Image_Already_Optimized_Error( esc_html__( 'Image already optimized', 'image-optimization' ) ),
|
||||
];
|
||||
$this->response = $response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Client;
|
||||
|
||||
use ImageOptimization\Classes\Exceptions\Client_Exception;
|
||||
use ImageOptimization\Classes\File_Utils;
|
||||
use ImageOptimization\Classes\Image\Image;
|
||||
use ImageOptimization\Classes\Logger;
|
||||
use ImageOptimization\Modules\Stats\Classes\Optimization_Stats;
|
||||
use Throwable;
|
||||
use WP_Error;
|
||||
|
||||
use ImageOptimization\Plugin;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Client
|
||||
*/
|
||||
class Client {
|
||||
const BASE_URL = 'https://my.elementor.com/api/v2/image-optimizer/';
|
||||
const BASE_URL_FEEDBACK = 'https://feedback-api.prod.apps.elementor.red/apps/api/v1/';
|
||||
const STATUS_CHECK = 'status/check';
|
||||
const SITE_INFO = 'site/info';
|
||||
const SITE_INFO_TRANSIENT = 'image_optimizer_site_info_transient';
|
||||
|
||||
|
||||
private bool $refreshed = false;
|
||||
|
||||
public static ?Client $instance = null;
|
||||
|
||||
/**
|
||||
* get_instance
|
||||
* @return Client|null
|
||||
*/
|
||||
public static function get_instance(): ?Client {
|
||||
if ( ! self::$instance ) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public static function get_site_info( $endpoint = null ): array {
|
||||
$data = [
|
||||
// Which API version is used.
|
||||
'app_version' => IMAGE_OPTIMIZATION_VERSION,
|
||||
// Which language to return.
|
||||
'site_lang' => get_bloginfo( 'language' ),
|
||||
// site to connect
|
||||
'site_url' => trailingslashit( home_url() ),
|
||||
// current user
|
||||
'local_id' => get_current_user_id(),
|
||||
|
||||
];
|
||||
|
||||
if ( $endpoint !== self::STATUS_CHECK ) {
|
||||
// Media library stats
|
||||
$data['media_data'] = base64_encode( wp_json_encode( self::get_request_stats() ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get site info
|
||||
* @return mixed|WP_Error|null
|
||||
*/
|
||||
public static function get_subscription_info() {
|
||||
$info = get_transient( self::SITE_INFO_TRANSIENT );
|
||||
if ( ! $info ) {
|
||||
try {
|
||||
$info = self::get_instance()->make_request( 'POST', self::SITE_INFO );
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, 'Cannot get site info response from service: ' . $t->getMessage() );
|
||||
return null;
|
||||
}
|
||||
|
||||
set_transient( self::SITE_INFO_TRANSIENT, $info, ( 24 * 60 * 60 ) );
|
||||
}
|
||||
return $info;
|
||||
}
|
||||
|
||||
private static function get_request_stats(): array {
|
||||
$optimization_stats = Optimization_Stats::get_image_stats();
|
||||
$image_sizes = [];
|
||||
|
||||
foreach ( wp_get_registered_image_subsizes() as $image_size_key => $image_size_data ) {
|
||||
$image_sizes[] = [
|
||||
'label' => $image_size_key,
|
||||
'size' => "{$image_size_data['width']}x{$image_size_data['height']}",
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'not_optimized_images' => $optimization_stats['total_image_count'] - $optimization_stats['optimized_image_count'],
|
||||
'optimized_images' => $optimization_stats['optimized_image_count'],
|
||||
'images_sizes' => $image_sizes,
|
||||
];
|
||||
}
|
||||
|
||||
public function make_request( $method, $endpoint, $body = [], array $headers = [], $file = false, $file_name = '' ) {
|
||||
$headers = array_replace_recursive([
|
||||
'x-elementor-image-optimizer' => IMAGE_OPTIMIZATION_VERSION,
|
||||
], $headers);
|
||||
|
||||
$headers = array_replace_recursive(
|
||||
$headers,
|
||||
$this->is_connected() ? $this->generate_authentication_headers( $endpoint ) : []
|
||||
);
|
||||
|
||||
$body = array_replace_recursive( $body, $this->get_site_info( $endpoint ) );
|
||||
|
||||
try {
|
||||
if ( $file ) {
|
||||
$boundary = wp_generate_password( 24, false );
|
||||
$body = $this->get_upload_request_body( $body, $file, $boundary, $file_name );
|
||||
// add content type header
|
||||
$headers['Content-Type'] = 'multipart/form-data; boundary=' . $boundary;
|
||||
}
|
||||
} catch ( Client_Exception $ce ) {
|
||||
return new WP_Error( 500, $ce->getMessage() );
|
||||
}
|
||||
|
||||
$response = $this->request(
|
||||
$method,
|
||||
$endpoint,
|
||||
[
|
||||
'timeout' => 100,
|
||||
'headers' => $headers,
|
||||
'body' => $body,
|
||||
]
|
||||
);
|
||||
|
||||
return ( new Client_Response( $response ) )->handle();
|
||||
}
|
||||
|
||||
public static function get_feedback_base_url() {
|
||||
return apply_filters( 'image_optimizer_feedback_base_url', self::BASE_URL_FEEDBACK );
|
||||
}
|
||||
|
||||
private static function get_remote_url( $endpoint ): string {
|
||||
$base_url = apply_filters( 'image_optimizer_client_get_base_url', self::BASE_URL );
|
||||
|
||||
if ( strpos( $endpoint, 'feedback/' ) !== false ) {
|
||||
return self::get_feedback_base_url() . $endpoint;
|
||||
}
|
||||
|
||||
return $base_url . $endpoint;
|
||||
}
|
||||
|
||||
protected function is_connected(): bool {
|
||||
return Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->is_connected();
|
||||
}
|
||||
|
||||
protected function generate_authentication_headers( $endpoint ): array {
|
||||
|
||||
$connect_instance = Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance;
|
||||
|
||||
if ( ! $connect_instance->get_is_connect_on_fly() ) {
|
||||
$headers = [
|
||||
'data' => base64_encode( // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
|
||||
wp_json_encode( [ 'app' => 'library' ] )
|
||||
),
|
||||
'access_token' => $connect_instance->get_access_token() ?? '',
|
||||
'client_id' => $connect_instance->get_client_id() ?? '',
|
||||
];
|
||||
|
||||
if ( $connect_instance->is_activated() ) {
|
||||
$headers['key'] = $connect_instance->get_activation_state() ?? '';
|
||||
}
|
||||
} else {
|
||||
$headers = $this->add_bearer_token([
|
||||
'x-elementor-apps-connect' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
$headers['endpoint'] = $endpoint;
|
||||
$headers['x-elementor-apps'] = 'image-optimizer';
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
protected function request( $method, $endpoint, $args = [] ) {
|
||||
$args['method'] = $method;
|
||||
|
||||
$response = wp_remote_request(
|
||||
self::get_remote_url( $endpoint ),
|
||||
$args
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
$message = $response->get_error_message();
|
||||
|
||||
return new WP_Error(
|
||||
$response->get_error_code(),
|
||||
is_array( $message ) ? join( ', ', $message ) : $message
|
||||
);
|
||||
}
|
||||
|
||||
$body = wp_remote_retrieve_body( $response );
|
||||
$response_code = (int) wp_remote_retrieve_response_code( $response );
|
||||
|
||||
if ( ! $response_code ) {
|
||||
return new WP_Error( 500, 'No Response' );
|
||||
}
|
||||
|
||||
// Server sent a success message without content.
|
||||
if ( 'null' === $body ) {
|
||||
$body = true;
|
||||
}
|
||||
|
||||
$body = json_decode( $body );
|
||||
|
||||
if ( false === $body ) {
|
||||
return new WP_Error( 422, 'Wrong Server Response' );
|
||||
}
|
||||
|
||||
if ( Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->get_is_connect_on_fly() ) {
|
||||
// If the token is invalid, refresh it and try again once only.
|
||||
if ( ! $this->refreshed && ! empty( $body->message ) && ( false !== strpos( $body->message, 'Invalid Token' ) ) ) {
|
||||
Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->refresh_token();
|
||||
$this->refreshed = true;
|
||||
$args['headers'] = $this->add_bearer_token( $args['headers'] );
|
||||
return $this->request( $method, $endpoint, $args );
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! in_array( $response_code, [ 200, 201 ], true ) ) {
|
||||
// In case $as_array = true.
|
||||
$message = $body->message ?? wp_remote_retrieve_response_message( $response );
|
||||
$message = is_array( $message ) ? join( ', ', $message ) : $message;
|
||||
$code = isset( $body->code ) ? (int) $body->code : $response_code;
|
||||
|
||||
return new WP_Error( $code, $message );
|
||||
}
|
||||
|
||||
return $body;
|
||||
}
|
||||
|
||||
public function add_bearer_token( $headers ) {
|
||||
if ( $this->is_connected() ) {
|
||||
$headers['Authorization'] = 'Bearer ' . Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->get_access_token();
|
||||
}
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* get_upload_request_body
|
||||
*
|
||||
* @param array $body
|
||||
* @param $file
|
||||
* @param string $boundary
|
||||
* @param string $file_name
|
||||
*
|
||||
* @return string
|
||||
* @throws Client_Exception
|
||||
*/
|
||||
private function get_upload_request_body( array $body, $file, string $boundary, string $file_name = '' ): string {
|
||||
$payload = '';
|
||||
// add all body fields as standard POST fields:
|
||||
foreach ( $body as $name => $value ) {
|
||||
$payload .= '--' . $boundary;
|
||||
$payload .= "\r\n";
|
||||
$payload .= 'Content-Disposition: form-data; name="' . esc_attr( $name ) . '"' . "\r\n\r\n";
|
||||
$payload .= $value;
|
||||
$payload .= "\r\n";
|
||||
}
|
||||
|
||||
if ( is_array( $file ) ) {
|
||||
foreach ( $file as $key => $file_data ) {
|
||||
$payload .= $this->get_file_payload( $file_data['name'], $file_data['type'], $file_data['path'], $boundary );
|
||||
}
|
||||
} else {
|
||||
$image_mime = image_type_to_mime_type( exif_imagetype( $file ) );
|
||||
|
||||
if (
|
||||
! in_array( $image_mime, Image::get_supported_mime_types(), true ) &&
|
||||
( 'application/octet-stream' === $image_mime && 'avif' !== File_Utils::get_extension( $file ) )
|
||||
) {
|
||||
throw new Client_Exception( "Unsupported mime type `$image_mime`" );
|
||||
}
|
||||
|
||||
if ( empty( $file_name ) ) {
|
||||
$file_name = basename( $file );
|
||||
}
|
||||
|
||||
$payload .= $this->get_file_payload( $file_name, $image_mime, $file, $boundary );
|
||||
}
|
||||
|
||||
$payload .= '--' . $boundary . '--';
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* get_file_payload
|
||||
* @param string $filename
|
||||
* @param string $file_type
|
||||
* @param string $file_path
|
||||
* @param string $boundary
|
||||
* @return string
|
||||
*/
|
||||
private function get_file_payload( string $filename, string $file_type, string $file_path, string $boundary ): string {
|
||||
$name = $filename ?? basename( $file_path );
|
||||
$mine_type = 'image' === $file_type ? image_type_to_mime_type( exif_imagetype( $file_path ) ) : $file_type;
|
||||
$payload = '';
|
||||
// Upload the file
|
||||
$payload .= '--' . $boundary;
|
||||
$payload .= "\r\n";
|
||||
$payload .= 'Content-Disposition: form-data; name="' . esc_attr( $name ) . '"; filename="' . esc_attr( $name ) . '"' . "\r\n";
|
||||
$payload .= 'Content-Type: ' . $mine_type . "\r\n";
|
||||
$payload .= "\r\n";
|
||||
$payload .= file_get_contents( $file_path );
|
||||
$payload .= "\r\n";
|
||||
|
||||
return $payload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Client_Exception extends Exception {
|
||||
protected $message = 'Unknown client error';
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class File_Operation_Error extends Exception {
|
||||
protected $message = 'File operation error';
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Quota_Exceeded_Error extends Exception {
|
||||
protected $message = 'Quota exceeded';
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\File_System\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class File_System_Operation_Error extends Exception {
|
||||
protected $message = 'File system operation error';
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\File_System;
|
||||
|
||||
use ImageOptimization\Classes\File_System\Exceptions\File_System_Operation_Error;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
require_once ABSPATH . 'wp-admin/includes/file.php';
|
||||
WP_Filesystem();
|
||||
|
||||
/**
|
||||
* A wrapper class under WP_Filesystem that throws clear exceptions in case if something went wrong.
|
||||
*/
|
||||
class File_System {
|
||||
/**
|
||||
* Writes a string to a file.
|
||||
*
|
||||
* @param string $file Remote path to the file where to write the data.
|
||||
* @param string $contents The data to write.
|
||||
* @param int|false $mode The file permissions as octal number, usually 0644.
|
||||
*
|
||||
* @return true
|
||||
*
|
||||
* @throws File_System_Operation_Error
|
||||
*/
|
||||
public static function put_contents( string $file, string $contents, $mode = false ): bool {
|
||||
global $wp_filesystem;
|
||||
|
||||
$result = $wp_filesystem->put_contents( $file, $contents, $mode );
|
||||
|
||||
if ( ! $result ) {
|
||||
throw new File_System_Operation_Error( 'Error while writing ' . $file );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a file or directory.
|
||||
*
|
||||
* @param string $file Path to the file or directory.
|
||||
* @param bool $recursive If set to true, deletes files and folders recursively.
|
||||
* @param string|false $type Type of resource. 'f' for file, 'd' for directory.
|
||||
*
|
||||
* @return true
|
||||
*
|
||||
* @throws File_System_Operation_Error
|
||||
*/
|
||||
public static function delete( string $file, bool $recursive = false, $type = false ): bool {
|
||||
global $wp_filesystem;
|
||||
|
||||
$result = $wp_filesystem->delete( $file, $recursive, $type );
|
||||
|
||||
if ( ! $result ) {
|
||||
throw new File_System_Operation_Error( 'Error while deleting ' . $file );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $source Path to the source file.
|
||||
* @param string $destination Path to the destination file.
|
||||
* @param bool $overwrite Whether to overwrite the destination file if it exists.
|
||||
*
|
||||
* @return true
|
||||
*
|
||||
* @throws File_System_Operation_Error
|
||||
*/
|
||||
public static function move( string $source, string $destination, bool $overwrite = false ): bool {
|
||||
global $wp_filesystem;
|
||||
|
||||
$result = $wp_filesystem->move( $source, $destination, $overwrite );
|
||||
|
||||
if ( ! $result ) {
|
||||
throw new File_System_Operation_Error( "Error while moving {$source} to {$destination}" );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies a file.
|
||||
*
|
||||
* @param string $source Path to the source file.
|
||||
* @param string $destination Path to the destination file.
|
||||
* @param bool $overwrite Whether to overwrite the destination file if it exists.
|
||||
* @param int|false $mode The permissions as octal number, usually 0644 for files, 0755 for dirs.
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @throws File_System_Operation_Error
|
||||
*/
|
||||
public static function copy( string $source, string $destination, bool $overwrite = false, $mode = false ): bool {
|
||||
global $wp_filesystem;
|
||||
|
||||
$result = $wp_filesystem->copy( $source, $destination, $overwrite, $mode );
|
||||
|
||||
if ( ! $result ) {
|
||||
throw new File_System_Operation_Error( "Error while copying {$source} to {$destination}" );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a file or directory exists.
|
||||
*
|
||||
* @param string $path Path to file or directory.
|
||||
*
|
||||
* @return bool Whether $path exists or not.
|
||||
*/
|
||||
public static function exists( string $path ): bool {
|
||||
global $wp_filesystem;
|
||||
|
||||
return $wp_filesystem->exists( $path );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the file size (in bytes).
|
||||
*
|
||||
* @param ?string $path Path to file.
|
||||
*
|
||||
* @return int Size of the file in bytes on success, false on failure.
|
||||
*
|
||||
* @throws File_System_Operation_Error
|
||||
*/
|
||||
public static function size( ?string $path ): int {
|
||||
global $wp_filesystem;
|
||||
|
||||
if ( is_null( $path ) ) {
|
||||
throw new File_System_Operation_Error( 'Null file path provided' );
|
||||
}
|
||||
|
||||
$size = $wp_filesystem->size( $path );
|
||||
|
||||
if ( ! $size ) {
|
||||
throw new File_System_Operation_Error( "Unable to calculate file size for $path" );
|
||||
}
|
||||
|
||||
return $size;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class File_Utils {
|
||||
public static function get_extension( string $path ): string {
|
||||
$locale = new Locale();
|
||||
$locale->set_utf_locale();
|
||||
|
||||
$extension = pathinfo( $path, PATHINFO_EXTENSION );
|
||||
|
||||
$locale->reset_to_original();
|
||||
|
||||
return $extension;
|
||||
}
|
||||
|
||||
public static function get_basename( string $path ): string {
|
||||
$locale = new Locale();
|
||||
$locale->set_utf_locale();
|
||||
|
||||
$basename = pathinfo( $path, PATHINFO_BASENAME );
|
||||
|
||||
$locale->reset_to_original();
|
||||
|
||||
return $basename;
|
||||
}
|
||||
|
||||
public static function replace_extension( string $path, string $new_extension, bool $unique_filename = false ): string {
|
||||
$locale = new Locale();
|
||||
$locale->set_utf_locale();
|
||||
|
||||
$path = pathinfo( $path );
|
||||
$basename = sprintf( '%s.%s', $path['filename'], $new_extension );
|
||||
|
||||
if ( $unique_filename ) {
|
||||
$basename = wp_unique_filename( $path['dirname'], $basename );
|
||||
}
|
||||
|
||||
$locale->reset_to_original();
|
||||
|
||||
return sprintf( '%s/%s', $path['dirname'], $basename );
|
||||
}
|
||||
|
||||
public static function get_unique_path( string $path ): string {
|
||||
$locale = new Locale();
|
||||
$locale->set_utf_locale();
|
||||
|
||||
$path = pathinfo( $path );
|
||||
$basename = sprintf( '%s.%s', $path['filename'], $path['extension'] );
|
||||
|
||||
$locale->reset_to_original();
|
||||
|
||||
return sprintf( '%s/%s', $path['dirname'], wp_unique_filename( $path['dirname'], $basename ) );
|
||||
}
|
||||
|
||||
public static function get_relative_upload_path( string $path ): string {
|
||||
$locale = new Locale();
|
||||
$locale->set_utf_locale();
|
||||
|
||||
$path = _wp_relative_upload_path( $path );
|
||||
|
||||
$locale->reset_to_original();
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
public static function get_url_from_path( string $full_path ): string {
|
||||
$locale = new Locale();
|
||||
$locale->set_utf_locale();
|
||||
|
||||
$upload_info = wp_upload_dir();
|
||||
$url_base = $upload_info['baseurl'];
|
||||
|
||||
$parts = preg_split(
|
||||
'/\/wp-content\/uploads/',
|
||||
$full_path
|
||||
);
|
||||
|
||||
$locale->reset_to_original();
|
||||
|
||||
return $url_base . $parts[1];
|
||||
}
|
||||
|
||||
public static function format_file_size( int $file_size_in_bytes, $decimals = 2 ): string {
|
||||
$sizes = [
|
||||
__( '%s Bytes', 'image-optimization' ),
|
||||
__( '%s Kb', 'image-optimization' ),
|
||||
__( '%s Mb', 'image-optimization' ),
|
||||
__( '%s Gb', 'image-optimization' ),
|
||||
];
|
||||
|
||||
if ( ! $file_size_in_bytes ) {
|
||||
return sprintf( $sizes[0], 0 );
|
||||
}
|
||||
|
||||
$current_scale = floor( log( $file_size_in_bytes ) / log( 1024 ) );
|
||||
$formatted_value = number_format( $file_size_in_bytes / pow( 1024, $current_scale ), $decimals );
|
||||
|
||||
return sprintf( $sizes[ $current_scale ], $formatted_value );
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Backup_Creation_Error extends Exception {
|
||||
protected $message = 'Backup creation error';
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Restoring_Exception extends Exception {
|
||||
protected $message = 'Image cannot be restored';
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Invalid_Image_Exception extends Exception {
|
||||
protected $message = 'Invalid image';
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\File_System\Exceptions\File_System_Operation_Error;
|
||||
use ImageOptimization\Classes\File_System\File_System;
|
||||
use ImageOptimization\Classes\File_Utils;
|
||||
use ImageOptimization\Classes\Image\Exceptions\Image_Backup_Creation_Error;
|
||||
use ImageOptimization\Classes\Logger;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
/**
|
||||
* We're saving backup paths in meta even though the backup path could be dynamically generated.
|
||||
* The next reasons affected this decision:
|
||||
*
|
||||
* 1. Possible path conflicts with other plugins and/or custom user logic. We can't guarantee that the image
|
||||
* we find using the dynamically created path will be the same image we saved.
|
||||
* 2. If a backup doesn't exist, but stored in our meta -- we can be almost sure it's not because of us.
|
||||
* Probably, some other plugin removed it or even user manually did it, but it's not our fault. Makes this logic
|
||||
* easier to debug.
|
||||
* 3. We can change backup file name using `wp_unique_filename()` if needed and easily point a backup path to an
|
||||
* image.
|
||||
*/
|
||||
class Image_Backup {
|
||||
/**
|
||||
* Creates a backup of a file by copying it to a new file with the backup extension.
|
||||
* Also, attaches a newly created backup to image's meta.
|
||||
*
|
||||
* @param int $image_id Attachment id.
|
||||
* @param string $image_size Image size (e.g. 'full', 'thumbnail', etc.).
|
||||
* @param string $image_path Path to an image we plan to back up.
|
||||
*
|
||||
* @return string Backup path if successfully created, false otherwise.
|
||||
*
|
||||
* @throws Image_Backup_Creation_Error
|
||||
*/
|
||||
public static function create( int $image_id, string $image_size, string $image_path ): string {
|
||||
$extension = File_Utils::get_extension( $image_path );
|
||||
$backup_path = File_Utils::replace_extension( $image_path, "backup.$extension" );
|
||||
|
||||
try {
|
||||
File_System::copy( $image_path, $backup_path, true );
|
||||
} catch ( File_System_Operation_Error $e ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"Error while creating a backup for image {$image_id} and size {$image_size}"
|
||||
);
|
||||
|
||||
throw new Image_Backup_Creation_Error(
|
||||
"Error while creating a backup for image {$image_id} and size {$image_size}"
|
||||
);
|
||||
}
|
||||
|
||||
$meta = new Image_Meta( $image_id );
|
||||
|
||||
$meta->set_image_backup_path( $image_size, $backup_path );
|
||||
$meta->save();
|
||||
|
||||
return $backup_path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks for registered backups and remove all files found.
|
||||
* Also, wipes removed files from image meta.
|
||||
*
|
||||
* @param int[] $image_ids Array of attachment ids.
|
||||
* @return void
|
||||
*/
|
||||
public static function remove_many( array $image_ids ): void {
|
||||
foreach ( $image_ids as $image_id ) {
|
||||
self::remove( $image_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes one or all backups for a specific image.
|
||||
* Also, wipes removed files from image meta.
|
||||
*
|
||||
* @param int $image_id Attachment id.
|
||||
* @param string|null $image_size Image size (e.g. 'full', 'thumbnail', etc.). All backups will be removed if no size provided.
|
||||
*
|
||||
* @return bool Returns true if backups were removed successfully, false otherwise.
|
||||
*/
|
||||
public static function remove( int $image_id, ?string $image_size = null ): bool {
|
||||
$meta = new Image_Meta( $image_id );
|
||||
$backups = $meta->get_image_backup_paths();
|
||||
|
||||
if ( empty( $backups ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( $image_size ) {
|
||||
if ( ! key_exists( $image_size, $backups ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
File_System::delete( $backups[ $image_size ], false, 'f' );
|
||||
} catch ( File_System_Operation_Error $e ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"Error while removing a backup for image {$image_id} and size {$image_size}"
|
||||
);
|
||||
}
|
||||
|
||||
$meta->remove_image_backup_path( $image_size );
|
||||
$meta->save();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ( $backups as $image_size => $backup_path ) {
|
||||
try {
|
||||
File_System::delete( $backup_path, false, 'f' );
|
||||
} catch ( File_System_Operation_Error $e ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, "Error while removing backups {$image_id}" );
|
||||
}
|
||||
|
||||
$meta->remove_image_backup_path( $image_size );
|
||||
}
|
||||
|
||||
$meta->save();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\Basic_Enum;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
final class Image_Conversion_Option extends Basic_Enum {
|
||||
public const ORIGINAL = 'original';
|
||||
public const WEBP = 'webp';
|
||||
public const AVIF = 'avif';
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Modules\Settings\Classes\Settings;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Conversion {
|
||||
protected ?string $convert_to_format;
|
||||
protected array $options;
|
||||
|
||||
public function is_enabled(): bool {
|
||||
return Image_Conversion_Option::ORIGINAL !== $this->convert_to_format;
|
||||
}
|
||||
|
||||
public function get_current_conversion_option(): string {
|
||||
return $this->convert_to_format;
|
||||
}
|
||||
|
||||
public function get_current_file_extension(): ?string {
|
||||
if ( ! $this->is_enabled() ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->options[ $this->convert_to_format ]['extension'];
|
||||
}
|
||||
|
||||
public function get_current_mime_type(): ?string {
|
||||
if ( ! $this->is_enabled() ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->options[ $this->convert_to_format ]['mime_type'];
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->convert_to_format = Settings::get( Settings::CONVERT_TO_FORMAT_OPTION_NAME );
|
||||
|
||||
$this->options = [
|
||||
Image_Conversion_Option::WEBP => [
|
||||
'extension' => 'webp',
|
||||
'mime_type' => 'image/webp',
|
||||
],
|
||||
Image_Conversion_Option::AVIF => [
|
||||
'extension' => 'avif',
|
||||
'mime_type' => 'image/avif',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use WP_Query;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_DB_Update {
|
||||
public static function update_posts_table_urls( string $old_url, string $new_url ) {
|
||||
$query = new WP_Query( [
|
||||
'post_type' => 'any',
|
||||
'post_status' => 'any',
|
||||
's' => $old_url,
|
||||
'search_columns' => [ 'post_content' ],
|
||||
] );
|
||||
|
||||
if ( ! $query->post_count ) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ( $query->posts as $post ) {
|
||||
$new_content = str_replace( $old_url, $new_url, $post->post_content );
|
||||
|
||||
wp_update_post([
|
||||
'ID' => $post->ID,
|
||||
'post_content' => $new_content,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\Logger;
|
||||
|
||||
use Imagick;
|
||||
use stdClass;
|
||||
use Throwable;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Dimensions {
|
||||
/**
|
||||
* @param string $file_path
|
||||
*
|
||||
* @return stdClass{width: int, height: int}
|
||||
*/
|
||||
public static function get_by_path( string $file_path ): stdClass {
|
||||
$dimensions = wp_getimagesize( $file_path );
|
||||
$output = new stdClass();
|
||||
|
||||
$output->width = 0;
|
||||
$output->height = 0;
|
||||
|
||||
if ( $dimensions ) {
|
||||
$output->width = $dimensions[0];
|
||||
$output->height = $dimensions[1];
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
if ( class_exists( 'Imagick' ) ) {
|
||||
try {
|
||||
$im = new Imagick( $file_path );
|
||||
$image_geometry = $im->getImageGeometry();
|
||||
$im->clear();
|
||||
|
||||
$output->width = $image_geometry['width'];
|
||||
$output->height = $image_geometry['height'];
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
'AVIF image dimensions calculation error: ' . $t->getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Meta {
|
||||
public const IMAGE_OPTIMIZER_METADATA_KEY = 'image_optimizer_metadata';
|
||||
private const INITIAL_META_VALUE = [
|
||||
'status' => Image_Status::NOT_OPTIMIZED,
|
||||
'error_type' => null,
|
||||
'compression_level' => null,
|
||||
'retry_count' => null,
|
||||
'sizes_optimized' => [],
|
||||
'backups' => [],
|
||||
'original_data' => [
|
||||
'sizes' => [],
|
||||
],
|
||||
];
|
||||
|
||||
private int $image_id;
|
||||
private array $image_meta;
|
||||
|
||||
public function get_status(): string {
|
||||
return $this->image_meta['status'];
|
||||
}
|
||||
|
||||
public function set_status( string $status ): Image_Meta {
|
||||
$this->image_meta['status'] = $status;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_error_type(): ?string {
|
||||
return $this->image_meta['error_type'];
|
||||
}
|
||||
|
||||
public function set_error_type( ?string $type ): Image_Meta {
|
||||
$this->image_meta['error_type'] = $type;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_compression_level(): ?string {
|
||||
return $this->image_meta['compression_level'];
|
||||
}
|
||||
|
||||
public function set_compression_level( string $compression_level ): Image_Meta {
|
||||
$this->image_meta['compression_level'] = $compression_level;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_retry_count(): ?int {
|
||||
return $this->image_meta['retry_count'];
|
||||
}
|
||||
|
||||
public function set_retry_count( ?int $retry_count ): Image_Meta {
|
||||
$this->image_meta['retry_count'] = $retry_count;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_optimized_sizes(): array {
|
||||
return $this->image_meta['sizes_optimized'];
|
||||
}
|
||||
|
||||
public function add_optimized_size( string $optimized_size ): Image_Meta {
|
||||
if ( ! in_array( $optimized_size, $this->image_meta['sizes_optimized'], true ) ) {
|
||||
$this->image_meta['sizes_optimized'][] = $optimized_size;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function clear_optimized_sizes(): Image_Meta {
|
||||
$this->image_meta['sizes_optimized'] = [];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_optimized_size( array $optimized_size ): Image_Meta {
|
||||
$this->image_meta['sizes_optimized'] = $optimized_size;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function clear_backups(): Image_Meta {
|
||||
$this->image_meta['backups'] = [];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_image_backup_paths(): array {
|
||||
return $this->image_meta['backups'];
|
||||
}
|
||||
|
||||
public function get_image_backup_path( string $image_size ): ?string {
|
||||
return $this->image_meta['backups'][ $image_size ] ?? null;
|
||||
}
|
||||
|
||||
public function set_image_backup_path( string $image_size, string $backup_path ): Image_Meta {
|
||||
$this->image_meta['backups'][ $image_size ] = $backup_path;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function remove_image_backup_path( string $image_size ): Image_Meta {
|
||||
unset( $this->image_meta['backups'][ $image_size ] );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_original_file_size( string $image_size ): ?int {
|
||||
if ( ! isset( $this->image_meta['original_data']['sizes'][ $image_size ]['filesize'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['original_data']['sizes'][ $image_size ]['filesize'];
|
||||
}
|
||||
|
||||
public function get_original_mime_type( string $image_size ): ?string {
|
||||
if ( ! isset( $this->image_meta['original_data']['sizes'][ $image_size ] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['original_data']['sizes'][ $image_size ]['mime-type'];
|
||||
}
|
||||
|
||||
public function get_original_width( string $image_size ): ?string {
|
||||
if ( ! isset( $this->image_meta['original_data']['sizes'][ $image_size ] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['original_data']['sizes'][ $image_size ]['width'];
|
||||
}
|
||||
|
||||
public function get_original_height( string $image_size ): ?string {
|
||||
if ( ! isset( $this->image_meta['original_data']['sizes'][ $image_size ] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['original_data']['sizes'][ $image_size ]['height'];
|
||||
}
|
||||
|
||||
public function add_original_data( string $size, array $data ): Image_Meta {
|
||||
$this->image_meta['original_data']['sizes'][ $size ] = $data;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function clear_original_data(): Image_Meta {
|
||||
$this->image_meta['original_data'] = [ 'sizes' => [] ];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function delete(): bool {
|
||||
return delete_post_meta( $this->image_id, self::IMAGE_OPTIMIZER_METADATA_KEY );
|
||||
}
|
||||
|
||||
public function save(): Image_Meta {
|
||||
update_post_meta( $this->image_id, self::IMAGE_OPTIMIZER_METADATA_KEY, $this->image_meta );
|
||||
|
||||
$this->query_meta();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
private function query_meta(): void {
|
||||
$meta = get_post_meta( $this->image_id, self::IMAGE_OPTIMIZER_METADATA_KEY, true );
|
||||
$this->image_meta = $meta ? array_replace_recursive( self::INITIAL_META_VALUE, $meta ) : self::INITIAL_META_VALUE;
|
||||
}
|
||||
|
||||
public function __construct( int $image_id ) {
|
||||
$this->image_id = $image_id;
|
||||
|
||||
$this->query_meta();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\Basic_Enum;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
final class Image_Optimization_Error_Type extends Basic_Enum {
|
||||
public const QUOTA_EXCEEDED = 'quota-exceeded';
|
||||
public const FILE_ALREADY_EXISTS = 'file-already-exists';
|
||||
public const PLUGIN_DEACTIVATION = 'plugin-deactivation';
|
||||
public const GENERIC = 'generic';
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use WP_Query;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Query_Builder {
|
||||
private array $query;
|
||||
|
||||
public function return_images_only_with_backups(): self {
|
||||
$this->query['meta_query'][] = [
|
||||
'compare' => 'NOT LIKE',
|
||||
'value' => '"backups";a:0', // Serialized empty array of backups
|
||||
'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY,
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function return_not_optimized_images(): self {
|
||||
$this->query['meta_query'][] = [
|
||||
'relation' => 'OR',
|
||||
[
|
||||
'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY,
|
||||
'compare' => 'NOT EXISTS',
|
||||
],
|
||||
[
|
||||
'compare' => 'LIKE',
|
||||
'value' => '-failed";',
|
||||
'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY,
|
||||
],
|
||||
[
|
||||
'compare' => 'LIKE',
|
||||
'value' => ':"not-optimized";',
|
||||
'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY,
|
||||
],
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function return_optimization_in_progress_images(): self {
|
||||
$this->query['meta_query'][] = [
|
||||
'relation' => 'AND',
|
||||
[
|
||||
'key' => '_wp_attachment_metadata',
|
||||
'compare' => 'EXISTS',
|
||||
],
|
||||
[
|
||||
'relation' => 'OR',
|
||||
[
|
||||
'compare' => 'LIKE',
|
||||
'value' => 'optimization-in-progress";',
|
||||
'key' => 'image_optimizer_metadata',
|
||||
],
|
||||
[
|
||||
'compare' => 'LIKE',
|
||||
'value' => 'reoptimizing-in-progress";',
|
||||
'key' => 'image_optimizer_metadata',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function return_optimized_images(): self {
|
||||
$this->query['meta_query'][] = [
|
||||
'compare' => 'LIKE',
|
||||
'value' => '"status";s:9:"optimized"',
|
||||
'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY,
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function return_images_with_non_empty_meta(): self {
|
||||
$this->query['meta_query'][] = [
|
||||
'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY,
|
||||
'compare' => 'EXISTS',
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_paging_size( int $paging_size ): self {
|
||||
$this->query['posts_per_page'] = $paging_size;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_current_page( int $current_page ): self {
|
||||
$this->query['paged'] = $current_page;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_image_ids( array $image_ids ): self {
|
||||
// Passing an empty array to post__in will return the last posts instead of an empty result.
|
||||
$this->query['post__in'] = count( $image_ids ) ? $image_ids : [ 0 ];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_mime_types( array $mime_types ): self {
|
||||
$this->query['post_mime_type'] = $mime_types;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function execute(): WP_Query {
|
||||
return new WP_Query( $this->query );
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$basic_query = [
|
||||
'post_type' => 'attachment',
|
||||
'post_mime_type' => Image::get_supported_mime_types(),
|
||||
'post_status' => 'any',
|
||||
'fields' => 'ids',
|
||||
'posts_per_page' => -1,
|
||||
'meta_query' => [
|
||||
'relation' => 'AND',
|
||||
[
|
||||
'key' => '_wp_attachment_metadata', // Images without this field considered invalid
|
||||
'compare' => 'EXISTS',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$this->query = $basic_query;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\File_System\{
|
||||
Exceptions\File_System_Operation_Error,
|
||||
File_System,
|
||||
};
|
||||
use ImageOptimization\Classes\File_Utils;
|
||||
use ImageOptimization\Classes\Image\Exceptions\{
|
||||
Image_Restoring_Exception,
|
||||
Invalid_Image_Exception,
|
||||
};
|
||||
use ImageOptimization\Classes\Logger;
|
||||
use Throwable;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Restore {
|
||||
public static function restore_many( array $image_ids, bool $keep_image_meta = false ): void {
|
||||
foreach ( $image_ids as $image_id ) {
|
||||
try {
|
||||
self::restore( $image_id, $keep_image_meta );
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, 'Bulk images restoring error: ' . $t->getMessage() );
|
||||
|
||||
( new Image_Meta( $image_id ) )
|
||||
->set_status( Image_Status::RESTORING_FAILED )
|
||||
->save();
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Invalid_Image_Exception|Image_Restoring_Exception|File_System_Operation_Error
|
||||
*/
|
||||
public static function restore( int $image_id, bool $keep_image_meta = false ): void {
|
||||
$image = new Image( $image_id );
|
||||
|
||||
if ( ! $image->can_be_restored() ) {
|
||||
throw new Image_Restoring_Exception( "Image $image_id cannot be restored" );
|
||||
}
|
||||
|
||||
$meta = new Image_Meta( $image_id );
|
||||
$wp_meta = new WP_Image_Meta( $image_id );
|
||||
|
||||
foreach ( $meta->get_optimized_sizes() as $image_size ) {
|
||||
$backup_path = $meta->get_image_backup_path( $image_size );
|
||||
$current_path = $image->get_file_path( $image_size );
|
||||
|
||||
if ( $backup_path && $current_path ) {
|
||||
$original_path = self::get_path_from_backup_path( $backup_path );
|
||||
|
||||
if ( $original_path === $backup_path ) {
|
||||
File_System::delete( $current_path, false, 'f' );
|
||||
|
||||
self::update_posts( $current_path, $original_path );
|
||||
} else {
|
||||
File_System::move( $backup_path, $original_path, $original_path === $current_path );
|
||||
|
||||
if ( $original_path !== $current_path ) {
|
||||
File_System::delete( $current_path, false, 'f' );
|
||||
|
||||
self::update_posts( $current_path, $original_path );
|
||||
}
|
||||
}
|
||||
|
||||
$file_size = $meta->get_original_file_size( $image_size ) ?? File_System::size( $original_path );
|
||||
|
||||
$wp_meta
|
||||
->set_file_path( $image_size, $original_path )
|
||||
->set_mime_type( $image_size, $meta->get_original_mime_type( $image_size ) )
|
||||
->set_width( $image_size, $meta->get_original_width( $image_size ) )
|
||||
->set_height( $image_size, $meta->get_original_height( $image_size ) )
|
||||
->set_file_size( $image_size, $file_size );
|
||||
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
self::update_image_post(
|
||||
$image,
|
||||
$original_path,
|
||||
$meta->get_original_mime_type( Image::SIZE_FULL )
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$wp_meta->save();
|
||||
|
||||
if ( $keep_image_meta ) {
|
||||
$meta
|
||||
->clear_optimized_sizes()
|
||||
->clear_backups()
|
||||
->clear_original_data()
|
||||
->save();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$meta->delete();
|
||||
}
|
||||
|
||||
private static function get_path_from_backup_path( string $backup_path ): string {
|
||||
$extension = File_Utils::get_extension( $backup_path );
|
||||
return str_replace( ".backup.$extension", ".$extension", $backup_path );
|
||||
}
|
||||
|
||||
private static function update_image_post( Image $image, string $image_path, string $mime_type ): void {
|
||||
$post_update_query = [
|
||||
'post_modified' => current_time( 'mysql' ),
|
||||
'post_modified_gmt' => current_time( 'mysql', true ),
|
||||
'post_mime_type' => $mime_type,
|
||||
'guid' => File_Utils::get_url_from_path( $image_path ),
|
||||
];
|
||||
|
||||
$image->update_attachment( $post_update_query );
|
||||
|
||||
update_attached_file( $image->get_id(), $image_path );
|
||||
}
|
||||
|
||||
/**
|
||||
* If we change an image extension, we should walk through the wp_posts table and update all the
|
||||
* hardcoded image links to prevent 404s.
|
||||
*
|
||||
* @param string $old_path Previous image path
|
||||
* @param string $new_path Current image path
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function update_posts( string $old_path, string $new_path ) {
|
||||
Image_DB_Update::update_posts_table_urls(
|
||||
File_Utils::get_url_from_path( $old_path ),
|
||||
File_Utils::get_url_from_path( $new_path )
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\Basic_Enum;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
final class Image_Status extends Basic_Enum {
|
||||
public const NOT_OPTIMIZED = 'not-optimized';
|
||||
public const OPTIMIZED = 'optimized';
|
||||
public const OPTIMIZATION_IN_PROGRESS = 'optimization-in-progress';
|
||||
public const OPTIMIZATION_FAILED = 'optimization-failed';
|
||||
public const RESTORING_IN_PROGRESS = 'restoring-in-progress';
|
||||
public const RESTORING_FAILED = 'restoring-failed';
|
||||
public const REOPTIMIZING_IN_PROGRESS = 'reoptimizing-in-progress';
|
||||
public const REOPTIMIZING_FAILED = 'reoptimizing-failed';
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\Image\Exceptions\Invalid_Image_Exception;
|
||||
use WP_Post;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image {
|
||||
public const SIZE_FULL = 'full';
|
||||
private const SUPPORTED_MIME_TYPES = [ 'image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/avif' ];
|
||||
|
||||
// Used for error messages
|
||||
private const SUPPORTED_FORMATS = [ 'jpeg', 'png', 'webp', 'gif', 'avif' ];
|
||||
private const MIME_TYPES_CANNOT_BE_OPTIMIZED = [ 'image/avif' ];
|
||||
private const FORMATS_CANNOT_BE_OPTIMIZED = [ 'avif' ];
|
||||
|
||||
protected int $image_id;
|
||||
protected $attachment_object;
|
||||
|
||||
/**
|
||||
* Returns attachment post id.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_id(): int {
|
||||
return $this->image_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns file URL for a specific image size.
|
||||
*
|
||||
* @param string $image_size Image size (e. g. 'full', 'thumbnail', etc)
|
||||
* @return string|null
|
||||
*/
|
||||
public function get_url( string $image_size ): ?string {
|
||||
$image_data = wp_get_attachment_image_src( $this->image_id, $image_size );
|
||||
|
||||
if ( empty( $image_data ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $image_data[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns absolute file path for a specific image size.
|
||||
*
|
||||
* @param string $image_size Image size (e. g. 'full', 'thumbnail', etc)
|
||||
* @return string|null
|
||||
*/
|
||||
public function get_file_path( string $image_size ): ?string {
|
||||
if ( 'full' === $image_size ) {
|
||||
$path = get_attached_file( $this->image_id );
|
||||
return $path ?? null;
|
||||
}
|
||||
|
||||
$path_data = image_get_intermediate_size( $this->image_id, $image_size );
|
||||
|
||||
if ( empty( $path_data ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return sprintf(
|
||||
'%s/%s',
|
||||
wp_get_upload_dir()['basedir'],
|
||||
$path_data['path']
|
||||
);
|
||||
}
|
||||
|
||||
public function file_exists( string $image_size ): bool {
|
||||
$path = $this->get_file_path( $image_size );
|
||||
|
||||
if ( ! $path ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return file_exists( $path );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if an image marked as optimized.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_optimized(): bool {
|
||||
$meta = new Image_Meta( $this->image_id );
|
||||
|
||||
return $meta->get_status() === Image_Status::OPTIMIZED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if an image can be restored from the backups.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function can_be_restored(): bool {
|
||||
$meta = new Image_Meta( $this->image_id );
|
||||
|
||||
return (bool) count( $meta->get_image_backup_paths() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns image's mime type.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_mime_type(): string {
|
||||
return $this->attachment_object->post_mime_type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an original attachment WP_Post object.
|
||||
*
|
||||
* @return WP_Post
|
||||
*/
|
||||
public function get_attachment_object(): WP_Post {
|
||||
return $this->attachment_object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates WP_Post fields of the attachment.
|
||||
*
|
||||
* @return bool True if the post was updated successfully, false otherwise.
|
||||
*/
|
||||
public function update_attachment( array $update_query ): bool {
|
||||
global $wpdb;
|
||||
|
||||
// Must use $wpdb here as `wp_update_post()` doesn't allow to rewrite guid.
|
||||
$result = $wpdb->update(
|
||||
$wpdb->posts,
|
||||
$update_query,
|
||||
[ 'ID' => $this->image_id ]
|
||||
);
|
||||
|
||||
if ( 0 !== $result ) {
|
||||
$this->attachment_object = get_post( $this->image_id );
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of mime types supported by the plugin.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function get_supported_mime_types(): array {
|
||||
return self::SUPPORTED_MIME_TYPES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of formats types supported by the plugin.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function get_supported_formats(): array {
|
||||
return self::SUPPORTED_FORMATS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of mime types that are supported by the plugin, but cannot be optimized
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function get_mime_types_cannot_be_optimized(): array {
|
||||
return self::MIME_TYPES_CANNOT_BE_OPTIMIZED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of formats that are supported by the plugin, but cannot be optimized
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function get_formats_cannot_be_optimized(): array {
|
||||
return self::FORMATS_CANNOT_BE_OPTIMIZED;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Invalid_Image_Exception
|
||||
*/
|
||||
public function __construct( int $image_id ) {
|
||||
$this->image_id = $image_id;
|
||||
$this->attachment_object = get_post( $image_id );
|
||||
|
||||
if ( ! $this->attachment_object ) {
|
||||
throw new Invalid_Image_Exception( "There is no entity with id '$image_id'" );
|
||||
}
|
||||
|
||||
if ( ! wp_attachment_is_image( $this->attachment_object ) ) {
|
||||
throw new Invalid_Image_Exception( "Post '$image_id' is not an image" );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\File_Utils;
|
||||
use ImageOptimization\Classes\Image\Exceptions\Invalid_Image_Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
/**
|
||||
* Class WP_Image_Meta
|
||||
*
|
||||
* This class is used to manage the metadata of an image in WordPress.
|
||||
*/
|
||||
class WP_Image_Meta {
|
||||
private int $image_id;
|
||||
private array $image_meta;
|
||||
private Image $image;
|
||||
|
||||
/**
|
||||
* Get the size data of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @return array|null The size data of the image or null if the size does not exist.
|
||||
*/
|
||||
public function get_size_data( string $image_size ): ?array {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
$output = [];
|
||||
|
||||
$output['file'] = $this->image_meta['file'];
|
||||
$output['filesize'] = $this->image_meta['filesize'];
|
||||
$output['width'] = $this->image_meta['width'];
|
||||
$output['height'] = $this->image_meta['height'];
|
||||
$output['mime-type'] = $this->image->get_attachment_object()->post_mime_type;
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
if ( ! isset( $this->image_meta['sizes'][ $image_size ] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['sizes'][ $image_size ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the keys of the image sizes.
|
||||
*
|
||||
* @return array The keys of the image sizes.
|
||||
*/
|
||||
public function get_size_keys(): array {
|
||||
return [ Image::SIZE_FULL, ...array_keys( $this->image_meta['sizes'] ) ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns keys of sizes that have the same dimensions as the one provided.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_size_duplicates( string $image_size ): array {
|
||||
$duplicates = [];
|
||||
|
||||
$width = $this->get_width( $image_size );
|
||||
$height = $this->get_height( $image_size );
|
||||
|
||||
foreach ( $this->image_meta['sizes'] as $size_key => $size_data ) {
|
||||
if ( $size_data['width'] === $width && $size_data['height'] === $height && $image_size !== $size_key ) {
|
||||
$duplicates[] = $size_key;
|
||||
}
|
||||
}
|
||||
|
||||
return array_unique( $duplicates );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file size of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @return int|null The file size of the image or null if the size does not exist.
|
||||
*/
|
||||
public function get_file_size( string $image_size ): ?int {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
return $this->image_meta['filesize'] ?? null;
|
||||
}
|
||||
|
||||
if ( ! isset( $this->image_meta['sizes'][ $image_size ]['filesize'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['sizes'][ $image_size ]['filesize'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the file size of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @param int $file_size The file size to set.
|
||||
* @return WP_Image_Meta The current instance.
|
||||
*/
|
||||
public function set_file_size( string $image_size, int $file_size ): WP_Image_Meta {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
$this->image_meta['filesize'] = $file_size;
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->maybe_add_new_size( $image_size );
|
||||
|
||||
$this->image_meta['sizes'][ $image_size ]['filesize'] = $file_size;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the file path of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @param string $full_path The full path to set.
|
||||
* @return WP_Image_Meta The current instance.
|
||||
*/
|
||||
public function set_file_path( string $image_size, string $full_path ): WP_Image_Meta {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
$this->image_meta['file'] = File_Utils::get_relative_upload_path( $full_path );
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->maybe_add_new_size( $image_size );
|
||||
|
||||
$this->image_meta['sizes'][ $image_size ]['file'] = File_Utils::get_basename( $full_path );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the width of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function get_width( string $image_size ): ?int {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
return $this->image_meta['width'];
|
||||
}
|
||||
|
||||
if ( ! isset( $this->image_meta['sizes'][ $image_size ]['width'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['sizes'][ $image_size ]['width'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the width of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @param int $width The width to set.
|
||||
* @return WP_Image_Meta The current instance.
|
||||
*/
|
||||
public function set_width( string $image_size, int $width ): WP_Image_Meta {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
$this->image_meta['width'] = $width;
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->maybe_add_new_size( $image_size );
|
||||
|
||||
$this->image_meta['sizes'][ $image_size ]['width'] = $width;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the height of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function get_height( string $image_size ): ?int {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
return $this->image_meta['height'];
|
||||
}
|
||||
|
||||
if ( ! isset( $this->image_meta['sizes'][ $image_size ]['height'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['sizes'][ $image_size ]['height'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the height of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @param int $height The height to set.
|
||||
* @return WP_Image_Meta The current instance.
|
||||
*/
|
||||
public function set_height( string $image_size, int $height ): WP_Image_Meta {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
$this->image_meta['height'] = $height;
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->maybe_add_new_size( $image_size );
|
||||
|
||||
$this->image_meta['sizes'][ $image_size ]['height'] = $height;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the mime type of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @param string $mime_type The mime type to set.
|
||||
* @return WP_Image_Meta The current instance.
|
||||
*/
|
||||
public function set_mime_type( string $image_size, string $mime_type ): WP_Image_Meta {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
// WP doesn't store it in meta for the original image
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->maybe_add_new_size( $image_size );
|
||||
|
||||
$this->image_meta['sizes'][ $image_size ]['mime-type'] = $mime_type;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new size to the image if it does not exist.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
*/
|
||||
private function maybe_add_new_size( $image_size ): void {
|
||||
if ( ! isset( $this->image_meta['sizes'][ $image_size ] ) ) {
|
||||
$this->image_meta['sizes'][ $image_size ] = [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the image metadata.
|
||||
*
|
||||
* @return WP_Image_Meta The current instance.
|
||||
*/
|
||||
public function save(): WP_Image_Meta {
|
||||
wp_update_attachment_metadata( $this->image_id, $this->image_meta );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Query the image metadata.
|
||||
*
|
||||
* @throws Invalid_Image_Exception
|
||||
*/
|
||||
private function query_meta(): void {
|
||||
$meta = wp_get_attachment_metadata( $this->image_id );
|
||||
|
||||
if ( ! $meta ) {
|
||||
throw new Invalid_Image_Exception( 'Invalid WP image meta' );
|
||||
}
|
||||
|
||||
// Handle unsupported formats that WP doesn't create thumbnails for
|
||||
if ( ! isset( $meta['sizes'] ) ) {
|
||||
$meta['sizes'] = [];
|
||||
}
|
||||
|
||||
$this->image_meta = $meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* WP_Image_Meta constructor.
|
||||
*
|
||||
* @param int $image_id The ID of the image.
|
||||
* @param Image|null $image The image object.
|
||||
* @throws Invalid_Image_Exception If the image metadata is invalid.
|
||||
*/
|
||||
public function __construct( int $image_id, ?Image $image = null ) {
|
||||
$this->image_id = $image_id;
|
||||
$this->image = $image ?? new Image( $image_id );
|
||||
|
||||
$this->query_meta();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Locale {
|
||||
private $original_locale;
|
||||
|
||||
public function set_utf_locale( int $category = LC_CTYPE ) {
|
||||
setlocale( $category, 'en_US.UTF-8' );
|
||||
}
|
||||
|
||||
public function get_locale( int $category = LC_CTYPE ) {
|
||||
return setlocale( $category, 0 );
|
||||
}
|
||||
|
||||
public function reset_to_original( int $category = LC_CTYPE ) {
|
||||
return setlocale( $category, $this->original_locale );
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->original_locale = $this->get_locale();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Logger {
|
||||
public const LEVEL_ERROR = 'error';
|
||||
public const LEVEL_WARN = 'warn';
|
||||
public const LEVEL_INFO = 'info';
|
||||
public const LEVEL_DEBUG = 'debug';
|
||||
|
||||
public const LOG_LEVEL_PRIORITY = [
|
||||
'debug' => 1,
|
||||
'info' => 2,
|
||||
'warn' => 3,
|
||||
'error' => 4,
|
||||
];
|
||||
|
||||
public static function log( string $log_level, $message ): void {
|
||||
if (
|
||||
defined( 'IMAGE_OPTIMIZATION_MINIMUM_LOG_LEVEL' ) &&
|
||||
self::LOG_LEVEL_PRIORITY[ $log_level ] < (int) IMAGE_OPTIMIZATION_MINIMUM_LOG_LEVEL
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
$backtrace = debug_backtrace(); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
|
||||
|
||||
$class = $backtrace[1]['class'] ?? null;
|
||||
$type = $backtrace[1]['type'] ?? null;
|
||||
$function = $backtrace[1]['function'];
|
||||
|
||||
if ( $class ) {
|
||||
$message = '[Image Optimizer]: ' . $log_level . ' in ' . "$class$type$function()" . ': ' . $message;
|
||||
} else {
|
||||
$message = '[Image Optimizer]: ' . $log_level . ' in ' . "$function()" . ': ' . $message;
|
||||
}
|
||||
|
||||
error_log( $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
}
|
||||
|
||||
public static function debug( $message ): void {
|
||||
self::log( self::LEVEL_DEBUG, $message );
|
||||
}
|
||||
|
||||
public static function info( $message ): void {
|
||||
self::log( self::LEVEL_INFO, $message );
|
||||
}
|
||||
|
||||
public static function warn( $message ): void {
|
||||
self::log( self::LEVEL_WARN, $message );
|
||||
}
|
||||
|
||||
public static function error( $message ): void {
|
||||
self::log( self::LEVEL_ERROR, $message );
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Migration\Handlers;
|
||||
|
||||
use ImageOptimization\Classes\Image\{
|
||||
Image,
|
||||
Image_Dimensions,
|
||||
Image_Query_Builder,
|
||||
WP_Image_Meta,
|
||||
};
|
||||
|
||||
use ImageOptimization\Classes\Migration\Migration;
|
||||
use Throwable;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Fix_Avif_With_Zero_Dimensions extends Migration {
|
||||
public static function get_name(): string {
|
||||
return 'fix_avif_with_zero_dimensions';
|
||||
}
|
||||
|
||||
public static function run(): bool {
|
||||
$query = ( new Image_Query_Builder() )
|
||||
->set_mime_types( [ 'image/avif', 'application/octet-stream' ] )
|
||||
->return_images_with_non_empty_meta()
|
||||
->execute();
|
||||
|
||||
if ( ! $query->post_count ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ( $query->posts as $attachment_id ) {
|
||||
try {
|
||||
$wp_meta = new WP_Image_Meta( $attachment_id );
|
||||
$image = new Image( $attachment_id );
|
||||
|
||||
foreach ( $wp_meta->get_size_keys() as $size_key ) {
|
||||
if ( 0 === $wp_meta->get_width( $size_key ) || 0 === $wp_meta->get_height( $size_key ) ) {
|
||||
$dimensions = Image_Dimensions::get_by_path( $image->get_file_path( $size_key ) );
|
||||
|
||||
$wp_meta
|
||||
->set_width( $size_key, $dimensions->width )
|
||||
->set_height( $size_key, $dimensions->height )
|
||||
->save();
|
||||
}
|
||||
}
|
||||
} catch ( Throwable $t ) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Migration\Handlers;
|
||||
|
||||
use ImageOptimization\Classes\Image\{
|
||||
Image,
|
||||
Image_Meta,
|
||||
Image_Query_Builder,
|
||||
WP_Image_Meta
|
||||
};
|
||||
|
||||
use ImageOptimization\Classes\Migration\Migration;
|
||||
use ImageOptimization\Modules\Stats\Classes\Optimization_Stats;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Fix_Mime_Type extends Migration {
|
||||
public static function get_name(): string {
|
||||
return 'fix_mime_type';
|
||||
}
|
||||
|
||||
public static function run(): bool {
|
||||
$query = ( new Image_Query_Builder() )
|
||||
->return_optimized_images()
|
||||
->execute();
|
||||
|
||||
if ( ! $query->post_count ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ( $query->posts as $attachment_id ) {
|
||||
$stats = Optimization_Stats::get_image_stats( $attachment_id );
|
||||
$fully_optimized = ( $stats['initial_image_size'] - $stats['current_image_size'] ) <= 0;
|
||||
|
||||
if ( $fully_optimized ) {
|
||||
$io_meta = new Image_Meta( $attachment_id );
|
||||
$wp_meta = new WP_Image_Meta( $attachment_id );
|
||||
$size_data = $wp_meta->get_size_data( Image::SIZE_FULL );
|
||||
|
||||
if (
|
||||
! str_contains( $size_data['file'], '.webp' ) && 'image/webp' === $size_data['mime-type'] ||
|
||||
! str_contains( $size_data['file'], '.avif' ) && 'image/avif' === $size_data['mime-type'] ||
|
||||
! str_contains( $size_data['file'], '.avif' ) && 'application/octet-stream' === $size_data['mime-type']
|
||||
) {
|
||||
$original_mime_type = $io_meta->get_original_mime_type( Image::SIZE_FULL );
|
||||
|
||||
foreach ( $wp_meta->get_size_keys() as $size ) {
|
||||
$wp_meta
|
||||
->set_mime_type( $size, $original_mime_type )
|
||||
->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Migration\Handlers;
|
||||
|
||||
use ImageOptimization\Classes\Image\{
|
||||
Image_Meta,
|
||||
Image_Query_Builder,
|
||||
};
|
||||
|
||||
use ImageOptimization\Classes\Migration\Migration;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Fix_Optimized_Size_Keys extends Migration {
|
||||
public static function get_name(): string {
|
||||
return 'fix_optimized_size_keys';
|
||||
}
|
||||
|
||||
public static function run(): bool {
|
||||
$query = ( new Image_Query_Builder() )
|
||||
->return_optimized_images()
|
||||
->execute();
|
||||
|
||||
if ( ! $query->post_count ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ( $query->posts as $attachment_id ) {
|
||||
$meta = new Image_Meta( $attachment_id );
|
||||
$size_keys = array_unique( $meta->get_optimized_sizes() );
|
||||
|
||||
$meta
|
||||
->set_optimized_size( $size_keys )
|
||||
->save();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Migration;
|
||||
|
||||
use ImageOptimization\Classes\Async_Operation\{
|
||||
Async_Operation,
|
||||
Async_Operation_Hook,
|
||||
Async_Operation_Queue,
|
||||
Exceptions\Async_Operation_Exception,
|
||||
};
|
||||
|
||||
use ImageOptimization\Classes\Logger;
|
||||
use ImageOptimization\Classes\Migration\Handlers\{
|
||||
Fix_Avif_With_Zero_Dimensions,
|
||||
Fix_Mime_Type,
|
||||
Fix_Optimized_Size_Keys,
|
||||
};
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Migration_Manager {
|
||||
public static function get_migrations(): array {
|
||||
return [
|
||||
Fix_Optimized_Size_Keys::class,
|
||||
Fix_Mime_Type::class,
|
||||
Fix_Avif_With_Zero_Dimensions::class,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $migration_name
|
||||
*
|
||||
* @return \class-string|null
|
||||
*/
|
||||
public static function get_migration( $migration_name ): ?string {
|
||||
foreach ( self::get_migrations() as $migration ) {
|
||||
if ( $migration::get_name() === $migration_name ) {
|
||||
return $migration;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static function init() {
|
||||
$migrations_passed = ( new Migration_Meta() )->get_migrations_passed();
|
||||
|
||||
foreach ( self::get_migrations() as $migration ) {
|
||||
if ( in_array( $migration::get_name(), $migrations_passed, true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
Async_Operation::create(
|
||||
Async_Operation_Hook::DB_MIGRATION,
|
||||
[ 'name' => $migration::get_name() ],
|
||||
Async_Operation_Queue::MIGRATION,
|
||||
0,
|
||||
true
|
||||
);
|
||||
} catch ( Async_Operation_Exception $aoe ) {
|
||||
$name = $migration::get_name();
|
||||
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"Error while running migration `$name`: " . $aoe->getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Migration;
|
||||
|
||||
use DateTime;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Migration_Meta {
|
||||
public const IMAGE_OPTIMIZER_MIGRATION_KEY = 'image_optimizer_migrations';
|
||||
private const INITIAL_META_VALUE = [
|
||||
'last_run' => null,
|
||||
'last_wp_version_run' => null,
|
||||
'migrations_passed' => [],
|
||||
];
|
||||
private array $migration_meta;
|
||||
|
||||
public function get_last_run(): ?string {
|
||||
return $this->migration_meta['last_run'];
|
||||
}
|
||||
|
||||
public function set_last_run( DateTime $date ): Migration_Meta {
|
||||
$this->migration_meta['last_run'] = $date;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_last_wp_version(): string {
|
||||
return $this->migration_meta['last_wp_version_run'];
|
||||
}
|
||||
|
||||
public function set_last_wp_version( ?string $version ): Migration_Meta {
|
||||
if ( ! $version ) {
|
||||
$this->migration_meta['last_wp_version_run'] = get_bloginfo( 'version' );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->migration_meta['last_wp_version_run'] = $version;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_migrations_passed(): array {
|
||||
return $this->migration_meta['migrations_passed'];
|
||||
}
|
||||
|
||||
public function add_migration_passed( string $migration ): Migration_Meta {
|
||||
$this->migration_meta['migrations_passed'][] = $migration;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function delete(): bool {
|
||||
return delete_option( self::IMAGE_OPTIMIZER_MIGRATION_KEY );
|
||||
}
|
||||
|
||||
public function save(): Migration_Meta {
|
||||
update_option( self::IMAGE_OPTIMIZER_MIGRATION_KEY, $this->migration_meta, false );
|
||||
|
||||
$this->query_meta();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
private function query_meta(): void {
|
||||
$meta = get_option( self::IMAGE_OPTIMIZER_MIGRATION_KEY, [] );
|
||||
$this->migration_meta = $meta ? array_replace_recursive( self::INITIAL_META_VALUE, $meta ) : self::INITIAL_META_VALUE;
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->query_meta();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Migration;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
abstract class Migration {
|
||||
abstract public static function run(): bool;
|
||||
abstract public static function get_name(): string;
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
/**
|
||||
* Module Base.
|
||||
*
|
||||
* An abstract class providing the properties and methods needed to
|
||||
* manage and handle modules in inheriting classes.
|
||||
*
|
||||
* @abstract
|
||||
*/
|
||||
abstract class Module_Base {
|
||||
|
||||
/**
|
||||
* Module class reflection.
|
||||
*
|
||||
* Holds the information about a class.
|
||||
* @access private
|
||||
*
|
||||
* @var \ReflectionClass
|
||||
*/
|
||||
private $reflection = null;
|
||||
|
||||
/**
|
||||
* Module routes.
|
||||
*
|
||||
* Holds the module registered routes.
|
||||
* @access public
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $routes = [];
|
||||
|
||||
/**
|
||||
* Module components.
|
||||
*
|
||||
* Holds the module components.
|
||||
* @access private
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $components = [];
|
||||
|
||||
/**
|
||||
* Module instance.
|
||||
*
|
||||
* Holds the module instance.
|
||||
* @access protected
|
||||
*
|
||||
* @var Module_Base[]
|
||||
*/
|
||||
protected static $_instances = [];
|
||||
|
||||
/**
|
||||
* Get module name.
|
||||
*
|
||||
* Retrieve the module name.
|
||||
* @access public
|
||||
* @abstract
|
||||
*
|
||||
* @return string Module name.
|
||||
*/
|
||||
abstract public function get_name();
|
||||
|
||||
/**
|
||||
* Instance.
|
||||
*
|
||||
* Ensures only one instance of the module class is loaded or can be loaded.
|
||||
* @access public
|
||||
* @static
|
||||
*
|
||||
* @return Module_Base An instance of the class.
|
||||
*/
|
||||
public static function instance() {
|
||||
$class_name = static::class_name();
|
||||
|
||||
if ( empty( static::$_instances[ $class_name ] ) ) {
|
||||
static::$_instances[ $class_name ] = new static(); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
return static::$_instances[ $class_name ];
|
||||
}
|
||||
|
||||
/**
|
||||
* is_active
|
||||
* @access public
|
||||
* @static
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_active() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class name.
|
||||
*
|
||||
* Retrieve the name of the class.
|
||||
* @access public
|
||||
* @static
|
||||
*/
|
||||
public static function class_name() {
|
||||
return get_called_class();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone.
|
||||
*
|
||||
* Disable class cloning and throw an error on object clone.
|
||||
*
|
||||
* The whole idea of the singleton design pattern is that there is a single
|
||||
* object. Therefore, we don't want the object to be cloned.
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function __clone() {
|
||||
// Cloning instances of the class is forbidden
|
||||
_doing_it_wrong( __FUNCTION__, esc_html__( 'Something went wrong.', 'image-optimization' ), '1.0.0' ); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
/**
|
||||
* Wakeup.
|
||||
*
|
||||
* Disable unserializing of the class.
|
||||
* @access public
|
||||
*/
|
||||
public function __wakeup() {
|
||||
// Unserializing instances of the class is forbidden
|
||||
_doing_it_wrong( __FUNCTION__, esc_html__( 'Something went wrong.', 'image-optimization' ), '1.0.0' ); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
/**
|
||||
* @access public
|
||||
*/
|
||||
public function get_reflection() {
|
||||
if ( null === $this->reflection ) {
|
||||
try {
|
||||
$this->reflection = new \ReflectionClass( $this );
|
||||
} catch ( \ReflectionException $e ) {
|
||||
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
|
||||
error_log( $e->getMessage() );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this->reflection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add module component.
|
||||
*
|
||||
* Add new component to the current module.
|
||||
* @access public
|
||||
*
|
||||
* @param string $id Component ID.
|
||||
* @param mixed $instance An instance of the component.
|
||||
*/
|
||||
public function add_component( string $id, $instance ) {
|
||||
$this->components[ $id ] = $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add module route.
|
||||
*
|
||||
* Add new route to the current module.
|
||||
* @access public
|
||||
*
|
||||
* @param string $id Route ID.
|
||||
* @param mixed $instance An instance of the route.
|
||||
*/
|
||||
public function add_route( string $id, $instance ) {
|
||||
$this->routes[ $id ] = $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* @access public
|
||||
* @return string[]
|
||||
*/
|
||||
public function get_components(): array {
|
||||
return $this->components;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get module component.
|
||||
*
|
||||
* Retrieve the module component.
|
||||
* @access public
|
||||
*
|
||||
* @param string $id Component ID.
|
||||
*
|
||||
* @return mixed An instance of the component, or `false` if the component
|
||||
* doesn't exist.
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function get_component( string $id ) {
|
||||
if ( isset( $this->components[ $id ] ) ) {
|
||||
return $this->components[ $id ];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the namespace of the class
|
||||
*
|
||||
* @access public
|
||||
* @static
|
||||
*/
|
||||
public static function namespace_name() {
|
||||
$class_name = static::class_name();
|
||||
return substr( $class_name, 0, strrpos( $class_name, '\\' ) );
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get assets url.
|
||||
*
|
||||
* @param string $file_name
|
||||
* @param string $file_extension
|
||||
* @param string $relative_url Optional. Default is null.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
final protected function get_assets_url( $file_name, $file_extension, $relative_url = null ): string {
|
||||
static $is_test_mode = null;
|
||||
|
||||
if ( null === $is_test_mode ) {
|
||||
$is_test_mode = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG;
|
||||
}
|
||||
|
||||
if ( ! $relative_url ) {
|
||||
$relative_url = $this->get_assets_relative_url();
|
||||
}
|
||||
|
||||
$url = $this->get_assets_base_url() . $relative_url . $file_name;
|
||||
|
||||
return $url . '.' . $file_extension;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get js assets url
|
||||
*
|
||||
* @param string $file_name
|
||||
* @param string $relative_url Optional. Default is null.
|
||||
* @param string $add_min_suffix Optional. Default is 'default'.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
final protected function get_js_assets_url( $file_name, $relative_url = null, $add_min_suffix = 'default' ): string {
|
||||
return $this->get_assets_url( $file_name, 'js', $relative_url, $add_min_suffix );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get css assets url
|
||||
*
|
||||
* @param string $file_name
|
||||
* @param string $relative_url Optional. Default is null.
|
||||
* @param string $add_min_suffix Optional. Default is 'default'.
|
||||
* @param bool $add_direction_suffix Optional. Default is `false`
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
final protected function get_css_assets_url( $file_name, $relative_url = null, $add_min_suffix = 'default', $add_direction_suffix = false ): string {
|
||||
static $direction_suffix = null;
|
||||
|
||||
if ( ! $direction_suffix ) {
|
||||
$direction_suffix = is_rtl() ? '-rtl' : '';
|
||||
}
|
||||
|
||||
if ( $add_direction_suffix ) {
|
||||
$file_name .= $direction_suffix;
|
||||
}
|
||||
|
||||
return $this->get_assets_url( $file_name, 'css', $relative_url, $add_min_suffix );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get assets base url
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_assets_base_url(): string {
|
||||
return IMAGE_OPTIMIZATION_URL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get assets relative url
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_assets_relative_url(): string {
|
||||
return 'assets/build/';
|
||||
}
|
||||
|
||||
public static function routes_list() : array {
|
||||
return [];
|
||||
}
|
||||
|
||||
public static function component_list() : array {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an array of components.
|
||||
* Assumes namespace structure contains `\Components\`
|
||||
*/
|
||||
public function register_components() {
|
||||
$namespace = static::namespace_name();
|
||||
$components_ids = static::component_list();
|
||||
|
||||
foreach ( $components_ids as $component_id ) {
|
||||
$class_name = $namespace . '\\Components\\' . $component_id;
|
||||
$this->add_component( $component_id, new $class_name() );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an array of routes.
|
||||
* Assumes namespace structure contains `\Rest\`
|
||||
*/
|
||||
public function register_routes() {
|
||||
$namespace = static::namespace_name();
|
||||
$routes_ids = static::routes_list();
|
||||
|
||||
foreach ( $routes_ids as $route_id ) {
|
||||
$class_name = $namespace . '\\Rest\\' . $route_id;
|
||||
$this->add_route( $route_id, new $class_name() );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Rest;
|
||||
|
||||
use ReflectionClass;
|
||||
use WP_Error;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_User;
|
||||
|
||||
abstract class Route {
|
||||
|
||||
/**
|
||||
* Should the endpoint be validated for user authentication?
|
||||
* If set to TRUE, the default permission callback will make sure the user is logged in and has a valid user id
|
||||
* @var bool
|
||||
*/
|
||||
protected $auth = true;
|
||||
|
||||
/**
|
||||
* holds current authenticated user id
|
||||
* @var int
|
||||
*/
|
||||
protected $current_user_id;
|
||||
|
||||
|
||||
/**
|
||||
* Should the endpoint override an existing one?
|
||||
* @var bool
|
||||
*/
|
||||
protected bool $override = false;
|
||||
|
||||
/**
|
||||
* Rest Endpoint namespace
|
||||
* @var string
|
||||
*/
|
||||
protected string $namespace = 'image-optimizer/v1';
|
||||
|
||||
/**
|
||||
* @var array The valid HTTP methods. The list represents the general REST methods. Do not modify.
|
||||
*/
|
||||
private array $valid_http_methods = [
|
||||
'GET',
|
||||
'PATCH',
|
||||
'POST',
|
||||
'PUT',
|
||||
'DELETE',
|
||||
'HEAD',
|
||||
];
|
||||
|
||||
/**
|
||||
* Route_Base constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
add_action( 'rest_api_init', [ $this, 'rest_api_init' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* rest_api_init
|
||||
*
|
||||
* Registers REST endpoints.
|
||||
* Loops through the REST methods for this route, creates an endpoint configuration for
|
||||
* each of them and registers all the endpoints with the WordPress system.
|
||||
*/
|
||||
public function rest_api_init(): void {
|
||||
$methods = $this->get_methods();
|
||||
if ( empty( $methods ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$callbacks = false;
|
||||
foreach ( (array) $methods as $method ) {
|
||||
if ( ! in_array( $method, $this->valid_http_methods ) ) {
|
||||
continue;
|
||||
}
|
||||
if ( $method && ! $callbacks ) {
|
||||
$callbacks = [];
|
||||
}
|
||||
$callbacks[] = $this->build_endpoint_method_config( $method );
|
||||
}
|
||||
|
||||
$arguments = $this->get_arguments();
|
||||
|
||||
if ( ! $callbacks && empty( $arguments ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$arguments = array_merge( $arguments, (array) $callbacks );
|
||||
register_rest_route( $this->namespace, '/' . $this->get_endpoint() . '/', $arguments, $this->override );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_methods
|
||||
* Rest Endpoint methods
|
||||
*
|
||||
* Returns an array of the supported REST methods for this route
|
||||
* @return array<string> REST methods being configured for this route.
|
||||
*/
|
||||
abstract public function get_methods(): array;
|
||||
|
||||
/**
|
||||
* get_callback
|
||||
*
|
||||
* Returns a reference to the callback function to handle the REST method specified by the /method/ parameter.
|
||||
* @param string $method The REST method name
|
||||
*
|
||||
* @return callable A reference to a member function with the same name as the REST method being passed as a parameter,
|
||||
* or a reference to the default function /callback/.
|
||||
*/
|
||||
public function get_callback_method( string $method ): callable {
|
||||
$method_name = strtolower( $method );
|
||||
$callback = $this->method_exists_in_current_class( $method_name ) ? $method_name : 'callback';
|
||||
return [ $this, $callback ];
|
||||
}
|
||||
|
||||
/**
|
||||
* get_permission_callback_method
|
||||
*
|
||||
* Returns a reference to the permission callback for the method if exists or the default one if it doesn't.
|
||||
* @param string $method The REST method name
|
||||
*
|
||||
* @return callable If a method called (rest-method)_permission_callback exists, returns a reference to it, otherwise
|
||||
* returns a reference to the default member method /permission_callback/.
|
||||
*/
|
||||
public function get_permission_callback_method( string $method ): callable {
|
||||
$method_name = strtolower( $method );
|
||||
$permission_callback_method = $method_name . '_permission_callback';
|
||||
$permission_callback = $this->method_exists_in_current_class( $permission_callback_method ) ? $permission_callback_method : 'permission_callback';
|
||||
return [ $this, $permission_callback ];
|
||||
}
|
||||
|
||||
/**
|
||||
* maybe_add_args_to_config
|
||||
*
|
||||
* Checks if the class has a method call (rest-method)_args.
|
||||
* If it does, the function calls it and adds its response to the config object passed to the function, under the /args/ key.
|
||||
* if the function (rest-method)_consumes exists, it will add the response to the config object under the /consumes/ key.
|
||||
* if the function (rest-method)_produces exists, it will add the response to the config object under the /produces/ key.
|
||||
* if the function (rest-method)_summary exists, it will add the response to the config object under the /summary/ key.
|
||||
* if the function (rest-method)_description exists, it will add the response to the config object under the /description/ key.
|
||||
* @param string $method The REST method name being configured
|
||||
* @param array $config The configuration object for the method
|
||||
*
|
||||
* @return array The configuration object for the method, possibly after being amended
|
||||
*/
|
||||
public function maybe_add_args_to_config( string $method, array $config ): array {
|
||||
$method_name = strtolower( $method );
|
||||
$method_args = $method_name . '_args';
|
||||
if ( $this->method_exists_in_current_class( $method_args ) ) {
|
||||
$config['args'] = $this->{$method_args}();
|
||||
}
|
||||
$config['consumes'] = [ 'application/json' ];
|
||||
if ( $this->method_exists_in_current_class( $method . '_consumes' ) ) {
|
||||
$config['consumes'] = $this->{$method . '_consumes'}();
|
||||
}
|
||||
$config['produces'] = [ 'application/json' ];
|
||||
if ( $this->method_exists_in_current_class( $method . '_produces' ) ) {
|
||||
$config['produces'] = $this->{$method . '_produces'}();
|
||||
}
|
||||
if ( $this->method_exists_in_current_class( $method . '_summary' ) ) {
|
||||
$config['summary'] = $this->{$method . '_summary'}();
|
||||
}
|
||||
if ( $this->method_exists_in_current_class( $method . '_description' ) ) {
|
||||
$config['description'] = $this->{$method . '_description'}();
|
||||
}
|
||||
return $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* maybe_add_response_to_swagger
|
||||
*
|
||||
* If the function method /(rest-method)_response_callback/ exists, adds the filter
|
||||
* /swagger_api_response_(namespace with slashes replaced with underscores)_(endpoint with slashes replaced with underscores)/
|
||||
* with the aforementioned function method.
|
||||
* This filter is used with the WP API Swagger UI plugin to create documentation for the API.
|
||||
* The value being passed is an array: [
|
||||
'200' => ['description' => 'OK'],
|
||||
'404' => ['description' => 'Not Found'],
|
||||
'400' => ['description' => 'Bad Request']
|
||||
]
|
||||
* @param string $method REST method name
|
||||
*/
|
||||
public function maybe_add_response_to_swagger( string $method ): void {
|
||||
$method_name = strtolower( $method );
|
||||
$method_response_callback = $method_name . '_response_callback';
|
||||
if ( $this->method_exists_in_current_class( $method_response_callback ) ) {
|
||||
$response_filter = $method_name . '_' . str_replace(
|
||||
'/',
|
||||
'_',
|
||||
$this->namespace . '/' . $this->get_endpoint()
|
||||
);
|
||||
add_filter( 'swagger_api_responses_' . $response_filter, [ $this, $method_response_callback ] );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* build_endpoint_method_config
|
||||
*
|
||||
* Builds a configuration array for the endpoint based on the presence of the callback, permission, additional parameters,
|
||||
* and response to Swagger member functions.
|
||||
* @param string $method The REST method for the endpoint
|
||||
*
|
||||
* @return array The endpoint configuration for the method specified by the parameter
|
||||
*/
|
||||
private function build_endpoint_method_config( string $method ): array {
|
||||
$config = [
|
||||
'methods' => $method,
|
||||
'callback' => $this->get_callback_method( $method ),
|
||||
'permission_callback' => $this->get_permission_callback_method( $method ),
|
||||
];
|
||||
$this->maybe_add_response_to_swagger( $method );
|
||||
return $this->maybe_add_args_to_config( $method, $config );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* method_exists_in_current_class
|
||||
*
|
||||
* Uses reflection to check if this class has the /method/ method.
|
||||
* @param string $method The name of the method being checked.
|
||||
*
|
||||
* @return bool TRUE if the class has the /method/ method, FALSE otherwise.
|
||||
*/
|
||||
private function method_exists_in_current_class( string $method ): bool {
|
||||
$class_name = get_class( $this );
|
||||
try {
|
||||
$reflection = new ReflectionClass( $class_name );
|
||||
} catch ( \ReflectionException $e ) {
|
||||
return false;
|
||||
}
|
||||
if ( ! $reflection->hasMethod( $method ) ) {
|
||||
return false;
|
||||
}
|
||||
$method_ref = $reflection->getMethod( $method );
|
||||
|
||||
return ( $method_ref && $class_name === $method_ref->class );
|
||||
}
|
||||
|
||||
/**
|
||||
* permission_callback
|
||||
* Permissions callback fallback for the endpoint
|
||||
* Gets the current user ID and sets the /current_user_id/ property.
|
||||
* If the /auth/ property is set to /true/ will make sure that the user is logged in (has an id greater than 0)
|
||||
*
|
||||
* @param WP_REST_Request $request unused
|
||||
*
|
||||
* @return bool TRUE, if permission granted, FALSE otherwise
|
||||
*/
|
||||
public function permission_callback( WP_REST_Request $request ): bool {
|
||||
// try to get current user
|
||||
$this->current_user_id = get_current_user_id();
|
||||
if ( $this->auth ) {
|
||||
return $this->current_user_id > 0;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* callback
|
||||
* Fallback callback function, returns a response consisting of the string /ok/.
|
||||
*
|
||||
* @param WP_REST_Request $request unused
|
||||
*
|
||||
* @return WP_REST_Response Default Response of the string 'ok'.
|
||||
*/
|
||||
public function callback( WP_REST_Request $request ): WP_REST_Response {
|
||||
return rest_ensure_response( [ 'OK' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* respond_wrong_method
|
||||
*
|
||||
* Creates a WordPress error object with the /rest_no_route/ code and the message and code supplied or the defaults.
|
||||
* @param null $message The error message for the wrong method.
|
||||
* Optional.
|
||||
* Defaults to null, which makes sets the message to /No route was found matching the URL and request method/
|
||||
* @param int $code The HTTP status code.
|
||||
* Optional.
|
||||
* Defaults to 404 (Not found).
|
||||
*
|
||||
* @return WP_Error The WordPress error object with the error message and status code supplied
|
||||
*/
|
||||
public function respond_wrong_method( $message = null, int $code = 404 ): WP_Error {
|
||||
if ( null === $message ) {
|
||||
$message = __( 'No route was found matching the URL and request method', 'cloud-backup' );
|
||||
}
|
||||
|
||||
return new WP_Error( 'rest_no_route', $message, [ 'status' => $code ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* respond_with_code
|
||||
* Create a new /WP_REST_Response/ object with the specified data and HTTP response code.
|
||||
*
|
||||
* @param array|null $data The data to return in this response
|
||||
* @param int $code The HTTP response code.
|
||||
* Optional.
|
||||
* Defaults to 200 (OK).
|
||||
*
|
||||
* @return WP_REST_Response The WordPress response object loaded with the data and the response code.
|
||||
*/
|
||||
public function respond_with_code( ?array $data = null, int $code = 200 ): WP_REST_Response {
|
||||
return new WP_REST_Response( $data, $code );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_user_from_request
|
||||
*
|
||||
* Returns the current user object.
|
||||
* Depends on the property /current_user_id/ to be set.
|
||||
* @return WP_User|false The user object or false if not found or on error.
|
||||
*/
|
||||
public function get_user_from_request() {
|
||||
return get_user_by( 'id', $this->current_user_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_arguments
|
||||
* Rest Endpoint extra arguments
|
||||
* @return array Additional arguments for the route configuration
|
||||
*/
|
||||
public function get_arguments(): array {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* get_endpoint
|
||||
* Rest route Endpoint
|
||||
* @return string Endpoint uri component (comes after the route namespace)
|
||||
*/
|
||||
abstract public function get_endpoint(): string;
|
||||
|
||||
/**
|
||||
* get_name
|
||||
* @return string The name of the route
|
||||
*/
|
||||
abstract public function get_name(): string;
|
||||
|
||||
/**
|
||||
* get_self_url
|
||||
*
|
||||
* @param string $endpoint
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_self_url( string $endpoint = '' ): string {
|
||||
return rest_url( $this->namespace . '/' . $endpoint );
|
||||
}
|
||||
|
||||
public function respond_success_json( $data = [] ): WP_REST_Response {
|
||||
return new WP_REST_Response([
|
||||
'success' => true,
|
||||
'data' => $data,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{message: string, code: string} $data
|
||||
*
|
||||
* @return WP_Error
|
||||
*/
|
||||
public function respond_error_json( array $data ): WP_Error {
|
||||
if ( ! isset( $data['message'] ) || ! isset( $data['code'] ) ) {
|
||||
_doing_it_wrong(
|
||||
__FUNCTION__,
|
||||
esc_html__( 'Both `message` and `code` keys must be provided', 'image-optimization' ),
|
||||
'1.0.0'
|
||||
); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
return new WP_Error(
|
||||
$data['code'] ?? 'internal_server_error',
|
||||
$data['message'] ?? esc_html__( 'Internal server error', 'image-optimization' ),
|
||||
);
|
||||
}
|
||||
|
||||
public function verify_nonce( $nonce = '', $name = '' ) {
|
||||
if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $nonce ) ), $name ) ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => esc_html__( 'Invalid nonce', 'image-optimization' ),
|
||||
'code' => 'bad_request',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function verify_capability( $capability = 'manage_options' ) {
|
||||
if ( ! current_user_can( $capability ) ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => esc_html__( 'You do not have sufficient permissions to access this data.', 'image-optimization' ),
|
||||
'code' => 'bad_request',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function verify_nonce_and_capability( $nonce = '', $name = '', $capability = 'manage_options' ) {
|
||||
$valid = $this->verify_nonce( $nonce, $name );
|
||||
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $valid;
|
||||
}
|
||||
|
||||
if ( ! current_user_can( $capability ) ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => esc_html__( 'You do not have sufficient permissions to access this data.', 'image-optimization' ),
|
||||
'code' => 'bad_request',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function trigger_internal( $method, $endpoint, $args = [] ): array {
|
||||
$request = new WP_REST_Request( $method, $this->get_self_url( $endpoint ) );
|
||||
if ( ! empty( $args['body'] ) ) {
|
||||
$request->set_body_params( $args['body'] );
|
||||
}
|
||||
if ( ! empty( $args['headers'] ) ) {
|
||||
$request->set_headers( $args['headers'] );
|
||||
}
|
||||
if ( ! empty( $args['params'] ) ) {
|
||||
$request->set_query_params( $args['params'] );
|
||||
}
|
||||
|
||||
$response = rest_do_request( $request );
|
||||
$server = rest_get_server();
|
||||
return $server->response_to_data( $response, false );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
use ReflectionClass;
|
||||
use WP_Error;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
abstract class Route {
|
||||
|
||||
/**
|
||||
* Should the endpoint be validated for user authentication?
|
||||
* If set to TRUE, the default permission callback will make sure the user is logged in and has a valid user id
|
||||
* @var bool
|
||||
*/
|
||||
protected $auth = true;
|
||||
|
||||
/**
|
||||
* holds current authenticated user id
|
||||
* @var int
|
||||
*/
|
||||
protected $current_user_id;
|
||||
|
||||
protected $override = false;
|
||||
|
||||
/**
|
||||
* Rest Endpoint namespace
|
||||
* @var string
|
||||
*/
|
||||
protected $namespace = 'image-optimizer/v1';
|
||||
|
||||
/**
|
||||
* @var array The valid HTTP methods. The list represents the general REST methods. Do not modify.
|
||||
*/
|
||||
private $valid_http_methods = [
|
||||
'GET',
|
||||
'PATCH',
|
||||
'POST',
|
||||
'PUT',
|
||||
'DELETE',
|
||||
];
|
||||
|
||||
/**
|
||||
* Route_Base constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
add_action( 'rest_api_init', [ $this, 'rest_api_init' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* rest_api_init
|
||||
*
|
||||
* Registers REST endpoints.
|
||||
* Loops through the REST methods for this route, creates an endpoint configuration for
|
||||
* each of them and registers all the endpoints with the WordPress system.
|
||||
*/
|
||||
public function rest_api_init(): void {
|
||||
$methods = $this->get_methods();
|
||||
|
||||
if ( empty( $methods ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$callbacks = [];
|
||||
|
||||
foreach ( $methods as $method ) {
|
||||
if ( ! in_array( $method, $this->valid_http_methods, true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$callbacks[] = $this->build_endpoint_method_config( $method );
|
||||
}
|
||||
|
||||
$arguments = $this->get_arguments();
|
||||
|
||||
if ( ! $callbacks && empty( $arguments ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$arguments = array_merge( $arguments, $callbacks );
|
||||
|
||||
register_rest_route( $this->namespace, '/' . $this->get_endpoint() . '/', $arguments, $this->override );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_methods
|
||||
* Rest Endpoint methods
|
||||
*
|
||||
* Returns an array of the supported REST methods for this route
|
||||
* @return array<string> REST methods being configured for this route.
|
||||
*/
|
||||
abstract public function get_methods(): array;
|
||||
|
||||
/**
|
||||
* get_callback
|
||||
*
|
||||
* Returns a reference to the callback function to handle the REST method specified by the /method/ parameter.
|
||||
* @param string $method The REST method name
|
||||
*
|
||||
* @return callable A reference to a member function with the same name as the REST method being passed as a parameter,
|
||||
* or a reference to the default function /callback/.
|
||||
*/
|
||||
public function get_callback_method( string $method ): callable {
|
||||
$method_name = strtolower( $method );
|
||||
$callback = $this->method_exists_in_current_class( $method_name ) ? $method_name : 'callback';
|
||||
return [ $this, $callback ];
|
||||
}
|
||||
|
||||
/**
|
||||
* get_permission_callback_method
|
||||
*
|
||||
* Returns a reference to the permission callback for the method if exists or the default one if it doesn't.
|
||||
* @param string $method The REST method name
|
||||
*
|
||||
* @return callable If a method called (rest-method)_permission_callback exists, returns a reference to it, otherwise
|
||||
* returns a reference to the default member method /permission_callback/.
|
||||
*/
|
||||
public function get_permission_callback_method( string $method ): callable {
|
||||
$method_name = strtolower( $method );
|
||||
$permission_callback_method = $method_name . '_permission_callback';
|
||||
$permission_callback = $this->method_exists_in_current_class( $permission_callback_method ) ? $permission_callback_method : 'permission_callback';
|
||||
return [ $this, $permission_callback ];
|
||||
}
|
||||
|
||||
/**
|
||||
* maybe_add_args_to_config
|
||||
*
|
||||
* Checks if the class has a method call (rest-method)_args.
|
||||
* If it does, the function calls it and adds its response to the config object passed to the function, under the /args/ key.
|
||||
* @param string $method The REST method name being configured
|
||||
* @param array $config The configuration object for the method
|
||||
*
|
||||
* @return array The configuration object for the method, possibly after being amended
|
||||
*/
|
||||
public function maybe_add_args_to_config( string $method, array $config ): array {
|
||||
$method_name = strtolower( $method );
|
||||
$method_args = $method_name . '_args';
|
||||
if ( $this->method_exists_in_current_class( $method_args ) ) {
|
||||
$config['args'] = $this->{$method_args}();
|
||||
}
|
||||
return $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* maybe_add_response_to_swagger
|
||||
*
|
||||
* If the function method /(rest-method)_response_callback/ exists, adds the filter
|
||||
* /swagger_api_response_(namespace with slashes replaced with underscores)_(endpoint with slashes replaced with underscores)/
|
||||
* with the aforementioned function method.
|
||||
* This filter is used with the WP API Swagger UI plugin to create documentation for the API.
|
||||
* The value being passed is an array: [
|
||||
'200' => ['description' => 'OK'],
|
||||
'404' => ['description' => 'Not Found'],
|
||||
'400' => ['description' => 'Bad Request']
|
||||
]
|
||||
* @param string $method REST method name
|
||||
*/
|
||||
public function maybe_add_response_to_swagger( string $method ): void {
|
||||
$method_name = strtolower( $method );
|
||||
$method_response_callback = $method_name . '_response_callback';
|
||||
if ( $this->method_exists_in_current_class( $method_response_callback ) ) {
|
||||
$response_filter = $method_name . '_' . str_replace(
|
||||
'/',
|
||||
'_',
|
||||
$this->namespace . '/' . $this->get_endpoint()
|
||||
);
|
||||
add_filter( 'swagger_api_responses_' . $response_filter, [ $this, $method_response_callback ] );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* build_endpoint_method_config
|
||||
*
|
||||
* Builds a configuration array for the endpoint based on the presence of the callback, permission, additional parameters,
|
||||
* and response to Swagger member functions.
|
||||
* @param string $method The REST method for the endpoint
|
||||
*
|
||||
* @return array The endpoint configuration for the method specified by the parameter
|
||||
*/
|
||||
private function build_endpoint_method_config( string $method ): array {
|
||||
$config = [
|
||||
'methods' => $method,
|
||||
'callback' => $this->get_callback_method( $method ),
|
||||
'permission_callback' => $this->get_permission_callback_method( $method ),
|
||||
];
|
||||
$config = $this->maybe_add_args_to_config( $method, $config );
|
||||
return $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* method_exists_in_current_class
|
||||
*
|
||||
* Uses reflection to check if this class has the /method/ method.
|
||||
* @param string $method The name of the method being checked.
|
||||
*
|
||||
* @return bool TRUE if the class has the /method/ method, FALSE otherwise.
|
||||
*/
|
||||
private function method_exists_in_current_class( string $method ): bool {
|
||||
$class_name = get_class( $this );
|
||||
try {
|
||||
$reflection = new ReflectionClass( $class_name );
|
||||
} catch ( \ReflectionException $e ) {
|
||||
return false;
|
||||
}
|
||||
if ( ! $reflection->hasMethod( $method ) ) {
|
||||
return false;
|
||||
}
|
||||
$method_ref = $reflection->getMethod( $method );
|
||||
|
||||
return ( $method_ref && $class_name === $method_ref->class );
|
||||
}
|
||||
|
||||
/**
|
||||
* permission_callback
|
||||
* Permissions callback fallback for the endpoint
|
||||
* Gets the current user ID and sets the /current_user_id/ property.
|
||||
* If the /auth/ property is set to /true/ will make sure that the user is logged in (has an id greater than 0)
|
||||
*
|
||||
* @param WP_REST_Request $request unused
|
||||
*
|
||||
* @return bool TRUE, if permission granted, FALSE otherwise
|
||||
*/
|
||||
public function permission_callback( WP_REST_Request $request ): bool {
|
||||
// try to get current user
|
||||
$this->current_user_id = get_current_user_id();
|
||||
if ( $this->auth ) {
|
||||
return $this->current_user_id > 0;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* callback
|
||||
* Fallback callback function, returns a response consisting of the string /ok/.
|
||||
*
|
||||
* @param WP_REST_Request $request unused
|
||||
*
|
||||
* @return WP_REST_Response Default Response of the string 'ok'.
|
||||
*/
|
||||
public function callback( WP_REST_Request $request ): WP_REST_Response {
|
||||
return rest_ensure_response( [ 'OK' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* respond_wrong_method
|
||||
*
|
||||
* Creates a WordPress error object with the /rest_no_route/ code and the message and code supplied or the defaults.
|
||||
* @param null $message The error message for the wrong method.
|
||||
* Optional.
|
||||
* Defaults to null, which makes sets the message to /No route was found matching the URL and request method/
|
||||
* @param int $code The HTTP status code.
|
||||
* Optional.
|
||||
* Defaults to 404 (Not found).
|
||||
*
|
||||
* @return WP_Error The WordPress error object with the error message and status code supplied
|
||||
*/
|
||||
public function respond_wrong_method( $message = null, int $code = 404 ): WP_Error {
|
||||
if ( null === $message ) {
|
||||
$message = 'No route was found matching the URL and request method';
|
||||
}
|
||||
|
||||
return new WP_Error( 'rest_no_route', $message, [ 'status' => $code ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* respond_with_code
|
||||
* Create a new /WP_REST_Response/ object with the specified data and HTTP response code.
|
||||
*
|
||||
* @param array|null $data The data to return in this response
|
||||
* @param int $code The HTTP response code.
|
||||
* Optional.
|
||||
* Defaults to 200 (OK).
|
||||
*
|
||||
* @return WP_REST_Response The WordPress response object loaded with the data and the response code.
|
||||
*/
|
||||
public function respond_with_code( ?array $data = null, int $code = 200 ): WP_REST_Response {
|
||||
return new WP_REST_Response( $data, $code );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_user_from_request
|
||||
*
|
||||
* Returns the current user object.
|
||||
* Depends on the property /current_user_id/ to be set.
|
||||
* @return WP_User|false The user object or false if not found or on error.
|
||||
*/
|
||||
public function get_user_from_request() {
|
||||
return get_user_by( 'id', $this->current_user_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_arguments
|
||||
* Rest Endpoint extra arguments
|
||||
* @return array Additional arguments for the route configuration
|
||||
*/
|
||||
public function get_arguments(): array {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* get_endpoint
|
||||
* Rest route Endpoint
|
||||
* @return string Endpoint uri component (comes after the route namespace)
|
||||
*/
|
||||
abstract public function get_endpoint(): string;
|
||||
|
||||
/**
|
||||
* get_name
|
||||
* @return string The name of the route
|
||||
*/
|
||||
abstract public function get_name(): string;
|
||||
|
||||
public function get_self_url( $endpoint = '' ): string {
|
||||
return rest_url( $this->namespace . '/' . $endpoint );
|
||||
}
|
||||
|
||||
public function respond_success_json( $data = [] ): WP_REST_Response {
|
||||
return new WP_REST_Response([
|
||||
'success' => true,
|
||||
'data' => $data,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{message: string, code: string} $data
|
||||
*
|
||||
* @return WP_Error
|
||||
*/
|
||||
public function respond_error_json( array $data ): WP_Error {
|
||||
if ( ! isset( $data['message'] ) || ! isset( $data['code'] ) ) {
|
||||
_doing_it_wrong(
|
||||
__FUNCTION__,
|
||||
esc_html__( 'Both `message` and `code` keys must be provided', 'image-optimization' ),
|
||||
'1.0.0'
|
||||
); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
return new WP_Error(
|
||||
$data['code'] ?? 'internal_server_error',
|
||||
$data['message'] ?? esc_html__( 'Internal server error', 'image-optimization' ),
|
||||
);
|
||||
}
|
||||
|
||||
public function verify_nonce( $nonce = '', $name = '' ) {
|
||||
if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $nonce ) ), $name ) ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => esc_html__( 'Invalid nonce', 'image-optimization' ),
|
||||
'code' => 'bad_request',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function verify_nonce_and_capability( $nonce = '', $name = '', $capability = 'manage_options' ) {
|
||||
$this->verify_nonce( $nonce, $name );
|
||||
|
||||
if ( ! current_user_can( $capability ) ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => esc_html__( 'You do not have sufficient permissions to access this data.', 'image-optimization' ),
|
||||
'code' => 'bad_request',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
use ImageOptimization\Classes\Client\Client;
|
||||
use ImageOptimization\Plugin;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Utils {
|
||||
/**
|
||||
* get_elementor
|
||||
* @param $instance
|
||||
*
|
||||
* @return \Elementor\Plugin|false|mixed|null
|
||||
*/
|
||||
public static function get_elementor( $instance = false ) {
|
||||
static $_instance = null;
|
||||
if ( false !== $instance ) {
|
||||
$_instance = $instance;
|
||||
|
||||
return $instance;
|
||||
}
|
||||
if ( null !== $_instance ) {
|
||||
return $_instance;
|
||||
}
|
||||
if ( class_exists( 'Elementor\Plugin' ) ) {
|
||||
return \Elementor\Plugin::instance(); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function get_api_client(): ?Client {
|
||||
return Client::get_instance();
|
||||
}
|
||||
|
||||
public static function get_module( $module_name = '' ) {
|
||||
return Plugin::instance()->modules_manager->get_modules( $module_name );
|
||||
}
|
||||
|
||||
public static function get_module_component( $module_name, $component ) {
|
||||
$module = self::get_module( $module_name );
|
||||
if ( $module ) {
|
||||
return $module->get_component( $component );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* is_elementor_installed
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_elementor_installed(): bool {
|
||||
$plugins = get_plugins();
|
||||
return isset( $plugins['elementor/elementor.php'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* is_elementor_installed_and_active
|
||||
* should be used only after `plugins_loaded` action
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_elementor_installed_and_active(): bool {
|
||||
return did_action( 'elementor/loaded' );
|
||||
}
|
||||
|
||||
public static function is_media_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
if ( ! $current_screen ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return 'upload' === $current_screen->id && 'attachment' === $current_screen->post_type;
|
||||
}
|
||||
|
||||
public static function is_media_upload_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
if ( ! $current_screen ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return 'media' === $current_screen->id && 'add' === $current_screen->action;
|
||||
}
|
||||
|
||||
public static function is_single_attachment_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
if ( ! $current_screen ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return 'attachment' === $current_screen->id && 'post' === $current_screen->base;
|
||||
}
|
||||
|
||||
public static function is_plugin_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
return str_contains( $current_screen->id, 'image-optimization-' );
|
||||
}
|
||||
|
||||
public static function is_plugin_settings_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
return str_contains( $current_screen->id, 'image-optimization-settings' );
|
||||
}
|
||||
|
||||
public static function is_bulk_optimization_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
return str_contains( $current_screen->id, 'image-optimization-bulk-optimization' );
|
||||
}
|
||||
|
||||
public static function user_is_admin(): bool {
|
||||
return current_user_can( 'manage_options' );
|
||||
}
|
||||
|
||||
public static function is_wp_dashboard_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
return str_contains( $current_screen->id, 'dashboard' );
|
||||
}
|
||||
|
||||
public static function is_wp_updates_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
return str_contains( $current_screen->id, 'update' );
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user