forked from SimplesIP/pabx-app
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
246 lines
9.2 KiB
246 lines
9.2 KiB
<?php |
|
|
|
include "Logger.php"; |
|
|
|
/** |
|
* Classe de Conexao com banco de dados. |
|
* |
|
* - Criar uma conexao de forma mais rápida. |
|
* - Gerar logs da conexao. |
|
* - Fazer consultas mais rápidas. |
|
* |
|
* @author Lucas Awade |
|
*/ |
|
class Conexao { |
|
|
|
/** @conexao */ |
|
private $connection; |
|
private $credentials = array(); |
|
|
|
/** @DB */ |
|
private $host; |
|
private $port; |
|
private $database; |
|
private $user; |
|
private $password; |
|
|
|
/** @Logs */ |
|
private $logger; |
|
|
|
const FILE_DB = "/var/www/html/include/bd"; |
|
|
|
function __construct($host = null, $user = null, $password = null, $port = null, $database = null) { |
|
$this->logger = new Logger('ConexaoDB_' . ($host ? str_replace(".", "", $host) : 'local'), true, ''); |
|
$this->logger->debug("Criando instancia de Conexao"); |
|
|
|
if ($host && $port && $user && $password) { |
|
$this->host = $host; |
|
$this->port = $port; |
|
$this->database = $database; |
|
$this->user = $user; |
|
$this->password = $password; |
|
} else { |
|
$this->filedb(); |
|
$this->host = $this->credentials['host_db']; |
|
$this->port = $this->credentials['porta_db']; |
|
$this->database = $this->credentials['base_db']; |
|
$this->user = $this->credentials['usuario']; |
|
$this->password = $this->credentials['senha']; |
|
} |
|
} |
|
|
|
/** |
|
* Pega as informacoes das credenciais no arquivos padrao "bd"; |
|
*/ |
|
private function filedb() { |
|
if (file_exists(self::FILE_DB)) { |
|
$contents = fopen(self::FILE_DB, 'r'); |
|
while (!feof($contents) && $contents) { |
|
$str = fgets($contents); |
|
$dados = explode('=', $str); |
|
$this->credentials[strtolower($dados[0])] = str_replace('"', '', $dados[1]); |
|
} |
|
fclose($contents); |
|
$this->credentials = array_filter($this->credentials); |
|
$this->logger->debug("Credenciais banco de dados: " . print_r($this->credentials, true), debug_backtrace()); |
|
} else { |
|
$this->logger->error("Nao foi possivel encontrar o arquivo 'bd' em " . self::FILE_DB); |
|
} |
|
} |
|
|
|
######################################################################## |
|
#### POSTGRESQL #### |
|
######################################################################## |
|
|
|
public function quotedStr($str) { |
|
return sprintf("'%s'", pg_escape_string(trim($str))); |
|
} |
|
|
|
/** |
|
* Cria uma instancia de conexao com o PostgreSQL e mantém um conexao aberta. |
|
* @return void |
|
* @throws Exception |
|
*/ |
|
private function postgresql() { |
|
$this->logger->error("Conexao com " . __FUNCTION__, debug_backtrace()); |
|
if ($this->connection) { |
|
return null; |
|
} |
|
if ($this->host && $this->user && $this->password && $this->port && $this->database) { |
|
$this->connection = pg_connect("host={$this->host} port={$this->port} dbname={$this->database} user={$this->user} password={$this->password}"); |
|
$this->pg_get_errors(); |
|
$this->logger->success("Conexao realizada!", debug_backtrace()); |
|
} else { |
|
$this->logger->error("Autenticacao incompleta! Verifique os dados passados de conexao.", debug_backtrace()); |
|
throw new Exception($this->logger->getText()); |
|
} |
|
} |
|
|
|
/** |
|
* Verifica erros de consultas e erros para serem gerados manualmente. |
|
* @param string $error |
|
* @throws Exception |
|
*/ |
|
private function pg_get_errors($error = null) { |
|
if (pg_last_error()) { |
|
$this->logger->error("Error PostgreSQL [ {$this->host} ] ", debug_backtrace()); |
|
$message = $error ? "Message: " . $error . " | Error DB: " . pg_last_error() : "Error DB: " . pg_last_error(); |
|
$this->logger->error($message, debug_backtrace()); |
|
throw new Exception($message); |
|
} |
|
} |
|
|
|
/** |
|
* Realiza a consulta no banco de dados com o tipo de retorno. |
|
* |
|
* - Busca com a conexao aberta, caso tenha uma sessao encerrada tentará |
|
* recria-la. |
|
* |
|
* @param string $query |
|
* @param string $type |
|
* @return array |
|
*/ |
|
function pg_execute($query, $type = "ALL") { |
|
try { |
|
$this->postgresql(); |
|
$result = pg_query($query); |
|
$this->pg_get_errors(); |
|
|
|
if ($this->selectQuery($query)) { |
|
switch (strtoupper($type)) { |
|
case "ALL": |
|
return pg_fetch_all($result); |
|
case "ASSOC": |
|
return pg_fetch_assoc($result); |
|
case "ROW": |
|
return pg_fetch_row($result); |
|
case "ARRAY": |
|
return pg_fetch_array($result); |
|
} |
|
} |
|
return !$result ? false : true; |
|
} catch (Exception $ex) { |
|
$this->logger->error($ex->getMessage()); |
|
} |
|
return false; |
|
} |
|
|
|
######################################################################## |
|
#### MySQL #### |
|
######################################################################## |
|
|
|
private function selectQuery($query) { |
|
$type = explode(' ', $query); |
|
if (trim(strtoupper($type[0])) == 'SELECT') { |
|
return true; |
|
} |
|
return false; |
|
} |
|
|
|
/** |
|
* Cria uma instancia de conexao com o PostgreSQL e mantém um conexao aberta. |
|
* @return void |
|
* @throws Exception |
|
*/ |
|
private function mysql() { |
|
$this->logger->error("Conexao com " . __FUNCTION__, debug_backtrace()); |
|
if ($this->connection) { |
|
return null; |
|
} |
|
|
|
if ($this->host && $this->user && $this->password && $this->port && $this->database) { |
|
$this->connection = mysql_connect($this->host, $this->user, $this->password); |
|
mysql_select_db($this->database, $this->connection); |
|
|
|
$this->mysql_get_errors(); |
|
$this->logger->success("Conexao realizada!", debug_backtrace()); |
|
} else { |
|
$this->logger->error("Autenticacao incompleta! Verifique os dados passados de conexao.", debug_backtrace()); |
|
throw new Exception($this->logger->getText()); |
|
} |
|
} |
|
|
|
/** |
|
* Verifica erros de consultas e erros para serem gerados manualmente. |
|
* @param string $error |
|
* @throws Exception |
|
*/ |
|
private function mysql_get_errors($error = null) { |
|
if (mysql_error()) { |
|
$this->logger->error("Error MySQL [ {$this->host} ] ", debug_backtrace()); |
|
$message = $error ? "Message: " . $error . " | Error DB: " . mysql_error() : "Error DB: " . mysql_error(); |
|
$this->logger->error($message, debug_backtrace()); |
|
throw new Exception($message); |
|
} |
|
} |
|
|
|
/** |
|
* Realiza a consulta no banco de dados com o tipo de retorno. |
|
* |
|
* - Busca com a conexao aberta, caso tenha uma sessao encerrada tentará |
|
* recria-la. |
|
* |
|
* @param string $query |
|
* @param string $type |
|
* @return array |
|
*/ |
|
function mysql_execute($query, $type = "ARRAY") { |
|
try { |
|
$this->mysql(); |
|
$result = mysql_query($query); |
|
switch (strtoupper($type)) { |
|
case "INSERT": |
|
$result = mysql_insert_id(); |
|
break; |
|
case "ASSOC": |
|
$result = mysql_fetch_assoc($result); |
|
break; |
|
case "ROW": |
|
$result = mysql_fetch_row($result); |
|
break; |
|
case "ARRAY": |
|
$result = mysql_fetch_array($result); |
|
break; |
|
} |
|
$this->mysql_get_errors(); |
|
return $result; |
|
} catch (Exception $ex) { |
|
$this->logger->error($ex->getMessage()); |
|
return null; |
|
} |
|
} |
|
|
|
######################################################################## |
|
#### SISTEMA DE LOGS GERADOS #### |
|
######################################################################## |
|
|
|
/** |
|
* Metodo para ativar e desativar o registros de log. |
|
* @param bool $active |
|
*/ |
|
function logger($active = false) { |
|
$this->logger->setLogger($active); |
|
} |
|
|
|
} |
|
|