amimoto-ami / c3-cloudfront-clear-cache

This is simple plugin that clear all cloudfront cache if you publish posts.
25 stars 32 forks source link

Undefined array key "scheme" and "host" #115

Open newtechdigitalau opened 1 year ago

newtechdigitalau commented 1 year ago

Fresh install... Flush All Cache worked fine but on page/post update couldn't see invalidation request submitting successfully to CloudFront. Error in log:

2023/04/13 17:47:52 [error] 378720#378720: *1341 FastCGI sent in stderr: "PHP message: PHP Warning:  Undefined array key "scheme" in /var/www/example.com/html/wp-content/plugins/c3-cloudfront-clear-cache/classes/WP/Post.php on line 57
PHP message: PHP Warning:  Undefined array key "host" in /var/www/example.com/html/wp-content/plugins/c3-cloudfront-clear-cache/classes/WP/Post.php on line 57

PHP message: exception 'Aws\CloudFront\Exception\CloudFrontException' with message 'Error executing "CreateInvalidation" on "https://cloudfront.amazonaws.com/2020-05-31/distribution/<DIST_ID>/invalidation"; AWS HTTP error: Client error: `POST https://cloudfront.amazonaws.com/2020-05-31/distribution/<DIST_ID>/invalidation` resulted in a `400 Bad Request` response:
<?xml version="1.0"?>
<ErrorResponse xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/"><Error><Type>Sender</Type>< (truncated...)
 InvalidArgument (client): Your request contains one or more invalid invalidation paths. - <?xml version="1.0"?>
<ErrorResponse xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/"><Error><Type>Sender</Type><Code>InvalidArgument</Code><Message>Your request contains one or more invalid invalidation paths.</Message></Error><RequestId><REQ_ID></RequestId></ErrorResponse>'
GuzzleHttp\Exception\ClientException: Client error: `POST https://cloudfront.amazonaws.com/2020-05" while reading response header from upstream, client: <Client_IP>, server: example.com, request: "POST /wp-json/wp/v2/pages/378?_locale=user HTTP/1.1", upstream: "fastcgi://unix:/run/php/php8.1-fpm.sock"

In /wp-content/plugins/c3-cloudfront-clear-cache/classes/WP/Post.php I modified this function from:

/**
     * Parse the url
     *
     * @param string $url Target URL.
     */
    public function parse_url( string $url ) {
        $parsed_url = parse_url( $url );
        $url        = $parsed_url['scheme'] . '://' . $parsed_url['host'];
        if ( isset( $parsed_url['path'] ) ) {
            $url .= $parsed_url['path'];
        }
        return $url;
    }

Updated to:

/**
 * Parse the url
 *
 * @param string $url Target URL.
 */
public function parse_url( string $url ) {
    if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
        return false;
    }

    $parsed_url = parse_url( $url );
    $url        = $parsed_url['scheme'] . '://' . $parsed_url['host'];
    if ( isset( $parsed_url['path'] ) ) {
        $url .= $parsed_url['path'];
    }
    return $url;
}

Which has allowed me to temporarily workaround this issue.