| 1 |
<?php |
| 2 |
/** |
| 3 |
* Handles Google Bot IPs. |
| 4 |
* |
| 5 |
* @package WP_Defender\Component\Known_Bots\Bots |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WP_Defender\Component\Known_Bots\Bots; |
| 9 |
|
| 10 |
/** |
| 11 |
* This class is responsible for fetching and managing Google Bot IPs. |
| 12 |
*/ |
| 13 |
class Google_Bot extends Abstract_Bot { |
| 14 |
/** |
| 15 |
* Returns the name of the bot. |
| 16 |
* |
| 17 |
* @return string The name of the bot. |
| 18 |
*/ |
| 19 |
public function get_name(): string { |
| 20 |
return 'googlebot'; |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* Fetches the IPs for Google Bot. |
| 25 |
* |
| 26 |
* This method retrieves the IP ranges used by Google Bot from a remote JSON endpoint. |
| 27 |
* It returns an array of IP addresses in both IPv4 and IPv6 formats. |
| 28 |
* |
| 29 |
* @return array An array of IP addresses used by Google Bot. |
| 30 |
*/ |
| 31 |
public function fetch_ips(): array { |
| 32 |
$url = 'https://developers.google.com/static/search/apis/ipranges/googlebot.json'; |
| 33 |
$ips = array(); |
| 34 |
|
| 35 |
$response = wp_remote_get( $url ); |
| 36 |
if ( is_array( $response ) && ! is_wp_error( $response ) ) { |
| 37 |
$data = json_decode( wp_remote_retrieve_body( $response ), true ); |
| 38 |
foreach ( $data['prefixes'] ?? array() as $entry ) { |
| 39 |
if ( isset( $entry['ipv4Prefix'] ) ) { |
| 40 |
$ips[] = $entry['ipv4Prefix']; |
| 41 |
} |
| 42 |
|
| 43 |
if ( isset( $entry['ipv6Prefix'] ) ) { |
| 44 |
$ips[] = $entry['ipv6Prefix']; |
| 45 |
} |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
return $ips; |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Checks if the user agent belongs to Google. |
| 54 |
* |
| 55 |
* @param string $user_agent Optional user agent string to check. |
| 56 |
* |
| 57 |
* @return bool |
| 58 |
*/ |
| 59 |
public function is_ua( string $user_agent = '' ): bool { |
| 60 |
$ua = $this->normalize_ua( $user_agent ); |
| 61 |
if ( '' === $ua ) { |
| 62 |
return false; |
| 63 |
} |
| 64 |
|
| 65 |
return false !== stristr( $ua, 'googlebot' ); |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
* Checks if IP is from Google, based on DNS verification. |
| 70 |
* |
| 71 |
* @param string $ip The IP address to check. |
| 72 |
* |
| 73 |
* @return bool |
| 74 |
*/ |
| 75 |
public function is_ip( string $ip ): bool { |
| 76 |
return $this->verify_dns( $ip, '(^|\.)(googlebot\.com|google\.com)' ); |
| 77 |
} |
| 78 |
} |
| 79 |
|