Make WordPress Core

Changeset 42063


Ignore:
Timestamp:
10/31/2017 12:50:23 PM (9 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.2 branch.
See #41925.

Location:
branches/4.2
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • branches/4.2

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

    r33556 r42063  
    42254225        $page_path = str_replace('%20', ' ', $page_path);
    42264226        $parts = explode( '/', trim( $page_path, '/' ) );
    4227         $parts = esc_sql( $parts );
    42284227        $parts = array_map( 'sanitize_title_for_query', $parts );
    4229 
    4230         $in_string = "'" . implode( "','", $parts ) . "'";
     4228        $escaped_parts = esc_sql( $parts );
     4229
     4230        $in_string = "'" . implode( "','", $escaped_parts ) . "'";
    42314231
    42324232        if ( is_array( $post_type ) ) {
  • branches/4.2/src/wp-includes/wp-db.php

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

    r31251 r42063  
    602602
    603603        public function test_build_time_query_hour_minute() {
     604                global $wpdb;
    604605                $q = new WP_Date_Query( array() );
    605606
    … …  
    608609                // $compare value is floating point - use regex to account for
    609610                // varying precision on different PHP installations
    610                 $this->assertRegExp( "/DATE_FORMAT\( post_date, '%H\.%i' \) = 5\.150*/", $found );
     611                $this->assertRegExp( "/DATE_FORMAT\( post_date, '%H\.%i' \) = 5\.150*/", $wpdb->remove_placeholder_escape( $found ) );
    611612        }
    612613
    613614        public function test_build_time_query_hour_minute_second() {
     615                global $wpdb;
    614616                $q = new WP_Date_Query( array() );
    615617
    … …  
    618620                // $compare value is floating point - use regex to account for
    619621                // varying precision on different PHP installations
    620                 $this->assertRegExp( "/DATE_FORMAT\( post_date, '%H\.%i%s' \) = 5\.15350*/", $found );
     622                $this->assertRegExp( "/DATE_FORMAT\( post_date, '%H\.%i%s' \) = 5\.15350*/", $wpdb->remove_placeholder_escape( $found ) );
    621623        }
    622624
    623625        public function test_build_time_query_minute_second() {
     626                global $wpdb;
    624627                $q = new WP_Date_Query( array() );
    625628
    … …  
    628631                // $compare value is floating point - use regex to account for
    629632                // varying precision on different PHP installations
    630                 $this->assertRegExp( "/DATE_FORMAT\( post_date, '0\.%i%s' \) = 0\.15350*/", $found );
     633                $this->assertRegExp( "/DATE_FORMAT\( post_date, '0\.%i%s' \) = 0\.15350*/", $wpdb->remove_placeholder_escape( $found ) );
    631634        }
    632635
  • branches/4.2/tests/phpunit/tests/db.php

    r41503 r42063  
    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        }
    … …  
    374377        }
    375378
    376         function test_prepare_vsprintf() {
    377                 global $wpdb;
     379    function test_prepare_vsprintf() {
     380                global $wpdb;
    378381
    379382                $prepared = $wpdb->prepare( "SELECT * FROM $wpdb->users WHERE id = %d AND user_login = %s", array( 1, "admin" ) );
    … …  
    392395                $prepared = @$wpdb->prepare( "SELECT * FROM $wpdb->users WHERE id = %d AND user_login = %s", array( array( 1 ), "admin" ) );
    393396                $this->assertEquals( "SELECT * FROM $wpdb->users WHERE id = 0 AND user_login = 'admin'", $prepared );
    394         }
     397        }
     398
     399        /**
     400         * @ticket 42040
     401         * @dataProvider data_prepare_incorrect_arg_count
     402         * @expectedIncorrectUsage wpdb::prepare
     403         */
     404        public function test_prepare_incorrect_arg_count( $query, $args, $expected ) {
     405                global $wpdb;
     406
     407                // $query is the first argument to be passed to wpdb::prepare()
     408                array_unshift( $args, $query );
     409
     410                $prepared = @call_user_func_array( array( $wpdb, 'prepare' ), $args );
     411                $this->assertEquals( $expected, $prepared );
     412        }
     413
     414        public function data_prepare_incorrect_arg_count() {
     415                global $wpdb;
     416
     417                return array(
     418                        array(
     419                                "SELECT * FROM $wpdb->users WHERE id = %d AND user_login = %s",     // Query
     420                                array( 1, "admin", "extra-arg" ),                                   // ::prepare() args, to be passed via call_user_func_array
     421                                "SELECT * FROM $wpdb->users WHERE id = 1 AND user_login = 'admin'", // Expected output
     422                        ),
     423                        array(
     424                                "SELECT * FROM $wpdb->users WHERE id = %%%d AND user_login = %s",
     425                                array( 1 ),
     426                                false,
     427                        ),
     428                        array(
     429                                "SELECT * FROM $wpdb->users WHERE id = %d AND user_login = %s",
     430                                array( array( 1, "admin", "extra-arg" ) ),
     431                                "SELECT * FROM $wpdb->users WHERE id = 1 AND user_login = 'admin'",
     432                        ),
     433                        array(
     434                                "SELECT * FROM $wpdb->users WHERE id = %d AND %% AND user_login = %s",
     435                                array( 1, "admin", "extra-arg" ),
     436                                "SELECT * FROM $wpdb->users WHERE id = 1 AND {$wpdb->placeholder_escape()} AND user_login = 'admin'",
     437                        ),
     438                        array(
     439                                "SELECT * FROM $wpdb->users WHERE id = %%%d AND %F AND %f AND user_login = %s",
     440                                array( 1, 2.3, "4.5", "admin", "extra-arg" ),
     441                                "SELECT * FROM $wpdb->users WHERE id = {$wpdb->placeholder_escape()}1 AND 2.300000 AND 4.500000 AND user_login = 'admin'",
     442                        ),
     443                        array(
     444                                "SELECT * FROM $wpdb->users WHERE id = %d AND user_login = %s",
     445                                array( array( 1 ), "admin", "extra-arg" ),
     446                                "SELECT * FROM $wpdb->users WHERE id = 0 AND user_login = 'admin'",
     447                        ),
     448                        array(
     449                                "SELECT * FROM $wpdb->users WHERE id = %d and user_nicename = %s and user_status = %d and user_login = %s",
     450                                array( 1, "admin", 0 ),
     451                                '',
     452                        ),
     453                        array(
     454                                "SELECT * FROM $wpdb->users WHERE id = %d and user_nicename = %s and user_status = %d and user_login = %s",
     455                                array( array( 1, "admin", 0 ) ),
     456                                '',
     457                        ),
     458                        array(
     459                                "SELECT * FROM $wpdb->users WHERE id = %d and %% and user_login = %s and user_status = %d and user_login = %s",
     460                                array( 1, "admin", "extra-arg" ),
     461                                '',
     462                        ),
     463                );
     464        }
    395465
    396466        function test_db_version() {
    … …  
    850920
    851921        /**
    852          *
    853          */
    854         function test_prepare_with_unescaped_percents() {
    855                 global $wpdb;
    856 
    857                 $sql = $wpdb->prepare( '%d %1$d %%% %', 1 );
    858                 $this->assertEquals( '1 %1$d %% %', $sql );
     922         * @dataProvider data_prepare_with_placeholders
     923         */
     924        function test_prepare_with_placeholders_and_individual_args( $sql, $values, $incorrect_usage, $expected) {
     925                global $wpdb;
     926
     927                if ( $incorrect_usage ) {
     928                        $this->setExpectedIncorrectUsage( 'wpdb::prepare' );
     929                }
     930
     931                if ( ! is_array( $values ) ) {
     932                        $values = array( $values );
     933                }
     934
     935                array_unshift( $values, $sql );
     936
     937                $sql = call_user_func_array( array( $wpdb, 'prepare' ), $values );
     938                $this->assertEquals( $expected, $sql );
     939        }
     940
     941        /**
     942         * @dataProvider data_prepare_with_placeholders
     943         */
     944        function test_prepare_with_placeholders_and_array_args( $sql, $values, $incorrect_usage, $expected) {
     945                global $wpdb;
     946
     947                if ( $incorrect_usage ) {
     948                        $this->setExpectedIncorrectUsage( 'wpdb::prepare' );
     949                }
     950
     951                if ( ! is_array( $values ) ) {
     952                        $values = array( $values );
     953                }
     954
     955                $sql = call_user_func_array( array( $wpdb, 'prepare' ), array( $sql, $values ) );
     956                $this->assertEquals( $expected, $sql );
     957        }
     958
     959        function data_prepare_with_placeholders() {
     960                global $wpdb;
     961
     962                return array(
     963                        array(
     964                                '%5s',   // SQL to prepare
     965                                'foo',   // Value to insert in the SQL
     966                                false,   // Whether to expect an incorrect usage error or not
     967                                '  foo', // Expected output
     968                        ),
     969                        array(
     970                                '%1$d %%% % %%1$d%% %%%1$d%%',
     971                                1,
     972                                true,
     973                                "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()}",
     974                        ),
     975                        array(
     976                                '%-5s',
     977                                'foo',
     978                                false,
     979                                'foo  ',
     980                        ),
     981                        array(
     982                                '%05s',
     983                                'foo',
     984                                false,
     985                                '00foo',
     986                        ),
     987                        array(
     988                                "%'#5s",
     989                                'foo',
     990                                false,
     991                                '##foo',
     992                        ),
     993                        array(
     994                                '%.3s',
     995                                'foobar',
     996                                false,
     997                                'foo',
     998                        ),
     999                        array(
     1000                                '%.3f',
     1001                                5.123456,
     1002                                false,
     1003                                '5.123',
     1004                        ),
     1005                        array(
     1006                                '%.3f',
     1007                                5.12,
     1008                                false,
     1009                                '5.120',
     1010                        ),
     1011                        array(
     1012                                '%s',
     1013                                ' %s ',
     1014                                false,
     1015                                "' {$wpdb->placeholder_escape()}s '",
     1016                        ),
     1017                        array(
     1018                                '%1$s',
     1019                                ' %s ',
     1020                                false,
     1021                                " {$wpdb->placeholder_escape()}s ",
     1022                        ),
     1023                        array(
     1024                                '%1$s',
     1025                                ' %1$s ',
     1026                                false,
     1027                                " {$wpdb->placeholder_escape()}1\$s ",
     1028                        ),
     1029                        array(
     1030                                '%d %1$d %%% %',
     1031                                1,
     1032                                true,
     1033                                "1 1 {$wpdb->placeholder_escape()}{$wpdb->placeholder_escape()} {$wpdb->placeholder_escape()}",
     1034                        ),
     1035                        array(
     1036                                '%d %2$s',
     1037                                array( 1, 'hello' ),
     1038                                false,
     1039                                "1 hello",
     1040                        ),
     1041                        array(
     1042                                "'%s'",
     1043                                'hello',
     1044                                false,
     1045                                "'hello'",
     1046                        ),
     1047                        array(
     1048                                '"%s"',
     1049                                'hello',
     1050                                false,
     1051                                "'hello'",
     1052                        ),
     1053                        array(
     1054                                "%s '%1\$s'",
     1055                                'hello',
     1056                                true,
     1057                                "'hello' 'hello'",
     1058                        ),
     1059                        array(
     1060                                "%s '%1\$s'",
     1061                                'hello',
     1062                                true,
     1063                                "'hello' 'hello'",
     1064                        ),
     1065                        array(
     1066                                '%s "%1$s"',
     1067                                'hello',
     1068                                true,
     1069                                "'hello' \"hello\"",
     1070                        ),
     1071                        array(
     1072                                "%%s %%'%1\$s'",
     1073                                'hello',
     1074                                false,
     1075                                "{$wpdb->placeholder_escape()}s {$wpdb->placeholder_escape()}'hello'",
     1076                        ),
     1077                        array(
     1078                                '%%s %%"%1$s"',
     1079                                'hello',
     1080                                false,
     1081                                "{$wpdb->placeholder_escape()}s {$wpdb->placeholder_escape()}\"hello\"",
     1082                        ),
     1083                        array(
     1084                                '%s',
     1085                                ' %  s ',
     1086                                false,
     1087                                "' {$wpdb->placeholder_escape()}  s '",
     1088                        ),
     1089                        array(
     1090                                '%%f %%"%1$f"',
     1091                                3,
     1092                                false,
     1093                                "{$wpdb->placeholder_escape()}f {$wpdb->placeholder_escape()}\"3.000000\"",
     1094                        ),
     1095                        array(
     1096                                'WHERE second=\'%2$s\' AND first=\'%1$s\'',
     1097                                array( 'first arg', 'second arg' ),
     1098                                false,
     1099                                "WHERE second='second arg' AND first='first arg'",
     1100                        ),
     1101                        array(
     1102                                'WHERE second=%2$d AND first=%1$d',
     1103                                array( 1, 2 ),
     1104                                false,
     1105                                "WHERE second=2 AND first=1",
     1106                        ),
     1107                        array(
     1108                                "'%'%%s",
     1109                                'hello',
     1110                                true,
     1111                                "'{$wpdb->placeholder_escape()}'{$wpdb->placeholder_escape()}s",
     1112                        ),
     1113                        array(
     1114                                "'%'%%s%s",
     1115                                'hello',
     1116                                false,
     1117                                "'{$wpdb->placeholder_escape()}'{$wpdb->placeholder_escape()}s'hello'",
     1118                        ),
     1119                        array(
     1120                                "'%'%%s %s",
     1121                                'hello',
     1122                                false,
     1123                                "'{$wpdb->placeholder_escape()}'{$wpdb->placeholder_escape()}s 'hello'",
     1124                        ),
     1125                        array(
     1126                                "'%-'#5s' '%'#-+-5s'",
     1127                                array( 'hello', 'foo' ),
     1128                                false,
     1129                                "'hello' 'foo##'",
     1130                        ),
     1131                );
     1132        }
     1133
     1134        /**
     1135         * @dataProvider data_escape_and_prepare
     1136         */
     1137        function test_escape_and_prepare( $escape, $sql, $values, $incorrect_usage, $expected ) {
     1138                global $wpdb;
     1139
     1140                if ( $incorrect_usage ) {
     1141                        $this->setExpectedIncorrectUsage( 'wpdb::prepare' );
     1142                }
     1143
     1144                $escape = esc_sql( $escape );
     1145
     1146                $sql = str_replace( '{ESCAPE}', $escape, $sql );
     1147
     1148                $actual = $wpdb->prepare( $sql, $values );
     1149
     1150                $this->assertEquals( $expected, $actual );
     1151        }
     1152
     1153        function data_escape_and_prepare() {
     1154                global $wpdb;
     1155                return array(
     1156                        array(
     1157                                '%s',                                  // String to pass through esc_url()
     1158                                ' {ESCAPE} ',                          // Query to insert the output of esc_url() into, replacing "{ESCAPE}"
     1159                                'foo',                                 // Data to send to prepare()
     1160                                true,                                  // Whether to expect an incorrect usage error or not
     1161                                " {$wpdb->placeholder_escape()}s ",    // Expected output
     1162                        ),
     1163                        array(
     1164                                'foo%sbar',
     1165                                "SELECT * FROM bar WHERE foo='{ESCAPE}' OR baz=%s",
     1166                                array( ' SQLi -- -', 'pewpewpew' ),
     1167                                true,
     1168                                null,
     1169                        ),
     1170                        array(
     1171                                '%s',
     1172                                ' %s {ESCAPE} ',
     1173                                'foo',
     1174                                false,
     1175                                " 'foo' {$wpdb->placeholder_escape()}s ",
     1176                        ),
     1177                );
     1178        }
     1179
     1180        /**
     1181         * @expectedIncorrectUsage wpdb::prepare
     1182         */
     1183        function test_double_prepare() {
     1184                global $wpdb;
     1185
     1186                $part = $wpdb->prepare( ' AND meta_value = %s', ' %s ' );
     1187                $this->assertNotContains( '%s', $part );
     1188                $query = $wpdb->prepare( 'SELECT * FROM {$wpdb->postmeta} WHERE meta_key = %s $part', array( 'foo', 'bar' ) );
     1189                $this->assertNull( $query );
     1190        }
     1191
     1192        function test_prepare_numeric_placeholders_float_args() {
     1193                global $wpdb;
     1194
     1195                $actual = $wpdb->prepare(
     1196                        'WHERE second=%2$f AND first=%1$f',
     1197                        1.1,
     1198                        2.2
     1199                );
     1200
     1201                /* Floats can be right padded, need to assert differently */
     1202                $this->assertContains( ' first=1.1', $actual );
     1203                $this->assertContains( ' second=2.2', $actual );
     1204        }
     1205
     1206        function test_prepare_numeric_placeholders_float_array() {
     1207                global $wpdb;
     1208
     1209                $actual = $wpdb->prepare(
     1210                        'WHERE second=%2$f AND first=%1$f',
     1211                        array( 1.1, 2.2 )
     1212                );
     1213
     1214                /* Floats can be right padded, need to assert differently */
     1215                $this->assertContains( ' first=1.1', $actual );
     1216                $this->assertContains( ' second=2.2', $actual );
     1217        }
     1218
     1219        function test_query_unescapes_placeholders() {
     1220                global $wpdb;
     1221
     1222                $value = ' %s ';
     1223
     1224                $wpdb->query( "CREATE TABLE {$wpdb->prefix}test_placeholder( a VARCHAR(100) );" );
     1225                $sql = $wpdb->prepare( "INSERT INTO {$wpdb->prefix}test_placeholder VALUES(%s)", $value );
     1226                $wpdb->query( $sql );
     1227
     1228                $actual = $wpdb->get_var( "SELECT a FROM {$wpdb->prefix}test_placeholder" );
     1229
     1230                $wpdb->query( "DROP TABLE {$wpdb->prefix}test_placeholder" );
     1231
     1232                $this->assertNotContains( '%s', $sql );
     1233                $this->assertEquals( $value, $actual );
     1234        }
     1235
     1236        function test_esc_sql_with_unsupported_placeholder_type() {
     1237                global $wpdb;
     1238
     1239                $sql = $wpdb->prepare( ' %s %1$c ', 'foo' );
     1240                $sql = $wpdb->prepare( " $sql %s ", 'foo' );
     1241
     1242                $this->assertEquals( "  'foo' {$wpdb->placeholder_escape()}1\$c  'foo' ", $sql );
    8591243        }
    8601244}
  • branches/4.2/wp-tests-config-sample.php

    r25571 r42063  
    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.