Make WordPress Core

Changeset 42064


Ignore:
Timestamp:
10/31/2017 12:52:03 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.1
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • branches/4.1

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

    r33557 r42064  
    41774177        $page_path = str_replace('%20', ' ', $page_path);
    41784178        $parts = explode( '/', trim( $page_path, '/' ) );
    4179         $parts = esc_sql( $parts );
    41804179        $parts = array_map( 'sanitize_title_for_query', $parts );
    4181 
    4182         $in_string = "'" . implode( "','", $parts ) . "'";
     4180        $escaped_parts = esc_sql( $parts );
     4181
     4182        $in_string = "'" . implode( "','", $escaped_parts ) . "'";
    41834183
    41844184        if ( is_array( $post_type ) ) {
  • branches/4.1/src/wp-includes/wp-db.php

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

    r40246 r42064  
    255255                        $this->fail( "Unexpected incorrect usage notice for $unexpected" );
    256256                }
     257        }
     258
     259        /**
     260         * Declare an expected `_doing_it_wrong()` call from within a test.
     261         *
     262         * @since 4.2.0
     263         *
     264         * @param string $deprecated Name of the function, method, or class that appears in the first argument of the
     265         *                           source `_doing_it_wrong()` call.
     266         */
     267        public function setExpectedIncorrectUsage( $doing_it_wrong ) {
     268                array_push( $this->expected_doing_it_wrong, $doing_it_wrong );
    257269        }
    258270
  • branches/4.1/tests/phpunit/tests/date/query.php

    r31396 r42064  
    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.1/tests/phpunit/tests/db.php

    r41504 r42064  
    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() {
     
    845915
    846916        /**
    847          *
    848          */
    849         function test_prepare_with_unescaped_percents() {
    850                 global $wpdb;
    851 
    852                 $sql = $wpdb->prepare( '%d %1$d %%% %', 1 );
    853                 $this->assertEquals( '1 %1$d %% %', $sql );
     917         * @dataProvider data_prepare_with_placeholders
     918         */
     919        function test_prepare_with_placeholders_and_individual_args( $sql, $values, $incorrect_usage, $expected) {
     920                global $wpdb;
     921
     922                if ( $incorrect_usage ) {
     923                        $this->setExpectedIncorrectUsage( 'wpdb::prepare' );
     924                }
     925
     926                if ( ! is_array( $values ) ) {
     927                        $values = array( $values );
     928                }
     929
     930                array_unshift( $values, $sql );
     931
     932                $sql = call_user_func_array( array( $wpdb, 'prepare' ), $values );
     933                $this->assertEquals( $expected, $sql );
     934        }
     935
     936        /**
     937         * @dataProvider data_prepare_with_placeholders
     938         */
     939        function test_prepare_with_placeholders_and_array_args( $sql, $values, $incorrect_usage, $expected) {
     940                global $wpdb;
     941
     942                if ( $incorrect_usage ) {
     943                        $this->setExpectedIncorrectUsage( 'wpdb::prepare' );
     944                }
     945
     946                if ( ! is_array( $values ) ) {
     947                        $values = array( $values );
     948                }
     949
     950                $sql = call_user_func_array( array( $wpdb, 'prepare' ), array( $sql, $values ) );
     951                $this->assertEquals( $expected, $sql );
     952        }
     953
     954        function data_prepare_with_placeholders() {
     955                global $wpdb;
     956
     957                return array(
     958                        array(
     959                                '%5s',   // SQL to prepare
     960                                'foo',   // Value to insert in the SQL
     961                                false,   // Whether to expect an incorrect usage error or not
     962                                '  foo', // Expected output
     963                        ),
     964                        array(
     965                                '%1$d %%% % %%1$d%% %%%1$d%%',
     966                                1,
     967                                true,
     968                                "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()}",
     969                        ),
     970                        array(
     971                                '%-5s',
     972                                'foo',
     973                                false,
     974                                'foo  ',
     975                        ),
     976                        array(
     977                                '%05s',
     978                                'foo',
     979                                false,
     980                                '00foo',
     981                        ),
     982                        array(
     983                                "%'#5s",
     984                                'foo',
     985                                false,
     986                                '##foo',
     987                        ),
     988                        array(
     989                                '%.3s',
     990                                'foobar',
     991                                false,
     992                                'foo',
     993                        ),
     994                        array(
     995                                '%.3f',
     996                                5.123456,
     997                                false,
     998                                '5.123',
     999                        ),
     1000                        array(
     1001                                '%.3f',
     1002                                5.12,
     1003                                false,
     1004                                '5.120',
     1005                        ),
     1006                        array(
     1007                                '%s',
     1008                                ' %s ',
     1009                                false,
     1010                                "' {$wpdb->placeholder_escape()}s '",
     1011                        ),
     1012                        array(
     1013                                '%1$s',
     1014                                ' %s ',
     1015                                false,
     1016                                " {$wpdb->placeholder_escape()}s ",
     1017                        ),
     1018                        array(
     1019                                '%1$s',
     1020                                ' %1$s ',
     1021                                false,
     1022                                " {$wpdb->placeholder_escape()}1\$s ",
     1023                        ),
     1024                        array(
     1025                                '%d %1$d %%% %',
     1026                                1,
     1027                                true,
     1028                                "1 1 {$wpdb->placeholder_escape()}{$wpdb->placeholder_escape()} {$wpdb->placeholder_escape()}",
     1029                        ),
     1030                        array(
     1031                                '%d %2$s',
     1032                                array( 1, 'hello' ),
     1033                                false,
     1034                                "1 hello",
     1035                        ),
     1036                        array(
     1037                                "'%s'",
     1038                                'hello',
     1039                                false,
     1040                                "'hello'",
     1041                        ),
     1042                        array(
     1043                                '"%s"',
     1044                                'hello',
     1045                                false,
     1046                                "'hello'",
     1047                        ),
     1048                        array(
     1049                                "%s '%1\$s'",
     1050                                'hello',
     1051                                true,
     1052                                "'hello' 'hello'",
     1053                        ),
     1054                        array(
     1055                                "%s '%1\$s'",
     1056                                'hello',
     1057                                true,
     1058                                "'hello' 'hello'",
     1059                        ),
     1060                        array(
     1061                                '%s "%1$s"',
     1062                                'hello',
     1063                                true,
     1064                                "'hello' \"hello\"",
     1065                        ),
     1066                        array(
     1067                                "%%s %%'%1\$s'",
     1068                                'hello',
     1069                                false,
     1070                                "{$wpdb->placeholder_escape()}s {$wpdb->placeholder_escape()}'hello'",
     1071                        ),
     1072                        array(
     1073                                '%%s %%"%1$s"',
     1074                                'hello',
     1075                                false,
     1076                                "{$wpdb->placeholder_escape()}s {$wpdb->placeholder_escape()}\"hello\"",
     1077                        ),
     1078                        array(
     1079                                '%s',
     1080                                ' %  s ',
     1081                                false,
     1082                                "' {$wpdb->placeholder_escape()}  s '",
     1083                        ),
     1084                        array(
     1085                                '%%f %%"%1$f"',
     1086                                3,
     1087                                false,
     1088                                "{$wpdb->placeholder_escape()}f {$wpdb->placeholder_escape()}\"3.000000\"",
     1089                        ),
     1090                        array(
     1091                                'WHERE second=\'%2$s\' AND first=\'%1$s\'',
     1092                                array( 'first arg', 'second arg' ),
     1093                                false,
     1094                                "WHERE second='second arg' AND first='first arg'",
     1095                        ),
     1096                        array(
     1097                                'WHERE second=%2$d AND first=%1$d',
     1098                                array( 1, 2 ),
     1099                                false,
     1100                                "WHERE second=2 AND first=1",
     1101                        ),
     1102                        array(
     1103                                "'%'%%s",
     1104                                'hello',
     1105                                true,
     1106                                "'{$wpdb->placeholder_escape()}'{$wpdb->placeholder_escape()}s",
     1107                        ),
     1108                        array(
     1109                                "'%'%%s%s",
     1110                                'hello',
     1111                                false,
     1112                                "'{$wpdb->placeholder_escape()}'{$wpdb->placeholder_escape()}s'hello'",
     1113                        ),
     1114                        array(
     1115                                "'%'%%s %s",
     1116                                'hello',
     1117                                false,
     1118                                "'{$wpdb->placeholder_escape()}'{$wpdb->placeholder_escape()}s 'hello'",
     1119                        ),
     1120                        array(
     1121                                "'%-'#5s' '%'#-+-5s'",
     1122                                array( 'hello', 'foo' ),
     1123                                false,
     1124                                "'hello' 'foo##'",
     1125                        ),
     1126                );
     1127        }
     1128
     1129        /**
     1130         * @dataProvider data_escape_and_prepare
     1131         */
     1132        function test_escape_and_prepare( $escape, $sql, $values, $incorrect_usage, $expected ) {
     1133                global $wpdb;
     1134
     1135                if ( $incorrect_usage ) {
     1136                        $this->setExpectedIncorrectUsage( 'wpdb::prepare' );
     1137                }
     1138
     1139                $escape = esc_sql( $escape );
     1140
     1141                $sql = str_replace( '{ESCAPE}', $escape, $sql );
     1142
     1143                $actual = $wpdb->prepare( $sql, $values );
     1144
     1145                $this->assertEquals( $expected, $actual );
     1146        }
     1147
     1148        function data_escape_and_prepare() {
     1149                global $wpdb;
     1150                return array(
     1151                        array(
     1152                                '%s',                                  // String to pass through esc_url()
     1153                                ' {ESCAPE} ',                          // Query to insert the output of esc_url() into, replacing "{ESCAPE}"
     1154                                'foo',                                 // Data to send to prepare()
     1155                                true,                                  // Whether to expect an incorrect usage error or not
     1156                                " {$wpdb->placeholder_escape()}s ",    // Expected output
     1157                        ),
     1158                        array(
     1159                                'foo%sbar',
     1160                                "SELECT * FROM bar WHERE foo='{ESCAPE}' OR baz=%s",
     1161                                array( ' SQLi -- -', 'pewpewpew' ),
     1162                                true,
     1163                                null,
     1164                        ),
     1165                        array(
     1166                                '%s',
     1167                                ' %s {ESCAPE} ',
     1168                                'foo',
     1169                                false,
     1170                                " 'foo' {$wpdb->placeholder_escape()}s ",
     1171                        ),
     1172                );
     1173        }
     1174
     1175        /**
     1176         * @expectedIncorrectUsage wpdb::prepare
     1177         */
     1178        function test_double_prepare() {
     1179                global $wpdb;
     1180
     1181                $part = $wpdb->prepare( ' AND meta_value = %s', ' %s ' );
     1182                $this->assertNotContains( '%s', $part );
     1183                $query = $wpdb->prepare( 'SELECT * FROM {$wpdb->postmeta} WHERE meta_key = %s $part', array( 'foo', 'bar' ) );
     1184                $this->assertNull( $query );
     1185        }
     1186
     1187        function test_prepare_numeric_placeholders_float_args() {
     1188                global $wpdb;
     1189
     1190                $actual = $wpdb->prepare(
     1191                        'WHERE second=%2$f AND first=%1$f',
     1192                        1.1,
     1193                        2.2
     1194                );
     1195
     1196                /* Floats can be right padded, need to assert differently */
     1197                $this->assertContains( ' first=1.1', $actual );
     1198                $this->assertContains( ' second=2.2', $actual );
     1199        }
     1200
     1201        function test_prepare_numeric_placeholders_float_array() {
     1202                global $wpdb;
     1203
     1204                $actual = $wpdb->prepare(
     1205                        'WHERE second=%2$f AND first=%1$f',
     1206                        array( 1.1, 2.2 )
     1207                );
     1208
     1209                /* Floats can be right padded, need to assert differently */
     1210                $this->assertContains( ' first=1.1', $actual );
     1211                $this->assertContains( ' second=2.2', $actual );
     1212        }
     1213
     1214        function test_query_unescapes_placeholders() {
     1215                global $wpdb;
     1216
     1217                $value = ' %s ';
     1218
     1219                $wpdb->query( "CREATE TABLE {$wpdb->prefix}test_placeholder( a VARCHAR(100) );" );
     1220                $sql = $wpdb->prepare( "INSERT INTO {$wpdb->prefix}test_placeholder VALUES(%s)", $value );
     1221                $wpdb->query( $sql );
     1222
     1223                $actual = $wpdb->get_var( "SELECT a FROM {$wpdb->prefix}test_placeholder" );
     1224
     1225                $wpdb->query( "DROP TABLE {$wpdb->prefix}test_placeholder" );
     1226
     1227                $this->assertNotContains( '%s', $sql );
     1228                $this->assertEquals( $value, $actual );
     1229        }
     1230
     1231        function test_esc_sql_with_unsupported_placeholder_type() {
     1232                global $wpdb;
     1233
     1234                $sql = $wpdb->prepare( ' %s %1$c ', 'foo' );
     1235                $sql = $wpdb->prepare( " $sql %s ", 'foo' );
     1236
     1237                $this->assertEquals( "  'foo' {$wpdb->placeholder_escape()}1\$c  'foo' ", $sql );
    8541238        }
    8551239}
  • branches/4.1/wp-tests-config-sample.php

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