Make WordPress Core


Ignore:
Timestamp:
06/28/2022 11:25:21 AM (4 years ago)
Author:
SergeyBiryukov
Message:

Docs: Adjust some DocBlocks in wpdb per the documentation standards.

Includes:

  • Wrapping long single-line comments to multi-line for better readability.
  • Formatting code blocks to display correctly on the Code Reference.
  • Other minor edits for consistency.

This applies to:

  • wpdb::$allow_unsafe_unquoted_parameters
  • wpdb::escape_identifier()
  • wpdb::_escape_identifier_value()
  • wpdb::prepare()
  • wpdb::has_cap()

Follow-up to [53575].

See #52506, #55646.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/wp-db.php

    r53575 r53584  
    646646
    647647        /**
    648          * Backwards compatibility, where wpdb::prepare() has not quoted formatted/argnum placeholders.
     648         * Backward compatibility, where wpdb::prepare() has not quoted formatted/argnum placeholders.
    649649         *
    650650         * Historically this could be used for table/field names, or for some string formatting, e.g.
    651          *   $wpdb->prepare( 'WHERE `%1s` = "%1s something %1s" OR %1$s = "%-10s"', 'field_1', 'a', 'b', 'c' );
     651         *
     652         *     $wpdb->prepare( 'WHERE `%1s` = "%1s something %1s" OR %1$s = "%-10s"', 'field_1', 'a', 'b', 'c' );
    652653         *
    653654         * But it's risky, e.g. forgetting to add quotes, resulting in SQL Injection vulnerabilities:
    654          *   $wpdb->prepare( 'WHERE (id = %1s) OR (id = %2$s)', $_GET['id'], $_GET['id'] ); // ?id=id
     655         *
     656         *     $wpdb->prepare( 'WHERE (id = %1s) OR (id = %2$s)', $_GET['id'], $_GET['id'] ); // ?id=id
    655657         *
    656658         * This feature is preserved while plugin authors update their code to use safer approaches:
    657          *   $wpdb->prepare( 'WHERE %1s = %s', $_GET['key'], $_GET['value'] );
    658          *   $wpdb->prepare( 'WHERE %i  = %s', $_GET['key'], $_GET['value'] );
     659         *
     660         *     $wpdb->prepare( 'WHERE %1s = %s', $_GET['key'], $_GET['value'] );
     661         *     $wpdb->prepare( 'WHERE %i  = %s', $_GET['key'], $_GET['value'] );
    659662         *
    660663         * While changing to false will be fine for queries not using formatted/argnum placeholders,
    661664         * any remaining cases are most likely going to result in SQL errors (good, in a way):
    662          *   $wpdb->prepare( 'WHERE %1s = "%-10s"', 'my_field', 'my_value' );
     665         *
     666         *     $wpdb->prepare( 'WHERE %1s = "%-10s"', 'my_field', 'my_value' );
    663667         *     true  = WHERE my_field = "my_value  "
    664668         *     false = WHERE 'my_field' = "'my_value  '"
     669         *
    665670         * But there may be some queries that result in an SQL Injection vulnerability:
    666          *   $wpdb->prepare( 'WHERE id = %1s', $_GET['id'] ); // ?id=id
    667          * So there may need to be a `_doing_it_wrong()` phase, after we know everyone can use Identifier
    668          * placeholders (%i), but before this feature is disabled or removed.
     671         *
     672         *     $wpdb->prepare( 'WHERE id = %1s', $_GET['id'] ); // ?id=id
     673         *
     674         * So there may need to be a `_doing_it_wrong()` phase, after we know everyone can use
     675         * identifier placeholders (%i), but before this feature is disabled or removed.
    669676         *
    670677         * @since 6.1.0
     
    13771384
    13781385        /**
    1379          * Escapes an identifier for a MySQL database (e.g. table/field names).
     1386         * Escapes an identifier for a MySQL database, e.g. table/field names.
    13801387         *
    13811388         * @since 6.1.0
    13821389         *
    13831390         * @param string $identifier Identifier to escape.
    1384          * @return string Escaped Identifier
     1391         * @return string Escaped identifier.
    13851392         */
    13861393        public function escape_identifier( $identifier ) {
     
    13891396
    13901397        /**
    1391          * Escapes an identifier value.
    1392          *
    13931398         * Escapes an identifier value without adding the surrounding quotes.
    13941399         *
    1395          * - Permitted characters in quoted identifiers include the full Unicode Basic Multilingual Plane (BMP), except U+0000
    1396          * - To quote the identifier itself, then you need to double the character, e.g. `a``b`
    1397          *
    1398          * @link https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
     1400         * - Permitted characters in quoted identifiers include the full Unicode
     1401         *   Basic Multilingual Plane (BMP), except U+0000.
     1402         * - To quote the identifier itself, you need to double the character, e.g. `a``b`.
     1403         *
    13991404         * @since 6.1.0
    14001405         * @access private
    14011406         *
     1407         * @link https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
     1408         *
    14021409         * @param string $identifier Identifier to escape.
    1403          * @return string Escaped Identifier
     1410         * @return string Escaped identifier.
    14041411         */
    14051412        private function _escape_identifier_value( $identifier ) {
     
    14341441         * Examples:
    14351442         *
    1436          *     $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", array( 'foo', 1337, '%bar' ) );
    1437          *     $wpdb->prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
     1443         *     $wpdb->prepare(
     1444         *         "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s",
     1445         *         array( 'foo', 1337, '%bar' )
     1446         *     );
     1447         *
     1448         *     $wpdb->prepare(
     1449         *         "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s",
     1450         *         'foo'
     1451         *     );
    14381452         *
    14391453         * @since 2.3.0
     
    14411455         *              by updating the function signature. The second parameter was changed
    14421456         *              from `$args` to `...$args`.
    1443          * @since 6.1.0 Added '%i' for Identifiers, e.g. table or field names.
    1444          *              Check support via `wpdb::has_cap( 'identifier_placeholders' )`
    1445          *              This preserves compatibility with sprinf, as the C version uses %d and $i
    1446          *              as a signed integer, whereas PHP only supports %d.
     1457         * @since 6.1.0 Added `%i` for identifiers, e.g. table or field names.
     1458         *              Check support via `wpdb::has_cap( 'identifier_placeholders' )`.
     1459         *              This preserves compatibility with sprintf(), as the C version uses
     1460         *              `%d` and `$i` as a signed integer, whereas PHP only supports `%d`.
    14471461         *
    14481462         * @link https://www.php.net/sprintf Description of syntax.
     
    14791493                 * Specify the formatting allowed in a placeholder. The following are allowed:
    14801494                 *
    1481                  * - Sign specifier. eg, $+d
    1482                  * - Numbered placeholders. eg, %1$s
    1483                  * - Padding specifier, including custom padding characters. eg, %05s, %'#5s
    1484                  * - Alignment specifier. eg, %05-s
    1485                  * - Precision specifier. eg, %.2f
     1495                 * - Sign specifier, e.g. $+d
     1496                 * - Numbered placeholders, e.g. %1$s
     1497                 * - Padding specifier, including custom padding characters, e.g. %05s, %'#5s
     1498                 * - Alignment specifier, e.g. %05-s
     1499                 * - Precision specifier, e.g. %.2f
    14861500                 */
    14871501                $allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0|\'.)?[-+0-9]*(?:\.[0-9]+)?';
    14881502
    14891503                /*
    1490                  * If a %s placeholder already has quotes around it, removing the existing quotes and re-inserting them
    1491                  * ensures the quotes are consistent.
     1504                 * If a %s placeholder already has quotes around it, removing the existing quotes
     1505                 * and re-inserting them ensures the quotes are consistent.
    14921506                 *
    1493                  * For backward compatibility, this is only applied to %s, and not to placeholders like %1$s, which are frequently
    1494                  * used in the middle of longer strings, or as table name placeholders.
     1507                 * For backward compatibility, this is only applied to %s, and not to placeholders like %1$s,
     1508                 * which are frequently used in the middle of longer strings, or as table name placeholders.
    14951509                 */
    14961510                $query = str_replace( "'%s'", '%s', $query ); // Strip any existing single quotes.
    14971511                $query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes.
    14981512
    1499                 $query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdfFi]))/", '%%\\1', $query ); // Escape any unescaped percents (i.e. anything unrecognised).
     1513                // Escape any unescaped percents (i.e. anything unrecognised).
     1514                $query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdfFi]))/", '%%\\1', $query );
    15001515
    15011516                // Extract placeholders from the query.
     
    15031518
    15041519                $split_query_count = count( $split_query );
    1505                 $placeholder_count = ( ( $split_query_count - 1 ) / 3 ); // Split always returns with 1 value before the first placeholder (even with $query = "%s"), then 3 additional values per placeholder.
    1506 
    1507                 // If args were passed as an array (as in vsprintf), move them up.
     1520                /*
     1521                 * Split always returns with 1 value before the first placeholder (even with $query = "%s"),
     1522                 * then 3 additional values per placeholder.
     1523                 */
     1524                $placeholder_count = ( ( $split_query_count - 1 ) / 3 );
     1525
     1526                // If args were passed as an array, as in vsprintf(), move them up.
    15081527                $passed_as_array = ( isset( $args[0] ) && is_array( $args[0] ) && 1 === count( $args ) );
    15091528                if ( $passed_as_array ) {
     
    15121531
    15131532                $new_query       = '';
    1514                 $key             = 2; // keys 0 and 1 in $split_query contain values before the first placeholder.
     1533                $key             = 2; // Keys 0 and 1 in $split_query contain values before the first placeholder.
    15151534                $arg_id          = 0;
    15161535                $arg_identifiers = array();
    15171536                $arg_strings     = array();
     1537
    15181538                while ( $key < $split_query_count ) {
    15191539                        $placeholder = $split_query[ $key ];
     
    15291549                        if ( 'i' === $type ) {
    15301550                                $placeholder = '`%' . $format . 's`';
    1531                                 $argnum_pos  = strpos( $format, '$' ); // Using a simple strpos() due to previous checking (e.g. $allowed_format).
     1551                                // Using a simple strpos() due to previous checking (e.g. $allowed_format).
     1552                                $argnum_pos = strpos( $format, '$' );
     1553
    15321554                                if ( false !== $argnum_pos ) {
    1533                                         $arg_identifiers[] = ( intval( substr( $format, 0, $argnum_pos ) ) - 1 ); // sprintf argnum starts at 1, $arg_id from 0.
     1555                                        // sprintf() argnum starts at 1, $arg_id from 0.
     1556                                        $arg_identifiers[] = ( intval( substr( $format, 0, $argnum_pos ) ) - 1 );
    15341557                                } else {
    15351558                                        $arg_identifiers[] = $arg_id;
    15361559                                }
    1537                         } elseif ( 'd' !== $type && 'F' !== $type ) { // i.e. ('s' === $type), where 'd' and 'F' keeps $placeholder unchanged, and we ensure string escaping is used as a safe default (e.g. even if 'x').
     1560                        } elseif ( 'd' !== $type && 'F' !== $type ) {
     1561                                /*
     1562                                 * i.e. ( 's' === $type ), where 'd' and 'F' keeps $placeholder unchanged,
     1563                                 * and we ensure string escaping is used as a safe default (e.g. even if 'x').
     1564                                 */
    15381565                                $argnum_pos = strpos( $format, '$' );
     1566
    15391567                                if ( false !== $argnum_pos ) {
    15401568                                        $arg_strings[] = ( intval( substr( $format, 0, $argnum_pos ) ) - 1 );
    15411569                                }
    1542                                 if ( true !== $this->allow_unsafe_unquoted_parameters || '' === $format ) { // Unquoted strings for backwards compatibility (dangerous).
     1570
     1571                                // Unquoted strings for backward compatibility (dangerous).
     1572                                if ( true !== $this->allow_unsafe_unquoted_parameters || '' === $format ) {
    15431573                                        $placeholder = "'%" . $format . "s'";
    15441574                                }
    15451575                        }
    15461576
    1547                         $new_query .= $split_query[ $key - 2 ] . $split_query[ $key - 1 ] . $placeholder; // Glue (-2), any leading characters (-1), then the new $placeholder.
     1577                        // Glue (-2), any leading characters (-1), then the new $placeholder.
     1578                        $new_query .= $split_query[ $key - 2 ] . $split_query[ $key - 1 ] . $placeholder;
    15481579
    15491580                        $key += 3;
    15501581                        $arg_id++;
    15511582                }
    1552                 $query = $new_query . $split_query[ $key - 2 ]; // Replace $query; and add remaining $query characters, or index 0 if there were no placeholders.
     1583
     1584                // Replace $query; and add remaining $query characters, or index 0 if there were no placeholders.
     1585                $query = $new_query . $split_query[ $key - 2 ];
    15531586
    15541587                $dual_use = array_intersect( $arg_identifiers, $arg_strings );
     1588
    15551589                if ( count( $dual_use ) ) {
    15561590                        wp_load_translations_early();
     
    15721606                if ( $args_count !== $placeholder_count ) {
    15731607                        if ( 1 === $placeholder_count && $passed_as_array ) {
    1574                                 // If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
     1608                                /*
     1609                                 * If the passed query only expected one argument,
     1610                                 * but the wrong number of arguments was sent as an array, bail.
     1611                                 */
    15751612                                wp_load_translations_early();
    15761613                                _doing_it_wrong(
     
    15831620                        } else {
    15841621                                /*
    1585                                  * If we don't have the right number of placeholders, but they were passed as individual arguments,
     1622                                 * If we don't have the right number of placeholders,
     1623                                 * but they were passed as individual arguments,
    15861624                                 * or we were expecting multiple arguments in an array, throw a warning.
    15871625                                 */
     
    16041642                                if ( $args_count < $placeholder_count ) {
    16051643                                        $max_numbered_placeholder = 0;
     1644
    16061645                                        for ( $i = 2, $l = $split_query_count; $i < $l; $i += 3 ) {
    1607                                                 $argnum = intval( substr( $split_query[ $i ], 1 ) ); // Assume a leading number is for a numbered placeholder, e.g. '%3$s'.
     1646                                                // Assume a leading number is for a numbered placeholder, e.g. '%3$s'.
     1647                                                $argnum = intval( substr( $split_query[ $i ], 1 ) );
     1648
    16081649                                                if ( $max_numbered_placeholder < $argnum ) {
    16091650                                                        $max_numbered_placeholder = $argnum;
    16101651                                                }
    16111652                                        }
     1653
    16121654                                        if ( ! $max_numbered_placeholder || $args_count < $max_numbered_placeholder ) {
    16131655                                                return '';
     
    16361678                                                '4.8.2'
    16371679                                        );
    1638                                         $value = ''; // Preserving old behaviour, where values are escaped as strings.
    1639                                 }
     1680
     1681                                        // Preserving old behavior, where values are escaped as strings.
     1682                                        $value = '';
     1683                                }
     1684
    16401685                                $args_escaped[] = $this->_real_escape( $value );
    16411686                        }
     
    38733918
    38743919        /**
    3875          * Determine DB or WPDB support for a particular feature.
    3876          *
    3877          * Capability sniffs for the database server and current version of wpdb.
    3878          *
    3879          * Database sniffs test based on the version of MySQL the site is using.
     3920         * Determines whether the database or WPDB supports a particular feature.
     3921         *
     3922         * Capability sniffs for the database server and current version of WPDB.
     3923         *
     3924         * Database sniffs are based on the version of MySQL the site is using.
    38803925         *
    38813926         * WPDB sniffs are added as new features are introduced to allow theme and plugin
     
    39273972                        case 'utf8mb4_520': // @since 4.6.0
    39283973                                return version_compare( $version, '5.6', '>=' );
    3929                         case 'identifier_placeholders': // @since 6.1.0, wpdb::prepare() supports identifiers via '%i' - e.g. table/field names.
     3974                        case 'identifier_placeholders': // @since 6.1.0
     3975                                /*
     3976                                 * As of WordPress 6.1, wpdb::prepare() supports identifiers via '%i',
     3977                                 * e.g. table/field names.
     3978                                 */
    39303979                                return true;
    39313980                }
Note: See TracChangeset for help on using the changeset viewer.