Файловый менеджер - Редактировать - /var/www/xthruster/html/wp-content/uploads/flags/image-optimization.tar
Назад
classes/locale.php 0000644 00000001101 14720461212 0010141 0 ustar 00 <?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(); } } classes/file-utils.php 0000644 00000005040 14720461212 0010765 0 ustar 00 <?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 ); } } classes/client/client.php 0000644 00000020257 14720461212 0011453 0 ustar 00 <?php namespace ImageOptimization\Classes\Client; use ImageOptimization\Classes\Exceptions\Client_Exception; use ImageOptimization\Classes\File_Utils; use ImageOptimization\Classes\Image\Image; use ImageOptimization\Modules\Stats\Classes\Optimization_Stats; 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 STATUS_CHECK = 'status/check'; 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(): array { return [ // 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(), // Media library stats 'media_data' => base64_encode( wp_json_encode( self::get_request_stats() ) ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode ]; } 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() ); 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(); } private static function get_remote_url( $endpoint ): string { return self::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 ( 200 !== $response_code ) { // 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; } } classes/client/client-response.php 0000644 00000002536 14720461212 0013307 0 ustar 00 <?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; } } classes/logger.php 0000644 00000001555 14720461212 0010176 0 ustar 00 <?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 static function log( string $log_level, $message ): void { $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 } } classes/file-system/exceptions/file-system-operation-error.php 0000644 00000000411 14720461212 0020715 0 ustar 00 <?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'; } classes/file-system/file-system.php 0000644 00000007450 14720461212 0013421 0 ustar 00 <?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; } } classes/rest/route.php 0000644 00000032455 14720461212 0011035 0 ustar 00 <?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' ) { $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', ]); } } 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 ); } } classes/async-operation/async-operation.php 0000644 00000007172 14720461212 0015146 0 ustar 00 <?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 ); } /** * @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; } /** * @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(); } } } classes/async-operation/async-operation-hook.php 0000644 00000001725 14720461212 0016102 0 ustar 00 <?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'; } classes/async-operation/exceptions/async-operation-exception.php 0000644 00000000425 14720461212 0021315 0 ustar 00 <?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'; } classes/async-operation/interfaces/operation-query-interface.php 0000644 00000000411 14720461212 0021244 0 ustar 00 <?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; } classes/async-operation/async-operation-queue.php 0000644 00000000767 14720461212 0016273 0 ustar 00 <?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'; } classes/async-operation/queries/image-optimization-operation-query.php 0000644 00000003505 14720461212 0022453 0 ustar 00 <?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', ]; } } classes/async-operation/queries/operation-query.php 0000644 00000003051 14720461212 0016643 0 ustar 00 <?php namespace ImageOptimization\Classes\Async_Operation\Queries; use ImageOptimization\Classes\Async_Operation\Async_Operation_Hook; 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; } /** * @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', ]; } } classes/async-operation/async-operation-item.php 0000644 00000003015 14720461212 0016072 0 ustar 00 <?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; } } classes/exceptions/file-operation-error.php 0000644 00000000357 14720461212 0015143 0 ustar 00 <?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'; } classes/exceptions/client-exception.php 0000644 00000000353 14720461212 0014345 0 ustar 00 <?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'; } classes/exceptions/quota-exceeded-error.php 0000644 00000000351 14720461212 0015115 0 ustar 00 <?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'; } classes/migration/handlers/fix-mime-type.php 0000644 00000003144 14720461212 0015176 0 ustar 00 <?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; } } classes/migration/handlers/fix-optimized-size-keys.php 0000644 00000001467 14720461212 0017223 0 ustar 00 <?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; } } classes/migration/handlers/fix-avif-with-zero-dimensions.php 0000644 00000002467 14720461212 0020320 0 ustar 00 <?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; } } classes/migration/migration.php 0000644 00000000377 14720461212 0012702 0 ustar 00 <?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; } classes/migration/migration-meta.php 0000644 00000003456 14720461212 0013627 0 ustar 00 <?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(); } } classes/migration/migration-manager.php 0000644 00000003104 14720461212 0014301 0 ustar 00 <?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() ); } } } } classes/module-base.php 0000644 00000016146 14720461212 0011116 0 ustar 00 <?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() ); } } } classes/image/image-status.php 0000644 00000001240 14720461212 0012373 0 ustar 00 <?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'; } classes/image/image.php 0000644 00000010452 14720461212 0011057 0 ustar 00 <?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'] ); } /** * 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" ); } } } classes/image/image-db-update.php 0000644 00000001217 14720461212 0012721 0 ustar 00 <?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, ]); } } } classes/image/image-backup.php 0000644 00000007766 14720461212 0012340 0 ustar 00 <?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; } } classes/image/image-query-builder.php 0000644 00000004547 14720461212 0013656 0 ustar 00 <?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_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 { $this->query['post__in'] = $image_ids; 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; } } classes/image/image-optimization-error-type.php 0000644 00000000566 14720461212 0015716 0 ustar 00 <?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 GENERIC = 'generic'; } classes/image/image-meta.php 0000644 00000010566 14720461212 0012011 0 ustar 00 <?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, '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_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(); } } classes/image/image-conversion-option.php 0000644 00000000500 14720461212 0014541 0 ustar 00 <?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'; } classes/image/exceptions/invalid-image-exception.php 0000644 00000000361 14720461212 0016656 0 ustar 00 <?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'; } classes/image/exceptions/image-backup-creation-error.php 0000644 00000000375 14720461212 0017437 0 ustar 00 <?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'; } classes/image/exceptions/image-restoring-exception.php 0000644 00000000376 14720461212 0017252 0 ustar 00 <?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'; } classes/image/wp-image-meta.php 0000644 00000016433 14720461212 0012434 0 ustar 00 <?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(); } } classes/image/image-restore.php 0000644 00000007736 14720461212 0012553 0 ustar 00 <?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 ) ); } } classes/image/image-conversion.php 0000644 00000002263 14720461212 0013243 0 ustar 00 <?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', ], ]; } } classes/image/image-dimensions.php 0000644 00000002041 14720461212 0013220 0 ustar 00 <?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; } } classes/route.php 0000644 00000026102 14720461212 0010050 0 ustar 00 <?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', ]); } } } classes/basic-enum.php 0000644 00000001273 14720461212 0010737 0 ustar 00 <?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 ]; } } classes/utils.php 0000644 00000006207 14720461212 0010056 0 ustar 00 <?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' ); } } plugin.php 0000644 00000004261 14720461212 0006555 0 ustar 00 <?php namespace ImageOptimization; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } /** * Class Plugin * Main Plugin class */ class Plugin { /** * Instance * * @access public * @static * * @var Plugin The single instance of the class. */ public static $instance = null; /** * Modules Manager * @var null|Manager */ public $modules_manager = null; /** * class aliases * @access private * @var array */ private $classes_aliases = []; /** * Instance * * Ensures only one instance of the class is loaded or can be loaded. * * @access public * * @return Plugin An instance of the class. */ public static function instance() { if ( is_null( self::$instance ) ) { self::$instance = new self(); } return self::$instance; } public function autoload( $class ) { if ( 0 !== strpos( $class, __NAMESPACE__ ) ) { return; } $has_class_alias = isset( $this->classes_aliases[ $class ] ); // Backward Compatibility: Save old class name for set an alias after the new class is loaded if ( $has_class_alias ) { $class_alias_name = $this->classes_aliases[ $class ]; $class_to_load = $class_alias_name; } else { $class_to_load = $class; } if ( ! class_exists( $class_to_load ) ) { $filename = strtolower( preg_replace( [ '/^' . __NAMESPACE__ . '\\\/', '/([a-z])([A-Z])/', '/_/', '/\\\/' ], [ '', '$1-$2', '-', DIRECTORY_SEPARATOR ], $class_to_load ) ); $filename = IMAGE_OPTIMIZATION_PATH . $filename . '.php'; if ( is_readable( $filename ) ) { include $filename; } } if ( $has_class_alias ) { class_alias( $class_alias_name, $class ); } } private function includes() { require_once IMAGE_OPTIMIZATION_PATH . 'includes/modules-manager.php'; $this->modules_manager = new Manager(); } /** * Plugin class constructor * * Register plugin action hooks and filters * * @access public */ public function __construct() { static $autoloader_registered = false; if ( ! $autoloader_registered ) { $autoloader_registered = spl_autoload_register( [ $this, 'autoload' ] ); } $this->includes(); } } // Instantiate Plugin Class Plugin::instance(); includes/modules-manager.php 0000644 00000003015 14720461212 0012141 0 ustar 00 <?php namespace ImageOptimization; use ImageOptimization\Classes\Module_Base; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } final class Manager { /** * @var Module_Base[] */ private array $modules = []; public static function get_module_list(): array { return [ 'core', 'connect', 'Oauth', 'connect-manager', 'settings', 'stats', 'optimization', 'backups', ]; } /** * @codeCoverageIgnore */ public function __construct() { $modules = self::get_module_list(); foreach ( $modules as $module_name ) { $class_name = str_replace( '-', ' ', $module_name ); $class_name = str_replace( ' ', '', ucwords( $class_name ) ); $class_name = __NAMESPACE__ . '\\Modules\\' . $class_name . '\Module'; /** @var Module_Base $class_name */ if ( $class_name::is_active() ) { $this->modules[ $module_name ] = $class_name::instance(); } } // Action Scheduler needs to be registered before `plugins_loaded` hook priority 0 add_action( 'plugins_loaded', [ $this, 'include_external_libraries' ], -10 ); } /** * @param string $module_name * * @return Module_Base|Module_Base[] */ public function get_modules( $module_name ) { if ( $module_name ) { if ( isset( $this->modules[ $module_name ] ) ) { return $this->modules[ $module_name ]; } return null; } return $this->modules; } public function include_external_libraries() { require_once IMAGE_OPTIMIZATION_PATH . 'vendor/woocommerce/action-scheduler/action-scheduler.php'; } } index.php 0000644 00000000034 14720461212 0006360 0 ustar 00 <?php // Silence is golden. readme.txt 0000644 00000031121 14720461212 0006537 0 ustar 00 === Image Optimizer - Optimize Images and Convert to WebP or AVIF === Contributors: elemntor Tags: image optimization, image compression, convert webp, convert avif, performance, Requires at least: 6.2 Tested up to: 6.6 Requires PHP: 7.4 Stable tag: 1.5.4 License: GPL-3 License URI: https://www.gnu.org/licenses/gpl-3.0.en.html Automatically resize, optimize, and convert images to WebP and AVIF. Compress images in bulk or on upload to boost your WordPress site performance. == Description == https://www.youtube.com/watch?v=Fco5omeF50w Image Optimizer is an easy-to-use WordPress plugin that reduces image size through various compression and resizing techniques - all of which preserve the highest possible image quality. Image Optimizer supports many popular formats, including JPEG, PNG, WebP, AVIF, and GIF. = REDUCED FILE SIZES FOR BOOSTED PERFORMANCE = Image Optimizer ensures faster loading times, enhanced user experience, and overall boosted website performance by reducing the size of your website's images, resulting in improved Core Web Vitals and search engine rankings. With the Image Optimizer’s exceptional capabilities and unique algorithms, you can fine tune images and reduce their file sizes while retaining quality with lossless or lossy compression. **FEATURES** * **Image formats supported** include JPEG, PNG, WebP, AVIF and GIF. * **Works in the background**: The only plugin in the category that optimizes your images in the background, without you having to stay on the page during optimization. * **Resize large images**: The user can set a maximum pixel width, after which images will automatically be resized. (default value set to 1920px) * **2 compression levels**: Lossless - highest quality with minimal compression; Lossy - maximum compression with somewhat reduced quality. * **Optimize on upload**: Automatically optimizes images when you upload them. * **Bulk or individual optimization**: Flexible image optimization options, whether it's on-demand scaling and compression, or bulk optimization for your entire image library. * **EXIF Metadata**: Select whether to clear image metadata to reduce size even further without impacting image quality. * **Backup original images**: Ability to delete backups permanently to save space. (We recommend backing up your website beforehand.) * **Restore original images** (all sizes) for selected media files if needed. * **Convert to WebP and AVIF**: Get efficient and faster-loading formats with WebP and AVIF for even better web performance. * **Image thumbnails**: Resize all image sizes by default. Allow the user to choose specific image sizes based on WordPress-registered thumbnail sizes. = BULK OR SINGLE IMAGE OPTIMIZATION = Image Optimizer by Elementor lets you optimize all images in your library either one at a time, or in a batch according to your preferences and settings. Easily configure the plugin to scale or compress your images on-demand, or automatically have them triggered as they are being uploaded. Or, if you have a large number of images already uploaded, the bulk optimization feature allows you to resize and/or compress your entire library of existing images in just a few clicks. = 2 COMPRESSION LEVELS = With Image Optimizer’s advanced algorithms, you can compress images and reduce their file size at the level that makes the most sense for you. We offer 2 types of compression where images will be processed, giving you the perfect balance of compression and quality. **Lossless Compression**: Lossless compression reduces image file sizes without sacrificing or diminishing the quality of your images. This type of compression reduces file sizes by removing unused or unnecessary data so that no image details are lost along the way. Hence, you are able to reduce the file size and still maintain the quality of your image. **Lossy Compression**: Lossy compression performs maximum compression resulting in lightweight images and smaller file sizes. It reduces image size by removing image data that is generally invisible to the human eye and minimizes any compromise in image quality. **Convert to WebP and AVIF**: Convert images to the slimmer WebP or AVIF formats for even better optimization with a 25-30% savings over JPEG and PNG. Most browsers support WebP, however if they don’t, you can have fallback versions of the image available in the same format as the original image. By tailoring compression to the level you need, your visitors will enjoy faster load times, improved responsiveness, and a seamless browsing experience. Our approach also enables your website to rank higher in search results. Since a search engine's ranking is heavily influenced by speed, user experience, and Core Web Vitals, Image Optimizer by Elementor is an invaluable tool for any website, especially one that’s abundant with images. = Get Started Today = For more information about Image Optimizer, visit our [official website](https://go.elementor.com/wp-repo-description-tab-io-product-page/) or [Try It Now](https://go.elementor.com/wp-repo-description-tab-io-free-trial/). If you have any questions or need support, feel free to [contact us](https://go.elementor.com/wp-repo-description-tab-io-contact-us/) or visit our [help center](https://go.elementor.com/wp-repo-description-tab-io-help-center/). This plugin requires a connection to an active Elementor account in order to identify the user and provide the user with the purchased service. This connection is triggered manually by the user via the plugin's settings panel. This plugin uses a 3rd party service operated by Elementor, which accepts a standard image in JPG, PNG, GIF or WEBP format and returns a web optimized image based on the selected settings. This flow is triggered by the user or automatically (based on the selected plugin settings) on compatible image upload or by manually initiating optimize process. == Related Plugins == [Site Mailer](https://wordpress.org/plugins/site-mailer/): Effortlessly manage transactional emails with Site Mailer. High deliverability, logs and statistics, and no SMTP plugins needed. == Installation == **Get started with a few easy steps** 1. Install using the WordPress built-in Plugin installer, or Extract the zip file and drop the contents in the wp-content/plugins/ directory of your WordPress installation. 2. Activate the plugin through the ‘Plugins’ menu in WordPress. 3. Go to the Image Optimizer tab within the Media menu. 4. Press the ‘Connect’ button and follow the instructions. == Frequently Asked Questions == = Can I use Image Optimizer for any of my WordPress websites? = Absolutely. Image Optimizer by Elementor is a stand-alone WordPress plugin that can be used to optimize images for any or all of your WordPress websites. = Why do I need to optimize images on my website? = Image optimization can significantly improve your website's loading time, which is crucial for user experience and SEO. It reduces the size of your images without compromising their quality, leading to faster page load times and better performance scores. = Why should I consider Image Optimizer by Elementor? = This plugin is a modern approach that is designed to do all the “heavy lifting” of converting and compressing images on a dedicated server, so your own server won’t suffer from any downtime or the need to keep the tab open. It offers on-the-fly optimization, WebP and AVIF conversion, and other features tailored to WordPress users' needs. = Will the original version of my images be lost after compression? = No, The Image Optimizer plugin will save both the original and the compressed versions of your images. You can always restore the original image if needed. = Why should I consider converting my images to WebP or AVIF? = WebP and AVIF are modern image formats that provide superior lossless and lossy compression. They can significantly reduce the file size of images, leading to faster website load times. Most web browsers today support these format, but if they don’t - the original backup will be used. = Can I choose which images to compress? = Absolutely! You can either compress images in bulk, compress specific image files individually, or automatically compress upon image upload. = Is the EXIF metadata of images removed? = EXIF data can be removed if you choose so in the settings page. Best practice for better image optimization would be to remove EXIF metadata. = Is it possible to re-optimize images? = Yes. By changing the requested level of optimization in the settings page, you can re-optimize all images at once. In addition, at any point in time, you can reoptimize any of your images individually; whether after restoring the original, making changes to the optimization settings, or for any other reason. = Do you offer support? = Yes, the Elementor team offers full support for image optimization questions. You can contact us via [https://elementor.com/contact/](https://go.elementor.com/wp-repo-description-tab-io-contact-us/) == Screenshots == 1. Image Optimizer - Settings Page 2. Image Optimizer - Bulk Optimization Page 3. Image Optimizer - Bulk Actions and Individual Actions in the Media Library 4. Image Optimizer - Image Optimization in the Media Library 5. Image Optimizer - Image Optimization in the Media Uploader == Changelog == = 1.5.4 - 2024-10-01 = * New: Added a notice to help users connect from dashboard * Fix: Undefined property notice * Fix: Improved support for caching plugins = 1.5.3 - 2024-09-24 = * New: Added an option to reset connect when invalid * Tweak: Improved AVIF display support * Fix: Invalid char in Plugin name header = 1.5.2 - 2024-08-21 = * New: Implemented a solution for site URL update * Tweak: Added an fallback for AVIF dimensions calculation when coming from 3rd party solution * Tweak: Added asynchronous size calculation for large image galleries * Tweak: Updated plugin CTAs on the plugins page * Fix: File extension issues * Fix: Optimization button stuck on edge cases * Fix: Stats calculation for the total/optimized count on edge cases = 1.5.1 - 2024-07-29 = * Fix: Optimized on upload not working in edge cases = 1.5.0 - 2024-07-29 = * New: Option to convert images to AVIF * Fix: Overall Saving display * Fix: Bulk optimization stats calculation for big galleries = 1.4.1 - 2024-07-08 = * Fix: API error message displayed when trying to reconnect = 1.4.0 - 2024-06-26 = * New: Implement to "One Step" connect & activate * Tweak: New error message for JPEG/Lossless not converted to WebP * Tweak: Description string of convert to webP * Fix: Image not resizing when height and width are equal * Fix: Pointer is displayed for non-admin users * Fix: Overall savings for optimized images is not correct = 1.3.0 - 2024-03-05 = * Tweak: Updated reoptimization option when changing settings * Tweak: Added RTL adjustments * Fix: Optimization button status not updating * Fix: Error while deactivating or switching Elementor account = 1.2.1 - 2024-02-28 = * Fix: Image optimization stats not loading * Tweak: Added notice regarding extended bulk optimization not affecting user's website = 1.2.0 - 2024-02-19 = * Tweak: Reduced status checks for better performance * Tweak: Improved Elementor support by removing cached thumbnails * Tweak: Added DB version check during activation to prevent requirement conflicts * Fix: Optimization failed with numerous errors * Fix: Bulk Optimization stopped with an Invalid WordPress image meta error * Fix: Avoid optimizing too large image files as part of bulk optimization * Fix: Added RTL support for plugin settings page = 1.1.0 - 2024-02-06 = * Tweak: Design for quota reached in top bar * Tweak: Refresh bulk token if the current one is expired * Tweak: Rename all plugin assets, namespace and text-domain to image-optimization * Tweak: Replace hardcoded references in posts content when updating image type * Tweak: Added file checksum validation before updating an image * Tweak: Avoid overriding existing images with identical file names * Fix: Columns are not distributed properly on bulk optimization screen * Fix: Incorrect behavior when trying to optimize without enough credits * Fix: File is missing Error incorrectly shown * Fix: Clear local data on disconnect * Fix: Optimization error with broken image = 1.0.2 - 2024-01-16 = * Tweak: Added tooltip to explain compression level in settings * Tweak: Added failure notice when trying to activate the plugin without meeting requirements * Fix: Usage progress bar filling incorrectly = 1.0.1 - 2024-01-10 = * Tweak: Quota reached user notification messaging * Tweak: Add Bulk Optimize success message * Tweak: Add progress percentage number below the bulk optimization progress bar * Fix: Top bar "Try again" option with error doesn't work = 1.0.0 - 2024-01-08 = * Initial release modules/core/module.php 0000644 00000021076 14720461212 0011147 0 ustar 00 <?php namespace ImageOptimization\Modules\Core; use ImageOptimization\Modules\Optimization\{ Rest\Cancel_Bulk_Optimization, Rest\Optimize_Bulk, }; use ImageOptimization\Modules\Backups\Rest\{ Restore_All, Remove_Backups, }; use ImageOptimization\Classes\{ Migration\Migration_Manager, Module_Base, Utils }; use ImageOptimization\Plugin; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Module extends Module_Base { public function get_name(): string { return 'core'; } public static function component_list() : array { return [ 'Pointers', 'Migrations', 'Conflicts', 'User_Feedback', 'Not_Connected', ]; } private function render_top_bar() { ?> <div id="image-optimization-top-bar"></div> <?php } private function render_app() { ?> <div class="clear"></div> <div id="image-optimization-app"></div> <?php } public function maybe_add_quota_reached_notice() { // @var ImageOptimizer/Modules/ConnectManager/Module $module = Plugin::instance()->modules_manager->get_modules( 'connect-manager' ); if ( ! $module->connect_instance->get_connect_status() || $module->connect_instance->images_left() > 0 ) { return; } ?> <div class="notice notice-warning notice image-optimizer__notice image-optimizer__notice--warning"> <p> <b> <?php esc_html_e( 'You’ve reached your plan quota.', 'image-optimization' ); ?> </b> <span> <?php esc_html_e( 'You have no images left to optimize in your current plan.', 'image-optimization' ); ?> <a href="https://go.elementor.com/io-quota-upgrade/"> <?php esc_html_e( 'Upgrade plan now', 'image-optimization' ); ?> </a> </span> </p> </div> <?php } public function maybe_add_url_mismatch_notice() { // @var ImageOptimizer/Modules/ConnectManager/Module $module = Plugin::instance()->modules_manager->get_modules( 'connect-manager' ); if ( $module->connect_instance->is_valid_home_url() ) { return; } ?> <div class="notice notice-error notice image-optimizer__notice image-optimizer__notice--error"> <p> <b> <?php esc_html_e( 'Your license key does not match your current domain, causing a mismatch.', 'image-optimization' ); ?> </b> <span> <?php esc_html_e( 'This is most likely due to a change in the domain URL of your site (including HTTP/SSL migration).', 'image-optimization' ); ?> <button type="button" onclick="document.dispatchEvent( new Event( 'image-optimizer/auth/url-mismatch-modal/open' ) );"> <?php esc_html_e( 'Fix mismatched URL', 'image-optimization' ); ?> </button> </span> </p> </div> <?php } public function add_plugin_links( $links, $plugin_file_name ): array { if ( ! str_ends_with( $plugin_file_name, '/image-optimization.php' ) ) { return (array) $links; } $custom_links = [ 'settings' => sprintf( '<a href="%s">%s</a>', admin_url( 'admin.php?page=' . \ImageOptimization\Modules\Settings\Module::SETTING_BASE_SLUG ), esc_html__( 'Settings', 'image-optimization' ) ), ]; // @var ImageOptimizer/Modules/ConnectManager/Module $module = Plugin::instance()->modules_manager->get_modules( 'connect-manager' ); if ( $module->connect_instance->is_connected() ) { $custom_links['upgrade'] = sprintf( '<a href="%s" style="color: #524CFF; font-weight: 700;" target="_blank" rel="noopener noreferrer">%s</a>', 'https://go.elementor.com/io-plugins-upgrade/', esc_html__( 'Upgrade', 'image-optimization' ) ); } else { $custom_links['connect'] = sprintf( '<a href="%s" style="color: #524CFF; font-weight: 700;">%s</a>', admin_url( 'admin.php?page=' . \ImageOptimization\Modules\Settings\Module::SETTING_BASE_SLUG ), esc_html__( 'Connect', 'image-optimization' ) ); } return array_merge( $custom_links, $links ); } public function enqueue_global_assets() { wp_enqueue_style( 'image-optimization-admin-fonts', 'https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap', [], IMAGE_OPTIMIZATION_VERSION ); wp_enqueue_style( 'image-optimization-core-style-admin', $this->get_css_assets_url( 'style-admin', 'assets/build/' ), [], IMAGE_OPTIMIZATION_VERSION, ); } /** * Enqueue styles and scripts */ private function enqueue_scripts() { $asset_file = require IMAGE_OPTIMIZATION_ASSETS_PATH . 'build/admin.asset.php'; foreach ( $asset_file['dependencies'] as $style ) { wp_enqueue_style( $style ); } wp_enqueue_script( 'image-optimization-admin', $this->get_js_assets_url( 'admin' ), array_merge( $asset_file['dependencies'], [ 'wp-util' ] ), $asset_file['version'], true ); wp_localize_script( 'image-optimization-admin', 'imageOptimizerAppSettings', [ 'siteUrl' => wp_parse_url( get_site_url(), PHP_URL_HOST ), 'thumbnailSizes' => wp_get_registered_image_subsizes(), 'isDevelopment' => defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG, ] ); /** * @var ImageOptimizer\Modules\ConnectManager\Module $module */ $module = Plugin::instance()->modules_manager->get_modules( 'connect-manager' ); $is_connect_on_fly = $module->connect_instance->get_is_connect_on_fly(); $connect_email = $module->connect_instance->get_connect_data()['user']['email'] ?? null; $show_reset = ! $module->connect_instance->is_connected() && ( $module->connect_instance->get_client_id() || $module->connect_instance->get_client_secret() ); wp_localize_script( 'image-optimization-admin', 'imageOptimizerUserData', [ 'isConnectOnFly' => $is_connect_on_fly, 'isConnected' => $module->connect_instance->is_connected(), 'isActivated' => $module->connect_instance->is_activated(), 'isUrlMismatch' => ! $module->connect_instance->is_valid_home_url(), 'planData' => $module->connect_instance->is_activated() ? $module->connect_instance->get_connect_status() : null, 'licenseKey' => $module->connect_instance->is_activated() ? $module->connect_instance->get_activation_state() : null, 'imagesLeft' => $module->connect_instance->is_activated() ? $module->connect_instance->images_left() : null, 'isOwner' => $module->connect_instance->is_connected() ? $module->connect_instance->user_is_subscription_owner() : null, 'subscriptionEmail' => $connect_email ? $connect_email : null, 'showResetButton' => $show_reset, 'wpRestNonce' => wp_create_nonce( 'wp_rest' ), 'disconnect' => wp_create_nonce( 'wp_rest' ), 'authInitNonce' => wp_create_nonce( $module->connect_instance->connect_init_nonce() ), 'authDisconnectNonce' => wp_create_nonce( $module->connect_instance->disconnect_nonce() ), 'authDeactivateNonce' => wp_create_nonce( $module->connect_instance->deactivate_nonce() ), 'authGetSubscriptionsNonce' => wp_create_nonce( $module->connect_instance->get_subscriptions_nonce() ), 'authActivateNonce' => wp_create_nonce( $module->connect_instance->activate_nonce() ), 'versionNonce' => wp_create_nonce( $module->connect_instance->version_nonce() ), 'removeBackupsNonce' => wp_create_nonce( Remove_Backups::NONCE_NAME ), 'restoreAllImagesNonce' => wp_create_nonce( Restore_All::NONCE_NAME ), 'optimizeBulkNonce' => wp_create_nonce( Optimize_Bulk::NONCE_NAME ), 'cancelBulkOptimizationNonce' => wp_create_nonce( Cancel_Bulk_Optimization::NONCE_NAME ), ] ); wp_set_script_translations( 'image-optimization-admin', 'image-optimization' ); } private function should_render(): bool { return ( Utils::is_media_page() || Utils::is_plugin_page() ) && Utils::user_is_admin(); } /** * Module constructor. */ public function __construct() { $this->register_components(); add_action( 'action_scheduler_init', [ Migration_Manager::class, 'init' ] ); add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_global_assets' ] ); add_filter( 'plugin_action_links', [ $this, 'add_plugin_links' ], 10, 2 ); add_action('current_screen', function () { if ( ! $this->should_render() ) { return; } add_action( 'admin_notices', [ $this, 'maybe_add_quota_reached_notice' ] ); add_action( 'admin_notices', [ $this, 'maybe_add_url_mismatch_notice' ] ); if ( Utils::is_media_page() ) { add_action('in_admin_header', function () { $this->render_top_bar(); }); add_action('all_admin_notices', function () { $this->render_app(); }); } if ( Utils::is_plugin_page() ) { add_action('in_admin_header', function () { $this->render_top_bar(); }); } add_action('admin_enqueue_scripts', function () { $this->enqueue_scripts(); }); }); } } modules/core/components/conflicts.php 0000644 00000005523 14720461212 0014032 0 ustar 00 <?php namespace ImageOptimization\Modules\Core\Components; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Conflicts { private array $conflicting_plugins; private const CONFLICTING_PLUGINS = [ 'imagify/imagify.php' => 'Imagify', 'optimole-wp/optimole-wp.php' => 'Image optimization service by Optimole', 'ewww-image-optimizer/ewww-image-optimizer.php' => 'EWWW Image Optimizer', 'ewww-image-optimizer-cloud/ewww-image-optimizer-cloud.php' => 'EWWW Image Optimizer Cloud', 'kraken-image-optimizer/kraken.php' => 'Kraken Image Optimizer', 'shortpixel-image-optimiser/wp-shortpixel.php' => 'ShortPixel Image Optimizer', 'wp-smushit/wp-smush.php' => 'Smush', 'wp-smush-pro/wp-smush.php' => 'Smush PRO', 'tiny-compress-images/tiny-compress-images.php' => 'TinyPNG - JPEG, PNG & WebP image compression', ]; public function render_notice(): void { $conflicting_plugins_names = $this->conflicting_plugins; ?> <div class="notice notice-warning image-optimizer__notice image-optimizer__notice--warning"> <p> <b> <?php esc_html_e( 'Image optimizer has detected multiple active image optimization plugins.', 'image-optimization' ); ?> </b> <span> <?php esc_html_e( 'Having more than one may result in unexpected results.', 'image-optimization' ); ?> </span> </p> <form action="<?php echo esc_url( admin_url( 'plugins.php' ) ); ?>" method="post" style="margin:0.5em 0;padding:2px"> <span style="margin-inline-end: 8px;"><?php echo esc_html( join( ', ', $conflicting_plugins_names ) ); ?></span> <input type="hidden" name="action" value="deactivate-selected"> <?php foreach ( array_keys( $this->conflicting_plugins ) as $plugin ) { ?> <input type="hidden" name="checked[]" value="<?php echo esc_attr( $plugin ); ?>"> <?php } ?> <input type="hidden" name="_wpnonce" value="<?php echo esc_attr( wp_create_nonce( 'bulk-plugins' ) ); ?>"> <input type="submit" style="border:none;background-color:transparent;text-decoration:underline;cursor:pointer;font-size:13px;color:#135e96;" value="<?php esc_html_e( 'Deactivate All', 'image-optimization' ); ?>"> </form> </div> <?php } public function get_conflicting_plugins(): array { $plugins = get_option( 'active_plugins' ); $conflicting_plugins_file_names = array_keys( self::CONFLICTING_PLUGINS ); $output = []; foreach ( $plugins as $plugin_file_name ) { if ( in_array( $plugin_file_name, $conflicting_plugins_file_names, true ) ) { $output[ $plugin_file_name ] = self::CONFLICTING_PLUGINS[ $plugin_file_name ]; } } return $output; } public function __construct() { $this->conflicting_plugins = $this->get_conflicting_plugins(); if ( ! empty( $this->conflicting_plugins ) ) { add_action( 'admin_notices', [ $this, 'render_notice' ] ); } } } modules/core/components/pointers.php 0000644 00000002625 14720461212 0013711 0 ustar 00 <?php namespace ImageOptimization\Modules\Core\Components; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Pointers { const DISMISSED_POINTERS_META_KEY = 'image_optimizer_dismissed_pointers'; public function dismiss_pointers() { if ( empty( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'image-optimization-pointer-dismissed' ) ) { wp_send_json_error( [ 'message' => 'Invalid nonce' ] ); } $pointer = sanitize_text_field( $_POST['data']['pointer'] ) ?? null; if ( empty( $pointer ) ) { wp_send_json_error( [ 'message' => 'The pointer id must be provided' ] ); } $pointer = explode( ',', $pointer ); $user_dismissed_meta = get_user_meta( get_current_user_id(), self::DISMISSED_POINTERS_META_KEY, true ); if ( ! $user_dismissed_meta ) { $user_dismissed_meta = []; } foreach ( $pointer as $item ) { $user_dismissed_meta[ $item ] = true; } update_user_meta( get_current_user_id(), self::DISMISSED_POINTERS_META_KEY, $user_dismissed_meta ); wp_send_json_success( [] ); } public static function is_dismissed( string $slug ): bool { $meta = (array) get_user_meta( get_current_user_id(), self::DISMISSED_POINTERS_META_KEY, true ); return key_exists( $slug, $meta ); } public function __construct() { add_action( 'wp_ajax_image_optimizer_pointer_dismissed', [ $this, 'dismiss_pointers' ] ); } } modules/core/components/not-connected.php 0000644 00000007555 14720461212 0014615 0 ustar 00 <?php namespace ImageOptimization\Modules\Core\Components; use ImageOptimization\Classes\Image\Image_Query_Builder; use ImageOptimization\Classes\Utils; use ImageOptimization\Plugin; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Not_Connected { const NOT_CONNECTED_NOTICE_SLUG = 'image-optimizer-not-connected'; public function render_not_connected_notice() { if ( Pointers::is_dismissed( self::NOT_CONNECTED_NOTICE_SLUG ) ) { return; } ?> <div class="notice notice-info notice is-dismissible image-optimizer__notice image-optimizer__notice--pink" data-notice-slug="<?php echo esc_attr( self::NOT_CONNECTED_NOTICE_SLUG ); ?>"> <div class="image-optimizer__icon-block"> <svg width="32" height="32" fill="none" role="presentation"> <rect width="32" height="32" fill="#FF7BE5" rx="16"/> <path fill="#fff" d="M10.508 4.135a.125.125 0 0 0-.236 0l-1.183 3.42a.125.125 0 0 1-.078.078L5.553 8.8a.125.125 0 0 0 0 .237l3.458 1.166a.125.125 0 0 1 .078.078l1.183 3.42a.125.125 0 0 0 .236 0l1.182-3.42a.125.125 0 0 1 .078-.078l3.458-1.166a.125.125 0 0 0 0-.237l-3.458-1.167a.125.125 0 0 1-.078-.077l-1.182-3.421ZM17.425 12.738v3.683l-4.073 4.582L26.495 9.598a.125.125 0 0 1 .207.094v14.851a.125.125 0 0 1-.125.125H5.874a.125.125 0 0 1-.09-.212l11.427-11.805a.125.125 0 0 1 .214.087Z"/> </svg> </div> <p> <b> <?php esc_html_e( 'Image Optimizer is not connected right now. To start optimizing your images, please connect your account.', 'image-optimization' ); ?> </b> <span> <a href="<?php echo admin_url( 'admin.php?page=' . \ImageOptimization\Modules\Settings\Module::SETTING_BASE_SLUG . '&action=connect' ); ?>"> <?php esc_html_e( 'Connect now', 'image-optimization' ); ?> </a> </span> </p> </div> <script> const onNotConnectedNoticeClose = () => { const pointer = '<?php echo esc_js( self::NOT_CONNECTED_NOTICE_SLUG ); ?>'; return wp.ajax.post( 'image_optimizer_pointer_dismissed', { data: { pointer, }, nonce: '<?php echo esc_js( wp_create_nonce( 'image-optimization-pointer-dismissed' ) ); ?>', } ); } jQuery( document ).ready( function( $ ) { setTimeout(() => { const $closeButton = $( '[data-notice-slug="<?php echo esc_js( self::NOT_CONNECTED_NOTICE_SLUG ); ?>"] .notice-dismiss' ) $closeButton .first() .on( 'click', onNotConnectedNoticeClose ) $( '[data-notice-slug="<?php echo esc_js( self::NOT_CONNECTED_NOTICE_SLUG ); ?>"] a' ) .first() .on( 'click', function ( e ) { e.preventDefault(); onNotConnectedNoticeClose().promise().done(() => { window.open( $( this ).attr( 'href' ), '_blank' ).focus(); $closeButton.click(); }); }) }, 0); } ); </script> <?php } public function add_media_menu_badge( $parent_file ) { global $menu; foreach ( $menu as &$item ) { if ( 'upload.php' === $item[2] ) { $item[0] .= ' <span class="update-plugins count-1"><span class="plugin-count">1</span></span>'; break; } } return $parent_file; } public function __construct() { add_action('current_screen', function () { if ( ! Utils::user_is_admin() ) { return; } // @var ImageOptimizer/Modules/ConnectManager/Module $module = Plugin::instance()->modules_manager->get_modules( 'connect-manager' ); if ( $module->connect_instance->is_connected() || ! $module->connect_instance->is_valid_home_url() ) { return; } add_filter( 'parent_file', [ $this, 'add_media_menu_badge' ] ); if ( Utils::is_media_page() || Utils::is_plugin_page() || Utils::is_single_attachment_page() || Utils::is_media_upload_page() || Utils::is_wp_dashboard_page() || Utils::is_wp_updates_page() ) { add_action( 'admin_notices', [ $this, 'render_not_connected_notice' ] ); } }); } } modules/core/components/migrations.php 0000644 00000003003 14720461212 0014211 0 ustar 00 <?php namespace ImageOptimization\Modules\Core\Components; use ImageOptimization\Classes\Async_Operation\Async_Operation_Hook; use ImageOptimization\Classes\Logger; use ImageOptimization\Classes\Migration\{ Migration_Manager, Migration_Meta, }; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Migrations { /** * @async * @param string $migration_name * * @return bool */ public function run_migration( string $migration_name ): bool { $migration_class = Migration_Manager::get_migration( $migration_name ); if ( ! $migration_class ) { Logger::log( Logger::LEVEL_ERROR, "Migration class for `$migration_name` does not exist." ); return false; } if ( ! method_exists( $migration_class, 'run' ) || ! is_callable( [ $migration_class, 'run' ] ) ) { Logger::log( Logger::LEVEL_ERROR, "The run method does not exist or is not static in the class `$migration_class`." ); return false; } try { $migration_class::run(); ( new Migration_Meta() ) ->add_migration_passed( $migration_name ) ->save(); Logger::log( Logger::LEVEL_INFO, "The migration `$migration_name` successfully executed." ); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, "Error while running the migration `$migration_name`: " . $t->getMessage() ); return false; } return true; } public function __construct() { add_action( Async_Operation_Hook::DB_MIGRATION, [ $this, 'run_migration' ] ); } } modules/core/components/user-feedback.php 0000644 00000016701 14720461212 0014546 0 ustar 00 <?php namespace ImageOptimization\Modules\Core\Components; use ImageOptimization\Classes\Image\Image_Query_Builder; use ImageOptimization\Classes\Utils; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class User_Feedback { public const NOTICE_FEEDBACK_LINK = 'https://go.elementor.com/io-wp-dash-notice-review'; public const FOOTER_FEEDBACK_LINK = 'https://go.elementor.com/io-wp-dash-footer-review'; private const FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG = 'image-optimizer-first-image-optimized-feedback'; private const THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG = 'image-optimizer-third-images-optimized-feedback'; /** * Checks if the notice after the first optimization should be rendered. * * @param bool $check_location * * @return bool */ public function should_render_first_optimized_notice( bool $check_location = true ): bool { if ( Pointers::is_dismissed( self::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG ) ) { return false; } $is_wrong_page = ( ! Utils::is_media_page() && ! Utils::is_plugin_page() && ! Utils::is_single_attachment_page() ) || Utils::is_plugin_settings_page(); if ( $check_location && $is_wrong_page ) { return false; } $optimized_image_query = ( new Image_Query_Builder() ) ->return_optimized_images() ->set_paging_size( 1 ) ->execute(); if ( ! $optimized_image_query->post_count ) { return false; } return true; } /** * Checks if the notice should be rendered after the one third of images were optimized. * * @param bool $check_location * * @return bool */ public function should_render_third_optimized_notice( bool $check_location = true ): bool { if ( Pointers::is_dismissed( self::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ) ) { return false; } if ( $check_location && ! Utils::is_plugin_settings_page() ) { return false; } $images_query = ( new Image_Query_Builder() ) ->execute(); $optimized_images_query = ( new Image_Query_Builder() ) ->return_optimized_images() ->execute(); if ( ! $optimized_images_query->post_count ) { return false; } $optimized_percentage = round( $optimized_images_query->post_count / $images_query->post_count * 100 ); if ( $optimized_percentage < 33.33 ) { return false; } return true; } /** * Renders the notice after the first optimization. * * @return void */ public function render_first_optimized_notice() { ?> <div class="notice is-dismissible notice-success notice image-optimizer__notice image-optimizer__notice--success image-optimizer__notice--feedback" data-notice-slug="<?php echo esc_attr( self::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG ); ?>"> <p> <b> <?php esc_html_e( 'Your image has been optimized!', 'image-optimization' ); ?> </b> <span> <?php printf( __( 'If you enjoyed using Image Optimizer, consider leaving a <a href="%1$s" aria-label="%2$s" target="_blank" rel="noopener noreferrer">★★★★★</a> review to spread the word.', 'image-optimization' ), esc_url( self::NOTICE_FEEDBACK_LINK ), esc_attr__( 'Five stars', 'image-optimization' ) ); ?> </span> </p> </div> <script> const onClose = () => { const pointer = '<?php echo $this->should_render_third_optimized_notice( false ) ? esc_js( join( ',', [ static::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG, static::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ] ) ) : esc_js( static::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG ) ?>'; return wp.ajax.post( 'image_optimizer_pointer_dismissed', { data: { pointer, }, nonce: '<?php echo esc_js( wp_create_nonce( 'image-optimization-pointer-dismissed' ) ); ?>', } ); } jQuery( document ).ready( function( $ ) { setTimeout(() => { const $closeButton = $( '[data-notice-slug="<?php echo esc_js( self::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG ); ?>"] .notice-dismiss' ) $closeButton .first() .on( 'click', onClose ) $( '[data-notice-slug="<?php echo esc_js( self::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG ); ?>"] a' ) .first() .on( 'click', function ( e ) { e.preventDefault(); onClose().promise().done(() => { window.open( $( this ).attr( 'href' ), '_blank' ).focus(); $closeButton.click(); }); }) }, 0); } ); </script> <?php } /** * Renders the notice after the one third of images were optimized. * * @return void */ public function render_third_optimized_notice() { ?> <div class="notice is-dismissible notice-success notice image-optimizer__notice image-optimizer__notice--success image-optimizer__notice--feedback" data-notice-slug="<?php echo esc_attr( self::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ); ?>"> <p> <b> <?php esc_html_e( 'Thanks for using Image Optimizer!', 'image-optimization' ); ?> </b> <span> <?php printf( __( 'If you\'ve enjoyed it, consider leaving a <a href="%1$s" aria-label="%2$s" target="_blank" rel="noopener noreferrer">★★★★★</a> review to spread the word.', 'image-optimization' ), esc_url( self::NOTICE_FEEDBACK_LINK ), esc_attr__( 'Five stars', 'image-optimization' ) ); ?> </span> </p> </div> <script> const onClose = () => { const pointer = '<?php echo $this->should_render_first_optimized_notice( false ) ? esc_js( join( ',', [ static::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG, static::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ] ) ) : esc_js( static::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ) ?>'; return wp.ajax.post( 'image_optimizer_pointer_dismissed', { data: { pointer, }, nonce: '<?php echo esc_js( wp_create_nonce( 'image-optimization-pointer-dismissed' ) ); ?>', } ); } jQuery( document ).ready( function( $ ) { setTimeout(() => { const $closeButton = $( '[data-notice-slug="<?php echo esc_js( self::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ); ?>"] .notice-dismiss' ); $closeButton .first() .on( 'click', onClose) $( '[data-notice-slug="<?php echo esc_js( self::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ); ?>"] a' ) .first() .on( 'click', function ( e ) { e.preventDefault(); onClose().promise().done(() => { window.open( $( this ).attr( 'href' ), '_blank' ).focus(); $closeButton.click(); }); }) }, 0); } ); </script> <?php } /** * Renders the admin footer feedback notice. * * @return void */ public function add_leave_feedback_footer_text(): void { printf( __( '<b>Found Image Optimizer helpful?</b> Leave us a <a href="%1$s" aria-label="%2$s" target="_blank" rel="noopener noreferrer">★★★★★</a> rating!', 'image-optimization' ), esc_url( self::FOOTER_FEEDBACK_LINK ), esc_attr__( 'Five stars', 'image-optimization' ) ); } public function __construct() { add_action('current_screen', function () { if ( ! Utils::user_is_admin() ) { return; } if ( $this->should_render_first_optimized_notice() ) { add_action( 'admin_notices', [ $this, 'render_first_optimized_notice' ] ); } if ( $this->should_render_third_optimized_notice() ) { add_action( 'admin_notices', [ $this, 'render_third_optimized_notice' ] ); } if ( Utils::is_media_page() || Utils::is_plugin_page() || Utils::is_single_attachment_page() ) { add_filter( 'admin_footer_text', [ $this, 'add_leave_feedback_footer_text' ] ); } }); } } modules/connect-manager/classes/connect-runner.php 0000644 00000004375 14720461212 0016373 0 ustar 00 <?php namespace ImageOptimization\Modules\ConnectManager\Classes; use ImageOptimization\Modules\ConnectManager\Components\Connect_Interface; if ( ! defined( 'ABSPATH' ) ) { exit; // exit if accessed directly } class Connect_Runner { public $connect; public function __construct( Connect_Interface $connect ) { $this->connect = $connect; } public function is_connected() { return $this->connect->is_connected(); } public function is_activated() : bool { return $this->connect->is_activated(); } public function is_valid_home_url() : bool { return $this->connect->is_valid_home_url(); } public function get_connect_status() { return $this->connect->get_connect_status(); } public function get_connect_data( bool $force = false ): array { return $this->connect->get_connect_data( $force ); } public function update_usage_data( $new_usage_data ): void { $this->connect->update_usage_data( $new_usage_data ); } public function get_activation_state() : string { return $this->connect->get_activation_state(); } public function get_access_token() { return $this->connect->get_access_token(); } public function get_client_id(): string { return $this->connect->get_client_id(); } public function get_client_secret(): string { return $this->connect->get_client_secret(); } public function images_left(): int { return $this->connect->images_left(); } public function user_is_subscription_owner(): bool { return $this->connect->user_is_subscription_owner(); } // Legacy Nonces. public function connect_init_nonce(): string { return $this->connect->connect_init_nonce(); } public function disconnect_nonce(): string { return $this->connect->disconnect_nonce(); } public function deactivate_nonce(): string { return $this->connect->deactivate_nonce(); } public function get_subscriptions_nonce(): string { return $this->connect->get_subscriptions_nonce(); } public function activate_nonce(): string { return $this->connect->activate_nonce(); } public function version_nonce(): string { return $this->connect->version_nonce(); } public function get_is_connect_on_fly(): bool { return $this->connect->get_is_connect_on_fly(); } public function refresh_token(): void { $this->connect->refresh_token(); } } modules/connect-manager/module.php 0000644 00000003040 14720461212 0013247 0 ustar 00 <?php namespace ImageOptimization\Modules\ConnectManager; use ImageOptimization; use ImageOptimization\Classes\{ Module_Base, }; use ImageOptimization\Modules\ConnectManager\Classes\Connect_Runner; use ImageOptimization\Modules\ConnectManager\Components\Legacy_Connect; use ImageOptimization\Modules\ConnectManager\Components\Connect; use ImageOptimization\Plugin; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Module */ class Module extends Module_Base { /** * Connect instance * * @var connect_instance */ public $connect_instance; /** * Get module name. * Retrieve the module name. * @access public * @return string Module name. */ public function get_name() { return 'connect-manager'; } /** * component_list * @return string[] */ public static function component_list() : array { return [ 'Legacy_Connect', 'Connect', ]; } public function __construct() { // Register components. $this->register_components(); // Load Connect Manager. add_action( 'plugins_loaded', [ $this, 'load_connect_manager' ] ); } /** * Load Connect Manager * * Load the correct version of Connect Manager based on whether * the user is already connected using legacy version or not. * * @return void */ public function load_connect_manager() { if ( ImageOptimization\Modules\Connect\Module::is_active() ) { $this->connect_instance = new Connect_Runner( new Connect() ); } else { $this->connect_instance = new Connect_Runner( new Legacy_Connect() ); } } } modules/connect-manager/components/connect.php 0000644 00000010110 14720461212 0015574 0 ustar 00 <?php namespace ImageOptimization\Modules\ConnectManager\Components; use ImageOptimization\Modules\Connect\{ Module as ConnectModule, Classes\Data, Classes\Service, Classes\Utils as ConnectUtils, Rest\Authorize, Rest\Version }; use ImageOptimization\Classes\Logger; use ImageOptimization\Classes\Utils; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // exit if accessed directly } class Connect implements Connect_Interface { const STATUS_CHECK_TRANSIENT = 'image_optimizer_status_check'; public function is_connected() : bool { return ConnectModule::is_connected(); } public function is_activated() : bool { return ConnectModule::is_connected(); } public function is_valid_home_url() : bool { return ConnectUtils::is_valid_home_url(); } public function get_connect_status() { if ( ! $this->is_connected() ) { Logger::log( Logger::LEVEL_INFO, 'Status check error. Reason: User is not connected' ); return null; } $cached_status = get_transient( self::STATUS_CHECK_TRANSIENT ); if ( $cached_status ) { return $cached_status; } try { $response = Utils::get_api_client()->make_request( 'POST', 'status/check' ); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Status check error. Reason: ' . $t->getMessage() ); return null; } if ( ! isset( $response->status ) ) { Logger::log( Logger::LEVEL_ERROR, 'Invalid response from server' ); return null; } if ( ! empty( $response->site_url ) && Data::get_home_url() !== $response->site_url ) { Data::set_home_url( $response->site_url ); } set_transient( self::STATUS_CHECK_TRANSIENT, $response, MINUTE_IN_SECONDS * 5 ); return $response; } public function get_connect_data( bool $force = false ): array { $data = get_transient( self::STATUS_CHECK_TRANSIENT ); $user = []; // Return empty array if transient does not exist or is expired. if ( ! $data ) { return $user; } // Return if user property does not exist in the data object. if ( ! property_exists( $data, 'user' ) ) { return $user; } if ( $data->user->email ) { $user = [ 'user' => [ 'email' => $data->user->email, ], ]; } return $user; } public function update_usage_data( $new_usage_data ): void { $connect_status = $this->get_connect_status(); if ( ! isset( $new_usage_data->allowed ) || ! isset( $new_usage_data->used ) ) { return; } if ( 0 === $new_usage_data->allowed - $new_usage_data->used ) { $connect_status->status = 'expired'; } $connect_status->quota = $new_usage_data->allowed; $connect_status->used_quota = $new_usage_data->used; set_transient( self::STATUS_CHECK_TRANSIENT, $connect_status, MINUTE_IN_SECONDS * 5 ); } public function get_activation_state() : string { /** * Returning true because the license key is * not used for deactivation in connect. */ return true; } public function get_access_token() { return Data::get_access_token(); } public function get_client_id(): string { return Data::get_client_id(); } public function get_client_secret(): string { return Data::get_client_secret(); } public function images_left(): int { $plan_data = $this->get_connect_status(); if ( empty( $plan_data ) ) { return 0; } $quota = $plan_data->quota; $used_quota = $plan_data->used_quota; return max( $quota - $used_quota, 0 ); } public function user_is_subscription_owner(): bool { return Data::user_is_subscription_owner(); } // Nonces. public function connect_init_nonce(): string { return Authorize::NONCE_NAME; } public function disconnect_nonce(): string { return Authorize::NONCE_NAME; } public function deactivate_nonce(): string { return Authorize::NONCE_NAME; } public function get_subscriptions_nonce(): string { return Authorize::NONCE_NAME; } public function activate_nonce(): string { return Authorize::NONCE_NAME; } public function version_nonce(): string { return Version::NONCE_NAME; } public function get_is_connect_on_fly(): bool { return true; } public function refresh_token(): void { Service::refresh_token(); } } modules/connect-manager/components/legacy-connect.php 0000644 00000004105 14720461212 0017045 0 ustar 00 <?php namespace ImageOptimization\Modules\ConnectManager\Components; use ImageOptimization\Modules\Oauth\{ Components\Connect, Classes\Data, Rest\Activate, Rest\Connect_Init, Rest\Deactivate, Rest\Disconnect, Rest\Get_Subscriptions, Rest\Version, }; if ( ! defined( 'ABSPATH' ) ) { exit; // exit if accessed directly } class Legacy_Connect implements Connect_Interface { public function is_connected() : bool { return Connect::is_connected(); } public function is_activated() : bool { return Connect::is_activated(); } public function is_valid_home_url() : bool { return true; } public function get_connect_status() { return Connect::get_connect_status(); } public function get_connect_data( bool $force = false ): array { return Data::get_connect_data( $force ); } public function update_usage_data( $new_usage_data ): void { Connect::update_usage_data( $new_usage_data ); } public function get_activation_state() : string { return Data::get_activation_state(); } public function get_access_token() { return Data::get_access_token(); } public function get_client_id(): string { return Data::get_client_id(); } public function get_client_secret(): string { return Data::get_client_secret(); } public function images_left(): int { return Data::images_left(); } public function user_is_subscription_owner(): bool { return Data::user_is_subscription_owner(); } // Legacy Nonces. public function connect_init_nonce(): string { return Connect_Init::NONCE_NAME; } public function disconnect_nonce(): string { return Disconnect::NONCE_NAME; } public function deactivate_nonce(): string { return Deactivate::NONCE_NAME; } public function get_subscriptions_nonce(): string { return Get_Subscriptions::NONCE_NAME; } public function activate_nonce(): string { return Activate::NONCE_NAME; } public function version_nonce(): string { return Version::NONCE_NAME; } public function get_is_connect_on_fly(): bool { return false; } // Placeholder function for legacy connect. public function refresh_token(): void { } } modules/connect-manager/components/connect-interface.php 0000644 00000002156 14720461212 0017545 0 ustar 00 <?php namespace ImageOptimization\Modules\ConnectManager\Components; if ( ! defined( 'ABSPATH' ) ) { exit; // exit if accessed directly } interface Connect_Interface { // Connect. public function is_connected(): bool; public function is_activated() : bool; public function is_valid_home_url() : bool; public function get_connect_status(); public function get_connect_data( bool $force = false ): array; public function update_usage_data( $new_usage_data ): void; public function get_activation_state() : string; public function get_access_token(); public function get_client_id(): string; public function get_client_secret(): string; public function images_left(): int; public function user_is_subscription_owner(): bool; // Nonces. public function connect_init_nonce(): string; public function disconnect_nonce(): string; public function deactivate_nonce(): string; public function get_subscriptions_nonce(): string; public function activate_nonce(): string; public function version_nonce(): string; public function get_is_connect_on_fly(): bool; public function refresh_token(): void; } modules/stats/classes/route-base.php 0000644 00000001353 14720461212 0013567 0 ustar 00 <?php namespace ImageOptimization\Modules\Stats\Classes; use ImageOptimization\Classes\Route; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Route_Base extends Route { protected $auth = true; protected string $path = ''; public function get_methods(): array { return []; } public function get_endpoint(): string { return 'stats/' . $this->get_path(); } public function get_path(): string { return $this->path; } public function get_name(): string { return ''; } public function get_permission_callback( WP_REST_Request $request ): bool { $valid = $this->permission_callback( $request ); return $valid && user_can( $this->current_user_id, 'manage_options' ); } } modules/stats/classes/stats.php 0000644 00000007472 14720461212 0012667 0 ustar 00 <?php namespace ImageOptimization\Modules\Stats\Classes; use ImageOptimization\Classes\Async_Operation\{ Async_Operation, Async_Operation_Hook, Queries\Image_Optimization_Operation_Query, Queries\Operation_Query, }; use ImageOptimization\Classes\Image\Image_Query_Builder; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Stats { public static function calculate_global_stats(): array { $bulk_optimization_operation_status = self::get_bulk_optimization_status(); $bulk_optimization_operation_id = Async_Operation::OPERATION_STATUS_RUNNING === $bulk_optimization_operation_status ? self::get_bulk_optimization_active_operation_id() : null; return [ 'optimization_stats' => Optimization_Stats::get_image_stats(), 'bulk_optimization_status' => $bulk_optimization_operation_status, 'bulk_optimization_operation_id' => $bulk_optimization_operation_id, 'bulk_restoring_status' => self::get_bulk_restoring_status(), 'bulk_backup_removing_status' => self::get_bulk_backup_removing_status(), 'backups_exist' => self::backups_exist(), ]; } private static function get_bulk_optimization_status(): string { $active_query = ( new Image_Optimization_Operation_Query() ) ->set_hook( Async_Operation_Hook::OPTIMIZE_BULK ) ->set_status( [ Async_Operation::OPERATION_STATUS_PENDING, Async_Operation::OPERATION_STATUS_RUNNING, ] ) ->set_limit( 1 ); $active_operations = Async_Operation::get( $active_query ); if ( empty( $active_operations ) ) { return Async_Operation::OPERATION_STATUS_NOT_STARTED; } $operation_id = $active_operations[0]->get_args()['operation_id']; $cancelled_query = ( new Image_Optimization_Operation_Query() ) ->set_hook( Async_Operation_Hook::OPTIMIZE_BULK ) ->set_status( Async_Operation::OPERATION_STATUS_CANCELED ) ->set_bulk_operation_id( $operation_id ) ->set_limit( 1 ); $cancelled_operations = Async_Operation::get( $cancelled_query ); if ( ! empty( $cancelled_operations ) ) { return Async_Operation::OPERATION_STATUS_CANCELED; } return Async_Operation::OPERATION_STATUS_RUNNING; } private static function get_bulk_optimization_active_operation_id(): ?string { $active_query = ( new Image_Optimization_Operation_Query() ) ->set_hook( Async_Operation_Hook::OPTIMIZE_BULK ) ->set_status( [ Async_Operation::OPERATION_STATUS_PENDING, Async_Operation::OPERATION_STATUS_RUNNING, ] ) ->set_limit( 1 ); $active_operation = Async_Operation::get( $active_query ); if ( empty( $active_operation ) ) { return null; } return $active_operation[0]->get_args()['operation_id']; } private static function get_bulk_restoring_status(): string { $active_query = ( new Operation_Query() ) ->set_hook( Async_Operation_Hook::RESTORE_MANY_IMAGES ) ->set_status( [ Async_Operation::OPERATION_STATUS_PENDING, Async_Operation::OPERATION_STATUS_RUNNING, ] ) ->set_limit( 1 ); $active_operations = Async_Operation::get( $active_query ); return ! empty( $active_operations ) ? Async_Operation::OPERATION_STATUS_RUNNING : Async_Operation::OPERATION_STATUS_NOT_STARTED; } private static function get_bulk_backup_removing_status(): string { $active_query = ( new Operation_Query() ) ->set_hook( Async_Operation_Hook::REMOVE_MANY_BACKUPS ) ->set_status( [ Async_Operation::OPERATION_STATUS_PENDING, Async_Operation::OPERATION_STATUS_RUNNING, ] ) ->set_limit( 1 ); $active_operations = Async_Operation::get( $active_query ); return ! empty( $active_operations ) ? Async_Operation::OPERATION_STATUS_RUNNING : Async_Operation::OPERATION_STATUS_NOT_STARTED; } private static function backups_exist(): bool { $query = ( new Image_Query_Builder() ) ->set_paging_size( 1 ) ->return_images_only_with_backups() ->execute(); return $query->post_count > 0; } } modules/stats/classes/optimization-stats.php 0000644 00000015337 14720461212 0015412 0 ustar 00 <?php namespace ImageOptimization\Modules\Stats\Classes; use ImageOptimization\Classes\Image\{ Image, Image_Meta, Image_Query_Builder, WP_Image_Meta, Exceptions\Invalid_Image_Exception }; use ImageOptimization\Classes\Async_Operation\{ Async_Operation, Async_Operation_Hook, Async_Operation_Queue, Exceptions\Async_Operation_Exception, Queries\Operation_Query, }; use ImageOptimization\Classes\File_System\{ Exceptions\File_System_Operation_Error, File_System, }; use ImageOptimization\Classes\Logger; use ImageOptimization\Modules\Optimization\Classes\Exceptions\Image_Validation_Error; use ImageOptimization\Modules\Optimization\Classes\Validate_Image; use ImageOptimization\Modules\Settings\Classes\Settings; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Optimization_Stats { const PAGING_SIZE = 25000; const STATS_CALCULATION_DELAY = 60 * 15; /** * Returns image stats. * If the library is too big, it queries images in chunks. * * @return array{total_image_count: int, optimized_image_count: int, current_image_size: int, initial_image_size: * int} */ public static function get_image_stats( ?int $image_id = null, ?bool $no_cache = false ): array { // No caching needed if we check a specific image. if ( $image_id ) { $output = self::get_image_stats_chunk( 1, $image_id ); unset( $output['pages'] ); return $output; } // Look at the stored data first. If it's still valid -- use it. $stats = self::get_stored_stats(); if ( ! $no_cache && ( time() - $stats['updated_at'] ) <= self::STATS_CALCULATION_DELAY ) { unset( $stats['updated_at'] ); return $stats; } // Otherwise, recalculate the stats. $output = self::get_image_stats_chunk( 1, $image_id ); $pages_count = $output['pages']; if ( $pages_count <= 1 ) { unset( $output['pages'] ); return $output; } if ( $pages_count > 1 && Async_Operation::OPERATION_STATUS_NOT_STARTED === self::get_stats_calculation_status() ) { try { Async_Operation::create( Async_Operation_Hook::CALCULATE_OPTIMIZATION_STATS, [ 'page' => 2, 'pages_count' => $pages_count, 'output' => $output, ], Async_Operation_Queue::STATS ); } catch ( Async_Operation_Exception $aoe ) { Logger::log( Logger::LEVEL_ERROR, 'Error while creating a stats calculation task: ' . $aoe->getMessage() ); } } unset( $stats['updated_at'] ); return $stats; } /** * @return array{pages: int, total_image_count: int, optimized_image_count: int, current_image_size: int, * initial_image_size: int} */ public static function get_image_stats_chunk( int $paged = 1, ?int $image_id = null ): array { $output = [ 'pages' => 1, 'total_image_count' => 0, 'optimized_image_count' => 0, 'current_image_size' => 0, 'initial_image_size' => 0, ]; $query = ( new Image_Query_Builder() ) ->set_paging_size( self::PAGING_SIZE ) ->set_current_page( $paged ); if ( $image_id ) { $query->set_image_ids( [ $image_id ] ); } $query = $query->execute(); $output['pages'] = (int) $query->max_num_pages; foreach ( $query->posts as $attachment_id ) { try { Validate_Image::is_valid( $attachment_id ); $wp_meta = new WP_Image_Meta( $attachment_id ); } catch ( Invalid_Image_Exception | Image_Validation_Error $ie ) { continue; } $meta = new Image_Meta( $attachment_id ); $image_sizes = $wp_meta->get_size_keys(); $current_sizes = self::filter_only_enabled_sizes( $image_sizes ); $optimized_sizes = self::filter_only_enabled_sizes( $meta->get_optimized_sizes() ); $output['total_image_count'] += count( $current_sizes ); $output['optimized_image_count'] += count( $optimized_sizes ); foreach ( $image_sizes as $image_size ) { $output['current_image_size'] += self::calculate_current_image_file_size( $attachment_id, $wp_meta, $image_size ); $output['initial_image_size'] += self::calculate_initial_image_file_size( $attachment_id, $meta, $wp_meta, $image_size ); } } return $output; } private static function calculate_current_image_file_size( int $image_id, WP_Image_Meta $wp_meta, string $image_size ): int { $size_from_meta = $wp_meta->get_file_size( $image_size ); if ( $size_from_meta ) { return $size_from_meta; } try { return File_System::size( ( new Image( $image_id ) )->get_file_path( $image_size ) ); } catch ( File_System_Operation_Error $e ) { return 0; } } private static function calculate_initial_image_file_size( int $image_id, Image_Meta $meta, WP_Image_Meta $wp_meta, string $image_size ): int { $size_from_meta = $meta->get_original_file_size( $image_size ) ?? $wp_meta->get_file_size( $image_size ); if ( $size_from_meta ) { return $size_from_meta; } try { return File_System::size( ( new Image( $image_id ) )->get_file_path( $image_size ) ); } catch ( File_System_Operation_Error $e ) { return 0; } } private static function filter_only_enabled_sizes( array $size_keys ): array { $enabled_sizes = Settings::get( Settings::CUSTOM_SIZES_OPTION_NAME ); if ( 'all' === $enabled_sizes ) { return array_filter( $size_keys, fn( string $size_key ) => ! str_starts_with( $size_key, 'elementor_' ) ); } return array_filter($size_keys, function( string $size ) use ( $enabled_sizes ) { if ( Image::SIZE_FULL === $size ) { return true; } if ( in_array( $size, $enabled_sizes, true ) ) { return true; } return false; }); } /** * Retrieves stats data. * * @return array{total_image_count: ?int, optimized_image_count: ?int, current_image_size: ?int, initial_image_size: * ?int, updated_at: ?int} */ public static function get_stored_stats(): array { $default = [ 'total_image_count' => null, 'optimized_image_count' => null, 'current_image_size' => null, 'initial_image_size' => null, 'updated_at' => null, ]; return json_decode( get_option( 'image_optimizer_optimization_stats', json_encode( $default ) ), ARRAY_A ); } /** * Updates the optimization stats with fresh values. * * @param array $stats * * @return bool */ public static function set_stored_stats( array $stats ) { $stats['updated_at'] = time(); return update_option( 'image_optimizer_optimization_stats', json_encode( $stats ) ); } private static function get_stats_calculation_status(): string { $active_query = ( new Operation_Query() ) ->set_hook( Async_Operation_Hook::CALCULATE_OPTIMIZATION_STATS ) ->set_status( [ Async_Operation::OPERATION_STATUS_PENDING, Async_Operation::OPERATION_STATUS_RUNNING, ] ) ->set_limit( 1 ); $active_operations = Async_Operation::get( $active_query ); return ! empty( $active_operations ) ? Async_Operation::OPERATION_STATUS_RUNNING : Async_Operation::OPERATION_STATUS_NOT_STARTED; } } modules/stats/rest/get-stats.php 0000644 00000001241 14720461212 0012750 0 ustar 00 <?php namespace ImageOptimization\Modules\Stats\Rest; use ImageOptimization\Modules\Stats\Classes\{ Route_Base, Stats }; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Get_Stats extends Route_Base { protected string $path = ''; public function get_name(): string { return 'get-stats'; } public function get_methods(): array { return [ 'GET' ]; } public function GET() { try { return $this->respond_success_json( Stats::calculate_global_stats() ); } catch ( Throwable $t ) { return $this->respond_error_json([ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ]); } } } modules/stats/module.php 0000644 00000001103 14720461212 0011342 0 ustar 00 <?php namespace ImageOptimization\Modules\Stats; use ImageOptimization\Classes\Module_Base; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Module extends Module_Base { public function get_name(): string { return 'stats'; } public static function component_list(): array { return [ 'Optimization_Stats_Handler', ]; } public static function routes_list() : array { return [ 'Get_Stats', ]; } /** * Module constructor. */ public function __construct() { $this->register_routes(); $this->register_components(); } } modules/stats/components/optimization-stats-handler.php 0000644 00000003001 14720461212 0017536 0 ustar 00 <?php namespace ImageOptimization\Modules\Stats\Components; use ImageOptimization\Classes\Async_Operation\{ Async_Operation, Async_Operation_Hook, Async_Operation_Queue, Exceptions\Async_Operation_Exception, }; use ImageOptimization\Classes\Logger; use ImageOptimization\Modules\Stats\Classes\Optimization_Stats; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Optimization_Stats_Handler { /** * @async * * @param $page * @param $pages_count * @param $output * * @return void */ public function handle_stats_chunk( $page, $pages_count, $output ) { $chunk = Optimization_Stats::get_image_stats_chunk( $page ); foreach ( array_keys( $chunk ) as $key ) { if ( isset( $output[ $key ] ) ) { $output[ $key ] += $chunk[ $key ]; continue; } $output[ $key ] = $chunk[ $key ]; } if ( $page < $pages_count ) { try { Async_Operation::create( Async_Operation_Hook::CALCULATE_OPTIMIZATION_STATS, [ 'page' => $page + 1, 'pages_count' => $pages_count, 'output' => $output, ], Async_Operation_Queue::STATS ); } catch ( Async_Operation_Exception $aoe ) { Logger::log( Logger::LEVEL_ERROR, 'Error while creating a stats calculation task: ' . $aoe->getMessage() ); } } else { unset( $output['pages'] ); Optimization_Stats::set_stored_stats( $output ); } } public function __construct() { add_action( Async_Operation_Hook::CALCULATE_OPTIMIZATION_STATS, [ $this, 'handle_stats_chunk' ], 10, 3 ); } } modules/optimization/classes/route-base.php 0000644 00000001574 14720461212 0015164 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes; use ImageOptimization\Classes\Route; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Route_Base extends Route { protected $auth = true; protected string $path = ''; public function get_methods(): array { return []; } public function get_endpoint(): string { return 'optimize/' . $this->get_path(); } public function get_path(): string { return $this->path; } public function get_name(): string { return ''; } public function post_permission_callback( WP_REST_Request $request ): bool { return $this->get_permission_callback( $request ); } public function get_permission_callback( WP_REST_Request $request ): bool { $valid = $this->permission_callback( $request ); return $valid && user_can( $this->current_user_id, 'manage_options' ); } } modules/optimization/classes/optimize-image.php 0000644 00000030626 14720461212 0016036 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes; use ImageOptimization\Classes\File_System\{ Exceptions\File_System_Operation_Error, File_System, }; use ImageOptimization\Classes\File_Utils; use ImageOptimization\Classes\Image\{ Exceptions\Image_Backup_Creation_Error, Exceptions\Invalid_Image_Exception, Image, Image_Backup, Image_Conversion, Image_DB_Update, Image_Dimensions, Image_Meta, Image_Status, WP_Image_Meta }; use ImageOptimization\Classes\Logger; use ImageOptimization\Classes\Utils; use ImageOptimization\Classes\Exceptions\Quota_Exceeded_Error; use ImageOptimization\Modules\Optimization\Classes\{ Exceptions\Image_File_Already_Exists_Error, Exceptions\Image_Optimization_Error, Exceptions\Bulk_Token_Expired_Error, Exceptions\Image_Already_Optimized_Error, }; use ImageOptimization\Modules\Settings\Classes\Settings; use Throwable; use ImageOptimization\Plugin; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } /** * The class is responsible for the optimization logic itself. It gets an image file, runs * backup process if needed, sends a file to the service, stores the result and updates image meta. * * This class is used by manual, bulk and on-upload optimization flows. */ class Optimize_Image { private const IMAGE_OPTIMIZE_ENDPOINT = 'image/optimize'; protected ?Image $image; protected WP_Image_Meta $wp_meta; protected string $initiator; protected ?string $bulk_token; private string $current_image_path; private string $current_image_size; private bool $keep_backups; private array $current_size_duplicates; protected Image_Conversion $image_conversion; private bool $is_reoptimize; /** * @throws Quota_Exceeded_Error|Bulk_Token_Expired_Error|Image_File_Already_Exists_Error|Image_Optimization_Error */ public function optimize(): void { $sizes_enabled = Settings::get( Settings::CUSTOM_SIZES_OPTION_NAME ); $sizes_exist = $this->wp_meta->get_size_keys(); Logger::log( Logger::LEVEL_INFO, "Start optimization of {$this->image->get_id()}" ); foreach ( $sizes_exist as $size_exist ) { // If some image sizes optimization is disabled in settings, we check if the current one is still enabled if ( 'all' !== $sizes_enabled && Image::SIZE_FULL !== $size_exist && ! in_array( $size_exist, $sizes_enabled, true ) ) { continue; } // Elementor editor generates thumbnails we don't need to optimize. if ( str_starts_with( $size_exist, 'elementor_' ) ) { continue; } $image_meta = new Image_Meta( $this->image->get_id() ); // If the current size was already optimized -- ignore it. if ( ! $this->is_reoptimize && in_array( $size_exist, $image_meta->get_optimized_sizes(), true ) ) { Logger::log( Logger::LEVEL_INFO, "Size `$size_exist` is already optimized" ); continue; } if ( ! file_exists( $this->image->get_file_path( $size_exist ) ) ) { Logger::log( Logger::LEVEL_ERROR, "Can't access file for size `$size_exist`" ); throw new Image_Optimization_Error( esc_html__( 'File is missing. Verify the upload', 'image-optimization' ) ); } $this->current_image_size = $size_exist; $this->current_size_duplicates = $this->wp_meta->get_size_duplicates( $size_exist ); $this->current_image_path = $this->image->get_file_path( $size_exist ); $this->optimize_current_size(); $this->current_image_size = ''; $this->current_size_duplicates = []; $this->current_image_path = ''; } $this->mark_as_optimized(); if ( ! $this->keep_backups ) { Image_Backup::remove( $this->image->get_id() ); } Logger::log( Logger::LEVEL_INFO, "End optimization of {$this->image->get_id()}" ); } private function optimize_current_size(): void { try { $original_path = $this->current_image_path; $response = $this->send_file(); $optimized_size = (int) $response->optimizedSize; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $optimized_image_binary = base64_decode( $response->image, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode $this->replace_image_file( $optimized_image_binary ); $this->update_attachment_meta( $optimized_size ); if ( $original_path !== $this->current_image_path ) { $this->update_posts( $original_path, $this->current_image_path ); } // This should only be updated after meta $this->update_attachment_post(); } catch ( Image_Already_Optimized_Error $iao ) { // If we can't optimize it further, just update the meta $original_size = $this->wp_meta->get_file_size( $this->current_image_size ) ?? File_System::size( $this->image->get_file_path( $this->current_image_size ) ); $this->update_attachment_meta( $original_size, true ); $this->update_attachment_post( true ); } catch ( Bulk_Token_Expired_Error | Quota_Exceeded_Error | Image_File_Already_Exists_Error $e ) { throw $e; } catch ( Throwable $t ) { // In case of anything else throw new Image_Optimization_Error( $t->getMessage() ); } } private function send_file() { $connect_status = Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->get_connect_status(); $headers = [ 'access_token' => $connect_status->access_token ?? '', ]; if ( $this->bulk_token ) { $headers['x-elementor-bulk-token'] = $this->bulk_token; } $optimization_options = [ 'compression_level' => Settings::get( Settings::COMPRESSION_LEVEL_OPTION_NAME ), 'convert_to_format' => $this->image_conversion->get_current_conversion_option(), 'strip_exif' => Settings::get( Settings::STRIP_EXIF_METADATA_OPTION_NAME ), ]; if ( Settings::get( Settings::RESIZE_LARGER_IMAGES_OPTION_NAME ) ) { $optimization_options['resize'] = Settings::get( Settings::RESIZE_LARGER_IMAGES_SIZE_OPTION_NAME ); } $image_key = wp_generate_password( 15, false ); $response = Utils::get_api_client()->make_request( 'POST', self::IMAGE_OPTIMIZE_ENDPOINT, [ 'initiator' => $this->initiator, 'image_url' => $this->image->get_url( $this->current_image_size ), 'image_key' => $image_key, 'checksum' => md5_file( $this->current_image_path ), 'attachment_id' => $this->image->get_id(), 'attachment_parent_id' => Image::SIZE_FULL === $this->current_image_size ? 0 : $this->image->get_id(), 'image_optimization_settings' => base64_encode( wp_json_encode( $optimization_options ) ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode ], $headers, $this->current_image_path, 'image' ); if ( isset( $response->stats ) ) { Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->update_usage_data( $response->stats ); } if ( ! isset( $response->imageKey ) || $image_key !== $response->imageKey ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase Logger::log( Logger::LEVEL_ERROR, "Image key must be $image_key, instead got $response->imageKey" ); throw new Image_Optimization_Error( esc_html__( 'Service response is incorrect', 'image-optimization' ) ); } $received_file_hash = md5( base64_decode( $response->image, true ) ); if ( ! isset( $response->checksum ) || $received_file_hash !== $response->checksum ) { Logger::log( Logger::LEVEL_ERROR, "Image key must be $response->checksum, instead calculated $received_file_hash" ); throw new Image_Optimization_Error( esc_html__( 'Service response is incorrect', 'image-optimization' ) ); } return $response; } /** * @throws File_System_Operation_Error|Image_Backup_Creation_Error|Image_File_Already_Exists_Error */ private function replace_image_file( string $file_data ): void { $path = $this->current_image_path; // If we have backups disabled, we want to make sure we can download and save new file before we // remove an existing one. $tmp_path = File_Utils::replace_extension( $path, 'tmp' ); File_System::put_contents( $tmp_path, $file_data ); if ( $this->image_conversion->is_enabled() ) { $converted_path = File_Utils::replace_extension( $tmp_path, $this->image_conversion->get_current_file_extension() ); $original_is_already_converted = strtolower( $path ) === strtolower( $converted_path ); if ( ! $original_is_already_converted && File_System::exists( $converted_path ) ) { throw new Image_File_Already_Exists_Error(); } // We want to keep both original as a fallback and optimized webp to prevent 404s if ( ! $original_is_already_converted ) { $this->keep_backups = true; ( new Image_Meta( $this->image->get_id() ) ) ->set_image_backup_path( $this->current_image_size, $this->current_image_path ) ->save(); } if ( $original_is_already_converted ) { Image_Backup::create( $this->image->get_id(), $this->current_image_size, $this->current_image_path ); } File_System::move( $tmp_path, $converted_path, true ); $path = $converted_path; } else { Image_Backup::create( $this->image->get_id(), $this->current_image_size, $this->current_image_path ); File_System::move( $tmp_path, $path, true ); } if ( Image::SIZE_FULL === $this->current_image_size ) { // Drop WP caches update_attached_file( $this->image->get_id(), $path ); } // Updating to the correct value $this->current_image_path = $path; } /** * Updates attachment records in the `wp_posts` table. * * @return void */ private function update_attachment_post( ?bool $is_fully_optimized = false ) { $update_query = []; if ( $this->image_conversion->is_enabled() && ! $is_fully_optimized ) { $attachment_object = $this->image->get_attachment_object(); $update_query['guid'] = File_Utils::replace_extension( $attachment_object->guid, $this->image_conversion->get_current_file_extension() ); $update_query['post_mime_type'] = $this->image_conversion->get_current_mime_type(); } $update_query['post_modified'] = current_time( 'mysql' ); $update_query['post_modified_gmt'] = current_time( 'mysql', true ); $this->image->update_attachment( $update_query ); } /** * Updates attachment records in the `wp_postmeta` table. * * @param int $optimized_size * @param bool|null $is_fully_optimized * * @return void */ private function update_attachment_meta( int $optimized_size, ?bool $is_fully_optimized = false ) { $meta = new Image_Meta( $this->image->get_id() ); $dimensions = Image_Dimensions::get_by_path( $this->current_image_path ); $sizes_to_update = [ $this->current_image_size, ...$this->current_size_duplicates ]; foreach ( $sizes_to_update as $size ) { $meta ->set_compression_level( Settings::get( Settings::COMPRESSION_LEVEL_OPTION_NAME ) ) ->add_optimized_size( $size ) ->add_original_data( $size, $this->wp_meta->get_size_data( $size ) ); $this->wp_meta ->set_width( $size, $dimensions->width ) ->set_height( $size, $dimensions->height ) ->set_file_size( $size, $optimized_size ); if ( $this->image_conversion->is_enabled() && ! $is_fully_optimized ) { $this->wp_meta ->set_file_path( $size, $this->current_image_path ) ->set_mime_type( $size, $this->image_conversion->get_current_mime_type() ); } } $meta->save(); $this->wp_meta->save(); } /** * 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 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 ) ); } /** * Changes image status after all image sizes were optimized. * * @return void */ private function mark_as_optimized() { ( new Image_Meta( $this->image->get_id() ) ) ->set_status( Image_Status::OPTIMIZED ) ->set_error_type( null ) ->save(); } /** * @throws Invalid_Image_Exception */ public function __construct( int $image_id, string $initiator, ?string $bulk_token = null, ?bool $is_reoptimize = false ) { $this->image = new Image( $image_id ); $this->wp_meta = new WP_Image_Meta( $image_id, $this->image ); $this->initiator = $initiator; $this->bulk_token = $bulk_token; $this->is_reoptimize = $is_reoptimize; $this->image_conversion = new Image_Conversion(); $this->keep_backups = Settings::get( Settings::BACKUP_ORIGINAL_IMAGES_OPTION_NAME ); } } modules/optimization/classes/optimization-status.php 0000644 00000003470 14720461212 0017162 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes; use ImageOptimization\Classes\Image\{ Image_Meta, Image_Optimization_Error_Type, Image_Status }; use ImageOptimization\Modules\Oauth\Classes\Data; use ImageOptimization\Modules\Stats\Classes\Optimization_Stats; use ImageOptimization\Plugin; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Optimization_Status { /** * * * @param int[] $image_ids * @return array */ public static function get_images_optimization_statuses( array $image_ids ): array { $output = []; $images_left = Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->images_left(); foreach ( $image_ids as $image_id ) { $meta = new Image_Meta( $image_id ); $data = []; $status = $meta->get_status(); $data['status'] = $status; if ( Image_Status::OPTIMIZED === $status ) { $data['stats'] = Optimization_Stats::get_image_stats( $image_id ); } if ( Image_Status::RESTORING_FAILED === $status ) { $data['message'] = esc_html__( 'Image restoring failed', 'image-optimization' ); } if ( Image_Status::OPTIMIZATION_FAILED === $status ) { $error_type = $meta->get_error_type() ?? Image_Optimization_Error_Type::GENERIC; $error_message = Optimization_Error_Message::get_optimization_error_message( $error_type ); $data['message'] = $error_message; $data['images_left'] = $images_left; } if ( Image_Status::REOPTIMIZING_FAILED === $status ) { $error_type = $meta->get_error_type() ?? Image_Optimization_Error_Type::GENERIC; $error_message = Optimization_Error_Message::get_reoptimization_error_message( $error_type ); $data['message'] = $error_message; $data['images_left'] = $images_left; } $output[ $image_id ] = $data; } return $output; } } modules/optimization/classes/exceptions/image-already-optimized-error.php 0000644 00000000571 14720461212 0023125 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes\Exceptions; use Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } /** * The service responses with the error when the optimized image size >= than the original size. */ class Image_Already_Optimized_Error extends Exception { protected $message = 'Image already optimized'; } modules/optimization/classes/exceptions/bulk-token-obtaining-error.php 0000644 00000000420 14720461212 0022436 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes\Exceptions; use Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Bulk_Token_Obtaining_Error extends Exception { protected $message = 'Bulk token obtaining error'; } modules/optimization/classes/exceptions/image-optimization-error.php 0000644 00000000414 14720461212 0022224 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes\Exceptions; use Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Image_Optimization_Error extends Exception { protected $message = 'Image optimization error'; } modules/optimization/classes/exceptions/image-validation-error.php 0000644 00000000410 14720461212 0021624 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes\Exceptions; use Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Image_Validation_Error extends Exception { protected $message = 'Image validation error'; } modules/optimization/classes/exceptions/image-optimization-already-in-progress-error.php 0000644 00000000464 14720461212 0026116 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes\Exceptions; use Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Image_Optimization_Already_In_Progress_Error extends Exception { protected $message = 'Image optimization already in progress error'; } modules/optimization/classes/exceptions/bulk-token-expired-error.php 0000644 00000000414 14720461212 0022127 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes\Exceptions; use Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Bulk_Token_Expired_Error extends Exception { protected $message = 'Bulk token expired error'; } modules/optimization/classes/exceptions/image-file-already-exists-error.php 0000644 00000000443 14720461212 0023353 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes\Exceptions; use Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Image_File_Already_Exists_Error extends Exception { protected $message = 'Image file with this name already exists'; } modules/optimization/classes/exceptions/image-optimization-retryable-error.php 0000644 00000000427 14720461212 0024217 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes\Exceptions; use Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Image_Optimization_Retryable_Error extends Exception { protected $message = 'Image optimization error'; } modules/optimization/classes/bulk-optimization-controller.php 0000644 00000031335 14720461212 0020756 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes; use ImageOptimization\Classes\Async_Operation\{ Async_Operation, Async_Operation_Hook, Async_Operation_Queue, Exceptions\Async_Operation_Exception, Queries\Image_Optimization_Operation_Query }; use ImageOptimization\Classes\Image\{ Exceptions\Invalid_Image_Exception, Image, Image_Meta, Image_Optimization_Error_Type, Image_Query_Builder, Image_Status, WP_Image_Meta }; use ImageOptimization\Classes\File_System\Exceptions\File_System_Operation_Error; use ImageOptimization\Classes\File_System\File_System; use ImageOptimization\Classes\Logger; use ImageOptimization\Classes\Utils; use ImageOptimization\Modules\Oauth\Classes\Data; use ImageOptimization\Classes\Exceptions\Quota_Exceeded_Error; use ImageOptimization\Modules\Optimization\Classes\Exceptions\Bulk_Token_Obtaining_Error; use ImageOptimization\Modules\Optimization\Components\Exceptions\Bulk_Optimization_Token_Not_Found_Error; use ImageOptimization\Modules\Stats\Classes\Optimization_Stats; use ImageOptimization\Plugin; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Bulk_Optimization_Controller { private const OBTAIN_TOKEN_ENDPOINT = 'image/bulk-token'; public static function reschedule_bulk_optimization() { self::cancel_bulk_optimization(); self::find_images_and_schedule_optimization(); } public static function reschedule_bulk_reoptimization() { self::cancel_bulk_reoptimization(); self::find_optimized_images_and_schedule_reoptimization(); } /** * Cancels pending bulk optimization operations. * * @return void * @throws Async_Operation_Exception */ public static function cancel_bulk_optimization(): void { $query = ( new Image_Optimization_Operation_Query() ) ->set_hook( Async_Operation_Hook::OPTIMIZE_BULK ) // It's risky to cancel in-progress operations at that point, so we cancel only the pending ones. ->set_status( Async_Operation::OPERATION_STATUS_PENDING ) ->set_limit( -1 ); $operations = Async_Operation::get( $query ); foreach ( $operations as $operation ) { $image_id = $operation->get_args()['attachment_id']; Async_Operation::cancel( $operation->get_id() ); ( new Image_Meta( $image_id ) )->delete(); } } /** * Cancels pending bulk re-optimization operations. * * @return void * @throws Async_Operation_Exception */ public static function cancel_bulk_reoptimization(): void { $query = ( new Image_Optimization_Operation_Query() ) ->set_hook( Async_Operation_Hook::REOPTIMIZE_BULK ) // It's risky to cancel in-progress operations at that point, so we cancel only the pending ones. ->set_status( Async_Operation::OPERATION_STATUS_PENDING ) ->set_limit( -1 ); $operations = Async_Operation::get( $query ); foreach ( $operations as $operation ) { $image_id = $operation->get_args()['attachment_id']; Async_Operation::cancel( $operation->get_id() ); ( new Image_Meta( $image_id ) )->delete(); } } /** * Looks for all non-optimized images and creates a bulk operation for each of them. * Also, obtains bulk token and passes it to a newly created operation. * * @return void * * @throws Quota_Exceeded_Error|Invalid_Image_Exception */ public static function find_images_and_schedule_optimization(): void { $images = self::find_images( ( new Image_Query_Builder() ) ->return_not_optimized_images(), true ); if ( ! $images['total_images_count'] ) { return; } $operation_id = wp_generate_password( 10, false ); try { $bulk_token = self::obtain_bulk_token( $images['total_images_count'] ); self::set_bulk_operation_token( $operation_id, $bulk_token ); } catch ( Bulk_Token_Obtaining_Error $e ) { $bulk_token = null; } foreach ( $images['attachments_in_quota'] as $attachment_id ) { $meta = new Image_Meta( $attachment_id ); if ( null === $bulk_token ) { $meta ->set_status( Image_Status::OPTIMIZATION_FAILED ) ->save(); continue; } try { Async_Operation::create( Async_Operation_Hook::OPTIMIZE_BULK, [ 'attachment_id' => $attachment_id, 'operation_id' => $operation_id, ], Async_Operation_Queue::OPTIMIZE ); $meta ->set_status( Image_Status::OPTIMIZATION_IN_PROGRESS ) ->save(); } catch ( Async_Operation_Exception $aoe ) { $meta ->set_status( Image_Status::OPTIMIZATION_FAILED ) ->save(); continue; } } } /** * Looks for already optimized images with backups and creates a bulk operation for each of them. * Also, obtains bulk token and passes it to a newly created operation. * * @return void * * @throws Quota_Exceeded_Error|Invalid_Image_Exception */ public static function find_optimized_images_and_schedule_reoptimization(): void { $images = self::find_images( ( new Image_Query_Builder() ) ->return_optimized_images() ); if ( ! $images['total_images_count'] ) { return; } $operation_id = wp_generate_password( 10, false ); try { $bulk_token = self::obtain_bulk_token( $images['total_images_count'] ); self::set_bulk_operation_token( $operation_id, $bulk_token ); } catch ( Bulk_Token_Obtaining_Error $e ) { $bulk_token = null; } foreach ( $images['attachments_in_quota'] as $attachment_id ) { $meta = new Image_Meta( $attachment_id ); if ( null === $bulk_token ) { $meta ->set_status( Image_Status::REOPTIMIZING_FAILED ) ->save(); continue; } try { Async_Operation::create( Async_Operation_Hook::REOPTIMIZE_BULK, [ 'attachment_id' => $attachment_id, 'operation_id' => $operation_id, ], Async_Operation_Queue::OPTIMIZE ); $meta ->set_status( Image_Status::REOPTIMIZING_IN_PROGRESS ) ->save(); } catch ( Async_Operation_Exception $aoe ) { $meta ->set_status( Image_Status::REOPTIMIZING_FAILED ) ->save(); continue; } } foreach ( $images['attachments_out_of_quota'] as $attachment_id ) { ( new Image_Meta( $attachment_id ) ) ->set_status( Image_Status::REOPTIMIZING_FAILED ) ->set_error_type( Image_Optimization_Error_Type::QUOTA_EXCEEDED ) ->save(); } } /** * Looks for images for bulk optimization operations based on a query passed and the quota left. * * @param Image_Query_Builder $query Image query to execute. * @param bool $limit_to_quota If true, it limits image query to the quota left. * @return array{total_images_count: int, attachments_in_quota: array, attachments_out_of_quota: array} * * @throws Invalid_Image_Exception * @throws Quota_Exceeded_Error */ private static function find_images( Image_Query_Builder $query, bool $limit_to_quota = false ): array { $output = [ 'total_images_count' => 0, 'attachments_in_quota' => [], 'attachments_out_of_quota' => [], ]; $images_left = Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->images_left(); if ( ! $images_left ) { throw new Quota_Exceeded_Error( __( 'Images quota exceeded', 'image-optimization' ) ); } if ( $limit_to_quota ) { $query->set_paging_size( $images_left ); } $wp_query = $query->execute(); if ( ! $wp_query->post_count ) { return $output; } foreach ( $wp_query->posts as $attachment_id ) { try { Validate_Image::is_valid( $attachment_id ); $wp_meta = new WP_Image_Meta( $attachment_id ); } catch ( Invalid_Image_Exception | Exceptions\Image_Validation_Error $ie ) { continue; } $sizes_count = count( $wp_meta->get_size_keys() ); if ( $output['total_images_count'] + $sizes_count <= $images_left ) { $output['total_images_count'] += $sizes_count; $output['attachments_in_quota'][] = $attachment_id; } else { break; } } $output['attachments_out_of_quota'] = array_diff( $wp_query->posts, $output['attachments_in_quota'] ); return $output; } /** * Looks for the bulk token in transients. * * @param string $operation_id Bulk optimization operation id * * @return string|null Bulk token. * * @throws Bulk_Optimization_Token_Not_Found_Error */ public static function get_bulk_operation_token( string $operation_id ): ?string { $bulk_token = get_transient( "image_optimizer_bulk_token_$operation_id" ); if ( ! $bulk_token ) { throw new Bulk_Optimization_Token_Not_Found_Error( "There is no token found for the operation $operation_id" ); } return $bulk_token; } /** * Saves bulk optimization token to transients for a day. * * @param string $operation_id Bulk optimization operation id * @param string $bulk_token Bulk optimization token * @return void */ public static function set_bulk_operation_token( string $operation_id, string $bulk_token ): void { set_transient( "image_optimizer_bulk_token_$operation_id", $bulk_token, HOUR_IN_SECONDS ); } /** * Sends a request to the BE to obtain bulk optimization token. * It prevents obtaining a token for each and every optimization operation. * * @return string * * @throws Bulk_Token_Obtaining_Error */ private static function obtain_bulk_token( int $images_count ): ?string { try { $response = Utils::get_api_client()->make_request( 'POST', self::OBTAIN_TOKEN_ENDPOINT, [ 'images_count' => $images_count, ] ); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Error while sending bulk token request: ' . $t->getMessage() ); throw new Bulk_Token_Obtaining_Error( $t->getMessage() ); } return $response->token ?? null; } /** * Checks if there is a bulk optimization operation in progress. * If there is at least a single active bulk optimization operation it returns true, otherwise false. * * @return bool * @throws Async_Operation_Exception */ public static function is_optimization_in_progress(): bool { $query = ( new Image_Optimization_Operation_Query() ) ->set_hook( Async_Operation_Hook::OPTIMIZE_BULK ) ->set_status( [ Async_Operation::OPERATION_STATUS_PENDING, Async_Operation::OPERATION_STATUS_RUNNING ] ) ->set_limit( 1 ) ->return_ids(); return ! empty( Async_Operation::get( $query ) ); } /** * Checks if there is a bulk re-optimization operation in progress. * If there is at least a single active bulk re-optimization operation it returns true, otherwise false. * * @return bool * @throws Async_Operation_Exception */ public static function is_reoptimization_in_progress(): bool { $query = ( new Image_Optimization_Operation_Query() ) ->set_hook( Async_Operation_Hook::REOPTIMIZE_BULK ) ->set_status( [ Async_Operation::OPERATION_STATUS_PENDING, Async_Operation::OPERATION_STATUS_RUNNING ] ) ->set_limit( 1 ) ->return_ids(); return ! empty( Async_Operation::get( $query ) ); } /** * Retrieves the bulk optimization process status. * * @return array{status: string, stats: array} * @throws Async_Operation_Exception */ public static function get_status(): array { $stats = Optimization_Stats::get_image_stats(); $output = [ 'status' => 'not-started', 'percentage' => round( $stats['optimized_image_count'] / $stats['total_image_count'] * 100 ), ]; $active_query = ( new Image_Optimization_Operation_Query() ) ->set_hook( Async_Operation_Hook::OPTIMIZE_BULK ) ->set_status( [ Async_Operation::OPERATION_STATUS_PENDING, Async_Operation::OPERATION_STATUS_RUNNING ] ) ->set_limit( -1 ); if ( empty( Async_Operation::get( $active_query ) ) ) { return $output; } $output['status'] = 'in-progress'; return $output; } /** * Returns latest operations for the bulk optimization screen. * * @param string|null $operation_id * * @return array * @throws Async_Operation_Exception */ public static function get_processed_images( string $operation_id ): array { $output = []; $query = ( new Image_Optimization_Operation_Query() ) ->set_hook( Async_Operation_Hook::OPTIMIZE_BULK ) ->set_bulk_operation_id( $operation_id ) ->set_limit( 50 ); $operations = Async_Operation::get( $query ); foreach ( $operations as $operation ) { $image_id = $operation->get_args()['attachment_id']; $image = new Image( $image_id ); try { $stats = Optimization_Stats::get_image_stats( $image_id ); } catch ( Invalid_Image_Exception $iie ) { continue; } catch ( Throwable $t ) { $original_file_size = 0; $current_file_size = 0; } $output[] = [ 'id' => $operation->get_id(), 'status' => $operation->get_status() === Async_Operation::OPERATION_STATUS_COMPLETE ? ( new Image_Meta( $image_id ) )->get_status() : $operation->get_status(), 'image_name' => $image->get_attachment_object()->post_title, 'image_id' => $image_id, 'thumbnail_url' => $image->get_url( 'thumbnail' ), 'original_file_size' => $stats['initial_image_size'], 'current_file_size' => $stats['current_image_size'], ]; } return $output; } } modules/optimization/classes/single-optimization.php 0000644 00000004556 14720461212 0017126 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes; use ImageOptimization\Classes\Async_Operation\{ Async_Operation, Async_Operation_Hook, Async_Operation_Queue, Exceptions\Async_Operation_Exception, Queries\Image_Optimization_Operation_Query }; use ImageOptimization\Classes\Image\{ Image_Meta, Image_Status, }; use ImageOptimization\Modules\Optimization\Classes\Exceptions\Image_Optimization_Already_In_Progress_Error; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Single_Optimization { /** * @throws Throwable|Async_Operation_Exception */ public static function optimize_many( array $image_ids, bool $is_reoptimize = false ): void { foreach ( $image_ids as $image_id ) { try { self::schedule_single_optimization( $image_id, $is_reoptimize ); } catch ( Image_Optimization_Already_In_Progress_Error $ioe ) { continue; } catch ( Throwable $t ) { throw $t; } } } /** * @throws Throwable|Async_Operation_Exception|Image_Optimization_Already_In_Progress_Error */ public static function schedule_single_optimization( int $image_id, bool $is_reoptimize = false ): void { if ( self::is_optimization_in_progress( $image_id ) ) { throw new Image_Optimization_Already_In_Progress_Error( esc_html__( 'Optimization is already in progress', 'image-optimization' ) ); } $meta = new Image_Meta( $image_id ); try { $meta ->set_status( $is_reoptimize ? Image_Status::REOPTIMIZING_IN_PROGRESS : Image_Status::OPTIMIZATION_IN_PROGRESS ) ->save(); Async_Operation::create( $is_reoptimize ? Async_Operation_Hook::REOPTIMIZE_SINGLE : Async_Operation_Hook::OPTIMIZE_SINGLE, [ 'attachment_id' => $image_id ], Async_Operation_Queue::OPTIMIZE ); } catch ( Throwable $t ) { $meta ->set_status( $is_reoptimize ? Image_Status::REOPTIMIZING_FAILED : Image_Status::OPTIMIZATION_FAILED ) ->save(); throw $t; } } /** * @throws Async_Operation_Exception */ private static function is_optimization_in_progress( int $image_id ): bool { $query = ( new Image_Optimization_Operation_Query() ) ->set_status( [ Async_Operation::OPERATION_STATUS_PENDING, Async_Operation::OPERATION_STATUS_RUNNING ] ) ->set_image_id( $image_id ) ->return_ids(); $operations = Async_Operation::get( $query ); return count( $operations ) > 0; } } modules/optimization/classes/validate-image.php 0000644 00000005726 14720461212 0015772 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes; use ImageOptimization\Classes\Image\{ Exceptions\Invalid_Image_Exception, Image, Image_Meta, WP_Image_Meta }; use ImageOptimization\Classes\File_System\Exceptions\File_System_Operation_Error; use ImageOptimization\Classes\File_System\File_System; use ImageOptimization\Classes\File_Utils; use ImageOptimization\Modules\Optimization\Classes\Exceptions\Image_Validation_Error; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Validate_Image { public const MAX_FILE_SIZE = 10 * 1024 * 1024; /** * Returns true if $image_id provided associated with an image that can be optimized. * * @param int $image_id Attachment id. * * @return true * @throws Image_Validation_Error * @throws Invalid_Image_Exception */ public static function is_valid( int $image_id ): bool { $attachment_object = get_post( $image_id ); if ( ! $attachment_object ) { throw new Image_Validation_Error( __( 'Can\'t optimize this file. If the issue persists, Contact Support', 'image-optimization' ) ); } if ( ! wp_attachment_is_image( $attachment_object ) || ! in_array( $attachment_object->post_mime_type, Image::get_supported_mime_types(), true ) || ( in_array( $attachment_object->post_mime_type, Image::get_mime_types_cannot_be_optimized(), true ) && ! get_post_meta( $image_id, Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY, true ) ) ) { throw new Image_Validation_Error( self::prepare_supported_formats_list_error() ); } if ( ! file_exists( get_attached_file( $image_id ) ) ) { throw new Image_Validation_Error( esc_html__( 'File is missing. Verify the upload', 'image-optimization' ) ); } $wp_meta = new WP_Image_Meta( $image_id ); try { $image_size = $wp_meta->get_file_size( Image::SIZE_FULL ) ?? File_System::size( ( new Image( $image_id ) )->get_file_path( Image::SIZE_FULL ) ); } catch ( File_System_Operation_Error $e ) { throw new Image_Validation_Error( esc_html__( 'File is missing. Verify the upload', 'image-optimization' ) ); } if ( $image_size > self::MAX_FILE_SIZE ) { throw new Image_Validation_Error( sprintf( __( 'File is too large. Max size is %s', 'image-optimization' ), File_Utils::format_file_size( self::MAX_FILE_SIZE, 0 ), ) ); } return true; } /** * Prepares the error message for the unsupported file formats. * * @return string The error message. */ private static function prepare_supported_formats_list_error(): string { $formats = Image::get_supported_formats(); $formats = array_filter( $formats, fn ( $format) => ! in_array( $format, Image::get_formats_cannot_be_optimized(), true ) ); $last_item = strtoupper( array_pop( $formats ) ); $formats_list = join( ', ', array_map( 'strtoupper', $formats ) ); return sprintf( __( 'Unsupported file format. Only %1$s, or %2$s are supported', 'image-optimization' ), $formats_list, $last_item ); } } modules/optimization/classes/optimization-error-message.php 0000644 00000002503 14720461212 0020406 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Classes; use ImageOptimization\Classes\Image\Image_Optimization_Error_Type; use TypeError; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Optimization_Error_Message { public static function get_reoptimization_error_message( string $error_type ) { if ( Image_Optimization_Error_Type::GENERIC === $error_type ) { return esc_html__( 'Image reoptimizing failed', 'image-optimization' ); } return self::get_optimization_error_message( $error_type ); } public static function get_optimization_error_message( string $error_type ) { if ( ! in_array( $error_type, Image_Optimization_Error_Type::get_values(), true ) ) { throw new TypeError( "Error type $error_type is not a part of Image_Optimization_Error_Type values" ); } $messages = [ Image_Optimization_Error_Type::FILE_ALREADY_EXISTS => esc_html__( 'File with this name already exists', 'image-optimization' ), Image_Optimization_Error_Type::QUOTA_EXCEEDED => esc_html__( 'Plan quota reached', 'image-optimization' ), Image_Optimization_Error_Type::GENERIC => esc_html__( 'Optimization error', 'image-optimization' ), ]; if ( isset( $messages[ $error_type ] ) ) { return $messages[ $error_type ]; } return $messages[ Image_Optimization_Error_Type::GENERIC ]; } } modules/optimization/rest/optimize-single-image.php 0000644 00000003414 14720461212 0016630 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Rest; use ImageOptimization\Classes\Image\Image; use ImageOptimization\Modules\Oauth\Components\Connect; use ImageOptimization\Modules\Optimization\Classes\{ Route_Base, Single_Optimization, Validate_Image, }; use Throwable; use WP_REST_Request; use ImageOptimization\Plugin; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Optimize_Single_Image extends Route_Base { const NONCE_NAME = 'image-optimization-optimize-image'; const IMAGE_ID_PARAM = 'imageId'; protected string $path = 'image'; public function get_name(): string { return 'optimize-single-image'; } public function get_methods(): array { return [ 'POST' ]; } public function POST( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); if ( ! Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->is_activated() ) { return $this->respond_error_json([ 'message' => esc_html__( 'Invalid activation', 'image-optimization' ), 'code' => 'unauthorized', ]); } $is_reoptimize = (bool) $request->get_param( 'reoptimize' ); $image_id = (int) $request->get_param( self::IMAGE_ID_PARAM ); if ( empty( $image_id ) ) { return $this->respond_error_json([ 'message' => esc_html__( 'Invalid image id', 'image-optimization' ), 'code' => 'bad_request', ]); } try { Validate_Image::is_valid( $image_id ); Single_Optimization::schedule_single_optimization( $image_id, $is_reoptimize ); return $this->respond_success_json(); } catch ( Throwable $t ) { return $this->respond_error_json([ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ]); } } } modules/optimization/rest/optimization-status.php 0000644 00000002271 14720461212 0016500 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Rest; use ImageOptimization\Modules\Optimization\Classes\Optimization_Status as Optimization_Status_Controller; use ImageOptimization\Modules\Optimization\Classes\Route_Base; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Optimization_Status extends Route_Base { protected string $path = 'status'; public function get_name(): string { return 'optimization-status'; } public function get_methods(): array { // There might be a huge amount of ids in some cases, so decided to keep it as POST return [ 'POST' ]; } public function POST( WP_REST_Request $request ) { try { $body = json_decode( $request->get_body() ); $image_ids = $body->image_ids ?? null; if ( empty( $image_ids ) ) { return $this->respond_success_json([ 'status' => [], ]); } return $this->respond_success_json([ 'status' => Optimization_Status_Controller::get_images_optimization_statuses( $image_ids ), ]); } catch ( Throwable $t ) { return $this->respond_error_json([ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ]); } } } modules/optimization/rest/cancel-bulk-optimization.php 0000644 00000003164 14720461212 0017337 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Rest; use ImageOptimization\Modules\Optimization\Classes\{ Bulk_Optimization_Controller, Route_Base, }; use ImageOptimization\Modules\Oauth\Components\Connect; use Throwable; use WP_REST_Request; use ImageOptimization\Plugin; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Cancel_Bulk_Optimization extends Route_Base { const NONCE_NAME = 'image-optimization-cancel-bulk-optimization'; protected string $path = 'bulk/cancel'; public function get_name(): string { return 'cancel-bulk-optimization'; } public function get_methods(): array { return [ 'POST' ]; } public function POST( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); if ( ! Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->is_activated() ) { return $this->respond_error_json([ 'message' => esc_html__( 'Invalid activation', 'image-optimization' ), 'code' => 'unauthorized', ]); } try { $is_in_progress = Bulk_Optimization_Controller::is_optimization_in_progress(); if ( ! $is_in_progress ) { return $this->respond_error_json([ 'message' => esc_html__( 'Bulk optimization is not in progress', 'image-optimization' ), 'code' => 'forbidden', ]); } Bulk_Optimization_Controller::cancel_bulk_optimization(); return $this->respond_success_json(); } catch ( Throwable $t ) { return $this->respond_error_json([ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ]); } } } modules/optimization/rest/optimize-bulk.php 0000644 00000005321 14720461212 0015223 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Rest; use ImageOptimization\Classes\Async_Operation\Exceptions\Async_Operation_Exception; use ImageOptimization\Modules\Optimization\Classes\{ Bulk_Optimization_Controller, Route_Base, }; use ImageOptimization\Classes\Image\Exceptions\Invalid_Image_Exception; use ImageOptimization\Classes\Exceptions\Quota_Exceeded_Error; use ImageOptimization\Modules\Oauth\Components\Connect; use Throwable; use WP_REST_Request; use ImageOptimization\Plugin; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Optimize_Bulk extends Route_Base { const NONCE_NAME = 'image-optimization-optimize-bulk'; protected string $path = 'bulk'; public function get_name(): string { return 'optimize-bulk'; } public function get_methods(): array { return [ 'POST' ]; } public function POST( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); if ( ! Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->is_activated() ) { return $this->respond_error_json([ 'message' => esc_html__( 'Invalid activation', 'image-optimization' ), 'code' => 'unauthorized', ]); } $is_reoptimize = (bool) $request->get_param( 'reoptimize' ); try { if ( $is_reoptimize ) { return $this->handle_bulk_reoptimization(); } else { return $this->handle_bulk_optimization(); } } catch ( Throwable $t ) { return $this->respond_error_json([ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ]); } } /** * @return \WP_Error|\WP_REST_Response * @throws Async_Operation_Exception|Invalid_Image_Exception|Quota_Exceeded_Error */ private function handle_bulk_optimization() { $is_in_progress = Bulk_Optimization_Controller::is_optimization_in_progress(); if ( $is_in_progress ) { return $this->respond_error_json( [ 'message' => esc_html__( 'Bulk optimization is already in progress', 'image-optimization' ), 'code' => 'forbidden', ] ); } Bulk_Optimization_Controller::find_images_and_schedule_optimization(); return $this->respond_success_json(); } /** * @throws Async_Operation_Exception|Quota_Exceeded_Error */ private function handle_bulk_reoptimization() { $is_in_progress = Bulk_Optimization_Controller::is_reoptimization_in_progress(); if ( $is_in_progress ) { return $this->respond_error_json( [ 'message' => esc_html__( 'Bulk re-optimization is already in progress', 'image-optimization' ), 'code' => 'forbidden', ] ); } Bulk_Optimization_Controller::find_optimized_images_and_schedule_reoptimization(); return $this->respond_success_json(); } } modules/optimization/rest/get-bulk-optimization-images.php 0000644 00000002163 14720461212 0020132 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Rest; use ImageOptimization\Modules\Optimization\Classes\{ Bulk_Optimization_Controller, Route_Base, }; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Get_Bulk_Optimization_Images extends Route_Base { protected string $path = 'bulk/images'; public function get_name(): string { return 'bulk-optimization-images'; } public function get_methods(): array { return [ 'GET' ]; } public function GET( WP_REST_Request $request ) { try { $operation_id = $request->get_param( 'operation_id' ); if ( empty( $operation_id ) ) { return $this->respond_error_json([ 'message' => esc_html__( 'Missed operation id', 'image-optimization' ), 'code' => 'bad_request', ]); } $images = Bulk_Optimization_Controller::get_processed_images( $operation_id ); return $this->respond_success_json([ 'images' => $images, ]); } catch ( Throwable $t ) { return $this->respond_error_json([ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ]); } } } modules/optimization/module.php 0000644 00000004563 14720461212 0012747 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization; use ImageOptimization\Classes\Module_Base; use ImageOptimization\Modules\Backups\Rest\Restore_Single; use ImageOptimization\Modules\Optimization\Rest\Optimize_Single_Image; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Module extends Module_Base { public function get_name(): string { return 'optimization'; } public static function routes_list() : array { return [ 'Optimize_Single_Image', 'Optimize_Bulk', 'Get_Bulk_Optimization_Images', 'Optimization_Status', 'Cancel_Bulk_Optimization', ]; } public static function component_list() : array { return [ 'Avif_Compatibility', 'Media_Control', 'Single_Optimization', 'Upload_Optimization', 'Bulk_Optimization', 'List_View_Pointer', 'Admin_Bulk_Actions', 'Admin_Filter', ]; } /** * Enqueue styles and scripts */ public function enqueue_scripts() { $asset_file = include IMAGE_OPTIMIZATION_ASSETS_PATH . 'build/control.asset.php'; foreach ( $asset_file['dependencies'] as $style ) { wp_enqueue_style( $style ); } wp_enqueue_style( 'image-optimization-control', $this->get_css_assets_url( 'control' ), [], IMAGE_OPTIMIZATION_VERSION, ); wp_enqueue_script( 'image-optimization-control', $this->get_js_assets_url( 'control' ), $asset_file['dependencies'], IMAGE_OPTIMIZATION_VERSION, true ); wp_set_script_translations( 'image-optimization-control', 'image-optimization' ); wp_localize_script( 'image-optimization-control', 'imageOptimizerControlSettings', [ 'optimizeSingleImageNonce' => wp_create_nonce( Optimize_Single_Image::NONCE_NAME ), 'restoreSingleImageNonce' => wp_create_nonce( Restore_Single::NONCE_NAME ), ] ); } public static function load_template( $path, $name, $args = [] ): bool { $templates_path = sprintf( '%s/templates/%s/%s.php', dirname( __FILE__ ), $path, $name ); try { load_template( $templates_path, false, $args ); } catch ( Throwable $t ) { return false; } return true; } /** * Module constructor. */ public function __construct() { $this->register_components(); $this->register_routes(); add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] ); add_action( 'elementor/editor/after_enqueue_scripts', [ $this, 'enqueue_scripts' ] ); } } modules/optimization/components/avif-compatibility.php 0000644 00000004106 14720461212 0017434 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Components; use ImageOptimization\Classes\Image\Image_Dimensions; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Avif_Compatibility { public function is_avif_supported(): bool { return in_array( 'image/avif', get_allowed_mime_types(), true ); } public function add_to_supported_types( $mime_types ) { $mime_types['avif'] = 'image/avif'; return $mime_types; } public function add_to_supported_mime_types( $mime_types ) { $mime_types['image/avif'] = 'avif'; return $mime_types; } public function mark_as_displayable( $result, $path ) { if ( str_ends_with( $path, '.avif' ) ) { return true; } return $result; } public function fix_avif_images( $metadata, $attachment_id ) { if ( empty( $metadata ) ) { return $metadata; } $attachment = get_post( $attachment_id ); if ( ! $attachment || is_wp_error( $attachment ) || 'image/avif' !== $attachment->post_mime_type ) { return $metadata; } if ( ( ! empty( $metadata['width'] ) && ( 0 !== $metadata['width'] ) ) && ( ! empty( $metadata['height'] ) && 0 !== $metadata['height'] ) ) { return $metadata; } $file = get_attached_file( $attachment_id ); if ( ! $file ) { return $metadata; } $dimensions = Image_Dimensions::get_by_path( $file ); $metadata['width'] = $dimensions->width; $metadata['height'] = $dimensions->height; if ( empty( $metadata['file'] ) ) { $metadata['file'] = _wp_relative_upload_path( $file ); } if ( empty( $metadata['sizes'] ) ) { $metadata['sizes'] = []; } return $metadata; } public function __construct() { if ( $this->is_avif_supported() ) { return; } add_filter( 'upload_mimes', [ $this, 'add_to_supported_types' ] ); add_filter( 'mime_types', [ $this, 'add_to_supported_types' ] ); add_filter( 'getimagesize_mimes_to_exts', [ $this, 'add_to_supported_mime_types' ] ); add_filter( 'file_is_displayable_image', [ $this, 'mark_as_displayable' ], 10, 2 ); add_filter( 'wp_generate_attachment_metadata', [ $this, 'fix_avif_images' ], 1, 3 ); } } modules/optimization/components/upload-optimization.php 0000644 00000006140 14720461212 0017650 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Components; use ImageOptimization\Classes\Async_Operation\{ Async_Operation, Async_Operation_Hook, Async_Operation_Queue, }; use ImageOptimization\Classes\Image\{ Image, Image_Meta, Image_Optimization_Error_Type, Image_Status }; use ImageOptimization\Classes\Logger; use ImageOptimization\Classes\Exceptions\Quota_Exceeded_Error; use ImageOptimization\Modules\Optimization\Classes\Exceptions\Image_File_Already_Exists_Error; use ImageOptimization\Modules\Optimization\Classes\Optimize_Image; use ImageOptimization\Modules\Settings\Classes\Settings; use Throwable; use ImageOptimization\Plugin; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Upload_Optimization { public function handle_upload( int $attachment_id ) { if ( ! Settings::get( Settings::OPTIMIZE_ON_UPLOAD_OPTION_NAME ) ) { return; } // @var ImageOptimizer/Modules/ConnectManager/Module $module = Plugin::instance()->modules_manager->get_modules( 'connect-manager' ); if ( ! $module->connect_instance->is_connected() || ! $module->connect_instance->is_activated() ) { return; } $attachment_object = get_post( $attachment_id ); // TODO: Check how we can use Validate_Image::is_valid() here if ( ! wp_attachment_is_image( $attachment_object ) || ! in_array( $attachment_object->post_mime_type, Image::get_supported_mime_types(), true ) || ( in_array( $attachment_object->post_mime_type, Image::get_mime_types_cannot_be_optimized(), true ) && ! get_post_meta( $attachment_id, Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY, true ) ) ) { return; } $meta = new Image_Meta( $attachment_id ); try { $meta ->set_status( Image_Status::OPTIMIZATION_IN_PROGRESS ) ->save(); Async_Operation::create( Async_Operation_Hook::OPTIMIZE_ON_UPLOAD, [ 'attachment_id' => $attachment_id ], Async_Operation_Queue::OPTIMIZE ); } catch ( Throwable $t ) { $meta ->set_status( Image_Status::OPTIMIZATION_FAILED ) ->save(); } } /** @async */ public function optimize_image_on_upload( int $image_id ) { try { $oi = new Optimize_Image( $image_id, 'upload', ); $oi->optimize(); } catch ( Quota_Exceeded_Error $qe ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::OPTIMIZATION_FAILED ) ->set_error_type( Image_Optimization_Error_Type::QUOTA_EXCEEDED ) ->save(); } catch ( Image_File_Already_Exists_Error $fe ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::OPTIMIZATION_FAILED ) ->set_error_type( Image_Optimization_Error_Type::FILE_ALREADY_EXISTS ) ->save(); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Optimization error. Reason: ' . $t->getMessage() ); ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::OPTIMIZATION_FAILED ) ->set_error_type( Image_Optimization_Error_Type::GENERIC ) ->save(); } } public function __construct() { add_action( 'add_attachment', [ $this, 'handle_upload' ] ); add_action( Async_Operation_Hook::OPTIMIZE_ON_UPLOAD, [ $this, 'optimize_image_on_upload' ] ); } } modules/optimization/components/admin-filter.php 0000644 00000005414 14720461212 0016216 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Components; use ImageOptimization\Classes\Image\Image_Meta; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Admin_Filter { public function add_filter( string $post_type ) { if ( 'attachment' !== $post_type ) { return; } $options = [ '' => __( 'All Media Files', 'image-optimization' ), 'optimized' => __( 'Optimized', 'image-optimization' ), 'not-optimized' => __( 'Unoptimized', 'image-optimization' ), 'in-progress' => __( 'In progress', 'image-optimization' ), 'failed' => __( 'Errors', 'image-optimization' ), ]; $current_value = $this->get_current_filter(); ?> <label class="screen-reader-text" for="image-optimization-filter"> <?php esc_html_e( 'Filter by optimization status', 'image-optimization' ); ?> </label> <select class="image-optimization-filter" id="image-optimization-filter" name="image-optimization-filter"> <?php foreach ( $options as $value => $title ) { printf( '<option value="%s" %s>%s</option>', esc_attr( $value ), selected( $value, $current_value, false ), esc_html( $title ) ); } ?> </select> <?php } public function handle_filter( $query ) { global $pagenow; if ( 'upload.php' !== $pagenow ) { return; } $current_value = $this->get_current_filter(); if ( empty( $current_value ) ) { return; } $meta_query = empty( $query->get( 'meta_query' ) ) ? [] : $query->get( 'meta_query' ); $meta_query[] = [ [ 'key' => '_wp_attachment_metadata', // Images without this field considered invalid 'compare' => 'EXISTS', ], ]; switch ( $current_value ) { case 'not-optimized': $meta_query[] = [ 'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY, 'compare' => 'NOT EXISTS', ]; break; case 'optimized': $meta_query[] = [ 'compare' => 'LIKE', 'value' => '"status";s:9:"optimized"', 'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY, ]; break; case 'in-progress': $meta_query[] = [ 'compare' => 'LIKE', 'value' => '-in-progress"', // Covers both optimization and restoring 'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY, ]; break; case 'failed': $meta_query[] = [ 'compare' => 'LIKE', 'value' => '-failed"', // Covers both optimization and restoring 'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY, ]; break; } $query->set( 'meta_query', $meta_query ); } private function get_current_filter(): string { return sanitize_text_field( wp_unslash( $_GET['image-optimization-filter'] ?? '' ) ); } public function __construct() { add_filter( 'restrict_manage_posts', [ $this, 'add_filter' ] ); add_filter( 'parse_query', [ $this, 'handle_filter' ] ); } } modules/optimization/components/list-view-pointer.php 0000644 00000003734 14720461212 0017247 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Components; use ImageOptimization\Modules\Core\Components\Pointers; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class List_View_Pointer { const CURRENT_POINTER_SLUG = 'image-optimizer-list-view'; public function admin_print_script() { if ( $this->is_dismissed() ) { return; } wp_enqueue_script( 'wp-pointer' ); wp_enqueue_style( 'wp-pointer' ); $pointer_content = '<h3>' . esc_html__( 'Switch to list view', 'image-optimization' ) . '</h3>'; $pointer_content .= '<p>' . esc_html__( 'Get the most out of your optimizing options. Use the List view to quickly optimize your uploaded images with Image Optimizer.', 'image-optimization' ) . '</p>'; $allowed_tags = [ 'h3' => [], 'p' => [], ]; ?> <script> jQuery( document ).ready( function( $ ) { setTimeout(() => { $( '#wp-media-grid div.media-toolbar.wp-filter' ).first().pointer( { content: '<?php echo wp_kses( $pointer_content, $allowed_tags ); ?>', pointerClass: 'image-optimization-list-view-pointer', position: { edge: 'top', align: '<?php echo is_rtl() ? 'right' : 'left'; ?>', }, close() { wp.ajax.post( 'image_optimizer_pointer_dismissed', { data: { pointer: '<?php echo esc_attr( static::CURRENT_POINTER_SLUG ); ?>', }, nonce: '<?php echo esc_attr( wp_create_nonce( 'image-optimization-pointer-dismissed' ) ); ?>', } ); } } ).pointer( 'open' ); }, 0) } ); </script> <style> .image-optimization-list-view-pointer .wp-pointer-arrow { inset-inline-start: 15px; } </style> <?php } private function is_dismissed(): bool { $meta = (array) get_user_meta( get_current_user_id(), Pointers::DISMISSED_POINTERS_META_KEY, true ); return key_exists( static::CURRENT_POINTER_SLUG, $meta ); } public function __construct() { add_action( 'in_admin_header', [ $this, 'admin_print_script' ] ); } } modules/optimization/components/exceptions/bulk-optimization-token-not-found-error.php 0000644 00000000447 14720461212 0025662 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Components\Exceptions; use Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Bulk_Optimization_Token_Not_Found_Error extends Exception { protected $message = 'Bulk optimization token not found'; } modules/optimization/components/single-optimization.php 0000644 00000005405 14720461212 0017650 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Components; use ImageOptimization\Classes\Async_Operation\Async_Operation_Hook; use ImageOptimization\Classes\Image\{ Image, Image_Meta, Image_Optimization_Error_Type, Image_Restore, Image_Status }; use ImageOptimization\Classes\Logger; use ImageOptimization\Classes\Exceptions\Quota_Exceeded_Error; use ImageOptimization\Modules\Optimization\Classes\Exceptions\Image_File_Already_Exists_Error; use ImageOptimization\Modules\Optimization\Classes\Optimize_Image; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Single_Optimization { /** @async */ public function optimize_single_image( int $image_id ) { try { $oi = new Optimize_Image( $image_id, 'manual', ); $oi->optimize(); } catch ( Quota_Exceeded_Error $qe ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::OPTIMIZATION_FAILED ) ->set_error_type( Image_Optimization_Error_Type::QUOTA_EXCEEDED ) ->save(); } catch ( Image_File_Already_Exists_Error $fe ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::OPTIMIZATION_FAILED ) ->set_error_type( Image_Optimization_Error_Type::FILE_ALREADY_EXISTS ) ->save(); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Optimization error. Reason: ' . $t->getMessage() ); ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::OPTIMIZATION_FAILED ) ->set_error_type( Image_Optimization_Error_Type::GENERIC ) ->save(); } } /** @async */ public function reoptimize_single_image( int $image_id ) { try { $image = new Image( $image_id ); if ( $image->can_be_restored() ) { Image_Restore::restore( $image_id, true ); } $oi = new Optimize_Image( $image_id, 'manual', null, true ); $oi->optimize(); } catch ( Quota_Exceeded_Error $qe ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::REOPTIMIZING_FAILED ) ->set_error_type( Image_Optimization_Error_Type::QUOTA_EXCEEDED ) ->save(); } catch ( Image_File_Already_Exists_Error $fe ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::REOPTIMIZING_FAILED ) ->set_error_type( Image_Optimization_Error_Type::FILE_ALREADY_EXISTS ) ->save(); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Reoptimizing error. Reason: ' . $t->getMessage() ); ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::REOPTIMIZING_FAILED ) ->set_error_type( Image_Optimization_Error_Type::GENERIC ) ->save(); } } public function __construct() { add_action( Async_Operation_Hook::OPTIMIZE_SINGLE, [ $this, 'optimize_single_image' ] ); add_action( Async_Operation_Hook::REOPTIMIZE_SINGLE, [ $this, 'reoptimize_single_image' ] ); } } modules/optimization/components/bulk-optimization.php 0000644 00000013234 14720461212 0017323 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Components; use ImageOptimization\Classes\Async_Operation\Async_Operation_Hook; use ImageOptimization\Classes\Image\{ Image, Image_Meta, Image_Optimization_Error_Type, Image_Restore, Image_Status }; use ImageOptimization\Classes\Async_Operation\Exceptions\Async_Operation_Exception; use ImageOptimization\Classes\Logger; use ImageOptimization\Classes\Utils; use ImageOptimization\Classes\Exceptions\Quota_Exceeded_Error; use ImageOptimization\Modules\Optimization\{ Classes\Exceptions\Bulk_Token_Expired_Error, Classes\Exceptions\Image_File_Already_Exists_Error, Classes\Optimize_Image, Classes\Bulk_Optimization_Controller, Components\Exceptions\Bulk_Optimization_Token_Not_Found_Error, }; use ImageOptimization\Modules\Stats\Classes\Optimization_Stats; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Bulk_Optimization { const BULK_OPTIMIZATION_BASE_SLUG = 'image-optimization-bulk-optimization'; const BULK_OPTIMIZATION_CAPABILITY = 'manage_options'; public function render_app() { ?> <!-- The hack required to wrap WP notifications --> <div class="wrap"> <h1 style="display: none;" role="presentation"></h1> </div> <div id="image-optimization-app"></div> <?php } public function register_page() { add_media_page( __( 'Bulk Optimization', 'image-optimization' ), __( 'Bulk Optimization', 'image-optimization' ), self::BULK_OPTIMIZATION_CAPABILITY, self::BULK_OPTIMIZATION_BASE_SLUG, [ $this, 'render_app' ], 7 ); } /** @async */ public function optimize_bulk( int $image_id, string $operation_id ) { try { $bulk_token = Bulk_Optimization_Controller::get_bulk_operation_token( $operation_id ); $oi = new Optimize_Image( $image_id, 'bulk', $bulk_token ); $oi->optimize(); } catch ( Quota_Exceeded_Error $qe ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::OPTIMIZATION_FAILED ) ->set_error_type( Image_Optimization_Error_Type::QUOTA_EXCEEDED ) ->save(); } catch ( Image_File_Already_Exists_Error $fe ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::OPTIMIZATION_FAILED ) ->set_error_type( Image_Optimization_Error_Type::FILE_ALREADY_EXISTS ) ->save(); } catch ( Bulk_Token_Expired_Error | Bulk_Optimization_Token_Not_Found_Error $bte ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::NOT_OPTIMIZED ) ->save(); Bulk_Optimization_Controller::reschedule_bulk_optimization(); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Optimization error. Reason: ' . $t->getMessage() ); ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::OPTIMIZATION_FAILED ) ->set_error_type( Image_Optimization_Error_Type::GENERIC ) ->save(); } finally { Optimization_Stats::get_image_stats( null, true ); } } /** @async */ public function reoptimize_bulk( int $image_id, string $operation_id ) { try { $image = new Image( $image_id ); if ( $image->can_be_restored() ) { Image_Restore::restore( $image_id, true ); } $bulk_token = Bulk_Optimization_Controller::get_bulk_operation_token( $operation_id ); $oi = new Optimize_Image( $image_id, 'bulk', $bulk_token, true ); $oi->optimize(); } catch ( Quota_Exceeded_Error $qe ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::REOPTIMIZING_FAILED ) ->set_error_type( Image_Optimization_Error_Type::QUOTA_EXCEEDED ) ->save(); } catch ( Image_File_Already_Exists_Error $fe ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::REOPTIMIZING_FAILED ) ->set_error_type( Image_Optimization_Error_Type::FILE_ALREADY_EXISTS ) ->save(); } catch ( Bulk_Token_Expired_Error | Bulk_Optimization_Token_Not_Found_Error $bte ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::NOT_OPTIMIZED ) ->save(); Bulk_Optimization_Controller::reschedule_bulk_reoptimization(); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Reoptimization error. Reason: ' . $t->getMessage() ); ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::REOPTIMIZING_FAILED ) ->set_error_type( Image_Optimization_Error_Type::GENERIC ) ->save(); } finally { Optimization_Stats::get_image_stats( null, true ); } } /** * Renders the bulk optimization notice * * @return void */ public function render_bulk_optimization_notice() { try { $is_in_progress = Bulk_Optimization_Controller::is_optimization_in_progress(); } catch ( Async_Operation_Exception $aoe ) { $is_in_progress = false; } ?> <div class="notice notice-info notice image-optimizer__notice image-optimizer__notice--info image-optimizer__notice--bulk-tip" style="display: <?php echo $is_in_progress ? 'block' : 'none'; ?>"> <p> <b> <?php esc_html_e( 'Heads up!', 'image-optimization' ); ?> </b> <span> <?php esc_html_e( 'Bulk optimizing may take a lot of processing and server time, depending on the number of images. Your site will still work smoothly until the processing is all done, without any downtime.', 'image-optimization' ); ?> </span> </p> </div> <?php } public function __construct() { add_action( 'admin_menu', [ $this, 'register_page' ] ); add_action( Async_Operation_Hook::OPTIMIZE_BULK, [ $this, 'optimize_bulk' ], 10, 2 ); add_action( Async_Operation_Hook::REOPTIMIZE_BULK, [ $this, 'reoptimize_bulk' ], 10, 2 ); add_action('current_screen', function () { if ( Utils::is_bulk_optimization_page() ) { add_filter( 'admin_footer_text', [ $this, 'render_bulk_optimization_notice' ] ); } }); } } modules/optimization/components/media-control.php 0000644 00000021044 14720461212 0016375 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Components; use ImageOptimization\Classes\Image\{ Exceptions\Invalid_Image_Exception, Image, Image_Conversion, Image_Conversion_Option, Image_Meta, Image_Optimization_Error_Type, Image_Status }; use ImageOptimization\Modules\Oauth\Components\{ Exceptions\Auth_Error, }; use ImageOptimization\Modules\Optimization\{ Classes\Exceptions\Image_Validation_Error, Classes\Optimization_Error_Message, Classes\Validate_Image, Module, }; use ImageOptimization\Classes\File_Utils; use ImageOptimization\Modules\Settings\Classes\Settings; use ImageOptimization\Modules\Stats\Classes\Optimization_Stats; use Throwable; use ImageOptimization\Plugin; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } /** * The class is responsible for rendering optimization control in all views. */ class Media_Control { const COLUMN_ID = 'image_optimization'; const META_BOX_ID = 'image_optimization_meta_box'; const DETAILS_MODAL_FIELD_ID = 'image_optimization_modal'; /** * Adds a new optimization column to the library list view. * * @param array $columns * @return array */ public function add_optimization_column( array $columns ): array { if ( empty( $columns ) ) { return $columns; } $columns[ self::COLUMN_ID ] = esc_html__( 'Image optimization', 'image-optimization' ); return $columns; } /** * Renders optimization controls in the library list view. * * @param string $column_name * @param int $attachment_id * @return void */ public function render_optimization_column( string $column_name, int $attachment_id ) { if ( self::COLUMN_ID !== $column_name ) { return; } $this->render_optimization_control( 'list-view', $attachment_id ); } /** * Adds optimization control as media meta box. * * @return void */ public function add_optimization_meta_box() { add_meta_box( self::META_BOX_ID, __( 'Image optimization', 'image-optimization' ), function( $post ) { $this->render_optimization_control( 'meta-box', $post->ID ); }, 'attachment', 'side', ); } /** * Adds optimization control to media modals. * * @param array $form_fields * @param \WP_Post $post * * @return array */ public function add_media_modal_details( array $form_fields, \WP_Post $post ): array { $form_fields[ self::DETAILS_MODAL_FIELD_ID ] = [ 'label' => '', 'input' => 'hidden', 'value' => $this->get_optimization_control_html( 'details-view', $post->ID ), 'required' => false, ]; return $form_fields; } /** * Returns optimization control as an HTML string. * * @param string $context Control placement context. One of ['list-view', 'meta-box', 'details-view']. * @param int $image_id Attachment id. * @return false|string */ public function get_optimization_control_html( string $context, int $image_id ) { ob_start(); $this->render_optimization_control( $context, $image_id ); $html = ob_get_contents(); ob_end_clean(); return $html; } /** * Renders the optimization control for the current image in the current context. * * @param string $context Control placement context. One of ['list-view', 'meta-box', 'details-view']. * @param int $image_id Attachment id. * @return void Renders the control. */ public function render_optimization_control( string $context, int $image_id ) { $global_context = [ 'image_id' => $image_id, 'can_be_restored' => false, ]; // @var ImageOptimizer/Modules/ConnectManager/Module $module = Plugin::instance()->modules_manager->get_modules( 'connect-manager' ); try { if ( ! $module->connect_instance->is_connected() || ! $module->connect_instance->is_activated() ) { throw new Auth_Error( 'You have to activate your license to use Image Optimizer' ); } Validate_Image::is_valid( $image_id ); $image = new Image( $image_id ); $meta = new Image_Meta( $image->get_id() ); if ( Image_Status::OPTIMIZED === $meta->get_status() ) { $global_context['can_be_restored'] = $image->can_be_restored(); } else { $ic = new Image_Conversion(); $path = $image->get_file_path( Image::SIZE_FULL ); $backups_enabled = Settings::get( Settings::BACKUP_ORIGINAL_IMAGES_OPTION_NAME ); $conversion_enabled = $ic->is_enabled(); $needs_conversion = $conversion_enabled && strtolower( File_Utils::get_extension( $path ) ) !== $ic->get_current_file_extension(); $global_context['can_be_restored'] = ( $needs_conversion && $conversion_enabled ) || $backups_enabled; } switch ( $meta->get_status() ) { case Image_Status::OPTIMIZATION_IN_PROGRESS: Module::load_template( $context, 'loading', array_merge( $global_context, [ 'action' => 'optimize', ] ) ); break; case Image_Status::REOPTIMIZING_IN_PROGRESS: Module::load_template( $context, 'loading', array_merge( $global_context, [ 'action' => 'reoptimize', ] ) ); break; case Image_Status::RESTORING_IN_PROGRESS: Module::load_template( $context, 'loading', array_merge( $global_context, [ 'action' => 'restore', ] ) ); break; case Image_Status::OPTIMIZED: $stats = Optimization_Stats::get_image_stats( $image_id ); $saved = [ 'relative' => max( 100 - round( $stats['current_image_size'] / $stats['initial_image_size'] * 100 ), 0 ), 'absolute' => $stats['initial_image_size'] - $stats['current_image_size'], ]; $is_losseless_and_webp = Image_Conversion_Option::WEBP === Settings::get( Settings::CONVERT_TO_FORMAT_OPTION_NAME ) && 'lossless' === Settings::get( Settings::COMPRESSION_LEVEL_OPTION_NAME ); Module::load_template( $context, 'optimized', array_merge( $global_context, [ 'sizes_optimized_count' => $stats['optimized_image_count'], 'saved' => $saved, 'is_losseless_and_webp' => $is_losseless_and_webp, ] ) ); break; case Image_Status::OPTIMIZATION_FAILED: $error_type = $meta->get_error_type() ?? Image_Optimization_Error_Type::GENERIC; $error_message = Optimization_Error_Message::get_optimization_error_message( $error_type ); $images_left = $module->connect_instance->images_left(); Module::load_template( $context, 'error', array_merge( $global_context, [ 'message' => $error_message, 'optimization_error_type' => $error_type, 'images_left' => $images_left, 'allow_retry' => true, 'action' => 'optimize', ] ) ); break; case Image_Status::REOPTIMIZING_FAILED: $error_type = $meta->get_error_type() ?? Image_Optimization_Error_Type::GENERIC; $error_message = Optimization_Error_Message::get_reoptimization_error_message( $error_type ); $images_left = $module->connect_instance->images_left(); Module::load_template( $context, 'error', array_merge( $global_context, [ 'message' => $error_message, 'optimization_error_type' => $error_type, 'images_left' => $images_left, 'allow_retry' => true, 'action' => 'reoptimize', ] ) ); break; case Image_Status::RESTORING_FAILED: Module::load_template( $context, 'error', array_merge( $global_context, [ 'message' => esc_html__( 'Image restoring error', 'image-optimization' ), 'allow_retry' => true, 'action' => 'restore', ] ) ); break; default: Module::load_template( $context, 'not-optimized', $global_context ); } } catch ( Invalid_Image_Exception | Image_Validation_Error $iie ) { Module::load_template( $context, 'error', array_merge( $global_context, [ 'action' => 'error', 'message' => $iie->getMessage(), 'allow_retry' => false, ] ) ); } catch ( Auth_Error $ae ) { Module::load_template( $context, 'error', array_merge( $global_context, [ 'action' => 'error', 'message' => esc_html__( 'N/A', 'image-optimization' ), 'allow_retry' => false, ] ) ); } catch ( Throwable $t ) { Module::load_template( $context, 'error', array_merge( $global_context, [ 'action' => 'error', 'message' => esc_html__( 'Internal server error', 'image-optimization' ), 'allow_retry' => false, ] ) ); } } public function __construct() { add_filter( 'manage_upload_columns', [ $this, 'add_optimization_column' ] ); add_action( 'manage_media_custom_column', [ $this, 'render_optimization_column' ], 10, 2 ); add_action( 'add_meta_boxes_attachment', [ $this, 'add_optimization_meta_box' ] ); add_filter( 'attachment_fields_to_edit', [ $this, 'add_media_modal_details' ], 10, 2 ); } } modules/optimization/components/admin-bulk-actions.php 0000644 00000002343 14720461212 0017322 0 ustar 00 <?php namespace ImageOptimization\Modules\Optimization\Components; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } use ImageOptimization\Modules\Backups\Classes\Restore_Images; use ImageOptimization\Modules\Optimization\Classes\Single_Optimization as Single_Optimization_Controller; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Admin_Bulk_Actions { public function add_bulk_actions( array $bulk_actions ): array { $bulk_actions['image-optimization-optimize'] = esc_html__( 'Optimize', 'image-optimization' ); $bulk_actions['image-optimization-restore'] = esc_html__( 'Restore original', 'image-optimization' ); return $bulk_actions; } public function handle_bulk_actions( $redirect_url, $action, $post_ids ): string { if ( 'image-optimization-optimize' === $action ) { Single_Optimization_Controller::optimize_many( $post_ids ); } if ( 'image-optimization-restore' === $action ) { Restore_Images::find_and_schedule_restoring( $post_ids ); } return $redirect_url; } public function __construct() { add_filter( 'bulk_actions-upload', [ $this, 'add_bulk_actions' ] ); add_filter( 'handle_bulk_actions-upload', [ $this, 'handle_bulk_actions' ], 10, 3 ); } } modules/optimization/templates/details-view/optimized.php 0000644 00000006307 14720461212 0020057 0 ustar 00 <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } use ImageOptimization\Classes\File_Utils; ?> <div class="image-optimization-control image-optimization-control--details-view image-optimization-control--optimized" data-image-optimization-context="details-view" data-image-optimization-status="optimized" data-image-optimization-image-id="<?php echo esc_attr( $args['image_id'] ); ?>" data-image-optimization-can-be-restored="<?php echo esc_attr( $args['can_be_restored'] ); ?>"> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"> <?php esc_html_e( 'Status', 'image-optimization' ); ?>: </span> <span class="image-optimization-control__property-value"> <?php esc_html_e( 'Optimized', 'image-optimization' ); ?> </span> </span> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"> <?php esc_html_e( 'Image sizes optimized', 'image-optimization' ); ?>: </span> <span class="image-optimization-control__property-value"> <?php echo esc_html( $args['sizes_optimized_count'] ); ?> </span> </span> <span class="setting image-optimization-setting"> <?php if ( 0 === $args['saved']['absolute'] ) { ?> <span class="name image-optimization-control__property"></span> <span class="name image-optimization-control__property-value" style="max-width: 50%;"> <?php if ( $args['is_losseless_and_webp'] ) { echo esc_html_e( 'Requested WebP format is larger than the original file. Switch to Lossy in settings to convert this image in an optimized manner.', 'image-optimization' ); } else { echo esc_html_e( 'Image is fully optimized', 'image-optimization' ); } ?> </span> <?php } else { ?> <span class="name image-optimization-control__property"> <?php esc_html_e( 'Overall saving', 'image-optimization' ); ?>: </span> <span class="image-optimization-control__property-value"> <?php printf( esc_html__( '%1$s%% (%2$s)', 'image-optimization' ), esc_html( $args['saved']['relative'] ), esc_html( File_Utils::format_file_size( $args['saved']['absolute'], 1 ) ) ); ?> </span> <?php } ?> </span> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"></span> <span class="image-optimization-control__property-value image-optimization-control__property-value--button"> <button class="button button-link image-optimization-control__button image-optimization-control__button--reoptimize" type="button"> <?php esc_html_e( 'Reoptimize', 'image-optimization' ); ?> </button> </span> </span> <?php if ( $args['can_be_restored'] ) { ?> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"></span> <span class="image-optimization-control__property-value image-optimization-control__property-value--button"> <button class="button button-link image-optimization-control__button image-optimization-control__button--restore-original" type="button"> <?php esc_html_e( 'Restore original', 'image-optimization' ); ?> </button> </span> </span> <?php } ?> </div> modules/optimization/templates/details-view/error.php 0000644 00000004230 14720461212 0017175 0 ustar 00 <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } ?> <div class="image-optimization-control image-optimization-control--details-view image-optimization-control--error" data-image-optimization-context="details-view" data-image-optimization-status="error" data-image-allow-retry="<?php echo esc_attr( $args['allow_retry'] ); ?>" data-image-optimization-action="<?php echo esc_attr( $args['action'] ); ?>" data-image-optimization-image-id="<?php echo esc_attr( $args['image_id'] ); ?>" data-image-optimization-can-be-restored="<?php echo esc_attr( $args['can_be_restored'] ); ?>"> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"> <?php esc_html_e( 'Status', 'image-optimization' ); ?>: </span> <span class="image-optimization-control__property-value"> <?php esc_html_e( 'Error', 'image-optimization' ); ?> </span> </span> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"> <?php esc_html_e( 'Reason', 'image-optimization' ); ?>: </span> <span class="image-optimization-control__property-value"> <?php echo esc_html( $args['message'] ); ?> </span> </span> <?php if ( $args['allow_retry'] ) { ?> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"></span> <span class="image-optimization-control__property-value image-optimization-control__property-value--button"> <?php if ( isset( $args['images_left'] ) && 0 === $args['images_left'] ) { ?> <a class="button button-secondary button-large image-optimization-control__button" href="https://go.elementor.com/io-panel-upgrade/" target="_blank" rel="noopener noreferrer"> <?php esc_html_e( 'Upgrade', 'image-optimization' ); ?> </a> <?php } else { ?> <button class="button button-secondary button-large button-link-delete image-optimization-control__button image-optimization-control__button--try-again" type="button"> <?php esc_html_e( 'Try again', 'image-optimization' ); ?> </button> <?php } ?> </span> </span> <?php } ?> </div> modules/optimization/templates/details-view/not-optimized.php 0000644 00000002402 14720461212 0020645 0 ustar 00 <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } ?> <div class="image-optimization-control image-optimization-control--details-view image-optimization-control--not-optimized" data-image-optimization-context="details-view" data-image-optimization-status="not-optimized" data-image-optimization-image-id="<?php echo esc_attr( $args['image_id'] ); ?>" data-image-optimization-can-be-restored="<?php echo esc_attr( $args['can_be_restored'] ); ?>"> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"> <?php esc_html_e( 'Status', 'image-optimization' ); ?>: </span> <span class="image-optimization-control__property-value"> <?php esc_html_e( 'Not optimized', 'image-optimization' ); ?> </span> </span> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"></span> <span class="image-optimization-control__property-value image-optimization-control__property-value--button"> <button type="button" class="button button-primary image-optimization-control__button image-optimization-control__button--optimize"> <?php esc_html_e( 'Optimize now', 'image-optimization' ); ?> </button> </span> </span> </div> modules/optimization/templates/details-view/loading.php 0000644 00000002220 14720461212 0017456 0 ustar 00 <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } ?> <div class="image-optimization-control image-optimization-control--details-view image-optimization-control--loading" data-image-optimization-context="details-view" data-image-optimization-status="loading" data-image-optimization-action="<?php echo esc_attr( $args['action'] ); ?>" data-image-optimization-image-id="<?php echo esc_attr( $args['image_id'] ); ?>" data-image-optimization-can-be-restored="<?php echo esc_attr( $args['can_be_restored'] ); ?>"> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"> <?php esc_html_e( 'Status', 'image-optimization' ); ?>: </span> <span class="image-optimization-control__property-value"> <?php esc_html_e( 'In Progress', 'image-optimization' ); ?> </span> </span> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"></span> <span class="image-optimization-control__property-value image-optimization-control__property-value--spinner"> <span class="spinner is-active"></span> </span> </span> </div> modules/optimization/templates/list-view/optimized.php 0000644 00000004072 14720461212 0017402 0 ustar 00 <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } use ImageOptimization\Classes\File_Utils; ?> <div class="image-optimization-control image-optimization-control--list-view image-optimization-control--optimized" data-image-optimization-context="list-view" data-image-optimization-status="optimized" data-image-optimization-image-id="<?php echo esc_attr( $args['image_id'] ); ?>" data-image-optimization-can-be-restored="<?php echo esc_attr( $args['can_be_restored'] ); ?>"> <p class="image-optimization-control__property"> <?php esc_html_e( 'Image sizes optimized', 'image-optimization' ); ?>: <span><?php echo esc_html( $args['sizes_optimized_count'] ); ?></span> </p> <p class="image-optimization-control__property"> <?php if ( 0 === $args['saved']['absolute'] ) { ?> <span> <?php if ( $args['is_losseless_and_webp'] ) { echo esc_html_e( 'Requested WebP format is larger than the original file. Switch to Lossy in settings to convert this image in an optimized manner.', 'image-optimization' ); } else { echo esc_html_e( 'Image is fully optimized', 'image-optimization' ); } ?> </span> <?php } else { ?> <?php esc_html_e( 'Overall saving', 'image-optimization' ); ?>: <span> <?php printf( esc_html__( '%1$s%% (%2$s)', 'image-optimization' ), esc_html( $args['saved']['relative'] ), esc_html( File_Utils::format_file_size( $args['saved']['absolute'], 1 ) ) ); ?> </span> <?php } ?> </p> <div class="image-optimization-control__buttons-wrapper"> <?php if ( $args['can_be_restored'] ) { ?> <button type="button" class="button button-secondary image-optimization-control__button image-optimization-control__button--restore-original"> <?php esc_html_e( 'Restore original', 'image-optimization' ); ?> </button> <?php } ?> <button type="button" class="button button-secondary image-optimization-control__button image-optimization-control__button--reoptimize"> <?php esc_html_e( 'Reoptimize', 'image-optimization' ); ?> </button> </div> </div> modules/optimization/templates/list-view/error.php 0000644 00000003362 14720461212 0016530 0 ustar 00 <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } ?> <div class="image-optimization-control image-optimization-control--list-view image-optimization-control--error" data-image-optimization-context="list-view" data-image-optimization-status="error" data-image-allow-retry="<?php echo esc_attr( $args['allow_retry'] ); ?>" data-image-optimization-action="<?php echo esc_attr( $args['action'] ); ?>" data-image-optimization-image-id="<?php echo esc_attr( $args['image_id'] ); ?>" data-image-optimization-can-be-restored="<?php echo esc_attr( $args['can_be_restored'] ); ?>"> <?php $message = esc_html( $args['message'] ); if ( false === $args['allow_retry'] ) { $message_chunks = explode( '. ', $message, 2 ); $message = "<span class='image-optimization-control__error-title'>{$message_chunks[0]}</span>"; if ( isset( $message_chunks[1] ) ) { $message .= "<span class='image-optimization-control__error-subtitle'>{$message_chunks[1]}</span>"; } } ?> <span class='image-optimization-control__error-message'><?php echo $message; ?></span> <?php if ( $args['allow_retry'] ) { ?> <?php if ( isset( $args['images_left'] ) && 0 === $args['images_left'] ) { ?> <a class="button button-secondary button-large image-optimization-control__button" href="https://go.elementor.com/io-panel-upgrade/" target="_blank" rel="noopener noreferrer"> <?php esc_html_e( 'Upgrade', 'image-optimization' ); ?> </a> <?php } else { ?> <button class="button button-secondary button-large button-link-delete image-optimization-control__button image-optimization-control__button--try-again" type="button"> <?php esc_html_e( 'Try again', 'image-optimization' ); ?> </button> <?php } ?> <?php } ?> </div> modules/optimization/templates/list-view/not-optimized.php 0000644 00000001266 14720461212 0020202 0 ustar 00 <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } ?> <div class="image-optimization-control image-optimization-control--list-view image-optimization-control--not-optimized" data-image-optimization-context="list-view" data-image-optimization-status="not-optimized" data-image-optimization-image-id="<?php echo esc_attr( $args['image_id'] ); ?>" data-image-optimization-can-be-restored="<?php echo esc_attr( $args['can_be_restored'] ); ?>"> <button type="button" class="button button-primary image-optimization-control__button image-optimization-control__button--optimize"> <?php esc_html_e( 'Optimize now', 'image-optimization' ); ?> </button> </div> modules/optimization/templates/list-view/loading.php 0000644 00000002143 14720461212 0017010 0 ustar 00 <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } ?> <div class="image-optimization-control image-optimization-control--list-view image-optimization-control--loading" data-image-optimization-context="list-view" data-image-optimization-status="loading" data-image-optimization-action="<?php echo esc_attr( $args['action'] ); ?>" data-image-optimization-image-id="<?php echo esc_attr( $args['image_id'] ); ?>" data-image-optimization-can-be-restored="<?php echo esc_attr( $args['can_be_restored'] ); ?>"> <button class="button button-secondary image-optimization-control__button image-optimization-control__button--optimize" disabled=""> <span class="spinner is-active"></span> <?php switch ( $args['action'] ) { case 'restore': esc_html_e( 'Restoring…', 'image-optimization' ); break; case 'optimize': esc_html_e( 'Optimizing…', 'image-optimization' ); break; case 'reoptimize': esc_html_e( 'Reoptimizing…', 'image-optimization' ); break; default: esc_html_e( 'Loading…', 'image-optimization' ); } ?> </button> </div> modules/optimization/templates/meta-box/optimized.php 0000644 00000004713 14720461212 0017175 0 ustar 00 <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } use ImageOptimization\Classes\File_Utils; ?> <div class="image-optimization-control image-optimization-control--meta-box image-optimization-control--optimized" data-image-optimization-context="meta-box" data-image-optimization-status="optimized" data-image-optimization-image-id="<?php echo esc_attr( $args['image_id'] ); ?>" data-image-optimization-can-be-restored="<?php echo esc_attr( $args['can_be_restored'] ); ?>"> <p class="image-optimization-control__property"> <?php esc_html_e( 'Status', 'image-optimization' ); ?>: <span class="image-optimization-control__property-value"> <?php esc_html_e( 'Optimized', 'image-optimization' ); ?> </span> </p> <p class="image-optimization-control__property"> <?php esc_html_e( 'Image sizes optimized', 'image-optimization' ); ?>: <span class="image-optimization-control__property-value"> <?php echo esc_html( $args['sizes_optimized_count'] ); ?> </span> </p> <p class="image-optimization-control__property"> <?php if ( 0 === $args['saved']['absolute'] ) { ?> <span class="image-optimization-control__property-value"> <?php if ( $args['is_losseless_and_webp'] ) { echo esc_html_e( 'Requested WebP format is larger than the original file. Switch to Lossy in settings to convert this image in an optimized manner.', 'image-optimization' ); } else { echo esc_html_e( 'Image is fully optimized', 'image-optimization' ); } ?> </span> <?php } else { ?> <?php esc_html_e( 'Overall saving', 'image-optimization' ); ?>: <span class="image-optimization-control__property-value"> <?php printf( esc_html__( '%1$s%% (%2$s)', 'image-optimization' ), esc_html( $args['saved']['relative'] ), esc_html( File_Utils::format_file_size( $args['saved']['absolute'], 1 ) ) ); ?> </span> <?php } ?> </p> <div class="image-optimization-control__action-button-wrapper"> <?php if ( $args['can_be_restored'] ) { ?> <button class="button button-link image-optimization-control__button image-optimization-control__button--restore-original" type="button"> <?php esc_html_e( 'Restore original', 'image-optimization' ); ?> </button> <?php } ?> <button class="button button-link image-optimization-control__button image-optimization-control__button--reoptimize" type="button"> <?php esc_html_e( 'Reoptimize', 'image-optimization' ); ?> </button> </div> </div> modules/optimization/templates/meta-box/error.php 0000644 00000003476 14720461212 0016327 0 ustar 00 <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } ?> <div class="image-optimization-control image-optimization-control--meta-box image-optimization-control--error" data-image-optimization-context="meta-box" data-image-optimization-status="error" data-image-allow-retry="<?php echo esc_attr( $args['allow_retry'] ); ?>" data-image-optimization-action="<?php echo esc_attr( $args['action'] ); ?>" data-image-optimization-image-id="<?php echo esc_attr( $args['image_id'] ); ?>" data-image-optimization-can-be-restored="<?php echo esc_attr( $args['can_be_restored'] ); ?>"> <p class="image-optimization-control__property"> <?php esc_html_e( 'Status', 'image-optimization' ); ?>: <span class="image-optimization-control__property-value"> <?php esc_html_e( 'Error', 'image-optimization' ); ?> </span> </p> <p class="image-optimization-control__property"> <?php esc_html_e( 'Reason', 'image-optimization' ); ?>: <span class="image-optimization-control__property-value"> <?php echo esc_html( $args['message'] ); ?> </span> </p> <?php if ( $args['allow_retry'] ) { ?> <div class="image-optimization-control__action-button-wrapper"> <?php if ( isset( $args['images_left'] ) && 0 === $args['images_left'] ) { ?> <a class="button button-secondary button-large image-optimization-control__button" href="https://go.elementor.com/io-panel-upgrade/" target="_blank" rel="noopener noreferrer"> <?php esc_html_e( 'Upgrade', 'image-optimization' ); ?> </a> <?php } else { ?> <button class="button button-secondary button-large button-link-delete image-optimization-control__button image-optimization-control__button--try-again" type="button"> <?php esc_html_e( 'Try again', 'image-optimization' ); ?> </button> <?php } ?> </div> <?php } ?> </div> modules/optimization/templates/meta-box/not-optimized.php 0000644 00000001775 14720461212 0020000 0 ustar 00 <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } ?> <div class="image-optimization-control image-optimization-control--meta-box image-optimization-control--not-optimized" data-image-optimization-context="meta-box" data-image-optimization-status="not-optimized" data-image-optimization-image-id="<?php echo esc_attr( $args['image_id'] ); ?>" data-image-optimization-can-be-restored="<?php echo esc_attr( $args['can_be_restored'] ); ?>"> <p class="image-optimization-control__property"> <?php esc_html_e( 'Status', 'image-optimization' ); ?>: <span class="image-optimization-control__property-value"> <?php esc_html_e( 'Not optimized', 'image-optimization' ); ?> </span> </p> <div class="image-optimization-control__action-button-wrapper"> <button type="button" class="button button-primary image-optimization-control__button image-optimization-control__button--optimize"> <?php esc_html_e( 'Optimize now', 'image-optimization' ); ?> </button> </div> </div> modules/optimization/templates/meta-box/loading.php 0000644 00000001616 14720461212 0016605 0 ustar 00 <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } ?> <div class="image-optimization-control image-optimization-control--meta-box image-optimization-control--loading" data-image-optimization-context="meta-box" data-image-optimization-status="loading" data-image-optimization-action="<?php echo esc_attr( $args['action'] ); ?>" data-image-optimization-image-id="<?php echo esc_attr( $args['image_id'] ); ?>" data-image-optimization-can-be-restored="<?php echo esc_attr( $args['can_be_restored'] ); ?>"> <p class="image-optimization-control__property"> <?php esc_html_e( 'Status', 'image-optimization' ); ?>: <span class="image-optimization-control__property-value"> <?php esc_html_e( 'In Progress', 'image-optimization' ); ?> </span> </p> <div class="image-optimization-control__action-spinner-wrapper"> <span class="spinner is-active"></span> </div> </div> modules/optimization/assets/css/control.css 0000644 00000006244 14720461212 0015233 0 ustar 00 .image-optimization-control--list-view { display: flex; justify-content: flex-start; align-items: center; min-height: 105px; } .image-optimization-control--list-view.image-optimization-control--error { justify-content: center; align-items: flex-start; } .image-optimization-control__buttons-wrapper { margin-block-start: 8px; } .image-optimization-control__buttons-wrapper :not(:last-of-type) { margin-inline-end: 8px; } .image-optimization-control--error { flex-direction: column; } .image-optimization-control--optimized { flex-direction: column; align-items: flex-start; } .image-optimization-control__error-message { display: flex; flex-direction: column; font-family: Roboto, sans-serif; font-size: 14px; font-weight: 600; line-height: 24px; margin-block-end: 15px; max-width: 200px; } .image-optimization-control__error-title { margin-block-end: 10px; } .image-optimization-control__error-subtitle { color: #DC2626; } .image-optimization-control__button { font-family: Roboto, sans-serif; font-weight: 500; border-radius: 4px; } .image-optimization-control__button--optimize > .spinner { float: left; padding: 0; margin-block-start: 4px; margin-left: 0; margin-block-end: 0; } .image-optimization-control--error .image-optimization-control__button--try-again, .image-optimization-control--error .image-optimization-control__button--try-again:hover { color: #DC2626; border-color: #DC2626; background: transparent; } .image-optimization-control__property { margin: 9px 0; } .image-optimization-control__property:last-of-type { margin-block-end: 0; } .image-optimization-control .image-optimization-setting { margin-block-end: 0; } .image-optimization-control__property-value, .image-optimization-control--details-view .setting .image-optimization-control__property-value { font-weight: 600; font-size: 13px; line-height: 24px; } .image-optimization-control--details-view .setting .image-optimization-control__property-value { margin: 6px 3px 3px; text-align: start; } .image-optimization-control--details-view .setting .image-optimization-control__property-value--button { margin: 0 0 0 3px; font-weight: initial; } .image-optimization-control--details-view .setting .image-optimization-control__property-value--spinner { display: flex; justify-content: center; margin: 25px 0 0 3px; } .image-optimization-control__action-button-wrapper { margin-block-start: 37px; display: flex; width: 100%; justify-content: flex-end; } .image-optimization-control__action-button-wrapper .button-link:not(:last-of-type) { margin-inline-end: 24px; } .image-optimization-control__action-button-wrapper .button-link, .image-optimization-control--details-view .image-optimization-control__property-value--button .button-link { text-decoration: none; } .image-optimization-control__action-button-wrapper .button-link:hover, .image-optimization-control--details-view .image-optimization-control__property-value--button .button-link:hover { background-color: transparent; } .image-optimization-control__action-spinner-wrapper { height: 75px; display: flex; justify-content: center; align-items: center; } div .components-tooltip { max-width: 165px; text-align: start; } modules/optimization/assets/js/classes/api.js 0000644 00000002375 14720461212 0015432 0 ustar 00 import apiFetch from '@wordpress/api-fetch'; import APIError from './exceptions/APIError'; const v1Prefix = '/image-optimizer/v1'; class API { static async request( { path, data, method = 'POST' } ) { try { const response = await apiFetch( { path, method, data, } ); if ( ! response.success ) { throw new APIError( response.data.message ); } return response.data; } catch ( e ) { if ( e instanceof APIError ) { throw e; } else { throw new APIError( e.message ); } } } static async optimizeSingleImage( { imageId, reoptimize = false } ) { return API.request( { path: `${ v1Prefix }/optimize/image`, data: { imageId, reoptimize, 'image-optimization-optimize-image': window?.imageOptimizerControlSettings?.optimizeSingleImageNonce, }, } ); } static async restoreSingleImage( imageId ) { return API.request( { path: `${ v1Prefix }/backups/restore/${ imageId }`, data: { 'image-optimization-restore-single': window?.imageOptimizerControlSettings?.restoreSingleImageNonce, }, } ); } static async getOptimizationStatus( imageIds ) { return API.request( { path: `${ v1Prefix }/optimize/status`, data: { image_ids: imageIds, }, } ); } } export default API; modules/optimization/assets/js/classes/extend-views.js 0000644 00000004231 14720461212 0017274 0 ustar 00 class ExtendViews { constructor() { this.init(); } init() { this.extendAttachmentDetails(); this.extendAttachmentDetailsTwoColumn(); } // #tmpl-attachment-details extendAttachmentDetails() { if ( ! wp?.media?.view?.Attachment?.Details ) { return; } wp.media.view.Attachment.Details = wp.media.view.Attachment.Details.extend( { template( view ) { const html = wp.media.template( 'attachment-details' )( view ); if ( this.model.attributes.type !== 'image' ) { return html; } const content = document.createElement( 'div' ); content.innerHTML = html; const optimizationControl = this.getOptimizationControlHTML( view.compat.item ); if ( ! optimizationControl ) { return content.innerHTML; } content.innerHTML += optimizationControl; return content.innerHTML; }, getOptimizationControlHTML( compatData ) { const tempElement = document.createElement( 'div' ); tempElement.innerHTML = compatData; return tempElement.querySelector( 'input[name*="[image_optimization_modal]"]' )?.value; }, } ); } // #tmpl-attachment-details-two-column extendAttachmentDetailsTwoColumn() { if ( ! wp?.media?.view?.Attachment?.Details?.TwoColumn ) { return; } wp.media.view.Attachment.Details.TwoColumn = wp.media.view.Attachment.Details.TwoColumn.extend( { template( view ) { const html = wp.media.template( 'attachment-details-two-column' )( view ); if ( this.model.attributes.type !== 'image' ) { return html; } const content = document.createElement( 'div' ); content.innerHTML = html; const optimizationControl = this.getOptimizationControlHTML( view.compat.item ); if ( ! optimizationControl ) { return content.innerHTML; } const settings = content.querySelector( '.settings' ); settings.innerHTML += optimizationControl; return content.innerHTML; }, getOptimizationControlHTML( compatData ) { const tempElement = document.createElement( 'div' ); tempElement.innerHTML = compatData; return tempElement.querySelector( 'input[name*="[image_optimization_modal]"]' )?.value; }, } ); } } export default ExtendViews; modules/optimization/assets/js/classes/exceptions/APIError.js 0000644 00000000207 14720461212 0020455 0 ustar 00 class APIError extends Error { constructor( message ) { super( message ); this.name = 'APIError'; } } export default APIError; modules/optimization/assets/js/classes/control/control-sync.js 0000644 00000004760 14720461212 0020773 0 ustar 00 import API from '../api'; import { SELECTORS } from '../../constants'; import ControlMeta from './control-meta'; import ControlStates from './control-states'; class ControlSync { async run() { const controls = document.querySelectorAll( SELECTORS.controlWrapperSelector ); if ( ! controls.length ) { return; } const imageIds = this.mapImageIds( controls ); const { status } = await API.getOptimizationStatus( imageIds ); controls.forEach( ( controlWrapper ) => { const imageId = new ControlMeta( controlWrapper ).getImageId(); const currentStatus = new ControlMeta( controlWrapper ).getStatus(); const imageData = status[ imageId ]; const controlStates = new ControlStates( controlWrapper ); if ( currentStatus === imageData.status ) { return; } if ( controlWrapper.dataset.isFrozen === 'true' ) { controlWrapper.dataset.isFrozen = false; return; } if ( currentStatus === 'error' && ! new ControlMeta( controlWrapper ).allowRetry() ) { return; } switch ( imageData.status ) { case 'optimization-in-progress': controlStates.renderLoading( 'optimize' ); break; case 'reoptimizing-in-progress': controlStates.renderLoading( 'reoptimize' ); break; case 'restoring-in-progress': controlStates.renderLoading( 'restore' ); break; case 'not-optimized': controlStates.renderNotOptimized(); break; case 'optimized': const statsData = { sizesOptimized: imageData.stats.optimized_image_count, saved: { absolute: imageData.stats.initial_image_size - imageData.stats.current_image_size, relative: Math.max( 100 - Math.round( imageData.stats.current_image_size / imageData.stats.initial_image_size * 100 ), 0 ), }, }; controlStates.renderOptimized( statsData ); break; case 'optimization-failed': controlStates.renderError( { message: imageData.message, imagesLeft: imageData.images_left, action: 'optimize', } ); break; case 'reoptimizing-failed': controlStates.renderError( { message: imageData.message, imagesLeft: imageData.images_left, action: 'reoptimize', } ); break; case 'restoring-failed': controlStates.renderError( { message: imageData.message, action: 'restore', } ); } } ); } mapImageIds( nodes ) { return Array.prototype.map.call( nodes, ( node ) => new ControlMeta( node ).getImageId(), ); } } export default ControlSync; modules/optimization/assets/js/classes/control/control-states.js 0000644 00000004767 14720461212 0021331 0 ustar 00 import listViewTemplates from '../../templates/list-view'; import metaBoxTemplates from '../../templates/meta-box'; import detailsViewTemplates from '../../templates/details-view'; import { SELECTORS } from '../../constants'; import ControlMeta from './control-meta'; class ControlStates { constructor( controlWrapper ) { this.controlWrapper = controlWrapper; this.context = new ControlMeta( controlWrapper ).getContext(); this.action = new ControlMeta( controlWrapper ).getAction(); this.canBeRestored = new ControlMeta( controlWrapper ).canBeRestored(); this.templates = { 'list-view': listViewTemplates, 'meta-box': metaBoxTemplates, 'details-view': detailsViewTemplates, }; } renderNotOptimized( data ) { this.controlWrapper.className = this.mixControlContextClass( SELECTORS.controlNotOptimizedClassName ); this.controlWrapper.innerHTML = this.getTemplates().notOptimizedTemplate( data ); this.controlWrapper.dataset.imageOptimizationStatus = 'not-optimized'; } renderOptimized( data ) { const canBeRestored = this.canBeRestored && data?.saved?.absolute !== 0; this.controlWrapper.className = this.mixControlContextClass( SELECTORS.controlOptimizedClassName ); this.controlWrapper.innerHTML = this.getTemplates().optimizedTemplate( { ...data, canBeRestored } ); this.controlWrapper.dataset.imageOptimizationStatus = 'optimized'; } renderError( { message, imagesLeft, action } ) { this.controlWrapper.className = this.mixControlContextClass( SELECTORS.controlErrorClassName ); this.controlWrapper.innerHTML = this.getTemplates().errorTemplate( message, imagesLeft ); this.controlWrapper.dataset.imageOptimizationAction = action; this.controlWrapper.dataset.imageOptimizationStatus = 'error'; } renderLoading( action ) { this.controlWrapper.className = this.mixControlContextClass( SELECTORS.controlLoadingClassName ); this.controlWrapper.innerHTML = this.getTemplates().loadingTemplate( action ); this.controlWrapper.dataset.imageOptimizationStatus = 'loading'; } getTemplates() { const template = this.templates[ this.context ]; if ( ! template ) { throw new Error( `No templates found for the context ${ this.context }` ); } return template; } mixControlContextClass( className ) { const contextClassName = SELECTORS.controlWrapper[ this.context ]; if ( ! contextClassName ) { throw new Error( `No context className found for the context ${ this.context }` ); } return `${ className } ${ contextClassName }`; } } export default ControlStates; modules/optimization/assets/js/classes/control/control-meta.js 0000644 00000001415 14720461212 0020737 0 ustar 00 class ControlMeta { constructor( controlNode ) { this.controlNode = controlNode; } getImageId() { return this.controlNode.dataset?.imageOptimizationImageId ? parseInt( this.controlNode.dataset?.imageOptimizationImageId, 10 ) : null; } getAction() { return this.controlNode.dataset?.imageOptimizationAction || null; } getContext() { return this.controlNode.dataset?.imageOptimizationContext || null; } getStatus() { return this.controlNode.dataset?.imageOptimizationStatus || null; } canBeRestored() { const value = this.controlNode.dataset?.imageOptimizationCanBeRestored; if ( ! value ) { return null; } return '1' === value; } allowRetry() { return this.controlNode.dataset?.allowRetry || null; } } export default ControlMeta; modules/optimization/assets/js/constants/index.js 0000644 00000002640 14720461212 0016342 0 ustar 00 export const UPGRADE_LINK = 'https://go.elementor.com/io-panel-upgrade/'; export const SELECTORS = Object.freeze( { optimizeButtonSelector: '.image-optimization-control__button--optimize', reoptimizeButtonSelector: '.image-optimization-control__button--reoptimize', tryAgainOptimizeButtonSelector: '[data-image-optimization-action="optimize"] .image-optimization-control__button--try-again', tryAgainReoptimizeButtonSelector: '[data-image-optimization-action="reoptimize"] .image-optimization-control__button--try-again', tryAgainRestoreButtonSelector: '[data-image-optimization-action="restore"] .image-optimization-control__button--try-again', controlWrapperSelector: '.image-optimization-control', controlNotOptimizedClassName: 'image-optimization-control image-optimization-control--not-optimized', controlLoadingClassName: 'image-optimization-control image-optimization-control--loading', controlOptimizedClassName: 'image-optimization-control image-optimization-control--optimized', controlErrorClassName: 'image-optimization-control image-optimization-control--error', controlWrapper: { 'list-view': 'image-optimization-control--list-view', 'meta-box': 'image-optimization-control--meta-box', 'details-view': 'image-optimization-control--details-view', }, restoreButtonSelector: '.image-optimization-control__button--restore-original', loadingControlsSelector: '[data-image-optimization-status="loading"]', } ); modules/optimization/assets/js/module.js 0000644 00000000467 14720461212 0014511 0 ustar 00 import '../css/control.css'; import ExtendViews from './classes/extend-views'; import OptimizationControl from './control'; class Module { constructor() { this.init(); } init() { new ExtendViews(); new OptimizationControl(); } } document.addEventListener( 'DOMContentLoaded', () => new Module() ); modules/optimization/assets/js/utils/index.js 0000644 00000001632 14720461212 0015466 0 ustar 00 import { __, sprintf } from '@wordpress/i18n'; export const formatFileSize = ( fileSizeInBytes, decimals = 2 ) => { const sizes = [ // translators: %s: file size in bytes __( '%s Bytes', 'image-optimization' ), // translators: %s: file size in kilobytes __( '%s Kb', 'image-optimization' ), // translators: %s: file size in megabytes __( '%s Mb', 'image-optimization' ), // translators: %s: file size in gigabytes __( '%s Gb', 'image-optimization' ), ]; if ( ! fileSizeInBytes ) { // translators: %s: file size in bytes return sprintf( __( '%s Bytes', 'image-optimization' ), 0 ); } const currentScale = Math.floor( Math.log( fileSizeInBytes ) / Math.log( 1024 ) ); const formattedValue = parseFloat( ( fileSizeInBytes / Math.pow( 1024, currentScale ) ).toFixed( decimals ) ); // eslint-disable-next-line @wordpress/valid-sprintf return sprintf( sizes[ currentScale ], formattedValue ); }; modules/optimization/assets/js/templates/details-view/index.js 0000644 00000012620 14720461212 0020720 0 ustar 00 import { __ } from '@wordpress/i18n'; import { escapeHTML } from '@wordpress/escape-html'; import { formatFileSize } from '../../utils'; import { UPGRADE_LINK } from '../../constants'; const notOptimizedTemplate = () => { return ` <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"> ${ __( 'Status', 'image-optimization' ) }: </span> <span class="image-optimization-control__property-value"> ${ __( 'Not optimized', 'image-optimization' ) } </span> </span> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"></span> <span class="image-optimization-control__property-value image-optimization-control__property-value--button"> <button type="button" class="button button-primary image-optimization-control__button image-optimization-control__button--optimize"> ${ __( 'Optimize now', 'image-optimization' ) } </button> </span> </span> `; }; const loadingTemplate = () => { return ` <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"> ${ __( 'Status', 'image-optimization' ) }: </span> <span class="image-optimization-control__property-value"> ${ __( 'In Progress', 'image-optimization' ) } </span> </span> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"></span> <span class="image-optimization-control__property-value image-optimization-control__property-value--spinner"> <span class="spinner is-active"></span> </span> </span> `; }; const errorTemplate = ( message, imagesLeft ) => { return ` <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"> ${ __( 'Status', 'image-optimization' ) }: </span> <span class="image-optimization-control__property-value"> ${ __( 'Error', 'image-optimization' ) } </span> </span> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"> ${ __( 'Reason', 'image-optimization' ) }: </span> <span class="image-optimization-control__property-value"> ${ escapeHTML( message ) } </span> </span> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"></span> <span class="image-optimization-control__property-value image-optimization-control__property-value--button"> ${ imagesLeft === 0 ? `<a class="button button-secondary button-large image-optimization-control__button" href="${ UPGRADE_LINK }" target="_blank" rel="noopener noreferrer"> ${ __( 'Upgrade', 'image-optimization' ) } </a> ` : ` <button class="button button-secondary button-large button-link-delete image-optimization-control__button image-optimization-control__button--try-again" type="button"> ${ __( 'Try again', 'image-optimization' ) } </button>` } </span> </span> `; }; const optimizedTemplate = ( data ) => { const absoluteValue = formatFileSize( data?.saved?.absolute, 1 ); return ` <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"> ${ __( 'Status', 'image-optimization' ) }: </span> <span class="image-optimization-control__property-value"> ${ __( 'Optimized', 'image-optimization' ) } </span> </span> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"> ${ __( 'Image sizes optimized', 'image-optimization' ) }: </span> <span class="image-optimization-control__property-value"> ${ data?.sizesOptimized } </span> </span> <span class="setting image-optimization-setting"> ${ data?.saved?.absolute !== 0 ? `<span class="name image-optimization-control__property"> ${ __( 'Overall saving', 'image-optimization' ) }: </span> <span class="image-optimization-control__property-value"> ${ data?.saved?.relative }% (${ absoluteValue }) </span>` : `<span class="name image-optimization-control__property"></span> <span class="image-optimization-control__property-value"> ${ __( 'Image is fully optimized', 'image-optimization' ) } </span>` } </span> <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"></span> <span class="image-optimization-control__property-value image-optimization-control__property-value--button"> <button class="button button-link image-optimization-control__button image-optimization-control__button--reoptimize" type="button"> ${ __( 'Reoptimize', 'image-optimization' ) } </button> </span> </span> ${ data?.canBeRestored ? ` <span class="setting image-optimization-setting"> <span class="name image-optimization-control__property"></span> <span class="image-optimization-control__property-value image-optimization-control__property-value--button"> <button class="button button-link image-optimization-control__button image-optimization-control__button--restore-original" type="button"> ${ __( 'Restore original', 'image-optimization' ) } </button> </span> </span> ` : '' } `; }; const detailsViewTemplates = Object.freeze( { notOptimizedTemplate, loadingTemplate, errorTemplate, optimizedTemplate, } ); export default detailsViewTemplates; modules/optimization/assets/js/templates/list-view/index.js 0000644 00000005736 14720461212 0020260 0 ustar 00 import { __ } from '@wordpress/i18n'; import { escapeHTML } from '@wordpress/escape-html'; import { formatFileSize } from '../../utils'; import { UPGRADE_LINK } from '../../constants'; const notOptimizedTemplate = () => { return ` <button type="button" class="button button-primary image-optimization-control__button image-optimization-control__button--optimize"> ${ __( 'Optimize now', 'image-optimization' ) } </button> `; }; const loadingTemplate = ( action ) => { let buttonText; switch ( action ) { case 'restore': buttonText = __( 'Restoring…', 'image-optimization' ); break; case 'optimize': buttonText = __( 'Optimizing…', 'image-optimization' ); break; case 'reoptimize': buttonText = __( 'Reoptimizing…', 'image-optimization' ); break; default: buttonText = __( 'Loading…', 'image-optimization' ); } return ` <button class="button button-secondary image-optimization-control__button image-optimization-control__button--optimize" disabled=""> <span class="spinner is-active"></span> ${ buttonText } </button> `; }; const errorTemplate = ( message, imagesLeft ) => { return ` <span class="image-optimization-control__error-message">${ escapeHTML( message ) }</span> ${ imagesLeft === 0 ? `<a class="button button-secondary button-large image-optimization-control__button" href="${ UPGRADE_LINK }" target="_blank" rel="noopener noreferrer"> ${ __( 'Upgrade', 'image-optimization' ) } </a> ` : ` <button class="button button-secondary button-large button-link-delete image-optimization-control__button image-optimization-control__button--try-again" type="button"> ${ __( 'Try again', 'image-optimization' ) } </button>` } `; }; const optimizedTemplate = ( data ) => { const absoluteValue = formatFileSize( data?.saved?.absolute, 1 ); return ` <p class="image-optimization-control__property"> ${ __( 'Image sizes optimized', 'image-optimization' ) }: <span>${ data?.sizesOptimized }</span> </p> <p class="image-optimization-control__property"> ${ data?.saved?.absolute !== 0 ? `${ __( 'Overall saving', 'image-optimization' ) }: <span>${ data?.saved?.relative }% (${ absoluteValue })</span>` : `<span>${ __( 'Image is fully optimized', 'image-optimization' ) }</span>` } </p> <div class="image-optimization-control__buttons-wrapper"> ${ data?.canBeRestored ? ` <button type="button" class="button button-secondary image-optimization-control__button image-optimization-control__button--restore-original"> ${ __( 'Restore original', 'image-optimization' ) } </button> ` : '' } <button type="button" class="button button-secondary image-optimization-control__button image-optimization-control__button--reoptimize"> ${ __( 'Reoptimize', 'image-optimization' ) } </button> </div> `; }; const listViewTemplates = Object.freeze( { notOptimizedTemplate, loadingTemplate, errorTemplate, optimizedTemplate, } ); export default listViewTemplates; modules/optimization/assets/js/templates/meta-box/index.js 0000644 00000007540 14720461212 0020044 0 ustar 00 import { __ } from '@wordpress/i18n'; import { escapeHTML } from '@wordpress/escape-html'; import { formatFileSize } from '../../utils'; import { UPGRADE_LINK } from '../../constants'; const notOptimizedTemplate = () => { return ` <p class="image-optimization-control__property"> ${ __( 'Status', 'image-optimization' ) }: <span class="image-optimization-control__property-value"> ${ __( 'Not optimized', 'image-optimization' ) } </span> </p> <div class="image-optimization-control__action-button-wrapper"> <button type="button" class="button button-primary image-optimization-control__button image-optimization-control__button--optimize"> ${ __( 'Optimize now', 'image-optimization' ) } </button> </div> `; }; const loadingTemplate = () => { return ` <p class="image-optimization-control__property"> ${ __( 'Status', 'image-optimization' ) }: <span class="image-optimization-control__property-value"> ${ __( 'In Progress', 'image-optimization' ) } </span> </p> <div class="image-optimization-control__action-spinner-wrapper"> <span class="spinner is-active"></span> </div> `; }; const errorTemplate = ( message, imagesLeft ) => { return ` <p class="image-optimization-control__property"> ${ __( 'Status', 'image-optimization' ) }: <span class="image-optimization-control__property-value"> ${ __( 'Error', 'image-optimization' ) } </span> </p> <p class="image-optimization-control__property"> ${ __( 'Reason', 'image-optimization' ) }: <span class="image-optimization-control__property-value"> ${ escapeHTML( message ) } </span> </p> <div class="image-optimization-control__action-button-wrapper"> ${ imagesLeft === 0 ? `<a class="button button-secondary button-large image-optimization-control__button" href="${ UPGRADE_LINK }" target="_blank" rel="noopener noreferrer"> ${ __( 'Upgrade', 'image-optimization' ) } </a> ` : ` <button class="button button-secondary button-large button-link-delete image-optimization-control__button image-optimization-control__button--try-again" type="button"> ${ __( 'Try again', 'image-optimization' ) } </button>` } </div> `; }; const optimizedTemplate = ( data ) => { const absoluteValue = formatFileSize( data?.saved?.absolute, 1 ); return ` <p class="image-optimization-control__property"> ${ __( 'Status', 'image-optimization' ) }: <span class="image-optimization-control__property-value"> ${ __( 'Optimized', 'image-optimization' ) } </span> </p> <p class="image-optimization-control__property"> ${ __( 'Image sizes optimized', 'image-optimization' ) }: <span class="image-optimization-control__property-value"> ${ data?.sizesOptimized } </span> </p> <p class="image-optimization-control__property"> ${ data?.saved?.absolute !== 0 ? ` <span class="image-optimization-control__property-value"> ${ __( 'Overall saving', 'image-optimization' ) }: ${ data?.saved?.relative }% (${ absoluteValue }) </span> ` : ` <span class="image-optimization-control__property-value"> ${ __( 'Image is fully optimized', 'image-optimization' ) } </span> ` } </p> <div class="image-optimization-control__action-button-wrapper"> ${ data?.canBeRestored ? ` <button class="button button-link image-optimization-control__button image-optimization-control__button--restore-original" type="button"> ${ __( 'Restore original', 'image-optimization' ) } </button> ` : '' } <button class="button button-link image-optimization-control__button image-optimization-control__button--reoptimize" type="button"> ${ __( 'Reoptimize', 'image-optimization' ) } </button> </div> `; }; const metaBoxTemplates = Object.freeze( { notOptimizedTemplate, loadingTemplate, errorTemplate, optimizedTemplate, } ); export default metaBoxTemplates; modules/optimization/assets/js/control.js 0000644 00000006050 14720461212 0014676 0 ustar 00 import { __ } from '@wordpress/i18n'; import { speak } from '@wordpress/a11y'; import { SELECTORS } from './constants'; import API from './classes/api'; import ControlSync from './classes/control/control-sync'; import ControlStates from './classes/control/control-states'; import ControlMeta from './classes/control/control-meta'; class OptimizationControl { constructor() { this.controlSyncRequestInProgress = false; this.init(); this.controlSync = new ControlSync(); } init() { this.initEventListeners(); setInterval( () => this.runStatusCheckLoop(), 5000 ); } async runStatusCheckLoop() { if ( this.controlSyncRequestInProgress ) { return; } this.controlSyncRequestInProgress = true; await this.controlSync.run(); this.controlSyncRequestInProgress = false; } initEventListeners() { document.addEventListener( 'click', ( e ) => this.handleOptimizeButtonClick( e ) ); document.addEventListener( 'click', ( e ) => this.handleReoptimizeButtonClick( e ) ); document.addEventListener( 'click', ( e ) => this.handleRestoreButtonClick( e ) ); } async handleOptimizeButtonClick( e ) { if ( ! e.target.closest( `${ SELECTORS.optimizeButtonSelector }, ${ SELECTORS.tryAgainOptimizeButtonSelector }` ) ) { return; } speak( __( 'Optimization is in progress', 'image-optimization' ), 'assertive' ); const controlWrapper = e.target.closest( SELECTORS.controlWrapperSelector ); const states = new ControlStates( controlWrapper ); states.renderLoading( 'optimize' ); try { controlWrapper.dataset.isFrozen = true; await API.optimizeSingleImage( { imageId: new ControlMeta( controlWrapper ).getImageId(), reoptimize: false, } ); } catch ( error ) { states.renderError( error ); } } async handleReoptimizeButtonClick( e ) { if ( ! e.target.closest( `${ SELECTORS.reoptimizeButtonSelector }, ${ SELECTORS.tryAgainReoptimizeButtonSelector }` ) ) { return; } speak( __( 'Reoptimizing is in progress', 'image-optimization' ), 'assertive' ); const controlWrapper = e.target.closest( SELECTORS.controlWrapperSelector ); const states = new ControlStates( controlWrapper ); states.renderLoading( 'reoptimize' ); try { controlWrapper.dataset.isFrozen = true; await API.optimizeSingleImage( { imageId: new ControlMeta( controlWrapper ).getImageId(), reoptimize: true, } ); } catch ( error ) { states.renderError( error ); } } async handleRestoreButtonClick( e ) { if ( ! e.target.closest( `${ SELECTORS.restoreButtonSelector }, ${ SELECTORS.tryAgainRestoreButtonSelector }` ) ) { return; } speak( __( 'Image restoring is in progress', 'image-optimization' ), 'assertive' ); const controlWrapper = e.target.closest( SELECTORS.controlWrapperSelector ); const states = new ControlStates( controlWrapper ); states.renderLoading( 'restore' ); try { controlWrapper.dataset.isFrozen = true; await API.restoreSingleImage( new ControlMeta( controlWrapper ).getImageId() ); } catch ( error ) { states.renderError( error ); } } } export default OptimizationControl; modules/oauth/classes/route-base.php 0000644 00000002361 14720461212 0013551 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth\Classes; use ImageOptimization\Classes\Route; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Route_Base extends Route { const SITE_URL = 'https://my.elementor.com/connect/v1/'; protected $auth = true; protected string $path = ''; public function get_methods(): array { return []; } public function get_endpoint(): string { return 'connect/' . $this->get_path(); } public function get_path(): string { return $this->path; } public function get_name(): string { return ''; } public function get_permission_callback( \WP_REST_Request $request ): bool { $valid = $this->permission_callback( $request ); return $valid && user_can( $this->current_user_id, 'manage_options' ); } public function verify_nonce( $nonce = '', $name = '' ) { if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $nonce ) ), $name ) ) { wp_die( 'Invalid nonce', 'image-optimization' ); } } public function verify_nonce_and_capability( $nonce = '', $name = '', $capability = 'manage_options' ) { $this->verify_nonce( $nonce, $name ); if ( ! current_user_can( $capability ) ) { wp_die( 'You do not have sufficient permissions to access this page.' ); } } } modules/oauth/classes/data.php 0000644 00000010706 14720461212 0012416 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth\Classes; use ImageOptimization\Modules\Oauth\Components\Connect; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } /** * Class Data */ class Data { const CONNECT_CLIENT_DATA_OPTION_NAME = 'image_optimizer_client_data'; const CONNECT_DATA_OPTION_NAME = 'image_optimizer_connect_data'; const OPTION_CONNECT_SITE_KEY = 'image_optimizer_site_key'; const OPTION_CONNECT_STATE = 'image_optimizer_connect_state'; const OPTION_ACTIVATION_STATE = 'image_optimizer_activation_state'; const OPTION_OWNER_USER_ID = 'image_optimizer_owner_user_id'; /** * set_client_data * @param $client_id * @param $auth_secret */ public static function set_client_data( $client_id, $auth_secret ) { update_option( self::CONNECT_CLIENT_DATA_OPTION_NAME, [ 'client_id' => $client_id, 'auth_secret' => $auth_secret, ], false ); } /** * get_client_data * @return array */ public static function get_client_data(): array { return get_option( self::CONNECT_CLIENT_DATA_OPTION_NAME, [ 'client_id' => '', 'auth_secret' => '', ] ); } /** * get_client_id * @return string */ public static function get_client_id(): string { return self::get_client_data()['client_id'] ?? ''; } /** * get_client_secret * @return string */ public static function get_client_secret(): string { return self::get_client_data()['auth_secret'] ?? ''; } /** * get_connect_data * * @param bool $force * * @return array|null */ public static function get_connect_data( bool $force = false ): array { static $connect_data = null; if ( $connect_data === null || $force ) { $connect_data = array_merge( [ 'access_token' => '', 'access_token_secret' => '', 'last_update' => 0, 'token_type' => 'bearer', 'user' => [], 'version' => 1, ], get_option( self::CONNECT_DATA_OPTION_NAME, [] ) ); } return $connect_data; } /** * set_connect_data * * @param array $data */ public static function set_connect_data( array $data = [] ): bool { $data['last_update'] = time(); $data['version'] = 1; update_option( self::OPTION_OWNER_USER_ID, get_current_user_id() ); return update_option( self::CONNECT_DATA_OPTION_NAME, $data ); } /** * get_access_token * @return false|mixed */ public static function get_access_token() { return self::get_connect_data()['access_token'] ?? false; } /** * get_connect_state * * @param bool $force * * @return false|mixed|null|string */ public static function get_connect_state( bool $force = false ) { $state = get_option( static::OPTION_CONNECT_STATE ); if ( ! $state || $force ) { $state = wp_generate_password( 12, false ); update_option( static::OPTION_CONNECT_STATE, $state, false ); } return $state; } /** * get_site_key * @return false|mixed|string|null */ public static function get_site_key() { $site_key = get_option( static::OPTION_CONNECT_SITE_KEY ); if ( ! $site_key ) { $site_key = md5( uniqid( wp_generate_password() ) ); update_option( static::OPTION_CONNECT_SITE_KEY, $site_key, false ); } return $site_key; } /** * delete_connect_state */ public static function delete_connect_state(): bool { return delete_option( static::OPTION_CONNECT_STATE ); } public static function get_activation_state(): string { return get_option( self::OPTION_ACTIVATION_STATE, '' ); } public static function set_activation_state( $state ): bool { return update_option( self::OPTION_ACTIVATION_STATE, $state ); } public static function delete_activation_state(): bool { return delete_option( self::OPTION_ACTIVATION_STATE ); } /** * reset connect data */ public static function reset(): void { self::delete_connect_state(); self::delete_activation_state(); delete_option( self::OPTION_OWNER_USER_ID ); delete_option( static::CONNECT_DATA_OPTION_NAME ); delete_option( self::CONNECT_CLIENT_DATA_OPTION_NAME ); delete_transient( Connect::STATUS_CHECK_TRANSIENT ); } public static function images_left(): int { $plan_data = Connect::get_connect_status(); if ( empty( $plan_data ) ) { return 0; } $quota = $plan_data->quota; $used_quota = $plan_data->used_quota; return max( $quota - $used_quota, 0 ); } public static function user_is_subscription_owner(): bool { $owner_id = (int) get_option( self::OPTION_OWNER_USER_ID ); return get_current_user_id() === $owner_id; } } modules/oauth/rest/activate.php 0000644 00000003042 14720461212 0012620 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth\Rest; use ImageOptimization\Modules\Oauth\{ Classes\Route_Base, Components\Connect, }; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Activate extends Route_Base { const NONCE_NAME = 'image-optimization-activate-subscription'; protected string $path = 'activate'; public function get_name(): string { return 'activate'; } public function get_methods(): array { return [ 'POST' ]; } public function POST( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); if ( ! Connect::is_connected() ) { return $this->respond_error_json( [ 'message' => esc_html__( 'Please connect first', 'image-optimization' ), 'code' => 'forbidden', ] ); } if ( Connect::is_activated() ) { return $this->respond_error_json( [ 'message' => esc_html__( 'Already activated', 'image-optimization' ), 'code' => 'bad_request', ] ); } if ( ! $request->get_param( 'license_key' ) ) { return $this->respond_error_json( [ 'message' => esc_html__( 'Missing license key', 'image-optimization' ), 'code' => 'bad_request', ] ); } $license_key = $request->get_param( 'license_key' ); try { Connect::activate( $license_key ); return $this->respond_success_json(); } catch ( Throwable $t ) { return $this->respond_error_json( [ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ] ); } } } modules/oauth/rest/version.php 0000644 00000001155 14720461212 0012510 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth\Rest; use ImageOptimization\Modules\Oauth\{ Classes\Route_Base, Components\Connect, }; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Version extends Route_Base { const NONCE_NAME = 'image-optimization-version'; protected string $path = 'version'; public function get_name(): string { return 'version'; } public function get_methods(): array { return [ 'GET' ]; } public function GET( WP_REST_Request $request ) { return $this->respond_success_json( [ 'version' => 1, ] ); } } modules/oauth/rest/disconnect.php 0000644 00000001651 14720461212 0013155 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth\Rest; use ImageOptimization\Modules\Oauth\{ Classes\Data, Classes\Route_Base, Components\Connect }; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Disconnect extends Route_Base { const NONCE_NAME = 'image-optimization-disconnect'; protected string $path = 'disconnect'; public function get_name(): string { return 'disconnect'; } public function get_methods(): array { return [ 'POST' ]; } public function POST( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); try { Connect::disconnect(); } catch ( Throwable $t ) { Data::reset(); return $this->respond_error_json( [ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ] ); } return $this->respond_success_json(); } } modules/oauth/rest/get-subscriptions.php 0000644 00000002217 14720461212 0014507 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth\Rest; use ImageOptimization\Modules\Oauth\{ Classes\Route_Base, Components\Connect, }; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Get_Subscriptions extends Route_Base { const NONCE_NAME = 'image-optimization-get-subscription'; protected string $path = 'get-subscriptions'; public function get_name(): string { return 'get_subscriptions'; } public function get_methods(): array { return [ 'POST' ]; } public function POST( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); if ( ! Connect::is_connected() ) { return $this->respond_error_json( [ 'message' => esc_html__( 'Please connect first', 'image-optimization' ), 'code' => 'forbidden', ] ); } try { $subscriptions = Connect::get_subscriptions(); return $this->respond_success_json( $subscriptions ); } catch ( Throwable $t ) { return $this->respond_error_json( [ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ] ); } } } modules/oauth/rest/connect-init.php 0000644 00000002155 14720461212 0013416 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth\Rest; use ImageOptimization\Modules\Oauth\{ Classes\Route_Base, Components\Connect, }; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Connect_Init extends Route_Base { const NONCE_NAME = 'image-optimization-connect'; protected string $path = 'init'; public function get_name(): string { return 'connect-init'; } public function get_methods(): array { return [ 'GET' ]; } public function get( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); if ( Connect::is_connected() ) { return $this->respond_error_json( [ 'message' => esc_html__( 'You are already connected', 'image-optimization' ), 'code' => 'forbidden', ] ); } try { $connect_url = Connect::initialize_connect(); return $this->respond_success_json( $connect_url ); } catch ( Throwable $t ) { return $this->respond_error_json( [ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ] ); } } } modules/oauth/rest/deactivate.php 0000644 00000002637 14720461212 0013142 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth\Rest; use ImageOptimization\Modules\Oauth\{ Classes\Data, Classes\Route_Base, Components\Connect }; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Deactivate extends Route_Base { const NONCE_NAME = 'image-optimization-deactivate-subscription'; protected string $path = 'deactivate'; public function get_name(): string { return 'deactivate'; } public function get_methods(): array { return [ 'POST' ]; } public function POST( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); if ( ! Connect::is_connected() ) { return $this->respond_error_json( [ 'message' => esc_html__( 'Please connect first', 'image-optimization' ), 'code' => 'forbidden', ] ); } if ( ! $request->get_param( 'license_key' ) ) { return $this->respond_error_json( [ 'message' => esc_html__( 'Missing license key', 'image-optimization' ), 'code' => 'bad_request', ] ); } $license_key = $request->get_param( 'license_key' ); try { Connect::deactivate( $license_key ); return $this->respond_success_json(); } catch ( Throwable $t ) { Data::delete_activation_state(); return $this->respond_error_json( [ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ] ); } } } modules/oauth/module.php 0000644 00000001615 14720461212 0011334 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth; use ImageOptimization\Classes\Module_Base; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } /** * Class Module */ class Module extends Module_Base { /** * Get module name. * Retrieve the module name. * @access public * @return string Module name. */ public function get_name(): string { return 'oauth'; } public static function routes_list() : array { return [ 'Connect_Init', 'Disconnect', 'Get_Subscriptions', 'Activate', 'Deactivate', 'Version', ]; } public static function component_list() : array { return [ 'Connect', 'Checkpoint', 'Connect_Pointer', ]; } public static function is_active() : bool { return ! empty( get_option( 'image_optimizer_client_data' ) ); } public function __construct() { $this->register_components(); $this->register_routes(); } } modules/oauth/components/connect.php 0000644 00000023246 14720461212 0013671 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth\Components; use ImageOptimization\Modules\Oauth\{ Classes\Route_Base, Components\Exceptions\Auth_Error, Classes\Data, }; use ImageOptimization\Classes\Logger; use ImageOptimization\Classes\Utils; use ImageOptimization\Modules\Settings\Module as Settings_Module; use stdClass; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } /** * Class Connect */ class Connect { const API_URL = 'https://my.elementor.com/api/connect/v1'; const STATUS_CHECK_TRANSIENT = 'image_optimizer_status_check'; /** * is_connected * @return bool */ public static function is_connected(): bool { return ! empty( Data::get_connect_data()['access_token'] ); } /** * is_activated * @return bool */ public static function is_activated(): bool { return ! empty( Data::get_activation_state() ); } /** * maybe_handle_admin_connect_page * @return bool */ public static function maybe_handle_admin_connect_page(): bool { if ( ! isset( $_GET['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['nonce'] ) ), 'nonce_actionget_token' ) ) { return false; } $args = [ 'page' => 'elementor-connect', 'app' => 'library', 'action' => 'get_token', 'state' => Data::get_connect_state(), ]; foreach ( $args as $key => $value ) { if ( ! isset( $_GET[ $key ] ) || $_GET[ $key ] !== $value ) { return false; } } if ( ! isset( $_GET['nonce'] ) || ! isset( $_GET['code'] ) ) { return false; } return true; } /** * handle_elementor_connect_admin */ public function handle_elementor_connect_admin(): void { // validate args if ( ! self::maybe_handle_admin_connect_page() ) { return; } // validate nonce if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['nonce'] ) ), 'nonce_actionget_token' ) ) { wp_die( 'Nonce verification failed', 'image-optimization' ); } $token_response = wp_remote_request( self::API_URL . '/get_token', [ 'method' => 'POST', 'body' => [ 'app' => 'library', 'grant_type' => 'authorization_code', 'client_id' => Data::get_client_id(), 'code' => sanitize_text_field( $_GET['code'] ), ], ] ); if ( is_wp_error( $token_response ) ) { wp_die( $token_response->get_error_message(), 'image-optimization' ); } $data = json_decode( wp_remote_retrieve_body( $token_response ), true ); Data::set_connect_data( $data ); do_action( Checkpoint::ON_CONNECT ); // cleanup Data::delete_connect_state(); wp_redirect( add_query_arg( [ 'page' => Settings_Module::SETTING_BASE_SLUG, 'connected' => 'true', ], admin_url( 'admin.php' ) ) ); die(); } /** * Gets required connection data from the service and generates a connect link. * * @return string User connect link * * @throws Auth_Error */ public static function initialize_connect(): string { try { $response = wp_remote_request( self::API_URL . '/library/get_client_id', [ 'method' => 'POST', 'body' => [ 'local_id' => get_current_user_id(), 'site_key' => Data::get_site_key(), 'app' => 'library', 'home_url' => trailingslashit( home_url() ), 'source' => 'image-optimizer', ], ] ); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Error while sending connection initialization request: ' . $t->getMessage() ); throw new Auth_Error( $t->getMessage() ); } $data = json_decode( wp_remote_retrieve_body( $response ) ); if ( ! isset( $data->client_id ) || ! isset( $data->auth_secret ) ) { Logger::log( Logger::LEVEL_ERROR, 'Invalid response from server: client id or auth secret are undefined' ); throw new Auth_Error( esc_html__( 'Invalid response from server', 'image-optimization' ) ); } Data::set_client_data( $data->client_id, $data->auth_secret ); return add_query_arg( [ 'utm_source' => 'image-optimizer-panel', 'utm_campaign' => 'image-optimizer', 'utm_medium' => 'wp-dash', 'source' => 'generic', 'action' => 'authorize', 'response_type' => 'code', 'client_id' => $data->client_id, 'auth_secret' => $data->auth_secret, 'state' => Data::get_connect_state( true ), 'redirect_uri' => rawurlencode( add_query_arg( [ 'page' => 'elementor-connect', 'app' => 'library', 'action' => 'get_token', 'nonce' => wp_create_nonce( 'nonce_action' . 'get_token' ), ], admin_url( 'admin.php' ) ) ), 'may_share_data' => 0, 'reconnect_nonce' => wp_create_nonce( 'nonce_action' . 'reconnect' ), ], Route_Base::SITE_URL . 'library' ); } /** * Disconnects a user and removes connection data from the DB. */ public static function disconnect() { do_action( Checkpoint::ON_DISCONNECT ); try { return wp_remote_request( self::API_URL . '/disconnect', [ 'method' => 'POST', 'body' => [ 'app' => 'library', 'home_url' => trailingslashit( home_url() ), 'client_id' => Data::get_client_id(), 'access_token' => Data::get_access_token(), ], ] ); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Error while sending disconnection request: ' . $t->getMessage() ); throw new Auth_Error( $t->getMessage() ); } finally { Data::reset(); } } /** * Sends an activation request and stores activation data in the DB. * * @param $license_key string License key to activate with. * @return mixed * * @throws Auth_Error */ public static function activate( string $license_key ) { try { $response = Utils::get_api_client()->make_request( 'POST', 'activation/activate', [], [ 'key' => $license_key ] ); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Error while sending activation request: ' . $t->getMessage() ); throw new Auth_Error( $t->getMessage() ); } if ( ! isset( $response->id ) ) { Logger::log( Logger::LEVEL_ERROR, 'Invalid response from server' ); throw new Auth_Error( esc_html__( 'Invalid response from server', 'image-optimization' ) ); } Data::set_activation_state( $license_key ); do_action( Checkpoint::ON_ACTIVATE, $license_key ); return $response; } /** * Deactivate specific license and remove activation data from the DB. * * @param $license_key string License key to deactivate. * * @return mixed * * @throws Auth_Error */ public static function deactivate( string $license_key ) { do_action( Checkpoint::ON_DEACTIVATE, $license_key ); try { $response = Utils::get_api_client()->make_request( 'POST', 'activation/deactivate', [ 'key' => $license_key, ] ); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Error while sending deactivation request: ' . $t->getMessage() ); throw new Auth_Error( $t->getMessage() ); } finally { Data::delete_activation_state(); } if ( ! isset( $response->id ) ) { Logger::log( Logger::LEVEL_ERROR, 'Invalid response from server' ); throw new Auth_Error( esc_html__( 'Invalid response from server', 'image-optimization' ) ); } return $response; } /** * Fetches and returns a list of available licenses for a specific user. * * @return array Available subscriptions or an empty array * * @throws Auth_Error */ public static function get_subscriptions(): array { try { $response = Utils::get_api_client()->make_request( 'POST', 'activation/get-subscriptions' ); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Error while fetching subscriptions: ' . $t->getMessage() ); throw new Auth_Error( $t->getMessage() ); } if ( ! isset( $response->subscriptions ) ) { Logger::log( Logger::LEVEL_ERROR, 'Invalid response from server' ); throw new Auth_Error( esc_html__( 'Invalid response from server', 'image-optimization' ) ); } return $response->subscriptions; } public static function get_connect_status() { if ( ! self::is_connected() ) { Logger::log( Logger::LEVEL_INFO, 'Status getting error. Reason: User is not connected' ); return null; } $cached_status = get_transient( self::STATUS_CHECK_TRANSIENT ); if ( $cached_status ) { return $cached_status; } $status = self::check_connect_status(); set_transient( self::STATUS_CHECK_TRANSIENT, $status, MINUTE_IN_SECONDS * 5 ); return $status; } private static function check_connect_status() { if ( ! self::is_connected() ) { Logger::log( Logger::LEVEL_INFO, 'Status check error. Reason: User is not connected' ); return null; } try { $response = Utils::get_api_client()->make_request( 'POST', 'status/check' ); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Status check error. Reason: ' . $t->getMessage() ); return null; } if ( ! isset( $response->status ) ) { Logger::log( Logger::LEVEL_ERROR, 'Invalid response from server' ); return null; } return $response; } public static function update_usage_data( stdClass $new_usage_data ) { $connect_status = self::get_connect_status(); if ( ! isset( $new_usage_data->allowed ) || ! isset( $new_usage_data->used ) ) { return; } if ( 0 === $new_usage_data->allowed - $new_usage_data->used ) { $connect_status->status = 'expired'; } $connect_status->quota = $new_usage_data->allowed; $connect_status->used_quota = $new_usage_data->used; set_transient( self::STATUS_CHECK_TRANSIENT, $connect_status, MINUTE_IN_SECONDS * 5 ); } public function __construct() { // handle connect if elementor is active add_action( 'load-elementor_page_elementor-connect', [ $this, 'handle_elementor_connect_admin' ], 9 ); // handle connect if elementor is not active add_action( '_admin_menu', [ $this, 'handle_elementor_connect_admin' ] ); } } modules/oauth/components/connect-pointer.php 0000644 00000003417 14720461212 0015345 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth\Components; use ImageOptimization\Modules\Core\Components\Pointers; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Connect_Pointer { const CURRENT_POINTER_SLUG = 'image-optimization-auth-connect'; public function admin_print_script() { if ( Connect::is_connected() ) { return; } wp_enqueue_script( 'wp-pointer' ); wp_enqueue_style( 'wp-pointer' ); $pointer_content = '<h3>' . esc_html__( 'Start by connecting your license', 'image-optimization' ) . '</h3>'; $pointer_content .= '<p>' . esc_html__( 'You’re one click away from improving your site’s performance dramatically!', 'image-optimization' ) . '</p>'; ?> <script> jQuery( document ).ready( function( $ ) { console.log( $( '.image-optimization-stats-connect-button' ) ); const intervalId = setInterval( () => { if ( ! $( '.image-optimization-stats-connect-button' ).length ) { return; } clearInterval(intervalId); $( '.image-optimization-stats-connect-button' ).first().pointer( { content: '<?php echo $pointer_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>', pointerClass: 'image-optimization-auth-connect-pointer', position: { edge: 'top', align: <?php echo is_rtl() ? "'left'" : "'right'"; ?>, }, } ).pointer( 'open' ); }, 100 ); } ); </script> <style> .image-optimization-auth-connect-pointer .wp-pointer-arrow { inset-block-start: 4px; inset-inline-start: 78%; } .image-optimization-auth-connect-pointer .wp-pointer-arrow-inner { inset-block-start: 10px; } </style> <?php } public function __construct() { add_action( 'in_admin_header', [ $this, 'admin_print_script' ] ); } } modules/oauth/components/exceptions/auth-error.php 0000644 00000000354 14720461212 0016504 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth\Components\Exceptions; use Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Auth_Error extends Exception { protected $message = 'Auth error'; } modules/oauth/components/checkpoint.php 0000644 00000002377 14720461212 0014371 0 ustar 00 <?php namespace ImageOptimization\Modules\Oauth\Components; use ImageOptimization\Classes\Utils; use ImageOptimization\Modules\Oauth\Classes\Data; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } /** * Class Checkpoint */ class Checkpoint { const ON_CONNECT = 'image-optimizer-connect'; const ON_DISCONNECT = 'image-optimizer-disconnect'; const ON_ACTIVATE = 'image-optimizer-activate'; const ON_DEACTIVATE = 'image-optimizer-deactivate'; /** * event * * @param array $event_data */ public static function event( array $event_data = [] ): void { $event_name = current_action(); // only allow specific events if ( ! in_array( $event_name, self::get_checkpoints() ) ) { return; } $response = Utils::get_api_client()->make_request( 'POST', 'status/checkpoint', [ 'event_name' => $event_name, 'event_data' => $event_data, ] ); } /** * get_checkpoints * @return string[] */ public static function get_checkpoints(): array { return [ self::ON_DISCONNECT, self::ON_CONNECT, self::ON_ACTIVATE, self::ON_DEACTIVATE, ]; } public function __construct() { foreach ( self::get_checkpoints() as $checkpoint ) { add_action( $checkpoint, [ __CLASS__, 'event' ], 10, 0 ); } } } modules/settings/classes/settings.php 0000644 00000004016 14720461212 0014062 0 ustar 00 <?php namespace ImageOptimization\Modules\Settings\Classes; use ImageOptimization\Classes\Image\Image_Conversion_Option; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Settings { public const COMPRESSION_LEVEL_OPTION_NAME = 'image_optimizer_compression_level'; public const OPTIMIZE_ON_UPLOAD_OPTION_NAME = 'image_optimizer_optimize_on_upload'; /** @deprecated Use self::CONVERT_TO_FORMAT_OPTION_NAME instead */ public const CONVERT_TO_WEBP_OPTION_NAME = 'image_optimizer_convert_to_webp'; public const CONVERT_TO_FORMAT_OPTION_NAME = 'image_optimizer_convert_to_format'; public const RESIZE_LARGER_IMAGES_OPTION_NAME = 'image_optimizer_resize_larger_images'; public const RESIZE_LARGER_IMAGES_SIZE_OPTION_NAME = 'image_optimizer_resize_larger_images_size'; public const STRIP_EXIF_METADATA_OPTION_NAME = 'image_optimizer_exif_metadata'; public const BACKUP_ORIGINAL_IMAGES_OPTION_NAME = 'image_optimizer_original_images'; public const CUSTOM_SIZES_OPTION_NAME = 'image_optimizer_custom_sizes'; /** * Returns plugin settings data by option name typecasted to an appropriate data type. * * @param string $option_name * @return mixed */ public static function get( string $option_name ) { $data = get_option( $option_name ); switch ( $option_name ) { case self::RESIZE_LARGER_IMAGES_SIZE_OPTION_NAME: return (int) $data; case self::RESIZE_LARGER_IMAGES_OPTION_NAME: case self::STRIP_EXIF_METADATA_OPTION_NAME: case self::BACKUP_ORIGINAL_IMAGES_OPTION_NAME: return (bool) $data; // TODO: [Stability] Remove this fallback after a few versions case self::CONVERT_TO_WEBP_OPTION_NAME: $new_option = get_option( self::CONVERT_TO_FORMAT_OPTION_NAME ); if ( Image_Conversion_Option::WEBP === $new_option ) { return true; } return false; case self::CUSTOM_SIZES_OPTION_NAME: if ( 'all' === $data ) { return $data; } if ( empty( $data ) ) { return []; } return explode( ',', $data ); default: return $data; } } } modules/settings/module.php 0000644 00000006552 14720461212 0012061 0 ustar 00 <?php namespace ImageOptimization\Modules\Settings; use ImageOptimization\Classes\Image\Image_Conversion_Option; use ImageOptimization\Classes\Module_Base; use ImageOptimization\Modules\Settings\Classes\Settings; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } class Module extends Module_Base { const SETTING_PREFIX = 'image_optimizer_'; const SETTING_GROUP = 'image_optimizer_settings'; const SETTING_BASE_SLUG = 'image-optimization-settings'; const SETTING_CAPABILITY = 'manage_options'; public function get_name(): string { return 'settings'; } public static function component_list() : array { return [ 'Settings_Pointer', ]; } public static function get_options() : array { return [ 'compression_level' => [ 'default' => 'lossy' ], 'optimize_on_upload' => [ 'type' => 'boolean', 'default' => true, ], 'resize_larger_images' => [ 'type' => 'boolean', 'default' => true, ], 'resize_larger_images_size' => [ 'type' => 'integer', 'default' => 1920, ], 'exif_metadata' => [ 'type' => 'boolean', 'default' => true, ], 'original_images' => [ 'type' => 'boolean', 'default' => true, ], 'convert_to_format' => [ 'type' => 'string', 'default' => Image_Conversion_Option::WEBP, ], 'custom_sizes' => [ 'type' => 'string', 'default' => 'all', ], ]; } public function register_options() { $options = $this->get_options(); foreach ( $options as $key => &$args ) { $args['type'] = $args['type'] ?? 'string'; $args['show_in_rest'] = $args['show_in_rest'] ?? true; $args['default'] = $args['default'] ?? ''; register_setting( self::SETTING_GROUP, self::SETTING_PREFIX . $key, $args ); // Set defaults add_option( self::SETTING_PREFIX . $key, $args['default'] ); } } public function render_app() { ?> <!-- The hack required to wrap WP notifications --> <div class="wrap"> <h1 style="display: none;" role="presentation"></h1> </div> <div id="image-optimization-app"></div> <?php } public function register_page() { add_media_page( __( 'Image Optimizer', 'image-optimization' ), __( 'Image Optimizer', 'image-optimization' ), self::SETTING_CAPABILITY, self::SETTING_BASE_SLUG, [ $this, 'render_app' ], 6 ); } /** * The handler converts an old CONVERT_TO_WEBP option to the new CONVERT_TO_FORMAT option. * TODO: [Stability] Remove this fallback after all users updated * * @return void */ public function maybe_migrate_legacy_conversion_option() { $legacy_convert_to_webp = get_option( Settings::CONVERT_TO_WEBP_OPTION_NAME, null ); if ( is_null( $legacy_convert_to_webp ) ) { return; } if ( '1' === $legacy_convert_to_webp ) { update_option( Settings::CONVERT_TO_FORMAT_OPTION_NAME, Image_Conversion_Option::WEBP, false ); } if ( '0' === $legacy_convert_to_webp ) { update_option( Settings::CONVERT_TO_FORMAT_OPTION_NAME, Image_Conversion_Option::ORIGINAL, false ); } delete_option( Settings::CONVERT_TO_WEBP_OPTION_NAME ); } public function __construct() { $this->register_components(); add_action( 'admin_init', [ $this, 'register_options' ] ); add_action( 'rest_api_init', [ $this, 'register_options' ] ); add_action( 'admin_init', [ $this, 'maybe_migrate_legacy_conversion_option' ] ); add_action( 'admin_menu', [ $this, 'register_page' ] ); } } modules/settings/components/settings-pointer.php 0000644 00000004632 14720461212 0016274 0 ustar 00 <?php namespace ImageOptimization\Modules\Settings\Components; use ImageOptimization\Modules\Core\Components\Pointers; use ImageOptimization\Modules\Settings\Module; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Settings_Pointer { const CURRENT_POINTER_SLUG = 'image-optimizer-settings'; public function admin_print_script() { if ( ! current_user_can( 'manage_options' ) ) { return; } if ( $this->is_dismissed() ) { return; } wp_enqueue_script( 'wp-pointer' ); wp_enqueue_style( 'wp-pointer' ); $pointer_content = '<h3>' . esc_html__( 'Image Optimization settings', 'image-optimization' ) . '</h3>'; $pointer_content .= '<p>' . esc_html__( 'Head over to the Image Optimization Settings to fine-tune how your media uploads are managed.', 'image-optimization' ) . '</p>'; $pointer_content .= sprintf( '<p><a class="button button-primary image-optimization-pointer-settings-link" href="%s">%s</a></p>', admin_url( 'admin.php?page=' . Module::SETTING_BASE_SLUG ), esc_html__( 'Take me there', 'image-optimization' ) ); $allowed_tags = [ 'h3' => [], 'p' => [], 'a' => [ 'class' => [], 'href' => [], ], ]; ?> <script> const onClose = () => { return wp.ajax.post( 'image_optimizer_pointer_dismissed', { data: { pointer: '<?php echo esc_attr( static::CURRENT_POINTER_SLUG ); ?>', }, nonce: '<?php echo esc_attr( wp_create_nonce( 'image-optimization-pointer-dismissed' ) ); ?>', } ); } jQuery( document ).ready( function( $ ) { $( '#menu-media' ).pointer( { content: '<?php echo wp_kses( $pointer_content, $allowed_tags ); ?>', position: { edge: <?php echo is_rtl() ? "'right'" : "'left'"; ?>, align: 'center' }, close: onClose } ).pointer( 'open' ); $( '.image-optimization-pointer-settings-link' ).first().on( 'click', function( e ) { e.preventDefault(); $(this).attr( 'disabled', true ); onClose().promise().done(() => { location = $(this).attr( 'href' ); }); }) } ); </script> <?php } public function is_dismissed(): bool { $meta = (array) get_user_meta( get_current_user_id(), Pointers::DISMISSED_POINTERS_META_KEY, true ); return key_exists( static::CURRENT_POINTER_SLUG, $meta ); } public function __construct() { add_action( 'in_admin_header', [ $this, 'admin_print_script' ] ); } } modules/backups/classes/route-base.php 0000644 00000001357 14720461212 0014065 0 ustar 00 <?php namespace ImageOptimization\Modules\Backups\Classes; use ImageOptimization\Classes\Route; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Route_Base extends Route { protected $auth = true; protected string $path = ''; public function get_methods(): array { return []; } public function get_endpoint(): string { return 'backups/' . $this->get_path(); } public function get_path(): string { return $this->path; } public function get_name(): string { return ''; } public function get_permission_callback( WP_REST_Request $request ): bool { $valid = $this->permission_callback( $request ); return $valid && user_can( $this->current_user_id, 'manage_options' ); } } modules/backups/classes/remove-all-backups.php 0000644 00000001462 14720461212 0015505 0 ustar 00 <?php namespace ImageOptimization\Modules\Backups\Classes; use ImageOptimization\Classes\Async_Operation\{ Async_Operation, Async_Operation_Hook, Async_Operation_Queue, }; use ImageOptimization\Classes\Image\Image_Query_Builder; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Remove_All_Backups { private const CHUNK_SIZE = 100; public static function find_and_schedule_removing(): void { $query = ( new Image_Query_Builder() ) ->return_images_only_with_backups() ->execute(); $attachment_ids = $query->posts; $chunks = array_chunk( $attachment_ids, self::CHUNK_SIZE ); foreach ( $chunks as $chunk ) { Async_Operation::create( Async_Operation_Hook::REMOVE_MANY_BACKUPS, [ 'attachment_ids' => $chunk ], Async_Operation_Queue::BACKUP ); } } } modules/backups/classes/restore-images.php 0000644 00000005072 14720461212 0014743 0 ustar 00 <?php namespace ImageOptimization\Modules\Backups\Classes; use ImageOptimization\Classes\Async_Operation\{ Async_Operation, Async_Operation_Hook, Async_Operation_Queue, }; use ImageOptimization\Classes\Image\{ Image_Meta, Image_Query_Builder, Image_Status }; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Restore_Images { private const CHUNK_SIZE = 100; /** * Schedules a single restoring operation. * * @param int $image_id * @return void * @throws Throwable * @throws \ImageOptimization\Classes\Async_Operation\Exceptions\Async_Operation_Exception */ public static function schedule_single_restoring( int $image_id ): void { $meta = new Image_Meta( $image_id ); try { $meta ->set_status( Image_Status::RESTORING_IN_PROGRESS ) ->save(); Async_Operation::create( Async_Operation_Hook::RESTORE_SINGLE_IMAGE, [ 'attachment_id' => $image_id ], Async_Operation_Queue::RESTORE ); } catch ( Throwable $t ) { $meta ->set_status( Image_Status::RESTORING_FAILED ) ->save(); throw $t; } } /** * Schedules restoring operations for all valid images with backups created. * * @param array $image_ids * * @return void */ public static function find_and_schedule_restoring( array $image_ids = [] ): void { $query = ( new Image_Query_Builder() ) ->return_images_only_with_backups(); if ( ! empty( $image_ids ) ) { $query->set_image_ids( $image_ids ); } $query = $query->execute(); $attachment_ids = $query->posts; $chunks = array_chunk( $attachment_ids, self::CHUNK_SIZE ); foreach ( $chunks as $chunk ) { try { Async_Operation::create( Async_Operation_Hook::RESTORE_MANY_IMAGES, [ 'attachment_ids' => $chunk ], Async_Operation_Queue::RESTORE ); self::mark_chunk_as_in_progress( $chunk ); } catch ( Throwable $t ) { self::fail_restoring_for_chunk( $chunk ); } } } /** * Updates chunk images optimization status to in-progress. * * @param int[] $chunk * @return void */ private static function mark_chunk_as_in_progress( array $chunk ) { foreach ( $chunk as $image_id ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::RESTORING_IN_PROGRESS ) ->save(); } } /** * Updates chunk images optimization status to failed. * * @param int[] $chunk * @return void */ private static function fail_restoring_for_chunk( array $chunk ) { foreach ( $chunk as $image_id ) { ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::RESTORING_FAILED ) ->save(); } } } modules/backups/rest/restore-all.php 0000644 00000001640 14720461212 0013563 0 ustar 00 <?php namespace ImageOptimization\Modules\Backups\Rest; use ImageOptimization\Modules\Backups\Classes\{ Restore_Images, Route_Base, }; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Restore_All extends Route_Base { const NONCE_NAME = 'image-optimization-restore-all'; protected string $path = 'restore'; public function get_name(): string { return 'restore-all'; } public function get_methods(): array { return [ 'POST' ]; } public function POST( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); try { Restore_Images::find_and_schedule_restoring(); return $this->respond_success_json(); } catch ( Throwable $t ) { return $this->respond_error_json([ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ]); } } } modules/backups/rest/remove-backups.php 0000644 00000001655 14720461212 0014263 0 ustar 00 <?php namespace ImageOptimization\Modules\Backups\Rest; use ImageOptimization\Modules\Backups\Classes\{ Route_Base, Remove_All_Backups, }; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Remove_Backups extends Route_Base { const NONCE_NAME = 'image-optimization-remove-backups'; protected string $path = ''; public function get_name(): string { return 'remove-backups'; } public function get_methods(): array { return [ 'DELETE' ]; } public function DELETE( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); try { Remove_All_Backups::find_and_schedule_removing(); return $this->respond_success_json(); } catch ( Throwable $t ) { return $this->respond_error_json([ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ]); } } } modules/backups/rest/restore-single.php 0000644 00000002454 14720461212 0014300 0 ustar 00 <?php namespace ImageOptimization\Modules\Backups\Rest; use ImageOptimization\Modules\Optimization\Classes\Validate_Image; use ImageOptimization\Modules\Backups\Classes\{ Restore_Images, Route_Base, }; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Restore_Single extends Route_Base { const NONCE_NAME = 'image-optimization-restore-single'; protected string $path = 'restore/(?P<image_id>\d+)'; public function get_name(): string { return 'restore-single'; } public function get_methods(): array { return [ 'POST' ]; } public function POST( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); $image_id = (int) $request->get_param( 'image_id' ); if ( empty( $image_id ) ) { return $this->respond_error_json( [ 'message' => esc_html__( 'Invalid image id', 'image-optimization' ), 'code' => 'internal_server_error', ] ); } try { Validate_Image::is_valid( $image_id ); Restore_Images::schedule_single_restoring( $image_id ); return $this->respond_success_json(); } catch ( Throwable $t ) { return $this->respond_error_json([ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ]); } } } modules/backups/module.php 0000644 00000001210 14720461212 0011633 0 ustar 00 <?php namespace ImageOptimization\Modules\Backups; use ImageOptimization\Classes\Module_Base; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Module extends Module_Base { public function get_name(): string { return 'backups'; } public static function routes_list() : array { return [ 'Remove_Backups', 'Restore_Single', 'Restore_All', ]; } public static function component_list() : array { return [ 'Handle_Backups_Removing', 'Restore_Images', ]; } /** * Module constructor. */ public function __construct() { $this->register_components(); $this->register_routes(); } } modules/backups/components/handle-backups-removing.php 0000644 00000001561 14720461212 0017251 0 ustar 00 <?php namespace ImageOptimization\Modules\Backups\Components; use ImageOptimization\Classes\Async_Operation\Async_Operation_Hook; use ImageOptimization\Classes\Image\Image_Backup; use WP_Post; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Handle_Backups_Removing { public function remove_backups_on_attachment_removing( int $attachment_id, WP_Post $attachment_post ) { if ( ! wp_attachment_is_image( $attachment_post ) ) { return; } Image_Backup::remove( $attachment_id ); } /** @async */ public function remove_many_backups( array $attachment_ids ) { Image_Backup::remove_many( $attachment_ids ); } public function __construct() { add_action( 'delete_attachment', [ $this, 'remove_backups_on_attachment_removing' ], 10, 2 ); add_action( Async_Operation_Hook::REMOVE_MANY_BACKUPS, [ $this, 'remove_many_backups' ] ); } } modules/backups/components/restore-images.php 0000644 00000002055 14720461212 0015471 0 ustar 00 <?php namespace ImageOptimization\Modules\Backups\Components; use ImageOptimization\Classes\Async_Operation\Async_Operation_Hook; use ImageOptimization\Classes\Image\{ Image_Meta, Image_Restore, Image_Status, }; use ImageOptimization\Classes\Logger; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Restore_Images { /** @async */ public function restore_image( int $image_id ) { try { Image_Restore::restore( $image_id ); } catch ( Throwable $t ) { Logger::log( Logger::LEVEL_ERROR, 'Image restoring error: ' . $t->getMessage() ); ( new Image_Meta( $image_id ) ) ->set_status( Image_Status::RESTORING_FAILED ) ->save(); throw $t; } } /** @async */ public function restore_many_images( array $attachment_ids ) { Image_Restore::restore_many( $attachment_ids ); } public function __construct() { add_action( Async_Operation_Hook::RESTORE_SINGLE_IMAGE, [ $this, 'restore_image' ] ); add_action( Async_Operation_Hook::RESTORE_MANY_IMAGES, [ $this, 'restore_many_images' ] ); } } modules/connect/classes/route-base.php 0000644 00000001645 14720461212 0014066 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Classes; use ImageOptimization\Classes\Rest\Route; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Route_Base */ class Route_Base extends Route { protected bool $override = false; protected $auth = true; protected string $path = ''; public function get_methods(): array { return []; } public function get_endpoint(): string { return 'connect/' . $this->get_path(); } public function get_path(): string { return $this->path; } public function get_name(): string { return ''; } public function post_permission_callback( \WP_REST_Request $request ): bool { return $this->get_permission_callback( $request ); } public function get_permission_callback( \WP_REST_Request $request ): bool { $valid = $this->permission_callback( $request ); return $valid && user_can( $this->current_user_id, 'manage_options' ); } } modules/connect/classes/grant-types.php 0000644 00000000524 14720461212 0014270 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Classes; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class GrantTypes */ class GrantTypes extends Basic_Enum { const CLIENT_CREDENTIALS = 'client_credentials'; const AUTHORIZATION_CODE = 'authorization_code'; const REFRESH_TOKEN = 'refresh_token'; } modules/connect/classes/config.php 0000644 00000001157 14720461212 0013263 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Classes; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Config */ class Config { const APP_NAME = 'image-optimizer'; const APP_PREFIX = 'image_optimizer'; const APP_REST_NAMESPACE = 'image_optimizer'; const BASE_URL = 'https://my.elementor.com/connect'; const ADMIN_PAGE = 'upload.php?page=image-optimization-settings'; const APP_TYPE = 'app_io'; const SCOPES = 'openid offline_access'; const STATE_NONCE = 'image_optimizer_auth_nonce'; /** * Connect mode * accepts 'site' or 'user' */ const CONNECT_MODE = 'site'; } modules/connect/classes/data.php 0000644 00000021555 14720461212 0012733 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Classes; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Data */ class Data { const CLIENT_ID = '_client_id'; const CLIENT_SECRET = '_client_secret'; const ACCESS_TOKEN = '_access_token'; const REFRESH_TOKEN = '_refresh_token'; const TOKEN_ID = '_token_id'; const SUBSCRIPTION_ID = '_subscription_id'; const OPTION_OWNER_USER_ID = '_owner_user_id'; const HOME_URL = '_home_url'; /** * get_option * @param $option_name * @param $default * * @return false|mixed|null */ public static function get_option( $option_name, $default ) { return get_option( Config::APP_PREFIX . $option_name, $default ); } /** * set_option * @param $option_name * @param $option_value * @param $auto_load * * @return bool */ public static function set_option( $option_name, $option_value, $auto_load = false ): bool { return update_option( Config::APP_PREFIX . $option_name, $option_value, $auto_load ); } /** * delete_option * @param $option_name * * @return bool */ public static function delete_option( $option_name ) : bool { return delete_option( Config::APP_PREFIX . $option_name ); } /** * get_user_data * @param $user_id * @param $data_name * @param mixed|bool $default * * @return false|mixed */ public static function get_user_data( $user_id, $data_name, $default = false ) { $data = get_user_meta( $user_id, Config::APP_PREFIX . $data_name, true ); return empty( $data ) ? $default : $data; } /** * set_user_data * @param $user_id * @param $data_name * @param $value * * @return bool|int */ public static function set_user_data( $user_id, $data_name, $value ) { return update_user_meta( $user_id, Config::APP_PREFIX . $data_name, $value ); } /** * delete_user_data * @param $user_id * @param $data_name * * @return bool */ public static function delete_user_data( $user_id, $data_name ): bool { return delete_user_meta( $user_id, Config::APP_PREFIX . $data_name ); } /** * get_connect_mode_data * @param ...$data * * @return false|mixed|null|string */ public static function get_connect_mode_data( ...$data ) { if ( Config::CONNECT_MODE === 'site' ) { return self::get_option( ...$data ); } $user_id = get_current_user_id(); return self::get_user_data( ...( [ $user_id, ...$data ] ) ); } /** * set_connect_mode_data * @param ...$data * * @return bool|int */ public static function set_connect_mode_data( ...$data ) { if ( Config::CONNECT_MODE === 'site' ) { return self::set_option( ...$data ); } $user_id = get_current_user_id(); return self::set_user_data( ...( [ $user_id, ...$data ] ) ); } /** * get_client_id * * @return string|bool|mixed */ public static function get_client_id() { return self::get_connect_mode_data( self::CLIENT_ID, false ); } /** * get_client_secret * @return false|mixed|string|null */ public static function get_client_secret() { return self::get_connect_mode_data( self::CLIENT_SECRET, false ); } /** * set_client_id * @param $value * * @return bool */ public static function set_client_id( $value ): bool { return self::set_connect_mode_data( self::CLIENT_ID, $value ); } public static function get_subscription_id() { return self::get_connect_mode_data( self::SUBSCRIPTION_ID, false ); } public static function set_subscription_id( $value ): bool { return self::set_connect_mode_data( self::SUBSCRIPTION_ID, $value ); } /** * set_client_secret * @param $value * * @return bool */ public static function set_client_secret( $value ): bool { return self::set_connect_mode_data( self::CLIENT_SECRET, $value ); } /** * get_access_token * @return false|mixed|string|null */ public static function get_access_token() { return self::get_connect_mode_data( self::ACCESS_TOKEN, false ); } public static function get_token_id() { return self::get_connect_mode_data( self::TOKEN_ID, false ); } /** * get_refresh_token * @return false|mixed|string|null */ public static function get_refresh_token() { return self::get_connect_mode_data( self::REFRESH_TOKEN, false ); } public static function get_home_url() { $raw = self::get_connect_mode_data( self::HOME_URL, false ); $is_base64 = base64_encode( base64_decode( $raw, true ) ) === $raw; return $is_base64 ? base64_decode( $raw ) : $raw; } /** * set_home_url * * Stores home URL as a base64 string to avoid migration/stg tools from overriding value */ public static function set_home_url( ?string $home_url = null ): bool { $home_url = $home_url ?? home_url(); return self::set_connect_mode_data( self::HOME_URL, base64_encode( $home_url ) ); } /** * set_user_is_owner_option */ public static function set_user_is_owner_option( $value ) { return self::set_connect_mode_data( self::OPTION_OWNER_USER_ID, $value ); } /** * get_user_is_owner_option */ public static function get_user_is_owner_option() { return self::get_connect_mode_data( self::OPTION_OWNER_USER_ID, false ); } /** * fetch_option * direct query to avoid cache and race condition issues * * @param $option_name * @param $default * * @return mixed|null */ public static function fetch_option( $option_name, $default = null ) { global $wpdb; $cache_buster = wp_generate_uuid4(); $option = $wpdb->get_col( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s AND %s = %s LIMIT 1", $option_name, $cache_buster, $cache_buster ) ); if ( ! empty( $option ) ) { return $option[0]; } return $default; } /** * insert_option_uniquely * used to insert option if not there already * direct query to avoid cache and race condition issues * @param $option_name * @param $option_value * * @return bool */ public static function insert_option_uniquely( $option_name, $option_value ): bool { global $wpdb; $cache_buster = wp_generate_uuid4(); $result = $wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->options (option_name, option_value, autoload) SELECT * FROM (SELECT %s, %s, 'no') AS tmp WHERE NOT EXISTS ( SELECT option_name FROM $wpdb->options WHERE option_name = %s AND option_value = %s AND %s = %s ) LIMIT 1", $option_name, $option_value, $option_name, $option_value, $cache_buster, $cache_buster ) ); if ( false === $result || 0 === $result ) { // false means query failed, 0 means no row inserted because it exists return false; } return true; } /** * User is subscription owner. * * Check if current user is subscription owner. * * @return boolean */ public static function user_is_subscription_owner(): bool { $owner_id = (int) self::get_connect_mode_data( self::OPTION_OWNER_USER_ID, false ); return get_current_user_id() === $owner_id; } public static function ensure_reset_connect() { if ( Config::CONNECT_MODE === 'site' ) { self::delete_option( self::ACCESS_TOKEN ); self::delete_option( self::REFRESH_TOKEN ); self::delete_option( self::TOKEN_ID ); self::delete_option( self::SUBSCRIPTION_ID ); self::delete_option( self::OPTION_OWNER_USER_ID ); self::delete_option( self::HOME_URL ); delete_transient( 'image_optimizer_status_check' ); } else { $user_id = get_current_user_id(); self::delete_user_data( $user_id, self::ACCESS_TOKEN ); self::delete_user_data( $user_id, self::REFRESH_TOKEN ); self::delete_user_data( $user_id, self::TOKEN_ID ); self::delete_user_data( $user_id, self::SUBSCRIPTION_ID ); self::delete_user_data( $user_id, self::OPTION_OWNER_USER_ID ); self::delete_user_data( $user_id, self::HOME_URL ); delete_transient( 'image_optimizer_status_check' ); } } /** * clear_session */ public static function clear_session() { if ( Config::CONNECT_MODE === 'site' ) { self::delete_option( self::CLIENT_ID ); self::delete_option( self::CLIENT_SECRET ); self::delete_option( self::ACCESS_TOKEN ); self::delete_option( self::REFRESH_TOKEN ); self::delete_option( self::TOKEN_ID ); self::delete_option( self::SUBSCRIPTION_ID ); self::delete_option( self::OPTION_OWNER_USER_ID ); self::delete_option( self::HOME_URL ); delete_transient( 'image_optimizer_status_check' ); } else { $user_id = get_current_user_id(); self::delete_user_data( $user_id, self::CLIENT_ID ); self::delete_user_data( $user_id, self::CLIENT_SECRET ); self::delete_user_data( $user_id, self::ACCESS_TOKEN ); self::delete_user_data( $user_id, self::REFRESH_TOKEN ); self::delete_user_data( $user_id, self::TOKEN_ID ); self::delete_user_data( $user_id, self::SUBSCRIPTION_ID ); self::delete_user_data( $user_id, self::OPTION_OWNER_USER_ID ); self::delete_user_data( $user_id, self::HOME_URL ); delete_transient( 'image_optimizer_status_check' ); } } } modules/connect/classes/exceptions/service-exception.php 0000644 00000000371 14720461212 0017630 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Classes\Exceptions; use Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Service_Exception extends Exception { protected $message = 'Service Exception'; } modules/connect/classes/service.php 0000644 00000016276 14720461212 0013466 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Classes; use ImageOptimization\Modules\Connect\Classes\Exceptions\Service_Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Service */ class Service { const REFRESH_TOKEN_LOCK = '_connect_refresh_token'; /** * Registers new client and returns client ID * * @return string * @throws Service_Exception */ public static function register_client(): string { $clients_url = Utils::get_clients_url(); if ( ! $clients_url ) { throw new Service_Exception( 'Missing client registration URL' ); } $client_data = self::request( $clients_url, [ 'method' => 'POST', 'headers' => [ 'Content-Type' => 'application/json', ], 'body' => wp_json_encode( [ 'redirect_uri' => Utils::get_redirect_uri(), 'app_type' => Config::APP_TYPE, ] ), ], 201 ); $client_id = $client_data['client_id'] ?? null; $client_secret = $client_data['client_secret'] ?? null; Data::set_client_id( $client_id ); Data::set_client_secret( $client_secret ); Data::set_home_url(); return $client_id; } /** * Deactivate license * * @return void * @throws Service_Exception */ public static function deactivate_license(): void { $client_id = Data::get_client_id(); if ( ! $client_id ) { throw new Service_Exception( 'Missing client ID' ); } $deactivation_url = Utils::get_deactivation_url( $client_id ); if ( ! $deactivation_url ) { throw new Service_Exception( 'Missing deactivation URL' ); } $access_token = Data::get_access_token(); if ( ! $access_token ) { throw new Service_Exception( 'Missing access token' ); } $refresh_token = Data::get_refresh_token(); if ( ! $refresh_token ) { throw new Service_Exception( 'Missing refresh token' ); } self::request( $deactivation_url, [ 'method' => 'DELETE', 'headers' => [ 'Authorization' => "Bearer {$access_token}", ], ], 204 ); self::get_token( 'refresh_token', $refresh_token ); } /** * disconnect * * @return void * @throws Service_Exception */ public static function disconnect(): void { $sessions_url = Utils::get_sessions_url(); if ( ! $sessions_url ) { throw new Service_Exception( 'Missing sessions URL' ); } $access_token = Data::get_access_token(); if ( ! $access_token ) { throw new Service_Exception( 'Missing access token' ); } self::request( $sessions_url, [ 'method' => 'DELETE', 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => "Bearer {$access_token}", ], ], 204 ); Data::clear_session(); } /** * Get token & optionally save to user * * @param string $grant_type * * @param string|null $credential * * @return array * @throws Service_Exception */ public static function get_token( string $grant_type, ?string $credential = null, ?bool $update = true ): array { $token_url = Utils::get_token_url(); if ( ! $token_url ) { throw new Service_Exception( 'Missing token URL' ); } $client_id = Data::get_client_id(); $client_secret = Data::get_client_secret(); if ( empty( $client_id ) || empty( $client_secret ) ) { throw new Service_Exception( 'Missing client ID or secret' ); } $body = [ 'grant_type' => $grant_type, 'redirect_uri' => Utils::get_redirect_uri(), ]; switch ( $grant_type ) { case GrantTypes::AUTHORIZATION_CODE: $body['code'] = $credential; break; case GrantTypes::REFRESH_TOKEN: $body[ GrantTypes::REFRESH_TOKEN ] = $credential; break; case GrantTypes::CLIENT_CREDENTIALS: $body['redirect_uri'] = Utils::get_redirect_uri( Data::get_home_url() ); break; default: throw new Service_Exception( 'Invalid grant type' ); } $data = self::request( $token_url, [ 'method' => 'POST', 'headers' => [ 'x-elementor-apps' => Config::APP_NAME, 'Authorization' => 'Basic ' . base64_encode( "{$client_id}:{$client_secret}" ), ], 'body' => $body, ] ); if ( $update ) { Data::set_connect_mode_data( Data::TOKEN_ID, $data['id_token'] ?? null ); Data::set_connect_mode_data( Data::ACCESS_TOKEN, $data['access_token'] ?? null ); Data::set_connect_mode_data( Data::REFRESH_TOKEN, $data['refresh_token'] ?? null ); Data::set_connect_mode_data( Data::OPTION_OWNER_USER_ID, get_current_user_id() ); } return $data; } public static function jwt_decode( $payload ): string { static $jwks = null; $jwks_url = Utils::get_jwks_url(); if ( ! $jwks_url ) { return __( 'Missing JWKS URL' ); } if ( ! $jwks ) { $jwks = self::request( $jwks_url, [ 'method' => 'GET', ] ); } if ( ! class_exists( 'JWT' ) ) { require_once IMAGE_OPTIMIZATION_PATH . 'vendor/autoload.php'; } try { $decoded = \Firebase\JWT\JWT::decode( $payload, \Firebase\JWT\JWK::parseKeySet( $jwks ) ); return json_encode( $decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ); } catch ( \Throwable $th ) { if ( $th instanceof \Firebase\JWT\ExpiredException ) { self::get_token( GrantTypes::REFRESH_TOKEN, Data::get_refresh_token() ); return self::jwt_decode( $payload ); } return $th->getMessage(); } } /** * @param string $url * @param array $args * @param int $valid_response_code * * @return array|null * @throws Service_Exception */ public static function request( string $url, array $args, int $valid_response_code = 200 ): ?array { $args['timeout'] = 30; $response = wp_remote_request( $url, $args ); if ( is_wp_error( $response ) ) { error_log( '[Connect Service]: ' . $response->get_error_message() ); throw new Service_Exception( $response->get_error_message() ); } if ( $valid_response_code !== wp_remote_retrieve_response_code( $response ) ) { error_log( '[Connect Service]: invalid status code' . wp_remote_retrieve_response_code( $response ) ); throw new Service_Exception( wp_remote_retrieve_body( $response ) ); } return json_decode( wp_remote_retrieve_body( $response ), true ); } public static function refresh_token() { $lock_key = Config::APP_NAME . self::REFRESH_TOKEN_LOCK; $last_token = Data::fetch_option( $lock_key, '' ); $current_refresh_token = Data::get_refresh_token(); if ( ! empty( $last_token ) && $last_token === $current_refresh_token ) { sleep( 1 ); return; } delete_option( $lock_key ); $locked = Data::insert_option_uniquely( $lock_key, $current_refresh_token ); if ( ! $locked ) { sleep( 1 ); return; } self::get_token( GrantTypes::REFRESH_TOKEN, $current_refresh_token ); } /** * @throws Service_Exception */ public static function update_redirect_uri(): void { $client_id = Data::get_client_id(); if ( ! $client_id ) { throw new Service_Exception( 'Missing client ID' ); } $client_patch_url = Utils::get_clients_patch_url( $client_id ); [ 'access_token' => $access_token ] = self::get_token( GrantTypes::CLIENT_CREDENTIALS, null, false ); self::request( $client_patch_url, [ 'method' => 'PATCH', 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => "Bearer {$access_token}", ], 'body' => json_encode( [ 'redirect_uri' => Utils::get_redirect_uri(), ] ), ] ); self::refresh_token(); Data::set_home_url(); } } modules/connect/classes/basic-enum.php 0000644 00000001313 14720461212 0014033 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\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 ]; } } modules/connect/classes/utils.php 0000644 00000005536 14720461212 0013163 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Classes; use ImageOptimization\Modules\Connect\Classes\Exceptions\Service_Exception; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Utils */ class Utils { /** * get_clients_url * @return string */ public static function get_clients_url(): string { return self::get_base_url() . '/api/v1/clients'; } /** * get_redirect_uri * @return string */ public static function get_redirect_uri( string $domain = '' ): string { if ( false !== strpos( Config::ADMIN_PAGE, '?page=' ) ) { $admin_url = admin_url( Config::ADMIN_PAGE ); } else { $admin_url = admin_url( 'options-general.php?page=' . Config::ADMIN_PAGE ); } if ( $domain ) { $parsed_url = parse_url( $admin_url ); $path = $parsed_url['path'] . ( isset( $parsed_url['query'] ) ? '?' . $parsed_url['query'] : '' ); return rtrim( $domain, '/' ) . $path; } return $admin_url; } public static function get_auth_url(): string { return self::get_base_url() . '/v1/oauth2/auth'; } /** * Get full authorization URL with all required parameters * * @param string $client_id * * @return string * @throws Service_Exception */ public static function get_authorize_url( string $client_id ): string { return add_query_arg( [ 'client_id' => $client_id, 'redirect_uri' => rawurlencode( self::get_redirect_uri() ), 'response_type' => 'code', 'scope' => Config::SCOPES, 'state' => wp_create_nonce( Config::STATE_NONCE ), ], self::get_auth_url() ); } /** * get_deactivation_url * @param string $client_id * * @return string */ public static function get_deactivation_url( string $client_id ): string { return self::get_base_url() . "/api/v1/clients/{$client_id}/activation"; } public static function get_jwks_url(): string { return self::get_base_url() . '/v1/.well-known/jwks.json'; } /** * get_sessions_url * @return string */ public static function get_sessions_url(): string { return self::get_base_url() . '/api/v1/session'; } public static function get_token_url(): string { return self::get_base_url() . '/api/v1/oauth2/token'; } /** * Get clients URL * * @param string $client_id * * @return string */ public static function get_clients_patch_url( string $client_id ): string { return self::get_base_url() . "/api/v1/clients/{$client_id}"; } /** * get_base_url * @return string */ public static function get_base_url(): string { return apply_filters( 'image_optimizer_connect_get_base_url', Config::BASE_URL ); } /** * is_valid_home_url * @return bool */ public static function is_valid_home_url(): bool { static $valid = null; if ( null === $valid ) { if ( empty( Data::get_home_url() ) ) { $valid = true; } else { $valid = Data::get_home_url() === home_url(); } } return $valid; } } modules/connect/rest/authorize.php 0000644 00000004610 14720461212 0013345 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Rest; use ImageOptimization\Modules\Connect\Classes\{ Data, Route_Base, Service, Utils }; use ImageOptimization\Modules\Connect\Module as Connect; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Authorize */ class Authorize extends Route_Base { public string $path = 'authorize'; public const NONCE_NAME = 'wp_rest'; public function get_methods(): array { return [ 'POST' ]; } public function get_name(): string { return 'authorize'; } public function POST( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); if ( Connect::is_connected() && Utils::is_valid_home_url() ) { return $this->respond_error_json( [ 'message' => esc_html__( 'You are already connected', 'image-optimization' ), 'code' => 'forbidden', ] ); } try { $client_id = Data::get_client_id(); if ( ! $client_id ) { $client_id = Service::register_client(); } if ( ! Utils::is_valid_home_url() ) { if ( $request->get_param( 'update_redirect_uri' ) ) { Service::update_redirect_uri(); } else { return $this->respond_error_json( [ 'message' => esc_html__( 'Connected domain mismatch', 'image-optimization' ), 'code' => 'forbidden', ] ); } } $authorize_url = Utils::get_authorize_url( $client_id ); $additional_source_campaign = []; $image_optimization_campaign = get_transient( 'elementor_image_optimization_campaign' ); if ( ! empty( $image_optimization_campaign['source'] ) ) { $additional_source_campaign['utm_source'] = $image_optimization_campaign['source']; } if ( ! empty( $image_optimization_campaign['medium'] ) ) { $additional_source_campaign['utm_medium'] = $image_optimization_campaign['medium']; } if ( ! empty( $image_optimization_campaign['campaign'] ) ) { $additional_source_campaign['utm_campaign'] = $image_optimization_campaign['campaign']; } if ( ! empty( $additional_source_campaign ) ) { $authorize_url = add_query_arg( $additional_source_campaign, $authorize_url ); } return $this->respond_success_json( $authorize_url ); } catch ( Throwable $t ) { return $this->respond_error_json( [ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ] ); } } } modules/connect/rest/version.php 0000644 00000001531 14720461212 0013017 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Rest; use ImageOptimization\Modules\Connect\Classes\{ Data, Route_Base, Service, Utils }; use ImageOptimization\Modules\Connect\Module as Connect; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Version */ class Version extends Route_Base { public string $path = 'version'; public const NONCE_NAME = 'wp_rest'; public function get_methods(): array { return [ 'GET' ]; } public function get_name(): string { return 'version'; } public function GET( WP_REST_Request $request ) { try { return $this->respond_success_json([ 'version' => 2, ]); } catch ( Throwable $t ) { return $this->respond_error_json( [ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ] ); } } } modules/connect/rest/disconnect.php 0000644 00000001361 14720461212 0013464 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Rest; use ImageOptimization\Modules\Connect\Classes\{ Data, Route_Base, Service }; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Disconnect */ class Disconnect extends Route_Base { public string $path = 'disconnect'; public function get_methods(): array { return [ 'POST' ]; } public function get_name(): string { return 'disconnect'; } public function POST() { try { Service::disconnect(); return $this->respond_success_json(); } catch ( Throwable $t ) { Data::ensure_reset_connect(); return $this->respond_error_json( [ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ] ); } } } modules/connect/rest/deactivate-and-disconnect.php 0000644 00000001755 14720461212 0016342 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Rest; use ImageOptimization\Modules\Connect\Classes\{ Data, Route_Base, Service }; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Disconnect */ class Deactivate_And_Disconnect extends Route_Base { public string $path = 'deactivate_and_disconnect'; public function get_methods(): array { return [ 'POST' ]; } public function get_name(): string { return 'deactivate_and_disconnect'; } public function POST( WP_REST_Request $request ) { try { if ( $request->get_param( 'clear_session' ) ) { Data::clear_session(); return $this->respond_success_json(); } Service::deactivate_license(); Service::disconnect(); return $this->respond_success_json(); } catch ( Throwable $t ) { Data::ensure_reset_connect(); return $this->respond_error_json( [ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ] ); } } } modules/connect/rest/switch-domain.php 0000644 00000002333 14720461212 0014101 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Rest; use ImageOptimization\Modules\Connect\Classes\{ Data, Route_Base, Service, }; use Throwable; use WP_REST_Request; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Switch_Domain */ class Switch_Domain extends Route_Base { public string $path = 'switch_domain'; public const NONCE_NAME = 'wp_rest'; public function get_methods(): array { return [ 'POST' ]; } public function get_name(): string { return 'switch_domain'; } public function POST( WP_REST_Request $request ) { $this->verify_nonce_and_capability( $request->get_param( self::NONCE_NAME ), self::NONCE_NAME ); try { $client_id = Data::get_client_id(); if ( ! $client_id ) { return $this->respond_error_json( [ 'message' => esc_html__( 'Client ID not found', 'image-optimization' ), 'code' => 'bad_request', ] ); } Service::update_redirect_uri(); return $this->respond_success_json( [ 'message' => esc_html__( 'Domain updated!', 'image-optimization' ), ] ); } catch ( Throwable $t ) { return $this->respond_error_json( [ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ] ); } } } modules/connect/rest/deactivate.php 0000644 00000001371 14720461212 0013445 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Rest; use ImageOptimization\Modules\Connect\Classes\{ Data, Route_Base, Service }; use Throwable; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Deactivate */ class Deactivate extends Route_Base { public string $path = 'deactivate'; public function get_methods(): array { return [ 'POST' ]; } public function get_name(): string { return 'deactivate'; } public function POST() { try { Service::deactivate_license(); return $this->respond_success_json(); } catch ( Throwable $t ) { Data::ensure_reset_connect(); return $this->respond_error_json( [ 'message' => $t->getMessage(), 'code' => 'internal_server_error', ] ); } } } modules/connect/module.php 0000644 00000002314 14720461212 0011642 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect; use ImageOptimization\Classes\Module_Base; use ImageOptimization\Modules\Connect\Classes\{ Data, Utils, }; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Module */ class Module extends Module_Base { /** * Get module name. * Retrieve the module name. * @access public * @return string Module name. */ public function get_name() { return 'connect'; } /** * component_list * @return string[] */ public static function component_list() : array { return [ 'Handler', ]; } /** * routes_list * @return string[] */ public static function routes_list() : array { return [ 'Authorize', 'Disconnect', 'Deactivate', 'Deactivate_And_Disconnect', 'Version', 'Switch_Domain', ]; } public static function is_connected() : bool { return ! ! Data::get_access_token() && Utils::is_valid_home_url(); } public static function is_active() : bool { // TODO: Add login to check if the function should be active or not. return empty( get_option( 'image_optimizer_client_data' ) ); } public function __construct() { $this->register_components(); $this->register_routes(); } } modules/connect/components/handler.php 0000644 00000003336 14720461212 0014164 0 ustar 00 <?php namespace ImageOptimization\Modules\Connect\Components; use ImageOptimization\Modules\Connect\Classes\{ Config, Data, GrantTypes, Service, Utils, }; use ImageOptimization\Classes\Services\Client; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Class Handler */ class Handler { private function should_handle_auth_code(): bool { global $plugin_page; $page_slug = explode( 'page=', Config::ADMIN_PAGE ); $is_connect_admin_page = false; if ( ! empty( $page_slug[1] ) && $page_slug[1] === $plugin_page ) { $is_connect_admin_page = true; } if ( ! $is_connect_admin_page && Config::ADMIN_PAGE === $plugin_page ) { $is_connect_admin_page = true; } if ( ! $is_connect_admin_page ) { return false; } $code = $_GET['code'] ?? null; $state = $_GET['state'] ?? null; if ( empty( $code ) || empty( $state ) ) { return false; } return true; } private function validate_nonce( $state ) { if ( ! wp_verify_nonce( $state, Config::STATE_NONCE ) ) { wp_die( 'Invalid state' ); } } public function handle_auth_code() { if ( ! $this->should_handle_auth_code() ) { return; } $code = sanitize_text_field( $_GET['code'] ); $state = sanitize_text_field( $_GET['state'] ); // Check if the state is valid $this->validate_nonce( $state ); // Exchange the code for an access token and store it Service::get_token( GrantTypes::AUTHORIZATION_CODE, $code ); // Makes sure we won't stick in the mismatch limbo Data::set_home_url(); // Redirect to the redirect URI wp_redirect( Utils::get_redirect_uri() ); exit; } /** * Handler constructor. */ public function __construct() { add_action( 'admin_init', [ $this, 'handle_auth_code' ] ); } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_AdminView.php 0000644 00000022057 14720461212 0023003 0 ustar 00 <?php /** * Class ActionScheduler_AdminView * @codeCoverageIgnore */ class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated { /** @var null|self */ private static $admin_view = NULL; /** @var string */ private static $screen_id = 'tools_page_action-scheduler'; /** @var ActionScheduler_ListTable */ protected $list_table; /** * @return ActionScheduler_AdminView * @codeCoverageIgnore */ public static function instance() { if ( empty( self::$admin_view ) ) { $class = apply_filters('action_scheduler_admin_view_class', 'ActionScheduler_AdminView'); self::$admin_view = new $class(); } return self::$admin_view; } /** * Initialize. * * @codeCoverageIgnore */ public function init() { if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || false == DOING_AJAX ) ) { if ( class_exists( 'WooCommerce' ) ) { add_action( 'woocommerce_admin_status_content_action-scheduler', array( $this, 'render_admin_ui' ) ); add_action( 'woocommerce_system_status_report', array( $this, 'system_status_report' ) ); add_filter( 'woocommerce_admin_status_tabs', array( $this, 'register_system_status_tab' ) ); } add_action( 'admin_menu', array( $this, 'register_menu' ) ); add_action( 'admin_notices', array( $this, 'maybe_check_pastdue_actions' ) ); add_action( 'current_screen', array( $this, 'add_help_tabs' ) ); } } /** * Print system status report. */ public function system_status_report() { $table = new ActionScheduler_wcSystemStatus( ActionScheduler::store() ); $table->render(); } /** * Registers action-scheduler into WooCommerce > System status. * * @param array $tabs An associative array of tab key => label. * @return array $tabs An associative array of tab key => label, including Action Scheduler's tabs */ public function register_system_status_tab( array $tabs ) { $tabs['action-scheduler'] = __( 'Scheduled Actions', 'action-scheduler' ); return $tabs; } /** * Include Action Scheduler's administration under the Tools menu. * * A menu under the Tools menu is important for backward compatibility (as that's * where it started), and also provides more convenient access than the WooCommerce * System Status page, and for sites where WooCommerce isn't active. */ public function register_menu() { $hook_suffix = add_submenu_page( 'tools.php', __( 'Scheduled Actions', 'action-scheduler' ), __( 'Scheduled Actions', 'action-scheduler' ), 'manage_options', 'action-scheduler', array( $this, 'render_admin_ui' ) ); add_action( 'load-' . $hook_suffix , array( $this, 'process_admin_ui' ) ); } /** * Triggers processing of any pending actions. */ public function process_admin_ui() { $this->get_list_table(); } /** * Renders the Admin UI */ public function render_admin_ui() { $table = $this->get_list_table(); $table->display_page(); } /** * Get the admin UI object and process any requested actions. * * @return ActionScheduler_ListTable */ protected function get_list_table() { if ( null === $this->list_table ) { $this->list_table = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() ); $this->list_table->process_actions(); } return $this->list_table; } /** * Action: admin_notices * * Maybe check past-due actions, and print notice. * * @uses $this->check_pastdue_actions() */ public function maybe_check_pastdue_actions() { // Filter to prevent checking actions (ex: inappropriate user). if ( ! apply_filters( 'action_scheduler_check_pastdue_actions', current_user_can( 'manage_options' ) ) ) { return; } // Get last check transient. $last_check = get_transient( 'action_scheduler_last_pastdue_actions_check' ); // If transient exists, we're within interval, so bail. if ( ! empty( $last_check ) ) { return; } // Perform the check. $this->check_pastdue_actions(); } /** * Check past-due actions, and print notice. * * @todo update $link_url to "Past-due" filter when released (see issue #510, PR #511) */ protected function check_pastdue_actions() { // Set thresholds. $threshold_seconds = (int) apply_filters( 'action_scheduler_pastdue_actions_seconds', DAY_IN_SECONDS ); $threshold_min = (int) apply_filters( 'action_scheduler_pastdue_actions_min', 1 ); // Set fallback value for past-due actions count. $num_pastdue_actions = 0; // Allow third-parties to preempt the default check logic. $check = apply_filters( 'action_scheduler_pastdue_actions_check_pre', null ); // If no third-party preempted and there are no past-due actions, return early. if ( ! is_null( $check ) ) { return; } // Scheduled actions query arguments. $query_args = array( 'date' => as_get_datetime_object( time() - $threshold_seconds ), 'status' => ActionScheduler_Store::STATUS_PENDING, 'per_page' => $threshold_min, ); // If no third-party preempted, run default check. if ( is_null( $check ) ) { $store = ActionScheduler_Store::instance(); $num_pastdue_actions = (int) $store->query_actions( $query_args, 'count' ); // Check if past-due actions count is greater than or equal to threshold. $check = ( $num_pastdue_actions >= $threshold_min ); $check = (bool) apply_filters( 'action_scheduler_pastdue_actions_check', $check, $num_pastdue_actions, $threshold_seconds, $threshold_min ); } // If check failed, set transient and abort. if ( ! boolval( $check ) ) { $interval = apply_filters( 'action_scheduler_pastdue_actions_check_interval', round( $threshold_seconds / 4 ), $threshold_seconds ); set_transient( 'action_scheduler_last_pastdue_actions_check', time(), $interval ); return; } $actions_url = add_query_arg( array( 'page' => 'action-scheduler', 'status' => 'past-due', 'order' => 'asc', ), admin_url( 'tools.php' ) ); // Print notice. echo '<div class="notice notice-warning"><p>'; printf( // translators: 1) is the number of affected actions, 2) is a link to an admin screen. _n( '<strong>Action Scheduler:</strong> %1$d <a href="%2$s">past-due action</a> found; something may be wrong. <a href="https://actionscheduler.org/faq/#my-site-has-past-due-actions-what-can-i-do" target="_blank">Read documentation »</a>', '<strong>Action Scheduler:</strong> %1$d <a href="%2$s">past-due actions</a> found; something may be wrong. <a href="https://actionscheduler.org/faq/#my-site-has-past-due-actions-what-can-i-do" target="_blank">Read documentation »</a>', $num_pastdue_actions, 'action-scheduler' ), $num_pastdue_actions, esc_attr( esc_url( $actions_url ) ) ); echo '</p></div>'; // Facilitate third-parties to evaluate and print notices. do_action( 'action_scheduler_pastdue_actions_extra_notices', $query_args ); } /** * Provide more information about the screen and its data in the help tab. */ public function add_help_tabs() { $screen = get_current_screen(); if ( ! $screen || self::$screen_id != $screen->id ) { return; } $as_version = ActionScheduler_Versions::instance()->latest_version(); $screen->add_help_tab( array( 'id' => 'action_scheduler_about', 'title' => __( 'About', 'action-scheduler' ), 'content' => // translators: %s is the Action Scheduler version. '<h2>' . sprintf( __( 'About Action Scheduler %s', 'action-scheduler' ), $as_version ) . '</h2>' . '<p>' . __( 'Action Scheduler is a scalable, traceable job queue for background processing large sets of actions. Action Scheduler works by triggering an action hook to run at some time in the future. Scheduled actions can also be scheduled to run on a recurring schedule.', 'action-scheduler' ) . '</p>', ) ); $screen->add_help_tab( array( 'id' => 'action_scheduler_columns', 'title' => __( 'Columns', 'action-scheduler' ), 'content' => '<h2>' . __( 'Scheduled Action Columns', 'action-scheduler' ) . '</h2>' . '<ul>' . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Hook', 'action-scheduler' ), __( 'Name of the action hook that will be triggered.', 'action-scheduler' ) ) . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Status', 'action-scheduler' ), __( 'Action statuses are Pending, Complete, Canceled, Failed', 'action-scheduler' ) ) . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Arguments', 'action-scheduler' ), __( 'Optional data array passed to the action hook.', 'action-scheduler' ) ) . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Group', 'action-scheduler' ), __( 'Optional action group.', 'action-scheduler' ) ) . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Recurrence', 'action-scheduler' ), __( 'The action\'s schedule frequency.', 'action-scheduler' ) ) . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Scheduled', 'action-scheduler' ), __( 'The date/time the action is/was scheduled to run.', 'action-scheduler' ) ) . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Log', 'action-scheduler' ), __( 'Activity log for the action.', 'action-scheduler' ) ) . '</ul>', ) ); } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_QueueCleaner.php 0000644 00000017374 14720461212 0023504 0 ustar 00 <?php /** * Class ActionScheduler_QueueCleaner */ class ActionScheduler_QueueCleaner { /** @var int */ protected $batch_size; /** @var ActionScheduler_Store */ private $store = null; /** * 31 days in seconds. * * @var int */ private $month_in_seconds = 2678400; /** * @var string[] Default list of statuses purged by the cleaner process. */ private $default_statuses_to_purge = [ ActionScheduler_Store::STATUS_COMPLETE, ActionScheduler_Store::STATUS_CANCELED, ]; /** * ActionScheduler_QueueCleaner constructor. * * @param ActionScheduler_Store $store The store instance. * @param int $batch_size The batch size. */ public function __construct( ActionScheduler_Store $store = null, $batch_size = 20 ) { $this->store = $store ? $store : ActionScheduler_Store::instance(); $this->batch_size = $batch_size; } /** * Default queue cleaner process used by queue runner. * * @return array */ public function delete_old_actions() { /** * Filter the minimum scheduled date age for action deletion. * * @param int $retention_period Minimum scheduled age in seconds of the actions to be deleted. */ $lifespan = apply_filters( 'action_scheduler_retention_period', $this->month_in_seconds ); try { $cutoff = as_get_datetime_object( $lifespan . ' seconds ago' ); } catch ( Exception $e ) { _doing_it_wrong( __METHOD__, sprintf( /* Translators: %s is the exception message. */ esc_html__( 'It was not possible to determine a valid cut-off time: %s.', 'action-scheduler' ), esc_html( $e->getMessage() ) ), '3.5.5' ); return array(); } /** * Filter the statuses when cleaning the queue. * * @param string[] $default_statuses_to_purge Action statuses to clean. */ $statuses_to_purge = (array) apply_filters( 'action_scheduler_default_cleaner_statuses', $this->default_statuses_to_purge ); return $this->clean_actions( $statuses_to_purge, $cutoff, $this->get_batch_size() ); } /** * Delete selected actions limited by status and date. * * @param string[] $statuses_to_purge List of action statuses to purge. Defaults to canceled, complete. * @param DateTime $cutoff_date Date limit for selecting actions. Defaults to 31 days ago. * @param int|null $batch_size Maximum number of actions per status to delete. Defaults to 20. * @param string $context Calling process context. Defaults to `old`. * @return array Actions deleted. */ public function clean_actions( array $statuses_to_purge, DateTime $cutoff_date, $batch_size = null, $context = 'old' ) { $batch_size = $batch_size !== null ? $batch_size : $this->batch_size; $cutoff = $cutoff_date !== null ? $cutoff_date : as_get_datetime_object( $this->month_in_seconds . ' seconds ago' ); $lifespan = time() - $cutoff->getTimestamp(); if ( empty( $statuses_to_purge ) ) { $statuses_to_purge = $this->default_statuses_to_purge; } $deleted_actions = []; foreach ( $statuses_to_purge as $status ) { $actions_to_delete = $this->store->query_actions( array( 'status' => $status, 'modified' => $cutoff, 'modified_compare' => '<=', 'per_page' => $batch_size, 'orderby' => 'none', ) ); $deleted_actions = array_merge( $deleted_actions, $this->delete_actions( $actions_to_delete, $lifespan, $context ) ); } return $deleted_actions; } /** * Delete actions. * * @param int[] $actions_to_delete List of action IDs to delete. * @param int $lifespan Minimum scheduled age in seconds of the actions being deleted. * @param string $context Context of the delete request. * @return array Deleted action IDs. */ private function delete_actions( array $actions_to_delete, $lifespan = null, $context = 'old' ) { $deleted_actions = []; if ( $lifespan === null ) { $lifespan = $this->month_in_seconds; } foreach ( $actions_to_delete as $action_id ) { try { $this->store->delete_action( $action_id ); $deleted_actions[] = $action_id; } catch ( Exception $e ) { /** * Notify 3rd party code of exceptions when deleting a completed action older than the retention period * * This hook provides a way for 3rd party code to log or otherwise handle exceptions relating to their * actions. * * @param int $action_id The scheduled actions ID in the data store * @param Exception $e The exception thrown when attempting to delete the action from the data store * @param int $lifespan The retention period, in seconds, for old actions * @param int $count_of_actions_to_delete The number of old actions being deleted in this batch * @since 2.0.0 * */ do_action( "action_scheduler_failed_{$context}_action_deletion", $action_id, $e, $lifespan, count( $actions_to_delete ) ); } } return $deleted_actions; } /** * Unclaim pending actions that have not been run within a given time limit. * * When called by ActionScheduler_Abstract_QueueRunner::run_cleanup(), the time limit passed * as a parameter is 10x the time limit used for queue processing. * * @param int $time_limit The number of seconds to allow a queue to run before unclaiming its pending actions. Default 300 (5 minutes). */ public function reset_timeouts( $time_limit = 300 ) { $timeout = apply_filters( 'action_scheduler_timeout_period', $time_limit ); if ( $timeout < 0 ) { return; } $cutoff = as_get_datetime_object($timeout . ' seconds ago'); $actions_to_reset = $this->store->query_actions( array( 'status' => ActionScheduler_Store::STATUS_PENDING, 'modified' => $cutoff, 'modified_compare' => '<=', 'claimed' => true, 'per_page' => $this->get_batch_size(), 'orderby' => 'none', ) ); foreach ( $actions_to_reset as $action_id ) { $this->store->unclaim_action( $action_id ); do_action( 'action_scheduler_reset_action', $action_id ); } } /** * Mark actions that have been running for more than a given time limit as failed, based on * the assumption some uncatchable and unloggable fatal error occurred during processing. * * When called by ActionScheduler_Abstract_QueueRunner::run_cleanup(), the time limit passed * as a parameter is 10x the time limit used for queue processing. * * @param int $time_limit The number of seconds to allow an action to run before it is considered to have failed. Default 300 (5 minutes). */ public function mark_failures( $time_limit = 300 ) { $timeout = apply_filters( 'action_scheduler_failure_period', $time_limit ); if ( $timeout < 0 ) { return; } $cutoff = as_get_datetime_object($timeout . ' seconds ago'); $actions_to_reset = $this->store->query_actions( array( 'status' => ActionScheduler_Store::STATUS_RUNNING, 'modified' => $cutoff, 'modified_compare' => '<=', 'per_page' => $this->get_batch_size(), 'orderby' => 'none', ) ); foreach ( $actions_to_reset as $action_id ) { $this->store->mark_failure( $action_id ); do_action( 'action_scheduler_failed_action', $action_id, $timeout ); } } /** * Do all of the cleaning actions. * * @param int $time_limit The number of seconds to use as the timeout and failure period. Default 300 (5 minutes). * @author Jeremy Pry */ public function clean( $time_limit = 300 ) { $this->delete_old_actions(); $this->reset_timeouts( $time_limit ); $this->mark_failures( $time_limit ); } /** * Get the batch size for cleaning the queue. * * @author Jeremy Pry * @return int */ protected function get_batch_size() { /** * Filter the batch size when cleaning the queue. * * @param int $batch_size The number of actions to clean in one batch. */ return absint( apply_filters( 'action_scheduler_cleanup_batch_size', $this->batch_size ) ); } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_FatalErrorMonitor.php 0000644 00000004571 14720461212 0024532 0 ustar 00 <?php /** * Class ActionScheduler_FatalErrorMonitor */ class ActionScheduler_FatalErrorMonitor { /** @var ActionScheduler_ActionClaim */ private $claim = NULL; /** @var ActionScheduler_Store */ private $store = NULL; /** @var int */ private $action_id = 0; /** * Construct. * * @param ActionScheduler_Store $store Action store. */ public function __construct( ActionScheduler_Store $store ) { $this->store = $store; } /** * Start monitoring. * * @param ActionScheduler_ActionClaim $claim Claimed actions. */ public function attach( ActionScheduler_ActionClaim $claim ) { $this->claim = $claim; add_action( 'shutdown', array( $this, 'handle_unexpected_shutdown' ) ); add_action( 'action_scheduler_before_execute', array( $this, 'track_current_action' ), 0, 1 ); add_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0, 0 ); add_action( 'action_scheduler_execution_ignored', array( $this, 'untrack_action' ), 0, 0 ); add_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 0, 0 ); } /** * Stop monitoring. */ public function detach() { $this->claim = NULL; $this->untrack_action(); remove_action( 'shutdown', array( $this, 'handle_unexpected_shutdown' ) ); remove_action( 'action_scheduler_before_execute', array( $this, 'track_current_action' ), 0 ); remove_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0 ); remove_action( 'action_scheduler_execution_ignored', array( $this, 'untrack_action' ), 0 ); remove_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 0 ); } /** * Track specified action. * * @param int $action_id Action ID to track. */ public function track_current_action( $action_id ) { $this->action_id = $action_id; } /** * Un-track action. */ public function untrack_action() { $this->action_id = 0; } /** * Handle unexpected shutdown. */ public function handle_unexpected_shutdown() { $error = error_get_last(); if ( $error ) { if ( in_array( $error['type'], array( E_ERROR, E_PARSE, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR ) ) ) { if ( !empty($this->action_id) ) { $this->store->mark_failure( $this->action_id ); do_action( 'action_scheduler_unexpected_shutdown', $this->action_id, $error ); } } $this->store->release_claim( $this->claim ); } } } vendor/woocommerce/action-scheduler/classes/WP_CLI/ActionScheduler_WPCLI_Scheduler_command.php 0000644 00000015370 14720461212 0026507 0 ustar 00 <?php /** * Commands for Action Scheduler. */ class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command { /** * Force tables schema creation for Action Scheduler * * ## OPTIONS * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * * @subcommand fix-schema */ public function fix_schema( $args, $assoc_args ) { $schema_classes = array( ActionScheduler_LoggerSchema::class, ActionScheduler_StoreSchema::class ); foreach ( $schema_classes as $classname ) { if ( is_subclass_of( $classname, ActionScheduler_Abstract_Schema::class ) ) { $obj = new $classname(); $obj->init(); $obj->register_tables( true ); WP_CLI::success( sprintf( /* translators: %s refers to the schema name*/ __( 'Registered schema for %s', 'action-scheduler' ), $classname ) ); } } } /** * Run the Action Scheduler * * ## OPTIONS * * [--batch-size=<size>] * : The maximum number of actions to run. Defaults to 100. * * [--batches=<size>] * : Limit execution to a number of batches. Defaults to 0, meaning batches will continue being executed until all actions are complete. * * [--cleanup-batch-size=<size>] * : The maximum number of actions to clean up. Defaults to the value of --batch-size. * * [--hooks=<hooks>] * : Only run actions with the specified hook. Omitting this option runs actions with any hook. Define multiple hooks as a comma separated string (without spaces), e.g. `--hooks=hook_one,hook_two,hook_three` * * [--group=<group>] * : Only run actions from the specified group. Omitting this option runs actions from all groups. * * [--exclude-groups=<groups>] * : Run actions from all groups except the specified group(s). Define multiple groups as a comma separated string (without spaces), e.g. '--group_a,group_b'. This option is ignored when `--group` is used. * * [--free-memory-on=<count>] * : The number of actions to process between freeing memory. 0 disables freeing memory. Default 50. * * [--pause=<seconds>] * : The number of seconds to pause when freeing memory. Default no pause. * * [--force] * : Whether to force execution despite the maximum number of concurrent processes being exceeded. * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * @throws \WP_CLI\ExitException When an error occurs. * * @subcommand run */ public function run( $args, $assoc_args ) { // Handle passed arguments. $batch = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batch-size', 100 ) ); $batches = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batches', 0 ) ); $clean = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'cleanup-batch-size', $batch ) ); $hooks = explode( ',', WP_CLI\Utils\get_flag_value( $assoc_args, 'hooks', '' ) ); $hooks = array_filter( array_map( 'trim', $hooks ) ); $group = \WP_CLI\Utils\get_flag_value( $assoc_args, 'group', '' ); $exclude_groups = \WP_CLI\Utils\get_flag_value( $assoc_args, 'exclude-groups', '' ); $free_on = \WP_CLI\Utils\get_flag_value( $assoc_args, 'free-memory-on', 50 ); $sleep = \WP_CLI\Utils\get_flag_value( $assoc_args, 'pause', 0 ); $force = \WP_CLI\Utils\get_flag_value( $assoc_args, 'force', false ); ActionScheduler_DataController::set_free_ticks( $free_on ); ActionScheduler_DataController::set_sleep_time( $sleep ); $batches_completed = 0; $actions_completed = 0; $unlimited = $batches === 0; if ( is_callable( [ ActionScheduler::store(), 'set_claim_filter' ] ) ) { $exclude_groups = $this->parse_comma_separated_string( $exclude_groups ); if ( ! empty( $exclude_groups ) ) { ActionScheduler::store()->set_claim_filter('exclude-groups', $exclude_groups ); } } try { // Custom queue cleaner instance. $cleaner = new ActionScheduler_QueueCleaner( null, $clean ); // Get the queue runner instance. $runner = new ActionScheduler_WPCLI_QueueRunner( null, null, $cleaner ); // Determine how many tasks will be run in the first batch. $total = $runner->setup( $batch, $hooks, $group, $force ); // Run actions for as long as possible. while ( $total > 0 ) { $this->print_total_actions( $total ); $actions_completed += $runner->run(); $batches_completed++; // Maybe set up tasks for the next batch. $total = ( $unlimited || $batches_completed < $batches ) ? $runner->setup( $batch, $hooks, $group, $force ) : 0; } } catch ( Exception $e ) { $this->print_error( $e ); } $this->print_total_batches( $batches_completed ); $this->print_success( $actions_completed ); } /** * Converts a string of comma-separated values into an array of those same values. * * @param string $string The string of one or more comma separated values. * * @return array */ private function parse_comma_separated_string( $string ): array { return array_filter( str_getcsv( $string ) ); } /** * Print WP CLI message about how many actions are about to be processed. * * @author Jeremy Pry * * @param int $total Number of actions found. */ protected function print_total_actions( $total ) { WP_CLI::log( sprintf( /* translators: %d refers to how many scheduled tasks were found to run */ _n( 'Found %d scheduled task', 'Found %d scheduled tasks', $total, 'action-scheduler' ), $total ) ); } /** * Print WP CLI message about how many batches of actions were processed. * * @author Jeremy Pry * * @param int $batches_completed Number of completed batches. */ protected function print_total_batches( $batches_completed ) { WP_CLI::log( sprintf( /* translators: %d refers to the total number of batches executed */ _n( '%d batch executed.', '%d batches executed.', $batches_completed, 'action-scheduler' ), $batches_completed ) ); } /** * Convert an exception into a WP CLI error. * * @author Jeremy Pry * * @param Exception $e The error object. * * @throws \WP_CLI\ExitException */ protected function print_error( Exception $e ) { WP_CLI::error( sprintf( /* translators: %s refers to the exception error message */ __( 'There was an error running the action scheduler: %s', 'action-scheduler' ), $e->getMessage() ) ); } /** * Print a success message with the number of completed actions. * * @author Jeremy Pry * * @param int $actions_completed Number of completed actions. */ protected function print_success( $actions_completed ) { WP_CLI::success( sprintf( /* translators: %d refers to the total number of tasks completed */ _n( '%d scheduled task completed.', '%d scheduled tasks completed.', $actions_completed, 'action-scheduler' ), $actions_completed ) ); } } vendor/woocommerce/action-scheduler/classes/WP_CLI/ProgressBar.php 0000644 00000004722 14720461212 0021231 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI; /** * WP_CLI progress bar for Action Scheduler. */ /** * Class ProgressBar * * @package Action_Scheduler\WP_CLI * * @since 3.0.0 * * @codeCoverageIgnore */ class ProgressBar { /** @var integer */ protected $total_ticks; /** @var integer */ protected $count; /** @var integer */ protected $interval; /** @var string */ protected $message; /** @var \cli\progress\Bar */ protected $progress_bar; /** * ProgressBar constructor. * * @param string $message Text to display before the progress bar. * @param integer $count Total number of ticks to be performed. * @param integer $interval Optional. The interval in milliseconds between updates. Default 100. * * @throws \Exception When this is not run within WP CLI. */ public function __construct( $message, $count, $interval = 100 ) { if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) { /* translators: %s php class name */ throw new \Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), __CLASS__ ) ); } $this->total_ticks = 0; $this->message = $message; $this->count = $count; $this->interval = $interval; } /** * Increment the progress bar ticks. */ public function tick() { if ( null === $this->progress_bar ) { $this->setup_progress_bar(); } $this->progress_bar->tick(); $this->total_ticks++; do_action( 'action_scheduler/progress_tick', $this->total_ticks ); } /** * Get the progress bar tick count. * * @return int */ public function current() { return $this->progress_bar ? $this->progress_bar->current() : 0; } /** * Finish the current progress bar. */ public function finish() { if ( null !== $this->progress_bar ) { $this->progress_bar->finish(); } $this->progress_bar = null; } /** * Set the message used when creating the progress bar. * * @param string $message The message to be used when the next progress bar is created. */ public function set_message( $message ) { $this->message = $message; } /** * Set the count for a new progress bar. * * @param integer $count The total number of ticks expected to complete. */ public function set_count( $count ) { $this->count = $count; $this->finish(); } /** * Set up the progress bar. */ protected function setup_progress_bar() { $this->progress_bar = \WP_CLI\Utils\make_progress_bar( $this->message, $this->count, $this->interval ); } } vendor/woocommerce/action-scheduler/classes/WP_CLI/Migration_Command.php 0000644 00000011305 14720461212 0022362 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI; use Action_Scheduler\Migration\Config; use Action_Scheduler\Migration\Runner; use Action_Scheduler\Migration\Scheduler; use Action_Scheduler\Migration\Controller; use WP_CLI; use WP_CLI_Command; /** * Class Migration_Command * * @package Action_Scheduler\WP_CLI * * @since 3.0.0 * * @codeCoverageIgnore */ class Migration_Command extends WP_CLI_Command { /** @var int */ private $total_processed = 0; /** * Register the command with WP-CLI */ public function register() { if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) { return; } WP_CLI::add_command( 'action-scheduler migrate', [ $this, 'migrate' ], [ 'shortdesc' => 'Migrates actions to the DB tables store', 'synopsis' => [ [ 'type' => 'assoc', 'name' => 'batch-size', 'optional' => true, 'default' => 100, 'description' => 'The number of actions to process in each batch', ], [ 'type' => 'assoc', 'name' => 'free-memory-on', 'optional' => true, 'default' => 50, 'description' => 'The number of actions to process between freeing memory. 0 disables freeing memory', ], [ 'type' => 'assoc', 'name' => 'pause', 'optional' => true, 'default' => 0, 'description' => 'The number of seconds to pause when freeing memory', ], [ 'type' => 'flag', 'name' => 'dry-run', 'optional' => true, 'description' => 'Reports on the actions that would have been migrated, but does not change any data', ], ], ] ); } /** * Process the data migration. * * @param array $positional_args Required for WP CLI. Not used in migration. * @param array $assoc_args Optional arguments. * * @return void */ public function migrate( $positional_args, $assoc_args ) { $this->init_logging(); $config = $this->get_migration_config( $assoc_args ); $runner = new Runner( $config ); $runner->init_destination(); $batch_size = isset( $assoc_args[ 'batch-size' ] ) ? (int) $assoc_args[ 'batch-size' ] : 100; $free_on = isset( $assoc_args[ 'free-memory-on' ] ) ? (int) $assoc_args[ 'free-memory-on' ] : 50; $sleep = isset( $assoc_args[ 'pause' ] ) ? (int) $assoc_args[ 'pause' ] : 0; \ActionScheduler_DataController::set_free_ticks( $free_on ); \ActionScheduler_DataController::set_sleep_time( $sleep ); do { $actions_processed = $runner->run( $batch_size ); $this->total_processed += $actions_processed; } while ( $actions_processed > 0 ); if ( ! $config->get_dry_run() ) { // let the scheduler know that there's nothing left to do. $scheduler = new Scheduler(); $scheduler->mark_complete(); } WP_CLI::success( sprintf( '%s complete. %d actions processed.', $config->get_dry_run() ? 'Dry run' : 'Migration', $this->total_processed ) ); } /** * Build the config object used to create the Runner * * @param array $args Optional arguments. * * @return ActionScheduler\Migration\Config */ private function get_migration_config( $args ) { $args = wp_parse_args( $args, [ 'dry-run' => false, ] ); $config = Controller::instance()->get_migration_config_object(); $config->set_dry_run( ! empty( $args[ 'dry-run' ] ) ); return $config; } /** * Hook command line logging into migration actions. */ private function init_logging() { add_action( 'action_scheduler/migrate_action_dry_run', function ( $action_id ) { WP_CLI::debug( sprintf( 'Dry-run: migrated action %d', $action_id ) ); }, 10, 1 ); add_action( 'action_scheduler/no_action_to_migrate', function ( $action_id ) { WP_CLI::debug( sprintf( 'No action found to migrate for ID %d', $action_id ) ); }, 10, 1 ); add_action( 'action_scheduler/migrate_action_failed', function ( $action_id ) { WP_CLI::warning( sprintf( 'Failed migrating action with ID %d', $action_id ) ); }, 10, 1 ); add_action( 'action_scheduler/migrate_action_incomplete', function ( $source_id, $destination_id ) { WP_CLI::warning( sprintf( 'Unable to remove source action with ID %d after migrating to new ID %d', $source_id, $destination_id ) ); }, 10, 2 ); add_action( 'action_scheduler/migrated_action', function ( $source_id, $destination_id ) { WP_CLI::debug( sprintf( 'Migrated source action with ID %d to new store with ID %d', $source_id, $destination_id ) ); }, 10, 2 ); add_action( 'action_scheduler/migration_batch_starting', function ( $batch ) { WP_CLI::debug( 'Beginning migration of batch: ' . print_r( $batch, true ) ); }, 10, 1 ); add_action( 'action_scheduler/migration_batch_complete', function ( $batch ) { WP_CLI::log( sprintf( 'Completed migration of %d actions', count( $batch ) ) ); }, 10, 1 ); } } vendor/woocommerce/action-scheduler/classes/WP_CLI/ActionScheduler_WPCLI_QueueRunner.php 0000644 00000014407 14720461212 0025351 0 ustar 00 <?php use Action_Scheduler\WP_CLI\ProgressBar; /** * WP CLI Queue runner. * * This class can only be called from within a WP CLI instance. */ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRunner { /** @var array */ protected $actions; /** @var ActionScheduler_ActionClaim */ protected $claim; /** @var \cli\progress\Bar */ protected $progress_bar; /** * ActionScheduler_WPCLI_QueueRunner constructor. * * @param ActionScheduler_Store $store Store object. * @param ActionScheduler_FatalErrorMonitor $monitor Monitor object. * @param ActionScheduler_QueueCleaner $cleaner Cleaner object. * * @throws Exception When this is not run within WP CLI. */ public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null ) { if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) { /* translators: %s php class name */ throw new Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), __CLASS__ ) ); } parent::__construct( $store, $monitor, $cleaner ); } /** * Set up the Queue before processing. * * @author Jeremy Pry * * @param int $batch_size The batch size to process. * @param array $hooks The hooks being used to filter the actions claimed in this batch. * @param string $group The group of actions to claim with this batch. * @param bool $force Whether to force running even with too many concurrent processes. * * @return int The number of actions that will be run. * @throws \WP_CLI\ExitException When there are too many concurrent batches. */ public function setup( $batch_size, $hooks = array(), $group = '', $force = false ) { $this->run_cleanup(); $this->add_hooks(); // Check to make sure there aren't too many concurrent processes running. if ( $this->has_maximum_concurrent_batches() ) { if ( $force ) { WP_CLI::warning( __( 'There are too many concurrent batches, but the run is forced to continue.', 'action-scheduler' ) ); } else { WP_CLI::error( __( 'There are too many concurrent batches.', 'action-scheduler' ) ); } } // Stake a claim and store it. $this->claim = $this->store->stake_claim( $batch_size, null, $hooks, $group ); $this->monitor->attach( $this->claim ); $this->actions = $this->claim->get_actions(); return count( $this->actions ); } /** * Add our hooks to the appropriate actions. * * @author Jeremy Pry */ protected function add_hooks() { add_action( 'action_scheduler_before_execute', array( $this, 'before_execute' ) ); add_action( 'action_scheduler_after_execute', array( $this, 'after_execute' ), 10, 2 ); add_action( 'action_scheduler_failed_execution', array( $this, 'action_failed' ), 10, 2 ); } /** * Set up the WP CLI progress bar. * * @author Jeremy Pry */ protected function setup_progress_bar() { $count = count( $this->actions ); $this->progress_bar = new ProgressBar( /* translators: %d: amount of actions */ sprintf( _n( 'Running %d action', 'Running %d actions', $count, 'action-scheduler' ), $count ), $count ); } /** * Process actions in the queue. * * @author Jeremy Pry * * @param string $context Optional runner context. Default 'WP CLI'. * * @return int The number of actions processed. */ public function run( $context = 'WP CLI' ) { do_action( 'action_scheduler_before_process_queue' ); $this->setup_progress_bar(); foreach ( $this->actions as $action_id ) { // Error if we lost the claim. if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $this->claim->get_id() ) ) ) { WP_CLI::warning( __( 'The claim has been lost. Aborting current batch.', 'action-scheduler' ) ); break; } $this->process_action( $action_id, $context ); $this->progress_bar->tick(); } $completed = $this->progress_bar->current(); $this->progress_bar->finish(); $this->store->release_claim( $this->claim ); do_action( 'action_scheduler_after_process_queue' ); return $completed; } /** * Handle WP CLI message when the action is starting. * * @author Jeremy Pry * * @param int $action_id Action ID. */ public function before_execute( $action_id ) { /* translators: %s refers to the action ID */ WP_CLI::log( sprintf( __( 'Started processing action %s', 'action-scheduler' ), $action_id ) ); } /** * Handle WP CLI message when the action has completed. * * @author Jeremy Pry * * @param int $action_id ActionID. * @param null|ActionScheduler_Action $action The instance of the action. Default to null for backward compatibility. */ public function after_execute( $action_id, $action = null ) { // backward compatibility. if ( null === $action ) { $action = $this->store->fetch_action( $action_id ); } /* translators: 1: action ID 2: hook name */ WP_CLI::log( sprintf( __( 'Completed processing action %1$s with hook: %2$s', 'action-scheduler' ), $action_id, $action->get_hook() ) ); } /** * Handle WP CLI message when the action has failed. * * @author Jeremy Pry * * @param int $action_id Action ID. * @param Exception $exception Exception. * @throws \WP_CLI\ExitException With failure message. */ public function action_failed( $action_id, $exception ) { WP_CLI::error( /* translators: 1: action ID 2: exception message */ sprintf( __( 'Error processing action %1$s: %2$s', 'action-scheduler' ), $action_id, $exception->getMessage() ), false ); } /** * Sleep and help avoid hitting memory limit * * @param int $sleep_time Amount of seconds to sleep. * @deprecated 3.0.0 */ protected function stop_the_insanity( $sleep_time = 0 ) { _deprecated_function( 'ActionScheduler_WPCLI_QueueRunner::stop_the_insanity', '3.0.0', 'ActionScheduler_DataController::free_memory' ); ActionScheduler_DataController::free_memory(); } /** * Maybe trigger the stop_the_insanity() method to free up memory. */ protected function maybe_stop_the_insanity() { // The value returned by progress_bar->current() might be padded. Remove padding, and convert to int. $current_iteration = intval( trim( $this->progress_bar->current() ) ); if ( 0 === $current_iteration % 50 ) { $this->stop_the_insanity(); } } } vendor/woocommerce/action-scheduler/classes/WP_CLI/ActionScheduler_WPCLI_Clean_Command.php 0000644 00000007430 14720461212 0025551 0 ustar 00 <?php /** * Commands for Action Scheduler. */ class ActionScheduler_WPCLI_Clean_Command extends WP_CLI_Command { /** * Run the Action Scheduler Queue Cleaner * * ## OPTIONS * * [--batch-size=<size>] * : The maximum number of actions to delete per batch. Defaults to 20. * * [--batches=<size>] * : Limit execution to a number of batches. Defaults to 0, meaning batches will continue all eligible actions are deleted. * * [--status=<status>] * : Only clean actions with the specified status. Defaults to Canceled, Completed. Define multiple statuses as a comma separated string (without spaces), e.g. `--status=complete,failed,canceled` * * [--before=<datestring>] * : Only delete actions with scheduled date older than this. Defaults to 31 days. e.g `--before='7 days ago'`, `--before='02-Feb-2020 20:20:20'` * * [--pause=<seconds>] * : The number of seconds to pause between batches. Default no pause. * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * @throws \WP_CLI\ExitException When an error occurs. * * @subcommand clean */ public function clean( $args, $assoc_args ) { // Handle passed arguments. $batch = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batch-size', 20 ) ); $batches = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batches', 0 ) ); $status = explode( ',', WP_CLI\Utils\get_flag_value( $assoc_args, 'status', '' ) ); $status = array_filter( array_map( 'trim', $status ) ); $before = \WP_CLI\Utils\get_flag_value( $assoc_args, 'before', '' ); $sleep = \WP_CLI\Utils\get_flag_value( $assoc_args, 'pause', 0 ); $batches_completed = 0; $actions_deleted = 0; $unlimited = $batches === 0; try { $lifespan = as_get_datetime_object( $before ); } catch ( Exception $e ) { $lifespan = null; } try { // Custom queue cleaner instance. $cleaner = new ActionScheduler_QueueCleaner( null, $batch ); // Clean actions for as long as possible. while ( $unlimited || $batches_completed < $batches ) { if ( $sleep && $batches_completed > 0 ) { sleep( $sleep ); } $deleted = count( $cleaner->clean_actions( $status, $lifespan, null,'CLI' ) ); if ( $deleted <= 0 ) { break; } $actions_deleted += $deleted; $batches_completed++; $this->print_success( $deleted ); } } catch ( Exception $e ) { $this->print_error( $e ); } $this->print_total_batches( $batches_completed ); if ( $batches_completed > 1 ) { $this->print_success( $actions_deleted ); } } /** * Print WP CLI message about how many batches of actions were processed. * * @param int $batches_processed Number of batches processed. */ protected function print_total_batches( int $batches_processed ) { WP_CLI::log( sprintf( /* translators: %d refers to the total number of batches processed */ _n( '%d batch processed.', '%d batches processed.', $batches_processed, 'action-scheduler' ), $batches_processed ) ); } /** * Convert an exception into a WP CLI error. * * @param Exception $e The error object. * * @throws \WP_CLI\ExitException */ protected function print_error( Exception $e ) { WP_CLI::error( sprintf( /* translators: %s refers to the exception error message */ __( 'There was an error deleting an action: %s', 'action-scheduler' ), $e->getMessage() ) ); } /** * Print a success message with the number of completed actions. * * @param int $actions_deleted Number of deleted actions. */ protected function print_success( int $actions_deleted ) { WP_CLI::success( sprintf( /* translators: %d refers to the total number of actions deleted */ _n( '%d action deleted.', '%d actions deleted.', $actions_deleted, 'action-scheduler' ), $actions_deleted ) ); } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_OptionLock.php 0000644 00000007751 14720461212 0023205 0 ustar 00 <?php /** * Provide a way to set simple transient locks to block behaviour * for up-to a given duration. * * Class ActionScheduler_OptionLock * @since 3.0.0 */ class ActionScheduler_OptionLock extends ActionScheduler_Lock { /** * Set a lock using options for a given amount of time (60 seconds by default). * * Using an autoloaded option avoids running database queries or other resource intensive tasks * on frequently triggered hooks, like 'init' or 'shutdown'. * * For example, ActionScheduler_QueueRunner->maybe_dispatch_async_request() uses a lock to avoid * calling ActionScheduler_QueueRunner->has_maximum_concurrent_batches() every time the 'shutdown', * hook is triggered, because that method calls ActionScheduler_QueueRunner->store->get_claim_count() * to find the current number of claims in the database. * * @param string $lock_type A string to identify different lock types. * @bool True if lock value has changed, false if not or if set failed. */ public function set( $lock_type ) { global $wpdb; $lock_key = $this->get_key( $lock_type ); $existing_lock_value = $this->get_existing_lock( $lock_type ); $new_lock_value = $this->new_lock_value( $lock_type ); // The lock may not exist yet, or may have been deleted. if ( empty( $existing_lock_value ) ) { return (bool) $wpdb->insert( $wpdb->options, array( 'option_name' => $lock_key, 'option_value' => $new_lock_value, 'autoload' => 'no', ) ); } if ( $this->get_expiration_from( $existing_lock_value ) >= time() ) { return false; } // Otherwise, try to obtain the lock. return (bool) $wpdb->update( $wpdb->options, array( 'option_value' => $new_lock_value ), array( 'option_name' => $lock_key, 'option_value' => $existing_lock_value, ) ); } /** * If a lock is set, return the timestamp it was set to expiry. * * @param string $lock_type A string to identify different lock types. * @return bool|int False if no lock is set, otherwise the timestamp for when the lock is set to expire. */ public function get_expiration( $lock_type ) { return $this->get_expiration_from( $this->get_existing_lock( $lock_type ) ); } /** * Given the lock string, derives the lock expiration timestamp (or false if it cannot be determined). * * @param string $lock_value String containing a timestamp, or pipe-separated combination of unique value and timestamp. * * @return false|int */ private function get_expiration_from( $lock_value ) { $lock_string = explode( '|', $lock_value ); // Old style lock? if ( count( $lock_string ) === 1 && is_numeric( $lock_string[0] ) ) { return (int) $lock_string[0]; } // New style lock? if ( count( $lock_string ) === 2 && is_numeric( $lock_string[1] ) ) { return (int) $lock_string[1]; } return false; } /** * Get the key to use for storing the lock in the transient * * @param string $lock_type A string to identify different lock types. * @return string */ protected function get_key( $lock_type ) { return sprintf( 'action_scheduler_lock_%s', $lock_type ); } /** * Supplies the existing lock value, or an empty string if not set. * * @param string $lock_type A string to identify different lock types. * * @return string */ private function get_existing_lock( $lock_type ) { global $wpdb; // Now grab the existing lock value, if there is one. return (string) $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s", $this->get_key( $lock_type ) ) ); } /** * Supplies a lock value consisting of a unique value and the current timestamp, which are separated by a pipe * character. * * Example: (string) "649de012e6b262.09774912|1688068114" * * @param string $lock_type A string to identify different lock types. * * @return string */ private function new_lock_value( $lock_type ) { return uniqid( '', true ) . '|' . ( time() + $this->get_duration( $lock_type ) ); } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_ListTable.php 0000644 00000051640 14720461212 0023003 0 ustar 00 <?php /** * Implements the admin view of the actions. * @codeCoverageIgnore */ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable { /** * The package name. * * @var string */ protected $package = 'action-scheduler'; /** * Columns to show (name => label). * * @var array */ protected $columns = array(); /** * Actions (name => label). * * @var array */ protected $row_actions = array(); /** * The active data stores * * @var ActionScheduler_Store */ protected $store; /** * A logger to use for getting action logs to display * * @var ActionScheduler_Logger */ protected $logger; /** * A ActionScheduler_QueueRunner runner instance (or child class) * * @var ActionScheduler_QueueRunner */ protected $runner; /** * Bulk actions. The key of the array is the method name of the implementation: * * bulk_<key>(array $ids, string $sql_in). * * See the comments in the parent class for further details * * @var array */ protected $bulk_actions = array(); /** * Flag variable to render our notifications, if any, once. * * @var bool */ protected static $did_notification = false; /** * Array of seconds for common time periods, like week or month, alongside an internationalised string representation, i.e. "Day" or "Days" * * @var array */ private static $time_periods; /** * Sets the current data store object into `store->action` and initialises the object. * * @param ActionScheduler_Store $store Store object. * @param ActionScheduler_Logger $logger Logger object. * @param ActionScheduler_QueueRunner $runner Runner object. */ public function __construct( ActionScheduler_Store $store, ActionScheduler_Logger $logger, ActionScheduler_QueueRunner $runner ) { $this->store = $store; $this->logger = $logger; $this->runner = $runner; $this->table_header = __( 'Scheduled Actions', 'action-scheduler' ); $this->bulk_actions = array( 'delete' => __( 'Delete', 'action-scheduler' ), ); $this->columns = array( 'hook' => __( 'Hook', 'action-scheduler' ), 'status' => __( 'Status', 'action-scheduler' ), 'args' => __( 'Arguments', 'action-scheduler' ), 'group' => __( 'Group', 'action-scheduler' ), 'recurrence' => __( 'Recurrence', 'action-scheduler' ), 'schedule' => __( 'Scheduled Date', 'action-scheduler' ), 'log_entries' => __( 'Log', 'action-scheduler' ), ); $this->sort_by = array( 'schedule', 'hook', 'group', ); $this->search_by = array( 'hook', 'args', 'claim_id', ); $request_status = $this->get_request_status(); if ( empty( $request_status ) ) { $this->sort_by[] = 'status'; } elseif ( in_array( $request_status, array( 'in-progress', 'failed' ) ) ) { $this->columns += array( 'claim_id' => __( 'Claim ID', 'action-scheduler' ) ); $this->sort_by[] = 'claim_id'; } $this->row_actions = array( 'hook' => array( 'run' => array( 'name' => __( 'Run', 'action-scheduler' ), 'desc' => __( 'Process the action now as if it were run as part of a queue', 'action-scheduler' ), ), 'cancel' => array( 'name' => __( 'Cancel', 'action-scheduler' ), 'desc' => __( 'Cancel the action now to avoid it being run in future', 'action-scheduler' ), 'class' => 'cancel trash', ), ), ); self::$time_periods = array( array( 'seconds' => YEAR_IN_SECONDS, /* translators: %s: amount of time */ 'names' => _n_noop( '%s year', '%s years', 'action-scheduler' ), ), array( 'seconds' => MONTH_IN_SECONDS, /* translators: %s: amount of time */ 'names' => _n_noop( '%s month', '%s months', 'action-scheduler' ), ), array( 'seconds' => WEEK_IN_SECONDS, /* translators: %s: amount of time */ 'names' => _n_noop( '%s week', '%s weeks', 'action-scheduler' ), ), array( 'seconds' => DAY_IN_SECONDS, /* translators: %s: amount of time */ 'names' => _n_noop( '%s day', '%s days', 'action-scheduler' ), ), array( 'seconds' => HOUR_IN_SECONDS, /* translators: %s: amount of time */ 'names' => _n_noop( '%s hour', '%s hours', 'action-scheduler' ), ), array( 'seconds' => MINUTE_IN_SECONDS, /* translators: %s: amount of time */ 'names' => _n_noop( '%s minute', '%s minutes', 'action-scheduler' ), ), array( 'seconds' => 1, /* translators: %s: amount of time */ 'names' => _n_noop( '%s second', '%s seconds', 'action-scheduler' ), ), ); parent::__construct( array( 'singular' => 'action-scheduler', 'plural' => 'action-scheduler', 'ajax' => false, ) ); add_screen_option( 'per_page', array( 'default' => $this->items_per_page, ) ); add_filter( 'set_screen_option_' . $this->get_per_page_option_name(), array( $this, 'set_items_per_page_option' ), 10, 3 ); set_screen_options(); } /** * Handles setting the items_per_page option for this screen. * * @param mixed $status Default false (to skip saving the current option). * @param string $option Screen option name. * @param int $value Screen option value. * @return int */ public function set_items_per_page_option( $status, $option, $value ) { return $value; } /** * Convert an interval of seconds into a two part human friendly string. * * The WordPress human_time_diff() function only calculates the time difference to one degree, meaning * even if an action is 1 day and 11 hours away, it will display "1 day". This function goes one step * further to display two degrees of accuracy. * * Inspired by the Crontrol::interval() function by Edward Dale: https://wordpress.org/plugins/wp-crontrol/ * * @param int $interval A interval in seconds. * @param int $periods_to_include Depth of time periods to include, e.g. for an interval of 70, and $periods_to_include of 2, both minutes and seconds would be included. With a value of 1, only minutes would be included. * @return string A human friendly string representation of the interval. */ private static function human_interval( $interval, $periods_to_include = 2 ) { if ( $interval <= 0 ) { return __( 'Now!', 'action-scheduler' ); } $output = ''; $num_time_periods = count( self::$time_periods ); for ( $time_period_index = 0, $periods_included = 0, $seconds_remaining = $interval; $time_period_index < $num_time_periods && $seconds_remaining > 0 && $periods_included < $periods_to_include; $time_period_index++ ) { $periods_in_interval = floor( $seconds_remaining / self::$time_periods[ $time_period_index ]['seconds'] ); if ( $periods_in_interval > 0 ) { if ( ! empty( $output ) ) { $output .= ' '; } $output .= sprintf( translate_nooped_plural( self::$time_periods[ $time_period_index ]['names'], $periods_in_interval, 'action-scheduler' ), $periods_in_interval ); $seconds_remaining -= $periods_in_interval * self::$time_periods[ $time_period_index ]['seconds']; $periods_included++; } } return $output; } /** * Returns the recurrence of an action or 'Non-repeating'. The output is human readable. * * @param ActionScheduler_Action $action Action object. * * @return string */ protected function get_recurrence( $action ) { $schedule = $action->get_schedule(); if ( $schedule->is_recurring() && method_exists( $schedule, 'get_recurrence' ) ) { $recurrence = $schedule->get_recurrence(); if ( is_numeric( $recurrence ) ) { /* translators: %s: time interval */ return sprintf( __( 'Every %s', 'action-scheduler' ), self::human_interval( $recurrence ) ); } else { return $recurrence; } } return __( 'Non-repeating', 'action-scheduler' ); } /** * Serializes the argument of an action to render it in a human friendly format. * * @param array $row The array representation of the current row of the table. * * @return string */ public function column_args( array $row ) { if ( empty( $row['args'] ) ) { return apply_filters( 'action_scheduler_list_table_column_args', '', $row ); } $row_html = '<ul>'; foreach ( $row['args'] as $key => $value ) { $row_html .= sprintf( '<li><code>%s => %s</code></li>', esc_html( var_export( $key, true ) ), esc_html( var_export( $value, true ) ) ); } $row_html .= '</ul>'; return apply_filters( 'action_scheduler_list_table_column_args', $row_html, $row ); } /** * Prints the logs entries inline. We do so to avoid loading Javascript and other hacks to show it in a modal. * * @param array $row Action array. * @return string */ public function column_log_entries( array $row ) { $log_entries_html = '<ol>'; $timezone = new DateTimezone( 'UTC' ); foreach ( $row['log_entries'] as $log_entry ) { $log_entries_html .= $this->get_log_entry_html( $log_entry, $timezone ); } $log_entries_html .= '</ol>'; return $log_entries_html; } /** * Prints the logs entries inline. We do so to avoid loading Javascript and other hacks to show it in a modal. * * @param ActionScheduler_LogEntry $log_entry Log entry object. * @param DateTimezone $timezone Timestamp. * @return string */ protected function get_log_entry_html( ActionScheduler_LogEntry $log_entry, DateTimezone $timezone ) { $date = $log_entry->get_date(); $date->setTimezone( $timezone ); return sprintf( '<li><strong>%s</strong><br/>%s</li>', esc_html( $date->format( 'Y-m-d H:i:s O' ) ), esc_html( $log_entry->get_message() ) ); } /** * Only display row actions for pending actions. * * @param array $row Row to render. * @param string $column_name Current row. * * @return string */ protected function maybe_render_actions( $row, $column_name ) { if ( 'pending' === strtolower( $row[ 'status_name' ] ) ) { return parent::maybe_render_actions( $row, $column_name ); } return ''; } /** * Renders admin notifications * * Notifications: * 1. When the maximum number of tasks are being executed simultaneously. * 2. Notifications when a task is manually executed. * 3. Tables are missing. */ public function display_admin_notices() { global $wpdb; if ( ( is_a( $this->store, 'ActionScheduler_HybridStore' ) || is_a( $this->store, 'ActionScheduler_DBStore' ) ) && apply_filters( 'action_scheduler_enable_recreate_data_store', true ) ) { $table_list = array( 'actionscheduler_actions', 'actionscheduler_logs', 'actionscheduler_groups', 'actionscheduler_claims', ); $found_tables = $wpdb->get_col( "SHOW TABLES LIKE '{$wpdb->prefix}actionscheduler%'" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared foreach ( $table_list as $table_name ) { if ( ! in_array( $wpdb->prefix . $table_name, $found_tables ) ) { $this->admin_notices[] = array( 'class' => 'error', 'message' => __( 'It appears one or more database tables were missing. Attempting to re-create the missing table(s).' , 'action-scheduler' ), ); $this->recreate_tables(); parent::display_admin_notices(); return; } } } if ( $this->runner->has_maximum_concurrent_batches() ) { $claim_count = $this->store->get_claim_count(); $this->admin_notices[] = array( 'class' => 'updated', 'message' => sprintf( /* translators: %s: amount of claims */ _n( 'Maximum simultaneous queues already in progress (%s queue). No additional queues will begin processing until the current queues are complete.', 'Maximum simultaneous queues already in progress (%s queues). No additional queues will begin processing until the current queues are complete.', $claim_count, 'action-scheduler' ), $claim_count ), ); } elseif ( $this->store->has_pending_actions_due() ) { $async_request_lock_expiration = ActionScheduler::lock()->get_expiration( 'async-request-runner' ); // No lock set or lock expired. if ( false === $async_request_lock_expiration || $async_request_lock_expiration < time() ) { $in_progress_url = add_query_arg( 'status', 'in-progress', remove_query_arg( 'status' ) ); /* translators: %s: process URL */ $async_request_message = sprintf( __( 'A new queue has begun processing. <a href="%s">View actions in-progress »</a>', 'action-scheduler' ), esc_url( $in_progress_url ) ); } else { /* translators: %d: seconds */ $async_request_message = sprintf( __( 'The next queue will begin processing in approximately %d seconds.', 'action-scheduler' ), $async_request_lock_expiration - time() ); } $this->admin_notices[] = array( 'class' => 'notice notice-info', 'message' => $async_request_message, ); } $notification = get_transient( 'action_scheduler_admin_notice' ); if ( is_array( $notification ) ) { delete_transient( 'action_scheduler_admin_notice' ); $action = $this->store->fetch_action( $notification['action_id'] ); $action_hook_html = '<strong><code>' . $action->get_hook() . '</code></strong>'; if ( 1 == $notification['success'] ) { $class = 'updated'; switch ( $notification['row_action_type'] ) { case 'run' : /* translators: %s: action HTML */ $action_message_html = sprintf( __( 'Successfully executed action: %s', 'action-scheduler' ), $action_hook_html ); break; case 'cancel' : /* translators: %s: action HTML */ $action_message_html = sprintf( __( 'Successfully canceled action: %s', 'action-scheduler' ), $action_hook_html ); break; default : /* translators: %s: action HTML */ $action_message_html = sprintf( __( 'Successfully processed change for action: %s', 'action-scheduler' ), $action_hook_html ); break; } } else { $class = 'error'; /* translators: 1: action HTML 2: action ID 3: error message */ $action_message_html = sprintf( __( 'Could not process change for action: "%1$s" (ID: %2$d). Error: %3$s', 'action-scheduler' ), $action_hook_html, esc_html( $notification['action_id'] ), esc_html( $notification['error_message'] ) ); } $action_message_html = apply_filters( 'action_scheduler_admin_notice_html', $action_message_html, $action, $notification ); $this->admin_notices[] = array( 'class' => $class, 'message' => $action_message_html, ); } parent::display_admin_notices(); } /** * Prints the scheduled date in a human friendly format. * * @param array $row The array representation of the current row of the table. * * @return string */ public function column_schedule( $row ) { return $this->get_schedule_display_string( $row['schedule'] ); } /** * Get the scheduled date in a human friendly format. * * @param ActionScheduler_Schedule $schedule Action's schedule. * @return string */ protected function get_schedule_display_string( ActionScheduler_Schedule $schedule ) { $schedule_display_string = ''; if ( is_a( $schedule, 'ActionScheduler_NullSchedule' ) ) { return __( 'async', 'action-scheduler' ); } if ( ! method_exists( $schedule, 'get_date' ) || ! $schedule->get_date() ) { return '0000-00-00 00:00:00'; } $next_timestamp = $schedule->get_date()->getTimestamp(); $schedule_display_string .= $schedule->get_date()->format( 'Y-m-d H:i:s O' ); $schedule_display_string .= '<br/>'; if ( gmdate( 'U' ) > $next_timestamp ) { /* translators: %s: date interval */ $schedule_display_string .= sprintf( __( ' (%s ago)', 'action-scheduler' ), self::human_interval( gmdate( 'U' ) - $next_timestamp ) ); } else { /* translators: %s: date interval */ $schedule_display_string .= sprintf( __( ' (%s)', 'action-scheduler' ), self::human_interval( $next_timestamp - gmdate( 'U' ) ) ); } return $schedule_display_string; } /** * Bulk delete. * * Deletes actions based on their ID. This is the handler for the bulk delete. It assumes the data * properly validated by the callee and it will delete the actions without any extra validation. * * @param int[] $ids Action IDs. * @param string $ids_sql Inherited and unused. */ protected function bulk_delete( array $ids, $ids_sql ) { foreach ( $ids as $id ) { try { $this->store->delete_action( $id ); } catch ( Exception $e ) { // A possible reason for an exception would include a scenario where the same action is deleted by a // concurrent request. error_log( sprintf( /* translators: 1: action ID 2: exception message. */ __( 'Action Scheduler was unable to delete action %1$d. Reason: %2$s', 'action-scheduler' ), $id, $e->getMessage() ) ); } } } /** * Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their * parameters are valid. * * @param int $action_id Action ID. */ protected function row_action_cancel( $action_id ) { $this->process_row_action( $action_id, 'cancel' ); } /** * Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their * parameters are valid. * * @param int $action_id Action ID. */ protected function row_action_run( $action_id ) { $this->process_row_action( $action_id, 'run' ); } /** * Force the data store schema updates. */ protected function recreate_tables() { if ( is_a( $this->store, 'ActionScheduler_HybridStore' ) ) { $store = $this->store; } else { $store = new ActionScheduler_HybridStore(); } add_action( 'action_scheduler/created_table', array( $store, 'set_autoincrement' ), 10, 2 ); $store_schema = new ActionScheduler_StoreSchema(); $logger_schema = new ActionScheduler_LoggerSchema(); $store_schema->register_tables( true ); $logger_schema->register_tables( true ); remove_action( 'action_scheduler/created_table', array( $store, 'set_autoincrement' ), 10 ); } /** * Implements the logic behind processing an action once an action link is clicked on the list table. * * @param int $action_id Action ID. * @param string $row_action_type The type of action to perform on the action. */ protected function process_row_action( $action_id, $row_action_type ) { try { switch ( $row_action_type ) { case 'run' : $this->runner->process_action( $action_id, 'Admin List Table' ); break; case 'cancel' : $this->store->cancel_action( $action_id ); break; } $success = 1; $error_message = ''; } catch ( Exception $e ) { $success = 0; $error_message = $e->getMessage(); } set_transient( 'action_scheduler_admin_notice', compact( 'action_id', 'success', 'error_message', 'row_action_type' ), 30 ); } /** * {@inheritDoc} */ public function prepare_items() { $this->prepare_column_headers(); $per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page ); $query = array( 'per_page' => $per_page, 'offset' => $this->get_items_offset(), 'status' => $this->get_request_status(), 'orderby' => $this->get_request_orderby(), 'order' => $this->get_request_order(), 'search' => $this->get_request_search_query(), ); /** * Change query arguments to query for past-due actions. * Past-due actions have the 'pending' status and are in the past. * This is needed because registering 'past-due' as a status is overkill. */ if ( 'past-due' === $this->get_request_status() ) { $query['status'] = ActionScheduler_Store::STATUS_PENDING; $query['date'] = as_get_datetime_object(); } $this->items = array(); $total_items = $this->store->query_actions( $query, 'count' ); $status_labels = $this->store->get_status_labels(); foreach ( $this->store->query_actions( $query ) as $action_id ) { try { $action = $this->store->fetch_action( $action_id ); } catch ( Exception $e ) { continue; } if ( is_a( $action, 'ActionScheduler_NullAction' ) ) { continue; } $this->items[ $action_id ] = array( 'ID' => $action_id, 'hook' => $action->get_hook(), 'status_name' => $this->store->get_status( $action_id ), 'status' => $status_labels[ $this->store->get_status( $action_id ) ], 'args' => $action->get_args(), 'group' => $action->get_group(), 'log_entries' => $this->logger->get_logs( $action_id ), 'claim_id' => $this->store->get_claim_id( $action_id ), 'recurrence' => $this->get_recurrence( $action ), 'schedule' => $action->get_schedule(), ); } $this->set_pagination_args( array( 'total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil( $total_items / $per_page ), ) ); } /** * Prints the available statuses so the user can click to filter. */ protected function display_filter_by_status() { $this->status_counts = $this->store->action_counts() + $this->store->extra_action_counts(); parent::display_filter_by_status(); } /** * Get the text to display in the search box on the list table. */ protected function get_search_box_button_text() { return __( 'Search hook, args and claim ID', 'action-scheduler' ); } /** * {@inheritDoc} */ protected function get_per_page_option_name() { return str_replace( '-', '_', $this->screen->id ) . '_per_page'; } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_DataController.php 0000644 00000012246 14720461212 0024034 0 ustar 00 <?php use Action_Scheduler\Migration\Controller; /** * Class ActionScheduler_DataController * * The main plugin/initialization class for the data stores. * * Responsible for hooking everything up with WordPress. * * @package Action_Scheduler * * @since 3.0.0 */ class ActionScheduler_DataController { /** Action data store class name. */ const DATASTORE_CLASS = 'ActionScheduler_DBStore'; /** Logger data store class name. */ const LOGGER_CLASS = 'ActionScheduler_DBLogger'; /** Migration status option name. */ const STATUS_FLAG = 'action_scheduler_migration_status'; /** Migration status option value. */ const STATUS_COMPLETE = 'complete'; /** Migration minimum required PHP version. */ const MIN_PHP_VERSION = '5.5'; /** @var ActionScheduler_DataController */ private static $instance; /** @var int */ private static $sleep_time = 0; /** @var int */ private static $free_ticks = 50; /** * Get a flag indicating whether the migration environment dependencies are met. * * @return bool */ public static function dependencies_met() { $php_support = version_compare( PHP_VERSION, self::MIN_PHP_VERSION, '>=' ); return $php_support && apply_filters( 'action_scheduler_migration_dependencies_met', true ); } /** * Get a flag indicating whether the migration is complete. * * @return bool Whether the flag has been set marking the migration as complete */ public static function is_migration_complete() { return get_option( self::STATUS_FLAG ) === self::STATUS_COMPLETE; } /** * Mark the migration as complete. */ public static function mark_migration_complete() { update_option( self::STATUS_FLAG, self::STATUS_COMPLETE ); } /** * Unmark migration when a plugin is de-activated. Will not work in case of silent activation, for example in an update. * We do this to mitigate the bug of lost actions which happens if there was an AS 2.x to AS 3.x migration in the past, but that plugin is now * deactivated and the site was running on AS 2.x again. */ public static function mark_migration_incomplete() { delete_option( self::STATUS_FLAG ); } /** * Set the action store class name. * * @param string $class Classname of the store class. * * @return string */ public static function set_store_class( $class ) { return self::DATASTORE_CLASS; } /** * Set the action logger class name. * * @param string $class Classname of the logger class. * * @return string */ public static function set_logger_class( $class ) { return self::LOGGER_CLASS; } /** * Set the sleep time in seconds. * * @param integer $sleep_time The number of seconds to pause before resuming operation. */ public static function set_sleep_time( $sleep_time ) { self::$sleep_time = (int) $sleep_time; } /** * Set the tick count required for freeing memory. * * @param integer $free_ticks The number of ticks to free memory on. */ public static function set_free_ticks( $free_ticks ) { self::$free_ticks = (int) $free_ticks; } /** * Free memory if conditions are met. * * @param int $ticks Current tick count. */ public static function maybe_free_memory( $ticks ) { if ( self::$free_ticks && 0 === $ticks % self::$free_ticks ) { self::free_memory(); } } /** * Reduce memory footprint by clearing the database query and object caches. */ public static function free_memory() { if ( 0 < self::$sleep_time ) { /* translators: %d: amount of time */ \WP_CLI::warning( sprintf( _n( 'Stopped the insanity for %d second', 'Stopped the insanity for %d seconds', self::$sleep_time, 'action-scheduler' ), self::$sleep_time ) ); sleep( self::$sleep_time ); } \WP_CLI::warning( __( 'Attempting to reduce used memory...', 'action-scheduler' ) ); /** * @var $wpdb \wpdb * @var $wp_object_cache \WP_Object_Cache */ global $wpdb, $wp_object_cache; $wpdb->queries = array(); if ( ! is_a( $wp_object_cache, 'WP_Object_Cache' ) ) { return; } $wp_object_cache->group_ops = array(); $wp_object_cache->stats = array(); $wp_object_cache->memcache_debug = array(); $wp_object_cache->cache = array(); if ( is_callable( array( $wp_object_cache, '__remoteset' ) ) ) { call_user_func( array( $wp_object_cache, '__remoteset' ) ); // important! } } /** * Connect to table datastores if migration is complete. * Otherwise, proceed with the migration if the dependencies have been met. */ public static function init() { if ( self::is_migration_complete() ) { add_filter( 'action_scheduler_store_class', array( 'ActionScheduler_DataController', 'set_store_class' ), 100 ); add_filter( 'action_scheduler_logger_class', array( 'ActionScheduler_DataController', 'set_logger_class' ), 100 ); add_action( 'deactivate_plugin', array( 'ActionScheduler_DataController', 'mark_migration_incomplete' ) ); } elseif ( self::dependencies_met() ) { Controller::init(); } add_action( 'action_scheduler/progress_tick', array( 'ActionScheduler_DataController', 'maybe_free_memory' ) ); } /** * Singleton factory. */ public static function instance() { if ( ! isset( self::$instance ) ) { self::$instance = new static(); } return self::$instance; } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_Versions.php 0000644 00000003141 14720461212 0022721 0 ustar 00 <?php /** * Class ActionScheduler_Versions */ class ActionScheduler_Versions { /** * @var ActionScheduler_Versions */ private static $instance = NULL; /** @var array<string, callable> */ private $versions = array(); /** * Register version's callback. * * @param string $version_string Action Scheduler version. * @param callable $initialization_callback Callback to initialize the version. */ public function register( $version_string, $initialization_callback ) { if ( isset($this->versions[$version_string]) ) { return FALSE; } $this->versions[$version_string] = $initialization_callback; return TRUE; } /** * Get all versions. */ public function get_versions() { return $this->versions; } /** * Get latest version registered. */ public function latest_version() { $keys = array_keys($this->versions); if ( empty($keys) ) { return false; } uasort( $keys, 'version_compare' ); return end($keys); } /** * Get callback for latest registered version. */ public function latest_version_callback() { $latest = $this->latest_version(); if ( empty($latest) || !isset($this->versions[$latest]) ) { return '__return_null'; } return $this->versions[$latest]; } /** * @return ActionScheduler_Versions * @codeCoverageIgnore */ public static function instance() { if ( empty(self::$instance) ) { self::$instance = new self(); } return self::$instance; } /** * @codeCoverageIgnore */ public static function initialize_latest_version() { $self = self::instance(); call_user_func($self->latest_version_callback()); } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_wcSystemStatus.php 0000644 00000012270 14720461212 0024136 0 ustar 00 <?php /** * Class ActionScheduler_wcSystemStatus */ class ActionScheduler_wcSystemStatus { /** * The active data stores * * @var ActionScheduler_Store */ protected $store; /** * Constructor method for ActionScheduler_wcSystemStatus. * * @param ActionScheduler_Store $store Active store object. * * @return void */ public function __construct( $store ) { $this->store = $store; } /** * Display action data, including number of actions grouped by status and the oldest & newest action in each status. * * Helpful to identify issues, like a clogged queue. */ public function render() { $action_counts = $this->store->action_counts(); $status_labels = $this->store->get_status_labels(); $oldest_and_newest = $this->get_oldest_and_newest( array_keys( $status_labels ) ); $this->get_template( $status_labels, $action_counts, $oldest_and_newest ); } /** * Get oldest and newest scheduled dates for a given set of statuses. * * @param array $status_keys Set of statuses to find oldest & newest action for. * @return array */ protected function get_oldest_and_newest( $status_keys ) { $oldest_and_newest = array(); foreach ( $status_keys as $status ) { $oldest_and_newest[ $status ] = array( 'oldest' => '–', 'newest' => '–', ); if ( 'in-progress' === $status ) { continue; } $oldest_and_newest[ $status ]['oldest'] = $this->get_action_status_date( $status, 'oldest' ); $oldest_and_newest[ $status ]['newest'] = $this->get_action_status_date( $status, 'newest' ); } return $oldest_and_newest; } /** * Get oldest or newest scheduled date for a given status. * * @param string $status Action status label/name string. * @param string $date_type Oldest or Newest. * @return DateTime */ protected function get_action_status_date( $status, $date_type = 'oldest' ) { $order = 'oldest' === $date_type ? 'ASC' : 'DESC'; $action = $this->store->query_actions( array( 'claimed' => false, 'status' => $status, 'per_page' => 1, 'order' => $order, ) ); if ( ! empty( $action ) ) { $date_object = $this->store->get_date( $action[0] ); $action_date = $date_object->format( 'Y-m-d H:i:s O' ); } else { $action_date = '–'; } return $action_date; } /** * Get oldest or newest scheduled date for a given status. * * @param array $status_labels Set of statuses to find oldest & newest action for. * @param array $action_counts Number of actions grouped by status. * @param array $oldest_and_newest Date of the oldest and newest action with each status. */ protected function get_template( $status_labels, $action_counts, $oldest_and_newest ) { $as_version = ActionScheduler_Versions::instance()->latest_version(); $as_datastore = get_class( ActionScheduler_Store::instance() ); ?> <table class="wc_status_table widefat" cellspacing="0"> <thead> <tr> <th colspan="5" data-export-label="Action Scheduler"><h2><?php esc_html_e( 'Action Scheduler', 'action-scheduler' ); ?><?php echo wc_help_tip( esc_html__( 'This section shows details of Action Scheduler.', 'action-scheduler' ) ); ?></h2></th> </tr> <tr> <td colspan="2" data-export-label="Version"><?php esc_html_e( 'Version:', 'action-scheduler' ); ?></td> <td colspan="3"><?php echo esc_html( $as_version ); ?></td> </tr> <tr> <td colspan="2" data-export-label="Data store"><?php esc_html_e( 'Data store:', 'action-scheduler' ); ?></td> <td colspan="3"><?php echo esc_html( $as_datastore ); ?></td> </tr> <tr> <td><strong><?php esc_html_e( 'Action Status', 'action-scheduler' ); ?></strong></td> <td class="help"> </td> <td><strong><?php esc_html_e( 'Count', 'action-scheduler' ); ?></strong></td> <td><strong><?php esc_html_e( 'Oldest Scheduled Date', 'action-scheduler' ); ?></strong></td> <td><strong><?php esc_html_e( 'Newest Scheduled Date', 'action-scheduler' ); ?></strong></td> </tr> </thead> <tbody> <?php foreach ( $action_counts as $status => $count ) { // WC uses the 3rd column for export, so we need to display more data in that (hidden when viewed as part of the table) and add an empty 2nd column. printf( '<tr><td>%1$s</td><td> </td><td>%2$s<span style="display: none;">, Oldest: %3$s, Newest: %4$s</span></td><td>%3$s</td><td>%4$s</td></tr>', esc_html( $status_labels[ $status ] ), esc_html( number_format_i18n( $count ) ), esc_html( $oldest_and_newest[ $status ]['oldest'] ), esc_html( $oldest_and_newest[ $status ]['newest'] ) ); } ?> </tbody> </table> <?php } /** * Is triggered when invoking inaccessible methods in an object context. * * @param string $name Name of method called. * @param array $arguments Parameters to invoke the method with. * * @return mixed * @link https://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods */ public function __call( $name, $arguments ) { switch ( $name ) { case 'print': _deprecated_function( __CLASS__ . '::print()', '2.2.4', __CLASS__ . '::render()' ); return call_user_func_array( array( $this, 'render' ), $arguments ); } return null; } } vendor/woocommerce/action-scheduler/classes/schema/ActionScheduler_LoggerSchema.php 0000644 00000005630 14720461212 0024716 0 ustar 00 <?php /** * Class ActionScheduler_LoggerSchema * * @codeCoverageIgnore * * Creates a custom table for storing action logs */ class ActionScheduler_LoggerSchema extends ActionScheduler_Abstract_Schema { const LOG_TABLE = 'actionscheduler_logs'; /** * @var int Increment this value to trigger a schema update. */ protected $schema_version = 3; /** * Construct. */ public function __construct() { $this->tables = [ self::LOG_TABLE, ]; } /** * Performs additional setup work required to support this schema. */ public function init() { add_action( 'action_scheduler_before_schema_update', array( $this, 'update_schema_3_0' ), 10, 2 ); } /** * Get table definition. * * @param string $table Table name. */ protected function get_table_definition( $table ) { global $wpdb; $table_name = $wpdb->$table; $charset_collate = $wpdb->get_charset_collate(); switch ( $table ) { case self::LOG_TABLE: $default_date = ActionScheduler_StoreSchema::DEFAULT_DATE; return "CREATE TABLE $table_name ( log_id bigint(20) unsigned NOT NULL auto_increment, action_id bigint(20) unsigned NOT NULL, message text NOT NULL, log_date_gmt datetime NULL default '{$default_date}', log_date_local datetime NULL default '{$default_date}', PRIMARY KEY (log_id), KEY action_id (action_id), KEY log_date_gmt (log_date_gmt) ) $charset_collate"; default: return ''; } } /** * Update the logs table schema, allowing datetime fields to be NULL. * * This is needed because the NOT NULL constraint causes a conflict with some versions of MySQL * configured with sql_mode=NO_ZERO_DATE, which can for instance lead to tables not being created. * * Most other schema updates happen via ActionScheduler_Abstract_Schema::update_table(), however * that method relies on dbDelta() and this change is not possible when using that function. * * @param string $table Name of table being updated. * @param string $db_version The existing schema version of the table. */ public function update_schema_3_0( $table, $db_version ) { global $wpdb; if ( 'actionscheduler_logs' !== $table || version_compare( $db_version, '3', '>=' ) ) { return; } // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared $table_name = $wpdb->prefix . 'actionscheduler_logs'; $table_list = $wpdb->get_col( "SHOW TABLES LIKE '{$table_name}'" ); $default_date = ActionScheduler_StoreSchema::DEFAULT_DATE; if ( ! empty( $table_list ) ) { $query = " ALTER TABLE {$table_name} MODIFY COLUMN log_date_gmt datetime NULL default '{$default_date}', MODIFY COLUMN log_date_local datetime NULL default '{$default_date}' "; $wpdb->query( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared } } vendor/woocommerce/action-scheduler/classes/schema/ActionScheduler_StoreSchema.php 0000644 00000011732 14720461212 0024573 0 ustar 00 <?php /** * Class ActionScheduler_StoreSchema * * @codeCoverageIgnore * * Creates custom tables for storing scheduled actions */ class ActionScheduler_StoreSchema extends ActionScheduler_Abstract_Schema { const ACTIONS_TABLE = 'actionscheduler_actions'; const CLAIMS_TABLE = 'actionscheduler_claims'; const GROUPS_TABLE = 'actionscheduler_groups'; const DEFAULT_DATE = '0000-00-00 00:00:00'; /** * @var int Increment this value to trigger a schema update. */ protected $schema_version = 7; /** * Construct. */ public function __construct() { $this->tables = [ self::ACTIONS_TABLE, self::CLAIMS_TABLE, self::GROUPS_TABLE, ]; } /** * Performs additional setup work required to support this schema. */ public function init() { add_action( 'action_scheduler_before_schema_update', array( $this, 'update_schema_5_0' ), 10, 2 ); } /** * Get table definition. * * @param string $table Table name. */ protected function get_table_definition( $table ) { global $wpdb; $table_name = $wpdb->$table; $charset_collate = $wpdb->get_charset_collate(); // phpcs:ignore Squiz.PHP.CommentedOutCode $max_index_length = 191; // @see wp_get_db_schema() $hook_status_scheduled_date_gmt_max_index_length = $max_index_length - 20 - 8; // - status, - scheduled_date_gmt $default_date = self::DEFAULT_DATE; switch ( $table ) { case self::ACTIONS_TABLE: return "CREATE TABLE {$table_name} ( action_id bigint(20) unsigned NOT NULL auto_increment, hook varchar(191) NOT NULL, status varchar(20) NOT NULL, scheduled_date_gmt datetime NULL default '{$default_date}', scheduled_date_local datetime NULL default '{$default_date}', priority tinyint unsigned NOT NULL default '10', args varchar($max_index_length), schedule longtext, group_id bigint(20) unsigned NOT NULL default '0', attempts int(11) NOT NULL default '0', last_attempt_gmt datetime NULL default '{$default_date}', last_attempt_local datetime NULL default '{$default_date}', claim_id bigint(20) unsigned NOT NULL default '0', extended_args varchar(8000) DEFAULT NULL, PRIMARY KEY (action_id), KEY hook_status_scheduled_date_gmt (hook($hook_status_scheduled_date_gmt_max_index_length), status, scheduled_date_gmt), KEY status_scheduled_date_gmt (status, scheduled_date_gmt), KEY scheduled_date_gmt (scheduled_date_gmt), KEY args (args($max_index_length)), KEY group_id (group_id), KEY last_attempt_gmt (last_attempt_gmt), KEY `claim_id_status_scheduled_date_gmt` (`claim_id`, `status`, `scheduled_date_gmt`) ) $charset_collate"; case self::CLAIMS_TABLE: return "CREATE TABLE {$table_name} ( claim_id bigint(20) unsigned NOT NULL auto_increment, date_created_gmt datetime NULL default '{$default_date}', PRIMARY KEY (claim_id), KEY date_created_gmt (date_created_gmt) ) $charset_collate"; case self::GROUPS_TABLE: return "CREATE TABLE {$table_name} ( group_id bigint(20) unsigned NOT NULL auto_increment, slug varchar(255) NOT NULL, PRIMARY KEY (group_id), KEY slug (slug($max_index_length)) ) $charset_collate"; default: return ''; } } /** * Update the actions table schema, allowing datetime fields to be NULL. * * This is needed because the NOT NULL constraint causes a conflict with some versions of MySQL * configured with sql_mode=NO_ZERO_DATE, which can for instance lead to tables not being created. * * Most other schema updates happen via ActionScheduler_Abstract_Schema::update_table(), however * that method relies on dbDelta() and this change is not possible when using that function. * * @param string $table Name of table being updated. * @param string $db_version The existing schema version of the table. */ public function update_schema_5_0( $table, $db_version ) { global $wpdb; if ( 'actionscheduler_actions' !== $table || version_compare( $db_version, '5', '>=' ) ) { return; } // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared $table_name = $wpdb->prefix . 'actionscheduler_actions'; $table_list = $wpdb->get_col( "SHOW TABLES LIKE '{$table_name}'" ); $default_date = self::DEFAULT_DATE; if ( ! empty( $table_list ) ) { $query = " ALTER TABLE {$table_name} MODIFY COLUMN scheduled_date_gmt datetime NULL default '{$default_date}', MODIFY COLUMN scheduled_date_local datetime NULL default '{$default_date}', MODIFY COLUMN last_attempt_gmt datetime NULL default '{$default_date}', MODIFY COLUMN last_attempt_local datetime NULL default '{$default_date}' "; $wpdb->query( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared } } vendor/woocommerce/action-scheduler/classes/migration/LogMigrator.php 0000644 00000002272 14720461212 0022200 0 ustar 00 <?php namespace Action_Scheduler\Migration; use ActionScheduler_Logger; /** * Class LogMigrator * * @package Action_Scheduler\Migration * * @since 3.0.0 * * @codeCoverageIgnore */ class LogMigrator { /** @var ActionScheduler_Logger */ private $source; /** @var ActionScheduler_Logger */ private $destination; /** * ActionMigrator constructor. * * @param ActionScheduler_Logger $source_logger Source logger object. * @param ActionScheduler_Logger $destination_Logger Destination logger object. */ public function __construct( ActionScheduler_Logger $source_logger, ActionScheduler_Logger $destination_Logger ) { $this->source = $source_logger; $this->destination = $destination_Logger; } /** * Migrate an action log. * * @param int $source_action_id Source logger object. * @param int $destination_action_id Destination logger object. */ public function migrate( $source_action_id, $destination_action_id ) { $logs = $this->source->get_logs( $source_action_id ); foreach ( $logs as $log ) { if ( $log->get_action_id() == $source_action_id ) { $this->destination->log( $destination_action_id, $log->get_message(), $log->get_date() ); } } } } vendor/woocommerce/action-scheduler/classes/migration/Controller.php 0000644 00000014200 14720461212 0022067 0 ustar 00 <?php namespace Action_Scheduler\Migration; use ActionScheduler_DataController; use ActionScheduler_LoggerSchema; use ActionScheduler_StoreSchema; use Action_Scheduler\WP_CLI\ProgressBar; /** * Class Controller * * The main plugin/initialization class for migration to custom tables. * * @package Action_Scheduler\Migration * * @since 3.0.0 * * @codeCoverageIgnore */ class Controller { /** @var self */ private static $instance; /** @var Action_Scheduler\Migration\Scheduler */ private $migration_scheduler; /** @var string */ private $store_classname; /** @var string */ private $logger_classname; /** @var bool */ private $migrate_custom_store; /** * Controller constructor. * * @param Scheduler $migration_scheduler Migration scheduler object. */ protected function __construct( Scheduler $migration_scheduler ) { $this->migration_scheduler = $migration_scheduler; $this->store_classname = ''; } /** * Set the action store class name. * * @param string $class Classname of the store class. * * @return string */ public function get_store_class( $class ) { if ( \ActionScheduler_DataController::is_migration_complete() ) { return \ActionScheduler_DataController::DATASTORE_CLASS; } elseif ( \ActionScheduler_Store::DEFAULT_CLASS !== $class ) { $this->store_classname = $class; return $class; } else { return 'ActionScheduler_HybridStore'; } } /** * Set the action logger class name. * * @param string $class Classname of the logger class. * * @return string */ public function get_logger_class( $class ) { \ActionScheduler_Store::instance(); if ( $this->has_custom_datastore() ) { $this->logger_classname = $class; return $class; } else { return \ActionScheduler_DataController::LOGGER_CLASS; } } /** * Get flag indicating whether a custom datastore is in use. * * @return bool */ public function has_custom_datastore() { return (bool) $this->store_classname; } /** * Set up the background migration process. * * @return void */ public function schedule_migration() { $logging_tables = new ActionScheduler_LoggerSchema(); $store_tables = new ActionScheduler_StoreSchema(); /* * In some unusual cases, the expected tables may not have been created. In such cases * we do not schedule a migration as doing so will lead to fatal error conditions. * * In such cases the user will likely visit the Tools > Scheduled Actions screen to * investigate, and will see appropriate messaging (this step also triggers an attempt * to rebuild any missing tables). * * @see https://github.com/woocommerce/action-scheduler/issues/653 */ if ( ActionScheduler_DataController::is_migration_complete() || $this->migration_scheduler->is_migration_scheduled() || ! $store_tables->tables_exist() || ! $logging_tables->tables_exist() ) { return; } $this->migration_scheduler->schedule_migration(); } /** * Get the default migration config object * * @return ActionScheduler\Migration\Config */ public function get_migration_config_object() { static $config = null; if ( ! $config ) { $source_store = $this->store_classname ? new $this->store_classname() : new \ActionScheduler_wpPostStore(); $source_logger = $this->logger_classname ? new $this->logger_classname() : new \ActionScheduler_wpCommentLogger(); $config = new Config(); $config->set_source_store( $source_store ); $config->set_source_logger( $source_logger ); $config->set_destination_store( new \ActionScheduler_DBStoreMigrator() ); $config->set_destination_logger( new \ActionScheduler_DBLogger() ); if ( defined( 'WP_CLI' ) && WP_CLI ) { $config->set_progress_bar( new ProgressBar( '', 0 ) ); } } return apply_filters( 'action_scheduler/migration_config', $config ); } /** * Hook dashboard migration notice. */ public function hook_admin_notices() { if ( ! $this->allow_migration() || \ActionScheduler_DataController::is_migration_complete() ) { return; } add_action( 'admin_notices', array( $this, 'display_migration_notice' ), 10, 0 ); } /** * Show a dashboard notice that migration is in progress. */ public function display_migration_notice() { printf( '<div class="notice notice-warning"><p>%s</p></div>', esc_html__( 'Action Scheduler migration in progress. The list of scheduled actions may be incomplete.', 'action-scheduler' ) ); } /** * Add store classes. Hook migration. */ private function hook() { add_filter( 'action_scheduler_store_class', array( $this, 'get_store_class' ), 100, 1 ); add_filter( 'action_scheduler_logger_class', array( $this, 'get_logger_class' ), 100, 1 ); add_action( 'init', array( $this, 'maybe_hook_migration' ) ); add_action( 'wp_loaded', array( $this, 'schedule_migration' ) ); // Action Scheduler may be displayed as a Tools screen or WooCommerce > Status administration screen. add_action( 'load-tools_page_action-scheduler', array( $this, 'hook_admin_notices' ), 10, 0 ); add_action( 'load-woocommerce_page_wc-status', array( $this, 'hook_admin_notices' ), 10, 0 ); } /** * Possibly hook the migration scheduler action. * * @author Jeremy Pry */ public function maybe_hook_migration() { if ( ! $this->allow_migration() || \ActionScheduler_DataController::is_migration_complete() ) { return; } $this->migration_scheduler->hook(); } /** * Allow datastores to enable migration to AS tables. */ public function allow_migration() { if ( ! \ActionScheduler_DataController::dependencies_met() ) { return false; } if ( null === $this->migrate_custom_store ) { $this->migrate_custom_store = apply_filters( 'action_scheduler_migrate_data_store', false ); } return ( ! $this->has_custom_datastore() ) || $this->migrate_custom_store; } /** * Proceed with the migration if the dependencies have been met. */ public static function init() { if ( \ActionScheduler_DataController::dependencies_met() ) { self::instance()->hook(); } } /** * Singleton factory. */ public static function instance() { if ( ! isset( self::$instance ) ) { self::$instance = new static( new Scheduler() ); } return self::$instance; } } vendor/woocommerce/action-scheduler/classes/migration/Runner.php 0000644 00000007230 14720461212 0021222 0 ustar 00 <?php namespace Action_Scheduler\Migration; /** * Class Runner * * @package Action_Scheduler\Migration * * @since 3.0.0 * * @codeCoverageIgnore */ class Runner { /** @var ActionScheduler_Store */ private $source_store; /** @var ActionScheduler_Store */ private $destination_store; /** @var ActionScheduler_Logger */ private $source_logger; /** @var ActionScheduler_Logger */ private $destination_logger; /** @var BatchFetcher */ private $batch_fetcher; /** @var ActionMigrator */ private $action_migrator; /** @var LogMigrator */ private $log_migrator; /** @var ProgressBar */ private $progress_bar; /** * Runner constructor. * * @param Config $config Migration configuration object. */ public function __construct( Config $config ) { $this->source_store = $config->get_source_store(); $this->destination_store = $config->get_destination_store(); $this->source_logger = $config->get_source_logger(); $this->destination_logger = $config->get_destination_logger(); $this->batch_fetcher = new BatchFetcher( $this->source_store ); if ( $config->get_dry_run() ) { $this->log_migrator = new DryRun_LogMigrator( $this->source_logger, $this->destination_logger ); $this->action_migrator = new DryRun_ActionMigrator( $this->source_store, $this->destination_store, $this->log_migrator ); } else { $this->log_migrator = new LogMigrator( $this->source_logger, $this->destination_logger ); $this->action_migrator = new ActionMigrator( $this->source_store, $this->destination_store, $this->log_migrator ); } if ( defined( 'WP_CLI' ) && WP_CLI ) { $this->progress_bar = $config->get_progress_bar(); } } /** * Run migration batch. * * @param int $batch_size Optional batch size. Default 10. * * @return int Size of batch processed. */ public function run( $batch_size = 10 ) { $batch = $this->batch_fetcher->fetch( $batch_size ); $batch_size = count( $batch ); if ( ! $batch_size ) { return 0; } if ( $this->progress_bar ) { /* translators: %d: amount of actions */ $this->progress_bar->set_message( sprintf( _n( 'Migrating %d action', 'Migrating %d actions', $batch_size, 'action-scheduler' ), $batch_size ) ); $this->progress_bar->set_count( $batch_size ); } $this->migrate_actions( $batch ); return $batch_size; } /** * Migration a batch of actions. * * @param array $action_ids List of action IDs to migrate. */ public function migrate_actions( array $action_ids ) { do_action( 'action_scheduler/migration_batch_starting', $action_ids ); \ActionScheduler::logger()->unhook_stored_action(); $this->destination_logger->unhook_stored_action(); foreach ( $action_ids as $source_action_id ) { $destination_action_id = $this->action_migrator->migrate( $source_action_id ); if ( $destination_action_id ) { $this->destination_logger->log( $destination_action_id, sprintf( /* translators: 1: source action ID 2: source store class 3: destination action ID 4: destination store class */ __( 'Migrated action with ID %1$d in %2$s to ID %3$d in %4$s', 'action-scheduler' ), $source_action_id, get_class( $this->source_store ), $destination_action_id, get_class( $this->destination_store ) ) ); } if ( $this->progress_bar ) { $this->progress_bar->tick(); } } if ( $this->progress_bar ) { $this->progress_bar->finish(); } \ActionScheduler::logger()->hook_stored_action(); do_action( 'action_scheduler/migration_batch_complete', $action_ids ); } /** * Initialize destination store and logger. */ public function init_destination() { $this->destination_store->init(); $this->destination_logger->init(); } } vendor/woocommerce/action-scheduler/classes/migration/BatchFetcher.php 0000644 00000003226 14720461212 0022274 0 ustar 00 <?php namespace Action_Scheduler\Migration; use ActionScheduler_Store as Store; /** * Class BatchFetcher * * @package Action_Scheduler\Migration * * @since 3.0.0 * * @codeCoverageIgnore */ class BatchFetcher { /** @var ActionScheduler_Store */ private $store; /** * BatchFetcher constructor. * * @param ActionScheduler_Store $source_store Source store object. */ public function __construct( Store $source_store ) { $this->store = $source_store; } /** * Retrieve a list of actions. * * @param int $count The number of actions to retrieve. * * @return int[] A list of action IDs */ public function fetch( $count = 10 ) { foreach ( $this->get_query_strategies( $count ) as $query ) { $action_ids = $this->store->query_actions( $query ); if ( ! empty( $action_ids ) ) { return $action_ids; } } return []; } /** * Generate a list of prioritized of action search parameters. * * @param int $count Number of actions to find. * * @return array */ private function get_query_strategies( $count ) { $now = as_get_datetime_object(); $args = [ 'date' => $now, 'per_page' => $count, 'offset' => 0, 'orderby' => 'date', 'order' => 'ASC', ]; $priorities = [ Store::STATUS_PENDING, Store::STATUS_FAILED, Store::STATUS_CANCELED, Store::STATUS_COMPLETE, Store::STATUS_RUNNING, '', // any other unanticipated status. ]; foreach ( $priorities as $status ) { yield wp_parse_args( [ 'status' => $status, 'date_compare' => '<=', ], $args ); yield wp_parse_args( [ 'status' => $status, 'date_compare' => '>=', ], $args ); } } } vendor/woocommerce/action-scheduler/classes/migration/DryRun_LogMigrator.php 0000644 00000000713 14720461212 0023501 0 ustar 00 <?php namespace Action_Scheduler\Migration; /** * Class DryRun_LogMigrator * * @package Action_Scheduler\Migration * * @codeCoverageIgnore */ class DryRun_LogMigrator extends LogMigrator { /** * Simulate migrating an action log. * * @param int $source_action_id Source logger object. * @param int $destination_action_id Destination logger object. */ public function migrate( $source_action_id, $destination_action_id ) { // no-op. } } vendor/woocommerce/action-scheduler/classes/migration/Config.php 0000644 00000007554 14720461212 0021167 0 ustar 00 <?php namespace Action_Scheduler\Migration; use Action_Scheduler\WP_CLI\ProgressBar; use ActionScheduler_Logger as Logger; use ActionScheduler_Store as Store; /** * Class Config * * @package Action_Scheduler\Migration * * @since 3.0.0 * * A config builder for the ActionScheduler\Migration\Runner class */ class Config { /** @var ActionScheduler_Store */ private $source_store; /** @var ActionScheduler_Logger */ private $source_logger; /** @var ActionScheduler_Store */ private $destination_store; /** @var ActionScheduler_Logger */ private $destination_logger; /** @var Progress bar */ private $progress_bar; /** @var bool */ private $dry_run = false; /** * Config constructor. */ public function __construct() { } /** * Get the configured source store. * * @return ActionScheduler_Store * @throws \RuntimeException When source store is not configured. */ public function get_source_store() { if ( empty( $this->source_store ) ) { throw new \RuntimeException( __( 'Source store must be configured before running a migration', 'action-scheduler' ) ); } return $this->source_store; } /** * Set the configured source store. * * @param ActionScheduler_Store $store Source store object. */ public function set_source_store( Store $store ) { $this->source_store = $store; } /** * Get the configured source logger. * * @return ActionScheduler_Logger * @throws \RuntimeException When source logger is not configured. */ public function get_source_logger() { if ( empty( $this->source_logger ) ) { throw new \RuntimeException( __( 'Source logger must be configured before running a migration', 'action-scheduler' ) ); } return $this->source_logger; } /** * Set the configured source logger. * * @param ActionScheduler_Logger $logger Logger object. */ public function set_source_logger( Logger $logger ) { $this->source_logger = $logger; } /** * Get the configured destination store. * * @return ActionScheduler_Store * @throws \RuntimeException When destination store is not configured. */ public function get_destination_store() { if ( empty( $this->destination_store ) ) { throw new \RuntimeException( __( 'Destination store must be configured before running a migration', 'action-scheduler' ) ); } return $this->destination_store; } /** * Set the configured destination store. * * @param ActionScheduler_Store $store Action store object. */ public function set_destination_store( Store $store ) { $this->destination_store = $store; } /** * Get the configured destination logger. * * @return ActionScheduler_Logger * @throws \RuntimeException When destination logger is not configured. */ public function get_destination_logger() { if ( empty( $this->destination_logger ) ) { throw new \RuntimeException( __( 'Destination logger must be configured before running a migration', 'action-scheduler' ) ); } return $this->destination_logger; } /** * Set the configured destination logger. * * @param ActionScheduler_Logger $logger Logger object. */ public function set_destination_logger( Logger $logger ) { $this->destination_logger = $logger; } /** * Get flag indicating whether it's a dry run. * * @return bool */ public function get_dry_run() { return $this->dry_run; } /** * Set flag indicating whether it's a dry run. * * @param bool $dry_run Dry run toggle. */ public function set_dry_run( $dry_run ) { $this->dry_run = (bool) $dry_run; } /** * Get progress bar object. * * @return ActionScheduler\WPCLI\ProgressBar */ public function get_progress_bar() { return $this->progress_bar; } /** * Set progress bar object. * * @param ActionScheduler\WPCLI\ProgressBar $progress_bar Progress bar object. */ public function set_progress_bar( ProgressBar $progress_bar ) { $this->progress_bar = $progress_bar; } } vendor/woocommerce/action-scheduler/classes/migration/ActionMigrator.php 0000644 00000007274 14720461212 0022703 0 ustar 00 <?php namespace Action_Scheduler\Migration; /** * Class ActionMigrator * * @package Action_Scheduler\Migration * * @since 3.0.0 * * @codeCoverageIgnore */ class ActionMigrator { /** @var ActionScheduler_Store */ private $source; /** @var ActionScheduler_Store */ private $destination; /** @var LogMigrator */ private $log_migrator; /** * ActionMigrator constructor. * * @param \ActionScheduler_Store $source_store Source store object. * @param \ActionScheduler_Store $destination_store Destination store object. * @param LogMigrator $log_migrator Log migrator object. */ public function __construct( \ActionScheduler_Store $source_store, \ActionScheduler_Store $destination_store, LogMigrator $log_migrator ) { $this->source = $source_store; $this->destination = $destination_store; $this->log_migrator = $log_migrator; } /** * Migrate an action. * * @param int $source_action_id Action ID. * * @return int 0|new action ID * @throws \RuntimeException When unable to delete action from the source store. */ public function migrate( $source_action_id ) { try { $action = $this->source->fetch_action( $source_action_id ); $status = $this->source->get_status( $source_action_id ); } catch ( \Exception $e ) { $action = null; $status = ''; } if ( is_null( $action ) || empty( $status ) || ! $action->get_schedule()->get_date() ) { // null action or empty status means the fetch operation failed or the action didn't exist. // null schedule means it's missing vital data. // delete it and move on. try { $this->source->delete_action( $source_action_id ); } catch ( \Exception $e ) { // nothing to do, it didn't exist in the first place. } do_action( 'action_scheduler/no_action_to_migrate', $source_action_id, $this->source, $this->destination ); return 0; } try { // Make sure the last attempt date is set correctly for completed and failed actions. $last_attempt_date = ( $status !== \ActionScheduler_Store::STATUS_PENDING ) ? $this->source->get_date( $source_action_id ) : null; $destination_action_id = $this->destination->save_action( $action, null, $last_attempt_date ); } catch ( \Exception $e ) { do_action( 'action_scheduler/migrate_action_failed', $source_action_id, $this->source, $this->destination ); return 0; // could not save the action in the new store. } try { switch ( $status ) { case \ActionScheduler_Store::STATUS_FAILED : $this->destination->mark_failure( $destination_action_id ); break; case \ActionScheduler_Store::STATUS_CANCELED : $this->destination->cancel_action( $destination_action_id ); break; } $this->log_migrator->migrate( $source_action_id, $destination_action_id ); $this->source->delete_action( $source_action_id ); $test_action = $this->source->fetch_action( $source_action_id ); if ( ! is_a( $test_action, 'ActionScheduler_NullAction' ) ) { // translators: %s is an action ID. throw new \RuntimeException( sprintf( __( 'Unable to remove source migrated action %s', 'action-scheduler' ), $source_action_id ) ); } do_action( 'action_scheduler/migrated_action', $source_action_id, $destination_action_id, $this->source, $this->destination ); return $destination_action_id; } catch ( \Exception $e ) { // could not delete from the old store. $this->source->mark_migrated( $source_action_id ); do_action( 'action_scheduler/migrate_action_incomplete', $source_action_id, $destination_action_id, $this->source, $this->destination ); do_action( 'action_scheduler/migrated_action', $source_action_id, $destination_action_id, $this->source, $this->destination ); return $destination_action_id; } } } vendor/woocommerce/action-scheduler/classes/migration/DryRun_ActionMigrator.php 0000644 00000000741 14720461212 0024176 0 ustar 00 <?php namespace Action_Scheduler\Migration; /** * Class DryRun_ActionMigrator * * @package Action_Scheduler\Migration * * @since 3.0.0 * * @codeCoverageIgnore */ class DryRun_ActionMigrator extends ActionMigrator { /** * Simulate migrating an action. * * @param int $source_action_id Action ID. * * @return int */ public function migrate( $source_action_id ) { do_action( 'action_scheduler/migrate_action_dry_run', $source_action_id ); return 0; } } vendor/woocommerce/action-scheduler/classes/migration/ActionScheduler_DBStoreMigrator.php 0000644 00000003410 14720461212 0026110 0 ustar 00 <?php /** * Class ActionScheduler_DBStoreMigrator * * A class for direct saving of actions to the table data store during migration. * * @since 3.0.0 */ class ActionScheduler_DBStoreMigrator extends ActionScheduler_DBStore { /** * Save an action with optional last attempt date. * * Normally, saving an action sets its attempted date to 0000-00-00 00:00:00 because when an action is first saved, * it can't have been attempted yet, but migrated completed actions will have an attempted date, so we need to save * that when first saving the action. * * @param ActionScheduler_Action $action Action to migrate. * @param null|\DateTime $scheduled_date Optional date of the first instance to store. * @param null|\DateTime $last_attempt_date Optional date the action was last attempted. * * @return string The action ID * @throws \RuntimeException When the action is not saved. */ public function save_action( ActionScheduler_Action $action, \DateTime $scheduled_date = null, \DateTime $last_attempt_date = null ){ try { /** @var \wpdb $wpdb */ global $wpdb; $action_id = parent::save_action( $action, $scheduled_date ); if ( null !== $last_attempt_date ) { $data = [ 'last_attempt_gmt' => $this->get_scheduled_date_string( $action, $last_attempt_date ), 'last_attempt_local' => $this->get_scheduled_date_string_local( $action, $last_attempt_date ), ]; $wpdb->update( $wpdb->actionscheduler_actions, $data, array( 'action_id' => $action_id ), array( '%s', '%s' ), array( '%d' ) ); } return $action_id; } catch ( \Exception $e ) { // translators: %s is an error message. throw new \RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 ); } } } vendor/woocommerce/action-scheduler/classes/migration/Scheduler.php 0000644 00000005542 14720461212 0021673 0 ustar 00 <?php namespace Action_Scheduler\Migration; /** * Class Scheduler * * @package Action_Scheduler\WP_CLI * * @since 3.0.0 * * @codeCoverageIgnore */ class Scheduler { /** Migration action hook. */ const HOOK = 'action_scheduler/migration_hook'; /** Migration action group. */ const GROUP = 'action-scheduler-migration'; /** * Set up the callback for the scheduled job. */ public function hook() { add_action( self::HOOK, array( $this, 'run_migration' ), 10, 0 ); } /** * Remove the callback for the scheduled job. */ public function unhook() { remove_action( self::HOOK, array( $this, 'run_migration' ), 10 ); } /** * The migration callback. */ public function run_migration() { $migration_runner = $this->get_migration_runner(); $count = $migration_runner->run( $this->get_batch_size() ); if ( $count === 0 ) { $this->mark_complete(); } else { $this->schedule_migration( time() + $this->get_schedule_interval() ); } } /** * Mark the migration complete. */ public function mark_complete() { $this->unschedule_migration(); \ActionScheduler_DataController::mark_migration_complete(); do_action( 'action_scheduler/migration_complete' ); } /** * Get a flag indicating whether the migration is scheduled. * * @return bool Whether there is a pending action in the store to handle the migration */ public function is_migration_scheduled() { $next = as_next_scheduled_action( self::HOOK ); return ! empty( $next ); } /** * Schedule the migration. * * @param int $when Optional timestamp to run the next migration batch. Defaults to now. * * @return string The action ID */ public function schedule_migration( $when = 0 ) { $next = as_next_scheduled_action( self::HOOK ); if ( ! empty( $next ) ) { return $next; } if ( empty( $when ) ) { $when = time() + MINUTE_IN_SECONDS; } return as_schedule_single_action( $when, self::HOOK, array(), self::GROUP ); } /** * Remove the scheduled migration action. */ public function unschedule_migration() { as_unschedule_action( self::HOOK, null, self::GROUP ); } /** * Get migration batch schedule interval. * * @return int Seconds between migration runs. Defaults to 0 seconds to allow chaining migration via Async Runners. */ private function get_schedule_interval() { return (int) apply_filters( 'action_scheduler/migration_interval', 0 ); } /** * Get migration batch size. * * @return int Number of actions to migrate in each batch. Defaults to 250. */ private function get_batch_size() { return (int) apply_filters( 'action_scheduler/migration_batch_size', 250 ); } /** * Get migration runner object. * * @return Runner */ private function get_migration_runner() { $config = Controller::instance()->get_migration_config_object(); return new Runner( $config ); } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_AsyncRequest_QueueRunner.php 0000644 00000004265 14720461212 0026105 0 ustar 00 <?php defined( 'ABSPATH' ) || exit; /** * ActionScheduler_AsyncRequest_QueueRunner class. */ class ActionScheduler_AsyncRequest_QueueRunner extends WP_Async_Request { /** * Data store for querying actions * * @var ActionScheduler_Store * @access protected */ protected $store; /** * Prefix for ajax hooks * * @var string * @access protected */ protected $prefix = 'as'; /** * Action for ajax hooks * * @var string * @access protected */ protected $action = 'async_request_queue_runner'; /** * Initiate new async request. * * @param ActionScheduler_Store $store Store object. */ public function __construct( ActionScheduler_Store $store ) { parent::__construct(); $this->store = $store; } /** * Handle async requests * * Run a queue, and maybe dispatch another async request to run another queue * if there are still pending actions after completing a queue in this request. */ protected function handle() { do_action( 'action_scheduler_run_queue', 'Async Request' ); // run a queue in the same way as WP Cron, but declare the Async Request context. $sleep_seconds = $this->get_sleep_seconds(); if ( $sleep_seconds ) { sleep( $sleep_seconds ); } $this->maybe_dispatch(); } /** * If the async request runner is needed and allowed to run, dispatch a request. */ public function maybe_dispatch() { if ( ! $this->allow() ) { return; } $this->dispatch(); ActionScheduler_QueueRunner::instance()->unhook_dispatch_async_request(); } /** * Only allow async requests when needed. * * Also allow 3rd party code to disable running actions via async requests. */ protected function allow() { if ( ! has_action( 'action_scheduler_run_queue' ) || ActionScheduler::runner()->has_maximum_concurrent_batches() || ! $this->store->has_pending_actions_due() ) { $allow = false; } else { $allow = true; } return apply_filters( 'action_scheduler_allow_async_request_runner', $allow ); } /** * Chaining async requests can crash MySQL. A brief sleep call in PHP prevents that. */ protected function get_sleep_seconds() { return apply_filters( 'action_scheduler_async_request_sleep_seconds', 5, $this ); } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_QueueRunner.php 0000644 00000022274 14720461212 0023377 0 ustar 00 <?php /** * Class ActionScheduler_QueueRunner */ class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner { const WP_CRON_HOOK = 'action_scheduler_run_queue'; const WP_CRON_SCHEDULE = 'every_minute'; /** @var ActionScheduler_AsyncRequest_QueueRunner */ protected $async_request; /** @var ActionScheduler_QueueRunner */ private static $runner = null; /** @var int */ private $processed_actions_count = 0; /** * @return ActionScheduler_QueueRunner * @codeCoverageIgnore */ public static function instance() { if ( empty(self::$runner) ) { $class = apply_filters('action_scheduler_queue_runner_class', 'ActionScheduler_QueueRunner'); self::$runner = new $class(); } return self::$runner; } /** * ActionScheduler_QueueRunner constructor. * * @param ActionScheduler_Store $store Store object. * @param ActionScheduler_FatalErrorMonitor $monitor Monitor object. * @param ActionScheduler_QueueCleaner $cleaner Cleaner object. * @param ActionScheduler_AsyncRequest_QueueRunner $async_request Async request runner object. */ public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null, ActionScheduler_AsyncRequest_QueueRunner $async_request = null ) { parent::__construct( $store, $monitor, $cleaner ); if ( is_null( $async_request ) ) { $async_request = new ActionScheduler_AsyncRequest_QueueRunner( $this->store ); } $this->async_request = $async_request; } /** * @codeCoverageIgnore */ public function init() { add_filter( 'cron_schedules', array( self::instance(), 'add_wp_cron_schedule' ) ); // Check for and remove any WP Cron hook scheduled by Action Scheduler < 3.0.0, which didn't include the $context param. $next_timestamp = wp_next_scheduled( self::WP_CRON_HOOK ); if ( $next_timestamp ) { wp_unschedule_event( $next_timestamp, self::WP_CRON_HOOK ); } $cron_context = array( 'WP Cron' ); if ( ! wp_next_scheduled( self::WP_CRON_HOOK, $cron_context ) ) { $schedule = apply_filters( 'action_scheduler_run_schedule', self::WP_CRON_SCHEDULE ); wp_schedule_event( time(), $schedule, self::WP_CRON_HOOK, $cron_context ); } add_action( self::WP_CRON_HOOK, array( self::instance(), 'run' ) ); $this->hook_dispatch_async_request(); } /** * Hook check for dispatching an async request. */ public function hook_dispatch_async_request() { add_action( 'shutdown', array( $this, 'maybe_dispatch_async_request' ) ); } /** * Unhook check for dispatching an async request. */ public function unhook_dispatch_async_request() { remove_action( 'shutdown', array( $this, 'maybe_dispatch_async_request' ) ); } /** * Check if we should dispatch an async request to process actions. * * This method is attached to 'shutdown', so is called frequently. To avoid slowing down * the site, it mitigates the work performed in each request by: * 1. checking if it's in the admin context and then * 2. haven't run on the 'shutdown' hook within the lock time (60 seconds by default) * 3. haven't exceeded the number of allowed batches. * * The order of these checks is important, because they run from a check on a value: * 1. in memory - is_admin() maps to $GLOBALS or the WP_ADMIN constant * 2. in memory - transients use autoloaded options by default * 3. from a database query - has_maximum_concurrent_batches() run the query * $this->store->get_claim_count() to find the current number of claims in the DB. * * If all of these conditions are met, then we request an async runner check whether it * should dispatch a request to process pending actions. */ public function maybe_dispatch_async_request() { // Only start an async queue at most once every 60 seconds. if ( is_admin() && ! ActionScheduler::lock()->is_locked( 'async-request-runner' ) && ActionScheduler::lock()->set( 'async-request-runner' ) ) { $this->async_request->maybe_dispatch(); } } /** * Process actions in the queue. Attached to self::WP_CRON_HOOK i.e. 'action_scheduler_run_queue' * * The $context param of this method defaults to 'WP Cron', because prior to Action Scheduler 3.0.0 * that was the only context in which this method was run, and the self::WP_CRON_HOOK hook had no context * passed along with it. New code calling this method directly, or by triggering the self::WP_CRON_HOOK, * should set a context as the first parameter. For an example of this, refer to the code seen in * @see ActionScheduler_AsyncRequest_QueueRunner::handle() * * @param string $context Optional identifier for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron' * Generally, this should be capitalised and not localised as it's a proper noun. * @return int The number of actions processed. */ public function run( $context = 'WP Cron' ) { ActionScheduler_Compatibility::raise_memory_limit(); ActionScheduler_Compatibility::raise_time_limit( $this->get_time_limit() ); do_action( 'action_scheduler_before_process_queue' ); $this->run_cleanup(); $this->processed_actions_count = 0; if ( false === $this->has_maximum_concurrent_batches() ) { do { $batch_size = apply_filters( 'action_scheduler_queue_runner_batch_size', 25 ); $processed_actions_in_batch = $this->do_batch( $batch_size, $context ); $this->processed_actions_count += $processed_actions_in_batch; } while ( $processed_actions_in_batch > 0 && ! $this->batch_limits_exceeded( $this->processed_actions_count ) ); // keep going until we run out of actions, time, or memory. } do_action( 'action_scheduler_after_process_queue' ); return $this->processed_actions_count; } /** * Process a batch of actions pending in the queue. * * Actions are processed by claiming a set of pending actions then processing each one until either the batch * size is completed, or memory or time limits are reached, defined by @see $this->batch_limits_exceeded(). * * @param int $size The maximum number of actions to process in the batch. * @param string $context Optional identifier for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron' * Generally, this should be capitalised and not localised as it's a proper noun. * @return int The number of actions processed. */ protected function do_batch( $size = 100, $context = '' ) { $claim = $this->store->stake_claim($size); $this->monitor->attach($claim); $processed_actions = 0; foreach ( $claim->get_actions() as $action_id ) { // bail if we lost the claim. if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $claim->get_id() ) ) ) { break; } $this->process_action( $action_id, $context ); $processed_actions++; if ( $this->batch_limits_exceeded( $processed_actions + $this->processed_actions_count ) ) { break; } } $this->store->release_claim($claim); $this->monitor->detach(); $this->clear_caches(); return $processed_actions; } /** * Flush the cache if possible (intended for use after a batch of actions has been processed). * * This is useful because running large batches can eat up memory and because invalid data can accrue in the * runtime cache, which may lead to unexpected results. */ protected function clear_caches() { /* * Calling wp_cache_flush_runtime() lets us clear the runtime cache without invalidating the external object * cache, so we will always prefer this method (as compared to calling wp_cache_flush()) when it is available. * * However, this function was only introduced in WordPress 6.0. Additionally, the preferred way of detecting if * it is supported changed in WordPress 6.1 so we use two different methods to decide if we should utilize it. */ $flushing_runtime_cache_explicitly_supported = function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_runtime' ); $flushing_runtime_cache_implicitly_supported = ! function_exists( 'wp_cache_supports' ) && function_exists( 'wp_cache_flush_runtime' ); if ( $flushing_runtime_cache_explicitly_supported || $flushing_runtime_cache_implicitly_supported ) { wp_cache_flush_runtime(); } elseif ( ! wp_using_ext_object_cache() /** * When an external object cache is in use, and when wp_cache_flush_runtime() is not available, then * normally the cache will not be flushed after processing a batch of actions (to avoid a performance * penalty for other processes). * * This filter makes it possible to override this behavior and always flush the cache, even if an external * object cache is in use. * * @since 1.0 * * @param bool $flush_cache If the cache should be flushed. */ || apply_filters( 'action_scheduler_queue_runner_flush_cache', false ) ) { wp_cache_flush(); } } /** * Add schedule to WP cron. * * @param array<string, array<string, int|string>> $schedules Schedules. * @return array<string, array<string, int|string>> */ public function add_wp_cron_schedule( $schedules ) { $schedules['every_minute'] = array( 'interval' => 60, // in seconds. 'display' => __( 'Every minute', 'action-scheduler' ), ); return $schedules; } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_NullLogEntry.php 0000644 00000000512 14720461212 0023506 0 ustar 00 <?php /** * Class ActionScheduler_NullLogEntry */ class ActionScheduler_NullLogEntry extends ActionScheduler_LogEntry { /** * Construct. * * @param string $action_id Action ID. * @param string $message Log entry. */ public function __construct( $action_id = '', $message = '' ) { // nothing to see here. } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_Compatibility.php 0000644 00000007144 14720461212 0023731 0 ustar 00 <?php /** * Class ActionScheduler_Compatibility */ class ActionScheduler_Compatibility { /** * Converts a shorthand byte value to an integer byte value. * * Wrapper for wp_convert_hr_to_bytes(), moved to load.php in WordPress 4.6 from media.php * * @link https://secure.php.net/manual/en/function.ini-get.php * @link https://secure.php.net/manual/en/faq.using.php#faq.using.shorthandbytes * * @param string $value A (PHP ini) byte value, either shorthand or ordinary. * @return int An integer byte value. */ public static function convert_hr_to_bytes( $value ) { if ( function_exists( 'wp_convert_hr_to_bytes' ) ) { return wp_convert_hr_to_bytes( $value ); } $value = strtolower( trim( $value ) ); $bytes = (int) $value; if ( false !== strpos( $value, 'g' ) ) { $bytes *= GB_IN_BYTES; } elseif ( false !== strpos( $value, 'm' ) ) { $bytes *= MB_IN_BYTES; } elseif ( false !== strpos( $value, 'k' ) ) { $bytes *= KB_IN_BYTES; } // Deal with large (float) values which run into the maximum integer size. return min( $bytes, PHP_INT_MAX ); } /** * Attempts to raise the PHP memory limit for memory intensive processes. * * Only allows raising the existing limit and prevents lowering it. * * Wrapper for wp_raise_memory_limit(), added in WordPress v4.6.0 * * @return bool|int|string The limit that was set or false on failure. */ public static function raise_memory_limit() { if ( function_exists( 'wp_raise_memory_limit' ) ) { return wp_raise_memory_limit( 'admin' ); } $current_limit = @ini_get( 'memory_limit' ); $current_limit_int = self::convert_hr_to_bytes( $current_limit ); if ( -1 === $current_limit_int ) { return false; } $wp_max_limit = WP_MAX_MEMORY_LIMIT; $wp_max_limit_int = self::convert_hr_to_bytes( $wp_max_limit ); $filtered_limit = apply_filters( 'admin_memory_limit', $wp_max_limit ); $filtered_limit_int = self::convert_hr_to_bytes( $filtered_limit ); if ( -1 === $filtered_limit_int || ( $filtered_limit_int > $wp_max_limit_int && $filtered_limit_int > $current_limit_int ) ) { if ( false !== @ini_set( 'memory_limit', $filtered_limit ) ) { return $filtered_limit; } else { return false; } } elseif ( -1 === $wp_max_limit_int || $wp_max_limit_int > $current_limit_int ) { if ( false !== @ini_set( 'memory_limit', $wp_max_limit ) ) { return $wp_max_limit; } else { return false; } } return false; } /** * Attempts to raise the PHP timeout for time intensive processes. * * Only allows raising the existing limit and prevents lowering it. Wrapper for wc_set_time_limit(), when available. * * @param int $limit The time limit in seconds. */ public static function raise_time_limit( $limit = 0 ) { $limit = (int) $limit; $max_execution_time = (int) ini_get( 'max_execution_time' ); // If the max execution time is already set to zero (unlimited), there is no reason to make a further change. if ( 0 === $max_execution_time ) { return; } // Whichever of $max_execution_time or $limit is higher is the amount by which we raise the time limit. $raise_by = 0 === $limit || $limit > $max_execution_time ? $limit : $max_execution_time; if ( function_exists( 'wc_set_time_limit' ) ) { wc_set_time_limit( $raise_by ); } elseif ( function_exists( 'set_time_limit' ) && false === strpos( ini_get( 'disable_functions' ), 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) { // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.safe_modeDeprecatedRemoved @set_time_limit( $raise_by ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged } } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_Exception.php 0000644 00000000317 14720461212 0023051 0 ustar 00 <?php /** * ActionScheduler Exception Interface. * * Facilitates catching Exceptions unique to Action Scheduler. * * @package ActionScheduler * @since 2.1.0 */ interface ActionScheduler_Exception {} vendor/woocommerce/action-scheduler/classes/ActionScheduler_ActionClaim.php 0000644 00000001111 14720461212 0023267 0 ustar 00 <?php /** * Class ActionScheduler_ActionClaim */ class ActionScheduler_ActionClaim { /** @var string */ private $id = ''; /** @var int[] */ private $action_ids = array(); /** * Construct. * * @param string $id Claim ID. * @param int[] $action_ids Action IDs. */ public function __construct( $id, array $action_ids ) { $this->id = $id; $this->action_ids = $action_ids; } /** * Get claim ID. */ public function get_id() { return $this->id; } /** * Get IDs of claimed actions. */ public function get_actions() { return $this->action_ids; } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_ActionFactory.php 0000644 00000037373 14720461212 0023674 0 ustar 00 <?php /** * Class ActionScheduler_ActionFactory */ class ActionScheduler_ActionFactory { /** * Return stored actions for given params. * * @param string $status The action's status in the data store. * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass to callbacks when the hook is triggered. * @param ActionScheduler_Schedule $schedule The action's schedule. * @param string $group A group to put the action in. * phpcs:ignore Squiz.Commenting.FunctionComment.ExtraParamComment * @param int $priority The action priority. * * @return ActionScheduler_Action An instance of the stored action. */ public function get_stored_action( $status, $hook, array $args = array(), ActionScheduler_Schedule $schedule = null, $group = '' ) { // The 6th parameter ($priority) is not formally declared in the method signature to maintain compatibility with // third-party subclasses created before this param was added. $priority = func_num_args() >= 6 ? (int) func_get_arg( 5 ) : 10; switch ( $status ) { case ActionScheduler_Store::STATUS_PENDING: $action_class = 'ActionScheduler_Action'; break; case ActionScheduler_Store::STATUS_CANCELED: $action_class = 'ActionScheduler_CanceledAction'; if ( ! is_null( $schedule ) && ! is_a( $schedule, 'ActionScheduler_CanceledSchedule' ) && ! is_a( $schedule, 'ActionScheduler_NullSchedule' ) ) { $schedule = new ActionScheduler_CanceledSchedule( $schedule->get_date() ); } break; default: $action_class = 'ActionScheduler_FinishedAction'; break; } $action_class = apply_filters( 'action_scheduler_stored_action_class', $action_class, $status, $hook, $args, $schedule, $group ); $action = new $action_class( $hook, $args, $schedule, $group ); $action->set_priority( $priority ); /** * Allow 3rd party code to change the instantiated action for a given hook, args, schedule and group. * * @param ActionScheduler_Action $action The instantiated action. * @param string $hook The instantiated action's hook. * @param array $args The instantiated action's args. * @param ActionScheduler_Schedule $schedule The instantiated action's schedule. * @param string $group The instantiated action's group. * @param int $priority The action priority. */ return apply_filters( 'action_scheduler_stored_action_instance', $action, $hook, $args, $schedule, $group, $priority ); } /** * Enqueue an action to run one time, as soon as possible (rather a specific scheduled time). * * This method creates a new action using the NullSchedule. In practice, this results in an action scheduled to * execute "now". Therefore, it will generally run as soon as possible but is not prioritized ahead of other actions * that are already past-due. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param string $group A group to put the action in. * * @return int The ID of the stored action. */ public function async( $hook, $args = array(), $group = '' ) { return $this->async_unique( $hook, $args, $group, false ); } /** * Same as async, but also supports $unique param. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param string $group A group to put the action in. * @param bool $unique Whether to ensure the action is unique. * * @return int The ID of the stored action. */ public function async_unique( $hook, $args = array(), $group = '', $unique = true ) { $schedule = new ActionScheduler_NullSchedule(); $action = new ActionScheduler_Action( $hook, $args, $schedule, $group ); return $unique ? $this->store_unique_action( $action, $unique ) : $this->store( $action ); } /** * Create single action. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param int $when Unix timestamp when the action will run. * @param string $group A group to put the action in. * * @return int The ID of the stored action. */ public function single( $hook, $args = array(), $when = null, $group = '' ) { return $this->single_unique( $hook, $args, $when, $group, false ); } /** * Create single action only if there is no pending or running action with same name and params. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param int $when Unix timestamp when the action will run. * @param string $group A group to put the action in. * @param bool $unique Whether action scheduled should be unique. * * @return int The ID of the stored action. */ public function single_unique( $hook, $args = array(), $when = null, $group = '', $unique = true ) { $date = as_get_datetime_object( $when ); $schedule = new ActionScheduler_SimpleSchedule( $date ); $action = new ActionScheduler_Action( $hook, $args, $schedule, $group ); return $unique ? $this->store_unique_action( $action ) : $this->store( $action ); } /** * Create the first instance of an action recurring on a given interval. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param int $first Unix timestamp for the first run. * @param int $interval Seconds between runs. * @param string $group A group to put the action in. * * @return int The ID of the stored action. */ public function recurring( $hook, $args = array(), $first = null, $interval = null, $group = '' ) { return $this->recurring_unique( $hook, $args, $first, $interval, $group, false ); } /** * Create the first instance of an action recurring on a given interval only if there is no pending or running action with same name and params. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param int $first Unix timestamp for the first run. * @param int $interval Seconds between runs. * @param string $group A group to put the action in. * @param bool $unique Whether action scheduled should be unique. * * @return int The ID of the stored action. */ public function recurring_unique( $hook, $args = array(), $first = null, $interval = null, $group = '', $unique = true ) { if ( empty( $interval ) ) { return $this->single_unique( $hook, $args, $first, $group, $unique ); } $date = as_get_datetime_object( $first ); $schedule = new ActionScheduler_IntervalSchedule( $date, $interval ); $action = new ActionScheduler_Action( $hook, $args, $schedule, $group ); return $unique ? $this->store_unique_action( $action ) : $this->store( $action ); } /** * Create the first instance of an action recurring on a Cron schedule. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param int $base_timestamp The first instance of the action will be scheduled * to run at a time calculated after this timestamp matching the cron * expression. This can be used to delay the first instance of the action. * @param int $schedule A cron definition string. * @param string $group A group to put the action in. * * @return int The ID of the stored action. */ public function cron( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '' ) { return $this->cron_unique( $hook, $args, $base_timestamp, $schedule, $group, false ); } /** * Create the first instance of an action recurring on a Cron schedule only if there is no pending or running action with same name and params. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param int $base_timestamp The first instance of the action will be scheduled * to run at a time calculated after this timestamp matching the cron * expression. This can be used to delay the first instance of the action. * @param int $schedule A cron definition string. * @param string $group A group to put the action in. * @param bool $unique Whether action scheduled should be unique. * * @return int The ID of the stored action. **/ public function cron_unique( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '', $unique = true ) { if ( empty( $schedule ) ) { return $this->single_unique( $hook, $args, $base_timestamp, $group, $unique ); } $date = as_get_datetime_object( $base_timestamp ); $cron = CronExpression::factory( $schedule ); $schedule = new ActionScheduler_CronSchedule( $date, $cron ); $action = new ActionScheduler_Action( $hook, $args, $schedule, $group ); return $unique ? $this->store_unique_action( $action ) : $this->store( $action ); } /** * Create a successive instance of a recurring or cron action. * * Importantly, the action will be rescheduled to run based on the current date/time. * That means when the action is scheduled to run in the past, the next scheduled date * will be pushed forward. For example, if a recurring action set to run every hour * was scheduled to run 5 seconds ago, it will be next scheduled for 1 hour in the * future, which is 1 hour and 5 seconds from when it was last scheduled to run. * * Alternatively, if the action is scheduled to run in the future, and is run early, * likely via manual intervention, then its schedule will change based on the time now. * For example, if a recurring action set to run every day, and is run 12 hours early, * it will run again in 24 hours, not 36 hours. * * This slippage is less of an issue with Cron actions, as the specific run time can * be set for them to run, e.g. 1am each day. In those cases, and entire period would * need to be missed before there was any change is scheduled, e.g. in the case of an * action scheduled for 1am each day, the action would need to run an entire day late. * * @param ActionScheduler_Action $action The existing action. * * @return string The ID of the stored action * @throws InvalidArgumentException If $action is not a recurring action. */ public function repeat( $action ) { $schedule = $action->get_schedule(); $next = $schedule->get_next( as_get_datetime_object() ); if ( is_null( $next ) || ! $schedule->is_recurring() ) { throw new InvalidArgumentException( __( 'Invalid action - must be a recurring action.', 'action-scheduler' ) ); } $schedule_class = get_class( $schedule ); $new_schedule = new $schedule( $next, $schedule->get_recurrence(), $schedule->get_first_date() ); $new_action = new ActionScheduler_Action( $action->get_hook(), $action->get_args(), $new_schedule, $action->get_group() ); $new_action->set_priority( $action->get_priority() ); return $this->store( $new_action ); } /** * Creates a scheduled action. * * This general purpose method can be used in place of specific methods such as async(), * async_unique(), single() or single_unique(), etc. * * @internal Not intended for public use, should not be overridden by subclasses. * * @param array $options { * Describes the action we wish to schedule. * * @type string $type Must be one of 'async', 'cron', 'recurring', or 'single'. * @type string $hook The hook to be executed. * @type array $arguments Arguments to be passed to the callback. * @type string $group The action group. * @type bool $unique If the action should be unique. * @type int $when Timestamp. Indicates when the action, or first instance of the action in the case * of recurring or cron actions, becomes due. * @type int|string $pattern Recurrence pattern. This is either an interval in seconds for recurring actions * or a cron expression for cron actions. * @type int $priority Lower values means higher priority. Should be in the range 0-255. * } * * @return int The action ID. Zero if there was an error scheduling the action. */ public function create( array $options = array() ) { $defaults = array( 'type' => 'single', 'hook' => '', 'arguments' => array(), 'group' => '', 'unique' => false, 'when' => time(), 'pattern' => null, 'priority' => 10, ); $options = array_merge( $defaults, $options ); // Cron/recurring actions without a pattern are treated as single actions (this gives calling code the ability // to use functions like as_schedule_recurring_action() to schedule recurring as well as single actions). if ( ( 'cron' === $options['type'] || 'recurring' === $options['type'] ) && empty( $options['pattern'] ) ) { $options['type'] = 'single'; } switch ( $options['type'] ) { case 'async': $schedule = new ActionScheduler_NullSchedule(); break; case 'cron': $date = as_get_datetime_object( $options['when'] ); $cron = CronExpression::factory( $options['pattern'] ); $schedule = new ActionScheduler_CronSchedule( $date, $cron ); break; case 'recurring': $date = as_get_datetime_object( $options['when'] ); $schedule = new ActionScheduler_IntervalSchedule( $date, $options['pattern'] ); break; case 'single': $date = as_get_datetime_object( $options['when'] ); $schedule = new ActionScheduler_SimpleSchedule( $date ); break; default: error_log( "Unknown action type '{$options['type']}' specified when trying to create an action for '{$options['hook']}'." ); return 0; } $action = new ActionScheduler_Action( $options['hook'], $options['arguments'], $schedule, $options['group'] ); $action->set_priority( $options['priority'] ); $action_id = 0; try { $action_id = $options['unique'] ? $this->store_unique_action( $action ) : $this->store( $action ); } catch ( Exception $e ) { error_log( sprintf( /* translators: %1$s is the name of the hook to be enqueued, %2$s is the exception message. */ __( 'Caught exception while enqueuing action "%1$s": %2$s', 'action-scheduler' ), $options['hook'], $e->getMessage() ) ); } return $action_id; } /** * Save action to database. * * @param ActionScheduler_Action $action Action object to save. * * @return int The ID of the stored action */ protected function store( ActionScheduler_Action $action ) { $store = ActionScheduler_Store::instance(); return $store->save_action( $action ); } /** * Store action if it's unique. * * @param ActionScheduler_Action $action Action object to store. * * @return int ID of the created action. Will be 0 if action was not created. */ protected function store_unique_action( ActionScheduler_Action $action ) { $store = ActionScheduler_Store::instance(); if ( method_exists( $store, 'save_unique_action' ) ) { return $store->save_unique_action( $action ); } else { /** * Fallback to non-unique action if the store doesn't support unique actions. * We try to save the action as unique, accepting that there might be a race condition. * This is likely still better than giving up on unique actions entirely. */ $existing_action_id = (int) $store->find_action( $action->get_hook(), array( 'args' => $action->get_args(), 'status' => ActionScheduler_Store::STATUS_PENDING, 'group' => $action->get_group(), ) ); if ( $existing_action_id > 0 ) { return 0; } return $store->save_action( $action ); } } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_InvalidActionException.php 0000644 00000002532 14720461212 0025517 0 ustar 00 <?php /** * InvalidAction Exception. * * Used for identifying actions that are invalid in some way. * * @package ActionScheduler */ class ActionScheduler_InvalidActionException extends \InvalidArgumentException implements ActionScheduler_Exception { /** * Create a new exception when the action's schedule cannot be fetched. * * @param string $action_id The action ID with bad args. * @param mixed $schedule Passed schedule. * @return static */ public static function from_schedule( $action_id, $schedule ) { $message = sprintf( /* translators: 1: action ID 2: schedule */ __( 'Action [%1$s] has an invalid schedule: %2$s', 'action-scheduler' ), $action_id, var_export( $schedule, true ) ); return new static( $message ); } /** * Create a new exception when the action's args cannot be decoded to an array. * * @author Jeremy Pry * * @param string $action_id The action ID with bad args. * @param mixed $args Passed arguments. * @return static */ public static function from_decoding_args( $action_id, $args = array() ) { $message = sprintf( /* translators: 1: action ID 2: arguments */ __( 'Action [%1$s] has invalid arguments. It cannot be JSON decoded to an array. $args = %2$s', 'action-scheduler' ), $action_id, var_export( $args, true ) ); return new static( $message ); } } vendor/woocommerce/action-scheduler/classes/actions/ActionScheduler_NullAction.php 0000644 00000001130 14720461212 0024615 0 ustar 00 <?php /** * Class ActionScheduler_NullAction */ class ActionScheduler_NullAction extends ActionScheduler_Action { /** * Construct. * * @param string $hook Action hook. * @param mixed[] $args Action arguments. * @param null|ActionScheduler_Schedule $schedule Action schedule. */ public function __construct( $hook = '', array $args = array(), ActionScheduler_Schedule $schedule = NULL ) { $this->set_schedule( new ActionScheduler_NullSchedule() ); } /** * Execute action. */ public function execute() { // don't execute. } } vendor/woocommerce/action-scheduler/classes/actions/ActionScheduler_CanceledAction.php 0000644 00000001562 14720461212 0025412 0 ustar 00 <?php /** * Class ActionScheduler_CanceledAction * * Stored action which was canceled and therefore acts like a finished action but should always return a null schedule, * regardless of schedule passed to its constructor. */ class ActionScheduler_CanceledAction extends ActionScheduler_FinishedAction { /** * Construct. * * @param string $hook Action's hook. * @param array $args Action's arguments. * @param null|ActionScheduler_Schedule $schedule Action's schedule. * @param string $group Action's group. */ public function __construct( $hook, array $args = array(), ActionScheduler_Schedule $schedule = null, $group = '' ) { parent::__construct( $hook, $args, $schedule, $group ); if ( is_null( $schedule ) ) { $this->set_schedule( new ActionScheduler_NullSchedule() ); } } } vendor/woocommerce/action-scheduler/classes/actions/ActionScheduler_Action.php 0000644 00000007217 14720461212 0023776 0 ustar 00 <?php /** * Class ActionScheduler_Action */ class ActionScheduler_Action { /** @var string */ protected $hook = ''; /** @var array<string, mixed> */ protected $args = array(); /** @var ActionScheduler_Schedule */ protected $schedule = NULL; /** @var string */ protected $group = ''; /** * Priorities are conceptually similar to those used for regular WordPress actions. * Like those, a lower priority takes precedence over a higher priority and the default * is 10. * * Unlike regular WordPress actions, the priority of a scheduled action is strictly an * integer and should be kept within the bounds 0-255 (anything outside the bounds will * be brought back into the acceptable range). * * @var int */ protected $priority = 10; /** * Construct. * * @param string $hook Action's hook. * @param mixed[] $args Action's arguments. * @param null|ActionScheduler_Schedule $schedule Action's schedule. * @param string $group Action's group. */ public function __construct( $hook, array $args = array(), ActionScheduler_Schedule $schedule = NULL, $group = '' ) { $schedule = empty( $schedule ) ? new ActionScheduler_NullSchedule() : $schedule; $this->set_hook($hook); $this->set_schedule($schedule); $this->set_args($args); $this->set_group($group); } /** * Executes the action. * * If no callbacks are registered, an exception will be thrown and the action will not be * fired. This is useful to help detect cases where the code responsible for setting up * a scheduled action no longer exists. * * @throws Exception If no callbacks are registered for this action. */ public function execute() { $hook = $this->get_hook(); if ( ! has_action( $hook ) ) { throw new Exception( sprintf( /* translators: 1: action hook. */ __( 'Scheduled action for %1$s will not be executed as no callbacks are registered.', 'action-scheduler' ), $hook ) ); } do_action_ref_array( $hook, array_values( $this->get_args() ) ); } /** * Set action's hook. * * @param string $hook Action's hook. */ protected function set_hook( $hook ) { $this->hook = $hook; } /** * Get action's hook. */ public function get_hook() { return $this->hook; } /** * Set action's schedule. * * @param ActionScheduler_Schedule $schedule Action's schedule. */ protected function set_schedule( ActionScheduler_Schedule $schedule ) { $this->schedule = $schedule; } /** * @return ActionScheduler_Schedule */ public function get_schedule() { return $this->schedule; } /** * Set action's args. * * @param mixed[] $args Action's arguments. */ protected function set_args( array $args ) { $this->args = $args; } /** * Get action's args. */ public function get_args() { return $this->args; } /** * Section action's group. * * @param string $group Action's group. */ protected function set_group( $group ) { $this->group = $group; } /** * @return string */ public function get_group() { return $this->group; } /** * @return bool If the action has been finished */ public function is_finished() { return FALSE; } /** * Sets the priority of the action. * * @param int $priority Priority level (lower is higher priority). Should be in the range 0-255. * * @return void */ public function set_priority( $priority ) { if ( $priority < 0 ) { $priority = 0; } elseif ( $priority > 255 ) { $priority = 255; } $this->priority = (int) $priority; } /** * Gets the action priority. * * @return int */ public function get_priority() { return $this->priority; } } vendor/woocommerce/action-scheduler/classes/actions/ActionScheduler_FinishedAction.php 0000644 00000000450 14720461212 0025440 0 ustar 00 <?php /** * Class ActionScheduler_FinishedAction */ class ActionScheduler_FinishedAction extends ActionScheduler_Action { /** * Execute action. */ public function execute() { // don't execute. } /** * Get finished state. */ public function is_finished() { return TRUE; } } vendor/woocommerce/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore.php 0000644 00000106175 14720461212 0025663 0 ustar 00 <?php /** * Class ActionScheduler_wpPostStore */ class ActionScheduler_wpPostStore extends ActionScheduler_Store { const POST_TYPE = 'scheduled-action'; const GROUP_TAXONOMY = 'action-group'; const SCHEDULE_META_KEY = '_action_manager_schedule'; const DEPENDENCIES_MET = 'as-post-store-dependencies-met'; /** * Used to share information about the before_date property of claims internally. * * This is used in preference to passing the same information as a method param * for backwards-compatibility reasons. * * @var DateTime|null */ private $claim_before_date = null; /** * Local Timezone. * * @var DateTimeZone */ protected $local_timezone = null; /** * Save action. * * @param ActionScheduler_Action $action Scheduled Action. * @param DateTime $scheduled_date Scheduled Date. * * @throws RuntimeException Throws an exception if the action could not be saved. * @return int */ public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = null ) { try { $this->validate_action( $action ); $post_array = $this->create_post_array( $action, $scheduled_date ); $post_id = $this->save_post_array( $post_array ); $this->save_post_schedule( $post_id, $action->get_schedule() ); $this->save_action_group( $post_id, $action->get_group() ); do_action( 'action_scheduler_stored_action', $post_id ); return $post_id; } catch ( Exception $e ) { /* translators: %s: action error message */ throw new RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 ); } } /** * Create post array. * * @param ActionScheduler_Action $action Scheduled Action. * @param DateTime $scheduled_date Scheduled Date. * * @return array Returns an array of post data. */ protected function create_post_array( ActionScheduler_Action $action, DateTime $scheduled_date = null ) { $post = array( 'post_type' => self::POST_TYPE, 'post_title' => $action->get_hook(), 'post_content' => wp_json_encode( $action->get_args() ), 'post_status' => ( $action->is_finished() ? 'publish' : 'pending' ), 'post_date_gmt' => $this->get_scheduled_date_string( $action, $scheduled_date ), 'post_date' => $this->get_scheduled_date_string_local( $action, $scheduled_date ), ); return $post; } /** * Save post array. * * @param array $post_array Post array. * @return int Returns the post ID. * @throws RuntimeException Throws an exception if the action could not be saved. */ protected function save_post_array( $post_array ) { add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 ); add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 ); $has_kses = false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' ); if ( $has_kses ) { // Prevent KSES from corrupting JSON in post_content. kses_remove_filters(); } $post_id = wp_insert_post( $post_array ); if ( $has_kses ) { kses_init_filters(); } remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 ); remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 ); if ( is_wp_error( $post_id ) || empty( $post_id ) ) { throw new RuntimeException( __( 'Unable to save action.', 'action-scheduler' ) ); } return $post_id; } /** * Filter insert post data. * * @param array $postdata Post data to filter. * * @return array */ public function filter_insert_post_data( $postdata ) { if ( self::POST_TYPE === $postdata['post_type'] ) { $postdata['post_author'] = 0; if ( 'future' === $postdata['post_status'] ) { $postdata['post_status'] = 'publish'; } } return $postdata; } /** * Create a (probably unique) post name for scheduled actions in a more performant manner than wp_unique_post_slug(). * * When an action's post status is transitioned to something other than 'draft', 'pending' or 'auto-draft, like 'publish' * or 'failed' or 'trash', WordPress will find a unique slug (stored in post_name column) using the wp_unique_post_slug() * function. This is done to ensure URL uniqueness. The approach taken by wp_unique_post_slug() is to iterate over existing * post_name values that match, and append a number 1 greater than the largest. This makes sense when manually creating a * post from the Edit Post screen. It becomes a bottleneck when automatically processing thousands of actions, with a * database containing thousands of related post_name values. * * WordPress 5.1 introduces the 'pre_wp_unique_post_slug' filter for plugins to address this issue. * * We can short-circuit WordPress's wp_unique_post_slug() approach using the 'pre_wp_unique_post_slug' filter. This * method is available to be used as a callback on that filter. It provides a more scalable approach to generating a * post_name/slug that is probably unique. Because Action Scheduler never actually uses the post_name field, or an * action's slug, being probably unique is good enough. * * For more backstory on this issue, see: * - https://github.com/woocommerce/action-scheduler/issues/44 and * - https://core.trac.wordpress.org/ticket/21112 * * @param string $override_slug Short-circuit return value. * @param string $slug The desired slug (post_name). * @param int $post_ID Post ID. * @param string $post_status The post status. * @param string $post_type Post type. * @return string */ public function set_unique_post_slug( $override_slug, $slug, $post_ID, $post_status, $post_type ) { if ( self::POST_TYPE === $post_type ) { $override_slug = uniqid( self::POST_TYPE . '-', true ) . '-' . wp_generate_password( 32, false ); } return $override_slug; } /** * Save post schedule. * * @param int $post_id Post ID of the scheduled action. * @param string $schedule Schedule to save. * * @return void */ protected function save_post_schedule( $post_id, $schedule ) { update_post_meta( $post_id, self::SCHEDULE_META_KEY, $schedule ); } /** * Save action group. * * @param int $post_id Post ID. * @param string $group Group to save. * @return void */ protected function save_action_group( $post_id, $group ) { if ( empty( $group ) ) { wp_set_object_terms( $post_id, array(), self::GROUP_TAXONOMY, false ); } else { wp_set_object_terms( $post_id, array( $group ), self::GROUP_TAXONOMY, false ); } } /** * Fetch actions. * * @param int $action_id Action ID. * @return object */ public function fetch_action( $action_id ) { $post = $this->get_post( $action_id ); if ( empty( $post ) || self::POST_TYPE !== $post->post_type ) { return $this->get_null_action(); } try { $action = $this->make_action_from_post( $post ); } catch ( ActionScheduler_InvalidActionException $exception ) { do_action( 'action_scheduler_failed_fetch_action', $post->ID, $exception ); return $this->get_null_action(); } return $action; } /** * Get post. * * @param string $action_id - Action ID. * @return WP_Post|null */ protected function get_post( $action_id ) { if ( empty( $action_id ) ) { return null; } return get_post( $action_id ); } /** * Get NULL action. * * @return ActionScheduler_NullAction */ protected function get_null_action() { return new ActionScheduler_NullAction(); } /** * Make action from post. * * @param WP_Post $post Post object. * @return WP_Post */ protected function make_action_from_post( $post ) { $hook = $post->post_title; $args = json_decode( $post->post_content, true ); $this->validate_args( $args, $post->ID ); $schedule = get_post_meta( $post->ID, self::SCHEDULE_META_KEY, true ); $this->validate_schedule( $schedule, $post->ID ); $group = wp_get_object_terms( $post->ID, self::GROUP_TAXONOMY, array( 'fields' => 'names' ) ); $group = empty( $group ) ? '' : reset( $group ); return ActionScheduler::factory()->get_stored_action( $this->get_action_status_by_post_status( $post->post_status ), $hook, $args, $schedule, $group ); } /** * Get action status by post status. * * @param string $post_status Post status. * * @throws InvalidArgumentException Throw InvalidArgumentException if $post_status not in known status fields returned by $this->get_status_labels(). * @return string */ protected function get_action_status_by_post_status( $post_status ) { switch ( $post_status ) { case 'publish': $action_status = self::STATUS_COMPLETE; break; case 'trash': $action_status = self::STATUS_CANCELED; break; default: if ( ! array_key_exists( $post_status, $this->get_status_labels() ) ) { throw new InvalidArgumentException( sprintf( 'Invalid post status: "%s". No matching action status available.', $post_status ) ); } $action_status = $post_status; break; } return $action_status; } /** * Get post status by action status. * * @param string $action_status Action status. * * @throws InvalidArgumentException Throws InvalidArgumentException if $post_status not in known status fields returned by $this->get_status_labels(). * @return string */ protected function get_post_status_by_action_status( $action_status ) { switch ( $action_status ) { case self::STATUS_COMPLETE: $post_status = 'publish'; break; case self::STATUS_CANCELED: $post_status = 'trash'; break; default: if ( ! array_key_exists( $action_status, $this->get_status_labels() ) ) { throw new InvalidArgumentException( sprintf( 'Invalid action status: "%s".', $action_status ) ); } $post_status = $action_status; break; } return $post_status; } /** * Returns the SQL statement to query (or count) actions. * * @param array $query - Filtering options. * @param string $select_or_count - Whether the SQL should select and return the IDs or just the row count. * * @throws InvalidArgumentException - Throw InvalidArgumentException if $select_or_count not count or select. * @return string SQL statement. The returned SQL is already properly escaped. */ protected function get_query_actions_sql( array $query, $select_or_count = 'select' ) { if ( ! in_array( $select_or_count, array( 'select', 'count' ), true ) ) { throw new InvalidArgumentException( __( 'Invalid schedule. Cannot save action.', 'action-scheduler' ) ); } $query = wp_parse_args( $query, array( 'hook' => '', 'args' => null, 'date' => null, 'date_compare' => '<=', 'modified' => null, 'modified_compare' => '<=', 'group' => '', 'status' => '', 'claimed' => null, 'per_page' => 5, 'offset' => 0, 'orderby' => 'date', 'order' => 'ASC', 'search' => '', ) ); /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; $sql = ( 'count' === $select_or_count ) ? 'SELECT count(p.ID)' : 'SELECT p.ID '; $sql .= "FROM {$wpdb->posts} p"; $sql_params = array(); if ( empty( $query['group'] ) && 'group' === $query['orderby'] ) { $sql .= " LEFT JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID"; $sql .= " LEFT JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id"; $sql .= " LEFT JOIN {$wpdb->terms} t ON tt.term_id=t.term_id"; } elseif ( ! empty( $query['group'] ) ) { $sql .= " INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID"; $sql .= " INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id"; $sql .= " INNER JOIN {$wpdb->terms} t ON tt.term_id=t.term_id"; $sql .= ' AND t.slug=%s'; $sql_params[] = $query['group']; } $sql .= ' WHERE post_type=%s'; $sql_params[] = self::POST_TYPE; if ( $query['hook'] ) { $sql .= ' AND p.post_title=%s'; $sql_params[] = $query['hook']; } if ( ! is_null( $query['args'] ) ) { $sql .= ' AND p.post_content=%s'; $sql_params[] = wp_json_encode( $query['args'] ); } if ( $query['status'] ) { $post_statuses = array_map( array( $this, 'get_post_status_by_action_status' ), (array) $query['status'] ); $placeholders = array_fill( 0, count( $post_statuses ), '%s' ); $sql .= ' AND p.post_status IN (' . join( ', ', $placeholders ) . ')'; $sql_params = array_merge( $sql_params, array_values( $post_statuses ) ); } if ( $query['date'] instanceof DateTime ) { $date = clone $query['date']; $date->setTimezone( new DateTimeZone( 'UTC' ) ); $date_string = $date->format( 'Y-m-d H:i:s' ); $comparator = $this->validate_sql_comparator( $query['date_compare'] ); $sql .= " AND p.post_date_gmt $comparator %s"; $sql_params[] = $date_string; } if ( $query['modified'] instanceof DateTime ) { $modified = clone $query['modified']; $modified->setTimezone( new DateTimeZone( 'UTC' ) ); $date_string = $modified->format( 'Y-m-d H:i:s' ); $comparator = $this->validate_sql_comparator( $query['modified_compare'] ); $sql .= " AND p.post_modified_gmt $comparator %s"; $sql_params[] = $date_string; } if ( true === $query['claimed'] ) { $sql .= " AND p.post_password != ''"; } elseif ( false === $query['claimed'] ) { $sql .= " AND p.post_password = ''"; } elseif ( ! is_null( $query['claimed'] ) ) { $sql .= ' AND p.post_password = %s'; $sql_params[] = $query['claimed']; } if ( ! empty( $query['search'] ) ) { $sql .= ' AND (p.post_title LIKE %s OR p.post_content LIKE %s OR p.post_password LIKE %s)'; for ( $i = 0; $i < 3; $i++ ) { $sql_params[] = sprintf( '%%%s%%', $query['search'] ); } } if ( 'select' === $select_or_count ) { switch ( $query['orderby'] ) { case 'hook': $orderby = 'p.post_title'; break; case 'group': $orderby = 't.name'; break; case 'status': $orderby = 'p.post_status'; break; case 'modified': $orderby = 'p.post_modified'; break; case 'claim_id': $orderby = 'p.post_password'; break; case 'schedule': case 'date': default: $orderby = 'p.post_date_gmt'; break; } if ( 'ASC' === strtoupper( $query['order'] ) ) { $order = 'ASC'; } else { $order = 'DESC'; } $sql .= " ORDER BY $orderby $order"; if ( $query['per_page'] > 0 ) { $sql .= ' LIMIT %d, %d'; $sql_params[] = $query['offset']; $sql_params[] = $query['per_page']; } } return $wpdb->prepare( $sql, $sql_params ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } /** * Query for action count or list of action IDs. * * @since 3.3.0 $query['status'] accepts array of statuses instead of a single status. * * @see ActionScheduler_Store::query_actions for $query arg usage. * * @param array $query Query filtering options. * @param string $query_type Whether to select or count the results. Defaults to select. * * @return string|array|null The IDs of actions matching the query. Null on failure. */ public function query_actions( $query = array(), $query_type = 'select' ) { /** * Global $wpdb object. * * @var wpdb $wpdb */ global $wpdb; $sql = $this->get_query_actions_sql( $query, $query_type ); return ( 'count' === $query_type ) ? $wpdb->get_var( $sql ) : $wpdb->get_col( $sql ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared } /** * Get a count of all actions in the store, grouped by status * * @return array */ public function action_counts() { $action_counts_by_status = array(); $action_stati_and_labels = $this->get_status_labels(); $posts_count_by_status = (array) wp_count_posts( self::POST_TYPE, 'readable' ); foreach ( $posts_count_by_status as $post_status_name => $count ) { try { $action_status_name = $this->get_action_status_by_post_status( $post_status_name ); } catch ( Exception $e ) { // Ignore any post statuses that aren't for actions. continue; } if ( array_key_exists( $action_status_name, $action_stati_and_labels ) ) { $action_counts_by_status[ $action_status_name ] = $count; } } return $action_counts_by_status; } /** * Cancel action. * * @param int $action_id Action ID. * * @throws InvalidArgumentException If $action_id is not identified. */ public function cancel_action( $action_id ) { $post = get_post( $action_id ); if ( empty( $post ) || ( self::POST_TYPE !== $post->post_type ) ) { /* translators: %s is the action ID */ throw new InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to cancel this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } do_action( 'action_scheduler_canceled_action', $action_id ); add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 ); wp_trash_post( $action_id ); remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 ); } /** * Delete action. * * @param int $action_id Action ID. * @return void * @throws InvalidArgumentException If action is not identified. */ public function delete_action( $action_id ) { $post = get_post( $action_id ); if ( empty( $post ) || ( self::POST_TYPE !== $post->post_type ) ) { /* translators: %s is the action ID */ throw new InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to delete this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } do_action( 'action_scheduler_deleted_action', $action_id ); wp_delete_post( $action_id, true ); } /** * Get date for claim id. * * @param int $action_id Action ID. * @return ActionScheduler_DateTime The date the action is schedule to run, or the date that it ran. */ public function get_date( $action_id ) { $next = $this->get_date_gmt( $action_id ); return ActionScheduler_TimezoneHelper::set_local_timezone( $next ); } /** * Get Date GMT. * * @param int $action_id Action ID. * * @throws InvalidArgumentException If $action_id is not identified. * @return ActionScheduler_DateTime The date the action is schedule to run, or the date that it ran. */ public function get_date_gmt( $action_id ) { $post = get_post( $action_id ); if ( empty( $post ) || ( self::POST_TYPE !== $post->post_type ) ) { /* translators: %s is the action ID */ throw new InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to determine the date of this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } if ( 'publish' === $post->post_status ) { return as_get_datetime_object( $post->post_modified_gmt ); } else { return as_get_datetime_object( $post->post_date_gmt ); } } /** * Stake claim. * * @param int $max_actions Maximum number of actions. * @param DateTime $before_date Jobs must be schedule before this date. Defaults to now. * @param array $hooks Claim only actions with a hook or hooks. * @param string $group Claim only actions in the given group. * * @return ActionScheduler_ActionClaim * @throws RuntimeException When there is an error staking a claim. * @throws InvalidArgumentException When the given group is not valid. */ public function stake_claim( $max_actions = 10, DateTime $before_date = null, $hooks = array(), $group = '' ) { $this->claim_before_date = $before_date; $claim_id = $this->generate_claim_id(); $this->claim_actions( $claim_id, $max_actions, $before_date, $hooks, $group ); $action_ids = $this->find_actions_by_claim_id( $claim_id ); $this->claim_before_date = null; return new ActionScheduler_ActionClaim( $claim_id, $action_ids ); } /** * Get claim count. * * @return int */ public function get_claim_count() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching return $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(DISTINCT post_password) FROM {$wpdb->posts} WHERE post_password != '' AND post_type = %s AND post_status IN ('in-progress','pending')", array( self::POST_TYPE ) ) ); } /** * Generate claim id. * * @return string */ protected function generate_claim_id() { $claim_id = md5( microtime( true ) . wp_rand( 0, 1000 ) ); return substr( $claim_id, 0, 20 ); // to fit in db field with 20 char limit. } /** * Claim actions. * * @param string $claim_id Claim ID. * @param int $limit Limit. * @param DateTime $before_date Should use UTC timezone. * @param array $hooks Claim only actions with a hook or hooks. * @param string $group Claim only actions in the given group. * * @return int The number of actions that were claimed. * @throws RuntimeException When there is a database error. */ protected function claim_actions( $claim_id, $limit, DateTime $before_date = null, $hooks = array(), $group = '' ) { // Set up initial variables. $date = null === $before_date ? as_get_datetime_object() : clone $before_date; $limit_ids = ! empty( $group ); $ids = $limit_ids ? $this->get_actions_by_group( $group, $limit, $date ) : array(); // If limiting by IDs and no posts found, then return early since we have nothing to update. if ( $limit_ids && 0 === count( $ids ) ) { return 0; } /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; /* * Build up custom query to update the affected posts. Parameters are built as a separate array * to make it easier to identify where they are in the query. * * We can't use $wpdb->update() here because of the "ID IN ..." clause. */ $update = "UPDATE {$wpdb->posts} SET post_password = %s, post_modified_gmt = %s, post_modified = %s"; $params = array( $claim_id, current_time( 'mysql', true ), current_time( 'mysql' ), ); // Build initial WHERE clause. $where = "WHERE post_type = %s AND post_status = %s AND post_password = ''"; $params[] = self::POST_TYPE; $params[] = ActionScheduler_Store::STATUS_PENDING; if ( ! empty( $hooks ) ) { $placeholders = array_fill( 0, count( $hooks ), '%s' ); $where .= ' AND post_title IN (' . join( ', ', $placeholders ) . ')'; $params = array_merge( $params, array_values( $hooks ) ); } /* * Add the IDs to the WHERE clause. IDs not escaped because they came directly from a prior DB query. * * If we're not limiting by IDs, then include the post_date_gmt clause. */ if ( $limit_ids ) { $where .= ' AND ID IN (' . join( ',', $ids ) . ')'; } else { $where .= ' AND post_date_gmt <= %s'; $params[] = $date->format( 'Y-m-d H:i:s' ); } // Add the ORDER BY clause and,ms limit. $order = 'ORDER BY menu_order ASC, post_date_gmt ASC, ID ASC LIMIT %d'; $params[] = $limit; // Run the query and gather results. $rows_affected = $wpdb->query( $wpdb->prepare( "{$update} {$where} {$order}", $params ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare if ( false === $rows_affected ) { throw new RuntimeException( __( 'Unable to claim actions. Database error.', 'action-scheduler' ) ); } return (int) $rows_affected; } /** * Get IDs of actions within a certain group and up to a certain date/time. * * @param string $group The group to use in finding actions. * @param int $limit The number of actions to retrieve. * @param DateTime $date DateTime object representing cutoff time for actions. Actions retrieved will be * up to and including this DateTime. * * @return array IDs of actions in the appropriate group and before the appropriate time. * @throws InvalidArgumentException When the group does not exist. */ protected function get_actions_by_group( $group, $limit, DateTime $date ) { // Ensure the group exists before continuing. if ( ! term_exists( $group, self::GROUP_TAXONOMY ) ) { /* translators: %s is the group name */ throw new InvalidArgumentException( sprintf( __( 'The group "%s" does not exist.', 'action-scheduler' ), $group ) ); } // Set up a query for post IDs to use later. $query = new WP_Query(); $query_args = array( 'fields' => 'ids', 'post_type' => self::POST_TYPE, 'post_status' => ActionScheduler_Store::STATUS_PENDING, 'has_password' => false, 'posts_per_page' => $limit * 3, 'suppress_filters' => true, // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.SuppressFilters_suppress_filters 'no_found_rows' => true, 'orderby' => array( 'menu_order' => 'ASC', 'date' => 'ASC', 'ID' => 'ASC', ), 'date_query' => array( 'column' => 'post_date_gmt', 'before' => $date->format( 'Y-m-d H:i' ), 'inclusive' => true, ), 'tax_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery array( 'taxonomy' => self::GROUP_TAXONOMY, 'field' => 'slug', 'terms' => $group, 'include_children' => false, ), ), ); return $query->query( $query_args ); } /** * Find actions by claim ID. * * @param string $claim_id Claim ID. * @return array */ public function find_actions_by_claim_id( $claim_id ) { /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; $action_ids = array(); $before_date = isset( $this->claim_before_date ) ? $this->claim_before_date : as_get_datetime_object(); $cut_off = $before_date->format( 'Y-m-d H:i:s' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_date_gmt FROM {$wpdb->posts} WHERE post_type = %s AND post_password = %s", array( self::POST_TYPE, $claim_id, ) ) ); // Verify that the scheduled date for each action is within the expected bounds (in some unusual // cases, we cannot depend on MySQL to honor all of the WHERE conditions we specify). foreach ( $results as $claimed_action ) { if ( $claimed_action->post_date_gmt <= $cut_off ) { $action_ids[] = absint( $claimed_action->ID ); } } return $action_ids; } /** * Release claim. * * @param ActionScheduler_ActionClaim $claim Claim object to release. * @return void * @throws RuntimeException When the claim is not unlocked. */ public function release_claim( ActionScheduler_ActionClaim $claim ) { $action_ids = $this->find_actions_by_claim_id( $claim->get_id() ); if ( empty( $action_ids ) ) { return; // nothing to do. } $action_id_string = implode( ',', array_map( 'intval', $action_ids ) ); /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $result = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_password = '' WHERE ID IN ($action_id_string) AND post_password = %s", //phpcs:ignore array( $claim->get_id(), ) ) ); if ( false === $result ) { /* translators: %s: claim ID */ throw new RuntimeException( sprintf( __( 'Unable to unlock claim %s. Database error.', 'action-scheduler' ), $claim->get_id() ) ); } } /** * Unclaim action. * * @param string $action_id Action ID. * @throws RuntimeException When unable to unlock claim on action ID. */ public function unclaim_action( $action_id ) { /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $result = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_password = '' WHERE ID = %d AND post_type = %s", $action_id, self::POST_TYPE ) ); if ( false === $result ) { /* translators: %s: action ID */ throw new RuntimeException( sprintf( __( 'Unable to unlock claim on action %s. Database error.', 'action-scheduler' ), $action_id ) ); } } /** * Mark failure on action. * * @param int $action_id Action ID. * * @return void * @throws RuntimeException When unable to mark failure on action ID. */ public function mark_failure( $action_id ) { /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $result = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_status = %s WHERE ID = %d AND post_type = %s", self::STATUS_FAILED, $action_id, self::POST_TYPE ) ); if ( false === $result ) { /* translators: %s: action ID */ throw new RuntimeException( sprintf( __( 'Unable to mark failure on action %s. Database error.', 'action-scheduler' ), $action_id ) ); } } /** * Return an action's claim ID, as stored in the post password column * * @param int $action_id Action ID. * @return mixed */ public function get_claim_id( $action_id ) { return $this->get_post_column( $action_id, 'post_password' ); } /** * Return an action's status, as stored in the post status column * * @param int $action_id Action ID. * * @return mixed * @throws InvalidArgumentException When the action ID is invalid. */ public function get_status( $action_id ) { $status = $this->get_post_column( $action_id, 'post_status' ); if ( null === $status ) { throw new InvalidArgumentException( __( 'Invalid action ID. No status found.', 'action-scheduler' ) ); } return $this->get_action_status_by_post_status( $status ); } /** * Get post column * * @param string $action_id Action ID. * @param string $column_name Column Name. * * @return string|null */ private function get_post_column( $action_id, $column_name ) { /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return $wpdb->get_var( $wpdb->prepare( "SELECT {$column_name} FROM {$wpdb->posts} WHERE ID=%d AND post_type=%s", // phpcs:ignore $action_id, self::POST_TYPE ) ); } /** * Log Execution. * * @throws Exception If the action status cannot be updated to self::STATUS_RUNNING ('in-progress'). * * @param string $action_id Action ID. */ public function log_execution( $action_id ) { /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $status_updated = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET menu_order = menu_order+1, post_status=%s, post_modified_gmt = %s, post_modified = %s WHERE ID = %d AND post_type = %s", self::STATUS_RUNNING, current_time( 'mysql', true ), current_time( 'mysql' ), $action_id, self::POST_TYPE ) ); if ( ! $status_updated ) { throw new Exception( sprintf( /* translators: 1: action ID. 2: status slug. */ __( 'Unable to update the status of action %1$d to %2$s.', 'action-scheduler' ), $action_id, self::STATUS_RUNNING ) ); } } /** * Record that an action was completed. * * @param string $action_id ID of the completed action. * * @throws InvalidArgumentException When the action ID is invalid. * @throws RuntimeException When there was an error executing the action. */ public function mark_complete( $action_id ) { $post = get_post( $action_id ); if ( empty( $post ) || ( self::POST_TYPE !== $post->post_type ) ) { /* translators: %s is the action ID */ throw new InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to mark this action as having completed. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 ); add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 ); $result = wp_update_post( array( 'ID' => $action_id, 'post_status' => 'publish', ), true ); remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 ); remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 ); if ( is_wp_error( $result ) ) { throw new RuntimeException( $result->get_error_message() ); } /** * Fires after a scheduled action has been completed. * * @since 3.4.2 * * @param int $action_id Action ID. */ do_action( 'action_scheduler_completed_action', $action_id ); } /** * Mark action as migrated when there is an error deleting the action. * * @param int $action_id Action ID. */ public function mark_migrated( $action_id ) { wp_update_post( array( 'ID' => $action_id, 'post_status' => 'migrated', ) ); } /** * Determine whether the post store can be migrated. * * @param [type] $setting - Setting value. * @return bool */ public function migration_dependencies_met( $setting ) { global $wpdb; $dependencies_met = get_transient( self::DEPENDENCIES_MET ); if ( empty( $dependencies_met ) ) { $maximum_args_length = apply_filters( 'action_scheduler_maximum_args_length', 191 ); $found_action = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND CHAR_LENGTH(post_content) > %d LIMIT 1", $maximum_args_length, self::POST_TYPE ) ); $dependencies_met = $found_action ? 'no' : 'yes'; set_transient( self::DEPENDENCIES_MET, $dependencies_met, DAY_IN_SECONDS ); } return 'yes' === $dependencies_met ? $setting : false; } /** * InnoDB indexes have a maximum size of 767 bytes by default, which is only 191 characters with utf8mb4. * * Previously, AS wasn't concerned about args length, as we used the (unindex) post_content column. However, * as we prepare to move to custom tables, and can use an indexed VARCHAR column instead, we want to warn * developers of this impending requirement. * * @param ActionScheduler_Action $action Action object. */ protected function validate_action( ActionScheduler_Action $action ) { try { parent::validate_action( $action ); } catch ( Exception $e ) { /* translators: %s is the error message */ $message = sprintf( __( '%s Support for strings longer than this will be removed in a future version.', 'action-scheduler' ), $e->getMessage() ); _doing_it_wrong( 'ActionScheduler_Action::$args', esc_html( $message ), '2.1.0' ); } } /** * (@codeCoverageIgnore) */ public function init() { add_filter( 'action_scheduler_migration_dependencies_met', array( $this, 'migration_dependencies_met' ) ); $post_type_registrar = new ActionScheduler_wpPostStore_PostTypeRegistrar(); $post_type_registrar->register(); $post_status_registrar = new ActionScheduler_wpPostStore_PostStatusRegistrar(); $post_status_registrar->register(); $taxonomy_registrar = new ActionScheduler_wpPostStore_TaxonomyRegistrar(); $taxonomy_registrar->register(); } } vendor/woocommerce/action-scheduler/classes/data-stores/ActionScheduler_wpCommentLogger.php 0000644 00000016571 14720461212 0026463 0 ustar 00 <?php /** * Class ActionScheduler_wpCommentLogger */ class ActionScheduler_wpCommentLogger extends ActionScheduler_Logger { const AGENT = 'ActionScheduler'; const TYPE = 'action_log'; /** * Create log entry. * * @param string $action_id Action ID. * @param string $message Action log's message. * @param DateTime $date Action log's timestamp. * * @return string The log entry ID */ public function log( $action_id, $message, DateTime $date = NULL ) { if ( empty($date) ) { $date = as_get_datetime_object(); } else { $date = as_get_datetime_object( clone $date ); } $comment_id = $this->create_wp_comment( $action_id, $message, $date ); return $comment_id; } /** * Create comment. * * @param int $action_id Action ID. * @param string $message Action log's message. * @param DateTime $date Action log entry's timestamp. */ protected function create_wp_comment( $action_id, $message, DateTime $date ) { $comment_date_gmt = $date->format('Y-m-d H:i:s'); ActionScheduler_TimezoneHelper::set_local_timezone( $date ); $comment_data = array( 'comment_post_ID' => $action_id, 'comment_date' => $date->format('Y-m-d H:i:s'), 'comment_date_gmt' => $comment_date_gmt, 'comment_author' => self::AGENT, 'comment_content' => $message, 'comment_agent' => self::AGENT, 'comment_type' => self::TYPE, ); return wp_insert_comment($comment_data); } /** * Get single log entry for action. * * @param string $entry_id Entry ID. * * @return ActionScheduler_LogEntry */ public function get_entry( $entry_id ) { $comment = $this->get_comment( $entry_id ); if ( empty($comment) || $comment->comment_type != self::TYPE ) { return new ActionScheduler_NullLogEntry(); } $date = as_get_datetime_object( $comment->comment_date_gmt ); ActionScheduler_TimezoneHelper::set_local_timezone( $date ); return new ActionScheduler_LogEntry( $comment->comment_post_ID, $comment->comment_content, $date ); } /** * Get action's logs. * * @param string $action_id Action ID. * * @return ActionScheduler_LogEntry[] */ public function get_logs( $action_id ) { $status = 'all'; if ( get_post_status($action_id) == 'trash' ) { $status = 'post-trashed'; } $comments = get_comments(array( 'post_id' => $action_id, 'orderby' => 'comment_date_gmt', 'order' => 'ASC', 'type' => self::TYPE, 'status' => $status, )); $logs = array(); foreach ( $comments as $c ) { $entry = $this->get_entry( $c ); if ( !empty($entry) ) { $logs[] = $entry; } } return $logs; } /** * Get comment. * * @param int $comment_id Comment ID. */ protected function get_comment( $comment_id ) { return get_comment( $comment_id ); } /** * Filter comment queries. * * @param WP_Comment_Query $query Comment query object. */ public function filter_comment_queries( $query ) { foreach ( array('ID', 'parent', 'post_author', 'post_name', 'post_parent', 'type', 'post_type', 'post_id', 'post_ID') as $key ) { if ( !empty($query->query_vars[$key]) ) { return; // don't slow down queries that wouldn't include action_log comments anyway. } } $query->query_vars['action_log_filter'] = TRUE; add_filter( 'comments_clauses', array( $this, 'filter_comment_query_clauses' ), 10, 2 ); } /** * Filter comment queries. * * @param array $clauses Query's clauses. * @param WP_Comment_Query $query Query object. * * @return array */ public function filter_comment_query_clauses( $clauses, $query ) { if ( !empty($query->query_vars['action_log_filter']) ) { $clauses['where'] .= $this->get_where_clause(); } return $clauses; } /** * Make sure Action Scheduler logs are excluded from comment feeds, which use WP_Query, not * the WP_Comment_Query class handled by @see self::filter_comment_queries(). * * @param string $where Query's `where` clause. * @param WP_Query $query Query object. * * @return string */ public function filter_comment_feed( $where, $query ) { if ( is_comment_feed() ) { $where .= $this->get_where_clause(); } return $where; } /** * Return a SQL clause to exclude Action Scheduler comments. * * @return string */ protected function get_where_clause() { global $wpdb; return sprintf( " AND {$wpdb->comments}.comment_type != '%s'", self::TYPE ); } /** * Remove action log entries from wp_count_comments() * * @param array $stats Comment count. * @param int $post_id Post ID. * * @return object */ public function filter_comment_count( $stats, $post_id ) { global $wpdb; if ( 0 === $post_id ) { $stats = $this->get_comment_count(); } return $stats; } /** * Retrieve the comment counts from our cache, or the database if the cached version isn't set. * * @return object */ protected function get_comment_count() { global $wpdb; $stats = get_transient( 'as_comment_count' ); if ( ! $stats ) { $stats = array(); $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} WHERE comment_type NOT IN('order_note','action_log') GROUP BY comment_approved", ARRAY_A ); $total = 0; $stats = array(); $approved = array( '0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed' ); foreach ( (array) $count as $row ) { // Don't count post-trashed toward totals. if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) { $total += $row['num_comments']; } if ( isset( $approved[ $row['comment_approved'] ] ) ) { $stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments']; } } $stats['total_comments'] = $total; $stats['all'] = $total; foreach ( $approved as $key ) { if ( empty( $stats[ $key ] ) ) { $stats[ $key ] = 0; } } $stats = (object) $stats; set_transient( 'as_comment_count', $stats ); } return $stats; } /** * Delete comment count cache whenever there is new comment or the status of a comment changes. Cache * will be regenerated next time ActionScheduler_wpCommentLogger::filter_comment_count() is called. */ public function delete_comment_count_cache() { delete_transient( 'as_comment_count' ); } /** * Initialize. * * @codeCoverageIgnore */ public function init() { add_action( 'action_scheduler_before_process_queue', array( $this, 'disable_comment_counting' ), 10, 0 ); add_action( 'action_scheduler_after_process_queue', array( $this, 'enable_comment_counting' ), 10, 0 ); parent::init(); add_action( 'pre_get_comments', array( $this, 'filter_comment_queries' ), 10, 1 ); add_action( 'wp_count_comments', array( $this, 'filter_comment_count' ), 20, 2 ); // run after WC_Comments::wp_count_comments() to make sure we exclude order notes and action logs. add_action( 'comment_feed_where', array( $this, 'filter_comment_feed' ), 10, 2 ); // Delete comments count cache whenever there is a new comment or a comment status changes. add_action( 'wp_insert_comment', array( $this, 'delete_comment_count_cache' ) ); add_action( 'wp_set_comment_status', array( $this, 'delete_comment_count_cache' ) ); } /** * Defer comment counting. */ public function disable_comment_counting() { wp_defer_comment_counting(true); } /** * Enable comment counting. */ public function enable_comment_counting() { wp_defer_comment_counting(false); } } vendor/woocommerce/action-scheduler/classes/data-stores/ActionScheduler_DBStore.php 0000644 00000113257 14720461212 0024653 0 ustar 00 <?php /** * Class ActionScheduler_DBStore * * Action data table data store. * * @since 3.0.0 */ class ActionScheduler_DBStore extends ActionScheduler_Store { /** * Used to share information about the before_date property of claims internally. * * This is used in preference to passing the same information as a method param * for backwards-compatibility reasons. * * @var DateTime|null */ private $claim_before_date = null; /** @var int */ protected static $max_args_length = 8000; /** @var int */ protected static $max_index_length = 191; /** @var array List of claim filters. */ protected $claim_filters = [ 'group' => '', 'hooks' => '', 'exclude-groups' => '', ]; /** * Initialize the data store * * @codeCoverageIgnore */ public function init() { $table_maker = new ActionScheduler_StoreSchema(); $table_maker->init(); $table_maker->register_tables(); } /** * Save an action, checks if this is a unique action before actually saving. * * @param ActionScheduler_Action $action Action object. * @param \DateTime $scheduled_date Optional schedule date. Default null. * * @return int Action ID. * @throws RuntimeException Throws exception when saving the action fails. */ public function save_unique_action( ActionScheduler_Action $action, \DateTime $scheduled_date = null ) { return $this->save_action_to_db( $action, $scheduled_date, true ); } /** * Save an action. Can save duplicate action as well, prefer using `save_unique_action` instead. * * @param ActionScheduler_Action $action Action object. * @param \DateTime $scheduled_date Optional schedule date. Default null. * * @return int Action ID. * @throws RuntimeException Throws exception when saving the action fails. */ public function save_action( ActionScheduler_Action $action, \DateTime $scheduled_date = null ) { return $this->save_action_to_db( $action, $scheduled_date, false ); } /** * Save an action. * * @param ActionScheduler_Action $action Action object. * @param ?DateTime $date Optional schedule date. Default null. * @param bool $unique Whether the action should be unique. * * @return int Action ID. * @throws \RuntimeException Throws exception when saving the action fails. */ private function save_action_to_db( ActionScheduler_Action $action, DateTime $date = null, $unique = false ) { global $wpdb; try { $this->validate_action( $action ); $data = array( 'hook' => $action->get_hook(), 'status' => ( $action->is_finished() ? self::STATUS_COMPLETE : self::STATUS_PENDING ), 'scheduled_date_gmt' => $this->get_scheduled_date_string( $action, $date ), 'scheduled_date_local' => $this->get_scheduled_date_string_local( $action, $date ), 'schedule' => serialize( $action->get_schedule() ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize 'group_id' => current( $this->get_group_ids( $action->get_group() ) ), 'priority' => $action->get_priority(), ); $args = wp_json_encode( $action->get_args() ); if ( strlen( $args ) <= static::$max_index_length ) { $data['args'] = $args; } else { $data['args'] = $this->hash_args( $args ); $data['extended_args'] = $args; } $insert_sql = $this->build_insert_sql( $data, $unique ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $insert_sql should be already prepared. $wpdb->query( $insert_sql ); $action_id = $wpdb->insert_id; if ( is_wp_error( $action_id ) ) { throw new \RuntimeException( $action_id->get_error_message() ); } elseif ( empty( $action_id ) ) { if ( $unique ) { return 0; } throw new \RuntimeException( $wpdb->last_error ? $wpdb->last_error : __( 'Database error.', 'action-scheduler' ) ); } do_action( 'action_scheduler_stored_action', $action_id ); return $action_id; } catch ( \Exception $e ) { /* translators: %s: error message */ throw new \RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 ); } } /** * Helper function to build insert query. * * @param array $data Row data for action. * @param bool $unique Whether the action should be unique. * * @return string Insert query. */ private function build_insert_sql( array $data, $unique ) { global $wpdb; $columns = array_keys( $data ); $values = array_values( $data ); $placeholders = array_map( array( $this, 'get_placeholder_for_column' ), $columns ); $table_name = ! empty( $wpdb->actionscheduler_actions ) ? $wpdb->actionscheduler_actions : $wpdb->prefix . 'actionscheduler_actions'; $column_sql = '`' . implode( '`, `', $columns ) . '`'; $placeholder_sql = implode( ', ', $placeholders ); $where_clause = $this->build_where_clause_for_insert( $data, $table_name, $unique ); // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $column_sql and $where_clause are already prepared. $placeholder_sql is hardcoded. $insert_query = $wpdb->prepare( " INSERT INTO $table_name ( $column_sql ) SELECT $placeholder_sql FROM DUAL WHERE ( $where_clause ) IS NULL", $values ); // phpcs:enable return $insert_query; } /** * Helper method to build where clause for action insert statement. * * @param array $data Row data for action. * @param string $table_name Action table name. * @param bool $unique Where action should be unique. * * @return string Where clause to be used with insert. */ private function build_where_clause_for_insert( $data, $table_name, $unique ) { global $wpdb; if ( ! $unique ) { return 'SELECT NULL FROM DUAL'; } $pending_statuses = array( ActionScheduler_Store::STATUS_PENDING, ActionScheduler_Store::STATUS_RUNNING, ); $pending_status_placeholders = implode( ', ', array_fill( 0, count( $pending_statuses ), '%s' ) ); // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- $pending_status_placeholders is hardcoded. $where_clause = $wpdb->prepare( " SELECT action_id FROM $table_name WHERE status IN ( $pending_status_placeholders ) AND hook = %s AND `group_id` = %d ", array_merge( $pending_statuses, array( $data['hook'], $data['group_id'], ) ) ); // phpcs:enable return "$where_clause" . ' LIMIT 1'; } /** * Helper method to get $wpdb->prepare placeholder for a given column name. * * @param string $column_name Name of column in actions table. * * @return string Placeholder to use for given column. */ private function get_placeholder_for_column( $column_name ) { $string_columns = array( 'hook', 'status', 'scheduled_date_gmt', 'scheduled_date_local', 'args', 'schedule', 'last_attempt_gmt', 'last_attempt_local', 'extended_args', ); return in_array( $column_name, $string_columns ) ? '%s' : '%d'; } /** * Generate a hash from json_encoded $args using MD5 as this isn't for security. * * @param string $args JSON encoded action args. * @return string */ protected function hash_args( $args ) { return md5( $args ); } /** * Get action args query param value from action args. * * @param array $args Action args. * @return string */ protected function get_args_for_query( $args ) { $encoded = wp_json_encode( $args ); if ( strlen( $encoded ) <= static::$max_index_length ) { return $encoded; } return $this->hash_args( $encoded ); } /** * Get a group's ID based on its name/slug. * * @param string|array $slugs The string name of a group, or names for several groups. * @param bool $create_if_not_exists Whether to create the group if it does not already exist. Default, true - create the group. * * @return array The group IDs, if they exist or were successfully created. May be empty. */ protected function get_group_ids( $slugs, $create_if_not_exists = true ) { $slugs = (array) $slugs; $group_ids = array(); if ( empty( $slugs ) ) { return array(); } /** @var \wpdb $wpdb */ global $wpdb; foreach ( $slugs as $slug ) { $group_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT group_id FROM {$wpdb->actionscheduler_groups} WHERE slug=%s", $slug ) ); if ( empty( $group_id ) && $create_if_not_exists ) { $group_id = $this->create_group( $slug ); } if ( $group_id ) { $group_ids[] = $group_id; } } return $group_ids; } /** * Create an action group. * * @param string $slug Group slug. * * @return int Group ID. */ protected function create_group( $slug ) { /** @var \wpdb $wpdb */ global $wpdb; $wpdb->insert( $wpdb->actionscheduler_groups, array( 'slug' => $slug ) ); return (int) $wpdb->insert_id; } /** * Retrieve an action. * * @param int $action_id Action ID. * * @return ActionScheduler_Action */ public function fetch_action( $action_id ) { /** @var \wpdb $wpdb */ global $wpdb; $data = $wpdb->get_row( $wpdb->prepare( "SELECT a.*, g.slug AS `group` FROM {$wpdb->actionscheduler_actions} a LEFT JOIN {$wpdb->actionscheduler_groups} g ON a.group_id=g.group_id WHERE a.action_id=%d", $action_id ) ); if ( empty( $data ) ) { return $this->get_null_action(); } if ( ! empty( $data->extended_args ) ) { $data->args = $data->extended_args; unset( $data->extended_args ); } // Convert NULL dates to zero dates. $date_fields = array( 'scheduled_date_gmt', 'scheduled_date_local', 'last_attempt_gmt', 'last_attempt_gmt', ); foreach ( $date_fields as $date_field ) { if ( is_null( $data->$date_field ) ) { $data->$date_field = ActionScheduler_StoreSchema::DEFAULT_DATE; } } try { $action = $this->make_action_from_db_record( $data ); } catch ( ActionScheduler_InvalidActionException $exception ) { do_action( 'action_scheduler_failed_fetch_action', $action_id, $exception ); return $this->get_null_action(); } return $action; } /** * Create a null action. * * @return ActionScheduler_NullAction */ protected function get_null_action() { return new ActionScheduler_NullAction(); } /** * Create an action from a database record. * * @param object $data Action database record. * * @return ActionScheduler_Action|ActionScheduler_CanceledAction|ActionScheduler_FinishedAction */ protected function make_action_from_db_record( $data ) { $hook = $data->hook; $args = json_decode( $data->args, true ); $schedule = unserialize( $data->schedule ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize $this->validate_args( $args, $data->action_id ); $this->validate_schedule( $schedule, $data->action_id ); if ( empty( $schedule ) ) { $schedule = new ActionScheduler_NullSchedule(); } $group = $data->group ? $data->group : ''; return ActionScheduler::factory()->get_stored_action( $data->status, $data->hook, $args, $schedule, $group, $data->priority ); } /** * Returns the SQL statement to query (or count) actions. * * @since 3.3.0 $query['status'] accepts array of statuses instead of a single status. * * @param array $query Filtering options. * @param string $select_or_count Whether the SQL should select and return the IDs or just the row count. * * @return string SQL statement already properly escaped. * @throws \InvalidArgumentException If the query is invalid. * @throws \RuntimeException When "unknown partial args matching value". */ protected function get_query_actions_sql( array $query, $select_or_count = 'select' ) { if ( ! in_array( $select_or_count, array( 'select', 'count' ), true ) ) { throw new InvalidArgumentException( __( 'Invalid value for select or count parameter. Cannot query actions.', 'action-scheduler' ) ); } $query = wp_parse_args( $query, array( 'hook' => '', 'args' => null, 'partial_args_matching' => 'off', // can be 'like' or 'json'. 'date' => null, 'date_compare' => '<=', 'modified' => null, 'modified_compare' => '<=', 'group' => '', 'status' => '', 'claimed' => null, 'per_page' => 5, 'offset' => 0, 'orderby' => 'date', 'order' => 'ASC', ) ); /** @var \wpdb $wpdb */ global $wpdb; $db_server_info = is_callable( array( $wpdb, 'db_server_info' ) ) ? $wpdb->db_server_info() : $wpdb->db_version(); if ( false !== strpos( $db_server_info, 'MariaDB' ) ) { $supports_json = version_compare( PHP_VERSION_ID >= 80016 ? $wpdb->db_version() : preg_replace( '/[^0-9.].*/', '', str_replace( '5.5.5-', '', $db_server_info ) ), '10.2', '>=' ); } else { $supports_json = version_compare( $wpdb->db_version(), '5.7', '>=' ); } $sql = ( 'count' === $select_or_count ) ? 'SELECT count(a.action_id)' : 'SELECT a.action_id'; $sql .= " FROM {$wpdb->actionscheduler_actions} a"; $sql_params = array(); if ( ! empty( $query['group'] ) || 'group' === $query['orderby'] ) { $sql .= " LEFT JOIN {$wpdb->actionscheduler_groups} g ON g.group_id=a.group_id"; } $sql .= ' WHERE 1=1'; if ( ! empty( $query['group'] ) ) { $sql .= ' AND g.slug=%s'; $sql_params[] = $query['group']; } if ( ! empty( $query['hook'] ) ) { $sql .= ' AND a.hook=%s'; $sql_params[] = $query['hook']; } if ( ! is_null( $query['args'] ) ) { switch ( $query['partial_args_matching'] ) { case 'json': if ( ! $supports_json ) { throw new \RuntimeException( __( 'JSON partial matching not supported in your environment. Please check your MySQL/MariaDB version.', 'action-scheduler' ) ); } $supported_types = array( 'integer' => '%d', 'boolean' => '%s', 'double' => '%f', 'string' => '%s', ); foreach ( $query['args'] as $key => $value ) { $value_type = gettype( $value ); if ( 'boolean' === $value_type ) { $value = $value ? 'true' : 'false'; } $placeholder = isset( $supported_types[ $value_type ] ) ? $supported_types[ $value_type ] : false; if ( ! $placeholder ) { throw new \RuntimeException( sprintf( /* translators: %s: provided value type */ __( 'The value type for the JSON partial matching is not supported. Must be either integer, boolean, double or string. %s type provided.', 'action-scheduler' ), $value_type ) ); } $sql .= ' AND JSON_EXTRACT(a.args, %s)=' . $placeholder; $sql_params[] = '$.' . $key; $sql_params[] = $value; } break; case 'like': foreach ( $query['args'] as $key => $value ) { $sql .= ' AND a.args LIKE %s'; $json_partial = $wpdb->esc_like( trim( wp_json_encode( array( $key => $value ) ), '{}' ) ); $sql_params[] = "%{$json_partial}%"; } break; case 'off': $sql .= ' AND a.args=%s'; $sql_params[] = $this->get_args_for_query( $query['args'] ); break; default: throw new \RuntimeException( __( 'Unknown partial args matching value.', 'action-scheduler' ) ); } } if ( $query['status'] ) { $statuses = (array) $query['status']; $placeholders = array_fill( 0, count( $statuses ), '%s' ); $sql .= ' AND a.status IN (' . join( ', ', $placeholders ) . ')'; $sql_params = array_merge( $sql_params, array_values( $statuses ) ); } if ( $query['date'] instanceof \DateTime ) { $date = clone $query['date']; $date->setTimezone( new \DateTimeZone( 'UTC' ) ); $date_string = $date->format( 'Y-m-d H:i:s' ); $comparator = $this->validate_sql_comparator( $query['date_compare'] ); $sql .= " AND a.scheduled_date_gmt $comparator %s"; $sql_params[] = $date_string; } if ( $query['modified'] instanceof \DateTime ) { $modified = clone $query['modified']; $modified->setTimezone( new \DateTimeZone( 'UTC' ) ); $date_string = $modified->format( 'Y-m-d H:i:s' ); $comparator = $this->validate_sql_comparator( $query['modified_compare'] ); $sql .= " AND a.last_attempt_gmt $comparator %s"; $sql_params[] = $date_string; } if ( true === $query['claimed'] ) { $sql .= ' AND a.claim_id != 0'; } elseif ( false === $query['claimed'] ) { $sql .= ' AND a.claim_id = 0'; } elseif ( ! is_null( $query['claimed'] ) ) { $sql .= ' AND a.claim_id = %d'; $sql_params[] = $query['claimed']; } if ( ! empty( $query['search'] ) ) { $sql .= ' AND (a.hook LIKE %s OR (a.extended_args IS NULL AND a.args LIKE %s) OR a.extended_args LIKE %s'; for ( $i = 0; $i < 3; $i++ ) { $sql_params[] = sprintf( '%%%s%%', $query['search'] ); } $search_claim_id = (int) $query['search']; if ( $search_claim_id ) { $sql .= ' OR a.claim_id = %d'; $sql_params[] = $search_claim_id; } $sql .= ')'; } if ( 'select' === $select_or_count ) { if ( 'ASC' === strtoupper( $query['order'] ) ) { $order = 'ASC'; } else { $order = 'DESC'; } switch ( $query['orderby'] ) { case 'hook': $sql .= " ORDER BY a.hook $order"; break; case 'group': $sql .= " ORDER BY g.slug $order"; break; case 'modified': $sql .= " ORDER BY a.last_attempt_gmt $order"; break; case 'none': break; case 'action_id': $sql .= " ORDER BY a.action_id $order"; break; case 'date': default: $sql .= " ORDER BY a.scheduled_date_gmt $order"; break; } if ( $query['per_page'] > 0 ) { $sql .= ' LIMIT %d, %d'; $sql_params[] = $query['offset']; $sql_params[] = $query['per_page']; } } if ( ! empty( $sql_params ) ) { $sql = $wpdb->prepare( $sql, $sql_params ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } return $sql; } /** * Query for action count or list of action IDs. * * @since 3.3.0 $query['status'] accepts array of statuses instead of a single status. * * @see ActionScheduler_Store::query_actions for $query arg usage. * * @param array $query Query filtering options. * @param string $query_type Whether to select or count the results. Defaults to select. * * @return string|array|null The IDs of actions matching the query. Null on failure. */ public function query_actions( $query = array(), $query_type = 'select' ) { /** @var wpdb $wpdb */ global $wpdb; $sql = $this->get_query_actions_sql( $query, $query_type ); return ( 'count' === $query_type ) ? $wpdb->get_var( $sql ) : $wpdb->get_col( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.NoSql, WordPress.DB.DirectDatabaseQuery.NoCaching } /** * Get a count of all actions in the store, grouped by status. * * @return array Set of 'status' => int $count pairs for statuses with 1 or more actions of that status. */ public function action_counts() { global $wpdb; $sql = "SELECT a.status, count(a.status) as 'count'"; $sql .= " FROM {$wpdb->actionscheduler_actions} a"; $sql .= ' GROUP BY a.status'; $actions_count_by_status = array(); $action_stati_and_labels = $this->get_status_labels(); foreach ( $wpdb->get_results( $sql ) as $action_data ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared // Ignore any actions with invalid status. if ( array_key_exists( $action_data->status, $action_stati_and_labels ) ) { $actions_count_by_status[ $action_data->status ] = $action_data->count; } } return $actions_count_by_status; } /** * Cancel an action. * * @param int $action_id Action ID. * * @return void * @throws \InvalidArgumentException If the action update failed. */ public function cancel_action( $action_id ) { /** @var \wpdb $wpdb */ global $wpdb; $updated = $wpdb->update( $wpdb->actionscheduler_actions, array( 'status' => self::STATUS_CANCELED ), array( 'action_id' => $action_id ), array( '%s' ), array( '%d' ) ); if ( false === $updated ) { /* translators: %s: action ID */ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to cancel this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } do_action( 'action_scheduler_canceled_action', $action_id ); } /** * Cancel pending actions by hook. * * @since 3.0.0 * * @param string $hook Hook name. * * @return void */ public function cancel_actions_by_hook( $hook ) { $this->bulk_cancel_actions( array( 'hook' => $hook ) ); } /** * Cancel pending actions by group. * * @param string $group Group slug. * * @return void */ public function cancel_actions_by_group( $group ) { $this->bulk_cancel_actions( array( 'group' => $group ) ); } /** * Bulk cancel actions. * * @since 3.0.0 * * @param array $query_args Query parameters. */ protected function bulk_cancel_actions( $query_args ) { /** @var \wpdb $wpdb */ global $wpdb; if ( ! is_array( $query_args ) ) { return; } // Don't cancel actions that are already canceled. if ( isset( $query_args['status'] ) && self::STATUS_CANCELED === $query_args['status'] ) { return; } $action_ids = true; $query_args = wp_parse_args( $query_args, array( 'per_page' => 1000, 'status' => self::STATUS_PENDING, 'orderby' => 'none', ) ); while ( $action_ids ) { $action_ids = $this->query_actions( $query_args ); if ( empty( $action_ids ) ) { break; } $format = array_fill( 0, count( $action_ids ), '%d' ); $query_in = '(' . implode( ',', $format ) . ')'; $parameters = $action_ids; array_unshift( $parameters, self::STATUS_CANCELED ); $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->actionscheduler_actions} SET status = %s WHERE action_id IN {$query_in}", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $parameters ) ); do_action( 'action_scheduler_bulk_cancel_actions', $action_ids ); } } /** * Delete an action. * * @param int $action_id Action ID. * @throws \InvalidArgumentException If the action deletion failed. */ public function delete_action( $action_id ) { /** @var \wpdb $wpdb */ global $wpdb; $deleted = $wpdb->delete( $wpdb->actionscheduler_actions, array( 'action_id' => $action_id ), array( '%d' ) ); if ( empty( $deleted ) ) { /* translators: %s is the action ID */ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to delete this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } do_action( 'action_scheduler_deleted_action', $action_id ); } /** * Get the schedule date for an action. * * @param string $action_id Action ID. * * @return \DateTime The local date the action is scheduled to run, or the date that it ran. */ public function get_date( $action_id ) { $date = $this->get_date_gmt( $action_id ); ActionScheduler_TimezoneHelper::set_local_timezone( $date ); return $date; } /** * Get the GMT schedule date for an action. * * @param int $action_id Action ID. * * @throws \InvalidArgumentException If action cannot be identified. * @return \DateTime The GMT date the action is scheduled to run, or the date that it ran. */ protected function get_date_gmt( $action_id ) { /** @var \wpdb $wpdb */ global $wpdb; $record = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_actions} WHERE action_id=%d", $action_id ) ); if ( empty( $record ) ) { /* translators: %s is the action ID */ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to determine the date of this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } if ( self::STATUS_PENDING === $record->status ) { return as_get_datetime_object( $record->scheduled_date_gmt ); } else { return as_get_datetime_object( $record->last_attempt_gmt ); } } /** * Stake a claim on actions. * * @param int $max_actions Maximum number of action to include in claim. * @param \DateTime $before_date Jobs must be schedule before this date. Defaults to now. * @param array $hooks Hooks to filter for. * @param string $group Group to filter for. * * @return ActionScheduler_ActionClaim */ public function stake_claim( $max_actions = 10, \DateTime $before_date = null, $hooks = array(), $group = '' ) { $claim_id = $this->generate_claim_id(); $this->claim_before_date = $before_date; $this->claim_actions( $claim_id, $max_actions, $before_date, $hooks, $group ); $action_ids = $this->find_actions_by_claim_id( $claim_id ); $this->claim_before_date = null; return new ActionScheduler_ActionClaim( $claim_id, $action_ids ); } /** * Generate a new action claim. * * @return int Claim ID. */ protected function generate_claim_id() { /** @var \wpdb $wpdb */ global $wpdb; $now = as_get_datetime_object(); $wpdb->insert( $wpdb->actionscheduler_claims, array( 'date_created_gmt' => $now->format( 'Y-m-d H:i:s' ) ) ); return $wpdb->insert_id; } /** * Set a claim filter. * * @param string $filter_name Claim filter name. * @param mixed $filter_values Values to filter. * @return void */ public function set_claim_filter( $filter_name, $filter_values ) { if ( isset( $this->claim_filters[ $filter_name ] ) ) { $this->claim_filters[ $filter_name ] = $filter_values; } } /** * Get the claim filter value. * * @param string $filter_name Claim filter name. * @return mixed */ public function get_claim_filter( $filter_name ) { if ( isset( $this->claim_filters[ $filter_name ] ) ) { return $this->claim_filters[ $filter_name ]; } return ''; } /** * Mark actions claimed. * * @param string $claim_id Claim Id. * @param int $limit Number of action to include in claim. * @param \DateTime $before_date Should use UTC timezone. * @param array $hooks Hooks to filter for. * @param string $group Group to filter for. * * @return int The number of actions that were claimed. * @throws \InvalidArgumentException Throws InvalidArgumentException if group doesn't exist. * @throws \RuntimeException Throws RuntimeException if unable to claim action. */ protected function claim_actions( $claim_id, $limit, \DateTime $before_date = null, $hooks = array(), $group = '' ) { /** @var \wpdb $wpdb */ global $wpdb; $now = as_get_datetime_object(); $date = is_null( $before_date ) ? $now : clone $before_date; // can't use $wpdb->update() because of the <= condition. $update = "UPDATE {$wpdb->actionscheduler_actions} SET claim_id=%d, last_attempt_gmt=%s, last_attempt_local=%s"; $params = array( $claim_id, $now->format( 'Y-m-d H:i:s' ), current_time( 'mysql' ), ); // Set claim filters. if ( ! empty( $hooks ) ) { $this->set_claim_filter( 'hooks', $hooks ); } else { $hooks = $this->get_claim_filter( 'hooks' ); } if ( ! empty( $group ) ) { $this->set_claim_filter( 'group', $group ); } else { $group = $this->get_claim_filter( 'group' ); } $where = 'WHERE claim_id = 0 AND scheduled_date_gmt <= %s AND status=%s'; $params[] = $date->format( 'Y-m-d H:i:s' ); $params[] = self::STATUS_PENDING; if ( ! empty( $hooks ) ) { $placeholders = array_fill( 0, count( $hooks ), '%s' ); $where .= ' AND hook IN (' . join( ', ', $placeholders ) . ')'; $params = array_merge( $params, array_values( $hooks ) ); } $group_operator = 'IN'; if ( empty( $group ) ) { $group = $this->get_claim_filter( 'exclude-groups' ); $group_operator = 'NOT IN'; } if ( ! empty( $group ) ) { $group_ids = $this->get_group_ids( $group, false ); // throw exception if no matching group(s) found, this matches ActionScheduler_wpPostStore's behaviour. if ( empty( $group_ids ) ) { throw new InvalidArgumentException( sprintf( /* translators: %s: group name(s) */ _n( 'The group "%s" does not exist.', 'The groups "%s" do not exist.', is_array( $group ) ? count( $group ) : 1, 'action-scheduler' ), $group ) ); } $id_list = implode( ',', array_map( 'intval', $group_ids ) ); $where .= " AND group_id {$group_operator} ( $id_list )"; } /** * Sets the order-by clause used in the action claim query. * * @since 3.4.0 * * @param string $order_by_sql */ $order = apply_filters( 'action_scheduler_claim_actions_order_by', 'ORDER BY priority ASC, attempts ASC, scheduled_date_gmt ASC, action_id ASC' ); $params[] = $limit; $sql = $wpdb->prepare( "{$update} {$where} {$order} LIMIT %d", $params ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders $rows_affected = $wpdb->query( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching if ( false === $rows_affected ) { $error = empty( $wpdb->last_error ) ? _x( 'unknown', 'database error', 'action-scheduler' ) : $wpdb->last_error; throw new \RuntimeException( sprintf( /* translators: %s database error. */ __( 'Unable to claim actions. Database error: %s.', 'action-scheduler' ), $error ) ); } return (int) $rows_affected; } /** * Get the number of active claims. * * @return int */ public function get_claim_count() { global $wpdb; $sql = "SELECT COUNT(DISTINCT claim_id) FROM {$wpdb->actionscheduler_actions} WHERE claim_id != 0 AND status IN ( %s, %s)"; $sql = $wpdb->prepare( $sql, array( self::STATUS_PENDING, self::STATUS_RUNNING ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared return (int) $wpdb->get_var( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } /** * Return an action's claim ID, as stored in the claim_id column. * * @param string $action_id Action ID. * @return mixed */ public function get_claim_id( $action_id ) { /** @var \wpdb $wpdb */ global $wpdb; $sql = "SELECT claim_id FROM {$wpdb->actionscheduler_actions} WHERE action_id=%d"; $sql = $wpdb->prepare( $sql, $action_id ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared return (int) $wpdb->get_var( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } /** * Retrieve the action IDs of action in a claim. * * @param int $claim_id Claim ID. * @return int[] */ public function find_actions_by_claim_id( $claim_id ) { /** @var \wpdb $wpdb */ global $wpdb; $action_ids = array(); $before_date = isset( $this->claim_before_date ) ? $this->claim_before_date : as_get_datetime_object(); $cut_off = $before_date->format( 'Y-m-d H:i:s' ); $sql = $wpdb->prepare( "SELECT action_id, scheduled_date_gmt FROM {$wpdb->actionscheduler_actions} WHERE claim_id = %d ORDER BY priority ASC, attempts ASC, scheduled_date_gmt ASC, action_id ASC", $claim_id ); // Verify that the scheduled date for each action is within the expected bounds (in some unusual // cases, we cannot depend on MySQL to honor all of the WHERE conditions we specify). foreach ( $wpdb->get_results( $sql ) as $claimed_action ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared if ( $claimed_action->scheduled_date_gmt <= $cut_off ) { $action_ids[] = absint( $claimed_action->action_id ); } } return $action_ids; } /** * Release actions from a claim and delete the claim. * * @param ActionScheduler_ActionClaim $claim Claim object. * @throws \RuntimeException When unable to release actions from claim. */ public function release_claim( ActionScheduler_ActionClaim $claim ) { /** @var \wpdb $wpdb */ global $wpdb; /** * Deadlock warning: This function modifies actions to release them from claims that have been processed. Earlier, we used to it in a atomic query, i.e. we would update all actions belonging to a particular claim_id with claim_id = 0. * While this was functionally correct, it would cause deadlock, since this update query will hold a lock on the claim_id_.. index on the action table. * This allowed the possibility of a race condition, where the claimer query is also running at the same time, then the claimer query will also try to acquire a lock on the claim_id_.. index, and in this case if claim release query has already progressed to the point of acquiring the lock, but have not updated yet, it would cause a deadlock. * * We resolve this by getting all the actions_id that we want to release claim from in a separate query, and then releasing the claim on each of them. This way, our lock is acquired on the action_id index instead of the claim_id index. Note that the lock on claim_id will still be acquired, but it will only when we actually make the update, rather than when we select the actions. */ $action_ids = $wpdb->get_col( $wpdb->prepare( "SELECT action_id FROM {$wpdb->actionscheduler_actions} WHERE claim_id = %d", $claim->get_id() ) ); $row_updates = 0; if ( count( $action_ids ) > 0 ) { $action_id_string = implode( ',', array_map( 'absint', $action_ids ) ); $row_updates = $wpdb->query( "UPDATE {$wpdb->actionscheduler_actions} SET claim_id = 0 WHERE action_id IN ({$action_id_string})" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared } $wpdb->delete( $wpdb->actionscheduler_claims, array( 'claim_id' => $claim->get_id() ), array( '%d' ) ); if ( $row_updates < count( $action_ids ) ) { throw new RuntimeException( sprintf( // translators: %d is an id. __( 'Unable to release actions from claim id %d.', 'action-scheduler' ), $claim->get_id() ) ); } } /** * Remove the claim from an action. * * @param int $action_id Action ID. * * @return void */ public function unclaim_action( $action_id ) { /** @var \wpdb $wpdb */ global $wpdb; $wpdb->update( $wpdb->actionscheduler_actions, array( 'claim_id' => 0 ), array( 'action_id' => $action_id ), array( '%s' ), array( '%d' ) ); } /** * Mark an action as failed. * * @param int $action_id Action ID. * @throws \InvalidArgumentException Throw an exception if action was not updated. */ public function mark_failure( $action_id ) { /** @var \wpdb $wpdb */ global $wpdb; $updated = $wpdb->update( $wpdb->actionscheduler_actions, array( 'status' => self::STATUS_FAILED ), array( 'action_id' => $action_id ), array( '%s' ), array( '%d' ) ); if ( empty( $updated ) ) { /* translators: %s is the action ID */ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to mark this action as having failed. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } } /** * Add execution message to action log. * * @throws Exception If the action status cannot be updated to self::STATUS_RUNNING ('in-progress'). * * @param int $action_id Action ID. * * @return void */ public function log_execution( $action_id ) { /** @var \wpdb $wpdb */ global $wpdb; $sql = "UPDATE {$wpdb->actionscheduler_actions} SET attempts = attempts+1, status=%s, last_attempt_gmt = %s, last_attempt_local = %s WHERE action_id = %d"; $sql = $wpdb->prepare( $sql, self::STATUS_RUNNING, current_time( 'mysql', true ), current_time( 'mysql' ), $action_id ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $status_updated = $wpdb->query( $sql ); if ( ! $status_updated ) { throw new Exception( sprintf( /* translators: 1: action ID. 2: status slug. */ __( 'Unable to update the status of action %1$d to %2$s.', 'action-scheduler' ), $action_id, self::STATUS_RUNNING ) ); } } /** * Mark an action as complete. * * @param int $action_id Action ID. * * @return void * @throws \InvalidArgumentException Throw an exception if action was not updated. */ public function mark_complete( $action_id ) { /** @var \wpdb $wpdb */ global $wpdb; $updated = $wpdb->update( $wpdb->actionscheduler_actions, array( 'status' => self::STATUS_COMPLETE, 'last_attempt_gmt' => current_time( 'mysql', true ), 'last_attempt_local' => current_time( 'mysql' ), ), array( 'action_id' => $action_id ), array( '%s' ), array( '%d' ) ); if ( empty( $updated ) ) { /* translators: %s is the action ID */ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to mark this action as having completed. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } /** * Fires after a scheduled action has been completed. * * @since 3.4.2 * * @param int $action_id Action ID. */ do_action( 'action_scheduler_completed_action', $action_id ); } /** * Get an action's status. * * @param int $action_id Action ID. * * @return string * @throws \InvalidArgumentException Throw an exception if not status was found for action_id. * @throws \RuntimeException Throw an exception if action status could not be retrieved. */ public function get_status( $action_id ) { /** @var \wpdb $wpdb */ global $wpdb; $sql = "SELECT status FROM {$wpdb->actionscheduler_actions} WHERE action_id=%d"; $sql = $wpdb->prepare( $sql, $action_id ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $status = $wpdb->get_var( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared if ( null === $status ) { throw new \InvalidArgumentException( __( 'Invalid action ID. No status found.', 'action-scheduler' ) ); } elseif ( empty( $status ) ) { throw new \RuntimeException( __( 'Unknown status found for action.', 'action-scheduler' ) ); } else { return $status; } } } woocommerce/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_PostTypeRegistrar.php 0000644 00000003446 14720461212 0031333 0 ustar 00 vendor <?php /** * Class ActionScheduler_wpPostStore_PostTypeRegistrar * @codeCoverageIgnore */ class ActionScheduler_wpPostStore_PostTypeRegistrar { /** * Registrar. */ public function register() { register_post_type( ActionScheduler_wpPostStore::POST_TYPE, $this->post_type_args() ); } /** * Build the args array for the post type definition * * @return array */ protected function post_type_args() { $args = array( 'label' => __( 'Scheduled Actions', 'action-scheduler' ), 'description' => __( 'Scheduled actions are hooks triggered on a certain date and time.', 'action-scheduler' ), 'public' => false, 'map_meta_cap' => true, 'hierarchical' => false, 'supports' => array('title', 'editor','comments'), 'rewrite' => false, 'query_var' => false, 'can_export' => true, 'ep_mask' => EP_NONE, 'labels' => array( 'name' => __( 'Scheduled Actions', 'action-scheduler' ), 'singular_name' => __( 'Scheduled Action', 'action-scheduler' ), 'menu_name' => _x( 'Scheduled Actions', 'Admin menu name', 'action-scheduler' ), 'add_new' => __( 'Add', 'action-scheduler' ), 'add_new_item' => __( 'Add New Scheduled Action', 'action-scheduler' ), 'edit' => __( 'Edit', 'action-scheduler' ), 'edit_item' => __( 'Edit Scheduled Action', 'action-scheduler' ), 'new_item' => __( 'New Scheduled Action', 'action-scheduler' ), 'view' => __( 'View Action', 'action-scheduler' ), 'view_item' => __( 'View Action', 'action-scheduler' ), 'search_items' => __( 'Search Scheduled Actions', 'action-scheduler' ), 'not_found' => __( 'No actions found', 'action-scheduler' ), 'not_found_in_trash' => __( 'No actions found in trash', 'action-scheduler' ), ), ); $args = apply_filters('action_scheduler_post_type_args', $args); return $args; } } woocommerce/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_TaxonomyRegistrar.php 0000644 00000001311 14720461212 0031347 0 ustar 00 vendor <?php /** * Class ActionScheduler_wpPostStore_TaxonomyRegistrar * @codeCoverageIgnore */ class ActionScheduler_wpPostStore_TaxonomyRegistrar { /** * Registrar. */ public function register() { register_taxonomy( ActionScheduler_wpPostStore::GROUP_TAXONOMY, ActionScheduler_wpPostStore::POST_TYPE, $this->taxonomy_args() ); } /** * Get taxonomy arguments. */ protected function taxonomy_args() { $args = array( 'label' => __( 'Action Group', 'action-scheduler' ), 'public' => false, 'hierarchical' => false, 'show_admin_column' => true, 'query_var' => false, 'rewrite' => false, ); $args = apply_filters( 'action_scheduler_taxonomy_args', $args ); return $args; } } woocommerce/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_PostStatusRegistrar.php0000644 00000003477 14720461212 0031701 0 ustar 00 vendor <?php /** * Class ActionScheduler_wpPostStore_PostStatusRegistrar * @codeCoverageIgnore */ class ActionScheduler_wpPostStore_PostStatusRegistrar { /** * Registrar. */ public function register() { register_post_status( ActionScheduler_Store::STATUS_RUNNING, array_merge( $this->post_status_args(), $this->post_status_running_labels() ) ); register_post_status( ActionScheduler_Store::STATUS_FAILED, array_merge( $this->post_status_args(), $this->post_status_failed_labels() ) ); } /** * Build the args array for the post type definition * * @return array */ protected function post_status_args() { $args = array( 'public' => false, 'exclude_from_search' => false, 'show_in_admin_all_list' => true, 'show_in_admin_status_list' => true, ); return apply_filters( 'action_scheduler_post_status_args', $args ); } /** * Build the args array for the post type definition * * @return array */ protected function post_status_failed_labels() { $labels = array( 'label' => _x( 'Failed', 'post', 'action-scheduler' ), /* translators: %s: count */ 'label_count' => _n_noop( 'Failed <span class="count">(%s)</span>', 'Failed <span class="count">(%s)</span>', 'action-scheduler' ), ); return apply_filters( 'action_scheduler_post_status_failed_labels', $labels ); } /** * Build the args array for the post type definition * * @return array */ protected function post_status_running_labels() { $labels = array( 'label' => _x( 'In-Progress', 'post', 'action-scheduler' ), /* translators: %s: count */ 'label_count' => _n_noop( 'In-Progress <span class="count">(%s)</span>', 'In-Progress <span class="count">(%s)</span>', 'action-scheduler' ), ); return apply_filters( 'action_scheduler_post_status_running_labels', $labels ); } } vendor/woocommerce/action-scheduler/classes/data-stores/ActionScheduler_DBLogger.php 0000644 00000010600 14720461212 0024762 0 ustar 00 <?php /** * Class ActionScheduler_DBLogger * * Action logs data table data store. * * @since 3.0.0 */ class ActionScheduler_DBLogger extends ActionScheduler_Logger { /** * Add a record to an action log. * * @param int $action_id Action ID. * @param string $message Message to be saved in the log entry. * @param DateTime $date Timestamp of the log entry. * * @return int The log entry ID. */ public function log( $action_id, $message, DateTime $date = null ) { if ( empty( $date ) ) { $date = as_get_datetime_object(); } else { $date = clone $date; } $date_gmt = $date->format( 'Y-m-d H:i:s' ); ActionScheduler_TimezoneHelper::set_local_timezone( $date ); $date_local = $date->format( 'Y-m-d H:i:s' ); /** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort global $wpdb; $wpdb->insert( $wpdb->actionscheduler_logs, array( 'action_id' => $action_id, 'message' => $message, 'log_date_gmt' => $date_gmt, 'log_date_local' => $date_local, ), array( '%d', '%s', '%s', '%s' ) ); return $wpdb->insert_id; } /** * Retrieve an action log entry. * * @param int $entry_id Log entry ID. * * @return ActionScheduler_LogEntry */ public function get_entry( $entry_id ) { /** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort global $wpdb; $entry = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_logs} WHERE log_id=%d", $entry_id ) ); return $this->create_entry_from_db_record( $entry ); } /** * Create an action log entry from a database record. * * @param object $record Log entry database record object. * * @return ActionScheduler_LogEntry */ private function create_entry_from_db_record( $record ) { if ( empty( $record ) ) { return new ActionScheduler_NullLogEntry(); } if ( is_null( $record->log_date_gmt ) ) { $date = as_get_datetime_object( ActionScheduler_StoreSchema::DEFAULT_DATE ); } else { $date = as_get_datetime_object( $record->log_date_gmt ); } return new ActionScheduler_LogEntry( $record->action_id, $record->message, $date ); } /** * Retrieve an action's log entries from the database. * * @param int $action_id Action ID. * * @return ActionScheduler_LogEntry[] */ public function get_logs( $action_id ) { /** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort global $wpdb; $records = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_logs} WHERE action_id=%d", $action_id ) ); return array_map( array( $this, 'create_entry_from_db_record' ), $records ); } /** * Initialize the data store. * * @codeCoverageIgnore */ public function init() { $table_maker = new ActionScheduler_LoggerSchema(); $table_maker->init(); $table_maker->register_tables(); parent::init(); add_action( 'action_scheduler_deleted_action', array( $this, 'clear_deleted_action_logs' ), 10, 1 ); } /** * Delete the action logs for an action. * * @param int $action_id Action ID. */ public function clear_deleted_action_logs( $action_id ) { /** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort global $wpdb; $wpdb->delete( $wpdb->actionscheduler_logs, array( 'action_id' => $action_id ), array( '%d' ) ); } /** * Bulk add cancel action log entries. * * @param array $action_ids List of action ID. */ public function bulk_log_cancel_actions( $action_ids ) { if ( empty( $action_ids ) ) { return; } /** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort global $wpdb; $date = as_get_datetime_object(); $date_gmt = $date->format( 'Y-m-d H:i:s' ); ActionScheduler_TimezoneHelper::set_local_timezone( $date ); $date_local = $date->format( 'Y-m-d H:i:s' ); $message = __( 'action canceled', 'action-scheduler' ); $format = '(%d, ' . $wpdb->prepare( '%s, %s, %s', $message, $date_gmt, $date_local ) . ')'; $sql_query = "INSERT {$wpdb->actionscheduler_logs} (action_id, message, log_date_gmt, log_date_local) VALUES "; $value_rows = array(); foreach ( $action_ids as $action_id ) { $value_rows[] = $wpdb->prepare( $format, $action_id ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } $sql_query .= implode( ',', $value_rows ); $wpdb->query( $sql_query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } } vendor/woocommerce/action-scheduler/classes/data-stores/ActionScheduler_HybridStore.php 0000644 00000030211 14720461212 0025573 0 ustar 00 <?php use ActionScheduler_Store as Store; use Action_Scheduler\Migration\Runner; use Action_Scheduler\Migration\Config; use Action_Scheduler\Migration\Controller; /** * Class ActionScheduler_HybridStore * * A wrapper around multiple stores that fetches data from both. * * @since 3.0.0 */ class ActionScheduler_HybridStore extends Store { const DEMARKATION_OPTION = 'action_scheduler_hybrid_store_demarkation'; /** @var ActionScheduler_Store */ private $primary_store; /** @var ActionScheduler_Store */ private $secondary_store; /** @var Action_Scheduler\Migration\Runner */ private $migration_runner; /** * @var int The dividing line between IDs of actions created * by the primary and secondary stores. * * Methods that accept an action ID will compare the ID against * this to determine which store will contain that ID. In almost * all cases, the ID should come from the primary store, but if * client code is bypassing the API functions and fetching IDs * from elsewhere, then there is a chance that an unmigrated ID * might be requested. */ private $demarkation_id = 0; /** * ActionScheduler_HybridStore constructor. * * @param Config $config Migration config object. */ public function __construct( Config $config = null ) { $this->demarkation_id = (int) get_option( self::DEMARKATION_OPTION, 0 ); if ( empty( $config ) ) { $config = Controller::instance()->get_migration_config_object(); } $this->primary_store = $config->get_destination_store(); $this->secondary_store = $config->get_source_store(); $this->migration_runner = new Runner( $config ); } /** * Initialize the table data store tables. * * @codeCoverageIgnore */ public function init() { add_action( 'action_scheduler/created_table', [ $this, 'set_autoincrement' ], 10, 2 ); $this->primary_store->init(); $this->secondary_store->init(); remove_action( 'action_scheduler/created_table', [ $this, 'set_autoincrement' ], 10 ); } /** * When the actions table is created, set its autoincrement * value to be one higher than the posts table to ensure that * there are no ID collisions. * * @param string $table_name Table name. * @param string $table_suffix Suffix of table name. * * @return void * @codeCoverageIgnore */ public function set_autoincrement( $table_name, $table_suffix ) { if ( ActionScheduler_StoreSchema::ACTIONS_TABLE === $table_suffix ) { if ( empty( $this->demarkation_id ) ) { $this->demarkation_id = $this->set_demarkation_id(); } /** @var \wpdb $wpdb */ global $wpdb; /** * A default date of '0000-00-00 00:00:00' is invalid in MySQL 5.7 when configured with * sql_mode including both STRICT_TRANS_TABLES and NO_ZERO_DATE. */ $default_date = new DateTime( 'tomorrow' ); $null_action = new ActionScheduler_NullAction(); $date_gmt = $this->get_scheduled_date_string( $null_action, $default_date ); $date_local = $this->get_scheduled_date_string_local( $null_action, $default_date ); $row_count = $wpdb->insert( $wpdb->{ActionScheduler_StoreSchema::ACTIONS_TABLE}, [ 'action_id' => $this->demarkation_id, 'hook' => '', 'status' => '', 'scheduled_date_gmt' => $date_gmt, 'scheduled_date_local' => $date_local, 'last_attempt_gmt' => $date_gmt, 'last_attempt_local' => $date_local, ] ); if ( $row_count > 0 ) { $wpdb->delete( $wpdb->{ActionScheduler_StoreSchema::ACTIONS_TABLE}, [ 'action_id' => $this->demarkation_id ] ); } } } /** * Store the demarkation id in WP options. * * @param int $id The ID to set as the demarkation point between the two stores * Leave null to use the next ID from the WP posts table. * * @return int The new ID. * * @codeCoverageIgnore */ private function set_demarkation_id( $id = null ) { if ( empty( $id ) ) { /** @var \wpdb $wpdb */ global $wpdb; $id = (int) $wpdb->get_var( "SELECT MAX(ID) FROM $wpdb->posts" ); $id ++; } update_option( self::DEMARKATION_OPTION, $id ); return $id; } /** * Find the first matching action from the secondary store. * If it exists, migrate it to the primary store immediately. * After it migrates, the secondary store will logically contain * the next matching action, so return the result thence. * * @param string $hook Action's hook. * @param array $params Action's arguments. * * @return string */ public function find_action( $hook, $params = [] ) { $found_unmigrated_action = $this->secondary_store->find_action( $hook, $params ); if ( ! empty( $found_unmigrated_action ) ) { $this->migrate( [ $found_unmigrated_action ] ); } return $this->primary_store->find_action( $hook, $params ); } /** * Find actions matching the query in the secondary source first. * If any are found, migrate them immediately. Then the secondary * store will contain the canonical results. * * @param array $query Query arguments. * @param string $query_type Whether to select or count the results. Default, select. * * @return int[] */ public function query_actions( $query = [], $query_type = 'select' ) { $found_unmigrated_actions = $this->secondary_store->query_actions( $query, 'select' ); if ( ! empty( $found_unmigrated_actions ) ) { $this->migrate( $found_unmigrated_actions ); } return $this->primary_store->query_actions( $query, $query_type ); } /** * Get a count of all actions in the store, grouped by status * * @return array Set of 'status' => int $count pairs for statuses with 1 or more actions of that status. */ public function action_counts() { $unmigrated_actions_count = $this->secondary_store->action_counts(); $migrated_actions_count = $this->primary_store->action_counts(); $actions_count_by_status = array(); foreach ( $this->get_status_labels() as $status_key => $status_label ) { $count = 0; if ( isset( $unmigrated_actions_count[ $status_key ] ) ) { $count += $unmigrated_actions_count[ $status_key ]; } if ( isset( $migrated_actions_count[ $status_key ] ) ) { $count += $migrated_actions_count[ $status_key ]; } $actions_count_by_status[ $status_key ] = $count; } $actions_count_by_status = array_filter( $actions_count_by_status ); return $actions_count_by_status; } /** * If any actions would have been claimed by the secondary store, * migrate them immediately, then ask the primary store for the * canonical claim. * * @param int $max_actions Maximum number of actions to claim. * @param null|DateTime $before_date Latest timestamp of actions to claim. * @param string[] $hooks Hook of actions to claim. * @param string $group Group of actions to claim. * * @return ActionScheduler_ActionClaim */ public function stake_claim( $max_actions = 10, DateTime $before_date = null, $hooks = array(), $group = '' ) { $claim = $this->secondary_store->stake_claim( $max_actions, $before_date, $hooks, $group ); $claimed_actions = $claim->get_actions(); if ( ! empty( $claimed_actions ) ) { $this->migrate( $claimed_actions ); } $this->secondary_store->release_claim( $claim ); return $this->primary_store->stake_claim( $max_actions, $before_date, $hooks, $group ); } /** * Migrate a list of actions to the table data store. * * @param array $action_ids List of action IDs. */ private function migrate( $action_ids ) { $this->migration_runner->migrate_actions( $action_ids ); } /** * Save an action to the primary store. * * @param ActionScheduler_Action $action Action object to be saved. * @param DateTime $date Optional. Schedule date. Default null. * * @return int The action ID */ public function save_action( ActionScheduler_Action $action, DateTime $date = null ) { return $this->primary_store->save_action( $action, $date ); } /** * Retrieve an existing action whether migrated or not. * * @param int $action_id Action ID. */ public function fetch_action( $action_id ) { $store = $this->get_store_from_action_id( $action_id, true ); if ( $store ) { return $store->fetch_action( $action_id ); } else { return new ActionScheduler_NullAction(); } } /** * Cancel an existing action whether migrated or not. * * @param int $action_id Action ID. */ public function cancel_action( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { $store->cancel_action( $action_id ); } } /** * Delete an existing action whether migrated or not. * * @param int $action_id Action ID. */ public function delete_action( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { $store->delete_action( $action_id ); } } /** * Get the schedule date an existing action whether migrated or not. * * @param int $action_id Action ID. */ public function get_date( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { return $store->get_date( $action_id ); } else { return null; } } /** * Mark an existing action as failed whether migrated or not. * * @param int $action_id Action ID. */ public function mark_failure( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { $store->mark_failure( $action_id ); } } /** * Log the execution of an existing action whether migrated or not. * * @param int $action_id Action ID. */ public function log_execution( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { $store->log_execution( $action_id ); } } /** * Mark an existing action complete whether migrated or not. * * @param int $action_id Action ID. */ public function mark_complete( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { $store->mark_complete( $action_id ); } } /** * Get an existing action status whether migrated or not. * * @param int $action_id Action ID. */ public function get_status( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { return $store->get_status( $action_id ); } return null; } /** * Return which store an action is stored in. * * @param int $action_id ID of the action. * @param bool $primary_first Optional flag indicating search the primary store first. * @return ActionScheduler_Store */ protected function get_store_from_action_id( $action_id, $primary_first = false ) { if ( $primary_first ) { $stores = [ $this->primary_store, $this->secondary_store, ]; } elseif ( $action_id < $this->demarkation_id ) { $stores = [ $this->secondary_store, $this->primary_store, ]; } else { $stores = [ $this->primary_store, ]; } foreach ( $stores as $store ) { $action = $store->fetch_action( $action_id ); if ( ! is_a( $action, 'ActionScheduler_NullAction' ) ) { return $store; } } return null; } /** * * * * * * * * * * * * * * * * * * * * * * * * * * * * All claim-related functions should operate solely * on the primary store. * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Get the claim count from the table data store. */ public function get_claim_count() { return $this->primary_store->get_claim_count(); } /** * Retrieve the claim ID for an action from the table data store. * * @param int $action_id Action ID. */ public function get_claim_id( $action_id ) { return $this->primary_store->get_claim_id( $action_id ); } /** * Release a claim in the table data store. * * @param ActionScheduler_ActionClaim $claim Claim object. */ public function release_claim( ActionScheduler_ActionClaim $claim ) { $this->primary_store->release_claim( $claim ); } /** * Release claims on an action in the table data store. * * @param int $action_id Action ID. */ public function unclaim_action( $action_id ) { $this->primary_store->unclaim_action( $action_id ); } /** * Retrieve a list of action IDs by claim. * * @param int $claim_id Claim ID. */ public function find_actions_by_claim_id( $claim_id ) { return $this->primary_store->find_actions_by_claim_id( $claim_id ); } } vendor/woocommerce/action-scheduler/classes/schedules/ActionScheduler_CanceledSchedule.php 0000644 00000002754 14720461212 0026254 0 ustar 00 <?php /** * Class ActionScheduler_SimpleSchedule */ class ActionScheduler_CanceledSchedule extends ActionScheduler_SimpleSchedule { /** * Deprecated property @see $this->__wakeup() for details. * * @var null */ private $timestamp = NULL; /** * @param DateTime $after Timestamp. * * @return DateTime|null */ public function calculate_next( DateTime $after ) { return null; } /** * Cancelled actions should never have a next schedule, even if get_next() * is called with $after < $this->scheduled_date. * * @param DateTime $after Timestamp. * @return DateTime|null */ public function get_next( DateTime $after ) { return null; } /** * @return bool */ public function is_recurring() { return false; } /** * Unserialize recurring schedules serialized/stored prior to AS 3.0.0 * * Prior to Action Scheduler 3.0.0, schedules used different property names to refer * to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0 * aligned properties and property names for better inheritance. To maintain backward * compatibility with schedules serialized and stored prior to 3.0, we need to correctly * map the old property names with matching visibility. */ public function __wakeup() { if ( ! is_null( $this->timestamp ) ) { $this->scheduled_timestamp = $this->timestamp; unset( $this->timestamp ); } parent::__wakeup(); } } vendor/woocommerce/action-scheduler/classes/schedules/ActionScheduler_SimpleSchedule.php 0000644 00000004221 14720461212 0025776 0 ustar 00 <?php /** * Class ActionScheduler_SimpleSchedule */ class ActionScheduler_SimpleSchedule extends ActionScheduler_Abstract_Schedule { /** * Deprecated property @see $this->__wakeup() for details. * * @var null|DateTime */ private $timestamp = NULL; /** * @param DateTime $after Timestamp. * * @return DateTime|null */ public function calculate_next( DateTime $after ) { return null; } /** * @return bool */ public function is_recurring() { return false; } /** * Serialize schedule with data required prior to AS 3.0.0 * * Prior to Action Scheduler 3.0.0, schedules used different property names to refer * to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0 * aligned properties and property names for better inheritance. To guard against the * scheduled date for single actions always being seen as "now" if downgrading to * Action Scheduler < 3.0.0, we need to also store the data with the old property names * so if it's unserialized in AS < 3.0, the schedule doesn't end up with a null recurrence. * * @return array */ public function __sleep() { $sleep_params = parent::__sleep(); $this->timestamp = $this->scheduled_timestamp; return array_merge( $sleep_params, array( 'timestamp', ) ); } /** * Unserialize recurring schedules serialized/stored prior to AS 3.0.0 * * Prior to Action Scheduler 3.0.0, schedules used different property names to refer * to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0 * aligned properties and property names for better inheritance. To maintain backward * compatibility with schedules serialized and stored prior to 3.0, we need to correctly * map the old property names with matching visibility. */ public function __wakeup() { if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->timestamp ) ) { $this->scheduled_timestamp = $this->timestamp; unset( $this->timestamp ); } parent::__wakeup(); } } vendor/woocommerce/action-scheduler/classes/schedules/ActionScheduler_NullSchedule.php 0000644 00000001236 14720461212 0025462 0 ustar 00 <?php /** * Class ActionScheduler_NullSchedule */ class ActionScheduler_NullSchedule extends ActionScheduler_SimpleSchedule { /** @var DateTime|null */ protected $scheduled_date; /** * Make the $date param optional and default to null. * * @param null|DateTime $date The date & time to run the action. */ public function __construct( DateTime $date = null ) { $this->scheduled_date = null; } /** * This schedule has no scheduled DateTime, so we need to override the parent __sleep() * @return array */ public function __sleep() { return array(); } /** * Wakeup. */ public function __wakeup() { $this->scheduled_date = null; } } vendor/woocommerce/action-scheduler/classes/schedules/ActionScheduler_CronSchedule.php 0000644 00000007303 14720461212 0025452 0 ustar 00 <?php /** * Class ActionScheduler_CronSchedule */ class ActionScheduler_CronSchedule extends ActionScheduler_Abstract_RecurringSchedule implements ActionScheduler_Schedule { /** * Deprecated property @see $this->__wakeup() for details. * * @var null */ private $start_timestamp = NULL; /** * Deprecated property @see $this->__wakeup() for details. * * @var null */ private $cron = NULL; /** * Wrapper for parent constructor to accept a cron expression string and map it to a CronExpression for this * objects $recurrence property. * * @param DateTime $start The date & time to run the action at or after. If $start aligns with the CronSchedule passed via $recurrence, it will be used. If it does not align, the first matching date after it will be used. * @param CronExpression|string $recurrence The CronExpression used to calculate the schedule's next instance. * @param DateTime|null $first (Optional) The date & time the first instance of this interval schedule ran. Default null, meaning this is the first instance. */ public function __construct( DateTime $start, $recurrence, DateTime $first = null ) { if ( ! is_a( $recurrence, 'CronExpression' ) ) { $recurrence = CronExpression::factory( $recurrence ); } // For backward compatibility, we need to make sure the date is set to the first matching cron date, not whatever date is passed in. Importantly, by passing true as the 3rd param, if $start matches the cron expression, then it will be used. This was previously handled in the now deprecated next() method. $date = $recurrence->getNextRunDate( $start, 0, true ); // parent::__construct() will set this to $date by default, but that may be different to $start now. $first = empty( $first ) ? $start : $first; parent::__construct( $date, $recurrence, $first ); } /** * Calculate when an instance of this schedule would start based on a given * date & time using its the CronExpression. * * @param DateTime $after Timestamp. * @return DateTime */ protected function calculate_next( DateTime $after ) { return $this->recurrence->getNextRunDate( $after, 0, false ); } /** * @return string */ public function get_recurrence() { return strval( $this->recurrence ); } /** * Serialize cron schedules with data required prior to AS 3.0.0 * * Prior to Action Scheduler 3.0.0, recurring schedules used different property names to * refer to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0 * aligned properties and property names for better inheritance. To guard against the * possibility of infinite loops if downgrading to Action Scheduler < 3.0.0, we need to * also store the data with the old property names so if it's unserialized in AS < 3.0, * the schedule doesn't end up with a null recurrence. * * @return array */ public function __sleep() { $sleep_params = parent::__sleep(); $this->start_timestamp = $this->scheduled_timestamp; $this->cron = $this->recurrence; return array_merge( $sleep_params, array( 'start_timestamp', 'cron' ) ); } /** * Unserialize cron schedules serialized/stored prior to AS 3.0.0 * * For more background, @see ActionScheduler_Abstract_RecurringSchedule::__wakeup(). */ public function __wakeup() { if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->start_timestamp ) ) { $this->scheduled_timestamp = $this->start_timestamp; unset( $this->start_timestamp ); } if ( is_null( $this->recurrence ) && ! is_null( $this->cron ) ) { $this->recurrence = $this->cron; unset( $this->cron ); } parent::__wakeup(); } } vendor/woocommerce/action-scheduler/classes/schedules/ActionScheduler_Schedule.php 0000644 00000000425 14720461212 0024626 0 ustar 00 <?php /** * Class ActionScheduler_Schedule */ interface ActionScheduler_Schedule { /** * @param null|DateTime $after Timestamp. * @return DateTime|null */ public function next( DateTime $after = NULL ); /** * @return bool */ public function is_recurring(); } vendor/woocommerce/action-scheduler/classes/schedules/ActionScheduler_IntervalSchedule.php 0000644 00000005027 14720461212 0026336 0 ustar 00 <?php /** * Class ActionScheduler_IntervalSchedule */ class ActionScheduler_IntervalSchedule extends ActionScheduler_Abstract_RecurringSchedule implements ActionScheduler_Schedule { /** * Deprecated property @see $this->__wakeup() for details. * * @var null */ private $start_timestamp = NULL; /** * Deprecated property @see $this->__wakeup() for details. * * @var null */ private $interval_in_seconds = NULL; /** * Calculate when this schedule should start after a given date & time using * the number of seconds between recurrences. * * @param DateTime $after Timestamp. * @return DateTime */ protected function calculate_next( DateTime $after ) { $after->modify( '+' . (int) $this->get_recurrence() . ' seconds' ); return $after; } /** * @return int */ public function interval_in_seconds() { _deprecated_function( __METHOD__, '3.0.0', '(int)ActionScheduler_Abstract_RecurringSchedule::get_recurrence()' ); return (int) $this->get_recurrence(); } /** * Serialize interval schedules with data required prior to AS 3.0.0 * * Prior to Action Scheduler 3.0.0, recurring schedules used different property names to * refer to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0 * aligned properties and property names for better inheritance. To guard against the * possibility of infinite loops if downgrading to Action Scheduler < 3.0.0, we need to * also store the data with the old property names so if it's unserialized in AS < 3.0, * the schedule doesn't end up with a null/false/0 recurrence. * * @return array */ public function __sleep() { $sleep_params = parent::__sleep(); $this->start_timestamp = $this->scheduled_timestamp; $this->interval_in_seconds = $this->recurrence; return array_merge( $sleep_params, array( 'start_timestamp', 'interval_in_seconds' ) ); } /** * Unserialize interval schedules serialized/stored prior to AS 3.0.0 * * For more background, @see ActionScheduler_Abstract_RecurringSchedule::__wakeup(). */ public function __wakeup() { if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->start_timestamp ) ) { $this->scheduled_timestamp = $this->start_timestamp; unset( $this->start_timestamp ); } if ( is_null( $this->recurrence ) && ! is_null( $this->interval_in_seconds ) ) { $this->recurrence = $this->interval_in_seconds; unset( $this->interval_in_seconds ); } parent::__wakeup(); } } vendor/woocommerce/action-scheduler/classes/abstracts/ActionScheduler.php 0000644 00000024233 14720461212 0023024 0 ustar 00 <?php use Action_Scheduler\WP_CLI\Migration_Command; use Action_Scheduler\Migration\Controller; /** * Class ActionScheduler * @codeCoverageIgnore */ abstract class ActionScheduler { /** @var string */ private static $plugin_file = ''; /** @var ActionScheduler_ActionFactory */ private static $factory = NULL; /** @var bool */ private static $data_store_initialized = false; /** * Factory. */ public static function factory() { if ( !isset(self::$factory) ) { self::$factory = new ActionScheduler_ActionFactory(); } return self::$factory; } /** * Get Store instance. */ public static function store() { return ActionScheduler_Store::instance(); } /** * Get Lock instance. */ public static function lock() { return ActionScheduler_Lock::instance(); } /** * Get Logger instance. */ public static function logger() { return ActionScheduler_Logger::instance(); } /** * Get QueueRunner instance. */ public static function runner() { return ActionScheduler_QueueRunner::instance(); } /** * Get AdminView instance. */ public static function admin_view() { return ActionScheduler_AdminView::instance(); } /** * Get the absolute system path to the plugin directory, or a file therein * @static * @param string $path Path relative to plugin directory. * @return string */ public static function plugin_path( $path ) { $base = dirname(self::$plugin_file); if ( $path ) { return trailingslashit($base) . $path; } else { return untrailingslashit($base); } } /** * Get the absolute URL to the plugin directory, or a file therein * @static * @param string $path Path relative to plugin directory. * @return string */ public static function plugin_url( $path ) { return plugins_url($path, self::$plugin_file); } /** * Autoload. * * @param string $class Class name. */ public static function autoload( $class ) { $d = DIRECTORY_SEPARATOR; $classes_dir = self::plugin_path( 'classes' . $d ); $separator = strrpos( $class, '\\' ); if ( false !== $separator ) { if ( 0 !== strpos( $class, 'Action_Scheduler' ) ) { return; } $class = substr( $class, $separator + 1 ); } if ( 'Deprecated' === substr( $class, -10 ) ) { $dir = self::plugin_path( 'deprecated' . $d ); } elseif ( self::is_class_abstract( $class ) ) { $dir = $classes_dir . 'abstracts' . $d; } elseif ( self::is_class_migration( $class ) ) { $dir = $classes_dir . 'migration' . $d; } elseif ( 'Schedule' === substr( $class, -8 ) ) { $dir = $classes_dir . 'schedules' . $d; } elseif ( 'Action' === substr( $class, -6 ) ) { $dir = $classes_dir . 'actions' . $d; } elseif ( 'Schema' === substr( $class, -6 ) ) { $dir = $classes_dir . 'schema' . $d; } elseif ( strpos( $class, 'ActionScheduler' ) === 0 ) { $segments = explode( '_', $class ); $type = isset( $segments[ 1 ] ) ? $segments[ 1 ] : ''; switch ( $type ) { case 'WPCLI': $dir = $classes_dir . 'WP_CLI' . $d; break; case 'DBLogger': case 'DBStore': case 'HybridStore': case 'wpPostStore': case 'wpCommentLogger': $dir = $classes_dir . 'data-stores' . $d; break; default: $dir = $classes_dir; break; } } elseif ( self::is_class_cli( $class ) ) { $dir = $classes_dir . 'WP_CLI' . $d; } elseif ( strpos( $class, 'CronExpression' ) === 0 ) { $dir = self::plugin_path( 'lib' . $d . 'cron-expression' . $d ); } elseif ( strpos( $class, 'WP_Async_Request' ) === 0 ) { $dir = self::plugin_path( 'lib' . $d ); } else { return; } if ( file_exists( $dir . "{$class}.php" ) ) { include( $dir . "{$class}.php" ); return; } } /** * Initialize the plugin * * @static * @param string $plugin_file Plugin file path. */ public static function init( $plugin_file ) { self::$plugin_file = $plugin_file; spl_autoload_register( array( __CLASS__, 'autoload' ) ); /** * Fires in the early stages of Action Scheduler init hook. */ do_action( 'action_scheduler_pre_init' ); require_once( self::plugin_path( 'functions.php' ) ); ActionScheduler_DataController::init(); $store = self::store(); $logger = self::logger(); $runner = self::runner(); $admin_view = self::admin_view(); // Ensure initialization on plugin activation. if ( ! did_action( 'init' ) ) { // phpcs:ignore Squiz.PHP.CommentedOutCode add_action( 'init', array( $admin_view, 'init' ), 0, 0 ); // run before $store::init(). add_action( 'init', array( $store, 'init' ), 1, 0 ); add_action( 'init', array( $logger, 'init' ), 1, 0 ); add_action( 'init', array( $runner, 'init' ), 1, 0 ); add_action( 'init', /** * Runs after the active store's init() method has been called. * * It would probably be preferable to have $store->init() (or it's parent method) set this itself, * once it has initialized, however that would cause problems in cases where a custom data store is in * use and it has not yet been updated to follow that same logic. */ function () { self::$data_store_initialized = true; /** * Fires when Action Scheduler is ready: it is safe to use the procedural API after this point. * * @since 3.5.5 */ do_action( 'action_scheduler_init' ); }, 1 ); } else { $admin_view->init(); $store->init(); $logger->init(); $runner->init(); self::$data_store_initialized = true; /** * Fires when Action Scheduler is ready: it is safe to use the procedural API after this point. * * @since 3.5.5 */ do_action( 'action_scheduler_init' ); } if ( apply_filters( 'action_scheduler_load_deprecated_functions', true ) ) { require_once( self::plugin_path( 'deprecated/functions.php' ) ); } if ( defined( 'WP_CLI' ) && WP_CLI ) { WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Scheduler_command' ); WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Clean_Command' ); if ( ! ActionScheduler_DataController::is_migration_complete() && Controller::instance()->allow_migration() ) { $command = new Migration_Command(); $command->register(); } } /** * Handle WP comment cleanup after migration. */ if ( is_a( $logger, 'ActionScheduler_DBLogger' ) && ActionScheduler_DataController::is_migration_complete() && ActionScheduler_WPCommentCleaner::has_logs() ) { ActionScheduler_WPCommentCleaner::init(); } add_action( 'action_scheduler/migration_complete', 'ActionScheduler_WPCommentCleaner::maybe_schedule_cleanup' ); } /** * Check whether the AS data store has been initialized. * * @param string $function_name The name of the function being called. Optional. Default `null`. * @return bool */ public static function is_initialized( $function_name = null ) { if ( ! self::$data_store_initialized && ! empty( $function_name ) ) { $message = sprintf( /* translators: %s function name. */ __( '%s() was called before the Action Scheduler data store was initialized', 'action-scheduler' ), esc_attr( $function_name ) ); _doing_it_wrong( $function_name, $message, '3.1.6' ); } return self::$data_store_initialized; } /** * Determine if the class is one of our abstract classes. * * @since 3.0.0 * * @param string $class The class name. * * @return bool */ protected static function is_class_abstract( $class ) { static $abstracts = array( 'ActionScheduler' => true, 'ActionScheduler_Abstract_ListTable' => true, 'ActionScheduler_Abstract_QueueRunner' => true, 'ActionScheduler_Abstract_Schedule' => true, 'ActionScheduler_Abstract_RecurringSchedule' => true, 'ActionScheduler_Lock' => true, 'ActionScheduler_Logger' => true, 'ActionScheduler_Abstract_Schema' => true, 'ActionScheduler_Store' => true, 'ActionScheduler_TimezoneHelper' => true, ); return isset( $abstracts[ $class ] ) && $abstracts[ $class ]; } /** * Determine if the class is one of our migration classes. * * @since 3.0.0 * * @param string $class The class name. * * @return bool */ protected static function is_class_migration( $class ) { static $migration_segments = array( 'ActionMigrator' => true, 'BatchFetcher' => true, 'DBStoreMigrator' => true, 'DryRun' => true, 'LogMigrator' => true, 'Config' => true, 'Controller' => true, 'Runner' => true, 'Scheduler' => true, ); $segments = explode( '_', $class ); $segment = isset( $segments[ 1 ] ) ? $segments[ 1 ] : $class; return isset( $migration_segments[ $segment ] ) && $migration_segments[ $segment ]; } /** * Determine if the class is one of our WP CLI classes. * * @since 3.0.0 * * @param string $class The class name. * * @return bool */ protected static function is_class_cli( $class ) { static $cli_segments = array( 'QueueRunner' => true, 'Command' => true, 'ProgressBar' => true, ); $segments = explode( '_', $class ); $segment = isset( $segments[ 1 ] ) ? $segments[ 1 ] : $class; return isset( $cli_segments[ $segment ] ) && $cli_segments[ $segment ]; } /** * Clone. */ final public function __clone() { trigger_error('Singleton. No cloning allowed!', E_USER_ERROR); } /** * Wakeup. */ final public function __wakeup() { trigger_error('Singleton. No serialization allowed!', E_USER_ERROR); } /** * Construct. */ final private function __construct() {} /** Deprecated **/ /** * Get DateTime object. * * @param null|string $when Date/time string. * @param string $timezone Timezone string. */ public static function get_datetime_object( $when = null, $timezone = 'UTC' ) { _deprecated_function( __METHOD__, '2.0', 'wcs_add_months()' ); return as_get_datetime_object( $when, $timezone ); } /** * Issue deprecated warning if an Action Scheduler function is called in the shutdown hook. * * @param string $function_name The name of the function being called. * @deprecated 3.1.6. */ public static function check_shutdown_hook( $function_name ) { _deprecated_function( __FUNCTION__, '3.1.6' ); } } vendor/woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Abstract_Schedule.php 0000644 00000003516 14720461212 0026464 0 ustar 00 <?php /** * Class ActionScheduler_Abstract_Schedule */ abstract class ActionScheduler_Abstract_Schedule extends ActionScheduler_Schedule_Deprecated { /** * The date & time the schedule is set to run. * * @var DateTime */ private $scheduled_date = NULL; /** * Timestamp equivalent of @see $this->scheduled_date * * @var int */ protected $scheduled_timestamp = NULL; /** * @param DateTime $date The date & time to run the action. */ public function __construct( DateTime $date ) { $this->scheduled_date = $date; } /** * Check if a schedule should recur. * * @return bool */ abstract public function is_recurring(); /** * Calculate when the next instance of this schedule would run based on a given date & time. * * @param DateTime $after Start timestamp. * @return DateTime */ abstract protected function calculate_next( DateTime $after ); /** * Get the next date & time when this schedule should run after a given date & time. * * @param DateTime $after Start timestamp. * @return DateTime|null */ public function get_next( DateTime $after ) { $after = clone $after; if ( $after > $this->scheduled_date ) { $after = $this->calculate_next( $after ); return $after; } return clone $this->scheduled_date; } /** * Get the date & time the schedule is set to run. * * @return DateTime|null */ public function get_date() { return $this->scheduled_date; } /** * For PHP 5.2 compat, since DateTime objects can't be serialized * @return array */ public function __sleep() { $this->scheduled_timestamp = $this->scheduled_date->getTimestamp(); return array( 'scheduled_timestamp', ); } /** * Wakeup. */ public function __wakeup() { $this->scheduled_date = as_get_datetime_object( $this->scheduled_timestamp ); unset( $this->scheduled_timestamp ); } } vendor/woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Abstract_Schema.php 0000644 00000011302 14720461212 0026120 0 ustar 00 <?php /** * Class ActionScheduler_Abstract_Schema * * @package Action_Scheduler * * @codeCoverageIgnore * * Utility class for creating/updating custom tables */ abstract class ActionScheduler_Abstract_Schema { /** * @var int Increment this value in derived class to trigger a schema update. */ protected $schema_version = 1; /** * @var string Schema version stored in database. */ protected $db_version; /** * @var array Names of tables that will be registered by this class. */ protected $tables = array(); /** * Can optionally be used by concrete classes to carry out additional initialization work * as needed. */ public function init() {} /** * Register tables with WordPress, and create them if needed. * * @param bool $force_update Optional. Default false. Use true to always run the schema update. * * @return void */ public function register_tables( $force_update = false ) { global $wpdb; // make WP aware of our tables. foreach ( $this->tables as $table ) { $wpdb->tables[] = $table; $name = $this->get_full_table_name( $table ); $wpdb->$table = $name; } // create the tables. if ( $this->schema_update_required() || $force_update ) { foreach ( $this->tables as $table ) { /** * Allow custom processing before updating a table schema. * * @param string $table Name of table being updated. * @param string $db_version Existing version of the table being updated. */ do_action( 'action_scheduler_before_schema_update', $table, $this->db_version ); $this->update_table( $table ); } $this->mark_schema_update_complete(); } } /** * Get table definition. * * @param string $table The name of the table. * * @return string The CREATE TABLE statement, suitable for passing to dbDelta */ abstract protected function get_table_definition( $table ); /** * Determine if the database schema is out of date * by comparing the integer found in $this->schema_version * with the option set in the WordPress options table * * @return bool */ private function schema_update_required() { $option_name = 'schema-' . static::class; $this->db_version = get_option( $option_name, 0 ); // Check for schema option stored by the Action Scheduler Custom Tables plugin in case site has migrated from that plugin with an older schema. if ( 0 === $this->db_version ) { $plugin_option_name = 'schema-'; switch ( static::class ) { case 'ActionScheduler_StoreSchema': $plugin_option_name .= 'Action_Scheduler\Custom_Tables\DB_Store_Table_Maker'; break; case 'ActionScheduler_LoggerSchema': $plugin_option_name .= 'Action_Scheduler\Custom_Tables\DB_Logger_Table_Maker'; break; } $this->db_version = get_option( $plugin_option_name, 0 ); delete_option( $plugin_option_name ); } return version_compare( $this->db_version, $this->schema_version, '<' ); } /** * Update the option in WordPress to indicate that * our schema is now up to date * * @return void */ private function mark_schema_update_complete() { $option_name = 'schema-' . static::class; // work around race conditions and ensure that our option updates. $value_to_save = (string) $this->schema_version . '.0.' . time(); update_option( $option_name, $value_to_save ); } /** * Update the schema for the given table * * @param string $table The name of the table to update. * * @return void */ private function update_table( $table ) { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $definition = $this->get_table_definition( $table ); if ( $definition ) { $updated = dbDelta( $definition ); foreach ( $updated as $updated_table => $update_description ) { if ( strpos( $update_description, 'Created table' ) === 0 ) { do_action( 'action_scheduler/created_table', $updated_table, $table ); } } } } /** * Get full table name. * * @param string $table Table name. * * @return string The full name of the table, including the * table prefix for the current blog */ protected function get_full_table_name( $table ) { return $GLOBALS['wpdb']->prefix . $table; } /** * Confirms that all of the tables registered by this schema class have been created. * * @return bool */ public function tables_exist() { global $wpdb; $tables_exist = true; foreach ( $this->tables as $table_name ) { $table_name = $wpdb->prefix . $table_name; $pattern = str_replace( '_', '\\_', $table_name ); $existing_table = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $pattern ) ); if ( $existing_table !== $table_name ) { $tables_exist = false; break; } } return $tables_exist; } } vendor/woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Abstract_QueueRunner.php 0000644 00000032371 14720461212 0027207 0 ustar 00 <?php /** * Abstract class with common Queue Cleaner functionality. */ abstract class ActionScheduler_Abstract_QueueRunner extends ActionScheduler_Abstract_QueueRunner_Deprecated { /** @var ActionScheduler_QueueCleaner */ protected $cleaner; /** @var ActionScheduler_FatalErrorMonitor */ protected $monitor; /** @var ActionScheduler_Store */ protected $store; /** * The created time. * * Represents when the queue runner was constructed and used when calculating how long a PHP request has been running. * For this reason it should be as close as possible to the PHP request start time. * * @var int */ private $created_time; /** * ActionScheduler_Abstract_QueueRunner constructor. * * @param ActionScheduler_Store $store Store object. * @param ActionScheduler_FatalErrorMonitor $monitor Monitor object. * @param ActionScheduler_QueueCleaner $cleaner Cleaner object. */ public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null ) { $this->created_time = microtime( true ); $this->store = $store ? $store : ActionScheduler_Store::instance(); $this->monitor = $monitor ? $monitor : new ActionScheduler_FatalErrorMonitor( $this->store ); $this->cleaner = $cleaner ? $cleaner : new ActionScheduler_QueueCleaner( $this->store ); } /** * Process an individual action. * * @param int $action_id The action ID to process. * @param string $context Optional identifier for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron' * Generally, this should be capitalised and not localised as it's a proper noun. * @throws \Exception When error running action. */ public function process_action( $action_id, $context = '' ) { // Temporarily override the error handler while we process the current action. set_error_handler( /** * Temporary error handler which can catch errors and convert them into exceptions. This facilitates more * robust error handling across all supported PHP versions. * * @throws Exception * * @param int $type Error level expressed as an integer. * @param string $message Error message. */ function ( $type, $message ) { throw new Exception( $message ); }, E_USER_ERROR | E_RECOVERABLE_ERROR ); /* * The nested try/catch structure is required because we potentially need to convert thrown errors into * exceptions (and an exception thrown from a catch block cannot be caught by a later catch block in the *same* * structure). */ try { try { $valid_action = false; do_action( 'action_scheduler_before_execute', $action_id, $context ); if ( ActionScheduler_Store::STATUS_PENDING !== $this->store->get_status( $action_id ) ) { do_action( 'action_scheduler_execution_ignored', $action_id, $context ); return; } $valid_action = true; do_action( 'action_scheduler_begin_execute', $action_id, $context ); $action = $this->store->fetch_action( $action_id ); $this->store->log_execution( $action_id ); $action->execute(); do_action( 'action_scheduler_after_execute', $action_id, $action, $context ); $this->store->mark_complete( $action_id ); } catch ( Throwable $e ) { // Throwable is defined when executing under PHP 7.0 and up. We convert it to an exception, for // compatibility with ActionScheduler_Logger. throw new Exception( $e->getMessage(), $e->getCode(), $e ); } } catch ( Exception $e ) { // This catch block exists for compatibility with PHP 5.6. $this->handle_action_error( $action_id, $e, $context, $valid_action ); } finally { restore_error_handler(); } if ( isset( $action ) && is_a( $action, 'ActionScheduler_Action' ) && $action->get_schedule()->is_recurring() ) { $this->schedule_next_instance( $action, $action_id ); } } /** * Marks actions as either having failed execution or failed validation, as appropriate. * * @param int $action_id Action ID. * @param Exception $e Exception instance. * @param string $context Execution context. * @param bool $valid_action If the action is valid. * * @return void */ private function handle_action_error( $action_id, $e, $context, $valid_action ) { if ( $valid_action ) { $this->store->mark_failure( $action_id ); /** * Runs when action execution fails. * * @param int $action_id Action ID. * @param Exception $e Exception instance. * @param string $context Execution context. */ do_action( 'action_scheduler_failed_execution', $action_id, $e, $context ); } else { /** * Runs when action validation fails. * * @param int $action_id Action ID. * @param Exception $e Exception instance. * @param string $context Execution context. */ do_action( 'action_scheduler_failed_validation', $action_id, $e, $context ); } } /** * Schedule the next instance of the action if necessary. * * @param ActionScheduler_Action $action Action. * @param int $action_id Action ID. */ protected function schedule_next_instance( ActionScheduler_Action $action, $action_id ) { // If a recurring action has been consistently failing, we may wish to stop rescheduling it. if ( ActionScheduler_Store::STATUS_FAILED === $this->store->get_status( $action_id ) && $this->recurring_action_is_consistently_failing( $action, $action_id ) ) { ActionScheduler_Logger::instance()->log( $action_id, __( 'This action appears to be consistently failing. A new instance will not be scheduled.', 'action-scheduler' ) ); return; } try { ActionScheduler::factory()->repeat( $action ); } catch ( Exception $e ) { do_action( 'action_scheduler_failed_to_schedule_next_instance', $action_id, $e, $action ); } } /** * Determine if the specified recurring action has been consistently failing. * * @param ActionScheduler_Action $action The recurring action to be rescheduled. * @param int $action_id The ID of the recurring action. * * @return bool */ private function recurring_action_is_consistently_failing( ActionScheduler_Action $action, $action_id ) { /** * Controls the failure threshold for recurring actions. * * Before rescheduling a recurring action, we look at its status. If it failed, we then check if all of the most * recent actions (upto the threshold set by this filter) sharing the same hook have also failed: if they have, * that is considered consistent failure and a new instance of the action will not be scheduled. * * @param int $failure_threshold Number of actions of the same hook to examine for failure. Defaults to 5. */ $consistent_failure_threshold = (int) apply_filters( 'action_scheduler_recurring_action_failure_threshold', 5 ); // This query should find the earliest *failing* action (for the hook we are interested in) within our threshold. $query_args = array( 'hook' => $action->get_hook(), 'status' => ActionScheduler_Store::STATUS_FAILED, 'date' => date_create( 'now', timezone_open( 'UTC' ) )->format( 'Y-m-d H:i:s' ), 'date_compare' => '<', 'per_page' => 1, 'offset' => $consistent_failure_threshold - 1 ); $first_failing_action_id = $this->store->query_actions( $query_args ); // If we didn't retrieve an action ID, then there haven't been enough failures for us to worry about. if ( empty( $first_failing_action_id ) ) { return false; } // Now let's fetch the first action (having the same hook) of *any status* within the same window. unset( $query_args['status'] ); $first_action_id_with_the_same_hook = $this->store->query_actions( $query_args ); /** * If a recurring action is assessed as consistently failing, it will not be rescheduled. This hook provides a * way to observe and optionally override that assessment. * * @param bool $is_consistently_failing If the action is considered to be consistently failing. * @param ActionScheduler_Action $action The action being assessed. */ return (bool) apply_filters( 'action_scheduler_recurring_action_is_consistently_failing', $first_action_id_with_the_same_hook === $first_failing_action_id, $action ); } /** * Run the queue cleaner. * * @author Jeremy Pry */ protected function run_cleanup() { $this->cleaner->clean( 10 * $this->get_time_limit() ); } /** * Get the number of concurrent batches a runner allows. * * @return int */ public function get_allowed_concurrent_batches() { return apply_filters( 'action_scheduler_queue_runner_concurrent_batches', 1 ); } /** * Check if the number of allowed concurrent batches is met or exceeded. * * @return bool */ public function has_maximum_concurrent_batches() { return $this->store->get_claim_count() >= $this->get_allowed_concurrent_batches(); } /** * Get the maximum number of seconds a batch can run for. * * @return int The number of seconds. */ protected function get_time_limit() { $time_limit = 30; // Apply deprecated filter from deprecated get_maximum_execution_time() method. if ( has_filter( 'action_scheduler_maximum_execution_time' ) ) { _deprecated_function( 'action_scheduler_maximum_execution_time', '2.1.1', 'action_scheduler_queue_runner_time_limit' ); $time_limit = apply_filters( 'action_scheduler_maximum_execution_time', $time_limit ); } return absint( apply_filters( 'action_scheduler_queue_runner_time_limit', $time_limit ) ); } /** * Get the number of seconds the process has been running. * * @return int The number of seconds. */ protected function get_execution_time() { $execution_time = microtime( true ) - $this->created_time; // Get the CPU time if the hosting environment uses it rather than wall-clock time to calculate a process's execution time. if ( function_exists( 'getrusage' ) && apply_filters( 'action_scheduler_use_cpu_execution_time', defined( 'PANTHEON_ENVIRONMENT' ) ) ) { $resource_usages = getrusage(); if ( isset( $resource_usages['ru_stime.tv_usec'], $resource_usages['ru_stime.tv_usec'] ) ) { $execution_time = $resource_usages['ru_stime.tv_sec'] + ( $resource_usages['ru_stime.tv_usec'] / 1000000 ); } } return $execution_time; } /** * Check if the host's max execution time is (likely) to be exceeded if processing more actions. * * @param int $processed_actions The number of actions processed so far - used to determine the likelihood of exceeding the time limit if processing another action. * @return bool */ protected function time_likely_to_be_exceeded( $processed_actions ) { $execution_time = $this->get_execution_time(); $max_execution_time = $this->get_time_limit(); // Safety against division by zero errors. if ( 0 === $processed_actions ) { return $execution_time >= $max_execution_time; } $time_per_action = $execution_time / $processed_actions; $estimated_time = $execution_time + ( $time_per_action * 3 ); $likely_to_be_exceeded = $estimated_time > $max_execution_time; return apply_filters( 'action_scheduler_maximum_execution_time_likely_to_be_exceeded', $likely_to_be_exceeded, $this, $processed_actions, $execution_time, $max_execution_time ); } /** * Get memory limit * * Based on WP_Background_Process::get_memory_limit() * * @return int */ protected function get_memory_limit() { if ( function_exists( 'ini_get' ) ) { $memory_limit = ini_get( 'memory_limit' ); } else { $memory_limit = '128M'; // Sensible default, and minimum required by WooCommerce. } if ( ! $memory_limit || -1 === $memory_limit || '-1' === $memory_limit ) { // Unlimited, set to 32GB. $memory_limit = '32G'; } return ActionScheduler_Compatibility::convert_hr_to_bytes( $memory_limit ); } /** * Memory exceeded * * Ensures the batch process never exceeds 90% of the maximum WordPress memory. * * Based on WP_Background_Process::memory_exceeded() * * @return bool */ protected function memory_exceeded() { $memory_limit = $this->get_memory_limit() * 0.90; $current_memory = memory_get_usage( true ); $memory_exceeded = $current_memory >= $memory_limit; return apply_filters( 'action_scheduler_memory_exceeded', $memory_exceeded, $this ); } /** * See if the batch limits have been exceeded, which is when memory usage is almost at * the maximum limit, or the time to process more actions will exceed the max time limit. * * Based on WC_Background_Process::batch_limits_exceeded() * * @param int $processed_actions The number of actions processed so far - used to determine the likelihood of exceeding the time limit if processing another action. * @return bool */ protected function batch_limits_exceeded( $processed_actions ) { return $this->memory_exceeded() || $this->time_likely_to_be_exceeded( $processed_actions ); } /** * Process actions in the queue. * * @author Jeremy Pry * @param string $context Optional identifier for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron' * Generally, this should be capitalised and not localised as it's a proper noun. * @return int The number of actions processed. */ abstract public function run( $context = '' ); } vendor/woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Abstract_RecurringSchedule.php0000644 00000006163 14720461212 0030346 0 ustar 00 <?php /** * Class ActionScheduler_Abstract_RecurringSchedule */ abstract class ActionScheduler_Abstract_RecurringSchedule extends ActionScheduler_Abstract_Schedule { /** * The date & time the first instance of this schedule was setup to run (which may not be this instance). * * Schedule objects are attached to an action object. Each schedule stores the run date for that * object as the start date - @see $this->start - and logic to calculate the next run date after * that - @see $this->calculate_next(). The $first_date property also keeps a record of when the very * first instance of this chain of schedules ran. * * @var DateTime */ private $first_date = NULL; /** * Timestamp equivalent of @see $this->first_date * * @var int */ protected $first_timestamp = NULL; /** * The recurrence between each time an action is run using this schedule. * Used to calculate the start date & time. Can be a number of seconds, in the * case of ActionScheduler_IntervalSchedule, or a cron expression, as in the * case of ActionScheduler_CronSchedule. Or something else. * * @var mixed */ protected $recurrence; /** * @param DateTime $date The date & time to run the action. * @param mixed $recurrence The data used to determine the schedule's recurrence. * @param DateTime|null $first (Optional) The date & time the first instance of this interval schedule ran. Default null, meaning this is the first instance. */ public function __construct( DateTime $date, $recurrence, DateTime $first = null ) { parent::__construct( $date ); $this->first_date = empty( $first ) ? $date : $first; $this->recurrence = $recurrence; } /** * @return bool */ public function is_recurring() { return true; } /** * Get the date & time of the first schedule in this recurring series. * * @return DateTime|null */ public function get_first_date() { return clone $this->first_date; } /** * @return string */ public function get_recurrence() { return $this->recurrence; } /** * For PHP 5.2 compat, since DateTime objects can't be serialized * @return array */ public function __sleep() { $sleep_params = parent::__sleep(); $this->first_timestamp = $this->first_date->getTimestamp(); return array_merge( $sleep_params, array( 'first_timestamp', 'recurrence' ) ); } /** * Unserialize recurring schedules serialized/stored prior to AS 3.0.0 * * Prior to Action Scheduler 3.0.0, schedules used different property names to refer * to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp * was the same as ActionScheduler_SimpleSchedule::timestamp. This was addressed in * Action Scheduler 3.0.0, where properties and property names were aligned for better * inheritance. To maintain backward compatibility with scheduled serialized and stored * prior to 3.0, we need to correctly map the old property names. */ public function __wakeup() { parent::__wakeup(); if ( $this->first_timestamp > 0 ) { $this->first_date = as_get_datetime_object( $this->first_timestamp ); } else { $this->first_date = $this->get_date(); } } } vendor/woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Abstract_ListTable.php 0000644 00000061057 14720461212 0026617 0 ustar 00 <?php if ( ! class_exists( 'WP_List_Table' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php'; } /** * Action Scheduler Abstract List Table class * * This abstract class enhances WP_List_Table making it ready to use. * * By extending this class we can focus on describing how our table looks like, * which columns needs to be shown, filter, ordered by and more and forget about the details. * * This class supports: * - Bulk actions * - Search * - Sortable columns * - Automatic translations of the columns * * @codeCoverageIgnore * @since 2.0.0 */ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table { /** * The table name * * @var string */ protected $table_name; /** * Package name, used to get options from WP_List_Table::get_items_per_page. * * @var string */ protected $package; /** * How many items do we render per page? * * @var int */ protected $items_per_page = 10; /** * Enables search in this table listing. If this array * is empty it means the listing is not searchable. * * @var array */ protected $search_by = array(); /** * Columns to show in the table listing. It is a key => value pair. The * key must much the table column name and the value is the label, which is * automatically translated. * * @var array */ protected $columns = array(); /** * Defines the row-actions. It expects an array where the key * is the column name and the value is an array of actions. * * The array of actions are key => value, where key is the method name * (with the prefix row_action_<key>) and the value is the label * and title. * * @var array */ protected $row_actions = array(); /** * The Primary key of our table * * @var string */ protected $ID = 'ID'; /** * Enables sorting, it expects an array * of columns (the column names are the values) * * @var array */ protected $sort_by = array(); /** * The default sort order * * @var string */ protected $filter_by = array(); /** * The status name => count combinations for this table's items. Used to display status filters. * * @var array */ protected $status_counts = array(); /** * Notices to display when loading the table. Array of arrays of form array( 'class' => {updated|error}, 'message' => 'This is the notice text display.' ). * * @var array */ protected $admin_notices = array(); /** * Localised string displayed in the <h1> element above the able. * * @var string */ protected $table_header; /** * Enables bulk actions. It must be an array where the key is the action name * and the value is the label (which is translated automatically). It is important * to notice that it will check that the method exists (`bulk_$name`) and will throw * an exception if it does not exists. * * This class will automatically check if the current request has a bulk action, will do the * validations and afterwards will execute the bulk method, with two arguments. The first argument * is the array with primary keys, the second argument is a string with a list of the primary keys, * escaped and ready to use (with `IN`). * * @var array */ protected $bulk_actions = array(); /** * Makes translation easier, it basically just wraps * `_x` with some default (the package name). * * @param string $text The new text to translate. * @param string $context The context of the text. * @return string|void The translated text. * * @deprecated 3.0.0 Use `_x()` instead. */ protected function translate( $text, $context = '' ) { return $text; } /** * Reads `$this->bulk_actions` and returns an array that WP_List_Table understands. It * also validates that the bulk method handler exists. It throws an exception because * this is a library meant for developers and missing a bulk method is a development-time error. * * @return array * * @throws RuntimeException Throws RuntimeException when the bulk action does not have a callback method. */ protected function get_bulk_actions() { $actions = array(); foreach ( $this->bulk_actions as $action => $label ) { if ( ! is_callable( array( $this, 'bulk_' . $action ) ) ) { throw new RuntimeException( "The bulk action $action does not have a callback method" ); } $actions[ $action ] = $label; } return $actions; } /** * Checks if the current request has a bulk action. If that is the case it will validate and will * execute the bulk method handler. Regardless if the action is valid or not it will redirect to * the previous page removing the current arguments that makes this request a bulk action. */ protected function process_bulk_action() { global $wpdb; // Detect when a bulk action is being triggered. $action = $this->current_action(); if ( ! $action ) { return; } check_admin_referer( 'bulk-' . $this->_args['plural'] ); $method = 'bulk_' . $action; if ( array_key_exists( $action, $this->bulk_actions ) && is_callable( array( $this, $method ) ) && ! empty( $_GET['ID'] ) && is_array( $_GET['ID'] ) ) { $ids_sql = '(' . implode( ',', array_fill( 0, count( $_GET['ID'] ), '%s' ) ) . ')'; $id = array_map( 'absint', $_GET['ID'] ); $this->$method( $id, $wpdb->prepare( $ids_sql, $id ) ); //phpcs:ignore WordPress.DB.PreparedSQL } if ( isset( $_SERVER['REQUEST_URI'] ) ) { wp_safe_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce', 'ID', 'action', 'action2' ), esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ); exit; } } /** * Default code for deleting entries. * validated already by process_bulk_action() * * @param array $ids ids of the items to delete. * @param string $ids_sql the sql for the ids. * @return void */ protected function bulk_delete( array $ids, $ids_sql ) { $store = ActionScheduler::store(); foreach ( $ids as $action_id ) { $store->delete( $action_id ); } } /** * Prepares the _column_headers property which is used by WP_Table_List at rendering. * It merges the columns and the sortable columns. */ protected function prepare_column_headers() { $this->_column_headers = array( $this->get_columns(), get_hidden_columns( $this->screen ), $this->get_sortable_columns(), ); } /** * Reads $this->sort_by and returns the columns name in a format that WP_Table_List * expects */ public function get_sortable_columns() { $sort_by = array(); foreach ( $this->sort_by as $column ) { $sort_by[ $column ] = array( $column, true ); } return $sort_by; } /** * Returns the columns names for rendering. It adds a checkbox for selecting everything * as the first column */ public function get_columns() { $columns = array_merge( array( 'cb' => '<input type="checkbox" />' ), $this->columns ); return $columns; } /** * Get prepared LIMIT clause for items query * * @global wpdb $wpdb * * @return string Prepared LIMIT clause for items query. */ protected function get_items_query_limit() { global $wpdb; $per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page ); return $wpdb->prepare( 'LIMIT %d', $per_page ); } /** * Returns the number of items to offset/skip for this current view. * * @return int */ protected function get_items_offset() { $per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page ); $current_page = $this->get_pagenum(); if ( 1 < $current_page ) { $offset = $per_page * ( $current_page - 1 ); } else { $offset = 0; } return $offset; } /** * Get prepared OFFSET clause for items query * * @global wpdb $wpdb * * @return string Prepared OFFSET clause for items query. */ protected function get_items_query_offset() { global $wpdb; return $wpdb->prepare( 'OFFSET %d', $this->get_items_offset() ); } /** * Prepares the ORDER BY sql statement. It uses `$this->sort_by` to know which * columns are sortable. This requests validates the orderby $_GET parameter is a valid * column and sortable. It will also use order (ASC|DESC) using DESC by default. */ protected function get_items_query_order() { if ( empty( $this->sort_by ) ) { return ''; } $orderby = esc_sql( $this->get_request_orderby() ); $order = esc_sql( $this->get_request_order() ); return "ORDER BY {$orderby} {$order}"; } /** * Querystring arguments to persist between form submissions. * * @since 3.7.3 * * @return string[] */ protected function get_request_query_args_to_persist() { return array_merge( $this->sort_by, array( 'page', 'status', 'tab', ) ); } /** * Return the sortable column specified for this request to order the results by, if any. * * @return string */ protected function get_request_orderby() { $valid_sortable_columns = array_values( $this->sort_by ); if ( ! empty( $_GET['orderby'] ) && in_array( $_GET['orderby'], $valid_sortable_columns, true ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended $orderby = sanitize_text_field( wp_unslash( $_GET['orderby'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended } else { $orderby = $valid_sortable_columns[0]; } return $orderby; } /** * Return the sortable column order specified for this request. * * @return string */ protected function get_request_order() { if ( ! empty( $_GET['order'] ) && 'desc' === strtolower( sanitize_text_field( wp_unslash( $_GET['order'] ) ) ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended $order = 'DESC'; } else { $order = 'ASC'; } return $order; } /** * Return the status filter for this request, if any. * * @return string */ protected function get_request_status() { $status = ( ! empty( $_GET['status'] ) ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended return $status; } /** * Return the search filter for this request, if any. * * @return string */ protected function get_request_search_query() { $search_query = ( ! empty( $_GET['s'] ) ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended return $search_query; } /** * Process and return the columns name. This is meant for using with SQL, this means it * always includes the primary key. * * @return array */ protected function get_table_columns() { $columns = array_keys( $this->columns ); if ( ! in_array( $this->ID, $columns, true ) ) { $columns[] = $this->ID; } return $columns; } /** * Check if the current request is doing a "full text" search. If that is the case * prepares the SQL to search texts using LIKE. * * If the current request does not have any search or if this list table does not support * that feature it will return an empty string. * * @return string */ protected function get_items_query_search() { global $wpdb; if ( empty( $_GET['s'] ) || empty( $this->search_by ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended return ''; } $search_string = sanitize_text_field( wp_unslash( $_GET['s'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended $filter = array(); foreach ( $this->search_by as $column ) { $wild = '%'; $sql_like = $wild . $wpdb->esc_like( $search_string ) . $wild; $filter[] = $wpdb->prepare( '`' . $column . '` LIKE %s', $sql_like ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.DB.PreparedSQL.NotPrepared } return implode( ' OR ', $filter ); } /** * Prepares the SQL to filter rows by the options defined at `$this->filter_by`. Before trusting * any data sent by the user it validates that it is a valid option. */ protected function get_items_query_filters() { global $wpdb; if ( ! $this->filter_by || empty( $_GET['filter_by'] ) || ! is_array( $_GET['filter_by'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended return ''; } $filter = array(); foreach ( $this->filter_by as $column => $options ) { if ( empty( $_GET['filter_by'][ $column ] ) || empty( $options[ $_GET['filter_by'][ $column ] ] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended continue; } $filter[] = $wpdb->prepare( "`$column` = %s", sanitize_text_field( wp_unslash( $_GET['filter_by'][ $column ] ) ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.DB.PreparedSQL.InterpolatedNotPrepared } return implode( ' AND ', $filter ); } /** * Prepares the data to feed WP_Table_List. * * This has the core for selecting, sorting and filtering data. To keep the code simple * its logic is split among many methods (get_items_query_*). * * Beside populating the items this function will also count all the records that matches * the filtering criteria and will do fill the pagination variables. */ public function prepare_items() { global $wpdb; $this->process_bulk_action(); $this->process_row_actions(); if ( ! empty( $_REQUEST['_wp_http_referer'] && ! empty( $_SERVER['REQUEST_URI'] ) ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended // _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter wp_safe_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ); exit; } $this->prepare_column_headers(); $limit = $this->get_items_query_limit(); $offset = $this->get_items_query_offset(); $order = $this->get_items_query_order(); $where = array_filter( array( $this->get_items_query_search(), $this->get_items_query_filters(), ) ); $columns = '`' . implode( '`, `', $this->get_table_columns() ) . '`'; if ( ! empty( $where ) ) { $where = 'WHERE (' . implode( ') AND (', $where ) . ')'; } else { $where = ''; } $sql = "SELECT $columns FROM {$this->table_name} {$where} {$order} {$limit} {$offset}"; $this->set_items( $wpdb->get_results( $sql, ARRAY_A ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $query_count = "SELECT COUNT({$this->ID}) FROM {$this->table_name} {$where}"; $total_items = $wpdb->get_var( $query_count ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page ); $this->set_pagination_args( array( 'total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil( $total_items / $per_page ), ) ); } /** * Display the table. * * @param string $which The name of the table. */ public function extra_tablenav( $which ) { if ( ! $this->filter_by || 'top' !== $which ) { return; } echo '<div class="alignleft actions">'; foreach ( $this->filter_by as $id => $options ) { $default = ! empty( $_GET['filter_by'][ $id ] ) ? sanitize_text_field( wp_unslash( $_GET['filter_by'][ $id ] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( empty( $options[ $default ] ) ) { $default = ''; } echo '<select name="filter_by[' . esc_attr( $id ) . ']" class="first" id="filter-by-' . esc_attr( $id ) . '">'; foreach ( $options as $value => $label ) { echo '<option value="' . esc_attr( $value ) . '" ' . esc_html( $value === $default ? 'selected' : '' ) . '>' . esc_html( $label ) . '</option>'; } echo '</select>'; } submit_button( esc_html__( 'Filter', 'action-scheduler' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) ); echo '</div>'; } /** * Set the data for displaying. It will attempt to unserialize (There is a chance that some columns * are serialized). This can be override in child classes for further data transformation. * * @param array $items Items array. */ protected function set_items( array $items ) { $this->items = array(); foreach ( $items as $item ) { $this->items[ $item[ $this->ID ] ] = array_map( 'maybe_unserialize', $item ); } } /** * Renders the checkbox for each row, this is the first column and it is named ID regardless * of how the primary key is named (to keep the code simpler). The bulk actions will do the proper * name transformation though using `$this->ID`. * * @param array $row The row to render. */ public function column_cb( $row ) { return '<input name="ID[]" type="checkbox" value="' . esc_attr( $row[ $this->ID ] ) . '" />'; } /** * Renders the row-actions. * * This method renders the action menu, it reads the definition from the $row_actions property, * and it checks that the row action method exists before rendering it. * * @param array $row Row to be rendered. * @param string $column_name Column name. * @return string */ protected function maybe_render_actions( $row, $column_name ) { if ( empty( $this->row_actions[ $column_name ] ) ) { return; } $row_id = $row[ $this->ID ]; $actions = '<div class="row-actions">'; $action_count = 0; foreach ( $this->row_actions[ $column_name ] as $action_key => $action ) { $action_count++; if ( ! method_exists( $this, 'row_action_' . $action_key ) ) { continue; } $action_link = ! empty( $action['link'] ) ? $action['link'] : add_query_arg( array( 'row_action' => $action_key, 'row_id' => $row_id, 'nonce' => wp_create_nonce( $action_key . '::' . $row_id ), ) ); $span_class = ! empty( $action['class'] ) ? $action['class'] : $action_key; $separator = ( $action_count < count( $this->row_actions[ $column_name ] ) ) ? ' | ' : ''; $actions .= sprintf( '<span class="%s">', esc_attr( $span_class ) ); $actions .= sprintf( '<a href="%1$s" title="%2$s">%3$s</a>', esc_url( $action_link ), esc_attr( $action['desc'] ), esc_html( $action['name'] ) ); $actions .= sprintf( '%s</span>', $separator ); } $actions .= '</div>'; return $actions; } /** * Process the bulk actions. * * @return void */ protected function process_row_actions() { $parameters = array( 'row_action', 'row_id', 'nonce' ); foreach ( $parameters as $parameter ) { if ( empty( $_REQUEST[ $parameter ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended return; } } $action = sanitize_text_field( wp_unslash( $_REQUEST['row_action'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated $row_id = sanitize_text_field( wp_unslash( $_REQUEST['row_id'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated $nonce = sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated $method = 'row_action_' . $action; // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( wp_verify_nonce( $nonce, $action . '::' . $row_id ) && method_exists( $this, $method ) ) { $this->$method( sanitize_text_field( wp_unslash( $row_id ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended } if ( isset( $_SERVER['REQUEST_URI'] ) ) { wp_safe_redirect( remove_query_arg( array( 'row_id', 'row_action', 'nonce' ), esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ); exit; } } /** * Default column formatting, it will escape everything for security. * * @param array $item The item array. * @param string $column_name Column name to display. * * @return string */ public function column_default( $item, $column_name ) { $column_html = esc_html( $item[ $column_name ] ); $column_html .= $this->maybe_render_actions( $item, $column_name ); return $column_html; } /** * Display the table heading and search query, if any */ protected function display_header() { echo '<h1 class="wp-heading-inline">' . esc_attr( $this->table_header ) . '</h1>'; if ( $this->get_request_search_query() ) { /* translators: %s: search query */ echo '<span class="subtitle">' . esc_attr( sprintf( __( 'Search results for "%s"', 'action-scheduler' ), $this->get_request_search_query() ) ) . '</span>'; } echo '<hr class="wp-header-end">'; } /** * Display the table heading and search query, if any */ protected function display_admin_notices() { foreach ( $this->admin_notices as $notice ) { echo '<div id="message" class="' . esc_attr( $notice['class'] ) . '">'; echo ' <p>' . wp_kses_post( $notice['message'] ) . '</p>'; echo '</div>'; } } /** * Prints the available statuses so the user can click to filter. */ protected function display_filter_by_status() { $status_list_items = array(); $request_status = $this->get_request_status(); // Helper to set 'all' filter when not set on status counts passed in. if ( ! isset( $this->status_counts['all'] ) ) { $all_count = array_sum( $this->status_counts ); if ( isset( $this->status_counts['past-due'] ) ) { $all_count -= $this->status_counts['past-due']; } $this->status_counts = array( 'all' => $all_count ) + $this->status_counts; } // Translated status labels. $status_labels = ActionScheduler_Store::instance()->get_status_labels(); $status_labels['all'] = esc_html_x( 'All', 'status labels', 'action-scheduler' ); $status_labels['past-due'] = esc_html_x( 'Past-due', 'status labels', 'action-scheduler' ); foreach ( $this->status_counts as $status_slug => $count ) { if ( 0 === $count ) { continue; } if ( $status_slug === $request_status || ( empty( $request_status ) && 'all' === $status_slug ) ) { $status_list_item = '<li class="%1$s"><a href="%2$s" class="current">%3$s</a> (%4$d)</li>'; } else { $status_list_item = '<li class="%1$s"><a href="%2$s">%3$s</a> (%4$d)</li>'; } $status_name = isset( $status_labels[ $status_slug ] ) ? $status_labels[ $status_slug ] : ucfirst( $status_slug ); $status_filter_url = ( 'all' === $status_slug ) ? remove_query_arg( 'status' ) : add_query_arg( 'status', $status_slug ); $status_filter_url = remove_query_arg( array( 'paged', 's' ), $status_filter_url ); $status_list_items[] = sprintf( $status_list_item, esc_attr( $status_slug ), esc_url( $status_filter_url ), esc_html( $status_name ), absint( $count ) ); } if ( $status_list_items ) { echo '<ul class="subsubsub">'; echo implode( " | \n", $status_list_items ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo '</ul>'; } } /** * Renders the table list, we override the original class to render the table inside a form * and to render any needed HTML (like the search box). By doing so the callee of a function can simple * forget about any extra HTML. */ protected function display_table() { echo '<form id="' . esc_attr( $this->_args['plural'] ) . '-filter" method="get">'; foreach ( $this->get_request_query_args_to_persist() as $arg ) { $arg_value = isset( $_GET[ $arg ] ) ? sanitize_text_field( wp_unslash( $_GET[ $arg ] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( ! $arg_value ) { continue; } echo '<input type="hidden" name="' . esc_attr( $arg ) . '" value="' . esc_attr( $arg_value ) . '" />'; } if ( ! empty( $this->search_by ) ) { echo $this->search_box( $this->get_search_box_button_text(), 'plugin' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } parent::display(); echo '</form>'; } /** * Process any pending actions. */ public function process_actions() { $this->process_bulk_action(); $this->process_row_actions(); if ( ! empty( $_REQUEST['_wp_http_referer'] ) && ! empty( $_SERVER['REQUEST_URI'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended // _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter wp_safe_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ); exit; } } /** * Render the list table page, including header, notices, status filters and table. */ public function display_page() { $this->prepare_items(); echo '<div class="wrap">'; $this->display_header(); $this->display_admin_notices(); $this->display_filter_by_status(); $this->display_table(); echo '</div>'; } /** * Get the text to display in the search box on the list table. */ protected function get_search_box_placeholder() { return esc_html__( 'Search', 'action-scheduler' ); } /** * Gets the screen per_page option name. * * @return string */ protected function get_per_page_option_name() { return $this->package . '_items_per_page'; } } vendor/woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Store.php 0000644 00000033507 14720461212 0024204 0 ustar 00 <?php /** * Class ActionScheduler_Store * @codeCoverageIgnore */ abstract class ActionScheduler_Store extends ActionScheduler_Store_Deprecated { const STATUS_COMPLETE = 'complete'; const STATUS_PENDING = 'pending'; const STATUS_RUNNING = 'in-progress'; const STATUS_FAILED = 'failed'; const STATUS_CANCELED = 'canceled'; const DEFAULT_CLASS = 'ActionScheduler_wpPostStore'; /** @var ActionScheduler_Store */ private static $store = NULL; /** @var int */ protected static $max_args_length = 191; /** * @param ActionScheduler_Action $action Action to save. * @param null|DateTime $scheduled_date Optional Date of the first instance * to store. Otherwise uses the first date of the action's * schedule. * * @return int The action ID */ abstract public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ); /** * Get action. * * @param string $action_id Action ID. * * @return ActionScheduler_Action */ abstract public function fetch_action( $action_id ); /** * Find an action. * * Note: the query ordering changes based on the passed 'status' value. * * @param string $hook Action hook. * @param array $params Parameters of the action to find. * * @return string|null ID of the next action matching the criteria or NULL if not found. */ public function find_action( $hook, $params = array() ) { $params = wp_parse_args( $params, array( 'args' => null, 'status' => self::STATUS_PENDING, 'group' => '', ) ); // These params are fixed for this method. $params['hook'] = $hook; $params['orderby'] = 'date'; $params['per_page'] = 1; if ( ! empty( $params['status'] ) ) { if ( self::STATUS_PENDING === $params['status'] ) { $params['order'] = 'ASC'; // Find the next action that matches. } else { $params['order'] = 'DESC'; // Find the most recent action that matches. } } $results = $this->query_actions( $params ); return empty( $results ) ? null : $results[0]; } /** * Query for action count or list of action IDs. * * @since 3.3.0 $query['status'] accepts array of statuses instead of a single status. * * @param array $query { * Query filtering options. * * @type string $hook The name of the actions. Optional. * @type string|array $status The status or statuses of the actions. Optional. * @type array $args The args array of the actions. Optional. * @type DateTime $date The scheduled date of the action. Used in UTC timezone. Optional. * @type string $date_compare Operator for selecting by $date param. Accepted values are '!=', '>', '>=', '<', '<=', '='. Defaults to '<='. * @type DateTime $modified The last modified date of the action. Used in UTC timezone. Optional. * @type string $modified_compare Operator for comparing $modified param. Accepted values are '!=', '>', '>=', '<', '<=', '='. Defaults to '<='. * @type string $group The group the action belongs to. Optional. * @type bool|int $claimed TRUE to find claimed actions, FALSE to find unclaimed actions, an int to find a specific claim ID. Optional. * @type int $per_page Number of results to return. Defaults to 5. * @type int $offset The query pagination offset. Defaults to 0. * @type int $orderby Accepted values are 'hook', 'group', 'modified', 'date' or 'none'. Defaults to 'date'. * @type string $order Accepted values are 'ASC' or 'DESC'. Defaults to 'ASC'. * } * @param string $query_type Whether to select or count the results. Default, select. * * @return string|array|null The IDs of actions matching the query. Null on failure. */ abstract public function query_actions( $query = array(), $query_type = 'select' ); /** * Run query to get a single action ID. * * @since 3.3.0 * * @see ActionScheduler_Store::query_actions for $query arg usage but 'per_page' and 'offset' can't be used. * * @param array $query Query parameters. * * @return int|null */ public function query_action( $query ) { $query['per_page'] = 1; $query['offset'] = 0; $results = $this->query_actions( $query ); if ( empty( $results ) ) { return null; } else { return (int) $results[0]; } } /** * Get a count of all actions in the store, grouped by status * * @return array */ abstract public function action_counts(); /** * Get additional action counts. * * - add past-due actions * * @return array */ public function extra_action_counts() { $extra_actions = array(); $pastdue_action_counts = (int) $this->query_actions( array( 'status' => self::STATUS_PENDING, 'date' => as_get_datetime_object(), ), 'count' ); if ( $pastdue_action_counts ) { $extra_actions['past-due'] = $pastdue_action_counts; } /** * Allows 3rd party code to add extra action counts (used in filters in the list table). * * @since 3.5.0 * @param $extra_actions array Array with format action_count_identifier => action count. */ return apply_filters( 'action_scheduler_extra_action_counts', $extra_actions ); } /** * Cancel action. * * @param string $action_id Action ID. */ abstract public function cancel_action( $action_id ); /** * Delete action. * * @param string $action_id Action ID. */ abstract public function delete_action( $action_id ); /** * Get action's schedule or run timestamp. * * @param string $action_id Action ID. * * @return DateTime The date the action is schedule to run, or the date that it ran. */ abstract public function get_date( $action_id ); /** * Make a claim. * * @param int $max_actions Maximum number of actions to claim. * @param DateTime $before_date Claim only actions schedule before the given date. Defaults to now. * @param array $hooks Claim only actions with a hook or hooks. * @param string $group Claim only actions in the given group. * * @return ActionScheduler_ActionClaim */ abstract public function stake_claim( $max_actions = 10, DateTime $before_date = null, $hooks = array(), $group = '' ); /** * Get claim count. * * @return int */ abstract public function get_claim_count(); /** * Release the claim. * * @param ActionScheduler_ActionClaim $claim Claim object. */ abstract public function release_claim( ActionScheduler_ActionClaim $claim ); /** * Un-claim the action. * * @param string $action_id Action ID. */ abstract public function unclaim_action( $action_id ); /** * Mark action as failed. * * @param string $action_id Action ID. */ abstract public function mark_failure( $action_id ); /** * Log action's execution. * * @param string $action_id Actoin ID. */ abstract public function log_execution( $action_id ); /** * Mark action as complete. * * @param string $action_id Action ID. */ abstract public function mark_complete( $action_id ); /** * Get action's status. * * @param string $action_id Action ID. * @return string */ abstract public function get_status( $action_id ); /** * Get action's claim ID. * * @param string $action_id Action ID. * @return mixed */ abstract public function get_claim_id( $action_id ); /** * Find actions by claim ID. * * @param string $claim_id Claim ID. * @return array */ abstract public function find_actions_by_claim_id( $claim_id ); /** * Validate SQL operator. * * @param string $comparison_operator Operator. * @return string */ protected function validate_sql_comparator( $comparison_operator ) { if ( in_array( $comparison_operator, array('!=', '>', '>=', '<', '<=', '=') ) ) { return $comparison_operator; } return '='; } /** * Get the time MySQL formatted date/time string for an action's (next) scheduled date. * * @param ActionScheduler_Action $action Action. * @param null|DateTime $scheduled_date Action's schedule date (optional). * @return string */ protected function get_scheduled_date_string( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) { $next = null === $scheduled_date ? $action->get_schedule()->get_date() : $scheduled_date; if ( ! $next ) { $next = date_create(); } $next->setTimezone( new DateTimeZone( 'UTC' ) ); return $next->format( 'Y-m-d H:i:s' ); } /** * Get the time MySQL formatted date/time string for an action's (next) scheduled date. * * @param ActionScheduler_Action $action Action. * @param null|DateTime $scheduled_date Action's scheduled date (optional). * @return string */ protected function get_scheduled_date_string_local( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) { $next = null === $scheduled_date ? $action->get_schedule()->get_date() : $scheduled_date; if ( ! $next ) { $next = date_create(); } ActionScheduler_TimezoneHelper::set_local_timezone( $next ); return $next->format( 'Y-m-d H:i:s' ); } /** * Validate that we could decode action arguments. * * @param mixed $args The decoded arguments. * @param int $action_id The action ID. * * @throws ActionScheduler_InvalidActionException When the decoded arguments are invalid. */ protected function validate_args( $args, $action_id ) { // Ensure we have an array of args. if ( ! is_array( $args ) ) { throw ActionScheduler_InvalidActionException::from_decoding_args( $action_id ); } // Validate JSON decoding if possible. if ( function_exists( 'json_last_error' ) && JSON_ERROR_NONE !== json_last_error() ) { throw ActionScheduler_InvalidActionException::from_decoding_args( $action_id, $args ); } } /** * Validate a ActionScheduler_Schedule object. * * @param mixed $schedule The unserialized ActionScheduler_Schedule object. * @param int $action_id The action ID. * * @throws ActionScheduler_InvalidActionException When the schedule is invalid. */ protected function validate_schedule( $schedule, $action_id ) { if ( empty( $schedule ) || ! is_a( $schedule, 'ActionScheduler_Schedule' ) ) { throw ActionScheduler_InvalidActionException::from_schedule( $action_id, $schedule ); } } /** * InnoDB indexes have a maximum size of 767 bytes by default, which is only 191 characters with utf8mb4. * * Previously, AS wasn't concerned about args length, as we used the (unindex) post_content column. However, * with custom tables, we use an indexed VARCHAR column instead. * * @param ActionScheduler_Action $action Action to be validated. * @throws InvalidArgumentException When json encoded args is too long. */ protected function validate_action( ActionScheduler_Action $action ) { if ( strlen( wp_json_encode( $action->get_args() ) ) > static::$max_args_length ) { // translators: %d is a number (maximum length of action arguments). throw new InvalidArgumentException( sprintf( __( 'ActionScheduler_Action::$args too long. To ensure the args column can be indexed, action args should not be more than %d characters when encoded as JSON.', 'action-scheduler' ), static::$max_args_length ) ); } } /** * Cancel pending actions by hook. * * @since 3.0.0 * * @param string $hook Hook name. * * @return void */ public function cancel_actions_by_hook( $hook ) { $action_ids = true; while ( ! empty( $action_ids ) ) { $action_ids = $this->query_actions( array( 'hook' => $hook, 'status' => self::STATUS_PENDING, 'per_page' => 1000, 'orderby' => 'none', ) ); $this->bulk_cancel_actions( $action_ids ); } } /** * Cancel pending actions by group. * * @since 3.0.0 * * @param string $group Group slug. * * @return void */ public function cancel_actions_by_group( $group ) { $action_ids = true; while ( ! empty( $action_ids ) ) { $action_ids = $this->query_actions( array( 'group' => $group, 'status' => self::STATUS_PENDING, 'per_page' => 1000, 'orderby' => 'none', ) ); $this->bulk_cancel_actions( $action_ids ); } } /** * Cancel a set of action IDs. * * @since 3.0.0 * * @param int[] $action_ids List of action IDs. * * @return void */ private function bulk_cancel_actions( $action_ids ) { foreach ( $action_ids as $action_id ) { $this->cancel_action( $action_id ); } do_action( 'action_scheduler_bulk_cancel_actions', $action_ids ); } /** * Get status labels. * * @return array<string, string> */ public function get_status_labels() { return array( self::STATUS_COMPLETE => __( 'Complete', 'action-scheduler' ), self::STATUS_PENDING => __( 'Pending', 'action-scheduler' ), self::STATUS_RUNNING => __( 'In-progress', 'action-scheduler' ), self::STATUS_FAILED => __( 'Failed', 'action-scheduler' ), self::STATUS_CANCELED => __( 'Canceled', 'action-scheduler' ), ); } /** * Check if there are any pending scheduled actions due to run. * * @return string */ public function has_pending_actions_due() { $pending_actions = $this->query_actions( array( 'date' => as_get_datetime_object(), 'status' => self::STATUS_PENDING, 'orderby' => 'none', ) ); return ! empty( $pending_actions ); } /** * Callable initialization function optionally overridden in derived classes. */ public function init() {} /** * Callable function to mark an action as migrated optionally overridden in derived classes. * * @param int $action_id Action ID. */ public function mark_migrated( $action_id ) {} /** * @return ActionScheduler_Store */ public static function instance() { if ( empty( self::$store ) ) { $class = apply_filters( 'action_scheduler_store_class', self::DEFAULT_CLASS ); self::$store = new $class(); } return self::$store; } } vendor/woocommerce/action-scheduler/classes/abstracts/ActionScheduler_TimezoneHelper.php 0000644 00000011317 14720461212 0026035 0 ustar 00 <?php /** * Class ActionScheduler_TimezoneHelper */ abstract class ActionScheduler_TimezoneHelper { /** @var null|DateTimeZone */ private static $local_timezone = NULL; /** * Set a DateTime's timezone to the WordPress site's timezone, or a UTC offset * if no timezone string is available. * * @since 2.1.0 * * @param DateTime $date Timestamp. * @return ActionScheduler_DateTime */ public static function set_local_timezone( DateTime $date ) { // Accept a DateTime for easier backward compatibility, even though we require methods on ActionScheduler_DateTime. if ( ! is_a( $date, 'ActionScheduler_DateTime' ) ) { $date = as_get_datetime_object( $date->format( 'U' ) ); } if ( get_option( 'timezone_string' ) ) { $date->setTimezone( new DateTimeZone( self::get_local_timezone_string() ) ); } else { $date->setUtcOffset( self::get_local_timezone_offset() ); } return $date; } /** * Helper to retrieve the timezone string for a site until a WP core method exists * (see https://core.trac.wordpress.org/ticket/24730). * * Adapted from wc_timezone_string() and https://secure.php.net/manual/en/function.timezone-name-from-abbr.php#89155. * * If no timezone string is set, and its not possible to match the UTC offset set for the site to a timezone * string, then an empty string will be returned, and the UTC offset should be used to set a DateTime's * timezone. * * @since 2.1.0 * @param bool $reset Unused. * @return string PHP timezone string for the site or empty if no timezone string is available. */ protected static function get_local_timezone_string( $reset = false ) { // If site timezone string exists, return it. $timezone = get_option( 'timezone_string' ); if ( $timezone ) { return $timezone; } // Get UTC offset, if it isn't set then return UTC. $utc_offset = intval( get_option( 'gmt_offset', 0 ) ); if ( 0 === $utc_offset ) { return 'UTC'; } // Adjust UTC offset from hours to seconds. $utc_offset *= 3600; // Attempt to guess the timezone string from the UTC offset. $timezone = timezone_name_from_abbr( '', $utc_offset ); if ( $timezone ) { return $timezone; } // Last try, guess timezone string manually. foreach ( timezone_abbreviations_list() as $abbr ) { foreach ( $abbr as $city ) { if ( (bool) date( 'I' ) === (bool) $city['dst'] && $city['timezone_id'] && intval( $city['offset'] ) === $utc_offset ) { // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- we are actually interested in the runtime timezone. return $city['timezone_id']; } } } // No timezone string. return ''; } /** * Get timezone offset in seconds. * * @since 2.1.0 * @return float */ protected static function get_local_timezone_offset() { $timezone = get_option( 'timezone_string' ); if ( $timezone ) { $timezone_object = new DateTimeZone( $timezone ); return $timezone_object->getOffset( new DateTime( 'now' ) ); } else { return floatval( get_option( 'gmt_offset', 0 ) ) * HOUR_IN_SECONDS; } } /** * Get local timezone. * * @param bool $reset Toggle to discard stored value. * @deprecated 2.1.0 */ public static function get_local_timezone( $reset = FALSE ) { _deprecated_function( __FUNCTION__, '2.1.0', 'ActionScheduler_TimezoneHelper::set_local_timezone()' ); if ( $reset ) { self::$local_timezone = NULL; } if ( !isset(self::$local_timezone) ) { $tzstring = get_option('timezone_string'); if ( empty($tzstring) ) { $gmt_offset = get_option('gmt_offset'); if ( $gmt_offset == 0 ) { $tzstring = 'UTC'; } else { $gmt_offset *= HOUR_IN_SECONDS; $tzstring = timezone_name_from_abbr( '', $gmt_offset, 1 ); // If there's no timezone string, try again with no DST. if ( false === $tzstring ) { $tzstring = timezone_name_from_abbr( '', $gmt_offset, 0 ); } // Try mapping to the first abbreviation we can find. if ( false === $tzstring ) { $is_dst = date( 'I' ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- we are actually interested in the runtime timezone. foreach ( timezone_abbreviations_list() as $abbr ) { foreach ( $abbr as $city ) { if ( $city['dst'] == $is_dst && $city['offset'] == $gmt_offset ) { // If there's no valid timezone ID, keep looking. if ( null === $city['timezone_id'] ) { continue; } $tzstring = $city['timezone_id']; break 2; } } } } // If we still have no valid string, then fall back to UTC. if ( false === $tzstring ) { $tzstring = 'UTC'; } } } self::$local_timezone = new DateTimeZone($tzstring); } return self::$local_timezone; } } vendor/woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Logger.php 0000644 00000017436 14720461212 0024332 0 ustar 00 <?php /** * Class ActionScheduler_Logger * @codeCoverageIgnore */ abstract class ActionScheduler_Logger { /** @var null|self */ private static $logger = NULL; /** * Get instance. * * @return ActionScheduler_Logger */ public static function instance() { if ( empty(self::$logger) ) { $class = apply_filters('action_scheduler_logger_class', 'ActionScheduler_wpCommentLogger'); self::$logger = new $class(); } return self::$logger; } /** * Create log entry. * * @param string $action_id Action ID. * @param string $message Log message. * @param DateTime $date Log date. * * @return string The log entry ID */ abstract public function log( $action_id, $message, DateTime $date = NULL ); /** * Get action's log entry. * * @param string $entry_id Entry ID. * * @return ActionScheduler_LogEntry */ abstract public function get_entry( $entry_id ); /** * Get action's logs. * * @param string $action_id Action ID. * * @return ActionScheduler_LogEntry[] */ abstract public function get_logs( $action_id ); /** * Initialize. * * @codeCoverageIgnore */ public function init() { $this->hook_stored_action(); add_action( 'action_scheduler_canceled_action', array( $this, 'log_canceled_action' ), 10, 1 ); add_action( 'action_scheduler_begin_execute', array( $this, 'log_started_action' ), 10, 2 ); add_action( 'action_scheduler_after_execute', array( $this, 'log_completed_action' ), 10, 3 ); add_action( 'action_scheduler_failed_execution', array( $this, 'log_failed_action' ), 10, 3 ); add_action( 'action_scheduler_failed_action', array( $this, 'log_timed_out_action' ), 10, 2 ); add_action( 'action_scheduler_unexpected_shutdown', array( $this, 'log_unexpected_shutdown' ), 10, 2 ); add_action( 'action_scheduler_reset_action', array( $this, 'log_reset_action' ), 10, 1 ); add_action( 'action_scheduler_execution_ignored', array( $this, 'log_ignored_action' ), 10, 2 ); add_action( 'action_scheduler_failed_fetch_action', array( $this, 'log_failed_fetch_action' ), 10, 2 ); add_action( 'action_scheduler_failed_to_schedule_next_instance', array( $this, 'log_failed_schedule_next_instance' ), 10, 2 ); add_action( 'action_scheduler_bulk_cancel_actions', array( $this, 'bulk_log_cancel_actions' ), 10, 1 ); } /** * Register callback for storing action. */ public function hook_stored_action() { add_action( 'action_scheduler_stored_action', array( $this, 'log_stored_action' ) ); } /** * Unhook callback for storing action. */ public function unhook_stored_action() { remove_action( 'action_scheduler_stored_action', array( $this, 'log_stored_action' ) ); } /** * Log action stored. * * @param int $action_id Action ID. */ public function log_stored_action( $action_id ) { $this->log( $action_id, __( 'action created', 'action-scheduler' ) ); } /** * Log action cancellation. * * @param int $action_id Action ID. */ public function log_canceled_action( $action_id ) { $this->log( $action_id, __( 'action canceled', 'action-scheduler' ) ); } /** * Log action start. * * @param int $action_id Action ID. * @param string $context Action execution context. */ public function log_started_action( $action_id, $context = '' ) { if ( ! empty( $context ) ) { /* translators: %s: context */ $message = sprintf( __( 'action started via %s', 'action-scheduler' ), $context ); } else { $message = __( 'action started', 'action-scheduler' ); } $this->log( $action_id, $message ); } /** * Log action completion. * * @param int $action_id Action ID. * @param null|ActionScheduler_Action $action Action. * @param string $context Action exeuction context. */ public function log_completed_action( $action_id, $action = NULL, $context = '' ) { if ( ! empty( $context ) ) { /* translators: %s: context */ $message = sprintf( __( 'action complete via %s', 'action-scheduler' ), $context ); } else { $message = __( 'action complete', 'action-scheduler' ); } $this->log( $action_id, $message ); } /** * Log action failure. * * @param int $action_id Action ID. * @param Exception $exception Exception. * @param string $context Action execution context. */ public function log_failed_action( $action_id, Exception $exception, $context = '' ) { if ( ! empty( $context ) ) { /* translators: 1: context 2: exception message */ $message = sprintf( __( 'action failed via %1$s: %2$s', 'action-scheduler' ), $context, $exception->getMessage() ); } else { /* translators: %s: exception message */ $message = sprintf( __( 'action failed: %s', 'action-scheduler' ), $exception->getMessage() ); } $this->log( $action_id, $message ); } /** * Log action timeout. * * @param int $action_id Action ID. * @param string $timeout Timeout. */ public function log_timed_out_action( $action_id, $timeout ) { /* translators: %s: amount of time */ $this->log( $action_id, sprintf( __( 'action marked as failed after %s seconds. Unknown error occurred. Check server, PHP and database error logs to diagnose cause.', 'action-scheduler' ), $timeout ) ); } /** * Log unexpected shutdown. * * @param int $action_id Action ID. * @param mixed[] $error Error. */ public function log_unexpected_shutdown( $action_id, $error ) { if ( ! empty( $error ) ) { /* translators: 1: error message 2: filename 3: line */ $this->log( $action_id, sprintf( __( 'unexpected shutdown: PHP Fatal error %1$s in %2$s on line %3$s', 'action-scheduler' ), $error['message'], $error['file'], $error['line'] ) ); } } /** * Log action reset. * * @param int $action_id Action ID. */ public function log_reset_action( $action_id ) { $this->log( $action_id, __( 'action reset', 'action-scheduler' ) ); } /** * Log ignored action. * * @param int $action_id Action ID. * @param string $context Action execution context. */ public function log_ignored_action( $action_id, $context = '' ) { if ( ! empty( $context ) ) { /* translators: %s: context */ $message = sprintf( __( 'action ignored via %s', 'action-scheduler' ), $context ); } else { $message = __( 'action ignored', 'action-scheduler' ); } $this->log( $action_id, $message ); } /** * Log the failure of fetching the action. * * @param string $action_id Action ID. * @param null|Exception $exception The exception which occurred when fetching the action. NULL by default for backward compatibility. */ public function log_failed_fetch_action( $action_id, Exception $exception = NULL ) { if ( ! is_null( $exception ) ) { /* translators: %s: exception message */ $log_message = sprintf( __( 'There was a failure fetching this action: %s', 'action-scheduler' ), $exception->getMessage() ); } else { $log_message = __( 'There was a failure fetching this action', 'action-scheduler' ); } $this->log( $action_id, $log_message ); } /** * Log the failure of scheduling the action's next instance. * * @param int $action_id Action ID. * @param Exception $exception Exception object. */ public function log_failed_schedule_next_instance( $action_id, Exception $exception ) { /* translators: %s: exception message */ $this->log( $action_id, sprintf( __( 'There was a failure scheduling the next instance of this action: %s', 'action-scheduler' ), $exception->getMessage() ) ); } /** * Bulk add cancel action log entries. * * Implemented here for backward compatibility. Should be implemented in parent loggers * for more performant bulk logging. * * @param array $action_ids List of action ID. */ public function bulk_log_cancel_actions( $action_ids ) { if ( empty( $action_ids ) ) { return; } foreach ( $action_ids as $action_id ) { $this->log_canceled_action( $action_id ); } } } vendor/woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Lock.php 0000644 00000003312 14720461212 0023767 0 ustar 00 <?php /** * Abstract class for setting a basic lock to throttle some action. * * Class ActionScheduler_Lock */ abstract class ActionScheduler_Lock { /** @var ActionScheduler_Lock */ private static $locker = NULL; /** @var int */ protected static $lock_duration = MINUTE_IN_SECONDS; /** * Check if a lock is set for a given lock type. * * @param string $lock_type A string to identify different lock types. * @return bool */ public function is_locked( $lock_type ) { return ( $this->get_expiration( $lock_type ) >= time() ); } /** * Set a lock. * * To prevent race conditions, implementations should avoid setting the lock if the lock is already held. * * @param string $lock_type A string to identify different lock types. * @return bool */ abstract public function set( $lock_type ); /** * If a lock is set, return the timestamp it was set to expiry. * * @param string $lock_type A string to identify different lock types. * @return bool|int False if no lock is set, otherwise the timestamp for when the lock is set to expire. */ abstract public function get_expiration( $lock_type ); /** * Get the amount of time to set for a given lock. 60 seconds by default. * * @param string $lock_type A string to identify different lock types. * @return int */ protected function get_duration( $lock_type ) { return apply_filters( 'action_scheduler_lock_duration', self::$lock_duration, $lock_type ); } /** * @return ActionScheduler_Lock */ public static function instance() { if ( empty( self::$locker ) ) { $class = apply_filters( 'action_scheduler_lock_class', 'ActionScheduler_OptionLock' ); self::$locker = new $class(); } return self::$locker; } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_WPCommentCleaner.php 0000644 00000010471 14720461212 0024260 0 ustar 00 <?php /** * Class ActionScheduler_WPCommentCleaner * * @since 3.0.0 */ class ActionScheduler_WPCommentCleaner { /** * Post migration hook used to cleanup the WP comment table. * * @var string */ protected static $cleanup_hook = 'action_scheduler/cleanup_wp_comment_logs'; /** * An instance of the ActionScheduler_wpCommentLogger class to interact with the comments table. * * This instance should only be used as an interface. It should not be initialized. * * @var ActionScheduler_wpCommentLogger */ protected static $wp_comment_logger = null; /** * The key used to store the cached value of whether there are logs in the WP comment table. * * @var string */ protected static $has_logs_option_key = 'as_has_wp_comment_logs'; /** * Initialize the class and attach callbacks. */ public static function init() { if ( empty( self::$wp_comment_logger ) ) { self::$wp_comment_logger = new ActionScheduler_wpCommentLogger(); } add_action( self::$cleanup_hook, array( __CLASS__, 'delete_all_action_comments' ) ); // While there are orphaned logs left in the comments table, we need to attach the callbacks which filter comment counts. add_action( 'pre_get_comments', array( self::$wp_comment_logger, 'filter_comment_queries' ), 10, 1 ); add_action( 'wp_count_comments', array( self::$wp_comment_logger, 'filter_comment_count' ), 20, 2 ); // run after WC_Comments::wp_count_comments() to make sure we exclude order notes and action logs. add_action( 'comment_feed_where', array( self::$wp_comment_logger, 'filter_comment_feed' ), 10, 2 ); // Action Scheduler may be displayed as a Tools screen or WooCommerce > Status administration screen. add_action( 'load-tools_page_action-scheduler', array( __CLASS__, 'register_admin_notice' ) ); add_action( 'load-woocommerce_page_wc-status', array( __CLASS__, 'register_admin_notice' ) ); } /** * Determines if there are log entries in the wp comments table. * * Uses the flag set on migration completion set by @see self::maybe_schedule_cleanup(). * * @return boolean Whether there are scheduled action comments in the comments table. */ public static function has_logs() { return 'yes' === get_option( self::$has_logs_option_key ); } /** * Schedules the WP Post comment table cleanup to run in 6 months if it's not already scheduled. * Attached to the migration complete hook 'action_scheduler/migration_complete'. */ public static function maybe_schedule_cleanup() { if ( (bool) get_comments( array( 'type' => ActionScheduler_wpCommentLogger::TYPE, 'number' => 1, 'fields' => 'ids' ) ) ) { update_option( self::$has_logs_option_key, 'yes' ); if ( ! as_next_scheduled_action( self::$cleanup_hook ) ) { as_schedule_single_action( gmdate( 'U' ) + ( 6 * MONTH_IN_SECONDS ), self::$cleanup_hook ); } } } /** * Delete all action comments from the WP Comments table. */ public static function delete_all_action_comments() { global $wpdb; $wpdb->delete( $wpdb->comments, array( 'comment_type' => ActionScheduler_wpCommentLogger::TYPE, 'comment_agent' => ActionScheduler_wpCommentLogger::AGENT ) ); delete_option( self::$has_logs_option_key ); } /** * Registers admin notices about the orphaned action logs. */ public static function register_admin_notice() { add_action( 'admin_notices', array( __CLASS__, 'print_admin_notice' ) ); } /** * Prints details about the orphaned action logs and includes information on where to learn more. */ public static function print_admin_notice() { $next_cleanup_message = ''; $next_scheduled_cleanup_hook = as_next_scheduled_action( self::$cleanup_hook ); if ( $next_scheduled_cleanup_hook ) { /* translators: %s: date interval */ $next_cleanup_message = sprintf( __( 'This data will be deleted in %s.', 'action-scheduler' ), human_time_diff( gmdate( 'U' ), $next_scheduled_cleanup_hook ) ); } $notice = sprintf( /* translators: 1: next cleanup message 2: github issue URL */ __( 'Action Scheduler has migrated data to custom tables; however, orphaned log entries exist in the WordPress Comments table. %1$s <a href="%2$s">Learn more »</a>', 'action-scheduler' ), $next_cleanup_message, 'https://github.com/woocommerce/action-scheduler/issues/368' ); echo '<div class="notice notice-warning"><p>' . wp_kses_post( $notice ) . '</p></div>'; } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_LogEntry.php 0000644 00000003474 14720461212 0022665 0 ustar 00 <?php /** * Class ActionScheduler_LogEntry */ class ActionScheduler_LogEntry { /** * @var int $action_id */ protected $action_id = ''; /** * @var string $message */ protected $message = ''; /** * @var Datetime $date */ protected $date; /** * Constructor * * @param mixed $action_id Action ID. * @param string $message Message. * @param Datetime $date Datetime object with the time when this log entry was created. If this parameter is * not provided a new Datetime object (with current time) will be created. */ public function __construct( $action_id, $message, $date = null ) { /* * ActionScheduler_wpCommentLogger::get_entry() previously passed a 3rd param of $comment->comment_type * to ActionScheduler_LogEntry::__construct(), goodness knows why, and the Follow-up Emails plugin * hard-codes loading its own version of ActionScheduler_wpCommentLogger with that out-dated method, * goodness knows why, so we need to guard against that here instead of using a DateTime type declaration * for the constructor's 3rd param of $date and causing a fatal error with older versions of FUE. */ if ( null !== $date && ! is_a( $date, 'DateTime' ) ) { _doing_it_wrong( __METHOD__, 'The third parameter must be a valid DateTime instance, or null.', '2.0.0' ); $date = null; } $this->action_id = $action_id; $this->message = $message; $this->date = $date ? $date : new Datetime; } /** * Returns the date when this log entry was created * * @return Datetime */ public function get_date() { return $this->date; } /** * Get action ID of log entry. */ public function get_action_id() { return $this->action_id; } /** * Get log entry message. */ public function get_message() { return $this->message; } } vendor/woocommerce/action-scheduler/classes/ActionScheduler_DateTime.php 0000644 00000003264 14720461212 0022613 0 ustar 00 <?php /** * ActionScheduler DateTime class. * * This is a custom extension to DateTime that */ class ActionScheduler_DateTime extends DateTime { /** * UTC offset. * * Only used when a timezone is not set. When a timezone string is * used, this will be set to 0. * * @var int */ protected $utcOffset = 0; /** * Get the unix timestamp of the current object. * * Missing in PHP 5.2 so just here so it can be supported consistently. * * @return int */ #[\ReturnTypeWillChange] public function getTimestamp() { return method_exists( 'DateTime', 'getTimestamp' ) ? parent::getTimestamp() : $this->format( 'U' ); } /** * Set the UTC offset. * * This represents a fixed offset instead of a timezone setting. * * @param string|int $offset UTC offset value. */ public function setUtcOffset( $offset ) { $this->utcOffset = intval( $offset ); } /** * Returns the timezone offset. * * @return int * @link http://php.net/manual/en/datetime.getoffset.php */ #[\ReturnTypeWillChange] public function getOffset() { return $this->utcOffset ? $this->utcOffset : parent::getOffset(); } /** * Set the TimeZone associated with the DateTime * * @param DateTimeZone $timezone Timezone object. * * @return static * @link http://php.net/manual/en/datetime.settimezone.php */ #[\ReturnTypeWillChange] public function setTimezone( $timezone ) { $this->utcOffset = 0; parent::setTimezone( $timezone ); return $this; } /** * Get the timestamp with the WordPress timezone offset added or subtracted. * * @since 3.0.0 * @return int */ public function getOffsetTimestamp() { return $this->getTimestamp() + $this->getOffset(); } } vendor/woocommerce/action-scheduler/license.txt 0000644 00000104515 14720461212 0016001 0 ustar 00 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/licenses/why-not-lgpl.html>. vendor/woocommerce/action-scheduler/README.md 0000644 00000005357 14720461212 0015101 0 ustar 00 # Action Scheduler - Job Queue for WordPress [![Build Status](https://travis-ci.org/woocommerce/action-scheduler.png?branch=master)](https://travis-ci.org/woocommerce/action-scheduler) [![codecov](https://codecov.io/gh/woocommerce/action-scheduler/branch/master/graph/badge.svg)](https://codecov.io/gh/woocommerce/action-scheduler) Action Scheduler is a scalable, traceable job queue for background processing large sets of actions in WordPress. It's specially designed to be distributed in WordPress plugins. Action Scheduler works by triggering an action hook to run at some time in the future. Each hook can be scheduled with unique data, to allow callbacks to perform operations on that data. The hook can also be scheduled to run on one or more occasions. Think of it like an extension to `do_action()` which adds the ability to delay and repeat a hook. ## Battle-Tested Background Processing Every month, Action Scheduler processes millions of payments for [Subscriptions](https://woocommerce.com/products/woocommerce-subscriptions/), webhooks for [WooCommerce](https://wordpress.org/plugins/woocommerce/), as well as emails and other events for a range of other plugins. It's been seen on live sites processing queues in excess of 50,000 jobs and doing resource intensive operations, like processing payments and creating orders, at a sustained rate of over 10,000 / hour without negatively impacting normal site operations. This is all on infrastructure and WordPress sites outside the control of the plugin author. If your plugin needs background processing, especially of large sets of tasks, Action Scheduler can help. ## Learn More To learn more about how to Action Scheduler works, and how to use it in your plugin, check out the docs on [ActionScheduler.org](https://actionscheduler.org). There you will find: * [Usage guide](https://actionscheduler.org/usage/): instructions on installing and using Action Scheduler * [WP CLI guide](https://actionscheduler.org/wp-cli/): instructions on running Action Scheduler at scale via WP CLI * [API Reference](https://actionscheduler.org/api/): complete reference guide for all API functions * [Administration Guide](https://actionscheduler.org/admin/): guide to managing scheduled actions via the administration screen * [Guide to Background Processing at Scale](https://actionscheduler.org/perf/): instructions for running Action Scheduler at scale via the default WP Cron queue runner ## Credits Action Scheduler is developed and maintained by [Automattic](http://automattic.com/) with significant early development completed by [Flightless](https://flightless.us/). Collaboration is cool. We'd love to work with you to improve Action Scheduler. [Pull Requests](https://github.com/woocommerce/action-scheduler/pulls) welcome. vendor/woocommerce/action-scheduler/functions.php 0000644 00000045177 14720461212 0016347 0 ustar 00 <?php /** * General API functions for scheduling actions * * @package ActionScheduler. */ /** * Enqueue an action to run one time, as soon as possible * * @param string $hook The hook to trigger. * @param array $args Arguments to pass when the hook triggers. * @param string $group The group to assign this job to. * @param bool $unique Whether the action should be unique. It will not be scheduled if another pending or running action has the same hook and group parameters. * @param int $priority Lower values take precedence over higher values. Defaults to 10, with acceptable values falling in the range 0-255. * * @return int The action ID. Zero if there was an error scheduling the action. */ function as_enqueue_async_action( $hook, $args = array(), $group = '', $unique = false, $priority = 10 ) { if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) { return 0; } /** * Provides an opportunity to short-circuit the default process for enqueuing async * actions. * * Returning a value other than null from the filter will short-circuit the normal * process. The expectation in such a scenario is that callbacks will return an integer * representing the enqueued action ID (enqueued using some alternative process) or else * zero. * * @param int|null $pre_option The value to return instead of the option value. * @param string $hook Action hook. * @param array $args Action arguments. * @param string $group Action group. * @param int $priority Action priority. * @param bool $unique Unique action. */ $pre = apply_filters( 'pre_as_enqueue_async_action', null, $hook, $args, $group, $priority, $unique ); if ( null !== $pre ) { return is_int( $pre ) ? $pre : 0; } return ActionScheduler::factory()->create( array( 'type' => 'async', 'hook' => $hook, 'arguments' => $args, 'group' => $group, 'unique' => $unique, 'priority' => $priority, ) ); } /** * Schedule an action to run one time * * @param int $timestamp When the job will run. * @param string $hook The hook to trigger. * @param array $args Arguments to pass when the hook triggers. * @param string $group The group to assign this job to. * @param bool $unique Whether the action should be unique. It will not be scheduled if another pending or running action has the same hook and group parameters. * @param int $priority Lower values take precedence over higher values. Defaults to 10, with acceptable values falling in the range 0-255. * * @return int The action ID. Zero if there was an error scheduling the action. */ function as_schedule_single_action( $timestamp, $hook, $args = array(), $group = '', $unique = false, $priority = 10 ) { if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) { return 0; } /** * Provides an opportunity to short-circuit the default process for enqueuing single * actions. * * Returning a value other than null from the filter will short-circuit the normal * process. The expectation in such a scenario is that callbacks will return an integer * representing the scheduled action ID (scheduled using some alternative process) or else * zero. * * @param int|null $pre_option The value to return instead of the option value. * @param int $timestamp When the action will run. * @param string $hook Action hook. * @param array $args Action arguments. * @param string $group Action group. * @param int $priorities Action priority. */ $pre = apply_filters( 'pre_as_schedule_single_action', null, $timestamp, $hook, $args, $group, $priority ); if ( null !== $pre ) { return is_int( $pre ) ? $pre : 0; } return ActionScheduler::factory()->create( array( 'type' => 'single', 'hook' => $hook, 'arguments' => $args, 'when' => $timestamp, 'group' => $group, 'unique' => $unique, 'priority' => $priority, ) ); } /** * Schedule a recurring action * * @param int $timestamp When the first instance of the job will run. * @param int $interval_in_seconds How long to wait between runs. * @param string $hook The hook to trigger. * @param array $args Arguments to pass when the hook triggers. * @param string $group The group to assign this job to. * @param bool $unique Whether the action should be unique. It will not be scheduled if another pending or running action has the same hook and group parameters. * @param int $priority Lower values take precedence over higher values. Defaults to 10, with acceptable values falling in the range 0-255. * * @return int The action ID. Zero if there was an error scheduling the action. */ function as_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args = array(), $group = '', $unique = false, $priority = 10 ) { if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) { return 0; } $interval = (int) $interval_in_seconds; // We expect an integer and allow it to be passed using float and string types, but otherwise // should reject unexpected values. if ( ! is_numeric( $interval_in_seconds ) || $interval_in_seconds != $interval ) { _doing_it_wrong( __METHOD__, sprintf( /* translators: 1: provided value 2: provided type. */ esc_html__( 'An integer was expected but "%1$s" (%2$s) was received.', 'action-scheduler' ), esc_html( $interval_in_seconds ), esc_html( gettype( $interval_in_seconds ) ) ), '3.6.0' ); return 0; } /** * Provides an opportunity to short-circuit the default process for enqueuing recurring * actions. * * Returning a value other than null from the filter will short-circuit the normal * process. The expectation in such a scenario is that callbacks will return an integer * representing the scheduled action ID (scheduled using some alternative process) or else * zero. * * @param int|null $pre_option The value to return instead of the option value. * @param int $timestamp When the action will run. * @param int $interval_in_seconds How long to wait between runs. * @param string $hook Action hook. * @param array $args Action arguments. * @param string $group Action group. * @param int $priority Action priority. */ $pre = apply_filters( 'pre_as_schedule_recurring_action', null, $timestamp, $interval_in_seconds, $hook, $args, $group, $priority ); if ( null !== $pre ) { return is_int( $pre ) ? $pre : 0; } return ActionScheduler::factory()->create( array( 'type' => 'recurring', 'hook' => $hook, 'arguments' => $args, 'when' => $timestamp, 'pattern' => $interval_in_seconds, 'group' => $group, 'unique' => $unique, 'priority' => $priority, ) ); } /** * Schedule an action that recurs on a cron-like schedule. * * @param int $timestamp The first instance of the action will be scheduled * to run at a time calculated after this timestamp matching the cron * expression. This can be used to delay the first instance of the action. * @param string $schedule A cron-link schedule string. * @see http://en.wikipedia.org/wiki/Cron * * * * * * * * ┬ ┬ ┬ ┬ ┬ ┬ * | | | | | | * | | | | | + year [optional] * | | | | +----- day of week (0 - 7) (Sunday=0 or 7) * | | | +---------- month (1 - 12) * | | +--------------- day of month (1 - 31) * | +-------------------- hour (0 - 23) * +------------------------- min (0 - 59) * @param string $hook The hook to trigger. * @param array $args Arguments to pass when the hook triggers. * @param string $group The group to assign this job to. * @param bool $unique Whether the action should be unique. It will not be scheduled if another pending or running action has the same hook and group parameters. * @param int $priority Lower values take precedence over higher values. Defaults to 10, with acceptable values falling in the range 0-255. * * @return int The action ID. Zero if there was an error scheduling the action. */ function as_schedule_cron_action( $timestamp, $schedule, $hook, $args = array(), $group = '', $unique = false, $priority = 10 ) { if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) { return 0; } /** * Provides an opportunity to short-circuit the default process for enqueuing cron * actions. * * Returning a value other than null from the filter will short-circuit the normal * process. The expectation in such a scenario is that callbacks will return an integer * representing the scheduled action ID (scheduled using some alternative process) or else * zero. * * @param int|null $pre_option The value to return instead of the option value. * @param int $timestamp When the action will run. * @param string $schedule Cron-like schedule string. * @param string $hook Action hook. * @param array $args Action arguments. * @param string $group Action group. * @param int $priority Action priority. */ $pre = apply_filters( 'pre_as_schedule_cron_action', null, $timestamp, $schedule, $hook, $args, $group, $priority ); if ( null !== $pre ) { return is_int( $pre ) ? $pre : 0; } return ActionScheduler::factory()->create( array( 'type' => 'cron', 'hook' => $hook, 'arguments' => $args, 'when' => $timestamp, 'pattern' => $schedule, 'group' => $group, 'unique' => $unique, 'priority' => $priority, ) ); } /** * Cancel the next occurrence of a scheduled action. * * While only the next instance of a recurring or cron action is unscheduled by this method, that will also prevent * all future instances of that recurring or cron action from being run. Recurring and cron actions are scheduled in * a sequence instead of all being scheduled at once. Each successive occurrence of a recurring action is scheduled * only after the former action is run. If the next instance is never run, because it's unscheduled by this function, * then the following instance will never be scheduled (or exist), which is effectively the same as being unscheduled * by this method also. * * @param string $hook The hook that the job will trigger. * @param array $args Args that would have been passed to the job. * @param string $group The group the job is assigned to. * * @return int|null The scheduled action ID if a scheduled action was found, or null if no matching action found. */ function as_unschedule_action( $hook, $args = array(), $group = '' ) { if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) { return 0; } $params = array( 'hook' => $hook, 'status' => ActionScheduler_Store::STATUS_PENDING, 'orderby' => 'date', 'order' => 'ASC', 'group' => $group, ); if ( is_array( $args ) ) { $params['args'] = $args; } $action_id = ActionScheduler::store()->query_action( $params ); if ( $action_id ) { try { ActionScheduler::store()->cancel_action( $action_id ); } catch ( Exception $exception ) { ActionScheduler::logger()->log( $action_id, sprintf( /* translators: %1$s is the name of the hook to be cancelled, %2$s is the exception message. */ __( 'Caught exception while cancelling action "%1$s": %2$s', 'action-scheduler' ), $hook, $exception->getMessage() ) ); $action_id = null; } } return $action_id; } /** * Cancel all occurrences of a scheduled action. * * @param string $hook The hook that the job will trigger. * @param array $args Args that would have been passed to the job. * @param string $group The group the job is assigned to. */ function as_unschedule_all_actions( $hook, $args = array(), $group = '' ) { if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) { return; } if ( empty( $args ) ) { if ( ! empty( $hook ) && empty( $group ) ) { ActionScheduler_Store::instance()->cancel_actions_by_hook( $hook ); return; } if ( ! empty( $group ) && empty( $hook ) ) { ActionScheduler_Store::instance()->cancel_actions_by_group( $group ); return; } } do { $unscheduled_action = as_unschedule_action( $hook, $args, $group ); } while ( ! empty( $unscheduled_action ) ); } /** * Check if there is an existing action in the queue with a given hook, args and group combination. * * An action in the queue could be pending, in-progress or async. If the is pending for a time in * future, its scheduled date will be returned as a timestamp. If it is currently being run, or an * async action sitting in the queue waiting to be processed, in which case boolean true will be * returned. Or there may be no async, in-progress or pending action for this hook, in which case, * boolean false will be the return value. * * @param string $hook Name of the hook to search for. * @param array $args Arguments of the action to be searched. * @param string $group Group of the action to be searched. * * @return int|bool The timestamp for the next occurrence of a pending scheduled action, true for an async or in-progress action or false if there is no matching action. */ function as_next_scheduled_action( $hook, $args = null, $group = '' ) { if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) { return false; } $params = array( 'hook' => $hook, 'orderby' => 'date', 'order' => 'ASC', 'group' => $group, ); if ( is_array( $args ) ) { $params['args'] = $args; } $params['status'] = ActionScheduler_Store::STATUS_RUNNING; $action_id = ActionScheduler::store()->query_action( $params ); if ( $action_id ) { return true; } $params['status'] = ActionScheduler_Store::STATUS_PENDING; $action_id = ActionScheduler::store()->query_action( $params ); if ( null === $action_id ) { return false; } $action = ActionScheduler::store()->fetch_action( $action_id ); $scheduled_date = $action->get_schedule()->get_date(); if ( $scheduled_date ) { return (int) $scheduled_date->format( 'U' ); } elseif ( null === $scheduled_date ) { // pending async action with NullSchedule. return true; } return false; } /** * Check if there is a scheduled action in the queue but more efficiently than as_next_scheduled_action(). * * It's recommended to use this function when you need to know whether a specific action is currently scheduled * (pending or in-progress). * * @since 3.3.0 * * @param string $hook The hook of the action. * @param array $args Args that have been passed to the action. Null will matches any args. * @param string $group The group the job is assigned to. * * @return bool True if a matching action is pending or in-progress, false otherwise. */ function as_has_scheduled_action( $hook, $args = null, $group = '' ) { if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) { return false; } $query_args = array( 'hook' => $hook, 'status' => array( ActionScheduler_Store::STATUS_RUNNING, ActionScheduler_Store::STATUS_PENDING ), 'group' => $group, 'orderby' => 'none', ); if ( null !== $args ) { $query_args['args'] = $args; } $action_id = ActionScheduler::store()->query_action( $query_args ); return null !== $action_id; } /** * Find scheduled actions * * @param array $args Possible arguments, with their default values. * 'hook' => '' - the name of the action that will be triggered. * 'args' => NULL - the args array that will be passed with the action. * 'date' => NULL - the scheduled date of the action. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone. * 'date_compare' => '<=' - operator for testing "date". accepted values are '!=', '>', '>=', '<', '<=', '='. * 'modified' => NULL - the date the action was last updated. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone. * 'modified_compare' => '<=' - operator for testing "modified". accepted values are '!=', '>', '>=', '<', '<=', '='. * 'group' => '' - the group the action belongs to. * 'status' => '' - ActionScheduler_Store::STATUS_COMPLETE or ActionScheduler_Store::STATUS_PENDING. * 'claimed' => NULL - TRUE to find claimed actions, FALSE to find unclaimed actions, a string to find a specific claim ID. * 'per_page' => 5 - Number of results to return. * 'offset' => 0. * 'orderby' => 'date' - accepted values are 'hook', 'group', 'modified', 'date' or 'none'. * 'order' => 'ASC'. * * @param string $return_format OBJECT, ARRAY_A, or ids. * * @return array */ function as_get_scheduled_actions( $args = array(), $return_format = OBJECT ) { if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) { return array(); } $store = ActionScheduler::store(); foreach ( array( 'date', 'modified' ) as $key ) { if ( isset( $args[ $key ] ) ) { $args[ $key ] = as_get_datetime_object( $args[ $key ] ); } } $ids = $store->query_actions( $args ); if ( 'ids' === $return_format || 'int' === $return_format ) { return $ids; } $actions = array(); foreach ( $ids as $action_id ) { $actions[ $action_id ] = $store->fetch_action( $action_id ); } if ( ARRAY_A == $return_format ) { foreach ( $actions as $action_id => $action_object ) { $actions[ $action_id ] = get_object_vars( $action_object ); } } return $actions; } /** * Helper function to create an instance of DateTime based on a given * string and timezone. By default, will return the current date/time * in the UTC timezone. * * Needed because new DateTime() called without an explicit timezone * will create a date/time in PHP's timezone, but we need to have * assurance that a date/time uses the right timezone (which we almost * always want to be UTC), which means we need to always include the * timezone when instantiating datetimes rather than leaving it up to * the PHP default. * * @param mixed $date_string A date/time string. Valid formats are explained in http://php.net/manual/en/datetime.formats.php. * @param string $timezone A timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available http://php.net/manual/en/timezones.php. * * @return ActionScheduler_DateTime */ function as_get_datetime_object( $date_string = null, $timezone = 'UTC' ) { if ( is_object( $date_string ) && $date_string instanceof DateTime ) { $date = new ActionScheduler_DateTime( $date_string->format( 'Y-m-d H:i:s' ), new DateTimeZone( $timezone ) ); } elseif ( is_numeric( $date_string ) ) { $date = new ActionScheduler_DateTime( '@' . $date_string, new DateTimeZone( $timezone ) ); } else { $date = new ActionScheduler_DateTime( null === $date_string ? 'now' : $date_string, new DateTimeZone( $timezone ) ); } return $date; } vendor/woocommerce/action-scheduler/readme.txt 0000644 00000024305 14720461212 0015612 0 ustar 00 === Action Scheduler === Contributors: Automattic, wpmuguru, claudiosanches, peterfabian1000, vedjain, jamosova, obliviousharmony, konamiman, sadowski, royho, barryhughes-1 Tags: scheduler, cron Stable tag: 3.8.2 License: GPLv3 Requires at least: 6.4 Tested up to: 6.6 Requires PHP: 7.0 Action Scheduler - Job Queue for WordPress == Description == Action Scheduler is a scalable, traceable job queue for background processing large sets of actions in WordPress. It's specially designed to be distributed in WordPress plugins. Action Scheduler works by triggering an action hook to run at some time in the future. Each hook can be scheduled with unique data, to allow callbacks to perform operations on that data. The hook can also be scheduled to run on one or more occasions. Think of it like an extension to `do_action()` which adds the ability to delay and repeat a hook. ## Battle-Tested Background Processing Every month, Action Scheduler processes millions of payments for [Subscriptions](https://woocommerce.com/products/woocommerce-subscriptions/), webhooks for [WooCommerce](https://wordpress.org/plugins/woocommerce/), as well as emails and other events for a range of other plugins. It's been seen on live sites processing queues in excess of 50,000 jobs and doing resource intensive operations, like processing payments and creating orders, at a sustained rate of over 10,000 / hour without negatively impacting normal site operations. This is all on infrastructure and WordPress sites outside the control of the plugin author. If your plugin needs background processing, especially of large sets of tasks, Action Scheduler can help. ## Learn More To learn more about how to Action Scheduler works, and how to use it in your plugin, check out the docs on [ActionScheduler.org](https://actionscheduler.org). There you will find: * [Usage guide](https://actionscheduler.org/usage/): instructions on installing and using Action Scheduler * [WP CLI guide](https://actionscheduler.org/wp-cli/): instructions on running Action Scheduler at scale via WP CLI * [API Reference](https://actionscheduler.org/api/): complete reference guide for all API functions * [Administration Guide](https://actionscheduler.org/admin/): guide to managing scheduled actions via the administration screen * [Guide to Background Processing at Scale](https://actionscheduler.org/perf/): instructions for running Action Scheduler at scale via the default WP Cron queue runner ## Credits Action Scheduler is developed and maintained by [Automattic](http://automattic.com/) with significant early development completed by [Flightless](https://flightless.us/). Collaboration is cool. We'd love to work with you to improve Action Scheduler. [Pull Requests](https://github.com/woocommerce/action-scheduler/pulls) welcome. == Changelog == = 3.8.2 - 2024-09-12 = * Add missing parameter to the `pre_as_enqueue_async_action` hook. * Bump minimum PHP version to 7.0. * Bump minimum WordPress version to 6.4. * Make the batch size adjustable during processing. = 3.8.1 - 2024-06-20 = * Fix typos. * Improve the messaging in our unidentified action exceptions. = 3.8.0 - 2024-05-22 = * Documentation - Fixed typos in perf.md. * Update - We now require WordPress 6.3 or higher. * Update - We now require PHP 7.0 or higher. = 3.7.4 - 2024-04-05 = * Give a clear description of how the $unique parameter works. * Preserve the tab field if set. * Tweak - WP 6.5 compatibility. = 3.7.3 - 2024-03-20 = * Do not iterate over all of GET when building form in list table. * Fix a few issues reported by PCP (Plugin Check Plugin). * Try to save actions as unique even when the store doesn't support it. * Tweak - WP 6.4 compatibility. * Update "Tested up to" tag to WordPress 6.5. * update version in package-lock.json. = 3.7.2 - 2024-02-14 = * No longer user variables in `_n()` translation function. = 3.7.1 - 2023-12-13 = * update semver to 5.7.2 because of a security vulnerability in 5.7.1. = 3.7.0 - 2023-11-20 = * Important: starting with this release, Action Scheduler follows an L-2 version policy (WordPress, and consequently PHP). * Add extended indexes for hook_status_scheduled_date_gmt and status_scheduled_date_gmt. * Catch and log exceptions thrown when actions can't be created, e.g. under a corrupt database schema. * Tweak - WP 6.4 compatibility. * Update unit tests for upcoming dependency version policy. * make sure hook action_scheduler_failed_execution can access original exception object. * mention dependency version policy in usage.md. = 3.6.4 - 2023-10-11 = * Performance improvements when bulk cancelling actions. * Dev-related fixes. = 3.6.3 - 2023-09-13 = * Use `_doing_it_wrong` in initialization check. = 3.6.2 - 2023-08-09 = * Add guidance about passing arguments. * Atomic option locking. * Improve bulk delete handling. * Include database error in the exception message. * Tweak - WP 6.3 compatibility. = 3.6.1 - 2023-06-14 = * Document new optional `$priority` arg for various API functions. * Document the new `--exclude-groups` WP CLI option. * Document the new `action_scheduler_init` hook. * Ensure actions within each claim are executed in the expected order. * Fix incorrect text domain. * Remove SHOW TABLES usage when checking if tables exist. = 3.6.0 - 2023-05-10 = * Add $unique parameter to function signatures. * Add a cast-to-int for extra safety before forming new DateTime object. * Add a hook allowing exceptions for consistently failing recurring actions. * Add action priorities. * Add init hook. * Always raise the time limit. * Bump minimatch from 3.0.4 to 3.0.8. * Bump yaml from 2.2.1 to 2.2.2. * Defensive coding relating to gaps in declared schedule types. * Do not process an action if it cannot be set to `in-progress`. * Filter view labels (status names) should be translatable | #919. * Fix WPCLI progress messages. * Improve data-store initialization flow. * Improve error handling across all supported PHP versions. * Improve logic for flushing the runtime cache. * Support exclusion of multiple groups. * Update lint-staged and Node/NPM requirements. * add CLI clean command. * add CLI exclude-group filter. * exclude past-due from list table all filter count. * throwing an exception if as_schedule_recurring_action interval param is not of type integer. = 3.5.4 - 2023-01-17 = * Add pre filters during action registration. * Async scheduling. * Calculate timeouts based on total actions. * Correctly order the parameters for `ActionScheduler_ActionFactory`'s calls to `single_unique`. * Fetch action in memory first before releasing claim to avoid deadlock. * PHP 8.2: declare property to fix creation of dynamic property warning. * PHP 8.2: fix "Using ${var} in strings is deprecated, use {$var} instead". * Prevent `undefined variable` warning for `$num_pastdue_actions`. = 3.5.3 - 2022-11-09 = * Query actions with partial match. = 3.5.2 - 2022-09-16 = * Fix - erroneous 3.5.1 release. = 3.5.1 - 2022-09-13 = * Maintenance on A/S docs. * fix: PHP 8.2 deprecated notice. = 3.5.0 - 2022-08-25 = * Add - The active view link within the "Tools > Scheduled Actions" screen is now clickable. * Add - A warning when there are past-due actions. * Enhancement - Added the ability to schedule unique actions via an atomic operation. * Enhancement - Improvements to cache invalidation when processing batches (when running on WordPress 6.0+). * Enhancement - If a recurring action is found to be consistently failing, it will stop being rescheduled. * Enhancement - Adds a new "Past Due" view to the scheduled actions list table. = 3.4.2 - 2022-06-08 = * Fix - Change the include for better linting. * Fix - update: Added Action scheduler completed action hook. = 3.4.1 - 2022-05-24 = * Fix - Change the include for better linting. * Fix - Fix the documented return type. = 3.4.0 - 2021-10-29 = * Enhancement - Number of items per page can now be set for the Scheduled Actions view (props @ovidiul). #771 * Fix - Do not lower the max_execution_time if it is already set to 0 (unlimited) (props @barryhughes). #755 * Fix - Avoid triggering autoloaders during the version resolution process (props @olegabr). #731 & #776 * Dev - ActionScheduler_wcSystemStatus PHPCS fixes (props @ovidiul). #761 * Dev - ActionScheduler_DBLogger.php PHPCS fixes (props @ovidiul). #768 * Dev - Fixed phpcs for ActionScheduler_Schedule_Deprecated (props @ovidiul). #762 * Dev - Improve actions table indices (props @glagonikas). #774 & #777 * Dev - PHPCS fixes for ActionScheduler_DBStore.php (props @ovidiul). #769 & #778 * Dev - PHPCS Fixes for ActionScheduler_Abstract_ListTable (props @ovidiul). #763 & #779 * Dev - Adds new filter action_scheduler_claim_actions_order_by to allow tuning of the claim query (props @glagonikas). #773 * Dev - PHPCS fixes for ActionScheduler_WpPostStore class (props @ovidiul). #780 = 3.3.0 - 2021-09-15 = * Enhancement - Adds as_has_scheduled_action() to provide a performant way to test for existing actions. #645 * Fix - Improves compatibility with environments where NO_ZERO_DATE is enabled. #519 * Fix - Adds safety checks to guard against errors when our database tables cannot be created. #645 * Dev - Now supports queries that use multiple statuses. #649 * Dev - Minimum requirements for WordPress and PHP bumped (to 5.2 and 5.6 respectively). #723 = 3.2.1 - 2021-06-21 = * Fix - Add extra safety/account for different versions of AS and different loading patterns. #714 * Fix - Handle hidden columns (Tools → Scheduled Actions) | #600. = 3.2.0 - 2021-06-03 = * Fix - Add "no ordering" option to as_next_scheduled_action(). * Fix - Add secondary scheduled date checks when claiming actions (DBStore) | #634. * Fix - Add secondary scheduled date checks when claiming actions (wpPostStore) | #634. * Fix - Adds a new index to the action table, reducing the potential for deadlocks (props: @glagonikas). * Fix - Fix unit tests infrastructure and adapt tests to PHP 8. * Fix - Identify in-use data store. * Fix - Improve test_migration_is_scheduled. * Fix - PHP notice on list table. * Fix - Speed up clean up and batch selects. * Fix - Update pending dependencies. * Fix - [PHP 8.0] Only pass action arg values through to do_action_ref_array(). * Fix - [PHP 8] Set the PHP version to 7.1 in composer.json for PHP 8 compatibility. * Fix - add is_initialized() to docs. * Fix - fix file permissions. * Fix - fixes #664 by replacing __ with esc_html__. vendor/woocommerce/action-scheduler/changelog.txt 0000644 00000016762 14720461212 0016314 0 ustar 00 *** Changelog *** = 3.8.2 - 2024-09-12 = * Add missing parameter to the `pre_as_enqueue_async_action` hook. * Bump minimum PHP version to 7.0. * Bump minimum WordPress version to 6.4. * Make the batch size adjustable during processing. = 3.8.1 - 2024-06-20 = * Fix typos. * Improve the messaging in our unidentified action exceptions. = 3.8.0 - 2024-05-22 = * Documentation - Fixed typos in perf.md. * Update - We now require WordPress 6.3 or higher. * Update - We now require PHP 7.0 or higher. = 3.7.4 - 2024-04-05 = * Give a clear description of how the $unique parameter works. * Preserve the tab field if set. * Tweak - WP 6.5 compatibility. = 3.7.3 - 2024-03-20 = * Do not iterate over all of GET when building form in list table. * Fix a few issues reported by PCP (Plugin Check Plugin). * Try to save actions as unique even when the store doesn't support it. * Tweak - WP 6.4 compatibility. * Update "Tested up to" tag to WordPress 6.5. * update version in package-lock.json. = 3.7.2 - 2024-02-14 = * No longer user variables in `_n()` translation function. = 3.7.1 - 2023-12-13 = * update semver to 5.7.2 because of a security vulnerability in 5.7.1. = 3.7.0 - 2023-11-20 = * Important: starting with this release, Action Scheduler follows an L-2 version policy (WordPress, and consequently PHP). * Add extended indexes for hook_status_scheduled_date_gmt and status_scheduled_date_gmt. * Catch and log exceptions thrown when actions can't be created, e.g. under a corrupt database schema. * Tweak - WP 6.4 compatibility. * Update unit tests for upcoming dependency version policy. * make sure hook action_scheduler_failed_execution can access original exception object. * mention dependency version policy in usage.md. = 3.6.4 - 2023-10-11 = * Performance improvements when bulk cancelling actions. * Dev-related fixes. = 3.6.3 - 2023-09-13 = * Use `_doing_it_wrong` in initialization check. = 3.6.2 - 2023-08-09 = * Add guidance about passing arguments. * Atomic option locking. * Improve bulk delete handling. * Include database error in the exception message. * Tweak - WP 6.3 compatibility. = 3.6.1 - 2023-06-14 = * Document new optional `$priority` arg for various API functions. * Document the new `--exclude-groups` WP CLI option. * Document the new `action_scheduler_init` hook. * Ensure actions within each claim are executed in the expected order. * Fix incorrect text domain. * Remove SHOW TABLES usage when checking if tables exist. = 3.6.0 - 2023-05-10 = * Add $unique parameter to function signatures. * Add a cast-to-int for extra safety before forming new DateTime object. * Add a hook allowing exceptions for consistently failing recurring actions. * Add action priorities. * Add init hook. * Always raise the time limit. * Bump minimatch from 3.0.4 to 3.0.8. * Bump yaml from 2.2.1 to 2.2.2. * Defensive coding relating to gaps in declared schedule types. * Do not process an action if it cannot be set to `in-progress`. * Filter view labels (status names) should be translatable | #919. * Fix WPCLI progress messages. * Improve data-store initialization flow. * Improve error handling across all supported PHP versions. * Improve logic for flushing the runtime cache. * Support exclusion of multiple groups. * Update lint-staged and Node/NPM requirements. * add CLI clean command. * add CLI exclude-group filter. * exclude past-due from list table all filter count. * throwing an exception if as_schedule_recurring_action interval param is not of type integer. = 3.5.4 - 2023-01-17 = * Add pre filters during action registration. * Async scheduling. * Calculate timeouts based on total actions. * Correctly order the parameters for `ActionScheduler_ActionFactory`'s calls to `single_unique`. * Fetch action in memory first before releasing claim to avoid deadlock. * PHP 8.2: declare property to fix creation of dynamic property warning. * PHP 8.2: fix "Using ${var} in strings is deprecated, use {$var} instead". * Prevent `undefined variable` warning for `$num_pastdue_actions`. = 3.5.3 - 2022-11-09 = * Query actions with partial match. = 3.5.2 - 2022-09-16 = * Fix - erroneous 3.5.1 release. = 3.5.1 - 2022-09-13 = * Maintenance on A/S docs. * fix: PHP 8.2 deprecated notice. = 3.5.0 - 2022-08-25 = * Add - The active view link within the "Tools > Scheduled Actions" screen is now clickable. * Add - A warning when there are past-due actions. * Enhancement - Added the ability to schedule unique actions via an atomic operation. * Enhancement - Improvements to cache invalidation when processing batches (when running on WordPress 6.0+). * Enhancement - If a recurring action is found to be consistently failing, it will stop being rescheduled. * Enhancement - Adds a new "Past Due" view to the scheduled actions list table. = 3.4.2 - 2022-06-08 = * Fix - Change the include for better linting. * Fix - update: Added Action scheduler completed action hook. = 3.4.1 - 2022-05-24 = * Fix - Change the include for better linting. * Fix - Fix the documented return type. = 3.4.0 - 2021-10-29 = * Enhancement - Number of items per page can now be set for the Scheduled Actions view (props @ovidiul). #771 * Fix - Do not lower the max_execution_time if it is already set to 0 (unlimited) (props @barryhughes). #755 * Fix - Avoid triggering autoloaders during the version resolution process (props @olegabr). #731 & #776 * Dev - ActionScheduler_wcSystemStatus PHPCS fixes (props @ovidiul). #761 * Dev - ActionScheduler_DBLogger.php PHPCS fixes (props @ovidiul). #768 * Dev - Fixed phpcs for ActionScheduler_Schedule_Deprecated (props @ovidiul). #762 * Dev - Improve actions table indices (props @glagonikas). #774 & #777 * Dev - PHPCS fixes for ActionScheduler_DBStore.php (props @ovidiul). #769 & #778 * Dev - PHPCS Fixes for ActionScheduler_Abstract_ListTable (props @ovidiul). #763 & #779 * Dev - Adds new filter action_scheduler_claim_actions_order_by to allow tuning of the claim query (props @glagonikas). #773 * Dev - PHPCS fixes for ActionScheduler_WpPostStore class (props @ovidiul). #780 = 3.3.0 - 2021-09-15 = * Enhancement - Adds as_has_scheduled_action() to provide a performant way to test for existing actions. #645 * Fix - Improves compatibility with environments where NO_ZERO_DATE is enabled. #519 * Fix - Adds safety checks to guard against errors when our database tables cannot be created. #645 * Dev - Now supports queries that use multiple statuses. #649 * Dev - Minimum requirements for WordPress and PHP bumped (to 5.2 and 5.6 respectively). #723 = 3.2.1 - 2021-06-21 = * Fix - Add extra safety/account for different versions of AS and different loading patterns. #714 * Fix - Handle hidden columns (Tools → Scheduled Actions) | #600. = 3.2.0 - 2021-06-03 = * Fix - Add "no ordering" option to as_next_scheduled_action(). * Fix - Add secondary scheduled date checks when claiming actions (DBStore) | #634. * Fix - Add secondary scheduled date checks when claiming actions (wpPostStore) | #634. * Fix - Adds a new index to the action table, reducing the potential for deadlocks (props: @glagonikas). * Fix - Fix unit tests infrastructure and adapt tests to PHP 8. * Fix - Identify in-use data store. * Fix - Improve test_migration_is_scheduled. * Fix - PHP notice on list table. * Fix - Speed up clean up and batch selects. * Fix - Update pending dependencies. * Fix - [PHP 8.0] Only pass action arg values through to do_action_ref_array(). * Fix - [PHP 8] Set the PHP version to 7.1 in composer.json for PHP 8 compatibility. * Fix - add is_initialized() to docs. * Fix - fix file permissions. * Fix - fixes #664 by replacing __ with esc_html__. = 3.1.6 - 2020-05-12 = * Change log starts. vendor/woocommerce/action-scheduler/action-scheduler.php 0000644 00000005717 14720461212 0017564 0 ustar 00 <?php /** * Plugin Name: Action Scheduler * Plugin URI: https://actionscheduler.org * Description: A robust scheduling library for use in WordPress plugins. * Author: Automattic * Author URI: https://automattic.com/ * Version: 3.8.2 * License: GPLv3 * Requires at least: 6.4 * Tested up to: 6.6 * Requires PHP: 7.0 * * Copyright 2019 Automattic, Inc. (https://automattic.com/contact/) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * @package ActionScheduler */ if ( ! function_exists( 'action_scheduler_register_3_dot_8_dot_2' ) && function_exists( 'add_action' ) ) { // WRCS: DEFINED_VERSION. if ( ! class_exists( 'ActionScheduler_Versions', false ) ) { require_once __DIR__ . '/classes/ActionScheduler_Versions.php'; add_action( 'plugins_loaded', array( 'ActionScheduler_Versions', 'initialize_latest_version' ), 1, 0 ); } add_action( 'plugins_loaded', 'action_scheduler_register_3_dot_8_dot_2', 0, 0 ); // WRCS: DEFINED_VERSION. // phpcs:disable Generic.Functions.OpeningFunctionBraceKernighanRitchie.ContentAfterBrace /** * Registers this version of Action Scheduler. */ function action_scheduler_register_3_dot_8_dot_2() { // WRCS: DEFINED_VERSION. $versions = ActionScheduler_Versions::instance(); $versions->register( '3.8.2', 'action_scheduler_initialize_3_dot_8_dot_2' ); // WRCS: DEFINED_VERSION. } // phpcs:disable Generic.Functions.OpeningFunctionBraceKernighanRitchie.ContentAfterBrace /** * Initializes this version of Action Scheduler. */ function action_scheduler_initialize_3_dot_8_dot_2() { // WRCS: DEFINED_VERSION. // A final safety check is required even here, because historic versions of Action Scheduler // followed a different pattern (in some unusual cases, we could reach this point and the // ActionScheduler class is already defined—so we need to guard against that). if ( ! class_exists( 'ActionScheduler', false ) ) { require_once __DIR__ . '/classes/abstracts/ActionScheduler.php'; ActionScheduler::init( __FILE__ ); } } // Support usage in themes - load this version if no plugin has loaded a version yet. if ( did_action( 'plugins_loaded' ) && ! doing_action( 'plugins_loaded' ) && ! class_exists( 'ActionScheduler', false ) ) { action_scheduler_initialize_3_dot_8_dot_2(); // WRCS: DEFINED_VERSION. do_action( 'action_scheduler_pre_theme_init' ); ActionScheduler_Versions::initialize_latest_version(); } } vendor/woocommerce/action-scheduler/lib/WP_Async_Request.php 0000644 00000007340 14720461212 0020266 0 ustar 00 <?php /** * WP Async Request * * @package WP-Background-Processing */ /* Library URI: https://github.com/deliciousbrains/wp-background-processing/blob/fbbc56f2480910d7959972ec9ec0819a13c6150a/classes/wp-async-request.php Author: Delicious Brains Inc. Author URI: https://deliciousbrains.com/ License: GNU General Public License v2.0 License URI: https://github.com/deliciousbrains/wp-background-processing/commit/126d7945dd3d39f39cb6488ca08fe1fb66cb351a */ if ( ! class_exists( 'WP_Async_Request' ) ) { /** * Abstract WP_Async_Request class. * * @abstract */ abstract class WP_Async_Request { /** * Prefix * * (default value: 'wp') * * @var string * @access protected */ protected $prefix = 'wp'; /** * Action * * (default value: 'async_request') * * @var string * @access protected */ protected $action = 'async_request'; /** * Identifier * * @var mixed * @access protected */ protected $identifier; /** * Data * * (default value: array()) * * @var array * @access protected */ protected $data = array(); /** * Initiate new async request */ public function __construct() { $this->identifier = $this->prefix . '_' . $this->action; add_action( 'wp_ajax_' . $this->identifier, array( $this, 'maybe_handle' ) ); add_action( 'wp_ajax_nopriv_' . $this->identifier, array( $this, 'maybe_handle' ) ); } /** * Set data used during the request * * @param array $data Data. * * @return $this */ public function data( $data ) { $this->data = $data; return $this; } /** * Dispatch the async request * * @return array|WP_Error */ public function dispatch() { $url = add_query_arg( $this->get_query_args(), $this->get_query_url() ); $args = $this->get_post_args(); return wp_remote_post( esc_url_raw( $url ), $args ); } /** * Get query args * * @return array */ protected function get_query_args() { if ( property_exists( $this, 'query_args' ) ) { return $this->query_args; } $args = array( 'action' => $this->identifier, 'nonce' => wp_create_nonce( $this->identifier ), ); /** * Filters the post arguments used during an async request. * * @param array $url */ return apply_filters( $this->identifier . '_query_args', $args ); } /** * Get query URL * * @return string */ protected function get_query_url() { if ( property_exists( $this, 'query_url' ) ) { return $this->query_url; } $url = admin_url( 'admin-ajax.php' ); /** * Filters the post arguments used during an async request. * * @param string $url */ return apply_filters( $this->identifier . '_query_url', $url ); } /** * Get post args * * @return array */ protected function get_post_args() { if ( property_exists( $this, 'post_args' ) ) { return $this->post_args; } $args = array( 'timeout' => 0.01, 'blocking' => false, 'body' => $this->data, 'cookies' => $_COOKIE, 'sslverify' => apply_filters( 'https_local_ssl_verify', false ), ); /** * Filters the post arguments used during an async request. * * @param array $args */ return apply_filters( $this->identifier . '_post_args', $args ); } /** * Maybe handle * * Check for correct nonce and pass to handler. */ public function maybe_handle() { // Don't lock up other requests while processing session_write_close(); check_ajax_referer( $this->identifier, 'nonce' ); $this->handle(); wp_die(); } /** * Handle * * Override this method to perform any actions required * during the async request. */ abstract protected function handle(); } } vendor/woocommerce/action-scheduler/lib/cron-expression/CronExpression_HoursField.php 0000644 00000002205 14720461212 0025331 0 ustar 00 <?php /** * Hours field. Allows: * , / - * * @author Michael Dowling <mtdowling@gmail.com> */ class CronExpression_HoursField extends CronExpression_AbstractField { /** * {@inheritdoc} */ public function isSatisfiedBy(DateTime $date, $value) { return $this->isSatisfied($date->format('H'), $value); } /** * {@inheritdoc} */ public function increment(DateTime $date, $invert = false) { // Change timezone to UTC temporarily. This will // allow us to go back or forwards and hour even // if DST will be changed between the hours. $timezone = $date->getTimezone(); $date->setTimezone(new DateTimeZone('UTC')); if ($invert) { $date->modify('-1 hour'); $date->setTime($date->format('H'), 59); } else { $date->modify('+1 hour'); $date->setTime($date->format('H'), 0); } $date->setTimezone($timezone); return $this; } /** * {@inheritdoc} */ public function validate($value) { return (bool) preg_match('/[\*,\/\-0-9]+/', $value); } } vendor/woocommerce/action-scheduler/lib/cron-expression/CronExpression_FieldFactory.php 0000644 00000003321 14720461212 0025640 0 ustar 00 <?php /** * CRON field factory implementing a flyweight factory * * @author Michael Dowling <mtdowling@gmail.com> * @link http://en.wikipedia.org/wiki/Cron */ class CronExpression_FieldFactory { /** * @var array Cache of instantiated fields */ private $fields = array(); /** * Get an instance of a field object for a cron expression position * * @param int $position CRON expression position value to retrieve * * @return CronExpression_FieldInterface * @throws InvalidArgumentException if a position is not valid */ public function getField($position) { if (!isset($this->fields[$position])) { switch ($position) { case 0: $this->fields[$position] = new CronExpression_MinutesField(); break; case 1: $this->fields[$position] = new CronExpression_HoursField(); break; case 2: $this->fields[$position] = new CronExpression_DayOfMonthField(); break; case 3: $this->fields[$position] = new CronExpression_MonthField(); break; case 4: $this->fields[$position] = new CronExpression_DayOfWeekField(); break; case 5: $this->fields[$position] = new CronExpression_YearField(); break; default: throw new InvalidArgumentException( $position . ' is not a valid position' ); } } return $this->fields[$position]; } } vendor/woocommerce/action-scheduler/lib/cron-expression/README.md 0000644 00000006277 14720461212 0021007 0 ustar 00 PHP Cron Expression Parser ========================== [![Latest Stable Version](https://poser.pugx.org/mtdowling/cron-expression/v/stable.png)](https://packagist.org/packages/mtdowling/cron-expression) [![Total Downloads](https://poser.pugx.org/mtdowling/cron-expression/downloads.png)](https://packagist.org/packages/mtdowling/cron-expression) [![Build Status](https://secure.travis-ci.org/mtdowling/cron-expression.png)](http://travis-ci.org/mtdowling/cron-expression) The PHP cron expression parser can parse a CRON expression, determine if it is due to run, calculate the next run date of the expression, and calculate the previous run date of the expression. You can calculate dates far into the future or past by skipping n number of matching dates. The parser can handle increments of ranges (e.g. */12, 2-59/3), intervals (e.g. 0-9), lists (e.g. 1,2,3), W to find the nearest weekday for a given day of the month, L to find the last day of the month, L to find the last given weekday of a month, and hash (#) to find the nth weekday of a given month. Credits ========== Created by Micheal Dowling. Ported to PHP 5.2 by Flightless, Inc. Based on version 1.0.3: https://github.com/mtdowling/cron-expression/tree/v1.0.3 Installing ========== Add the following to your project's composer.json: ```javascript { "require": { "mtdowling/cron-expression": "1.0.*" } } ``` Usage ===== ```php <?php require_once '/vendor/autoload.php'; // Works with predefined scheduling definitions $cron = Cron\CronExpression::factory('@daily'); $cron->isDue(); echo $cron->getNextRunDate()->format('Y-m-d H:i:s'); echo $cron->getPreviousRunDate()->format('Y-m-d H:i:s'); // Works with complex expressions $cron = Cron\CronExpression::factory('3-59/15 2,6-12 */15 1 2-5'); echo $cron->getNextRunDate()->format('Y-m-d H:i:s'); // Calculate a run date two iterations into the future $cron = Cron\CronExpression::factory('@daily'); echo $cron->getNextRunDate(null, 2)->format('Y-m-d H:i:s'); // Calculate a run date relative to a specific time $cron = Cron\CronExpression::factory('@monthly'); echo $cron->getNextRunDate('2010-01-12 00:00:00')->format('Y-m-d H:i:s'); ``` CRON Expressions ================ A CRON expression is a string representing the schedule for a particular command to execute. The parts of a CRON schedule are as follows: * * * * * * - - - - - - | | | | | | | | | | | + year [optional] | | | | +----- day of week (0 - 7) (Sunday=0 or 7) | | | +---------- month (1 - 12) | | +--------------- day of month (1 - 31) | +-------------------- hour (0 - 23) +------------------------- min (0 - 59) Requirements ============ - PHP 5.3+ - PHPUnit is required to run the unit tests - Composer is required to run the unit tests CHANGELOG ========= 1.0.3 (2013-11-23) ------------------ * Only set default timezone if the given $currentTime is not a DateTime instance (#34) * Fixes issue #28 where PHP increments of ranges were failing due to PHP casting hyphens to 0 * Now supports expressions with any number of extra spaces, tabs, or newlines * Using static instead of self in `CronExpression::factory` vendor/woocommerce/action-scheduler/lib/cron-expression/CronExpression_DayOfWeekField.php 0000644 00000007521 14720461212 0026055 0 ustar 00 <?php /** * Day of week field. Allows: * / , - ? L # * * Days of the week can be represented as a number 0-7 (0|7 = Sunday) * or as a three letter string: SUN, MON, TUE, WED, THU, FRI, SAT. * * 'L' stands for "last". It allows you to specify constructs such as * "the last Friday" of a given month. * * '#' is allowed for the day-of-week field, and must be followed by a * number between one and five. It allows you to specify constructs such as * "the second Friday" of a given month. * * @author Michael Dowling <mtdowling@gmail.com> */ class CronExpression_DayOfWeekField extends CronExpression_AbstractField { /** * {@inheritdoc} */ public function isSatisfiedBy(DateTime $date, $value) { if ($value == '?') { return true; } // Convert text day of the week values to integers $value = str_ireplace( array('SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'), range(0, 6), $value ); $currentYear = $date->format('Y'); $currentMonth = $date->format('m'); $lastDayOfMonth = $date->format('t'); // Find out if this is the last specific weekday of the month if (strpos($value, 'L')) { $weekday = str_replace('7', '0', substr($value, 0, strpos($value, 'L'))); $tdate = clone $date; $tdate->setDate($currentYear, $currentMonth, $lastDayOfMonth); while ($tdate->format('w') != $weekday) { $tdate->setDate($currentYear, $currentMonth, --$lastDayOfMonth); } return $date->format('j') == $lastDayOfMonth; } // Handle # hash tokens if (strpos($value, '#')) { list($weekday, $nth) = explode('#', $value); // Validate the hash fields if ($weekday < 1 || $weekday > 5) { throw new InvalidArgumentException("Weekday must be a value between 1 and 5. {$weekday} given"); } if ($nth > 5) { throw new InvalidArgumentException('There are never more than 5 of a given weekday in a month'); } // The current weekday must match the targeted weekday to proceed if ($date->format('N') != $weekday) { return false; } $tdate = clone $date; $tdate->setDate($currentYear, $currentMonth, 1); $dayCount = 0; $currentDay = 1; while ($currentDay < $lastDayOfMonth + 1) { if ($tdate->format('N') == $weekday) { if (++$dayCount >= $nth) { break; } } $tdate->setDate($currentYear, $currentMonth, ++$currentDay); } return $date->format('j') == $currentDay; } // Handle day of the week values if (strpos($value, '-')) { $parts = explode('-', $value); if ($parts[0] == '7') { $parts[0] = '0'; } elseif ($parts[1] == '0') { $parts[1] = '7'; } $value = implode('-', $parts); } // Test to see which Sunday to use -- 0 == 7 == Sunday $format = in_array(7, str_split($value)) ? 'N' : 'w'; $fieldValue = $date->format($format); return $this->isSatisfied($fieldValue, $value); } /** * {@inheritdoc} */ public function increment(DateTime $date, $invert = false) { if ($invert) { $date->modify('-1 day'); $date->setTime(23, 59, 0); } else { $date->modify('+1 day'); $date->setTime(0, 0, 0); } return $this; } /** * {@inheritdoc} */ public function validate($value) { return (bool) preg_match('/[\*,\/\-0-9A-Z]+/', $value); } } vendor/woocommerce/action-scheduler/lib/cron-expression/CronExpression.php 0000644 00000026536 14720461212 0023222 0 ustar 00 <?php /** * CRON expression parser that can determine whether or not a CRON expression is * due to run, the next run date and previous run date of a CRON expression. * The determinations made by this class are accurate if checked run once per * minute (seconds are dropped from date time comparisons). * * Schedule parts must map to: * minute [0-59], hour [0-23], day of month, month [1-12|JAN-DEC], day of week * [1-7|MON-SUN], and an optional year. * * @author Michael Dowling <mtdowling@gmail.com> * @link http://en.wikipedia.org/wiki/Cron */ class CronExpression { const MINUTE = 0; const HOUR = 1; const DAY = 2; const MONTH = 3; const WEEKDAY = 4; const YEAR = 5; /** * @var array CRON expression parts */ private $cronParts; /** * @var CronExpression_FieldFactory CRON field factory */ private $fieldFactory; /** * @var array Order in which to test of cron parts */ private static $order = array(self::YEAR, self::MONTH, self::DAY, self::WEEKDAY, self::HOUR, self::MINUTE); /** * Factory method to create a new CronExpression. * * @param string $expression The CRON expression to create. There are * several special predefined values which can be used to substitute the * CRON expression: * * @yearly, @annually) - Run once a year, midnight, Jan. 1 - 0 0 1 1 * * @monthly - Run once a month, midnight, first of month - 0 0 1 * * * @weekly - Run once a week, midnight on Sun - 0 0 * * 0 * @daily - Run once a day, midnight - 0 0 * * * * @hourly - Run once an hour, first minute - 0 * * * * * *@param CronExpression_FieldFactory $fieldFactory (optional) Field factory to use * * @return CronExpression */ public static function factory($expression, CronExpression_FieldFactory $fieldFactory = null) { $mappings = array( '@yearly' => '0 0 1 1 *', '@annually' => '0 0 1 1 *', '@monthly' => '0 0 1 * *', '@weekly' => '0 0 * * 0', '@daily' => '0 0 * * *', '@hourly' => '0 * * * *' ); if (isset($mappings[$expression])) { $expression = $mappings[$expression]; } return new self($expression, $fieldFactory ? $fieldFactory : new CronExpression_FieldFactory()); } /** * Parse a CRON expression * * @param string $expression CRON expression (e.g. '8 * * * *') * @param CronExpression_FieldFactory $fieldFactory Factory to create cron fields */ public function __construct($expression, CronExpression_FieldFactory $fieldFactory) { $this->fieldFactory = $fieldFactory; $this->setExpression($expression); } /** * Set or change the CRON expression * * @param string $value CRON expression (e.g. 8 * * * *) * * @return CronExpression * @throws InvalidArgumentException if not a valid CRON expression */ public function setExpression($value) { $this->cronParts = preg_split('/\s/', $value, -1, PREG_SPLIT_NO_EMPTY); if (count($this->cronParts) < 5) { throw new InvalidArgumentException( $value . ' is not a valid CRON expression' ); } foreach ($this->cronParts as $position => $part) { $this->setPart($position, $part); } return $this; } /** * Set part of the CRON expression * * @param int $position The position of the CRON expression to set * @param string $value The value to set * * @return CronExpression * @throws InvalidArgumentException if the value is not valid for the part */ public function setPart($position, $value) { if (!$this->fieldFactory->getField($position)->validate($value)) { throw new InvalidArgumentException( 'Invalid CRON field value ' . $value . ' as position ' . $position ); } $this->cronParts[$position] = $value; return $this; } /** * Get a next run date relative to the current date or a specific date * * @param string|DateTime $currentTime (optional) Relative calculation date * @param int $nth (optional) Number of matches to skip before returning a * matching next run date. 0, the default, will return the current * date and time if the next run date falls on the current date and * time. Setting this value to 1 will skip the first match and go to * the second match. Setting this value to 2 will skip the first 2 * matches and so on. * @param bool $allowCurrentDate (optional) Set to TRUE to return the * current date if it matches the cron expression * * @return DateTime * @throws RuntimeException on too many iterations */ public function getNextRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false) { return $this->getRunDate($currentTime, $nth, false, $allowCurrentDate); } /** * Get a previous run date relative to the current date or a specific date * * @param string|DateTime $currentTime (optional) Relative calculation date * @param int $nth (optional) Number of matches to skip before returning * @param bool $allowCurrentDate (optional) Set to TRUE to return the * current date if it matches the cron expression * * @return DateTime * @throws RuntimeException on too many iterations * @see CronExpression::getNextRunDate */ public function getPreviousRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false) { return $this->getRunDate($currentTime, $nth, true, $allowCurrentDate); } /** * Get multiple run dates starting at the current date or a specific date * * @param int $total Set the total number of dates to calculate * @param string|DateTime $currentTime (optional) Relative calculation date * @param bool $invert (optional) Set to TRUE to retrieve previous dates * @param bool $allowCurrentDate (optional) Set to TRUE to return the * current date if it matches the cron expression * * @return array Returns an array of run dates */ public function getMultipleRunDates($total, $currentTime = 'now', $invert = false, $allowCurrentDate = false) { $matches = array(); for ($i = 0; $i < max(0, $total); $i++) { $matches[] = $this->getRunDate($currentTime, $i, $invert, $allowCurrentDate); } return $matches; } /** * Get all or part of the CRON expression * * @param string $part (optional) Specify the part to retrieve or NULL to * get the full cron schedule string. * * @return string|null Returns the CRON expression, a part of the * CRON expression, or NULL if the part was specified but not found */ public function getExpression($part = null) { if (null === $part) { return implode(' ', $this->cronParts); } elseif (array_key_exists($part, $this->cronParts)) { return $this->cronParts[$part]; } return null; } /** * Helper method to output the full expression. * * @return string Full CRON expression */ public function __toString() { return $this->getExpression(); } /** * Determine if the cron is due to run based on the current date or a * specific date. This method assumes that the current number of * seconds are irrelevant, and should be called once per minute. * * @param string|DateTime $currentTime (optional) Relative calculation date * * @return bool Returns TRUE if the cron is due to run or FALSE if not */ public function isDue($currentTime = 'now') { if ('now' === $currentTime) { $currentDate = date('Y-m-d H:i'); $currentTime = strtotime($currentDate); } elseif ($currentTime instanceof DateTime) { $currentDate = $currentTime->format('Y-m-d H:i'); $currentTime = strtotime($currentDate); } else { $currentTime = new DateTime($currentTime); $currentTime->setTime($currentTime->format('H'), $currentTime->format('i'), 0); $currentDate = $currentTime->format('Y-m-d H:i'); $currentTime = (int)($currentTime->getTimestamp()); } return $this->getNextRunDate($currentDate, 0, true)->getTimestamp() == $currentTime; } /** * Get the next or previous run date of the expression relative to a date * * @param string|DateTime $currentTime (optional) Relative calculation date * @param int $nth (optional) Number of matches to skip before returning * @param bool $invert (optional) Set to TRUE to go backwards in time * @param bool $allowCurrentDate (optional) Set to TRUE to return the * current date if it matches the cron expression * * @return DateTime * @throws RuntimeException on too many iterations */ protected function getRunDate($currentTime = null, $nth = 0, $invert = false, $allowCurrentDate = false) { if ($currentTime instanceof DateTime) { $currentDate = $currentTime; } else { $currentDate = new DateTime($currentTime ? $currentTime : 'now'); $currentDate->setTimezone(new DateTimeZone(date_default_timezone_get())); } $currentDate->setTime($currentDate->format('H'), $currentDate->format('i'), 0); $nextRun = clone $currentDate; $nth = (int) $nth; // Set a hard limit to bail on an impossible date for ($i = 0; $i < 1000; $i++) { foreach (self::$order as $position) { $part = $this->getExpression($position); if (null === $part) { continue; } $satisfied = false; // Get the field object used to validate this part $field = $this->fieldFactory->getField($position); // Check if this is singular or a list if (strpos($part, ',') === false) { $satisfied = $field->isSatisfiedBy($nextRun, $part); } else { foreach (array_map('trim', explode(',', $part)) as $listPart) { if ($field->isSatisfiedBy($nextRun, $listPart)) { $satisfied = true; break; } } } // If the field is not satisfied, then start over if (!$satisfied) { $field->increment($nextRun, $invert); continue 2; } } // Skip this match if needed if ((!$allowCurrentDate && $nextRun == $currentDate) || --$nth > -1) { $this->fieldFactory->getField(0)->increment($nextRun, $invert); continue; } return $nextRun; } // @codeCoverageIgnoreStart throw new RuntimeException('Impossible CRON expression'); // @codeCoverageIgnoreEnd } } vendor/woocommerce/action-scheduler/lib/cron-expression/CronExpression_MinutesField.php 0000644 00000001371 14720461212 0025660 0 ustar 00 <?php /** * Minutes field. Allows: * , / - * * @author Michael Dowling <mtdowling@gmail.com> */ class CronExpression_MinutesField extends CronExpression_AbstractField { /** * {@inheritdoc} */ public function isSatisfiedBy(DateTime $date, $value) { return $this->isSatisfied($date->format('i'), $value); } /** * {@inheritdoc} */ public function increment(DateTime $date, $invert = false) { if ($invert) { $date->modify('-1 minute'); } else { $date->modify('+1 minute'); } return $this; } /** * {@inheritdoc} */ public function validate($value) { return (bool) preg_match('/[\*,\/\-0-9]+/', $value); } } vendor/woocommerce/action-scheduler/lib/cron-expression/LICENSE 0000644 00000002112 14720461212 0020515 0 ustar 00 Copyright (c) 2011 Michael Dowling <mtdowling@gmail.com> and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. vendor/woocommerce/action-scheduler/lib/cron-expression/CronExpression_YearField.php 0000644 00000001651 14720461212 0025135 0 ustar 00 <?php /** * Year field. Allows: * , / - * * @author Michael Dowling <mtdowling@gmail.com> */ class CronExpression_YearField extends CronExpression_AbstractField { /** * {@inheritdoc} */ public function isSatisfiedBy(DateTime $date, $value) { return $this->isSatisfied($date->format('Y'), $value); } /** * {@inheritdoc} */ public function increment(DateTime $date, $invert = false) { if ($invert) { $date->modify('-1 year'); $date->setDate($date->format('Y'), 12, 31); $date->setTime(23, 59, 0); } else { $date->modify('+1 year'); $date->setDate($date->format('Y'), 1, 1); $date->setTime(0, 0, 0); } return $this; } /** * {@inheritdoc} */ public function validate($value) { return (bool) preg_match('/[\*,\/\-0-9]+/', $value); } } vendor/woocommerce/action-scheduler/lib/cron-expression/CronExpression_DayOfMonthField.php 0000644 00000007014 14720461212 0026244 0 ustar 00 <?php /** * Day of month field. Allows: * , / - ? L W * * 'L' stands for "last" and specifies the last day of the month. * * The 'W' character is used to specify the weekday (Monday-Friday) nearest the * given day. As an example, if you were to specify "15W" as the value for the * day-of-month field, the meaning is: "the nearest weekday to the 15th of the * month". So if the 15th is a Saturday, the trigger will fire on Friday the * 14th. If the 15th is a Sunday, the trigger will fire on Monday the 16th. If * the 15th is a Tuesday, then it will fire on Tuesday the 15th. However if you * specify "1W" as the value for day-of-month, and the 1st is a Saturday, the * trigger will fire on Monday the 3rd, as it will not 'jump' over the boundary * of a month's days. The 'W' character can only be specified when the * day-of-month is a single day, not a range or list of days. * * @author Michael Dowling <mtdowling@gmail.com> */ class CronExpression_DayOfMonthField extends CronExpression_AbstractField { /** * Get the nearest day of the week for a given day in a month * * @param int $currentYear Current year * @param int $currentMonth Current month * @param int $targetDay Target day of the month * * @return DateTime Returns the nearest date */ private static function getNearestWeekday($currentYear, $currentMonth, $targetDay) { $tday = str_pad($targetDay, 2, '0', STR_PAD_LEFT); $target = new DateTime("$currentYear-$currentMonth-$tday"); $currentWeekday = (int) $target->format('N'); if ($currentWeekday < 6) { return $target; } $lastDayOfMonth = $target->format('t'); foreach (array(-1, 1, -2, 2) as $i) { $adjusted = $targetDay + $i; if ($adjusted > 0 && $adjusted <= $lastDayOfMonth) { $target->setDate($currentYear, $currentMonth, $adjusted); if ($target->format('N') < 6 && $target->format('m') == $currentMonth) { return $target; } } } } /** * {@inheritdoc} */ public function isSatisfiedBy(DateTime $date, $value) { // ? states that the field value is to be skipped if ($value == '?') { return true; } $fieldValue = $date->format('d'); // Check to see if this is the last day of the month if ($value == 'L') { return $fieldValue == $date->format('t'); } // Check to see if this is the nearest weekday to a particular value if (strpos($value, 'W')) { // Parse the target day $targetDay = substr($value, 0, strpos($value, 'W')); // Find out if the current day is the nearest day of the week return $date->format('j') == self::getNearestWeekday( $date->format('Y'), $date->format('m'), $targetDay )->format('j'); } return $this->isSatisfied($date->format('d'), $value); } /** * {@inheritdoc} */ public function increment(DateTime $date, $invert = false) { if ($invert) { $date->modify('previous day'); $date->setTime(23, 59); } else { $date->modify('next day'); $date->setTime(0, 0); } return $this; } /** * {@inheritdoc} */ public function validate($value) { return (bool) preg_match('/[\*,\/\-\?LW0-9A-Za-z]+/', $value); } } vendor/woocommerce/action-scheduler/lib/cron-expression/CronExpression_FieldInterface.php 0000644 00000002162 14720461212 0026133 0 ustar 00 <?php /** * CRON field interface * * @author Michael Dowling <mtdowling@gmail.com> */ interface CronExpression_FieldInterface { /** * Check if the respective value of a DateTime field satisfies a CRON exp * * @param DateTime $date DateTime object to check * @param string $value CRON expression to test against * * @return bool Returns TRUE if satisfied, FALSE otherwise */ public function isSatisfiedBy(DateTime $date, $value); /** * When a CRON expression is not satisfied, this method is used to increment * or decrement a DateTime object by the unit of the cron field * * @param DateTime $date DateTime object to change * @param bool $invert (optional) Set to TRUE to decrement * * @return CronExpression_FieldInterface */ public function increment(DateTime $date, $invert = false); /** * Validates a CRON expression for a given field * * @param string $value CRON expression value to validate * * @return bool Returns TRUE if valid, FALSE otherwise */ public function validate($value); } vendor/woocommerce/action-scheduler/lib/cron-expression/CronExpression_MonthField.php 0000644 00000002567 14720461212 0025331 0 ustar 00 <?php /** * Month field. Allows: * , / - * * @author Michael Dowling <mtdowling@gmail.com> */ class CronExpression_MonthField extends CronExpression_AbstractField { /** * {@inheritdoc} */ public function isSatisfiedBy(DateTime $date, $value) { // Convert text month values to integers $value = str_ireplace( array( 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC' ), range(1, 12), $value ); return $this->isSatisfied($date->format('m'), $value); } /** * {@inheritdoc} */ public function increment(DateTime $date, $invert = false) { if ($invert) { // $date->modify('last day of previous month'); // remove for php 5.2 compat $date->modify('previous month'); $date->modify($date->format('Y-m-t')); $date->setTime(23, 59); } else { //$date->modify('first day of next month'); // remove for php 5.2 compat $date->modify('next month'); $date->modify($date->format('Y-m-01')); $date->setTime(0, 0); } return $this; } /** * {@inheritdoc} */ public function validate($value) { return (bool) preg_match('/[\*,\/\-0-9A-Z]+/', $value); } } vendor/woocommerce/action-scheduler/lib/cron-expression/CronExpression_AbstractField.php 0000644 00000005020 14720461212 0025772 0 ustar 00 <?php /** * Abstract CRON expression field * * @author Michael Dowling <mtdowling@gmail.com> */ abstract class CronExpression_AbstractField implements CronExpression_FieldInterface { /** * Check to see if a field is satisfied by a value * * @param string $dateValue Date value to check * @param string $value Value to test * * @return bool */ public function isSatisfied($dateValue, $value) { if ($this->isIncrementsOfRanges($value)) { return $this->isInIncrementsOfRanges($dateValue, $value); } elseif ($this->isRange($value)) { return $this->isInRange($dateValue, $value); } return $value == '*' || $dateValue == $value; } /** * Check if a value is a range * * @param string $value Value to test * * @return bool */ public function isRange($value) { return strpos($value, '-') !== false; } /** * Check if a value is an increments of ranges * * @param string $value Value to test * * @return bool */ public function isIncrementsOfRanges($value) { return strpos($value, '/') !== false; } /** * Test if a value is within a range * * @param string $dateValue Set date value * @param string $value Value to test * * @return bool */ public function isInRange($dateValue, $value) { $parts = array_map('trim', explode('-', $value, 2)); return $dateValue >= $parts[0] && $dateValue <= $parts[1]; } /** * Test if a value is within an increments of ranges (offset[-to]/step size) * * @param string $dateValue Set date value * @param string $value Value to test * * @return bool */ public function isInIncrementsOfRanges($dateValue, $value) { $parts = array_map('trim', explode('/', $value, 2)); $stepSize = isset($parts[1]) ? $parts[1] : 0; if ($parts[0] == '*' || $parts[0] === '0') { return (int) $dateValue % $stepSize == 0; } $range = explode('-', $parts[0], 2); $offset = $range[0]; $to = isset($range[1]) ? $range[1] : $dateValue; // Ensure that the date value is within the range if ($dateValue < $offset || $dateValue > $to) { return false; } for ($i = $offset; $i <= $to; $i+= $stepSize) { if ($i == $dateValue) { return true; } } return false; } } vendor/woocommerce/action-scheduler/deprecated/functions.php 0000644 00000011766 14720461212 0020444 0 ustar 00 <?php /** * Deprecated API functions for scheduling actions * * Functions with the wc prefix were deprecated to avoid confusion with * Action Scheduler being included in WooCommerce core, and it providing * a different set of APIs for working with the action queue. */ /** * Schedule an action to run one time * * @param int $timestamp When the job will run * @param string $hook The hook to trigger * @param array $args Arguments to pass when the hook triggers * @param string $group The group to assign this job to * * @return string The job ID */ function wc_schedule_single_action( $timestamp, $hook, $args = array(), $group = '' ) { _deprecated_function( __FUNCTION__, '2.1.0', 'as_schedule_single_action()' ); return as_schedule_single_action( $timestamp, $hook, $args, $group ); } /** * Schedule a recurring action * * @param int $timestamp When the first instance of the job will run * @param int $interval_in_seconds How long to wait between runs * @param string $hook The hook to trigger * @param array $args Arguments to pass when the hook triggers * @param string $group The group to assign this job to * * @deprecated 2.1.0 * * @return string The job ID */ function wc_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args = array(), $group = '' ) { _deprecated_function( __FUNCTION__, '2.1.0', 'as_schedule_recurring_action()' ); return as_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args, $group ); } /** * Schedule an action that recurs on a cron-like schedule. * * @param int $timestamp The schedule will start on or after this time * @param string $schedule A cron-link schedule string * @see http://en.wikipedia.org/wiki/Cron * * * * * * * * ┬ ┬ ┬ ┬ ┬ ┬ * | | | | | | * | | | | | + year [optional] * | | | | +----- day of week (0 - 7) (Sunday=0 or 7) * | | | +---------- month (1 - 12) * | | +--------------- day of month (1 - 31) * | +-------------------- hour (0 - 23) * +------------------------- min (0 - 59) * @param string $hook The hook to trigger * @param array $args Arguments to pass when the hook triggers * @param string $group The group to assign this job to * * @deprecated 2.1.0 * * @return string The job ID */ function wc_schedule_cron_action( $timestamp, $schedule, $hook, $args = array(), $group = '' ) { _deprecated_function( __FUNCTION__, '2.1.0', 'as_schedule_cron_action()' ); return as_schedule_cron_action( $timestamp, $schedule, $hook, $args, $group ); } /** * Cancel the next occurrence of a job. * * @param string $hook The hook that the job will trigger * @param array $args Args that would have been passed to the job * @param string $group * * @deprecated 2.1.0 */ function wc_unschedule_action( $hook, $args = array(), $group = '' ) { _deprecated_function( __FUNCTION__, '2.1.0', 'as_unschedule_action()' ); as_unschedule_action( $hook, $args, $group ); } /** * @param string $hook * @param array $args * @param string $group * * @deprecated 2.1.0 * * @return int|bool The timestamp for the next occurrence, or false if nothing was found */ function wc_next_scheduled_action( $hook, $args = NULL, $group = '' ) { _deprecated_function( __FUNCTION__, '2.1.0', 'as_next_scheduled_action()' ); return as_next_scheduled_action( $hook, $args, $group ); } /** * Find scheduled actions * * @param array $args Possible arguments, with their default values: * 'hook' => '' - the name of the action that will be triggered * 'args' => NULL - the args array that will be passed with the action * 'date' => NULL - the scheduled date of the action. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone. * 'date_compare' => '<=' - operator for testing "date". accepted values are '!=', '>', '>=', '<', '<=', '=' * 'modified' => NULL - the date the action was last updated. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone. * 'modified_compare' => '<=' - operator for testing "modified". accepted values are '!=', '>', '>=', '<', '<=', '=' * 'group' => '' - the group the action belongs to * 'status' => '' - ActionScheduler_Store::STATUS_COMPLETE or ActionScheduler_Store::STATUS_PENDING * 'claimed' => NULL - TRUE to find claimed actions, FALSE to find unclaimed actions, a string to find a specific claim ID * 'per_page' => 5 - Number of results to return * 'offset' => 0 * 'orderby' => 'date' - accepted values are 'hook', 'group', 'modified', or 'date' * 'order' => 'ASC' * @param string $return_format OBJECT, ARRAY_A, or ids * * @deprecated 2.1.0 * * @return array */ function wc_get_scheduled_actions( $args = array(), $return_format = OBJECT ) { _deprecated_function( __FUNCTION__, '2.1.0', 'as_get_scheduled_actions()' ); return as_get_scheduled_actions( $args, $return_format ); } vendor/woocommerce/action-scheduler/deprecated/ActionScheduler_Store_Deprecated.php 0000644 00000002040 14720461212 0024765 0 ustar 00 <?php /** * Class ActionScheduler_Store_Deprecated * @codeCoverageIgnore */ abstract class ActionScheduler_Store_Deprecated { /** * Mark an action that failed to fetch correctly as failed. * * @since 2.2.6 * * @param int $action_id The ID of the action. */ public function mark_failed_fetch_action( $action_id ) { _deprecated_function( __METHOD__, '3.0.0', 'ActionScheduler_Store::mark_failure()' ); self::$store->mark_failure( $action_id ); } /** * Add base hooks * * @since 2.2.6 */ protected static function hook() { _deprecated_function( __METHOD__, '3.0.0' ); } /** * Remove base hooks * * @since 2.2.6 */ protected static function unhook() { _deprecated_function( __METHOD__, '3.0.0' ); } /** * Get the site's local time. * * @deprecated 2.1.0 * @return DateTimeZone */ protected function get_local_timezone() { _deprecated_function( __FUNCTION__, '2.1.0', 'ActionScheduler_TimezoneHelper::set_local_timezone()' ); return ActionScheduler_TimezoneHelper::get_local_timezone(); } } vendor/woocommerce/action-scheduler/deprecated/ActionScheduler_Schedule_Deprecated.php 0000644 00000001477 14720461212 0025442 0 ustar 00 <?php /** * Class ActionScheduler_Abstract_Schedule */ abstract class ActionScheduler_Schedule_Deprecated implements ActionScheduler_Schedule { /** * Get the date & time this schedule was created to run, or calculate when it should be run * after a given date & time. * * @param DateTime $after DateTime to calculate against. * * @return DateTime|null */ public function next( DateTime $after = null ) { if ( empty( $after ) ) { $return_value = $this->get_date(); $replacement_method = 'get_date()'; } else { $return_value = $this->get_next( $after ); $replacement_method = 'get_next( $after )'; } _deprecated_function( __METHOD__, '3.0.0', __CLASS__ . '::' . $replacement_method ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped return $return_value; } } vendor/woocommerce/action-scheduler/deprecated/ActionScheduler_Abstract_QueueRunner_Deprecated.php 0000644 00000001523 14720461212 0027777 0 ustar 00 <?php /** * Abstract class with common Queue Cleaner functionality. */ abstract class ActionScheduler_Abstract_QueueRunner_Deprecated { /** * Get the maximum number of seconds a batch can run for. * * @deprecated 2.1.1 * @return int The number of seconds. */ protected function get_maximum_execution_time() { _deprecated_function( __METHOD__, '2.1.1', 'ActionScheduler_Abstract_QueueRunner::get_time_limit()' ); $maximum_execution_time = 30; // Apply deprecated filter if ( has_filter( 'action_scheduler_maximum_execution_time' ) ) { _deprecated_function( 'action_scheduler_maximum_execution_time', '2.1.1', 'action_scheduler_queue_runner_time_limit' ); $maximum_execution_time = apply_filters( 'action_scheduler_maximum_execution_time', $maximum_execution_time ); } return absint( $maximum_execution_time ); } } vendor/woocommerce/action-scheduler/deprecated/ActionScheduler_AdminView_Deprecated.php 0000644 00000012507 14720461212 0025565 0 ustar 00 <?php /** * Class ActionScheduler_AdminView_Deprecated * * Store deprecated public functions previously found in the ActionScheduler_AdminView class. * Keeps them out of the way of the main class. * * @codeCoverageIgnore */ class ActionScheduler_AdminView_Deprecated { public function action_scheduler_post_type_args( $args ) { _deprecated_function( __METHOD__, '2.0.0' ); return $args; } /** * Customise the post status related views displayed on the Scheduled Actions administration screen. * * @param array $views An associative array of views and view labels which can be used to filter the 'scheduled-action' posts displayed on the Scheduled Actions administration screen. * @return array $views An associative array of views and view labels which can be used to filter the 'scheduled-action' posts displayed on the Scheduled Actions administration screen. */ public function list_table_views( $views ) { _deprecated_function( __METHOD__, '2.0.0' ); return $views; } /** * Do not include the "Edit" action for the Scheduled Actions administration screen. * * Hooked to the 'bulk_actions-edit-action-scheduler' filter. * * @param array $actions An associative array of actions which can be performed on the 'scheduled-action' post type. * @return array $actions An associative array of actions which can be performed on the 'scheduled-action' post type. */ public function bulk_actions( $actions ) { _deprecated_function( __METHOD__, '2.0.0' ); return $actions; } /** * Completely customer the columns displayed on the Scheduled Actions administration screen. * * Because we can't filter the content of the default title and date columns, we need to recreate our own * custom columns for displaying those post fields. For the column content, @see self::list_table_column_content(). * * @param array $columns An associative array of columns that are use for the table on the Scheduled Actions administration screen. * @return array $columns An associative array of columns that are use for the table on the Scheduled Actions administration screen. */ public function list_table_columns( $columns ) { _deprecated_function( __METHOD__, '2.0.0' ); return $columns; } /** * Make our custom title & date columns use defaulting title & date sorting. * * @param array $columns An associative array of columns that can be used to sort the table on the Scheduled Actions administration screen. * @return array $columns An associative array of columns that can be used to sort the table on the Scheduled Actions administration screen. */ public static function list_table_sortable_columns( $columns ) { _deprecated_function( __METHOD__, '2.0.0' ); return $columns; } /** * Print the content for our custom columns. * * @param string $column_name The key for the column for which we should output our content. * @param int $post_id The ID of the 'scheduled-action' post for which this row relates. */ public static function list_table_column_content( $column_name, $post_id ) { _deprecated_function( __METHOD__, '2.0.0' ); } /** * Hide the inline "Edit" action for all 'scheduled-action' posts. * * Hooked to the 'post_row_actions' filter. * * @param array $actions An associative array of actions which can be performed on the 'scheduled-action' post type. * @return array $actions An associative array of actions which can be performed on the 'scheduled-action' post type. */ public static function row_actions( $actions, $post ) { _deprecated_function( __METHOD__, '2.0.0' ); return $actions; } /** * Run an action when triggered from the Action Scheduler administration screen. * * @codeCoverageIgnore */ public static function maybe_execute_action() { _deprecated_function( __METHOD__, '2.0.0' ); } /** * Convert an interval of seconds into a two part human friendly string. * * The WordPress human_time_diff() function only calculates the time difference to one degree, meaning * even if an action is 1 day and 11 hours away, it will display "1 day". This function goes one step * further to display two degrees of accuracy. * * Based on Crontrol::interval() function by Edward Dale: https://wordpress.org/plugins/wp-crontrol/ * * @param int $interval A interval in seconds. * @return string A human friendly string representation of the interval. */ public static function admin_notices() { _deprecated_function( __METHOD__, '2.0.0' ); } /** * Filter search queries to allow searching by Claim ID (i.e. post_password). * * @param string $orderby MySQL orderby string. * @param WP_Query $query Instance of a WP_Query object * @return string MySQL orderby string. */ public function custom_orderby( $orderby, $query ){ _deprecated_function( __METHOD__, '2.0.0' ); } /** * Filter search queries to allow searching by Claim ID (i.e. post_password). * * @param string $search MySQL search string. * @param WP_Query $query Instance of a WP_Query object * @return string MySQL search string. */ public function search_post_password( $search, $query ) { _deprecated_function( __METHOD__, '2.0.0' ); } /** * Change messages when a scheduled action is updated. * * @param array $messages * @return array */ public function post_updated_messages( $messages ) { _deprecated_function( __METHOD__, '2.0.0' ); return $messages; } } vendor/composer/platform_check.php 0000644 00000001635 14720461212 0013366 0 ustar 00 <?php // platform_check.php @generated by Composer $issues = array(); if (!(PHP_VERSION_ID >= 70000)) { $issues[] = 'Your Composer dependencies require a PHP version ">= 7.0.0". You are running ' . PHP_VERSION . '.'; } if ($issues) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); } elseif (!headers_sent()) { echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; } } trigger_error( 'Composer detected issues in your platform: ' . implode(' ', $issues), E_USER_ERROR ); } vendor/composer/autoload_real.php 0000644 00000002161 14720461212 0013213 0 ustar 00 <?php // autoload_real.php @generated by Composer class ComposerAutoloaderInit4cf7848c3d7e3b30582e3c6bcdb292a6 { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } /** * @return \Composer\Autoload\ClassLoader */ public static function getLoader() { if (null !== self::$loader) { return self::$loader; } require __DIR__ . '/platform_check.php'; spl_autoload_register(array('ComposerAutoloaderInit4cf7848c3d7e3b30582e3c6bcdb292a6', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); spl_autoload_unregister(array('ComposerAutoloaderInit4cf7848c3d7e3b30582e3c6bcdb292a6', 'loadClassLoader')); require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInit4cf7848c3d7e3b30582e3c6bcdb292a6::getInitializer($loader)); $loader->register(true); return $loader; } } vendor/composer/autoload_static.php 0000644 00000001050 14720461212 0013553 0 ustar 00 <?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInit4cf7848c3d7e3b30582e3c6bcdb292a6 { public static $classMap = array ( 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->classMap = ComposerStaticInit4cf7848c3d7e3b30582e3c6bcdb292a6::$classMap; }, null, ClassLoader::class); } } vendor/composer/autoload_namespaces.php 0000644 00000000213 14720461212 0014403 0 ustar 00 <?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( ); vendor/composer/installed.json 0000644 00000004056 14720461212 0012546 0 ustar 00 { "packages": [ { "name": "woocommerce/action-scheduler", "version": "3.8.2", "version_normalized": "3.8.2.0", "source": { "type": "git", "url": "https://github.com/woocommerce/action-scheduler.git", "reference": "2bc91d88fdbc2c07ab899cbb56b983e11e62cf69" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/woocommerce/action-scheduler/zipball/2bc91d88fdbc2c07ab899cbb56b983e11e62cf69", "reference": "2bc91d88fdbc2c07ab899cbb56b983e11e62cf69", "shasum": "" }, "require": { "php": ">=7.0" }, "require-dev": { "phpunit/phpunit": "^7.5", "woocommerce/woocommerce-sniffs": "0.1.0", "wp-cli/wp-cli": "~2.5.0", "yoast/phpunit-polyfills": "^2.0" }, "time": "2024-09-12T23:12:58+00:00", "type": "wordpress-plugin", "extra": { "scripts-description": { "test": "Run unit tests", "phpcs": "Analyze code against the WordPress coding standards with PHP_CodeSniffer", "phpcbf": "Fix coding standards warnings/errors automatically with PHP Code Beautifier" } }, "installation-source": "dist", "notification-url": "https://packagist.org/downloads/", "license": [ "GPL-3.0-or-later" ], "description": "Action Scheduler for WordPress and WooCommerce", "homepage": "https://actionscheduler.org/", "support": { "issues": "https://github.com/woocommerce/action-scheduler/issues", "source": "https://github.com/woocommerce/action-scheduler/tree/3.8.2" }, "install-path": "../woocommerce/action-scheduler" } ], "dev": false, "dev-package-names": [] } vendor/composer/ClassLoader.php 0000644 00000037772 14720461212 0012614 0 ustar 00 <?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Autoload; /** * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. * * $loader = new \Composer\Autoload\ClassLoader(); * * // register classes with namespaces * $loader->add('Symfony\Component', __DIR__.'/component'); * $loader->add('Symfony', __DIR__.'/framework'); * * // activate the autoloader * $loader->register(); * * // to enable searching the include path (eg. for PEAR packages) * $loader->setUseIncludePath(true); * * In this example, if you try to use a class in the Symfony\Component * namespace or one of its children (Symfony\Component\Console for instance), * the autoloader will first look for the class under the component/ * directory, and it will then fallback to the framework/ directory if not * found before giving up. * * This class is loosely based on the Symfony UniversalClassLoader. * * @author Fabien Potencier <fabien@symfony.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @see https://www.php-fig.org/psr/psr-0/ * @see https://www.php-fig.org/psr/psr-4/ */ class ClassLoader { /** @var \Closure(string):void */ private static $includeFile; /** @var string|null */ private $vendorDir; // PSR-4 /** * @var array<string, array<string, int>> */ private $prefixLengthsPsr4 = array(); /** * @var array<string, list<string>> */ private $prefixDirsPsr4 = array(); /** * @var list<string> */ private $fallbackDirsPsr4 = array(); // PSR-0 /** * List of PSR-0 prefixes * * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2'))) * * @var array<string, array<string, list<string>>> */ private $prefixesPsr0 = array(); /** * @var list<string> */ private $fallbackDirsPsr0 = array(); /** @var bool */ private $useIncludePath = false; /** * @var array<string, string> */ private $classMap = array(); /** @var bool */ private $classMapAuthoritative = false; /** * @var array<string, bool> */ private $missingClasses = array(); /** @var string|null */ private $apcuPrefix; /** * @var array<string, self> */ private static $registeredLoaders = array(); /** * @param string|null $vendorDir */ public function __construct($vendorDir = null) { $this->vendorDir = $vendorDir; self::initializeIncludeClosure(); } /** * @return array<string, list<string>> */ public function getPrefixes() { if (!empty($this->prefixesPsr0)) { return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); } return array(); } /** * @return array<string, list<string>> */ public function getPrefixesPsr4() { return $this->prefixDirsPsr4; } /** * @return list<string> */ public function getFallbackDirs() { return $this->fallbackDirsPsr0; } /** * @return list<string> */ public function getFallbackDirsPsr4() { return $this->fallbackDirsPsr4; } /** * @return array<string, string> Array of classname => path */ public function getClassMap() { return $this->classMap; } /** * @param array<string, string> $classMap Class to filename map * * @return void */ public function addClassMap(array $classMap) { if ($this->classMap) { $this->classMap = array_merge($this->classMap, $classMap); } else { $this->classMap = $classMap; } } /** * Registers a set of PSR-0 directories for a given prefix, either * appending or prepending to the ones previously set for this prefix. * * @param string $prefix The prefix * @param list<string>|string $paths The PSR-0 root directories * @param bool $prepend Whether to prepend the directories * * @return void */ public function add($prefix, $paths, $prepend = false) { $paths = (array) $paths; if (!$prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( $paths, $this->fallbackDirsPsr0 ); } else { $this->fallbackDirsPsr0 = array_merge( $this->fallbackDirsPsr0, $paths ); } return; } $first = $prefix[0]; if (!isset($this->prefixesPsr0[$first][$prefix])) { $this->prefixesPsr0[$first][$prefix] = $paths; return; } if ($prepend) { $this->prefixesPsr0[$first][$prefix] = array_merge( $paths, $this->prefixesPsr0[$first][$prefix] ); } else { $this->prefixesPsr0[$first][$prefix] = array_merge( $this->prefixesPsr0[$first][$prefix], $paths ); } } /** * Registers a set of PSR-4 directories for a given namespace, either * appending or prepending to the ones previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param list<string>|string $paths The PSR-4 base directories * @param bool $prepend Whether to prepend the directories * * @throws \InvalidArgumentException * * @return void */ public function addPsr4($prefix, $paths, $prepend = false) { $paths = (array) $paths; if (!$prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( $paths, $this->fallbackDirsPsr4 ); } else { $this->fallbackDirsPsr4 = array_merge( $this->fallbackDirsPsr4, $paths ); } } elseif (!isset($this->prefixDirsPsr4[$prefix])) { // Register directories for a new namespace. $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = $paths; } elseif ($prepend) { // Prepend directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $paths, $this->prefixDirsPsr4[$prefix] ); } else { // Append directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $this->prefixDirsPsr4[$prefix], $paths ); } } /** * Registers a set of PSR-0 directories for a given prefix, * replacing any others previously set for this prefix. * * @param string $prefix The prefix * @param list<string>|string $paths The PSR-0 base directories * * @return void */ public function set($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr0 = (array) $paths; } else { $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; } } /** * Registers a set of PSR-4 directories for a given namespace, * replacing any others previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param list<string>|string $paths The PSR-4 base directories * * @throws \InvalidArgumentException * * @return void */ public function setPsr4($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr4 = (array) $paths; } else { $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } } /** * Turns on searching the include path for class files. * * @param bool $useIncludePath * * @return void */ public function setUseIncludePath($useIncludePath) { $this->useIncludePath = $useIncludePath; } /** * Can be used to check if the autoloader uses the include path to check * for classes. * * @return bool */ public function getUseIncludePath() { return $this->useIncludePath; } /** * Turns off searching the prefix and fallback directories for classes * that have not been registered with the class map. * * @param bool $classMapAuthoritative * * @return void */ public function setClassMapAuthoritative($classMapAuthoritative) { $this->classMapAuthoritative = $classMapAuthoritative; } /** * Should class lookup fail if not found in the current class map? * * @return bool */ public function isClassMapAuthoritative() { return $this->classMapAuthoritative; } /** * APCu prefix to use to cache found/not-found classes, if the extension is enabled. * * @param string|null $apcuPrefix * * @return void */ public function setApcuPrefix($apcuPrefix) { $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; } /** * The APCu prefix in use, or null if APCu caching is not enabled. * * @return string|null */ public function getApcuPrefix() { return $this->apcuPrefix; } /** * Registers this instance as an autoloader. * * @param bool $prepend Whether to prepend the autoloader or not * * @return void */ public function register($prepend = false) { spl_autoload_register(array($this, 'loadClass'), true, $prepend); if (null === $this->vendorDir) { return; } if ($prepend) { self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; } else { unset(self::$registeredLoaders[$this->vendorDir]); self::$registeredLoaders[$this->vendorDir] = $this; } } /** * Unregisters this instance as an autoloader. * * @return void */ public function unregister() { spl_autoload_unregister(array($this, 'loadClass')); if (null !== $this->vendorDir) { unset(self::$registeredLoaders[$this->vendorDir]); } } /** * Loads the given class or interface. * * @param string $class The name of the class * @return true|null True if loaded, null otherwise */ public function loadClass($class) { if ($file = $this->findFile($class)) { $includeFile = self::$includeFile; $includeFile($file); return true; } return null; } /** * Finds the path to the file where the class is defined. * * @param string $class The name of the class * * @return string|false The path if found, false otherwise */ public function findFile($class) { // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } if (null !== $this->apcuPrefix) { $file = apcu_fetch($this->apcuPrefix.$class, $hit); if ($hit) { return $file; } } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } if (null !== $this->apcuPrefix) { apcu_add($this->apcuPrefix.$class, $file); } if (false === $file) { // Remember that this class does not exist. $this->missingClasses[$class] = true; } return $file; } /** * Returns the currently registered loaders keyed by their corresponding vendor directories. * * @return array<string, self> */ public static function getRegisteredLoaders() { return self::$registeredLoaders; } /** * @param string $class * @param string $ext * @return string|false */ private function findFileWithExtension($class, $ext) { // PSR-4 lookup $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { $subPath = $class; while (false !== $lastPos = strrpos($subPath, '\\')) { $subPath = substr($subPath, 0, $lastPos); $search = $subPath . '\\'; if (isset($this->prefixDirsPsr4[$search])) { $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); foreach ($this->prefixDirsPsr4[$search] as $dir) { if (file_exists($file = $dir . $pathEnd)) { return $file; } } } } } // PSR-4 fallback dirs foreach ($this->fallbackDirsPsr4 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { return $file; } } // PSR-0 lookup if (false !== $pos = strrpos($class, '\\')) { // namespaced class name $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); } else { // PEAR-like class name $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; } if (isset($this->prefixesPsr0[$first])) { foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { if (0 === strpos($class, $prefix)) { foreach ($dirs as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } } } } // PSR-0 fallback dirs foreach ($this->fallbackDirsPsr0 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } // PSR-0 include paths. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { return $file; } return false; } /** * @return void */ private static function initializeIncludeClosure() { if (self::$includeFile !== null) { return; } /** * Scope isolated include. * * Prevents access to $this/self from included files. * * @param string $file * @return void */ self::$includeFile = \Closure::bind(static function($file) { include $file; }, null, null); } } vendor/composer/LICENSE 0000644 00000002056 14720461212 0010677 0 ustar 00 Copyright (c) Nils Adermann, Jordi Boggiano Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. vendor/composer/autoload_psr4.php 0000644 00000000205 14720461212 0013155 0 ustar 00 <?php // autoload_psr4.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( ); vendor/composer/installed.php 0000644 00000002217 14720461212 0012361 0 ustar 00 <?php return array( 'root' => array( 'name' => 'elementor/image-optimizer', 'pretty_version' => 'dev-main', 'version' => 'dev-main', 'reference' => 'ccbca9b715e85f5bd971b5e8f56ca5844aace47e', 'type' => 'library', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), 'dev' => false, ), 'versions' => array( 'elementor/image-optimizer' => array( 'pretty_version' => 'dev-main', 'version' => 'dev-main', 'reference' => 'ccbca9b715e85f5bd971b5e8f56ca5844aace47e', 'type' => 'library', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), 'dev_requirement' => false, ), 'woocommerce/action-scheduler' => array( 'pretty_version' => '3.8.2', 'version' => '3.8.2.0', 'reference' => '2bc91d88fdbc2c07ab899cbb56b983e11e62cf69', 'type' => 'wordpress-plugin', 'install_path' => __DIR__ . '/../woocommerce/action-scheduler', 'aliases' => array(), 'dev_requirement' => false, ), ), ); vendor/composer/autoload_classmap.php 0000644 00000000336 14720461212 0014075 0 ustar 00 <?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', ); vendor/composer/InstalledVersions.php 0000644 00000037417 14720461212 0014064 0 ustar 00 <?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer; use Composer\Autoload\ClassLoader; use Composer\Semver\VersionParser; /** * This class is copied in every Composer installed project and available to all * * See also https://getcomposer.org/doc/07-runtime.md#installed-versions * * To require its presence, you can require `composer-runtime-api ^2.0` * * @final */ class InstalledVersions { /** * @var mixed[]|null * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null */ private static $installed; /** * @var bool|null */ private static $canGetVendors; /** * @var array[] * @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}> */ private static $installedByVendor = array(); /** * Returns a list of all package names which are present, either by being installed, replaced or provided * * @return string[] * @psalm-return list<string> */ public static function getInstalledPackages() { $packages = array(); foreach (self::getInstalled() as $installed) { $packages[] = array_keys($installed['versions']); } if (1 === \count($packages)) { return $packages[0]; } return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); } /** * Returns a list of all package names with a specific type e.g. 'library' * * @param string $type * @return string[] * @psalm-return list<string> */ public static function getInstalledPackagesByType($type) { $packagesByType = array(); foreach (self::getInstalled() as $installed) { foreach ($installed['versions'] as $name => $package) { if (isset($package['type']) && $package['type'] === $type) { $packagesByType[] = $name; } } } return $packagesByType; } /** * Checks whether the given package is installed * * This also returns true if the package name is provided or replaced by another package * * @param string $packageName * @param bool $includeDevRequirements * @return bool */ public static function isInstalled($packageName, $includeDevRequirements = true) { foreach (self::getInstalled() as $installed) { if (isset($installed['versions'][$packageName])) { return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; } } return false; } /** * Checks whether the given package satisfies a version constraint * * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: * * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') * * @param VersionParser $parser Install composer/semver to have access to this class and functionality * @param string $packageName * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package * @return bool */ public static function satisfies(VersionParser $parser, $packageName, $constraint) { $constraint = $parser->parseConstraints((string) $constraint); $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); return $provided->matches($constraint); } /** * Returns a version constraint representing all the range(s) which are installed for a given package * * It is easier to use this via isInstalled() with the $constraint argument if you need to check * whether a given version of a package is installed, and not just whether it exists * * @param string $packageName * @return string Version constraint usable with composer/semver */ public static function getVersionRanges($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } $ranges = array(); if (isset($installed['versions'][$packageName]['pretty_version'])) { $ranges[] = $installed['versions'][$packageName]['pretty_version']; } if (array_key_exists('aliases', $installed['versions'][$packageName])) { $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); } if (array_key_exists('replaced', $installed['versions'][$packageName])) { $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); } if (array_key_exists('provided', $installed['versions'][$packageName])) { $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); } return implode(' || ', $ranges); } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present */ public static function getVersion($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } if (!isset($installed['versions'][$packageName]['version'])) { return null; } return $installed['versions'][$packageName]['version']; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present */ public static function getPrettyVersion($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } if (!isset($installed['versions'][$packageName]['pretty_version'])) { return null; } return $installed['versions'][$packageName]['pretty_version']; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference */ public static function getReference($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } if (!isset($installed['versions'][$packageName]['reference'])) { return null; } return $installed['versions'][$packageName]['reference']; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. */ public static function getInstallPath($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @return array * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} */ public static function getRootPackage() { $installed = self::getInstalled(); return $installed[0]['root']; } /** * Returns the raw installed.php data for custom implementations * * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. * @return array[] * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} */ public static function getRawData() { @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); if (null === self::$installed) { // only require the installed.php file if this file is loaded from its dumped location, // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 if (substr(__DIR__, -8, 1) !== 'C') { self::$installed = include __DIR__ . '/installed.php'; } else { self::$installed = array(); } } return self::$installed; } /** * Returns the raw data of all installed.php which are currently loaded for custom implementations * * @return array[] * @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}> */ public static function getAllRawData() { return self::getInstalled(); } /** * Lets you reload the static array from another file * * This is only useful for complex integrations in which a project needs to use * this class but then also needs to execute another project's autoloader in process, * and wants to ensure both projects have access to their version of installed.php. * * A typical case would be PHPUnit, where it would need to make sure it reads all * the data it needs from this class, then call reload() with * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure * the project in which it runs can then also use this class safely, without * interference between PHPUnit's dependencies and the project's dependencies. * * @param array[] $data A vendor/composer/installed.php data set * @return void * * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data */ public static function reload($data) { self::$installed = $data; self::$installedByVendor = array(); } /** * @return array[] * @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}> */ private static function getInstalled() { if (null === self::$canGetVendors) { self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); } $installed = array(); if (self::$canGetVendors) { foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { if (isset(self::$installedByVendor[$vendorDir])) { $installed[] = self::$installedByVendor[$vendorDir]; } elseif (is_file($vendorDir.'/composer/installed.php')) { /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */ $required = require $vendorDir.'/composer/installed.php'; $installed[] = self::$installedByVendor[$vendorDir] = $required; if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { self::$installed = $installed[count($installed) - 1]; } } } } if (null === self::$installed) { // only require the installed.php file if this file is loaded from its dumped location, // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 if (substr(__DIR__, -8, 1) !== 'C') { /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */ $required = require __DIR__ . '/installed.php'; self::$installed = $required; } else { self::$installed = array(); } } if (self::$installed !== array()) { $installed[] = self::$installed; } return $installed; } } vendor/autoload.php 0000644 00000001403 14720461212 0010357 0 ustar 00 <?php // autoload.php @generated by Composer if (PHP_VERSION_ID < 50600) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } $err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL; if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, $err); } elseif (!headers_sent()) { echo $err; } } trigger_error( $err, E_USER_ERROR ); } require_once __DIR__ . '/composer/autoload_real.php'; return ComposerAutoloaderInit4cf7848c3d7e3b30582e3c6bcdb292a6::getLoader(); image-optimization.php 0000644 00000012200 14720461212 0011055 0 ustar 00 <?php /** * Plugin Name: Image Optimizer - Compress, Resize and Optimize Images * Description: Automatically resize, optimize, and convert images to WebP and AVIF. Compress images in bulk or on upload to boost your WordPress site performance. * Plugin URI: https://go.elementor.com/wp-repo-description-tab-io-product-page/ * Version: 1.5.4 * Author: Elementor.com * Author URI: https://go.elementor.com/author-uri-io/ * Text Domain: image-optimization * License: GPL-3 * License URI: https://www.gnu.org/licenses/gpl-3.0.en.html */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } define( 'IMAGE_OPTIMIZATION_VERSION', '1.5.4' ); define( 'IMAGE_OPTIMIZATION_PATH', plugin_dir_path( __FILE__ ) ); define( 'IMAGE_OPTIMIZATION_URL', plugins_url( '/', __FILE__ ) ); define( 'IMAGE_OPTIMIZATION_ASSETS_PATH', IMAGE_OPTIMIZATION_PATH . 'assets/' ); define( 'IMAGE_OPTIMIZATION_ASSETS_URL', IMAGE_OPTIMIZATION_URL . 'assets/' ); define( 'IMAGE_OPTIMIZATION_PLUGIN_FILE', basename( __FILE__ ) ); /** * ImageOptimization Class */ final class ImageOptimization { private $requirements_errors = []; const REQUIRED_EXTENSIONS = [ 'exif', 'fileinfo', 'gd', ]; /** * Constructor * * @access public */ public function __construct() { // Load translation add_action( 'plugins_loaded', [ $this, 'i18n' ] ); // Init Plugin add_action( 'plugins_loaded', [ $this, 'init' ], -11 ); } /** * Load plugin localization files. * * Fired by `plugins_loaded` action hook. * * @access public */ public function i18n() { load_plugin_textdomain( 'image-optimization' ); } /** * Checks if all requirements met to safely start the plugin and renders admin notices * if something is not right. * * @access public * @return bool */ public function plugin_can_start(): bool { $can_start = true; if ( ! version_compare( PHP_VERSION, '7.4', '>=' ) ) { $this->requirements_errors[] = sprintf( '%1$s <a href="https://go.elementor.com/wp-dash-update-php/" target="_blank">%2$s</a>', sprintf( /* translators: %s: PHP version. */ esc_html__( 'Update to PHP version %s and get back to optimizing!', 'image-optimization' ), '7.4', ), esc_html__( 'Show me how', 'image-optimization' ) ); $can_start = false; } if ( count( $this->get_missing_extensions_list() ) ) { $missed_extensions = $this->get_missing_extensions_list(); $this->requirements_errors[] = sprintf( esc_html__( 'The following required PHP extensions are missing: %s', 'image-optimization' ), implode( ', ', $missed_extensions ) ); $can_start = false; } if ( ! $this->is_db_json_supported() ) { $this->requirements_errors[] = sprintf( /* translators: 1: MySQL minimum version. 2: MariaDB minimum version. */ esc_html__( 'The database server version is outdated. Update to MySQL version %1$s or MariaDB version %2$s.', 'image-optimization' ), '5.7', '10.2' ); $can_start = false; } $upload_dir = wp_upload_dir(); if ( ! wp_is_writable( $upload_dir['basedir'] ) ) { $this->requirements_errors[] = esc_html__( 'Your site doesn’t have the necessary read/write permissions for your file system to use this plugin. Please contact your hosting provider to resolve this matter.', 'image-optimization', ); $can_start = false; } return $can_start; } /** * Retrieve an array of missing extensions mentioned in self::REQUIRED_EXTENSIONS. * * @access private * @return array Missing extensions. */ private function get_missing_extensions_list(): array { $output = []; foreach ( self::REQUIRED_EXTENSIONS as $extension ) { if ( ! extension_loaded( $extension ) ) { $output[] = $extension; } } return $output; } public function is_db_json_supported(): bool { global $wpdb; $result = $wpdb->query(" SELECT JSON_EXTRACT('[1, 2]', '$[1]'); "); return false !== $result; } /** * Renders an admin notice if the setup did not meet requirements. * * Fired by `admin_notices` action hook. * * @access public * @return void */ public function add_requirements_error() { $message = sprintf( '<h3>%s</h3>', esc_html__( 'Image Optimizer isn’t running because:', 'image-optimization' ) ); $message .= '<ul>'; foreach ( $this->requirements_errors as $error ) { $message .= sprintf( '%s%s%s', '<li>', $error, '</li>' ); } $message .= '</ul>'; $html_message = sprintf( '<div class="error">%s</div>', wpautop( $message ) ); echo wp_kses_post( $html_message ); } /** * Initialize the plugin. * * Validates that PHP version is sufficient. Checks for basic plugin requirements, * if one check fail don't continue, if all check have passed include the plugin class. * * Fired by `plugins_loaded` action hook. * * @access public */ public function init() { if ( ! $this->plugin_can_start() ) { add_action( 'admin_notices', [ $this, 'add_requirements_error' ] ); } else { // Once we get here, We have passed all validation checks, so we can safely include our plugin require_once 'plugin.php'; } } } // Instantiate ImageOptimization. new ImageOptimization(); assets/build/admin.js 0000644 00001117627 14720461212 0010611 0 ustar 00 !function(){var t,e={998:function(t,e,n){"use strict";n(196),e.Z="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMCIgaGVpZ2h0PSIzMCIgZmlsbD0ibm9uZSI+CiAgICA8ZyBmaWxsPSIjQkFCRkM1IiBjbGlwLXBhdGg9InVybCgjYSkiPgogICAgICAgIDxwYXRoIGQ9Im0xNS43NTUgMTEuMzM1LTIuMDgtMi4wOGEzLjc1IDMuNzUgMCAwIDAtNS4zMDQgNS4zMDJsMi42NTIgMi42NTJhMy43NSAzLjc1IDAgMCAwIDYuMDM2LTEuMDM0bC0uNzMzLS43MzRhMS4yMzUgMS4yMzUgMCAwIDAtLjI0OS0uMTkzIDIuNSAyLjUgMCAwIDEtNC4xNyAxLjA3N2wtMi42NTItMi42NTFhMi41IDIuNSAwIDEgMSAzLjUzNS0zLjUzNmwxLjM1NyAxLjM1N2E1LjAyIDUuMDIgMCAwIDEgMS42MDktLjE2aC0uMDAxWiIvPgogICAgICAgIDxwYXRoIGQ9Im0xNS4yMzMgMTIuNTgxLjIwOS4yMDljLjMyMi4zMjIuNTM4LjcxLjY0NyAxLjEyLjQyNC4xMTQuODEuMzM3IDEuMTIuNjQ4bC4yMS4yMDhhMy43NTYgMy43NTYgMCAwIDAtLjM2LTEuODI2IDMuNzUgMy43NSAwIDAgMC0xLjgyNi0uMzU5WiIvPgogICAgICAgIDxwYXRoIGQ9Ik0xOC4wOTMgMTMuNjc0YTMuNzUgMy43NSAwIDAgMC02LjAzNyAxLjAzNGwuOTcxLjk3YTIuNSAyLjUgMCAwIDEgNC4xODMtMS4xMmwyLjY1MSAyLjY1MWEyLjUgMi41IDAgMSAxLTMuNTM1IDMuNTM2bC0xLjM1Ny0xLjM1N2E1LjAyNSA1LjAyNSAwIDAgMS0xLjYwOS4xNTlsMi4wODIgMi4wODFhMy43NSAzLjc1IDAgMCAwIDUuMzAzLTUuMzAzbC0yLjY1Mi0yLjY1MVoiLz4KICAgICAgICA8cGF0aCBkPSJNMTIuMDU2IDE3Ljk0M2MuNTcuMjcgMS4xOTguMzk0IDEuODI3LjM1OWwtLjIwOS0uMjA5YTIuNDg3IDIuNDg3IDAgMCAxLS42NDctMS4xMiAyLjQ4NyAyLjQ4NyAwIDAgMS0xLjEyLS42NDhsLS4yMS0uMjA4YTMuNzYyIDMuNzYyIDAgMCAwIC4zNiAxLjgyNloiLz4KICAgIDwvZz4KICAgIDxkZWZzPgogICAgICAgIDxjbGlwUGF0aCBpZD0iYSI+CiAgICAgICAgICAgIDxwYXRoIGZpbGw9IiNmZmYiIGQ9Ik0xNSAuODU3IDI5LjE0MiAxNSAxNSAyOS4xNDIuODU4IDE1eiIvPgogICAgICAgIDwvY2xpcFBhdGg+CiAgICA8L2RlZnM+Cjwvc3ZnPgo="},282:function(t,e,n){"use strict";var r=window.wp.element,o=n(196),i=function(){function t(t){var e=this;this._insertTag=function(t){var n;n=0===e.tags.length?e.insertionPoint?e.insertionPoint.nextSibling:e.prepend?e.container.firstChild:e.before:e.tags[e.tags.length-1].nextSibling,e.container.insertBefore(t,n),e.tags.push(t)},this.isSpeedy=void 0===t.speedy||t.speedy,this.tags=[],this.ctr=0,this.nonce=t.nonce,this.key=t.key,this.container=t.container,this.prepend=t.prepend,this.insertionPoint=t.insertionPoint,this.before=null}var e=t.prototype;return e.hydrate=function(t){t.forEach(this._insertTag)},e.insert=function(t){this.ctr%(this.isSpeedy?65e3:1)==0&&this._insertTag(function(t){var e=document.createElement("style");return e.setAttribute("data-emotion",t.key),void 0!==t.nonce&&e.setAttribute("nonce",t.nonce),e.appendChild(document.createTextNode("")),e.setAttribute("data-s",""),e}(this));var e=this.tags[this.tags.length-1];if(this.isSpeedy){var n=function(t){if(t.sheet)return t.sheet;for(var e=0;e<document.styleSheets.length;e++)if(document.styleSheets[e].ownerNode===t)return document.styleSheets[e]}(e);try{n.insertRule(t,n.cssRules.length)}catch(t){}}else e.appendChild(document.createTextNode(t));this.ctr++},e.flush=function(){this.tags.forEach((function(t){return t.parentNode&&t.parentNode.removeChild(t)})),this.tags=[],this.ctr=0},t}(),a=Math.abs,u=String.fromCharCode,c=Object.assign;function l(t){return t.trim()}function s(t,e,n){return t.replace(e,n)}function f(t,e){return t.indexOf(e)}function p(t,e){return 0|t.charCodeAt(e)}function d(t,e,n){return t.slice(e,n)}function h(t){return t.length}function m(t){return t.length}function g(t,e){return e.push(t),t}var v=1,y=1,b=0,w=0,x=0,_="";function S(t,e,n,r,o,i,a){return{value:t,root:e,parent:n,type:r,props:o,children:i,line:v,column:y,length:a,return:""}}function k(t,e){return c(S("",null,null,"",null,null,0),t,{length:-t.length},e)}function O(){return x=w>0?p(_,--w):0,y--,10===x&&(y=1,v--),x}function E(){return x=w<b?p(_,w++):0,y++,10===x&&(y=1,v++),x}function R(){return p(_,w)}function z(){return w}function C(t,e){return d(_,t,e)}function j(t){switch(t){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function L(t){return v=y=1,b=h(_=t),w=0,[]}function P(t){return _="",t}function I(t){return l(C(w-1,N(91===t?t+2:40===t?t+1:t)))}function T(t){for(;(x=R())&&x<33;)E();return j(t)>2||j(x)>3?"":" "}function A(t,e){for(;--e&&E()&&!(x<48||x>102||x>57&&x<65||x>70&&x<97););return C(t,z()+(e<6&&32==R()&&32==E()))}function N(t){for(;E();)switch(x){case t:return w;case 34:case 39:34!==t&&39!==t&&N(x);break;case 40:41===t&&N(t);break;case 92:E()}return w}function G(t,e){for(;E()&&t+x!==57&&(t+x!==84||47!==R()););return"/*"+C(e,w-1)+"*"+u(47===t?t:E())}function M(t){for(;!j(R());)E();return C(t,w)}var F="-ms-",D="-moz-",B="-webkit-",H="comm",W="rule",U="decl",q="@keyframes";function Z(t,e){for(var n="",r=m(t),o=0;o<r;o++)n+=e(t[o],o,t,e)||"";return n}function $(t,e,n,r){switch(t.type){case"@layer":if(t.children.length)break;case"@import":case U:return t.return=t.return||t.value;case H:return"";case q:return t.return=t.value+"{"+Z(t.children,r)+"}";case W:t.value=t.props.join(",")}return h(n=Z(t.children,r))?t.return=t.value+"{"+n+"}":""}function V(t){return P(Y("",null,null,null,[""],t=L(t),0,[0],t))}function Y(t,e,n,r,o,i,a,c,l){for(var d=0,m=0,v=a,y=0,b=0,w=0,x=1,_=1,S=1,k=0,C="",j=o,L=i,P=r,N=C;_;)switch(w=k,k=E()){case 40:if(108!=w&&58==p(N,v-1)){-1!=f(N+=s(I(k),"&","&\f"),"&\f")&&(S=-1);break}case 34:case 39:case 91:N+=I(k);break;case 9:case 10:case 13:case 32:N+=T(w);break;case 92:N+=A(z()-1,7);continue;case 47:switch(R()){case 42:case 47:g(K(G(E(),z()),e,n),l);break;default:N+="/"}break;case 123*x:c[d++]=h(N)*S;case 125*x:case 59:case 0:switch(k){case 0:case 125:_=0;case 59+m:-1==S&&(N=s(N,/\f/g,"")),b>0&&h(N)-v&&g(b>32?Q(N+";",r,n,v-1):Q(s(N," ","")+";",r,n,v-2),l);break;case 59:N+=";";default:if(g(P=X(N,e,n,d,m,o,c,C,j=[],L=[],v),i),123===k)if(0===m)Y(N,e,P,P,j,i,v,c,L);else switch(99===y&&110===p(N,3)?100:y){case 100:case 108:case 109:case 115:Y(t,P,P,r&&g(X(t,P,P,0,0,o,c,C,o,j=[],v),L),o,L,v,c,r?j:L);break;default:Y(N,P,P,P,[""],L,0,c,L)}}d=m=b=0,x=S=1,C=N="",v=a;break;case 58:v=1+h(N),b=w;default:if(x<1)if(123==k)--x;else if(125==k&&0==x++&&125==O())continue;switch(N+=u(k),k*x){case 38:S=m>0?1:(N+="\f",-1);break;case 44:c[d++]=(h(N)-1)*S,S=1;break;case 64:45===R()&&(N+=I(E())),y=R(),m=v=h(C=N+=M(z())),k++;break;case 45:45===w&&2==h(N)&&(x=0)}}return i}function X(t,e,n,r,o,i,u,c,f,p,h){for(var g=o-1,v=0===o?i:[""],y=m(v),b=0,w=0,x=0;b<r;++b)for(var _=0,k=d(t,g+1,g=a(w=u[b])),O=t;_<y;++_)(O=l(w>0?v[_]+" "+k:s(k,/&\f/g,v[_])))&&(f[x++]=O);return S(t,e,n,0===o?W:c,f,p,h)}function K(t,e,n){return S(t,e,n,H,u(x),d(t,2,-2),0)}function Q(t,e,n,r){return S(t,e,n,U,d(t,0,r),d(t,r+1,-1),r)}var J=function(t,e,n){for(var r=0,o=0;r=o,o=R(),38===r&&12===o&&(e[n]=1),!j(o);)E();return C(t,w)},tt=new WeakMap,et=function(t){if("rule"===t.type&&t.parent&&!(t.length<1)){for(var e=t.value,n=t.parent,r=t.column===n.column&&t.line===n.line;"rule"!==n.type;)if(!(n=n.parent))return;if((1!==t.props.length||58===e.charCodeAt(0)||tt.get(n))&&!r){tt.set(t,!0);for(var o=[],i=function(t,e){return P(function(t,e){var n=-1,r=44;do{switch(j(r)){case 0:38===r&&12===R()&&(e[n]=1),t[n]+=J(w-1,e,n);break;case 2:t[n]+=I(r);break;case 4:if(44===r){t[++n]=58===R()?"&\f":"",e[n]=t[n].length;break}default:t[n]+=u(r)}}while(r=E());return t}(L(t),e))}(e,o),a=n.props,c=0,l=0;c<i.length;c++)for(var s=0;s<a.length;s++,l++)t.props[l]=o[c]?i[c].replace(/&\f/g,a[s]):a[s]+" "+i[c]}}},nt=function(t){if("decl"===t.type){var e=t.value;108===e.charCodeAt(0)&&98===e.charCodeAt(2)&&(t.return="",t.value="")}};function rt(t,e){switch(function(t,e){return 45^p(t,0)?(((e<<2^p(t,0))<<2^p(t,1))<<2^p(t,2))<<2^p(t,3):0}(t,e)){case 5103:return B+"print-"+t+t;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return B+t+t;case 5349:case 4246:case 4810:case 6968:case 2756:return B+t+D+t+F+t+t;case 6828:case 4268:return B+t+F+t+t;case 6165:return B+t+F+"flex-"+t+t;case 5187:return B+t+s(t,/(\w+).+(:[^]+)/,B+"box-$1$2"+F+"flex-$1$2")+t;case 5443:return B+t+F+"flex-item-"+s(t,/flex-|-self/,"")+t;case 4675:return B+t+F+"flex-line-pack"+s(t,/align-content|flex-|-self/,"")+t;case 5548:return B+t+F+s(t,"shrink","negative")+t;case 5292:return B+t+F+s(t,"basis","preferred-size")+t;case 6060:return B+"box-"+s(t,"-grow","")+B+t+F+s(t,"grow","positive")+t;case 4554:return B+s(t,/([^-])(transform)/g,"$1"+B+"$2")+t;case 6187:return s(s(s(t,/(zoom-|grab)/,B+"$1"),/(image-set)/,B+"$1"),t,"")+t;case 5495:case 3959:return s(t,/(image-set\([^]*)/,B+"$1$`$1");case 4968:return s(s(t,/(.+:)(flex-)?(.*)/,B+"box-pack:$3"+F+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+B+t+t;case 4095:case 3583:case 4068:case 2532:return s(t,/(.+)-inline(.+)/,B+"$1$2")+t;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(h(t)-1-e>6)switch(p(t,e+1)){case 109:if(45!==p(t,e+4))break;case 102:return s(t,/(.+:)(.+)-([^]+)/,"$1"+B+"$2-$3$1"+D+(108==p(t,e+3)?"$3":"$2-$3"))+t;case 115:return~f(t,"stretch")?rt(s(t,"stretch","fill-available"),e)+t:t}break;case 4949:if(115!==p(t,e+1))break;case 6444:switch(p(t,h(t)-3-(~f(t,"!important")&&10))){case 107:return s(t,":",":"+B)+t;case 101:return s(t,/(.+:)([^;!]+)(;|!.+)?/,"$1"+B+(45===p(t,14)?"inline-":"")+"box$3$1"+B+"$2$3$1"+F+"$2box$3")+t}break;case 5936:switch(p(t,e+11)){case 114:return B+t+F+s(t,/[svh]\w+-[tblr]{2}/,"tb")+t;case 108:return B+t+F+s(t,/[svh]\w+-[tblr]{2}/,"tb-rl")+t;case 45:return B+t+F+s(t,/[svh]\w+-[tblr]{2}/,"lr")+t}return B+t+F+t+t}return t}var ot=[function(t,e,n,r){if(t.length>-1&&!t.return)switch(t.type){case U:t.return=rt(t.value,t.length);break;case q:return Z([k(t,{value:s(t.value,"@","@"+B)})],r);case W:if(t.length)return function(t,e){return t.map(e).join("")}(t.props,(function(e){switch(function(t,e){return(t=/(::plac\w+|:read-\w+)/.exec(t))?t[0]:t}(e)){case":read-only":case":read-write":return Z([k(t,{props:[s(e,/:(read-\w+)/,":-moz-$1")]})],r);case"::placeholder":return Z([k(t,{props:[s(e,/:(plac\w+)/,":"+B+"input-$1")]}),k(t,{props:[s(e,/:(plac\w+)/,":-moz-$1")]}),k(t,{props:[s(e,/:(plac\w+)/,F+"input-$1")]})],r)}return""}))}}],it=function(t){var e=t.key;if("css"===e){var n=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(n,(function(t){-1!==t.getAttribute("data-emotion").indexOf(" ")&&(document.head.appendChild(t),t.setAttribute("data-s",""))}))}var r,o,a=t.stylisPlugins||ot,u={},c=[];r=t.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+e+' "]'),(function(t){for(var e=t.getAttribute("data-emotion").split(" "),n=1;n<e.length;n++)u[e[n]]=!0;c.push(t)}));var l,s,f,p,d=[$,(p=function(t){l.insert(t)},function(t){t.root||(t=t.return)&&p(t)})],h=(s=[et,nt].concat(a,d),f=m(s),function(t,e,n,r){for(var o="",i=0;i<f;i++)o+=s[i](t,e,n,r)||"";return o});o=function(t,e,n,r){l=n,Z(V(t?t+"{"+e.styles+"}":e.styles),h),r&&(g.inserted[e.name]=!0)};var g={key:e,sheet:new i({key:e,container:r,nonce:t.nonce,speedy:t.speedy,prepend:t.prepend,insertionPoint:t.insertionPoint}),nonce:t.nonce,inserted:u,registered:{},insert:o};return g.sheet.hydrate(c),g};function at(){return at=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},at.apply(this,arguments)}var ut=function(t){var e=new WeakMap;return function(n){if(e.has(n))return e.get(n);var r=t(n);return e.set(n,r),r}};function ct(t,e,n){var r="";return n.split(" ").forEach((function(n){void 0!==t[n]?e.push(t[n]+";"):r+=n+" "})),r}var lt=function(t,e,n){var r=t.key+"-"+e.name;!1===n&&void 0===t.registered[r]&&(t.registered[r]=e.styles)},st=function(t,e,n){lt(t,e,n);var r=t.key+"-"+e.name;if(void 0===t.inserted[e.name]){var o=e;do{t.insert(e===o?"."+r:"",o,t.sheet,!0),o=o.next}while(void 0!==o)}},ft={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1};function pt(t){var e=Object.create(null);return function(n){return void 0===e[n]&&(e[n]=t(n)),e[n]}}var dt=/[A-Z]|^ms/g,ht=/_EMO_([^_]+?)_([^]*?)_EMO_/g,mt=function(t){return 45===t.charCodeAt(1)},gt=function(t){return null!=t&&"boolean"!=typeof t},vt=pt((function(t){return mt(t)?t:t.replace(dt,"-$&").toLowerCase()})),yt=function(t,e){switch(t){case"animation":case"animationName":if("string"==typeof e)return e.replace(ht,(function(t,e,n){return wt={name:e,styles:n,next:wt},e}))}return 1===ft[t]||mt(t)||"number"!=typeof e||0===e?e:e+"px"};function bt(t,e,n){if(null==n)return"";if(void 0!==n.__emotion_styles)return n;switch(typeof n){case"boolean":return"";case"object":if(1===n.anim)return wt={name:n.name,styles:n.styles,next:wt},n.name;if(void 0!==n.styles){var r=n.next;if(void 0!==r)for(;void 0!==r;)wt={name:r.name,styles:r.styles,next:wt},r=r.next;return n.styles+";"}return function(t,e,n){var r="";if(Array.isArray(n))for(var o=0;o<n.length;o++)r+=bt(t,e,n[o])+";";else for(var i in n){var a=n[i];if("object"!=typeof a)null!=e&&void 0!==e[a]?r+=i+"{"+e[a]+"}":gt(a)&&(r+=vt(i)+":"+yt(i,a)+";");else if(!Array.isArray(a)||"string"!=typeof a[0]||null!=e&&void 0!==e[a[0]]){var u=bt(t,e,a);switch(i){case"animation":case"animationName":r+=vt(i)+":"+u+";";break;default:r+=i+"{"+u+"}"}}else for(var c=0;c<a.length;c++)gt(a[c])&&(r+=vt(i)+":"+yt(i,a[c])+";")}return r}(t,e,n);case"function":if(void 0!==t){var o=wt,i=n(t);return wt=o,bt(t,e,i)}}if(null==e)return n;var a=e[n];return void 0!==a?a:n}var wt,xt=/label:\s*([^\s;\n{]+)\s*(;|$)/g,_t=function(t,e,n){if(1===t.length&&"object"==typeof t[0]&&null!==t[0]&&void 0!==t[0].styles)return t[0];var r=!0,o="";wt=void 0;var i=t[0];null==i||void 0===i.raw?(r=!1,o+=bt(n,e,i)):o+=i[0];for(var a=1;a<t.length;a++)o+=bt(n,e,t[a]),r&&(o+=i[a]);xt.lastIndex=0;for(var u,c="";null!==(u=xt.exec(o));)c+="-"+u[1];var l=function(t){for(var e,n=0,r=0,o=t.length;o>=4;++r,o-=4)e=1540483477*(65535&(e=255&t.charCodeAt(r)|(255&t.charCodeAt(++r))<<8|(255&t.charCodeAt(++r))<<16|(255&t.charCodeAt(++r))<<24))+(59797*(e>>>16)<<16),n=1540483477*(65535&(e^=e>>>24))+(59797*(e>>>16)<<16)^1540483477*(65535&n)+(59797*(n>>>16)<<16);switch(o){case 3:n^=(255&t.charCodeAt(r+2))<<16;case 2:n^=(255&t.charCodeAt(r+1))<<8;case 1:n=1540483477*(65535&(n^=255&t.charCodeAt(r)))+(59797*(n>>>16)<<16)}return(((n=1540483477*(65535&(n^=n>>>13))+(59797*(n>>>16)<<16))^n>>>15)>>>0).toString(36)}(o)+c;return{name:l,styles:o,next:wt}},St=!!o.useInsertionEffect&&o.useInsertionEffect,kt=St||function(t){return t()},Ot=(St||o.useLayoutEffect,{}.hasOwnProperty),Et=o.createContext("undefined"!=typeof HTMLElement?it({key:"css"}):null);Et.Provider;var Rt=function(t){return(0,o.forwardRef)((function(e,n){var r=(0,o.useContext)(Et);return t(e,r,n)}))},zt=o.createContext({}),Ct=function(){return o.useContext(zt)},jt=ut((function(t){return ut((function(e){return function(t,e){return"function"==typeof e?e(t):at({},t,e)}(t,e)}))})),Lt=function(t){var e=o.useContext(zt);return t.theme!==e&&(e=jt(e)(t.theme)),o.createElement(zt.Provider,{value:e},t.children)},Pt="__EMOTION_TYPE_PLEASE_DO_NOT_USE__",It=function(t){var e=t.cache,n=t.serialized,r=t.isStringTag;return lt(e,n,r),kt((function(){return st(e,n,r)})),null},Tt=Rt((function(t,e,n){var r=t.css;"string"==typeof r&&void 0!==e.registered[r]&&(r=e.registered[r]);var i=t[Pt],a=[r],u="";"string"==typeof t.className?u=ct(e.registered,a,t.className):null!=t.className&&(u=t.className+" ");var c=_t(a,void 0,o.useContext(zt));u+=e.key+"-"+c.name;var l={};for(var s in t)Ot.call(t,s)&&"css"!==s&&s!==Pt&&(l[s]=t[s]);return l.ref=n,l.className=u,o.createElement(o.Fragment,null,o.createElement(It,{cache:e,serialized:c,isStringTag:"string"==typeof i}),o.createElement(i,l))})),At={palette:{native:{blue:"#2271b1",blueActive:"#135e96"},primary:{main:"#F0ABFC",light:"#5EEAD4",accent:"#524CFF"},text:{default:"#3A3F45",white:"#FFFFFF",primary:"#0C0D0E",secondary:"#2271B1",tertiary:"#69727D",lightGrey:"#535961",dark:"#26292C",darkGrey:"#64666A",disabled:"#DDDDDD",toast:"#D5DADF",noticeInfo:"#1E1E1E",link:"#040080",brand:"#45f2b6"},background:{default:"#FFFFFF",lightGrey:"#F6F7F7",grey:"#D9D9D9",toast:"#2D2D2D",noticeInfo:"#F1F6FB",brand:"#040080",disabled:"#D5D8DC"},border:{default:"#E6E8EA",lightest:"#D5DADF",grey:"#D9D9D9",grey600:"#949494"},info:{notice:"#0288D1"},success:{main:"#5EEAD4"},warning:{},error:{main:"#DC2626"},badge:{background:{success:"#E9FCF2",danger:"#FDE8EB",warning:"#FFF6E6"},text:{success:"#0F6737",danger:"#B21027",warning:"#8D5E01"}}},fonts:{default:"Roboto, sans-serif"}},Nt=/^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|enterKeyHint|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/,Gt=pt((function(t){return Nt.test(t)||111===t.charCodeAt(0)&&110===t.charCodeAt(1)&&t.charCodeAt(2)<91})),Mt=function(t){return"theme"!==t},Ft=function(t){return"string"==typeof t&&t.charCodeAt(0)>96?Gt:Mt},Dt=function(t,e,n){var r;if(e){var o=e.shouldForwardProp;r=t.__emotion_forwardProp&&o?function(e){return t.__emotion_forwardProp(e)&&o(e)}:o}return"function"!=typeof r&&n&&(r=t.__emotion_forwardProp),r},Bt=function(t){var e=t.cache,n=t.serialized,r=t.isStringTag;return lt(e,n,r),kt((function(){return st(e,n,r)})),null},Ht=function t(e,n){var r,i,a=e.__emotion_real===e,u=a&&e.__emotion_base||e;void 0!==n&&(r=n.label,i=n.target);var c=Dt(e,n,a),l=c||Ft(u),s=!l("as");return function(){var f=arguments,p=a&&void 0!==e.__emotion_styles?e.__emotion_styles.slice(0):[];if(void 0!==r&&p.push("label:"+r+";"),null==f[0]||void 0===f[0].raw)p.push.apply(p,f);else{p.push(f[0][0]);for(var d=f.length,h=1;h<d;h++)p.push(f[h],f[0][h])}var m=Rt((function(t,e,n){var r=s&&t.as||u,a="",f=[],d=t;if(null==t.theme){for(var h in d={},t)d[h]=t[h];d.theme=o.useContext(zt)}"string"==typeof t.className?a=ct(e.registered,f,t.className):null!=t.className&&(a=t.className+" ");var m=_t(p.concat(f),e.registered,d);a+=e.key+"-"+m.name,void 0!==i&&(a+=" "+i);var g=s&&void 0===c?Ft(r):l,v={};for(var y in t)s&&"as"===y||g(y)&&(v[y]=t[y]);return v.className=a,v.ref=n,o.createElement(o.Fragment,null,o.createElement(Bt,{cache:e,serialized:m,isStringTag:"string"==typeof r}),o.createElement(r,v))}));return m.displayName=void 0!==r?r:"Styled("+("string"==typeof u?u:u.displayName||u.name||"Component")+")",m.defaultProps=e.defaultProps,m.__emotion_real=m,m.__emotion_base=u,m.__emotion_styles=p,m.__emotion_forwardProp=c,Object.defineProperty(m,"toString",{value:function(){return"."+i}}),m.withComponent=function(e,r){return t(e,at({},n,r,{shouldForwardProp:Dt(m,r,!0)})).apply(void 0,p)},m}},Wt=n(697),Ut=n.n(Wt),qt=function(t){return t.children};qt.propTypes={children:Ut().node},qt.__name="Header";var Zt=qt,$t=(n(679),function(t,e){var n=arguments;if(null==e||!Ot.call(e,"css"))return o.createElement.apply(void 0,n);var r=n.length,i=new Array(r);i[0]=Tt,i[1]=function(t,e){var n={};for(var r in e)Ot.call(e,r)&&(n[r]=e[r]);return n[Pt]=t,n}(t,e);for(var a=2;a<r;a++)i[a]=n[a];return o.createElement.apply(null,i)});function Vt(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return _t(e)}var Yt=Ht("div",{target:"e11nhus00"})("width:",(function(t){return t.fullWidth?"100vw":"calc(100% - 16px - 225px)"}),";"),Xt=function(t){var e=t.fullWidth,n=t.children;return $t(Yt,{fullWidth:e},n)};Xt.propTypes={fullWidth:Ut().bool,children:Ut().node},Xt.__name="Content";var Kt=Xt,Qt=Ht("aside",{target:"e1o94q9m0"})({name:"1i30uc2",styles:"width:225px"}),Jt=function(t){var e=t.children;return $t(Qt,null,e)};Jt.propTypes={children:Ut().node},Jt.__name="Sidebar";var te=Jt,ee=Ht("main",{target:"e11mga1l0"})({name:"1p0vzpg",styles:"display:flex;justify-content:space-between;margin-block-start:16px"}),ne=function(t){var e,n,r;return t.children.forEach((function(t){var o,i,a;"Header"===(null==t||null===(o=t.type)||void 0===o?void 0:o.__name)&&(e=t),"Content"===(null==t||null===(i=t.type)||void 0===i?void 0:i.__name)&&(n=t),"Sidebar"===(null==t||null===(a=t.type)||void 0===a?void 0:a.__name)&&(r=t)})),$t(React.Fragment,null,e,r?$t(ee,{className:"wrap"},n,r):$t(ee,{className:"wrap"},n))};ne.propTypes={children:Ut().node},ne.Header=Zt,ne.Content=Kt,ne.Sidebar=te;var re=ne,oe=window.wp.i18n,ie=window.wp.apiFetch,ae=n.n(ie),ue=window.wp.url;function ce(t){return ce="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ce(t)}function le(t){var e="function"==typeof Map?new Map:void 0;return le=function(t){if(null===t||(n=t,-1===Function.toString.call(n).indexOf("[native code]")))return t;var n;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return se(t,arguments,de(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),pe(r,t)},le(t)}function se(t,e,n){return se=fe()?Reflect.construct.bind():function(t,e,n){var r=[null];r.push.apply(r,e);var o=new(Function.bind.apply(t,r));return n&&pe(o,n.prototype),o},se.apply(null,arguments)}function fe(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function pe(t,e){return pe=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},pe(t,e)}function de(t){return de=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},de(t)}var he=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&pe(t,e)}(i,t);var e,n,r,o=(n=i,r=fe(),function(){var t,e=de(n);if(r){var o=de(this).constructor;t=Reflect.construct(e,arguments,o)}else t=e.apply(this,arguments);return function(t,e){if(e&&("object"===ce(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(this,t)});function i(t){var e;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,i),(e=o.call(this,t)).name="APIError",e}return e=i,Object.defineProperty(e,"prototype",{writable:!1}),e}(le(Error));function me(t){return me="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},me(t)}function ge(){ge=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==me(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(me(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function ve(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}function ye(t){return function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){ve(i,r,o,a,u,"next",t)}function u(t){ve(i,r,o,a,u,"throw",t)}a(void 0)}))}}function be(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,(void 0,o=function(t,e){if("object"!==me(t)||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!==me(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(r.key),"symbol"===me(o)?o:String(o)),r)}var o}var we,xe="/wp/v2",_e="/image-optimizer/v1",Se=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var e,n,r,o,i,a,u,c,l,s,f,p,d,h,m,g,v,y;return e=t,null,n=[{key:"request",value:(y=ye(ge().mark((function t(e){var n,r,o,i,a,u;return ge().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=e.path,o=e.data,i=e.method,a=void 0===i?"POST":i,null!==(n=window)&&void 0!==n&&null!==(n=n.imageOptimizerUserData)&&void 0!==n&&n.isConnectOnFly&&r.includes(_e+"/connect/init")&&(r=r.replace("/init","/authorize")),"GET"!==a||r.startsWith(xe)||(r=(0,ue.addQueryArgs)(r,{io_time:(new Date).getTime()})),t.prev=3,t.next=6,ae()({path:r,method:a,data:o});case 6:if(u=t.sent,!r.startsWith(xe)){t.next=9;break}return t.abrupt("return",u);case 9:if(u.success){t.next=11;break}throw new he(u.data.message);case 11:return t.abrupt("return",u.data);case 14:if(t.prev=14,t.t0=t.catch(3),!(t.t0 instanceof he)){t.next=20;break}throw t.t0;case 20:throw new he(t.t0.message);case 21:case"end":return t.stop()}}),t,null,[[3,14]])}))),function(_x){return y.apply(this,arguments)})},{key:"initConnect",value:(v=ye(ge().mark((function e(){var n,r,o,i,a,u,c,l,s=arguments;return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=s.length>0&&void 0!==s[0]?s[0]:"new",u={action:"image_optimizer_connect",wp_rest:null===(n=window)||void 0===n||null===(n=n.imageOptimizerUserData)||void 0===n?void 0:n.wpRestNonce,"image-optimization-connect":null===(r=window)||void 0===r||null===(r=r.imageOptimizerUserData)||void 0===r?void 0:r.authInitNonce},"update"===a&&(u.update_redirect_uri=!0),e.next=5,ae()({path:"/image-optimizer/v1/connect/version",method:"GET"});case 5:return c=e.sent,l="init",2===(null==c||null===(o=c.data)||void 0===o?void 0:o.version)&&(l="authorize"),e.abrupt("return",t.request({method:null!==(i=window)&&void 0!==i&&null!==(i=i.imageOptimizerUserData)&&void 0!==i&&i.isConnectOnFly?"POST":"GET",path:(0,ue.addQueryArgs)("".concat(_e,"/connect/").concat(l),u)}));case 9:case"end":return e.stop()}}),e)}))),function(){return v.apply(this,arguments)})},{key:"clearSession",value:(g=ye(ge().mark((function e(){var n,r,o,i;return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!==(n=window)&&void 0!==n&&null!==(n=n.imageOptimizerUserData)&&void 0!==n&&n.isConnectOnFly){e.next=2;break}return e.abrupt("return",!0);case 2:return e.prev=2,e.next=5,t.request({method:"POST",path:"".concat(_e,"/connect/deactivate_and_disconnect"),data:{wp_rest:null===(r=window)||void 0===r||null===(r=r.imageOptimizerUserData)||void 0===r?void 0:r.wpRestNonce,"image-optimization-deactivate-subscription":null===(o=window)||void 0===o||null===(o=o.imageOptimizerUserData)||void 0===o?void 0:o.authDeactivateNonce,clear_session:!0}});case 5:return i=e.sent,e.abrupt("return",i);case 9:return e.prev=9,e.t0=e.catch(2),e.abrupt("return",!1);case 12:case"end":return e.stop()}}),e,null,[[2,9]])}))),function(){return g.apply(this,arguments)})},{key:"disconnect",value:(m=ye(ge().mark((function e(){var n,r,o,i,a,u;return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ae()({path:"/image-optimizer/v1/connect/version",method:"GET"});case 2:if(r=e.sent,o="disconnect",2!==(null==r||null===(n=r.data)||void 0===n?void 0:n.version)){e.next=6;break}return e.abrupt("return");case 6:return e.prev=6,e.next=9,t.request({method:"POST",path:"".concat(_e,"/connect/").concat(o),data:{wp_rest:null===(i=window)||void 0===i||null===(i=i.imageOptimizerUserData)||void 0===i?void 0:i.wpRestNonce,"image-optimization-disconnect":null===(a=window)||void 0===a||null===(a=a.imageOptimizerUserData)||void 0===a?void 0:a.authDisconnectNonce}});case 9:return u=e.sent,e.abrupt("return",u);case 13:return e.prev=13,e.t0=e.catch(6),e.abrupt("return",!1);case 16:case"end":return e.stop()}}),e,null,[[6,13]])}))),function(){return m.apply(this,arguments)})},{key:"deactivate",value:(h=ye(ge().mark((function e(n){var r,o,i,a,u;return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o="deactivate",null!==(r=window)&&void 0!==r&&null!==(r=r.imageOptimizerUserData)&&void 0!==r&&r.isConnectOnFly&&(o="deactivate_and_disconnect"),e.prev=2,e.next=5,t.request({method:"POST",path:"".concat(_e,"/connect/").concat(o),data:{license_key:n,wp_rest:null===(i=window)||void 0===i||null===(i=i.imageOptimizerUserData)||void 0===i?void 0:i.wpRestNonce,"image-optimization-deactivate-subscription":null===(a=window)||void 0===a||null===(a=a.imageOptimizerUserData)||void 0===a?void 0:a.authDeactivateNonce}});case 5:return u=e.sent,e.abrupt("return",u);case 9:return e.prev=9,e.t0=e.catch(2),e.abrupt("return",!1);case 12:case"end":return e.stop()}}),e,null,[[2,9]])}))),function(t){return h.apply(this,arguments)})},{key:"activateSubscription",value:(d=ye(ge().mark((function e(n){var r,o;return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.request({method:"POST",path:"".concat(_e,"/connect/activate"),data:{license_key:n,wp_rest:null===(r=window)||void 0===r||null===(r=r.imageOptimizerUserData)||void 0===r?void 0:r.wpRestNonce,"image-optimization-activate-subscription":null===(o=window)||void 0===o||null===(o=o.imageOptimizerUserData)||void 0===o?void 0:o.authActivateNonce}}));case 1:case"end":return e.stop()}}),e)}))),function(t){return d.apply(this,arguments)})},{key:"fetchSubscriptions",value:(p=ye(ge().mark((function e(){var n,r;return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.request({method:"POST",path:"".concat(_e,"/connect/get-subscriptions"),data:{wp_rest:null===(n=window)||void 0===n||null===(n=n.imageOptimizerUserData)||void 0===n?void 0:n.wpRestNonce,"image-optimization-get-subscription":null===(r=window)||void 0===r||null===(r=r.imageOptimizerUserData)||void 0===r?void 0:r.authGetSubscriptionsNonce}}));case 1:case"end":return e.stop()}}),e)}))),function(){return p.apply(this,arguments)})},{key:"getSettings",value:(f=ye(ge().mark((function e(){return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.request({method:"GET",path:"".concat(xe,"/settings")}));case 1:case"end":return e.stop()}}),e)}))),function(){return f.apply(this,arguments)})},{key:"updateSettings",value:(s=ye(ge().mark((function e(n){return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.request({method:"PUT",path:"".concat(xe,"/settings"),data:n}));case 1:case"end":return e.stop()}}),e)}))),function(t){return s.apply(this,arguments)})},{key:"getStats",value:(l=ye(ge().mark((function e(){return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.request({method:"GET",path:"".concat(_e,"/stats")}));case 1:case"end":return e.stop()}}),e)}))),function(){return l.apply(this,arguments)})},{key:"removeAllImageBackups",value:(c=ye(ge().mark((function e(){var n;return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.request({method:"DELETE",path:"".concat(_e,"/backups"),data:{"image-optimization-remove-backups":null===(n=window)||void 0===n||null===(n=n.imageOptimizerUserData)||void 0===n?void 0:n.removeBackupsNonce}}));case 1:case"end":return e.stop()}}),e)}))),function(){return c.apply(this,arguments)})},{key:"restoreAllImages",value:(u=ye(ge().mark((function e(){var n;return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.request({path:"".concat(_e,"/backups/restore"),data:{"image-optimization-restore-all":null===(n=window)||void 0===n||null===(n=n.imageOptimizerUserData)||void 0===n?void 0:n.restoreAllImagesNonce}}));case 1:case"end":return e.stop()}}),e)}))),function(){return u.apply(this,arguments)})},{key:"runBulkOptimization",value:(a=ye(ge().mark((function e(){var n,r,o=arguments;return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=o.length>0&&void 0!==o[0]&&o[0],e.abrupt("return",t.request({path:"".concat(_e,"/optimize/bulk"),data:{reoptimize:r,"image-optimization-optimize-bulk":null===(n=window)||void 0===n||null===(n=n.imageOptimizerUserData)||void 0===n?void 0:n.optimizeBulkNonce}}));case 2:case"end":return e.stop()}}),e)}))),function(){return a.apply(this,arguments)})},{key:"cancelBulkOptimization",value:(i=ye(ge().mark((function e(){var n;return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.request({path:"".concat(_e,"/optimize/bulk/cancel"),data:{"image-optimization-cancel-bulk-optimization":null===(n=window)||void 0===n||null===(n=n.imageOptimizerUserData)||void 0===n?void 0:n.cancelBulkOptimizationNonce}}));case 1:case"end":return e.stop()}}),e)}))),function(){return i.apply(this,arguments)})},{key:"getBulkOptimizationStatus",value:(o=ye(ge().mark((function e(){return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.request({method:"GET",path:"".concat(_e,"/optimize/bulk/status")}));case 1:case"end":return e.stop()}}),e)}))),function(){return o.apply(this,arguments)})},{key:"getBulkOptimizationImages",value:(r=ye(ge().mark((function e(n){var r;return ge().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r={operation_id:n},e.abrupt("return",t.request({method:"GET",path:(0,ue.addQueryArgs)("".concat(_e,"/optimize/bulk/images"),r)}));case 2:case"end":return e.stop()}}),e)}))),function(t){return r.apply(this,arguments)})}],n&&be(e,n),Object.defineProperty(e,"prototype",{writable:!1}),t}(),ke=Se;function Oe(t){return Oe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Oe(t)}function Ee(t,e,n){return(e=function(t){var e=function(t,e){if("object"!==Oe(t)||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!==Oe(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"===Oe(e)?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var Re=Object.freeze({NOT_STARTED:"not-started",OPTIMIZED:"optimized",PENDING:"pending",IN_PROGRESS:"in-progress",FAILED:"optimization-failed",CANCELLED:"canceled"}),ze=Object.freeze((Ee(we={},Re.NOT_STARTED,(0,oe.__)("Not started","image-optimization")),Ee(we,Re.OPTIMIZED,(0,oe.__)("Optimized","image-optimization")),Ee(we,Re.PENDING,(0,oe.__)("Pending","image-optimization")),Ee(we,Re.IN_PROGRESS,(0,oe.__)("In progress","image-optimization")),Ee(we,Re.FAILED,(0,oe.__)("Failed","image-optimization")),Ee(we,Re.CANCELLED,(0,oe.__)("Cancelled","image-optimization")),we));function Ce(t){return Ce="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ce(t)}function je(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,(void 0,o=function(t,e){if("object"!==Ce(t)||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!==Ce(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(r.key),"symbol"===Ce(o)?o:String(o)),r)}var o}function Le(t,e,n){return e&&je(t.prototype,e),n&&je(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}var Pe=Le((function t(e){var n=e.id,r=e.level,o=e.message,i=e.actions;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.id=n,this.level=r,this.message=o,this.actions=i}));function Ie(t){return function(t){if(Array.isArray(t))return Ne(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||Ae(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Te(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,u=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(u.push(r.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||Ae(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Ae(t,e){if(t){if("string"==typeof t)return Ne(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ne(t,e):void 0}}function Ne(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var Ge=(0,r.createContext)({}),Me=function(t){var e=t.children,n=(0,r.useState)([]),o=(0,r.useState)([]);return $t(Ge.Provider,{value:{toastNotificationsState:n,generalNotificationsState:o}},e)};Me.propTypes={children:Ut().node};var Fe=function(){var t=Te((0,r.useContext)(Ge).toastNotificationsState,2),e=t[0],n=t[1];return{toastNotifications:e,showToastNotification:function(t){var r=Ie(e);t.id=e.length+1,r.push(t),n(r)},hideToastNotification:function(t){var r=Ie(e),o=r.findIndex((function(e){return e.id===t}));-1!==o&&(r.splice(o,1),n(r))}}},De=function(){var t=Te((0,r.useContext)(Ge).generalNotificationsState,2),e=t[0],n=t[1];return{generalNotifications:e,showGeneralNotification:function(t){var r=Ie(e);if(t.id){if(-1!==r.findIndex((function(e){return e.id===t.id})))return}else t.id=e.length+1;r.push(t),window.scrollTo({top:0,behavior:"smooth"}),n(r)},hideGeneralNotification:function(t){var r=Ie(e),o=r.findIndex((function(e){return e.id===t}));-1!==o&&(r.splice(o,1),n(r))}}};function Be(t){return Be="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Be(t)}function He(){He=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==Be(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(Be(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function We(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}function Ue(t){return function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){We(i,r,o,a,u,"next",t)}function u(t){We(i,r,o,a,u,"throw",t)}a(void 0)}))}}function qe(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,u=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(u.push(r.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||Ze(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Ze(t,e){if(t){if("string"==typeof t)return $e(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?$e(t,e):void 0}}function $e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var Ve=(0,r.createContext)({}),Ye=function(t){var e=t.children,n=(0,r.useState)({}),o=(0,r.useState)(!1),i=(0,r.useState)(null),a=(0,r.useState)(Re.NOT_STARTED),u=(0,r.useState)([]),c=(0,r.useState)(!1),l=(0,r.useState)(""),s=(0,r.useState)(""),f=(0,r.useState)(Re.NOT_STARTED),p=(0,r.useState)(Re.NOT_STARTED),d=(0,r.useState)(!1);return $t(Ve.Provider,{value:{statsDataState:n,statsLoadingState:o,bulkOptimizationOperationIdState:i,bulkOptimizationStatusState:a,bulkOptimizationImagesState:u,bulkOptimizationImagesLoadingState:c,bulkOptimizationImagesErrorState:l,generalErrorState:s,bulkRestoringState:f,bulkBackupRemovingState:p,backupsExistState:d}},e)};Ye.propTypes={children:Ut().node};var Xe=function(){var t=(0,r.useContext)(Ve),e=t.statsDataState,n=t.statsLoadingState,o=t.bulkOptimizationOperationIdState,i=t.bulkOptimizationStatusState,a=t.bulkOptimizationImagesState,u=t.bulkOptimizationImagesLoadingState,c=t.bulkOptimizationImagesErrorState,l=t.generalErrorState,s=t.bulkRestoringState,f=t.bulkBackupRemovingState,p=t.backupsExistState,d=qe(e,2),h=d[0],m=d[1],g=qe(n,2),v=g[0],y=g[1],b=qe(o,2),w=b[0],x=b[1],_=qe(i,2),S=_[0],k=_[1],O=qe(a,2),E=O[0],R=O[1],z=qe(u,2),C=z[0],j=z[1],L=qe(c,2),P=L[0],I=L[1],T=qe(l,2),A=T[0],N=T[1],G=qe(s,2),M=G[0],F=G[1],D=qe(f,2),B=D[0],H=D[1],W=qe(p,2),U=W[0],q=W[1],Z=function(){var t=Ue(He().mark((function t(){var e;return He().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return y(!0),N(""),t.prev=2,t.next=5,ke.getStats();case 5:(e=t.sent).bulk_optimization_operation_id&&e.bulk_optimization_operation_id!==w&&x(e.bulk_optimization_operation_id),m(e.optimization_stats),k(e.bulk_optimization_status),F(e.bulk_restoring_status),H(e.bulk_backup_removing_status),q(e.backups_exist),t.next=17;break;case 14:t.prev=14,t.t0=t.catch(2),N(t.t0.message);case 17:y(!1);case 18:case"end":return t.stop()}}),t,null,[[2,14]])})));return function(){return t.apply(this,arguments)}}(),$=function(){var t=Ue(He().mark((function t(e){var n;return He().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return j(!0),I(""),t.prev=2,t.next=5,ke.getBulkOptimizationImages(e);case 5:n=t.sent,R((function(t){if(!t.length)return n.images;var e,r=function(t){if(Array.isArray(t))return $e(t)}(e=t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(e)||Ze(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}();return n.images.forEach((function(t){var e=r.findIndex((function(e){return e.id===t.id}));r[e]=t})),r})),t.next=12;break;case 9:t.prev=9,t.t0=t.catch(2),I(t.t0.message);case 12:j(!1);case 13:case"end":return t.stop()}}),t,null,[[2,9]])})));return function(_x){return t.apply(this,arguments)}}();return{stats:h,statsIsLoading:v,bulkOptimizationOperationId:w,bulkOptimizationStatus:S,setBulkOptimizationStatus:k,bulkOptimizationImages:E,setBulkOptimizationImages:R,bulkOptimizationImagesLoading:C,bulkOptimizationImagesError:P,error:A,bulkRestoringStatus:M,setBulkRestoringStatus:F,bulkBackupRemovingStatus:B,setBulkBackupRemovingStatus:H,backupsExist:U,fetchStats:Z,fetchBulkOptimizationImages:$}};function Ke(t){return Ke="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ke(t)}function Qe(){Qe=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==Ke(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(Ke(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function Je(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}function tn(t){return function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){Je(i,r,o,a,u,"next",t)}function u(t){Je(i,r,o,a,u,"throw",t)}a(void 0)}))}}function en(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,u=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(u.push(r.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||function(t,e){if(t){if("string"==typeof t)return nn(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?nn(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function nn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var rn=function(){var t=Xe().setBulkOptimizationStatus,e=Fe().showToastNotification,n=en((0,r.useState)(!1),2),o=n[0],i=n[1],a=en((0,r.useState)(null),2),u=a[0],c=a[1],l=function(){var e=tn(Qe().mark((function e(){return Qe().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i(!0),c(null),e.prev=2,e.next=5,ke.runBulkOptimization(!1);case 5:t(Re.IN_PROGRESS),p(),e.next=12;break;case 9:e.prev=9,e.t0=e.catch(2),c(e.t0.message);case 12:i(!1);case 13:case"end":return e.stop()}}),e,null,[[2,9]])})));return function(){return e.apply(this,arguments)}}(),s=function(){var t=tn(Qe().mark((function t(){return Qe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,ke.runBulkOptimization(!0);case 3:t.next=8;break;case 5:t.prev=5,t.t0=t.catch(0),e(new Pe({level:"error",message:(0,oe.__)("Reoptimization failed","image-optimization"),actions:[{label:(0,oe.__)("Try again","image-optimization"),onClick:s}]}));case 8:case"end":return t.stop()}}),t,null,[[0,5]])})));return function(){return t.apply(this,arguments)}}(),f=function(){var e=tn(Qe().mark((function e(){return Qe().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i(!0),c(null),e.prev=2,e.next=5,ke.cancelBulkOptimization();case 5:t(Re.CANCELLED),d(),e.next=12;break;case 9:e.prev=9,e.t0=e.catch(2),c(e.t0.message);case 12:i(!1);case 13:case"end":return e.stop()}}),e,null,[[2,9]])})));return function(){return e.apply(this,arguments)}}(),p=function(){var t=document.querySelector(".image-optimizer__notice--bulk-tip");t&&(t.style.display="block")},d=function(){var t=document.querySelector(".image-optimizer__notice--bulk-tip");t&&(t.style.display="none")};return{loading:o,error:u,runOptimization:l,runReoptimization:s,cancelOptimization:f,hideBulkWPNotice:d}},on=function(){var t=window.imageOptimizerUserData;return"isConnected"in t&&(t.isConnected=Boolean(t.isConnected)),"isActivated"in t&&(t.isActivated=Boolean(t.isActivated)),"isUrlMismatch"in t&&(t.isUrlMismatch=Boolean(t.isUrlMismatch)),"imagesLeft"in t&&(t.imagesLeft=Number(t.imagesLeft)),"isOwner"in t&&(t.isOwner=Boolean(t.isOwner)),"isConnectOnFly"in t&&(t.isConnectOnFly=Boolean(t.isConnectOnFly)),t},an=Object.freeze({SETTINGS:"image-optimization-settings",BULK_OPTIMIZATION:"image-optimization-bulk-optimization"}),un=Object.freeze({SPEED:2,FOREGROUND_COLOR:"#D9D9D9"}),cn="https://go.elementor.com/io-panel-upgrade/",ln=["as","children","variant"];function sn(){return sn=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},sn.apply(this,arguments)}var fn=function(t){return Vt("color:",t.palette.text.default,";font-family:",t.fonts.default,";font-size:14px;font-style:normal;font-weight:400;line-height:150%;","","")},pn={h4:{name:"18b6qqh",styles:"font-size:24px;font-weight:700;line-height:130%"},h6:{name:"bfkuon",styles:"font-size:18px;font-weight:700;line-height:130%"},subtitle1:{name:"jfk0b9",styles:"font-weight:700;line-height:130%"}},dn=function(t){var e=t.as,n=t.children,r=t.variant,o=function(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}(t,ln),i=Ct(),a=e||"span",u=r?pn[r]:[],c=[fn(i).styles,(null==u?void 0:u.styles)||""].join(" ");return $t(a,sn({css:Vt(c,";","","")},o),n)};dn.propTypes={as:Ut().oneOf(["span","label","p","h1","h2","h3","h4","h5","h6"]),variant:Ut().oneOf(["h4","h6","subtitle1"]),children:Ut().node.isRequired};var hn=dn,mn=window.wp.components,gn=function(t){var e=t.size,n=t.props;return $t(mn.Icon,{icon:$t("svg",n,$t("path",{d:"M7.333 4.667h1.333V6H7.333V4.667Zm0 2.667h1.333v4H7.333v-4Zm.667-6A6.67 6.67 0 0 0 1.333 8 6.669 6.669 0 0 0 8 14.667 6.669 6.669 0 0 0 14.666 8 6.669 6.669 0 0 0 8 1.333Zm0 12A5.34 5.34 0 0 1 2.666 8 5.34 5.34 0 0 1 8 2.667 5.34 5.34 0 0 1 13.333 8 5.34 5.34 0 0 1 8 13.334Z"})),size:e})},vn=["children"];function yn(){return yn=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},yn.apply(this,arguments)}var bn=function(t){var e=t.children,n=function(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}(t,vn);return $t(mn.Tooltip,yn({children:e},n))},wn=Ht("div",{target:"e10skkyh4"})("width:100px;height:100px;display:flex;justify-content:center;align-items:center;margin-block-end:10px;border-radius:100%;background:radial-gradient(closest-side, white 79%, transparent 80% 100%),conic-gradient(",(function(t){return t.theme.palette.native.blue})," ",(function(t){return t.percentage}),"%, ",(function(t){return t.theme.palette.border.default})," 0);&>span{color:",(function(t){return t.theme.palette.native.blue}),";}"),xn=Ht("div",{target:"e10skkyh3"})("width:123px;height:11px;margin-block-end:10px;background-color:",(function(t){return t.theme.palette.background.grey}),";"),Sn=Ht("div",{target:"e10skkyh2"})("width:",(function(t){return t.percentage}),"%;height:11px;background-color:",(function(t){return t.theme.palette.native.blue}),";"),kn=Ht("div",{target:"e10skkyh1"})("width:123px;margin-block-end:17px;display:flex;justify-content:space-between;color:",(function(t){return t.theme.palette.text.tertiary}),";"),On=Ht(hn,{target:"e10skkyh0"})("color:",(function(t){return t.theme.palette.text.tertiary}),";"),En=function(t){var e=t.type,n=t.value,r=t.min,o=t.max;return"relative"===e?$t(wn,{percentage:n},$t(hn,{variant:"h4"},"".concat(n,"%"))):$t(React.Fragment,null,$t(xn,null,$t(Sn,{percentage:n})),$t(kn,null,$t(On,null,r||0),o&&$t(On,null,o)))};En.propTypes={type:Ut().oneOf(["absolute","relative"]),value:Ut().number.isRequired,min:Ut().number,max:Ut().number};var Rn=En,zn=Ht("div",{target:"eo04e8w5"})("display:flex;padding:15px 11px 16px 5px;border:1px solid ",(function(t){return t.theme.palette.border.lightest}),";width:calc(100% / ",(function(t){return t.columns}),");&:not(:last-child){border-inline-end:none;}@media screen and (max-width: 768px){justify-content:space-between;width:auto;padding:16px 50px;}"),Cn=Ht("div",{target:"eo04e8w4"})({name:"1u6n871",styles:"display:flex;flex-direction:column;justify-content:center;align-items:flex-start"}),jn=Ht(Cn,{target:"eo04e8w3"})("width:50%;align-items:center;justify-content:",(function(t){return"absolute"===t.type?"flex-end":"center"}),";@media screen and (max-width: 1120px){width:auto;}"),Ln=Ht(hn,{target:"eo04e8w2"})("display:flex;justify-content:center;align-items:center;margin-inline-start:20px;& span{display:flex;margin-inline-start:4.5px;}& svg{fill:",(function(t){return t.theme.palette.text.tertiary}),";}"),Pn=Ht(Cn,{target:"eo04e8w1"})("width:45%;margin-inline-start:10px;@media screen and (max-width: 1120px){width:auto;}",(function(t){return t.isButtonShown&&"\n\t\t& div {\n\t\t\tmargin-block-start: auto;\n\t\t}\n\n\t\t& button,\n\t\t& a {\n\t\t\tmargin-block-start: 6px;\n\t\t}\n\t"}),";"),In=Ht("hr",{target:"eo04e8w0"})("border:0.5px solid ",(function(t){return t.theme.palette.border.grey}),";width:100%;"),Tn=(0,r.memo)((function(t){var e=t.title,n=t.tooltipText,r=t.type,o=t.value,i=t.min,a=t.max,u=t.firstRow,c=t.secondRow,l=t.actionButton,s=t.columns;return $t(zn,{columns:s},$t(jn,{type:r},$t(Rn,{type:r,value:o,max:a,min:i}),$t(Ln,{variant:"subtitle1"},e,n&&$t(bn,{text:n,placement:"top"},$t("span",null,$t(gn,{size:16}))))),$t(Pn,{isButtonShown:!!l},$t("div",null,$t(hn,null,u),$t(In,null),$t(hn,null,c)),l))}));Tn.propTypes={title:Ut().string.isRequired,type:Ut().oneOf(["absolute","relative"]),value:Ut().number.isRequired,min:Ut().number,max:Ut().number,firstRow:Ut().node.isRequired,secondRow:Ut().node,actionButton:Ut().node};var An=Tn,Nn=["isNative","isPink"];var Gn=Ht(mn.Button,{target:"ey2oztq2"})("&.components-button.is-primary{background:",(function(t){return t.theme.palette.native.blue}),";border-color:",(function(t){return t.theme.palette.native.blue}),";border-radius:4px;color:",(function(t){return t.theme.palette.text.white}),";font-size:13px;line-height:2.15;height:revert;min-height:30px;padding:0 10px;}&.components-button:disabled{opacity:0.4;cursor:not-allowed;}&.components-button.is-primary:not(:disabled):hover{background:",(function(t){return t.theme.palette.native.blueActive}),";border-color:",(function(t){return t.theme.palette.native.blueActive}),";color:",(function(t){return t.theme.palette.text.white}),";}"),Mn=Ht(Gn,{target:"ey2oztq1"})("background-color:",(function(t){return t.theme.palette.primary.main}),"!important;color:",(function(t){return t.theme.palette.text.primary}),"!important;font-weight:500!important;"),Fn=Ht(mn.Button,{target:"ey2oztq0"})("border-radius:4px;&.components-button.is-primary:not(.is-destructive){background:",(function(t){return t.theme.palette.native.blue}),";border-color:",(function(t){return t.theme.palette.native.blue}),";color:",(function(t){return t.theme.palette.text.white}),";}&.components-button.is-primary:not(.is-destructive):not(:disabled):hover{background:",(function(t){return t.theme.palette.native.blueActive}),";border-color:",(function(t){return t.theme.palette.native.blueActive}),";color:",(function(t){return t.theme.palette.text.white}),";}&.components-button.is-secondary:not(.is-destructive){background:",(function(t){return t.theme.palette.background.default}),";box-shadow:inset 0 0 0 1px ",(function(t){return t.theme.palette.native.blue}),";color:",(function(t){return t.theme.palette.native.blue}),";}&.components-button.is-secondary:not(.is-destructive):not(:disabled):hover{background:",(function(t){return t.theme.palette.background.default}),";box-shadow:inset 0 0 0 1px ",(function(t){return t.theme.palette.native.blueActive}),";color:",(function(t){return t.theme.palette.native.blueActive}),";}&.components-button:disabled{opacity:0.4;cursor:not-allowed;}&.components-button.is-primary.is-destructive{background-color:",(function(t){return t.theme.palette.error.main}),";}"),Dn=function(t){var e=t.isNative,n=t.isPink,r=function(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}(t,Nn);return $t(n?Mn:e?Gn:Fn,r)},Bn=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2,n=[ // translators: %s: file size in bytes (0,oe.__)("%s Bytes","image-optimization"), // translators: %s: file size in kilobytes (0,oe.__)("%s Kb","image-optimization"), // translators: %s: file size in megabytes (0,oe.__)("%s Mb","image-optimization"), // translators: %s: file size in gigabytes (0,oe.__)("%s Gb","image-optimization")];if(!t) // translators: %s: file size in bytes return(0,oe.sprintf)((0,oe.__)("%s Bytes","image-optimization"),0);var r=Math.floor(Math.log(t)/Math.log(1024)),o=parseFloat((t/Math.pow(1024,r)).toFixed(e));return(0,oe.sprintf)(n[r],o)},Hn="active",Wn="expired",Un="exceeded",qn="not_connected",Zn="not_activated",$n="url_mismatch",Vn="error",Yn=function(){var t=on(),e=t.isConnected,n=t.isActivated,r=t.isUrlMismatch,o=t.planData,i=t.imagesLeft;if(r)return $n;if(!e)return qn;if(e&&!n)return Zn;if(!o)return Vn;var a=o.status;return 0===i?Un:"active"===a?Hn:Wn};function Xn(t){return Xn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Xn(t)}function Kn(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,(void 0,o=function(t,e){if("object"!==Xn(t)||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!==Xn(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(r.key),"symbol"===Xn(o)?o:String(o)),r)}var o}var Qn="image-optimizer/auth/activation-modal/open",Jn="image-optimizer/auth/url-mismatch-modal/open",tr=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var e,n;return e=t,n=[{key:"dispatch",value:function(t){var e=new Event(t);document.dispatchEvent(e)}},{key:"listen",value:function(t,e){document.addEventListener(t,(function(){return e.apply(void 0,arguments)}))}}],null&&Kn(e.prototype,null),n&&Kn(e,n),Object.defineProperty(e,"prototype",{writable:!1}),t}(),er=tr;function nr(t){return nr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},nr(t)}function rr(){rr=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==nr(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(nr(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function or(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}function ir(t){return function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){or(i,r,o,a,u,"next",t)}function u(t){or(i,r,o,a,u,"throw",t)}a(void 0)}))}}var ar=function(){var t=on(),e=t.isActivated,n=t.licenseKey,r=function(){var t=ir(rr().mark((function t(){var e;return rr().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,o();case 2:e=t.sent,window.open(e,"_self").focus();case 4:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}(),o=function(){var t=ir(rr().mark((function t(){return rr().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",ke.initConnect());case 1:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}(),i=function(){var t=ir(rr().mark((function t(){return rr().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!e){t.next=3;break}return t.next=3,ke.deactivate(n);case 3:return t.next=5,ke.disconnect();case 5:setTimeout((function(){window.location.href=(0,ue.addQueryArgs)(window.location.href,{action:"connect"})}),300);case 6:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}();return{redirectToConnect:r,sendActivationEvent:function(){er.dispatch(Qn)},sendUrlMismatchEvent:function(){er.dispatch(Jn)},getConnectLink:o,switchUser:i}},ur=function(){var t=on().planData,e=ar(),n=e.redirectToConnect,r=e.sendActivationEvent,o=e.sendUrlMismatchEvent,i=Yn();return $n===i?$t(Dn,{type:"button",className:"image-optimization-stats-connect-button",variant:"primary",onClick:o,isNative:!0,isPink:!0},(0,oe.__)("Fix mismatched URL","image-optimization")):qn===i?$t(Dn,{type:"button",className:"image-optimization-stats-connect-button",variant:"primary",onClick:n,isNative:!0,isPink:!0},(0,oe.__)("Connect to start","image-optimization")):Zn===i?$t(Dn,{type:"button",variant:"primary",onClick:r,isNative:!0,isPink:!0},(0,oe.__)("Activate to start","image-optimization")):t?t.status===Wn?$t(Dn,{type:"button",variant:"primary",href:"https://go.elementor.com/io-quota-upgrade/",isNative:!0,isPink:!0,target:"_blank",rel:"noopener noreferrer"},(0,oe.__)("Renew Plan","image-optimization")):$t(Dn,{type:"button",variant:"primary",href:cn,isNative:!0,isPink:!0,target:"_blank",rel:"noopener noreferrer"},(0,oe.__)("Upgrade Plan","image-optimization")):$t("div",null)},cr=function(){return cr=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},cr.apply(this,arguments)},lr=function(t){var e=t.animate,n=void 0===e||e,r=t.animateBegin,i=t.backgroundColor,a=void 0===i?"#f5f6f7":i,u=t.backgroundOpacity,c=void 0===u?1:u,l=t.baseUrl,s=void 0===l?"":l,f=t.children,p=t.foregroundColor,d=void 0===p?"#eee":p,h=t.foregroundOpacity,m=void 0===h?1:h,g=t.gradientRatio,v=void 0===g?2:g,y=t.gradientDirection,b=void 0===y?"left-right":y,w=t.uniqueKey,x=t.interval,_=void 0===x?.25:x,S=t.rtl,k=void 0!==S&&S,O=t.speed,E=void 0===O?1.2:O,R=t.style,z=void 0===R?{}:R,C=t.title,j=void 0===C?"Loading...":C,L=t.beforeMask,P=void 0===L?null:L,I=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(t);o<r.length;o++)e.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(t,r[o])&&(n[r[o]]=t[r[o]])}return n}(t,["animate","animateBegin","backgroundColor","backgroundOpacity","baseUrl","children","foregroundColor","foregroundOpacity","gradientRatio","gradientDirection","uniqueKey","interval","rtl","speed","style","title","beforeMask"]),T=w||Math.random().toString(36).substring(6),A=T+"-diff",N=T+"-animated-diff",G=T+"-aria",M=k?{transform:"scaleX(-1)"}:null,F="0; "+_+"; 1",D=E+"s",B="top-bottom"===b?"rotate(90)":void 0;return(0,o.createElement)("svg",cr({"aria-labelledby":G,role:"img",style:cr(cr({},z),M)},I),j?(0,o.createElement)("title",{id:G},j):null,P&&(0,o.isValidElement)(P)?P:null,(0,o.createElement)("rect",{role:"presentation",x:"0",y:"0",width:"100%",height:"100%",clipPath:"url("+s+"#"+A+")",style:{fill:"url("+s+"#"+N+")"}}),(0,o.createElement)("defs",null,(0,o.createElement)("clipPath",{id:A},f),(0,o.createElement)("linearGradient",{id:N,gradientTransform:B},(0,o.createElement)("stop",{offset:"0%",stopColor:a,stopOpacity:c},n&&(0,o.createElement)("animate",{attributeName:"offset",values:-v+"; "+-v+"; 1",keyTimes:F,dur:D,repeatCount:"indefinite",begin:r})),(0,o.createElement)("stop",{offset:"50%",stopColor:d,stopOpacity:m},n&&(0,o.createElement)("animate",{attributeName:"offset",values:-v/2+"; "+-v/2+"; "+(1+v/2),keyTimes:F,dur:D,repeatCount:"indefinite",begin:r})),(0,o.createElement)("stop",{offset:"100%",stopColor:a,stopOpacity:c},n&&(0,o.createElement)("animate",{attributeName:"offset",values:"0; 0; "+(1+v),keyTimes:F,dur:D,repeatCount:"indefinite",begin:r})))))},sr=function(t){return t.children?(0,o.createElement)(lr,cr({},t)):(0,o.createElement)(fr,cr({},t))},fr=function(t){return(0,o.createElement)(sr,cr({viewBox:"0 0 476 124"},t),(0,o.createElement)("rect",{x:"48",y:"8",width:"88",height:"6",rx:"3"}),(0,o.createElement)("rect",{x:"48",y:"26",width:"52",height:"6",rx:"3"}),(0,o.createElement)("rect",{x:"0",y:"56",width:"410",height:"6",rx:"3"}),(0,o.createElement)("rect",{x:"0",y:"72",width:"380",height:"6",rx:"3"}),(0,o.createElement)("rect",{x:"0",y:"88",width:"178",height:"6",rx:"3"}),(0,o.createElement)("circle",{cx:"20",cy:"20",r:"20"}))},pr=sr,dr=Ht("div",{target:"e4bhht70"})("display:flex;justify-content:center;align-items:center;padding:15px 11px 16px 5px;border:1px solid ",(function(t){return t.theme.palette.border.lightest}),";width:calc(100% / ",(function(t){return t.columns}),");&:not(:last-child){border-inline-end:none;}"),hr=(0,r.memo)((function(){return $t(pr,{speed:un.SPEED,foregroundColor:un.FOREGROUND_COLOR,height:127},$t("path",{d:"M34 42a4 4 0 0 0-4 4v8a4 4 0 0 0 4 4h32a4 4 0 0 0 4-4v-8a4 4 0 0 0-4-4H34Z"}),$t("path",{fillRule:"evenodd",d:"M100 50c0 27.614-22.386 50-50 50S0 77.614 0 50 22.386 0 50 0s50 22.386 50 50Zm-90 0c0 22.091 17.909 40 40 40s40-17.909 40-40-17.909-40-40-40-40 17.909-40 40Z",clipRule:"evenodd"}),$t("path",{d:"M157 37a4 4 0 0 0-4 4v8a4 4 0 0 0 4 4h104a4 4 0 0 0 4-4v-8a4 4 0 0 0-4-4H157ZM157 75a4 4 0 0 0-4 4v8a4 4 0 0 0 4 4h120a4 4 0 0 0 4-4v-8a4 4 0 0 0-4-4H157ZM14 111a4 4 0 0 0-4 4v8a4 4 0 0 0 4 4h72a4 4 0 0 0 4-4v-8a4 4 0 0 0-4-4H14ZM366 63H137v1h229v-1Z"}))})),mr=(0,r.memo)((function(){return $t(pr,{speed:un.SPEED,foregroundColor:un.FOREGROUND_COLOR,height:90},$t("path",{d:"M171 4a4 4 0 0 1 4-4h104a4 4 0 0 1 4 4v8a4 4 0 0 1-4 4H175a4 4 0 0 1-4-4V4ZM123 19v11H0V19h123ZM379 26H150v1h229v-1ZM22 78a4 4 0 0 1 4-4h72a4 4 0 0 1 4 4v8a4 4 0 0 1-4 4H26a4 4 0 0 1-4-4v-8ZM171 42a4 4 0 0 1 4-4h120a4 4 0 0 1 4 4v8a4 4 0 0 1-4 4H175a4 4 0 0 1-4-4v-8Z"}))})),gr=(0,r.memo)((function(t){var e=t.isOwner,n=e?3:2;return $t(React.Fragment,null,$t(dr,{columns:n},$t(hr,null)),$t(dr,{columns:n},$t(hr,null)),e&&$t(dr,{columns:n},$t(mr,null)))}));gr.propTypes={isOwner:Ut().bool.isRequired};var vr=gr,yr=Ht("div",{target:"e17a0xp02"})("display:flex;justify-content:center;align-items:center;flex-direction:column;background-color:",(function(t){return t.theme.palette.background.default}),";position:absolute;inset:0;"),br=Ht(hn,{target:"e17a0xp01"})({name:"ocysru",styles:"margin-block-end:9px"}),wr=Ht(hn,{target:"e17a0xp00"})({name:"19m435s",styles:"margin-block-start:0"}),xr=function(t){var e=t.onTryAgainClick;return $t(yr,null,$t(br,{variant:"subtitle1",as:"h2"},(0,oe.__)("We couldn't load your stats.","image-optimization")),$t(wr,{as:"p"},(0,oe.__)("It's probably a temporary glitch.","image-optimization")),$t(Dn,{variant:"secondary",onClick:e},(0,oe.__)("Try again","image-optimization")))};xr.propTypes={onTryAgainClick:Ut().func.isRequired};var _r=xr;function Sr(t){return Sr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Sr(t)}function kr(){return kr=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},kr.apply(this,arguments)}function Or(){Or=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==Sr(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(Sr(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function Er(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}var Rr=Ht("div",{target:"e5t2zyp0"})("display:flex;background-color:",(function(t){return t.theme.palette.background.default}),";position:relative;min-height:161px;@media screen and (max-width: 768px){flex-direction:column;height:auto;}"),zr=function(t){var e=t.isOwner;return $t(Rr,null,$t(vr,{isOwner:e}))},Cr=function(t){var e,n,o,i=t.page,a=on(),u=a.subscriptionEmail,c=a.isOwner,l=rn().runOptimization,s=Xe(),f=s.stats,p=s.bulkOptimizationStatus,d=s.statsIsLoading,h=s.error,m=s.fetchStats,g=function(){var t=on().planData,e=Yn();return[qn,Zn,$n,Vn].includes(e)?{type:"absolute",value:0,min:0,max:1e3,title:(0,oe.__)("Images in your plan","image-optimization"),tooltipText:(0,oe.__)("This refers to the amount of credits in your plan that you've already used.","image-optimization"),firstRow:$t(hn,null,(0,oe.sprintf)( // translators: %s: Subscription plan title (0,oe.__)("Current plan: %s","image-optimization"),(0,oe.__)("N/A","image-optimization"))),secondRow:$t(hn,null,(0,oe.sprintf)( // translators: %s: Images left in a plan (0,oe.__)("Images left: %s","image-optimization"),(0,oe.__)("N/A","image-optimization"))),actionButton:$t(ur,null)}:{type:"absolute",value:100-t.used_quota/t.quota*100,min:0,max:t.quota,title:(0,oe.__)("Images in your plan","image-optimization"),tooltipText:(0,oe.__)("This refers to the amount of credits in your plan that you've already used.","image-optimization"),firstRow:$t(hn,null,(0,oe.sprintf)( // translators: %s: Subscription plan title (0,oe.__)("Current plan: %s","image-optimization"),t.subscription_plan.title)),secondRow:$t(hn,null,(0,oe.sprintf)( // translators: %s: Images left in a plan (0,oe.__)("Images left: %s","image-optimization"),"".concat(t.quota-t.used_quota,"/").concat(t.quota))),actionButton:$t(ur,null)}}(),v=function(){var t,e=(t=Or().mark((function t(){return Or().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,l();case 2:i!==an.BULK_OPTIMIZATION&&(location.href="/wp-admin/upload.php?page=image-optimization-bulk-optimization");case 3:case"end":return t.stop()}}),t)})),function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){Er(i,r,o,a,u,"next",t)}function u(t){Er(i,r,o,a,u,"throw",t)}a(void 0)}))});return function(){return e.apply(this,arguments)}}(),y=(0,r.useDeferredValue)(f),b=(e=y.initial_image_size,n=y.current_image_size,o=Math.round(100-n/e*100),Number.isNaN(o)&&(o=0),{type:"relative",value:o,title:(0,oe.__)("Space saved","image-optimization"),tooltipText:(0,oe.__)("This refers to the percentage of storage space saved by optimizing your images.","image-optimization"),firstRow:(0,oe.sprintf)( // translators: %s: File size (0,oe.__)("Initial size: %s","image-optimization"),null!==e?Bn(e):(0,oe.__)("N/A","image-optimization")),secondRow:(0,oe.sprintf)( // translators: %s: File size (0,oe.__)("Current size: %s","image-optimization"),null!==n?Bn(n):(0,oe.__)("N/A","image-optimization"))}),w=function(t,e,n,r){var o=t-e,i=Math.round(e/t*100),a=on(),u=a.isActivated,c=a.imagesLeft;return Number.isNaN(i)&&(i=0),{type:"relative",value:Math.min(i,100),title:(0,oe.__)("Images optimized","image-optimization"),tooltipText:(0,oe.__)("This refers to the amount of images you've optimized out of your whole library.","image-optimization"),firstRow:(0,oe.sprintf)( // translators: %s: Images count (0,oe.__)("Total: %s","image-optimization"),null!==t?Math.max(t,0):(0,oe.__)("N/A","image-optimization")),secondRow:(0,oe.sprintf)( // translators: %s: Images count (0,oe.__)("Unoptimized: %s","image-optimization"),null!==t?Math.max(o,0):(0,oe.__)("N/A","image-optimization")),actionButton:u&&o>0&&c>0&&$t(Dn,{type:"button",variant:"primary",disabled:[Re.IN_PROGRESS,Re.CANCELLED].includes(n),onClick:r,isNative:!0},(0,oe.sprintf)( // Translators: %s: Images count (0,oe.__)("Optimize All (%s)","image-optimization"),o))}}(y.total_image_count,y.optimized_image_count,p,v);if(!Object.keys(y).length&&d)return $t(zr,{isOwner:c});if(h)return $t(Rr,null,$t(vr,{isOwner:c}),$t(_r,{onTryAgainClick:m}));var x=[b,w];return(!u||u&&c)&&x.push(g),$t(r.Suspense,{fallback:$t(zr,{isOwner:c})},$t(Rr,null,x.map((function(t,e){return $t(An,kr({key:"optimization-stats-item-".concat(e),columns:x.length},t))}))))};Cr.propTypes={page:Ut().string};var jr=Cr;function Lr(t){return Lr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Lr(t)}function Pr(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,u=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(u.push(r.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||function(t,e){if(t){if("string"==typeof t)return Ir(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ir(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Ir(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var Tr=(0,r.createContext)({}),Ar=function(t){var e=t.children,n=(0,r.useState)({}),o=(0,r.useState)({});return $t(Tr.Provider,{value:{formDataState:n,lastUpdateState:o}},e)};Ar.propTypes={children:Ut().node};var Nr=function(){var t=(0,r.useContext)(Tr),e=t.formDataState,n=t.lastUpdateState,o=Pr(e,2),i=o[0],a=o[1],u=Pr(n,2)[1];return{getControlData:function(t){return i&&t in i?i[t]:null},setControlData:function(t,e){var n=JSON.parse(JSON.stringify(i));n[t]=e,u(function(t,e,n){return(e=function(t){var e=function(t,e){if("object"!==Lr(t)||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!==Lr(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"===Lr(e)?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}({},t,e)),a(n)}}},Gr=["title","subtitle","children","showUpdated","error","showDivider"];function Mr(){return Mr=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Mr.apply(this,arguments)}var Fr=Ht(mn.PanelRow,{target:"efkj2fw5"})("justify-content:flex-start;margin-block-start:16px;padding-inline-start:7px;padding-inline-end:7px;padding-block-end:16px;",(function(t){var e=t.showDivider,n=t.theme;return e&&"\n\t\tborder-block-end: 1px solid ".concat(n.palette.border.grey,";\n\t")})," &.components-panel__row--advanced-action{padding-inline-start:21px;padding-inline-end:21px;}"),Dr=Ht("div",{target:"efkj2fw4"})({name:"h3t0bk",styles:"display:flex;flex-direction:column;align-self:flex-start;width:300px;margin-inline-end:50px"}),Br=Ht(hn,{target:"efkj2fw3"})("color:",(function(t){return t.theme.palette.text.primary}),";&:not(:disabled){margin-block-end:9px;}"),Hr=Ht(hn,{target:"efkj2fw2"})("color:",(function(t){return t.theme.palette.text.tertiary}),";"),Wr=Ht(hn,{target:"efkj2fw1"})("color:",(function(t){return t.theme.palette.error.main}),";margin-inline-start:16px;"),Ur=Ht(hn,{target:"efkj2fw0"})("color:",(function(t){return t.theme.palette.badge.text.success}),";margin-inline-start:16px;"),qr=function(t){var e=t.title,n=t.subtitle,r=t.children,o=t.showUpdated,i=t.error,a=t.showDivider,u=void 0===a||a,c=function(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}(t,Gr);return $t(Fr,Mr({showDivider:u},c),$t(Dr,null,e&&$t(Br,{variant:"subtitle1",as:"h3"},e),$t(Hr,null,n)),$t("div",null,r),i&&$t(Wr,null,i),o&&$t(Ur,null,(0,oe.__)("Setting saved!","image-optimization")))};qr.propTypes={title:Ut().string,subtitle:Ut().oneOfType([Ut().string,Ut().node]).isRequired,children:Ut().node.isRequired,showUpdated:Ut().bool.isRequired,error:Ut().string,showDivider:Ut().bool};var Zr=qr,$r=function(t){var e=t.message,n=t.supportiveText;return $t("p",null,$t("b",null,e)," ",$t("span",null,n))},Vr=Ht(mn.PanelBody,{target:"e16t28jn0"})({name:"sq4cu8",styles:'.components-panel__row:last-of-type{padding-block-end:0;}& .components-panel__body-toggle .components-panel__arrow{position:relative;inset-block-start:1px;inset-inline-end:0;transform:rotate(-90deg);width:16px;height:16px;margin-inline-end:4px;}& .components-panel__body-toggle[aria-expanded="true"] .components-panel__arrow{transform:rotate(180deg);}'}),Yr=function(t){var e=t.title,n=t.children,r=t.initialOpen,o=void 0===r||r,i=e?$t(hn,{variant:"subtitle1"},e):void 0;return $t(Vr,{title:i,initialOpen:o},n)};Yr.propTypes={title:Ut().string,children:Ut().node,initialOpen:Ut().bool};var Xr=Yr,Kr=Ht(mn.Disabled,{target:"e1f5yh580"})({name:"o9ww1u",styles:"opacity:0.5"}),Qr=function(t){var e=t.isDisabled,n=t.children;return $t(Kr,{isDisabled:e},n)},Jr=Ht(mn.Panel,{target:"eopetj90"})("margin-block-start:16px;min-height:50vh;& .components-panel__header{height:67px;padding:0 23px;}& .components-panel__header h2{color:",(function(t){return t.theme.palette.text.primary}),";}.components-panel__body.is-opened{padding:16px;}"),to=function(t){var e=t.header,n=t.children,r=$t(hn,{variant:"h6"},e);return $t(Jr,{header:r},n)};to.propTypes={header:Ut().string.isRequired,children:Ut().node};var eo=to,no=function(t){var e=t.children;return $t(eo,{header:(0,oe.__)("Settings","image-optimization")},e)};no.propTypes={children:Ut().node};var ro=no,oo=Ht("span",{target:"e8cyu560"})({name:"96f02t",styles:"display:flex;padding:4px 8px;align-items:center;border-radius:4px;&>svg{margin-inline-end:4px;}"}),io=function(t){return Vt("color:",t.palette.badge.text.success,";background-color:",t.palette.badge.background.success,";&>svg{fill:",t.palette.badge.text.success,";}","","")},ao={success:io,error:function(t){return Vt("color:",t.palette.badge.text.danger,";background-color:",t.palette.badge.background.danger,";&>svg{fill:",t.palette.badge.text.danger,";}","","")},warning:function(t){return Vt("color:",t.palette.badge.text.warning,";background-color:",t.palette.badge.background.warning,";&>svg{fill:",t.palette.badge.text.warning,";}","","")}},uo=function(t){var e=t.icon,n=t.text,r=t.variant,o=Ct();return $t(oo,{css:Vt((r?ao[r]:io)(o).styles,";","","")},e||"",n)};uo.propTypes={icon:Ut().node,text:Ut().string.isRequired,variant:Ut().oneOf(["success","warning","error"])};var co=uo;function lo(){return lo=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},lo.apply(this,arguments)}var so,fo,po=function(t){var e=t.size,n=t.props;return $t(mn.Icon,{icon:$t("svg",lo({width:"8",height:"8"},n),$t("circle",{cx:"4",cy:"4",r:"4"})),size:e})};function ho(t){return ho="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ho(t)}function mo(t,e,n){return(e=function(t){var e=function(t,e){if("object"!==ho(t)||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!==ho(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"===ho(e)?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var go=Object.freeze((mo(so={},Hn,"success"),mo(so,qn,"warning"),mo(so,Zn,"warning"),mo(so,$n,"error"),mo(so,Vn,"error"),mo(so,Wn,"error"),mo(so,Un,"error"),so)),vo=Object.freeze((mo(fo={},Hn,(0,oe.__)("Active","image-optimization")),mo(fo,qn,(0,oe.__)("Not Connected","image-optimization")),mo(fo,Zn,(0,oe.__)("Not Activated","image-optimization")),mo(fo,$n,(0,oe.__)("Mismatch","image-optimization")),mo(fo,Vn,(0,oe.__)("Connection error","image-optimization")),mo(fo,Wn,(0,oe.__)("Expired","image-optimization")),mo(fo,Un,(0,oe.__)("Quota reached","image-optimization")),fo)),yo=function(t){var e=t.status;return $t(co,{variant:go[e],text:vo[e],icon:$t(po,{size:"8"})})};yo.propTypes={status:Ut().oneOf(Object.keys(go))};var bo=yo,wo=Ht("div",{target:"ezm8g9k1"})({name:"1nsxxnd",styles:"display:flex;align-items:center;&>:first-of-type{margin-inline-end:16px;}"}),xo=Ht(hn,{target:"ezm8g9k0"})("color:",(function(t){return t.theme.palette.text.primary}),";"),_o=function(){var t,e=on().planData,n=Yn();return $t(wo,null,[Un,Hn,Wn].includes(n)&&$t(xo,null,null==e||null===(t=e.subscription_plan)||void 0===t?void 0:t.title),$t(bo,{status:n}))},So=Ht("div",{target:"e1cnhkfy0"})('& [data-wp-component="ToggleGroupControl"]{border-radius:2px;border:1px solid ',(function(t){return t.theme.palette.border.grey600}),';}& button[aria-checked="true"],& div[role="presentation"]{background-color:',(function(t){return t.theme.palette.text.secondary}),";}& .components-base-control__field>:first-of-type{display:",(function(t){return t.hasLabel?"flex":"none"}),";}"),ko=function(t){var e=t.id,n=t.options,r=t.label,o=void 0===r?"":r,i=Nr(),a=i.getControlData,u=i.setControlData,c=a(e)||"";if(c)return $t(So,{hasLabel:!!o},$t(mn.__experimentalToggleGroupControl,{id:e,value:c,label:o,isAdaptiveWidth:!0,onChange:function(t){return function(t){c!==t&&u(e,t)}(t)}},n.map((function(t){var e=t.label,n=t.value,r=t.tooltip;return $t(mn.__experimentalToggleGroupControlOption,{key:n,label:e,value:n,showTooltip:Boolean(r),"aria-label":Boolean(r)?r:""})}))))};ko.propTypes={id:Ut().string.isRequired,options:Ut().array.isRequired,label:Ut().string};var Oo=ko,Eo=Ht(mn.CheckboxControl,{target:"ehetvcd0"})("& .components-checkbox-control__label{color:",(function(t){return t.theme.palette.text.primary}),';}& .components-checkbox-control__input[type="checkbox"]:checked,& .components-checkbox-control__input[type="checkbox"]:indeterminate{background-color:',(function(t){return t.theme.palette.native.blue}),";}"),Ro=function(t){var e=t.id,n=t.label,r=Nr(),o=r.getControlData,i=r.setControlData,a=o(e)||!1;return $t(Eo,{id:e,checked:a,label:n,onChange:function(){i(e,!a)}})};Ro.propTypes={id:Ut().string.isRequired,label:Ut().string.isRequired};var zo=Ro,Co=Ht(mn.TextControl,{target:"eruxtwg0"})({name:"l0gpp6",styles:"& ::-webkit-outer-spin-button,& ::-webkit-inner-spin-button{-webkit-appearance:none;margin:0;}& input{-moz-appearance:textfield;}"}),jo=function(t){var e=t.id,n=t.type,r=void 0===n?"text":n,o=t.label,i=Nr(),a=i.getControlData,u=i.setControlData,c=a(e)||"";return $t(Co,{id:e,defaultValue:c,type:r,label:o,onChange:function(){},onBlur:function(t){return n=t.target.value,void(c!==n&&u(e,n));var n}})};jo.propTypes={id:Ut().string.isRequired,type:Ut().oneOf(["number","text","search","email","password","tel","url"]),label:Ut().string};var Lo=jo,Po=Ht("div",{target:"elnnxye0"})("display:flex;align-items:center;margin-block-start:13px;margin-inline-start:32px;color:",(function(t){return t.theme.palette.text.primary}),';input[id*="resize_larger_images_size"]{width:64px;margin:0 8px;}'),Io=function(){var t=(0,Nr().getControlData)(zi);return $t(React.Fragment,null,$t(zo,{id:zi,label:(0,oe.__)("Allow large image resizing","image-optimization")}),t&&$t(Po,null,(0,oe.__)("to maximum","image-optimization"),$t(Lo,{id:Ci,type:"number"}),(0,oe.__)("pixels width/height","image-optimization")))},To=Ht(mn.ToggleControl,{target:"e1knkpa90"})("margin-block-end:0!important;& .components-toggle-control__label{color:",(function(t){return t.theme.palette.text.primary}),";}& .components-form-toggle.is-checked .components-form-toggle__track{background-color:",(function(t){return t.theme.palette.native.blue}),";}"),Ao=function(t){var e=t.id,n=t.label,r=Nr(),o=r.getControlData,i=r.setControlData,a=o(e)||!1;return $t(To,{id:e,checked:a,label:n,onChange:function(){i(e,!a)}})};Ao.propTypes={id:Ut().string.isRequired,label:Ut().string.isRequired};var No=Ao;function Go(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var Mo=function(){var t,e,n=(t=(0,r.useState)(!1),e=2,function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,u=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(u.push(r.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||function(t,e){if(t){if("string"==typeof t)return Go(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Go(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),o=n[0],i=n[1];return{isOpen:o,open:function(){i(!0)},close:function(){i(!1)}}},Fo=["title","isDestructive","onCancel","onClose","onApprove","approveText","children"];function Do(){return Do=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Do.apply(this,arguments)}var Bo=Ht(mn.Modal,{target:"e1yhoqj01"})("font-family:",(function(t){return t.theme.fonts.default}),";"),Ho=Ht("div",{target:"e1yhoqj00"})("display:flex;justify-content:flex-end;margin-block-start:40px;& button:first-of-type{margin-inline-end:13px;color:",(function(t){return t.theme.palette.text.secondary}),";}"),Wo=function(t){var e=t.title,n=t.isDestructive,r=void 0!==n&&n,o=t.onCancel,i=t.onClose,a=t.onApprove,u=t.approveText,c=void 0===u?(0,oe.__)("Submit","image-optimization"):u,l=t.children,s=function(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}(t,Fo);return $t(Bo,Do({title:e,onRequestClose:i},s),$t("div",null,l),$t(Ho,null,$t(Dn,{onClick:o},(0,oe.__)("Cancel","image-optimization")),$t(Dn,{isDestructive:r,variant:"primary",onClick:a},c)))};Wo.propTypes={title:Ut().string.isRequired,isDestructive:Ut().bool,onCancel:Ut().func.isRequired,onClose:Ut().func.isRequired,onApprove:Ut().func.isRequired,approveText:Ut().string,children:Ut().node};var Uo=Wo;function qo(t){return qo="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},qo(t)}function Zo(){Zo=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==qo(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(qo(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function $o(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}var Vo=function(){var t=Mo(),e=t.isOpen,n=t.open,r=t.close,o=Xe(),i=o.backupsExist,a=o.bulkRestoringStatus,u=o.setBulkRestoringStatus,c=Fe().showToastNotification,l=function(){var t,e=(t=Zo().mark((function t(){return Zo().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,ke.restoreAllImages();case 3:u(Re.IN_PROGRESS),t.next=9;break;case 6:t.prev=6,t.t0=t.catch(0),c(new Pe({level:"error",message:(0,oe.__)("An error occurred while restoring your original images.","image-optimization"),actions:[{label:(0,oe.__)("Retry","image-optimization"),onClick:l}]}));case 9:r();case 10:case"end":return t.stop()}}),t,null,[[0,6]])})),function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){$o(i,r,o,a,u,"next",t)}function u(t){$o(i,r,o,a,u,"throw",t)}a(void 0)}))});return function(){return e.apply(this,arguments)}}(),s=Re.IN_PROGRESS===a?(0,oe.__)("Restoring…","image-optimization"):(0,oe.__)("Restore originals","image-optimization"),f=!i||Re.IN_PROGRESS===a;return $t(React.Fragment,null,$t(Dn,{variant:"primary",isDestructive:!0,onClick:e?r:n,disabled:f},s),e&&$t(Uo,{isDestructive:!0,onClose:r,onCancel:r,title:(0,oe.__)("Restore all original images?","image-optimization"),approveText:(0,oe.__)("Restore","image-optimization"),onApprove:l,style:{width:"335px"}},$t(hn,{as:"p"},(0,oe.__)("This will remove all optimized images and may cause performance issues.","image-optimization"))))},Yo=function(){return imageOptimizerAppSettings};function Xo(){return Xo=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Xo.apply(this,arguments)}var Ko=function(t){var e=t.size,n=t.props;return $t(mn.Icon,{icon:$t("svg",Xo({width:"20",height:"24"},n),$t("path",{fillRule:"evenodd",d:"m13.99 10.889-3.988 3.418-3.988-3.418.976-1.139 3.012 2.582 3.012-2.582.976 1.139Z",clipRule:"evenodd"})),size:e})},Qo=Ht("button",{target:"e1kawxtg1"})("display:flex;align-items:center;background-color:transparent;border:none;color:",(function(t){return t.theme.palette.text.primary}),";& svg{transform:",(function(t){return t.isOpen?"initial":"rotate(-90deg);"})," margin-inline-end:6px;}&:disabled{color:",(function(t){return t.theme.palette.text.disabled}),";}&:disabled svg{fill:",(function(t){return t.theme.palette.text.disabled}),";}"),Jo=Ht("div",{target:"e1kawxtg0"})("height:",(function(t){return t.isOpen?"initial":"0"}),";overflow:hidden;margin-block-start:10px;margin-inline-start:29px;"),ti=function(t){var e=t.isOpen,n=t.onOpen,r=t.onClose,o=t.title,i=t.disabled,a=t.children;return $t(React.Fragment,null,$t(Qo,{onClick:function(){if(!i)return e?r():n()},isOpen:e,disabled:i},$t(Ko,null),o),$t(Jo,{isOpen:e},a))};ti.propTypes={isOpen:Ut().bool.isRequired,onOpen:Ut().func.isRequired,onClose:Ut().func.isRequired,title:Ut().string.isRequired,disabled:Ut().bool,children:Ut().node};var ei=ti;function ni(t){return ni="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ni(t)}var ri=["getControlData","setControlData"];function oi(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}var ii=function(t){var e=t.getControlData,n=t.setControlData;return function(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?oi(Object(n),!0).forEach((function(e){var r,o,i;r=t,o=e,i=n[e],(o=function(t){var e=function(t,e){if("object"!==ni(t)||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!==ni(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"===ni(e)?e:String(e)}(o))in r?Object.defineProperty(r,o,{value:i,enumerable:!0,configurable:!0,writable:!0}):r[o]=i})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):oi(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}({getControlData:function(){return(t=e.apply(void 0,arguments))&&"all"!==t?t.split(","):t;var t},setControlData:function(t,e){return n(t,function(t){return Array.isArray(t)?t.join():t}(e))}},function(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}(t,ri))};function ai(t){return function(t){if(Array.isArray(t))return li(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||ci(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function ui(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,u=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(u.push(r.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||ci(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function ci(t,e){if(t){if("string"==typeof t)return li(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?li(t,e):void 0}}function li(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var si=Ht("div",{target:"e1ncrsyk0"})('margin-block-start:15px;margin-inline-start:15px;& .components-checkbox-control__input[type="checkbox"]:checked,& .components-checkbox-control__input[type="checkbox"]:indeterminate{background-color:',(function(t){return t.theme.palette.native.blue}),";}& .components-checkbox-control:not(:last-of-type){margin-block-end:12px;}"),fi="all",pi="custom",di=[{label:(0,oe.__)("All Sizes","image-optimization"),value:fi},{label:(0,oe.__)("Custom","image-optimization"),value:pi}],hi=function(){var t,e=Yo().thumbnailSizes,n=ui((0,r.useState)(!1),2),o=n[0],i=n[1],a=ii(Nr()),u=a.getControlData,c=a.setControlData,l=u(Ii);return(0,r.useEffect)((function(){l===fi||o||i(!0),l===fi&&o&&i(!1)}),[]),$t(React.Fragment,null,$t(mn.SelectControl,{id:zi,options:di,value:o?pi:fi,onChange:function(t){return function(t){if(t===fi)return l!==fi&&c(Ii,fi),void i(!1);i(!0)}(t)}}),$t(si,null,$t(ei,{title:(0,oe.__)("Custom sizes","image-optimization"),disabled:!o,isOpen:o,onOpen:function(){i(!0)},onClose:function(){i(!1),c(Ii,fi)}},null===(t=Object.entries(e))||void 0===t?void 0:t.map((function(t){var n,r,o=ui(t,2),i=o[0],a=o[1],u=a.width,s=a.height;return $t(Eo,{key:i,id:i,checked:l===fi||(null==l?void 0:l.includes(i)),label:(n=i,r="".concat(u,"x").concat(s),n=(n=n.charAt(0).toUpperCase()+n.slice(1)).replaceAll("_"," "),"".concat(n," (").concat(r,")")),onChange:function(t){return function(t,n){if(l!==fi){var r=ai(l);n?r.push(t):r.splice(r.findIndex((function(e){return e===t})),1),c(Ii,r)}else{var o=ai(Object.keys(e));c(Ii,o.filter((function(e){return e!==t})))}}(i,t)}})})))))};function mi(t){return mi="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},mi(t)}function gi(){gi=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==mi(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(mi(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function vi(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}var yi=function(){var t=Mo(),e=t.isOpen,n=t.open,r=t.close,o=Xe(),i=o.backupsExist,a=o.bulkBackupRemovingStatus,u=o.setBulkBackupRemovingStatus,c=o.bulkRestoringStatus,l=Fe().showToastNotification,s=function(){var t,e=(t=gi().mark((function t(){return gi().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,ke.removeAllImageBackups();case 3:u(Re.IN_PROGRESS),t.next=9;break;case 6:t.prev=6,t.t0=t.catch(0),l(new Pe({level:"error",message:(0,oe.__)("An error occurred while deleting your backups.","image-optimization"),actions:[{label:(0,oe.__)("Retry","image-optimization"),onClick:s}]}));case 9:r();case 10:case"end":return t.stop()}}),t,null,[[0,6]])})),function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){vi(i,r,o,a,u,"next",t)}function u(t){vi(i,r,o,a,u,"throw",t)}a(void 0)}))});return function(){return e.apply(this,arguments)}}(),f=Re.IN_PROGRESS===a?(0,oe.__)("Deleting…","image-optimization"):(0,oe.__)("Delete backups","image-optimization"),p=!i||[a,c].includes(Re.IN_PROGRESS);return $t(React.Fragment,null,$t(Dn,{variant:"primary",isDestructive:!0,onClick:e?r:n,disabled:p},f),e&&$t(Uo,{isDestructive:!0,onClose:r,onCancel:r,title:(0,oe.__)("Delete all original images?","image-optimization"),approveText:(0,oe.__)("Delete","image-optimization"),onApprove:s,style:{width:"335px"}},$t(hn,{as:"p"},(0,oe.__)("This action can’t be undone and your library will only contain the new, optimized versions.","image-optimization"))))},bi=Ht("div",{target:"e161r2h60"})("display:flex;align-items:start;&:not(:last-of-type){margin-block-end:20px;}& input{position:relative;top:5px;}& div{display:flex;flex-direction:column;margin-inline-start:16px;}& div label{color:",(function(t){return t.theme.palette.text.primary}),";}& div span{color:",(function(t){return t.theme.palette.text.tertiary}),";}"),wi=function(){var t=Nr(),e=t.getControlData,n=t.setControlData,r=e(Pi);return Ni.map((function(t){return $t(bi,{key:t.id},$t("input",{type:"radio",id:"io-convert-format-field-".concat(t.id),name:Pi,value:t.id,checked:t.id===r,onChange:function(){return e=t.id,void n(Pi,e);var e}}),$t("div",null,$t(hn,{as:"label",htmlFor:"io-convert-format-field-".concat(t.id)},t.title),$t(hn,null,t.description)))}))};function xi(t){return xi="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xi(t)}function _i(){_i=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==xi(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(xi(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function Si(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}function ki(t){return function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){Si(i,r,o,a,u,"next",t)}function u(t){Si(i,r,o,a,u,"throw",t)}a(void 0)}))}}function Oi(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var Ei="image_optimizer_compression_level",Ri="image_optimizer_optimize_on_upload",zi="image_optimizer_resize_larger_images",Ci="image_optimizer_resize_larger_images_size",ji="image_optimizer_exif_metadata",Li="image_optimizer_original_images",Pi="image_optimizer_convert_to_format",Ii="image_optimizer_custom_sizes",Ti=[Ei],Ai=[{label:(0,oe.__)("Lossless","image-optimization"),value:"lossless",tooltip:(0,oe.__)("Reduces image file sizes without compromising the integrity or quality of your images.","image-optimization")},{label:(0,oe.__)("Lossy","image-optimization"),value:"lossy",tooltip:(0,oe.__)("Maximizes compression to produce lightweight images with smaller file sizes","image-optimization")}],Ni=[{id:"webp",title:(0,oe.__)("WebP","image-optimization"),description:(0,oe.__)("Best for high compatibility.","image-optimization")},{id:"avif",title:(0,oe.__)("AVIF","image-optimization"),description:(0,oe.__)("Offers superior compression.","image-optimization")},{id:"original",title:(0,oe.__)("Keep original format","image-optimization"),description:(0,oe.__)("No changes to the format will be made.","image-optimization")}];function Gi(t){return Gi="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Gi(t)}function Mi(){Mi=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==Gi(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(Gi(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function Fi(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}function Di(t){return function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){Fi(i,r,o,a,u,"next",t)}function u(t){Fi(i,r,o,a,u,"throw",t)}a(void 0)}))}}function Bi(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,u=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(u.push(r.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||function(t,e){if(t){if("string"==typeof t)return Hi(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Hi(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Hi(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var Wi=function(t){return Object.keys(t).forEach((function(e){e.startsWith("image_optimizer_")||delete t[e]})),t},Ui=Ht(mn.Panel,{target:"ezomauk0"})({name:"1tmq4qk",styles:"margin-block-start:16px;min-height:50vh;padding:23px"}),qi=(0,r.memo)((function(){return $t(pr,{speed:un.SPEED,foregroundColor:un.FOREGROUND_COLOR,height:222,width:595},$t("path",{d:"M4 0a4 4 0 0 0-4 4v8a4 4 0 0 0 4 4h168a4 4 0 0 0 4-4V4a4 4 0 0 0-4-4H4ZM4 60a4 4 0 0 0-4 4v4a4 4 0 0 0 4 4h168a4 4 0 0 0 4-4v-4a4 4 0 0 0-4-4H4ZM4 162a4 4 0 0 0-4 4v4a4 4 0 0 0 4 4h168a4 4 0 0 0 4-4v-4a4 4 0 0 0-4-4H4ZM4 88a4 4 0 0 0-4 4v4a4 4 0 0 0 4 4h272a4 4 0 0 0 4-4v-4a4 4 0 0 0-4-4H4ZM4 190a4 4 0 0 0-4 4v4a4 4 0 0 0 4 4h272a4 4 0 0 0 4-4v-4a4 4 0 0 0-4-4H4ZM4 108a4 4 0 0 0-4 4v4a4 4 0 0 0 4 4h208a4 4 0 0 0 4-4v-4a4 4 0 0 0-4-4H4ZM4 210a4 4 0 0 0-4 4v4a4 4 0 0 0 4 4h208a4 4 0 0 0 4-4v-4a4 4 0 0 0-4-4H4ZM439 81a4 4 0 0 0-4 4v16a4 4 0 0 0 4 4h112a4 4 0 0 0 4-4V85a4 4 0 0 0-4-4H439ZM439 178a4 4 0 0 0-4 4v24a4 4 0 0 0 4 4h152a4 4 0 0 0 4-4v-24a4 4 0 0 0-4-4H439Z"}))})),Zi=(0,r.memo)((function(t){var e=t.children;return $t(Ui,null,$t(qi,null),e)}));Zi.propTypes={children:Ut().node};var $i=Zi,Vi=Ht("div",{target:"euy8j142"})({name:"18ywltx",styles:"display:flex;justify-content:center;align-items:center;flex-direction:column;margin-block-start:92px"}),Yi=Ht(hn,{target:"euy8j141"})({name:"ocysru",styles:"margin-block-end:9px"}),Xi=Ht(hn,{target:"euy8j140"})({name:"19m435s",styles:"margin-block-start:0"}),Ki=(0,r.memo)((function(t){var e=t.onTryAgainClick;return $t(Vi,null,$t(Yi,{variant:"subtitle1",as:"h2"},(0,oe.__)("Oh! There was a temporary glitch.","image-optimization")),$t(Xi,{as:"p"},(0,oe.__)("No big deal. Wait a moment then try again.","image-optimization")),$t(Dn,{variant:"secondary",onClick:e},(0,oe.__)("Try again","image-optimization")))}));Ki.propTypes={onTryAgainClick:Ut().func.isRequired};var Qi=Ki,Ji=["key","component","alwaysVisible"],ta=["key","component"];function ea(){return ea=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},ea.apply(this,arguments)}function na(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}var ra=function(){var t,e,n,o,i,a,u=(e=(t=(0,r.useContext)(Tr)).formDataState,n=t.lastUpdateState,{formData:(o=Pr(e,2))[0],setFormData:o[1],lastUpdate:Pr(n,1)[0]}),c=u.formData,l=u.setFormData,s=u.lastUpdate,f=Yn(),p=function(){var t=Bi((0,r.useState)(null),2),e=t[0],n=t[1],o=Bi((0,r.useState)(!1),2),i=o[0],a=o[1],u=Bi((0,r.useState)(null),2),c=u[0],l=u[1],s=Bi((0,r.useState)({}),2),f=s[0],p=s[1],d=Bi((0,r.useState)({}),2),h=d[0],m=d[1],g=function(){var t=Di(Mi().mark((function t(){var e;return Mi().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return a(!0),l(null),t.prev=2,t.next=5,ke.getSettings();case 5:e=t.sent,n(Wi(e)),t.next=12;break;case 9:t.prev=9,t.t0=t.catch(2),l(t.t0.message);case 12:a(!1);case 13:case"end":return t.stop()}}),t,null,[[2,9]])})));return function(){return t.apply(this,arguments)}}(),v=function(){var t=Di(Mi().mark((function t(e){var n,r;return Mi().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return a(!0),m({}),p({}),t.prev=3,t.next=6,ke.updateSettings(e);case 6:n={},Object.keys(e).forEach((function(t){return n[t]=!0})),p(n),t.next=16;break;case 11:t.prev=11,t.t0=t.catch(3),r={},Object.keys(e).forEach((function(e){return r[e]=t.t0.message})),m(r);case 16:a(!1);case 17:case"end":return t.stop()}}),t,null,[[3,11]])})));return function(_x){return t.apply(this,arguments)}}();return{isLoading:i,data:e,fetchingError:c,updatedFields:f,updatingError:h,hideUpdateSuccessMessages:function(){p({})},hideUpdatingErrors:function(){m({})},fetchSettings:g,pushSettings:v}}(),d=p.data,h=p.isLoading,m=p.fetchingError,g=p.updatedFields,v=p.updatingError,y=p.fetchSettings,b=p.pushSettings,w=p.hideUpdateSuccessMessages,x=p.hideUpdatingErrors,_=De().showGeneralNotification,S=rn().runReoptimization,k=Xe().backupsExist,O=(i=on().isOwner,a=[{key:Ei,title:(0,oe.__)("Compression level","image-optimization"),subtitle:(0,oe.__)("This refers to the amount of data preserved in the image file.","image-optimization"),component:$t(Oo,{id:Ei,options:Ai})},{key:Ri,title:(0,oe.__)("Optimize new uploads","image-optimization"),subtitle:(0,oe.__)("This will automatically apply your optimization settings to all new uploads.","image-optimization"),component:$t(No,{id:Ri,label:(0,oe.__)("Optimize new uploads","image-optimization")})},{key:zi,title:(0,oe.__)("Resize larger images","image-optimization"),subtitle:(0,oe.__)("This uses one additional credit per image.","image-optimization"),component:$t(Io,null)},{key:ji,title:(0,oe.__)("Clear EXIF Metadata","image-optimization"),subtitle:(0,oe.__)("This refers to date, time, location, etc.","image-optimization"),component:$t(No,{id:ji,label:(0,oe.__)("Clear metadata","image-optimization")})},{key:Li,title:(0,oe.__)("Backup original images","image-optimization"),subtitle:(0,oe.__)("This takes up additional space in your library.","image-optimization"),component:$t(No,{id:Li,label:(0,oe.__)("Backup originals","image-optimization")})},{key:Pi,title:(0,oe.__)("Convert to a different format","image-optimization"),subtitle:(0,oe.__)("Select the type of format to convert the images on your site. Original formats will be saved as a backup, even if you convert your images.","image-optimization"),component:$t(wi,null)},{key:"files_optimization",title:(0,oe.__)("File optimization","image-optimization"),subtitle:(0,oe.__)("In addition to your original upload, you can optimize the versions resized by WordPress. Each additional size counts as one credit.","image-optimization"),component:$t(hi,null),showDivider:!1}],i&&a.unshift({key:"subscription_status",title:(0,oe.__)("Subscription status","image-optimization"),subtitle:(0,oe.__)("To use Image Optimizer, first you need to connect an Elementor account.","image-optimization"),component:$t(_o,null),alwaysVisible:!0}),{fields:a}).fields,E=function(){var t,e,n=on(),o=n.isConnected,i=n.isActivated,a=n.subscriptionEmail,u=n.licenseKey,c=n.showResetButton,l=ar().switchUser,s=Fe().showToastNotification,f=(t=(0,r.useState)(!1),e=2,function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,u=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(u.push(r.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||function(t,e){if(t){if("string"==typeof t)return Oi(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Oi(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),p=f[0],d=f[1],h=function(){var t=ki(_i().mark((function t(){return _i().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return d(!0),t.prev=1,t.next=4,l();case 4:t.next=16;break;case 6:return t.prev=6,t.t0=t.catch(1),t.prev=8,t.next=11,l();case 11:t.next=16;break;case 13:t.prev=13,t.t1=t.catch(8),s(new Pe({level:"error",message:(0,oe.__)("Error while disconnecting","image-optimization"),actions:[{label:(0,oe.__)("Got it","image-optimization"),onClick:function(){}}]}));case 16:d(!1);case 17:case"end":return t.stop()}}),t,null,[[1,6],[8,13]])})));return function(){return t.apply(this,arguments)}}(),m=function(){var t=ki(_i().mark((function t(){return _i().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,ke.deactivate(u);case 3:location.reload(),t.next=9;break;case 6:t.prev=6,t.t0=t.catch(0),s(new Pe({level:"error",message:(0,oe.__)("Error while deactivating","image-optimization"),actions:[{label:(0,oe.__)("Got it","image-optimization"),onClick:function(){}}]}));case 9:case"end":return t.stop()}}),t,null,[[0,6]])})));return function(){return t.apply(this,arguments)}}(),g=function(){var t=ki(_i().mark((function t(){return _i().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,ke.clearSession();case 3:location.reload(),t.next=9;break;case 6:t.prev=6,t.t0=t.catch(0),s(new Pe({level:"error",message:(0,oe.__)("Error while deactivating","image-optimization"),actions:[{label:(0,oe.__)("Got it","image-optimization"),onClick:function(){}}]}));case 9:case"end":return t.stop()}}),t,null,[[0,6]])})));return function(){return t.apply(this,arguments)}}(),v=[{key:"restore_originals",title:(0,oe.__)("Restore original images","image-optimization"),subtitle:"",component:$t(Vo,null),showDivider:!1},{key:"remove_backups",title:(0,oe.__)("Remove backups permanently","image-optimization"),subtitle:"",component:$t(yi,null),showDivider:!1},{key:"subscription_settings",title:(0,oe.__)("Subscription settings","image-optimization"),subtitle:a?(0,oe.sprintf)( // translators: %s: User email (0,oe.__)("You're connected as %s. Want to switch this subscription to a different account?","image-optimization"),a):(0,oe.__)("Want to switch this subscription to a different account?","image-optimization"),component:$t(Dn,{variant:"primary",disabled:!o||p,onClick:h},p&&$t(mn.Spinner,null),(0,oe.__)("Switch account","image-optimization")),showDivider:!1},{key:"deactivate",subtitle:(0,oe.__)("Want to deactivate the subscription for any reason?","image-optimization"),component:$t(Dn,{variant:"secondary",disabled:!o||!i,onClick:m},(0,oe.__)("Deactivate","image-optimization")),showDivider:!1}];return c&&v.push({key:"reset_connection",subtitle:(0,oe.__)("Having issues with connecting the plugin?","image-optimization"),component:$t(Dn,{variant:"secondary",onClick:g},(0,oe.__)("Reset connect","image-optimization")),showDivider:!1}),{fields:v}}(),R=E.fields,z=Object.keys(v).length,C=new Pe({id:"settings_changed",level:"info",message:$t($r,{message:(0,oe.__)("You’ve updated your optimization settings.","image-optimization"),supportiveText:(0,oe.__)("These new settings apply to future uploads, but you can apply them to the existing content in your library.","image-optimization")}),actions:[{label:(0,oe.__)("Apply them now","image-optimization"),onClick:S,variant:"link",noDefaultClasses:!0}]});return(0,r.useEffect)((function(){y()}),[]),(0,r.useEffect)((function(){d&&l(d)}),[d]),(0,r.useEffect)((function(){Object.keys(s).length&&(b(s),!z&&k&&Ti.includes(Object.keys(s)[0])&&_(C))}),[s]),(0,r.useEffect)((function(){if(z){l(d);var t=setTimeout((function(){x()}),2e3);return function(){return clearTimeout(t)}}}),[v]),(0,r.useEffect)((function(){var t=setTimeout((function(){w()}),2e3);return function(){return clearTimeout(t)}}),[g]),!d&&h?$t($i,null):m?$t($i,null,$t(Qi,{onTryAgainClick:y})):$t(r.Suspense,{fallback:$t($i,null)},$t(ro,null,0!==Object.keys(c).length&&$t(React.Fragment,null,$t(Xr,null,O.map((function(t){var e=t.key,n=t.component,r=t.alwaysVisible,o=na(t,Ji);return $t(Zr,ea({key:e,showUpdated:e in g,error:e in v?v[e]:""},o),[qn,Zn,$n].includes(f)&&!r?$t(Qr,null,n):n)}))),$t(Xr,{title:(0,oe.__)("Advanced actions","image-optimization"),initialOpen:!1},R.map((function(t){var e=t.key,n=t.component,r=na(t,ta);return $t(Zr,ea({className:"components-panel__row--advanced-action",key:e},r),n)}))))))},oa=Ht("div",{target:"eoepye53"})("width:100%;height:8px;margin-block-end:10px;background-color:",(function(t){return t.theme.palette.background.grey}),";"),ia=Ht("div",{target:"eoepye52"})("width:",(function(t){return t.percentage}),"%;height:8px;background-color:",(function(t){return t.theme.palette.primary.light}),";"),aa=Ht("div",{target:"eoepye51"})({name:"a7eilb",styles:"width:100%;margin-block-end:12px;display:flex;justify-content:space-between"}),ua=Ht(hn,{target:"eoepye50"})("color:",(function(t){return t.theme.palette.text.dark}),";"),ca=function(t){var e=t.percentage,n=t.min,r=t.max,o=void 0!==n&&void 0!==r;return $t(React.Fragment,null,$t(oa,null,$t(ia,{percentage:e})),o&&$t(aa,null,$t(ua,{variant:"subtitle1"},n),$t(ua,{variant:"h6"},"".concat(e,"%")),$t(ua,{variant:"subtitle1"},r)))};ca.propTypes={percentage:Ut().number.isRequired,min:Ut().string,max:Ut().string};var la=ca,sa=["isNative"];var fa=function(t){var e=t.isNative,n=function(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}(t,sa),r=Ct();return e?$t("span",{className:"spinner is-active",style:{margin:"0 10px 0 0",backgroundColor:r.palette.background.default,borderRadius:"100%"}}):$t(mn.Spinner,n)},pa=function(t){var e=t.disabled,n=t.optimizationStatus,r=t.onCancelOptimization,o=t.onStartOptimization;return[Re.CANCELLED,Re.IN_PROGRESS].includes(n)?$t(React.Fragment,null,$t(Dn,{variant:"secondary",onClick:r,disabled:Re.CANCELLED===n},(0,oe.__)("Cancel","image-optimization")),$t(Dn,{variant:"primary",disabled:!0},$t(fa,{isNative:!0}),(0,oe.__)("In progress…","image-optimization"))):$t(Dn,{variant:"primary",onClick:o,disabled:e},(0,oe.__)("Start","image-optimization"))};pa.propTypes={disabled:Ut().bool.isRequired,optimizationStatus:Ut().oneOf(Object.values(Re)).isRequired,onCancelOptimization:Ut().func.isRequired,onStartOptimization:Ut().func.isRequired};var da=pa,ha=Ht("div",{target:"efssyw54"})("background-color:",(function(t){return t.theme.palette.background.default}),";border:0.5px solid ",(function(t){return t.theme.palette.border.grey}),";margin:16px 0;padding:24px;text-align:center;"),ma=Ht("div",{target:"efssyw53"})({name:"1v91bu0",styles:"display:flex;justify-content:flex-end;align-items:center;position:relative"}),ga=Ht(hn,{target:"efssyw52"})("position:absolute;inset-inline-end:0;inset-inline-start:0;color:",(function(t){return t.theme.palette.error.main}),";font-weight:700;"),va=Ht("div",{target:"efssyw51"})({name:"fq8405",styles:"display:flex;align-items:center;z-index:10;& :not(:last-of-type){margin-inline-end:24px;}"}),ya=Ht(hn,{target:"efssyw50"})("color:",(function(t){return t.theme.palette.text.darkGrey}),";margin:0;&:last-of-type{margin-block-end:31px;}"),ba=function(t){var e=t.error,n=t.optimizationStatus,r=t.totalImages,o=t.progressPercentage,i=t.onCancelOptimization,a=t.onStartOptimization;return o>100&&(o=100),$t(ha,null,$t(ya,{as:"p"},(0,oe.__)("Optimize all the images left in your library in one go.","image-optimization")),$t(la,{percentage:o||0,min:"0%",max:"100%"}),$t(ma,null,e&&$t(ga,null,(0,oe.__)("There was a snag with the bulk optimization.","image-optimization")),$t(va,null,$t(da,{disabled:100===o||!r,onCancelOptimization:i,onStartOptimization:a,optimizationStatus:n}))))};ba.propTypes={error:Ut().string,optimizationStatus:Ut().oneOf(Object.values(Re)).isRequired,totalImages:Ut().number,progressPercentage:Ut().number.isRequired,onCancelOptimization:Ut().func.isRequired,onStartOptimization:Ut().func.isRequired};var wa=ba,xa=n(521),_a=[{Header:"",accessor:"thumbnail"},{Header:(0,oe.__)("File name","image-optimization"),accessor:"fileName"},{Header:(0,oe.__)("Original size","image-optimization"),accessor:"originalSize"},{Header:(0,oe.__)("Current size","image-optimization"),accessor:"currentSize"},{Header:(0,oe.__)("Optimization level","image-optimization"),accessor:"optimizationLevel"},{Header:(0,oe.__)("Status","image-optimization"),accessor:"status"}];function Sa(){return Sa=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Sa.apply(this,arguments)}var ka=Ht("table",{target:"e1g7ufyo2"})("width:100%;background-color:",(function(t){return t.theme.palette.background.default}),";margin:16px 0;padding:24px;border-spacing:0;& img{width:40px;height:40px;}& th{color:",(function(t){return t.theme.palette.text.dark}),";}& td{height:40px;}"),Oa=Ht("thead",{target:"e1g7ufyo1"})({name:"1flj9lk",styles:"text-align:left"}),Ea=Ht("tr",{target:"e1g7ufyo0"})("background-color:",(function(t){var e=t.index,n=t.theme;return e%2==0?n.palette.background.default:n.palette.background.lightGrey}),";"),Ra="optimization-table-bulk",za=function(t){var e=t.images,n=(0,r.useMemo)((function(){return _a}),[]),o=(0,r.useMemo)((function(){return e.map((function(t){var e,n=null==t?void 0:t.current_file_size,r=null!=t&&t.original_file_size?null==t?void 0:t.original_file_size:n,o=Math.max(Math.round(100-n/r*100),0);return{thumbnail:$t("img",{src:t.thumbnail_url,alt:""}),fileName:t.image_name,originalSize:"".concat(Bn(r)),currentSize:"".concat(Bn(n)),optimizationLevel:"".concat(o,"%"),status:null!==(e=ze[t.status])&&void 0!==e?e:ze[Re.NOT_STARTED]}}))}),[e]),i=(0,xa.useTable)({autoResetExpanded:!1,columns:n,data:o}),a=i.getTableProps,u=i.getTableBodyProps,c=i.headerGroups,l=i.rows,s=i.prepareRow;return $t(ka,a(),$t(Oa,null,c.map((function(t,e){return $t("tr",Sa({},t.getHeaderGroupProps(),{key:"".concat(Ra,"-header-group-").concat(e)}),t.headers.map((function(t,e){return $t("th",Sa({},t.getHeaderProps(),{key:"".concat(Ra,"-header-cell-").concat(e)}),$t(hn,{variant:"subtitle1"},t.render("Header")))})))}))),$t("tbody",u(),l.map((function(t,e){return s(t),$t(Ea,Sa({index:parseInt(t.id)},t.getRowProps(),{key:"".concat(Ra,"-row-").concat(e)}),t.cells.map((function(t,e){return $t("td",Sa({},t.getCellProps(),{key:"".concat(Ra,"-cell-").concat(e)}),t.render("Cell"))})))}))))};za.propTypes={images:Ut().array.isRequired};var Ca=za,ja=function(){var t=Xe(),e=t.stats,n=t.bulkOptimizationStatus,r=t.bulkOptimizationImages,o=on(),i=o.isConnected,a=o.isActivated,u=o.imagesLeft,c=rn(),l=c.error,s=c.cancelOptimization,f=c.runOptimization,p=0===e.total_image_count?0:Math.round(e.optimized_image_count/e.total_image_count*100);return $t(Qr,{isDisabled:!i||!a||0===u},$t(wa,{error:l,optimizationStatus:n,totalImages:e.total_image_count,progressPercentage:p,onCancelOptimization:s,onStartOptimization:f}),$t(Ca,{images:r}))},La=function(t){var e=t.page;return e===an.SETTINGS?$t(Ar,null,$t(ra,null)):e===an.BULK_OPTIMIZATION?$t(ja,null):null};La.propTypes={page:Ut().string};var Pa=La,Ia=function(t){var e=t.size,n=t.props;return $t(mn.Icon,{icon:$t("svg",n,$t("path",{d:"M8 .333A6.67 6.67 0 0 0 1.333 7 6.669 6.669 0 0 0 8 13.666 6.669 6.669 0 0 0 14.667 7 6.669 6.669 0 0 0 8 .333Zm.667 10H7.334V9h1.333v1.333Zm0-2.667H7.334v-4h1.333v4Z"})),size:e})},Ta=function(t){var e=t.size,n=t.props;return $t(mn.Icon,{icon:$t("svg",n,$t("path",{d:"M8 1.333A6.67 6.67 0 0 0 1.333 8 6.669 6.669 0 0 0 8 14.666 6.669 6.669 0 0 0 14.667 8 6.669 6.669 0 0 0 8 1.333Zm-1.333 10L3.334 8l.94-.94 2.393 2.386 5.06-5.06.94.947-6 6Z"})),size:e})},Aa=function(t){var e=t.level,n=Ct();return"error"===e?$t(Ia,{size:16,props:{fill:n.palette.error.main}}):$t(Ta,{size:16,props:{fill:n.palette.success.main}})};Aa.propTypes={level:Ut().string.isRequired};var Na=Aa,Ga=Ht(mn.SnackbarList,{target:"e1div4p60"})("width:98%;position:fixed;inset-inline-end:20px;inset-block-end:15px;& .components-snackbar{border-radius:3px;color:",(function(t){return t.theme.palette.text.toast}),";background-color:",(function(t){return t.theme.palette.background.toast}),";font-family:",(function(t){return t.theme.fonts.default}),';font-weight:500;padding:20px 6px;}& .components-snackbar-list__notice-container{display:flex;justify-content:flex-end;}& .components-snackbar__content{display:flex;flex-direction:column;justify-content:center;align-items:flex-end;}& .components-snackbar__content .components-snackbar__custom-message{display:flex;align-items:flex-start;max-width:280px;margin-block-start:0;margin-block-end:17px;}& .components-snackbar__content .components-snackbar__custom-message span{max-width:260px;}& .components-snackbar__content .components-snackbar__custom-message svg{margin-inline-end:4px;position:relative;inset-block-start:2px;}& .components-snackbar__content .components-snackbar__action:not(:disabled):not([aria-disabled="true"]):not(.is-secondary){font-weight:500;text-decoration:none;text-transform:uppercase;}& .components-snackbar__content .components-snackbar__action svg{margin-inline-end:4px;position:relative;inset-block-start:-1px;}'),Ma=function(){var t=Fe(),e=t.toastNotifications,n=t.hideToastNotification,r=e.map((function(t){return{actions:t.actions,id:t.id,content:$t("p",{className:"components-snackbar__custom-message"},$t(Na,{level:t.level}),$t("span",null,t.message)),spokenMessage:t.message,status:t.level,politeness:"assertive"}}));return $t(Ga,{notices:r,onRemove:function(t){return n(t)}})},Fa=Ht(mn.NoticeList,{target:"ez8pnkz0"})("margin:16px 0;& .components-notice{margin:0;}& .components-notice:not(:last-of-type){margin-block-end:16px;}& .components-notice.is-info{background-color:",(function(t){return t.theme.palette.background.noticeInfo}),";color:",(function(t){return t.theme.palette.text.noticeInfo}),";border-inline-start:4px solid ",(function(t){return t.theme.palette.info.notice}),";}& .components-notice__content,& .components-notice__content p{margin:0 15px 0 0;}& .components-notice__content p,& .components-notice__content .components-notice__actions{display:inline-block;}& .components-notice__dismiss svg{color:",(function(t){return t.theme.palette.text.noticeInfo}),";}"),Da=function(){var t=De(),e=t.generalNotifications,n=t.hideGeneralNotification,r=e.map((function(t){return{actions:t.actions.map((function(e){if("onClick"in e){var r=e.onClick;e.onClick=function(){n(t.id),r()}}return e})),id:t.id,content:t.message,spokenMessage:t.message,status:t.level,politeness:"assertive"}}));return $t("div",{className:"wrap"},$t(Fa,{notices:r,onRemove:function(t){return n(t)}}))},Ba=window.wp.date,Ha=["options"];function Wa(){return Wa=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Wa.apply(this,arguments)}var Ua=function(t){var e=t.options,n=function(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}(t,Ha);return $t(mn.CustomSelectControl,Wa({options:e,label:"",size:"__unstable-large"},n))};Ua.propTypes={options:Ut().array.isRequired};var qa=Ua,Za=Ht("div",{target:"e16a6jh43"})({name:"1azakc",styles:"text-align:center"}),$a=Ht("hr",{target:"e16a6jh42"})({name:"19miswd",styles:"max-width:560px;margin:12px auto"}),Va=Ht(hn,{target:"e16a6jh41"})("color:",(function(t){return t.theme.palette.text.primary}),";font-size:16px;"),Ya=Ht(qa,{target:"e16a6jh40"})({name:"f8a4yy",styles:"max-width:560px;margin:0 auto"}),Xa=function(t){var e=t.subscriptions,n=t.onLicenseSelect;if(!e.length)return $t(Za,null,$t(Va,{as:"p",style:{marginBlockEnd:"12px"}},(0,oe.__)("No available license","image-optimization")),$t($a,null));if(1===e.length){var r=e[0];return $t(Za,null,$t(Va,{as:"p",style:{marginBlockEnd:"45px"}},(0,oe.sprintf)( // translators: %s: Subscription plan name, %s: expiration date (0,oe.__)("Image Optimizer - %1$s license, Expiration Date: %2$s","image-optimization"),r.plan.title,(0,Ba.dateI18n)("M Y",r.date_next_payment,void 0))))}var o=null==e?void 0:e.map((function(t){return{name:(0,oe.sprintf)( // translators: %s: Subscription plan name, %s: expiration date (0,oe.__)("Image Optimizer - %1$s license, Expiration Date: %2$s","image-optimization"),t.plan.title,(0,Ba.dateI18n)("M Y",t.date_next_payment,void 0)),key:t.license_key,style:{fontSize:"100%"}}}));return o.unshift({name:(0,oe.__)("Select","image-optimization"),key:"",style:{fontSize:"100%"}}),$t(React.Fragment,null,$t(Ya,{id:"subscription_list",options:o,onChange:function(t){return n(t)}}),$t($a,null))};Xa.propTypes={subscriptions:Ut().array.isRequired};var Ka=Xa,Qa=Ht("div",{target:"ecxzfwj2"})({name:"1azakc",styles:"text-align:center"}),Ja=Ht(hn,{target:"ecxzfwj1"})("margin:0 0 20px 0;font-size:36px;font-style:normal;font-weight:700;line-height:normal;letter-spacing:-0.72px;color:",(function(t){return t.theme.palette.text.primary}),";"),tu=Ht(hn,{target:"ecxzfwj0"})("font-size:16px;font-weight:400;line-height:150%;max-width:386px;margin:0 auto 45px;color:",(function(t){return t.theme.palette.text.tertiary}),";"),eu=function(){return $t(Qa,null,$t(Ja,{as:"h1",variant:"h4"},(0,oe.__)("Ready to use Image Optimizer?","image-optimization")),$t(tu,{as:"p",variant:"subtitle1"},(0,oe.__)("Connect your WordPress site and activate your license to use all of of the features in Image Optimizer.","image-optimization")))},nu=function(t){var e=t.size,n=void 0===e?60:e,r=t.props;return $t(mn.Icon,{icon:$t("svg",r,$t("rect",{width:"60",height:"60",fill:"#FF7BE5",rx:"30"}),$t("path",{fill:"#fff",d:"M19.702 7.754a.234.234 0 0 0-.443 0l-2.217 6.413a.234.234 0 0 1-.146.146L10.412 16.5a.234.234 0 0 0 0 .444l6.484 2.187a.234.234 0 0 1 .146.146l2.217 6.413c.073.21.37.21.443 0l2.217-6.413a.234.234 0 0 1 .147-.146l6.483-2.187a.234.234 0 0 0 0-.444l-6.483-2.187a.234.234 0 0 1-.147-.146l-2.217-6.413ZM32.672 23.884v6.907l-7.638 8.59L49.68 17.996a.234.234 0 0 1 .388.177V46.02c0 .13-.105.234-.235.234H11.014a.234.234 0 0 1-.168-.397L32.27 23.72a.234.234 0 0 1 .402.163Z"})),size:n})},ru=function(t){var e=t.size,n=void 0===e?60:e,r=t.props;return $t(mn.Icon,{icon:$t("svg",r,$t("circle",{cx:"30",cy:"30",r:"30",fill:"#F1F2F3"}),$t("path",{fill:"#69727D",fillRule:"evenodd",d:"M34.2 31.5c-1.345 0-1.992.75-4.2.75s-2.85-.75-4.2-.75a6.302 6.302 0 0 0-6.3 6.3v1.95A2.25 2.25 0 0 0 21.75 42h16.5a2.25 2.25 0 0 0 2.25-2.25V37.8c0-3.478-2.822-6.3-6.3-6.3Zm4.8 8.25c0 .413-.337.75-.75.75h-16.5a.752.752 0 0 1-.75-.75V37.8c0-2.648 2.152-4.8 4.8-4.8.919 0 1.833.75 4.2.75 2.362 0 3.281-.75 4.2-.75 2.648 0 4.8 2.152 4.8 4.8v1.95ZM30 30a6 6 0 1 0 0-12 6 6 0 1 0 0 12Zm0-10.5c2.48 0 4.5 2.02 4.5 4.5s-2.02 4.5-4.5 4.5-4.5-2.02-4.5-4.5 2.02-4.5 4.5-4.5Z",clipRule:"evenodd"}),$t("path",{fill:"#69727D",d:"M34.2 31.4c-.691 0-1.206.194-1.806.38-.6.185-1.303.37-2.394.37v.2c1.117 0 1.841-.19 2.453-.38.612-.189 1.093-.37 1.747-.37v-.2Zm-4.2.75a7.45 7.45 0 0 1-2.392-.37c-.6-.186-1.114-.38-1.808-.38v.2c.656 0 1.138.181 1.749.37.61.19 1.334.38 2.451.38v-.2Zm-4.2-.75a6.402 6.402 0 0 0-6.4 6.4h.2c0-3.423 2.777-6.2 6.2-6.2v-.2Zm-6.4 6.4v1.95h.2V37.8h-.2Zm0 1.95a2.35 2.35 0 0 0 2.35 2.35v-.2a2.15 2.15 0 0 1-2.15-2.15h-.2Zm2.35 2.35h16.5v-.2h-16.5v.2Zm16.5 0a2.35 2.35 0 0 0 2.35-2.35h-.2a2.15 2.15 0 0 1-2.15 2.15v.2Zm2.35-2.35V37.8h-.2v1.95h.2Zm0-1.95c0-3.533-2.867-6.4-6.4-6.4v.2c3.423 0 6.2 2.777 6.2 6.2h.2Zm-1.7 1.95c0 .357-.293.65-.65.65v.2c.468 0 .85-.382.85-.85h-.2Zm-.65.65h-16.5v.2h16.5v-.2Zm-16.5 0a.652.652 0 0 1-.65-.65h-.2c0 .468.382.85.85.85v-.2Zm-.65-.65V37.8h-.2v1.95h.2Zm0-1.95c0-2.593 2.107-4.7 4.7-4.7v-.2a4.903 4.903 0 0 0-4.9 4.9h.2Zm4.7-4.7c.216 0 .436.044.684.114.255.07.516.16.845.257.646.19 1.476.379 2.671.379v-.2a8.825 8.825 0 0 1-2.615-.371c-.31-.091-.598-.189-.847-.258a2.736 2.736 0 0 0-.738-.121v.2Zm4.2.75a9.03 9.03 0 0 0 2.67-.379c.328-.096.59-.186.845-.257a2.55 2.55 0 0 1 .685-.114v-.2c-.243 0-.483.05-.739.12-.25.07-.537.168-.848.259A8.829 8.829 0 0 1 30 33.65v.2Zm4.2-.75c2.593 0 4.7 2.107 4.7 4.7h.2c0-2.704-2.196-4.9-4.9-4.9v.2Zm4.7 4.7v1.95h.2V37.8h-.2ZM30 30.1a6.1 6.1 0 0 0 6.1-6.1h-.2a5.9 5.9 0 0 1-5.9 5.9v.2Zm6.1-6.1a6.1 6.1 0 0 0-6.1-6.1v.2a5.9 5.9 0 0 1 5.9 5.9h.2ZM30 17.9a6.1 6.1 0 0 0-6.1 6.1h.2a5.9 5.9 0 0 1 5.9-5.9v-.2ZM23.9 24a6.1 6.1 0 0 0 6.1 6.1v-.2a5.9 5.9 0 0 1-5.9-5.9h-.2Zm6.1-4.4c2.425 0 4.4 1.976 4.4 4.4h.2c0-2.535-2.065-4.6-4.6-4.6v.2Zm4.4 4.4c0 2.424-1.975 4.4-4.4 4.4v.2c2.535 0 4.6-2.065 4.6-4.6h-.2ZM30 28.4a4.407 4.407 0 0 1-4.4-4.4h-.2c0 2.535 2.065 4.6 4.6 4.6v-.2ZM25.6 24c0-2.424 1.976-4.4 4.4-4.4v-.2a4.607 4.607 0 0 0-4.6 4.6h.2Z"})),size:n})};function ou(t){return ou="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ou(t)}function iu(){iu=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==ou(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(ou(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function au(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}var uu=Ht("div",{target:"e1j22c7t3"})("display:flex;justify-content:space-between;align-items:baseline;max-width:420px;margin:0 auto 40px;position:relative;& svg{margin-block-end:14px;}&::before{content:'';position:absolute;inset-block-start:22px;inset-inline-end:20px;inset-inline-start:0;margin:auto;border:2px dashed ",(function(t){return t.theme.palette.background.grey}),";width:48%;}&::after{content:url(",n(998).Z,");display:flex;justify-content:center;align-items:center;position:absolute;inset-block-start:7px;inset-inline-start:0;inset-inline-end:20px;width:32px;height:32px;margin:auto;border:1px solid ",(function(t){return t.theme.palette.background.grey}),";border-radius:100%;background-color:",(function(t){return t.theme.palette.background.default}),";}"),cu=Ht("div",{target:"e1j22c7t2"})({name:"zigog8",styles:"display:flex;flex-direction:column;align-items:center"}),lu=Ht(hn,{target:"e1j22c7t1"})("color:",(function(t){return t.theme.palette.text.tertiary}),";margin-block-end:8px;"),su=Ht(Dn,{target:"e1j22c7t0"})("&.is-link{color:",(function(t){return t.theme.palette.text.tertiary}),";font-size:14px;font-style:normal;font-weight:500;line-height:100%;text-decoration:none;}"),fu=function(){var t=Yo().siteUrl,e=on().subscriptionEmail,n=ar().switchUser,r=Fe().showToastNotification,o=function(){var t,e=(t=iu().mark((function t(){return iu().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,n();case 3:close(),t.next=9;break;case 6:t.prev=6,t.t0=t.catch(0),r(new Pe({level:"error",message:(0,oe.__)("Error while disconnecting","image-optimization"),actions:[{label:(0,oe.__)("Got it","image-optimization"),onClick:function(){}}]}));case 9:case"end":return t.stop()}}),t,null,[[0,6]])})),function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){au(i,r,o,a,u,"next",t)}function u(t){au(i,r,o,a,u,"throw",t)}a(void 0)}))});return function(){return e.apply(this,arguments)}}();return $t(uu,null,$t(cu,null,$t(nu,null),$t(lu,null,t)),$t(cu,null,$t(ru,null),$t(lu,null,e),$t(su,{variant:"link",onClick:o},(0,oe.__)("Switch User","image-optimization"))))},pu=Ht("div",{target:"emrn7r52"})({name:"1yldona",styles:"display:flex;flex-direction:column;justify-content:center;align-items:center;margin-block-end:35px;& p{margin:0;}"}),du=Ht(hn,{target:"emrn7r51"})("color:",(function(t){return t.theme.palette.text.tertiary}),";"),hu=Ht(Dn,{target:"emrn7r50"})("&.is-link{color:",(function(t){return t.theme.palette.text.link}),";font-size:14px;line-height:normal;}"),mu=function(){return $t(pu,null,$t(du,{as:"p"},(0,oe.sprintf)( // translators: %s: Full year (0,oe.__)("© %s All Rights Reserved.","image-optimization"),(0,Ba.dateI18n)("Y",new Date,void 0))),$t("p",null,$t(hu,{variant:"link",href:"https://elementor.com/terms/",target:"_blank",rel:"noopener noreferrer"},(0,oe.__)("Terms of Service","image-optimization")),$t("span",null,", "),$t(hu,{variant:"link",href:"https://elementor.com/about/privacy/",target:"_blank",rel:"noopener noreferrer"},(0,oe.__)("Privacy Policy","image-optimization"))))};function gu(t){return gu="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},gu(t)}function vu(){vu=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==gu(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(gu(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function yu(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}function bu(t){return function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){yu(i,r,o,a,u,"next",t)}function u(t){yu(i,r,o,a,u,"throw",t)}a(void 0)}))}}function wu(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,u=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(u.push(r.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||function(t,e){if(t){if("string"==typeof t)return xu(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?xu(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function xu(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var _u=Ht(mn.Modal,{target:"e1c223pl2"})("font-family:",(function(t){return t.theme.fonts.default}),";width:900px;max-height:80%;border-radius:0;.components-modal__header{padding:0 23px 8px;}.components-modal__content{padding:0;margin-block-start:55px;}"),Su=Ht("div",{target:"e1c223pl1"})({name:"lhj7k3",styles:"display:flex;flex-direction:column;justify-content:center;align-items:center;max-width:560px;margin:0 auto 56px"}),ku=Ht(Dn,{target:"e1c223pl0"})("display:flex;justify-content:center;align-items:center;background-color:",(function(t){return t.theme.palette.background.brand}),"!important;width:100%;letter-spacing:-.02em;color:",(function(t){return t.theme.palette.text.brand}),"!important;font-size:15px;font-weight:500;user-select:none;max-width:560px;border-radius:0;height:48px;&:not(:last-of-type){margin-block-end:20px;}&:disabled{color:#9DA5AE!important;background:",(function(t){return t.theme.palette.background.disabled}),"!important;}"),Ou=function(t){var e=t.page,n=on(),o=n.isConnected,i=n.isActivated,a=Mo(),u=a.isOpen,c=a.close,l=a.open,s=Fe().showToastNotification,f=wu((0,r.useState)([]),2),p=f[0],d=f[1],h=wu((0,r.useState)(null),2),m=h[0],g=h[1],v=function(){var t=bu(vu().mark((function t(){var e;return vu().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,ke.fetchSubscriptions();case 2:1===(e=t.sent).length&&g(e[0].license_key),d(e),l();case 6:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}();return(0,r.useEffect)((function(){e===an.SETTINGS&&o&&!i&&v(),er.listen(Qn,v)}),[]),u?$t(_u,{onRequestClose:c,value:m,title:""},$t(eu,null),$t(fu,null),$t(Ka,{subscriptions:p,onLicenseSelect:function(t){g(t.selectedItem.key)}}),$t(Su,null,null!=p&&p.length?$t(ku,{variant:"primary",disabled:!m,onClick:function(){var t=function(){var t=bu(vu().mark((function t(){return vu().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,ke.activateSubscription(m);case 3:location.reload(),t.next=9;break;case 6:t.prev=6,t.t0=t.catch(0),s(new Pe({level:"error",message:(0,oe.__)("Activation error","image-optimization"),actions:[{label:(0,oe.__)("Got it","image-optimization"),onClick:function(){}}]}));case 9:c();case 10:case"end":return t.stop()}}),t,null,[[0,6]])})));return function(){return t.apply(this,arguments)}}();t()}},(0,oe.__)("Activate my license","image-optimization")):$t(ku,{variant:"primary",href:"https://go.elementor.com/io-panel-get-free/",target:"_blank",rel:"noopener noreferrer",onClick:c},(0,oe.__)("Get a new subscription","image-optimization"))),$t(mu,null)):""};Ou.propTypes={page:Ut().string};var Eu=Ou;function Ru(t){return Ru="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ru(t)}function zu(){zu=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==Ru(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(Ru(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function Cu(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}var ju=["size"];function Lu(){return Lu=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Lu.apply(this,arguments)}var Pu=function(t){var e=t.size,n=function(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}(t,ju);return $t(mn.Icon,{icon:$t("svg",Lu({width:"32",height:"32",fill:"none"},n),$t("path",{fill:"#000",fillRule:"evenodd",d:"M2.696 24.89A16 16 0 1 1 29.304 7.11 16 16 0 0 1 2.696 24.89Zm9.305-15.557H9.334v13.333h2.667V9.333Zm10.665 0h-8v2.666h8V9.333Zm0 5.332h-8v2.667h8v-2.667Zm0 5.335h-8v2.666h8V20Z",clipRule:"evenodd"})),size:e})};function Iu(t){return Iu="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Iu(t)}function Tu(){Tu=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),u=new j(r||[]);return o(a,"_invoke",{value:E(t,n,u)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",g={};function v(){}function y(){}function b(){}var w={};l(w,a,(function(){return this}));var x=Object.getPrototypeOf,_=x&&x(x(L([])));_&&_!==n&&r.call(_,a)&&(w=_);var S=b.prototype=v.prototype=Object.create(w);function k(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function n(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var l=c.arg,s=l.value;return s&&"object"==Iu(s)&&r.call(s,"__await")?e.resolve(s.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,o){n(t,r,e,o)}))}return i=i?i.then(o,o):o()}})}function E(e,n,r){var o=p;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var u=r.delegate;if(u){var c=R(u,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=h;var l=f(e,n,r);if("normal"===l.type){if(o=r.done?m:d,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=m,r.method="throw",r.arg=l.arg)}}}function R(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,R(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=f(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function z(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(z,this),this.reset(!0)}function L(e){if(e||""===e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function n(){for(;++o<e.length;)if(r.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}throw new TypeError(Iu(e)+" is not iterable")}return y.prototype=b,o(S,"constructor",{value:b,configurable:!0}),o(b,"constructor",{value:y,configurable:!0}),y.displayName=l(b,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,c,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},k(O.prototype),l(O.prototype,u,(function(){return this})),e.AsyncIterator=O,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new O(s(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(S),l(S,c,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=L,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(C),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function o(r,o){return u.type="throw",u.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:L(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),g}},e}function Au(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}function Nu(t){return function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){Au(i,r,o,a,u,"next",t)}function u(t){Au(i,r,o,a,u,"throw",t)}a(void 0)}))}}var Gu=Ht("span",{target:"e18vfjh05"})({name:"13zqvnj",styles:"display:flex;justify-content:center;align-items:center;& svg{margin-inline-end:8px;}& span{font-size:16px;font-style:normal;font-weight:500;line-height:130%;letter-spacing:0.15px;}"}),Mu=Ht(mn.Modal,{target:"e18vfjh04"})("font-family:",(function(t){return t.theme.fonts.default}),";width:900px;max-height:80%;.components-modal__header{padding:0 24px 0;height:48px;border-block-end:1px solid #0000001F;}.components-modal__content{padding:0;margin-block-start:55px;}"),Fu=Ht("div",{target:"e18vfjh03"})({name:"149rfrl",styles:"text-align:center;h2{font-size:32px;font-style:normal;font-weight:700;line-height:123.5%;letter-spacing:0.25px;}"}),Du=Ht("div",{target:"e18vfjh02"})({name:"15vee90",styles:"display:flex;justify-content:center;padding:40px 24px;column-gap:51px;@media screen and (max-width: 768px){flex-wrap:wrap;row-gap:50px;padding:20px 24px;}& h3{margin-block-end:24px;font-size:16px;font-style:normal;font-weight:500;line-height:130%;letter-spacing:0.15px;}"}),Bu=Ht("div",{target:"e18vfjh01"})({name:"1kexohv",styles:"display:flex;flex-direction:column;width:50%;padding:40px;border:1px solid rgba(0, 0, 0, 0.12);border-radius:4px;@media screen and (max-width: 768px){width:100%;}& span{margin-block-end:24px;}"}),Hu=Ht(Dn,{target:"e18vfjh00"})({name:"4wjgsd",styles:"&.components-button{margin:0 auto;font-size:16px;font-style:normal;font-weight:500;line-height:26px;color:#C00BB9;text-decoration:none;}"}),Wu=function(){var t=Mo(),e=t.isOpen,n=t.close,o=t.open,i=Fe().showToastNotification;(0,r.useEffect)((function(){er.listen(Jn,o)}),[]);var a=function(){var t=Nu(Tu().mark((function t(){var e;return Tu().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,ke.initConnect("update");case 3:e=t.sent,window.open(e,"_self").focus(),t.next=10;break;case 7:t.prev=7,t.t0=t.catch(0),i(new Pe({level:"error",message:(0,oe.__)("An error occurred","image-optimization"),actions:[]}));case 10:n();case 11:case"end":return t.stop()}}),t,null,[[0,7]])})));return function(){return t.apply(this,arguments)}}(),u=function(){var t=Nu(Tu().mark((function t(){return Tu().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,ke.clearSession();case 3:window.location.href=(0,ue.addQueryArgs)(window.location.href,{action:"connect"}),t.next=9;break;case 6:t.prev=6,t.t0=t.catch(0),i(new Pe({level:"error",message:(0,oe.__)("An error occurred","image-optimization"),actions:[]}));case 9:n();case 10:case"end":return t.stop()}}),t,null,[[0,6]])})));return function(){return t.apply(this,arguments)}}();return e?$t(Mu,{onRequestClose:n,title:$t(Gu,null,$t(Pu,{size:24,viewBox:"0 0 32 32"}),$t(hn,null,(0,oe.__)("Fix mismatched URL","image-optimization")))},$t(Fu,null,$t(hn,{as:"h2"},(0,oe.__)("Select the case that applies to you","image-optimization")),$t(Du,null,$t(Bu,null,$t(hn,{as:"h3"},(0,oe.__)("Are you updating the URL?","image-optimization")),$t(hn,null,(0,oe.__)("Choose this option if you want to just switch to the new URL for the same site","image-optimization")),$t(Hu,{variant:"link",onClick:a},(0,oe.__)("Update connected URL","image-optimization"))),$t(Bu,null,$t(hn,{as:"h3"},(0,oe.__)("Are you creating a new site?","image-optimization")),$t(hn,null,(0,oe.__)("Choose this if you are connecting the plugin to a new site","image-optimization")),$t(Hu,{variant:"link",onClick:u},(0,oe.__)("Connect as a new site","image-optimization")))))):""},Uu=["isShown"];var qu=Ht("div",{target:"e1r0tp9s0"})("position:fixed;display:flex;justify-content:center;align-items:center;top:0;left:0;right:0;bottom:0;z-index:9999;background:",(function(t){return t.theme.palette.background.toast}),";opacity:.7;& svg{width:48px;height:48px;}"),Zu=function(t){var e=t.isShown,n=void 0!==e&&e,r=function(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}(t,Uu);return!!n&&$t(qu,null,$t(mn.Spinner,r))};Zu.propTypes={isShown:Ut().bool};var $u=Zu,Vu=function(){var t=function(){var t=window.location;return new URLSearchParams(t.search).get("page")||null}();!function(){var t=Xe(),e=t.fetchStats,n=t.bulkRestoringStatus,o=t.bulkBackupRemovingStatus,i=t.bulkOptimizationOperationId,a=t.bulkOptimizationStatus,u=t.setBulkOptimizationImages,c=t.fetchBulkOptimizationImages,l=Fe().showToastNotification,s=rn().hideBulkWPNotice,f=(0,r.useRef)(n),p=(0,r.useRef)(o),d=(0,r.useRef)(a),h=(0,r.useRef)(!1),m=(0,r.useRef)(!1),g=function(){var t=Ue(He().mark((function t(){return He().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!h.current){t.next=2;break}return t.abrupt("return");case 2:return h.current=!0,t.next=5,e();case 5:h.current=!1;case 6:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}(),v=function(){var t=Ue(He().mark((function t(e){return He().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!m.current){t.next=2;break}return t.abrupt("return");case 2:return m.current=!0,t.next=5,c(e);case 5:m.current=!1;case 6:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}();(0,r.useEffect)((function(){g();var t=setInterval(g,5e3);return function(){return clearInterval(t)}}),[]),(0,r.useEffect)((function(){Re.NOT_STARTED===n&&Re.IN_PROGRESS===f.current&&l(new Pe({level:"success",message:(0,oe.__)("Restoring your original images was completed successfully.","image-optimization"),actions:[{label:(0,oe.__)("Got it","image-optimization"),onClick:function(){}}]})),f.current=n}),[n]),(0,r.useEffect)((function(){Re.NOT_STARTED===o&&Re.IN_PROGRESS===p.current&&l(new Pe({level:"success",message:(0,oe.__)("Deleting your backups was completed successfully.","image-optimization"),actions:[{label:(0,oe.__)("Got it","image-optimization"),onClick:function(){}}]})),p.current=o}),[o]),(0,r.useEffect)((function(){Re.NOT_STARTED===a&&Re.IN_PROGRESS===d.current&&(l(new Pe({level:"success",message:(0,oe.__)("Bulk optimization is completed.","image-optimization"),actions:[{label:(0,oe.__)("Got it","image-optimization"),onClick:function(){}}]})),s()),d.current=a}),[a]);var y=(0,r.useRef)(null),b=(0,r.useRef)(null);(0,r.useEffect)((function(){return a===Re.NOT_STARTED&&y.current&&(clearInterval(y.current),y.current=null,b.current=null,v(i)),a===Re.IN_PROGRESS&&!y.current&&i?(v(i),y.current=setInterval((function(){return v(i)}),5e3),b.current=i,function(){return clearInterval(y.current)}):a===Re.IN_PROGRESS&&y.current&&b!==i?(clearInterval(y.current),u([]),y.current=setInterval((function(){return v(i)}),5e3),b.current=i,function(){return clearInterval(y.current)}):void 0}),[a,i])}(),function(t){var e=ar().redirectToConnect,n=Fe().showToastNotification,o=function(){var t,r=(t=zu().mark((function t(){return zu().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e();case 3:t.next=8;break;case 5:t.prev=5,t.t0=t.catch(0),n(new Pe({level:"error",message:(0,oe.__)("Error while connecting","image-optimization"),actions:[{label:(0,oe.__)("Got it","image-optimization"),onClick:function(){}}]}));case 8:case"end":return t.stop()}}),t,null,[[0,5]])})),function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){Cu(i,r,o,a,u,"next",t)}function u(t){Cu(i,r,o,a,u,"throw",t)}a(void 0)}))});return function(){return r.apply(this,arguments)}}();(0,r.useEffect)((function(){t===an.SETTINGS&&"connect"===new URLSearchParams(location.search).get("action")&&o()}),[])}(t);var e=!1;return t===an.SETTINGS&&"connect"===new URLSearchParams(location.search).get("action")&&(e=!0),$t(re,null,$t(re.Header,null,$t(Da,null)),$t(re.Content,{fullWidth:!0},$t(Eu,{page:t}),$t(Wu,null),$t($u,{isShown:e}),$t(jr,{page:t}),$t(Pa,{page:t}),$t(Ma,null)))},Yu=Ht("div",{target:"ehbyabb1"})({name:"s5xdrg",styles:"display:flex;align-items:center"}),Xu=Ht("span",{target:"ehbyabb0"})("margin-inline-start:8px;color:",(function(t){return t.theme.palette.text.lightGrey}),";font-feature-settings:'clig' off,'liga' off;font-family:",(function(t){return t.theme.fonts.default}),";font-size:15px;font-style:normal;font-weight:700;line-height:130%;user-select:none;"),Ku=function(){return $t(Yu,null,$t(Pu,{size:32}),$t(Xu,null,function(){var t=window.location;return t.href.endsWith("/upload.php")&&!t.search}()?(0,oe.__)("Media Library","image-optimization"):(0,oe.__)("Image Optimizer","image-optimization")))},Qu=function(t){var e=t.size,n=t.props;return $t(mn.Icon,{icon:$t("svg",n,$t("path",{fillRule:"evenodd",d:"M8 2.5a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11ZM1.5 8a6.5 6.5 0 1 1 13 0 6.5 6.5 0 0 1-13 0Zm6.123-3.793a1.984 1.984 0 0 1 1.316.186h.002c.404.214.724.558.91.976.188.418.232.886.126 1.332a2.061 2.061 0 0 1-.71 1.13c-.225.181-.482.31-.756.382v.454a.5.5 0 0 1-1 0v-.89a.5.5 0 0 1 .498-.5c.227 0 .45-.078.63-.224.18-.146.31-.35.365-.583a1.086 1.086 0 0 0-.065-.693 1.045 1.045 0 0 0-.464-.498.984.984 0 0 0-.652-.093 1.005 1.005 0 0 0-.572.345.5.5 0 0 1-.769-.639 2.004 2.004 0 0 1 1.141-.685ZM8 10.167a.5.5 0 0 1 .5.5v.026a.5.5 0 1 1-1 0v-.026a.5.5 0 0 1 .5-.5Z",clipRule:"evenodd"})),size:e})},Ju=Ht(mn.Button,{target:"e19jt8ef0"})("border-radius:4px;&.is-primary,&.is-primary:hover:not(:disabled){background-color:",(function(t){return t.theme.palette.primary.main}),";color:",(function(t){return t.theme.palette.text.primary}),";font-weight:500;}&.is-secondary{box-shadow:inset 0 0 0 1px ",(function(t){return t.theme.palette.primary.main}),";color:",(function(t){return t.theme.palette.text.primary}),";font-weight:500;}"),tc=function(){var t=ar(),e=t.redirectToConnect,n=t.sendActivationEvent,r=t.sendUrlMismatchEvent,o=Yn();return $n===o?$t(Ju,{variant:"secondary",onClick:r},(0,oe.__)("Fix mismatched URL","image-optimization")):qn===o?$t(Ju,{variant:"secondary",onClick:e},(0,oe.__)("Connect to start","image-optimization")):Zn===o?$t(Ju,{variant:"secondary",onClick:n},(0,oe.__)("Activate to start","image-optimization")):Wn===o?$t(Ju,{variant:"primary",href:cn,target:"_blank",rel:"noopener noreferrer"},(0,oe.__)("Renew Plan","image-optimization")):Vn!==o&&$t(Ju,{variant:"primary",href:cn,target:"_blank",rel:"noopener noreferrer"},(0,oe.__)("Upgrade Plan","image-optimization"))},ec=Ht("ul",{target:"e190q66r2"})({name:"1ktpmw2",styles:"display:flex;align-items:center;margin:0;@media screen and (max-width: 782px){flex-wrap:wrap;}"}),nc=Ht("li",{target:"e190q66r1"})({name:"10dw8fv",styles:"margin:0;&:not(:last-child){margin-inline-end:40px;@media screen and (max-width: 960px){margin-inline-end:10px;}}"}),rc=Ht(Dn,{target:"e190q66r0"})("&.is-link{color:",(function(t){return t.theme.palette.text.lightGrey}),";text-decoration:none;font-family:",(function(t){return t.theme.fonts.default}),";font-weight:500;line-height:150%;&>svg{margin-inline-end:6px;}}"),oc=function(){return $t("nav",null,$t(ec,null,$t(nc,{role:"menuitem"},$t(rc,{href:"https://go.elementor.com/io-panel-learn-more/",variant:"link",target:"_blank",rel:"noopener noreferrer"},$t(Qu,{size:16}),(0,oe.__)("Help","image-optimization"))),$t(nc,null,$t(tc,null))))},ic=Ht("div",{target:"e1dnt4qf0"})("padding:10px 20px;position:relative;inset-inline-start:-20px;width:calc(100vw - 160px - 40px);box-shadow:0 3px 16px 0 rgba(35, 38, 42, 0.20);background-color:",(function(t){return t.theme.palette.background.default}),";display:flex;justify-content:space-between;align-items:center;@media screen and (max-width: 960px){width:calc(100vw - 36px - 32px);}@media screen and (max-width: 782px){inset-inline-start:-10px;width:calc(100vw - 32px);}"),ac=function(){return $t(ic,{role:"navigation"},$t(Ku,null),$t(oc,null))},uc=(0,r.createContext)({}),cc=function(t){var e=t.children,n=Mo();return $t(uc.Provider,{value:{activationModalState:n}},e)};cc.propTypes={children:Ut().node};var lc,sc=document.getElementById("image-optimization-top-bar"),fc=document.getElementById("image-optimization-app"),pc=(null===(lc=window)||void 0===lc||null===(lc=lc.imageOptimizerAppSettings)||void 0===lc?void 0:lc.isDevelopment)?r.Fragment:r.StrictMode,dc=(0,r.createRoot)(sc),hc=(0,r.createRoot)(fc);dc.render($t(pc,null,$t((function(){return $t(Lt,{theme:At},$t(cc,null,$t(ac,null)))}),null))),hc.render($t(pc,null,$t((function(){return $t(Lt,{theme:At},$t(Ye,null,$t(Me,null,$t(Vu,null))))}),null)))},679:function(t,e,n){"use strict";var r=n(296),o={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},i={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},a={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},u={};function c(t){return r.isMemo(t)?a:u[t.$$typeof]||o}u[r.ForwardRef]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},u[r.Memo]=a;var l=Object.defineProperty,s=Object.getOwnPropertyNames,f=Object.getOwnPropertySymbols,p=Object.getOwnPropertyDescriptor,d=Object.getPrototypeOf,h=Object.prototype;t.exports=function t(e,n,r){if("string"!=typeof n){if(h){var o=d(n);o&&o!==h&&t(e,o,r)}var a=s(n);f&&(a=a.concat(f(n)));for(var u=c(e),m=c(n),g=0;g<a.length;++g){var v=a[g];if(!(i[v]||r&&r[v]||m&&m[v]||u&&u[v])){var y=p(n,v);try{l(e,v,y)}catch(t){}}}}return e}},103:function(t,e){"use strict";var n="function"==typeof Symbol&&Symbol.for,r=n?Symbol.for("react.element"):60103,o=n?Symbol.for("react.portal"):60106,i=n?Symbol.for("react.fragment"):60107,a=n?Symbol.for("react.strict_mode"):60108,u=n?Symbol.for("react.profiler"):60114,c=n?Symbol.for("react.provider"):60109,l=n?Symbol.for("react.context"):60110,s=n?Symbol.for("react.async_mode"):60111,f=n?Symbol.for("react.concurrent_mode"):60111,p=n?Symbol.for("react.forward_ref"):60112,d=n?Symbol.for("react.suspense"):60113,h=n?Symbol.for("react.suspense_list"):60120,m=n?Symbol.for("react.memo"):60115,g=n?Symbol.for("react.lazy"):60116,v=n?Symbol.for("react.block"):60121,y=n?Symbol.for("react.fundamental"):60117,b=n?Symbol.for("react.responder"):60118,w=n?Symbol.for("react.scope"):60119;function x(t){if("object"==typeof t&&null!==t){var e=t.$$typeof;switch(e){case r:switch(t=t.type){case s:case f:case i:case u:case a:case d:return t;default:switch(t=t&&t.$$typeof){case l:case p:case g:case m:case c:return t;default:return e}}case o:return e}}}function _(t){return x(t)===f}e.AsyncMode=s,e.ConcurrentMode=f,e.ContextConsumer=l,e.ContextProvider=c,e.Element=r,e.ForwardRef=p,e.Fragment=i,e.Lazy=g,e.Memo=m,e.Portal=o,e.Profiler=u,e.StrictMode=a,e.Suspense=d,e.isAsyncMode=function(t){return _(t)||x(t)===s},e.isConcurrentMode=_,e.isContextConsumer=function(t){return x(t)===l},e.isContextProvider=function(t){return x(t)===c},e.isElement=function(t){return"object"==typeof t&&null!==t&&t.$$typeof===r},e.isForwardRef=function(t){return x(t)===p},e.isFragment=function(t){return x(t)===i},e.isLazy=function(t){return x(t)===g},e.isMemo=function(t){return x(t)===m},e.isPortal=function(t){return x(t)===o},e.isProfiler=function(t){return x(t)===u},e.isStrictMode=function(t){return x(t)===a},e.isSuspense=function(t){return x(t)===d},e.isValidElementType=function(t){return"string"==typeof t||"function"==typeof t||t===i||t===f||t===u||t===a||t===d||t===h||"object"==typeof t&&null!==t&&(t.$$typeof===g||t.$$typeof===m||t.$$typeof===c||t.$$typeof===l||t.$$typeof===p||t.$$typeof===y||t.$$typeof===b||t.$$typeof===w||t.$$typeof===v)},e.typeOf=x},296:function(t,e,n){"use strict";t.exports=n(103)},703:function(t,e,n){"use strict";var r=n(414);function o(){}function i(){}i.resetWarningCache=o,t.exports=function(){function t(t,e,n,o,i,a){if(a!==r){var u=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw u.name="Invariant Violation",u}}function e(){return t}t.isRequired=t;var n={array:t,bigint:t,bool:t,func:t,number:t,object:t,string:t,symbol:t,any:t,arrayOf:e,element:t,elementType:t,instanceOf:e,node:t,objectOf:e,oneOf:e,oneOfType:e,shape:e,exact:e,checkPropTypes:i,resetWarningCache:o};return n.PropTypes=n,n}},697:function(t,e,n){t.exports=n(703)()},414:function(t){"use strict";t.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},217:function(t,e,n){!function(t,e){"use strict";function n(t,e,n,r,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void n(t)}u.done?e(c):Promise.resolve(c).then(r,o)}function r(t){return function(){var e=this,r=arguments;return new Promise((function(o,i){var a=t.apply(e,r);function u(t){n(a,o,i,u,c,"next",t)}function c(t){n(a,o,i,u,c,"throw",t)}u(void 0)}))}}function o(){return(o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}function i(t,e){if(null==t)return{};var n,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)n=i[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}function a(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==typeof e?e:String(e)}e=e&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e;var u={init:"init"},c=function(t){var e=t.value;return void 0===e?"":e},l=function(){return e.createElement(e.Fragment,null," ")},s={Cell:c,width:150,minWidth:0,maxWidth:Number.MAX_SAFE_INTEGER};function f(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return e.reduce((function(t,e){var n=e.style,r=e.className;return t=o({},t,{},i(e,["style","className"])),n&&(t.style=t.style?o({},t.style||{},{},n||{}):n),r&&(t.className=t.className?t.className+" "+r:r),""===t.className&&delete t.className,t}),{})}var p=function(t,e){return void 0===e&&(e={}),function(n){return void 0===n&&(n={}),[].concat(t,[n]).reduce((function(t,r){return function t(e,n,r){return"function"==typeof n?t({},n(e,r)):Array.isArray(n)?f.apply(void 0,[e].concat(n)):f(e,n)}(t,r,o({},e,{userProps:n}))}),{})}},d=function(t,e,n,r){return void 0===n&&(n={}),t.reduce((function(t,e){return e(t,n)}),e)},h=function(t,e,n){return void 0===n&&(n={}),t.forEach((function(t){t(e,n)}))};function m(t,e,n,r){t.findIndex((function(t){return t.pluginName===n})),e.forEach((function(e){t.findIndex((function(t){return t.pluginName===e}))}))}function g(t,e){return"function"==typeof t?t(e):t}function v(t){var n=e.useRef();return n.current=t,e.useCallback((function(){return n.current}),[])}var y="undefined"!=typeof document?e.useLayoutEffect:e.useEffect;function b(t,n){var r=e.useRef(!1);y((function(){r.current&&t(),r.current=!0}),n)}function w(t,e,n){return void 0===n&&(n={}),function(r,i){void 0===i&&(i={});var a="string"==typeof r?e[r]:r;if(void 0===a)throw console.info(e),new Error("Renderer Error ☝️");return x(a,o({},t,{column:e},n,{},i))}}function x(t,n){return function(t){return"function"==typeof t&&(e=Object.getPrototypeOf(t)).prototype&&e.prototype.isReactComponent;var e}(r=t)||"function"==typeof r||function(t){return"object"==typeof t&&"symbol"==typeof t.$$typeof&&["react.memo","react.forward_ref"].includes(t.$$typeof.description)}(r)?e.createElement(t,n):t;var r}function _(t,e,n){return void 0===n&&(n=0),t.map((function(t){return k(t=o({},t,{parent:e,depth:n})),t.columns&&(t.columns=_(t.columns,t,n+1)),t}))}function S(t){return C(t,"columns")}function k(t){var e=t.id,n=t.accessor,r=t.Header;if("string"==typeof n){e=e||n;var o=n.split(".");n=function(t){return function(t,e,n){if(!e)return t;var r,o="function"==typeof e?e:JSON.stringify(e),i=E.get(o)||function(){var t=function(t){return function t(e,n){if(void 0===n&&(n=[]),Array.isArray(e))for(var r=0;r<e.length;r+=1)t(e[r],n);else n.push(e);return n}(t).map((function(t){return String(t).replace(".","_")})).join(".").replace(A,".").replace(N,"").split(".")}(e);return E.set(o,t),t}();try{r=i.reduce((function(t,e){return t[e]}),t)}catch(t){}return void 0!==r?r:void 0}(t,o)}}if(!e&&"string"==typeof r&&r&&(e=r),!e&&t.columns)throw console.error(t),new Error('A column ID (or unique "Header" value) is required!');if(!e)throw console.error(t),new Error("A column ID (or string accessor) is required!");return Object.assign(t,{id:e,accessor:n}),t}function O(t,e){if(!e)throw new Error;return Object.assign(t,o({Header:l,Footer:l},s,{},e,{},t)),Object.assign(t,{originalWidth:t.width}),t}var E=new Map;function R(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];for(var r=0;r<e.length;r+=1)if(void 0!==e[r])return e[r]}function z(t){if("function"==typeof t)return t}function C(t,e){var n=[];return function t(r){r.forEach((function(r){r[e]?t(r[e]):n.push(r)}))}(t),n}function j(t,e){var n=e.manualExpandedKey,r=e.expanded,o=e.expandSubRows,i=void 0===o||o,a=[];return t.forEach((function(t){return function t(e,o){void 0===o&&(o=!0),e.isExpanded=e.original&&e.original[n]||r[e.id],e.canExpand=e.subRows&&!!e.subRows.length,o&&a.push(e),e.subRows&&e.subRows.length&&e.isExpanded&&e.subRows.forEach((function(e){return t(e,i)}))}(t)})),a}function L(t,e,n){return z(t)||e[t]||n[t]||n.text}function P(t,e,n){return t?t(e,n):void 0===e}function I(){throw new Error("React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.")}var T=null,A=/\[/g,N=/\]/g,G=function(t){return o({role:"table"},t)},M=function(t){return o({role:"rowgroup"},t)},F=function(t,e){var n=e.column;return o({key:"header_"+n.id,colSpan:n.totalVisibleHeaderCount,role:"columnheader"},t)},D=function(t,e){var n=e.column;return o({key:"footer_"+n.id,colSpan:n.totalVisibleHeaderCount},t)},B=function(t,e){return o({key:"headerGroup_"+e.index,role:"row"},t)},H=function(t,e){return o({key:"footerGroup_"+e.index},t)},W=function(t,e){return o({key:"row_"+e.row.id,role:"row"},t)},U=function(t,e){var n=e.cell;return o({key:"cell_"+n.row.id+"_"+n.column.id,role:"cell"},t)};function q(){return{useOptions:[],stateReducers:[],useControlledState:[],columns:[],columnsDeps:[],allColumns:[],allColumnsDeps:[],accessValue:[],materializedColumns:[],materializedColumnsDeps:[],useInstanceAfterData:[],visibleColumns:[],visibleColumnsDeps:[],headerGroups:[],headerGroupsDeps:[],useInstanceBeforeDimensions:[],useInstance:[],prepareRow:[],getTableProps:[G],getTableBodyProps:[M],getHeaderGroupProps:[B],getFooterGroupProps:[H],getHeaderProps:[F],getFooterProps:[D],getRowProps:[W],getCellProps:[U],useFinalInstance:[]}}u.resetHiddenColumns="resetHiddenColumns",u.toggleHideColumn="toggleHideColumn",u.setHiddenColumns="setHiddenColumns",u.toggleHideAllColumns="toggleHideAllColumns";var Z=function(t){t.getToggleHiddenProps=[$],t.getToggleHideAllColumnsProps=[V],t.stateReducers.push(Y),t.useInstanceBeforeDimensions.push(X),t.headerGroupsDeps.push((function(t,e){var n=e.instance;return[].concat(t,[n.state.hiddenColumns])})),t.useInstance.push(K)};Z.pluginName="useColumnVisibility";var $=function(t,e){var n=e.column;return[t,{onChange:function(t){n.toggleHidden(!t.target.checked)},style:{cursor:"pointer"},checked:n.isVisible,title:"Toggle Column Visible"}]},V=function(t,e){var n=e.instance;return[t,{onChange:function(t){n.toggleHideAllColumns(!t.target.checked)},style:{cursor:"pointer"},checked:!n.allColumnsHidden&&!n.state.hiddenColumns.length,title:"Toggle All Columns Hidden",indeterminate:!n.allColumnsHidden&&n.state.hiddenColumns.length}]};function Y(t,e,n,r){if(e.type===u.init)return o({hiddenColumns:[]},t);if(e.type===u.resetHiddenColumns)return o({},t,{hiddenColumns:r.initialState.hiddenColumns||[]});if(e.type===u.toggleHideColumn){var i=(void 0!==e.value?e.value:!t.hiddenColumns.includes(e.columnId))?[].concat(t.hiddenColumns,[e.columnId]):t.hiddenColumns.filter((function(t){return t!==e.columnId}));return o({},t,{hiddenColumns:i})}return e.type===u.setHiddenColumns?o({},t,{hiddenColumns:g(e.value,t.hiddenColumns)}):e.type===u.toggleHideAllColumns?o({},t,{hiddenColumns:(void 0!==e.value?e.value:!t.hiddenColumns.length)?r.allColumns.map((function(t){return t.id})):[]}):void 0}function X(t){var n=t.headers,r=t.state.hiddenColumns;e.useRef(!1).current;var o=0;n.forEach((function(t){return o+=function t(e,n){e.isVisible=n&&!r.includes(e.id);var o=0;return e.headers&&e.headers.length?e.headers.forEach((function(n){return o+=t(n,e.isVisible)})):o=e.isVisible?1:0,e.totalVisibleHeaderCount=o,o}(t,!0)}))}function K(t){var n=t.columns,r=t.flatHeaders,o=t.dispatch,i=t.allColumns,a=t.getHooks,c=t.state.hiddenColumns,l=t.autoResetHiddenColumns,s=void 0===l||l,f=v(t),d=i.length===c.length,h=e.useCallback((function(t,e){return o({type:u.toggleHideColumn,columnId:t,value:e})}),[o]),m=e.useCallback((function(t){return o({type:u.setHiddenColumns,value:t})}),[o]),g=e.useCallback((function(t){return o({type:u.toggleHideAllColumns,value:t})}),[o]),y=p(a().getToggleHideAllColumnsProps,{instance:f()});r.forEach((function(t){t.toggleHidden=function(e){o({type:u.toggleHideColumn,columnId:t.id,value:e})},t.getToggleHiddenProps=p(a().getToggleHiddenProps,{instance:f(),column:t})}));var w=v(s);b((function(){w()&&o({type:u.resetHiddenColumns})}),[o,n]),Object.assign(t,{allColumnsHidden:d,toggleHideColumn:h,setHiddenColumns:m,toggleHideAllColumns:g,getToggleHideAllColumnsProps:y})}var Q={},J={},tt=function(t,e,n){return t},et=function(t,e){return t.subRows||[]},nt=function(t,e,n){return""+(n?[n.id,e].join("."):e)},rt=function(t){return t};function ot(t){var e=t.initialState,n=void 0===e?Q:e,r=t.defaultColumn,a=void 0===r?J:r,u=t.getSubRows,c=void 0===u?et:u,l=t.getRowId,s=void 0===l?nt:l,f=t.stateReducer,p=void 0===f?tt:f,d=t.useControlledState,h=void 0===d?rt:d;return o({},i(t,["initialState","defaultColumn","getSubRows","getRowId","stateReducer","useControlledState"]),{initialState:n,defaultColumn:a,getSubRows:c,getRowId:s,stateReducer:p,useControlledState:h})}function it(t,e){void 0===e&&(e=0);var n=0,r=0,o=0,i=0;return t.forEach((function(t){var a=t.headers;if(t.totalLeft=e,a&&a.length){var u=it(a,e),c=u[0],l=u[1],s=u[2],f=u[3];t.totalMinWidth=c,t.totalWidth=l,t.totalMaxWidth=s,t.totalFlexWidth=f}else t.totalMinWidth=t.minWidth,t.totalWidth=Math.min(Math.max(t.minWidth,t.width),t.maxWidth),t.totalMaxWidth=t.maxWidth,t.totalFlexWidth=t.canResize?t.totalWidth:0;t.isVisible&&(e+=t.totalWidth,n+=t.totalMinWidth,r+=t.totalWidth,o+=t.totalMaxWidth,i+=t.totalFlexWidth)})),[n,r,o,i]}function at(t){var e=t.data,n=t.rows,r=t.flatRows,o=t.rowsById,i=t.column,a=t.getRowId,u=t.getSubRows,c=t.accessValueHooks,l=t.getInstance;e.forEach((function(t,s){return function t(n,s,f,p,h){void 0===f&&(f=0);var m=n,g=a(n,s,p),v=o[g];if(v)v.subRows&&v.originalSubRows.forEach((function(e,n){return t(e,n,f+1,v)}));else if((v={id:g,original:m,index:s,depth:f,cells:[{}]}).cells.map=I,v.cells.filter=I,v.cells.forEach=I,v.cells[0].getCellProps=I,v.values={},h.push(v),r.push(v),o[g]=v,v.originalSubRows=u(n,s),v.originalSubRows){var y=[];v.originalSubRows.forEach((function(e,n){return t(e,n,f+1,v,y)})),v.subRows=y}i.accessor&&(v.values[i.id]=i.accessor(n,s,v,h,e)),v.values[i.id]=d(c,v.values[i.id],{row:v,column:i,instance:l()})}(t,s,0,void 0,n)}))}u.resetExpanded="resetExpanded",u.toggleRowExpanded="toggleRowExpanded",u.toggleAllRowsExpanded="toggleAllRowsExpanded";var ut=function(t){t.getToggleAllRowsExpandedProps=[ct],t.getToggleRowExpandedProps=[lt],t.stateReducers.push(st),t.useInstance.push(ft),t.prepareRow.push(pt)};ut.pluginName="useExpanded";var ct=function(t,e){var n=e.instance;return[t,{onClick:function(t){n.toggleAllRowsExpanded()},style:{cursor:"pointer"},title:"Toggle All Rows Expanded"}]},lt=function(t,e){var n=e.row;return[t,{onClick:function(){n.toggleRowExpanded()},style:{cursor:"pointer"},title:"Toggle Row Expanded"}]};function st(t,e,n,r){if(e.type===u.init)return o({expanded:{}},t);if(e.type===u.resetExpanded)return o({},t,{expanded:r.initialState.expanded||{}});if(e.type===u.toggleAllRowsExpanded){var c=e.value,l=r.rowsById,s=Object.keys(l).length===Object.keys(t.expanded).length;if(void 0!==c?c:!s){var f={};return Object.keys(l).forEach((function(t){f[t]=!0})),o({},t,{expanded:f})}return o({},t,{expanded:{}})}if(e.type===u.toggleRowExpanded){var p,d=e.id,h=e.value,m=t.expanded[d],g=void 0!==h?h:!m;if(!m&&g)return o({},t,{expanded:o({},t.expanded,(p={},p[d]=!0,p))});if(m&&!g){var v=t.expanded;return v[d],o({},t,{expanded:i(v,[d].map(a))})}return t}}function ft(t){var n=t.data,r=t.rows,o=t.rowsById,i=t.manualExpandedKey,a=void 0===i?"expanded":i,c=t.paginateExpandedRows,l=void 0===c||c,s=t.expandSubRows,f=void 0===s||s,d=t.autoResetExpanded,h=void 0===d||d,g=t.getHooks,y=t.plugins,w=t.state.expanded,x=t.dispatch;m(y,["useSortBy","useGroupBy","usePivotColumns","useGlobalFilter"],"useExpanded");var _=v(h),S=Boolean(Object.keys(o).length&&Object.keys(w).length);S&&Object.keys(o).some((function(t){return!w[t]}))&&(S=!1),b((function(){_()&&x({type:u.resetExpanded})}),[x,n]);var k=e.useCallback((function(t,e){x({type:u.toggleRowExpanded,id:t,value:e})}),[x]),O=e.useCallback((function(t){return x({type:u.toggleAllRowsExpanded,value:t})}),[x]),E=e.useMemo((function(){return l?j(r,{manualExpandedKey:a,expanded:w,expandSubRows:f}):r}),[l,r,a,w,f]),R=e.useMemo((function(){return function(t){var e=0;return Object.keys(t).forEach((function(t){var n=t.split(".");e=Math.max(e,n.length)})),e}(w)}),[w]),z=v(t),C=p(g().getToggleAllRowsExpandedProps,{instance:z()});Object.assign(t,{preExpandedRows:r,expandedRows:E,rows:E,expandedDepth:R,isAllRowsExpanded:S,toggleRowExpanded:k,toggleAllRowsExpanded:O,getToggleAllRowsExpandedProps:C})}function pt(t,e){var n=e.instance.getHooks,r=e.instance;t.toggleRowExpanded=function(e){return r.toggleRowExpanded(t.id,e)},t.getToggleRowExpandedProps=p(n().getToggleRowExpandedProps,{instance:r,row:t})}var dt=function(t,e,n){return t.filter((function(t){return e.some((function(e){var r=t.values[e];return String(r).toLowerCase().includes(String(n).toLowerCase())}))}))};dt.autoRemove=function(t){return!t};var ht=function(t,e,n){return t.filter((function(t){return e.some((function(e){var r=t.values[e];return void 0===r||String(r).toLowerCase()===String(n).toLowerCase()}))}))};ht.autoRemove=function(t){return!t};var mt=function(t,e,n){return t.filter((function(t){return e.some((function(e){var r=t.values[e];return void 0===r||String(r)===String(n)}))}))};mt.autoRemove=function(t){return!t};var gt=function(t,e,n){return t.filter((function(t){return e.some((function(e){return t.values[e].includes(n)}))}))};gt.autoRemove=function(t){return!t||!t.length};var vt=function(t,e,n){return t.filter((function(t){return e.some((function(e){var r=t.values[e];return r&&r.length&&n.every((function(t){return r.includes(t)}))}))}))};vt.autoRemove=function(t){return!t||!t.length};var yt=function(t,e,n){return t.filter((function(t){return e.some((function(e){var r=t.values[e];return r&&r.length&&n.some((function(t){return r.includes(t)}))}))}))};yt.autoRemove=function(t){return!t||!t.length};var bt=function(t,e,n){return t.filter((function(t){return e.some((function(e){var r=t.values[e];return n.includes(r)}))}))};bt.autoRemove=function(t){return!t||!t.length};var wt=function(t,e,n){return t.filter((function(t){return e.some((function(e){return t.values[e]===n}))}))};wt.autoRemove=function(t){return void 0===t};var xt=function(t,e,n){return t.filter((function(t){return e.some((function(e){return t.values[e]==n}))}))};xt.autoRemove=function(t){return null==t};var _t=function(t,e,n){var r=n||[],o=r[0],i=r[1];if((o="number"==typeof o?o:-1/0)>(i="number"==typeof i?i:1/0)){var a=o;o=i,i=a}return t.filter((function(t){return e.some((function(e){var n=t.values[e];return n>=o&&n<=i}))}))};_t.autoRemove=function(t){return!t||"number"!=typeof t[0]&&"number"!=typeof t[1]};var St=Object.freeze({__proto__:null,text:dt,exactText:ht,exactTextCase:mt,includes:gt,includesAll:vt,includesSome:yt,includesValue:bt,exact:wt,equals:xt,between:_t});u.resetFilters="resetFilters",u.setFilter="setFilter",u.setAllFilters="setAllFilters";var kt=function(t){t.stateReducers.push(Ot),t.useInstance.push(Et)};function Ot(t,e,n,r){if(e.type===u.init)return o({filters:[]},t);if(e.type===u.resetFilters)return o({},t,{filters:r.initialState.filters||[]});if(e.type===u.setFilter){var i=e.columnId,a=e.filterValue,c=r.allColumns,l=r.filterTypes,s=c.find((function(t){return t.id===i}));if(!s)throw new Error("React-Table: Could not find a column with id: "+i);var f=L(s.filter,l||{},St),p=t.filters.find((function(t){return t.id===i})),d=g(a,p&&p.value);return P(f.autoRemove,d,s)?o({},t,{filters:t.filters.filter((function(t){return t.id!==i}))}):o({},t,p?{filters:t.filters.map((function(t){return t.id===i?{id:i,value:d}:t}))}:{filters:[].concat(t.filters,[{id:i,value:d}])})}if(e.type===u.setAllFilters){var h=e.filters,m=r.allColumns,v=r.filterTypes;return o({},t,{filters:g(h,t.filters).filter((function(t){var e=m.find((function(e){return e.id===t.id}));return!P(L(e.filter,v||{},St).autoRemove,t.value,e)}))})}}function Et(t){var n=t.data,r=t.rows,o=t.flatRows,i=t.rowsById,a=t.allColumns,c=t.filterTypes,l=t.manualFilters,s=t.defaultCanFilter,f=void 0!==s&&s,p=t.disableFilters,d=t.state.filters,h=t.dispatch,m=t.autoResetFilters,g=void 0===m||m,y=e.useCallback((function(t,e){h({type:u.setFilter,columnId:t,filterValue:e})}),[h]),w=e.useCallback((function(t){h({type:u.setAllFilters,filters:t})}),[h]);a.forEach((function(t){var e=t.id,n=t.accessor,r=t.defaultCanFilter,o=t.disableFilters;t.canFilter=n?R(!0!==o&&void 0,!0!==p&&void 0,!0):R(r,f,!1),t.setFilter=function(e){return y(t.id,e)};var i=d.find((function(t){return t.id===e}));t.filterValue=i&&i.value}));var x=e.useMemo((function(){if(l||!d.length)return[r,o,i];var t=[],e={};return[function n(r,o){void 0===o&&(o=0);var i=r;return(i=d.reduce((function(t,e){var n=e.id,r=e.value,i=a.find((function(t){return t.id===n}));if(!i)return t;0===o&&(i.preFilteredRows=t);var u=L(i.filter,c||{},St);return u?(i.filteredRows=u(t,[n],r),i.filteredRows):(console.warn("Could not find a valid 'column.filter' for column with the ID: "+i.id+"."),t)}),r)).forEach((function(r){t.push(r),e[r.id]=r,r.subRows&&(r.subRows=r.subRows&&r.subRows.length>0?n(r.subRows,o+1):r.subRows)})),i}(r),t,e]}),[l,d,r,o,i,a,c]),_=x[0],S=x[1],k=x[2];e.useMemo((function(){a.filter((function(t){return!d.find((function(e){return e.id===t.id}))})).forEach((function(t){t.preFilteredRows=_,t.filteredRows=_}))}),[_,d,a]);var O=v(g);b((function(){O()&&h({type:u.resetFilters})}),[h,l?null:n]),Object.assign(t,{preFilteredRows:r,preFilteredFlatRows:o,preFilteredRowsById:i,filteredRows:_,filteredFlatRows:S,filteredRowsById:k,rows:_,flatRows:S,rowsById:k,setFilter:y,setAllFilters:w})}kt.pluginName="useFilters",u.resetGlobalFilter="resetGlobalFilter",u.setGlobalFilter="setGlobalFilter";var Rt=function(t){t.stateReducers.push(zt),t.useInstance.push(Ct)};function zt(t,e,n,r){if(e.type===u.resetGlobalFilter)return o({},t,{globalFilter:r.initialState.globalFilter||void 0});if(e.type===u.setGlobalFilter){var a=e.filterValue,c=r.userFilterTypes,l=L(r.globalFilter,c||{},St),s=g(a,t.globalFilter);return P(l.autoRemove,s)?(t.globalFilter,i(t,["globalFilter"])):o({},t,{globalFilter:s})}}function Ct(t){var n=t.data,r=t.rows,o=t.flatRows,i=t.rowsById,a=t.allColumns,c=t.filterTypes,l=t.globalFilter,s=t.manualGlobalFilter,f=t.state.globalFilter,p=t.dispatch,d=t.autoResetGlobalFilter,h=void 0===d||d,m=t.disableGlobalFilter,g=e.useCallback((function(t){p({type:u.setGlobalFilter,filterValue:t})}),[p]),y=e.useMemo((function(){if(s||void 0===f)return[r,o,i];var t=[],e={},n=L(l,c||{},St);if(!n)return console.warn("Could not find a valid 'globalFilter' option."),r;a.forEach((function(t){var e=t.disableGlobalFilter;t.canFilter=R(!0!==e&&void 0,!0!==m&&void 0,!0)}));var u=a.filter((function(t){return!0===t.canFilter}));return[function r(o){return(o=n(o,u.map((function(t){return t.id})),f)).forEach((function(n){t.push(n),e[n.id]=n,n.subRows=n.subRows&&n.subRows.length?r(n.subRows):n.subRows})),o}(r),t,e]}),[s,f,l,c,a,r,o,i,m]),w=y[0],x=y[1],_=y[2],S=v(h);b((function(){S()&&p({type:u.resetGlobalFilter})}),[p,s?null:n]),Object.assign(t,{preGlobalFilteredRows:r,preGlobalFilteredFlatRows:o,preGlobalFilteredRowsById:i,globalFilteredRows:w,globalFilteredFlatRows:x,globalFilteredRowsById:_,rows:w,flatRows:x,rowsById:_,setGlobalFilter:g,disableGlobalFilter:m})}function jt(t,e){return e.reduce((function(t,e){return t+("number"==typeof e?e:0)}),0)}Rt.pluginName="useGlobalFilter";var Lt=Object.freeze({__proto__:null,sum:jt,min:function(t){var e=t[0]||0;return t.forEach((function(t){"number"==typeof t&&(e=Math.min(e,t))})),e},max:function(t){var e=t[0]||0;return t.forEach((function(t){"number"==typeof t&&(e=Math.max(e,t))})),e},minMax:function(t){var e=t[0]||0,n=t[0]||0;return t.forEach((function(t){"number"==typeof t&&(e=Math.min(e,t),n=Math.max(n,t))})),e+".."+n},average:function(t){return jt(0,t)/t.length},median:function(t){if(!t.length)return null;var e=Math.floor(t.length/2),n=[].concat(t).sort((function(t,e){return t-e}));return t.length%2!=0?n[e]:(n[e-1]+n[e])/2},unique:function(t){return Array.from(new Set(t).values())},uniqueCount:function(t){return new Set(t).size},count:function(t){return t.length}}),Pt=[],It={};u.resetGroupBy="resetGroupBy",u.setGroupBy="setGroupBy",u.toggleGroupBy="toggleGroupBy";var Tt=function(t){t.getGroupByToggleProps=[At],t.stateReducers.push(Nt),t.visibleColumnsDeps.push((function(t,e){var n=e.instance;return[].concat(t,[n.state.groupBy])})),t.visibleColumns.push(Gt),t.useInstance.push(Ft),t.prepareRow.push(Dt)};Tt.pluginName="useGroupBy";var At=function(t,e){var n=e.header;return[t,{onClick:n.canGroupBy?function(t){t.persist(),n.toggleGroupBy()}:void 0,style:{cursor:n.canGroupBy?"pointer":void 0},title:"Toggle GroupBy"}]};function Nt(t,e,n,r){if(e.type===u.init)return o({groupBy:[]},t);if(e.type===u.resetGroupBy)return o({},t,{groupBy:r.initialState.groupBy||[]});if(e.type===u.setGroupBy)return o({},t,{groupBy:e.value});if(e.type===u.toggleGroupBy){var i=e.columnId,a=e.value,c=void 0!==a?a:!t.groupBy.includes(i);return o({},t,c?{groupBy:[].concat(t.groupBy,[i])}:{groupBy:t.groupBy.filter((function(t){return t!==i}))})}}function Gt(t,e){var n=e.instance.state.groupBy,r=n.map((function(e){return t.find((function(t){return t.id===e}))})).filter(Boolean),o=t.filter((function(t){return!n.includes(t.id)}));return(t=[].concat(r,o)).forEach((function(t){t.isGrouped=n.includes(t.id),t.groupedIndex=n.indexOf(t.id)})),t}var Mt={};function Ft(t){var n=t.data,r=t.rows,i=t.flatRows,a=t.rowsById,c=t.allColumns,l=t.flatHeaders,s=t.groupByFn,f=void 0===s?Bt:s,d=t.manualGroupBy,h=t.aggregations,g=void 0===h?Mt:h,y=t.plugins,w=t.state.groupBy,x=t.dispatch,_=t.autoResetGroupBy,S=void 0===_||_,k=t.disableGroupBy,O=t.defaultCanGroupBy,E=t.getHooks;m(y,["useColumnOrder","useFilters"],"useGroupBy");var z=v(t);c.forEach((function(e){var n=e.accessor,r=e.defaultGroupBy,o=e.disableGroupBy;e.canGroupBy=n?R(e.canGroupBy,!0!==o&&void 0,!0!==k&&void 0,!0):R(e.canGroupBy,r,O,!1),e.canGroupBy&&(e.toggleGroupBy=function(){return t.toggleGroupBy(e.id)}),e.Aggregated=e.Aggregated||e.Cell}));var j=e.useCallback((function(t,e){x({type:u.toggleGroupBy,columnId:t,value:e})}),[x]),L=e.useCallback((function(t){x({type:u.setGroupBy,value:t})}),[x]);l.forEach((function(t){t.getGroupByToggleProps=p(E().getGroupByToggleProps,{instance:z(),header:t})}));var P=e.useMemo((function(){if(d||!w.length)return[r,i,a,Pt,It,i,a];var t=w.filter((function(t){return c.find((function(e){return e.id===t}))})),e=[],n={},u=[],l={},s=[],p={},h=function r(i,a,d){if(void 0===a&&(a=0),a===t.length)return i.map((function(t){return o({},t,{depth:a})}));var h=t[a],m=f(i,h);return Object.entries(m).map((function(o,i){var f=o[0],m=o[1],v=h+":"+f,y=r(m,a+1,v=d?d+">"+v:v),b=a?C(m,"leafRows"):m,w=function(e,n,r){var o={};return c.forEach((function(i){if(t.includes(i.id))o[i.id]=n[0]?n[0].values[i.id]:null;else{var a="function"==typeof i.aggregate?i.aggregate:g[i.aggregate]||Lt[i.aggregate];if(a){var u=n.map((function(t){return t.values[i.id]})),c=e.map((function(t){var e=t.values[i.id];if(!r&&i.aggregateValue){var n="function"==typeof i.aggregateValue?i.aggregateValue:g[i.aggregateValue]||Lt[i.aggregateValue];if(!n)throw console.info({column:i}),new Error("React Table: Invalid column.aggregateValue option for column listed above");e=n(e,t,i)}return e}));o[i.id]=a(c,u)}else{if(i.aggregate)throw console.info({column:i}),new Error("React Table: Invalid column.aggregate option for column listed above");o[i.id]=null}}})),o}(b,m,a),x={id:v,isGrouped:!0,groupByID:h,groupByVal:f,values:w,subRows:y,leafRows:b,depth:a,index:i};return y.forEach((function(t){e.push(t),n[t.id]=t,t.isGrouped?(u.push(t),l[t.id]=t):(s.push(t),p[t.id]=t)})),x}))}(r);return h.forEach((function(t){e.push(t),n[t.id]=t,t.isGrouped?(u.push(t),l[t.id]=t):(s.push(t),p[t.id]=t)})),[h,e,n,u,l,s,p]}),[d,w,r,i,a,c,g,f]),I=P[0],T=P[1],A=P[2],N=P[3],G=P[4],M=P[5],F=P[6],D=v(S);b((function(){D()&&x({type:u.resetGroupBy})}),[x,d?null:n]),Object.assign(t,{preGroupedRows:r,preGroupedFlatRow:i,preGroupedRowsById:a,groupedRows:I,groupedFlatRows:T,groupedRowsById:A,onlyGroupedFlatRows:N,onlyGroupedRowsById:G,nonGroupedFlatRows:M,nonGroupedRowsById:F,rows:I,flatRows:T,rowsById:A,toggleGroupBy:j,setGroupBy:L})}function Dt(t){t.allCells.forEach((function(e){var n;e.isGrouped=e.column.isGrouped&&e.column.id===t.groupByID,e.isPlaceholder=!e.isGrouped&&e.column.isGrouped,e.isAggregated=!e.isGrouped&&!e.isPlaceholder&&(null==(n=t.subRows)?void 0:n.length)}))}function Bt(t,e){return t.reduce((function(t,n,r){var o=""+n.values[e];return t[o]=Array.isArray(t[o])?t[o]:[],t[o].push(n),t}),{})}var Ht=/([0-9]+)/gm;function Wt(t,e){return t===e?0:t>e?1:-1}function Ut(t,e,n){return[t.values[n],e.values[n]]}function qt(t){return"number"==typeof t?isNaN(t)||t===1/0||t===-1/0?"":String(t):"string"==typeof t?t:""}var Zt=Object.freeze({__proto__:null,alphanumeric:function(t,e,n){var r=Ut(t,e,n),o=r[0],i=r[1];for(o=qt(o),i=qt(i),o=o.split(Ht).filter(Boolean),i=i.split(Ht).filter(Boolean);o.length&&i.length;){var a=o.shift(),u=i.shift(),c=parseInt(a,10),l=parseInt(u,10),s=[c,l].sort();if(isNaN(s[0])){if(a>u)return 1;if(u>a)return-1}else{if(isNaN(s[1]))return isNaN(c)?-1:1;if(c>l)return 1;if(l>c)return-1}}return o.length-i.length},datetime:function(t,e,n){var r=Ut(t,e,n),o=r[0],i=r[1];return Wt(o=o.getTime(),i=i.getTime())},basic:function(t,e,n){var r=Ut(t,e,n);return Wt(r[0],r[1])},string:function(t,e,n){var r=Ut(t,e,n),o=r[0],i=r[1];for(o=o.split("").filter(Boolean),i=i.split("").filter(Boolean);o.length&&i.length;){var a=o.shift(),u=i.shift(),c=a.toLowerCase(),l=u.toLowerCase();if(c>l)return 1;if(l>c)return-1;if(a>u)return 1;if(u>a)return-1}return o.length-i.length},number:function(t,e,n){var r=Ut(t,e,n),o=r[0],i=r[1],a=/[^0-9.]/gi;return Wt(o=Number(String(o).replace(a,"")),i=Number(String(i).replace(a,"")))}});u.resetSortBy="resetSortBy",u.setSortBy="setSortBy",u.toggleSortBy="toggleSortBy",u.clearSortBy="clearSortBy",s.sortType="alphanumeric",s.sortDescFirst=!1;var $t=function(t){t.getSortByToggleProps=[Vt],t.stateReducers.push(Yt),t.useInstance.push(Xt)};$t.pluginName="useSortBy";var Vt=function(t,e){var n=e.instance,r=e.column,o=n.isMultiSortEvent,i=void 0===o?function(t){return t.shiftKey}:o;return[t,{onClick:r.canSort?function(t){t.persist(),r.toggleSortBy(void 0,!n.disableMultiSort&&i(t))}:void 0,style:{cursor:r.canSort?"pointer":void 0},title:r.canSort?"Toggle SortBy":void 0}]};function Yt(t,e,n,r){if(e.type===u.init)return o({sortBy:[]},t);if(e.type===u.resetSortBy)return o({},t,{sortBy:r.initialState.sortBy||[]});if(e.type===u.clearSortBy)return o({},t,{sortBy:t.sortBy.filter((function(t){return t.id!==e.columnId}))});if(e.type===u.setSortBy)return o({},t,{sortBy:e.sortBy});if(e.type===u.toggleSortBy){var i,a=e.columnId,c=e.desc,l=e.multi,s=r.allColumns,f=r.disableMultiSort,p=r.disableSortRemove,d=r.disableMultiRemove,h=r.maxMultiSortColCount,m=void 0===h?Number.MAX_SAFE_INTEGER:h,g=t.sortBy,v=s.find((function(t){return t.id===a})).sortDescFirst,y=g.find((function(t){return t.id===a})),b=g.findIndex((function(t){return t.id===a})),w=null!=c,x=[];return"toggle"!=(i=!f&&l?y?"toggle":"add":b!==g.length-1||1!==g.length?"replace":y?"toggle":"replace")||p||w||l&&d||!(y&&y.desc&&!v||!y.desc&&v)||(i="remove"),"replace"===i?x=[{id:a,desc:w?c:v}]:"add"===i?(x=[].concat(g,[{id:a,desc:w?c:v}])).splice(0,x.length-m):"toggle"===i?x=g.map((function(t){return t.id===a?o({},t,{desc:w?c:!y.desc}):t})):"remove"===i&&(x=g.filter((function(t){return t.id!==a}))),o({},t,{sortBy:x})}}function Xt(t){var n=t.data,r=t.rows,o=t.flatRows,i=t.allColumns,a=t.orderByFn,c=void 0===a?Kt:a,l=t.sortTypes,s=t.manualSortBy,f=t.defaultCanSort,d=t.disableSortBy,h=t.flatHeaders,g=t.state.sortBy,y=t.dispatch,w=t.plugins,x=t.getHooks,_=t.autoResetSortBy,S=void 0===_||_;m(w,["useFilters","useGlobalFilter","useGroupBy","usePivotColumns"],"useSortBy");var k=e.useCallback((function(t){y({type:u.setSortBy,sortBy:t})}),[y]),O=e.useCallback((function(t,e,n){y({type:u.toggleSortBy,columnId:t,desc:e,multi:n})}),[y]),E=v(t);h.forEach((function(t){var e=t.accessor,n=t.canSort,r=t.disableSortBy,o=t.id,i=e?R(!0!==r&&void 0,!0!==d&&void 0,!0):R(f,n,!1);t.canSort=i,t.canSort&&(t.toggleSortBy=function(e,n){return O(t.id,e,n)},t.clearSortBy=function(){y({type:u.clearSortBy,columnId:t.id})}),t.getSortByToggleProps=p(x().getSortByToggleProps,{instance:E(),column:t});var a=g.find((function(t){return t.id===o}));t.isSorted=!!a,t.sortedIndex=g.findIndex((function(t){return t.id===o})),t.isSortedDesc=t.isSorted?a.desc:void 0}));var C=e.useMemo((function(){if(s||!g.length)return[r,o];var t=[],e=g.filter((function(t){return i.find((function(e){return e.id===t.id}))}));return[function n(r){var o=c(r,e.map((function(t){var e=i.find((function(e){return e.id===t.id}));if(!e)throw new Error("React-Table: Could not find a column with id: "+t.id+" while sorting");var n=e.sortType,r=z(n)||(l||{})[n]||Zt[n];if(!r)throw new Error("React-Table: Could not find a valid sortType of '"+n+"' for column '"+t.id+"'.");return function(e,n){return r(e,n,t.id,t.desc)}})),e.map((function(t){var e=i.find((function(e){return e.id===t.id}));return e&&e.sortInverted?t.desc:!t.desc})));return o.forEach((function(e){t.push(e),e.subRows&&0!==e.subRows.length&&(e.subRows=n(e.subRows))})),o}(r),t]}),[s,g,r,o,i,c,l]),j=C[0],L=C[1],P=v(S);b((function(){P()&&y({type:u.resetSortBy})}),[s?null:n]),Object.assign(t,{preSortedRows:r,preSortedFlatRows:o,sortedRows:j,sortedFlatRows:L,rows:j,flatRows:L,setSortBy:k,toggleSortBy:O})}function Kt(t,e,n){return[].concat(t).sort((function(t,r){for(var o=0;o<e.length;o+=1){var i=e[o],a=!1===n[o]||"desc"===n[o],u=i(t,r);if(0!==u)return a?-u:u}return n[0]?t.index-r.index:r.index-t.index}))}u.resetPage="resetPage",u.gotoPage="gotoPage",u.setPageSize="setPageSize";var Qt=function(t){t.stateReducers.push(Jt),t.useInstance.push(te)};function Jt(t,e,n,r){if(e.type===u.init)return o({pageSize:10,pageIndex:0},t);if(e.type===u.resetPage)return o({},t,{pageIndex:r.initialState.pageIndex||0});if(e.type===u.gotoPage){var i=r.pageCount,a=r.page,c=g(e.pageIndex,t.pageIndex),l=!1;return c>t.pageIndex?l=-1===i?a.length>=t.pageSize:c<i:c<t.pageIndex&&(l=c>-1),l?o({},t,{pageIndex:c}):t}if(e.type===u.setPageSize){var s=e.pageSize,f=t.pageSize*t.pageIndex;return o({},t,{pageIndex:Math.floor(f/s),pageSize:s})}}function te(t){var n=t.rows,r=t.autoResetPage,o=void 0===r||r,i=t.manualExpandedKey,a=void 0===i?"expanded":i,c=t.plugins,l=t.pageCount,s=t.paginateExpandedRows,f=void 0===s||s,p=t.expandSubRows,d=void 0===p||p,h=t.state,g=h.pageSize,y=h.pageIndex,w=h.expanded,x=h.globalFilter,_=h.filters,S=h.groupBy,k=h.sortBy,O=t.dispatch,E=t.data,R=t.manualPagination;m(c,["useGlobalFilter","useFilters","useGroupBy","useSortBy","useExpanded"],"usePagination");var z=v(o);b((function(){z()&&O({type:u.resetPage})}),[O,R?null:E,x,_,S,k]);var C=R?l:Math.ceil(n.length/g),L=e.useMemo((function(){return C>0?[].concat(new Array(C)).fill(null).map((function(t,e){return e})):[]}),[C]),P=e.useMemo((function(){var t;if(R)t=n;else{var e=g*y,r=e+g;t=n.slice(e,r)}return f?t:j(t,{manualExpandedKey:a,expanded:w,expandSubRows:d})}),[d,w,a,R,y,g,f,n]),I=y>0,T=-1===C?P.length>=g:y<C-1,A=e.useCallback((function(t){O({type:u.gotoPage,pageIndex:t})}),[O]),N=e.useCallback((function(){return A((function(t){return t-1}))}),[A]),G=e.useCallback((function(){return A((function(t){return t+1}))}),[A]),M=e.useCallback((function(t){O({type:u.setPageSize,pageSize:t})}),[O]);Object.assign(t,{pageOptions:L,pageCount:C,page:P,canPreviousPage:I,canNextPage:T,gotoPage:A,previousPage:N,nextPage:G,setPageSize:M})}Qt.pluginName="usePagination",u.resetPivot="resetPivot",u.togglePivot="togglePivot";var ee=function(t){t.getPivotToggleProps=[re],t.stateReducers.push(oe),t.useInstanceAfterData.push(ie),t.allColumns.push(ae),t.accessValue.push(ue),t.materializedColumns.push(ce),t.materializedColumnsDeps.push(le),t.visibleColumns.push(se),t.visibleColumnsDeps.push(fe),t.useInstance.push(pe),t.prepareRow.push(de)};ee.pluginName="usePivotColumns";var ne=[],re=function(t,e){var n=e.header;return[t,{onClick:n.canPivot?function(t){t.persist(),n.togglePivot()}:void 0,style:{cursor:n.canPivot?"pointer":void 0},title:"Toggle Pivot"}]};function oe(t,e,n,r){if(e.type===u.init)return o({pivotColumns:ne},t);if(e.type===u.resetPivot)return o({},t,{pivotColumns:r.initialState.pivotColumns||ne});if(e.type===u.togglePivot){var i=e.columnId,a=e.value,c=void 0!==a?a:!t.pivotColumns.includes(i);return o({},t,c?{pivotColumns:[].concat(t.pivotColumns,[i])}:{pivotColumns:t.pivotColumns.filter((function(t){return t!==i}))})}}function ie(t){t.allColumns.forEach((function(e){e.isPivotSource=t.state.pivotColumns.includes(e.id)}))}function ae(t,e){var n=e.instance;return t.forEach((function(t){t.isPivotSource=n.state.pivotColumns.includes(t.id),t.uniqueValues=new Set})),t}function ue(t,e){var n=e.column;return n.uniqueValues&&void 0!==t&&n.uniqueValues.add(t),t}function ce(t,e){var n=e.instance,r=n.allColumns,i=n.state;if(!i.pivotColumns.length||!i.groupBy||!i.groupBy.length)return t;var a=i.pivotColumns.map((function(t){return r.find((function(e){return e.id===t}))})).filter(Boolean),u=r.filter((function(t){return!t.isPivotSource&&!i.groupBy.includes(t.id)&&!i.pivotColumns.includes(t.id)})),c=S(function t(e,n,r){void 0===e&&(e=0),void 0===r&&(r=[]);var i=a[e];return i?Array.from(i.uniqueValues).sort().map((function(a){var u=o({},i,{Header:i.PivotHeader||"string"==typeof i.header?i.Header+": "+a:a,isPivotGroup:!0,parent:n,depth:e,id:n?n.id+"."+i.id+"."+a:i.id+"."+a,pivotValue:a});return u.columns=t(e+1,u,[].concat(r,[function(t){return t.values[i.id]===a}])),u})):u.map((function(t){return o({},t,{canPivot:!1,isPivoted:!0,parent:n,depth:e,id:""+(n?n.id+"."+t.id:t.id),accessor:function(e,n,o){if(r.every((function(t){return t(o)})))return o.values[t.id]}})}))}());return[].concat(t,c)}function le(t,e){var n=e.instance.state,r=n.pivotColumns,o=n.groupBy;return[].concat(t,[r,o])}function se(t,e){var n=e.instance.state;return t=t.filter((function(t){return!t.isPivotSource})),n.pivotColumns.length&&n.groupBy&&n.groupBy.length&&(t=t.filter((function(t){return t.isGrouped||t.isPivoted}))),t}function fe(t,e){var n=e.instance;return[].concat(t,[n.state.pivotColumns,n.state.groupBy])}function pe(t){var e=t.columns,n=t.allColumns,r=t.flatHeaders,o=t.getHooks,i=t.plugins,a=t.dispatch,c=t.autoResetPivot,l=void 0===c||c,s=t.manaulPivot,f=t.disablePivot,d=t.defaultCanPivot;m(i,["useGroupBy"],"usePivotColumns");var h=v(t);n.forEach((function(e){var n=e.accessor,r=e.defaultPivot,o=e.disablePivot;e.canPivot=n?R(e.canPivot,!0!==o&&void 0,!0!==f&&void 0,!0):R(e.canPivot,r,d,!1),e.canPivot&&(e.togglePivot=function(){return t.togglePivot(e.id)}),e.Aggregated=e.Aggregated||e.Cell})),r.forEach((function(t){t.getPivotToggleProps=p(o().getPivotToggleProps,{instance:h(),header:t})}));var g=v(l);b((function(){g()&&a({type:u.resetPivot})}),[a,s?null:e]),Object.assign(t,{togglePivot:function(t,e){a({type:u.togglePivot,columnId:t,value:e})}})}function de(t){t.allCells.forEach((function(t){t.isPivoted=t.column.isPivoted}))}u.resetSelectedRows="resetSelectedRows",u.toggleAllRowsSelected="toggleAllRowsSelected",u.toggleRowSelected="toggleRowSelected",u.toggleAllPageRowsSelected="toggleAllPageRowsSelected";var he=function(t){t.getToggleRowSelectedProps=[me],t.getToggleAllRowsSelectedProps=[ge],t.getToggleAllPageRowsSelectedProps=[ve],t.stateReducers.push(ye),t.useInstance.push(be),t.prepareRow.push(we)};he.pluginName="useRowSelect";var me=function(t,e){var n=e.instance,r=e.row,o=n.manualRowSelectedKey,i=void 0===o?"isSelected":o;return[t,{onChange:function(t){r.toggleRowSelected(t.target.checked)},style:{cursor:"pointer"},checked:!(!r.original||!r.original[i])||r.isSelected,title:"Toggle Row Selected",indeterminate:r.isSomeSelected}]},ge=function(t,e){var n=e.instance;return[t,{onChange:function(t){n.toggleAllRowsSelected(t.target.checked)},style:{cursor:"pointer"},checked:n.isAllRowsSelected,title:"Toggle All Rows Selected",indeterminate:Boolean(!n.isAllRowsSelected&&Object.keys(n.state.selectedRowIds).length)}]},ve=function(t,e){var n=e.instance;return[t,{onChange:function(t){n.toggleAllPageRowsSelected(t.target.checked)},style:{cursor:"pointer"},checked:n.isAllPageRowsSelected,title:"Toggle All Current Page Rows Selected",indeterminate:Boolean(!n.isAllPageRowsSelected&&n.page.some((function(t){var e=t.id;return n.state.selectedRowIds[e]})))}]};function ye(t,e,n,r){if(e.type===u.init)return o({selectedRowIds:{}},t);if(e.type===u.resetSelectedRows)return o({},t,{selectedRowIds:r.initialState.selectedRowIds||{}});if(e.type===u.toggleAllRowsSelected){var i=e.value,a=r.isAllRowsSelected,c=r.rowsById,l=r.nonGroupedRowsById,s=void 0===l?c:l,f=void 0!==i?i:!a,p=Object.assign({},t.selectedRowIds);return f?Object.keys(s).forEach((function(t){p[t]=!0})):Object.keys(s).forEach((function(t){delete p[t]})),o({},t,{selectedRowIds:p})}if(e.type===u.toggleRowSelected){var d=e.id,h=e.value,m=r.rowsById,g=r.selectSubRows,v=void 0===g||g,y=r.getSubRows,b=t.selectedRowIds[d],w=void 0!==h?h:!b;if(b===w)return t;var x=o({},t.selectedRowIds);return function t(e){var n=m[e];if(n&&(n.isGrouped||(w?x[e]=!0:delete x[e]),v&&y(n)))return y(n).forEach((function(e){return t(e.id)}))}(d),o({},t,{selectedRowIds:x})}if(e.type===u.toggleAllPageRowsSelected){var _=e.value,S=r.page,k=r.rowsById,O=r.selectSubRows,E=void 0===O||O,R=r.isAllPageRowsSelected,z=r.getSubRows,C=void 0!==_?_:!R,j=o({},t.selectedRowIds);return S.forEach((function(t){return function t(e){var n=k[e];if(n.isGrouped||(C?j[e]=!0:delete j[e]),E&&z(n))return z(n).forEach((function(e){return t(e.id)}))}(t.id)})),o({},t,{selectedRowIds:j})}return t}function be(t){var n=t.data,r=t.rows,o=t.getHooks,i=t.plugins,a=t.rowsById,c=t.nonGroupedRowsById,l=void 0===c?a:c,s=t.autoResetSelectedRows,f=void 0===s||s,d=t.state.selectedRowIds,h=t.selectSubRows,g=void 0===h||h,y=t.dispatch,w=t.page,x=t.getSubRows;m(i,["useFilters","useGroupBy","useSortBy","useExpanded","usePagination"],"useRowSelect");var _=e.useMemo((function(){var t=[];return r.forEach((function(e){var n=g?function t(e,n,r){if(n[e.id])return!0;var o=r(e);if(o&&o.length){var i=!0,a=!1;return o.forEach((function(e){a&&!i||(t(e,n,r)?a=!0:i=!1)})),!!i||!!a&&null}return!1}(e,d,x):!!d[e.id];e.isSelected=!!n,e.isSomeSelected=null===n,n&&t.push(e)})),t}),[r,g,d,x]),S=Boolean(Object.keys(l).length&&Object.keys(d).length),k=S;S&&Object.keys(l).some((function(t){return!d[t]}))&&(S=!1),S||w&&w.length&&w.some((function(t){var e=t.id;return!d[e]}))&&(k=!1);var O=v(f);b((function(){O()&&y({type:u.resetSelectedRows})}),[y,n]);var E=e.useCallback((function(t){return y({type:u.toggleAllRowsSelected,value:t})}),[y]),R=e.useCallback((function(t){return y({type:u.toggleAllPageRowsSelected,value:t})}),[y]),z=e.useCallback((function(t,e){return y({type:u.toggleRowSelected,id:t,value:e})}),[y]),C=v(t),j=p(o().getToggleAllRowsSelectedProps,{instance:C()}),L=p(o().getToggleAllPageRowsSelectedProps,{instance:C()});Object.assign(t,{selectedFlatRows:_,isAllRowsSelected:S,isAllPageRowsSelected:k,toggleRowSelected:z,toggleAllRowsSelected:E,getToggleAllRowsSelectedProps:j,getToggleAllPageRowsSelectedProps:L,toggleAllPageRowsSelected:R})}function we(t,e){var n=e.instance;t.toggleRowSelected=function(e){return n.toggleRowSelected(t.id,e)},t.getToggleRowSelectedProps=p(n.getHooks().getToggleRowSelectedProps,{instance:n,row:t})}var xe=function(t){return{}},_e=function(t){return{}};u.setRowState="setRowState",u.setCellState="setCellState",u.resetRowState="resetRowState";var Se=function(t){t.stateReducers.push(ke),t.useInstance.push(Oe),t.prepareRow.push(Ee)};function ke(t,e,n,r){var i=r.initialRowStateAccessor,a=void 0===i?xe:i,c=r.initialCellStateAccessor,l=void 0===c?_e:c,s=r.rowsById;if(e.type===u.init)return o({rowState:{}},t);if(e.type===u.resetRowState)return o({},t,{rowState:r.initialState.rowState||{}});if(e.type===u.setRowState){var f,p=e.rowId,d=e.value,h=void 0!==t.rowState[p]?t.rowState[p]:a(s[p]);return o({},t,{rowState:o({},t.rowState,(f={},f[p]=g(d,h),f))})}if(e.type===u.setCellState){var m,v,y,b,w,x=e.rowId,_=e.columnId,S=e.value,k=void 0!==t.rowState[x]?t.rowState[x]:a(s[x]),O=void 0!==(null==k||null==(m=k.cellState)?void 0:m[_])?k.cellState[_]:l(null==(v=s[x])||null==(y=v.cells)?void 0:y.find((function(t){return t.column.id===_})));return o({},t,{rowState:o({},t.rowState,(w={},w[x]=o({},k,{cellState:o({},k.cellState||{},(b={},b[_]=g(S,O),b))}),w))})}}function Oe(t){var n=t.autoResetRowState,r=void 0===n||n,o=t.data,i=t.dispatch,a=e.useCallback((function(t,e){return i({type:u.setRowState,rowId:t,value:e})}),[i]),c=e.useCallback((function(t,e,n){return i({type:u.setCellState,rowId:t,columnId:e,value:n})}),[i]),l=v(r);b((function(){l()&&i({type:u.resetRowState})}),[o]),Object.assign(t,{setRowState:a,setCellState:c})}function Ee(t,e){var n=e.instance,r=n.initialRowStateAccessor,o=void 0===r?xe:r,i=n.initialCellStateAccessor,a=void 0===i?_e:i,u=n.state.rowState;t&&(t.state=void 0!==u[t.id]?u[t.id]:o(t),t.setState=function(e){return n.setRowState(t.id,e)},t.cells.forEach((function(e){t.state.cellState||(t.state.cellState={}),e.state=void 0!==t.state.cellState[e.column.id]?t.state.cellState[e.column.id]:a(e),e.setState=function(r){return n.setCellState(t.id,e.column.id,r)}})))}Se.pluginName="useRowState",u.resetColumnOrder="resetColumnOrder",u.setColumnOrder="setColumnOrder";var Re=function(t){t.stateReducers.push(ze),t.visibleColumnsDeps.push((function(t,e){var n=e.instance;return[].concat(t,[n.state.columnOrder])})),t.visibleColumns.push(Ce),t.useInstance.push(je)};function ze(t,e,n,r){return e.type===u.init?o({columnOrder:[]},t):e.type===u.resetColumnOrder?o({},t,{columnOrder:r.initialState.columnOrder||[]}):e.type===u.setColumnOrder?o({},t,{columnOrder:g(e.columnOrder,t.columnOrder)}):void 0}function Ce(t,e){var n=e.instance.state.columnOrder;if(!n||!n.length)return t;for(var r=[].concat(n),o=[].concat(t),i=[],a=function(){var t=r.shift(),e=o.findIndex((function(e){return e.id===t}));e>-1&&i.push(o.splice(e,1)[0])};o.length&&r.length;)a();return[].concat(i,o)}function je(t){var n=t.dispatch;t.setColumnOrder=e.useCallback((function(t){return n({type:u.setColumnOrder,columnOrder:t})}),[n])}Re.pluginName="useColumnOrder",s.canResize=!0,u.columnStartResizing="columnStartResizing",u.columnResizing="columnResizing",u.columnDoneResizing="columnDoneResizing",u.resetResize="resetResize";var Le=function(t){t.getResizerProps=[Pe],t.getHeaderProps.push({style:{position:"relative"}}),t.stateReducers.push(Ie),t.useInstance.push(Ae),t.useInstanceBeforeDimensions.push(Te)},Pe=function(t,e){var n=e.instance,r=e.header,o=n.dispatch,i=function(t,e){var n=!1;if("touchstart"===t.type){if(t.touches&&t.touches.length>1)return;n=!0}var r,i,a=function(t){var e=[];return function t(n){n.columns&&n.columns.length&&n.columns.map(t),e.push(n)}(t),e}(e).map((function(t){return[t.id,t.totalWidth]})),c=n?Math.round(t.touches[0].clientX):t.clientX,l=function(){window.cancelAnimationFrame(r),r=null,o({type:u.columnDoneResizing})},s=function(){window.cancelAnimationFrame(r),r=null,o({type:u.columnResizing,clientX:i})},f=function(t){i=t,r||(r=window.requestAnimationFrame(s))},p={mouse:{moveEvent:"mousemove",moveHandler:function(t){return f(t.clientX)},upEvent:"mouseup",upHandler:function(t){document.removeEventListener("mousemove",p.mouse.moveHandler),document.removeEventListener("mouseup",p.mouse.upHandler),l()}},touch:{moveEvent:"touchmove",moveHandler:function(t){return t.cancelable&&(t.preventDefault(),t.stopPropagation()),f(t.touches[0].clientX),!1},upEvent:"touchend",upHandler:function(t){document.removeEventListener(p.touch.moveEvent,p.touch.moveHandler),document.removeEventListener(p.touch.upEvent,p.touch.moveHandler),l()}}},d=n?p.touch:p.mouse,h=!!function(){if("boolean"==typeof T)return T;var t=!1;try{var e={get passive(){return t=!0,!1}};window.addEventListener("test",null,e),window.removeEventListener("test",null,e)}catch(e){t=!1}return T=t}()&&{passive:!1};document.addEventListener(d.moveEvent,d.moveHandler,h),document.addEventListener(d.upEvent,d.upHandler,h),o({type:u.columnStartResizing,columnId:e.id,columnWidth:e.totalWidth,headerIdWidths:a,clientX:c})};return[t,{onMouseDown:function(t){return t.persist()||i(t,r)},onTouchStart:function(t){return t.persist()||i(t,r)},style:{cursor:"col-resize"},draggable:!1,role:"separator"}]};function Ie(t,e){if(e.type===u.init)return o({columnResizing:{columnWidths:{}}},t);if(e.type===u.resetResize)return o({},t,{columnResizing:{columnWidths:{}}});if(e.type===u.columnStartResizing){var n=e.clientX,r=e.columnId,i=e.columnWidth,a=e.headerIdWidths;return o({},t,{columnResizing:o({},t.columnResizing,{startX:n,headerIdWidths:a,columnWidth:i,isResizingColumn:r})})}if(e.type===u.columnResizing){var c=e.clientX,l=t.columnResizing,s=l.startX,f=l.columnWidth,p=l.headerIdWidths,d=(c-s)/f,h={};return(void 0===p?[]:p).forEach((function(t){var e=t[0],n=t[1];h[e]=Math.max(n+n*d,0)})),o({},t,{columnResizing:o({},t.columnResizing,{columnWidths:o({},t.columnResizing.columnWidths,{},h)})})}return e.type===u.columnDoneResizing?o({},t,{columnResizing:o({},t.columnResizing,{startX:null,isResizingColumn:null})}):void 0}Le.pluginName="useResizeColumns";var Te=function(t){var e=t.flatHeaders,n=t.disableResizing,r=t.getHooks,o=t.state.columnResizing,i=v(t);e.forEach((function(t){var e=R(!0!==t.disableResizing&&void 0,!0!==n&&void 0,!0);t.canResize=e,t.width=o.columnWidths[t.id]||t.originalWidth||t.width,t.isResizing=o.isResizingColumn===t.id,e&&(t.getResizerProps=p(r().getResizerProps,{instance:i(),header:t}))}))};function Ae(t){var n=t.plugins,r=t.dispatch,o=t.autoResetResize,i=void 0===o||o,a=t.columns;m(n,["useAbsoluteLayout"],"useResizeColumns");var c=v(i);b((function(){c()&&r({type:u.resetResize})}),[a]);var l=e.useCallback((function(){return r({type:u.resetResize})}),[r]);Object.assign(t,{resetResizing:l})}var Ne={position:"absolute",top:0},Ge=function(t){t.getTableBodyProps.push(Me),t.getRowProps.push(Me),t.getHeaderGroupProps.push(Me),t.getFooterGroupProps.push(Me),t.getHeaderProps.push((function(t,e){var n=e.column;return[t,{style:o({},Ne,{left:n.totalLeft+"px",width:n.totalWidth+"px"})}]})),t.getCellProps.push((function(t,e){var n=e.cell;return[t,{style:o({},Ne,{left:n.column.totalLeft+"px",width:n.column.totalWidth+"px"})}]})),t.getFooterProps.push((function(t,e){var n=e.column;return[t,{style:o({},Ne,{left:n.totalLeft+"px",width:n.totalWidth+"px"})}]}))};Ge.pluginName="useAbsoluteLayout";var Me=function(t,e){return[t,{style:{position:"relative",width:e.instance.totalColumnsWidth+"px"}}]},Fe={display:"inline-block",boxSizing:"border-box"},De=function(t,e){return[t,{style:{display:"flex",width:e.instance.totalColumnsWidth+"px"}}]},Be=function(t){t.getRowProps.push(De),t.getHeaderGroupProps.push(De),t.getFooterGroupProps.push(De),t.getHeaderProps.push((function(t,e){var n=e.column;return[t,{style:o({},Fe,{width:n.totalWidth+"px"})}]})),t.getCellProps.push((function(t,e){var n=e.cell;return[t,{style:o({},Fe,{width:n.column.totalWidth+"px"})}]})),t.getFooterProps.push((function(t,e){var n=e.column;return[t,{style:o({},Fe,{width:n.totalWidth+"px"})}]}))};function He(t){t.getTableProps.push(We),t.getRowProps.push(Ue),t.getHeaderGroupProps.push(Ue),t.getFooterGroupProps.push(Ue),t.getHeaderProps.push(qe),t.getCellProps.push(Ze),t.getFooterProps.push($e)}Be.pluginName="useBlockLayout",He.pluginName="useFlexLayout";var We=function(t,e){return[t,{style:{minWidth:e.instance.totalColumnsMinWidth+"px"}}]},Ue=function(t,e){return[t,{style:{display:"flex",flex:"1 0 auto",minWidth:e.instance.totalColumnsMinWidth+"px"}}]},qe=function(t,e){var n=e.column;return[t,{style:{boxSizing:"border-box",flex:n.totalFlexWidth?n.totalFlexWidth+" 0 auto":void 0,minWidth:n.totalMinWidth+"px",width:n.totalWidth+"px"}}]},Ze=function(t,e){var n=e.cell;return[t,{style:{boxSizing:"border-box",flex:n.column.totalFlexWidth+" 0 auto",minWidth:n.column.totalMinWidth+"px",width:n.column.totalWidth+"px"}}]},$e=function(t,e){var n=e.column;return[t,{style:{boxSizing:"border-box",flex:n.totalFlexWidth?n.totalFlexWidth+" 0 auto":void 0,minWidth:n.totalMinWidth+"px",width:n.totalWidth+"px"}}]};function Ve(t){t.stateReducers.push(Qe),t.getTableProps.push(Ye),t.getHeaderProps.push(Xe),t.getRowProps.push(Ke)}u.columnStartResizing="columnStartResizing",u.columnResizing="columnResizing",u.columnDoneResizing="columnDoneResizing",u.resetResize="resetResize",Ve.pluginName="useGridLayout";var Ye=function(t,e){var n=e.instance;return[t,{style:{display:"grid",gridTemplateColumns:n.visibleColumns.map((function(t){var e;return n.state.gridLayout.columnWidths[t.id]?n.state.gridLayout.columnWidths[t.id]+"px":(null==(e=n.state.columnResizing)?void 0:e.isResizingColumn)?n.state.gridLayout.startWidths[t.id]+"px":"number"==typeof t.width?t.width+"px":t.width})).join(" ")}}]},Xe=function(t,e){var n=e.column;return[t,{id:"header-cell-"+n.id,style:{position:"sticky",gridColumn:"span "+n.totalVisibleHeaderCount}}]},Ke=function(t,e){var n=e.row;return n.isExpanded?[t,{style:{gridColumn:"1 / "+(n.cells.length+1)}}]:[t,{}]};function Qe(t,e,n,r){if(e.type===u.init)return o({gridLayout:{columnWidths:{}}},t);if(e.type===u.resetResize)return o({},t,{gridLayout:{columnWidths:{}}});if(e.type===u.columnStartResizing){var i=e.columnId,a=e.headerIdWidths,c=Je(i);if(void 0!==c){var l=r.visibleColumns.reduce((function(t,e){var n;return o({},t,((n={})[e.id]=Je(e.id),n))}),{}),s=r.visibleColumns.reduce((function(t,e){var n;return o({},t,((n={})[e.id]=e.minWidth,n))}),{}),f=r.visibleColumns.reduce((function(t,e){var n;return o({},t,((n={})[e.id]=e.maxWidth,n))}),{}),p=a.map((function(t){var e=t[0];return[e,Je(e)]}));return o({},t,{gridLayout:o({},t.gridLayout,{startWidths:l,minWidths:s,maxWidths:f,headerIdGridWidths:p,columnWidth:c})})}return t}if(e.type===u.columnResizing){var d=e.clientX,h=t.columnResizing.startX,m=t.gridLayout,g=m.columnWidth,v=m.minWidths,y=m.maxWidths,b=m.headerIdGridWidths,w=(d-h)/g,x={};return(void 0===b?[]:b).forEach((function(t){var e=t[0],n=t[1];x[e]=Math.min(Math.max(v[e],n+n*w),y[e])})),o({},t,{gridLayout:o({},t.gridLayout,{columnWidths:o({},t.gridLayout.columnWidths,{},x)})})}return e.type===u.columnDoneResizing?o({},t,{gridLayout:o({},t.gridLayout,{startWidths:{},minWidths:{},maxWidths:{}})}):void 0}function Je(t){var e,n=null==(e=document.getElementById("header-cell-"+t))?void 0:e.offsetWidth;if(void 0!==n)return n}t._UNSTABLE_usePivotColumns=ee,t.actions=u,t.defaultColumn=s,t.defaultGroupByFn=Bt,t.defaultOrderByFn=Kt,t.defaultRenderer=c,t.emptyRenderer=l,t.ensurePluginOrder=m,t.flexRender=x,t.functionalUpdate=g,t.loopHooks=h,t.makePropGetter=p,t.makeRenderer=w,t.reduceHooks=d,t.safeUseLayoutEffect=y,t.useAbsoluteLayout=Ge,t.useAsyncDebounce=function(t,n){void 0===n&&(n=0);var o=e.useRef({}),i=v(t),a=v(n);return e.useCallback(function(){var t=r(regeneratorRuntime.mark((function t(){var e,n,u,c=arguments;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:for(e=c.length,n=new Array(e),u=0;u<e;u++)n[u]=c[u];return o.current.promise||(o.current.promise=new Promise((function(t,e){o.current.resolve=t,o.current.reject=e}))),o.current.timeout&&clearTimeout(o.current.timeout),o.current.timeout=setTimeout(r(regeneratorRuntime.mark((function t(){return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return delete o.current.timeout,t.prev=1,t.t0=o.current,t.next=5,i().apply(void 0,n);case 5:t.t1=t.sent,t.t0.resolve.call(t.t0,t.t1),t.next=12;break;case 9:t.prev=9,t.t2=t.catch(1),o.current.reject(t.t2);case 12:return t.prev=12,delete o.current.promise,t.finish(12);case 15:case"end":return t.stop()}}),t,null,[[1,9,12,15]])}))),a()),t.abrupt("return",o.current.promise);case 5:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}(),[i,a])},t.useBlockLayout=Be,t.useColumnOrder=Re,t.useExpanded=ut,t.useFilters=kt,t.useFlexLayout=He,t.useGetLatest=v,t.useGlobalFilter=Rt,t.useGridLayout=Ve,t.useGroupBy=Tt,t.useMountedLayoutEffect=b,t.usePagination=Qt,t.useResizeColumns=Le,t.useRowSelect=he,t.useRowState=Se,t.useSortBy=$t,t.useTable=function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];t=ot(t),r=[Z].concat(r);var a=v(e.useRef({}).current);Object.assign(a(),o({},t,{plugins:r,hooks:q()})),r.filter(Boolean).forEach((function(t){t(a().hooks)}));var c=v(a().hooks);a().getHooks=c,delete a().hooks,Object.assign(a(),d(c().useOptions,ot(t)));var l=a(),s=l.data,f=l.columns,m=l.initialState,g=l.defaultColumn,y=l.getSubRows,b=l.getRowId,x=l.stateReducer,E=l.useControlledState,R=v(x),z=e.useCallback((function(t,e){if(!e.type)throw console.info({action:e}),new Error("Unknown Action 👆");return[].concat(c().stateReducers,Array.isArray(R())?R():[R()]).reduce((function(n,r){return r(n,e,t,a())||n}),t)}),[c,R,a]),C=e.useReducer(z,void 0,(function(){return z(m,{type:u.init})})),j=C[0],L=C[1],P=d([].concat(c().useControlledState,[E]),j,{instance:a()});Object.assign(a(),{state:P,dispatch:L});var I=e.useMemo((function(){return _(d(c().columns,f,{instance:a()}))}),[c,a,f].concat(d(c().columnsDeps,[],{instance:a()})));a().columns=I;var T=e.useMemo((function(){return d(c().allColumns,S(I),{instance:a()}).map(k)}),[I,c,a].concat(d(c().allColumnsDeps,[],{instance:a()})));a().allColumns=T;var A=e.useMemo((function(){for(var t=[],e=[],n={},r=[].concat(T);r.length;){var o=r.shift();at({data:s,rows:t,flatRows:e,rowsById:n,column:o,getRowId:b,getSubRows:y,accessValueHooks:c().accessValue,getInstance:a})}return[t,e,n]}),[T,s,b,y,c,a]),N=A[0],G=A[1],M=A[2];Object.assign(a(),{rows:N,initialRows:[].concat(N),flatRows:G,rowsById:M}),h(c().useInstanceAfterData,a());var F=e.useMemo((function(){return d(c().visibleColumns,T,{instance:a()}).map((function(t){return O(t,g)}))}),[c,T,a,g].concat(d(c().visibleColumnsDeps,[],{instance:a()})));T=e.useMemo((function(){var t=[].concat(F);return T.forEach((function(e){t.find((function(t){return t.id===e.id}))||t.push(e)})),t}),[T,F]),a().allColumns=T;var D=e.useMemo((function(){return d(c().headerGroups,function(t,e,n){void 0===n&&(n=function(){return{}});for(var r=[],i=t,a=0,u=function(){return a++},c=function(){var t={headers:[]},a=[],c=i.some((function(t){return t.parent}));i.forEach((function(r){var i,l=[].concat(a).reverse()[0];c&&(i=r.parent?o({},r.parent,{originalId:r.parent.id,id:r.parent.id+"_"+u(),headers:[r]},n(r)):O(o({originalId:r.id+"_placeholder",id:r.id+"_placeholder_"+u(),placeholderOf:r,headers:[r]},n(r)),e),l&&l.originalId===i.originalId?l.headers.push(r):a.push(i)),t.headers.push(r)})),r.push(t),i=a};i.length;)c();return r.reverse()}(F,g),a())}),[c,F,g,a].concat(d(c().headerGroupsDeps,[],{instance:a()})));a().headerGroups=D;var B=e.useMemo((function(){return D.length?D[0].headers:[]}),[D]);a().headers=B,a().flatHeaders=D.reduce((function(t,e){return[].concat(t,e.headers)}),[]),h(c().useInstanceBeforeDimensions,a());var H=F.filter((function(t){return t.isVisible})).map((function(t){return t.id})).sort().join("_");F=e.useMemo((function(){return F.filter((function(t){return t.isVisible}))}),[F,H]),a().visibleColumns=F;var W=it(B),U=W[0],$=W[1],V=W[2];return a().totalColumnsMinWidth=U,a().totalColumnsWidth=$,a().totalColumnsMaxWidth=V,h(c().useInstance,a()),[].concat(a().flatHeaders,a().allColumns).forEach((function(t){t.render=w(a(),t),t.getHeaderProps=p(c().getHeaderProps,{instance:a(),column:t}),t.getFooterProps=p(c().getFooterProps,{instance:a(),column:t})})),a().headerGroups=e.useMemo((function(){return D.filter((function(t,e){return t.headers=t.headers.filter((function(t){return t.headers?function t(e){return e.filter((function(e){return e.headers?t(e.headers):e.isVisible})).length}(t.headers):t.isVisible})),!!t.headers.length&&(t.getHeaderGroupProps=p(c().getHeaderGroupProps,{instance:a(),headerGroup:t,index:e}),t.getFooterGroupProps=p(c().getFooterGroupProps,{instance:a(),headerGroup:t,index:e}),!0)}))}),[D,a,c]),a().footerGroups=[].concat(a().headerGroups).reverse(),a().prepareRow=e.useCallback((function(t){t.getRowProps=p(c().getRowProps,{instance:a(),row:t}),t.allCells=T.map((function(e){var n=t.values[e.id],r={column:e,row:t,value:n};return r.getCellProps=p(c().getCellProps,{instance:a(),cell:r}),r.render=w(a(),e,{row:t,cell:r,value:n}),r})),t.cells=F.map((function(e){return t.allCells.find((function(t){return t.column.id===e.id}))})),h(c().prepareRow,t,{instance:a()})}),[c,a,T,F]),a().getTableProps=p(c().getTableProps,{instance:a()}),a().getTableBodyProps=p(c().getTableBodyProps,{instance:a()}),h(c().useFinalInstance,a()),a()},Object.defineProperty(t,"__esModule",{value:!0})}(e,n(196))},521:function(t,e,n){t.exports=n(217)},196:function(t){"use strict";t.exports=window.React}},n={};function r(t){var o=n[t];if(void 0!==o)return o.exports;var i=n[t]={exports:{}};return e[t].call(i.exports,i,i.exports,r),i.exports}r.m=e,t=[],r.O=function(e,n,o,i){if(!n){var a=1/0;for(s=0;s<t.length;s++){n=t[s][0],o=t[s][1],i=t[s][2];for(var u=!0,c=0;c<n.length;c++)(!1&i||a>=i)&&Object.keys(r.O).every((function(t){return r.O[t](n[c])}))?n.splice(c--,1):(u=!1,i<a&&(a=i));if(u){t.splice(s--,1);var l=o();void 0!==l&&(e=l)}}return e}i=i||0;for(var s=t.length;s>0&&t[s-1][2]>i;s--)t[s]=t[s-1];t[s]=[n,o,i]},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,{a:e}),e},r.d=function(t,e){for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},function(){var t={328:0,72:0};r.O.j=function(e){return 0===t[e]};var e=function(e,n){var o,i,a=n[0],u=n[1],c=n[2],l=0;if(a.some((function(e){return 0!==t[e]}))){for(o in u)r.o(u,o)&&(r.m[o]=u[o]);if(c)var s=c(r)}for(e&&e(n);l<a.length;l++)i=a[l],r.o(t,i)&&t[i]&&t[i][0](),t[i]=0;return r.O(s)},n=self.webpackChunkimage_optimization=self.webpackChunkimage_optimization||[];n.forEach(e.bind(null,0)),n.push=e.bind(null,n.push.bind(n))}();var o=r.O(void 0,[72],(function(){return r(282)}));o=r.O(o)}(); assets/build/control.css 0000644 00000005533 14720461212 0011344 0 ustar 00 .image-optimization-control--list-view{align-items:center;display:flex;justify-content:flex-start;min-height:105px}.image-optimization-control--list-view.image-optimization-control--error{align-items:flex-start;justify-content:center}.image-optimization-control__buttons-wrapper{margin-block-start:8px}.image-optimization-control__buttons-wrapper :not(:last-of-type){margin-inline-end:8px}.image-optimization-control--error{flex-direction:column}.image-optimization-control--optimized{align-items:flex-start;flex-direction:column}.image-optimization-control__error-message{display:flex;flex-direction:column;font-family:Roboto,sans-serif;font-size:14px;font-weight:600;line-height:24px;margin-block-end:15px;max-width:200px}.image-optimization-control__error-title{margin-block-end:10px}.image-optimization-control__error-subtitle{color:#dc2626}.image-optimization-control__button{border-radius:4px;font-family:Roboto,sans-serif;font-weight:500}.image-optimization-control__button--optimize>.spinner{float:left;margin-block-end:0;margin-block-start:4px;margin-left:0;padding:0}.image-optimization-control--error .image-optimization-control__button--try-again,.image-optimization-control--error .image-optimization-control__button--try-again:hover{background:transparent;border-color:#dc2626;color:#dc2626}.image-optimization-control__property{margin:9px 0}.image-optimization-control .image-optimization-setting,.image-optimization-control__property:last-of-type{margin-block-end:0}.image-optimization-control--details-view .setting .image-optimization-control__property-value,.image-optimization-control__property-value{font-size:13px;font-weight:600;line-height:24px}.image-optimization-control--details-view .setting .image-optimization-control__property-value{margin:6px 3px 3px;text-align:start}.image-optimization-control--details-view .setting .image-optimization-control__property-value--button{font-weight:400;margin:0 0 0 3px}.image-optimization-control--details-view .setting .image-optimization-control__property-value--spinner{display:flex;justify-content:center;margin:25px 0 0 3px}.image-optimization-control__action-button-wrapper{display:flex;justify-content:flex-end;margin-block-start:37px;width:100%}.image-optimization-control__action-button-wrapper .button-link:not(:last-of-type){margin-inline-end:24px}.image-optimization-control--details-view .image-optimization-control__property-value--button .button-link,.image-optimization-control__action-button-wrapper .button-link{text-decoration:none}.image-optimization-control--details-view .image-optimization-control__property-value--button .button-link:hover,.image-optimization-control__action-button-wrapper .button-link:hover{background-color:transparent}.image-optimization-control__action-spinner-wrapper{align-items:center;display:flex;height:75px;justify-content:center}div .components-tooltip{max-width:165px;text-align:start} assets/build/control.asset.php 0000644 00000000212 14720461212 0012446 0 ustar 00 <?php return array('dependencies' => array('wp-a11y', 'wp-api-fetch', 'wp-escape-html', 'wp-i18n'), 'version' => 'fbafd726e64c78f54260'); assets/build/admin.asset.php 0000644 00000000252 14720461212 0012062 0 ustar 00 <?php return array('dependencies' => array('react', 'wp-api-fetch', 'wp-components', 'wp-date', 'wp-element', 'wp-i18n', 'wp-url'), 'version' => '854988ee84bc360edc11'); assets/build/style-admin.css 0000644 00000002443 14720461212 0012107 0 ustar 00 .image-optimizer__notice{border:none;padding:12px;& p{margin:0}& .notice-dismiss:before{color:#1e1e1e;content:"\f335";font:normal 22px/24px dashicons;width:24px}}.image-optimizer__notice button:not(.notice-dismiss){background:none;border:none;color:#dc2626;cursor:pointer;display:block;font-size:13px;font-style:normal;font-weight:400;letter-spacing:-.247px;line-height:150%;padding:0;text-decoration-line:underline}.image-optimizer__notice--error{background-color:#fde8ec;border-inline-start:4px solid #dc2626}.image-optimizer__notice--warning{background-color:#fef8ee;border-inline-start:4px solid #f0b849}.image-optimizer__notice--success{background-color:#eff9f1;border-inline-start:4px solid #4ab866}.image-optimizer__notice--info{background-color:#f1f6fb;border-inline-start:4px solid #0288d1}.image-optimizer__notice--pink{background-color:#fff;border:1px solid #d8d8da;border-inline-start:4px solid #ff7be5;padding-left:54px;position:relative}.image-optimizer__notice--pink b{color:#444950;font-weight:500}.image-optimizer__notice--pink a{color:#d004d4;font-weight:500;margin-inline-start:10px;text-decoration:none}.image-optimizer__notice--pink .image-optimizer__icon-block{align-items:center;background-color:#fae8ff;bottom:0;display:flex;justify-content:center;left:0;position:absolute;top:0;width:48px} assets/build/control.js 0000644 00000156414 14720461212 0011175 0 ustar 00 !function(){"use strict";var t={};function n(t){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},n(t)}function e(t,e){for(var o=0;o<e.length;o++){var r=e[o];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,(void 0,i=function(t,e){if("object"!==n(t)||null===t)return t;var o=t[Symbol.toPrimitive];if(void 0!==o){var r=o.call(t,"string");if("object"!==n(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(r.key),"symbol"===n(i)?i:String(i)),r)}var i}t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,{a:e}),e},t.d=function(n,e){for(var o in e)t.o(e,o)&&!t.o(n,o)&&Object.defineProperty(n,o,{enumerable:!0,get:e[o]})},t.o=function(t,n){return Object.prototype.hasOwnProperty.call(t,n)};var o=function(){function t(){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t),this.init()}var n,o;return n=t,(o=[{key:"init",value:function(){this.extendAttachmentDetails(),this.extendAttachmentDetailsTwoColumn()}},{key:"extendAttachmentDetails",value:function(){var t;null!==(t=wp)&&void 0!==t&&null!==(t=t.media)&&void 0!==t&&null!==(t=t.view)&&void 0!==t&&null!==(t=t.Attachment)&&void 0!==t&&t.Details&&(wp.media.view.Attachment.Details=wp.media.view.Attachment.Details.extend({template:function(t){var n=wp.media.template("attachment-details")(t);if("image"!==this.model.attributes.type)return n;var e=document.createElement("div");e.innerHTML=n;var o=this.getOptimizationControlHTML(t.compat.item);return o?(e.innerHTML+=o,e.innerHTML):e.innerHTML},getOptimizationControlHTML:function(t){var n,e=document.createElement("div");return e.innerHTML=t,null===(n=e.querySelector('input[name*="[image_optimization_modal]"]'))||void 0===n?void 0:n.value}}))}},{key:"extendAttachmentDetailsTwoColumn",value:function(){var t;null!==(t=wp)&&void 0!==t&&null!==(t=t.media)&&void 0!==t&&null!==(t=t.view)&&void 0!==t&&null!==(t=t.Attachment)&&void 0!==t&&null!==(t=t.Details)&&void 0!==t&&t.TwoColumn&&(wp.media.view.Attachment.Details.TwoColumn=wp.media.view.Attachment.Details.TwoColumn.extend({template:function(t){var n=wp.media.template("attachment-details-two-column")(t);if("image"!==this.model.attributes.type)return n;var e=document.createElement("div");e.innerHTML=n;var o=this.getOptimizationControlHTML(t.compat.item);return o?(e.querySelector(".settings").innerHTML+=o,e.innerHTML):e.innerHTML},getOptimizationControlHTML:function(t){var n,e=document.createElement("div");return e.innerHTML=t,null===(n=e.querySelector('input[name*="[image_optimization_modal]"]'))||void 0===n?void 0:n.value}}))}}])&&e(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),t}(),r=window.wp.i18n,i=window.wp.a11y,a="https://go.elementor.com/io-panel-upgrade/",c=Object.freeze({optimizeButtonSelector:".image-optimization-control__button--optimize",reoptimizeButtonSelector:".image-optimization-control__button--reoptimize",tryAgainOptimizeButtonSelector:'[data-image-optimization-action="optimize"] .image-optimization-control__button--try-again',tryAgainReoptimizeButtonSelector:'[data-image-optimization-action="reoptimize"] .image-optimization-control__button--try-again',tryAgainRestoreButtonSelector:'[data-image-optimization-action="restore"] .image-optimization-control__button--try-again',controlWrapperSelector:".image-optimization-control",controlNotOptimizedClassName:"image-optimization-control image-optimization-control--not-optimized",controlLoadingClassName:"image-optimization-control image-optimization-control--loading",controlOptimizedClassName:"image-optimization-control image-optimization-control--optimized",controlErrorClassName:"image-optimization-control image-optimization-control--error",controlWrapper:{"list-view":"image-optimization-control--list-view","meta-box":"image-optimization-control--meta-box","details-view":"image-optimization-control--details-view"},restoreButtonSelector:".image-optimization-control__button--restore-original",loadingControlsSelector:'[data-image-optimization-status="loading"]'}),u=window.wp.apiFetch,s=t.n(u);function l(t){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},l(t)}function p(t){var n="function"==typeof Map?new Map:void 0;return p=function(t){if(null===t||(e=t,-1===Function.toString.call(e).indexOf("[native code]")))return t;var e;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(t))return n.get(t);n.set(t,o)}function o(){return m(t,arguments,y(this).constructor)}return o.prototype=Object.create(t.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),g(o,t)},p(t)}function m(t,n,e){return m=f()?Reflect.construct.bind():function(t,n,e){var o=[null];o.push.apply(o,n);var r=new(Function.bind.apply(t,o));return e&&g(r,e.prototype),r},m.apply(null,arguments)}function f(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function g(t,n){return g=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},g(t,n)}function y(t){return y=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},y(t)}var h=function(t){!function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(n&&n.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),n&&g(t,n)}(i,t);var n,e,o,r=(e=i,o=f(),function(){var t,n=y(e);if(o){var r=y(this).constructor;t=Reflect.construct(n,arguments,r)}else t=n.apply(this,arguments);return function(t,n){if(n&&("object"===l(n)||"function"==typeof n))return n;if(void 0!==n)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(this,t)});function i(t){var n;return function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,i),(n=r.call(this,t)).name="APIError",n}return n=i,Object.defineProperty(n,"prototype",{writable:!1}),n}(p(Error));function v(t){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},v(t)}function d(){d=function(){return n};var t,n={},e=Object.prototype,o=e.hasOwnProperty,r=Object.defineProperty||function(t,n,e){t[n]=e.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function s(t,n,e){return Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}),t[n]}try{s({},"")}catch(t){s=function(t,n,e){return t[n]=e}}function l(t,n,e,o){var i=n&&n.prototype instanceof b?n:b,a=Object.create(i.prototype),c=new C(o||[]);return r(a,"_invoke",{value:k(t,e,c)}),a}function p(t,n,e){try{return{type:"normal",arg:t.call(n,e)}}catch(t){return{type:"throw",arg:t}}}n.wrap=l;var m="suspendedStart",f="suspendedYield",g="executing",y="completed",h={};function b(){}function _(){}function w(){}var z={};s(z,a,(function(){return this}));var O=Object.getPrototypeOf,S=O&&O(O(I([])));S&&S!==e&&o.call(S,a)&&(z=S);var x=w.prototype=b.prototype=Object.create(z);function L(t){["next","throw","return"].forEach((function(n){s(t,n,(function(t){return this._invoke(n,t)}))}))}function E(t,n){function e(r,i,a,c){var u=p(t[r],t,i);if("throw"!==u.type){var s=u.arg,l=s.value;return l&&"object"==v(l)&&o.call(l,"__await")?n.resolve(l.__await).then((function(t){e("next",t,a,c)}),(function(t){e("throw",t,a,c)})):n.resolve(l).then((function(t){s.value=t,a(s)}),(function(t){return e("throw",t,a,c)}))}c(u.arg)}var i;r(this,"_invoke",{value:function(t,o){function r(){return new n((function(n,r){e(t,o,n,r)}))}return i=i?i.then(r,r):r()}})}function k(n,e,o){var r=m;return function(i,a){if(r===g)throw new Error("Generator is already running");if(r===y){if("throw"===i)throw a;return{value:t,done:!0}}for(o.method=i,o.arg=a;;){var c=o.delegate;if(c){var u=j(c,o);if(u){if(u===h)continue;return u}}if("next"===o.method)o.sent=o._sent=o.arg;else if("throw"===o.method){if(r===m)throw r=y,o.arg;o.dispatchException(o.arg)}else"return"===o.method&&o.abrupt("return",o.arg);r=g;var s=p(n,e,o);if("normal"===s.type){if(r=o.done?y:f,s.arg===h)continue;return{value:s.arg,done:o.done}}"throw"===s.type&&(r=y,o.method="throw",o.arg=s.arg)}}}function j(n,e){var o=e.method,r=n.iterator[o];if(r===t)return e.delegate=null,"throw"===o&&n.iterator.return&&(e.method="return",e.arg=t,j(n,e),"throw"===e.method)||"return"!==o&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+o+"' method")),h;var i=p(r,n.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,h;var a=i.arg;return a?a.done?(e[n.resultName]=a.value,e.next=n.nextLoc,"return"!==e.method&&(e.method="next",e.arg=t),e.delegate=null,h):a:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function T(t){var n={tryLoc:t[0]};1 in t&&(n.catchLoc=t[1]),2 in t&&(n.finallyLoc=t[2],n.afterLoc=t[3]),this.tryEntries.push(n)}function P(t){var n=t.completion||{};n.type="normal",delete n.arg,t.completion=n}function C(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(T,this),this.reset(!0)}function I(n){if(n||""===n){var e=n[a];if(e)return e.call(n);if("function"==typeof n.next)return n;if(!isNaN(n.length)){var r=-1,i=function e(){for(;++r<n.length;)if(o.call(n,r))return e.value=n[r],e.done=!1,e;return e.value=t,e.done=!0,e};return i.next=i}}throw new TypeError(v(n)+" is not iterable")}return _.prototype=w,r(x,"constructor",{value:w,configurable:!0}),r(w,"constructor",{value:_,configurable:!0}),_.displayName=s(w,u,"GeneratorFunction"),n.isGeneratorFunction=function(t){var n="function"==typeof t&&t.constructor;return!!n&&(n===_||"GeneratorFunction"===(n.displayName||n.name))},n.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,s(t,u,"GeneratorFunction")),t.prototype=Object.create(x),t},n.awrap=function(t){return{__await:t}},L(E.prototype),s(E.prototype,c,(function(){return this})),n.AsyncIterator=E,n.async=function(t,e,o,r,i){void 0===i&&(i=Promise);var a=new E(l(t,e,o,r),i);return n.isGeneratorFunction(e)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},L(x),s(x,u,"Generator"),s(x,a,(function(){return this})),s(x,"toString",(function(){return"[object Generator]"})),n.keys=function(t){var n=Object(t),e=[];for(var o in n)e.push(o);return e.reverse(),function t(){for(;e.length;){var o=e.pop();if(o in n)return t.value=o,t.done=!1,t}return t.done=!0,t}},n.values=I,C.prototype={constructor:C,reset:function(n){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(P),!n)for(var e in this)"t"===e.charAt(0)&&o.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(n){if(this.done)throw n;var e=this;function r(o,r){return c.type="throw",c.arg=n,e.next=o,r&&(e.method="next",e.arg=t),!!r}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var u=o.call(a,"catchLoc"),s=o.call(a,"finallyLoc");if(u&&s){if(this.prev<a.catchLoc)return r(a.catchLoc,!0);if(this.prev<a.finallyLoc)return r(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return r(a.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return r(a.finallyLoc)}}}},abrupt:function(t,n){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc<=this.prev&&o.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=n&&n<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=n,i?(this.method="next",this.next=i.finallyLoc,h):this.complete(a)},complete:function(t,n){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&n&&(this.next=n),h},finish:function(t){for(var n=this.tryEntries.length-1;n>=0;--n){var e=this.tryEntries[n];if(e.finallyLoc===t)return this.complete(e.completion,e.afterLoc),P(e),h}},catch:function(t){for(var n=this.tryEntries.length-1;n>=0;--n){var e=this.tryEntries[n];if(e.tryLoc===t){var o=e.completion;if("throw"===o.type){var r=o.arg;P(e)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(n,e,o){return this.delegate={iterator:I(n),resultName:e,nextLoc:o},"next"===this.method&&(this.arg=t),h}},n}function b(t,n,e,o,r,i,a){try{var c=t[i](a),u=c.value}catch(t){return void e(t)}c.done?n(u):Promise.resolve(u).then(o,r)}function _(t){return function(){var n=this,e=arguments;return new Promise((function(o,r){var i=t.apply(n,e);function a(t){b(i,o,r,a,c,"next",t)}function c(t){b(i,o,r,a,c,"throw",t)}a(void 0)}))}}function w(t,n){for(var e=0;e<n.length;e++){var o=n[e];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,(void 0,r=function(t,n){if("object"!==v(t)||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var o=e.call(t,"string");if("object"!==v(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(o.key),"symbol"===v(r)?r:String(r)),o)}var r}var z="/image-optimizer/v1",O=function(){function t(){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t)}var n,e,o,r,i,a;return n=t,null,e=[{key:"request",value:(a=_(d().mark((function t(n){var e,o,r,i,a;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return e=n.path,o=n.data,r=n.method,i=void 0===r?"POST":r,t.prev=1,t.next=4,s()({path:e,method:i,data:o});case 4:if((a=t.sent).success){t.next=7;break}throw new h(a.data.message);case 7:return t.abrupt("return",a.data);case 10:if(t.prev=10,t.t0=t.catch(1),!(t.t0 instanceof h)){t.next=16;break}throw t.t0;case 16:throw new h(t.t0.message);case 17:case"end":return t.stop()}}),t,null,[[1,10]])}))),function(_x){return a.apply(this,arguments)})},{key:"optimizeSingleImage",value:(i=_(d().mark((function n(e){var o,r,i,a;return d().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return r=e.imageId,i=e.reoptimize,a=void 0!==i&&i,n.abrupt("return",t.request({path:"".concat(z,"/optimize/image"),data:{imageId:r,reoptimize:a,"image-optimization-optimize-image":null===(o=window)||void 0===o||null===(o=o.imageOptimizerControlSettings)||void 0===o?void 0:o.optimizeSingleImageNonce}}));case 2:case"end":return n.stop()}}),n)}))),function(t){return i.apply(this,arguments)})},{key:"restoreSingleImage",value:(r=_(d().mark((function n(e){var o;return d().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.abrupt("return",t.request({path:"".concat(z,"/backups/restore/").concat(e),data:{"image-optimization-restore-single":null===(o=window)||void 0===o||null===(o=o.imageOptimizerControlSettings)||void 0===o?void 0:o.restoreSingleImageNonce}}));case 1:case"end":return n.stop()}}),n)}))),function(t){return r.apply(this,arguments)})},{key:"getOptimizationStatus",value:(o=_(d().mark((function n(e){return d().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.abrupt("return",t.request({path:"".concat(z,"/optimize/status"),data:{image_ids:e}}));case 1:case"end":return n.stop()}}),n)}))),function(t){return o.apply(this,arguments)})}],e&&w(n,e),Object.defineProperty(n,"prototype",{writable:!1}),t}(),S=O;function x(t){return x="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},x(t)}function L(t,n){for(var e=0;e<n.length;e++){var o=n[e];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,(void 0,r=function(t,n){if("object"!==x(t)||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var o=e.call(t,"string");if("object"!==x(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(o.key),"symbol"===x(r)?r:String(r)),o)}var r}var E=function(){function t(n){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t),this.controlNode=n}var n,e;return n=t,(e=[{key:"getImageId",value:function(){var t,n;return null!==(t=this.controlNode.dataset)&&void 0!==t&&t.imageOptimizationImageId?parseInt(null===(n=this.controlNode.dataset)||void 0===n?void 0:n.imageOptimizationImageId,10):null}},{key:"getAction",value:function(){var t;return(null===(t=this.controlNode.dataset)||void 0===t?void 0:t.imageOptimizationAction)||null}},{key:"getContext",value:function(){var t;return(null===(t=this.controlNode.dataset)||void 0===t?void 0:t.imageOptimizationContext)||null}},{key:"getStatus",value:function(){var t;return(null===(t=this.controlNode.dataset)||void 0===t?void 0:t.imageOptimizationStatus)||null}},{key:"canBeRestored",value:function(){var t,n=null===(t=this.controlNode.dataset)||void 0===t?void 0:t.imageOptimizationCanBeRestored;return n?"1"===n:null}},{key:"allowRetry",value:function(){var t;return(null===(t=this.controlNode.dataset)||void 0===t?void 0:t.allowRetry)||null}}])&&L(n.prototype,e),Object.defineProperty(n,"prototype",{writable:!1}),t}(),k=window.wp.escapeHtml,j=function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2,e=[ // translators: %s: file size in bytes (0,r.__)("%s Bytes","image-optimization"), // translators: %s: file size in kilobytes (0,r.__)("%s Kb","image-optimization"), // translators: %s: file size in megabytes (0,r.__)("%s Mb","image-optimization"), // translators: %s: file size in gigabytes (0,r.__)("%s Gb","image-optimization")];if(!t) // translators: %s: file size in bytes return(0,r.sprintf)((0,r.__)("%s Bytes","image-optimization"),0);var o=Math.floor(Math.log(t)/Math.log(1024)),i=parseFloat((t/Math.pow(1024,o)).toFixed(n));return(0,r.sprintf)(e[o],i)},T=Object.freeze({notOptimizedTemplate:function(){return'\n\t\t<button type="button"\n\t\t\t\t\tclass="button button-primary image-optimization-control__button image-optimization-control__button--optimize">\n\t\t\t'.concat((0,r.__)("Optimize now","image-optimization"),"\n\t\t</button>\n\t")},loadingTemplate:function(t){var n;switch(t){case"restore":n=(0,r.__)("Restoring…","image-optimization");break;case"optimize":n=(0,r.__)("Optimizing…","image-optimization");break;case"reoptimize":n=(0,r.__)("Reoptimizing…","image-optimization");break;default:n=(0,r.__)("Loading…","image-optimization")}return'\n\t\t<button class="button button-secondary image-optimization-control__button image-optimization-control__button--optimize"\n\t\t\t\t\t\tdisabled="">\n\t\t\t<span class="spinner is-active"></span> '.concat(n,"\n\t\t</button>\n\t")},errorTemplate:function(t,n){return'\n\t\t<span class="image-optimization-control__error-message">'.concat((0,k.escapeHTML)(t),"</span>\n\n\t\t").concat(0===n?'<a class="button button-secondary button-large image-optimization-control__button"\n\t\t\t\t href="'.concat(a,'"\n\t\t\t\t target="_blank" rel="noopener noreferrer">\n \t\t\t\t').concat((0,r.__)("Upgrade","image-optimization"),"\n\t\t\t</a>\n\t\t"):'\n\t\t<button class="button button-secondary button-large button-link-delete image-optimization-control__button image-optimization-control__button--try-again"\n\t\t\t\t\t\ttype="button">\n\t\t\t'.concat((0,r.__)("Try again","image-optimization"),"\n\t\t</button>"),"\n\t")},optimizedTemplate:function(t){var n,e,o,i=j(null==t||null===(n=t.saved)||void 0===n?void 0:n.absolute,1);return'\n\t\t<p class="image-optimization-control__property">\n\t\t\t'.concat((0,r.__)("Image sizes optimized","image-optimization"),":\n\n\t\t\t<span>").concat(null==t?void 0:t.sizesOptimized,'</span>\n\t\t</p>\n\n\t\t<p class="image-optimization-control__property">\n\t\t\t').concat(0!==(null==t||null===(e=t.saved)||void 0===e?void 0:e.absolute)?"".concat((0,r.__)("Overall saving","image-optimization"),": <span>").concat(null==t||null===(o=t.saved)||void 0===o?void 0:o.relative,"% (").concat(i,")</span>"):"<span>".concat((0,r.__)("Image is fully optimized","image-optimization"),"</span>"),'\n\t\t</p>\n\n\t\t<div class="image-optimization-control__buttons-wrapper">\n\t\t\t').concat(null!=t&&t.canBeRestored?'\n\t\t\t\t<button type="button"\n\t\t\t\t\tclass="button button-secondary image-optimization-control__button image-optimization-control__button--restore-original">\n\t\t\t\t\t'.concat((0,r.__)("Restore original","image-optimization"),"\n\t\t\t\t</button>\n\t\t\t"):"",'\n\n\t\t\t<button type="button"\n\t\t\t\tclass="button button-secondary image-optimization-control__button image-optimization-control__button--reoptimize">\n\t\t\t\t').concat((0,r.__)("Reoptimize","image-optimization"),"\n\t\t\t</button>\n\t\t</div>\n\t")}}),P=Object.freeze({notOptimizedTemplate:function(){return'\n\t\t<p class="image-optimization-control__property">\n\t\t\t'.concat((0,r.__)("Status","image-optimization"),':\n\n\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t').concat((0,r.__)("Not optimized","image-optimization"),'\n\t\t\t</span>\n\t\t</p>\n\n\t\t<div class="image-optimization-control__action-button-wrapper">\n\t\t\t<button type="button"\n\t\t\t\t\t\t\tclass="button button-primary image-optimization-control__button image-optimization-control__button--optimize">\n\t\t\t\t').concat((0,r.__)("Optimize now","image-optimization"),"\n\t\t\t</button>\n\t\t</div>\n\t")},loadingTemplate:function(){return'\n\t\t<p class="image-optimization-control__property">\n\t\t\t'.concat((0,r.__)("Status","image-optimization"),':\n\n\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t').concat((0,r.__)("In Progress","image-optimization"),'\n\t\t\t</span>\n\t\t</p>\n\n\t\t<div class="image-optimization-control__action-spinner-wrapper">\n\t\t\t<span class="spinner is-active"></span>\n\t\t</div>\n\t')},errorTemplate:function(t,n){return'\n\t\t<p class="image-optimization-control__property">\n\t\t\t'.concat((0,r.__)("Status","image-optimization"),':\n\n\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t').concat((0,r.__)("Error","image-optimization"),'\n\t\t\t</span>\n\t\t</p>\n\n\t\t<p class="image-optimization-control__property">\n\t\t\t').concat((0,r.__)("Reason","image-optimization"),':\n\n\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t').concat((0,k.escapeHTML)(t),'\n\t\t\t</span>\n\t\t</p>\n\n\t\t<div class="image-optimization-control__action-button-wrapper">\n\t\t\t').concat(0===n?'<a class="button button-secondary button-large image-optimization-control__button"\n\t\t\t\t href="'.concat(a,'"\n\t\t\t\t target="_blank" rel="noopener noreferrer">\n\t\t\t\t').concat((0,r.__)("Upgrade","image-optimization"),"\n\t\t\t</a>\n\t\t\t"):'\n\t\t\t<button class="button button-secondary button-large button-link-delete image-optimization-control__button image-optimization-control__button--try-again"\n\t\t\t\t\t\t\ttype="button">\n\t\t\t\t'.concat((0,r.__)("Try again","image-optimization"),"\n\t\t\t</button>"),"\n\t\t</div>\n\t")},optimizedTemplate:function(t){var n,e,o,i=j(null==t||null===(n=t.saved)||void 0===n?void 0:n.absolute,1);return'\n\t\t<p class="image-optimization-control__property">\n\t\t\t'.concat((0,r.__)("Status","image-optimization"),':\n\n\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t').concat((0,r.__)("Optimized","image-optimization"),'\n\t\t\t</span>\n\t\t</p>\n\n\t\t<p class="image-optimization-control__property">\n\t\t\t').concat((0,r.__)("Image sizes optimized","image-optimization"),':\n\n\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t').concat(null==t?void 0:t.sizesOptimized,'\n\t\t\t</span>\n\t\t</p>\n\n\t\t<p class="image-optimization-control__property">\n\t\t\t').concat(0!==(null==t||null===(e=t.saved)||void 0===e?void 0:e.absolute)?'\n\t\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t\t'.concat((0,r.__)("Overall saving","image-optimization"),": ").concat(null==t||null===(o=t.saved)||void 0===o?void 0:o.relative,"% (").concat(i,")\n\t\t\t\t</span>\n\t\t\t"):'\n\t\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t\t'.concat((0,r.__)("Image is fully optimized","image-optimization"),"\n\t\t\t\t</span>\n\t\t\t"),'\n\t\t</p>\n\n\t\t<div class="image-optimization-control__action-button-wrapper">\n\t\t\t').concat(null!=t&&t.canBeRestored?'\n\t\t\t\t<button class="button button-link image-optimization-control__button image-optimization-control__button--restore-original"\n\t\t\t\t\t\t\t\ttype="button">\n\t\t\t\t\t'.concat((0,r.__)("Restore original","image-optimization"),"\n\t\t\t\t</button>\n\t\t\t"):"",'\n\n\t\t\t<button class="button button-link image-optimization-control__button image-optimization-control__button--reoptimize"\n\t\t\t\t\t\t\ttype="button">\n\t\t\t\t').concat((0,r.__)("Reoptimize","image-optimization"),"\n\t\t\t</button>\n\t\t</div>\n\t")}}),C=Object.freeze({notOptimizedTemplate:function(){return'\n\t\t<span class="setting image-optimization-setting">\n\t\t\t<span class="name image-optimization-control__property">\n\t\t\t\t'.concat((0,r.__)("Status","image-optimization"),':\n\t\t\t</span>\n\n\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t').concat((0,r.__)("Not optimized","image-optimization"),'\n\t\t\t</span>\n\t\t</span>\n\n\t\t<span class="setting image-optimization-setting">\n\t\t\t<span class="name image-optimization-control__property"></span>\n\n\t\t\t<span class="image-optimization-control__property-value image-optimization-control__property-value--button">\n\t\t\t\t<button type="button"\n\t\t\t\t\t\t\tclass="button button-primary image-optimization-control__button image-optimization-control__button--optimize">\n\t\t\t\t\t').concat((0,r.__)("Optimize now","image-optimization"),"\n\t\t\t\t</button>\n\t\t\t</span>\n\t\t</span>\n\t")},loadingTemplate:function(){return'\n\t\t<span class="setting image-optimization-setting">\n\t\t\t<span class="name image-optimization-control__property">\n\t\t\t\t'.concat((0,r.__)("Status","image-optimization"),':\n\t\t\t</span>\n\n\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t').concat((0,r.__)("In Progress","image-optimization"),'\n\t\t\t</span>\n\t\t</span>\n\n\t\t<span class="setting image-optimization-setting">\n\t\t\t<span class="name image-optimization-control__property"></span>\n\n\t\t\t<span class="image-optimization-control__property-value image-optimization-control__property-value--spinner">\n\t\t\t\t<span class="spinner is-active"></span>\n\t\t\t</span>\n\t\t</span>\n\t')},errorTemplate:function(t,n){return'\n\t\t<span class="setting image-optimization-setting">\n\t\t\t<span class="name image-optimization-control__property">\n\t\t\t\t'.concat((0,r.__)("Status","image-optimization"),':\n\t\t\t</span>\n\n\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t').concat((0,r.__)("Error","image-optimization"),'\n\t\t\t</span>\n\t\t</span>\n\n\t\t<span class="setting image-optimization-setting">\n\t\t\t<span class="name image-optimization-control__property">\n\t\t\t\t').concat((0,r.__)("Reason","image-optimization"),':\n\t\t\t</span>\n\n\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t').concat((0,k.escapeHTML)(t),'\n\t\t\t</span>\n\t\t</span>\n\n\t\t<span class="setting image-optimization-setting">\n\t\t\t<span class="name image-optimization-control__property"></span>\n\n\t\t\t<span class="image-optimization-control__property-value image-optimization-control__property-value--button">\n\t\t\t\t').concat(0===n?'<a class="button button-secondary button-large image-optimization-control__button"\n\t\t\t\t\thref="'.concat(a,'"\n\t\t\t\t\ttarget="_blank" rel="noopener noreferrer">\n\t\t\t\t\t').concat((0,r.__)("Upgrade","image-optimization"),"\n\t\t\t\t</a>\n\t\t\t\t"):'\n\t\t\t\t<button class="button button-secondary button-large button-link-delete image-optimization-control__button image-optimization-control__button--try-again"\n\t\t\t\t\t\t\t\ttype="button">\n\t\t\t\t\t'.concat((0,r.__)("Try again","image-optimization"),"\n\t\t\t\t</button>"),"\n\t\t\t</span>\n\t\t</span>\n\t")},optimizedTemplate:function(t){var n,e,o,i=j(null==t||null===(n=t.saved)||void 0===n?void 0:n.absolute,1);return'\n\t\t<span class="setting image-optimization-setting">\n\t\t\t<span class="name image-optimization-control__property">\n\t\t\t\t'.concat((0,r.__)("Status","image-optimization"),':\n\t\t\t</span>\n\n\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t').concat((0,r.__)("Optimized","image-optimization"),'\n\t\t\t</span>\n\t\t</span>\n\n\t\t<span class="setting image-optimization-setting">\n\t\t\t<span class="name image-optimization-control__property">\n\t\t\t\t').concat((0,r.__)("Image sizes optimized","image-optimization"),':\n\t\t\t</span>\n\n\t\t\t<span class="image-optimization-control__property-value">\n\t\t\t\t').concat(null==t?void 0:t.sizesOptimized,'\n\t\t\t</span>\n\t\t</span>\n\n\t\t<span class="setting image-optimization-setting">\n\t\t\t').concat(0!==(null==t||null===(e=t.saved)||void 0===e?void 0:e.absolute)?'<span class="name image-optimization-control__property">\n\t\t\t\t'.concat((0,r.__)("Overall saving","image-optimization"),':\n\t\t\t </span>\n\n\t\t\t <span class="image-optimization-control__property-value">\n\t\t\t\t').concat(null==t||null===(o=t.saved)||void 0===o?void 0:o.relative,"% (").concat(i,")\n\t\t\t </span>"):'<span class="name image-optimization-control__property"></span>\n\n\t\t\t <span class="image-optimization-control__property-value">\n\t\t\t\t'.concat((0,r.__)("Image is fully optimized","image-optimization"),"\n\t\t\t </span>"),'\n\t\t</span>\n\n\t\t<span class="setting image-optimization-setting">\n\t\t\t<span class="name image-optimization-control__property"></span>\n\n\t\t\t<span class="image-optimization-control__property-value image-optimization-control__property-value--button">\n\t\t\t\t<button class="button button-link image-optimization-control__button image-optimization-control__button--reoptimize"\n\t\t\t\t\t\t\t\ttype="button">\n\t\t\t\t\t').concat((0,r.__)("Reoptimize","image-optimization"),"\n\t\t\t\t</button>\n\t\t\t</span>\n\t\t</span>\n\n\t\t").concat(null!=t&&t.canBeRestored?'\n\t\t\t<span class="setting image-optimization-setting">\n\t\t\t\t<span class="name image-optimization-control__property"></span>\n\n\t\t\t\t<span class="image-optimization-control__property-value image-optimization-control__property-value--button">\n\t\t\t\t\t<button class="button button-link image-optimization-control__button image-optimization-control__button--restore-original"\n\t\t\t\t\t\t\t\t\ttype="button">\n\t\t\t\t\t\t'.concat((0,r.__)("Restore original","image-optimization"),"\n\t\t\t\t\t</button>\n\t\t\t\t</span>\n\t\t\t</span>\n\t"):"","\n\t")}});function I(t){return I="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},I(t)}function N(t,n){var e=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);n&&(o=o.filter((function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable}))),e.push.apply(e,o)}return e}function R(t){for(var n=1;n<arguments.length;n++){var e=null!=arguments[n]?arguments[n]:{};n%2?N(Object(e),!0).forEach((function(n){var o,r,i;o=t,r=n,i=e[n],(r=B(r))in o?Object.defineProperty(o,r,{value:i,enumerable:!0,configurable:!0,writable:!0}):o[r]=i})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(e)):N(Object(e)).forEach((function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}))}return t}function M(t,n){for(var e=0;e<n.length;e++){var o=n[e];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,B(o.key),o)}}function B(t){var n=function(t,n){if("object"!==I(t)||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var o=e.call(t,"string");if("object"!==I(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"===I(n)?n:String(n)}var A=function(){function t(n){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t),this.controlWrapper=n,this.context=new E(n).getContext(),this.action=new E(n).getAction(),this.canBeRestored=new E(n).canBeRestored(),this.templates={"list-view":T,"meta-box":P,"details-view":C}}var n,e;return n=t,(e=[{key:"renderNotOptimized",value:function(t){this.controlWrapper.className=this.mixControlContextClass(c.controlNotOptimizedClassName),this.controlWrapper.innerHTML=this.getTemplates().notOptimizedTemplate(t),this.controlWrapper.dataset.imageOptimizationStatus="not-optimized"}},{key:"renderOptimized",value:function(t){var n,e=this.canBeRestored&&0!==(null==t||null===(n=t.saved)||void 0===n?void 0:n.absolute);this.controlWrapper.className=this.mixControlContextClass(c.controlOptimizedClassName),this.controlWrapper.innerHTML=this.getTemplates().optimizedTemplate(R(R({},t),{},{canBeRestored:e})),this.controlWrapper.dataset.imageOptimizationStatus="optimized"}},{key:"renderError",value:function(t){var n=t.message,e=t.imagesLeft,o=t.action;this.controlWrapper.className=this.mixControlContextClass(c.controlErrorClassName),this.controlWrapper.innerHTML=this.getTemplates().errorTemplate(n,e),this.controlWrapper.dataset.imageOptimizationAction=o,this.controlWrapper.dataset.imageOptimizationStatus="error"}},{key:"renderLoading",value:function(t){this.controlWrapper.className=this.mixControlContextClass(c.controlLoadingClassName),this.controlWrapper.innerHTML=this.getTemplates().loadingTemplate(t),this.controlWrapper.dataset.imageOptimizationStatus="loading"}},{key:"getTemplates",value:function(){var t=this.templates[this.context];if(!t)throw new Error("No templates found for the context ".concat(this.context));return t}},{key:"mixControlContextClass",value:function(t){var n=c.controlWrapper[this.context];if(!n)throw new Error("No context className found for the context ".concat(this.context));return"".concat(t," ").concat(n)}}])&&M(n.prototype,e),Object.defineProperty(n,"prototype",{writable:!1}),t}();function F(t){return F="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},F(t)}function G(){G=function(){return n};var t,n={},e=Object.prototype,o=e.hasOwnProperty,r=Object.defineProperty||function(t,n,e){t[n]=e.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function s(t,n,e){return Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}),t[n]}try{s({},"")}catch(t){s=function(t,n,e){return t[n]=e}}function l(t,n,e,o){var i=n&&n.prototype instanceof v?n:v,a=Object.create(i.prototype),c=new T(o||[]);return r(a,"_invoke",{value:L(t,e,c)}),a}function p(t,n,e){try{return{type:"normal",arg:t.call(n,e)}}catch(t){return{type:"throw",arg:t}}}n.wrap=l;var m="suspendedStart",f="suspendedYield",g="executing",y="completed",h={};function v(){}function d(){}function b(){}var _={};s(_,a,(function(){return this}));var w=Object.getPrototypeOf,z=w&&w(w(P([])));z&&z!==e&&o.call(z,a)&&(_=z);var O=b.prototype=v.prototype=Object.create(_);function S(t){["next","throw","return"].forEach((function(n){s(t,n,(function(t){return this._invoke(n,t)}))}))}function x(t,n){function e(r,i,a,c){var u=p(t[r],t,i);if("throw"!==u.type){var s=u.arg,l=s.value;return l&&"object"==F(l)&&o.call(l,"__await")?n.resolve(l.__await).then((function(t){e("next",t,a,c)}),(function(t){e("throw",t,a,c)})):n.resolve(l).then((function(t){s.value=t,a(s)}),(function(t){return e("throw",t,a,c)}))}c(u.arg)}var i;r(this,"_invoke",{value:function(t,o){function r(){return new n((function(n,r){e(t,o,n,r)}))}return i=i?i.then(r,r):r()}})}function L(n,e,o){var r=m;return function(i,a){if(r===g)throw new Error("Generator is already running");if(r===y){if("throw"===i)throw a;return{value:t,done:!0}}for(o.method=i,o.arg=a;;){var c=o.delegate;if(c){var u=E(c,o);if(u){if(u===h)continue;return u}}if("next"===o.method)o.sent=o._sent=o.arg;else if("throw"===o.method){if(r===m)throw r=y,o.arg;o.dispatchException(o.arg)}else"return"===o.method&&o.abrupt("return",o.arg);r=g;var s=p(n,e,o);if("normal"===s.type){if(r=o.done?y:f,s.arg===h)continue;return{value:s.arg,done:o.done}}"throw"===s.type&&(r=y,o.method="throw",o.arg=s.arg)}}}function E(n,e){var o=e.method,r=n.iterator[o];if(r===t)return e.delegate=null,"throw"===o&&n.iterator.return&&(e.method="return",e.arg=t,E(n,e),"throw"===e.method)||"return"!==o&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+o+"' method")),h;var i=p(r,n.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,h;var a=i.arg;return a?a.done?(e[n.resultName]=a.value,e.next=n.nextLoc,"return"!==e.method&&(e.method="next",e.arg=t),e.delegate=null,h):a:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function k(t){var n={tryLoc:t[0]};1 in t&&(n.catchLoc=t[1]),2 in t&&(n.finallyLoc=t[2],n.afterLoc=t[3]),this.tryEntries.push(n)}function j(t){var n=t.completion||{};n.type="normal",delete n.arg,t.completion=n}function T(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(k,this),this.reset(!0)}function P(n){if(n||""===n){var e=n[a];if(e)return e.call(n);if("function"==typeof n.next)return n;if(!isNaN(n.length)){var r=-1,i=function e(){for(;++r<n.length;)if(o.call(n,r))return e.value=n[r],e.done=!1,e;return e.value=t,e.done=!0,e};return i.next=i}}throw new TypeError(F(n)+" is not iterable")}return d.prototype=b,r(O,"constructor",{value:b,configurable:!0}),r(b,"constructor",{value:d,configurable:!0}),d.displayName=s(b,u,"GeneratorFunction"),n.isGeneratorFunction=function(t){var n="function"==typeof t&&t.constructor;return!!n&&(n===d||"GeneratorFunction"===(n.displayName||n.name))},n.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,s(t,u,"GeneratorFunction")),t.prototype=Object.create(O),t},n.awrap=function(t){return{__await:t}},S(x.prototype),s(x.prototype,c,(function(){return this})),n.AsyncIterator=x,n.async=function(t,e,o,r,i){void 0===i&&(i=Promise);var a=new x(l(t,e,o,r),i);return n.isGeneratorFunction(e)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},S(O),s(O,u,"Generator"),s(O,a,(function(){return this})),s(O,"toString",(function(){return"[object Generator]"})),n.keys=function(t){var n=Object(t),e=[];for(var o in n)e.push(o);return e.reverse(),function t(){for(;e.length;){var o=e.pop();if(o in n)return t.value=o,t.done=!1,t}return t.done=!0,t}},n.values=P,T.prototype={constructor:T,reset:function(n){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!n)for(var e in this)"t"===e.charAt(0)&&o.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(n){if(this.done)throw n;var e=this;function r(o,r){return c.type="throw",c.arg=n,e.next=o,r&&(e.method="next",e.arg=t),!!r}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var u=o.call(a,"catchLoc"),s=o.call(a,"finallyLoc");if(u&&s){if(this.prev<a.catchLoc)return r(a.catchLoc,!0);if(this.prev<a.finallyLoc)return r(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return r(a.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return r(a.finallyLoc)}}}},abrupt:function(t,n){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc<=this.prev&&o.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=n&&n<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=n,i?(this.method="next",this.next=i.finallyLoc,h):this.complete(a)},complete:function(t,n){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&n&&(this.next=n),h},finish:function(t){for(var n=this.tryEntries.length-1;n>=0;--n){var e=this.tryEntries[n];if(e.finallyLoc===t)return this.complete(e.completion,e.afterLoc),j(e),h}},catch:function(t){for(var n=this.tryEntries.length-1;n>=0;--n){var e=this.tryEntries[n];if(e.tryLoc===t){var o=e.completion;if("throw"===o.type){var r=o.arg;j(e)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(n,e,o){return this.delegate={iterator:P(n),resultName:e,nextLoc:o},"next"===this.method&&(this.arg=t),h}},n}function H(t,n,e,o,r,i,a){try{var c=t[i](a),u=c.value}catch(t){return void e(t)}c.done?n(u):Promise.resolve(u).then(o,r)}function W(t,n){for(var e=0;e<n.length;e++){var o=n[e];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,(void 0,r=function(t,n){if("object"!==F(t)||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var o=e.call(t,"string");if("object"!==F(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(o.key),"symbol"===F(r)?r:String(r)),o)}var r}var D=function(){function t(){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t)}var n,e,o,r;return n=t,e=[{key:"run",value:(o=G().mark((function t(){var n,e,o,r;return G().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if((n=document.querySelectorAll(c.controlWrapperSelector)).length){t.next=3;break}return t.abrupt("return");case 3:return e=this.mapImageIds(n),t.next=6,S.getOptimizationStatus(e);case 6:o=t.sent,r=o.status,n.forEach((function(t){var n=new E(t).getImageId(),e=new E(t).getStatus(),o=r[n],i=new A(t);if(e!==o.status)if("true"!==t.dataset.isFrozen){if("error"!==e||new E(t).allowRetry())switch(o.status){case"optimization-in-progress":i.renderLoading("optimize");break;case"reoptimizing-in-progress":i.renderLoading("reoptimize");break;case"restoring-in-progress":i.renderLoading("restore");break;case"not-optimized":i.renderNotOptimized();break;case"optimized":var a={sizesOptimized:o.stats.optimized_image_count,saved:{absolute:o.stats.initial_image_size-o.stats.current_image_size,relative:Math.max(100-Math.round(o.stats.current_image_size/o.stats.initial_image_size*100),0)}};i.renderOptimized(a);break;case"optimization-failed":i.renderError({message:o.message,imagesLeft:o.images_left,action:"optimize"});break;case"reoptimizing-failed":i.renderError({message:o.message,imagesLeft:o.images_left,action:"reoptimize"});break;case"restoring-failed":i.renderError({message:o.message,action:"restore"})}}else t.dataset.isFrozen=!1}));case 9:case"end":return t.stop()}}),t,this)})),r=function(){var t=this,n=arguments;return new Promise((function(e,r){var i=o.apply(t,n);function a(t){H(i,e,r,a,c,"next",t)}function c(t){H(i,e,r,a,c,"throw",t)}a(void 0)}))},function(){return r.apply(this,arguments)})},{key:"mapImageIds",value:function(t){return Array.prototype.map.call(t,(function(t){return new E(t).getImageId()}))}}],e&&W(n.prototype,e),Object.defineProperty(n,"prototype",{writable:!1}),t}(),q=D;function Y(t){return Y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Y(t)}function U(){U=function(){return n};var t,n={},e=Object.prototype,o=e.hasOwnProperty,r=Object.defineProperty||function(t,n,e){t[n]=e.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function s(t,n,e){return Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}),t[n]}try{s({},"")}catch(t){s=function(t,n,e){return t[n]=e}}function l(t,n,e,o){var i=n&&n.prototype instanceof v?n:v,a=Object.create(i.prototype),c=new T(o||[]);return r(a,"_invoke",{value:L(t,e,c)}),a}function p(t,n,e){try{return{type:"normal",arg:t.call(n,e)}}catch(t){return{type:"throw",arg:t}}}n.wrap=l;var m="suspendedStart",f="suspendedYield",g="executing",y="completed",h={};function v(){}function d(){}function b(){}var _={};s(_,a,(function(){return this}));var w=Object.getPrototypeOf,z=w&&w(w(P([])));z&&z!==e&&o.call(z,a)&&(_=z);var O=b.prototype=v.prototype=Object.create(_);function S(t){["next","throw","return"].forEach((function(n){s(t,n,(function(t){return this._invoke(n,t)}))}))}function x(t,n){function e(r,i,a,c){var u=p(t[r],t,i);if("throw"!==u.type){var s=u.arg,l=s.value;return l&&"object"==Y(l)&&o.call(l,"__await")?n.resolve(l.__await).then((function(t){e("next",t,a,c)}),(function(t){e("throw",t,a,c)})):n.resolve(l).then((function(t){s.value=t,a(s)}),(function(t){return e("throw",t,a,c)}))}c(u.arg)}var i;r(this,"_invoke",{value:function(t,o){function r(){return new n((function(n,r){e(t,o,n,r)}))}return i=i?i.then(r,r):r()}})}function L(n,e,o){var r=m;return function(i,a){if(r===g)throw new Error("Generator is already running");if(r===y){if("throw"===i)throw a;return{value:t,done:!0}}for(o.method=i,o.arg=a;;){var c=o.delegate;if(c){var u=E(c,o);if(u){if(u===h)continue;return u}}if("next"===o.method)o.sent=o._sent=o.arg;else if("throw"===o.method){if(r===m)throw r=y,o.arg;o.dispatchException(o.arg)}else"return"===o.method&&o.abrupt("return",o.arg);r=g;var s=p(n,e,o);if("normal"===s.type){if(r=o.done?y:f,s.arg===h)continue;return{value:s.arg,done:o.done}}"throw"===s.type&&(r=y,o.method="throw",o.arg=s.arg)}}}function E(n,e){var o=e.method,r=n.iterator[o];if(r===t)return e.delegate=null,"throw"===o&&n.iterator.return&&(e.method="return",e.arg=t,E(n,e),"throw"===e.method)||"return"!==o&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+o+"' method")),h;var i=p(r,n.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,h;var a=i.arg;return a?a.done?(e[n.resultName]=a.value,e.next=n.nextLoc,"return"!==e.method&&(e.method="next",e.arg=t),e.delegate=null,h):a:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function k(t){var n={tryLoc:t[0]};1 in t&&(n.catchLoc=t[1]),2 in t&&(n.finallyLoc=t[2],n.afterLoc=t[3]),this.tryEntries.push(n)}function j(t){var n=t.completion||{};n.type="normal",delete n.arg,t.completion=n}function T(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(k,this),this.reset(!0)}function P(n){if(n||""===n){var e=n[a];if(e)return e.call(n);if("function"==typeof n.next)return n;if(!isNaN(n.length)){var r=-1,i=function e(){for(;++r<n.length;)if(o.call(n,r))return e.value=n[r],e.done=!1,e;return e.value=t,e.done=!0,e};return i.next=i}}throw new TypeError(Y(n)+" is not iterable")}return d.prototype=b,r(O,"constructor",{value:b,configurable:!0}),r(b,"constructor",{value:d,configurable:!0}),d.displayName=s(b,u,"GeneratorFunction"),n.isGeneratorFunction=function(t){var n="function"==typeof t&&t.constructor;return!!n&&(n===d||"GeneratorFunction"===(n.displayName||n.name))},n.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,s(t,u,"GeneratorFunction")),t.prototype=Object.create(O),t},n.awrap=function(t){return{__await:t}},S(x.prototype),s(x.prototype,c,(function(){return this})),n.AsyncIterator=x,n.async=function(t,e,o,r,i){void 0===i&&(i=Promise);var a=new x(l(t,e,o,r),i);return n.isGeneratorFunction(e)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},S(O),s(O,u,"Generator"),s(O,a,(function(){return this})),s(O,"toString",(function(){return"[object Generator]"})),n.keys=function(t){var n=Object(t),e=[];for(var o in n)e.push(o);return e.reverse(),function t(){for(;e.length;){var o=e.pop();if(o in n)return t.value=o,t.done=!1,t}return t.done=!0,t}},n.values=P,T.prototype={constructor:T,reset:function(n){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!n)for(var e in this)"t"===e.charAt(0)&&o.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(n){if(this.done)throw n;var e=this;function r(o,r){return c.type="throw",c.arg=n,e.next=o,r&&(e.method="next",e.arg=t),!!r}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var u=o.call(a,"catchLoc"),s=o.call(a,"finallyLoc");if(u&&s){if(this.prev<a.catchLoc)return r(a.catchLoc,!0);if(this.prev<a.finallyLoc)return r(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return r(a.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return r(a.finallyLoc)}}}},abrupt:function(t,n){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc<=this.prev&&o.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=n&&n<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=n,i?(this.method="next",this.next=i.finallyLoc,h):this.complete(a)},complete:function(t,n){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&n&&(this.next=n),h},finish:function(t){for(var n=this.tryEntries.length-1;n>=0;--n){var e=this.tryEntries[n];if(e.finallyLoc===t)return this.complete(e.completion,e.afterLoc),j(e),h}},catch:function(t){for(var n=this.tryEntries.length-1;n>=0;--n){var e=this.tryEntries[n];if(e.tryLoc===t){var o=e.completion;if("throw"===o.type){var r=o.arg;j(e)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(n,e,o){return this.delegate={iterator:P(n),resultName:e,nextLoc:o},"next"===this.method&&(this.arg=t),h}},n}function K(t,n,e,o,r,i,a){try{var c=t[i](a),u=c.value}catch(t){return void e(t)}c.done?n(u):Promise.resolve(u).then(o,r)}function J(t){return function(){var n=this,e=arguments;return new Promise((function(o,r){var i=t.apply(n,e);function a(t){K(i,o,r,a,c,"next",t)}function c(t){K(i,o,r,a,c,"throw",t)}a(void 0)}))}}function Q(t,n){for(var e=0;e<n.length;e++){var o=n[e];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,(void 0,r=function(t,n){if("object"!==Y(t)||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var o=e.call(t,"string");if("object"!==Y(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(o.key),"symbol"===Y(r)?r:String(r)),o)}var r}var V=function(){function t(){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t),this.controlSyncRequestInProgress=!1,this.init(),this.controlSync=new q}var n,e,o,a,u,s;return n=t,e=[{key:"init",value:function(){var t=this;this.initEventListeners(),setInterval((function(){return t.runStatusCheckLoop()}),5e3)}},{key:"runStatusCheckLoop",value:(s=J(U().mark((function t(){return U().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.controlSyncRequestInProgress){t.next=2;break}return t.abrupt("return");case 2:return this.controlSyncRequestInProgress=!0,t.next=5,this.controlSync.run();case 5:this.controlSyncRequestInProgress=!1;case 6:case"end":return t.stop()}}),t,this)}))),function(){return s.apply(this,arguments)})},{key:"initEventListeners",value:function(){var t=this;document.addEventListener("click",(function(n){return t.handleOptimizeButtonClick(n)})),document.addEventListener("click",(function(n){return t.handleReoptimizeButtonClick(n)})),document.addEventListener("click",(function(n){return t.handleRestoreButtonClick(n)}))}},{key:"handleOptimizeButtonClick",value:(u=J(U().mark((function t(n){var e,o;return U().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n.target.closest("".concat(c.optimizeButtonSelector,", ").concat(c.tryAgainOptimizeButtonSelector))){t.next=2;break}return t.abrupt("return");case 2:return(0,i.speak)((0,r.__)("Optimization is in progress","image-optimization"),"assertive"),e=n.target.closest(c.controlWrapperSelector),(o=new A(e)).renderLoading("optimize"),t.prev=6,e.dataset.isFrozen=!0,t.next=10,S.optimizeSingleImage({imageId:new E(e).getImageId(),reoptimize:!1});case 10:t.next=15;break;case 12:t.prev=12,t.t0=t.catch(6),o.renderError(t.t0);case 15:case"end":return t.stop()}}),t,null,[[6,12]])}))),function(_x){return u.apply(this,arguments)})},{key:"handleReoptimizeButtonClick",value:(a=J(U().mark((function t(n){var e,o;return U().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n.target.closest("".concat(c.reoptimizeButtonSelector,", ").concat(c.tryAgainReoptimizeButtonSelector))){t.next=2;break}return t.abrupt("return");case 2:return(0,i.speak)((0,r.__)("Reoptimizing is in progress","image-optimization"),"assertive"),e=n.target.closest(c.controlWrapperSelector),(o=new A(e)).renderLoading("reoptimize"),t.prev=6,e.dataset.isFrozen=!0,t.next=10,S.optimizeSingleImage({imageId:new E(e).getImageId(),reoptimize:!0});case 10:t.next=15;break;case 12:t.prev=12,t.t0=t.catch(6),o.renderError(t.t0);case 15:case"end":return t.stop()}}),t,null,[[6,12]])}))),function(t){return a.apply(this,arguments)})},{key:"handleRestoreButtonClick",value:(o=J(U().mark((function t(n){var e,o;return U().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n.target.closest("".concat(c.restoreButtonSelector,", ").concat(c.tryAgainRestoreButtonSelector))){t.next=2;break}return t.abrupt("return");case 2:return(0,i.speak)((0,r.__)("Image restoring is in progress","image-optimization"),"assertive"),e=n.target.closest(c.controlWrapperSelector),(o=new A(e)).renderLoading("restore"),t.prev=6,e.dataset.isFrozen=!0,t.next=10,S.restoreSingleImage(new E(e).getImageId());case 10:t.next=15;break;case 12:t.prev=12,t.t0=t.catch(6),o.renderError(t.t0);case 15:case"end":return t.stop()}}),t,null,[[6,12]])}))),function(t){return o.apply(this,arguments)})}],e&&Q(n.prototype,e),Object.defineProperty(n,"prototype",{writable:!1}),t}(),X=V;function Z(t){return Z="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Z(t)}function $(t,n){for(var e=0;e<n.length;e++){var o=n[e];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,(void 0,r=function(t,n){if("object"!==Z(t)||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var o=e.call(t,"string");if("object"!==Z(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(o.key),"symbol"===Z(r)?r:String(r)),o)}var r}var tt=function(){function t(){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t),this.init()}var n,e;return n=t,(e=[{key:"init",value:function(){new o,new X}}])&&$(n.prototype,e),Object.defineProperty(n,"prototype",{writable:!1}),t}();document.addEventListener("DOMContentLoaded",(function(){return new tt}))}(); assets/static/link.svg 0000644 00000002103 14720461212 0011006 0 ustar 00 <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="none"> <g fill="#BABFC5" clip-path="url(#a)"> <path d="m15.755 11.335-2.08-2.08a3.75 3.75 0 0 0-5.304 5.302l2.652 2.652a3.75 3.75 0 0 0 6.036-1.034l-.733-.734a1.235 1.235 0 0 0-.249-.193 2.5 2.5 0 0 1-4.17 1.077l-2.652-2.651a2.5 2.5 0 1 1 3.535-3.536l1.357 1.357a5.02 5.02 0 0 1 1.609-.16h-.001Z"/> <path d="m15.233 12.581.209.209c.322.322.538.71.647 1.12.424.114.81.337 1.12.648l.21.208a3.756 3.756 0 0 0-.36-1.826 3.75 3.75 0 0 0-1.826-.359Z"/> <path d="M18.093 13.674a3.75 3.75 0 0 0-6.037 1.034l.971.97a2.5 2.5 0 0 1 4.183-1.12l2.651 2.651a2.5 2.5 0 1 1-3.535 3.536l-1.357-1.357a5.025 5.025 0 0 1-1.609.159l2.082 2.081a3.75 3.75 0 0 0 5.303-5.303l-2.652-2.651Z"/> <path d="M12.056 17.943c.57.27 1.198.394 1.827.359l-.209-.209a2.487 2.487 0 0 1-.647-1.12 2.487 2.487 0 0 1-1.12-.648l-.21-.208a3.762 3.762 0 0 0 .36 1.826Z"/> </g> <defs> <clipPath id="a"> <path fill="#fff" d="M15 .857 29.142 15 15 29.142.858 15z"/> </clipPath> </defs> </svg>
| ver. 1.4 |
Github
|
.
| PHP 7.4.3-4ubuntu2.24 | Генерация страницы: 0.3 |
proxy
|
phpinfo
|
Настройка