} status: ok|blocked|unreachable */ public static function result( \AilysLens\Core\DefinitionRepository $repository ): array { $cached = get_transient( self::TRANSIENT ); if ( is_array( $cached ) && isset( $cached['status'] ) ) { return $cached; } $response = wp_remote_get( home_url( '/robots.txt' ), array( 'timeout' => 4 ) ); if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) { $result = array( 'status' => 'unreachable', 'blocked' => array(), ); set_transient( self::TRANSIENT, $result, 6 * HOUR_IN_SECONDS ); return $result; } $tokens = array(); foreach ( $repository->crawlers() as $crawler ) { $tokens[] = $crawler->uaPattern; } foreach ( $repository->robotsTxtTokens() as $token ) { $tokens[] = $token['token']; } $blocked = self::blocked_tokens( (string) wp_remote_retrieve_body( $response ), $tokens ); $result = array( 'status' => array() === $blocked ? 'ok' : 'blocked', 'blocked' => $blocked, ); set_transient( self::TRANSIENT, $result, 6 * HOUR_IN_SECONDS ); return $result; } /** * robots.txt本文から「Disallow: /」で全面拒否されているトークンを抽出する。 * * @param string $body robots.txt本文。 * @param array $tokens チェック対象トークン。 * @return array */ public static function blocked_tokens( string $body, array $tokens ): array { $groups = array(); $current_uas = array(); $in_rule_block = false; $raw_lines = preg_split( '/\r\n|\r|\n/', $body ); if ( false === $raw_lines ) { $raw_lines = array(); } foreach ( $raw_lines as $line ) { $line = trim( (string) preg_replace( '/#.*$/', '', $line ) ); if ( '' === $line || false === strpos( $line, ':' ) ) { continue; } list( $field, $value ) = array_map( 'trim', explode( ':', $line, 2 ) ); $field = strtolower( $field ); if ( 'user-agent' === $field ) { if ( $in_rule_block ) { $current_uas = array(); $in_rule_block = false; } $current_uas[] = strtolower( $value ); } elseif ( 'disallow' === $field || 'allow' === $field ) { $in_rule_block = true; foreach ( $current_uas as $ua ) { $groups[ $ua ][] = array( $field, $value ); } } } $blocked = array(); foreach ( $tokens as $token ) { $rules = $groups[ strtolower( $token ) ] ?? null; if ( null === $rules ) { continue; } $fully_blocked = false; foreach ( $rules as $rule ) { if ( 'disallow' === $rule[0] && '/' === $rule[1] ) { $fully_blocked = true; } if ( 'allow' === $rule[0] && '/' === $rule[1] ) { $fully_blocked = false; break; } } if ( $fully_blocked ) { $blocked[] = $token; } } return $blocked; } }