3.15.3
This commit is contained in:
@@ -0,0 +1,226 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare\API;
|
||||
|
||||
use WP_Error;
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\AuthInterface;
|
||||
|
||||
class Client {
|
||||
const CLOUDFLARE_API = 'https://api.cloudflare.com/client/v4/';
|
||||
|
||||
/**
|
||||
* Auth object
|
||||
*
|
||||
* @var AuthInterface
|
||||
*/
|
||||
private $auth;
|
||||
|
||||
/**
|
||||
* An array of arguments for wp_remote_request()
|
||||
*
|
||||
* @var mixed[]
|
||||
*/
|
||||
protected $args = [];
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param AuthInterface $auth Auth implementation.
|
||||
*/
|
||||
public function __construct( AuthInterface $auth ) {
|
||||
$this->auth = $auth;
|
||||
$this->args = [
|
||||
'sslverify' => true,
|
||||
'body' => [],
|
||||
'headers' => [],
|
||||
];
|
||||
}
|
||||
/**
|
||||
* Change client auth.
|
||||
*
|
||||
* @param AuthInterface $auth Client auth.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function set_auth( AuthInterface $auth ) {
|
||||
$this->auth = $auth;
|
||||
}
|
||||
|
||||
/**
|
||||
* API call method for sending requests using GET.
|
||||
*
|
||||
* @param string $path Path of the endpoint.
|
||||
* @param mixed[] $data Data to be sent along with the request.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function get( $path, array $data = [] ) {
|
||||
return $this->request( $path, 'get', $data );
|
||||
}
|
||||
|
||||
/**
|
||||
* API call method for sending requests using POST.
|
||||
*
|
||||
* @param string $path Path of the endpoint.
|
||||
* @param array $data Data to be sent along with the request.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function post( $path, array $data = [] ) {
|
||||
return $this->request( $path, 'post', $data );
|
||||
}
|
||||
|
||||
/**
|
||||
* API call method for sending requests using DELETE.
|
||||
*
|
||||
* @param string $path Path of the endpoint.
|
||||
* @param array $data Data to be sent along with the request.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function delete( $path, array $data = [] ) {
|
||||
return $this->request( $path, 'delete', $data );
|
||||
}
|
||||
|
||||
/**
|
||||
* API call method for sending requests using PATCH.
|
||||
*
|
||||
* @param string $path Path of the endpoint.
|
||||
* @param array $data Data to be sent along with the request.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function patch( $path, array $data = [] ) {
|
||||
return $this->request( $path, 'patch', $data );
|
||||
}
|
||||
|
||||
/**
|
||||
* API call method for sending requests
|
||||
*
|
||||
* @param string $path Path of the endpoint.
|
||||
* @param string $method Type of method that should be used.
|
||||
* @param array $data Data to be sent along with the request.
|
||||
*
|
||||
* @return object|WP_Error
|
||||
*/
|
||||
protected function request( $path, $method = 'get', array $data = [] ) {
|
||||
if ( '/ips' !== $path ) {
|
||||
$valid = $this->auth->is_valid_credentials();
|
||||
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $valid;
|
||||
}
|
||||
|
||||
if ( ! $valid ) {
|
||||
return new WP_Error( 'cloudflare_invalid_credentials', 'Cloudflare credentials are invalid.' );
|
||||
}
|
||||
}
|
||||
|
||||
$response = $this->do_remote_request( $path, $method, $data );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$content = wp_remote_retrieve_body( $response );
|
||||
|
||||
if ( empty( $content ) ) {
|
||||
return new WP_Error( 'cloudflare_no_reply', __( 'Cloudflare did not provide any reply. Please try again later.', 'rocket' ) );
|
||||
}
|
||||
|
||||
$content = json_decode( $content );
|
||||
|
||||
if ( ! is_object( $content ) ) {
|
||||
return new WP_Error( 'cloudflare_content_error', __( 'Cloudflare unexpected response', 'rocket' ) );
|
||||
}
|
||||
|
||||
if ( empty( $content->success ) ) {
|
||||
return $this->set_request_error( $content );
|
||||
}
|
||||
|
||||
if ( ! property_exists( $content, 'result' ) ) {
|
||||
return new WP_Error( 'cloudflare_no_reply', __( 'Missing Cloudflare result.', 'rocket' ) );
|
||||
}
|
||||
|
||||
return $content->result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the request remote request.
|
||||
*
|
||||
* @param string $path Path of the endpoint.
|
||||
* @param string $method Type of method that should be used.
|
||||
* @param array $data Data to be sent along with the request.
|
||||
*
|
||||
* @return array|WP_Error
|
||||
*/
|
||||
private function do_remote_request( string $path, string $method = 'GET', array $data = [] ) {
|
||||
$this->args['method'] = strtoupper( $method );
|
||||
|
||||
$headers = [
|
||||
'User-Agent' => 'wp-rocket/' . rocket_get_constant( 'WP_ROCKET_VERSION' ),
|
||||
'Content-Type' => 'application/json',
|
||||
];
|
||||
|
||||
if ( '/ips' !== $path ) {
|
||||
$this->args['headers'] = array_merge( $headers, $this->auth->get_headers() );
|
||||
}
|
||||
|
||||
$this->args['body'] = [];
|
||||
|
||||
if ( ! empty( $data ) ) {
|
||||
$this->args['body'] = wp_json_encode( $data );
|
||||
}
|
||||
|
||||
$response = wp_remote_request( self::CLOUDFLARE_API . $path, $this->args );
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the WP_Error when request is not successful
|
||||
*
|
||||
* @param object $content Response object.
|
||||
*
|
||||
* @return WP_Error
|
||||
*/
|
||||
private function set_request_error( $content ) {
|
||||
$errors = [];
|
||||
|
||||
foreach ( $content->errors as $error ) {
|
||||
if (
|
||||
6003 === $error->code || 9103 === $error->code ) {
|
||||
$msg = __( 'Incorrect Cloudflare email address or API key.', 'rocket' );
|
||||
|
||||
$msg .= ' ' . sprintf(
|
||||
/* translators: %1$s = opening link; %2$s = closing link */
|
||||
__( 'Read the %1$sdocumentation%2$s for further guidance.', 'rocket' ),
|
||||
// translators: Documentation exists in EN, FR; use localized URL if applicable.
|
||||
'<a href="' . esc_url( __( 'https://docs.wp-rocket.me/article/18-using-wp-rocket-with-cloudflare/?utm_source=wp_plugin&utm_medium=wp_rocket#add-on', 'rocket' ) ) . '" rel="noopener noreferrer" target="_blank">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return new WP_Error( 'cloudflare_incorrect_credentials', $msg );
|
||||
}
|
||||
|
||||
if ( 7003 === $error->code ) {
|
||||
$msg = __( 'Incorrect Cloudflare Zone ID.', 'rocket' );
|
||||
|
||||
$msg .= ' ' . sprintf(
|
||||
/* translators: %1$s = opening link; %2$s = closing link */
|
||||
__( 'Read the %1$sdocumentation%2$s for further guidance.', 'rocket' ),
|
||||
// translators: Documentation exists in EN, FR; use localized URL if applicable.
|
||||
'<a href="' . esc_url( __( 'https://docs.wp-rocket.me/article/18-using-wp-rocket-with-cloudflare/?utm_source=wp_plugin&utm_medium=wp_rocket#add-on', 'rocket' ) ) . '" rel="noopener noreferrer" target="_blank">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return new WP_Error( 'cloudflare_incorrect_zone_id', $msg );
|
||||
}
|
||||
|
||||
$errors[] = $error->message;
|
||||
}
|
||||
|
||||
return new WP_Error( 'cloudflare_request_error', wp_sprintf_l( '%l ', $errors ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare\API;
|
||||
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\AuthInterface;
|
||||
|
||||
class Endpoints {
|
||||
/**
|
||||
* Client instance
|
||||
*
|
||||
* @var Client
|
||||
*/
|
||||
private $client;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param Client $client Client instance.
|
||||
*/
|
||||
public function __construct( Client $client ) {
|
||||
$this->client = $client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get zone data.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function get_zones( string $zone_id ) {
|
||||
return $this->client->get( "zones/{$zone_id}" );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the zone's page rules.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string $status Rule status.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function list_pagerules( string $zone_id, string $status ) {
|
||||
return $this->client->get( "zones/{$zone_id}/pagerules?status={$status}" );
|
||||
}
|
||||
|
||||
/**
|
||||
* Purges the cache.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function purge( string $zone_id ) {
|
||||
return $this->client->post( "zones/{$zone_id}/purge_cache", [ 'purge_everything' => true ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Purges the given URLs.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param array $urls An array of URLs that should be removed from cache.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function purge_files( string $zone_id, array $urls = [] ) {
|
||||
return $this->client->post( "zones/{$zone_id}/purge_cache", [ 'files' => $urls ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the zone's browser cache TTL setting
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string $value Cache TTL value.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function update_browser_cache_ttl( string $zone_id, $value ) {
|
||||
return $this->update_setting( $zone_id, 'browser_cache_ttl', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the zone's rocket loader setting.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string $value Rocket Loader value.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function update_rocket_loader( string $zone_id, $value ) {
|
||||
return $this->update_setting( $zone_id, 'rocket_loader', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the zone's minify setting.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string[] $value Minify value.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function update_minify( string $zone_id, $value ) {
|
||||
return $this->update_setting( $zone_id, 'minify', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the zone's cache level.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string $value Cache level value.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function change_cache_level( string $zone_id, $value ) {
|
||||
return $this->update_setting( $zone_id, 'cache_level', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the zone's development mode.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string $value Development mode value.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function change_development_mode( string $zone_id, $value ) {
|
||||
return $this->update_setting( $zone_id, 'development_mode', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the given setting.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
* @param string $setting Name of the setting to change.
|
||||
* @param mixed $value Setting value.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
protected function update_setting( string $zone_id, $setting, $value ) {
|
||||
return $this->client->patch( "zones/{$zone_id}/settings/{$setting}", [ 'value' => $value ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all of the Cloudflare settings.
|
||||
*
|
||||
* @param string $zone_id Zone ID.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function get_settings( string $zone_id ) {
|
||||
return $this->client->get( "zones/{$zone_id}/settings" );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets Cloudflare's IPs.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function get_ips() {
|
||||
return $this->client->get( '/ips' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Change client auth.
|
||||
*
|
||||
* @param AuthInterface $auth Client auth.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function change_auth( AuthInterface $auth ) {
|
||||
$this->client->set_auth( $auth );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare\Admin;
|
||||
|
||||
use WP_Rocket\Engine\Admin\Settings\Settings;
|
||||
use WP_Rocket\Event_Management\Subscriber_Interface;
|
||||
|
||||
class Subscriber implements Subscriber_Interface {
|
||||
/**
|
||||
* Returns an array of events that this subscriber wants to listen to.
|
||||
*/
|
||||
public static function get_subscribed_events() {
|
||||
return [
|
||||
'admin_notices' => [
|
||||
[ 'maybe_display_purge_notice' ],
|
||||
[ 'maybe_display_update_settings_notice' ],
|
||||
],
|
||||
'rocket_input_sanitize' => [ 'sanitize_options', 20, 2 ],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* This notice is displayed after purging the CloudFlare cache.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function maybe_display_purge_notice() {
|
||||
if ( ! current_user_can( 'rocket_purge_cloudflare_cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$user_id = get_current_user_id();
|
||||
$notice = get_transient( $user_id . '_cloudflare_purge_result' );
|
||||
|
||||
if ( ! $notice ) {
|
||||
return;
|
||||
}
|
||||
|
||||
delete_transient( $user_id . '_cloudflare_purge_result' );
|
||||
|
||||
rocket_notice_html(
|
||||
[
|
||||
'status' => $notice['result'],
|
||||
'message' => $notice['message'],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* This notice is displayed after modifying the CloudFlare settings.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function maybe_display_update_settings_notice() {
|
||||
$screen = get_current_screen();
|
||||
|
||||
if ( ! current_user_can( 'rocket_manage_options' ) || 'settings_page_wprocket' !== $screen->id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$user_id = get_current_user_id();
|
||||
$notices = get_transient( $user_id . '_cloudflare_update_settings' );
|
||||
|
||||
if ( ! $notices ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$errors = '';
|
||||
$success = '';
|
||||
$pre = '';
|
||||
delete_transient( $user_id . '_cloudflare_update_settings' );
|
||||
|
||||
if ( isset( $notices['pre'] ) ) {
|
||||
$pre = $notices['pre'];
|
||||
|
||||
unset( $notices['pre'] );
|
||||
}
|
||||
|
||||
foreach ( $notices as $notice ) {
|
||||
if ( 'error' === $notice['result'] ) {
|
||||
$errors .= $notice['message'] . '<br>';
|
||||
} elseif ( 'success' === $notice['result'] ) {
|
||||
$success .= $notice['message'] . '<br>';
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! empty( $success ) ) {
|
||||
rocket_notice_html(
|
||||
[
|
||||
'message' => $pre . $success,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
if ( ! empty( $errors ) ) {
|
||||
rocket_notice_html(
|
||||
[
|
||||
'status' => 'error',
|
||||
'message' => $errors,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize Cloudflare options
|
||||
*
|
||||
* @param array $input gtArray of sanitized values after being submitted by the form.
|
||||
* @param Settings $settings Settings instance.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function sanitize_options( $input, $settings ) {
|
||||
$input['do_cloudflare'] = $settings->sanitize_checkbox( $input, 'do_cloudflare' );
|
||||
$input['cloudflare_devmode'] = $settings->sanitize_checkbox( $input, 'cloudflare_devmode' );
|
||||
$input['cloudflare_auto_settings'] = $settings->sanitize_checkbox( $input, 'cloudflare_auto_settings' );
|
||||
$input['cloudflare_protocol_rewrite'] = $settings->sanitize_checkbox( $input, 'cloudflare_protocol_rewrite' );
|
||||
|
||||
$input['cloudflare_email'] = isset( $input['cloudflare_email'] ) ? sanitize_email( $input['cloudflare_email'] ) : '';
|
||||
$input['cloudflare_zone_id'] = isset( $input['cloudflare_zone_id'] ) ? sanitize_text_field( $input['cloudflare_zone_id'] ) : '';
|
||||
|
||||
$input['cloudflare_api_key'] = isset( $input['cloudflare_api_key'] ) ? sanitize_text_field( $input['cloudflare_api_key'] ) : '';
|
||||
|
||||
if ( defined( 'WP_ROCKET_CF_API_KEY' ) ) {
|
||||
$input['cloudflare_api_key'] = rocket_get_constant( 'WP_ROCKET_CF_API_KEY', '' );
|
||||
}
|
||||
|
||||
return $input;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare\Auth;
|
||||
|
||||
use WP_Error;
|
||||
|
||||
class APIKey implements AuthInterface {
|
||||
/**
|
||||
* Cloudflare email
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $email = '';
|
||||
|
||||
/**
|
||||
* Cloudflare API Key
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $api_key = '';
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param string $email Cloudflare email.
|
||||
* @param string $api_key Cloudflare API key.
|
||||
*/
|
||||
public function __construct( string $email = '', string $api_key = '' ) {
|
||||
$this->email = $email;
|
||||
$this->api_key = $api_key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets headers for Cloudflare API request
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_headers(): array {
|
||||
return [
|
||||
'X-Auth-Email' => $this->email,
|
||||
'X-Auth-Key' => $this->api_key,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the credentials are set.
|
||||
*
|
||||
* @return bool|WP_Error true if authorized, false if not, WP_Error if either credential is empty.
|
||||
*/
|
||||
public function is_valid_credentials() {
|
||||
if (
|
||||
empty( $this->email )
|
||||
||
|
||||
empty( $this->api_key )
|
||||
) {
|
||||
return new WP_Error(
|
||||
'cloudflare_credentials_empty',
|
||||
sprintf(
|
||||
/* translators: %1$s = opening link; %2$s = closing link */
|
||||
__( 'Cloudflare email and/or API key are not set. Read the %1$sdocumentation%2$s for further guidance.', 'rocket' ),
|
||||
// translators: Documentation exists in EN, FR; use localized URL if applicable.
|
||||
'<a href="' . esc_url( __( 'https://docs.wp-rocket.me/article/18-using-wp-rocket-with-cloudflare/?utm_source=wp_plugin&utm_medium=wp_rocket#add-on', 'rocket' ) ) . '" rel="noopener noreferrer" target="_blank">',
|
||||
'</a>'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return false !== filter_var( $this->email, FILTER_VALIDATE_EMAIL );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace WPMedia\Cloudflare\Auth;
|
||||
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\APIKey;
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\AuthInterface;
|
||||
use WP_Rocket\Admin\Options_Data;
|
||||
|
||||
class APIKeyFactory implements AuthFactoryInterface {
|
||||
|
||||
|
||||
/**
|
||||
* Options Data instance.
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
protected $options;
|
||||
|
||||
/**
|
||||
* Instantiate the class.
|
||||
*
|
||||
* @param Options_Data $options Options Data instance.
|
||||
*/
|
||||
public function __construct( Options_Data $options ) {
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a new authentication instance.
|
||||
*
|
||||
* @param array $data Data to inject into the client.
|
||||
* @return AuthInterface
|
||||
*/
|
||||
public function create( array $data = [] ): AuthInterface {
|
||||
|
||||
$cf_api_key = defined( 'WP_ROCKET_CF_API_KEY' ) ? rocket_get_constant( 'WP_ROCKET_CF_API_KEY', '' ) : $this->options->get( 'cloudflare_api_key', '' );
|
||||
|
||||
$email = key_exists( 'cloudflare_email', $data ) ? $data['cloudflare_email'] : $this->options->get( 'cloudflare_email', '' );
|
||||
$api_key = key_exists( 'cloudflare_api_key', $data ) ? $data['cloudflare_api_key'] : $cf_api_key;
|
||||
|
||||
return new APIKey( $email, $api_key );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace WPMedia\Cloudflare\Auth;
|
||||
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\AuthInterface;
|
||||
|
||||
interface AuthFactoryInterface {
|
||||
|
||||
/**
|
||||
* Create a new authentication instance.
|
||||
*
|
||||
* @param array $data Data to inject into the client.
|
||||
* @return AuthInterface
|
||||
*/
|
||||
public function create( array $data = [] ): AuthInterface;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare\Auth;
|
||||
|
||||
use WP_Error;
|
||||
|
||||
interface AuthInterface {
|
||||
/**
|
||||
* Gets headers for Cloudflare API request
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_headers(): array;
|
||||
|
||||
/**
|
||||
* Checks if the credentials are set.
|
||||
*
|
||||
* @return bool|WP_Error true if authorized, false otherwise, WP_Error if missing credentials.
|
||||
*/
|
||||
public function is_valid_credentials();
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare;
|
||||
|
||||
use CloudFlare\IpRewrite;
|
||||
use DateTimeImmutable;
|
||||
use WP_Error;
|
||||
use WP_Post;
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\AuthInterface;
|
||||
use WP_Rocket\Admin\Options_Data;
|
||||
use WP_Rocket\Addon\Cloudflare\API\Endpoints;
|
||||
|
||||
class Cloudflare {
|
||||
/**
|
||||
* Options Data instance.
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* Endpoints instance.
|
||||
*
|
||||
* @var Endpoints
|
||||
*/
|
||||
private $endpoints;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param Options_Data $options WP Rocket options instance.
|
||||
* @param Endpoints $endpoints Endpoints instance.
|
||||
*/
|
||||
public function __construct( Options_Data $options, Endpoints $endpoints ) {
|
||||
$this->endpoints = $endpoints;
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check valid connection with Cloudflare
|
||||
*
|
||||
* @param string $zone_id Cloudflare zone ID.
|
||||
* @return bool|mixed|WP_Error
|
||||
*/
|
||||
public function check_connection( string $zone_id = '' ) {
|
||||
$is_valid = get_transient( 'rocket_cloudflare_is_api_keys_valid' );
|
||||
if ( false === $is_valid ) {
|
||||
|
||||
if ( '' === $zone_id ) {
|
||||
$zone_id = $this->options->get( 'cloudflare_zone_id', '' );
|
||||
}
|
||||
|
||||
$is_valid = $this->is_auth_valid( $zone_id );
|
||||
|
||||
set_transient( 'rocket_cloudflare_is_api_keys_valid', $is_valid, 2 * WEEK_IN_SECONDS );
|
||||
}
|
||||
|
||||
return $is_valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate Cloudflare input data.
|
||||
*
|
||||
* @param string $zone_id Cloudflare zone ID.
|
||||
*
|
||||
* @return bool|WP_Error true if credentials are ok, WP_Error otherwise.
|
||||
*/
|
||||
public function is_auth_valid( string $zone_id ) {
|
||||
if ( empty( $zone_id ) ) {
|
||||
$msg = __( 'Missing Cloudflare Zone ID.', 'rocket' );
|
||||
|
||||
$msg .= ' ' . sprintf(
|
||||
/* translators: %1$s = opening link; %2$s = closing link */
|
||||
__( 'Read the %1$sdocumentation%2$s for further guidance.', 'rocket' ),
|
||||
// translators: Documentation exists in EN, FR; use localized URL if applicable.
|
||||
'<a href="' . esc_url( __( 'https://docs.wp-rocket.me/article/18-using-wp-rocket-with-cloudflare/?utm_source=wp_plugin&utm_medium=wp_rocket#add-on', 'rocket' ) ) . '" rel="noopener noreferrer" target="_blank">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return new WP_Error( 'cloudflare_no_zone_id', $msg );
|
||||
}
|
||||
|
||||
$result = $this->endpoints->get_zones( $zone_id );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$zone_found = false;
|
||||
$site_url = get_site_url();
|
||||
|
||||
if ( function_exists( 'domain_mapping_siteurl' ) ) {
|
||||
$site_url = domain_mapping_siteurl( $site_url );
|
||||
}
|
||||
|
||||
$parsed_url = wp_parse_url( $site_url );
|
||||
|
||||
if ( property_exists( $result, 'name' ) && false !== strpos( strtolower( $parsed_url['host'] ), $result->name ) ) {
|
||||
$zone_found = true;
|
||||
}
|
||||
|
||||
if ( ! $zone_found ) {
|
||||
$msg = __( 'It looks like your domain is not set up on Cloudflare.', 'rocket' );
|
||||
|
||||
$msg .= ' ' . sprintf(
|
||||
/* translators: %1$s = opening link; %2$s = closing link */
|
||||
__( 'Read the %1$sdocumentation%2$s for further guidance.', 'rocket' ),
|
||||
// translators: Documentation exists in EN, FR; use localized URL if applicable.
|
||||
'<a href="' . esc_url( __( 'https://docs.wp-rocket.me/article/18-using-wp-rocket-with-cloudflare/?utm_source=wp_plugin&utm_medium=wp_rocket#add-on', 'rocket' ) ) . '" rel="noopener noreferrer" target="_blank">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return new WP_Error( 'cloudflare_zone_not_found', $msg );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if CF has the $action_value set as a Page Rule.
|
||||
*
|
||||
* @param string $action_value Action value.
|
||||
*
|
||||
* @return mixed true/false if $action_value was found or not, WP_Error otherwise.
|
||||
*/
|
||||
public function has_page_rule( $action_value ) {
|
||||
$result = $this->endpoints->list_pagerules( $this->options->get( 'cloudflare_zone_id', '' ), 'active' );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$page_rule = wp_json_encode( $result );
|
||||
|
||||
return (bool) preg_match( '/' . $action_value . '/', $page_rule );
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge Cloudflare cache.
|
||||
*
|
||||
* @return mixed true if the purge is successful, WP_Error otherwise.
|
||||
*/
|
||||
public function purge_cloudflare() {
|
||||
$result = $this->endpoints->purge( $this->options->get( 'cloudflare_zone_id', '' ) );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge Cloudflare Cache by URL
|
||||
*
|
||||
* @param WP_Post $post The post object.
|
||||
* @param array $purge_urls URLs cache files to remove.
|
||||
* @param string $lang The post language.
|
||||
*
|
||||
* @return mixed true if the purge is successful, WP_Error otherwise
|
||||
*/
|
||||
public function purge_by_url( $post, $purge_urls, $lang ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
|
||||
$result = $this->endpoints->purge_files( $this->options->get( 'cloudflare_zone_id', '' ), $purge_urls );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Browser Cache TTL in Cloudflare.
|
||||
*
|
||||
* @param string $value Value for Cloudflare browser cache TTL.
|
||||
*
|
||||
* @return mixed Value if the update is successful, WP_Error otherwise.
|
||||
*/
|
||||
public function set_browser_cache_ttl( $value ) {
|
||||
$result = $this->endpoints->update_browser_cache_ttl( $this->options->get( 'cloudflare_zone_id', '' ), (int) $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $this->convert_time( (int) $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert value in seconds to seconds/minutes/hours/days
|
||||
*
|
||||
* @param int $value Value in seconds.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function convert_time( int $value ): string {
|
||||
$base = new DateTimeImmutable( '@0' );
|
||||
$time = new DateTimeImmutable( "@$value" );
|
||||
$format = '%a ' . __( 'days', 'rocket' );
|
||||
|
||||
if ( 60 > $value ) {
|
||||
$format = '%s ' . __( 'seconds', 'rocket' );
|
||||
} elseif ( 3600 > $value ) {
|
||||
$format = '%i ' . __( 'minutes', 'rocket' );
|
||||
} elseif ( 86400 > $value ) {
|
||||
$format = '%h ' . __( 'hours', 'rocket' );
|
||||
}
|
||||
|
||||
return $base->diff( $time )->format( $format );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Cloudflare Rocket Loader.
|
||||
*
|
||||
* @param string $value Value for Cloudflare Rocket Loader.
|
||||
*
|
||||
* @return mixed Value if the update is successful, WP_Error otherwise.
|
||||
*/
|
||||
public function set_rocket_loader( $value ) {
|
||||
$result = $this->endpoints->update_rocket_loader( $this->options->get( 'cloudflare_zone_id', '' ), $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Cloudflare Minification.
|
||||
*
|
||||
* @param string $value Value for Cloudflare minification.
|
||||
*
|
||||
* @return mixed Value if the update is successful, WP_Error otherwise.
|
||||
*/
|
||||
public function set_minify( $value ) {
|
||||
$cf_minify_settings = [
|
||||
'css' => $value,
|
||||
'html' => $value,
|
||||
'js' => $value,
|
||||
];
|
||||
|
||||
$result = $this->endpoints->update_minify( $this->options->get( 'cloudflare_zone_id', '' ), $cf_minify_settings );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Cloudflare Caching level.
|
||||
*
|
||||
* @param string $value Value for Cloudflare caching level.
|
||||
*
|
||||
* @return mixed Value if the update is successful, WP_Error otherwise.
|
||||
*/
|
||||
public function set_cache_level( $value ) {
|
||||
$result = $this->endpoints->change_cache_level( $this->options->get( 'cloudflare_zone_id', '' ), $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Cloudflare Development mode.
|
||||
*
|
||||
* @param string $value Value for Cloudflare development mode.
|
||||
*
|
||||
* @return mixed Value if the update is successful, WP_Error otherwise.
|
||||
*/
|
||||
public function set_devmode( $value ) {
|
||||
if ( 0 === (int) $value ) {
|
||||
$value = 'off';
|
||||
} else {
|
||||
$value = 'on';
|
||||
}
|
||||
|
||||
$result = $this->endpoints->change_development_mode( $this->options->get( 'cloudflare_zone_id', '' ), $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
switch ( $value ) {
|
||||
case 'on':
|
||||
wp_schedule_single_event( time() + 3 * HOUR_IN_SECONDS, 'rocket_cron_deactivate_cloudflare_devmode' );
|
||||
break;
|
||||
case 'off':
|
||||
$next_event = wp_next_scheduled( 'rocket_cron_deactivate_cloudflare_devmode' );
|
||||
|
||||
if ( false !== $next_event ) {
|
||||
wp_unschedule_event( $next_event, 'rocket_cron_deactivate_cloudflare_devmode' );
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the current Cloudflare settings for a given domain.
|
||||
*
|
||||
* @return array|WP_Error Array of Cloudflare settings, WP_Error if any error connection to Cloudflare.
|
||||
*/
|
||||
public function get_settings() {
|
||||
$cf_settings = $this->endpoints->get_settings( $this->options->get( 'cloudflare_zone_id', '' ) );
|
||||
|
||||
if ( is_wp_error( $cf_settings ) ) {
|
||||
return $cf_settings;
|
||||
}
|
||||
|
||||
$browser_cache_ttl = 0;
|
||||
$cache_level = '';
|
||||
$rocket_loader = '';
|
||||
$cf_minify = '';
|
||||
|
||||
foreach ( $cf_settings as $cloudflare_option ) {
|
||||
switch ( $cloudflare_option->id ) {
|
||||
case 'browser_cache_ttl':
|
||||
$browser_cache_ttl = $cloudflare_option->value;
|
||||
break;
|
||||
case 'cache_level':
|
||||
$cache_level = $cloudflare_option->value;
|
||||
break;
|
||||
case 'rocket_loader':
|
||||
$rocket_loader = $cloudflare_option->value;
|
||||
break;
|
||||
case 'minify':
|
||||
$cf_minify = $cloudflare_option->value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
$cf_minify_value = 'on';
|
||||
|
||||
if (
|
||||
'off' === $cf_minify->js
|
||||
||
|
||||
'off' === $cf_minify->css
|
||||
||
|
||||
'off' === $cf_minify->html
|
||||
) {
|
||||
$cf_minify_value = 'off';
|
||||
}
|
||||
|
||||
$cf_settings_array = [
|
||||
'cache_level' => $cache_level,
|
||||
'minify' => $cf_minify_value,
|
||||
'rocket_loader' => $rocket_loader,
|
||||
'browser_cache_ttl' => $browser_cache_ttl,
|
||||
];
|
||||
|
||||
return $cf_settings_array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Cloudflare IPs. No API validation needed, all exceptions returns the default CF IPs array.
|
||||
*
|
||||
* @return object Result of API request if successful, default CF IPs otherwise.
|
||||
*/
|
||||
public function get_cloudflare_ips() {
|
||||
$cf_ips = get_transient( 'rocket_cloudflare_ips' );
|
||||
|
||||
if ( false !== $cf_ips ) {
|
||||
return $cf_ips;
|
||||
}
|
||||
|
||||
$cf_ips = $this->endpoints->get_ips();
|
||||
|
||||
if ( is_wp_error( $cf_ips ) ) {
|
||||
// Set default IPs from Cloudflare if call to Cloudflare /ips API does not contain a success.
|
||||
// Prevents from making API calls on each page load.
|
||||
$cf_ips = $this->get_default_ips();
|
||||
}
|
||||
|
||||
set_transient( 'rocket_cloudflare_ips', $cf_ips, 2 * WEEK_IN_SECONDS );
|
||||
|
||||
return $cf_ips;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default Cloudflare IPs.
|
||||
*
|
||||
* @return object Default Cloudflare connecting IPs.
|
||||
*/
|
||||
private function get_default_ips() {
|
||||
$cf_ips = (object) [
|
||||
'ipv4_cidrs' => [],
|
||||
'ipv6_cidrs' => [],
|
||||
];
|
||||
|
||||
$cf_ips->ipv4_cidrs = [
|
||||
'173.245.48.0/20',
|
||||
'103.21.244.0/22',
|
||||
'103.22.200.0/22',
|
||||
'103.31.4.0/22',
|
||||
'141.101.64.0/18',
|
||||
'108.162.192.0/18',
|
||||
'190.93.240.0/20',
|
||||
'188.114.96.0/20',
|
||||
'197.234.240.0/22',
|
||||
'198.41.128.0/17',
|
||||
'162.158.0.0/15',
|
||||
'104.16.0.0/12',
|
||||
'104.24.0.0/14',
|
||||
'172.64.0.0/13',
|
||||
'131.0.72.0/22',
|
||||
];
|
||||
|
||||
$cf_ips->ipv6_cidrs = [
|
||||
'2400:cb00::/32',
|
||||
'2606:4700::/32',
|
||||
'2803:f800::/32',
|
||||
'2405:b500::/32',
|
||||
'2405:8100::/32',
|
||||
'2a06:98c0::/29',
|
||||
'2c0f:f248::/32',
|
||||
];
|
||||
|
||||
return $cf_ips;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Cloudflare IP Rewrite
|
||||
*
|
||||
* @return IpRewrite
|
||||
*/
|
||||
public static function set_ip_rewrite() {
|
||||
static $instance = null;
|
||||
|
||||
if ( is_null( $instance ) ) {
|
||||
$instance = new IpRewrite();
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixes Cloudflare Flexible SSL redirect loop
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function fix_cf_flexible_ssl() {
|
||||
$ip_rewrite = self::set_ip_rewrite();
|
||||
|
||||
if ( $ip_rewrite->isCloudFlare() ) {
|
||||
// Fixes Flexible SSL.
|
||||
if ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && 'https' === $_SERVER['HTTP_X_FORWARDED_PROTO'] ) {
|
||||
$_SERVER['HTTPS'] = 'on';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Change client auth.
|
||||
*
|
||||
* @param AuthInterface $auth Client auth.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function change_auth( AuthInterface $auth ) {
|
||||
$this->endpoints->change_auth( $auth );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare;
|
||||
|
||||
use WP_Rocket\Addon\Cloudflare\Admin\Subscriber as CloudflareAdminSubscriber;
|
||||
use WP_Rocket\Addon\Cloudflare\API\{Client, Endpoints};
|
||||
use WP_Rocket\Addon\Cloudflare\Auth\APIKey;
|
||||
use WP_Rocket\Addon\Cloudflare\Cloudflare;
|
||||
use WP_Rocket\Addon\Cloudflare\Subscriber as CloudflareSubscriber;
|
||||
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
|
||||
use WPMedia\Cloudflare\Auth\APIKeyFactory;
|
||||
|
||||
/**
|
||||
* Service provider for Cloudflare Addon.
|
||||
*/
|
||||
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 = [
|
||||
'cloudflare_client',
|
||||
'cloudflare_endpoints',
|
||||
'cloudflare',
|
||||
'cloudflare_subscriber',
|
||||
'cloudflare_admin_subscriber',
|
||||
];
|
||||
|
||||
/**
|
||||
* Registers items with the container
|
||||
*/
|
||||
public function register() {
|
||||
$options = $this->getContainer()->get( 'options' );
|
||||
|
||||
$this->getLeagueContainer()->add( 'cloudflare_auth_factory', APIKeyFactory::class )->addArgument( $options );
|
||||
|
||||
$this->getLeagueContainer()->add( 'cloudflare_client', Client::class )
|
||||
->addArgument( $this->getContainer()->get( 'cloudflare_auth_factory' )->create() );
|
||||
$this->getLeagueContainer()->add( 'cloudflare_endpoints', Endpoints::class )
|
||||
->addArgument( $this->getContainer()->get( 'cloudflare_client' ) );
|
||||
|
||||
$this->getLeagueContainer()->add( 'cloudflare', Cloudflare::class )
|
||||
->addArgument( $options )
|
||||
->addArgument( $this->getContainer()->get( 'cloudflare_endpoints' ) );
|
||||
$this->getLeagueContainer()->share( 'cloudflare_subscriber', CloudflareSubscriber::class )
|
||||
->addArgument( $this->getContainer()->get( 'cloudflare' ) )
|
||||
->addArgument( $options )
|
||||
->addArgument( $this->getContainer()->get( 'options_api' ) )
|
||||
->addArgument( $this->getContainer()->get( 'cloudflare_auth_factory' ) )
|
||||
->addTag( 'cloudflare_subscriber' );
|
||||
$this->getLeagueContainer()->share(
|
||||
'cloudflare_admin_subscriber',
|
||||
CloudflareAdminSubscriber::class
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,736 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Cloudflare;
|
||||
|
||||
use WP_Post;
|
||||
use WP_Rocket\Event_Management\Subscriber_Interface;
|
||||
use WP_Rocket\Admin\{Options, Options_Data};
|
||||
use WPMedia\Cloudflare\Auth\AuthFactoryInterface;
|
||||
|
||||
class Subscriber implements Subscriber_Interface {
|
||||
/**
|
||||
* Cloudflare instance.
|
||||
*
|
||||
* @var Cloudflare
|
||||
*/
|
||||
private $cloudflare;
|
||||
|
||||
/**
|
||||
* Options Data instance.
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* Options instance.
|
||||
*
|
||||
* @var Options
|
||||
*/
|
||||
private $options_api;
|
||||
|
||||
/**
|
||||
* Authentication factory.
|
||||
*
|
||||
* @var AuthFactoryInterface
|
||||
*/
|
||||
protected $auth_factory;
|
||||
|
||||
/**
|
||||
* Creates an instance of the Cloudflare Subscriber.
|
||||
*
|
||||
* @param Cloudflare $cloudflare Cloudflare instance.
|
||||
* @param Options_Data $options WP Rocket options instance.
|
||||
* @param Options $options_api Options instance.
|
||||
* @param AuthFactoryInterface $auth_factory Authentication factory.
|
||||
*/
|
||||
public function __construct( Cloudflare $cloudflare, Options_Data $options, Options $options_api, AuthFactoryInterface $auth_factory ) {
|
||||
$this->options = $options;
|
||||
$this->options_api = $options_api;
|
||||
$this->cloudflare = $cloudflare;
|
||||
$this->auth_factory = $auth_factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of events that this subscriber wants to listen to.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_subscribed_events() {
|
||||
$slug = rocket_get_constant( 'WP_ROCKET_SLUG', 'wp_rocket_settings' );
|
||||
|
||||
return [
|
||||
'rocket_varnish_ip' => 'set_varnish_localhost',
|
||||
'rocket_varnish_purge_request_host' => 'set_varnish_purge_request_host',
|
||||
'rocket_cron_deactivate_cloudflare_devmode' => 'deactivate_devmode',
|
||||
'after_rocket_clean_domain' => 'auto_purge',
|
||||
'after_rocket_clean_post' => [ 'auto_purge_by_url', 10, 3 ],
|
||||
'admin_post_rocket_purge_cloudflare' => 'purge_cache',
|
||||
'init' => [ 'set_real_ip', 1 ],
|
||||
'update_option_' . $slug => [
|
||||
[ 'save_cloudflare_options', 10, 2 ],
|
||||
[ 'update_dev_mode', 11, 2 ],
|
||||
],
|
||||
'pre_update_option_' . $slug => [
|
||||
[ 'change_auth', 8, 2 ],
|
||||
[ 'delete_connection_transient', 10, 2 ],
|
||||
[ 'save_cloudflare_old_settings', 10, 2 ],
|
||||
[ 'display_settings_notice', 11, 2 ],
|
||||
],
|
||||
'rocket_buffer' => [ 'protocol_rewrite', PHP_INT_MAX ],
|
||||
'wp_calculate_image_srcset' => [ 'protocol_rewrite_srcset', PHP_INT_MAX ],
|
||||
'rocket_cdn_helper_addons' => 'add_cdn_helper_message',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Varnish IP to localhost if Cloudflare is active.
|
||||
*
|
||||
* @param string|array $varnish_ip Varnish IP.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function set_varnish_localhost( $varnish_ip ) {
|
||||
if ( ! $this->should_filter_varnish() ) {
|
||||
return $varnish_ip;
|
||||
}
|
||||
|
||||
if ( is_string( $varnish_ip ) ) {
|
||||
$varnish_ip = (array) $varnish_ip;
|
||||
}
|
||||
|
||||
$varnish_ip[] = 'localhost';
|
||||
|
||||
return $varnish_ip;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Host header to the website domain if Cloudflare is active.
|
||||
*
|
||||
* @param string $host the host header value.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function set_varnish_purge_request_host( $host ) {
|
||||
if ( ! $this->should_filter_varnish() ) {
|
||||
return $host;
|
||||
}
|
||||
|
||||
return wp_parse_url( home_url(), PHP_URL_HOST );
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if we should filter the value for the Varnish purge.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function should_filter_varnish(): bool {
|
||||
// This filter is documented in inc/Addon/Varnish.php.
|
||||
return apply_filters( 'do_rocket_varnish_http_purge', false ) // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
|
||||
||
|
||||
$this->options->get( 'varnish_auto_purge', 0 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically set Cloudflare development mode value to off after 3 hours to reflect Cloudflare behaviour.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function deactivate_devmode() {
|
||||
$this->options->set( 'cloudflare_devmode', 0 );
|
||||
$this->options_api->set( 'settings', $this->options->get_options() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge Cloudflare cache automatically if Cache Everything is set as a Page Rule.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function auto_purge() {
|
||||
if ( ! current_user_can( 'rocket_purge_cloudflare_cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$settings = $this->options_api->get( 'settings', [] );
|
||||
|
||||
$this->options->set_values( $settings );
|
||||
|
||||
$auth = $this->auth_factory->create( $settings );
|
||||
|
||||
$this->cloudflare->change_auth( $auth );
|
||||
|
||||
if ( is_wp_error( $this->cloudflare->check_connection( $this->options->get( 'cloudflare_zone_id', '' ) ) ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cf_cache_everything = $this->cloudflare->has_page_rule( 'cache_everything' );
|
||||
|
||||
if ( is_wp_error( $cf_cache_everything ) || ! $cf_cache_everything ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Purge CloudFlare.
|
||||
$this->cloudflare->purge_cloudflare();
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge Cloudflare cache URLs automatically if Cache Everything is set as a Page Rule.
|
||||
*
|
||||
* @param WP_Post $post The post object.
|
||||
* @param array $purge_urls URLs cache files to remove.
|
||||
* @param string $lang The post language.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function auto_purge_by_url( $post, $purge_urls, $lang ) {
|
||||
if ( ! current_user_can( 'rocket_purge_cloudflare_cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( is_wp_error( $this->cloudflare->check_connection() ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cf_cache_everything = $this->cloudflare->has_page_rule( 'cache_everything' );
|
||||
|
||||
if ( is_wp_error( $cf_cache_everything ) || ! $cf_cache_everything ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Add home URL and feeds URLs to Cloudflare clean cache URLs list.
|
||||
$purge_urls[] = get_rocket_i18n_home_url( $lang );
|
||||
$feed_urls = [];
|
||||
$feed_urls[] = get_feed_link();
|
||||
$feed_urls[] = get_feed_link( 'comments_' );
|
||||
|
||||
// this filter is documented in inc/functions/files.php.
|
||||
$feed_urls = apply_filters( 'rocket_clean_home_feeds', $feed_urls );
|
||||
$purge_urls = array_unique( array_merge( $purge_urls, $feed_urls ) );
|
||||
|
||||
// Purge CloudFlare.
|
||||
$this->cloudflare->purge_by_url( $post, $purge_urls, $lang );
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge CloudFlare cache.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function purge_cache_no_die() {
|
||||
if ( ! current_user_can( 'rocket_purge_cloudflare_cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$connection = $this->cloudflare->check_connection();
|
||||
|
||||
if ( is_wp_error( $connection ) ) {
|
||||
$cf_purge_result = [
|
||||
'result' => 'error',
|
||||
'message' => sprintf(
|
||||
// translators: %1$s = <strong>, %2$s = </strong>, %3$s = CloudFare API return message.
|
||||
__( '%1$sWP Rocket:%2$s %3$s', 'rocket' ),
|
||||
'<strong>',
|
||||
'</strong>',
|
||||
$connection->get_error_message()
|
||||
),
|
||||
];
|
||||
|
||||
set_transient( get_current_user_id() . '_cloudflare_purge_result', $cf_purge_result );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Purge CloudFlare.
|
||||
$cf_purge = $this->cloudflare->purge_cloudflare();
|
||||
$cf_purge_result = [
|
||||
'result' => 'success',
|
||||
'message' => sprintf(
|
||||
// translators: %1$s = <strong>, %2$s = </strong>.
|
||||
__( '%1$sWP Rocket:%2$s Cloudflare cache successfully purged.', 'rocket' ),
|
||||
'<strong>',
|
||||
'</strong>'
|
||||
),
|
||||
];
|
||||
|
||||
if ( is_wp_error( $cf_purge ) ) {
|
||||
$cf_purge_result = [
|
||||
'result' => 'error',
|
||||
'message' => sprintf(
|
||||
// translators: %1$s = <strong>, %2$s = </strong>, %3$s = CloudFare API return message.
|
||||
__( '%1$sWP Rocket:%2$s %3$s', 'rocket' ),
|
||||
'<strong>',
|
||||
'</strong>',
|
||||
$cf_purge->get_error_message()
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
set_transient( get_current_user_id() . '_cloudflare_purge_result', $cf_purge_result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge CloudFlare cache.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function purge_cache() {
|
||||
if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'rocket_purge_cloudflare' ) ) {
|
||||
wp_nonce_ays( '' );
|
||||
}
|
||||
|
||||
$this->purge_cache_no_die();
|
||||
|
||||
wp_safe_redirect( esc_url_raw( wp_get_referer() ) );
|
||||
defined( 'WPMEDIA_IS_TESTING' ) ? wp_die() : exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Real IP from CloudFlare.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function set_real_ip() {
|
||||
Cloudflare::set_ip_rewrite();
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare dev mode admin option.
|
||||
*
|
||||
* @param string $value New value for Cloudflare dev mode.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function save_cloudflare_devmode( $value ) {
|
||||
$result = $this->cloudflare->set_devmode( $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return [
|
||||
'result' => 'error',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare development mode error: %s', 'rocket' ), $result->get_error_message() ),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'result' => 'success',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare development mode %s', 'rocket' ), $result ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare cache_level admin option.
|
||||
*
|
||||
* @param string $value New value for Cloudflare cache_level.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function save_cache_level( $value ) {
|
||||
// Set Cache Level to Aggressive.
|
||||
$result = $this->cloudflare->set_cache_level( $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return [
|
||||
'result' => 'error',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare cache level error: %s', 'rocket' ), $result->get_error_message() ),
|
||||
];
|
||||
}
|
||||
|
||||
$level = $value;
|
||||
|
||||
if ( 'aggressive' === $result ) {
|
||||
$level = _x( 'standard', 'Cloudflare caching level', 'rocket' );
|
||||
}
|
||||
|
||||
return [
|
||||
'result' => 'success',
|
||||
// translators: %s is the caching level returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare cache level set to %s', 'rocket' ), $level ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare minify admin option.
|
||||
*
|
||||
* @param string $value New value for Cloudflare minify.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function save_minify( $value ) {
|
||||
$result = $this->cloudflare->set_minify( $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return [
|
||||
'result' => 'error',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare minification error: %s', 'rocket' ), $result->get_error_message() ),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'result' => 'success',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare minification %s', 'rocket' ), $result ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare rocket loader admin option.
|
||||
*
|
||||
* @param string $value New value for Cloudflare rocket loader.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function save_rocket_loader( $value ) {
|
||||
$result = $this->cloudflare->set_rocket_loader( $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return [
|
||||
'result' => 'error',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare rocket loader error: %s', 'rocket' ), $result->get_error_message() ),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'result' => 'success',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare rocket loader %s', 'rocket' ), $result ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare browser cache ttl admin option.
|
||||
*
|
||||
* @param int $value New value for Cloudflare browser cache ttl.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function save_browser_cache_ttl( $value ) {
|
||||
$result = $this->cloudflare->set_browser_cache_ttl( $value );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return [
|
||||
'result' => 'error',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare browser cache error: %s', 'rocket' ), $result->get_error_message() ),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'result' => 'success',
|
||||
// translators: %s is the message returned by the CloudFlare API.
|
||||
'message' => sprintf( __( 'Cloudflare browser cache set to %s', 'rocket' ), $result ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare auto settings admin option.
|
||||
*
|
||||
* @param int $auto_settings New value for Cloudflare auto_settings.
|
||||
* @param string $old_settings Cloudflare cloudflare_old_settings.
|
||||
*
|
||||
* @return array<int, array<string>>
|
||||
*/
|
||||
private function save_cloudflare_auto_settings( $auto_settings, $old_settings ) {
|
||||
$cf_old_settings = explode( ',', $old_settings );
|
||||
|
||||
$result = [];
|
||||
|
||||
// Set Cache Level to Aggressive.
|
||||
$cf_cache_level = isset( $cf_old_settings[0] ) && 0 === $auto_settings ? $cf_old_settings[0] : 'aggressive';
|
||||
$result[] = $this->save_cache_level( $cf_cache_level );
|
||||
|
||||
// Active Minification for HTML, CSS & JS.
|
||||
$cf_minify = isset( $cf_old_settings[1] ) && 0 === $auto_settings ? $cf_old_settings[1] : 'on';
|
||||
$result[] = $this->save_minify( $cf_minify );
|
||||
|
||||
// Deactivate Rocket Loader to prevent conflicts.
|
||||
$cf_rocket_loader = isset( $cf_old_settings[2] ) && 0 === $auto_settings ? $cf_old_settings[2] : 'off';
|
||||
$result[] = $this->save_rocket_loader( $cf_rocket_loader );
|
||||
|
||||
// Set Browser cache to 1 year.
|
||||
$cf_browser_cache_ttl = isset( $cf_old_settings[3] ) && 0 === $auto_settings ? $cf_old_settings[3] : 31536000;
|
||||
$result[] = $this->save_browser_cache_ttl( $cf_browser_cache_ttl );
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the development mode value on Cloudflare
|
||||
*
|
||||
* @param array $old_value An array of previous values for the settings.
|
||||
* @param array $value An array of submitted values for the settings.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function update_dev_mode( $old_value, $value ) {
|
||||
if ( ! current_user_can( 'rocket_manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! isset( $old_value['cloudflare_devmode'], $value['cloudflare_devmode'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( (int) $old_value['cloudflare_devmode'] === (int) $value['cloudflare_devmode'] ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$connection = $this->cloudflare->check_connection( $value['cloudflare_zone_id'] );
|
||||
|
||||
if ( is_wp_error( $connection ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$result = [
|
||||
'pre' => sprintf(
|
||||
'%1$sWP Rocket:%2$s',
|
||||
'<strong>',
|
||||
'</strong> '
|
||||
),
|
||||
];
|
||||
$update = get_transient( get_current_user_id() . '_cloudflare_update_settings' );
|
||||
|
||||
if ( false !== $update ) {
|
||||
$result = $update;
|
||||
}
|
||||
|
||||
$result[] = $this->save_cloudflare_devmode( $value['cloudflare_devmode'] );
|
||||
|
||||
set_transient( get_current_user_id() . '_cloudflare_update_settings', $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare admin options.
|
||||
*
|
||||
* @param array $old_value An array of previous values for the settings.
|
||||
* @param array $value An array of submitted values for the settings.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function save_cloudflare_options( $old_value, $value ) {
|
||||
if ( ! current_user_can( 'rocket_manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! isset( $old_value['cloudflare_auto_settings'], $value['cloudflare_auto_settings'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( (int) $old_value['cloudflare_auto_settings'] === (int) $value['cloudflare_auto_settings'] ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$connection = $this->cloudflare->check_connection( $value['cloudflare_zone_id'] );
|
||||
|
||||
if ( is_wp_error( $connection ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$result = [
|
||||
'pre' => sprintf(
|
||||
// translators: %1$s = strong opening tag, %2$s = strong closing tag.
|
||||
__( '%1$sWP Rocket:%2$s Optimal settings activated for Cloudflare:', 'rocket' ),
|
||||
'<strong>',
|
||||
'</strong>'
|
||||
) . '<br>',
|
||||
];
|
||||
|
||||
if ( 0 === (int) $value['cloudflare_auto_settings'] ) {
|
||||
$result['pre'] = sprintf(
|
||||
// translators: %1$s = strong opening tag, %2$s = strong closing tag.
|
||||
__( '%1$sWP Rocket:%2$s Optimal settings deactivated for Cloudflare, reverted to previous settings:', 'rocket' ),
|
||||
'<strong>',
|
||||
'</strong>'
|
||||
) . '<br>';
|
||||
}
|
||||
|
||||
$result = array_merge( $result, $this->save_cloudflare_auto_settings( $value['cloudflare_auto_settings'], $value['cloudflare_old_settings'] ) );
|
||||
|
||||
set_transient( get_current_user_id() . '_cloudflare_update_settings', $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Save Cloudflare old settings when the auto settings option is enabled.
|
||||
*
|
||||
* @param array $value An array of previous values for the settings.
|
||||
* @param array $old_value An array of submitted values for the settings.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function save_cloudflare_old_settings( $value, $old_value ) {
|
||||
if ( ! current_user_can( 'rocket_manage_options' ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ( ! isset( $value['cloudflare_auto_settings'], $old_value ['cloudflare_auto_settings'] ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ( $value['cloudflare_auto_settings'] === $old_value ['cloudflare_auto_settings'] ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ( 0 === (int) $value['cloudflare_auto_settings'] ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$cloudflare_zone_id = key_exists( 'cloudflare_zone_id', $value ) ? $value['cloudflare_zone_id'] : '';
|
||||
|
||||
if ( is_wp_error( $this->cloudflare->check_connection( $cloudflare_zone_id ) ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$cf_settings = $this->cloudflare->get_settings();
|
||||
$value['cloudflare_old_settings'] = ! is_wp_error( $cf_settings )
|
||||
? implode( ',', array_filter( $cf_settings ) )
|
||||
: '';
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the authentification.
|
||||
*
|
||||
* @param array $value An array of previous values for the settings.
|
||||
* @param array $old_value An array of submitted values for the settings.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function change_auth( $value, $old_value ) {
|
||||
$auth = $this->auth_factory->create( $value );
|
||||
$this->cloudflare->change_auth( $auth );
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the transient CF connection status when API Key, Email or Zone ID is changed
|
||||
*
|
||||
* @param array $value An array of previous values for the settings.
|
||||
* @param array $old_value An array of submitted values for the settings.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function delete_connection_transient( $value, $old_value ) {
|
||||
|
||||
$fields = [
|
||||
'cloudflare_api_key',
|
||||
'cloudflare_email',
|
||||
'cloudflare_zone_id',
|
||||
'cloudflare_devmode',
|
||||
'cloudflare_auto_settings',
|
||||
'cloudflare_protocol_rewrite',
|
||||
];
|
||||
|
||||
$change = false;
|
||||
|
||||
foreach ( $fields as $field ) {
|
||||
$change |= ! isset( $old_value[ $field ], $value[ $field ] ) || $old_value[ $field ] !== $value[ $field ];
|
||||
}
|
||||
|
||||
if ( ! $change ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
delete_transient( get_current_user_id() . '_cloudflare_update_settings' );
|
||||
delete_transient( 'rocket_cloudflare_is_api_keys_valid' );
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the error notice.
|
||||
*
|
||||
* @param array $value An array of previous values for the settings.
|
||||
* @param array $old_value An array of submitted values for the settings.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function display_settings_notice( $value, $old_value ) {
|
||||
|
||||
if ( ! key_exists( 'cloudflare_zone_id', $value ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$connection = $this->cloudflare->check_connection( $value['cloudflare_zone_id'] );
|
||||
|
||||
if ( is_wp_error( $connection ) ) {
|
||||
add_settings_error( 'general', 'cloudflare_api_key_invalid', __( 'WP Rocket: ', 'rocket' ) . '</strong>' . $connection->get_error_message() . '<strong>', 'error' );
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove HTTP protocol on script, link, img and form tags.
|
||||
*
|
||||
* @param string $buffer HTML content.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function protocol_rewrite( $buffer ) {
|
||||
if ( ! $this->can_protocol_rewrite() ) {
|
||||
return $buffer;
|
||||
}
|
||||
|
||||
$return = preg_replace( "/(<(script|link|img|form)(?!.*?[\"']\bcanonical\b[\"'])([^>]*)(href|src|action)=[\"'])https?:\\/\\//i", '$1//', $buffer );
|
||||
|
||||
if ( $return ) {
|
||||
$buffer = $return;
|
||||
}
|
||||
|
||||
return $buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove HTTP protocol on srcset attribute generated by WordPress
|
||||
*
|
||||
* @param array $sources an Array of images sources for srcset.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function protocol_rewrite_srcset( $sources ) {
|
||||
if ( ! $this->can_protocol_rewrite() ) {
|
||||
return $sources;
|
||||
}
|
||||
|
||||
if ( empty( $sources ) ) {
|
||||
return $sources;
|
||||
}
|
||||
|
||||
foreach ( $sources as $i => $source ) {
|
||||
$sources[ $i ]['url'] = str_replace( [ 'http:', 'https:' ], '', $source['url'] );
|
||||
}
|
||||
|
||||
return $sources;
|
||||
}
|
||||
|
||||
/**
|
||||
* Can rewrite protocol
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function can_protocol_rewrite(): bool {
|
||||
return $this->options->get( 'do_cloudflare', 0 )
|
||||
&&
|
||||
(
|
||||
$this->options->get( 'cloudflare_protocol_rewrite', 0 )
|
||||
||
|
||||
apply_filters( 'do_rocket_protocol_rewrite', false ) // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the helper message on the CDN settings.
|
||||
*
|
||||
* @param string[] $addons Name from the addon that requires the helper message.
|
||||
* @return string[]
|
||||
*/
|
||||
public function add_cdn_helper_message( array $addons ): array {
|
||||
$addons[] = 'Cloudflare';
|
||||
return $addons;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
namespace WP_Rocket\Addon;
|
||||
|
||||
use WP_Rocket\Addon\Sucuri\Subscriber as SucuriSubscriber;
|
||||
use WP_Rocket\Addon\WebP\AdminSubscriber as WebPAdminSubscriber;
|
||||
use WP_Rocket\Addon\WebP\Subscriber as WebPSubscriber;
|
||||
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
|
||||
|
||||
/**
|
||||
* Service provider for WP Rocket addons.
|
||||
*/
|
||||
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 = [
|
||||
'sucuri_subscriber',
|
||||
'webp_subscriber',
|
||||
'webp_admin_subscriber',
|
||||
];
|
||||
|
||||
/**
|
||||
* Registers items with the container
|
||||
*/
|
||||
public function register() {
|
||||
$options = $this->getContainer()->get( 'options' );
|
||||
|
||||
// Sucuri Addon.
|
||||
$this->getContainer()->share( 'sucuri_subscriber', SucuriSubscriber::class )
|
||||
->addArgument( $options )
|
||||
->addTag( 'common_subscriber' );
|
||||
|
||||
$this->getContainer()->share( 'webp_admin_subscriber', WebPAdminSubscriber::class )
|
||||
->addArgument( $options )
|
||||
->addArgument( $this->getContainer()->get( 'cdn_subscriber' ) )
|
||||
->addArgument( $this->getContainer()->get( 'beacon' ) )
|
||||
->addTag( 'common_subscriber' );
|
||||
|
||||
$this->getContainer()->share( 'webp_subscriber', WebPSubscriber::class )
|
||||
->addArgument( $options )
|
||||
->addArgument( $this->getContainer()->get( 'options_api' ) )
|
||||
->addArgument( $this->getContainer()->get( 'cdn_subscriber' ) )
|
||||
->addTag( 'common_subscriber' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\Sucuri;
|
||||
|
||||
use WP_Error;
|
||||
use WP_Rocket\Admin\Options_Data;
|
||||
use WP_Rocket\Event_Management\Subscriber_Interface;
|
||||
use WP_Rocket\Logger\Logger;
|
||||
|
||||
class Subscriber implements Subscriber_Interface {
|
||||
|
||||
/**
|
||||
* URL of the API.
|
||||
*
|
||||
* %s is here for the other query args.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const API_URL = 'https://waf.sucuri.net/api?v2&%s';
|
||||
|
||||
/**
|
||||
* Instance of the Option_Data class.
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Options_Data $options Instance of the Option_Data class.
|
||||
*/
|
||||
public function __construct( Options_Data $options ) {
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function get_subscribed_events() {
|
||||
return [
|
||||
'after_rocket_clean_domain' => 'maybe_clean_firewall_cache',
|
||||
'after_rocket_clean_post' => 'maybe_clean_firewall_cache',
|
||||
'after_rocket_clean_term' => 'maybe_clean_firewall_cache',
|
||||
'after_rocket_clean_user' => 'maybe_clean_firewall_cache',
|
||||
'after_rocket_clean_home' => 'maybe_clean_firewall_cache',
|
||||
'after_rocket_clean_files' => 'maybe_clean_firewall_cache',
|
||||
'admin_post_rocket_purge_sucuri' => 'do_admin_post_rocket_purge_sucuri',
|
||||
'admin_notices' => 'maybe_print_notice',
|
||||
'rocket_cdn_helper_addons' => 'add_cdn_helper_message',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear Sucuri firewall cache.
|
||||
*
|
||||
* @since 3.2
|
||||
*/
|
||||
public function maybe_clean_firewall_cache() {
|
||||
static $done = false;
|
||||
|
||||
if ( $done ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$done = true;
|
||||
|
||||
if ( ! $this->options->get( 'sucury_waf_cache_sync', 0 ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->clean_firewall_cache();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax callback to empty Sucury cache.
|
||||
*
|
||||
* @since 3.2
|
||||
*/
|
||||
public function do_admin_post_rocket_purge_sucuri() {
|
||||
if ( empty( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], 'rocket_purge_sucuri' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
|
||||
wp_nonce_ays( '' );
|
||||
}
|
||||
|
||||
if ( ! current_user_can( 'rocket_purge_sucuri_cache' ) ) {
|
||||
wp_nonce_ays( '' );
|
||||
}
|
||||
|
||||
$purged = $this->clean_firewall_cache();
|
||||
|
||||
if ( is_wp_error( $purged ) ) {
|
||||
$purged_result = [
|
||||
'result' => 'error',
|
||||
/* translators: %s is the error message returned by the API. */
|
||||
'message' => sprintf( __( 'Sucuri cache purge error: %s', 'rocket' ), $purged->get_error_message() ),
|
||||
];
|
||||
} else {
|
||||
$purged_result = [
|
||||
'result' => 'success',
|
||||
'message' => __( 'The Sucuri cache is being cleared. Note that it may take up to two minutes for it to be fully flushed.', 'rocket' ),
|
||||
];
|
||||
}
|
||||
|
||||
set_transient( get_current_user_id() . '_sucuri_purge_result', $purged_result );
|
||||
|
||||
wp_safe_redirect( esc_url_raw( wp_get_referer() ) );
|
||||
die();
|
||||
}
|
||||
|
||||
/**
|
||||
* Print an admin notice if the cache failed to be cleared.
|
||||
*
|
||||
* @since 3.2
|
||||
*/
|
||||
public function maybe_print_notice() {
|
||||
if ( ! current_user_can( 'rocket_purge_sucuri_cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! is_admin() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! $this->options->get( 'sucury_waf_cache_sync', 0 ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$user_id = get_current_user_id();
|
||||
|
||||
$notice = get_transient( $user_id . '_sucuri_purge_result' );
|
||||
|
||||
if ( ! $notice ) {
|
||||
return;
|
||||
}
|
||||
|
||||
delete_transient( $user_id . '_sucuri_purge_result' );
|
||||
|
||||
rocket_notice_html(
|
||||
[
|
||||
'status' => $notice['result'],
|
||||
'message' => $notice['message'],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell if an API key is well formatted.
|
||||
*
|
||||
* @since 3.2.3
|
||||
*
|
||||
* @param string $api_key An API key.
|
||||
*
|
||||
* @return array|false An array with the keys 'k' and 's' (required by the API) if valid. False otherwise.
|
||||
*/
|
||||
public static function is_api_key_valid( $api_key ) {
|
||||
if ( '' !== $api_key && preg_match( '@^(?<k>[a-z0-9]{32})/(?<s>[a-z0-9]{32})$@', $api_key, $matches ) ) {
|
||||
return $matches;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear Sucuri firewall cache.
|
||||
*
|
||||
* @since 3.2
|
||||
*
|
||||
* @return true|WP_Error True on success. A WP_Error object on failure.
|
||||
*/
|
||||
private function clean_firewall_cache() {
|
||||
$api_key = $this->get_api_key();
|
||||
|
||||
if ( is_wp_error( $api_key ) ) {
|
||||
return $api_key;
|
||||
}
|
||||
|
||||
$response = $this->request_api(
|
||||
[
|
||||
'a' => 'clear_cache',
|
||||
'k' => $api_key['k'],
|
||||
's' => $api_key['s'],
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
Logger::info(
|
||||
'Sucuri firewall cache cleared.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
]
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the API key.
|
||||
*
|
||||
* @since 3.2
|
||||
*
|
||||
* @return array|WP_Error An array with the keys 'k' and 's', required by the API. A WP_Error object if no key or invalid key.
|
||||
*/
|
||||
private function get_api_key() {
|
||||
$api_key = trim( $this->options->get( 'sucury_waf_api_key', '' ) );
|
||||
|
||||
if ( ! $api_key ) {
|
||||
Logger::error(
|
||||
'API key was not found.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
]
|
||||
);
|
||||
|
||||
return new WP_Error( 'no_sucuri_api_key', __( 'Sucuri firewall API key was not found.', 'rocket' ) );
|
||||
}
|
||||
|
||||
$matches = self::is_api_key_valid( $api_key );
|
||||
|
||||
if ( ! $matches ) {
|
||||
Logger::error(
|
||||
'API key is invalid.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
]
|
||||
);
|
||||
|
||||
return new WP_Error( 'invalid_sucuri_api_key', __( 'Sucuri firewall API key is invalid.', 'rocket' ) );
|
||||
}
|
||||
|
||||
return [
|
||||
'k' => $matches['k'],
|
||||
's' => $matches['s'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Request against the API.
|
||||
*
|
||||
* @since 3.2
|
||||
*
|
||||
* @param array $params Parameters to send.
|
||||
*
|
||||
* @return array|WP_Error The response data on success. A WP_Error object on failure.
|
||||
*/
|
||||
private function request_api( $params = [] ) {
|
||||
$params['time'] = time();
|
||||
$params = $this->build_query( $params );
|
||||
$url = sprintf( static::API_URL, $params );
|
||||
|
||||
/**
|
||||
* Filters the arguments for the Sucuri API request
|
||||
*
|
||||
* @since 3.3.4
|
||||
*
|
||||
* @param array $args Arguments for the request.
|
||||
*/
|
||||
$args = apply_filters(
|
||||
'rocket_sucuri_api_request_args',
|
||||
[
|
||||
'timeout' => 5,
|
||||
'redirection' => 5,
|
||||
'httpversion' => '1.1',
|
||||
'blocking' => true,
|
||||
// This filter is documented in wp-includes/class-wp-http-streams.php.
|
||||
'sslverify' => apply_filters( 'https_ssl_verify', true ), // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
|
||||
]
|
||||
);
|
||||
|
||||
$response = wp_remote_get( $url, $args );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
Logger::error(
|
||||
'Error when contacting the API.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
'url' => $url,
|
||||
'response' => $response->get_error_message(),
|
||||
]
|
||||
);
|
||||
|
||||
// translators: %s is an error message.
|
||||
return new WP_Error( 'wp_error_sucuri_api', sprintf( __( 'Error when contacting Sucuri firewall API. Error message was: %s', 'rocket' ), $response->get_error_message() ) );
|
||||
}
|
||||
|
||||
$contents = wp_remote_retrieve_body( $response );
|
||||
|
||||
if ( empty( $contents ) ) {
|
||||
Logger::error(
|
||||
'Could not get a response from the API.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
'url' => $url,
|
||||
'response' => $response,
|
||||
]
|
||||
);
|
||||
|
||||
return new WP_Error( 'sucuri_api_no_response', __( 'Could not get a response from the Sucuri firewall API.', 'rocket' ) );
|
||||
}
|
||||
|
||||
$data = json_decode( $contents, true );
|
||||
|
||||
if ( ! $data || ! is_array( $data ) ) {
|
||||
Logger::error(
|
||||
'Invalid response from the API.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
'url' => $url,
|
||||
'response_body' => $contents,
|
||||
]
|
||||
);
|
||||
|
||||
return new WP_Error( 'sucuri_api_invalid_response', __( 'Got an invalid response from the Sucuri firewall API.', 'rocket' ) );
|
||||
}
|
||||
|
||||
if ( empty( $data['status'] ) ) {
|
||||
Logger::error(
|
||||
'The action failed.',
|
||||
[
|
||||
'sucuri firewall cache',
|
||||
'url' => $url,
|
||||
'response_data' => $data,
|
||||
]
|
||||
);
|
||||
|
||||
if ( empty( $data['messages'] ) || ! is_array( $data['messages'] ) ) {
|
||||
return new WP_Error( 'sucuri_api_error_status', __( 'The Sucuri firewall API returned an unknown error.', 'rocket' ) );
|
||||
}
|
||||
|
||||
// translators: %s is an error message.
|
||||
$message = _n( 'The Sucuri firewall API returned the following error: %s', 'The Sucuri firewall API returned the following errors: %s', count( $data['messages'] ), 'rocket' );
|
||||
$message = sprintf( $message, '<br/>' . implode( '<br/>', $data['messages'] ) );
|
||||
|
||||
return new WP_Error( 'sucuri_api_error_status', $message );
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the helper message on the CDN settings.
|
||||
*
|
||||
* @param string[] $addons Name from the addon that requires the helper message.
|
||||
* @return string[]
|
||||
*/
|
||||
public function add_cdn_helper_message( array $addons ): array {
|
||||
|
||||
if ( ! $this->options->get( 'sucury_waf_cache_sync', false ) ) {
|
||||
return $addons;
|
||||
}
|
||||
|
||||
$addons[] = 'Sucuri';
|
||||
return $addons;
|
||||
}
|
||||
|
||||
/**
|
||||
* An i18n-friendly alternative to the built-in PHP method `http_build_query()`.
|
||||
*
|
||||
* @param array|object $params An array or object containing properties.
|
||||
*
|
||||
* @return string An URL-encoded string.
|
||||
*/
|
||||
private function build_query( $params ): string {
|
||||
if ( ! $params ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$params = (array) $params;
|
||||
|
||||
foreach ( $params as $param => $value ) {
|
||||
$params[ $param ] = $param . '=' . rawurlencode( (string) $value );
|
||||
}
|
||||
|
||||
return implode( '&', $params );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
namespace WP_Rocket\Addon\Varnish;
|
||||
|
||||
use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider;
|
||||
|
||||
/**
|
||||
* Service provider for Varnish Addon.
|
||||
*/
|
||||
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 = [
|
||||
'varnish',
|
||||
'varnish_subscriber',
|
||||
];
|
||||
|
||||
/**
|
||||
* Registers items with the container
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register() {
|
||||
$this->getContainer()->add( 'varnish', Varnish::class );
|
||||
$this->getContainer()->share( 'varnish_subscriber', Subscriber::class )
|
||||
->addArgument( $this->getContainer()->get( 'varnish' ) )
|
||||
->addArgument( $this->getContainer()->get( 'options' ) )
|
||||
->addTag( 'common_subscriber' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
namespace WP_Rocket\Addon\Varnish;
|
||||
|
||||
use WP_Rocket\Admin\Options_Data;
|
||||
use WP_Rocket\Event_Management\Subscriber_Interface;
|
||||
|
||||
/**
|
||||
* Subscriber for the Varnish Purge.
|
||||
*
|
||||
* @since 3.5
|
||||
*/
|
||||
class Subscriber implements Subscriber_Interface {
|
||||
/**
|
||||
* Varnish instance
|
||||
*
|
||||
* @var Varnish
|
||||
*/
|
||||
private $varnish;
|
||||
|
||||
/**
|
||||
* WP Rocket options instance
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param Varnish $varnish Varnish instance.
|
||||
* @param Options_Data $options WP Rocket options instance.
|
||||
*/
|
||||
public function __construct( Varnish $varnish, Options_Data $options ) {
|
||||
$this->varnish = $varnish;
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function get_subscribed_events() {
|
||||
return [
|
||||
'before_rocket_clean_domain' => [ 'clean_domain', 10, 3 ],
|
||||
'before_rocket_clean_file' => [ 'clean_file' ],
|
||||
'rocket_rucss_after_clearing_usedcss' => [ 'clean_file' ],
|
||||
'before_rocket_clean_home' => [ 'clean_home', 10, 2 ],
|
||||
'rocket_rucss_complete_job_status' => [ 'clean_file' ],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if Varnish cache should be purged
|
||||
*
|
||||
* @since 3.5
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function should_purge() {
|
||||
return (
|
||||
/**
|
||||
* Filters the use of the Varnish compatibility add-on
|
||||
*
|
||||
* @param bool $varnish_purge True to use, false otherwise.
|
||||
*/
|
||||
apply_filters( 'do_rocket_varnish_http_purge', false ) // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
|
||||
||
|
||||
(bool) $this->options->get( 'varnish_auto_purge', 0 )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears Varnish cache for the whole domain
|
||||
*
|
||||
* @param string $root The path of home cache file.
|
||||
* @param string $lang The current lang to purge.
|
||||
* @param string $url The home url.
|
||||
* @return void
|
||||
*/
|
||||
public function clean_domain( $root, $lang, $url ) {
|
||||
if ( ! $this->should_purge() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->varnish->purge( trailingslashit( $url ) . '?regex' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears a specific page in Varnish cache
|
||||
*
|
||||
* @param string $url The url to purge.
|
||||
* @return void
|
||||
*/
|
||||
public function clean_file( $url ) {
|
||||
if ( ! $this->should_purge() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->varnish->purge( trailingslashit( $url ) . '?regex' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the homepage in Varnish cache
|
||||
*
|
||||
* @param string $root The path of home cache file.
|
||||
* @param string $lang The current lang to purge.
|
||||
* @return void
|
||||
*/
|
||||
public function clean_home( $root, $lang ) {
|
||||
if ( ! $this->should_purge() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$home_url = trailingslashit( get_rocket_i18n_home_url( $lang ) );
|
||||
$home_pagination_url = $home_url . trailingslashit( $GLOBALS['wp_rewrite']->pagination_base ) . '?regex';
|
||||
|
||||
$this->varnish->purge( $home_url );
|
||||
$this->varnish->purge( $home_pagination_url );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
namespace WP_Rocket\Addon\Varnish;
|
||||
|
||||
/**
|
||||
* Varnish cache purge
|
||||
*
|
||||
* @since 3.5
|
||||
*/
|
||||
class Varnish {
|
||||
/**
|
||||
* Send purge request to Varnish
|
||||
*
|
||||
* @since 3.5
|
||||
*
|
||||
* @param string $url The URL to purge.
|
||||
* @return void
|
||||
*/
|
||||
public function purge( $url ) {
|
||||
$parse_url = get_rocket_parse_url( $url );
|
||||
$x_purge_method = 'default';
|
||||
$regex = '';
|
||||
|
||||
if ( 'regex' === $parse_url['query'] ) {
|
||||
$x_purge_method = 'regex';
|
||||
$regex = '.*';
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the HTTP protocol (scheme)
|
||||
*
|
||||
* @since 2.7.3
|
||||
* @param string $scheme The HTTP protocol
|
||||
*/
|
||||
$scheme = apply_filters( 'rocket_varnish_http_purge_scheme', 'http' );
|
||||
|
||||
/**
|
||||
* Filters the headers to send with the Varnish purge request
|
||||
*
|
||||
* @since 3.1
|
||||
*
|
||||
* @param array $headers Headers to send.
|
||||
*/
|
||||
$headers = apply_filters(
|
||||
'rocket_varnish_purge_headers',
|
||||
[
|
||||
/**
|
||||
* Filters the host value passed in the request headers
|
||||
*
|
||||
* @since 2.8.15
|
||||
* @param string $host The host value.
|
||||
*/
|
||||
'host' => apply_filters( 'rocket_varnish_purge_request_host', $parse_url['host'] ),
|
||||
'X-Purge-Method' => $x_purge_method,
|
||||
]
|
||||
);
|
||||
|
||||
/**
|
||||
* Filters the arguments passed to the Varnish purge request
|
||||
*
|
||||
* @since 3.5
|
||||
*
|
||||
* @param array $args Array of arguments for the request.
|
||||
*/
|
||||
$args = apply_filters(
|
||||
'rocket_varnish_purge_request_args',
|
||||
[
|
||||
'method' => 'PURGE',
|
||||
'blocking' => false,
|
||||
'redirection' => 0,
|
||||
'headers' => $headers,
|
||||
]
|
||||
);
|
||||
|
||||
foreach ( $this->get_varnish_ips() as $ip ) {
|
||||
$host = ! empty( $ip ) ? $ip : str_replace( '*', '', $parse_url['host'] );
|
||||
$purge_url_main = $scheme . '://' . $host . $parse_url['path'];
|
||||
|
||||
/**
|
||||
* Filters the purge url.
|
||||
*
|
||||
* @since 3.6.3
|
||||
*
|
||||
* @param string $purge_url_full Full url contains the main url plus regex pattern.
|
||||
* @param string $purge_url_main Main purge url without any additions params.
|
||||
* @param string $regex Regex string.
|
||||
*/
|
||||
$purge_url = apply_filters(
|
||||
'rocket_varnish_purge_url',
|
||||
$purge_url_main . $regex,
|
||||
$purge_url_main,
|
||||
$regex
|
||||
);
|
||||
|
||||
wp_remote_request( $purge_url, $args );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an array of Varnish IPs to send the purge request to
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function get_varnish_ips() {
|
||||
/**
|
||||
* Filter the Varnish IP to call
|
||||
*
|
||||
* @since 2.6.8
|
||||
* @param string|array $varnish_ip The Varnish IP
|
||||
*/
|
||||
$varnish_ip = apply_filters( 'rocket_varnish_ip', [] );
|
||||
$constant = rocket_get_constant( 'WP_ROCKET_VARNISH_IP' );
|
||||
|
||||
if (
|
||||
! empty( $constant )
|
||||
&&
|
||||
empty( $varnish_ip )
|
||||
) {
|
||||
$varnish_ip = $constant;
|
||||
}
|
||||
|
||||
if ( empty( $varnish_ip ) ) {
|
||||
$varnish_ip = [ '' ];
|
||||
} elseif ( is_string( $varnish_ip ) ) {
|
||||
$varnish_ip = (array) $varnish_ip;
|
||||
}
|
||||
|
||||
return $varnish_ip;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"name": "wp-media/module-varnish",
|
||||
"description": "Varnish Addon for WP Rocket",
|
||||
"homepage": "https://github.com/wp-media/module-varnish",
|
||||
"license": "GPL-2.0+",
|
||||
"authors": [
|
||||
{
|
||||
"name": "WP Media",
|
||||
"email": "contact@wp-media.me",
|
||||
"homepage": "https://wp-media.me"
|
||||
}
|
||||
],
|
||||
"type": "library",
|
||||
"config": {
|
||||
"sort-packages": true
|
||||
},
|
||||
"support": {
|
||||
"issues": "https://github.com/wp-media/module-varnish/issues",
|
||||
"source": "https://github.com/wp-media/module-varnish"
|
||||
},
|
||||
"require-dev": {
|
||||
"php": "^7 || ^8",
|
||||
"brain/monkey": "^2.0",
|
||||
"coenjacobs/mozart": "^0.7",
|
||||
"dealerdirect/phpcodesniffer-composer-installer": "^0.5.0",
|
||||
"league/container": "^3.3",
|
||||
"phpcompatibility/phpcompatibility-wp": "^2.0",
|
||||
"phpstan/phpstan": "^0.12.3",
|
||||
"phpunit/phpunit": "^7",
|
||||
"psr/container": "1.0.0",
|
||||
"roave/security-advisories": "dev-master",
|
||||
"szepeviktor/phpstan-wordpress": "^0.7",
|
||||
"wp-coding-standards/wpcs": "^2",
|
||||
"wp-media/event-manager": "^3.1",
|
||||
"wp-media/options": "^3.0",
|
||||
"wp-media/phpunit": "1.1.6"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": { "WP_Rocket\\Addon\\Varnish\\": "." }
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"WP_Rocket\\Tests\\": "Tests/",
|
||||
"WP_Rocket\\Dependencies\\": "Dependencies/"
|
||||
}
|
||||
},
|
||||
"extra": {
|
||||
"mozart": {
|
||||
"dep_namespace": "WP_Rocket\\Dependencies\\",
|
||||
"dep_directory": "/Dependencies/",
|
||||
"classmap_directory": "/classes/dependencies/",
|
||||
"classmap_prefix": "WP_Rocket_",
|
||||
"packages": [
|
||||
"league/container"
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test-unit": "\"vendor/bin/wpmedia-phpunit\" unit path=Tests/Unit",
|
||||
"test-integration": "\"vendor/bin/wpmedia-phpunit\" integration path=Tests/Integration/",
|
||||
"run-tests": [
|
||||
"@test-unit",
|
||||
"@test-integration"
|
||||
],
|
||||
"install-codestandards": "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\Plugin::run",
|
||||
"phpcs": "\"vendor/bin/phpcs\" .",
|
||||
"phpcs:fix": "\"vendor/bin/phpcbf\" ",
|
||||
"phpstan": "\"vendor/bin/phpstan\" analyse",
|
||||
"post-install-cmd": [
|
||||
"\"vendor/bin/mozart\" compose",
|
||||
"composer dump-autoload"
|
||||
],
|
||||
"post-update-cmd": [
|
||||
"\"vendor/bin/mozart\" compose",
|
||||
"composer dump-autoload"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\WebP;
|
||||
|
||||
use WP_Rocket\Engine\CDN\Subscriber as CDNSubscriber;
|
||||
use WP_Rocket\Subscriber\Third_Party\Plugins\Images\Webp\Webp_Interface;
|
||||
|
||||
abstract class AbstractWebp {
|
||||
/**
|
||||
* CDNSubscriber instance.
|
||||
*
|
||||
* @var CDNSubscriber
|
||||
*/
|
||||
protected $cdn_subscriber;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.12.6
|
||||
*
|
||||
* @param CDNSubscriber $cdn_subscriber CDNSubscriber instance.
|
||||
*/
|
||||
public function __construct( CDNSubscriber $cdn_subscriber ) {
|
||||
$this->cdn_subscriber = $cdn_subscriber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of active plugins that convert and/or serve webp images.
|
||||
*
|
||||
* @since 3.12.6
|
||||
*
|
||||
* @return array An array of Webp_Interface objects.
|
||||
*/
|
||||
protected function get_webp_plugins() {
|
||||
/**
|
||||
* Add Webp plugins.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array $webp_plugins An array of Webp_Interface objects.
|
||||
*/
|
||||
$webp_plugins = (array) apply_filters( 'rocket_webp_plugins', [] );
|
||||
|
||||
if ( ! $webp_plugins ) {
|
||||
// Somebody probably messed up.
|
||||
return [];
|
||||
}
|
||||
|
||||
foreach ( $webp_plugins as $plugin_key => $plugin ) {
|
||||
if ( ! $plugin instanceof Webp_Interface ) {
|
||||
unset( $webp_plugins[ $plugin_key ] );
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( ! $this->is_plugin_active( $plugin->get_basename() ) ) {
|
||||
unset( $webp_plugins[ $plugin_key ] );
|
||||
}
|
||||
}
|
||||
|
||||
return $webp_plugins;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell if a plugin is active.
|
||||
*
|
||||
* @since 3.12.6
|
||||
*
|
||||
* @param string $plugin_basename A plugin basename.
|
||||
* @return bool
|
||||
*/
|
||||
protected function is_plugin_active( string $plugin_basename ): bool {
|
||||
if ( doing_action( 'deactivate_' . $plugin_basename ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( doing_action( 'activate_' . $plugin_basename ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return rocket_is_plugin_active( $plugin_basename );
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell if WP Rocket uses a CDN for images.
|
||||
*
|
||||
* @since 3.12.6
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function is_using_cdn(): bool {
|
||||
// Don't use `$this->options_data->get( 'cdn' )` here, we need an up-to-date value when the CDN option changes.
|
||||
$use = get_rocket_option( 'cdn', 0 ) && $this->cdn_subscriber->get_cdn_hosts( [], [ 'all', 'images' ] );
|
||||
/**
|
||||
* Filter whether WP Rocket is using a CDN for webp images.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param bool $use True if WP Rocket is using a CDN for webp images. False otherwise.
|
||||
*/
|
||||
return (bool) apply_filters( 'rocket_webp_is_using_cdn', $use );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\WebP;
|
||||
|
||||
use WP_Rocket\Admin\Options_Data;
|
||||
use WP_Rocket\Engine\Admin\Beacon\Beacon;
|
||||
use WP_Rocket\Engine\CDN\Subscriber as CDNSubscriber;
|
||||
use WP_Rocket\Event_Management\Subscriber_Interface;
|
||||
|
||||
class AdminSubscriber extends AbstractWebp implements Subscriber_Interface {
|
||||
/**
|
||||
* Options_Data instance.
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
private $options_data;
|
||||
|
||||
/**
|
||||
* Beacon instance
|
||||
*
|
||||
* @var Beacon
|
||||
*/
|
||||
private $beacon;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param Options_Data $options_data Options_Data instance.
|
||||
* @param CDNSubscriber $cdn_subscriber CDNSubscriber instance.
|
||||
* @param Beacon $beacon Beacon instance.
|
||||
*/
|
||||
public function __construct( Options_Data $options_data, CDNSubscriber $cdn_subscriber, Beacon $beacon ) {
|
||||
parent::__construct( $cdn_subscriber );
|
||||
|
||||
$this->options_data = $options_data;
|
||||
$this->beacon = $beacon;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function get_subscribed_events() {
|
||||
return [
|
||||
'rocket_cache_webp_setting_field' => [
|
||||
[ 'maybe_disable_setting_field' ],
|
||||
[ 'webp_section_description' ],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Modifies the WebP section description of WP Rocket settings.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array $cache_webp_field Section description.
|
||||
* @return array
|
||||
*/
|
||||
public function webp_section_description( $cache_webp_field ) {
|
||||
$webp_beacon = $this->beacon->get_suggest( 'webp' );
|
||||
$webp_plugins = $this->get_webp_plugins();
|
||||
$serving = [];
|
||||
$serving_not_compatible = [];
|
||||
$creating = [];
|
||||
|
||||
if ( $webp_plugins ) {
|
||||
$is_using_cdn = $this->is_using_cdn();
|
||||
|
||||
foreach ( $webp_plugins as $plugin ) {
|
||||
if ( $plugin->is_serving_webp() ) {
|
||||
if ( $is_using_cdn && ! $plugin->is_serving_webp_compatible_with_cdn() ) {
|
||||
// Serving WebP using a method not compatible with CDN.
|
||||
$serving_not_compatible[ $plugin->get_id() ] = $plugin->get_name();
|
||||
} else {
|
||||
// Serving WebP when no CDN or with a method compatible with CDN.
|
||||
$serving[ $plugin->get_id() ] = $plugin->get_name();
|
||||
}
|
||||
}
|
||||
if ( $plugin->is_converting_to_webp() ) {
|
||||
// Generating WebP.
|
||||
$creating[ $plugin->get_id() ] = $plugin->get_name();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( $serving ) {
|
||||
// 5, 8.
|
||||
$cache_webp_field['description'] = sprintf(
|
||||
// Translators: %1$s = plugin name(s), %2$s = opening <a> tag, %3$s = closing </a> tag.
|
||||
esc_html( _n( 'You are using %1$s to serve WebP images so you do not need to enable this option. %2$sMore info%3$s %4$s If you prefer to have WP Rocket serve WebP for you instead, please disable WebP display in %1$s.', 'You are using %1$s to serve WebP images so you do not need to enable this option. %2$sMore info%3$s %4$s If you prefer to have WP Rocket serve WebP for you instead, please disable WebP display in %1$s.', count( $serving ), 'rocket' ) ),
|
||||
esc_html( wp_sprintf_l( '%l', $serving ) ),
|
||||
'<a href="' . esc_url( $webp_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $webp_beacon['id'] ) . '" target="_blank" rel="noopener noreferrer">',
|
||||
'</a>',
|
||||
'<br>'
|
||||
);
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
/** This filter is documented in inc/classes/buffer/class-cache.php */
|
||||
if ( apply_filters( 'rocket_disable_webp_cache', false ) ) {
|
||||
$cache_webp_field['description'] = esc_html__( 'WebP cache is disabled by filter.', 'rocket' );
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
if ( $serving_not_compatible ) {
|
||||
if ( ! $this->options_data->get( 'cache_webp', 0 ) ) {
|
||||
// 6.
|
||||
$cache_webp_field['description'] = sprintf(
|
||||
// Translators: %1$s = plugin name(s), %2$s = opening <a> tag, %3$s = closing </a> tag.
|
||||
esc_html( _n( 'You are using %1$s to convert images to WebP. If you want WP Rocket to serve them for you, activate this option. %2$sMore info%3$s', 'You are using %1$s to convert images to WebP. If you want WP Rocket to serve them for you, activate this option. %2$sMore info%3$s', count( $serving_not_compatible ), 'rocket' ) ),
|
||||
esc_html( wp_sprintf_l( '%l', $serving_not_compatible ) ),
|
||||
'<a href="' . esc_url( $webp_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $webp_beacon['id'] ) . '" target="_blank" rel="noopener noreferrer">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
// 7.
|
||||
$cache_webp_field['description'] = sprintf(
|
||||
// Translators: %1$s = plugin name(s), %2$s = opening <a> tag, %3$s = closing </a> tag.
|
||||
esc_html( _n( 'You are using %1$s to convert images to WebP. WP Rocket will create separate cache files to serve your WebP images. %2$sMore info%3$s', 'You are using %1$s to convert images to WebP. WP Rocket will create separate cache files to serve your WebP images. %2$sMore info%3$s', count( $serving_not_compatible ), 'rocket' ) ),
|
||||
esc_html( wp_sprintf_l( '%l', $serving_not_compatible ) ),
|
||||
'<a href="' . esc_url( $webp_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $webp_beacon['id'] ) . '" target="_blank" rel="noopener noreferrer">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
if ( $creating ) {
|
||||
if ( ! $this->options_data->get( 'cache_webp', 0 ) ) {
|
||||
// 3.
|
||||
$cache_webp_field['description'] = sprintf(
|
||||
// Translators: %1$s = plugin name(s), %2$s = opening <a> tag, %3$s = closing </a> tag.
|
||||
esc_html( _n( 'You are using %1$s to convert images to WebP. If you want WP Rocket to serve them for you, activate this option. %2$sMore info%3$s', 'You are using %1$s to convert images to WebP. If you want WP Rocket to serve them for you, activate this option. %2$sMore info%3$s', count( $creating ), 'rocket' ) ),
|
||||
esc_html( wp_sprintf_l( '%l', $creating ) ),
|
||||
'<a href="' . esc_url( $webp_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $webp_beacon['id'] ) . '" target="_blank" rel="noopener noreferrer">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
// 4.
|
||||
$cache_webp_field['description'] = sprintf(
|
||||
// Translators: %1$s = plugin name(s), %2$s = opening <a> tag, %3$s = closing </a> tag.
|
||||
esc_html( _n( 'You are using %1$s to convert images to WebP. WP Rocket will create separate cache files to serve your WebP images. %2$sMore info%3$s', 'You are using %1$s to convert images to WebP. WP Rocket will create separate cache files to serve your WebP images. %2$sMore info%3$s', count( $creating ), 'rocket' ) ),
|
||||
esc_html( wp_sprintf_l( '%l', $creating ) ),
|
||||
'<a href="' . esc_url( $webp_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $webp_beacon['id'] ) . '" target="_blank" rel="noopener noreferrer">',
|
||||
'</a>'
|
||||
);
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
if ( ! $this->options_data->get( 'cache_webp', 0 ) ) {
|
||||
// 1.
|
||||
if ( rocket_valid_key() && ! \Imagify_Partner::has_imagify_api_key() ) {
|
||||
$imagify_link = '<a href="#imagify">';
|
||||
} else {
|
||||
// The Imagify page is not displayed.
|
||||
$imagify_link = '<a href="https://wordpress.org/plugins/imagify/" target="_blank" rel="noopener noreferrer">';
|
||||
}
|
||||
|
||||
$cache_webp_field['description'] = sprintf(
|
||||
// Translators: %1$s = opening <a> tag, %2$s = closing </a> tag.
|
||||
esc_html__( '%5$sWe have not detected any compatible WebP plugin!%6$s%4$s If you don’t already have WebP images on your site consider using %3$sImagify%2$s or another supported plugin. %1$sMore info%2$s %4$s If you are not using WebP do not enable this option.', 'rocket' ),
|
||||
'<a href="' . esc_url( $webp_beacon['url'] ) . '" data-beacon-article="' . esc_attr( $webp_beacon['id'] ) . '" target="_blank" rel="noopener noreferrer">',
|
||||
'</a>',
|
||||
$imagify_link,
|
||||
'<br>',
|
||||
'<strong>',
|
||||
'</strong>'
|
||||
);
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
// 2.
|
||||
$cache_webp_field['description'] = esc_html__( 'WP Rocket will create separate cache files to serve your WebP images.', 'rocket' );
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable 'cache_webp' setting field if another plugin serves WebP.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array $cache_webp_field Data to be added to the setting field.
|
||||
* @return array
|
||||
*/
|
||||
public function maybe_disable_setting_field( $cache_webp_field ) {
|
||||
/** This filter is documented in inc/classes/buffer/class-cache.php */
|
||||
if ( ! apply_filters( 'rocket_disable_webp_cache', false ) ) {
|
||||
return $cache_webp_field;
|
||||
}
|
||||
|
||||
foreach ( [ 'input_attr', 'container_class' ] as $attr ) {
|
||||
if ( ! isset( $cache_webp_field[ $attr ] ) || ! is_array( $cache_webp_field[ $attr ] ) ) {
|
||||
$cache_webp_field[ $attr ] = [];
|
||||
}
|
||||
}
|
||||
|
||||
$cache_webp_field['input_attr']['disabled'] = 1;
|
||||
|
||||
return $cache_webp_field;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,598 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP_Rocket\Addon\WebP;
|
||||
|
||||
use WP_Rocket\Admin\Options;
|
||||
use WP_Rocket\Admin\Options_Data;
|
||||
use WP_Rocket\Event_Management\Subscriber_Interface;
|
||||
use WP_Rocket\Engine\CDN\Subscriber as CDNSubscriber;
|
||||
|
||||
/**
|
||||
* Subscriber for the WebP support.
|
||||
*
|
||||
* @since 3.4
|
||||
*/
|
||||
class Subscriber extends AbstractWebp implements Subscriber_Interface {
|
||||
/**
|
||||
* Options_Data instance.
|
||||
*
|
||||
* @var Options_Data
|
||||
*/
|
||||
private $options_data;
|
||||
|
||||
/**
|
||||
* Options instance.
|
||||
*
|
||||
* @var Options
|
||||
*/
|
||||
private $options_api;
|
||||
|
||||
/**
|
||||
* Values of $_SERVER to use for some tests.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $server;
|
||||
|
||||
/**
|
||||
* \WP_Filesystem_Direct instance.
|
||||
*
|
||||
* @var \WP_Filesystem_Direct
|
||||
*/
|
||||
private $filesystem;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param Options_Data $options_data Options_Data instance.
|
||||
* @param Options $options_api Options instance.
|
||||
* @param CDNSubscriber $cdn_subscriber CDNSubscriber instance.
|
||||
* @param array $server Values of $_SERVER to use for the tests. Default is $_SERVER.
|
||||
*/
|
||||
public function __construct( Options_Data $options_data, Options $options_api, CDNSubscriber $cdn_subscriber, $server = null ) {
|
||||
parent::__construct( $cdn_subscriber );
|
||||
|
||||
$this->options_data = $options_data;
|
||||
$this->options_api = $options_api;
|
||||
|
||||
if ( ! isset( $server ) && ! empty( $_SERVER ) && is_array( $_SERVER ) ) {
|
||||
$server = $_SERVER;
|
||||
}
|
||||
|
||||
$this->server = $server && is_array( $server ) ? $server : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function get_subscribed_events() {
|
||||
return [
|
||||
'rocket_buffer' => [ 'convert_to_webp', 16 ],
|
||||
'rocket_disable_webp_cache' => 'maybe_disable_webp_cache',
|
||||
'rocket_third_party_webp_change' => 'sync_webp_cache_with_third_party_plugins',
|
||||
'rocket_preload_before_preload_url' => 'add_accept_header',
|
||||
'rocket_lazyload_youtube_thumbnail_extension' => 'change_youtube_thumbnail',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts images extension to WebP if the file exists.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param string $html HTML content.
|
||||
* @return string
|
||||
*/
|
||||
public function convert_to_webp( $html ) {
|
||||
if ( ! $this->options_data->get( 'cache_webp', 0 ) ) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
/** This filter is documented in inc/classes/buffer/class-cache.php */
|
||||
if ( apply_filters( 'rocket_disable_webp_cache', false ) ) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
if ( ! $this->is_browser_webp_compatible() ) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$extensions = $this->get_extensions();
|
||||
$attribute_names = $this->get_attribute_names();
|
||||
|
||||
if (
|
||||
empty( $extensions )
|
||||
||
|
||||
empty( $attribute_names )
|
||||
) {
|
||||
return $html . '<!-- Rocket no webp -->';
|
||||
}
|
||||
|
||||
$extensions = implode( '|', $extensions );
|
||||
$attribute_names = implode( '|', $attribute_names );
|
||||
|
||||
if ( ! preg_match_all( '@["\'\s](?<name>(?:data-(?:[a-z0-9_-]+-)?)?(?:' . $attribute_names . '))\s*=\s*["\']\s*(?<value>(?:https?:/)?/[^"\']+\.(?:' . $extensions . ')[^"\']*?)\s*["\']@is', $html, $attributes, PREG_SET_ORDER ) ) {
|
||||
return $html . '<!-- Rocket no webp -->';
|
||||
}
|
||||
|
||||
if ( ! isset( $this->filesystem ) ) {
|
||||
$this->filesystem = \rocket_direct_filesystem();
|
||||
}
|
||||
|
||||
$has_webp = false;
|
||||
|
||||
foreach ( $attributes as $attribute ) {
|
||||
if ( preg_match( '@srcset$@i', strtolower( $attribute['name'] ) ) ) {
|
||||
// This is a srcset attribute, with probably multiple URLs.
|
||||
$new_value = $this->srcset_to_webp( $attribute['value'], $extensions );
|
||||
} else {
|
||||
// A single URL attibute.
|
||||
$new_value = $this->url_to_webp( $attribute['value'], $extensions );
|
||||
}
|
||||
|
||||
if ( ! $new_value ) {
|
||||
// No webp here.
|
||||
continue;
|
||||
}
|
||||
|
||||
// Replace in content.
|
||||
$has_webp = true;
|
||||
$new_attr = preg_replace( '@' . $attribute['name'] . '\s*=\s*["\'][^"\']+["\']@s', $attribute['name'] . '="' . $new_value . '"', $attribute[0] );
|
||||
$html = str_replace( $attribute[0], $new_attr, $html );
|
||||
}
|
||||
|
||||
$has_webp = apply_filters_deprecated( 'rocket_page_has_webp_files', [ $has_webp, $html ], '3.12.6', 'rocket_page_has_webp_files' );
|
||||
|
||||
/**
|
||||
* Tell if the page contains webp files.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param bool $has_webp True if the page contains webp files. False otherwise.
|
||||
* @param string $html The page’s html contents.
|
||||
*/
|
||||
|
||||
$has_webp = apply_filters( 'rocket_page_has_webp_files', $has_webp, $html );
|
||||
|
||||
if ( $has_webp ) {
|
||||
return $html . '<!-- Rocket has webp -->';
|
||||
}
|
||||
|
||||
return $html . '<!-- Rocket no webp -->';
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable the WebP cache if a WebP plugin is in use.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param bool $disable_webp_cache True to disable WebP cache. False otherwise (default).
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function maybe_disable_webp_cache( $disable_webp_cache ): bool {
|
||||
return $disable_webp_cache || ! empty( $this->get_plugins_serving_webp() );
|
||||
}
|
||||
|
||||
/**
|
||||
* When a 3rd party plugin enables or disables its webp feature, disable or enable WPR feature accordingly.
|
||||
*
|
||||
* @since 3.4
|
||||
*/
|
||||
public function sync_webp_cache_with_third_party_plugins() {
|
||||
if (
|
||||
$this->options_data->get( 'cache_webp', 0 )
|
||||
&&
|
||||
$this->get_plugins_serving_webp()
|
||||
) {
|
||||
// Disable the cache webp option.
|
||||
$this->options_data->set( 'cache_webp', 0 );
|
||||
$this->options_api->set( 'settings', $this->options_data->get_options() );
|
||||
}
|
||||
|
||||
rocket_generate_config_file();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add WebP to the HTTP_ACCEPT headers on preload request when the WebP option is active
|
||||
*
|
||||
* @param array $requests Requests to make.
|
||||
* @return array
|
||||
*/
|
||||
public function add_accept_header( $requests ) {
|
||||
if ( ! is_array( $requests ) || ! $this->options_data->get( 'cache_webp', 0 ) ) {
|
||||
return $requests;
|
||||
}
|
||||
|
||||
return array_map(
|
||||
function ( $request ) {
|
||||
$request['headers']['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8';
|
||||
$request['headers']['headers']['HTTP_ACCEPT'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8';
|
||||
return $request;
|
||||
},
|
||||
$requests
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the browser is WebP compatible
|
||||
*
|
||||
* @since 3.12.6
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function is_browser_webp_compatible(): bool {
|
||||
// Only to supporting browsers.
|
||||
$http_accept = isset( $this->server['HTTP_ACCEPT'] ) ? $this->server['HTTP_ACCEPT'] : '';
|
||||
|
||||
if (
|
||||
empty( $http_accept )
|
||||
&&
|
||||
function_exists( 'apache_request_headers' )
|
||||
) {
|
||||
$headers = apache_request_headers();
|
||||
$http_accept = isset( $headers['Accept'] ) ? $headers['Accept'] : '';
|
||||
}
|
||||
|
||||
if (
|
||||
! empty( $http_accept )
|
||||
&&
|
||||
false !== strpos( $http_accept, 'webp' )
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->is_user_agent_compatible();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the User Agent if the Accept headers is missing the WebP info
|
||||
*
|
||||
* @since 3.12.6
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function is_user_agent_compatible(): bool {
|
||||
$user_agent = isset( $this->server['HTTP_USER_AGENT'] ) ? $this->server['HTTP_USER_AGENT'] : '';
|
||||
|
||||
if ( empty( $user_agent ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( preg_match( '#Firefox/(?<version>[0-9]{2,})#i', $user_agent, $matches ) ) {
|
||||
if ( 66 >= (int) $matches['version'] ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if ( preg_match( '#(?:iPad|iPhone)(.*)Version/(?<version>[0-9]{2,})#i', $user_agent, $matches ) ) {
|
||||
if ( 14 > (int) $matches['version'] ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if ( preg_match( '#Version/(?<version>[0-9]{2,})(?:.*)Safari#i', $user_agent, $matches ) ) {
|
||||
if ( 16 > (int) $matches['version'] ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of file extensions that may have a webp version.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function get_extensions() {
|
||||
$extensions = [ 'jpg', 'jpeg', 'jpe', 'png', 'gif' ];
|
||||
|
||||
/**
|
||||
* Filter the list of file extensions that may have a webp version.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array $extensions An array of file extensions.
|
||||
*/
|
||||
$extensions = apply_filters( 'rocket_file_extensions_for_webp', $extensions );
|
||||
$extensions = array_filter(
|
||||
(array) $extensions,
|
||||
function ( $extension ) {
|
||||
return $extension && is_string( $extension );
|
||||
}
|
||||
);
|
||||
|
||||
return array_unique( $extensions );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the names of the HTML attributes where WP Rocket must search for image files.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function get_attribute_names() {
|
||||
$attributes = [ 'href', 'src', 'srcset', 'data-large_image', 'data-thumb' ];
|
||||
|
||||
/**
|
||||
* Filter the names of the HTML attributes where WP Rocket must search for image files.
|
||||
* Don't prepend new names with `data-`, WPR will do it. For example if you want to add `data-foo-bar`, you only need to add `foo-bar` or `bar` to the list.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array $attributes An array of HTML attribute names.
|
||||
*/
|
||||
$attributes = apply_filters( 'rocket_attributes_for_webp', $attributes );
|
||||
$attributes = array_filter(
|
||||
(array) $attributes,
|
||||
function ( $attributes ) {
|
||||
return $attributes && is_string( $attributes );
|
||||
}
|
||||
);
|
||||
|
||||
return array_unique( $attributes );
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a URL to an absolute path.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param string $url URL to convert.
|
||||
* @return string|bool
|
||||
*/
|
||||
private function url_to_path( $url ) {
|
||||
static $hosts, $site_host, $subdir_levels;
|
||||
|
||||
$url_host = wp_parse_url( $url, PHP_URL_HOST );
|
||||
|
||||
// Relative path.
|
||||
if ( null === $url_host ) {
|
||||
if ( ! isset( $subdir_levels ) ) {
|
||||
$subdir_levels = substr_count( preg_replace( '@^https?://@', '', site_url() ), '/' );
|
||||
}
|
||||
|
||||
if ( $subdir_levels ) {
|
||||
$url = ltrim( $url, '/' );
|
||||
$url = explode( '/', $url );
|
||||
array_splice( $url, 0, $subdir_levels );
|
||||
$url = implode( '/', $url );
|
||||
}
|
||||
|
||||
$url = site_url( $url );
|
||||
}
|
||||
|
||||
// CDN.
|
||||
if ( ! isset( $hosts ) ) {
|
||||
$hosts = $this->cdn_subscriber->get_cdn_hosts( [], [ 'all', 'images' ] );
|
||||
$hosts = array_flip( $hosts );
|
||||
}
|
||||
|
||||
if ( isset( $hosts[ $url_host ] ) ) {
|
||||
if ( ! isset( $site_host ) ) {
|
||||
$site_host = wp_parse_url( site_url( '/' ), PHP_URL_HOST );
|
||||
}
|
||||
if ( $site_host ) {
|
||||
$url = preg_replace( '@^(https?://)' . $url_host . '/@', '$1' . $site_host . '/', $url );
|
||||
}
|
||||
}
|
||||
|
||||
// URL to path.
|
||||
$url = preg_replace( '@^https?:@', '', $url );
|
||||
$paths = $this->get_url_to_path_associations();
|
||||
|
||||
if ( ! $paths ) {
|
||||
// Uh?
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ( $paths as $asso_url => $asso_path ) {
|
||||
if ( 0 === strpos( $url, $asso_url ) ) {
|
||||
$file = str_replace( $asso_url, $asso_path, $url );
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ( empty( $file ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** This filter is documented in inc/functions/formatting.php. */
|
||||
return (string) apply_filters( 'rocket_url_to_path', $file, $url );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a webp extension to a URL.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param string $url A URL (I see you're very surprised).
|
||||
* @param string $extensions Allowed image extensions.
|
||||
* @return string|bool The same URL with a webp extension if the file exists. False if the webp image doesn't exist.
|
||||
*/
|
||||
private function url_to_webp( $url, $extensions ) {
|
||||
if ( ! preg_match( '@^(?<src>.+\.(?<extension>' . $extensions . '))(?<query>(?:\?.*)?)$@i', $url, $src_url ) ) {
|
||||
// Probably something like "image.jpg.webp".
|
||||
return false;
|
||||
}
|
||||
|
||||
$src_path = $this->url_to_path( $src_url['src'] );
|
||||
|
||||
if ( empty( $src_path ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$src_path_webp = preg_replace( '@\.' . $src_url['extension'] . '$@', '.webp', $src_path );
|
||||
|
||||
if ( $this->filesystem->exists( $src_path_webp ) ) {
|
||||
// File name: image.jpg => image.webp.
|
||||
return preg_replace( '@\.' . $src_url['extension'] . '$@', '.webp', $src_url['src'] ) . $src_url['query'];
|
||||
}
|
||||
|
||||
if ( $this->filesystem->exists( $src_path . '.webp' ) ) {
|
||||
// File name: image.jpg => image.jpg.webp.
|
||||
return $src_url['src'] . '.webp' . $src_url['query'];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add webp extension to URLs in a srcset attribute.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array|string $srcset_values Value of a srcset attribute.
|
||||
* @param string $extensions Allowed image extensions.
|
||||
* @return string|bool An array similar to $srcset_values, with webp extensions when the files exist. False if no images have webp versions.
|
||||
*/
|
||||
private function srcset_to_webp( $srcset_values, $extensions ) {
|
||||
if ( ! $srcset_values ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( ! is_array( $srcset_values ) ) {
|
||||
$srcset_values = explode( ',', $srcset_values );
|
||||
}
|
||||
|
||||
$has_webp = false;
|
||||
|
||||
foreach ( $srcset_values as $i => $srcset_value ) {
|
||||
$srcset_value = preg_split( '/\s+/', trim( $srcset_value ) );
|
||||
|
||||
if ( count( $srcset_value ) > 2 ) {
|
||||
// Not a good idea to have space characters in file name.
|
||||
$descriptor = array_pop( $srcset_value );
|
||||
$srcset_value = [
|
||||
'url' => implode( ' ', $srcset_value ),
|
||||
'descriptor' => $descriptor,
|
||||
];
|
||||
} else {
|
||||
$srcset_value = [
|
||||
'url' => $srcset_value[0],
|
||||
'descriptor' => ! empty( $srcset_value[1] ) ? $srcset_value[1] : '1x',
|
||||
];
|
||||
}
|
||||
|
||||
$url_webp = $this->url_to_webp( $srcset_value['url'], $extensions );
|
||||
|
||||
if ( ! $url_webp ) {
|
||||
$srcset_values[ $i ] = implode( ' ', $srcset_value );
|
||||
continue;
|
||||
}
|
||||
|
||||
$srcset_values[ $i ] = $url_webp . ' ' . $srcset_value['descriptor'];
|
||||
$has_webp = true;
|
||||
}
|
||||
|
||||
if ( ! $has_webp ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return implode( ',', $srcset_values );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of URL/path associations.
|
||||
* URLs are schema-less, starting by a double slash.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @return array A list of URLs as keys and paths as values.
|
||||
*/
|
||||
private function get_url_to_path_associations() {
|
||||
static $list;
|
||||
|
||||
if ( isset( $list ) ) {
|
||||
return $list;
|
||||
}
|
||||
|
||||
$content_url = preg_replace( '@^https?:@', '', content_url( '/' ) );
|
||||
$content_dir = trailingslashit( rocket_get_constant( 'WP_CONTENT_DIR' ) );
|
||||
$list = [ $content_url => $content_dir ];
|
||||
|
||||
$upload = wp_upload_dir();
|
||||
$upload_dir = trailingslashit( $upload['basedir'] );
|
||||
|
||||
if ( strpos( $upload_dir, $content_dir ) === false ) {
|
||||
$upload_url = preg_replace( '@^https?:@', '', trailingslashit( $upload['baseurl'] ) );
|
||||
$list[ $upload_url ] = $upload_dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the list of URL/path associations.
|
||||
* The URLs with the most levels must come first.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param array $list The list of URL/path associations. URLs are schema-less, starting by a double slash.
|
||||
*/
|
||||
$list = apply_filters( 'rocket_url_to_path_associations', $list );
|
||||
$list = array_filter(
|
||||
$list,
|
||||
function ( $path, $url ) {
|
||||
return $path && $url && is_string( $path ) && is_string( $url );
|
||||
},
|
||||
ARRAY_FILTER_USE_BOTH
|
||||
);
|
||||
|
||||
if ( $list ) {
|
||||
$list = array_unique( $list );
|
||||
}
|
||||
|
||||
return $list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of plugins that serve webp images on frontend.
|
||||
* If the CDN is used, this won't list plugins that use a technique not compatible with CDN.
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @return array The WebP plugin names.
|
||||
*/
|
||||
private function get_plugins_serving_webp() {
|
||||
$webp_plugins = $this->get_webp_plugins();
|
||||
|
||||
if ( ! $webp_plugins ) {
|
||||
// Somebody probably messed up.
|
||||
return [];
|
||||
}
|
||||
|
||||
$checks = [];
|
||||
$is_using_cdn = $this->is_using_cdn();
|
||||
|
||||
foreach ( $webp_plugins as $plugin ) {
|
||||
if ( $is_using_cdn && $plugin->is_serving_webp_compatible_with_cdn() ) {
|
||||
$checks[ $plugin->get_id() ] = $plugin->get_name();
|
||||
} elseif ( ! $is_using_cdn && $plugin->is_serving_webp() ) {
|
||||
$checks[ $plugin->get_id() ] = $plugin->get_name();
|
||||
}
|
||||
}
|
||||
|
||||
return $checks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change Youtube thumbnail extension.
|
||||
*
|
||||
* @param string $extension extension from the thumbnail.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function change_youtube_thumbnail( $extension ) {
|
||||
if ( ! $this->options_data->get( 'cache_webp', 0 ) ) {
|
||||
return $extension;
|
||||
}
|
||||
return 'webp';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user