Commit inicial powerservice

This commit is contained in:
Gabriel
2026-10-19 12:45:45 -06:00
commit ad85486fe2
10158 changed files with 2736804 additions and 0 deletions
@@ -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>&nbsp;'
),
];
$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;
}
}