165 lines
6.8 KiB
PHP
165 lines
6.8 KiB
PHP
<?php
|
|
|
|
namespace BurnEvents;
|
|
|
|
defined( 'ABSPATH' ) || exit;
|
|
|
|
final class Maps {
|
|
public const KEY_OPTION = 'burn_events_maps_api_key';
|
|
public const ADDRESS_FIELDS = [ 'address', 'city', 'region', 'postal', 'country' ];
|
|
|
|
public static function register_setting(): void {
|
|
add_option( self::KEY_OPTION, '', '', false );
|
|
register_setting( 'burn_events', self::KEY_OPTION, [
|
|
'type' => 'string',
|
|
'sanitize_callback' => [ self::class, 'sanitize_key' ],
|
|
'show_in_rest' => false,
|
|
] );
|
|
}
|
|
|
|
public static function sanitize_key( $value ): string {
|
|
if ( ! empty( $_POST['burn_events_remove_maps_key'] ) && current_user_can( 'manage_options' ) ) {
|
|
return '';
|
|
}
|
|
$value = is_string( $value ) ? trim( $value ) : '';
|
|
if ( '' === $value ) {
|
|
return self::api_key();
|
|
}
|
|
if ( ! preg_match( '/^[A-Za-z0-9_-]{1,160}$/D', $value ) ) {
|
|
add_settings_error( self::KEY_OPTION, 'invalid_key', __( 'Enter a valid Geoapify API key.', 'burn-events' ) );
|
|
return self::api_key();
|
|
}
|
|
return $value;
|
|
}
|
|
|
|
public static function has_key(): bool {
|
|
return '' !== self::api_key();
|
|
}
|
|
|
|
private static function api_key(): string {
|
|
return (string) get_option( self::KEY_OPTION, '' );
|
|
}
|
|
|
|
public static function address( array $data ): string {
|
|
$parts = array_map( static fn( string $field ): string => trim( (string) ( $data[ $field ] ?? '' ) ), self::ADDRESS_FIELDS );
|
|
return implode( ', ', array_filter( $parts, static fn( string $part ): bool => '' !== $part ) );
|
|
}
|
|
|
|
public static function with_coordinates( array $data, array $previous, bool $retry ): array {
|
|
$address = self::address( $data );
|
|
$same_address = $address === self::address( $previous );
|
|
$status = $previous['geocode']['status'] ?? '';
|
|
$has_pin = self::valid_coordinates( $previous['latitude'] ?? null, $previous['longitude'] ?? null );
|
|
$data['latitude'] = '';
|
|
$data['longitude'] = '';
|
|
$data['geocode'] = [];
|
|
|
|
if ( $same_address && ! $retry ) {
|
|
if ( $has_pin && ( 'resolved' === $status || ! self::has_key() ) ) {
|
|
$data['latitude'] = $previous['latitude'];
|
|
$data['longitude'] = $previous['longitude'];
|
|
$data['geocode'] = $previous['geocode'] ?: [ 'status' => 'existing' ];
|
|
return $data;
|
|
}
|
|
if ( in_array( $status, [ 'unmatched', 'ambiguous', 'unavailable' ], true ) ) {
|
|
$data['geocode'] = $previous['geocode'];
|
|
return $data;
|
|
}
|
|
}
|
|
|
|
if ( '' === $address ) {
|
|
return $data;
|
|
}
|
|
if ( '' === $data['address'] || ( '' === $data['city'] && '' === $data['postal'] ) ) {
|
|
$data['geocode'] = [ 'status' => 'incomplete' ];
|
|
return $data;
|
|
}
|
|
$key = self::api_key();
|
|
if ( '' === $key ) {
|
|
$data['geocode'] = [ 'status' => 'missing_key' ];
|
|
return $data;
|
|
}
|
|
return array_replace( $data, self::lookup( $address, $key ) );
|
|
}
|
|
|
|
private static function lookup( string $address, string $key ): array {
|
|
$query = http_build_query( [
|
|
'text' => $address, 'format' => 'json', 'limit' => 5, 'apiKey' => $key,
|
|
], '', '&', PHP_QUERY_RFC3986 );
|
|
$response = wp_safe_remote_get( 'https://api.geoapify.com/v1/geocode/search?' . $query, [
|
|
'timeout' => 5, 'redirection' => 0, 'limit_response_size' => 262144,
|
|
] );
|
|
$body = json_decode( wp_remote_retrieve_body( $response ), true );
|
|
if ( 200 !== wp_remote_retrieve_response_code( $response ) || ! is_array( $body['results'] ?? null ) ) {
|
|
return [ 'geocode' => [ 'status' => 'unavailable' ] ];
|
|
}
|
|
|
|
$matches = array_filter( $body['results'], static function ( $candidate ): bool {
|
|
return is_array( $candidate )
|
|
&& self::valid_coordinates( $candidate['lat'] ?? null, $candidate['lon'] ?? null )
|
|
&& (float) ( $candidate['rank']['confidence'] ?? 0 ) >= 0.8
|
|
&& in_array( $candidate['rank']['match_type'] ?? '', [ 'full_match', 'match_by_building' ], true )
|
|
&& ( ! empty( $candidate['housenumber'] ) || in_array( $candidate['result_type'] ?? '', [ 'building', 'amenity' ], true ) );
|
|
} );
|
|
usort( $matches, static fn( array $first, array $second ): int => $second['rank']['confidence'] <=> $first['rank']['confidence'] );
|
|
if ( ! $matches ) {
|
|
return [ 'geocode' => [ 'status' => 'unmatched' ] ];
|
|
}
|
|
$match = array_shift( $matches );
|
|
foreach ( $matches as $other ) {
|
|
$similar_confidence = $match['rank']['confidence'] - $other['rank']['confidence'] < 0.05;
|
|
$different_place = abs( $match['lat'] - $other['lat'] ) > 0.0005 || abs( $match['lon'] - $other['lon'] ) > 0.0005;
|
|
if ( $similar_confidence && $different_place ) {
|
|
return [ 'geocode' => [ 'status' => 'ambiguous' ] ];
|
|
}
|
|
}
|
|
|
|
return [
|
|
'latitude' => (float) $match['lat'],
|
|
'longitude' => (float) $match['lon'],
|
|
'geocode' => [
|
|
'status' => 'resolved',
|
|
'provider' => 'geoapify',
|
|
'formatted_address' => sanitize_text_field( $match['formatted'] ?? '' ),
|
|
'attribution' => sanitize_text_field( $match['datasource']['attribution'] ?? '' ),
|
|
'license' => sanitize_text_field( $match['datasource']['license'] ?? '' ),
|
|
'source_url' => esc_url_raw( $match['datasource']['url'] ?? '', [ 'http', 'https' ] ),
|
|
],
|
|
];
|
|
}
|
|
|
|
public static function valid_coordinates( $latitude, $longitude ): bool {
|
|
return is_numeric( $latitude ) && is_numeric( $longitude ) && abs( (float) $latitude ) <= 90 && abs( (float) $longitude ) <= 180;
|
|
}
|
|
|
|
public static function lookup_message( array $data ): string {
|
|
return match ( $data['geocode']['status'] ?? '' ) {
|
|
'resolved' => __( 'Coordinates resolved from the saved address.', 'burn-events' ),
|
|
'existing' => __( 'Saved coordinates. Recheck the address to look up a new pin.', 'burn-events' ),
|
|
'incomplete' => __( 'Enter a street address and a city or postal code.', 'burn-events' ),
|
|
'missing_key' => __( 'Save a Geoapify API key under Events → Settings, then save this address again.', 'burn-events' ),
|
|
'unmatched' => __( 'No street-address match. Check the address, city, and postal code.', 'burn-events' ),
|
|
'ambiguous' => __( 'Multiple addresses matched. Add a postal code or country and save again.', 'burn-events' ),
|
|
'unavailable' => __( 'Address lookup failed. Check the Maps API key or try again.', 'burn-events' ),
|
|
default => __( 'Save a complete address to look up coordinates.', 'burn-events' ),
|
|
};
|
|
}
|
|
|
|
public static function attribution( array $data ): void {
|
|
$geocode = $data['geocode'] ?? [];
|
|
$geoapify = 'geoapify' === ( $geocode['provider'] ?? '' );
|
|
if ( ! $geoapify && empty( $geocode['attribution'] ) ) {
|
|
return;
|
|
}
|
|
echo '<small class="be-map-credit">';
|
|
if ( $geoapify ) {
|
|
echo '<a href="https://www.geoapify.com/">' . esc_html__( 'Geocoding by Geoapify', 'burn-events' ) . '</a>';
|
|
}
|
|
if ( ! empty( $geocode['attribution'] ) ) {
|
|
$credit = esc_html( $geocode['attribution'] );
|
|
echo ( $geoapify ? ' · ' : '' ) . ( empty( $geocode['source_url'] ) ? $credit : '<a href="' . esc_url( $geocode['source_url'] ) . '">' . $credit . '</a>' );
|
|
}
|
|
echo '</small>';
|
|
}
|
|
}
|