coords_from_cache_value( get_transient( $cache_key ) ); if ( null !== $cached_coords ) { return $cached_coords; } foreach ( self::LEGACY_CACHE_PREFIXES as $prefix ) { $legacy_coords = $this->coords_from_cache_value( get_transient( $prefix . $hash ) ); if ( null !== $legacy_coords ) { set_transient( $cache_key, $legacy_coords, self::CACHE_TTL ); return $legacy_coords; } } $url = add_query_arg( array( 'q' => $address, 'format' => 'json', 'limit' => 1, ), 'https://nominatim.openstreetmap.org/search' ); $response = $this->request_nominatim( $url ); if ( is_wp_error( $response ) ) { self::$last_error = 'transport: ' . $response->get_error_message(); return null; } $code = (int) wp_remote_retrieve_response_code( $response ); $body = (string) wp_remote_retrieve_body( $response ); if ( 200 !== $code ) { self::$last_error = 'HTTP ' . $code; return null; } $data = json_decode( $body, true ); if ( ! is_array( $data ) ) { self::$last_error = 'invalid_json'; return null; } if ( ! isset( $data[0] ) || ! is_array( $data[0] ) ) { self::$last_error = 'no_results'; return null; } $lat = $data[0]['lat'] ?? null; $lon = $data[0]['lon'] ?? null; if ( ! is_numeric( $lat ) || ! is_numeric( $lon ) ) { self::$last_error = 'missing_coordinates'; return null; } $result = array( 'lat' => (float) $lat, 'lng' => (float) $lon, ); set_transient( $cache_key, $result, self::CACHE_TTL ); return $result; } /** * Request Nominatim via the WordPress HTTP API only. * * @param string $url Fully built Nominatim URL. * @return array|WP_Error WP HTTP response array or error. */ private function request_nominatim( $url ) { $user_agent = $this->sanitize_header_value( $this->get_user_agent() ); $referer = $this->sanitize_header_value( home_url( '/' ) ); return wp_remote_get( $url, array( 'timeout' => 15, 'redirection' => 2, 'sslverify' => true, 'user-agent' => $user_agent, 'headers' => array( 'Accept' => 'application/json', 'Referer' => $referer, 'User-Agent' => $user_agent, ), ) ); } /** * Strip CR/LF so header values cannot break the HTTP request. * * @param string $value Raw header value. * @return string */ private function sanitize_header_value( $value ) { $value = str_replace( array( "\r", "\n" ), ' ', (string) $value ); return trim( $value ); } /** * Extract coordinates from a transient payload (ignores negative markers). * * @param mixed $cached Transient value. * @return array{lat: float, lng: float}|null */ private function coords_from_cache_value( $cached ) { if ( ! is_array( $cached ) || ! isset( $cached['lat'], $cached['lng'] ) ) { return null; } if ( ! is_numeric( $cached['lat'] ) || ! is_numeric( $cached['lng'] ) ) { return null; } return array( 'lat' => (float) $cached['lat'], 'lng' => (float) $cached['lng'], ); } /** * Build the required Nominatim user agent string. * * @return string */ private function get_user_agent() { return Insight_Maps_Tile_Provider::get_user_agent(); } }