Make WordPress Core


Ignore:
Timestamp:
10/31/2017 12:45:48 PM (9 years ago)
Author:
pento
Message:

Database: Restore numbered placeholders in wpdb::prepare().

[41496] removed support for numbered placeholders in queries send through wpdb::prepare(), which, despite being undocumented, were quite commonly used.

This change restores support for numbered placeholders (as well as a subset of placeholder formatting), while also adding extra checks to ensure the correct number of arguments are being passed to wpdb::prepare(), given the number of placeholders.

Merges [41662], [42056] to the 4.4 branch.
See #41925.

Location:
branches/4.4
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/4.4

  • branches/4.4/src/wp-includes/wp-db.php

    r41501 r42061  
    11251125                if ( $this->dbh ) {
    11261126                        if ( $this->use_mysqli ) {
    1127                                 return mysqli_real_escape_string( $this->dbh, $string );
     1127                                $escaped = mysqli_real_escape_string( $this->dbh, $string );
    11281128                        } else {
    1129                                 return mysql_real_escape_string( $string, $this->dbh );
    1130                         }
    1131                 }
    1132 
    1133                 $class = get_class( $this );
    1134                 if ( function_exists( '__' ) ) {
    1135                         /* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */
    1136                         _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), E_USER_NOTICE );
     1129                                $escaped = mysql_real_escape_string( $string, $this->dbh );
     1130                        }
    11371131                } else {
    1138                         _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), E_USER_NOTICE );
    1139                 }
    1140                 return addslashes( $string );
     1132                        $class = get_class( $this );
     1133                        if ( function_exists( '__' ) ) {
     1134                                /* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */
     1135                                _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
     1136                        } else {
     1137                                _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), '3.6.0' );
     1138                        }
     1139                        $escaped = addslashes( $string );
     1140                }
     1141
     1142                return $this->add_placeholder_escape( $escaped );
    11411143        }
    11421144
     
    12131215         * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
    12141216         *
    1215          * The following directives can be used in the query format string:
     1217         * The following placeholders can be used in the query string:
    12161218         *   %d (integer)
    12171219         *   %f (float)
    12181220         *   %s (string)
    1219          *   %% (literal percentage sign - no argument needed)
    1220          *
    1221          * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
    1222          * Literals (%) as parts of the query must be properly written as %%.
    1223          *
    1224          * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
    1225          * Does not support sign, padding, alignment, width or precision specifiers.
    1226          * Does not support argument numbering/swapping.
    1227          *
    1228          * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
    1229          *
    1230          * Both %d and %s should be left unquoted in the query string.
    1231          *
    1232          *     wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
    1233          *     wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
    1234          *
    1235          * @link http://php.net/sprintf Description of syntax.
     1221         *
     1222         * All placeholders MUST be left unquoted in the query string. A corresponding argument MUST be passed for each placeholder.
     1223         *
     1224         * For compatibility with old behavior, numbered or formatted string placeholders (eg, %1$s, %5s) will not have quotes
     1225         * added by this function, so should be passed with appropriate quotes around them for your usage.
     1226         *
     1227         * Literal percentage signs (%) in the query string must be written as %%. Percentage wildcards (for example,
     1228         * to use in LIKE syntax) must be passed via a substitution argument containing the complete LIKE string, these
     1229         * cannot be inserted directly in the query string. Also see {@see esc_like()}.
     1230         *
     1231         * Arguments may be passed as individual arguments to the method, or as a single array containing all arguments. A combination
     1232         * of the two is not supported.
     1233         *
     1234         * Examples:
     1235         *     $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", array( 'foo', 1337, '%bar' ) );
     1236         *     $wpdb->prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
     1237         *
     1238         * @link https://secure.php.net/sprintf Description of syntax.
    12361239         * @since 2.3.0
    12371240         *
    12381241         * @param string      $query    Query statement with sprintf()-like placeholders
    1239          * @param array|mixed $args     The array of variables to substitute into the query's placeholders if being called like
    1240          *                              {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
    1241          *                              being called like {@link http://php.net/sprintf sprintf()}.
    1242          * @param mixed       $args,... further variables to substitute into the query's placeholders if being called like
    1243          *                              {@link http://php.net/sprintf sprintf()}.
     1242         * @param array|mixed $args     The array of variables to substitute into the query's placeholders if being called with an array of arguments,
     1243         *                              or the first variable to substitute into the query's placeholders if being called with individual arguments.
     1244         * @param mixed       $args,... further variables to substitute into the query's placeholders if being called wih individual arguments.
    12441245         * @return string|void Sanitized query string, if there is a query to prepare.
    12451246         */
    12461247        public function prepare( $query, $args ) {
    1247                 if ( is_null( $query ) )
     1248                if ( is_null( $query ) ) {
    12481249                        return;
     1250                }
    12491251
    12501252                // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
    12511253                if ( strpos( $query, '%' ) === false ) {
    1252                         _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );
     1254                        wp_load_translations_early();
     1255                        _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9.0' );
    12531256                }
    12541257
     
    12561259                array_shift( $args );
    12571260
    1258                 // If args were passed as an array (as in vsprintf), move them up
     1261                // If args were passed as an array (as in vsprintf), move them up.
     1262                $passed_as_array = false;
    12591263                if ( is_array( $args[0] ) && count( $args ) == 1 ) {
     1264                        $passed_as_array = true;
    12601265                        $args = $args[0];
    12611266                }
     
    12631268                foreach ( $args as $arg ) {
    12641269                        if ( ! is_scalar( $arg ) && ! is_null( $arg ) ) {
    1265                                 _doing_it_wrong( 'wpdb::prepare', sprintf( 'Unsupported value type (%s).', gettype( $arg ) ), '4.4.11' );
    1266                         }
    1267                 }
    1268 
    1269                 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
    1270                 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
    1271                 $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
    1272                 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
    1273                 $query = preg_replace( '/%(?:%|$|([^dsF]))/', '%%\\1', $query ); // escape any unescaped percents
     1270                                wp_load_translations_early();
     1271                                _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'Unsupported value type (%s).' ), gettype( $arg ) ), '4.8.2' );
     1272                        }
     1273                }
     1274
     1275                /*
     1276                 * Specify the formatting allowed in a placeholder. The following are allowed:
     1277                 *
     1278                 * - Sign specifier. eg, $+d
     1279                 * - Numbered placeholders. eg, %1$s
     1280                 * - Padding specifier, including custom padding characters. eg, %05s, %'#5s
     1281                 * - Alignment specifier. eg, %05-s
     1282                 * - Precision specifier. eg, %.2f
     1283                 */
     1284                $allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0|\'.)?[-+0-9]*(?:\.[0-9]+)?';
     1285
     1286                /*
     1287                 * If a %s placeholder already has quotes around it, removing the existing quotes and re-inserting them
     1288                 * ensures the quotes are consistent.
     1289                 *
     1290                 * For backwards compatibility, this is only applied to %s, and not to placeholders like %1$s, which are frequently
     1291                 * used in the middle of longer strings, or as table name placeholders.
     1292                 */
     1293                $query = str_replace( "'%s'", '%s', $query ); // Strip any existing single quotes.
     1294                $query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes.
     1295                $query = preg_replace( '/(?<!%)%s/', "'%s'", $query ); // Quote the strings, avoiding escaped strings like %%s.
     1296
     1297                $query = preg_replace( "/(?<!%)(%($allowed_format)?f)/" , '%\\2F', $query ); // Force floats to be locale unaware.
     1298
     1299                $query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdF]))/", '%%\\1', $query ); // Escape any unescaped percents.
     1300
     1301                // Count the number of valid placeholders in the query.
     1302                $placeholders = preg_match_all( "/(^|[^%]|(%%)+)%($allowed_format)?[sdF]/", $query, $matches );
     1303
     1304                if ( count( $args ) !== $placeholders ) {
     1305                        if ( 1 === $placeholders && $passed_as_array ) {
     1306                                // If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
     1307                                wp_load_translations_early();
     1308                                _doing_it_wrong( 'wpdb::prepare', __( 'The query only expected one placeholder, but an array of multiple placeholders was sent.' ), '4.9.0' );
     1309
     1310                                return;
     1311                        } else {
     1312                                /*
     1313                                 * If we don't have the right number of placeholders, but they were passed as individual arguments,
     1314                                 * or we were expecting multiple arguments in an array, throw a warning.
     1315                                 */
     1316                                wp_load_translations_early();
     1317                                _doing_it_wrong( 'wpdb::prepare',
     1318                                        /* translators: 1: number of placeholders, 2: number of arguments passed */
     1319                                        sprintf( __( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d).' ),
     1320                                                $placeholders,
     1321                                                count( $args ) ),
     1322                                        '4.8.3'
     1323                                );
     1324                        }
     1325                }
     1326
    12741327                array_walk( $args, array( $this, 'escape_by_ref' ) );
    1275                 return @vsprintf( $query, $args );
     1328                $query = @vsprintf( $query, $args );
     1329
     1330                return $this->add_placeholder_escape( $query );
    12761331        }
    12771332
     
    18261881                        $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
    18271882                }
     1883        }
     1884
     1885        /**
     1886         * Generates and returns a placeholder escape string for use in queries returned by ::prepare().
     1887         *
     1888         * @since 4.8.3
     1889         *
     1890         * @return string String to escape placeholders.
     1891         */
     1892        public function placeholder_escape() {
     1893                static $placeholder;
     1894
     1895                if ( ! $placeholder ) {
     1896                        // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
     1897                        $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
     1898                        // Old WP installs may not have AUTH_SALT defined.
     1899                        $salt = defined( 'AUTH_SALT' ) ? AUTH_SALT : rand();
     1900
     1901                        $placeholder = '{' . hash_hmac( $algo, uniqid( $salt, true ), $salt ) . '}';
     1902                }
     1903
     1904                /*
     1905                 * Add the filter to remove the placeholder escaper. Uses priority 0, so that anything
     1906                 * else attached to this filter will recieve the query with the placeholder string removed.
     1907                 */
     1908                if ( ! has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) {
     1909                        add_filter( 'query', array( $this, 'remove_placeholder_escape' ), 0 );
     1910                }
     1911
     1912                return $placeholder;
     1913        }
     1914
     1915        /**
     1916         * Adds a placeholder escape string, to escape anything that resembles a printf() placeholder.
     1917         *
     1918         * @since 4.8.3
     1919         *
     1920         * @param string $query The query to escape.
     1921         * @return string The query with the placeholder escape string inserted where necessary.
     1922         */
     1923        public function add_placeholder_escape( $query ) {
     1924                /*
     1925                 * To prevent returning anything that even vaguely resembles a placeholder,
     1926                 * we clobber every % we can find.
     1927                 */
     1928                return str_replace( '%', $this->placeholder_escape(), $query );
     1929        }
     1930
     1931        /**
     1932         * Removes the placeholder escape strings from a query.
     1933         *
     1934         * @since 4.8.3
     1935         *
     1936         * @param string $query The query from which the placeholder will be removed.
     1937         * @return string The query with the placeholder removed.
     1938         */
     1939        public function remove_placeholder_escape( $query ) {
     1940                return str_replace( $this->placeholder_escape(), '%', $query );
    18281941        }
    18291942
Note: See TracChangeset for help on using the changeset viewer.