Skip to content

Commit

Permalink
Use correct PDO string for unix sockets
Browse files Browse the repository at this point in the history
Copied the get_connection_string function from db-dump and update PDO connections to use the new function. Resolves #572
  • Loading branch information
jessecowens authored Dec 12, 2023
1 parent d081468 commit b7b90da
Showing 1 changed file with 58 additions and 2 deletions.
60 changes: 58 additions & 2 deletions admin/class-boldgrid-backup-admin-db-import.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ public function import_lines( $lines ) {
}

/* phpcs:disable WordPress.DB.RestrictedClasses */
$db = new PDO( sprintf( 'mysql:host=%1$s;dbname=%2$s;', DB_HOST, DB_NAME ), DB_USER, DB_PASSWORD );
$db = new PDO( $this->get_connection_string(), DB_USER, DB_PASSWORD );

$templine = '';

Expand Down Expand Up @@ -331,7 +331,7 @@ public function get_db_privileges() {
* @return array an array of results from the database query
*/
public function show_grants_query() {
$db = new PDO( sprintf( 'mysql:host=%1$s;dbname=%2$s;', DB_HOST, DB_NAME ), DB_USER, DB_PASSWORD );
$db = new PDO( $this->get_connection_string(), DB_USER, DB_PASSWORD );
$db_statement = $db->query( 'SHOW GRANTS' );
return $db_statement->fetchAll();
}
Expand Down Expand Up @@ -374,4 +374,60 @@ public function get_grants_array( $grants_string ) {

return explode( ', ', $grants_string );
}

public function get_connection_string( $db_host = null, $db_name = null ) {
$params = array();

// Configure parameters passed in.
$db_name = empty( $db_name ) ? DB_NAME : $db_name;
$db_host = empty( $db_host ) ? DB_HOST : $db_host;
$db_host = explode( ':', $db_host );

// Parse info and get hostname, port, and socket. Not all required. See comments below.
switch ( count( $db_host ) ) {
/*
* Examples:
*
* # localhost
* # /var/lib/mysql/mysql.sock
*/
case 1:
$has_socket = 'sock' === pathinfo( $db_host[0], PATHINFO_EXTENSION );

if ( $has_socket ) {
$params['unix_socket'] = $db_host[0];
} else {
$params['host'] = $db_host[0];
}

break;
/*
* Examples:
*
* # localhost:/var/lib/mysql/mysql.sock
* # localhost:3306
*/
case 2:
$has_socket = 'sock' === pathinfo( $db_host[1], PATHINFO_EXTENSION );
$has_port = is_numeric( $db_host[1] );

$params['host'] = $db_host[0];

if ( $has_socket ) {
$params['unix_socket'] = $db_host[1];
} elseif ( $has_port ) {
$params['port'] = $db_host[1];
}

break;
}

$connection_string = 'mysql:';
foreach ( $params as $key => $value ) {
$connection_string .= $key . '=' . $value . ';';
}
$connection_string .= 'dbname=' . $db_name;

return $connection_string;
}
}

0 comments on commit b7b90da

Please sign in to comment.