*/ private static $post_block_occurrence = array(); /** * Map IDs already used during the current render pass. * * @var array */ private static $used_map_ids = array(); /** * @var Insight_Maps_Location_Resolver */ private $resolver; /** * Constructor. */ public function __construct() { $this->resolver = new Insight_Maps_Location_Resolver( new Insight_Maps_Geocoder() ); } /** * Register block assets and type. */ public function register() { wp_register_style( 'leaflet', INSIGHT_MAPS_URL . 'assets/leaflet/leaflet.css', array(), '1.9.4' ); wp_register_style( 'insight-maps-frontend', INSIGHT_MAPS_URL . 'assets/frontend.css', array(), INSIGHT_MAPS_VERSION ); // Leaflet + frontend CSS are dependencies so WordPress copies them into the // iframed editor canvas (WP 7.1+). Do not enqueue them only on the admin shell. wp_register_style( 'insight-maps-editor', INSIGHT_MAPS_URL . 'build/index.css', array( 'wp-edit-blocks', 'leaflet', 'insight-maps-frontend' ), INSIGHT_MAPS_VERSION ); wp_register_script( 'leaflet', INSIGHT_MAPS_URL . 'assets/leaflet/leaflet.js', array(), '1.9.4', true ); wp_register_script( 'insight-maps-frontend', INSIGHT_MAPS_URL . 'assets/frontend.js', array( 'leaflet' ), INSIGHT_MAPS_VERSION, true ); wp_register_script( 'insight-maps-editor', INSIGHT_MAPS_URL . 'build/index.js', array( 'wp-blocks', 'wp-element', 'wp-components', 'wp-block-editor', 'wp-editor', 'wp-i18n', 'wp-api-fetch', 'wp-data', 'leaflet', ), INSIGHT_MAPS_VERSION, true ); wp_set_script_translations( 'insight-maps-editor', 'insight-maps' ); register_block_type( 'osm-location-map/map', array( 'api_version' => 3, 'title' => __( 'Insight Maps', 'insight-maps' ), 'category' => WPINSIGHT_BLOCK_CATEGORY_SLUG, 'icon' => 'location-alt', 'description' => __( 'Set and render an OSM (OpenStreetMap) map from a manual address. No maps API key required.', 'insight-maps' ), 'keywords' => array( 'map', 'openstreetmap', 'location', 'address', 'osm' ), 'attributes' => $this->get_block_attributes(), 'supports' => array( 'html' => false, 'align' => array( 'wide', 'full' ), ), 'uses_context' => array( 'postId', 'postType' ), 'editor_script' => 'insight-maps-editor', 'editor_style' => 'insight-maps-editor', 'style' => 'insight-maps-frontend', 'view_script' => array( 'leaflet', 'insight-maps-frontend' ), 'render_callback' => array( $this, 'render' ), ) ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_assets' ), 20 ); add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_editor_preview_assets' ) ); add_action( 'enqueue_block_editor_assets', array( $this, 'dequeue_frontend_in_editor' ), 100 ); add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) ); } /** * Block attribute definitions. * * @return array> */ private function get_block_attributes() { return array( 'manualAddress' => array( 'type' => 'string', 'default' => '', ), 'manualLat' => array( 'type' => 'number', ), 'manualLng' => array( 'type' => 'number', ), 'height' => array( 'type' => 'string', 'default' => '400px', ), 'width' => array( 'type' => 'string', 'default' => '100%', ), 'zoom' => array( 'type' => 'integer', 'default' => 10, ), 'mapId' => array( 'type' => 'string', 'default' => '', ), ); } /** * Enqueue frontend assets early when the block is present. */ public function enqueue_frontend_assets() { if ( is_admin() ) { return; } $post = get_queried_object(); if ( ! $post instanceof WP_Post ) { return; } if ( has_block( 'osm-location-map/map', $post ) ) { wp_enqueue_style( 'leaflet' ); wp_enqueue_style( 'insight-maps-frontend' ); wp_enqueue_script( 'leaflet' ); wp_enqueue_script( 'insight-maps-frontend' ); wp_localize_script( 'insight-maps-frontend', 'insightMapsFrontendSettings', array( 'markerPreset' => Insight_Maps_Marker_Style::get_preset(), 'popupImageHeight' => Insight_Maps_Plugin_Settings::get_popup_image_height(), 'tileLayer' => Insight_Maps_Tile_Provider::get_leaflet_config(), ) ); } } /** * Load editor scripts/config. Canvas CSS comes from editor_style (+ deps) so it * reaches the iframed post editor (WP 7.1+). Leaflet JS stays in the parent frame. */ public function enqueue_editor_preview_assets() { wp_enqueue_script( 'leaflet' ); wp_localize_script( 'insight-maps-editor', 'insightMapsEditorSettings', array( 'renderInEditor' => Insight_Maps_Plugin_Settings::render_in_editor(), 'markerPreset' => Insight_Maps_Marker_Style::get_preset(), 'popupImageHeight' => Insight_Maps_Plugin_Settings::get_popup_image_height(), 'tileLayer' => Insight_Maps_Tile_Provider::get_leaflet_config(), ) ); } /** * Keep frontend map init out of the block editor. */ public function dequeue_frontend_in_editor() { wp_dequeue_script( 'insight-maps-frontend' ); } /** * Register REST routes used by the block editor. */ public function register_rest_routes() { $route = array( 'methods' => 'POST', 'callback' => array( $this, 'rest_resolve_location' ), 'permission_callback' => array( $this, 'rest_can_resolve_location' ), 'args' => array( 'post_id' => array( 'type' => 'integer', 'sanitize_callback' => 'absint', 'default' => 0, ), // Avoid schema stripping of block attribute keys (additionalProperties). 'attributes' => array( 'required' => true, 'validate_callback' => static function ( $value ) { return is_array( $value ) || is_object( $value ); }, 'sanitize_callback' => static function ( $value ) { if ( is_object( $value ) ) { $value = get_object_vars( $value ); } return is_array( $value ) ? $value : array(); }, ), 'block_occurrence' => array( 'type' => 'integer', 'sanitize_callback' => 'absint', 'default' => 0, ), ), ); register_rest_route( 'insight-maps/v1', '/location', $route ); // Legacy namespace kept so cached editor assets keep working after upgrade. register_rest_route( 'osm-location-map/v1', '/location', $route ); } /** * REST permission check for location resolution. * * @param WP_REST_Request $request Request. * @return bool */ public function rest_can_resolve_location( WP_REST_Request $request ) { $post_id = (int) $request->get_param( 'post_id' ); if ( $post_id > 0 ) { return current_user_can( 'edit_post', $post_id ); } return current_user_can( 'edit_posts' ); } /** * Resolve block coordinates for the editor preview. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function rest_resolve_location( WP_REST_Request $request ) { $post_id = (int) $request->get_param( 'post_id' ); $attributes = $request->get_param( 'attributes' ); $block_occurrence = (int) $request->get_param( 'block_occurrence' ); // Fallback: some stacks leave JSON body params only on get_json_params(). if ( ( ! is_array( $attributes ) || array() === $attributes ) ) { $json = $request->get_json_params(); if ( is_array( $json ) && isset( $json['attributes'] ) ) { $attributes = $json['attributes']; } } if ( is_object( $attributes ) ) { $attributes = get_object_vars( $attributes ); } if ( ! is_array( $attributes ) ) { return new WP_Error( 'insight_maps_invalid_attributes', __( 'Invalid block attributes.', 'insight-maps' ), array( 'status' => 400 ) ); } $result = $this->resolver->resolve_all( $post_id, $attributes ); $locations = ! empty( $result['locations'] ) ? $result['locations'] : array(); $first = ! empty( $locations ) ? $locations[0] : array( 'lat' => 0.0, 'lng' => 0.0, ); $payload = array( 'lat' => $first['lat'], 'lng' => $first['lng'], 'locations' => $locations, 'message' => $result['message'], ); if ( empty( $locations ) ) { $payload['geocode_error'] = Insight_Maps_Geocoder::get_last_error(); } return rest_ensure_response( $payload ); } /** * Render the map block. * * @param array $attributes Block attributes. * @param string $content Block content. * @param WP_Block $block Block instance. * @return string */ public function render( $attributes, $content, $block ) { $post_id = $this->resolve_post_id( $block ); if ( ! isset( self::$post_block_occurrence[ $post_id ] ) ) { self::$post_block_occurrence[ $post_id ] = 0; } self::$post_block_occurrence[ $post_id ]++; $result = $this->resolver->resolve_all( $post_id, $attributes ); if ( empty( $result['locations'] ) ) { // Empty message = unsupported/legacy config handled silently (no lock copy). if ( empty( $result['message'] ) ) { return ''; } return $this->render_failure( $result['message'] ); } $locations = $result['locations']; $first = $locations[0]; $height = $this->sanitize_css_size( $attributes['height'] ?? '400px', '400px' ); $width = $this->sanitize_css_size( $attributes['width'] ?? '100%', '100%' ); $zoom = isset( $attributes['zoom'] ) ? max( 1, min( 18, (int) $attributes['zoom'] ) ) : 10; $render_in_editor = Insight_Maps_Plugin_Settings::render_in_editor(); if ( $this->is_editor_context() && ! $render_in_editor ) { return $this->render_editor_summary( $locations, $height, $width, $zoom ); } if ( $this->is_editor_context() && $render_in_editor ) { return $this->render_editor_static_map( $first, $height, $width, $zoom, $attributes ); } wp_enqueue_style( 'leaflet' ); wp_enqueue_style( 'insight-maps-frontend' ); wp_localize_script( 'insight-maps-frontend', 'insightMapsFrontendSettings', array( 'markerPreset' => Insight_Maps_Marker_Style::get_preset(), 'popupImageHeight' => Insight_Maps_Plugin_Settings::get_popup_image_height(), 'tileLayer' => Insight_Maps_Tile_Provider::get_leaflet_config(), ) ); wp_enqueue_script( 'leaflet' ); wp_enqueue_script( 'insight-maps-frontend' ); $marker_preset = Insight_Maps_Marker_Style::get_preset(); $locations_json = wp_json_encode( $locations ); $map_id = $this->get_map_id( $attributes ); $wrapper_attributes = get_block_wrapper_attributes( array( 'id' => $map_id, 'class' => 'osm-location-map osm-location-map--marker-' . sanitize_html_class( $marker_preset ), 'data-lat' => (string) $first['lat'], 'data-lng' => (string) $first['lng'], 'data-locations' => $locations_json ? $locations_json : '[]', 'data-marker-preset' => sanitize_html_class( $marker_preset ), 'data-zoom' => (string) $zoom, 'style' => sprintf( 'height:%s;width:%s;', esc_attr( $height ), esc_attr( $width ) ), ) ); return sprintf( '
', $wrapper_attributes, esc_attr__( 'OpenStreetMap location map', 'insight-maps' ) ); } /** * Render a static image preview for the editor. * * @param array{lat: float, lng: float, message: string} $result Resolved location. * @param string $height Map height. * @param string $width Map width. * @param int $zoom Zoom level. * @param array $attributes Block attributes. * @return string */ private function render_editor_static_map( $result, $height, $width, $zoom, $attributes ) { $map_id = $this->get_map_id( $attributes ); $wrapper_attributes = get_block_wrapper_attributes( array( 'id' => $map_id, 'class' => 'osm-location-map osm-location-map--editor osm-location-map--static', 'style' => sprintf( 'height:%s;width:%s;', esc_attr( $height ), esc_attr( $width ) ), ) ); $builder = new Insight_Maps_Static_Map_Image(); $map_data = $builder->render_data_uri( $result['lat'], $result['lng'], $zoom ); if ( '' !== $map_data ) { return sprintf( '
%3$s
', $wrapper_attributes, esc_attr( $map_data ), esc_attr__( 'OpenStreetMap location map preview', 'insight-maps' ) ); } return $this->render_editor_embed_map( $result, $height, $width, $zoom, $wrapper_attributes ); } /** * Fallback editor preview using an OpenStreetMap embed iframe. * * @param array{lat: float, lng: float, message: string} $result Resolved location. * @param string $height Map height. * @param string $width Map width. * @param int $zoom Zoom level. * @param string $wrapper_attributes Wrapper HTML attributes. * @return string */ private function render_editor_embed_map( $result, $height, $width, $zoom, $wrapper_attributes ) { $size = $this->get_static_map_pixel_size( $height, $width ); $bbox = $this->calculate_map_bbox( $result['lat'], $result['lng'], $zoom, $size['width'], $size['height'] ); $embed_url = sprintf( 'https://www.openstreetmap.org/export/embed.html?bbox=%1$s,%2$s,%3$s,%4$s&layer=mapnik&marker=%5$s%%2C%6$s', rawurlencode( (string) $bbox['west'] ), rawurlencode( (string) $bbox['south'] ), rawurlencode( (string) $bbox['east'] ), rawurlencode( (string) $bbox['north'] ), rawurlencode( (string) $result['lat'] ), rawurlencode( (string) $result['lng'] ) ); return sprintf( '
', $wrapper_attributes, esc_url( $embed_url ), esc_attr__( 'OpenStreetMap location map preview', 'insight-maps' ) ); } /** * Calculate a bounding box for map embeds. * * @param float $lat Latitude. * @param float $lng Longitude. * @param int $zoom Zoom level. * @param int $width_px Width in pixels. * @param int $height_px Height in pixels. * @return array{west: float, south: float, east: float, north: float} */ private function calculate_map_bbox( $lat, $lng, $zoom, $width_px, $height_px ) { $world_width = 256 * pow( 2, $zoom ); $lon_delta = ( $width_px / $world_width * 360 ) / 2; $lat_adjustment = max( cos( deg2rad( $lat ) ), 0.0001 ); $lat_delta = ( $height_px / $world_width * 360 ) / 2 / $lat_adjustment; return array( 'west' => $lng - $lon_delta, 'south' => max( -85.0511, $lat - $lat_delta ), 'east' => $lng + $lon_delta, 'north' => min( 85.0511, $lat + $lat_delta ), ); } /** * Convert CSS map sizes into static image pixel dimensions. * * @param string $height CSS height. * @param string $width CSS width. * @return array{width: int, height: int} */ private function get_static_map_pixel_size( $height, $width ) { $pixel_height = 400; $pixel_width = 800; if ( preg_match( '/^(\d+)/', $height, $matches ) ) { $pixel_height = max( 120, min( 1024, (int) $matches[1] ) ); } if ( preg_match( '/^(\d+)/', $width, $matches ) ) { $pixel_width = max( 200, min( 1024, (int) $matches[1] ) ); } return array( 'width' => $pixel_width, 'height' => $pixel_height, ); } /** * Resolve the post ID for the current render request. * * @param WP_Block $block Block instance. * @return int */ private function resolve_post_id( $block ) { if ( isset( $block->context['postId'] ) && (int) $block->context['postId'] > 0 ) { return (int) $block->context['postId']; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( isset( $_GET['post_id'] ) && (int) $_GET['post_id'] > 0 ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended return (int) $_GET['post_id']; } if ( get_the_ID() ) { return (int) get_the_ID(); } return 0; } /** * Render a lightweight editor summary when live map preview is disabled. * * @param array $locations Resolved locations. * @param string $height Map height. * @param string $width Map width. * @param int $zoom Zoom level. * @return string */ private function render_editor_summary( $locations, $height, $width, $zoom ) { $count = count( $locations ); $first = $locations[0]; $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => 'osm-location-map osm-location-map--summary', 'style' => sprintf( 'min-height:%s;width:%s;', esc_attr( $height ), esc_attr( $width ) ), ) ); $count_line = $count > 1 ? sprintf( /* translators: %d: number of locations */ __( '%d locations resolved', 'insight-maps' ), $count ) : esc_html__( 'Location resolved', 'insight-maps' ); return sprintf( '

%2$s

%3$s: %4$s
%5$s: %6$s

%7$s: %8$d

%9$s

', $wrapper_attributes, esc_html( $count_line ), esc_html__( 'Latitude', 'insight-maps' ), esc_html( (string) $first['lat'] ), esc_html__( 'Longitude', 'insight-maps' ), esc_html( (string) $first['lng'] ), esc_html__( 'Zoom', 'insight-maps' ), $zoom, esc_html__( 'Enable "Render maps in the block editor" in Settings → Insight Maps to preview the interactive map here.', 'insight-maps' ) ); } /** * Render editor-only failure output. * * @param string $message Failure message. * @return string */ private function render_failure( $message ) { if ( ! $this->is_editor_context() ) { return ''; } $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => 'osm-location-map osm-location-map--empty', ) ); return sprintf( '

%2$s

', $wrapper_attributes, esc_html( $message ) ); } /** * Determine whether the block is being rendered in the editor. * * @return bool */ private function is_editor_context() { if ( is_admin() ) { return true; } if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) { return true; } if ( function_exists( 'wp_is_json_request' ) && wp_is_json_request() ) { return true; } if ( ! empty( $_SERVER['REQUEST_URI'] ) ) { $uri = sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ); if ( false !== strpos( $uri, 'block-renderer' ) ) { return true; } } return false; } /** * Resolve a stable map element ID for this block instance. * * Copied blocks can share the same saved mapId; suffix duplicates on render. * * @param array $attributes Block attributes. * @return string */ private function get_map_id( $attributes ) { $id = isset( $attributes['mapId'] ) ? (string) $attributes['mapId'] : ''; if ( ! preg_match( '/^osm-map-[a-z0-9-]+$/i', $id ) ) { return 'osm-map-' . wp_unique_id(); } $id = strtolower( $id ); if ( ! isset( self::$used_map_ids[ $id ] ) ) { self::$used_map_ids[ $id ] = 1; return $id; } self::$used_map_ids[ $id ]++; return $id . '-' . self::$used_map_ids[ $id ]; } /** * Sanitize a CSS width/height value. * * @param string $value Raw value. * @param string $default_value Default when invalid. * @return string */ private function sanitize_css_size( $value, $default_value ) { $value = trim( (string) $value ); if ( preg_match( '/^\d+(\.\d+)?(px|%|rem|em|vh|vw)$/', $value ) ) { return $value; } if ( preg_match( '/^\d+$/', $value ) ) { return $value . 'px'; } return $default_value; } }