Make WordPress Core

Changeset 42061


Ignore:
Timestamp:
10/31/2017 12:45:48 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.4 branch.
See #41925.

Location:
branches/4.4
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • branches/4.4

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

    r36151 r42061  
    40894089    $page_path = str_replace('%20', ' ', $page_path);
    40904090    $parts = explode( '/', trim( $page_path, '/' ) );
    4091     $parts = esc_sql( $parts );
    40924091    $parts = array_map( 'sanitize_title_for_query', $parts );
    4093 
    4094     $in_string = "'" . implode( "','", $parts ) . "'";
     4092    $escaped_parts = esc_sql( $parts );
     4093
     4094    $in_string = "'" . implode( "','", $escaped_parts ) . "'";
    40954095
    40964096    if ( is_array( $post_type ) ) {
  • 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
  • branches/4.4/tests/phpunit/tests/date/query.php

    r35242 r42061  
    513513     */
    514514    public function test_build_time_query_should_not_discard_hour_0() {
     515        global $wpdb;
    515516        $q = new WP_Date_Query( array() );
    516517
    517518        $found = $q->build_time_query( 'post_date', '=', 0, 10 );
    518519
    519         $this->assertContains( '%H', $found );
     520        $this->assertContains( '%H', $wpdb->remove_placeholder_escape( $found ) );
    520521    }
    521522
     
    613614
    614615    public function test_build_time_query_hour_minute() {
     616        global $wpdb;
    615617        $q = new WP_Date_Query( array() );
    616618
     
    619621        // $compare value is floating point - use regex to account for
    620622        // varying precision on different PHP installations
    621         $this->assertRegExp( "/DATE_FORMAT\( post_date, '%H\.%i' \) = 5\.150*/", $found );
     623        $this->assertRegExp( "/DATE_FORMAT\( post_date, '%H\.%i' \) = 5\.150*/", $wpdb->remove_placeholder_escape( $found ) );
    622624    }
    623625
    624626    public function test_build_time_query_hour_minute_second() {
     627        global $wpdb;
    625628        $q = new WP_Date_Query( array() );
    626629
     
    629632        // $compare value is floating point - use regex to account for
    630633        // varying precision on different PHP installations
    631         $this->assertRegExp( "/DATE_FORMAT\( post_date, '%H\.%i%s' \) = 5\.15350*/", $found );
     634        $this->assertRegExp( "/DATE_FORMAT\( post_date, '%H\.%i%s' \) = 5\.15350*/", $wpdb->remove_placeholder_escape( $found ) );
    632635    }
    633636
    634637    public function test_build_time_query_minute_second() {
     638        global $wpdb;
    635639        $q = new WP_Date_Query( array() );
    636640
     
    639643        // $compare value is floating point - use regex to account for
    640644        // varying precision on different PHP installations
    641         $this->assertRegExp( "/DATE_FORMAT\( post_date, '0\.%i%s' \) = 0\.15350*/", $found );
     645        $this->assertRegExp( "/DATE_FORMAT\( post_date, '0\.%i%s' \) = 0\.15350*/", $wpdb->remove_placeholder_escape( $found ) );
    642646    }
    643647
  • branches/4.4/tests/phpunit/tests/db.php

    r41501 r42061  
    270270        global $wpdb;
    271271        $sql = $wpdb->prepare( "UPDATE test_table SET string_column = '%%f is a float, %%d is an int %d, %%s is a string', field = %s", 3, '4' );
     272        $this->assertContains( $wpdb->placeholder_escape(), $sql );
     273
     274        $sql = $wpdb->remove_placeholder_escape( $sql );
    272275        $this->assertEquals( "UPDATE test_table SET string_column = '%f is a float, %d is an int 3, %s is a string', field = '4'", $sql );
    273276    }
     
    375378    }
    376379
    377         function test_prepare_vsprintf() {
    378                 global $wpdb;
     380    function test_prepare_vsprintf() {
     381        global $wpdb;
    379382
    380383        $prepared = $wpdb->prepare( "SELECT * FROM $wpdb->users WHERE id = %d AND user_login = %s", array( 1, "admin" ) );
     
    393396        $prepared = @$wpdb->prepare( "SELECT * FROM $wpdb->users WHERE id = %d AND user_login = %s", array( array( 1 ), "admin" ) );
    394397        $this->assertEquals( "SELECT * FROM $wpdb->users WHERE id = 0 AND user_login = 'admin'", $prepared );
    395         }
     398    }
     399
     400    /**
     401     * @ticket 42040
     402     * @dataProvider data_prepare_incorrect_arg_count
     403     * @expectedIncorrectUsage wpdb::prepare
     404     */
     405    public function test_prepare_incorrect_arg_count( $query, $args, $expected ) {
     406        global $wpdb;
     407
     408        // $query is the first argument to be passed to wpdb::prepare()
     409        array_unshift( $args, $query );
     410
     411        $prepared = @call_user_func_array( array( $wpdb, 'prepare' ), $args );
     412        $this->assertEquals( $expected, $prepared );
     413    }
     414
     415    public function data_prepare_incorrect_arg_count() {
     416        global $wpdb;
     417
     418        return array(
     419            array(
     420                "SELECT * FROM $wpdb->users WHERE id = %d AND user_login = %s",     // Query
     421                array( 1, "admin", "extra-arg" ),                                   // ::prepare() args, to be passed via call_user_func_array
     422                "SELECT * FROM $wpdb->users WHERE id = 1 AND user_login = 'admin'", // Expected output
     423            ),
     424            array(
     425                "SELECT * FROM $wpdb->users WHERE id = %%%d AND user_login = %s",
     426                array( 1 ),
     427                false,
     428            ),
     429            array(
     430                "SELECT * FROM $wpdb->users WHERE id = %d AND user_login = %s",
     431                array( array( 1, "admin", "extra-arg" ) ),
     432                "SELECT * FROM $wpdb->users WHERE id = 1 AND user_login = 'admin'",
     433            ),
     434            array(
     435                "SELECT * FROM $wpdb->users WHERE id = %d AND %% AND user_login = %s",
     436                array( 1, "admin", "extra-arg" ),
     437                "SELECT * FROM $wpdb->users WHERE id = 1 AND {$wpdb->placeholder_escape()} AND user_login = 'admin'",
     438            ),
     439            array(
     440                "SELECT * FROM $wpdb->users WHERE id = %%%d AND %F AND %f AND user_login = %s",
     441                array( 1, 2.3, "4.5", "admin", "extra-arg" ),
     442                "SELECT * FROM $wpdb->users WHERE id = {$wpdb->placeholder_escape()}1 AND 2.300000 AND 4.500000 AND user_login = 'admin'",
     443            ),
     444            array(
     445                "SELECT * FROM $wpdb->users WHERE id = %d AND user_login = %s",
     446                array( array( 1 ), "admin", "extra-arg" ),
     447                "SELECT * FROM $wpdb->users WHERE id = 0 AND user_login = 'admin'",
     448            ),
     449            array(
     450                "SELECT * FROM $wpdb->users WHERE id = %d and user_nicename = %s and user_status = %d and user_login = %s",
     451                array( 1, "admin", 0 ),
     452                '',
     453            ),
     454            array(
     455                "SELECT * FROM $wpdb->users WHERE id = %d and user_nicename = %s and user_status = %d and user_login = %s",
     456                array( array( 1, "admin", 0 ) ),
     457                '',
     458            ),
     459            array(
     460                "SELECT * FROM $wpdb->users WHERE id = %d and %% and user_login = %s and user_status = %d and user_login = %s",
     461                array( 1, "admin", "extra-arg" ),
     462                '',
     463            ),
     464        );
     465    }
    396466
    397467    function test_db_version() {
     
    9851055
    9861056    /**
    987      *
    988      */
    989     function test_prepare_with_unescaped_percents() {
    990         global $wpdb;
    991 
    992         $sql = $wpdb->prepare( '%d %1$d %%% %', 1 );
    993         $this->assertEquals( '1 %1$d %% %', $sql );
     1057     * @dataProvider data_prepare_with_placeholders
     1058     */
     1059    function test_prepare_with_placeholders_and_individual_args( $sql, $values, $incorrect_usage, $expected) {
     1060        global $wpdb;
     1061
     1062        if ( $incorrect_usage ) {
     1063            $this->setExpectedIncorrectUsage( 'wpdb::prepare' );
     1064        }
     1065
     1066        if ( ! is_array( $values ) ) {
     1067            $values = array( $values );
     1068        }
     1069
     1070        array_unshift( $values, $sql );
     1071
     1072        $sql = call_user_func_array( array( $wpdb, 'prepare' ), $values );
     1073        $this->assertEquals( $expected, $sql );
     1074    }
     1075
     1076    /**
     1077     * @dataProvider data_prepare_with_placeholders
     1078     */
     1079    function test_prepare_with_placeholders_and_array_args( $sql, $values, $incorrect_usage, $expected) {
     1080        global $wpdb;
     1081
     1082        if ( $incorrect_usage ) {
     1083            $this->setExpectedIncorrectUsage( 'wpdb::prepare' );
     1084        }
     1085
     1086        if ( ! is_array( $values ) ) {
     1087            $values = array( $values );
     1088        }
     1089
     1090        $sql = call_user_func_array( array( $wpdb, 'prepare' ), array( $sql, $values ) );
     1091        $this->assertEquals( $expected, $sql );
     1092    }
     1093
     1094    function data_prepare_with_placeholders() {
     1095        global $wpdb;
     1096
     1097        return array(
     1098            array(
     1099                '%5s',   // SQL to prepare
     1100                'foo',   // Value to insert in the SQL
     1101                false,   // Whether to expect an incorrect usage error or not
     1102                '  foo', // Expected output
     1103            ),
     1104            array(
     1105                '%1$d %%% % %%1$d%% %%%1$d%%',
     1106                1,
     1107                true,
     1108                "1 {$wpdb->placeholder_escape()}{$wpdb->placeholder_escape()} {$wpdb->placeholder_escape()} {$wpdb->placeholder_escape()}1\$d{$wpdb->placeholder_escape()} {$wpdb->placeholder_escape()}1{$wpdb->placeholder_escape()}",
     1109            ),
     1110            array(
     1111                '%-5s',
     1112                'foo',
     1113                false,
     1114                'foo  ',
     1115            ),
     1116            array(
     1117                '%05s',
     1118                'foo',
     1119                false,
     1120                '00foo',
     1121            ),
     1122            array(
     1123                "%'#5s",
     1124                'foo',
     1125                false,
     1126                '##foo',
     1127            ),
     1128            array(
     1129                '%.3s',
     1130                'foobar',
     1131                false,
     1132                'foo',
     1133            ),
     1134            array(
     1135                '%.3f',
     1136                5.123456,
     1137                false,
     1138                '5.123',
     1139            ),
     1140            array(
     1141                '%.3f',
     1142                5.12,
     1143                false,
     1144                '5.120',
     1145            ),
     1146            array(
     1147                '%s',
     1148                ' %s ',
     1149                false,
     1150                "' {$wpdb->placeholder_escape()}s '",
     1151            ),
     1152            array(
     1153                '%1$s',
     1154                ' %s ',
     1155                false,
     1156                " {$wpdb->placeholder_escape()}s ",
     1157            ),
     1158            array(
     1159                '%1$s',
     1160                ' %1$s ',
     1161                false,
     1162                " {$wpdb->placeholder_escape()}1\$s ",
     1163            ),
     1164            array(
     1165                '%d %1$d %%% %',
     1166                1,
     1167                true,
     1168                "1 1 {$wpdb->placeholder_escape()}{$wpdb->placeholder_escape()} {$wpdb->placeholder_escape()}",
     1169            ),
     1170            array(
     1171                '%d %2$s',
     1172                array( 1, 'hello' ),
     1173                false,
     1174                "1 hello",
     1175            ),
     1176            array(
     1177                "'%s'",
     1178                'hello',
     1179                false,
     1180                "'hello'",
     1181            ),
     1182            array(
     1183                '"%s"',
     1184                'hello',
     1185                false,
     1186                "'hello'",
     1187            ),
     1188            array(
     1189                "%s '%1\$s'",
     1190                'hello',
     1191                true,
     1192                "'hello' 'hello'",
     1193            ),
     1194            array(
     1195                "%s '%1\$s'",
     1196                'hello',
     1197                true,
     1198                "'hello' 'hello'",
     1199            ),
     1200            array(
     1201                '%s "%1$s"',
     1202                'hello',
     1203                true,
     1204                "'hello' \"hello\"",
     1205            ),
     1206            array(
     1207                "%%s %%'%1\$s'",
     1208                'hello',
     1209                false,
     1210                "{$wpdb->placeholder_escape()}s {$wpdb->placeholder_escape()}'hello'",
     1211            ),
     1212            array(
     1213                '%%s %%"%1$s"',
     1214                'hello',
     1215                false,
     1216                "{$wpdb->placeholder_escape()}s {$wpdb->placeholder_escape()}\"hello\"",
     1217            ),
     1218            array(
     1219                '%s',
     1220                ' %  s ',
     1221                false,
     1222                "' {$wpdb->placeholder_escape()}  s '",
     1223            ),
     1224            array(
     1225                '%%f %%"%1$f"',
     1226                3,
     1227                false,
     1228                "{$wpdb->placeholder_escape()}f {$wpdb->placeholder_escape()}\"3.000000\"",
     1229            ),
     1230            array(
     1231                'WHERE second=\'%2$s\' AND first=\'%1$s\'',
     1232                array( 'first arg', 'second arg' ),
     1233                false,
     1234                "WHERE second='second arg' AND first='first arg'",
     1235            ),
     1236            array(
     1237                'WHERE second=%2$d AND first=%1$d',
     1238                array( 1, 2 ),
     1239                false,
     1240                "WHERE second=2 AND first=1",
     1241            ),
     1242            array(
     1243                "'%'%%s",
     1244                'hello',
     1245                true,
     1246                "'{$wpdb->placeholder_escape()}'{$wpdb->placeholder_escape()}s",
     1247            ),
     1248            array(
     1249                "'%'%%s%s",
     1250                'hello',
     1251                false,
     1252                "'{$wpdb->placeholder_escape()}'{$wpdb->placeholder_escape()}s'hello'",
     1253            ),
     1254            array(
     1255                "'%'%%s %s",
     1256                'hello',
     1257                false,
     1258                "'{$wpdb->placeholder_escape()}'{$wpdb->placeholder_escape()}s 'hello'",
     1259            ),
     1260            array(
     1261                "'%-'#5s' '%'#-+-5s'",
     1262                array( 'hello', 'foo' ),
     1263                false,
     1264                "'hello' 'foo##'",
     1265            ),
     1266        );
     1267    }
     1268
     1269    /**
     1270     * @dataProvider data_escape_and_prepare
     1271     */
     1272    function test_escape_and_prepare( $escape, $sql, $values, $incorrect_usage, $expected ) {
     1273        global $wpdb;
     1274
     1275        if ( $incorrect_usage ) {
     1276            $this->setExpectedIncorrectUsage( 'wpdb::prepare' );
     1277        }
     1278
     1279        $escape = esc_sql( $escape );
     1280
     1281        $sql = str_replace( '{ESCAPE}', $escape, $sql );
     1282
     1283        $actual = $wpdb->prepare( $sql, $values );
     1284
     1285        $this->assertEquals( $expected, $actual );
     1286    }
     1287
     1288    function data_escape_and_prepare() {
     1289        global $wpdb;
     1290        return array(
     1291            array(
     1292                '%s',                                  // String to pass through esc_url()
     1293                ' {ESCAPE} ',                          // Query to insert the output of esc_url() into, replacing "{ESCAPE}"
     1294                'foo',                                 // Data to send to prepare()
     1295                true,                                  // Whether to expect an incorrect usage error or not
     1296                " {$wpdb->placeholder_escape()}s ",    // Expected output
     1297            ),
     1298            array(
     1299                'foo%sbar',
     1300                "SELECT * FROM bar WHERE foo='{ESCAPE}' OR baz=%s",
     1301                array( ' SQLi -- -', 'pewpewpew' ),
     1302                true,
     1303                null,
     1304            ),
     1305            array(
     1306                '%s',
     1307                ' %s {ESCAPE} ',
     1308                'foo',
     1309                false,
     1310                " 'foo' {$wpdb->placeholder_escape()}s ",
     1311            ),
     1312        );
     1313    }
     1314
     1315    /**
     1316     * @expectedIncorrectUsage wpdb::prepare
     1317     */
     1318    function test_double_prepare() {
     1319        global $wpdb;
     1320
     1321        $part = $wpdb->prepare( ' AND meta_value = %s', ' %s ' );
     1322        $this->assertNotContains( '%s', $part );
     1323        $query = $wpdb->prepare( 'SELECT * FROM {$wpdb->postmeta} WHERE meta_key = %s $part', array( 'foo', 'bar' ) );
     1324        $this->assertNull( $query );
     1325    }
     1326
     1327    function test_prepare_numeric_placeholders_float_args() {
     1328        global $wpdb;
     1329
     1330        $actual = $wpdb->prepare(
     1331            'WHERE second=%2$f AND first=%1$f',
     1332            1.1,
     1333            2.2
     1334        );
     1335
     1336        /* Floats can be right padded, need to assert differently */
     1337        $this->assertContains( ' first=1.1', $actual );
     1338        $this->assertContains( ' second=2.2', $actual );
     1339    }
     1340
     1341    function test_prepare_numeric_placeholders_float_array() {
     1342        global $wpdb;
     1343
     1344        $actual = $wpdb->prepare(
     1345            'WHERE second=%2$f AND first=%1$f',
     1346            array( 1.1, 2.2 )
     1347        );
     1348
     1349        /* Floats can be right padded, need to assert differently */
     1350        $this->assertContains( ' first=1.1', $actual );
     1351        $this->assertContains( ' second=2.2', $actual );
     1352    }
     1353
     1354    function test_query_unescapes_placeholders() {
     1355        global $wpdb;
     1356
     1357        $value = ' %s ';
     1358
     1359        $wpdb->query( "CREATE TABLE {$wpdb->prefix}test_placeholder( a VARCHAR(100) );" );
     1360        $sql = $wpdb->prepare( "INSERT INTO {$wpdb->prefix}test_placeholder VALUES(%s)", $value );
     1361        $wpdb->query( $sql );
     1362
     1363        $actual = $wpdb->get_var( "SELECT a FROM {$wpdb->prefix}test_placeholder" );
     1364
     1365        $wpdb->query( "DROP TABLE {$wpdb->prefix}test_placeholder" );
     1366
     1367        $this->assertNotContains( '%s', $sql );
     1368        $this->assertEquals( $value, $actual );
     1369    }
     1370
     1371    function test_esc_sql_with_unsupported_placeholder_type() {
     1372        global $wpdb;
     1373
     1374        $sql = $wpdb->prepare( ' %s %1$c ', 'foo' );
     1375        $sql = $wpdb->prepare( " $sql %s ", 'foo' );
     1376
     1377        $this->assertEquals( "  'foo' {$wpdb->placeholder_escape()}1\$c  'foo' ", $sql );
    9941378    }
    9951379}
  • branches/4.4/tests/phpunit/tests/term/meta.php

    r35585 r42061  
    354354        register_taxonomy( 'wptests_tax', 'post' );
    355355        $t1 = wp_insert_term( 'Foo', 'wptests_tax' );
    356         add_term_meta( $t1, 'foo', 'bar' );
     356        add_term_meta( $t1['term_id'], 'foo', 'bar' );
    357357
    358358        register_taxonomy( 'wptests_tax_2', 'post' );
  • branches/4.4/wp-tests-config-sample.php

    r25571 r42061  
    3131define( 'DB_COLLATE', '' );
    3232
     33/**#@+
     34 * Authentication Unique Keys and Salts.
     35 *
     36 * Change these to different unique phrases!
     37 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
     38 */
     39define('AUTH_KEY',         'put your unique phrase here');
     40define('SECURE_AUTH_KEY',  'put your unique phrase here');
     41define('LOGGED_IN_KEY',    'put your unique phrase here');
     42define('NONCE_KEY',        'put your unique phrase here');
     43define('AUTH_SALT',        'put your unique phrase here');
     44define('SECURE_AUTH_SALT', 'put your unique phrase here');
     45define('LOGGED_IN_SALT',   'put your unique phrase here');
     46define('NONCE_SALT',       'put your unique phrase here');
     47
    3348$table_prefix  = 'wptests_';   // Only numbers, letters, and underscores please!
    3449
Note: See TracChangeset for help on using the changeset viewer.