Database: Hardening to bring `wpdb::prepare()` inline with documentation.

`wpdb::prepare()` supports %s, %d, and %F as placeholders in the query string. Any other non-escaped % will be escaped.

Merges [41496] to 4.7 branch.



git-svn-id: https://develop.svn.wordpress.org/branches/4.7@41498 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Aaron D. Campbell 2017-09-19 18:11:46 +00:00
parent 48d3ca8825
commit c134dea3b6
2 changed files with 14 additions and 1 deletions

View File

@ -1315,6 +1315,7 @@ class wpdb {
$query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
$query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
$query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
$query = preg_replace( '/%(?:%|$|([^dsF]))/', '%%\\1', $query ); // escape any unescaped percents
array_walk( $args, array( $this, 'escape_by_ref' ) );
return @vsprintf( $query, $args );
}
@ -2897,7 +2898,8 @@ class wpdb {
}
if ( is_array( $value['length'] ) ) {
$queries[ $col ] = $this->prepare( "CONVERT( LEFT( CONVERT( %s USING $charset ), %.0f ) USING $connection_charset )", $value['value'], $value['length']['length'] );
$length = sprintf( '%.0f', $value['length']['length'] );
$queries[ $col ] = $this->prepare( "CONVERT( LEFT( CONVERT( %s USING $charset ), $length ) USING $connection_charset )", $value['value'] );
} else if ( 'binary' !== $charset ) {
// If we don't have a length, there's no need to convert binary - it will always return the same result.
$queries[ $col ] = $this->prepare( "CONVERT( CONVERT( %s USING $charset ) USING $connection_charset )", $value['value'] );

View File

@ -273,6 +273,7 @@ class Tests_DB extends WP_UnitTestCase {
$this->assertEquals( "UPDATE test_table SET string_column = '%f is a float, %d is an int 3, %s is a string', field = '4'", $sql );
}
/**
* Test that SQL modes are set correctly
* @ticket 26847
@ -1115,4 +1116,14 @@ class Tests_DB extends WP_UnitTestCase {
$this->assertSame( 'utf8', $result['charset'] );
$this->assertSame( 'utf8_general_ci', $result['collate'] );
}
/**
*
*/
function test_prepare_with_unescaped_percents() {
global $wpdb;
$sql = $wpdb->prepare( '%d %1$d %%% %', 1 );
$this->assertEquals( '1 %1$d %% %', $sql );
}
}