diff -r 3d4e9c994f10 -r a86126ab1dd4 wp/wp-includes/wp-db.php --- a/wp/wp-includes/wp-db.php Tue Oct 22 16:11:46 2019 +0200 +++ b/wp/wp-includes/wp-db.php Tue Dec 15 13:49:49 2020 +0100 @@ -1,6 +1,6 @@ '%d' + * Columns not listed here default to %s. Initialized during WP load. + * Keys are column names, values are format types: 'ID' => '%d'. * * @since 2.8.0 * @see wpdb::prepare() @@ -487,7 +482,7 @@ public $field_types = array(); /** - * Database table columns charset + * Database table columns charset. * * @since 2.2.0 * @var string @@ -495,7 +490,7 @@ public $charset; /** - * Database table columns collate + * Database table columns collate. * * @since 2.2.0 * @var string @@ -503,7 +498,7 @@ public $collate; /** - * Database Username + * Database Username. * * @since 2.9.0 * @var string @@ -511,7 +506,7 @@ protected $dbuser; /** - * Database Password + * Database Password. * * @since 3.1.0 * @var string @@ -519,7 +514,7 @@ protected $dbpassword; /** - * Database Name + * Database Name. * * @since 3.1.0 * @var string @@ -527,7 +522,7 @@ protected $dbname; /** - * Database Host + * Database Host. * * @since 3.1.0 * @var string @@ -535,7 +530,7 @@ protected $dbhost; /** - * Database Handle + * Database Handle. * * @since 0.71 * @var string @@ -543,7 +538,7 @@ protected $dbh; /** - * A textual description of the last query/get_row/get_var call + * A textual description of the last query/get_row/get_var call. * * @since 3.0.0 * @var string @@ -553,7 +548,7 @@ /** * Whether MySQL is used as the database engine. * - * Set in WPDB::db_connect() to true, by default. This is used when checking + * Set in wpdb::db_connect() to true, by default. This is used when checking * against the required MySQL version for WordPress. Normally, a replacement * database drop-in (db.php) will skip these checks, but setting this to true * will force the checks to occur. @@ -575,10 +570,11 @@ 'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', 'TRADITIONAL', + 'ANSI', ); /** - * Whether to use mysqli over mysql. + * Whether to use mysqli over mysql. Default false. * * @since 3.9.0 * @var bool @@ -586,7 +582,7 @@ private $use_mysqli = false; /** - * Whether we've managed to successfully connect at some point + * Whether we've managed to successfully connect at some point. * * @since 3.9.0 * @var bool @@ -594,30 +590,27 @@ private $has_connected = false; /** - * Connects to the database server and selects a database + * Connects to the database server and selects a database. * - * PHP5 style constructor for compatibility with PHP5. Does - * the actual setting up of the class properties and connection - * to the database. + * PHP5 style constructor for compatibility with PHP5. Does the actual setting up + * of the class properties and connection to the database. * - * @link https://core.trac.wordpress.org/ticket/3354 * @since 2.0.8 * - * @global string $wp_version + * @link https://core.trac.wordpress.org/ticket/3354 + * @global string $wp_version The WordPress version string. * - * @param string $dbuser MySQL database user - * @param string $dbpassword MySQL database password - * @param string $dbname MySQL database name - * @param string $dbhost MySQL database host + * @param string $dbuser MySQL database user. + * @param string $dbpassword MySQL database password. + * @param string $dbname MySQL database name. + * @param string $dbhost MySQL database host. */ public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) { - register_shutdown_function( array( $this, '__destruct' ) ); - if ( WP_DEBUG && WP_DEBUG_DISPLAY ) { $this->show_errors(); } - // Use ext/mysqli if it exists unless WP_USE_EXT_MYSQL is defined as true + // Use ext/mysqli if it exists unless WP_USE_EXT_MYSQL is defined as true. if ( function_exists( 'mysqli_connect' ) ) { $this->use_mysqli = true; @@ -640,23 +633,12 @@ } /** - * PHP5 style destructor and will run when database object is destroyed. - * - * @see wpdb::__construct() - * @since 2.0.8 - * @return true - */ - public function __destruct() { - return true; - } - - /** * Makes private properties readable for backward compatibility. * * @since 3.5.0 * - * @param string $name The private member to get, and optionally process - * @return mixed The private member + * @param string $name The private member to get, and optionally process. + * @return mixed The private member. */ public function __get( $name ) { if ( 'col_info' === $name ) { @@ -671,8 +653,8 @@ * * @since 3.5.0 * - * @param string $name The private member to set - * @param mixed $value The value to set + * @param string $name The private member to set. + * @param mixed $value The value to set. */ public function __set( $name, $value ) { $protected_members = array( @@ -691,9 +673,8 @@ * * @since 3.5.0 * - * @param string $name The private member to check - * - * @return bool If the member is set or not + * @param string $name The private member to check. + * @return bool If the member is set or not. */ public function __isset( $name ) { return isset( $this->$name ); @@ -711,7 +692,7 @@ } /** - * Set $this->charset and $this->collate + * Sets $this->charset and $this->collate. * * @since 3.1.0 */ @@ -749,7 +730,12 @@ * * @param string $charset The character set to check. * @param string $collate The collation to check. - * @return array The most appropriate character set and collation to use. + * @return array { + * The most appropriate character set and collation to use. + * + * @type string $charset Character set. + * @type string $collate Collation. + * } */ public function determine_charset( $charset, $collate ) { if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) { @@ -787,7 +773,7 @@ * * @since 3.1.0 * - * @param resource $dbh The resource given by mysql_connect + * @param resource $dbh The resource given by mysql_connect. * @param string $charset Optional. The character set. Default null. * @param string $collate Optional. The collation. Default null. */ @@ -829,14 +815,13 @@ } /** - * Change the current SQL mode, and ensure its WordPress compatibility. + * Changes the current SQL mode, and ensures its WordPress compatibility. * - * If no modes are passed, it will ensure the current MySQL server - * modes are compatible. + * If no modes are passed, it will ensure the current MySQL server modes are compatible. * * @since 3.9.0 * - * @param array $modes Optional. A list of SQL modes to set. + * @param array $modes Optional. A list of SQL modes to set. Default empty array. */ public function set_sql_mode( $modes = array() ) { if ( empty( $modes ) ) { @@ -879,7 +864,7 @@ $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes ); foreach ( $modes as $i => $mode ) { - if ( in_array( $mode, $incompatible_modes ) ) { + if ( in_array( $mode, $incompatible_modes, true ) ) { unset( $modes[ $i ] ); } } @@ -899,8 +884,9 @@ * @since 2.5.0 * * @param string $prefix Alphanumeric name for the new prefix. - * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not. - * @return string|WP_Error Old prefix or WP_Error on error + * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, + * should be updated or not. Default true. + * @return string|WP_Error Old prefix or WP_Error on error. */ public function set_prefix( $prefix, $set_table_names = true ) { @@ -939,13 +925,13 @@ } /** - * Sets blog id. + * Sets blog ID. * * @since 3.0.0 * * @param int $blog_id * @param int $network_id Optional. - * @return int previous blog id + * @return int Previous blog ID. */ public function set_blog_id( $blog_id, $network_id = 0 ) { if ( ! empty( $network_id ) ) { @@ -972,6 +958,7 @@ * Gets blog prefix. * * @since 3.0.0 + * * @param int $blog_id Optional. * @return string Blog prefix. */ @@ -980,8 +967,10 @@ if ( null === $blog_id ) { $blog_id = $this->blogid; } + $blog_id = (int) $blog_id; - if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) ) { + + if ( defined( 'MULTISITE' ) && ( 0 === $blog_id || 1 === $blog_id ) ) { return $this->base_prefix; } else { return $this->base_prefix . $blog_id . '_'; @@ -994,28 +983,30 @@ /** * Returns an array of WordPress tables. * - * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to - * override the WordPress users and usermeta tables that would otherwise - * be determined by the prefix. + * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to override the WordPress users + * and usermeta tables that would otherwise be determined by the prefix. * - * The scope argument can take one of the following: + * The $scope argument can take one of the following: * * 'all' - returns 'all' and 'global' tables. No old tables are returned. * 'blog' - returns the blog-level tables for the queried blog. - * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite. + * 'global' - returns the global tables for the installation, returning multisite tables only on multisite. * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite. * 'old' - returns tables which are deprecated. * * @since 3.0.0 + * * @uses wpdb::$tables * @uses wpdb::$old_tables * @uses wpdb::$global_tables * @uses wpdb::$ms_global_tables * - * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all. - * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog - * prefix is requested, then the custom users and usermeta tables will be mapped. - * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested. + * @param string $scope Optional. Possible values include 'all', 'global', 'ms_global', 'blog', + * or 'old' tables. Default 'all'. + * @param bool $prefix Optional. Whether to include table prefixes. If blog prefix is requested, + * then the custom users and usermeta tables will be mapped. Default true. + * @param int $blog_id Optional. The blog_id to prefix. Used only when prefix is requested. + * Defaults to wpdb::$blogid. * @return array Table names. When a prefix is requested, the key is the unprefixed table name. */ public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) { @@ -1053,7 +1044,7 @@ $base_prefix = $this->base_prefix; $global_tables = array_merge( $this->global_tables, $this->ms_global_tables ); foreach ( $tables as $k => $table ) { - if ( in_array( $table, $global_tables ) ) { + if ( in_array( $table, $global_tables, true ) ) { $tables[ $table ] = $base_prefix . $table; } else { $tables[ $table ] = $blog_prefix . $table; @@ -1076,12 +1067,12 @@ /** * Selects a database using the current database connection. * - * The database name will be changed based on the current database - * connection. On failure, the execution will bail and display an DB error. + * The database name will be changed based on the current database connection. + * On failure, the execution will bail and display a DB error. * * @since 0.71 * - * @param string $db MySQL database name + * @param string $db MySQL database name. * @param resource|null $dbh Optional link identifier. */ public function select( $db, $dbh = null ) { @@ -1102,7 +1093,7 @@ $message = '
' . sprintf(
- /* translators: %s: database name */
+ /* translators: %s: Database name. */
__( 'We were able to connect to the database server (which means your username and password is okay) but not able to select the %s database.' ),
'' . htmlspecialchars( $db, ENT_QUOTES ) . '
'
) . "
' . htmlspecialchars( $this->dbuser, ENT_QUOTES ) . '
',
'' . htmlspecialchars( $db, ENT_QUOTES ) . '
'
) . "username_%1$s
. Could that be the problem?' ),
htmlspecialchars( $db, ENT_QUOTES )
) . "' . sprintf( - /* translators: %s: support forums URL */ + /* translators: %s: Support forums URL. */ __( 'If you don’t know how to set up a database you should contact your host. If all else fails you may find help at the WordPress Support Forums.' ), __( 'https://wordpress.org/support/forums/' ) ) . "
\n"; @@ -1143,7 +1134,7 @@ * * @since 2.8.0 * @deprecated 3.6.0 Use wpdb::prepare() - * @see wpdb::prepare + * @see wpdb::prepare() * @see esc_sql() * * @param string $string @@ -1157,14 +1148,15 @@ } /** - * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string() + * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string(). + * + * @since 2.8.0 * * @see mysqli_real_escape_string() * @see mysql_real_escape_string() - * @since 2.8.0 * - * @param string $string to escape - * @return string escaped + * @param string $string String to escape. + * @return string Escaped string. */ function _real_escape( $string ) { if ( $this->dbh ) { @@ -1176,7 +1168,7 @@ } else { $class = get_class( $this ); if ( function_exists( '__' ) ) { - /* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */ + /* translators: %s: Database access abstraction class, usually wpdb or a class extending wpdb. */ _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' ); } else { _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), '3.6.0' ); @@ -1188,13 +1180,14 @@ } /** - * Escape data. Works on arrays. + * Escapes data. Works on arrays. + * + * @since 2.8.0 * * @uses wpdb::_real_escape() - * @since 2.8.0 * - * @param string|array $data - * @return string|array escaped + * @param string|array $data Data to escape. + * @return string|array Escaped data, in the same type as supplied. */ public function _escape( $data ) { if ( is_array( $data ) ) { @@ -1222,8 +1215,8 @@ * @see wpdb::prepare() * @see esc_sql() * - * @param mixed $data - * @return mixed + * @param string|array $data Data to escape. + * @return string|array Escaped data, in the same type as supplied. */ public function escape( $data ) { if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) ) { @@ -1245,13 +1238,13 @@ } /** - * Escapes content by reference for insertion into the database, for security + * Escapes content by reference for insertion into the database, for security. * * @uses wpdb::_real_escape() * * @since 2.3.0 * - * @param string $string to escape + * @param string $string String to escape. */ public function escape_by_ref( &$string ) { if ( ! is_float( $string ) ) { @@ -1260,39 +1253,49 @@ } /** - * Prepares a SQL query for safe execution. Uses sprintf()-like syntax. + * Prepares a SQL query for safe execution. * - * The following placeholders can be used in the query string: + * Uses sprintf()-like syntax. The following placeholders can be used in the query string: * %d (integer) * %f (float) * %s (string) * - * All placeholders MUST be left unquoted in the query string. A corresponding argument MUST be passed for each placeholder. + * All placeholders MUST be left unquoted in the query string. A corresponding argument + * MUST be passed for each placeholder. * - * For compatibility with old behavior, numbered or formatted string placeholders (eg, %1$s, %5s) will not have quotes - * added by this function, so should be passed with appropriate quotes around them for your usage. + * Note: There is one exception to the above: for compatibility with old behavior, + * numbered or formatted string placeholders (eg, %1$s, %5s) will not have quotes + * added by this function, so should be passed with appropriate quotes around them. * - * Literal percentage signs (%) in the query string must be written as %%. Percentage wildcards (for example, - * to use in LIKE syntax) must be passed via a substitution argument containing the complete LIKE string, these - * cannot be inserted directly in the query string. Also see wpdb::esc_like(). + * Literal percentage signs (%) in the query string must be written as %%. Percentage wildcards + * (for example, to use in LIKE syntax) must be passed via a substitution argument containing + * the complete LIKE string, these cannot be inserted directly in the query string. + * Also see wpdb::esc_like(). * - * Arguments may be passed as individual arguments to the method, or as a single array containing all arguments. A combination - * of the two is not supported. + * Arguments may be passed as individual arguments to the method, or as a single array + * containing all arguments. A combination of the two is not supported. * * Examples: * $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", array( 'foo', 1337, '%bar' ) ); * $wpdb->prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' ); * - * @link https://secure.php.net/sprintf Description of syntax. * @since 2.3.0 + * @since 5.3.0 Formalized the existing and already documented `...$args` parameter + * by updating the function signature. The second parameter was changed + * from `$args` to `...$args`. + * + * @link https://www.php.net/sprintf Description of syntax. * - * @param string $query Query statement with sprintf()-like placeholders - * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called with an array of arguments, - * or the first variable to substitute into the query's placeholders if being called with individual arguments. - * @param mixed $args,... further variables to substitute into the query's placeholders if being called wih individual arguments. + * @param string $query Query statement with sprintf()-like placeholders. + * @param array|mixed $args The array of variables to substitute into the query's placeholders + * if being called with an array of arguments, or the first variable + * to substitute into the query's placeholders if being called with + * individual arguments. + * @param mixed ...$args Further variables to substitute into the query's placeholders + * if being called with individual arguments. * @return string|void Sanitized query string, if there is a query to prepare. */ - public function prepare( $query, $args ) { + public function prepare( $query, ...$args ) { if ( is_null( $query ) ) { return; } @@ -1300,15 +1303,20 @@ // This is not meant to be foolproof -- but it will catch obviously incorrect usage. if ( strpos( $query, '%' ) === false ) { wp_load_translations_early(); - _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9.0' ); + _doing_it_wrong( + 'wpdb::prepare', + sprintf( + /* translators: %s: wpdb::prepare() */ + __( 'The query argument of %s must have a placeholder.' ), + 'wpdb::prepare()' + ), + '3.9.0' + ); } - $args = func_get_args(); - array_shift( $args ); - // If args were passed as an array (as in vsprintf), move them up. $passed_as_array = false; - if ( is_array( $args[0] ) && count( $args ) == 1 ) { + if ( is_array( $args[0] ) && count( $args ) === 1 ) { $passed_as_array = true; $args = $args[0]; } @@ -1316,7 +1324,15 @@ foreach ( $args as $arg ) { if ( ! is_scalar( $arg ) && ! is_null( $arg ) ) { wp_load_translations_early(); - _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'Unsupported value type (%s).' ), gettype( $arg ) ), '4.8.2' ); + _doing_it_wrong( + 'wpdb::prepare', + sprintf( + /* translators: %s: Value type. */ + __( 'Unsupported value type (%s).' ), + gettype( $arg ) + ), + '4.8.2' + ); } } @@ -1342,7 +1358,7 @@ $query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes. $query = preg_replace( '/(?add_placeholder_escape( $query ); } @@ -1384,7 +1404,7 @@ /** * First half of escaping for LIKE special characters % and _ before preparing for MySQL. * - * Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security. + * Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security. * * Example Prepared Statement: * @@ -1399,23 +1419,24 @@ * * @since 4.0.0 * - * @param string $text The raw text to be escaped. The input typed by the user should have no - * extra or deleted slashes. - * @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare() - * or real_escape next. + * @param string $text The raw text to be escaped. The input typed by the user + * should have no extra or deleted slashes. + * @return string Text in the form of a LIKE phrase. The output is not SQL safe. + * Call wpdb::prepare() or wpdb::_real_escape() next. */ public function esc_like( $text ) { return addcslashes( $text, '_%\\' ); } /** - * Print SQL/DB error. + * Prints SQL/DB error. * * @since 0.71 - * @global array $EZSQL_ERROR Stores error information of query and error string + * + * @global array $EZSQL_ERROR Stores error information of query and error string. * - * @param string $str The error to display - * @return false|void False if the showing of errors is disabled. + * @param string $str The error to display. + * @return void|false Void if the showing of errors is enabled, false if disabled. */ public function print_error( $str = '' ) { global $EZSQL_ERROR; @@ -1438,11 +1459,12 @@ wp_load_translations_early(); - if ( $caller = $this->get_caller() ) { - /* translators: 1: Database error message, 2: SQL query, 3: Name of the calling function */ + $caller = $this->get_caller(); + if ( $caller ) { + /* translators: 1: Database error message, 2: SQL query, 3: Name of the calling function. */ $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller ); } else { - /* translators: 1: Database error message, 2: SQL query */ + /* translators: 1: Database error message, 2: SQL query. */ $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query ); } @@ -1453,7 +1475,7 @@ return false; } - // If there is an error then take note of it + // If there is an error then take note of it. if ( is_multisite() ) { $msg = sprintf( "%s [%s]\n%s\n", @@ -1485,15 +1507,14 @@ * Enables showing of database errors. * * This function should be used only to enable showing of errors. - * wpdb::hide_errors() should be used instead for hiding of errors. However, - * this function can be used to enable and disable showing of database - * errors. + * wpdb::hide_errors() should be used instead for hiding errors. * * @since 0.71 + * * @see wpdb::hide_errors() * - * @param bool $show Whether to show or hide errors - * @return bool Old value for showing errors. + * @param bool $show Optional. Whether to show errors. Default true. + * @return bool Whether showing of errors was previously active. */ public function show_errors( $show = true ) { $errors = $this->show_errors; @@ -1507,9 +1528,10 @@ * By default database errors are not shown. * * @since 0.71 + * * @see wpdb::show_errors() * - * @return bool Whether showing of errors was active + * @return bool Whether showing of errors was previously active. */ public function hide_errors() { $show = $this->show_errors; @@ -1518,15 +1540,16 @@ } /** - * Whether to suppress database errors. + * Enables or disables suppressing of database errors. * - * By default database errors are suppressed, with a simple - * call to this function they can be enabled. + * By default database errors are suppressed. * * @since 2.5.0 + * * @see wpdb::hide_errors() - * @param bool $suppress Optional. New value. Defaults to true. - * @return bool Old value + * + * @param bool $suppress Optional. Whether to suppress errors. Default true. + * @return bool Whether suppressing of errors was previously active. */ public function suppress_errors( $suppress = true ) { $errors = $this->suppress_errors; @@ -1535,7 +1558,7 @@ } /** - * Kill cached query results. + * Kills cached query results. * * @since 0.71 */ @@ -1543,19 +1566,20 @@ $this->last_result = array(); $this->col_info = null; $this->last_query = null; - $this->rows_affected = $this->num_rows = 0; + $this->rows_affected = 0; + $this->num_rows = 0; $this->last_error = ''; if ( $this->use_mysqli && $this->result instanceof mysqli_result ) { mysqli_free_result( $this->result ); $this->result = null; - // Sanity check before using the handle + // Sanity check before using the handle. if ( empty( $this->dbh ) || ! ( $this->dbh instanceof mysqli ) ) { return; } - // Clear out any results from a multi-query + // Clear out any results from a multi-query. while ( mysqli_more_results( $this->dbh ) ) { mysqli_next_result( $this->dbh ); } @@ -1565,10 +1589,9 @@ } /** - * Connect to and select database. + * Connects to and selects database. * - * If $allow_bail is false, the lack of database connection will need - * to be handled manually. + * If $allow_bail is false, the lack of database connection will need to be handled manually. * * @since 3.0.0 * @since 3.9.0 $allow_bail parameter added. @@ -1594,14 +1617,14 @@ $socket = null; $is_ipv6 = false; - if ( $host_data = $this->parse_db_host( $this->dbhost ) ) { + $host_data = $this->parse_db_host( $this->dbhost ); + if ( $host_data ) { list( $host, $port, $socket, $is_ipv6 ) = $host_data; } /* - * If using the `mysqlnd` library, the IPv6 address needs to be - * enclosed in square brackets, whereas it doesn't while using the - * `libmysqlclient` library. + * If using the `mysqlnd` library, the IPv6 address needs to be enclosed + * in square brackets, whereas it doesn't while using the `libmysqlclient` library. * @see https://bugs.php.net/bug.php?id=67563 */ if ( $is_ipv6 && extension_loaded( 'mysqlnd' ) ) { @@ -1611,6 +1634,7 @@ if ( WP_DEBUG ) { mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags ); } else { + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags ); } @@ -1619,10 +1643,10 @@ /* * It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if: - * - We haven't previously connected, and - * - WP_USE_EXT_MYSQL isn't set to false, and - * - ext/mysql is loaded. - */ + * - We haven't previously connected, and + * - WP_USE_EXT_MYSQL isn't set to false, and + * - ext/mysql is loaded. + */ $attempt_fallback = true; if ( $this->has_connected ) { @@ -1642,6 +1666,7 @@ if ( WP_DEBUG ) { $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags ); } else { + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags ); } } @@ -1651,14 +1676,14 @@ // Load custom DB error template, if present. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) { - require_once( WP_CONTENT_DIR . '/db-error.php' ); + require_once WP_CONTENT_DIR . '/db-error.php'; die(); } $message = '' . sprintf(
- /* translators: 1: wp-config.php, 2: database host */
+ /* translators: 1: wp-config.php, 2: Database host. */
__( 'This either means that the username and password information in your %1$s file is incorrect or we can’t contact the database server at %2$s. This could mean your host’s database server is down.' ),
'wp-config.php
',
'' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '
'
@@ -1666,12 +1691,12 @@
$message .= "
' . sprintf( - /* translators: %s: support forums URL */ + /* translators: %s: Support forums URL. */ __( 'If you’re unsure what these terms mean you should probably contact your host. If you still need help you can always visit the WordPress Support Forums.' ), __( 'https://wordpress.org/support/forums/' ) ) . "
\n"; @@ -1699,18 +1724,18 @@ } /** - * Parse the DB_HOST setting to interpret it for mysqli_real_connect. + * Parses the DB_HOST setting to interpret it for mysqli_real_connect(). * - * mysqli_real_connect doesn't support the host param including a port or - * socket like mysql_connect does. This duplicates how mysql_connect detects - * a port and/or socket file. + * mysqli_real_connect() doesn't support the host param including a port or socket + * like mysql_connect() does. This duplicates how mysql_connect() detects a port + * and/or socket file. * * @since 4.9.0 * * @param string $host The DB_HOST setting to parse. - * @return array|bool Array containing the host, the port, the socket and whether - * it is an IPv6 address, in that order. If $host couldn't be parsed, - * returns false. + * @return array|false Array containing the host, the port, the socket and + * whether it is an IPv6 address, in that order. + * False if $host couldn't be parsed. */ public function parse_db_host( $host ) { $port = null; @@ -1719,7 +1744,7 @@ // First peel off the socket parameter from the right, if it exists. $socket_pos = strpos( $host, ':/' ); - if ( $socket_pos !== false ) { + if ( false !== $socket_pos ) { $socket = substr( $host, $socket_pos + 1 ); $host = substr( $host, 0, $socket_pos ); } @@ -1755,11 +1780,10 @@ /** * Checks that the connection to the database is still up. If not, try to reconnect. * - * If this function is unable to reconnect, it will forcibly die, or if after the - * the {@see 'template_redirect'} hook has been fired, return false instead. + * If this function is unable to reconnect, it will forcibly die, or if called + * after the {@see 'template_redirect'} hook has been fired, return false instead. * - * If $allow_bail is false, the lack of database connection will need - * to be handled manually. + * If $allow_bail is false, the lack of database connection will need to be handled manually. * * @since 3.9.0 * @@ -1779,15 +1803,15 @@ $error_reporting = false; - // Disable warnings, as we don't want to see a multitude of "unable to connect" messages + // Disable warnings, as we don't want to see a multitude of "unable to connect" messages. if ( WP_DEBUG ) { $error_reporting = error_reporting(); error_reporting( $error_reporting & ~E_WARNING ); } for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) { - // On the last try, re-enable warnings. We want to see a single instance of the - // "unable to connect" message on the bail() screen, if it appears. + // On the last try, re-enable warnings. We want to see a single instance + // of the "unable to connect" message on the bail() screen, if it appears. if ( $this->reconnect_retries === $tries && WP_DEBUG ) { error_reporting( $error_reporting ); } @@ -1818,18 +1842,18 @@ $message = '' . sprintf(
- /* translators: %s: database host */
+ /* translators: %s: Database host. */
__( 'This means that we lost contact with the database server at %s. This could mean your host’s database server is down.' ),
'' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '
'
) . "
' . sprintf( - /* translators: %s: support forums URL */ + /* translators: %s: Support forums URL. */ __( 'If you’re unsure what these terms mean you should probably contact your host. If you still need help you can always visit the WordPress Support Forums.' ), __( 'https://wordpress.org/support/forums/' ) ) . "
\n"; @@ -1837,18 +1861,21 @@ // We weren't able to reconnect, so we better bail. $this->bail( $message, 'db_connect_fail' ); - // Call dead_db() if bail didn't die, because this database is no more. It has ceased to be (at least temporarily). + // Call dead_db() if bail didn't die, because this database is no more. + // It has ceased to be (at least temporarily). dead_db(); } /** - * Perform a MySQL database query, using current database connection. + * Performs a MySQL database query, using current database connection. * - * More information can be found on the codex page. + * More information can be found on the Codex page. * * @since 0.71 * - * @param string $query Database query + * @link https://codex.wordpress.org/Function_Reference/wpdb_Class + * + * @param string $query Database query. * @return int|bool Boolean true for CREATE, ALTER, TRUNCATE and DROP queries. Number of rows * affected/selected for all other queries. Boolean false on error. */ @@ -1872,7 +1899,7 @@ $this->flush(); - // Log how the function was called + // Log how the function was called. $this->func_call = "\$db->query(\"$query\")"; // If we're writing to the database, make sure the query will write safely. @@ -1914,7 +1941,7 @@ } } - if ( empty( $this->dbh ) || 2006 == $mysql_errno ) { + if ( empty( $this->dbh ) || 2006 === $mysql_errno ) { if ( $this->check_connection() ) { $this->_do_query( $query ); } else { @@ -1956,7 +1983,7 @@ } else { $this->rows_affected = mysql_affected_rows( $this->dbh ); } - // Take note of the insert_id + // Take note of the insert_id. if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) { if ( $this->use_mysqli ) { $this->insert_id = mysqli_insert_id( $this->dbh ); @@ -1964,7 +1991,7 @@ $this->insert_id = mysql_insert_id( $this->dbh ); } } - // Return number of rows affected + // Return number of rows affected. $return_val = $this->rows_affected; } else { $num_rows = 0; @@ -1980,8 +2007,7 @@ } } - // Log number of rows the query returned - // and return number of rows selected + // Log and return the number of rows selected. $this->num_rows = $num_rows; $return_val = $num_rows; } @@ -2011,16 +2037,55 @@ $this->num_queries++; if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) { - $this->queries[] = array( + $this->log_query( $query, $this->timer_stop(), $this->get_caller(), $this->time_start, + array() ); } } /** + * Logs query data. + * + * @since 5.3.0 + * + * @param string $query The query's SQL. + * @param float $query_time Total time spent on the query, in seconds. + * @param string $query_callstack Comma-separated list of the calling functions. + * @param float $query_start Unix timestamp of the time at the start of the query. + * @param array $query_data Custom query data. + */ + public function log_query( $query, $query_time, $query_callstack, $query_start, $query_data ) { + /** + * Filters the custom query data being logged. + * + * Caution should be used when modifying any of this data, it is recommended that any additional + * information you need to store about a query be added as a new associative entry to the fourth + * element $query_data. + * + * @since 5.3.0 + * + * @param array $query_data Custom query data. + * @param string $query The query's SQL. + * @param float $query_time Total time spent on the query, in seconds. + * @param string $query_callstack Comma-separated list of the calling functions. + * @param float $query_start Unix timestamp of the time at the start of the query. + */ + $query_data = apply_filters( 'log_query_custom_data', $query_data, $query, $query_time, $query_callstack, $query_start ); + + $this->queries[] = array( + $query, + $query_time, + $query_callstack, + $query_start, + $query_data, + ); + } + + /** * Generates and returns a placeholder escape string for use in queries returned by ::prepare(). * * @since 4.8.3 @@ -2043,7 +2108,7 @@ * Add the filter to remove the placeholder escaper. Uses priority 0, so that anything * else attached to this filter will receive the query with the placeholder string removed. */ - if ( ! has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) { + if ( false === has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) { add_filter( 'query', array( $this, 'remove_placeholder_escape' ), 0 ); } @@ -2079,24 +2144,28 @@ } /** - * Insert a row into a table. + * Inserts a row into the table. * + * Examples: * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) ) * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) ) * * @since 2.5.0 + * * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * - * @param string $table Table name + * @param string $table Table name. * @param array $data Data to insert (in column => value pairs). * Both $data columns and $data values should be "raw" (neither should be SQL escaped). - * Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case. + * Sending a null value will cause the column to be set to NULL - the corresponding + * format is ignored in this case. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. * If string, that format will be used for all of the values in $data. * A format is one of '%d', '%f', '%s' (integer, float, string). - * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types. + * If omitted, all values in $data will be treated as strings unless otherwise + * specified in wpdb::$field_types. * @return int|false The number of rows inserted, or false on error. */ public function insert( $table, $data, $format = null ) { @@ -2104,24 +2173,28 @@ } /** - * Replace a row into a table. + * Replaces a row in the table. * + * Examples: * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) ) * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) ) * * @since 3.0.0 + * * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * - * @param string $table Table name + * @param string $table Table name. * @param array $data Data to insert (in column => value pairs). * Both $data columns and $data values should be "raw" (neither should be SQL escaped). - * Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case. + * Sending a null value will cause the column to be set to NULL - the corresponding + * format is ignored in this case. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. * If string, that format will be used for all of the values in $data. * A format is one of '%d', '%f', '%s' (integer, float, string). - * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types. + * If omitted, all values in $data will be treated as strings unless otherwise + * specified in wpdb::$field_types. * @return int|false The number of rows affected, or false on error. */ public function replace( $table, $data, $format = null ) { @@ -2134,25 +2207,29 @@ * Runs an insert or replace query based on $type argument. * * @since 3.0.0 + * * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * - * @param string $table Table name + * @param string $table Table name. * @param array $data Data to insert (in column => value pairs). * Both $data columns and $data values should be "raw" (neither should be SQL escaped). - * Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case. + * Sending a null value will cause the column to be set to NULL - the corresponding + * format is ignored in this case. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. * If string, that format will be used for all of the values in $data. * A format is one of '%d', '%f', '%s' (integer, float, string). - * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types. - * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT. + * If omitted, all values in $data will be treated as strings unless otherwise + * specified in wpdb::$field_types. + * @param string $type Optional. Type of operation. Possible values include 'INSERT' or 'REPLACE'. + * Default 'INSERT'. * @return int|false The number of rows affected, or false on error. */ function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) { $this->insert_id = 0; - if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) { + if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ), true ) ) { return false; } @@ -2161,7 +2238,8 @@ return false; } - $formats = $values = array(); + $formats = array(); + $values = array(); foreach ( $data as $value ) { if ( is_null( $value['value'] ) ) { $formats[] = 'NULL'; @@ -2182,17 +2260,19 @@ } /** - * Update a row in the table + * Updates a row in the table. * + * Examples: * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) ) * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) ) * * @since 2.5.0 + * * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * - * @param string $table Table name + * @param string $table Table name. * @param array $data Data to update (in column => value pairs). * Both $data columns and $data values should be "raw" (neither should be SQL escaped). * Sending a null value will cause the column to be set to NULL - the corresponding @@ -2200,11 +2280,13 @@ * @param array $where A named array of WHERE clauses (in column => value pairs). * Multiple clauses will be joined with ANDs. * Both $where columns and $where values should be "raw". - * Sending a null value will create an IS NULL comparison - the corresponding format will be ignored in this case. + * Sending a null value will create an IS NULL comparison - the corresponding + * format will be ignored in this case. * @param array|string $format Optional. An array of formats to be mapped to each of the values in $data. * If string, that format will be used for all of the values in $data. * A format is one of '%d', '%f', '%s' (integer, float, string). - * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types. + * If omitted, all values in $data will be treated as strings unless otherwise + * specified in wpdb::$field_types. * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where. * If string, that format will be used for all of the items in $where. * A format is one of '%d', '%f', '%s' (integer, float, string). @@ -2225,7 +2307,9 @@ return false; } - $fields = $conditions = $values = array(); + $fields = array(); + $conditions = array(); + $values = array(); foreach ( $data as $field => $value ) { if ( is_null( $value['value'] ) ) { $fields[] = "`$field` = NULL"; @@ -2255,25 +2339,29 @@ } /** - * Delete a row in the table + * Deletes a row in the table. * + * Examples: * wpdb::delete( 'table', array( 'ID' => 1 ) ) * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) ) * * @since 3.4.0 + * * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * - * @param string $table Table name + * @param string $table Table name. * @param array $where A named array of WHERE clauses (in column => value pairs). * Multiple clauses will be joined with ANDs. * Both $where columns and $where values should be "raw". - * Sending a null value will create an IS NULL comparison - the corresponding format will be ignored in this case. + * Sending a null value will create an IS NULL comparison - the corresponding + * format will be ignored in this case. * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where. * If string, that format will be used for all of the items in $where. * A format is one of '%d', '%f', '%s' (integer, float, string). - * If omitted, all values in $where will be treated as strings unless otherwise specified in wpdb::$field_types. + * If omitted, all values in $data will be treated as strings unless otherwise + * specified in wpdb::$field_types. * @return int|false The number of rows updated, or false on error. */ public function delete( $table, $where, $where_format = null ) { @@ -2286,7 +2374,8 @@ return false; } - $conditions = $values = array(); + $conditions = array(); + $values = array(); foreach ( $where as $field => $value ) { if ( is_null( $value['value'] ) ) { $conditions[] = "`$field` IS NULL"; @@ -2308,19 +2397,19 @@ /** * Processes arrays of field/value pairs and field formats. * - * This is a helper method for wpdb's CRUD methods, which take field/value - * pairs for inserts, updates, and where clauses. This method first pairs - * each value with a format. Then it determines the charset of that field, - * using that to determine if any invalid text would be stripped. If text is - * stripped, then field processing is rejected and the query fails. + * This is a helper method for wpdb's CRUD methods, which take field/value pairs + * for inserts, updates, and where clauses. This method first pairs each value + * with a format. Then it determines the charset of that field, using that + * to determine if any invalid text would be stripped. If text is stripped, + * then field processing is rejected and the query fails. * * @since 4.2.0 * * @param string $table Table name. * @param array $data Field/value pair. * @param mixed $format Format for each field. - * @return array|false Returns an array of fields that contain paired values - * and formats. Returns false for invalid values. + * @return array|false An array of fields that contain paired value and formats. + * False for invalid values. */ protected function process_fields( $table, $data, $format ) { $data = $this->process_field_formats( $data, $format ); @@ -2358,7 +2447,8 @@ * of 'value' and 'format' keys. */ protected function process_field_formats( $data, $format ) { - $formats = $original_formats = (array) $format; + $formats = (array) $format; + $original_formats = $formats; foreach ( $data as $field => $value ) { $value = array( @@ -2382,14 +2472,14 @@ } /** - * Adds field charsets to field/value/format arrays generated by - * the wpdb::process_field_formats() method. + * Adds field charsets to field/value/format arrays generated by wpdb::process_field_formats(). * * @since 4.2.0 * * @param array $data As it comes from the wpdb::process_field_formats() method. * @param string $table Table name. * @return array|false The same array as $data with additional 'charset' keys. + * False on failure. */ protected function process_field_charsets( $data, $table ) { foreach ( $data as $field => $value ) { @@ -2413,7 +2503,7 @@ } /** - * For string fields, record the maximum string length that field can safely save. + * For string fields, records the maximum string length that field can safely save. * * @since 4.2.1 * @@ -2444,18 +2534,19 @@ } /** - * Retrieve one variable from the database. + * Retrieves one variable from the database. * * Executes a SQL query and returns the value from the SQL result. - * If the SQL result contains more than one column and/or more than one row, this function returns the value in the column and row specified. - * If $query is null, this function returns the value in the specified column and row from the previous SQL result. + * If the SQL result contains more than one column and/or more than one row, + * the value in the column and row specified is returned. If $query is null, + * the value in the specified column and row from the previous SQL result is returned. * * @since 0.71 * * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query. * @param int $x Optional. Column of value to return. Indexed from 0. * @param int $y Optional. Row of value to return. Indexed from 0. - * @return string|null Database query result (as string), or null on failure + * @return string|null Database query result (as string), or null on failure. */ public function get_var( $query = null, $x = 0, $y = 0 ) { $this->func_call = "\$db->get_var(\"$query\", $x, $y)"; @@ -2468,27 +2559,28 @@ $this->query( $query ); } - // Extract var out of cached results based x,y vals + // Extract var out of cached results based on x,y vals. if ( ! empty( $this->last_result[ $y ] ) ) { $values = array_values( get_object_vars( $this->last_result[ $y ] ) ); } - // If there is a value return it else return null - return ( isset( $values[ $x ] ) && $values[ $x ] !== '' ) ? $values[ $x ] : null; + // If there is a value return it, else return null. + return ( isset( $values[ $x ] ) && '' !== $values[ $x ] ) ? $values[ $x ] : null; } /** - * Retrieve one row from the database. + * Retrieves one row from the database. * * Executes a SQL query and returns the row from the SQL result. * * @since 0.71 * * @param string|null $query SQL query. - * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to - * an stdClass object, an associative array, or a numeric array, respectively. Default OBJECT. + * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which + * correspond to an stdClass object, an associative array, or a numeric array, + * respectively. Default OBJECT. * @param int $y Optional. Row to return. Indexed from 0. - * @return array|object|null|void Database query result in format specified by $output or null on failure + * @return array|object|null|void Database query result in format specified by $output or null on failure. */ public function get_row( $query = null, $output = OBJECT, $y = 0 ) { $this->func_call = "\$db->get_row(\"$query\",$output,$y)"; @@ -2507,14 +2599,14 @@ return null; } - if ( $output == OBJECT ) { + if ( OBJECT === $output ) { return $this->last_result[ $y ] ? $this->last_result[ $y ] : null; - } elseif ( $output == ARRAY_A ) { + } elseif ( ARRAY_A === $output ) { return $this->last_result[ $y ] ? get_object_vars( $this->last_result[ $y ] ) : null; - } elseif ( $output == ARRAY_N ) { + } elseif ( ARRAY_N === $output ) { return $this->last_result[ $y ] ? array_values( get_object_vars( $this->last_result[ $y ] ) ) : null; - } elseif ( strtoupper( $output ) === OBJECT ) { - // Back compat for OBJECT being previously case insensitive. + } elseif ( OBJECT === strtoupper( $output ) ) { + // Back compat for OBJECT being previously case-insensitive. return $this->last_result[ $y ] ? $this->last_result[ $y ] : null; } else { $this->print_error( ' $db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N' ); @@ -2522,11 +2614,11 @@ } /** - * Retrieve one column from the database. + * Retrieves one column from the database. * * Executes a SQL query and returns the column from the SQL result. - * If the SQL result contains more than one column, this function returns the column specified. - * If $query is null, this function returns the specified column from the previous SQL result. + * If the SQL result contains more than one column, the column specified is returned. + * If $query is null, the specified column from the previous SQL result is returned. * * @since 0.71 * @@ -2544,7 +2636,7 @@ } $new_array = array(); - // Extract the column values + // Extract the column values. if ( $this->last_result ) { for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) { $new_array[ $i ] = $this->get_var( null, $x, $i ); @@ -2554,7 +2646,7 @@ } /** - * Retrieve an entire SQL result set from the database (i.e., many rows) + * Retrieves an entire SQL result set from the database (i.e., many rows). * * Executes a SQL query and returns the entire SQL result. * @@ -2562,11 +2654,13 @@ * * @param string $query SQL query. * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants. - * With one of the first three, return an array of rows indexed from 0 by SQL result row number. - * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively. - * With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value. - * Duplicate keys are discarded. - * @return array|object|null Database query results + * With one of the first three, return an array of rows indexed + * from 0 by SQL result row number. Each row is an associative array + * (column => value, ...), a numerically indexed array (0 => value, ...), + * or an object ( ->column = value ), respectively. With OBJECT_K, + * return an associative array of row objects keyed by the value + * of each row's first column's value. Duplicate keys are discarded. + * @return array|object|null Database query results. */ public function get_results( $query = null, $output = OBJECT ) { $this->func_call = "\$db->get_results(\"$query\", $output)"; @@ -2582,12 +2676,12 @@ } $new_array = array(); - if ( $output == OBJECT ) { - // Return an integer-keyed array of row objects + if ( OBJECT === $output ) { + // Return an integer-keyed array of row objects. return $this->last_result; - } elseif ( $output == OBJECT_K ) { - // Return an array of row objects with keys from column 1 - // (Duplicates are discarded) + } elseif ( OBJECT_K === $output ) { + // Return an array of row objects with keys from column 1. + // (Duplicates are discarded.) if ( $this->last_result ) { foreach ( $this->last_result as $row ) { $var_by_ref = get_object_vars( $row ); @@ -2598,22 +2692,22 @@ } } return $new_array; - } elseif ( $output == ARRAY_A || $output == ARRAY_N ) { + } elseif ( ARRAY_A === $output || ARRAY_N === $output ) { // Return an integer-keyed array of... if ( $this->last_result ) { foreach ( (array) $this->last_result as $row ) { - if ( $output == ARRAY_N ) { - // ...integer-keyed row arrays + if ( ARRAY_N === $output ) { + // ...integer-keyed row arrays. $new_array[] = array_values( get_object_vars( $row ) ); } else { - // ...column name-keyed row arrays + // ...column name-keyed row arrays. $new_array[] = get_object_vars( $row ); } } } return $new_array; } elseif ( strtoupper( $output ) === OBJECT ) { - // Back compat for OBJECT being previously case insensitive. + // Back compat for OBJECT being previously case-insensitive. return $this->last_result; } return null; @@ -2638,8 +2732,8 @@ * * @since 4.2.0 * - * @param string $charset The character set to use. Default null. - * @param string $table The name of the table being checked. + * @param string|null $charset The character set to use. Default null. + * @param string $table The name of the table being checked. */ $charset = apply_filters( 'pre_get_table_charset', null, $table ); if ( null !== $charset ) { @@ -2650,7 +2744,8 @@ return $this->table_charset[ $tablekey ]; } - $charsets = $columns = array(); + $charsets = array(); + $columns = array(); $table_parts = explode( '.', $table ); $table = '`' . implode( '`.`', $table_parts ) . '`'; @@ -2680,7 +2775,7 @@ list( $type ) = explode( '(', $column->Type ); // A binary/blob means the whole query gets treated like this. - if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ) ) ) { + if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ), true ) ) { $this->table_charset[ $tablekey ] = 'binary'; return 'binary'; } @@ -2726,8 +2821,8 @@ * * @param string $table Table name. * @param string $column Column name. - * @return string|false|WP_Error Column character set as a string. False if the column has no - * character set. WP_Error object if there was an error. + * @return string|false|WP_Error Column character set as a string. False if the column has + * no character set. WP_Error object if there was an error. */ public function get_col_charset( $table, $column ) { $tablekey = strtolower( $table ); @@ -2741,9 +2836,9 @@ * * @since 4.2.0 * - * @param string $charset The character set to use. Default null. - * @param string $table The name of the table being checked. - * @param string $column The name of the column being checked. + * @param string|null $charset The character set to use. Default null. + * @param string $table The name of the table being checked. + * @param string $column The name of the column being checked. */ $charset = apply_filters( 'pre_get_col_charset', null, $table, $column ); if ( null !== $charset ) { @@ -2783,15 +2878,16 @@ } /** - * Retrieve the maximum string length allowed in a given column. + * Retrieves the maximum string length allowed in a given column. + * * The length may either be specified as a byte length or a character length. * * @since 4.2.1 * * @param string $table Table name. * @param string $column Column name. - * @return array|false|WP_Error array( 'length' => (int), 'type' => 'byte' | 'char' ) - * false if the column has no length (for example, numeric column) + * @return array|false|WP_Error array( 'length' => (int), 'type' => 'byte' | 'char' ). + * False if the column has no length (for example, numeric column). * WP_Error object if there was an error. */ public function get_col_length( $table, $column ) { @@ -2873,7 +2969,7 @@ } /** - * Check if a string is ASCII. + * Checks if a string is ASCII. * * The negative regex is faster for non-ASCII strings, as it allows * the search to finish as soon as it encounters a non-ASCII character. @@ -2896,7 +2992,7 @@ } /** - * Check if the query is accessing a collation considered safe on the current version of MySQL. + * Checks if the query is accessing a collation considered safe on the current version of MySQL. * * @since 4.2.0 * @@ -2957,13 +3053,12 @@ * * @since 4.2.0 * - * @param array $data Array of value arrays. Each value array has the keys - * 'value' and 'charset'. An optional 'ascii' key can be - * set to false to avoid redundant ASCII checks. - * @return array|WP_Error The $data parameter, with invalid characters removed from - * each value. This works as a passthrough: any additional keys - * such as 'field' are retained in each value array. If we cannot - * remove invalid characters, a WP_Error object is returned. + * @param array $data Array of value arrays. Each value array has the keys 'value' and 'charset'. + * An optional 'ascii' key can be set to false to avoid redundant ASCII checks. + * @return array|WP_Error The $data parameter, with invalid characters removed from each value. + * This works as a passthrough: any additional keys such as 'field' are + * retained in each value array. If we cannot remove invalid characters, + * a WP_Error object is returned. */ protected function strip_invalid_text( $data ) { $db_check_string = false; @@ -2976,9 +3071,8 @@ $truncate_by_byte_length = 'byte' === $value['length']['type']; } else { $length = false; - // Since we have no length, we'll never truncate. - // Initialize the variable to false. true would take us - // through an unnecessary (for this case) codepath below. + // Since we have no length, we'll never truncate. Initialize the variable to false. + // True would take us through an unnecessary (for this case) codepath below. $truncate_by_byte_length = false; } @@ -2994,7 +3088,7 @@ $needs_validation = true; if ( - // latin1 can store any byte sequence + // latin1 can store any byte sequence. 'latin1' === $charset || // ASCII is always OK. @@ -3048,7 +3142,8 @@ } // We couldn't use any local conversions, send it to the DB. - $value['db'] = $db_check_string = true; + $value['db'] = true; + $db_check_string = true; } unset( $value ); // Remove by reference. @@ -3057,7 +3152,7 @@ foreach ( $data as $col => $value ) { if ( ! empty( $value['db'] ) ) { // We're going to need to truncate by characters or bytes, depending on the length value we have. - if ( 'byte' === $value['length']['type'] ) { + if ( isset( $value['length']['type'] ) && 'byte' === $value['length']['type'] ) { // Using binary causes LEFT() to truncate by bytes. $charset = 'binary'; } else { @@ -3133,7 +3228,7 @@ return $charset; } - // We can't reliably strip text from tables containing binary/blob columns + // We can't reliably strip text from tables containing binary/blob columns. if ( 'binary' === $charset ) { return $query; } @@ -3197,12 +3292,12 @@ } /** - * Find the first table name referenced in a query. + * Finds the first table name referenced in a query. * * @since 4.2.0 * * @param string $query The query to search. - * @return string|false $table The table name found, or false if a table couldn't be found. + * @return string|false The table name found, or false if a table couldn't be found. */ protected function get_table_from_query( $query ) { // Remove characters that can legally trail the table name. @@ -3234,11 +3329,13 @@ return $maybe[2]; } - // SHOW TABLE STATUS LIKE and SHOW TABLES LIKE 'wp\_123\_%' - // This quoted LIKE operand seldom holds a full table name. - // It is usually a pattern for matching a prefix so we just - // strip the trailing % and unescape the _ to get 'wp_123_' - // which drop-ins can use for routing these SQL statements. + /* + * SHOW TABLE STATUS LIKE and SHOW TABLES LIKE 'wp\_123\_%' + * This quoted LIKE operand seldom holds a full table name. + * It is usually a pattern for matching a prefix so we just + * strip the trailing % and unescape the _ to get 'wp_123_' + * which drop-ins can use for routing these SQL statements. + */ if ( preg_match( '/^\s*SHOW\s+(?:TABLE\s+STATUS|(?:FULL\s+)?TABLES)\s+(?:WHERE\s+Name\s+)?LIKE\s*("|\')((?:[\\\\0-9a-zA-Z$_.-]|[\xC2-\xDF][\x80-\xBF])+)%?\\1/is', $query, $maybe ) ) { return str_replace( '\\_', '_', $maybe[2] ); } @@ -3270,7 +3367,7 @@ } /** - * Load the column metadata from the last query. + * Loads the column metadata from the last query. * * @since 3.5.0 */ @@ -3293,19 +3390,22 @@ } /** - * Retrieve column metadata from the last query. + * Retrieves column metadata from the last query. * * @since 0.71 * - * @param string $info_type Optional. Type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill - * @param int $col_offset Optional. 0: col name. 1: which table the col's in. 2: col's max length. 3: if the col is numeric. 4: col's type - * @return mixed Column Results + * @param string $info_type Optional. Possible values include 'name', 'table', 'def', 'max_length', + * 'not_null', 'primary_key', 'multiple_key', 'unique_key', 'numeric', + * 'blob', 'type', 'unsigned', 'zerofill'. Default 'name'. + * @param int $col_offset Optional. 0: col name. 1: which table the col's in. 2: col's max length. + * 3: if the col is numeric. 4: col's type. Default -1. + * @return mixed Column results. */ public function get_col_info( $info_type = 'name', $col_offset = -1 ) { $this->load_col_info(); if ( $this->col_info ) { - if ( $col_offset == -1 ) { + if ( -1 === $col_offset ) { $i = 0; $new_array = array(); foreach ( (array) $this->col_info as $col ) { @@ -3336,7 +3436,7 @@ * * @since 1.5.0 * - * @return float Total time spent on the query, in seconds + * @return float Total time spent on the query, in seconds. */ public function timer_stop() { return ( microtime( true ) - $this->time_start ); @@ -3349,9 +3449,10 @@ * * @since 1.5.0 * - * @param string $message The Error message - * @param string $error_code Optional. A Computer readable string to identify the error. - * @return false|void + * @param string $message The error message. + * @param string $error_code Optional. A computer-readable string to identify the error. + * Default '500'. + * @return void|false Void if the showing of errors is enabled, false if disabled. */ public function bail( $message, $error_code = '500' ) { if ( $this->show_errors ) { @@ -3393,8 +3494,8 @@ * * @since 4.5.0 * - * @return bool True if the connection was successfully closed, false if it wasn't, - * or the connection doesn't exist. + * @return bool True if the connection was successfully closed, + * false if it wasn't, or if the connection doesn't exist. */ public function close() { if ( ! $this->dbh ) { @@ -3417,26 +3518,25 @@ } /** - * Whether MySQL database is at least the required minimum version. + * Determines whether MySQL database is at least the required minimum version. * * @since 2.5.0 * - * @global string $wp_version - * @global string $required_mysql_version - * - * @return WP_Error|void + * @global string $wp_version The WordPress version string. + * @global string $required_mysql_version The required MySQL version string. + * @return void|WP_Error */ public function check_database_version() { global $wp_version, $required_mysql_version; - // Make sure the server has the required MySQL version + // Make sure the server has the required MySQL version. if ( version_compare( $this->db_version(), $required_mysql_version, '<' ) ) { - /* translators: 1: WordPress version number, 2: Minimum required MySQL version number */ - return new WP_Error( 'database_version', sprintf( __( 'ERROR: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ) ); + /* translators: 1: WordPress version number, 2: Minimum required MySQL version number. */ + return new WP_Error( 'database_version', sprintf( __( 'Error: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ) ); } } /** - * Whether the database supports collation. + * Determines whether the database supports collation. * * Called when WordPress is generating the table scheme. * @@ -3445,7 +3545,7 @@ * @since 2.5.0 * @deprecated 3.5.0 Use wpdb::has_cap() * - * @return bool True if collation is supported, false if version does not + * @return bool True if collation is supported, false if not. */ public function supports_collation() { _deprecated_function( __FUNCTION__, '3.5.0', 'wpdb::has_cap( \'collation\' )' ); @@ -3453,7 +3553,7 @@ } /** - * The database character collate. + * Retrieves the database character collate. * * @since 3.5.0 * @@ -3473,7 +3573,7 @@ } /** - * Determine if a database supports a particular feature. + * Determines if a database supports a particular feature. * * @since 2.7.0 * @since 4.1.0 Added support for the 'utf8mb4' feature. @@ -3481,9 +3581,8 @@ * * @see wpdb::db_version() * - * @param string $db_cap The feature to check for. Accepts 'collation', - * 'group_concat', 'subqueries', 'set_charset', - * 'utf8mb4', or 'utf8mb4_520'. + * @param string $db_cap The feature to check for. Accepts 'collation', 'group_concat', + * 'subqueries', 'set_charset', 'utf8mb4', or 'utf8mb4_520'. * @return int|false Whether the database feature is supported, false otherwise. */ public function has_cap( $db_cap ) { @@ -3524,14 +3623,14 @@ } /** - * Retrieve the name of the function that called wpdb. + * Retrieves the name of the function that called wpdb. * - * Searches up the list of functions until it reaches - * the one that would most logically had called this method. + * Searches up the list of functions until it reaches the one that would + * most logically had called this method. * * @since 2.5.0 * - * @return string Comma separated list of the calling functions. + * @return string Comma-separated list of the calling functions. */ public function get_caller() { return wp_debug_backtrace_summary( __CLASS__ ); @@ -3542,14 +3641,26 @@ * * @since 2.7.0 * - * @return null|string Null on failure, version number on success. + * @return string|null Version number on success, null on failure. */ public function db_version() { + return preg_replace( '/[^0-9.].*/', '', $this->db_server_info() ); + } + + /** + * Retrieves full MySQL server information. + * + * @since 5.5.0 + * + * @return string|false Server info on success, false on failure. + */ + public function db_server_info() { if ( $this->use_mysqli ) { $server_info = mysqli_get_server_info( $this->dbh ); } else { $server_info = mysql_get_server_info( $this->dbh ); } - return preg_replace( '/[^0-9.].*/', '', $server_info ); + + return $server_info; } }