From 2cc42767461c4951e6ebaf5e1d5492c3f176a40a Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Wed, 16 Sep 2020 02:27:42 +0000 Subject: [PATCH] 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 --- src/wp-includes/wp-db.php | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/wp-db.php b/src/wp-includes/wp-db.php index 9761de99a8..ebcadb6ef0 100644 --- a/src/wp-includes/wp-db.php +++ b/src/wp-includes/wp-db.php @@ -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 ''; + } + } } }