Make WordPress Core

Changeset 42068 for branches/3.7/src


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

Location:
branches/3.7
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • branches/3.7

  • branches/3.7/src

  • branches/3.7/src/wp-includes/post.php

    r33561 r42068  
    34953495    $page_path = str_replace('%20', ' ', $page_path);
    34963496    $parts = explode( '/', trim( $page_path, '/' ) );
    3497     $parts = esc_sql( $parts );
    34983497    $parts = array_map( 'sanitize_title_for_query', $parts );
    3499 
    3500     $in_string = "'". implode( "','", $parts ) . "'";
     3498    $escaped_parts = esc_sql( $parts );
     3499
     3500    $in_string = "'". implode( "','", $escaped_parts ) . "'";
    35013501    $post_type_sql = esc_sql( $post_type );
    35023502    $pages = $wpdb->get_results( "SELECT ID, post_name, post_parent, post_type FROM $wpdb->posts WHERE post_name IN ($in_string) AND (post_type = '$post_type_sql' OR post_type = 'attachment')", OBJECT_K );
  • branches/3.7/src/wp-includes/wp-db.php

    r41508 r42068  
    912912
    913913    /**
    914      * Real escape, using mysql_real_escape_string()
    915      *
     914     * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string()
     915     *
     916     * @see mysqli_real_escape_string()
    916917     * @see mysql_real_escape_string()
    917918     * @since 2.8.0
     
    922923     */
    923924    function _real_escape( $string ) {
    924         if ( $this->dbh )
    925             return mysql_real_escape_string( $string, $this->dbh );
    926 
    927         $class = get_class( $this );
    928         _doing_it_wrong( $class, "$class must set a database connection for use with escaping.", E_USER_NOTICE );
    929         return addslashes( $string );
     925        if ( $this->dbh ) {
     926            $escaped = mysql_real_escape_string( $string, $this->dbh );
     927        } else {
     928            $class = get_class( $this );
     929            if ( function_exists( '__' ) ) {
     930                /* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */
     931                _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
     932            } else {
     933                _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), '3.6.0' );
     934            }
     935            $escaped = addslashes( $string );
     936        }
     937
     938        return $this->add_placeholder_escape( $escaped );
    930939    }
    931940
     
    10011010     * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
    10021011     *
    1003      * The following directives can be used in the query format string:
     1012     * The following placeholders can be used in the query string:
    10041013     *   %d (integer)
    10051014     *   %f (float)
    10061015     *   %s (string)
    1007      *   %% (literal percentage sign - no argument needed)
    1008      *
    1009      * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
    1010      * Literals (%) as parts of the query must be properly written as %%.
    1011      *
    1012      * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
    1013      * Does not support sign, padding, alignment, width or precision specifiers.
    1014      * Does not support argument numbering/swapping.
    1015      *
    1016      * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
    1017      *
    1018      * Both %d and %s should be left unquoted in the query string.
    1019      *
    1020      * <code>
    1021      * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
    1022      * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
    1023      * </code>
    1024      *
    1025      * @link http://php.net/sprintf Description of syntax.
     1016     *
     1017     * All placeholders MUST be left unquoted in the query string. A corresponding argument MUST be passed for each placeholder.
     1018     *
     1019     * For compatibility with old behavior, numbered or formatted string placeholders (eg, %1$s, %5s) will not have quotes
     1020     * added by this function, so should be passed with appropriate quotes around them for your usage.
     1021     *
     1022     * Literal percentage signs (%) in the query string must be written as %%. Percentage wildcards (for example,
     1023     * to use in LIKE syntax) must be passed via a substitution argument containing the complete LIKE string, these
     1024     * cannot be inserted directly in the query string. Also see {@see esc_like()}.
     1025     *
     1026     * Arguments may be passed as individual arguments to the method, or as a single array containing all arguments. A combination
     1027     * of the two is not supported.
     1028     *
     1029     * Examples:
     1030     *     $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", array( 'foo', 1337, '%bar' ) );
     1031     *     $wpdb->prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
     1032     *
     1033     * @link https://secure.php.net/sprintf Description of syntax.
    10261034     * @since 2.3.0
    10271035     *
    1028      * @param string $query Query statement with sprintf()-like placeholders
    1029      * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
    1030      *  {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
    1031      *  being called like {@link http://php.net/sprintf sprintf()}.
    1032      * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
    1033      *  {@link http://php.net/sprintf sprintf()}.
    1034      * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
    1035      *  if there was something to prepare
    1036      */
    1037     function prepare( $query, $args ) {
    1038         if ( is_null( $query ) )
     1036     * @param string      $query    Query statement with sprintf()-like placeholders
     1037     * @param array|mixed $args     The array of variables to substitute into the query's placeholders if being called with an array of arguments,
     1038     *                              or the first variable to substitute into the query's placeholders if being called with individual arguments.
     1039     * @param mixed       $args,... further variables to substitute into the query's placeholders if being called wih individual arguments.
     1040     * @return string|void Sanitized query string, if there is a query to prepare.
     1041     */
     1042    public function prepare( $query, $args ) {
     1043        if ( is_null( $query ) ) {
    10391044            return;
     1045        }
     1046
     1047        // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
     1048        if ( strpos( $query, '%' ) === false ) {
     1049            wp_load_translations_early();
     1050            _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9.0' );
     1051        }
    10401052
    10411053        $args = func_get_args();
    10421054        array_shift( $args );
    10431055
    1044         // If args were passed as an array (as in vsprintf), move them up
     1056        // If args were passed as an array (as in vsprintf), move them up.
     1057        $passed_as_array = false;
    10451058        if ( is_array( $args[0] ) && count( $args ) == 1 ) {
     1059            $passed_as_array = true;
    10461060            $args = $args[0];
    10471061        }
     
    10491063        foreach ( $args as $arg ) {
    10501064            if ( ! is_scalar( $arg ) && ! is_null( $arg ) ) {
    1051                 _doing_it_wrong( 'wpdb::prepare', sprintf( 'Unsupported value type (%s).', gettype( $arg ) ), '3.7.22' );
    1052             }
    1053         }
    1054 
    1055         $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
    1056         $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
    1057         $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
    1058         $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
    1059         $query = preg_replace( '/%(?:%|$|([^dsF]))/', '%%\\1', $query ); // escape any unescaped percents
     1065                wp_load_translations_early();
     1066                _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'Unsupported value type (%s).' ), gettype( $arg ) ), '4.8.2' );
     1067            }
     1068        }
     1069
     1070        /*
     1071         * Specify the formatting allowed in a placeholder. The following are allowed:
     1072         *
     1073         * - Sign specifier. eg, $+d
     1074         * - Numbered placeholders. eg, %1$s
     1075         * - Padding specifier, including custom padding characters. eg, %05s, %'#5s
     1076         * - Alignment specifier. eg, %05-s
     1077         * - Precision specifier. eg, %.2f
     1078         */
     1079        $allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0|\'.)?[-+0-9]*(?:\.[0-9]+)?';
     1080
     1081        /*
     1082         * If a %s placeholder already has quotes around it, removing the existing quotes and re-inserting them
     1083         * ensures the quotes are consistent.
     1084         *
     1085         * For backwards compatibility, this is only applied to %s, and not to placeholders like %1$s, which are frequently
     1086         * used in the middle of longer strings, or as table name placeholders.
     1087         */
     1088        $query = str_replace( "'%s'", '%s', $query ); // Strip any existing single quotes.
     1089        $query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes.
     1090        $query = preg_replace( '/(?<!%)%s/', "'%s'", $query ); // Quote the strings, avoiding escaped strings like %%s.
     1091
     1092        $query = preg_replace( "/(?<!%)(%($allowed_format)?f)/" , '%\\2F', $query ); // Force floats to be locale unaware.
     1093
     1094        $query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdF]))/", '%%\\1', $query ); // Escape any unescaped percents.
     1095
     1096        // Count the number of valid placeholders in the query.
     1097        $placeholders = preg_match_all( "/(^|[^%]|(%%)+)%($allowed_format)?[sdF]/", $query, $matches );
     1098
     1099        if ( count( $args ) !== $placeholders ) {
     1100            if ( 1 === $placeholders && $passed_as_array ) {
     1101                // If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
     1102                wp_load_translations_early();
     1103                _doing_it_wrong( 'wpdb::prepare', __( 'The query only expected one placeholder, but an array of multiple placeholders was sent.' ), '4.9.0' );
     1104
     1105                return;
     1106            } else {
     1107                /*
     1108                 * If we don't have the right number of placeholders, but they were passed as individual arguments,
     1109                 * or we were expecting multiple arguments in an array, throw a warning.
     1110                 */
     1111                wp_load_translations_early();
     1112                _doing_it_wrong( 'wpdb::prepare',
     1113                    /* translators: 1: number of placeholders, 2: number of arguments passed */
     1114                    sprintf( __( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d).' ),
     1115                        $placeholders,
     1116                        count( $args ) ),
     1117                    '4.8.3'
     1118                );
     1119            }
     1120        }
     1121
    10601122        array_walk( $args, array( $this, 'escape_by_ref' ) );
    1061         return @vsprintf( $query, $args );
     1123        $query = @vsprintf( $query, $args );
     1124
     1125        return $this->add_placeholder_escape( $query );
    10621126    }
    10631127
     
    13151379
    13161380        return $return_val;
     1381    }
     1382
     1383    /**
     1384     * Generates and returns a placeholder escape string for use in queries returned by ::prepare().
     1385     *
     1386     * @since 4.8.3
     1387     *
     1388     * @return string String to escape placeholders.
     1389     */
     1390    public function placeholder_escape() {
     1391        static $placeholder;
     1392
     1393        if ( ! $placeholder ) {
     1394            // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
     1395            $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
     1396            // Old WP installs may not have AUTH_SALT defined.
     1397            $salt = defined( 'AUTH_SALT' ) ? AUTH_SALT : rand();
     1398
     1399            $placeholder = '{' . hash_hmac( $algo, uniqid( $salt, true ), $salt ) . '}';
     1400        }
     1401
     1402        /*
     1403         * Add the filter to remove the placeholder escaper. Uses priority 0, so that anything
     1404         * else attached to this filter will recieve the query with the placeholder string removed.
     1405         */
     1406        if ( ! has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) {
     1407            add_filter( 'query', array( $this, 'remove_placeholder_escape' ), 0 );
     1408        }
     1409
     1410        return $placeholder;
     1411    }
     1412
     1413    /**
     1414     * Adds a placeholder escape string, to escape anything that resembles a printf() placeholder.
     1415     *
     1416     * @since 4.8.3
     1417     *
     1418     * @param string $query The query to escape.
     1419     * @return string The query with the placeholder escape string inserted where necessary.
     1420     */
     1421    public function add_placeholder_escape( $query ) {
     1422        /*
     1423         * To prevent returning anything that even vaguely resembles a placeholder,
     1424         * we clobber every % we can find.
     1425         */
     1426        return str_replace( '%', $this->placeholder_escape(), $query );
     1427    }
     1428
     1429    /**
     1430     * Removes the placeholder escape strings from a query.
     1431     *
     1432     * @since 4.8.3
     1433     *
     1434     * @param string $query The query from which the placeholder will be removed.
     1435     * @return string The query with the placeholder removed.
     1436     */
     1437    public function remove_placeholder_escape( $query ) {
     1438        return str_replace( $this->placeholder_escape(), '%', $query );
    13171439    }
    13181440
Note: See TracChangeset for help on using the changeset viewer.