Make WordPress Core


Ignore:
Timestamp:
10/31/2017 12:56:57 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 3.9 branch.
See #41925.

Location:
branches/3.9
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/3.9

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

    r41506 r42066  
    10741074        if ( $this->dbh ) {
    10751075            if ( $this->use_mysqli ) {
    1076                 return mysqli_real_escape_string( $this->dbh, $string );
     1076                $escaped = mysqli_real_escape_string( $this->dbh, $string );
    10771077            } else {
    1078                 return mysql_real_escape_string( $string, $this->dbh );
    1079             }
    1080         }
    1081 
    1082         $class = get_class( $this );
    1083         _doing_it_wrong( $class, "$class must set a database connection for use with escaping.", E_USER_NOTICE );
    1084         return addslashes( $string );
     1078                $escaped = mysql_real_escape_string( $string, $this->dbh );
     1079            }
     1080        } else {
     1081            $class = get_class( $this );
     1082            if ( function_exists( '__' ) ) {
     1083                /* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */
     1084                _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
     1085            } else {
     1086                _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), '3.6.0' );
     1087            }
     1088            $escaped = addslashes( $string );
     1089        }
     1090
     1091        return $this->add_placeholder_escape( $escaped );
    10851092    }
    10861093
     
    11561163     * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
    11571164     *
    1158      * The following directives can be used in the query format string:
     1165     * The following placeholders can be used in the query string:
    11591166     *   %d (integer)
    11601167     *   %f (float)
    11611168     *   %s (string)
    1162      *   %% (literal percentage sign - no argument needed)
    1163      *
    1164      * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
    1165      * Literals (%) as parts of the query must be properly written as %%.
    1166      *
    1167      * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
    1168      * Does not support sign, padding, alignment, width or precision specifiers.
    1169      * Does not support argument numbering/swapping.
    1170      *
    1171      * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
    1172      *
    1173      * Both %d and %s should be left unquoted in the query string.
    1174      *
    1175      * <code>
    1176      * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
    1177      * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
    1178      * </code>
    1179      *
    1180      * @link http://php.net/sprintf Description of syntax.
     1169     *
     1170     * All placeholders MUST be left unquoted in the query string. A corresponding argument MUST be passed for each placeholder.
     1171     *
     1172     * For compatibility with old behavior, numbered or formatted string placeholders (eg, %1$s, %5s) will not have quotes
     1173     * added by this function, so should be passed with appropriate quotes around them for your usage.
     1174     *
     1175     * Literal percentage signs (%) in the query string must be written as %%. Percentage wildcards (for example,
     1176     * to use in LIKE syntax) must be passed via a substitution argument containing the complete LIKE string, these
     1177     * cannot be inserted directly in the query string. Also see {@see esc_like()}.
     1178     *
     1179     * Arguments may be passed as individual arguments to the method, or as a single array containing all arguments. A combination
     1180     * of the two is not supported.
     1181     *
     1182     * Examples:
     1183     *     $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", array( 'foo', 1337, '%bar' ) );
     1184     *     $wpdb->prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
     1185     *
     1186     * @link https://secure.php.net/sprintf Description of syntax.
    11811187     * @since 2.3.0
    11821188     *
    1183      * @param string $query Query statement with sprintf()-like placeholders
    1184      * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
    1185      *  {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
    1186      *  being called like {@link http://php.net/sprintf sprintf()}.
    1187      * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
    1188      *  {@link http://php.net/sprintf sprintf()}.
    1189      * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
    1190      *  if there was something to prepare
    1191      */
    1192     function prepare( $query, $args ) {
    1193         if ( is_null( $query ) )
     1189     * @param string      $query    Query statement with sprintf()-like placeholders
     1190     * @param array|mixed $args     The array of variables to substitute into the query's placeholders if being called with an array of arguments,
     1191     *                              or the first variable to substitute into the query's placeholders if being called with individual arguments.
     1192     * @param mixed       $args,... further variables to substitute into the query's placeholders if being called wih individual arguments.
     1193     * @return string|void Sanitized query string, if there is a query to prepare.
     1194     */
     1195    public function prepare( $query, $args ) {
     1196        if ( is_null( $query ) ) {
    11941197            return;
     1198        }
    11951199
    11961200        // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
    11971201        if ( strpos( $query, '%' ) === false ) {
    1198             _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );
     1202            wp_load_translations_early();
     1203            _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9.0' );
    11991204        }
    12001205
     
    12021207        array_shift( $args );
    12031208
    1204         // If args were passed as an array (as in vsprintf), move them up
     1209        // If args were passed as an array (as in vsprintf), move them up.
     1210        $passed_as_array = false;
    12051211        if ( is_array( $args[0] ) && count( $args ) == 1 ) {
     1212            $passed_as_array = true;
    12061213            $args = $args[0];
    12071214        }
     
    12091216        foreach ( $args as $arg ) {
    12101217            if ( ! is_scalar( $arg ) && ! is_null( $arg ) ) {
    1211                 _doing_it_wrong( 'wpdb::prepare', sprintf( 'Unsupported value type (%s).', gettype( $arg ) ), '3.9.20' );
    1212             }
    1213         }
    1214 
    1215         $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
    1216         $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
    1217         $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
    1218         $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
    1219         $query = preg_replace( '/%(?:%|$|([^dsF]))/', '%%\\1', $query ); // escape any unescaped percents
     1218                wp_load_translations_early();
     1219                _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'Unsupported value type (%s).' ), gettype( $arg ) ), '4.8.2' );
     1220            }
     1221        }
     1222
     1223        /*
     1224         * Specify the formatting allowed in a placeholder. The following are allowed:
     1225         *
     1226         * - Sign specifier. eg, $+d
     1227         * - Numbered placeholders. eg, %1$s
     1228         * - Padding specifier, including custom padding characters. eg, %05s, %'#5s
     1229         * - Alignment specifier. eg, %05-s
     1230         * - Precision specifier. eg, %.2f
     1231         */
     1232        $allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0|\'.)?[-+0-9]*(?:\.[0-9]+)?';
     1233
     1234        /*
     1235         * If a %s placeholder already has quotes around it, removing the existing quotes and re-inserting them
     1236         * ensures the quotes are consistent.
     1237         *
     1238         * For backwards compatibility, this is only applied to %s, and not to placeholders like %1$s, which are frequently
     1239         * used in the middle of longer strings, or as table name placeholders.
     1240         */
     1241        $query = str_replace( "'%s'", '%s', $query ); // Strip any existing single quotes.
     1242        $query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes.
     1243        $query = preg_replace( '/(?<!%)%s/', "'%s'", $query ); // Quote the strings, avoiding escaped strings like %%s.
     1244
     1245        $query = preg_replace( "/(?<!%)(%($allowed_format)?f)/" , '%\\2F', $query ); // Force floats to be locale unaware.
     1246
     1247        $query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdF]))/", '%%\\1', $query ); // Escape any unescaped percents.
     1248
     1249        // Count the number of valid placeholders in the query.
     1250        $placeholders = preg_match_all( "/(^|[^%]|(%%)+)%($allowed_format)?[sdF]/", $query, $matches );
     1251
     1252        if ( count( $args ) !== $placeholders ) {
     1253            if ( 1 === $placeholders && $passed_as_array ) {
     1254                // If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
     1255                wp_load_translations_early();
     1256                _doing_it_wrong( 'wpdb::prepare', __( 'The query only expected one placeholder, but an array of multiple placeholders was sent.' ), '4.9.0' );
     1257
     1258                return;
     1259            } else {
     1260                /*
     1261                 * If we don't have the right number of placeholders, but they were passed as individual arguments,
     1262                 * or we were expecting multiple arguments in an array, throw a warning.
     1263                 */
     1264                wp_load_translations_early();
     1265                _doing_it_wrong( 'wpdb::prepare',
     1266                    /* translators: 1: number of placeholders, 2: number of arguments passed */
     1267                    sprintf( __( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d).' ),
     1268                        $placeholders,
     1269                        count( $args ) ),
     1270                    '4.8.3'
     1271                );
     1272            }
     1273        }
     1274
    12201275        array_walk( $args, array( $this, 'escape_by_ref' ) );
    1221         return @vsprintf( $query, $args );
     1276        $query = @vsprintf( $query, $args );
     1277
     1278        return $this->add_placeholder_escape( $query );
    12221279    }
    12231280
     
    16951752            $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
    16961753        }
     1754    }
     1755
     1756    /**
     1757     * Generates and returns a placeholder escape string for use in queries returned by ::prepare().
     1758     *
     1759     * @since 4.8.3
     1760     *
     1761     * @return string String to escape placeholders.
     1762     */
     1763    public function placeholder_escape() {
     1764        static $placeholder;
     1765
     1766        if ( ! $placeholder ) {
     1767            // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
     1768            $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
     1769            // Old WP installs may not have AUTH_SALT defined.
     1770            $salt = defined( 'AUTH_SALT' ) ? AUTH_SALT : rand();
     1771
     1772            $placeholder = '{' . hash_hmac( $algo, uniqid( $salt, true ), $salt ) . '}';
     1773        }
     1774
     1775        /*
     1776         * Add the filter to remove the placeholder escaper. Uses priority 0, so that anything
     1777         * else attached to this filter will recieve the query with the placeholder string removed.
     1778         */
     1779        if ( ! has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) {
     1780            add_filter( 'query', array( $this, 'remove_placeholder_escape' ), 0 );
     1781        }
     1782
     1783        return $placeholder;
     1784    }
     1785
     1786    /**
     1787     * Adds a placeholder escape string, to escape anything that resembles a printf() placeholder.
     1788     *
     1789     * @since 4.8.3
     1790     *
     1791     * @param string $query The query to escape.
     1792     * @return string The query with the placeholder escape string inserted where necessary.
     1793     */
     1794    public function add_placeholder_escape( $query ) {
     1795        /*
     1796         * To prevent returning anything that even vaguely resembles a placeholder,
     1797         * we clobber every % we can find.
     1798         */
     1799        return str_replace( '%', $this->placeholder_escape(), $query );
     1800    }
     1801
     1802    /**
     1803     * Removes the placeholder escape strings from a query.
     1804     *
     1805     * @since 4.8.3
     1806     *
     1807     * @param string $query The query from which the placeholder will be removed.
     1808     * @return string The query with the placeholder removed.
     1809     */
     1810    public function remove_placeholder_escape( $query ) {
     1811        return str_replace( $this->placeholder_escape(), '%', $query );
    16971812    }
    16981813
Note: See TracChangeset for help on using the changeset viewer.