Make WordPress Core

Changeset 42065


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

Location:
branches/4.0
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • branches/4.0

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

    r33558 r42065  
    41834183        $page_path = str_replace('%20', ' ', $page_path);
    41844184        $parts = explode( '/', trim( $page_path, '/' ) );
    4185         $parts = esc_sql( $parts );
    41864185        $parts = array_map( 'sanitize_title_for_query', $parts );
    4187 
    4188         $in_string = "'" . implode( "','", $parts ) . "'";
     4186        $escaped_parts = esc_sql( $parts );
     4187
     4188        $in_string = "'" . implode( "','", $escaped_parts ) . "'";
    41894189
    41904190        if ( is_array( $post_type ) ) {
  • branches/4.0/src/wp-includes/wp-db.php

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

    r41085 r42065  
    205205                        $this->fail( "Unexpected incorrect usage notice for $unexpected" );
    206206                }
     207        }
     208
     209        /**
     210         * Declare an expected `_doing_it_wrong()` call from within a test.
     211         *
     212         * @since 4.2.0
     213         *
     214         * @param string $deprecated Name of the function, method, or class that appears in the first argument of the
     215         *                           source `_doing_it_wrong()` call.
     216         */
     217        public function setExpectedIncorrectUsage( $doing_it_wrong ) {
     218                array_push( $this->expected_doing_it_wrong, $doing_it_wrong );
    207219        }
    208220
  • branches/4.0/tests/phpunit/tests/db.php

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

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