Make WordPress Core


Ignore:
Timestamp:
10/31/2017 12:54:43 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.0 branch.
See #41925.

Location:
branches/4.0
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/4.0

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

    r41505 r42065  
    10811081        if ( $this->dbh ) {
    10821082            if ( $this->use_mysqli ) {
    1083                 return mysqli_real_escape_string( $this->dbh, $string );
     1083                $escaped = mysqli_real_escape_string( $this->dbh, $string );
    10841084            } else {
    1085                 return mysql_real_escape_string( $string, $this->dbh );
    1086             }
    1087         }
    1088 
    1089         $class = get_class( $this );
    1090         _doing_it_wrong( $class, "$class must set a database connection for use with escaping.", E_USER_NOTICE );
    1091         return addslashes( $string );
     1085                $escaped = mysql_real_escape_string( $string, $this->dbh );
     1086            }
     1087        } else {
     1088            $class = get_class( $this );
     1089            if ( function_exists( '__' ) ) {
     1090                /* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */
     1091                _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
     1092            } else {
     1093                _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), '3.6.0' );
     1094            }
     1095            $escaped = addslashes( $string );
     1096        }
     1097
     1098        return $this->add_placeholder_escape( $escaped );
    10921099    }
    10931100
     
    11631170     * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
    11641171     *
    1165      * The following directives can be used in the query format string:
     1172     * The following placeholders can be used in the query string:
    11661173     *   %d (integer)
    11671174     *   %f (float)
    11681175     *   %s (string)
    1169      *   %% (literal percentage sign - no argument needed)
    1170      *
    1171      * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
    1172      * Literals (%) as parts of the query must be properly written as %%.
    1173      *
    1174      * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
    1175      * Does not support sign, padding, alignment, width or precision specifiers.
    1176      * Does not support argument numbering/swapping.
    1177      *
    1178      * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
    1179      *
    1180      * Both %d and %s should be left unquoted in the query string.
    1181      *
    1182      * <code>
    1183      * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
    1184      * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
    1185      * </code>
    1186      *
    1187      * @link http://php.net/sprintf Description of syntax.
     1176     *
     1177     * All placeholders MUST be left unquoted in the query string. A corresponding argument MUST be passed for each placeholder.
     1178     *
     1179     * For compatibility with old behavior, numbered or formatted string placeholders (eg, %1$s, %5s) will not have quotes
     1180     * added by this function, so should be passed with appropriate quotes around them for your usage.
     1181     *
     1182     * Literal percentage signs (%) in the query string must be written as %%. Percentage wildcards (for example,
     1183     * to use in LIKE syntax) must be passed via a substitution argument containing the complete LIKE string, these
     1184     * cannot be inserted directly in the query string. Also see {@see esc_like()}.
     1185     *
     1186     * Arguments may be passed as individual arguments to the method, or as a single array containing all arguments. A combination
     1187     * of the two is not supported.
     1188     *
     1189     * Examples:
     1190     *     $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", array( 'foo', 1337, '%bar' ) );
     1191     *     $wpdb->prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
     1192     *
     1193     * @link https://secure.php.net/sprintf Description of syntax.
    11881194     * @since 2.3.0
    11891195     *
    1190      * @param string $query Query statement with sprintf()-like placeholders
    1191      * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
    1192      *  {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
    1193      *  being called like {@link http://php.net/sprintf sprintf()}.
    1194      * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
    1195      *  {@link http://php.net/sprintf sprintf()}.
    1196      * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
    1197      *  if there was something to prepare
     1196     * @param string      $query    Query statement with sprintf()-like placeholders
     1197     * @param array|mixed $args     The array of variables to substitute into the query's placeholders if being called with an array of arguments,
     1198     *                              or the first variable to substitute into the query's placeholders if being called with individual arguments.
     1199     * @param mixed       $args,... further variables to substitute into the query's placeholders if being called wih individual arguments.
     1200     * @return string|void Sanitized query string, if there is a query to prepare.
    11981201     */
    11991202    public function prepare( $query, $args ) {
    1200         if ( is_null( $query ) )
     1203        if ( is_null( $query ) ) {
    12011204            return;
     1205        }
    12021206
    12031207        // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
    12041208        if ( strpos( $query, '%' ) === false ) {
    1205             _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );
     1209            wp_load_translations_early();
     1210            _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9.0' );
    12061211        }
    12071212
     
    12091214        array_shift( $args );
    12101215
    1211         // If args were passed as an array (as in vsprintf), move them up
     1216        // If args were passed as an array (as in vsprintf), move them up.
     1217        $passed_as_array = false;
    12121218        if ( is_array( $args[0] ) && count( $args ) == 1 ) {
     1219            $passed_as_array = true;
    12131220            $args = $args[0];
    12141221        }
     
    12161223        foreach ( $args as $arg ) {
    12171224            if ( ! is_scalar( $arg ) && ! is_null( $arg ) ) {
    1218                 _doing_it_wrong( 'wpdb::prepare', sprintf( 'Unsupported value type (%s).', gettype( $arg ) ), '4.0.19' );
    1219             }
    1220         }
    1221 
    1222         $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
    1223         $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
    1224         $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
    1225         $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
    1226         $query = preg_replace( '/%(?:%|$|([^dsF]))/', '%%\\1', $query ); // escape any unescaped percents
     1225                wp_load_translations_early();
     1226                _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'Unsupported value type (%s).' ), gettype( $arg ) ), '4.8.2' );
     1227            }
     1228        }
     1229
     1230        /*
     1231         * Specify the formatting allowed in a placeholder. The following are allowed:
     1232         *
     1233         * - Sign specifier. eg, $+d
     1234         * - Numbered placeholders. eg, %1$s
     1235         * - Padding specifier, including custom padding characters. eg, %05s, %'#5s
     1236         * - Alignment specifier. eg, %05-s
     1237         * - Precision specifier. eg, %.2f
     1238         */
     1239        $allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0|\'.)?[-+0-9]*(?:\.[0-9]+)?';
     1240
     1241        /*
     1242         * If a %s placeholder already has quotes around it, removing the existing quotes and re-inserting them
     1243         * ensures the quotes are consistent.
     1244         *
     1245         * For backwards compatibility, this is only applied to %s, and not to placeholders like %1$s, which are frequently
     1246         * used in the middle of longer strings, or as table name placeholders.
     1247         */
     1248        $query = str_replace( "'%s'", '%s', $query ); // Strip any existing single quotes.
     1249        $query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes.
     1250        $query = preg_replace( '/(?<!%)%s/', "'%s'", $query ); // Quote the strings, avoiding escaped strings like %%s.
     1251
     1252        $query = preg_replace( "/(?<!%)(%($allowed_format)?f)/" , '%\\2F', $query ); // Force floats to be locale unaware.
     1253
     1254        $query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdF]))/", '%%\\1', $query ); // Escape any unescaped percents.
     1255
     1256        // Count the number of valid placeholders in the query.
     1257        $placeholders = preg_match_all( "/(^|[^%]|(%%)+)%($allowed_format)?[sdF]/", $query, $matches );
     1258
     1259        if ( count( $args ) !== $placeholders ) {
     1260            if ( 1 === $placeholders && $passed_as_array ) {
     1261                // If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
     1262                wp_load_translations_early();
     1263                _doing_it_wrong( 'wpdb::prepare', __( 'The query only expected one placeholder, but an array of multiple placeholders was sent.' ), '4.9.0' );
     1264
     1265                return;
     1266            } else {
     1267                /*
     1268                 * If we don't have the right number of placeholders, but they were passed as individual arguments,
     1269                 * or we were expecting multiple arguments in an array, throw a warning.
     1270                 */
     1271                wp_load_translations_early();
     1272                _doing_it_wrong( 'wpdb::prepare',
     1273                    /* translators: 1: number of placeholders, 2: number of arguments passed */
     1274                    sprintf( __( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d).' ),
     1275                        $placeholders,
     1276                        count( $args ) ),
     1277                    '4.8.3'
     1278                );
     1279            }
     1280        }
     1281
    12271282        array_walk( $args, array( $this, 'escape_by_ref' ) );
    1228         return @vsprintf( $query, $args );
     1283        $query = @vsprintf( $query, $args );
     1284
     1285        return $this->add_placeholder_escape( $query );
    12291286    }
    12301287
     
    17311788            $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
    17321789        }
     1790    }
     1791
     1792    /**
     1793     * Generates and returns a placeholder escape string for use in queries returned by ::prepare().
     1794     *
     1795     * @since 4.8.3
     1796     *
     1797     * @return string String to escape placeholders.
     1798     */
     1799    public function placeholder_escape() {
     1800        static $placeholder;
     1801
     1802        if ( ! $placeholder ) {
     1803            // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
     1804            $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
     1805            // Old WP installs may not have AUTH_SALT defined.
     1806            $salt = defined( 'AUTH_SALT' ) ? AUTH_SALT : rand();
     1807
     1808            $placeholder = '{' . hash_hmac( $algo, uniqid( $salt, true ), $salt ) . '}';
     1809        }
     1810
     1811        /*
     1812         * Add the filter to remove the placeholder escaper. Uses priority 0, so that anything
     1813         * else attached to this filter will recieve the query with the placeholder string removed.
     1814         */
     1815        if ( ! has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) {
     1816            add_filter( 'query', array( $this, 'remove_placeholder_escape' ), 0 );
     1817        }
     1818
     1819        return $placeholder;
     1820    }
     1821
     1822    /**
     1823     * Adds a placeholder escape string, to escape anything that resembles a printf() placeholder.
     1824     *
     1825     * @since 4.8.3
     1826     *
     1827     * @param string $query The query to escape.
     1828     * @return string The query with the placeholder escape string inserted where necessary.
     1829     */
     1830    public function add_placeholder_escape( $query ) {
     1831        /*
     1832         * To prevent returning anything that even vaguely resembles a placeholder,
     1833         * we clobber every % we can find.
     1834         */
     1835        return str_replace( '%', $this->placeholder_escape(), $query );
     1836    }
     1837
     1838    /**
     1839     * Removes the placeholder escape strings from a query.
     1840     *
     1841     * @since 4.8.3
     1842     *
     1843     * @param string $query The query from which the placeholder will be removed.
     1844     * @return string The query with the placeholder removed.
     1845     */
     1846    public function remove_placeholder_escape( $query ) {
     1847        return str_replace( $this->placeholder_escape(), '%', $query );
    17331848    }
    17341849
Note: See TracChangeset for help on using the changeset viewer.