Initial commit xmarticaims

This commit is contained in:
2026-11-02 10:26:32 -06:00
commit e74236f5c1
9764 changed files with 2880647 additions and 0 deletions
@@ -0,0 +1,139 @@
<?php
declare( strict_types=1 );
namespace WP_Rocket\Engine\Optimization\RUCSS;
use WP_Error;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Logger\Logger;
abstract class AbstractAPIClient {
/**
* API URL.
*/
const API_URL = 'https://saas.wp-rocket.me/';
/**
* Part of request Url after the main API_URL.
*
* @var string
*/
protected $request_path;
/**
* Response Code.
*
* @var int
*/
protected $response_code = 200;
/**
* Error message.
*
* @var string
*/
protected $error_message = '';
/**
* Response Body.
*
* @var string
*/
protected $response_body;
/**
* Plugin options instance.
*
* @var Options_Data
*/
protected $options;
/**
* Instantiate the class.
*
* @param Options_Data $options Options instance.
*/
public function __construct( Options_Data $options ) {
$this->options = $options;
}
/**
* Handle the request.
*
* @param array $args Passed arguments.
* @param string $type GET or POST.
*
* @return bool
*/
private function handle_request( array $args, string $type = 'post' ) {
$api_url = rocket_get_constant( 'WP_ROCKET_SAAS_API_URL', false )
? rocket_get_constant( 'WP_ROCKET_SAAS_API_URL', false )
: self::API_URL;
if ( empty( $args['body'] ) ) {
$args['body'] = [];
}
$args['body']['credentials'] = [
'wpr_email' => $this->options->get( 'consumer_email', '' ),
'wpr_key' => $this->options->get( 'consumer_key', '' ),
];
$args['method'] = strtoupper( $type );
$response = wp_remote_request(
$api_url . $this->request_path,
$args
);
return $this->check_response( $response );
}
/**
* Handle remote POST.
*
* @param array $args Array with options sent to Saas API.
*
* @return bool WP Remote request status.
*/
protected function handle_post( array $args ): bool {
return $this->handle_request( $args );
}
/**
* Handle remote GET.
*
* @param array $args Array with options sent to Saas API.
*
* @return bool WP Remote request status.
*/
protected function handle_get( array $args ): bool {
return $this->handle_request( $args, 'get' );
}
/**
* Handle SaaS request error.
*
* @param array|WP_Error $response WP Remote request.
*
* @return bool
*/
private function check_response( $response ): bool {
$this->response_code = is_array( $response )
? wp_remote_retrieve_response_code( $response )
: $response->get_error_code();
if ( 200 !== $this->response_code ) {
$previous_errors = (int) get_transient( 'wp_rocket_rucss_errors_count' );
set_transient( 'wp_rocket_rucss_errors_count', $previous_errors + 1, 5 * MINUTE_IN_SECONDS );
$this->error_message = is_array( $response )
? wp_remote_retrieve_response_message( $response )
: $response->get_error_message();
return false;
}
delete_transient( 'wp_rocket_rucss_errors_count' );
$this->response_body = wp_remote_retrieve_body( $response );
return true;
}
}
@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Admin;
use WP_Rocket\Engine\Optimization\RUCSS\Database\Tables\UsedCSS;
class Database {
/**
* Instance of RUCSS used_css table.
*
* @var UsedCSS
*/
private $rucss_usedcss_table;
/**
* Creates an instance of the class.
*
* @param UsedCSS $rucss_usedcss_table RUCSS UsedCSS Database Table.
*/
public function __construct( UsedCSS $rucss_usedcss_table ) {
$this->rucss_usedcss_table = $rucss_usedcss_table;
}
/**
* Drop RUCSS Database Tables.
*
* @return void
*/
public function drop_rucss_database_tables() {
// If the table exist, then drop the table.
if ( $this->rucss_usedcss_table->exists() ) {
$this->rucss_usedcss_table->uninstall();
}
}
/**
* Truncate RUCSS used_css DB table.
*
* @return bool
*/
public function truncate_used_css_table(): bool {
if ( ! $this->rucss_usedcss_table->exists() ) {
return false;
}
return $this->rucss_usedcss_table->truncate();
}
/**
* Delete old used css based on last accessed date.
*
* @return void
*/
public function delete_old_used_css() {
if ( ! $this->rucss_usedcss_table->exists() ) {
return;
}
$this->rucss_usedcss_table->delete_old_used_css();
}
/**
* Get old used css based on last accessed date.
*
* @return array
*/
public function get_old_used_css(): array {
if ( ! $this->rucss_usedcss_table->exists() ) {
return [];
}
return $this->rucss_usedcss_table->get_old_used_css();
}
/**
* Remove all completed rows.
*
* @return bool|int
*/
public function remove_all_completed_rows() {
if ( ! $this->rucss_usedcss_table->exists() ) {
return false;
}
return $this->rucss_usedcss_table->remove_all_completed_rows();
}
/**
* Remove the resources table & version stored in options table
*
* @since 3.12
*
* @return bool
*/
public function drop_resources_table(): bool {
global $wpdb;
$result = $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}wpr_rucss_resources" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
if ( false === $result ) {
return false;
}
return delete_option( 'wpr_rucss_resources_version' );
}
}
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Admin;
use WP_Rocket\Engine\Admin\Settings\Settings as AdminSettings;
use WP_Rocket\Event_Management\Subscriber_Interface;
class OptionSubscriber implements Subscriber_Interface {
/**
* Settings instance
*
* @var Settings
*/
private $settings;
/**
* Instantiate the class
*
* @param Settings $settings Settings instance.
*/
public function __construct( Settings $settings ) {
$this->settings = $settings;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @return array
*/
public static function get_subscribed_events() {
return [
'rocket_first_install_options' => 'add_options_first_time',
'rocket_input_sanitize' => [ 'sanitize_options', 14, 2 ],
'rocket_meta_boxes_fields' => [ 'add_meta_box', 2 ],
];
}
/**
* Add the RUCSS options to the WP Rocket options array.
*
* @since 3.9
*
* @param array $options WP Rocket options array.
*
* @return array
*/
public function add_options_first_time( $options ): array {
return $this->settings->add_options( $options );
}
/**
* Sanitizes RUCSS options values when the settings form is submitted
*
* @since 3.9
*
* @param array $input Array of values submitted from the form.
* @param AdminSettings $settings Settings class instance.
*
* @return array
*/
public function sanitize_options( $input, AdminSettings $settings ): array {
return $this->settings->sanitize_options( $input, $settings );
}
/**
* Add the field to the WP Rocket metabox on the post edit page.
*
* @param string[] $fields Metaboxes fields.
*
* @return string[]
*/
public function add_meta_box( array $fields ) {
$fields['remove_unused_css'] = __( 'Remove Unused CSS', 'rocket' );
return $fields;
}
}
@@ -0,0 +1,580 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Admin;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Admin\Beacon\Beacon;
use WP_Rocket\Engine\Admin\Settings\Settings as AdminSettings;
use WP_Rocket\Engine\Optimization\RUCSS\Database\Tables\UsedCSS;
class Settings {
/**
* Instance of options handler.
*
* @var Options_Data
*/
private $options;
/**
* Instance of Beacon class.
*
* @var Beacon
*/
private $beacon;
/**
* Used CSS table.
*
* @var UsedCSS
*/
private $used_css;
/**
* Creates an instance of the class.
*
* @param Options_Data $options WP Rocket Options instance.
* @param Beacon $beacon Beacon instance.
* @param UsedCSS $used_css Used CSS table.
*/
public function __construct( Options_Data $options, Beacon $beacon, UsedCSS $used_css ) {
$this->options = $options;
$this->beacon = $beacon;
$this->used_css = $used_css;
}
/**
* Add the RUCSS options to the WP Rocket options array
*
* @since 3.9
*
* @param array $options WP Rocket options array.
*
* @return array
*/
public function add_options( $options ): array {
$options = (array) $options;
$options['remove_unused_css'] = 0;
$options['remove_unused_css_safelist'] = [];
return $options;
}
/**
* Determines if Remove Unused CSS option is enabled.
*
* @since 3.9
*
* @return boolean
*/
public function is_enabled(): bool {
return (bool) $this->options->get( 'remove_unused_css', 0 );
}
/**
* Sanitizes RUCSS options values when the settings form is submitted
*
* @since 3.9
*
* @param array $input Array of values submitted from the form.
* @param AdminSettings $settings Settings class instance.
*
* @return array
*/
public function sanitize_options( array $input, AdminSettings $settings ): array {
$input['remove_unused_css'] = $settings->sanitize_checkbox( $input, 'remove_unused_css' );
$input['remove_unused_css_safelist'] = ! empty( $input['remove_unused_css_safelist'] ) ? rocket_sanitize_textarea_field( 'remove_unused_css_safelist', $input['remove_unused_css_safelist'] ) : [];
return $input;
}
/**
* Add Clean used CSS link to WP Rocket admin bar item
*
* @since 3.9
*
* @param \WP_Admin_Bar $wp_admin_bar WP_Admin_Bar instance, passed by reference.
*
* @return void
*/
public function add_clean_used_css_menu_item( $wp_admin_bar ) {
if ( 'local' === wp_get_environment_type() ) {
return;
}
if ( ! current_user_can( 'rocket_remove_unused_css' ) ) {
return;
}
if ( ! is_admin() ) {
return;
}
if ( ! $this->is_enabled() ) {
return;
}
$referer = '';
$action = 'rocket_clear_usedcss';
if ( ! empty( $_SERVER['REQUEST_URI'] ) ) {
$referer_url = filter_var( wp_unslash( $_SERVER['REQUEST_URI'] ), FILTER_SANITIZE_URL );
$referer = '&_wp_http_referer=' . rawurlencode( remove_query_arg( 'fl_builder', $referer_url ) );
}
$wp_admin_bar->add_menu(
[
'parent' => 'wp-rocket',
'id' => 'clean-used-css',
'title' => __( 'Clear Used CSS', 'rocket' ),
'href' => wp_nonce_url( admin_url( "admin-post.php?action={$action}{$referer}" ), $action ),
]
);
}
/**
* Set optimize css delivery value
*
* @since 3.10
*
* @param array $field_args Array of field to be added to settings page.
*
* @return array
*/
public function set_optimize_css_delivery_value( $field_args ): array {
if ( 'optimize_css_delivery' !== $field_args['id'] ) {
return $field_args;
}
$async_css_value = (bool) $this->options->get( 'async_css', 0 );
$remove_unused_css_value = (bool) $this->options->get( 'remove_unused_css', 0 );
$field_args['value'] = ( $remove_unused_css_value || $async_css_value );
return $field_args;
}
/**
* Set optimize css delivery method value
*
* @since 3.10
*
* @param array $field_args Array of field to be added to settings page.
*
* @return array
*/
public function set_optimize_css_delivery_method_value( $field_args ): array {
if ( 'optimize_css_delivery_method' !== $field_args['id'] ) {
return $field_args;
}
$value = '';
if ( (bool) $this->options->get( 'async_css', 0 ) ) {
$value = 'async_css';
}
if ( (bool) $this->options->get( 'remove_unused_css', 0 ) ) {
$value = 'remove_unused_css';
}
$field_args['value'] = $value;
return $field_args;
}
/**
* Displays the RUCSS currently processing notice
*
* @since 3.11
*
* @return void
*/
public function display_processing_notice() {
if ( $this->has_saas_error_notice() ) {
return;
}
if ( ! $this->can_display_notice() ) {
return;
}
if ( ! $this->used_css->exists() ) {
return;
}
$transient = get_transient( 'rocket_rucss_processing' );
if ( false === $transient ) {
return;
}
$current_time = time();
if ( $transient < $current_time ) {
return;
}
$remaining = $transient - $current_time;
$message = sprintf(
// translators: %1$s = plugin name, %2$s = number of seconds.
__( '%1$s: Please wait %2$s seconds. The Remove Unused CSS service is processing your pages.', 'rocket' ),
'<strong>WP Rocket</strong>',
'<span id="rocket-rucss-timer">' . $remaining . '</span>'
);
rocket_notice_html(
[
'status' => 'info',
'message' => $message,
'id' => 'rocket-notice-rucss-processing',
]
);
}
/**
* Displays the RUCSS success notice
*
* @since 3.11
*
* @return void
*/
public function display_success_notice() {
if ( ! $this->can_display_notice() ) {
return;
}
if ( ! $this->used_css->exists() ) {
return;
}
if ( $this->has_saas_error_notice() ) {
return;
}
$boxes = get_user_meta( get_current_user_id(), 'rocket_boxes', true );
if ( in_array( 'rucss_success_notice', (array) $boxes, true ) ) {
return;
}
$transient = get_transient( 'rocket_rucss_processing' );
$class = '';
if ( false !== $transient ) {
$class = 'hidden';
}
$message = sprintf(
// translators: %1$s = plugin name, %2$s = number of URLs, %3$s = number of seconds.
__( '%1$s: The Used CSS of your homepage has been processed. WP Rocket will continue to generate Used CSS for up to %2$s URLs per %3$s second(s).', 'rocket' ),
'<strong>WP Rocket</strong>',
apply_filters( 'rocket_rucss_pending_jobs_cron_rows_count', 100 ),
apply_filters( 'rocket_rucss_pending_jobs_cron_interval', MINUTE_IN_SECONDS )
);
if ( ! $this->options->get( 'manual_preload', 0 ) ) {
$message .= ' ' . sprintf(
// translators: %1$s = opening link tag, %2$s = closing link tag.
__( 'We suggest enabling %1$sPreload%2$s for the fastest results.', 'rocket' ),
'<a href="#preload">',
'</a>'
);
}
$beacon = $this->beacon->get_suggest( 'async_opti' );
$message .= '<br>' . sprintf(
// translators: %1$s = opening link tag, %2$s = closing link tag.
__( 'To learn more about the process check our %1$sdocumentation%2$s.', 'rocket' ),
'<a href="' . esc_url( $beacon['url'] ) . '" data-beacon-article="' . esc_attr( $beacon['id'] ) . '" rel="noopener noreferrer" target="_blank">',
'</a>'
);
rocket_notice_html(
[
'message' => $message,
'dismissible' => $class,
'id' => 'rocket-notice-rucss-success',
'dismiss_button' => 'rucss_success_notice',
'dismiss_button_class' => 'button-primary',
]
);
}
/**
* Checks if we can display the RUCSS notices
*
* @param bool $check_enabled check if RUCSS is enabled.
*
* @since 3.11
*
* @return bool
*/
private function can_display_notice( $check_enabled = true ): bool {
$screen = get_current_screen();
if ( ! rocket_direct_filesystem()->is_writable( rocket_get_constant( 'WP_ROCKET_USED_CSS_PATH' ) ) ) {
return false;
}
if (
isset( $screen->id )
&&
'settings_page_wprocket' !== $screen->id
) {
return false;
}
if ( ! current_user_can( 'rocket_manage_options' ) ) {
return false;
}
if ( $check_enabled && ! $this->is_enabled() ) {
return false;
}
return true;
}
/**
* Adds the notice end time to WP Rocket localize script data
*
* @since 3.11
*
* @param array $data Localize script data.
*
* @return array
*/
public function add_localize_script_data( $data ): array {
if ( ! is_array( $data ) ) {
$data = (array) $data;
}
if ( ! $this->is_enabled() ) {
return $data;
}
$transient = get_transient( 'rocket_rucss_processing' );
if ( false === $transient ) {
return $data;
}
$data['notice_end_time'] = $transient;
return $data;
}
/**
* Disables combine CSS if RUCSS is enabled when updating to 3.11
*
* @since 3.11
*
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function set_option_on_update( $old_version ) {
if ( version_compare( $old_version, '3.11', '>=' ) ) {
return;
}
$options = get_option( 'wp_rocket_settings', [] );
if ( 'local' === wp_get_environment_type() ) {
$options['optimize_css_delivery'] = 0;
$options['remove_unused_css'] = 0;
$options['async_css'] = 0;
}
update_option( 'wp_rocket_settings', $options );
}
/**
* Updates safelist items for new SaaS compatibility
*
* @since 3.11.0.2
*
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function update_safelist_items( $old_version ) {
if ( version_compare( $old_version, '3.11.0.2', '>=' ) ) {
return;
}
$options = get_option( 'wp_rocket_settings', [] );
if ( empty( $options['remove_unused_css_safelist'] ) ) {
return;
}
foreach ( $options['remove_unused_css_safelist'] as $key => $value ) {
if ( str_contains( $value, '.css' ) ) {
continue;
}
if ( str_starts_with( $value, '(' ) ) {
continue;
}
$options['remove_unused_css_safelist'][ $key ] = '(.*)' . $value;
}
update_option( 'wp_rocket_settings', $options );
}
/**
* Display a notification on wrong license.
*
* @return void
*/
public function display_wrong_license_notice() {
if ( ! $this->can_display_notice( false ) ) {
return;
}
$main_message = __( "We couldn't generate the used CSS because you're using a nulled version of WP Rocket. You need an active license to use the Remove Unused CSS feature and further improve your website's performance.", 'rocket' );
$cta_message = sprintf(
// translators: %1$s = promo percentage.
__( 'Click here to get a WP Rocket single license at %1$s off!', 'rocket' ),
'10%%'
);
$message = sprintf(
// translators: %1$s = plugin name, %2$s = opening anchor tag, %3$s = closing anchor tag.
"%1\$s: <p>$main_message</p>%2\$s$cta_message%3\$s",
'<strong>WP Rocket</strong>',
'<a href="https://wp-rocket.me/?add-to-cart=191&coupon_code=iamnotapirate10" class="button button-primary" rel="noopener noreferrer" target="_blank">',
'</a>'
);
rocket_notice_html(
[
'status' => 'error',
'dismissible' => '',
'message' => $message,
'id' => 'rocket-notice-rucss-wrong-licence',
]
);
}
/**
* Display an error notice when the connection to the server fails
*
* @return void
*/
public function display_saas_error_notice() {
if ( ! $this->has_saas_error_notice() ) {
$boxes = get_user_meta( get_current_user_id(), 'rocket_boxes', true );
if ( in_array( 'rucss_saas_error_notice', (array) $boxes, true ) ) {
unset( $boxes['rucss_saas_error_notice'] );
update_user_meta( get_current_user_id(), 'rocket_boxes', $boxes );
}
return;
}
if ( ! $this->can_display_notice() ) {
return;
}
$boxes = get_user_meta( get_current_user_id(), 'rocket_boxes', true );
if ( in_array( 'rucss_error_notice', (array) $boxes, true ) ) {
return;
}
$firewall_beacon = $this->beacon->get_suggest( 'rucss_firewall_ips' );
$main_message = sprintf(
// translators: %1$s = <a> open tag, %2$s = </a> closing tag.
__( 'It seems a security plugin or the server\'s firewall prevents WP Rocket from accessing the Remove Unused CSS generator. IPs listed %1$shere in our documentation%2$s should be added to your allowlists:', 'rocket' ),
'<a href="' . esc_url( $firewall_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $firewall_beacon['id'] ) . '" rel="noopener noreferrer" target="_blank">',
'</a>'
);
$security_message = __( '- In the security plugin, if you are using one', 'rocket' );
$firewall_message = __( "- In the server's firewall. Your host can help you with this", 'rocket' );
$message = "<strong>WP Rocket</strong>: $main_message<ul><li>$security_message</li><li>$firewall_message</li></ul>";
rocket_notice_html(
[
'status' => 'error',
'message' => $message,
'dismissible' => '',
'id' => 'rocket-notice-rucss-error-http',
'dismiss_button' => 'rucss_error_notice',
'dismiss_button_class' => 'button-primary',
]
);
}
/**
* Is the error notice present.
*
* @return bool
*/
public function has_saas_error_notice() {
return (bool) get_transient( 'wp_rocket_rucss_errors_count' );
}
/**
* Display a notice on table missing.
*
* @return void
*/
public function display_no_table_notice() {
if ( ! $this->can_display_notice() ) {
return;
}
if ( $this->used_css->exists() ) {
return;
}
// translators: %1$s = plugin name, %2$s = table name, %3$s = <a> open tag, %4$s = </a> closing tag.
$main_message = esc_html__( '%1$s: Could not create the %2$s table in the database which is necessary for the Remove Unused CSS feature to work. Please reach out to %3$sour support%4$s.', 'rocket' );
$message = sprintf(
// translators: %1$s = plugin name, %2$s = table name, %3$s = <a> open tag, %4$s = </a> closing tag.
$main_message,
'<strong>WP Rocket</strong>',
$this->used_css->get_name(),
'<a href="' . $this->get_support_url() . '" target="_blank" rel="noopener">',
'</a>'
);
rocket_notice_html(
[
'status' => 'error',
'dismissible' => '',
'message' => $message,
'id' => 'rocket-notice-rucss-missing-table',
]
);
}
/**
* Get support URL.
*
* @return string
*/
protected function get_support_url() {
return rocket_get_external_url(
'support',
[
'utm_source' => 'wp_plugin',
'utm_medium' => 'wp_rocket',
]
);
}
}
@@ -0,0 +1,756 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Admin;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\Queue;
use WP_Rocket\Engine\Common\Queue\RUCSSQueueRunner;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\UsedCSS;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Admin_Bar;
class Subscriber implements Subscriber_Interface {
/**
* Settings instance
*
* @var Settings
*/
private $settings;
/**
* Database instance
*
* @var Database
*/
private $database;
/**
* UsedCSS instance
*
* @var UsedCSS
*/
private $used_css;
/**
* Queue instance
*
* @var Queue
*/
private $queue;
/**
* Instantiate the class
*
* @param Settings $settings Settings instance.
* @param Database $database Database instance.
* @param UsedCSS $used_css UsedCSS instance.
* @param Queue $queue Queue instance.
*/
public function __construct( Settings $settings, Database $database, UsedCSS $used_css, Queue $queue ) {
$this->settings = $settings;
$this->database = $database;
$this->used_css = $used_css;
$this->queue = $queue;
}
/**
* Return an array of events that this subscriber listens to.
*
* @return array
*/
public static function get_subscribed_events(): array {
$slug = rocket_get_constant( 'WP_ROCKET_SLUG', 'wp_rocket_settings' );
return [
'update_option_' . $slug => [
[ 'clean_used_css_and_cache', 9, 2 ],
[ 'maybe_set_processing_transient', 50, 2 ],
[ 'maybe_unlock_preload', 9, 2 ],
[ 'maybe_delete_transient', 10, 2 ],
],
'switch_theme' => 'truncate_used_css',
'permalink_structure_changed' => 'truncate_used_css',
'rocket_domain_options_changed' => 'truncate_used_css',
'wp_trash_post' => 'delete_used_css_on_update_or_delete',
'delete_post' => 'delete_used_css_on_update_or_delete',
'clean_post_cache' => 'delete_used_css_on_update_or_delete',
'wp_update_comment_count' => 'delete_used_css_on_update_or_delete',
'edit_term' => 'delete_term_used_css',
'pre_delete_term' => 'delete_term_used_css',
'admin_post_rocket_clear_usedcss' => 'truncate_used_css_handler',
'admin_post_rocket_clear_usedcss_url' => 'clear_url_usedcss',
'admin_notices' => [
[ 'clear_usedcss_result' ],
[ 'display_processing_notice' ],
[ 'display_success_notice' ],
[ 'display_wrong_license_notice' ],
[ 'display_saas_error_notice' ],
[ 'display_no_table_notice' ],
[ 'notice_write_permissions' ],
],
'rocket_admin_bar_items' => [
[ 'add_clean_used_css_menu_item' ],
[ 'add_clear_usedcss_bar_item' ],
],
'rocket_before_add_field_to_settings' => [
[ 'set_optimize_css_delivery_value', 10, 1 ],
[ 'set_optimize_css_delivery_method_value', 10, 1 ],
],
'rocket_localize_admin_script' => 'add_localize_script_data',
'wp_rocket_upgrade' => [
[ 'set_option_on_update', 14, 2 ],
[ 'update_safelist_items', 15, 2 ],
[ 'delete_used_css', 16, 2 ],
[ 'cancel_pending_jobs_as', 16, 2 ],
[ 'drop_resources_table', 18, 2 ],
],
'wp_ajax_rocket_spawn_cron' => 'spawn_cron',
'rocket_deactivation' => 'cancel_queues',
'admin_head-tools_page_action-scheduler' => 'delete_as_tables_transient_on_tools_page',
'pre_get_rocket_option_remove_unused_css' => 'disable_russ_on_wrong_license',
'rocket_before_rollback' => 'cancel_queues',
];
}
/**
* Delete used_css on Update Post or Delete post.
*
* @since 3.9
*
* @param int $post_id The post ID.
*
* @return void
*/
public function delete_used_css_on_update_or_delete( $post_id ) {
if ( ! $this->settings->is_enabled() ) {
return;
}
if ( ! $this->is_deletion_enabled() ) {
return;
}
$url = get_permalink( $post_id );
if ( false === $url ) {
return;
}
$this->used_css->delete_used_css( untrailingslashit( $url ) );
}
/**
* Maybe unlock all locked preload urls.
*
* @param array $old_value An array of submitted values for the settings.
* @param array $value An array of previous values for the settings.
*
* @return void
*/
public function maybe_unlock_preload( $old_value, $value ) {
if ( ! isset( $value['remove_unused_css'], $old_value['remove_unused_css'] ) ) {
return;
}
if ( $value['remove_unused_css'] === $old_value['remove_unused_css'] ) {
return;
}
if ( $value['remove_unused_css'] ) {
return;
}
do_action( 'rocket_preload_unlock_all_urls' );
}
/**
* Deletes the used CSS when updating a term
*
* @since 3.10.2
*
* @param int $term_id the term ID.
*
* @return void
*/
public function delete_term_used_css( $term_id ) {
if ( ! $this->settings->is_enabled() ) {
return;
}
if ( ! $this->is_deletion_enabled() ) {
return;
}
$url = get_term_link( (int) $term_id );
if ( is_wp_error( $url ) ) {
return;
}
$this->used_css->delete_used_css( untrailingslashit( $url ) );
}
/**
* Truncate RUCSS used_css DB table.
*
* @since 3.9
*
* @return void
*/
public function truncate_used_css() {
if ( ! $this->settings->is_enabled() ) {
return;
}
if ( ! $this->is_deletion_enabled() ) {
return;
}
$this->delete_used_css_rows();
$this->set_notice_transient();
}
/**
* Deletes the used CSS from the table
*
* @since 3.11
*
* @return void
*/
private function delete_used_css_rows() {
$this->used_css->delete_all_used_css();
if ( 0 < $this->used_css->get_not_completed_count() ) {
$this->database->remove_all_completed_rows();
} else {
$this->database->truncate_used_css_table();
}
/**
* Fires after the used CSS has been cleaned in the database
*
* @since 3.11
*/
do_action( 'rocket_after_clean_used_css' );
}
/**
* Truncate UsedCSS DB Table when `remove_unused_css_safelist` is changed.
*
* @since 3.9
*
* @param array $old_value An array of submitted values for the settings.
* @param array $value An array of previous values for the settings.
*
* @return void
*/
public function clean_used_css_and_cache( $old_value, $value ) {
if ( ! isset( $value['remove_unused_css_safelist'], $old_value['remove_unused_css_safelist'] ) ) {
return;
}
if ( $value['remove_unused_css_safelist'] === $old_value['remove_unused_css_safelist'] ) {
return;
}
$this->delete_used_css_rows();
$this->set_notice_transient();
}
/**
* Truncate used_css table when clicking on the dashboard button.
*
* @since 3.9
*
* @return void
*/
public function truncate_used_css_handler() {
if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'rocket_clear_usedcss' ) ) {
wp_nonce_ays( '' );
}
if ( ! current_user_can( 'rocket_remove_unused_css' ) ) {
rocket_get_constant( 'WP_ROCKET_IS_TESTING', false ) ? wp_die() : exit;
}
if ( ! $this->settings->is_enabled() ) {
set_transient(
'rocket_clear_usedcss_response',
[
'status' => 'error',
'message' => sprintf(
// translators: %1$s = plugin name.
__( '%1$s: Used CSS option is not enabled!', 'rocket' ),
'<strong>WP Rocket</strong>'
),
]
);
wp_safe_redirect( esc_url_raw( wp_get_referer() ) );
rocket_get_constant( 'WP_ROCKET_IS_TESTING', false ) ? wp_die() : exit;
}
rocket_clean_domain();
$this->delete_used_css_rows();
rocket_dismiss_box( 'rocket_warning_plugin_modification' );
set_transient(
'rocket_clear_usedcss_response',
[
'status' => 'success',
'message' => sprintf(
// translators: %1$s = plugin name.
__( '%1$s: Used CSS cache cleared!', 'rocket' ),
'<strong>WP Rocket</strong>'
),
]
);
$this->set_notice_transient();
wp_safe_redirect( esc_url_raw( wp_get_referer() ) );
rocket_get_constant( 'WP_ROCKET_IS_TESTING', false ) ? wp_die() : exit;
}
/**
* Show admin notice after clearing used_css table.
*
* @since 3.9
*
* @return void
*/
public function clear_usedcss_result() {
if ( ! current_user_can( 'rocket_remove_unused_css' ) ) {
return;
}
if ( ! $this->settings->is_enabled() ) {
return;
}
$response = get_transient( 'rocket_clear_usedcss_response' );
if ( ! $response ) {
return;
}
delete_transient( 'rocket_clear_usedcss_response' );
rocket_notice_html( $response );
}
/**
* Add Clean used CSS link to WP Rocket admin bar item
*
* @since 3.9
*
* @param \WP_Admin_Bar $wp_admin_bar WP_Admin_Bar instance, passed by reference.
*
* @return void
*/
public function add_clean_used_css_menu_item( $wp_admin_bar ) {
$this->settings->add_clean_used_css_menu_item( $wp_admin_bar );
}
/**
* Set optimize css delivery value
*
* @since 3.10
*
* @param array $field_args Array of field to be added to settings page.
*
* @return array
*/
public function set_optimize_css_delivery_value( $field_args ): array {
return $this->settings->set_optimize_css_delivery_value( $field_args );
}
/**
* Set optimize css delivery method value
*
* @since 3.10
*
* @param array $field_args Array of field to be added to settings page.
*
* @return array
*/
public function set_optimize_css_delivery_method_value( $field_args ): array {
return $this->settings->set_optimize_css_delivery_method_value( $field_args );
}
/**
* Displays the RUCSS currently processing notice
*
* @since 3.11
*
* @return void
*/
public function display_processing_notice() {
$this->settings->display_processing_notice();
}
/**
* Displays the RUCSS success notice
*
* @since 3.11
*
* @return void
*/
public function display_success_notice() {
$this->settings->display_success_notice();
}
/**
* Display a notification on wrong license.
*
* @return void
*/
public function display_wrong_license_notice() {
$transient = get_option( 'wp_rocket_no_licence' );
if ( ! $transient ) {
return;
}
$this->settings->display_wrong_license_notice();
}
/**
* Display error notice when connection to SAAS fails
*
* @return void
*/
public function display_saas_error_notice() {
$this->settings->display_saas_error_notice();
}
/**
* Display admin notice when detecting any missed Action scheduler tables.
*
* @since 3.11.0.3
*
* @return void
*/
public function display_as_missed_tables_notice() {
$screen = get_current_screen();
if ( isset( $screen->id ) && 'tools_page_action-scheduler' === $screen->id ) {
return;
}
if ( $this->is_valid_as_tables() ) {
return;
}
$this->settings->display_as_missed_tables_notice();
}
/**
* Adds the notice end time to WP Rocket localize script data
*
* @since 3.11
*
* @param array $data Localize script data.
* @return array
*/
public function add_localize_script_data( $data ): array {
return $this->settings->add_localize_script_data( $data );
}
/**
* Clear UsedCSS for the current URL.
*
* @return void
*/
public function clear_url_usedcss() {
check_admin_referer( 'rocket_clear_usedcss_url' );
if ( ! current_user_can( 'rocket_remove_unused_css' ) ) {
wp_nonce_ays( '' );
}
$url = wp_get_referer();
if ( 0 !== strpos( $url, 'http' ) ) {
$parse_url = get_rocket_parse_url( untrailingslashit( home_url() ) );
$url = $parse_url['scheme'] . '://' . $parse_url['host'] . $url;
}
$this->used_css->clear_url_usedcss( $url );
wp_safe_redirect( esc_url_raw( wp_get_referer() ) );
rocket_get_constant( 'WP_ROCKET_IS_TESTING', false ) ? wp_die() : exit;
}
/**
* Add clear UsedCSS adminbar item.
*
* @param WP_Admin_Bar $wp_admin_bar Adminbar object.
*
* @return void
*/
public function add_clear_usedcss_bar_item( WP_Admin_Bar $wp_admin_bar ) {
$this->used_css->add_clear_usedcss_bar_item( $wp_admin_bar );
}
/**
* Disables combine CSS if RUCSS is enabled when updating to 3.11
*
* @since 3.11
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function set_option_on_update( $new_version, $old_version ) {
$this->settings->set_option_on_update( $old_version );
if ( version_compare( $old_version, '3.11', '>=' ) ) {
return;
}
$this->database->truncate_used_css_table();
rocket_clean_domain();
$this->set_notice_transient();
}
/**
* Updates safelist items for new SaaS compatibility
*
* @since 3.11.0.2
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function update_safelist_items( $new_version, $old_version ) {
$this->settings->update_safelist_items( $old_version );
}
/**
* Cancel pending jobs actions in Action Scheduler on update to 3.11.3
*
* @since 3.11.3
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function cancel_pending_jobs_as( $new_version, $old_version ) {
if ( version_compare( $old_version, '3.11.3', '>=' ) ) {
return;
}
try {
$this->queue->cancel_pending_jobs_cron();
} catch ( \InvalidArgumentException $e ) {
// nothing to do.
return;
}
}
/**
* Sets the processing transient if RUCSS is enabled
*
* @since 3.11
*
* @param mixed $old_value Option old value.
* @param mixed $value Option new value.
*
* @return void
*/
public function maybe_set_processing_transient( $old_value, $value ) {
if ( ! isset( $old_value['remove_unused_css'], $value['remove_unused_css'] ) ) {
return;
}
if ( 0 === (int) $value['remove_unused_css'] ) {
return;
}
if ( $old_value['remove_unused_css'] === $value['remove_unused_css'] ) {
return;
}
$this->set_notice_transient();
}
/**
* Sets the transient for the processing notice
*
* @since 3.11
*
* @return void
*/
private function set_notice_transient() {
set_transient(
'rocket_rucss_processing',
time() + 90,
1.5 * MINUTE_IN_SECONDS
);
rocket_renew_box( 'rucss_success_notice' );
}
/**
* Sends a request to run cron when switching to RUCSS completed notice
*
* @since 3.11
*
* @return void
*/
public function spawn_cron() {
check_ajax_referer( 'rocket-ajax', 'nonce' );
if ( ! current_user_can( 'rocket_manage_options' ) ) {
wp_send_json_error();
return;
}
spawn_cron();
wp_send_json_success();
}
/**
* Cancel queues and crons for RUCSS.
*
* @return void
*/
public function cancel_queues() {
// Will unhook check for dispatching an async request without RUCSS process running.
\ActionScheduler_QueueRunner::instance()->unhook_dispatch_async_request();
// Will unhook check for dispatching an async request when RUCSS process is already running.
RUCSSQueueRunner::instance()->unhook_dispatch_async_request();
$this->queue->cancel_pending_jobs_cron();
if ( ! wp_next_scheduled( 'rocket_rucss_clean_rows_time_event' ) ) {
return;
}
wp_clear_scheduled_hook( 'rocket_rucss_clean_rows_time_event' );
}
/**
* Delete the transient for Action scheduler once admin visits the AS tools page.
*
* @return void
*/
public function delete_as_tables_transient_on_tools_page() {
delete_transient( 'rocket_rucss_as_tables_count' );
}
/**
* Deletes the used CSS on update to 3.11.4 for new storage method
*
* @since 3.11.4
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function delete_used_css( $new_version, $old_version ) {
if ( version_compare( $old_version, '3.11.4', '>=' ) ) {
return;
}
$this->database->truncate_used_css_table();
}
/**
* Disable RUCSS on wrong license.
*
* @return bool
*/
public function disable_russ_on_wrong_license() {
if ( false !== (bool) get_option( 'wp_rocket_no_licence' ) ) {
return false;
}
return null;
}
/**
* Remove the resources table & version stored in options table on update to 3.12
*
* @since 3.12
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function drop_resources_table( $new_version, $old_version ) {
if ( version_compare( $old_version, '3.12', '>=' ) ) {
return;
}
$this->database->drop_resources_table();
}
/**
* Displays a notice if the used CSS folder is not writable
*
* @since 3.11.4
*
* @return void
*/
public function notice_write_permissions() {
$this->used_css->notice_write_permissions();
}
/**
* Display a notice on table missing.
*
* @return void
*/
public function display_no_table_notice() {
$this->settings->display_no_table_notice();
}
/**
* Maybe delete transient.
*
* @param mixed $old_value Option old value.
* @param mixed $value Option new value.
*
* @return void
*/
public function maybe_delete_transient( $old_value, $value ) {
if ( ! isset( $old_value['remove_unused_css'], $value['remove_unused_css'] ) ) {
return;
}
if ( 1 === (int) $value['remove_unused_css'] ) {
return;
}
if ( $old_value['remove_unused_css'] === $value['remove_unused_css'] ) {
return;
}
delete_transient( 'wp_rocket_no_licence' );
}
/**
* Checks if the RUCSS deletion is enabled.
*
* @return bool
*/
protected function is_deletion_enabled(): bool {
/**
* Filters the enable RUCSS deletion value
*
* @param bool $delete_rucss True to enable deletion, false otherwise.
*/
return (bool) apply_filters( 'rocket_rucss_deletion_enabled', true );
}
}
@@ -0,0 +1,56 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS\Context;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Common\Context\AbstractContext;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\Filesystem;
class RUCSSContext extends AbstractContext {
/**
* Filesystem instance
*
* @var Filesystem
*/
protected $filesystem;
/**
* Instantiate the class.
*
* @param Options_Data $options Options.
* @param Filesystem $filesystem Filesystem instance.
*/
public function __construct( Options_Data $options, Filesystem $filesystem ) {
parent::__construct( $options );
$this->filesystem = $filesystem;
}
/**
* Check if the operation is allowed.
*
* @param array $data Data to provide to the context.
* @return bool
*/
public function is_allowed( array $data = [] ): bool {
$is_allowed = $this->run_common_checks(
[
'do_not_optimize' => false,
'bypass' => false,
'option' => 'remove_unused_css',
'password_protected' => false,
'post_excluded' => 'remove_unused_css',
'logged_in' => false,
]
);
if ( ! $is_allowed ) {
return false;
}
return $this->filesystem->is_writable_folder();
}
}
@@ -0,0 +1,46 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS\Context;
use WP_Rocket\Engine\Common\Context\AbstractContext;
class RUCSSOptimizeContext extends AbstractContext {
/**
* Check if the operation is allowed.
*
* @param array $data Data to provide to the context.
* @return bool
*/
public function is_allowed( array $data = [] ): bool {
$is_allowed = $this->run_common_checks(
[
'bypass' => false,
'option' => 'remove_unused_css',
'post_excluded' => 'remove_unused_css',
]
);
if ( 'local' === wp_get_environment_type() ) {
return false;
}
if ( ! current_user_can( 'rocket_remove_unused_css' ) ) {
return false;
}
if ( is_admin() ) {
return false;
}
if ( ! $is_allowed ) {
return false;
}
if ( ! rocket_can_display_options() ) {
return false;
}
return true;
}
}
@@ -0,0 +1,173 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Controller;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class Filesystem {
/**
* WP Filesystem instance
*
* @var WP_Filesystem_Direct
*/
private $filesystem;
/**
* Path to the used CSS storage
*
* @var string
*/
private $path;
/**
* Instantiate the class
*
* @param string $base_path Base path to the used CSS storage.
* @param WP_Filesystem_Direct $filesystem WP Filesystem instance.
*/
public function __construct( $base_path, $filesystem = null ) {
$this->filesystem = is_null( $filesystem ) ? rocket_direct_filesystem() : $filesystem;
$this->path = $base_path . get_current_blog_id() . '/';
}
/**
* Get the file path for the used CSS file.
*
* @param string $hash Hash of the file contents.
*
* @return string Path for the used CSS file.
*/
private function get_usedcss_full_path( string $hash ) {
return $this->path . $this->hash_to_path( $hash ) . '.css' . ( function_exists( 'gzdecode' ) ? '.gz' : '' );
}
/**
* Gets the used CSS content corresponding to the provided hash
*
* @param string $hash Hash of the corresponding used CSS.
*
* @return string
*/
public function get_used_css( string $hash ): string {
$file = $this->get_usedcss_full_path( $hash );
if ( ! $this->filesystem->exists( $file ) ) {
return '';
}
$file_contents = $this->filesystem->get_contents( $file );
$css = function_exists( 'gzdecode' ) ? gzdecode( $file_contents ) : $file_contents;
if ( ! $css ) {
return '';
}
return $css;
}
/**
* Writes the used CSS to the filesystem
*
* @param string $hash Hash to use for the filename.
* @param string $used_css Used CSS content.
*
* @return bool
*/
public function write_used_css( string $hash, string $used_css ): bool {
$file = $this->get_usedcss_full_path( $hash );
if ( ! rocket_mkdir_p( dirname( $file ) ) ) {
return false;
}
// This filter is documented in inc/classes/Buffer/class-cache.php.
$css = function_exists( 'gzencode' ) ? gzencode( $used_css, apply_filters( 'rocket_gzencode_level_compression', 6 ) ) : $used_css;
if ( ! $css ) {
return false;
}
return $this->filesystem->put_contents( $file, $css, rocket_get_filesystem_perms( 'file' ) );
}
/**
* Deletes the used CSS files for the corresponding hash
*
* @since 3.11.4
*
* @param string $hash md5 hash string.
*
* @return bool
*/
public function delete_used_css( string $hash ): bool {
$file = $this->get_usedcss_full_path( $hash );
return $this->filesystem->delete( $file, false, 'f' );
}
/**
* Deletes all the used CSS files
*
* @since 3.11.4
*
* @return void
*/
public function delete_all_used_css() {
try {
$dir = new RecursiveDirectoryIterator( $this->path, \FilesystemIterator::SKIP_DOTS );
$items = new RecursiveIteratorIterator( $dir, RecursiveIteratorIterator::CHILD_FIRST );
foreach ( $items as $item ) {
$this->filesystem->delete( $item );
}
} catch ( \Exception $e ) {
return;
}
}
/**
* Checks if the used CSS storage folder is writable
*
* @since 3.11.4
*
* @return bool
*/
public function is_writable_folder() {
if ( ! $this->filesystem->exists( $this->path ) ) {
rocket_mkdir_p( $this->path );
}
return $this->filesystem->is_writable( $this->path );
}
/**
* Converts hash to path with filtered number of levels
*
* @since 3.11.4
*
* @param string $hash md5 hash string.
*
* @return string
*/
private function hash_to_path( string $hash ): string {
/**
* Filters the number of sub-folders level to create for used CSS storage
*
* @since 3.11.4
*
* @param int $levels Number of levels.
*/
$levels = apply_filters( 'rocket_used_css_dir_level', 3 );
$base = substr( $hash, 0, $levels );
$remain = substr( $hash, $levels );
$path_array = str_split( $base );
$path_array[] = $remain;
return implode( '/', $path_array );
}
}
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Controller;
use WP_Rocket\Engine\Common\Queue\AbstractASQueue;
/**
* Queue
*
* A job queue using WordPress actions.
*
* @version 3.11.0
*/
class Queue extends AbstractASQueue {
/**
* Queue group.
*
* @var string
*/
protected $group = 'rocket-rucss';
/**
* Pending jobs cron hook.
*
* @var string
*/
private $pending_job_cron = 'rocket_rucss_pending_jobs_cron';
/**
* Check if pending jobs cron is scheduled.
*
* @return bool
*/
public function is_pending_jobs_cron_scheduled() {
return $this->is_scheduled( $this->pending_job_cron );
}
/**
* Cancel pending jobs cron.
*
* @return void
*/
public function cancel_pending_jobs_cron() {
$this->cancel_all( $this->pending_job_cron );
}
/**
* Schedule pending jobs cron.
*
* @param int $interval Cron interval in seconds.
*
* @return string
*/
public function schedule_pending_jobs_cron( int $interval ) {
return $this->schedule_recurring( time(), $interval, $this->pending_job_cron );
}
/**
* Add Async job with DB row ID.
*
* @param int $usedcss_row_id DB row ID.
*
* @return string
*/
public function add_job_status_check_async( int $usedcss_row_id ) {
return $this->add_async(
'rocket_rucss_job_check_status',
[
$usedcss_row_id,
]
);
}
}
@@ -0,0 +1,308 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Cron;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Rocket\Engine\Common\Queue\RUCSSQueueRunner;
use WP_Rocket\Engine\Optimization\RUCSS\Admin\Database;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\UsedCSS;
class Subscriber implements Subscriber_Interface {
/**
* UsedCss instance
*
* @var UsedCSS
*/
private $used_css;
/**
* Database instance
*
* @var Database
*/
private $database;
/**
* Instantiate the class
*
* @param UsedCSS $used_css UsedCSS instance.
* @param Database $database Database instance.
*/
public function __construct( UsedCSS $used_css, Database $database ) {
$this->used_css = $used_css;
$this->database = $database;
}
/**
* Return an array of events that this subscriber listens to.
*
* @return array
*/
public static function get_subscribed_events(): array {
return [
'rocket_rucss_pending_jobs' => 'process_pending_jobs',
'rocket_rucss_on_submit_jobs' => 'process_on_submit_jobs',
'rocket_rucss_job_check_status' => 'check_job_status',
'rocket_rucss_clean_rows_time_event' => 'cron_clean_rows',
'cron_schedules' => 'add_interval',
'rocket_deactivation' => 'on_deactivation',
'rocket_remove_rucss_failed_jobs' => 'cron_remove_failed_jobs',
'init' => [
[ 'schedule_clean_not_commonly_used_rows' ],
[ 'schedule_pending_jobs' ],
[ 'initialize_rucss_queue_runner' ],
[ 'schedule_removing_failed_jobs' ],
[ 'schedule_on_submit_jobs' ],
],
];
}
/**
* Schedules cron to clean not commonly used RUCSS rows.
*
* @since 3.9
*
* @return void
*/
public function schedule_clean_not_commonly_used_rows() {
if ( ! $this->used_css->is_enabled() ) {
return;
}
if ( wp_next_scheduled( 'rocket_rucss_clean_rows_time_event' ) ) {
return;
}
wp_schedule_event( time(), 'weekly', 'rocket_rucss_clean_rows_time_event' );
}
/**
* Initialize the queue runner for our RUCSS.
*
* @return void
*/
public function initialize_rucss_queue_runner() {
if ( ! $this->used_css->is_enabled() ) {
return;
}
RUCSSQueueRunner::instance()->init();
}
/**
* Process pending jobs with Cron iteration.
*
* @return void
*/
public function process_pending_jobs() {
$this->used_css->process_pending_jobs();
}
/**
* Process on submit jobs with Cron iteration.
*
* @return void
*/
public function process_on_submit_jobs() {
$this->used_css->process_on_submit_jobs();
}
/**
* Cron callback for deleting old rows in both table databases.
*
* @since 3.9
*
* @return void
*/
public function cron_clean_rows() {
if ( ! $this->is_deletion_enabled() ) {
return;
}
$this->database->delete_old_used_css();
}
/**
* Cron callback for removing failed jobs.
*
* @return void
*/
public function cron_remove_failed_jobs() {
$this->used_css->clear_failed_urls();
}
/**
* Handle job status by DB row ID.
*
* @param int $row_id DB Row ID.
*
* @return void
*/
public function check_job_status( int $row_id ) {
$this->used_css->check_job_status( $row_id );
}
/**
* Adds new interval for RUCSS pending jobs cron
*
* @since 3.11.3
*
* @param array[] $schedules An array of non-default cron schedule arrays.
*
* @return array
*/
public function add_interval( $schedules ) {
if ( ! $this->used_css->is_enabled() ) {
return $schedules;
}
/**
* Filters the cron interval.
*
* @since 3.11
*
* @param int $interval Interval in seconds.
*/
$interval = apply_filters( 'rocket_rucss_pending_jobs_cron_interval', 1 * rocket_get_constant( 'MINUTE_IN_SECONDS', 60 ) );
$schedules['rocket_rucss_pending_jobs'] = [
'interval' => $interval,
'display' => esc_html__( 'WP Rocket Remove Unused CSS pending jobs', 'rocket' ),
];
$default_interval = 3 * rocket_get_constant( 'DAY_IN_SECONDS', 86400 );
/**
* Filters the cron interval for clearing failed jobs.
*
* @param int $interval Interval in seconds.
*/
$interval = apply_filters( 'rocket_remove_rucss_failed_jobs_cron_interval', $default_interval );
$interval = (bool) $interval ? $interval : $default_interval;
$schedules['rocket_remove_rucss_failed_jobs'] = [
'interval' => $interval,
'display' => esc_html__( 'WP Rocket clear Remove Unused CSS failed jobs', 'rocket' ),
];
/**
* Filters the cron interval for processing on submit jobs.
*
* @param int $interval Interval in seconds.
*/
$interval = (int) apply_filters( 'rocket_remove_rucss_on_submit_jobs_cron_interval', 1 * rocket_get_constant( 'MINUTE_IN_SECONDS', 60 ) );
$schedules['rocket_rucss_on_submit_jobs'] = [
'interval' => $interval,
'display' => esc_html__( 'WP Rocket procees on submit jobs', 'rocket' ),
];
return $schedules;
}
/**
* Schedule on submit jobs.
*
* @return void
*/
public function schedule_on_submit_jobs() {
if (
! $this->used_css->is_enabled()
&&
wp_next_scheduled( 'rocket_rucss_on_submit_jobs' )
) {
wp_clear_scheduled_hook( 'rocket_rucss_on_submit_jobs' );
return;
}
if ( ! $this->used_css->is_enabled() ) {
return;
}
if ( wp_next_scheduled( 'rocket_rucss_on_submit_jobs' ) ) {
return;
}
wp_schedule_event( time(), 'rocket_rucss_on_submit_jobs', 'rocket_rucss_on_submit_jobs' );
}
/**
* Schedules cron to get RUCSS pendings jobs.
*
* @since 3.11.3
*
* @return void
*/
public function schedule_pending_jobs() {
if (
! $this->used_css->is_enabled()
&&
wp_next_scheduled( 'rocket_rucss_pending_jobs' )
) {
wp_clear_scheduled_hook( 'rocket_rucss_pending_jobs' );
return;
}
if ( ! $this->used_css->is_enabled() ) {
return;
}
if ( wp_next_scheduled( 'rocket_rucss_pending_jobs' ) ) {
return;
}
wp_schedule_event( time(), 'rocket_rucss_pending_jobs', 'rocket_rucss_pending_jobs' );
}
/**
* Schedules cron to remove failed jobs.
*
* @return void
*/
public function schedule_removing_failed_jobs() {
if (
! $this->used_css->is_enabled()
&&
wp_next_scheduled( 'rocket_remove_rucss_failed_jobs' )
) {
wp_clear_scheduled_hook( 'rocket_remove_rucss_failed_jobs' );
return;
}
if ( ! $this->used_css->is_enabled() ) {
return;
}
if ( wp_next_scheduled( 'rocket_remove_rucss_failed_jobs' ) ) {
return;
}
wp_schedule_event( time(), 'rocket_remove_rucss_failed_jobs', 'rocket_remove_rucss_failed_jobs' );
}
/**
* Clear schedule of RUCSS CRONs on deactivation.
*
* @return void
*/
public function on_deactivation() {
wp_clear_scheduled_hook( 'action_scheduler_run_queue_rucss', [ 'WP Cron' ] );
}
/**
* Checks if the RUCSS deletion is enabled.
*
* @return bool
*/
protected function is_deletion_enabled(): bool {
/**
* Filters the enable RUCSS deletion value
*
* @param bool $delete_rucss True to enable deletion, false otherwise.
*/
return (bool) apply_filters( 'rocket_rucss_deletion_enabled', true );
}
}
@@ -0,0 +1,608 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS\Database\Queries;
use WP_Rocket\Dependencies\Database\Query;
use WP_Rocket\Engine\Optimization\RUCSS\Database\Row\UsedCSS as UsedCSSRow;
use WP_Rocket\Engine\Optimization\RUCSS\Database\Schemas\UsedCSS as UsedCSSSchema;
/**
* RUCSS UsedCSS Query.
*/
class UsedCSS extends Query {
/**
* Name of the database table to query.
*
* @var string
*/
protected $table_name = 'wpr_rucss_used_css';
/**
* String used to alias the database table in MySQL statement.
*
* Keep this short, but descriptive. I.E. "tr" for term relationships.
*
* This is used to avoid collisions with JOINs.
*
* @var string
*/
protected $table_alias = 'wpr_rucss';
/**
* Name of class used to setup the database schema.
*
* @var string
*/
protected $table_schema = UsedCSSSchema::class;
/** Item ******************************************************************/
/**
* Name for a single item.
*
* Use underscores between words. I.E. "term_relationship"
*
* This is used to automatically generate action hooks.
*
* @var string
*/
protected $item_name = 'used_css';
/**
* Plural version for a group of items.
*
* Use underscores between words. I.E. "term_relationships"
*
* This is used to automatically generate action hooks.
*
* @var string
*/
protected $item_name_plural = 'used_css';
/**
* Name of class used to turn IDs into first-class objects.
*
* This is used when looping through return values to guarantee their shape.
*
* @var mixed
*/
protected $item_shape = UsedCSSRow::class;
/**
* Table status.
*
* @var boolean
*/
public static $table_exists = false;
/**
* Get pending jobs.
*
* @param int $count Number of rows.
*
* @return array
*/
public function get_pending_jobs( int $count = 100 ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return [];
}
$inprogress_count = $this->query(
[
'count' => true,
'status' => 'in-progress',
]
);
if ( $inprogress_count >= $count ) {
return [];
}
return $this->query(
[
'number' => ( $count - $inprogress_count ),
'status' => 'pending',
'fields' => [
'id',
'url',
],
'job_id__not_in' => [
'not_in' => '',
],
'orderby' => 'modified',
'order' => 'asc',
]
);
}
/**
* Fetch on submit jobs.
*
* @param int $count Number of jobs to fetch.
* @return array|int
*/
public function get_on_submit_jobs( int $count = 100 ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return [];
}
$in_progress_count = $this->query(
[
'count' => true,
'status' => [ 'in-progress' ],
]
);
$pending_count = $this->query(
[
'count' => true,
'status' => [ 'pending' ],
]
);
$processing_count = $in_progress_count + $pending_count;
if ( 0 !== $count && $processing_count >= $count ) {
return [];
}
$query_params = [
'status' => 'to-submit',
'orderby' => 'modified',
'order' => 'asc',
];
if ( 0 !== $count ) {
$query_params['number'] = ( $count - $processing_count );
}
return $this->query( $query_params );
}
/**
* Increment retries number and change status back to pending.
*
* @param int $id DB row ID.
* @param int $retries Current number of retries.
*
* @return bool
*/
public function increment_retries( $id, $retries = 0 ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$update_data = [
'retries' => $retries + 1,
'status' => 'pending',
];
return $this->update_item( $id, $update_data );
}
/**
* Update Job ID.
*
* @param int $id DB row ID.
* @param int $new_job_id new job id.
*
* @return bool
*/
public function update_job_id( $id, $new_job_id ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$update_data['job_id'] = $new_job_id;
return $this->update_item( $id, $update_data );
}
/**
* Create new DB row for specific url.
*
* @param string $url Current page url.
* @param string $job_id API job_id.
* @param string $queue_name API Queue name.
* @param bool $is_mobile if the request is for mobile page.
*
* @return bool
*/
public function create_new_job( string $url, string $job_id = '', string $queue_name = '', bool $is_mobile = false ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$item = [
'url' => untrailingslashit( $url ),
'is_mobile' => $is_mobile,
'job_id' => $job_id,
'queue_name' => $queue_name,
'status' => 'to-submit',
'retries' => 0,
'last_accessed' => current_time( 'mysql', true ),
'submitted_at' => current_time( 'mysql', true ),
];
return $this->add_item( $item );
}
/**
* Change the status to be in-progress.
*
* @param int $id DB row ID.
*
* @return bool
*/
public function make_status_inprogress( int $id ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return $this->update_item(
$id,
[
'status' => 'in-progress',
]
);
}
/**
* Reset the job and add new job_id pending.
*
* @param int $id DB row ID.
* @param string $job_id API job_id.
*
* @return bool
*/
public function reset_job( int $id, string $job_id = '' ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return $this->update_item(
$id,
[
'job_id' => $job_id,
'status' => 'to-submit',
'error_code' => '',
'error_message' => '',
'retries' => 0,
'modified' => current_time( 'mysql', true ),
'submitted_at' => current_time( 'mysql', true ),
]
);
}
/**
* Change the status to be failed.
*
* @param int $id DB row ID.
* @param string $error_code error code.
* @param string $error_message error message.
*
* @return bool
*/
public function make_status_failed( int $id, string $error_code, string $error_message ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return $this->update_item(
$id,
[
'status' => 'failed',
'error_code' => $error_code,
'error_message' => current_time( 'mysql', true ) . " {$error_code}: {$error_message}",
]
);
}
/**
* Complete a job.
*
* @param int $id DB row ID.
* @param string $hash Hash.
*
* @return bool
*/
public function make_status_completed( int $id, string $hash = '' ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return $this->update_item(
$id,
[
'hash' => $hash,
'status' => 'completed',
]
);
}
/**
* Get Used CSS for specific url.
*
* @param string $url Page Url.
* @param bool $is_mobile if the request is for mobile page.
*
* @return false|mixed
*/
public function get_row( string $url, bool $is_mobile = false ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$query = $this->query(
[
'url' => untrailingslashit( $url ),
'is_mobile' => $is_mobile,
]
);
if ( empty( $query[0] ) ) {
return false;
}
return $query[0];
}
/**
* Get all rows with the same url (desktop and mobile versions).
*
* @param string $url Page url.
*
* @return array|false
*/
public function get_rows_by_url( string $url ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$query = $this->query(
[
'url' => untrailingslashit( $url ),
]
);
if ( empty( $query ) ) {
return false;
}
return $query;
}
/**
* Get number of rows with the same hash value.
*
* @param string $hash Hash.
*
* @return int
*/
public function count_rows_by_hash( string $hash ): int {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return 0;
}
return $this->query(
[
'hash' => $hash,
'count' => true,
]
);
}
/**
* Update UsedCSS Row last_accessed date to current date.
*
* @param int $id Used CSS id.
*
* @return bool
*/
public function update_last_accessed( int $id ): bool {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return (bool) $this->update_item(
$id,
[
'last_accessed' => current_time( 'mysql', true ),
]
);
}
/**
* Delete DB row by url.
*
* @param string $url Page url to be deleted.
*
* @return bool
*/
public function delete_by_url( string $url ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$items = $this->get_rows_by_url( $url );
if ( ! $items ) {
return false;
}
$deleted = true;
foreach ( $items as $item ) {
$deleted = $deleted && $this->delete_item( $item->id );
}
return $deleted;
}
/**
* Get the count of not completed rows.
*
* @return int
*/
public function get_not_completed_count() {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return 0;
}
return $this->query(
[
'count' => true,
'status__in' => [ 'pending', 'in-progress' ],
]
);
}
/**
* Get the count of completed rows.
*
* @return int
*/
public function get_completed_count() {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return 0;
}
return $this->query(
[
'count' => true,
'status' => 'completed',
]
);
}
/**
* Get all failed rows.
*
* @param float $delay delay before the urls are deleted.
* @param string $unit unit from the delay.
* @return array|false
*/
public function get_failed_rows( float $delay = 3, string $unit = 'days' ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
$query = $this->query(
[
'status' => 'failed',
'date_query' => [
[
'column' => 'modified',
'before' => "$delay $unit ago",
'inclusive' => true,
],
],
],
false
);
if ( empty( $query ) ) {
return false;
}
return $query;
}
/**
* Revert status to pending.
*
* @param integer $id Used CSS id.
* @return boolean
*/
public function revert_to_pending( int $id ): bool {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return (bool) $this->update_item(
$id,
[
'error_code' => '',
'error_message' => '',
'retries' => 0,
'status' => 'pending',
'modified' => current_time( 'mysql', true ),
]
);
}
/**
* Returns the current status of `wpr_rucss_used_css` table; true if it exists, false otherwise.
*
* @return boolean
*/
private function table_exists(): bool {
if ( self::$table_exists ) {
return true;
}
// Get the database interface.
$db = $this->get_db();
// Bail if no database interface is available.
if ( empty( $db ) ) {
return false;
}
// Query statement.
$query = 'SHOW TABLES LIKE %s';
$like = $db->esc_like( $db->{$this->table_name} );
$prepared = $db->prepare( $query, $like );
$result = $db->get_var( $prepared );
// Does the table exist?
$exists = $this->is_success( $result );
if ( $exists ) {
self::$table_exists = $exists;
}
return $exists;
}
/**
* Update the error message.
*
* @param int $job_id Job ID.
* @param int $code Response code.
* @param string $message Response message.
* @param string $previous_message Previous saved message.
*
* @return bool
*/
public function update_message( int $job_id, int $code, string $message, string $previous_message = '' ): bool {
return $this->update_item(
$job_id,
[
'error_message' => $previous_message . ' - ' . current_time( 'mysql', true ) . " {$code}: {$message}",
]
);
}
/**
* Change the status to be pending.
*
* @param int $id DB row ID.
* @param string $job_id API job_id.
* @param string $queue_name API Queue name.
* @param bool $is_mobile if the request is for mobile page.
* @return bool
*/
public function make_status_pending( int $id, string $job_id = '', string $queue_name = '', bool $is_mobile = false ) {
if ( ! self::$table_exists && ! $this->table_exists() ) {
return false;
}
return $this->update_item(
$id,
[
'job_id' => $job_id,
'queue_name' => $queue_name,
'status' => 'pending',
'is_mobile' => $is_mobile,
]
);
}
}
@@ -0,0 +1,140 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS\Database\Row;
use WP_Rocket\Dependencies\Database\Row;
/**
* RUCSS UsedCSS Row.
*/
class UsedCSS extends Row {
/**
* Row ID
*
* @var int
*/
public $id;
/**
* URL
*
* @var string
*/
public $url;
/**
* CSS
*
* @var string
*/
public $css;
/**
* Hash storage value
*
* @var string
*/
public $hash;
/**
* Error code
*
* @var string
*/
public $error_code;
/**
* Error message
*
* @var string
*/
public $error_message;
/**
* Number of retries
*
* @var int
*/
public $retries;
/**
* Is CSS for mobile
*
* @var bool
*/
public $is_mobile;
/**
* Job ID
*
* @var string
*/
public $job_id;
/**
* Job queue name
*
* @var string
*/
public $queue_name;
/**
* Status
*
* @var string
*/
public $status;
/**
* Last modified time
*
* @var int
*/
public $modified;
/**
* Last accessed time
*
* @var int
*/
public $last_accessed;
/**
* Unused variable
*
* @var string
*/
public $unprocessedcss;
/**
* Submitted date
*
* @var int
*/
public $submitted_at;
/**
* UsedCSS constructor.
*
* @param mixed $item Object Row.
*/
public function __construct( $item ) {
parent::__construct( $item );
// Set the type of each column, and prepare.
$this->id = (int) $this->id;
$this->url = (string) $this->url;
$this->css = (string) $this->css;
$this->hash = (string) $this->hash;
$this->error_code = (string) $this->error_code;
$this->error_message = (string) $this->error_message;
$this->retries = (int) $this->retries;
$this->is_mobile = (bool) $this->is_mobile;
$this->job_id = (string) $this->job_id;
$this->queue_name = (string) $this->queue_name;
$this->status = (string) $this->status;
$this->modified = empty( $this->modified ) ? 0 : strtotime( $this->modified );
$this->last_accessed = empty( $this->last_accessed ) ? 0 : strtotime( $this->last_accessed );
$this->submitted_at = empty( $this->submitted_at ) ? 0 : strtotime( $this->submitted_at );
}
}
@@ -0,0 +1,168 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS\Database\Schemas;
use WP_Rocket\Dependencies\Database\Schema;
/**
* RUCSS UsedCSS Schema.
*/
class UsedCSS extends Schema {
/**
* Array of database column objects
*
* @var array
*/
public $columns = [
// ID column.
[
'name' => 'id',
'type' => 'bigint',
'length' => '20',
'unsigned' => true,
'extra' => 'auto_increment',
'primary' => true,
'sortable' => true,
],
// URL column.
[
'name' => 'url',
'type' => 'varchar',
'length' => '2000',
'default' => '',
'cache_key' => true,
'searchable' => true,
'sortable' => true,
],
// CSS column.
[
'name' => 'css',
'type' => 'longtext',
'default' => null,
'cache_key' => false,
'searchable' => true,
'sortable' => true,
],
// Hash column.
[
'name' => 'hash',
'type' => 'varchar',
'length' => '32',
'default' => '',
'cache_key' => false,
'searchable' => true,
'sortable' => true,
],
// error_code column.
[
'name' => 'error_code',
'type' => 'varchar',
'length' => '32',
'default' => null,
'cache_key' => false,
'searchable' => true,
'sortable' => true,
],
// error_message column.
[
'name' => 'error_message',
'type' => 'longtext',
'default' => null,
'cache_key' => false,
'searchable' => true,
'sortable' => true,
],
// RETRIES column.
[
'name' => 'retries',
'type' => 'tinyint',
'length' => '1',
'default' => 1,
'cache_key' => false,
'searchable' => true,
'sortable' => true,
],
// IS_MOBILE column.
[
'name' => 'is_mobile',
'type' => 'tinyint',
'length' => '1',
'default' => 0,
'cache_key' => true,
'searchable' => true,
'sortable' => true,
],
// JOB_ID column.
[
'name' => 'job_id',
'type' => 'varchar',
'length' => '255',
'default' => null,
'cache_key' => true,
'searchable' => false,
'sortable' => false,
],
// QUEUE_NAME column.
[
'name' => 'queue_name',
'type' => 'varchar',
'length' => '255',
'default' => null,
'cache_key' => true,
'searchable' => false,
'sortable' => false,
],
// STATUS column.
[
'name' => 'status',
'type' => 'varchar',
'length' => '255',
'default' => null,
'cache_key' => true,
'searchable' => true,
'sortable' => false,
],
// MODIFIED column.
[
'name' => 'modified',
'type' => 'timestamp',
'default' => '0000-00-00 00:00:00',
'created' => true,
'date_query' => true,
'sortable' => true,
],
// LAST_ACCESSED column.
[
'name' => 'last_accessed',
'type' => 'timestamp',
'default' => '0000-00-00 00:00:00',
'created' => true,
'date_query' => true,
'sortable' => true,
],
// SUBMITTED_AT column.
[
'name' => 'submitted_at',
'type' => 'timestamp',
'default' => null,
'created' => true,
'date_query' => true,
'sortable' => true,
],
];
}
@@ -0,0 +1,345 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS\Database\Tables;
use WP_Rocket\Dependencies\Database\Table;
/**
* RUCSS UsedCSS Table.
*/
class UsedCSS extends Table {
/**
* Table name
*
* @var string
*/
protected $name = 'wpr_rucss_used_css';
/**
* Database version key (saved in _options or _sitemeta)
*
* @var string
*/
protected $db_version_key = 'wpr_rucss_used_css_version';
/**
* Database version
*
* @var int
*/
protected $version = 20231010;
/**
* Key => value array of versions => methods.
*
* @var array
*/
protected $upgrades = [
20220121 => 'add_async_rucss_columns',
20220131 => 'make_status_column_index',
20220513 => 'add_hash_column',
20220920 => 'make_status_column_index_instead_queue_name',
20221104 => 'add_error_columns',
20231010 => 'add_submitted_at_column',
];
/**
* Instantiate class.
*/
public function __construct() {
parent::__construct();
add_action( 'admin_init', [ $this, 'maybe_trigger_recreate_table' ], 9 );
add_action( 'init', [ $this, 'maybe_upgrade' ] );
}
/**
* Setup the database schema
*
* @return void
*/
protected function set_schema() {
$this->schema = "
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
url varchar(2000) NOT NULL default '',
css longtext default NULL,
hash varchar(32) default '',
error_code varchar(32) NULL default NULL,
error_message longtext NULL default NULL,
unprocessedcss longtext NULL,
retries tinyint(1) NOT NULL default 1,
is_mobile tinyint(1) NOT NULL default 0,
job_id varchar(255) NOT NULL default '',
queue_name varchar(255) NOT NULL default '',
status varchar(255) NOT NULL default '',
modified timestamp NOT NULL default '0000-00-00 00:00:00',
last_accessed timestamp NOT NULL default '0000-00-00 00:00:00',
submitted_at timestamp NULL,
PRIMARY KEY (id),
KEY url (url(150), is_mobile),
KEY modified (modified),
KEY last_accessed (last_accessed),
INDEX `status_index` (`status`(191)),
INDEX `error_code_index` (`error_code`(32)),
KEY hash (hash)";
}
/**
* Delete all used_css which were not accessed in the last month.
*
* @return bool|int
*/
public function delete_old_used_css() {
// Get the database interface.
$db = $this->get_db();
// Bail if no database interface is available.
if ( empty( $db ) ) {
return false;
}
/**
* Filters the old RUCSS deletion interval
*
* @param int $delete_interval Old RUCSS deletion interval in months
*/
$delete_interval = (int) apply_filters( 'rocket_rucss_delete_interval', 1 );
if ( $delete_interval <= 0 ) {
return false;
}
$prefixed_table_name = $this->apply_prefix( $this->table_name );
$query = "DELETE FROM `$prefixed_table_name` WHERE `last_accessed` <= date_sub(now(), interval $delete_interval month)";
$rows_affected = $db->query( $query );
return $rows_affected;
}
/**
* Get all used_css which were not accessed in the last month.
*
* @return array
*/
public function get_old_used_css(): array {
// Get the database interface.
$db = $this->get_db();
// Bail if no database interface is available.
if ( empty( $db ) ) {
return false;
}
$prefixed_table_name = $this->apply_prefix( $this->table_name );
$query = "SELECT * FROM `$prefixed_table_name` WHERE `last_accessed` <= date_sub(now(), interval 1 month)";
$rows_affected = $db->get_results( $query );
return $rows_affected;
}
/**
* Add queue columns.
*
* @return bool
*/
protected function add_async_rucss_columns() {
$jobid_column_exists = $this->column_exists( 'job_id' );
$queuename_column_exists = $this->column_exists( 'queue_name' );
$status_column_exists = $this->column_exists( 'status' );
$created = true;
if ( ! $jobid_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD COLUMN job_id VARCHAR(255) NULL default '' AFTER is_mobile " );
}
if ( ! $queuename_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD COLUMN queue_name VARCHAR(255) NULL default '' AFTER job_id " );
}
if ( ! $status_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD COLUMN status VARCHAR(255) NULL default '' AFTER queue_name " );
}
return $this->is_success( $created );
}
/**
* Make status column as index.
*
* @return bool
*/
protected function make_status_column_index() {
$queuename_column_exists = $this->column_exists( 'queue_name' );
if ( ! $queuename_column_exists ) {
return $this->is_success( false );
}
if ( $this->index_exists( 'queue_name_index' ) ) {
return $this->is_success( true );
}
$index_added = $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD INDEX `queue_name_index` (`queue_name`) " );
return $this->is_success( $index_added );
}
/**
* Add hash column and index
*
* @return bool
*/
protected function add_hash_column() {
$hash_column_exists = $this->column_exists( 'hash' );
$created = true;
if ( ! $hash_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD COLUMN hash VARCHAR(32) NULL default '' AFTER css, ADD KEY hash (hash) " );
}
return $this->is_success( $created );
}
/**
* Make status column as index.
*
* @return bool
*/
protected function make_status_column_index_instead_queue_name() {
$queuename_column_exists = $this->column_exists( 'status' );
if ( ! $queuename_column_exists ) {
return $this->is_success( false );
}
if ( $this->index_exists( 'status_index' ) ) {
return $this->is_success( true );
}
if ( $this->index_exists( 'queue_name_index' ) ) {
if ( ! $this->get_db()->query( "ALTER TABLE {$this->table_name} DROP INDEX `queue_name_index`" ) ) {
return $this->is_success( false );
}
}
$index_added = $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD INDEX `status_index` (`status`(191)) " );
return $this->is_success( $index_added );
}
/**
* Remove all completed rows.
*
* @return bool|int
*/
public function remove_all_completed_rows() {
// Get the database interface.
$db = $this->get_db();
// Bail if no database interface is available.
if ( empty( $db ) ) {
return false;
}
$prefixed_table_name = $this->apply_prefix( $this->table_name );
return $db->query( "DELETE FROM `$prefixed_table_name` WHERE status IN ( 'failed', 'completed' )" );
}
/**
* Returns name from table.
*
* @return string
*/
public function get_name() {
return $this->apply_prefix( $this->table_name );
}
/**
* Trigger recreation of cache table if not exist.
*
* @return void
*/
public function maybe_trigger_recreate_table() {
if ( $this->exists() ) {
return;
}
delete_option( $this->db_version_key );
}
/**
* Add error columns
*
* @return bool
*/
protected function add_error_columns() {
return $this->add_error_message_column() && $this->add_error_code_column() && $this->make_error_code_column_index();
}
/**
* Add error_message column and index
*
* @return bool
*/
private function add_error_message_column() {
$error_message_column_exists = $this->column_exists( 'error_message' );
$created = true;
if ( ! $error_message_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE `{$this->table_name}` ADD COLUMN error_message longtext NULL default NULL AFTER hash" );
}
return $this->is_success( $created );
}
/**
* Add error_code column and index
*
* @return bool
*/
private function add_error_code_column() {
$error_code_column_exists = $this->column_exists( 'error_code' );
$created = true;
if ( ! $error_code_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE `{$this->table_name}` ADD COLUMN error_code VARCHAR(32) NULL default NULL AFTER hash" );
}
return $this->is_success( $created );
}
/**
* Make status column as index.
*
* @return bool
*/
private function make_error_code_column_index() {
$error_code_column_exists = $this->column_exists( 'error_code' );
if ( ! $error_code_column_exists ) {
return $this->is_success( false );
}
if ( $this->index_exists( 'error_code_index' ) ) {
return $this->is_success( true );
}
$index_added = $this->get_db()->query( "ALTER TABLE {$this->table_name} ADD INDEX `error_code_index` (`error_code`) " );
return $this->is_success( $index_added );
}
/**
* Adds the submitted_at column
*
* @return bool
*/
protected function add_submitted_at_column() {
$submitted_at_column_exists = $this->column_exists( 'submitted_at' );
$created = true;
if ( ! $submitted_at_column_exists ) {
$created &= $this->get_db()->query( "ALTER TABLE `{$this->table_name}` ADD COLUMN submitted_at timestamp NULL AFTER last_accessed" );
}
return $this->is_success( $created );
}
}
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Frontend;
use WP_Rocket\Engine\Optimization\RUCSS\AbstractAPIClient;
class APIClient extends AbstractAPIClient {
/**
* SaaS main API path.
*
* @var string
*/
protected $request_path = 'rucss-job';
/**
* Calls Central SaaS API.
*
* @param string $url Page url.
* @param array $options Array with options sent to Saas API.
*
* @return array
*/
public function add_to_queue( string $url, array $options ): array {
$args = [
'body' => [
'url' => add_query_arg(
[
'nowprocket' => 1,
'no_optimize' => 1,
],
$url
),
'config' => $options,
],
'timeout' => 5,
];
$sent = $this->handle_post( $args );
if ( ! $sent ) {
return [
'code' => $this->response_code,
'message' => $this->error_message,
];
}
$default = [
'code' => 400,
'message' => 'No message. Defaulted in add_to_queue',
'contents' => [
'jobId' => '0',
'queueName' => '',
],
];
$result = json_decode( $this->response_body, true );
return wp_parse_args( (array) $result, $default );
}
/**
* Get job status from RUCSS queue.
*
* @param string $job_id Job ID.
* @param string $queue_name Queue Name.
* @param bool $is_home Is home or not.
*
* @return array
*/
public function get_queue_job_status( $job_id, $queue_name, $is_home = false ) {
$args = [
'body' => [
'id' => $job_id,
'force_queue' => $queue_name,
'is_home' => $is_home,
],
'timeout' => 5,
];
if ( ! $this->handle_get( $args ) ) {
return [
'code' => $this->response_code,
'message' => $this->error_message,
];
}
$default = [
'code' => 400,
'status' => 'failed',
'message' => 'No message. Defaulted in get_queue_job_status',
'contents' => [
'success' => false,
'shakedCSS' => '',
],
];
$result = json_decode( $this->response_body, true );
return (array) wp_parse_args( ( $result && $result['returnvalue'] ) ? (array) $result['returnvalue'] : [], $default );
}
}
@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\RUCSS\Frontend;
use WP_Rocket\Engine\Common\Context\ContextInterface;
use WP_Rocket\Engine\Optimization\RUCSS\Context\RUCSSContext;
use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\UsedCSS;
class Subscriber implements Subscriber_Interface {
/**
* UsedCss instance
*
* @var UsedCSS
*/
private $used_css;
/**
* RUCSS context.
*
* @var ContextInterface
*/
protected $context;
/**
* Instantiate the class
*
* @param UsedCSS $used_css UsedCSS instance.
* @param ContextInterface $context RUCSS context.
*/
public function __construct( UsedCSS $used_css, ContextInterface $context ) {
$this->used_css = $used_css;
$this->context = $context;
}
/**
* Return an array of events that this subscriber listens to.
*
* @return array
*/
public static function get_subscribed_events(): array {
return [
'rocket_buffer' => [ 'treeshake', 1000 ],
'rocket_disable_preload_fonts' => 'maybe_disable_preload_fonts',
'rocket_first_install_options' => 'on_install',
'wp_rocket_upgrade' => [ 'on_update', 10, 2 ],
];
}
/**
* Apply TreeShaked CSS to the current HTML page.
*
* @param string $html HTML content.
*
* @return string HTML content.
*/
public function treeshake( string $html ): string {
return $this->used_css->treeshake( $html );
}
/**
* Disables the preload fonts if RUCSS is enabled
*
* @since 3.9
*
* @param bool $value Value for the disable preload fonts filter.
*
* @return bool
*/
public function maybe_disable_preload_fonts( $value ): bool {
if ( $this->context->is_allowed() ) {
return true;
}
return $value;
}
/**
* Add option on update.
*
* @param string $new_version New plugin version.
* @param string $old_version Previous plugin version.
*
* @return void
*/
public function on_update( $new_version, $old_version ) {
if ( version_compare( $old_version, '3.15', '>=' ) ) {
return;
}
$default = 0;
if ( get_transient( 'wp_rocket_no_licence' ) ) {
$default = get_transient( 'wp_rocket_no_licence' );
delete_transient( 'wp_rocket_no_licence' );
}
update_option( 'wp_rocket_no_licence', $default );
}
/**
* Add option on installation.
*
* @param array $options WP Rocket options array.
*
* @return array
*/
public function on_install( $options ) {
update_option( 'wp_rocket_no_licence', 0 );
return $options;
}
}
@@ -0,0 +1,104 @@
<?php
namespace WP_Rocket\Engine\Optimization\RUCSS;
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
use WP_Rocket\Engine\Optimization\RUCSS\Admin\{Database, OptionSubscriber, Settings};
use WP_Rocket\Engine\Optimization\RUCSS\Admin\Subscriber as AdminSubscriber;
use WP_Rocket\Engine\Optimization\RUCSS\Context\RUCSSContext;
use WP_Rocket\Engine\Optimization\RUCSS\Context\RUCSSOptimizeContext;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\Filesystem;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\Queue;
use WP_Rocket\Engine\Optimization\RUCSS\Controller\UsedCSS as UsedCSSController;
use WP_Rocket\Engine\Optimization\RUCSS\Cron\Subscriber as CronSubscriber;
use WP_Rocket\Engine\Optimization\RUCSS\Database\Queries\UsedCSS as UsedCSSQuery;
use WP_Rocket\Engine\Optimization\RUCSS\Database\Tables\UsedCSS as UsedCSSTable;
use WP_Rocket\Engine\Optimization\RUCSS\Frontend\APIClient;
use WP_Rocket\Engine\Optimization\RUCSS\Frontend\Subscriber as FrontendSubscriber;
/**
* Service provider for the WP Rocket RUCSS
*
* @since 3.9
*/
class ServiceProvider extends AbstractServiceProvider {
/**
* The provides array is a way to let the container
* know that a service is provided by this service
* provider. Every service that is registered via
* this service provider must have an alias added
* to this array or it will be ignored.
*
* @var array
*/
protected $provides = [
'rucss_settings',
'rucss_database',
'rucss_option_subscriber',
'rucss_admin_subscriber',
'rucss_frontend_api_client',
'rucss_used_css',
'rucss_used_css_query',
'rucss_frontend_subscriber',
'rucss_queue',
'rucss_filesystem',
'rucss_cron_subscriber',
'rucss_used_css_controller',
];
/**
* Registers the option array in the container
*
* @return void
*/
public function register() {
$this->getContainer()->share( 'rucss_usedcss_table', UsedCSSTable::class );
$this->getContainer()->add( 'rucss_database', Database::class )
->addArgument( $this->getContainer()->get( 'rucss_usedcss_table' ) );
$this->getContainer()->add( 'rucss_settings', Settings::class )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'beacon' ) )
->addArgument( $this->getContainer()->get( 'rucss_usedcss_table' ) );
$this->getContainer()->add( 'rucss_used_css_query', UsedCSSQuery::class );
$this->getContainer()->add( 'rucss_frontend_api_client', APIClient::class )
->addArgument( $this->getContainer()->get( 'options' ) );
$this->getContainer()->add( 'rucss_queue', Queue::class );
$this->getContainer()->add( 'rucss_filesystem', Filesystem::class )
->addArgument( rocket_get_constant( 'WP_ROCKET_USED_CSS_PATH' ) )
->addArgument( rocket_direct_filesystem() );
$this->getContainer()->add( 'rucss_context', RUCSSContext::class )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'rucss_filesystem' ) );
$this->getContainer()->add( 'rucss_optimize_context', RUCSSOptimizeContext::class )
->addArgument( $this->getContainer()->get( 'options' ) );
$this->getContainer()->add( 'rucss_used_css_controller', UsedCSSController::class )
->addArgument( $this->getContainer()->get( 'options' ) )
->addArgument( $this->getContainer()->get( 'rucss_used_css_query' ) )
->addArgument( $this->getContainer()->get( 'rucss_frontend_api_client' ) )
->addArgument( $this->getContainer()->get( 'rucss_queue' ) )
->addArgument( $this->getContainer()->get( 'dynamic_lists_defaultlists_data_manager' ) )
->addArgument( $this->getContainer()->get( 'rucss_filesystem' ) )
->addArgument( $this->getContainer()->get( 'rucss_context' ) )
->addArgument( $this->getContainer()->get( 'rucss_optimize_context' ) );
$this->getContainer()->share( 'rucss_option_subscriber', OptionSubscriber::class )
->addArgument( $this->getContainer()->get( 'rucss_settings' ) );
$this->getContainer()->share( 'rucss_admin_subscriber', AdminSubscriber::class )
->addArgument( $this->getContainer()->get( 'rucss_settings' ) )
->addArgument( $this->getContainer()->get( 'rucss_database' ) )
->addArgument( $this->getContainer()->get( 'rucss_used_css_controller' ) )
->addArgument( $this->getContainer()->get( 'rucss_queue' ) );
$this->getContainer()->share( 'rucss_frontend_subscriber', FrontendSubscriber::class )
->addArgument( $this->getContainer()->get( 'rucss_used_css_controller' ) )
->addArgument( $this->getContainer()->get( 'rucss_context' ) );
$this->getContainer()->share( 'rucss_cron_subscriber', CronSubscriber::class )
->addArgument( $this->getContainer()->get( 'rucss_used_css_controller' ) )
->addArgument( $this->getContainer()->get( 'rucss_database' ) );
}
}