<?php
/**
 * Goodreads block render implementation.
 *
 * Loaded lazily from goodreads.php only when the block is rendered, to keep
 * the render body out of the eager front-end PHP/opcache footprint.
 *
 * @package automattic/jetpack
 */

namespace Automattic\Jetpack\Extensions\Goodreads;

use Automattic\Jetpack\Blocks;
use Jetpack_Gutenberg;

if ( ! defined( 'ABSPATH' ) ) {
	exit( 0 );
}

/**
 * Validates a Goodreads widget script URL.
 *
 * Accepts only URLs shaped like those generated by createGoodreadsEmbedLink()
 * in utils.js — keep the two in sync when either side changes.
 *
 * @param mixed $url URL to validate.
 *
 * @return string Canonical URL rebuilt from the validated components, or an empty string when the URL is not allowed.
 */
function get_validated_script_url( $url ) {
	if ( ! is_string( $url ) || str_contains( $url, '\\' ) ) {
		return '';
	}

	$parsed                = wp_parse_url( esc_url_raw( $url, array( 'https' ) ) );
	$encoded_path          = is_array( $parsed ) ? $parsed['path'] ?? '' : '';
	$path                  = rawurldecode( $encoded_path );
	$has_encoded_separator = 1 === preg_match( '~%(?:2f|5c)~i', $encoded_path );

	if (
		! is_array( $parsed )
		|| empty( $parsed['scheme'] )
		|| 'https' !== strtolower( $parsed['scheme'] )
		|| empty( $parsed['host'] )
		|| 'www.goodreads.com' !== strtolower( $parsed['host'] )
		|| isset( $parsed['user'] )
		|| isset( $parsed['pass'] )
		|| isset( $parsed['port'] )
		|| isset( $parsed['fragment'] )
		|| empty( $parsed['query'] )
		|| $has_encoded_separator
		|| str_contains( $path, '\\' )
	) {
		return '';
	}

	// Only the documented widget endpoints: a numeric Goodreads ID and a non-empty title.
	// Goodreads treats literal slashes as part of the title, so allow them while
	// rejecting dot segments that a URL parser could normalize outside this route.
	if ( 1 !== preg_match( '~^/review/(custom|grid)_widget/[0-9]+\.(.+)$~', $path, $match ) ) {
		return '';
	}

	foreach ( explode( '/', $match[2] ) as $title_segment ) {
		if ( '.' === $title_segment || '..' === $title_segment ) {
			return '';
		}
	}

	$allowed_query_args = 'grid' === $match[1]
		? array( 'cover_size', 'num_books', 'order', 'shelf', 'sort', 'widget_id' )
		: array( 'num_books', 'order', 'shelf', 'show_author', 'show_cover', 'show_rating', 'show_review', 'show_tags', 'show_title', 'sort', 'widget_id' );
	$query_args         = array();

	wp_parse_str( $parsed['query'], $query_args );

	if ( array_diff( array_keys( $query_args ), $allowed_query_args ) ) {
		return '';
	}

	foreach ( $query_args as $value ) {
		if ( is_array( $value ) ) {
			return '';
		}
	}

	return 'https://www.goodreads.com' . $parsed['path'] . '?' . $parsed['query'];
}

/**
 * Dynamic rendering of the block.
 *
 * @param array $attr    Array containing the Goodreads block attributes.
 *
 * @return string
 */
function render_implementation( $attr ) {
	Jetpack_Gutenberg::load_assets_as_required( __DIR__ );

	if ( isset( $attr['id'] ) ) {
		if ( isset( $attr['link'] ) ) {
			$script_url = get_validated_script_url( $attr['link'] );

			if ( '' !== $script_url ) {
				wp_enqueue_script(
					'jetpack-goodreads-' . esc_attr( $attr['id'] ),
					$script_url,
					array(),
					JETPACK__VERSION,
					true
				);
			}
		}

		$id = esc_attr( $attr['id'] );
	} else {
		$id = '';
	}

	$classes = esc_attr( Blocks::classes( Blocks::get_block_feature( __DIR__ ), $attr ) );

	return sprintf(
		'<div id="%1$s" class="%2$s"></div>',
		$id,
		$classes
	);
}
