Files
plugi/plugi-core/src/Core/DB.php
T
deepDiverPaul e1767dcd2c media-library search, MIME-type and virtual-folder filters, persisted
folder and alt-text editing, and safe defaults for legacy uploads
2026-11-30 16:51:14 +01:00

334 lines
12 KiB
PHP

<?php
namespace Plugi\Core;
use Exception;
use PDO;
use PDOException;
use Plugi\Extensions;
use Plugi\Repositories\SettingRepository;
/**
* Class DB
*
* A basic shell around PDO.
*
* @package Plugi\Core
*/
class DB
{
/**
* @var PDO $pdo
*/
protected PDO $pdo;
/**
* @var string $databaseName
*/
protected string $databaseName;
/**
* DB constructor.
*
*/
public function __construct()
{
// Validate database charset against a whitelist to prevent SQL injection
$allowedCharsets = ['utf8mb4', 'utf8', 'latin1', 'ascii', 'utf8mb3'];
$charset = in_array($_ENV['DATABASE_CHARSET'], $allowedCharsets, true) ? $_ENV['DATABASE_CHARSET'] : 'utf8mb4';
$this->pdo = new PDO(
$_ENV['DATABASE_DRIVER'] . ':host=' . $_ENV['DATABASE_HOST'] . ';dbname=' . $_ENV['DATABASE_DATABASE'] . ";options='--client_encoding=" . $charset . "'",
$_ENV['DATABASE_USERNAME'],
$_ENV['DATABASE_PASSWORD'],
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
$this->pdo->exec("set names " . $charset);
$this->databaseName = $_ENV['DATABASE_DATABASE'];
}
/**
* Return the id of the last inserted record.
*
* @return string
*/
public function lastInsertId(): string
{
return $this->pdo->lastInsertId();
}
/**
* Return all records of the given table and return instances of the given class.
*
* @param array|string $columns
* @param string $table
* @return array
*/
public function all(string $table, array|string $columns = '*'): array
{
try {
// Sanitize table name to prevent SQL injection
$sanitizedTable = phpb_remove_non_alpha_numeric($table);
if (empty($sanitizedTable)) {
throw new PDOException('Invalid table name.');
}
if (is_array($columns)) {
foreach ($columns as &$column) {
$column = preg_replace('/[^a-zA-Z_]*/', '', $column);
}
$columns = implode(',', $columns);
$stmt = $this->pdo->prepare("SELECT $columns FROM $sanitizedTable");
} else {
$stmt = $this->pdo->prepare("SELECT * FROM $sanitizedTable");
}
$stmt->execute();
return $stmt->fetchAll();
} catch (PDOException $e) {
$_SESSION["phpb_flash"] = [
'message-type' => 'error',
'message' => phpb_trans('website-manager.check-database')
];
return [];
}
}
/**
* Return the first record of the given table as an instance of the given class.
*
* @param string $table
* @param $id
* @return mixed
*/
public function findWithId(string $table, $id)
{
$sanitizedTable = phpb_remove_non_alpha_numeric($table);
$stmt = $this->pdo->prepare("SELECT * FROM {$sanitizedTable} WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetchAll();
}
/**
* Perform a custom select query with user input data passed as $parameters.
*
* @param string $query
* @param array $parameters
* @return array
*/
public function select(string $query, array $parameters)
{
$stmt = $this->pdo->prepare($query);
$stmt->execute($parameters);
return $stmt->fetchAll();
}
/**
* Perform a custom query with user input data passed as $parameters.
*
* @param string $query
* @param array $parameters
* @return bool
*/
public function query(string $query, array $parameters = [])
{
$stmt = $this->pdo->prepare($query);
return $stmt->execute($parameters);
}
/**
* Run the callback inside a database transaction, rolling back false results and exceptions.
*/
public function transaction(callable $callback): mixed
{
$this->pdo->beginTransaction();
try {
$result = $callback();
if ($result === false) {
$this->pdo->rollBack();
return false;
}
$this->pdo->commit();
return $result;
} catch (\Throwable $exception) {
if ($this->pdo->inTransaction()) {
$this->pdo->rollBack();
}
throw $exception;
}
}
function tableExists(string $table): bool
{
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
try {
$this->pdo->query("SELECT 1 FROM {$tableName} LIMIT 1");
return true;
} catch (Exception $e) {
return false;
}
}
public function columnExists(string $table, string $column): bool
{
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
// check if table with the name $table exists. if not, execute $query.'
try {
$rs = $this->pdo->query("SELECT * FROM {$tableName} LIMIT 0");
for ($i = 0; $i < $rs->columnCount(); $i++) {
$col = $rs->getColumnMeta($i);
$columns[] = $col['name'];
}
if (in_array($column, $columns)) return true;
return false;
} catch (Exception $e) {
return false;
}
}
public function uniqueKeyExists(string $table, string $key)
{
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
// check if table with the name $table exists. if not, execute $query.'
try {
$keys = $this->select(
"SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME = ? AND TABLE_SCHEMA = ? AND TABLE_NAME = ? AND CONSTRAINT_TYPE = 'UNIQUE'",
[$key, $this->databaseName, $tableName]
);
if (count($keys) === 1) return true;
return false;
} catch (Exception $e) {
// Do not expose database error details to the user
return false;
}
}
public function primaryKeyExists(string $table, string $column): bool
{
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
$columnName = phpb_remove_non_alpha_numeric($column);
try {
return ! empty($this->select(
"SELECT 1 FROM information_schema.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ? AND CONSTRAINT_NAME = 'PRIMARY' LIMIT 1",
[$this->databaseName, $tableName, $columnName]
));
} catch (Exception $e) {
return false;
}
}
public function autoIncrementExists(string $table, string $column): bool
{
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
$columnName = phpb_remove_non_alpha_numeric($column);
try {
$columns = $this->select(
'SELECT EXTRA FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?',
[$this->databaseName, $tableName, $columnName]
);
return isset($columns[0]['EXTRA']) && stripos($columns[0]['EXTRA'], 'auto_increment') !== false;
} catch (Exception $e) {
return false;
}
}
public function getDBDefinition() {
$tables = include __DIR__.'/../../config/tables.php';
foreach (Extensions::getConfigs() as $extkey => $config){
if(key_exists('tables', $config)){
foreach ($config['tables'] as $table => $definition){
$tables['ext__'.$extkey.'_'.$table] = $definition;
}
}
}
return $tables;
}
public function getDBDefinitionHash() {
return hash('sha256', json_encode($this->getDBDefinition()));
}
public function diffDB() {
$tables = $this->getDBDefinition();
$diff = [];
foreach ($tables as $table => $tableDefinition) {
if ($this->tableExists($table) === false) {
$diff[$table] = false;
} else {
$diff[$table]['columns'] = [];
foreach ($tableDefinition['columns'] as $column => $columnDefinition) {
if(!$this->columnExists($table, $column)) $diff[$table]['columns'][$column] = $columnDefinition;
}
$diff[$table]['uniqueKeys'] = [];
foreach ($tableDefinition['uniqueKeys'] as $key => $keyDefinition) {
if(!$this->uniqueKeyExists($table, $key)) $diff[$table]['uniqueKeys'][$key] = '`'.implode('`,`', $keyDefinition).'`';
}
if (isset($tableDefinition['primaryKey'])) {
$diff[$table]['primaryKey'] = $this->primaryKeyExists($table, $tableDefinition['primaryKey'])
? null
: $tableDefinition['primaryKey'];
}
if (isset($tableDefinition['autoIncrement'])) {
$diff[$table]['autoIncrement'] = $this->autoIncrementExists($table, $tableDefinition['autoIncrement'])
? null
: $tableDefinition['autoIncrement'];
}
}
}
return $diff;
}
public function resolveDiffDB() {
$definitions = $this->getDBDefinition();
$diff = $this->diffDB();
foreach ($diff as $table => $tableDiff) {
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
if($tableDiff === false){
$this->query("CREATE TABLE {$tableName} (`id` int NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$this->query("ALTER TABLE {$tableName} ADD PRIMARY KEY (`id`)");
$this->query("ALTER TABLE {$tableName} MODIFY `id` int NOT NULL AUTO_INCREMENT");
$tableDefinition = $definitions[$table] ?? ['columns' => [], 'uniqueKeys' => []];
$tableDiff = [
'columns' => $tableDefinition['columns'] ?? [],
'uniqueKeys' => [],
];
foreach ($tableDefinition['uniqueKeys'] ?? [] as $key => $columns) {
$tableDiff['uniqueKeys'][$key] = '`' . implode('`,`', $columns) . '`';
}
}
if (is_array($tableDiff)) {
foreach ($tableDiff['columns'] as $column => $columnDefinition) {
// Validate column name to prevent SQL injection
$sanitizedColumn = phpb_remove_non_alpha_numeric($column);
if (empty($sanitizedColumn)) continue;
// Validate column definition against a safe pattern
if (!is_string($columnDefinition) || !preg_match("/^[A-Z\\s(),0-9_`']+$/i", $columnDefinition)) continue;
$this->query("ALTER TABLE {$tableName} ADD {$sanitizedColumn} {$columnDefinition}");
}
foreach ($tableDiff['uniqueKeys'] as $key => $keyDefinition) {
// Validate key name and definition
$sanitizedKey = phpb_remove_non_alpha_numeric($key);
if (empty($sanitizedKey)) continue;
if (!preg_match('/^[A-Z,`\s_]+$/i', $keyDefinition)) continue;
$this->query("ALTER TABLE {$tableName} ADD UNIQUE KEY {$sanitizedKey} ($keyDefinition)");
}
if (! empty($tableDiff['primaryKey'])) {
$column = phpb_remove_non_alpha_numeric($tableDiff['primaryKey']);
if (! empty($column)) {
$this->query("ALTER TABLE {$tableName} ADD PRIMARY KEY (`{$column}`)");
}
}
if (! empty($tableDiff['autoIncrement'])) {
$column = phpb_remove_non_alpha_numeric($tableDiff['autoIncrement']);
if (! empty($column)) {
$this->query("ALTER TABLE {$tableName} MODIFY `{$column}` int NOT NULL AUTO_INCREMENT");
}
}
}
}
$settingRepository = new SettingRepository;
$settingRepository->updateSettings(['db-definition' => $this->getDBDefinitionHash()]);
}
}