Database: start reworking the DBA to work with PDO

This commit is contained in:
2025-05-13 20:51:43 +02:00
parent 7faa59562d
commit 8dbf1dce7b
9 changed files with 391 additions and 506 deletions

View File

@@ -1,39 +1,29 @@
<?php
/*****************************************************************************
* Database.php
* Contains key class Database.
* Contains model class Database.
*
* Adapted from SMF 2.0's DBA (C) 2011 Simple Machines
* Used under BSD 3-clause license.
*
* Kabuki CMS (C) 2013-2015, Aaron van Geffen
* Kabuki CMS (C) 2013-2025, Aaron van Geffen
*****************************************************************************/
/**
* The database model used to communicate with the MySQL server.
*/
class Database
{
private $connection;
private $query_count = 0;
private $logged_queries = [];
private array $db_callback;
/**
* Initialises a new database connection.
* @param server: server to connect to.
* @param user: username to use for authentication.
* @param password: password to use for authentication.
* @param name: database to select.
*/
public function __construct($server, $user, $password, $name)
public function __construct($host, $user, $password, $name)
{
try
{
$this->connection = new mysqli($server, $user, $password, $name);
$this->connection->set_charset('utf8mb4');
$this->connection = new PDO("mysql:host=$host;dbname=$name;charset=utf8mb4", $user, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
}
catch (mysqli_sql_exception $e)
// Give up if we have a connection error.
catch (PDOException $e)
{
http_response_code(503);
echo '<h2>Database Connection Problems</h2><p>Our software could not connect to the database. We apologise for any inconvenience and ask you to check back later.</p>';
@@ -52,301 +42,178 @@ class Database
}
/**
* Fetches a row from a given recordset, using field names as keys.
* Fetches a row from a given statement/recordset, using field names as keys.
*/
public function fetch_assoc($resource)
public function fetchAssoc($stmt)
{
return mysqli_fetch_assoc($resource);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
/**
* Fetches a row from a given recordset, encapsulating into an object.
* Fetches a row from a given statement/recordset, encapsulating into an object.
*/
public function fetch_object($resource, $class)
public function fetchObject($stmt, $class)
{
return mysqli_fetch_object($resource, $class);
return $stmt->fetchObject($class);
}
/**
* Fetches a row from a given recordset, using numeric keys.
* Fetches a row from a given statement/recordset, using numeric keys.
*/
public function fetch_row($resource)
public function fetchNum($stmt)
{
return mysqli_fetch_row($resource);
return $stmt->fetch(PDO::FETCH_NUM);
}
/**
* Destroys a given recordset.
* Destroys a given statement/recordset.
*/
public function free_result($resource)
public function free($stmt)
{
return mysqli_free_result($resource);
}
public function data_seek($result, $row_num)
{
return mysqli_data_seek($result, $row_num);
return $stmt->closeCursor();
}
/**
* Returns the amount of rows in a given recordset.
* Returns the amount of rows in a given statement/recordset.
*/
public function num_rows($resource)
public function rowCount($stmt)
{
return mysqli_num_rows($resource);
return $stmt->rowCount();
}
/**
* Returns the amount of fields in a given recordset.
* Returns the amount of fields in a given statement/recordset.
*/
public function num_fields($resource)
public function columnCount($stmt)
{
return mysqli_num_fields($resource);
}
/**
* Escapes a string.
*/
public function escape_string($string)
{
return mysqli_real_escape_string($this->connection, $string);
}
/**
* Unescapes a string.
*/
public function unescape_string($string)
{
return stripslashes($string);
}
/**
* Returns the last MySQL error.
*/
public function error()
{
return mysqli_error($this->connection);
}
public function server_info()
{
return mysqli_get_server_info($this->connection);
}
/**
* Selects a database on a given connection.
*/
public function select_db($database)
{
return mysqli_select_db($database, $this->connection);
}
/**
* Returns the amount of rows affected by the previous query.
*/
public function affected_rows()
{
return mysqli_affected_rows($this->connection);
return $stmt->columnCount();
}
/**
* Returns the id of the row created by a previous query.
*/
public function insert_id()
public function insertId($name = null)
{
return mysqli_insert_id($this->connection);
return $this->connection->lastInsertId($name);
}
/**
* Do a MySQL transaction.
* Start a transaction.
*/
public function transaction($operation = 'commit')
public function beginTransaction()
{
switch ($operation)
{
case 'begin':
case 'rollback':
case 'commit':
return @mysqli_query($this->connection, strtoupper($operation));
default:
return false;
}
return $this->connection->beginTransaction();
}
/**
* Function used as a callback for the preg_match function that parses variables into database queries.
* Rollback changes in a transaction.
*/
private function replacement_callback($matches)
public function rollback()
{
list ($values, $connection) = $this->db_callback;
return $this->connection->rollBack();
}
if (!isset($matches[2]))
throw new UnexpectedValueException('Invalid value inserted or no type specified.');
/**
* Commit changes in a transaction.
*/
public function commit()
{
return $this->connection->commit();
}
if (!isset($values[$matches[2]]))
throw new UnexpectedValueException('The database value you\'re trying to insert does not exist: ' . htmlspecialchars($matches[2]));
$replacement = $values[$matches[2]];
switch ($matches[1])
private function expandPlaceholders($db_string, array &$db_values)
{
foreach ($db_values as $key => &$value)
{
case 'int':
if ((!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement) && $replacement !== 'NULL')
throw new UnexpectedValueException('Wrong value type sent to the database for field: ' . $matches[2] . '. Integer expected.');
return $replacement !== 'NULL' ? (string) (int) $replacement : 'NULL';
break;
case 'string':
case 'text':
return $replacement !== 'NULL' ? sprintf('\'%1$s\'', mysqli_real_escape_string($connection, $replacement)) : 'NULL';
break;
case 'array_int':
if (is_array($replacement))
if (str_contains($db_string, ':' . $key))
{
if (is_array($value))
{
if (empty($replacement))
throw new UnexpectedValueException('Database error, given array of integer values is empty.');
foreach ($replacement as $key => $value)
{
if (!is_numeric($value) || (string) $value !== (string) (int) $value)
throw new UnexpectedValueException('Wrong value type sent to the database for field: ' . $matches[2] . '. Array of integers expected.');
$replacement[$key] = (string) (int) $value;
}
return implode(', ', $replacement);
throw new UnexpectedValueException('Array ' . $key .
' is used as a scalar placeholder. Did you mean to use \'@\' instead?');
}
else
throw new UnexpectedValueException('Wrong value type sent to the database for field: ' . $matches[2] . '. Array of integers expected.');
break;
case 'array_string':
if (is_array($replacement))
// Prepare date/time values
if (is_a($value, 'DateTime'))
{
if (empty($replacement))
throw new UnexpectedValueException('Database error, given array of string values is empty.');
foreach ($replacement as $key => $value)
$replacement[$key] = sprintf('\'%1$s\'', mysqli_real_escape_string($connection, $value));
return implode(', ', $replacement);
$value = $value->format('Y-m-d H:i:s');
}
}
elseif (str_contains($db_string, '@' . $key))
{
if (!is_array($value))
{
throw new UnexpectedValueException('Scalar value ' . $key .
' is used as an array placeholder. Did you mean to use \':\' instead?');
}
else
throw new UnexpectedValueException('Wrong value type sent to the database for field: ' . $matches[2] . '. Array of strings expected.');
break;
case 'date':
if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1)
return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]);
elseif ($replacement === 'NULL')
return 'NULL';
else
throw new UnexpectedValueException('Wrong value type sent to the database for field: ' . $matches[2] . '. Date expected.');
break;
case 'datetime':
if (is_a($replacement, 'DateTime'))
return $replacement->format('\'Y-m-d H:i:s\'');
elseif (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d) (\d{2}):(\d{2}):(\d{2})$~', $replacement, $date_matches) === 1)
return sprintf('\'%04d-%02d-%02d %02d:%02d:%02d\'', $date_matches[1], $date_matches[2], $date_matches[3], $date_matches[4], $date_matches[5], $date_matches[6]);
elseif ($replacement === 'NULL')
return 'NULL';
else
throw new UnexpectedValueException('Wrong value type sent to the database for field: ' . $matches[2] . '. DateTime expected.');
break;
case 'float':
if (!is_numeric($replacement) && $replacement !== 'NULL')
throw new UnexpectedValueException('Wrong value type sent to the database for field: ' . $matches[2] . '. Floating point number expected.');
return $replacement !== 'NULL' ? (string) (float) $replacement : 'NULL';
break;
case 'identifier':
// Backticks inside identifiers are supported as of MySQL 4.1. We don't need them here.
return '`' . strtr($replacement, ['`' => '', '.' => '']) . '`';
break;
case 'raw':
return $replacement;
break;
case 'bool':
case 'boolean':
// In mysql this is a synonym for tinyint(1)
return (bool)$replacement ? 1 : 0;
break;
default:
throw new UnexpectedValueException('Undefined type <b>' . $matches[1] . '</b> used in the database query');
break;
// Create placeholders for all array elements
$placeholders = array_map(fn($num) => ':' . $key . $num, range(0, count($value) - 1));
$db_string = str_replace('@' . $key, implode(', ', $placeholders), $db_string);
}
else
{
// throw new Exception('Warning: unused key in query: ' . $key);
}
}
return $db_string;
}
/**
* Escapes and quotes a string using values passed, and executes the query.
*/
public function query($db_string, $db_values = [])
public function query($db_string, array $db_values = []): PDOStatement
{
// One more query....
$this->query_count ++;
// One more query...
$this->query_count++;
// Overriding security? This is evil!
$security_override = $db_values === 'security_override' || !empty($db_values['security_override']);
// Error out if hardcoded strings are detected
if (strpos($db_string, '\'') !== false)
throw new UnexpectedValueException('Hack attempt: illegal character (\') used in query.');
// Please, just use new style queries.
if (strpos($db_string, '\'') !== false && !$security_override)
throw new UnexpectedValueException('Hack attempt!', 'Illegal character (\') used in query.');
if (!$security_override && !empty($db_values))
{
// Set some values for use in the callback function.
$this->db_callback = [$db_values, $this->connection];
// Insert the values passed to this function.
$db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', [&$this, 'replacement_callback'], $db_string);
// Save some memory.
$this->db_callback = [];
}
if (defined("DB_LOG_QUERIES") && DB_LOG_QUERIES)
if (defined('DB_LOG_QUERIES') && DB_LOG_QUERIES)
$this->logged_queries[] = $db_string;
try
{
$return = @mysqli_query($this->connection, $db_string, empty($this->unbuffered) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT);
// Preprocessing/checks: prepare any arrays for binding
$db_string = $this->expandPlaceholders($db_string, $db_values);
// Prepare query for execution
$statement = $this->connection->prepare($db_string);
// Bind parameters... the hard way, due to a limit/offset hack.
// NB: bindParam binds by reference, hence &$value here.
foreach ($db_values as $key => &$value)
{
// Assumption: both scalar and array values are preprocessed to use named ':' placeholders
if (!str_contains($db_string, ':' . $key))
continue;
if (!is_array($value))
{
$statement->bindParam(':' . $key, $value);
continue;
}
foreach (array_values($value) as $num => &$element)
{
$statement->bindParam(':' . $key . $num, $element);
}
}
$statement->execute();
return $statement;
}
catch (Exception $e)
catch (PDOException $e)
{
$clean_sql = implode("\n", array_map('trim', explode("\n", $db_string)));
throw new UnexpectedValueException($this->error() . '<br>' . $clean_sql);
ob_start();
$debug = ob_get_clean();
throw new Exception($e->getMessage() . "\n" . var_export($e->errorInfo, true) . "\n" . var_export($db_values, true));
}
return $return;
}
/**
* Escapes and quotes a string just like db_query, but does not execute the query.
* Useful for debugging purposes.
*/
public function quote($db_string, $db_values = [])
{
// Please, just use new style queries.
if (strpos($db_string, '\'') !== false)
throw new UnexpectedValueException('Hack attempt!', 'Illegal character (\') used in query.');
// Save some values for use in the callback function.
$this->db_callback = [$db_values, $this->connection];
// Insert the values passed to this function.
$db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', [&$this, 'replacement_callback'], $db_string);
// Save some memory.
$this->db_callback = [];
return $db_string;
}
/**
@@ -356,11 +223,11 @@ class Database
{
$res = $this->query($db_string, $db_values);
if (!$res || $this->num_rows($res) == 0)
if (!$res || $this->rowCount($res) === 0)
return null;
$object = $this->fetch_object($res, $class);
$this->free_result($res);
$object = $this->fetchObject($res, $class);
$this->free($res);
return $object;
}
@@ -372,14 +239,14 @@ class Database
{
$res = $this->query($db_string, $db_values);
if (!$res || $this->num_rows($res) == 0)
if (!$res || $this->rowCount($res) === 0)
return [];
$rows = [];
while ($object = $this->fetch_object($res, $class))
while ($object = $this->fetchObject($res, $class))
$rows[] = $object;
$this->free_result($res);
$this->free($res);
return $rows;
}
@@ -387,15 +254,15 @@ class Database
/**
* Executes a query, returning an array of all the rows it returns.
*/
public function queryRow($db_string, $db_values = [])
public function queryRow($db_string, array $db_values = [])
{
$res = $this->query($db_string, $db_values);
if (!$res || $this->num_rows($res) == 0)
if ($this->rowCount($res) === 0)
return [];
$row = $this->fetch_row($res);
$this->free_result($res);
$row = $this->fetchNum($res);
$this->free($res);
return $row;
}
@@ -403,18 +270,18 @@ class Database
/**
* Executes a query, returning an array of all the rows it returns.
*/
public function queryRows($db_string, $db_values = [])
public function queryRows($db_string, array $db_values = [])
{
$res = $this->query($db_string, $db_values);
if (!$res || $this->num_rows($res) == 0)
if ($this->rowCount($res) === 0)
return [];
$rows = [];
while ($row = $this->fetch_row($res))
while ($row = $this->fetchNum($res))
$rows[] = $row;
$this->free_result($res);
$this->free($res);
return $rows;
}
@@ -422,18 +289,18 @@ class Database
/**
* Executes a query, returning an array of all the rows it returns.
*/
public function queryPair($db_string, $db_values = [])
public function queryPair($db_string, array $db_values = [])
{
$res = $this->query($db_string, $db_values);
if (!$res || $this->num_rows($res) == 0)
if ($this->rowCount($res) === 0)
return [];
$rows = [];
while ($row = $this->fetch_row($res))
while ($row = $this->fetchNum($res))
$rows[$row[0]] = $row[1];
$this->free_result($res);
$this->free($res);
return $rows;
}
@@ -441,21 +308,21 @@ class Database
/**
* Executes a query, returning an array of all the rows it returns.
*/
public function queryPairs($db_string, $db_values = [])
public function queryPairs($db_string, $db_values = array())
{
$res = $this->query($db_string, $db_values);
if (!$res || $this->num_rows($res) == 0)
if (!$res || $this->rowCount($res) === 0)
return [];
$rows = [];
while ($row = $this->fetch_assoc($res))
while ($row = $this->fetchAssoc($res))
{
$key_value = reset($row);
$rows[$key_value] = $row;
}
$this->free_result($res);
$this->free($res);
return $rows;
}
@@ -463,15 +330,15 @@ class Database
/**
* Executes a query, returning an associative array of all the rows it returns.
*/
public function queryAssoc($db_string, $db_values = [])
public function queryAssoc($db_string, array $db_values = [])
{
$res = $this->query($db_string, $db_values);
if (!$res || $this->num_rows($res) == 0)
if ($this->rowCount($res) === 0)
return [];
$row = $this->fetch_assoc($res);
$this->free_result($res);
$row = $this->fetchAssoc($res);
$this->free($res);
return $row;
}
@@ -479,18 +346,18 @@ class Database
/**
* Executes a query, returning an associative array of all the rows it returns.
*/
public function queryAssocs($db_string, $db_values = [], $connection = null)
public function queryAssocs($db_string, array $db_values = [])
{
$res = $this->query($db_string, $db_values);
if (!$res || $this->num_rows($res) == 0)
if ($this->rowCount($res) === 0)
return [];
$rows = [];
while ($row = $this->fetch_assoc($res))
while ($row = $this->fetchAssoc($res))
$rows[] = $row;
$this->free_result($res);
$this->free($res);
return $rows;
}
@@ -498,16 +365,16 @@ class Database
/**
* Executes a query, returning the first value of the first row.
*/
public function queryValue($db_string, $db_values = [])
public function queryValue($db_string, array $db_values = [])
{
$res = $this->query($db_string, $db_values);
// If this happens, you're doing it wrong.
if (!$res || $this->num_rows($res) == 0)
if ($this->rowCount($res) === 0)
return null;
list($value) = $this->fetch_row($res);
$this->free_result($res);
list($value) = $this->fetchNum($res);
$this->free($res);
return $value;
}
@@ -515,18 +382,18 @@ class Database
/**
* Executes a query, returning an array of the first value of each row.
*/
public function queryValues($db_string, $db_values = [])
public function queryValues($db_string, array $db_values = [])
{
$res = $this->query($db_string, $db_values);
if (!$res || $this->num_rows($res) == 0)
if ($this->rowCount($res) === 0)
return [];
$rows = [];
while ($row = $this->fetch_row($res))
while ($row = $this->fetchNum($res))
$rows[] = $row[0];
$this->free_result($res);
$this->free($res);
return $rows;
}
@@ -544,35 +411,45 @@ class Database
if (!is_array($data[array_rand($data)]))
$data = [$data];
// Create the mold for a single row insert.
$insertData = '(';
foreach ($columns as $columnName => $type)
{
// Are we restricting the length?
if (strpos($type, 'string-') !== false)
$insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
else
$insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
}
$insertData = substr($insertData, 0, -2) . ')';
// Create an array consisting of only the columns.
$indexed_columns = array_keys($columns);
// Here's where the variables are injected to the query.
$insertRows = [];
foreach ($data as $dataRow)
$insertRows[] = $this->quote($insertData, array_combine($indexed_columns, $dataRow));
// Determine the method of insertion.
$queryTitle = $method === 'replace' ? 'REPLACE' : ($method === 'ignore' ? 'INSERT IGNORE' : 'INSERT');
$method = $method == 'replace' ? 'REPLACE' : ($method == 'ignore' ? 'INSERT IGNORE' : 'INSERT');
// Do the insert.
return $this->query('
' . $queryTitle . ' INTO ' . $table . ' (`' . implode('`, `', $indexed_columns) . '`)
VALUES
' . implode(',
', $insertRows),
['security_override' => true]);
// What columns are we inserting?
$columns = array_keys($data[0]);
// Start building the query.
$db_string = $method . ' INTO ' . $table . ' (' . implode(',', $columns) . ') VALUES ';
// Create the mold for a single row insert.
$placeholders = '(' . substr(str_repeat('?, ', count($columns)), 0, -2) . '), ';
// Append it for every row we're to insert.
$values = [];
foreach ($data as $row)
{
$values = array_merge($values, array_values($row));
$db_string .= $placeholders;
}
// Get rid of the tailing comma.
$db_string = substr($db_string, 0, -2);
// Prepare for your impending demise!
$statement = $this->connection->prepare($db_string);
// Bind parameters... the hard way, due to a limit/offset hack.
foreach ($values as $key => $value)
$statement->bindValue($key + 1, $values[$key]);
// Handle errors.
try
{
$statement->execute();
return $statement;
}
catch (PDOException $e)
{
throw new Exception($e->getMessage() . '<br><br>' . $db_string . '<br><br>' . print_r($values, true));
}
}
}