101 lines
3.0 KiB
PHP
Executable File
101 lines
3.0 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Libraries;
|
|
|
|
use PDO;
|
|
|
|
class DataServiceSqlite
|
|
{
|
|
protected $sqliteDb;
|
|
|
|
public function __construct()
|
|
{
|
|
$dbPath = WRITEPATH . 'logs/sqlite.db';
|
|
|
|
try {
|
|
|
|
$this->sqliteDb = new PDO('sqlite:' . $dbPath);
|
|
$this->sqliteDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
|
$this->createDefaultTable();
|
|
} catch (\PDOException $e) {
|
|
// Database doesn't exist, create it
|
|
log_message('error', 'SQLite DB not found: ' . $e->getMessage());
|
|
try {
|
|
log_message('error', 'Creating SQLite DB: ');
|
|
$this->sqliteDb = new PDO('sqlite:' . $dbPath);
|
|
$this->sqliteDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
|
|
|
// Create default table
|
|
$this->createDefaultTable();
|
|
log_message('error', 'Creating SQLite DB doné');
|
|
} catch (\PDOException $e) {
|
|
log_message('error', 'Failed to create SQLite database: ' . $e->getMessage());
|
|
throw $e; // Re-throw to allow for further handling
|
|
}
|
|
}
|
|
}
|
|
|
|
// ... other methods ...
|
|
|
|
protected function createDefaultTable()
|
|
{
|
|
$sql = "CREATE TABLE IF NOT EXISTS http (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
uuid TEXT,
|
|
ip TEXT,
|
|
platform TEXT,
|
|
browser TEXT,
|
|
method TEXT,
|
|
endpoint TEXT,
|
|
getparams TEXT,
|
|
postparams TEXT,
|
|
createdon DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
)";
|
|
|
|
$this->sqliteDb->exec($sql);
|
|
|
|
$sql = "CREATE TABLE IF NOT EXISTS log (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
context TEXT,
|
|
uuid TEXT,
|
|
msg TEXT,
|
|
createdon DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
)";
|
|
|
|
$this->sqliteDb->exec($sql);
|
|
}
|
|
|
|
private const ALLOWED_TABLES = ['http', 'log'];
|
|
|
|
public function insertData(array $data, string $tableName): bool
|
|
{
|
|
log_message('error', 'SQLite insert called: ');
|
|
|
|
if (!in_array($tableName, self::ALLOWED_TABLES, true)) {
|
|
log_message('error', 'SQLite insert rejected: invalid table name: ' . $tableName);
|
|
return false;
|
|
}
|
|
|
|
unset($data['context']);
|
|
|
|
$safeColumns = array_map(function ($col) {
|
|
return preg_replace('/[^a-zA-Z0-9_]/', '', $col);
|
|
}, array_keys($data));
|
|
$columns = implode(', ', $safeColumns);
|
|
$placeholders = implode(', ', array_fill(0, count($data), '?'));
|
|
|
|
$sql = "INSERT INTO $tableName ($columns) VALUES ($placeholders)";
|
|
|
|
try {
|
|
$stmt = $this->sqliteDb->prepare($sql);
|
|
$stmt->execute(array_values($data));
|
|
return true;
|
|
} catch (\PDOException $e) {
|
|
log_message('error', 'SQLite insert failed: ' . $e->getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
}
|
|
|