Skip to content

Commit

Permalink
Closes #5729 Refactor Cloudflare implementation (#5884)
Browse files Browse the repository at this point in the history
Co-authored-by: COQUARD Cyrille <[email protected]>
  • Loading branch information
remyperona and CrochetFeve0251 authored Jun 12, 2023
1 parent 27ee917 commit 73ab0c3
Show file tree
Hide file tree
Showing 157 changed files with 9,853 additions and 2,094 deletions.
1 change: 1 addition & 0 deletions .github/workflows/lint_phpcs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ on:
- develop
- branch-*
- feature/*
- enhancement/*

jobs:
run:
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/test_wprocket.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ on:
- develop
- branch-*
- feature/*
- enhancement/*

jobs:
run:
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/test_wprocket_php8.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ on:
- develop
- branch-*
- feature/*
- enhancement/*

jobs:
run:
Expand Down
2 changes: 1 addition & 1 deletion assets/js/wpr-admin.js.min.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion assets/js/wpr-admin.min.js

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
],
"require": {
"php": ">=7.3",
"cloudflare/cf-ip-rewrite": "^1.0",
"composer/installers": "^1.0 || ^2.0",
"monolog/monolog": "^1.0 || ^2.0"
},
Expand Down Expand Up @@ -115,10 +116,11 @@
},
"scripts": {
"test-unit": "\"vendor/bin/phpunit\" --testsuite unit --colors=always --configuration tests/Unit/phpunit.xml.dist",
"test-integration": "\"vendor/bin/phpunit\" --testsuite integration --colors=always --configuration tests/Integration/phpunit.xml.dist --exclude-group AdminOnly,BeaverBuilder,Elementor,Hummingbird,WithSmush,WithWoo,WithAmp,WithAmpAndCloudflare,WithSCCSS,Cloudways,Dreampress,DoCloudflare,Multisite,WPEngine,SpinUpWP,WordPressCom,O2Switch,PDFEmbedder,PDFEmbedderPremium,PDFEmbedderSecure,Godaddy,LiteSpeed,RevolutionSlider,WordFence,ConvertPlug,Kinsta,Jetpack,RankMathSEO,AllInOneSeoPack,SEOPress,TheSEOFramework,OneCom,RocketLazyLoad,WPXCloud,TheEventsCalendar,Perfmatters,RapidLoad,ProIsp,WPGeotargeting",
"test-integration": "\"vendor/bin/phpunit\" --testsuite integration --colors=always --configuration tests/Integration/phpunit.xml.dist --exclude-group AdminOnly,BeaverBuilder,Elementor,Hummingbird,WithSmush,WithWoo,WithAmp,WithAmpAndCloudflare,WithSCCSS,Cloudways,Dreampress,Cloudflare,CloudflareAdmin,Multisite,WPEngine,SpinUpWP,WordPressCom,O2Switch,PDFEmbedder,PDFEmbedderPremium,PDFEmbedderSecure,Godaddy,LiteSpeed,RevolutionSlider,WordFence,ConvertPlug,Kinsta,Jetpack,RankMathSEO,AllInOneSeoPack,SEOPress,TheSEOFramework,OneCom,RocketLazyLoad,WPXCloud,TheEventsCalendar,Perfmatters,RapidLoad,ProIsp,WPGeotargeting",
"test-integration-adminonly": "\"vendor/bin/phpunit\" --testsuite integration --colors=always --configuration tests/Integration/phpunit.xml.dist --group AdminOnly",
"test-integration-bb": "\"vendor/bin/phpunit\" --testsuite integration --colors=always --configuration tests/Integration/phpunit.xml.dist --group BeaverBuilder",
"test-integration-cloudflare": "\"vendor/bin/phpunit\" --testsuite integration --colors=always --configuration tests/Integration/phpunit.xml.dist --group DoCloudflare",
"test-integration-cloudflare": "\"vendor/bin/phpunit\" --testsuite integration --colors=always --configuration tests/Integration/phpunit.xml.dist --group Cloudflare",
"test-integration-cloudflareadmin": "\"vendor/bin/phpunit\" --testsuite integration --colors=always --configuration tests/Integration/phpunit.xml.dist --group CloudflareAdmin",
"test-integration-cloudways": "\"vendor/bin/phpunit\" --testsuite integration --colors=always --configuration tests/Integration/phpunit.xml.dist --group Cloudways",
"test-integration-elementor": "\"vendor/bin/phpunit\" --testsuite integration --colors=always --configuration tests/Integration/phpunit.xml.dist --group Elementor",
"test-integration-hummingbird": "\"vendor/bin/phpunit\" --testsuite integration --colors=always --configuration tests/Integration/phpunit.xml.dist --group Hummingbird",
Expand Down Expand Up @@ -160,6 +162,7 @@
"@test-integration",
"@test-integration-adminonly",
"@test-integration-cloudflare",
"@test-integration-cloudflareadmin",
"@test-integration-bb",
"@test-integration-elementor",
"@test-integration-hummingbird",
Expand Down
218 changes: 218 additions & 0 deletions inc/Addon/Cloudflare/API/Client.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
<?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 array
*/
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 array $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 ( empty( $content->success ) ) {
return $this->set_request_error( $content );
}

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, array $data ) {
$this->args['method'] = isset( $method ) ? strtoupper( $method ) : 'GET';

$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 ) );
}
}
Loading

0 comments on commit 73ab0c3

Please sign in to comment.