Make WordPress Core


Ignore:
Timestamp:
10/31/2017 12:48:20 PM (8 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.3 branch.
See #41925.

Location:
branches/4.3
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/4.3

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

    r41502 r42062  
    10901090        if ( $this->dbh ) {
    10911091            if ( $this->use_mysqli ) {
    1092                 return mysqli_real_escape_string( $this->dbh, $string );
     1092                $escaped = mysqli_real_escape_string( $this->dbh, $string );
    10931093            } else {
    1094                 return mysql_real_escape_string( $string, $this->dbh );
    1095             }
    1096         }
    1097 
    1098         $class = get_class( $this );
    1099         if ( function_exists( '__' ) ) {
    1100             _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), E_USER_NOTICE );
     1094                $escaped = mysql_real_escape_string( $string, $this->dbh );
     1095            }
    11011096        } else {
    1102             _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), E_USER_NOTICE );
    1103         }
    1104         return addslashes( $string );
     1097            $class = get_class( $this );
     1098            if ( function_exists( '__' ) ) {
     1099                /* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */
     1100                _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
     1101            } else {
     1102                _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), '3.6.0' );
     1103            }
     1104            $escaped = addslashes( $string );
     1105        }
     1106
     1107        return $this->add_placeholder_escape( $escaped );
    11051108    }
    11061109
     
    11771180     * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
    11781181     *
    1179      * The following directives can be used in the query format string:
     1182     * The following placeholders can be used in the query string:
    11801183     *   %d (integer)
    11811184     *   %f (float)
    11821185     *   %s (string)
    1183      *   %% (literal percentage sign - no argument needed)
    1184      *
    1185      * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
    1186      * Literals (%) as parts of the query must be properly written as %%.
    1187      *
    1188      * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
    1189      * Does not support sign, padding, alignment, width or precision specifiers.
    1190      * Does not support argument numbering/swapping.
    1191      *
    1192      * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
    1193      *
    1194      * Both %d and %s should be left unquoted in the query string.
    1195      *
    1196      *     wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
    1197      *     wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
    1198      *
    1199      * @link http://php.net/sprintf Description of syntax.
     1186     *
     1187     * All placeholders MUST be left unquoted in the query string. A corresponding argument MUST be passed for each placeholder.
     1188     *
     1189     * For compatibility with old behavior, numbered or formatted string placeholders (eg, %1$s, %5s) will not have quotes
     1190     * added by this function, so should be passed with appropriate quotes around them for your usage.
     1191     *
     1192     * Literal percentage signs (%) in the query string must be written as %%. Percentage wildcards (for example,
     1193     * to use in LIKE syntax) must be passed via a substitution argument containing the complete LIKE string, these
     1194     * cannot be inserted directly in the query string. Also see {@see esc_like()}.
     1195     *
     1196     * Arguments may be passed as individual arguments to the method, or as a single array containing all arguments. A combination
     1197     * of the two is not supported.
     1198     *
     1199     * Examples:
     1200     *     $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", array( 'foo', 1337, '%bar' ) );
     1201     *     $wpdb->prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
     1202     *
     1203     * @link https://secure.php.net/sprintf Description of syntax.
    12001204     * @since 2.3.0
    12011205     *
    12021206     * @param string      $query    Query statement with sprintf()-like placeholders
    1203      * @param array|mixed $args     The array of variables to substitute into the query's placeholders if being called like
    1204      *                              {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
    1205      *                              being called like {@link http://php.net/sprintf sprintf()}.
    1206      * @param mixed       $args,... further variables to substitute into the query's placeholders if being called like
    1207      *                              {@link http://php.net/sprintf sprintf()}.
     1207     * @param array|mixed $args     The array of variables to substitute into the query's placeholders if being called with an array of arguments,
     1208     *                              or the first variable to substitute into the query's placeholders if being called with individual arguments.
     1209     * @param mixed       $args,... further variables to substitute into the query's placeholders if being called wih individual arguments.
    12081210     * @return string|void Sanitized query string, if there is a query to prepare.
    12091211     */
    12101212    public function prepare( $query, $args ) {
    1211         if ( is_null( $query ) )
     1213        if ( is_null( $query ) ) {
    12121214            return;
     1215        }
    12131216
    12141217        // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
    12151218        if ( strpos( $query, '%' ) === false ) {
    1216             _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );
     1219            wp_load_translations_early();
     1220            _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9.0' );
    12171221        }
    12181222
     
    12201224        array_shift( $args );
    12211225
    1222         // If args were passed as an array (as in vsprintf), move them up
     1226        // If args were passed as an array (as in vsprintf), move them up.
     1227        $passed_as_array = false;
    12231228        if ( is_array( $args[0] ) && count( $args ) == 1 ) {
     1229            $passed_as_array = true;
    12241230            $args = $args[0];
    12251231        }
     
    12271233        foreach ( $args as $arg ) {
    12281234            if ( ! is_scalar( $arg ) && ! is_null( $arg ) ) {
    1229                 _doing_it_wrong( 'wpdb::prepare', sprintf( 'Unsupported value type (%s).', gettype( $arg ) ), '4.3.12' );
    1230             }
    1231         }
    1232 
    1233         $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
    1234         $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
    1235         $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
    1236         $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
    1237         $query = preg_replace( '/%(?:%|$|([^dsF]))/', '%%\\1', $query ); // escape any unescaped percents
     1235                wp_load_translations_early();
     1236                _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'Unsupported value type (%s).' ), gettype( $arg ) ), '4.8.2' );
     1237            }
     1238        }
     1239
     1240        /*
     1241         * Specify the formatting allowed in a placeholder. The following are allowed:
     1242         *
     1243         * - Sign specifier. eg, $+d
     1244         * - Numbered placeholders. eg, %1$s
     1245         * - Padding specifier, including custom padding characters. eg, %05s, %'#5s
     1246         * - Alignment specifier. eg, %05-s
     1247         * - Precision specifier. eg, %.2f
     1248         */
     1249        $allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0|\'.)?[-+0-9]*(?:\.[0-9]+)?';
     1250
     1251        /*
     1252         * If a %s placeholder already has quotes around it, removing the existing quotes and re-inserting them
     1253         * ensures the quotes are consistent.
     1254         *
     1255         * For backwards compatibility, this is only applied to %s, and not to placeholders like %1$s, which are frequently
     1256         * used in the middle of longer strings, or as table name placeholders.
     1257         */
     1258        $query = str_replace( "'%s'", '%s', $query ); // Strip any existing single quotes.
     1259        $query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes.
     1260        $query = preg_replace( '/(?<!%)%s/', "'%s'", $query ); // Quote the strings, avoiding escaped strings like %%s.
     1261
     1262        $query = preg_replace( "/(?<!%)(%($allowed_format)?f)/" , '%\\2F', $query ); // Force floats to be locale unaware.
     1263
     1264        $query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdF]))/", '%%\\1', $query ); // Escape any unescaped percents.
     1265
     1266        // Count the number of valid placeholders in the query.
     1267        $placeholders = preg_match_all( "/(^|[^%]|(%%)+)%($allowed_format)?[sdF]/", $query, $matches );
     1268
     1269        if ( count( $args ) !== $placeholders ) {
     1270            if ( 1 === $placeholders && $passed_as_array ) {
     1271                // If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
     1272                wp_load_translations_early();
     1273                _doing_it_wrong( 'wpdb::prepare', __( 'The query only expected one placeholder, but an array of multiple placeholders was sent.' ), '4.9.0' );
     1274
     1275                return;
     1276            } else {
     1277                /*
     1278                 * If we don't have the right number of placeholders, but they were passed as individual arguments,
     1279                 * or we were expecting multiple arguments in an array, throw a warning.
     1280                 */
     1281                wp_load_translations_early();
     1282                _doing_it_wrong( 'wpdb::prepare',
     1283                    /* translators: 1: number of placeholders, 2: number of arguments passed */
     1284                    sprintf( __( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d).' ),
     1285                        $placeholders,
     1286                        count( $args ) ),
     1287                    '4.8.3'
     1288                );
     1289            }
     1290        }
     1291
    12381292        array_walk( $args, array( $this, 'escape_by_ref' ) );
    1239         return @vsprintf( $query, $args );
     1293        $query = @vsprintf( $query, $args );
     1294
     1295        return $this->add_placeholder_escape( $query );
    12401296    }
    12411297
     
    17651821            $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
    17661822        }
     1823    }
     1824
     1825    /**
     1826     * Generates and returns a placeholder escape string for use in queries returned by ::prepare().
     1827     *
     1828     * @since 4.8.3
     1829     *
     1830     * @return string String to escape placeholders.
     1831     */
     1832    public function placeholder_escape() {
     1833        static $placeholder;
     1834
     1835        if ( ! $placeholder ) {
     1836            // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
     1837            $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
     1838            // Old WP installs may not have AUTH_SALT defined.
     1839            $salt = defined( 'AUTH_SALT' ) ? AUTH_SALT : rand();
     1840
     1841            $placeholder = '{' . hash_hmac( $algo, uniqid( $salt, true ), $salt ) . '}';
     1842        }
     1843
     1844        /*
     1845         * Add the filter to remove the placeholder escaper. Uses priority 0, so that anything
     1846         * else attached to this filter will recieve the query with the placeholder string removed.
     1847         */
     1848        if ( ! has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) {
     1849            add_filter( 'query', array( $this, 'remove_placeholder_escape' ), 0 );
     1850        }
     1851
     1852        return $placeholder;
     1853    }
     1854
     1855    /**
     1856     * Adds a placeholder escape string, to escape anything that resembles a printf() placeholder.
     1857     *
     1858     * @since 4.8.3
     1859     *
     1860     * @param string $query The query to escape.
     1861     * @return string The query with the placeholder escape string inserted where necessary.
     1862     */
     1863    public function add_placeholder_escape( $query ) {
     1864        /*
     1865         * To prevent returning anything that even vaguely resembles a placeholder,
     1866         * we clobber every % we can find.
     1867         */
     1868        return str_replace( '%', $this->placeholder_escape(), $query );
     1869    }
     1870
     1871    /**
     1872     * Removes the placeholder escape strings from a query.
     1873     *
     1874     * @since 4.8.3
     1875     *
     1876     * @param string $query The query from which the placeholder will be removed.
     1877     * @return string The query with the placeholder removed.
     1878     */
     1879    public function remove_placeholder_escape( $query ) {
     1880        return str_replace( $this->placeholder_escape(), '%', $query );
    17671881    }
    17681882
Note: See TracChangeset for help on using the changeset viewer.