Skip to content

Commit

Permalink
HTML API: Prevent bookmarks from being set on virtual tokens
Browse files Browse the repository at this point in the history
Fixes the issue when an HTML_Processor bookmark was set at a virtual token (a node in the resulting document that does not correspond to an HTML token present in the input string), seek behavior was unreliable.

Props jonsurrell, gziolo.
Fixes #62521.




git-svn-id: https://develop.svn.wordpress.org/trunk@59502 602fd350-edb4-49c9-b593-d223f7449a82
  • Loading branch information
gziolo committed Dec 10, 2024
1 parent 6106332 commit 1467750
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/wp-includes/html-api/class-wp-html-processor.php
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,9 @@ public static function create_fragment( $html, $context = '<body>', $encoding =
}

while ( $context_processor->next_tag() ) {
$context_processor->set_bookmark( 'final_node' );
if ( ! $context_processor->is_virtual() ) {
$context_processor->set_bookmark( 'final_node' );
}
}

if (
Expand Down Expand Up @@ -5673,12 +5675,25 @@ public function seek( $bookmark_name ): bool {
* reaching for it, as inappropriate use could lead to broken
* HTML structure or unwanted processing overhead.
*
* Bookmarks cannot be set on tokens that do no appear in the original
* HTML text. For example, the HTML `<table><td>` stops at tags `TABLE`,
* `TBODY`, `TR`, and `TD`. The `TBODY` and `TR` tags do not appear in
* the original HTML and cannot be used as bookmarks.
*
* @since 6.4.0
*
* @param string $bookmark_name Identifies this particular bookmark.
* @return bool Whether the bookmark was successfully created.
*/
public function set_bookmark( $bookmark_name ): bool {
if ( $this->is_virtual() ) {
_doing_it_wrong(
__METHOD__,
__( 'Cannot set bookmarks on tokens that do no appear in the original HTML text.' ),
'6.8.0'
);
return false;
}
return parent::set_bookmark( "_{$bookmark_name}" );
}

Expand Down
13 changes: 13 additions & 0 deletions tests/phpunit/tests/html-api/wpHtmlProcessor-bookmark.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,4 +157,17 @@ public static function data_processor_constructors(): array {
'Fragment parser' => array( array( WP_HTML_Processor::class, 'create_fragment' ) ),
);
}

/**
* @ticket 62521
*
* @expectedIncorrectUsage WP_HTML_Processor::set_bookmark
*/
public function test_bookmarks_not_allowed_on_virtual_nodes() {
$processor = WP_HTML_Processor::create_full_parser( 'text' );
$this->assertTrue( $processor->next_tag( 'BODY' ) );
$this->assertFalse( $processor->set_bookmark( 'mark' ) );
$this->assertTrue( $processor->next_token() );
$this->assertTrue( $processor->set_bookmark( 'mark' ) );
}
}

0 comments on commit 1467750

Please sign in to comment.