Formatting: Handle non-scalar types passed to sanitize_key().

`sanitize_key()` expects a string type for the given `key`. Passing any other data type to `strtolower()` can result in `E_WARNING: strtolower() expects parameter 1 to be string, array given`.

A check is added that if the key is not a string, the key is set to an empty string. For performance, the additional string processing is skipped if the key is an empty string.

This change maintains backwards-compatibility for valid string keys while fixing the bug of non-string keys.

Props costdev, dd32. 
Fixes #54160.

git-svn-id: https://develop.svn.wordpress.org/trunk@52292 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Tonya Mork
2021-11-30 20:09:56 +00:00
parent d9dc716cff
commit 1db73227b6
2 changed files with 99 additions and 2 deletions

View File

@@ -2137,8 +2137,15 @@ function sanitize_user( $username, $strict = false ) {
*/
function sanitize_key( $key ) {
$raw_key = $key;
$key = strtolower( $key );
$key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
if ( ! is_string( $key ) ) {
$key = '';
}
if ( '' !== $key ) {
$key = strtolower( $key );
$key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
}
/**
* Filters a sanitized key string.

View File

@@ -0,0 +1,90 @@
<?php
/**
* @group formatting
* @covers ::sanitize_key
*/
class Tests_Formatting_SanitizeKey extends WP_UnitTestCase {
/**
* @ticket 54160
* @dataProvider data_sanitize_key
*
* @param mixed $key The key to sanitize.
* @param mixed $expected The expected value.
*/
public function test_sanitize_key( $key, $expected ) {
$this->assertSame( $expected, sanitize_key( $key ) );
}
public function data_sanitize_key() {
return array(
'an empty string key' => array(
'key' => '',
'expected' => '',
),
'a null key' => array(
'key' => null,
'expected' => '',
),
'an int 0 key' => array(
'key' => 0,
'expected' => '',
),
'a true key' => array(
'key' => true,
'expected' => '',
),
'an array key' => array(
'key' => array( 'Howdy, admin!' ),
'expected' => '',
),
'a lowercase key with commas' => array(
'key' => 'howdy,admin',
'expected' => 'howdyadmin',
),
'a lowercase key with commas' => array(
'key' => 'HOWDY,ADMIN',
'expected' => 'howdyadmin',
),
'a mixed case key with commas' => array(
'key' => 'HoWdY,aDmIn',
'expected' => 'howdyadmin',
),
'a key with dashes' => array(
'key' => 'howdy-admin',
'expected' => 'howdy-admin',
),
'a key with spaces' => array(
'key' => 'howdy admin',
'expected' => 'howdyadmin',
),
'a key with a HTML entity' => array(
'key' => 'howdy&nbsp;admin',
'expected' => 'howdynbspadmin',
),
'a key with a unicode character' => array(
'key' => 'howdy' . chr( 140 ) . 'admin',
'expected' => 'howdyadmin',
),
);
}
/**
* @ticket 54160
*
* @covers WP_Hook::sanitize_key
*/
public function test_filter_sanitize_key() {
$key = 'Howdy, admin!';
add_filter(
'sanitize_key',
static function( $key ) {
return 'Howdy, admin!';
}
);
$this->assertSame( $key, sanitize_key( $key ) );
}
}