Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions inc/css/class-css-utility.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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 . '{' : '';

Expand Down
12 changes: 7 additions & 5 deletions inc/plugins/class-abilities.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

namespace ThemeIsle\GutenbergBlocks\Plugins;

use ThemeIsle\GutenbergBlocks\CSS\CSS_Utility;
use ThemeIsle\GutenbergBlocks\Pro;
use WP_Error;
use WP_Query;
Expand Down Expand Up @@ -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 ),
Expand Down
5 changes: 3 additions & 2 deletions src/blocks/components/html-anchor-control/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
/**
* Internal dependencies
*/
import { sanitizeBlockId } from '../../helpers/block-utility';
import './editor.scss';

const HTMLAnchorControl = ({
Expand All @@ -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 );
Expand All @@ -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() }
/>

Expand Down
49 changes: 46 additions & 3 deletions src/blocks/helpers/block-utility.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
}
Expand Down Expand Up @@ -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 ) );

Expand Down
138 changes: 137 additions & 1 deletion src/blocks/test/unit/block-utility-lightweight.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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;
Expand Down
Loading