Code Modernization: Return an empty string from wpdb::prepare() if there are not enough arguments to match the placeholders.

This avoids a fatal error on PHP 8 caused by passing mismatched arguments to `vsprintf()`, and maintains the current behaviour.

Follow-up to [48979], [48980].

See #50913, #50639.

git-svn-id: https://develop.svn.wordpress.org/trunk@48981 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Sergey Biryukov 2020-09-16 02:27:42 +00:00
parent 35ceac68f4
commit 2cc4276746

View File

@ -1369,7 +1369,9 @@ class wpdb {
// Count the number of valid placeholders in the query.
$placeholders = preg_match_all( "/(^|[^%]|(%%)+)%($allowed_format)?[sdF]/", $query, $matches );
if ( count( $args ) !== $placeholders ) {
$args_count = count( $args );
if ( $args_count !== $placeholders ) {
if ( 1 === $placeholders && $passed_as_array ) {
// If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
wp_load_translations_early();
@ -1392,10 +1394,22 @@ class wpdb {
/* translators: 1: Number of placeholders, 2: Number of arguments passed. */
__( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d).' ),
$placeholders,
count( $args )
$args_count
),
'4.8.3'
);
/*
* If we don't have enough arguments to match the placeholders,
* return an empty string to avoid a fatal error on PHP 8.
*/
if ( $args_count < $placeholders ) {
$max_numbered_placeholder = ! empty( $matches[3] ) ? max( array_map( 'intval', $matches[3] ) ) : 0;
if ( ! $max_numbered_placeholder || $args_count < $max_numbered_placeholder ) {
return '';
}
}
}
}