diff --git a/inc/css/class-css-utility.php b/inc/css/class-css-utility.php index 8e54d88c1..7f1d07c80 100644 --- a/inc/css/class-css-utility.php +++ b/inc/css/class-css-utility.php @@ -119,6 +119,28 @@ public function set_id( $id ) { $this->block_id = $id; } + /** + * Restrict a Block ID to characters that are safe in id attributes and CSS + * selectors. ASCII punctuation, spaces and control characters are dropped, + * while hyphens, underscores and non-ASCII characters are kept, so ids + * already present in the saved markup are not renamed unnecessarily. The + * same rule applies on the JS side in sanitizeBlockId(). + * + * @access public + * @since 3.2.12 + * @param mixed $id Block ID. + * @return string + */ + public static function sanitize_block_id( $id ) { + if ( ! is_scalar( $id ) ) { + return ''; + } + + $id = preg_replace( '/[^\x{80}-\x{10FFFF}a-zA-Z0-9_-]/u', '', (string) $id ); + + return null === $id ? '' : $id; + } + /** * Filter media queries. * @@ -241,6 +263,15 @@ public function generate() { } } + // The ID is interpolated into selectors below, so it must not carry characters that would invalidate them. + $this->block_id = self::sanitize_block_id( $this->block_id ); + + // A CSS identifier cannot be empty nor start with a digit, a digit or hyphen after a leading hyphen, + // so rather than emit a rule that no browser would apply, drop it. + if ( isset( $attrs['id'] ) && ( '' === $this->block_id || preg_match( '/^(?:[0-9]|-[0-9-])/', $this->block_id ) ) ) { + return ''; + } + foreach ( $this->css_array as $media_query => $css_items ) { $style .= ( 'global' !== $media_query ) ? $media_query . '{' : ''; diff --git a/inc/plugins/class-abilities.php b/inc/plugins/class-abilities.php index 7eeca6e81..8f138f5b9 100644 --- a/inc/plugins/class-abilities.php +++ b/inc/plugins/class-abilities.php @@ -10,6 +10,7 @@ namespace ThemeIsle\GutenbergBlocks\Plugins; +use ThemeIsle\GutenbergBlocks\CSS\CSS_Utility; use ThemeIsle\GutenbergBlocks\Pro; use WP_Error; use WP_Query; @@ -723,15 +724,16 @@ private function get_post_forms( $post, $settings ) { } foreach ( $this->find_blocks( parse_blocks( $post->post_content ), array( self::FORM_BLOCK ) ) as $block ) { - $attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array(); - $form_id = isset( $attrs['optionName'] ) && is_string( $attrs['optionName'] ) ? $attrs['optionName'] : ''; - $block_id = isset( $attrs['id'] ) && is_string( $attrs['id'] ) ? $attrs['id'] : ''; - $saved = isset( $settings[ $form_id ] ) ? $settings[ $form_id ] : array(); + $attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array(); + $form_id = isset( $attrs['optionName'] ) && is_string( $attrs['optionName'] ) ? $attrs['optionName'] : ''; + $block_id = isset( $attrs['id'] ) && is_string( $attrs['id'] ) ? $attrs['id'] : ''; + $selector_id = CSS_Utility::sanitize_block_id( $block_id ); + $saved = isset( $settings[ $form_id ] ) ? $settings[ $form_id ] : array(); $forms[] = array( 'form_id' => $form_id, 'block_id' => $block_id, - 'block_selector' => '' !== $block_id ? '#' . $block_id : '', + 'block_selector' => '' !== $selector_id ? '#' . $selector_id : '', 'post_id' => (int) $post->ID, 'post_title' => get_the_title( $post ), 'fields' => $this->get_form_fields( $block ), diff --git a/src/blocks/components/html-anchor-control/index.js b/src/blocks/components/html-anchor-control/index.js index ff758019a..1287060d6 100644 --- a/src/blocks/components/html-anchor-control/index.js +++ b/src/blocks/components/html-anchor-control/index.js @@ -26,6 +26,7 @@ import { /** * Internal dependencies */ +import { sanitizeBlockId } from '../../helpers/block-utility'; import './editor.scss'; const HTMLAnchorControl = ({ @@ -34,7 +35,7 @@ const HTMLAnchorControl = ({ }) => { const instanceId = useInstanceId( HTMLAnchorControl ); - useEffect( () => setID( value ), [ value ]); + useEffect( () => setID( sanitizeBlockId( value ) ), [ value ]); const [ isEditing, setEditing ] = useState( false ); const [ ID, setID ] = useState( null ); @@ -54,7 +55,7 @@ const HTMLAnchorControl = ({ className="o-html-anchor-control-input" readOnly={ isEditing ? false : 'readonly' } value={ isEditing ? ID : value } - onChange={ e => setID( e.target.value ) } + onChange={ e => setID( sanitizeBlockId( e.target.value ) ) } onClick={ e => e.target.select() } /> diff --git a/src/blocks/helpers/block-utility.js b/src/blocks/helpers/block-utility.js index 48c3a5bb9..31db69b67 100644 --- a/src/blocks/helpers/block-utility.js +++ b/src/blocks/helpers/block-utility.js @@ -119,6 +119,24 @@ const isEmptyId = ( clientId ) => { return attributes?.id === undefined || '' === attributes?.id; }; +/** + * Restrict a block id to characters that are safe in HTML id attributes and + * CSS selectors. ASCII punctuation, spaces and control characters are dropped, + * while hyphens, underscores and non-ASCII letters are kept, so ids that + * already work in the saved markup are never renamed. The same rule applies on + * the PHP side in CSS_Utility::sanitize_block_id(). See https://github.com/Codeinwp/otter-blocks/issues/3085. + * + * @param {unknown} id The raw block id. + * @return {string} The sanitized id. + */ +export const sanitizeBlockId = ( id ) => { + if ( 'string' !== typeof id ) { + return ''; + } + + return id.replace( /[^\u0080-\uFFFFa-zA-Z0-9_-]/g, '' ); +}; + /** * Generate an Id based on the client id of the block. If the new id is also already used, create a new one using the `uuid`. * This might problem of duplicated new ids can be observed in the `Template Library` of the `Section` block when using Neve @@ -133,11 +151,11 @@ const isEmptyId = ( clientId ) => { */ const generateUniqIdInstance = ( idPrefix, clientId, idsList ) => { - const instanceId = `${ idPrefix }${ clientId.slice( 0, 8 ) }`; + const instanceId = sanitizeBlockId( `${ idPrefix }${ clientId.slice( 0, 8 ) }` ); if ( idsList.has( instanceId ) ) { - let newInstanceId = `${ idPrefix }${ uuidv4().slice( 0, 8 ) }`; + let newInstanceId = sanitizeBlockId( `${ idPrefix }${ uuidv4().slice( 0, 8 ) }` ); while ( idsList.has( newInstanceId ) ) { - newInstanceId = `${ idPrefix }${ uuidv4().slice( 0, 8 ) }`; + newInstanceId = sanitizeBlockId( `${ idPrefix }${ uuidv4().slice( 0, 8 ) }` ); } return newInstanceId; } @@ -197,6 +215,31 @@ export const addBlockId = ( args ) => { // Initialize with an empty array the id list for the given block localIDs[name] ??= new Set(); + // Stored ids end up in the markup and in CSS selectors, so keep only safe characters. + if ( attributes.id ) { + const sanitizedId = sanitizeBlockId( attributes.id ); + + if ( sanitizedId !== attributes.id ) { + + // Adopt the sanitized form, unless it is empty or used elsewhere on the page, in which case a fresh id is generated. + const instanceId = sanitizedId && ! localIDs[name].has( sanitizedId ) && ! blockIDs.includes( sanitizedId ) ? + sanitizedId : + generateUniqIdInstance( idPrefix || generatePrefix( name ), clientId, localIDs[name] ); + + localIDs[name].add( instanceId ); + blockIDs.push( instanceId ); + setAttributes({ id: instanceId }); + + return ( savedId ) => { + idGenerationStatus[clientId] = 'free'; + + // Callers with stale closures hand over the pre-sanitizing id, so drop both of them. + localIDs[name].delete( instanceId ); + localIDs[name].delete( savedId || attributes.id ); + }; + } + } + // Check if the ID is already used. EXCLUDE the one that come from reusable blocks. const idIsAlreadyUsed = Boolean( attributes.id && localIDs[name].has( attributes.id ) ); diff --git a/src/blocks/test/unit/block-utility-lightweight.test.ts b/src/blocks/test/unit/block-utility-lightweight.test.ts index d07af9c86..87427a1fd 100644 --- a/src/blocks/test/unit/block-utility-lightweight.test.ts +++ b/src/blocks/test/unit/block-utility-lightweight.test.ts @@ -37,12 +37,14 @@ jest.mock( '@wordpress/data', () => ({ }) ); import { + addBlockId, addGlobalDefaults, buildGetSyncValue, getDefaultValue, getDefaultValueByField, pullOtterPatterns, - pullPatterns + pullPatterns, + sanitizeBlockId } from '../../helpers/block-utility'; describe( 'block utility lightweight helpers', () => { @@ -201,6 +203,140 @@ describe( 'block utility lightweight helpers', () => { }); }); + describe( 'sanitizeBlockId', () => { + it( 'strips punctuation and whitespace but keeps hyphens and underscores', () => { + expect( sanitizeBlockId( 'bad id.with:chars_and spaces' ) ).toBe( 'badidwithchars_andspaces' ); + expect( sanitizeBlockId( 'my-anchor.x' ) ).toBe( 'my-anchorx' ); + }); + + it( 'keeps ids that are already valid selectors byte for byte', () => { + expect( sanitizeBlockId( 'my_section' ) ).toBe( 'my_section' ); + expect( sanitizeBlockId( 'café' ) ).toBe( 'café' ); + expect( sanitizeBlockId( 'sección_1' ) ).toBe( 'sección_1' ); + expect( sanitizeBlockId( 'wp-block-themeisle-blocks-advanced-heading-1a2b3c4d' ) ).toBe( 'wp-block-themeisle-blocks-advanced-heading-1a2b3c4d' ); + }); + + it( 'returns an empty string for non-string values', () => { + expect( sanitizeBlockId( undefined ) ).toBe( '' ); + expect( sanitizeBlockId( 42 ) ).toBe( '' ); + }); + }); + + describe( 'addBlockId stored ids', () => { + it( 'adopts the sanitized form of a stored id', () => { + const setAttributes = jest.fn(); + + addBlockId({ + attributes: { id: 'bad id.x' }, + setAttributes, + clientId: 'aaaa1111', + name: 'themeisle-blocks/advanced-heading-sanitize-adopt', + defaultAttributes: {} + }); + + expect( setAttributes ).toHaveBeenCalledWith({ id: 'badidx' }); + }); + + it( 'leaves a valid stored id as is', () => { + const setAttributes = jest.fn(); + + addBlockId({ + attributes: { id: 'wp-block-themeisle-blocks-advanced-heading-1a2b3c4d' }, + setAttributes, + clientId: 'bbbb2222', + name: 'themeisle-blocks/advanced-heading-sanitize-valid', + defaultAttributes: {} + }); + + expect( setAttributes ).not.toHaveBeenCalled(); + }); + + it( 'regenerates when the sanitized id collides with another block', () => { + addBlockId({ + attributes: { id: 'foo.bar' }, + setAttributes: jest.fn(), + clientId: 'cccc3333', + name: 'themeisle-blocks/advanced-heading-sanitize-collide', + idPrefix: 'wp-block-test-', + defaultAttributes: {} + }); + + const setAttributes = jest.fn(); + addBlockId({ + attributes: { id: 'foo:bar' }, + setAttributes, + clientId: 'dddd4444', + name: 'themeisle-blocks/advanced-heading-sanitize-collide', + idPrefix: 'wp-block-test-', + defaultAttributes: {} + }); + + expect( setAttributes ).toHaveBeenCalledWith({ id: 'wp-block-test-dddd4444' }); + }); + + it( 'regenerates when another block type already uses the sanitized id', () => { + addBlockId({ + attributes: { id: 'foobar' }, + setAttributes: jest.fn(), + clientId: 'gggg7777', + name: 'themeisle-blocks/button-sanitize-collide-page', + defaultAttributes: {} + }); + + const setAttributes = jest.fn(); + addBlockId({ + attributes: { id: 'foo.bar' }, + setAttributes, + clientId: 'hhhh8888', + name: 'themeisle-blocks/advanced-heading-sanitize-collide-page', + idPrefix: 'wp-block-test-', + defaultAttributes: {} + }); + + expect( setAttributes ).toHaveBeenCalledWith({ id: 'wp-block-test-hhhh8888' }); + }); + + it( 'forgets the adopted id when a caller cleans up with its pre-sanitizing id', () => { + // Mirrors blocks like Popup that mount blockInit once and pass the initially + // captured attributes.id to the returned cleanup on unmount. + const unsubscribe = addBlockId({ + attributes: { id: 'bad id.y' }, + setAttributes: jest.fn(), + clientId: 'ffff6666', + name: 'themeisle-blocks/advanced-heading-sanitize-cleanup', + defaultAttributes: {} + }); + + unsubscribe( 'bad id.y' ); + + const setAttributes = jest.fn(); + addBlockId({ + attributes: { id: 'badidy' }, + setAttributes, + clientId: 'ffff6666', + name: 'themeisle-blocks/advanced-heading-sanitize-cleanup', + defaultAttributes: {} + }); + + expect( setAttributes ).not.toHaveBeenCalled(); + }); + + it( 'regenerates when sanitizing empties the stored id', () => { + const setAttributes = jest.fn(); + + addBlockId({ + attributes: { id: '!!!' }, + setAttributes, + clientId: 'eeee5555', + name: 'themeisle-blocks/advanced-heading-sanitize-empty', + idPrefix: 'wp-block-test-', + defaultAttributes: {} + }); + + expect( setAttributes ).toHaveBeenCalledWith({ id: 'wp-block-test-eeee5555' }); + }); + }); + describe( 'pattern helpers', () => { it( 'returns empty list when pattern selector has no data', () => { mockCorePatterns = undefined; diff --git a/tests/test-css-utility-block-id.php b/tests/test-css-utility-block-id.php new file mode 100644 index 000000000..3f13d18c0 --- /dev/null +++ b/tests/test-css-utility-block-id.php @@ -0,0 +1,155 @@ + array( + 'id' => $id, + ), + ); + + $css = new CSS_Utility( $block ); + + $css->add_item( + array( + 'selector' => ' .highlight', + 'properties' => array( + array( + 'property' => 'color', + 'default' => 'red', + ), + ), + ) + ); + + return $css->generate(); + } + + /** + * Punctuation and whitespace must not survive into the selector. + */ + public function test_invalid_characters_are_stripped_from_generated_selectors() { + $style = $this->css_for_stored_id( 'bad id.with:chars_and spaces' ); + + $this->assertSame( '#badidwithchars_andspaces .highlight {color: red;}', $style ); + } + + /** + * Hyphens, underscores and non-ASCII characters are valid in selectors and + * are kept as is, so that ids already present in the saved markup keep matching. + */ + public function test_valid_css_identifier_characters_are_kept() { + $this->assertSame( '#my-anchorx .highlight {color: red;}', $this->css_for_stored_id( 'my-anchor.x' ) ); + $this->assertSame( '#my_section .highlight {color: red;}', $this->css_for_stored_id( 'my_section' ) ); + $this->assertSame( '#sección_1 .highlight {color: red;}', $this->css_for_stored_id( 'sección_1' ) ); + $this->assertSame( '#café .highlight {color: red;}', $this->css_for_stored_id( 'café' ) ); + } + + /** + * Ids produced by the editor stay byte for byte the same. + */ + public function test_valid_generated_id_is_left_untouched() { + $id = 'wp-block-themeisle-blocks-advanced-heading-1a2b3c4d'; + $style = $this->css_for_stored_id( $id ); + + $this->assertStringContainsString( '#' . $id . ' .highlight', $style ); + } + + /** + * A custom id set with set_id() goes through the same filtering. + */ + public function test_custom_id_is_sanitized() { + $block = array( + 'attrs' => array( + 'id' => 'original-id', + ), + ); + + $css = new CSS_Utility( $block ); + $css->set_id( 'custom id:x' ); + + $css->add_item( + array( + 'selector' => ' .highlight', + 'properties' => array( + array( + 'property' => 'color', + 'default' => 'red', + ), + ), + ) + ); + + $this->assertSame( '#customidx .highlight {color: red;}', $css->generate() ); + } + + /** + * The [id] placeholder used by some blocks is filtered too. + */ + public function test_id_placeholder_is_sanitized() { + $block = array( + 'attrs' => array( + 'id' => 'c:1', + ), + ); + + $css = new CSS_Utility( $block ); + + $css->add_item( + array( + 'selector' => '[id] .bar', + 'properties' => array( + array( + 'property' => 'color', + 'default' => 'red', + ), + ), + ) + ); + + $this->assertSame( '#c1 .bar {color: red;}', $css->generate() ); + } + + /** + * Ids that cannot form a valid CSS identifier (empty after filtering, + * starting with a digit, or starting the way a custom property does) + * drop the rules instead of emitting selectors no browser would apply. + */ + public function test_ids_outside_the_css_identifier_syntax_emit_no_rules() { + $this->assertSame( '', $this->css_for_stored_id( '!!!' ) ); + $this->assertSame( '', $this->css_for_stored_id( array( 'nope' ) ) ); + $this->assertSame( '', $this->css_for_stored_id( '42' ) ); + $this->assertSame( '', $this->css_for_stored_id( '--foo--' ) ); + $this->assertSame( '', $this->css_for_stored_id( '-1x' ) ); + } + + /** + * A single leading hyphen before letters is a valid selector and stays. + */ + public function test_leading_hyphen_before_letters_is_kept() { + $this->assertSame( '#-foo .highlight {color: red;}', $this->css_for_stored_id( '-foo' ) ); + } +}