token = null === $token ? Store::secret( 'cf_token' ) : (string) $token; } /** * Client for the stored connection. * * @return Cloudflare */ public static function stored() { return new self(); } /** * Whether a token is available. * * @return bool */ public function has_token() { return '' !== $this->token; } /** * Perform a request. * * @param string $method HTTP method. * @param string $path Path below /client/v4. * @param array|null $body JSON body. * @param array $query Query arguments. * @return array|WP_Error Decoded "result" (with "_info" for paging) or error. */ public function request( $method, $path, $body = null, array $query = array() ) { if ( ! $this->has_token() ) { return new WP_Error( 'fehu_ap_no_token', __( 'Cloudflare is not connected yet.', 'zonepilot' ) ); } $url = self::BASE . $path; if ( $query ) { $url = add_query_arg( array_map( 'rawurlencode', $query ), $url ); } $args = array( 'method' => $method, 'timeout' => 25, 'headers' => array( 'Authorization' => 'Bearer ' . $this->token, 'Content-Type' => 'application/json', 'User-Agent' => 'ZonePilot/' . FEHU_AP_VERSION . '; WordPress', ), ); if ( null !== $body ) { $args['body'] = wp_json_encode( $body ); } $response = wp_remote_request( $url, $args ); if ( is_wp_error( $response ) ) { return new WP_Error( 'fehu_ap_http', $response->get_error_message() ); } $code = (int) wp_remote_retrieve_response_code( $response ); $data = json_decode( (string) wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $data ) ) { return new WP_Error( 'fehu_ap_bad_response', sprintf( /* translators: %d: HTTP status */ __( 'Unexpected answer from Cloudflare (HTTP %d).', 'zonepilot' ), $code ), array( 'status' => $code ) ); } if ( empty( $data['success'] ) ) { $messages = array(); $codes = array(); foreach ( (array) ( isset( $data['errors'] ) ? $data['errors'] : array() ) as $err ) { $codes[] = isset( $err['code'] ) ? (int) $err['code'] : 0; $messages[] = ( isset( $err['code'] ) ? $err['code'] . ': ' : '' ) . ( isset( $err['message'] ) ? $err['message'] : '' ); } $message = $messages ? implode( '; ', $messages ) : sprintf( 'HTTP %d', $code ); return new WP_Error( 'fehu_ap_cf', $message, array( 'status' => $code, 'codes' => $codes, ) ); } $result = isset( $data['result'] ) ? $data['result'] : array(); if ( is_array( $result ) && isset( $data['result_info'] ) ) { $result['_info'] = $data['result_info']; } return is_array( $result ) ? $result : array( 'value' => $result ); } /** * Whether an error is a 404/"not found". * * @param mixed $error Value. * @return bool */ public static function is_not_found( $error ) { if ( ! is_wp_error( $error ) ) { return false; } $data = $error->get_error_data(); return is_array( $data ) && isset( $data['status'] ) && 404 === (int) $data['status']; } /* ---------------------------------------------------------------- Token & zone */ /** * Verify the token. * * @return array|WP_Error {id, status}. */ public function verify() { return $this->request( 'GET', '/user/tokens/verify' ); } /** * Find the zone that serves a host name (walks up the labels). * * @param string $host Host name, e.g. shop.example.com. * @return array|WP_Error Zone object. */ public function find_zone_for_host( $host ) { $labels = explode( '.', strtolower( $host ) ); $tried = array(); while ( count( $labels ) >= 2 ) { $candidate = implode( '.', $labels ); $tried[] = $candidate; $zones = $this->request( 'GET', '/zones', null, array( 'name' => $candidate ) ); if ( is_wp_error( $zones ) ) { return $zones; } unset( $zones['_info'] ); if ( ! empty( $zones[0]['id'] ) ) { return $zones[0]; } array_shift( $labels ); } return new WP_Error( 'fehu_ap_no_zone', sprintf( /* translators: %s: list of domain names */ __( 'This token cannot see a Cloudflare zone for %s. Check that the domain is on Cloudflare and the token includes it.', 'zonepilot' ), implode( ', ', $tried ) ) ); } /** * Zone details. * * @param string $zone_id Zone id. * @return array|WP_Error */ public function zone( $zone_id ) { return $this->request( 'GET', '/zones/' . rawurlencode( $zone_id ) ); } /** * Zone setting value. * * @param string $zone_id Zone id. * @param string $name Setting id. * @return mixed|WP_Error Value. */ public function setting( $zone_id, $name ) { $res = $this->request( 'GET', '/zones/' . rawurlencode( $zone_id ) . '/settings/' . rawurlencode( $name ) ); if ( is_wp_error( $res ) ) { return $res; } return isset( $res['value'] ) ? $res['value'] : null; } /** * Change a zone-wide setting. Callers must have the owner's confirmation. * * @param string $zone_id Zone id. * @param string $name Setting id. * @param mixed $value Value. * @return array|WP_Error */ public function set_setting( $zone_id, $name, $value ) { return $this->request( 'PATCH', '/zones/' . rawurlencode( $zone_id ) . '/settings/' . rawurlencode( $name ), array( 'value' => $value ) ); } /* ---------------------------------------------------------------- Rulesets */ /** * Phase entry point ruleset of a zone. * * @param string $zone_id Zone id. * @param string $phase Phase name. * @return array|null|WP_Error Null when the phase has no ruleset yet. */ public function entrypoint( $zone_id, $phase ) { $res = $this->request( 'GET', '/zones/' . rawurlencode( $zone_id ) . '/rulesets/phases/' . rawurlencode( $phase ) . '/entrypoint' ); if ( self::is_not_found( $res ) ) { return null; } return $res; } /** * Create the entry point ruleset (only when it does not exist yet). * * @param string $zone_id Zone id. * @param string $phase Phase. * @param array $rules Rules. * @return array|WP_Error */ public function create_entrypoint( $zone_id, $phase, array $rules ) { return $this->request( 'PUT', '/zones/' . rawurlencode( $zone_id ) . '/rulesets/phases/' . rawurlencode( $phase ) . '/entrypoint', array( 'description' => 'Entry point ruleset', 'rules' => $rules, ) ); } /** * Add one rule to an existing ruleset (other rules stay untouched). * * @param string $zone_id Zone id. * @param string $ruleset_id Ruleset id. * @param array $rule Rule. * @return array|WP_Error Ruleset. */ public function add_rule( $zone_id, $ruleset_id, array $rule ) { return $this->request( 'POST', '/zones/' . rawurlencode( $zone_id ) . '/rulesets/' . rawurlencode( $ruleset_id ) . '/rules', $rule ); } /** * Update one rule. * * @param string $zone_id Zone id. * @param string $ruleset_id Ruleset id. * @param string $rule_id Rule id. * @param array $rule Rule. * @return array|WP_Error Ruleset. */ public function update_rule( $zone_id, $ruleset_id, $rule_id, array $rule ) { return $this->request( 'PATCH', '/zones/' . rawurlencode( $zone_id ) . '/rulesets/' . rawurlencode( $ruleset_id ) . '/rules/' . rawurlencode( $rule_id ), $rule ); } /** * Delete one rule. * * @param string $zone_id Zone id. * @param string $ruleset_id Ruleset id. * @param string $rule_id Rule id. * @return array|WP_Error */ public function delete_rule( $zone_id, $ruleset_id, $rule_id ) { return $this->request( 'DELETE', '/zones/' . rawurlencode( $zone_id ) . '/rulesets/' . rawurlencode( $ruleset_id ) . '/rules/' . rawurlencode( $rule_id ) ); } /* ---------------------------------------------------------------- DNS */ /** * All DNS records of a zone. * * @param string $zone_id Zone id. * @return array|WP_Error */ public function dns_records( $zone_id ) { $all = array(); $page = 1; do { $res = $this->request( 'GET', '/zones/' . rawurlencode( $zone_id ) . '/dns_records', null, array( 'per_page' => '500', 'page' => (string) $page, ) ); if ( is_wp_error( $res ) ) { return $res; } $info = isset( $res['_info'] ) ? $res['_info'] : array(); unset( $res['_info'] ); $all = array_merge( $all, array_values( $res ) ); $pages = isset( $info['total_pages'] ) ? (int) $info['total_pages'] : 1; ++$page; } while ( $page <= $pages && $page < 20 ); return $all; } /** * Patch a DNS record. * * @param string $zone_id Zone id. * @param string $record_id Record id. * @param array $fields Fields. * @return array|WP_Error */ public function dns_patch( $zone_id, $record_id, array $fields ) { return $this->request( 'PATCH', '/zones/' . rawurlencode( $zone_id ) . '/dns_records/' . rawurlencode( $record_id ), $fields ); } /** * Create a DNS record. * * @param string $zone_id Zone id. * @param array $record Record. * @return array|WP_Error */ public function dns_create( $zone_id, array $record ) { return $this->request( 'POST', '/zones/' . rawurlencode( $zone_id ) . '/dns_records', $record ); } /** * Delete a DNS record. Only call after the owner confirmed it in the UI. * * @param string $zone_id Zone id. * @param string $record_id Record id. * @return array|WP_Error */ public function dns_delete( $zone_id, $record_id ) { return $this->request( 'DELETE', '/zones/' . rawurlencode( $zone_id ) . '/dns_records/' . rawurlencode( $record_id ) ); } /* ---------------------------------------------------------------- Cache */ /** * Purge cache. * * @param string $zone_id Zone id. * @param array $body One of files[], hosts[], prefixes[], tags[] or purge_everything. * @return array|WP_Error */ public function purge( $zone_id, array $body ) { return $this->request( 'POST', '/zones/' . rawurlencode( $zone_id ) . '/purge_cache', $body ); } /* ---------------------------------------------------------------- Account */ /** * Create a Turnstile widget. * * @param string $account_id Account id. * @param string $name Widget name. * @param array $domains Host names. * @return array|WP_Error {sitekey, secret, ...} */ public function turnstile_create( $account_id, $name, array $domains ) { return $this->request( 'POST', '/accounts/' . rawurlencode( $account_id ) . '/challenges/widgets', array( 'name' => $name, 'domains' => array_values( $domains ), 'mode' => 'managed', ) ); } /** * Delete a Turnstile widget. * * @param string $account_id Account id. * @param string $sitekey Site key. * @return array|WP_Error */ public function turnstile_delete( $account_id, $sitekey ) { return $this->request( 'DELETE', '/accounts/' . rawurlencode( $account_id ) . '/challenges/widgets/' . rawurlencode( $sitekey ) ); } /** * List R2 buckets. * * @param string $account_id Account id. * @return array|WP_Error */ public function r2_buckets( $account_id ) { return $this->request( 'GET', '/accounts/' . rawurlencode( $account_id ) . '/r2/buckets' ); } /** * Create an R2 bucket. * * @param string $account_id Account id. * @param string $name Bucket name. * @return array|WP_Error */ public function r2_create_bucket( $account_id, $name ) { return $this->request( 'POST', '/accounts/' . rawurlencode( $account_id ) . '/r2/buckets', array( 'name' => $name ) ); } }