Commit inicial powerservice

This commit is contained in:
Gabriel
2026-10-19 12:45:45 -06:00
commit ad85486fe2
10158 changed files with 2736804 additions and 0 deletions
@@ -0,0 +1,630 @@
<?php
namespace WordPress\DataLiberation\BlockMarkup;
use WP_Error;
use WP_HTML_Tag_Processor;
/**
* A processor class capable of reading and rewriting block markup.
*
* This class provides functionality to parse, traverse and modify WordPress block markup.
* It extends WP_HTML_Tag_Processor to add block-specific capabilities like:
* - Parsing block comments into name and attributes
* - Tracking block nesting depth
* - Modifying block attributes
* - Validating block structure
*
* Contrary to WP_HTML_Tag_Processor, this class does not support streaming.
* It assumes block markup blobs are small enough to fit into memory, otherwise
* WordPress won't be able to render them anyway.
*
* @see WP_HTML_Tag_Processor
*/
class BlockMarkupProcessor extends WP_HTML_Tag_Processor {
/**
* The name of the current block (e.g. 'core/paragraph')
*
* @var string|null
*/
private $block_name;
/**
* The attributes of the current block as an associative array
*
* @var array<string, mixed>|null
*/
protected $block_attributes;
/**
* Whether the current block's attributes have been modified and need to be serialized
*
* @var bool
*/
private $block_attributes_updated;
/**
* Whether the current block token is a closing tag (e.g. <!-- /wp:paragraph -->)
*
* @var bool
*/
private $block_closer;
/**
* Whether the current block is self-closing (e.g. <!-- wp:spacer /-->)
*
* @var bool
*/
private $self_closing_flag;
/**
* Stack tracking the names of currently open blocks for validation
*
* @var array<string>
*/
private $stack_of_open_blocks = array();
/**
* The most recent error encountered while parsing blocks
*
* @var string|null
*/
private $last_block_error;
/**
* A flattened list of paths (arrays of keys) to every attribute found in
* $block_attributes. This is used by next_block_attribute() to traverse
* attributes without relying on PHP iterator classes.
*
* @var array<int, array<int|string>>|null
*/
private $block_attribute_paths = null;
/**
* The index of the current attribute inside $block_attribute_paths.
* Starts at -1 so that the first call to next_block_attribute() positions
* the cursor at index 0.
*
* @var int
*/
private $block_attribute_index = -1;
/**
* Gets the type of the current token, adding a special '#block-comment' type
* for WordPress block delimiters.
*
* @return string|null The token type or null if no token
*/
public function get_token_type(): ?string {
switch ( $this->parser_state ) {
case self::STATE_COMMENT:
if ( null !== $this->block_name ) {
return '#block-comment';
}
return '#comment';
default:
return parent::get_token_type();
}
}
/**
* Gets the most recent error encountered while parsing blocks
*
* @return WP_Error|null The error message or null if no error
*/
public function get_last_error(): ?WP_Error {
return $this->last_block_error;
}
/**
* Advances past the block closer of the currently matched block and returns
* the HTML content found between the block's opener and closer.
*
* @return string|false The inner HTML content of the block or false if not a block opener.
*/
public function skip_and_get_block_inner_html() {
if ( '#block-comment' !== $this->get_token_type() ) {
return false;
}
if ( $this->is_block_closer() ) {
return false;
}
if ( false === WP_HTML_Tag_Processor::set_bookmark( 'block-start' ) ) {
return false;
}
$starting_block_depth = $this->get_block_depth();
while ( $this->next_token() ) {
if (
'#block-comment' === $this->get_token_type() &&
$this->is_block_closer() &&
$this->get_block_depth() === $starting_block_depth - 1
) {
break;
}
}
if ( false === WP_HTML_Tag_Processor::set_bookmark( 'block-end' ) ) {
WP_HTML_Tag_Processor::release_bookmark( 'block-start' );
return false;
}
$inner_html_start = $this->bookmarks['block-start']->start + $this->bookmarks['block-start']->length;
$inner_html_end = $this->bookmarks['block-end']->start - $inner_html_start;
WP_HTML_Tag_Processor::release_bookmark( 'block-start' );
WP_HTML_Tag_Processor::release_bookmark( 'block-end' );
return substr(
$this->html,
$inner_html_start,
$inner_html_end
);
}
/**
* Gets the depth of the currently matched block on the block stack. It only
* considers the parent blocks and not HTML elements.
*
* For example, the paragraph block in the following markup has a depth of 1:
*
* <!-- wp:core/blockquote -->
* <blockquote>
* <!-- wp:core/paragraph -->
* <p>Hello, there</p>
* <!-- /wp:core/paragraph -->
* </blockquote>
* <!-- /wp:core/blockquote -->
*
* @return int The number of ancestor blocks
*/
public function get_block_depth() {
return count( $this->stack_of_open_blocks );
}
/**
* Gets the names of all currently open blocks from outermost to innermost
*
* @return array List of block names in nesting order
*/
public function get_block_breadcrumbs() {
return $this->stack_of_open_blocks;
}
/**
* Returns the name of the block if the current token is a block comment.
*
* @return string|false The block name (e.g. 'core/paragraph') or false if not at a block
*/
public function get_block_name() {
if ( null === $this->block_name ) {
return false;
}
return $this->block_name;
}
/**
* Gets all attributes of the current block
*
* @return array|false The block attributes or false if not at a block
*/
public function get_block_attributes() {
if ( null === $this->block_attributes ) {
return false;
}
return $this->block_attributes;
}
/**
* Gets a specific attribute value from the current block
*
* @param string $attribute_name The name of the attribute to get
*
* @return mixed|false The attribute value or false if not found
*/
public function get_block_attribute( $attribute_name ) {
if ( null === $this->block_attributes ) {
return false;
}
return $this->block_attributes[ $attribute_name ] ?? false;
}
/**
* Overwrites all the block attributes of the currently matched block
* opener.
*
* @param array $attributes The new attributes to set
*
* @return bool Whether the attributes were successfully set
*/
public function set_block_attributes( $attributes ) {
if ( '#block-comment' !== $this->get_token_type() ) {
return false;
}
if ( $this->is_block_closer() ) {
return false;
}
$this->block_attributes = $attributes;
$this->block_attributes_updated = true;
return true;
}
/**
* Checks if the currently matched token is a block closer,
* e.g. <!-- /wp:paragraph -->.
*
* @return bool True if at a block closer.
*/
public function is_block_closer() {
return null !== $this->block_name && true === $this->block_closer;
}
/**
* Checks if the currently matched token is a self-closing block,
* e.g. <!-- wp:spacer /-->.
*
* @return bool True if at a self-closing block.
*/
public function is_self_closing_block() {
return null !== $this->block_name && true === $this->self_closing_flag;
}
/**
* Advances to the next token in the HTML stream. Matches:
* - The regular HTML tokens
* - WordPress block openers
* - WordPress block closers
* - WordPress self-closing blocks
*
* @return bool Whether a token was parsed.
*/
public function next_token(): bool {
if ( $this->has_bookmark( 'block-delimiter' ) ) {
$this->release_bookmark( 'block-delimiter' );
}
$this->get_updated_html();
$this->block_name = null;
$this->block_attributes = null;
$this->block_attribute_paths = null;
$this->block_attribute_index = -1;
$this->block_closer = false;
$this->self_closing_flag = false;
$this->block_attributes_updated = false;
while ( true ) {
if ( false === parent::next_token() ) {
return false;
}
if (
'#tag' === $this->get_token_type() && (
'HTML' === $this->get_tag() ||
'HEAD' === $this->get_tag() ||
'BODY' === $this->get_tag()
)
) {
continue;
}
break;
}
if ( '#comment' !== parent::get_token_type() ) {
return true;
}
$text = parent::get_modifiable_text();
/**
* Try to parse as a block. The block parser won't cut it because
* while it can parse blocks, it has no semantics for rewriting the
* block markup. Let's do our best here:
*/
$at = strspn( $text, " \t\f\r\n" ); // Whitespace.
if ( $at >= strlen( $text ) ) {
// This is an empty comment. Not a block.
return true;
}
// Blocks closers start with the solidus character (`/`).
if ( '/' === $text[ $at ] ) {
$this->block_closer = true;
++$at;
}
// Blocks start with wp.
if ( ! (
$at + 3 < strlen( $text ) &&
'w' === $text[ $at ] &&
'p' === $text[ $at + 1 ] &&
':' === $text[ $at + 2 ]
) ) {
return true;
}
$name_starts_at = $at;
// Skip wp.
$at += 3;
// Parse the actual block name after wp.
$name_length = strspn( $text, 'abcdefghijklmnopqrstuwxvyzABCDEFGHIJKLMNOPRQSTUWXVYZ0123456789_-', $at );
if ( 0 === $name_length ) {
// This wasn't a block after all, just a regular comment.
$this->last_block_error = new WP_Error(
'suspicious-delimiter',
sprintf( 'An HTML comment started with "wp:" that was not followed by a valid block name: %s', $text )
);
return true;
}
$name = substr( $text, $name_starts_at, $name_length + 3 );
$at += $name_length;
// Assume no attributes by default.
$attributes = array();
// Skip the whitespace that follows the block name.
$at += strspn( $text, " \t\f\r\n", $at );
if ( $at < strlen( $text ) ) {
// It may be a self-closing block or a block with attributes.
// However, block closers can be neither – let's short-circuit.
if ( $this->block_closer ) {
return true;
}
// The rest of the comment can only consist of block attributes
// and an optional solidus character.
$rest = ltrim( substr( $text, $at ) );
$at = strlen( $text );
// Inspect our potential JSON for the self-closing solidus (`/`) character.
$json_maybe = $rest;
if ( '/' === substr( $json_maybe, - 1 ) ) {
// Self-closing block (<!-- wp:image /-->).
$this->self_closing_flag = true;
$json_maybe = substr( $json_maybe, 0, - 1 );
}
// Let's try to parse attributes as JSON.
if ( strlen( $json_maybe ) > 0 ) {
$attributes = json_decode( trim( $json_maybe ), true );
if ( null === $attributes || ! is_array( $attributes ) ) {
// This comment looked like a block comment, but the attributes didn't
// parse as a JSON array. This means it wasn't a block after all.
$this->last_block_error = new WP_Error(
'suspicious-delimiter',
sprintf( '%s could be parsed as a delimiter but JSON attributes were malformed: %s.', $name, $json_maybe )
);
return true;
}
}
}
// We have a block name and a valid attributes array. We may not find a block
// closer, but let's assume is a block and process it as such
// @TODO: Confirm that WordPress block parser would have parsed this as a block.
$this->block_name = $name;
$this->block_attributes = $attributes;
if ( $this->block_closer ) {
$popped = array_pop( $this->stack_of_open_blocks );
if ( $popped !== $name ) {
$this->last_block_error = new WP_Error(
'mismatched-closer',
sprintf( 'Block closer %s does not match the last opened block %s.', $name, $popped )
);
return false;
}
} elseif ( ! $this->self_closing_flag ) {
array_push( $this->stack_of_open_blocks, $name );
}
$this->set_bookmark( 'block-delimiter' );
return true;
}
public function get_block_delimiter_span() {
if ( ! $this->has_bookmark( 'block-delimiter' ) ) {
return false;
}
return $this->bookmarks['block-delimiter'];
}
public function next_block_delimiter() {
while ( $this->next_token() ) {
if ( '#block-comment' === $this->get_token_type() ) {
break;
}
}
if ( '#block-comment' !== $this->get_token_type() ) {
return false;
}
return true;
}
/**
* @inheritDoc
*/
public function get_updated_html(): string {
$this->block_attribute_updates_to_modifiable_text_updates();
return parent::get_updated_html();
}
/**
* Converts block attribute updates into lexical updates.
*
* @return bool Whether any lexical updates were created
*/
private function block_attribute_updates_to_modifiable_text_updates() {
// Apply block attribute updates, if any.
if ( ! $this->block_attributes_updated ) {
return false;
}
$encoded_attributes = json_encode(
$this->block_attributes,
JSON_HEX_TAG | // Convert < and > to \u003C and \u003E.
JSON_HEX_AMP // Convert & to \u0026.
);
if ( '[]' === $encoded_attributes ) {
$encoded_attributes = '';
} else {
$encoded_attributes .= ' ';
}
$this->set_modifiable_text(
' ' .
$this->block_name .
' ' .
$encoded_attributes .
( $this->is_self_closing_block() ? '/' : '' )
);
return true;
}
/**
* Advances to the next block attribute when a block is matched.
*
* @return bool Whether we successfully advanced to the next attribute.
*/
public function next_block_attribute() {
if ( '#block-comment' !== $this->get_token_type() ) {
return false;
}
if ( null === $this->block_attribute_paths ) {
$block_attributes = $this->get_block_attributes();
if ( ! is_array( $block_attributes ) ) {
return false;
}
$this->block_attribute_paths = $this->build_block_attribute_paths( $block_attributes );
$this->block_attribute_index = -1;
}
++$this->block_attribute_index;
return isset( $this->block_attribute_paths[ $this->block_attribute_index ] );
}
protected function get_block_attribute_path() {
if ( null === $this->block_attribute_paths || ! isset( $this->block_attribute_paths[ $this->block_attribute_index ] ) ) {
return false;
}
return $this->block_attribute_paths[ $this->block_attribute_index ];
}
/**
* Gets the key of the currently matched block attribute.
*
* @return string|false The attribute key or false if no attribute was matched
*/
public function get_block_attribute_key() {
if ( null === $this->block_attribute_paths || ! isset( $this->block_attribute_paths[ $this->block_attribute_index ] ) ) {
return false;
}
$path = $this->block_attribute_paths[ $this->block_attribute_index ];
return $path[ count( $path ) - 1 ];
}
/**
* Gets the value of the currently matched block attribute.
*
* @return mixed|false The attribute value or false if no attribute was matched
*/
public function get_block_attribute_value() {
if ( null === $this->block_attribute_paths || ! isset( $this->block_attribute_paths[ $this->block_attribute_index ] ) ) {
return false;
}
$path = $this->block_attribute_paths[ $this->block_attribute_index ];
$value = $this->block_attributes;
foreach ( $path as $segment ) {
if ( ! is_array( $value ) || ! array_key_exists( $segment, $value ) ) {
return false;
}
$value = $value[ $segment ];
}
return $value;
}
/**
* Sets the value of the currently matched block attribute.
*
* @param mixed $new_value The new value to set
*
* @return bool Whether the value was successfully set
*/
public function set_block_attribute_value( $new_value ) {
if ( null === $this->block_attribute_paths || ! isset( $this->block_attribute_paths[ $this->block_attribute_index ] ) ) {
return false;
}
$path = $this->block_attribute_paths[ $this->block_attribute_index ];
$ref =& $this->block_attributes;
$depth = count( $path );
for ( $i = 0; $i < $depth - 1; $i++ ) {
$segment = $path[ $i ];
if ( ! is_array( $ref ) || ! array_key_exists( $segment, $ref ) ) {
return false; // Path is invalid.
}
$ref =& $ref[ $segment ];
}
$last_key = $path[ $depth - 1 ];
$ref[ $last_key ] = $new_value;
$this->block_attributes_updated = true;
return true;
}
/**
* Builds a list of attribute paths, using a depth-first, SELF_FIRST order
* that matches the previous iterator behaviour.
*
* @param array<int|string, mixed> $attributes
* @param array<int|string> $base_path
* @return array<int, array<int|string>>
*/
private function build_block_attribute_paths( $attributes, $base_path = array() ) {
$paths = array();
foreach ( $attributes as $key => $value ) {
$current_path = array_merge( $base_path, array( $key ) );
$paths[] = $current_path; // SELF_FIRST: include parent before children.
if ( is_array( $value ) ) {
$paths = array_merge( $paths, $this->build_block_attribute_paths( $value, $current_path ) );
}
}
return $paths;
}
}
@@ -0,0 +1,542 @@
<?php
namespace WordPress\DataLiberation\BlockMarkup;
use VendorPrefix\Rowbot\URL\URL;
use WordPress\DataLiberation\URL\URLInTextProcessor;
use WordPress\DataLiberation\URL\CSSURLProcessor;
use WordPress\DataLiberation\URL\WPURL;
/**
* Reports all the URLs in the imported post and enables rewriting them.
*/
class BlockMarkupUrlProcessor extends BlockMarkupProcessor {
private $raw_url;
/**
* @var URL
*/
private $parsed_url;
private $base_url_string;
private $base_url_object;
private $url_in_text_processor;
private $url_in_text_node_updated;
private $css_url_processor;
private $css_url_processor_updated;
/**
* The list of names of URL-related HTML attributes that may be available on
* the current token. They will be inspected by next_url_attribute().
*
* Possible values:
*
* - null: We haven't inspected any attribute yet.
* - array: The first element is the currently inspected attribute
* and the rest of the list are elements yet to be inspected on
* the upcoming next_url_attribute() call.
* - empty array: We've already inspected all the URL-related attributes.
*
* @var array<string>|null
*/
private $inspecting_html_attributes;
public function __construct( $html, ?string $base_url_string = null ) {
parent::__construct( $html );
$this->base_url_string = $base_url_string;
$this->base_url_object = $base_url_string ? WPURL::parse( $base_url_string ) : null;
}
public function get_updated_html(): string {
if ( $this->url_in_text_node_updated ) {
$this->set_modifiable_text( $this->url_in_text_processor->get_updated_text() );
$this->url_in_text_node_updated = false;
}
if ( $this->css_url_processor_updated ) {
if ( null !== $this->css_url_processor ) {
$updated_css = $this->css_url_processor->get_updated_css();
$this->set_attribute( 'style', $updated_css );
}
$this->css_url_processor_updated = false;
}
return parent::get_updated_html();
}
public function get_raw_url() {
return $this->raw_url;
}
public function get_parsed_url() {
return $this->parsed_url;
}
public function next_token(): bool {
$this->get_updated_html();
$this->raw_url = null;
$this->parsed_url = null;
$this->inspecting_html_attributes = null;
$this->url_in_text_processor = null;
$this->css_url_processor = null;
/*
* Do not reset url_in_text_node_updated or css_url_processor_updated – they're reset
* in get_updated_html() which is called in parent::next_token().
*/
return parent::next_token();
}
public function next_url() {
do {
if ( $this->next_url_in_current_token() ) {
return true;
}
} while ( false !== $this->next_token() );
return false;
}
public function next_url_in_current_token() {
$this->raw_url = null;
switch ( parent::get_token_type() ) {
case '#tag':
return $this->next_url_attribute();
case '#block-comment':
return $this->next_url_block_attribute();
case '#text':
return $this->next_url_in_text_node();
default:
return false;
}
}
private function next_url_in_text_node() {
if ( '#text' !== $this->get_token_type() ) {
return false;
}
if ( null === $this->url_in_text_processor ) {
/*
* Use the base URL for URLs matched in text nodes. This is the only
* way to recognize a substring "WordPress.org" as a URL. We might
* get some false positives this way, e.g. in this string:
*
* > And that's how you build a theme. Now let's take a look at..."
*
* `theme.Now` would be recognized as a URL. It's up to the API consumer
* to filter out such false positives e.g. by checking the domain against
* a list of accepted domains, or the TLD against a list of public suffixes.
*/
$this->url_in_text_processor = new URLInTextProcessor( $this->get_modifiable_text(), $this->base_url_string );
}
while ( $this->url_in_text_processor->next_url() ) {
$this->raw_url = $this->url_in_text_processor->get_raw_url();
$this->parsed_url = $this->url_in_text_processor->get_parsed_url();
return true;
}
return false;
}
/**
* Advances to the next CSS URL in the `style` attribute of the current tag token.
*
* @return bool Whether a CSS URL was found.
*/
private function next_url_in_css() {
if ( '#tag' !== $this->get_token_type() ) {
return false;
}
if ( null === $this->css_url_processor ) {
$css_value = $this->get_attribute( 'style' );
if ( ! is_string( $css_value ) ) {
return false;
}
$this->css_url_processor = new CSSURLProcessor( $css_value );
}
while ( $this->css_url_processor->next_url() ) {
/**
* Skip data URIs. They may be really large and they don't
* have a hostname to migrate.
*/
if ( $this->css_url_processor->is_data_uri() ) {
continue;
}
$this->raw_url = $this->css_url_processor->get_raw_url();
$this->parsed_url = WPURL::parse( $this->raw_url, $this->base_url_string );
if ( false === $this->parsed_url ) {
continue;
}
return true;
}
return false;
}
private function next_url_attribute() {
$tag = $this->get_tag();
// Check if we have a style attribute with CSS URLs to process.
if ( null !== $this->css_url_processor ) {
if ( $this->next_url_in_css() ) {
return true;
}
// Done with CSS URLs in this attribute, apply any pending updates and move on.
$this->get_updated_html();
$this->css_url_processor = null;
}
if ( null === $this->inspecting_html_attributes ) {
if ( array_key_exists( $tag, self::HTML_ATTRIBUTES_TO_ACCEPT_RELATIVE_URLS_FROM ) ) {
/**
* Initialize the list on the first call to next_url_attribute()
* for the current token. The last element is the attribute we'll
* inspect in the while() loop below.
*/
$this->inspecting_html_attributes = self::HTML_ATTRIBUTES_TO_ACCEPT_RELATIVE_URLS_FROM[ $tag ];
// Add style attribute to the list if it exists.
if ( null !== $this->get_attribute( 'style' ) ) {
$this->inspecting_html_attributes[] = 'style';
}
} elseif ( null !== $this->get_attribute( 'style' ) ) {
$this->inspecting_html_attributes = array( 'style' );
} else {
return false;
}
} else {
/**
* Forget the attribute we've inspected on the previous call to
* next_url_attribute().
*/
array_pop( $this->inspecting_html_attributes );
}
while ( count( $this->inspecting_html_attributes ) > 0 ) {
$attr = $this->inspecting_html_attributes[ count( $this->inspecting_html_attributes ) - 1 ];
$url_maybe = $this->get_attribute( $attr );
if ( ! is_string( $url_maybe ) ) {
array_pop( $this->inspecting_html_attributes );
continue;
}
// Rewrite any CSS `url()` declarations in the `style` attribute.
if ( 'style' === $attr ) {
$this->css_url_processor = new CSSURLProcessor( $url_maybe );
if ( $this->next_url_in_css() ) {
return true;
}
// No CSS URLs found, move to next attribute.
$this->css_url_processor = null;
array_pop( $this->inspecting_html_attributes );
continue;
}
/*
* Use base URL to resolve known URI attributes as we are certain we're
* dealing with URI values.
* With a base URL, the string "plugins.php" in <a href="plugins.php"> will
* be correctly recognized as a URL.
* Without a base URL, this Processor would incorrectly skip it.
*/
$parsed_url = WPURL::parse( $url_maybe, $this->base_url_string );
if ( false === $parsed_url ) {
array_pop( $this->inspecting_html_attributes );
continue;
}
$this->raw_url = $url_maybe;
$this->parsed_url = $parsed_url;
return true;
}
return false;
}
private function next_url_block_attribute() {
while ( $this->next_block_attribute() ) {
$url_maybe = $this->get_block_attribute_value();
if ( ! is_string( $url_maybe ) ||
count( $this->get_block_attribute_path() ) > 1
) {
// @TODO: support arrays, objects, and other non-string data structures.
continue;
}
/**
* Decide whether the current block attribute holds a URL.
*
* Known URL attributes can be assumed to hold a URL and be
* parsed with the base URL. For example, a "/about-us" value
* in a wp:navigation-link block's `url` attribute is a
* relative URL to the `/about-us` page.
*
* Other attributes may or may not contain URLs, but we cannot assume
* they do. A value `/about-us` could be a relative URL or a class name.
* In those cases, we'll let go of relative URLs and only detect
* absolute URLs to avoid treating every string as a URL. This requires
* parsing without a base URL.
*/
$is_relative_url_block_attribute = (
isset( self::BLOCK_ATTRIBUTES_TO_ACCEPT_RELATIVE_URLS_FROM[ $this->get_block_name() ] ) &&
in_array( $this->get_block_attribute_key(), self::BLOCK_ATTRIBUTES_TO_ACCEPT_RELATIVE_URLS_FROM[ $this->get_block_name() ], true )
);
/**
* Filters whether a block attribute is known to contain a relative URL.
*
* This filter allows extending the list of block attributes that are
* recognized as containing URLs. When a block attribute is marked as
* a known URL attribute, it will be parsed with the base URL, allowing
* relative URLs to be properly resolved.
*
* @since 6.8.0
*
* @param bool $is_relative_url_block_attribute Whether the block attribute is known to contain a relative URL.
* @param array $context {
* Context information about the block attribute.
*
* @type string $block_name The name of the block (e.g., 'wp:image', 'wp:button').
* @type string $attribute_name The name of the attribute (e.g., 'url', 'href').
* }
*/
$is_relative_url_block_attribute = apply_filters(
'url_processor_is_relative_url_block_attribute',
$is_relative_url_block_attribute,
array(
'block_name' => $this->get_block_name(),
'attribute_name' => $this->get_block_attribute_key(),
)
);
$parsed_url = false;
if ( $is_relative_url_block_attribute ) {
// Known relative URL attribute – let's parse with the base URL.
$parsed_url = WPURL::parse( $url_maybe, $this->base_url_string );
} else {
// Other attributes – let's parse without a base URL (and only detect absolute URLs).
$parsed_url = WPURL::parse( $url_maybe );
}
if ( false === $parsed_url ) {
continue;
}
$this->raw_url = $url_maybe;
$this->parsed_url = $parsed_url;
return true;
}
return false;
}
/**
* Replaces the currently matched URL with a new one.
*
* @param string $raw_url The raw URL.
* @param URL $parsed_url The parsed version of the raw URL. It is required
* as $raw_url might be a relative URL pointing to a different
* host than this processor's base URL.
*
* @return bool True if the URL was set, false otherwise.
*/
public function set_url( $raw_url, $parsed_url ) {
if ( null === $this->raw_url ) {
return false;
}
$this->raw_url = $raw_url;
$this->parsed_url = $parsed_url;
switch ( parent::get_token_type() ) {
case '#tag':
// Check if we're processing a CSS URL.
if ( null !== $this->css_url_processor ) {
$this->css_url_processor_updated = true;
return $this->css_url_processor->set_raw_url( $raw_url );
}
$attr = $this->get_inspected_attribute_name();
if ( false === $attr ) {
return false;
}
$this->set_attribute( $attr, $raw_url );
return true;
case '#block-comment':
return $this->set_block_attribute_value( $raw_url );
case '#text':
if ( null === $this->url_in_text_processor ) {
return false;
}
$this->url_in_text_node_updated = true;
return $this->url_in_text_processor->set_raw_url( $raw_url );
}
}
/**
* Rewrites the components of the currently matched URL from ones
* provided in $from_url to ones specified in $to_url.
*
* It preserves the relative nature of the matched URL.
*
* @TODO: Should this method live in this class? It's specific to the import process
* and the URL rewriting logic and has knowledge about the quirks of detecting
* relative URLs in text nodes. On the other hand, the detection is performed
* by this WPURL_In_Text_Processor class so maybe the two do go hand in hand?
*/
public function replace_base_url( URL $to_url, ?URL $base_url = null ) {
$base_url = $base_url ?? $this->base_url_object;
if ( ! $base_url ) {
return false;
}
$result = WPURL::replace_base_url(
$this->get_parsed_url(),
array(
'old_base_url' => $base_url,
'new_base_url' => $to_url,
'raw_url' => $this->get_raw_url(),
'is_relative' => (
/**
* In text nodes, the only detected URLs are absolute. The tricky part
* is they may start without a protocol, e.g. `wordpress.org`. Therefore,
* we need to tell WPURL::replace_base_url what's our intention regarding
* the URL's relativity. It cannot just infer it from the URL itself.
*/
'#text' !== $this->get_token_type() &&
! WPURL::can_parse( $this->get_raw_url() )
),
)
);
if ( false === $result ) {
return false;
}
$this->set_url( $result . '', $result->new_url );
return true;
}
/**
* Returns true if the currently matched URL is absolute.
*
* @return bool Whether the currently matched URL is absolute.
*/
public function is_url_absolute() {
return WPURL::can_parse( $this->get_raw_url() );
}
public function get_inspected_attribute_name() {
if ( '#tag' !== $this->get_token_type() ) {
return false;
}
if ( null === $this->inspecting_html_attributes ) {
return false;
}
if ( empty( $this->inspecting_html_attributes ) ) {
return false;
}
return $this->inspecting_html_attributes[ count( $this->inspecting_html_attributes ) - 1 ];
}
/**
* A list of block attributes that are known to contain URLs.
*
* It covers WordPress core blocks as of WordPress version 6.9. It can be
* extended by plugins and themes via the "url_processor_is_relative_url_block_attribute"
* filter.
*
* @var array
*/
public const BLOCK_ATTRIBUTES_TO_ACCEPT_RELATIVE_URLS_FROM = array(
'wp:button' => array( 'url', 'linkTarget' ),
'wp:cover' => array( 'url' ),
'wp:embed' => array( 'url' ),
'wp:gallery' => array( 'url', 'fullUrl' ),
'wp:image' => array( 'url', 'src', 'href' ),
'wp:media-text' => array( 'mediaUrl', 'href' ),
'wp:navigation-link' => array( 'url' ),
'wp:navigation-submenu' => array( 'url' ),
'wp:rss' => array( 'feedURL' ),
);
/**
* A list of HTML attributes meant to contain URLs, as defined in the HTML specification.
* It includes some deprecated attributes like `lowsrc` and `highsrc` for the `IMG` element.
*
* See https://html.spec.whatwg.org/multipage/indices.html#attributes-1.
* See https://stackoverflow.com/questions/2725156/complete-list-of-html-tag-attributes-which-have-a-url-value.
*/
public const HTML_ATTRIBUTES_TO_ACCEPT_RELATIVE_URLS_FROM = array(
'A' => array( 'href' ),
'APPLET' => array( 'codebase', 'archive' ),
'AREA' => array( 'href' ),
'AUDIO' => array( 'src' ),
'BASE' => array( 'href' ),
'BLOCKQUOTE' => array( 'cite' ),
'BODY' => array( 'background' ),
'BUTTON' => array( 'formaction' ),
'COMMAND' => array( 'icon' ),
'DEL' => array( 'cite' ),
'EMBED' => array( 'src' ),
'FORM' => array( 'action' ),
'FRAME' => array( 'longdesc', 'src' ),
'HEAD' => array( 'profile' ),
'HTML' => array( 'manifest' ),
'IFRAME' => array( 'longdesc', 'src' ),
// SVG <image> element.
'IMAGE' => array( 'href' ),
'IMG' => array( 'longdesc', 'src', 'usemap', 'lowsrc', 'highsrc' ),
'INPUT' => array( 'src', 'usemap', 'formaction' ),
'INS' => array( 'cite' ),
'LINK' => array( 'href' ),
'OBJECT' => array( 'classid', 'codebase', 'data', 'usemap' ),
'Q' => array( 'cite' ),
'SCRIPT' => array( 'src' ),
'SOURCE' => array( 'src' ),
'TRACK' => array( 'src' ),
'VIDEO' => array( 'poster', 'src' ),
);
/**
* @TODO: Either explicitly support these attributes, or explicitly drop support for
* handling their subsyntax. A generic URL matcher might be good enough.
*/
public const HTML_ATTRIBUTES_WITH_SUBSYNTAX_TO_ACCEPT_RELATIVE_URLS_FROM = array(
'*' => array( 'style' ), // background(), background-image().
'APPLET' => array( 'archive' ),
'IMG' => array( 'srcset' ),
'META' => array( 'content' ),
'SOURCE' => array( 'srcset' ),
'OBJECT' => array( 'archive' ),
);
/**
* Also <style> and <script> tag content can contain URLs.
* <style> has specific syntax rules we can use for matching, but perhaps a generic matcher would be good enough?
*
* <style>
* #domID { background:url(https://mysite.com/wp-content/uploads/image.png) }
* </style>
*
* @TODO: Either explicitly support these tags, or explicitly drop support for
* handling their subsyntax. A generic URL matcher might be good enough.
*/
public const HTML_TAGS_WITH_SUBSYNTAX_TO_ACCEPT_RELATIVE_URLS_FROM = array(
'STYLE',
'SCRIPT',
);
}
@@ -0,0 +1,15 @@
<?php
namespace WordPress\DataLiberation\BlockMarkup;
class BlockObject {
public $block_name;
public $attrs;
public $inner_blocks;
public function __construct( $block_name, $attrs = array(), $inner_blocks = array() ) {
$this->block_name = $block_name;
$this->attrs = $attrs;
$this->inner_blocks = $inner_blocks;
}
}