>|WP_Error */ public static function search( string $query ) { $key = self::key(); if ( null === $key ) { return new WP_Error( 'airanksuite_places_key', __( 'Add a Google Places API key first.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } $query = trim( $query ); if ( '' === $query ) { return new WP_Error( 'airanksuite_places_query', __( 'Type the business name and city.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } $response = wp_remote_post( 'https://places.googleapis.com/v1/places:searchText', array( 'timeout' => 15, 'headers' => array( 'Content-Type' => 'application/json', 'X-Goog-Api-Key' => $key, 'X-Goog-FieldMask' => 'places.id,places.displayName,places.formattedAddress,places.rating,places.userRatingCount,places.primaryTypeDisplayName', ), 'body' => wp_json_encode( array( 'textQuery' => $query, 'maxResultCount' => 6 ) ), ) ); $data = self::body( $response ); if ( $data instanceof WP_Error ) { return $data; } $out = array(); foreach ( (array) ( $data['places'] ?? array() ) as $p ) { $out[] = array( 'id' => (string) ( $p['id'] ?? '' ), 'name' => (string) ( $p['displayName']['text'] ?? '' ), 'address' => (string) ( $p['formattedAddress'] ?? '' ), 'rating' => isset( $p['rating'] ) ? (float) $p['rating'] : null, 'reviews' => (int) ( $p['userRatingCount'] ?? 0 ), 'type' => (string) ( $p['primaryTypeDisplayName']['text'] ?? '' ), ); } return $out; } /** * Fetch the public listing for a Place ID and store it as the snapshot. * * @return array|WP_Error */ public static function fetch( string $place_id ) { $key = self::key(); if ( null === $key ) { return new WP_Error( 'airanksuite_places_key', __( 'Add a Google Places API key first.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } $place_id = preg_replace( '/[^A-Za-z0-9_\-]/', '', $place_id ) ?? ''; if ( '' === $place_id ) { return new WP_Error( 'airanksuite_places_id', __( 'Pick a place first.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } $response = wp_remote_get( 'https://places.googleapis.com/v1/places/' . rawurlencode( $place_id ), array( 'timeout' => 15, 'headers' => array( 'X-Goog-Api-Key' => $key, 'X-Goog-FieldMask' => self::FIELDS, ), ) ); $p = self::body( $response ); if ( $p instanceof WP_Error ) { return $p; } $components = array(); foreach ( (array) ( $p['addressComponents'] ?? array() ) as $c ) { foreach ( (array) ( $c['types'] ?? array() ) as $t ) { $components[ $t ] = (string) ( $c['longText'] ?? '' ); if ( 'country' === $t ) { $components['country_code'] = (string) ( $c['shortText'] ?? '' ); } } } $hours = array(); foreach ( (array) ( $p['regularOpeningHours']['weekdayDescriptions'] ?? array() ) as $line ) { $hours[] = (string) $line; } $snapshot = array( 'place_id' => $place_id, 'name' => (string) ( $p['displayName']['text'] ?? '' ), 'address' => (string) ( $p['formattedAddress'] ?? '' ), 'street' => trim( ( $components['street_number'] ?? '' ) . ' ' . ( $components['route'] ?? '' ) ), 'city' => (string) ( $components['locality'] ?? $components['postal_town'] ?? '' ), 'region' => (string) ( $components['administrative_area_level_1'] ?? '' ), 'postal' => (string) ( $components['postal_code'] ?? '' ), 'country' => (string) ( $components['country_code'] ?? '' ), 'phone' => (string) ( $p['nationalPhoneNumber'] ?? '' ), 'phone_intl' => (string) ( $p['internationalPhoneNumber'] ?? '' ), 'website' => (string) ( $p['websiteUri'] ?? '' ), 'rating' => isset( $p['rating'] ) ? (float) $p['rating'] : null, 'reviews' => (int) ( $p['userRatingCount'] ?? 0 ), 'status' => (string) ( $p['businessStatus'] ?? '' ), 'maps_url' => (string) ( $p['googleMapsUri'] ?? '' ), 'type' => (string) ( $p['primaryTypeDisplayName']['text'] ?? '' ), 'hours' => $hours, 'lat' => isset( $p['location']['latitude'] ) ? (float) $p['location']['latitude'] : null, 'lng' => isset( $p['location']['longitude'] ) ? (float) $p['location']['longitude'] : null, 'fetched' => time(), ); update_option( self::SNAPSHOT_OPTION, $snapshot, false ); self::record( $snapshot ); return $snapshot; } /** @return array|null */ public static function snapshot(): ?array { $s = get_option( self::SNAPSHOT_OPTION ); return is_array( $s ) && ! empty( $s['place_id'] ) ? $s : null; } public static function forget(): void { delete_option( self::SNAPSHOT_OPTION ); } /** * One point per day: rating and review count. A listing that gains ten * reviews a month and one that gains none look identical in a snapshot. * * @param array $snapshot Fresh listing. */ private static function record( array $snapshot ): void { $history = get_option( self::HISTORY_OPTION, array() ); $history = is_array( $history ) ? $history : array(); $day = gmdate( 'Y-m-d' ); $history[ $day ] = array( 'rating' => $snapshot['rating'], 'reviews' => $snapshot['reviews'], ); ksort( $history ); if ( count( $history ) > self::HISTORY_DAYS ) { $history = array_slice( $history, -self::HISTORY_DAYS, null, true ); } update_option( self::HISTORY_OPTION, $history, false ); } /** @return array */ public static function history(): array { $history = get_option( self::HISTORY_OPTION, array() ); $out = array(); foreach ( is_array( $history ) ? $history : array() as $day => $row ) { $out[] = array( 'day' => (string) $day, 'rating' => isset( $row['rating'] ) ? (float) $row['rating'] : null, 'reviews' => (int) ( $row['reviews'] ?? 0 ), ); } return $out; } /** * Field-by-field comparison of the record against the listing. * * NAP consistency is the oldest rule in local search and still the one * most often broken: "Str." on one side and "Straße" on the other is two * businesses to a matching engine. The comparison is loose on whitespace, * case and punctuation, so only real differences are flagged. * * @param array $record The plugin's business record. * @param array $snapshot The Google listing. * @return array */ public static function compare( array $record, array $snapshot ): array { $norm = static function ( string $v ): string { $v = mb_strtolower( trim( $v ) ); $v = preg_replace( '/[\s\.,\-\/()]+/u', ' ', $v ) ?? $v; // The abbreviations every directory expands or contracts at will. $map = array( 'straße' => 'str', 'strasse' => 'str', 'street' => 'st', 'road' => 'rd', 'avenue' => 'ave', 'boulevard' => 'blvd', 'drive' => 'dr', 'lane' => 'ln', 'place' => 'pl', 'square' => 'sq', 'suite' => 'ste', 'floor' => 'fl', 'building' => 'bldg', 'number' => 'no', ); $v = preg_replace_callback( '/\b(' . implode( '|', array_keys( $map ) ) . ')\b/u', static fn( $m ) => $map[ $m[1] ], $v ) ?? $v; return trim( preg_replace( '/\s+/', ' ', $v ) ?? $v ); }; $phone = static function ( string $v ): string { return preg_replace( '/[^0-9+]/', '', $v ) ?? ''; }; $host = static function ( string $v ): string { $h = (string) wp_parse_url( $v, PHP_URL_HOST ); return preg_replace( '/^www\./', '', mb_strtolower( $h ) ) ?? ''; }; $ours_phone = (string) ( $record['phone'] ?? '' ); $theirs_phone = (string) ( $snapshot['phone_intl'] ?: $snapshot['phone'] ); $rows = array( array( 'name', __( 'Name', 'ai-rank-suite' ), (string) ( $record['name'] ?? '' ), (string) $snapshot['name'], $norm( (string) ( $record['name'] ?? '' ) ) === $norm( (string) $snapshot['name'] ) ), array( 'street', __( 'Street', 'ai-rank-suite' ), (string) ( $record['street'] ?? '' ), (string) $snapshot['street'], $norm( (string) ( $record['street'] ?? '' ) ) === $norm( (string) $snapshot['street'] ) ), array( 'postal_code', __( 'Postal code', 'ai-rank-suite' ), (string) ( $record['postal_code'] ?? '' ), (string) $snapshot['postal'], $norm( (string) ( $record['postal_code'] ?? '' ) ) === $norm( (string) $snapshot['postal'] ) ), array( 'city', __( 'City', 'ai-rank-suite' ), (string) ( $record['city'] ?? '' ), (string) $snapshot['city'], $norm( (string) ( $record['city'] ?? '' ) ) === $norm( (string) $snapshot['city'] ) ), array( 'phone', __( 'Phone', 'ai-rank-suite' ), $ours_phone, $theirs_phone, '' !== $phone( $ours_phone ) && ( $phone( $ours_phone ) === $phone( $theirs_phone ) || str_ends_with( $phone( $theirs_phone ), ltrim( $phone( $ours_phone ), '0' ) ) ) ), array( 'website', __( 'Website', 'ai-rank-suite' ), home_url( '/' ), (string) $snapshot['website'], '' !== $snapshot['website'] && $host( home_url( '/' ) ) === $host( (string) $snapshot['website'] ) ), ); $out = array(); foreach ( $rows as [ $key, $label, $ours, $theirs, $match ] ) { // Nothing on either side is not agreement; it is nothing to compare. $out[] = array( 'key' => $key, 'label' => $label, 'ours' => $ours, 'theirs' => $theirs, 'match' => ( '' === trim( $ours ) || '' === trim( $theirs ) ) ? null : (bool) $match, ); } return $out; } /** * Values to write into the record from the listing. * * @param array $snapshot Listing. * @param bool $overwrite Replace filled fields too. * @param array $record Current record. * @return array */ public static function import_values( array $snapshot, bool $overwrite, array $record ): array { $map = array( 'name' => $snapshot['name'], 'street' => $snapshot['street'], 'postal_code' => $snapshot['postal'], 'city' => $snapshot['city'], 'region' => $snapshot['region'], 'country' => $snapshot['country'], 'phone' => $snapshot['phone_intl'] ?: $snapshot['phone'], 'latitude' => null === $snapshot['lat'] ? '' : (string) $snapshot['lat'], 'longitude' => null === $snapshot['lng'] ? '' : (string) $snapshot['lng'], 'map_url' => $snapshot['maps_url'], ); $out = array(); foreach ( $map as $key => $value ) { $value = (string) $value; if ( '' === $value ) { continue; } if ( ! $overwrite && '' !== trim( (string) ( $record[ $key ] ?? '' ) ) ) { continue; } $out[ $key ] = $value; } return $out; } /** * Decode a Places response, turning Google's error envelope into a WP_Error * that says what to do — the API answers 403 for a key without the Places * API enabled, and that message is the one people actually need. * * @param array|WP_Error $response HTTP response. * @return array|WP_Error */ private static function body( $response ) { if ( $response instanceof WP_Error ) { return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); $data = json_decode( (string) wp_remote_retrieve_body( $response ), true ); if ( $code >= 400 || ! is_array( $data ) ) { $msg = is_array( $data ) ? (string) ( $data['error']['message'] ?? '' ) : ''; if ( 403 === $code || 400 === $code && str_contains( $msg, 'API key' ) ) { $msg = __( 'Google refused the key. In Google Cloud, enable "Places API (New)" for the project and allow this key to use it.', 'ai-rank-suite' ) . ( $msg ? ' (' . $msg . ')' : '' ); } elseif ( 404 === $code ) { $msg = __( 'Google knows no place with that ID any more — search again.', 'ai-rank-suite' ); } elseif ( '' === $msg ) { /* translators: %d: the HTTP status code Google returned. */ $msg = sprintf( __( 'Google answered HTTP %d.', 'ai-rank-suite' ), $code ); } return new WP_Error( 'airanksuite_places_http', $msg, array( 'status' => $code >= 500 ? 502 : 400 ) ); } return $data; } }