Files

332 lines
7.6 KiB
PHP
Raw Permalink Normal View History

2018-02-11 20:15:28 -05:00
<?php
/**
* Copyright (C) Apis Networks, Inc - All Rights Reserved.
*
* Unauthorized copying of this file, via any medium, is
* strictly prohibited without consent. Any dissemination of
* material herein is prohibited.
*
* For licensing inquiries email <licensing@apisnetworks.com>
*
* Written by Matt Saladna <matt@apisnetworks.com>, May 2017
*/
class PostgreSQL
{
/* database connection */
/** singleton tracking */
static private $instance;
static private $pdoConnection;
private static $host = POSTGRESQL_HOST;
private static $user = POSTGRESQL_USER;
private static $passwd = POSTGRESQL_PASSWORD;
private static $database = POSTGRESQL_DATABASE;
/** mimic mysqli */
public $error;
private $dbh;
private $qHandler;
private bool $usesSocket = false;
private const LOCAL_SOCKET = '/var/run/postgresql';
private function __construct(
$mHost = null,
$mUsename = null,
#[\SensitiveParameter]
$mPassword = null,
$mDatabase = null,
$mPort = null
) {
$this->error = null;
$this->connect($mHost, $mUsename, $mPassword, $mDatabase, $mPort);
}
2018-02-11 20:15:28 -05:00
public function connect(
$mHost = null,
$mUsename = null,
#[\SensitiveParameter]
$mPassword = null,
$mDatabase = null,
$mPort = null
): self {
if (is_null($mHost)) {
$mHost = self::$host;
}
if (is_null($mUsename)) {
$mUsename = self::$user;
}
if (is_null($mPassword)) {
$mPassword = self::$passwd;
}
if (is_null($mDatabase)) {
$mDatabase = self::$database;
}
if ($mHost === 'localhost' && $mUsename === APNSCP_SYSTEM_USER) {
// use peer-based authentication
$mHost = self::LOCAL_SOCKET;
}
$connStr = (!is_null($mHost) ? 'host=' . $mHost . ' ' : '');
$connStr .= (!is_null($mUsename) ? 'user=' . $mUsename . ' ' : '');
$connStr .= (!is_null($mPassword) ? "password='" . str_replace(["'", '\\'], ["\\'", '\\\\'],
$mPassword) : '') . "' ";
$connStr .= (!is_null($mDatabase) ? 'dbname=' . $mDatabase . ' ' : '');
$connStr .= (!is_null($mPort) ? 'port=' . $mPort : '');
$this->usesSocket = str_starts_with($mHost, '/');
if (!posix_geteuid() && $this->usesSocket) {
// allow peer authentication to succeed when intraserver communication blocked
// via private network in systemd (PrivateNetworking=yes)
posix_seteuid(posix_getpwnam(APNSCP_SYSTEM_USER)['uid']);
defer($_, static function () {
posix_seteuid(0);
});
}
if (!($this->dbh = pg_connect($connStr))) {
throw new PostgreSQLError('Unable to connect to pgsql db: ' . pg_last_error());
}
return $this;
}
/**
* Get a PDO connection of the primary DB conn
*
2020-03-29 23:22:08 -04:00
* @param bool $force
* @return \PDO
*/
public static function pdo(bool $force = false): PingablePDO
{
2020-03-29 23:22:08 -04:00
if (null === self::$pdoConnection || $force) {
if (0 && is_debug()) {
dlog("Creating new PDO");
}
$connection = new PingablePDO(
'pgsql:host=' . self::$host . ';dbname=' . self::$database,
self::$user,
self::$passwd,
[PDO::ATTR_PERSISTENT => false, PDO::ERRMODE_EXCEPTION => true]
);
if ($force) {
2020-03-29 23:22:08 -04:00
return $connection;
}
self::$pdoConnection = $connection;
}
return self::$pdoConnection->ping();
}
public static function stub(): self
{
$reflection = new ReflectionClass(__CLASS__);
return $reflection->newInstanceWithoutConstructor();
}
public function __destruct()
{
if (!is_null($this->dbh)) {
$this->close();
}
}
public function close()
{
if (!$this->dbh) {
return false;
}
2021-03-02 15:02:32 -05:00
if (!is_resource($this->dbh) || pg_close($this->dbh)) {
$this->dbh = null;
}
return true;
}
public function __clone()
{
throw new apnscpException('Cannot clone PostgreSQL class');
}
public function __wakeup()
{
self::initialize();
}
public static function initialize(
$mHost = null,
$mUsename = null,
#[\SensitiveParameter]
$mPassword = null,
$mDatabase = null,
$mPort = null
) {
if (!self::$instance || !self::$instance->ping()) {
self::$instance = new static($mHost, $mUsename, $mPassword, $mDatabase, $mPort);
}
return self::$instance;
}
public function query($mStr)
{
if (!$this->dbh) {
$this->connect();
}
$this->error = false;
if (!$this->ping()) {
$err = $this->handleValid() ? pg_last_error($this->dbh) : 'UNKNOWN';
2021-03-02 15:02:32 -05:00
throw new PostgreSQLError('Unable to ping pg database: ' . $err);
}
$this->qHandler = pg_query($this->dbh, $mStr);
if (!$this->qHandler) {
$this->error = pg_last_error($this->dbh);
Error_Reporter::report($this->error);
if (is_debug()) {
var_dump($this->error);
print 'Query: ' . (IS_ISAPI ? '<code><pre>' : '') .
$mStr . (IS_ISAPI ? '</pre></code>' : "\n");
}
}
return $this;
}
private function handleValid(): bool
{
return PHP_MAJOR_VERSION === 8 ? is_object($this->dbh) : is_resource($this->dbh);
}
public function ping()
{
if (!$this->handleValid()) {
return false;
}
if (!posix_geteuid() && $this->usesSocket) {
// allow peer authentication to succeed when intraserver communication blocked
// via private network in systemd (PrivateNetworking=yes)
posix_seteuid(posix_getpwnam(APNSCP_SYSTEM_USER)['uid']);
defer($_, static function () {
posix_seteuid(0);
});
}
return $this->handleValid() && pg_ping($this->dbh);
}
public function num_rows()
{
if (!$this->qHandler) {
fatal('doh');
}
return pg_num_rows($this->qHandler);
}
public function affected_rows()
{
if (!$this->qHandler) {
return false;
}
return pg_affected_rows($this->qHandler);
}
public function query_params($mStr, array $mParams)
{
if (!$this->dbh) {
$this->connect();
}
$this->error = false;
if (!pg_ping($this->dbh)) {
throw new PostgreSQLError('Unable to ping pg database: ' . pg_last_error());
return null;
} else {
$this->qHandler = pg_query_params($this->dbh, $mStr, $mParams);
}
$this->error = pg_last_error($this->dbh);
return $this;
}
/**
* @param null $mHandle
* @return null|object
* @throws PostgreSQLError
*/
public function fetch_object($mHandle = null): ?stdClass
{
if (null === $this->dbh) {
throw new PostgreSQLError('Unable to close non-existent PostgreSQL db connection.');
}
if (null === $mHandle) {
$mHandle = $this->qHandler;
}
if ($mHandle === false) {
report(pg_last_error());
error('database connection error - failed to retrieve record');
return null;
}
$row = pg_fetch_object($mHandle);
if ($row === false) {
if (($str = pg_last_error($this->dbh)) != false) {
throw new PostgreSQLError('Error in row retrieval: ' . $str);
}
pg_free_result($mHandle);
$this->error = false;
return null;
}
return $row;
}
public function fetch_assoc($mHandle = null)
{
if (is_null($this->dbh)) {
throw new PostgreSQLError('Unable to close non-existent PostgreSQL db connection.');
return null;
}
if (is_null($mHandle)) {
$mHandle = $this->qHandler;
}
$row = pg_fetch_assoc($mHandle);
if ($row === false) {
if (($str = pg_last_error($this->dbh)) != false) {
throw new PostgreSQLError('Error in row retrieval: ' . pg_last_error());
}
pg_free_result($mHandle);
$this->error = false;
return null;
}
return $row;
}
public function escape_string($mString)
{
if (is_null($this->dbh)) {
$this->connect();
}
return pg_escape_string($this->dbh, $mString);
}
public function error()
{
return !$this->dbh ?? pg_last_error($this->dbh);
}
public function getHandler()
{
return $this->dbh;
}
}