repositório com os arquivos utilizados para integração entre o sistema SimplesIP e diversos sistemas.
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.
 
 

982 lines
38 KiB

<?php
require_once 'Logger.php';
// *************************************************************************
// * SISTEMA UNICO DE INTEGRACAO *
// *************************************************************************
/**
* Classe para utilizar os registros do Banco de Dados;
*
* OBS: Deixar como usuario de execucao e acesso pbx:pbx
*
* @author Lucas Awade
* @function developer
* @company SimplesIP
* @version 1.0.1
*/
class IntegracaoDataBase {
private $query;
private $connection;
private $registros;
private $log;
private $credentials = array();
private $debug;
private $idAudioError;
/**
* @file
* Arquivo de configuracoes do banco e manager
*/
const FILE_DB = "/var/www/html/include/bd";
public function __construct() {
$this->log = new Logger(CONF_LOGGER_PATH, CONF_LOGGER_DB_ATIVO);
}
/**
* Retorna os registros armazenados na variavel registros pra ser disponibilizado
* no decorrer de uma integracao;
*
* @return array
*/
public function getRegistros() {
return $this->registros;
}
/**
* Informa<EFBFBD><EFBFBD>es coletadas do banco de dados para ser escritas no log.
*
* @param array $array
*/
private function logResult($array) {
if ($array) {
$this->log->success(print_r($array, true), $this->debug);
} else {
$this->log->warning('Nenhum resultado encontrado!', $this->debug);
}
}
/**
* Audio de erro padrao
*
* @param string $idAudioError
*/
public function setIdAudioError($idAudioError) {
$this->idAudioError = $idAudioError;
}
########################################################################
## BANCO DE DADOS ##
########################################################################
/**
* 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->log->debug("Credenciais banco de dados: " . print_r($this->credentials, true), debug_backtrace());
} else {
$this->log->error("Nao foi possivel encontrar o arquivo 'bd' em " . self::FILE_DB);
}
}
/**
* Executa as querys da consulta a serem feitas, al<EFBFBD>m de gravar logs de registros de dados,
* e qualquer erro <EFBFBD> repassado a classe que est<EFBFBD> executando para tratar o erro;
*
* @param string $type
* @return boolean|array
*/
private function execute($type = '') {
try {
if (!$this->connection) {
$this->connection = $this->getConnection();
}
$result = pg_query($this->connection, $this->query);
switch (strtolower($type)) {
case 'assoc':
$data = pg_fetch_assoc($result);
break;
case 'row':
$data = pg_fetch_row($result);
break;
case 'array':
$data = pg_fetch_array($result);
break;
case 'all':
$data = pg_fetch_all($result);
break;
}
$this->logResult($data);
return $data;
} catch (Exception $ex) {
$this->log->error("Exception: {$ex->getMessage()} | Postgres : " . pg_last_error(), $this->debug);
}
}
public function getConnection() {
$this->filedb();
$this->connection = pg_connect(sprintf('host=%s port=%s dbname=%s user=%s password=%s', $this->credentials['host_db'], $this->credentials['porta_db'], $this->credentials['base_db'], $this->credentials['usuario'], $this->credentials['senha']));
if (pg_connection_status($this->connection) === 0) {
$this->log->success("Conectado na base {$this->credentials['base_db']}.", debug_backtrace());
return $this->connection;
} else {
throw new Exception('Nao foi possivel conectar na base de dados');
}
}
private function getPDO() {
try {
if (!$this->connection) {
$drive = CONF_DB_DRIVER;
$host = CONF_DB_HOST;
$dbname = CONF_DB_BASE;
$user = CONF_DB_USER;
$pass = CONF_DB_PASSWD;
$this->connection = new pdo("$drive:host=$host;dbname=$dbname", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
} catch (PDOException $ex) {
$this->log->error("Exception: {$ex->getMessage()} ", $this->debug);
}
}
protected function strquery($stmt, $params) {
foreach ($params as $key => $value) {
if (!$value || $value == "null") {
$value = null;
}
$stmt->bindValue(":{$key}", $value, (is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR));
}
}
public function read($query, $params) {
try{
$this->getPDO();
$stmt = $this->connection->prepare($query);
$this->strquery($stmt, $params);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $data;
} catch (PDOException $ex) {
$this->log->error("Exception: {$ex->getMessage()} ", $this->debug);
}
}
public function create($query, $params) {
try{
$this->getPDO();
$stmt = $this->connection->prepare($query);
$this->strquery($stmt, $params);
$stmt->execute();
$data = $this->connection->lastInsertId();
return $data;
} catch (PDOException $ex) {
$this->log->error("Exception: {$ex->getMessage()} ", $this->debug);
}
}
public function delete($query, $params) {
try{
$this->getPDO();
$stmt = $this->connection->prepare($query);
$this->strquery($stmt, $params);
$stmt->execute();
$count = $stmt->rowCount();
$data = (!$count) ? false : true;
return $data;
} catch (PDOException $ex) {
$this->log->error("Exception: {$ex->getMessage()} ", $this->debug);
}
}
public function update($query, $params) {
try{
$this->getPDO();
$stmt = $this->connection->prepare($query);
$this->strquery($stmt, $params);
$stmt->execute();
$count = $stmt->rowCount();
$data = (!$count) ? false : true;
return $data;
} catch (PDOException $ex) {
$this->log->error("Exception: {$ex->getMessage()} ", $this->debug);
}
}
########################################################################
## ASTERISK ##
########################################################################
/**
* Coleta em qual Asterisk a central est<EFBFBD> rodadando e retorna o modelo padrao
* de configuracao do exten;
*
* @return string
*/
private function getVersionAsterisk() {
$result = array();
exec("asterisk -V", $result);
$this->log->info("Versao Asterisk: " . $result[0], debug_backtrace());
if (strpos($result[0], '1.4') !== false) {
return "|";
} else {
return ",";
}
}
/**
* Transforma uma string exten com "," para "|" de acordo com a versao do Asterisk
*
* @param string $string
* @return string
*/
private function string_exten($string) {
return str_replace(",", $this->getVersionAsterisk(), $string);
}
/**
* Coleta os dados de autenticacao do manager.
*
* @return array
*/
public function getAuthAgi() {
$data = array();
foreach ($this->credentials as $key => $value) {
if (strpos($key, '_sck') !== false) {
$data[$key] = $value;
}
}
return $data;
}
########################################################################
## QUERYS ##
########################################################################
/**
* Inicia um Transacao;
*/
public function beginTransaction() {
$this->debug = debug_backtrace();
$this->query = "BEGIN;";
$this->execute();
}
/**
* Registra uma Transacao.
*/
public function commitTransaction() {
$this->debug = debug_backtrace();
$this->query = "COMMIT;";
$this->execute();
}
/**
* Retorna as informacoes antes da Transacao.
*/
public function rollbackTransaction() {
$this->debug = debug_backtrace();
$this->query = "ROLLBACK;";
$this->execute();
}
/**
* Busca o DDD padrao cadastrado na central.
*
* @param string $name
* @return string
*/
public function getDDD() {
$this->debug = debug_backtrace();
$this->query = "SELECT prm_ddd_padrao FROM pbx_parametros";
return $this->execute('assoc') ? $this->execute('assoc')['prm_ddd_padrao'] : '';
}
/**
* Consulta no banco o nome do Anuncio e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getAnuncio($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_anuncios WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ext-anuncios,a%s,1'), $result);
}
/**
* Consulta no banco o nome do Ura e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getUra($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_ura WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ura-%s,s,1'), $result);
}
/**
* Consulta no banco a Ura por ID e retorna suas informacoes;
*
* @param string|int $id
* @return string
*/
public function getURAById($id) {
$this->debug = debug_backtrace();
$this->query = "SELECT * FROM pbx_ura WHERE id = '{$id}'";
$result = $this->execute('assoc') ? $this->execute('assoc') : $this->idAudioError;
return $result;
}
/**
* Consulta no banco o nome do Fila e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getFila($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT numero FROM pbx_dacs WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ext-fila,%s,1'), $result);
}
/**
* Consulta no banco o nome do Ramal e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getRamal($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT nome FROM pbx_ramais WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ext-ramais,%s,1'), $result);
}
/**
* Coleta as opcoes que o usuario passou nas uras da sua chamada.
*
* @param string $uniqueid
* @param int $ura_id
* @return boolean|array
*/
public function getOptionsURA($uniqueid, $ura_id) {
$this->debug = debug_backtrace();
$this->query = "SELECT umv_ura_id,umv_ura_nome,uniqueid,umv_ura_opcao "
. "FROM pbx_ura_movimento WHERE uniqueid = '$uniqueid' "
. "AND umv_ura_opcao IS NOT NULL AND umv_opcao = 'ura' "
. "AND umv_ura_id = $ura_id "
. "ORDER BY umv_id";
return $this->execute('all');
}
/**
* Retorna o ID e Data Hora da primeira entrada da ligacao em um URA de
* acordo com o uniqueid;
* @param string $uniqueid
* @return array
*/
public function getFristURA($uniqueid) {
$this->debug = debug_backtrace();
$this->query = "SELECT destino, min(data_registro) "
. "FROM ast_bilhetes_complemento "
. "WHERE direcao = 'ura' "
. "AND uniqueid2 = '{$uniqueid}' GROUP BY destino LIMIT 1";
$result = $this->execute('assoc');
return $result;
}
public function registraIntegracao() {
$this->debug = debug_backtrace();
/**
* Parametros REGISTROS
*
* id -> Id do qual gerou a integracao para o retorno_cliente
*
* Todos os parametros devem ser igual a da tabela pbx_integracao_reg
*/
$ura = trim($this->registros['reg_ura']) ? trim($this->registros['reg_ura']) : 'null';
$tronco = trim($this->registros['reg_tronco']) ? trim($this->registros['reg_tronco']) : 'null';
$this->query = "INSERT INTO pbx_integracao_reg (reg_id_metodo,reg_uniqueid,reg_uniqueid_old,reg_fone,reg_inicio, reg_tronco, reg_ura)
SELECT * FROM (
SELECT {$this->registros['reg_id_metodo']},'{$this->registros['reg_uniqueid']}','{$this->registros['reg_uniqueid_old']}','{$this->registros['reg_fone']}', now(), '$tronco', '$ura') AS dados
WHERE NOT EXISTS (
SELECT reg_uniqueid FROM pbx_integracao_reg WHERE reg_uniqueid = '{$this->registros['reg_uniqueid']}'
) LIMIT 1;";
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
public function atualizaIntegracao() {
$this->debug = debug_backtrace();
$tronco = trim($this->registros['reg_tronco']) ? sprintf(",\nreg_tronco='%s'", trim($this->registros['reg_tronco'])) : '';
$ura = trim($this->registros['reg_ura']) ? sprintf(",\nreg_ura='%s'", trim($this->registros['reg_ura'])) : '';
$reg_msg = QuotedStr($this->registros['reg_msg']);
$reg_retorno = QuotedStr($this->registros['reg_fone']);
$retorno_cliente = substr($this->registros['retorno_cliente'], 0, 255);
$this->query = "UPDATE pbx_integracao_reg
SET reg_fim = NOW(),
reg_retorno = $reg_retorno,
reg_msg = $reg_msg,
reg_status_exec = '{$this->registros['reg_status_exec']}',
retorno_cliente = '{$retorno_cliente}'{$tronco}{$ura}
WHERE reg_uniqueid = '{$this->registros['reg_uniqueid']}'";
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
/**
* Informa os dados para ser inseridos na tabela de integracao_reg;
*
* @param array $registros
*/
public function setRegistros($registros) {
if (is_array($registros) && !$this->registros) {
$this->registros = $registros;
$this->registraIntegracao();
} else {
foreach ($registros as $key => $value) {
$this->registros[$key] = $value;
}
}
}
/**
* Retorna todas as informacoes da tabela Supervisor_Dacs
* @param array $dacs
* @return array
*/
public function getSupervisorDAC($dacs = array()) {
$this->query = "SELECT * FROM pbx_supervisor_dacs ";
if ($dacs) {
$this->query .= sprintf("WHERE id IN (%s)", implode(",", $dacs));
}
return $this->execute('all');
}
/**
* Retorna credenciais cadastradas nos metodos de integracao
* @param int $id
* @return array
*/
public function getConexaoAPI($id) {
$this->query = "SELECT itgc_nome AS name, itgc_port AS id_user, itgc_host AS url,
itgc_database AS token, itgc_user AS user, itgc_password AS password,
itgc_timeout AS timeout
FROM pbx_integracao_configuracao
WHERE itgc_id = {$id}";
return $this->execute('assoc');
}
public function getScriptCredenciais($script) {
$this->query = "SELECT itgc_nome AS name, itgc_port AS id_user, itgc_host AS url,
itgc_database AS token, itgc_user AS user, itgc_password AS password,
itgc_timeout AS timeout
FROM pbx_integracao_configuracao a
INNER JOIN pbx_integracao_metodo b ON a.itgc_id = b.itgc_id
WHERE itgm_comando = '{$script}'";
return $this->execute('assoc');
}
public function getFilaPorNome($name) {
$this->debug = debug_backtrace();
$this->query = "SELECT * FROM pbx_dacs WHERE nome = '$name'";
return $this->execute('assoc');
}
public function getLastUraPorUniqueid($uniqueid) {
$this->query = "SELECT data_reg, umv_ura_id,umv_ura_nome,uniqueid,umv_ura_opcao
FROM pbx_ura_movimento WHERE uniqueid = '{$uniqueid}'
ORDER BY data_reg DESC
LIMIT 1";
return $this->execute('assoc');
}
public function getUraMovimentoByUniqueid($uniqueid, $orderByAtt = "data_reg", $orderByType = "ASC") {
$this->query = "SELECT data_reg, umv_ura_id,umv_ura_nome,uniqueid,umv_ura_opcao, umv_opcao
FROM pbx_ura_movimento WHERE uniqueid = '{$uniqueid}'
ORDER BY $orderByAtt $orderByType
LIMIT 1";
return $this->execute('assoc');
}
public function atualizaProtocoloParceiro($uid, $protocoloParceiro) {
$this->debug = debug_backtrace();
$this->query = "UPDATE pbx_protocolo_reg
SET protoparceiro='$protocoloParceiro'
WHERE uniqueid='$uid'";
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
public function getInfoIntegraReg($uniqueid){
$this->query = "SELECT REPLACE(SUBSTRING(retorno_cliente, POSITION('||' in retorno_cliente), LENGTH(retorno_cliente)), '||', '') AS dados
FROM pbx_integracao_reg
WHERE reg_uniqueid = '$uniqueid'";
return $this->execute('assoc');
}
########################################################################
#### INSTALACAO INTEGRACAO ####
########################################################################
public function findIntegracaoCustom() {
$this->debug = debug_backtrace();
$this->query = "SELECT itgp_id FROM pbx_integracao_protocolo WHERE itgp_descricao = 'Custom'";
$this->log->debug("Query: {$this->query}", $this->debug);
$return = $this->execute('assoc');
if (!$return['itgp_id']) {
$this->query = "INSERT INTO pbx_integracao_protocolo (itgt_id,itgp_id,itgp_descricao,itgp_status,itgp_prefix) VALUES(1,6,'Custom',0,'custom');";
$this->execute('assoc');
}
return 6;
}
public function findVersion($empresa = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT MAX(itgc_status) AS versao FROM pbx_integracao_configuracao where 1=1";
if($empresa){
$this->query .= "AND itgc_nome like '%$empresa%'";
}
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute('assoc');
}
public function createIntegracaoAtiva($nome, $versao, $comando) {
$this->debug = debug_backtrace();
$query = "insert into pbx_integracao_metodo(itgc_id, itgm_nome, itgm_comando, itgm_tipo, itgm_retorno, itgm_status, opcao, evento, stored_params, itgm_id_pai) values(%s,'%s','%s',%s,%s,%s,'%s',%s,'%s',%s) returning itgm_id;";
$this->query = "INSERT INTO pbx_integracao_configuracao "
. "(itgt_id, itgp_id, itgc_nome, itgc_host, itgc_port, itgc_database, itgc_user, itgc_password, itgc_timeout, itgc_status) "
. "VALUES (1, 6, '$nome', '127.0.0.1', '0', '0', '0', '0', '10', '$versao') RETURNING itgc_id; ";
$this->log->debug("Query: {$this->query}", $this->debug);
$return = $this->execute('assoc');
$this->query = sprintf($query, $return['itgc_id'], $nome, $comando, 1, 1, 0, 'anuncios', 'null', 'null', 'null');
$res = $this->execute('assoc');
unset($this->query);
for ($x = 2; $x < 4; $x++) {
$this->query .= sprintf($this->query, $return['itgc_id'], 'NOEXEC', 'NOEXEC', 1, 0, 0, 'null', $x, 'null', $res['itgm_id']);
}
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute('assoc');
}
/* Consulta no banco o nome da integracao metodo e retorna o ID;
*
* @param string $name
* @return string
*/
public function getIntegracaoMetodoByNameIntegracao($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT pim.itgm_id
FROM pbx_integracao_metodo pim INNER JOIN pbx_integracao_configuracao pic on pic.itgc_id = pim.itgc_id
WHERE pim.itgm_retorno = 1 AND pic.itgc_nome = '$name'";
$result = $this->execute('row')[0];
return $result;
}
##########################
### ANUNCIOS ###
##########################
/*
* Inserir Anuncio
*/
public function addAnuncio($nome, $musica, $opcao = null, $acao = null) {
$this->debug = debug_backtrace();
$this->query = sprintf("INSERT INTO pbx_anuncios (nome, musica, opcao, acao)
VALUES('%s','%s','%s', '%s')", $nome, $musica, strtolower($opcao), $acao);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
/* Consulta no banco o nome do Anuncio e retorna o ID;
*
* @param string $name
* @return string
*/
public function getAnuncioIdByName($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_anuncios WHERE nome = '$name'";
$result = $this->execute('row')[0];
return $result;
}
/* Consulta no banco o id do Anuncio e retorna o nome;
*
* @param string $name
* @return string
*/
public function getAnuncioNameById($id = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT nome FROM pbx_anuncios WHERE id = '$id'";
$result = $this->execute('row')[0];
return $result;
}
/* Atualiza no banco a acao e opcao do Anuncio;
*
* @param $opcao $acao Iid
* @return string
*/
public function updateAnuncio($opcao, $acao, $id) {
$this->debug = debug_backtrace();
$this->query = sprintf("UPDATE pbx_anuncios
SET opcao='%s', acao='%s'
WHERE id=%d", strtolower($opcao), $acao, $id);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
##########################
### URAS ###
##########################
/*
* Inserir Ura
*/
public function addUra($nome, $som_ura, $tempo_espera = 5, $timeout_digito = 3, $permite_ligacao = 'N', $opcao = null, $acao = null) {
$this->debug = debug_backtrace();
$this->query = sprintf("INSERT INTO pbx_ura (nome, permite_ligacao, tempo_espera, som_ura, opcao, acao, timeout_digito)
VALUES('%s', '%s', %d, '%s', '%s', %d, '%s')", $nome, $permite_ligacao, $tempo_espera, $som_ura, strtolower($opcao), $acao, $timeout_digito);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
/* Consulta no banco o nome do Ura e retorna o ID;
*
* @param string $name
* @return string
*/
public function getUraIdByName($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_ura WHERE nome = '$name'";
$result = $this->execute('row')[0];
return $result;
}
/* Consulta no banco o ID do Ura e retorna o nome;
*
* @param string $name
* @return string
*/
public function getUraNameById($id = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT nome FROM pbx_ura WHERE id = '$id'";
$result = $this->execute('row')[0];
return $result;
}
/* Atualiza no banco acao e opcao do Ura;
*
* @param $opcao $acao Iid
* @return string
*/
public function updateUra($id, $opcao, $acao) {
$this->debug = debug_backtrace();
$this->query = sprintf("UPDATE pbx_ura
SET opcao='%s', acao='%s'
WHERE id=%d", strtolower($opcao), $acao, $id);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
##########################
### URAS ITENS ###
##########################
/*
* Inserir Ura Destino
*/
public function addUraDestino($id_ura, $numero, $tipo, $comando = null, $sequencia, $nome_comando) {
$this->debug = debug_backtrace();
$this->query = sprintf("INSERT INTO pbx_ura_destino
(id_ura, numero, tipo, comando, sequencia, nome_comando)
VALUES(%d, '%s', '%s', '%s', %d, '%s')", $id_ura, $numero, $tipo, $comando, $sequencia, $nome_comando);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute(s);
}
/* Consulta no banco o nome do Ura e retorna os destinos;
*
* @param string $name
* @return string
*/
public function getUraDestinosIdByUraName($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT pud.* FROM pbx_ura_destino pud inner join pbx_ura pu on pu.id = pud.id_ura WHERE pu.nome ='$name'";
$result = $this->execute('all');
return $result;
}
/* Atualiza no banco acao e opcao do Ura;
*
* @param $opcao $acao Iid
* @return string
*/
public function updateUraDestino($opcao, $acao, $id) {
$this->debug = debug_backtrace();
$this->query = sprintf("UPDATE pbx_ura
SET opcao='%s', acao='%s'
WHERE id=%d", strtolower($opcao), $acao, $id);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
##########################
### HORARIOS ###
##########################
/*
* Inserir Horario
*/
public function addHorario($nome, $opcao = null, $acao = null, $status = 1) {
$this->debug = debug_backtrace();
$this->query = sprintf("INSERT INTO pbx_horarios
(nome, opcao_nao, acao_nao, status)
VALUES('%s', '%s', %d, %d)", $nome, strtolower($opcao), $acao, $status);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
/* Consulta no banco o nome do Horario e retorna o ID;
*
* @param string $name
* @return string
*/
public function getHorarioIdByName($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_horarios WHERE nome = '$name'";
$result = $this->execute('row')[0];
return $result;
}
/* Consulta no banco o ID do Horario e retorna o nome;
*
* @param string $name
* @return string
*/
public function getHorarioNameById($id = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT nome FROM pbx_horarios WHERE nome = '$id'";
$result = $this->execute('row')[0];
return $result;
}
/* Atualiza no banco opcao e acao do Horario;
*
* @param $opcao $acao Iid
* @return string
*/
public function updateHorario($id, $opcao, $acao) {
$this->debug = debug_backtrace();
$this->query = sprintf("UPDATE pbx_horarios
SET opcao_nao='%s', acao_nao='%s'
WHERE id=%d", strtolower($opcao), $acao, $id);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
##########################
### HORARIOS ITENS ###
##########################
/*
* Inserir Horario
*/
public function addHorarioItens($id_horario, $horario_ini = '08:00', $horario_fim = '17:59', $dias_semana = 0, $semana = 'mon', $semana_fim = 'fri', $opcao = null, $acao = null) {
$this->debug = debug_backtrace();
$this->query = sprintf("INSERT INTO pbx_horarios_itens
(id_horario, horario_inicio, horario_fim, todos_dias_semana, semana, semana_fim, opcao, acao)
VALUES(%d, '%s', '%s', %d, '%s', '%s', '%s', '%s')", $id_horario, $horario_ini, $horario_fim, $dias_semana, $semana, $semana_fim, $opcao, $acao);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
/* Consulta no banco o nome do Horario retornar Horario Itens;
*
* @param string $name
* @return string
*/
public function getHorarioItensByHorarioName($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT phi.* FROM pbx_horarios_itens phi INNER JOIN pbx_horarios ph ON ph.id = phi.id_horario WHERE ph.nome = '$name'";
$result = $this->execute('all');
return $result;
}
/* Atualiza no banco a opcao e acao do Horario Item;
*
* @param $opcao $acao Iid
* @return string
*/
public function updateItemHorario($opcao, $acao, $id) {
$this->debug = debug_backtrace();
$this->query = sprintf("UPDATE pbx_horarios_itens
SET opcao='%s', acao='%s'
WHERE id=%d", strtolower($opcao), $acao, $id);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
#########################
### FILAS ###
#########################
/* Consulta no banco o nome da Fila e retorna o numero;
*
* @param string $name
* @return string
*/
public function getFilaNumeroByName($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT numero FROM pbx_queues_grupos WHERE nome = '$name'";
$result = $this->execute('row')[0];
return $result;
}
/* Consulta no banco o numero da Fila e retorna o Nome;
*
* @param string $name
* @return string
*/
public function getFilaNameByNumero($numero = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT nome FROM pbx_queues_grupos WHERE numero = '$numero'";
$result = $this->execute('row')[0];
return $result;
}
#########################
### SERVICOS ###
#########################
public function getServiceByUniqueid($uniqueid) {
$this->debug = debug_backtrace();
$this->query = "SELECT * FROM pbx_servicos_registra WHERE uniqueid = '$uniqueid'";
$result = $this->execute('assoc');
return $result;
}
#########################
### HELPERS INSTALL ###
#########################
public function getIdDirecionamento($tipo, $nome){
switch ($tipo) {
case CONF_URA:
return $this->getUraIdByName($nome) . "-" . $nome;
break;
case CONF_ANUNCIOS:
return $this->getAnuncioIdByName($nome);
break;
case CONF_HORARIO:
return $this->getHorarioIdByName($nome);
break;
case CONF_INTEGRACAO:
return $this->getIntegracaoMetodoByNameIntegracao($nome);
break;
case CONF_FILAS:
return $this->getFilaNumeroByName($nome);
break;
default:
break;
}
}
public function getNomeDirecionamento($tipo, $id){
$id = intval($id);
switch ($tipo) {
case CONF_URA:
return $this->getUraNameById($id);
break;
case CONF_ANUNCIOS:
return $this->getAnuncioNameById($id);
break;
case CONF_HORARIO:
return $this->getHorarioNameById($id);
break;
case CONF_INTEGRACAO:
return null;
break;
case CONF_FILAS:
return $this->getFilaNameByNumero($id);
break;
default:
break;
}
}
public function redirectUraDestino($ura, $status, $nomenclatura){
if(strpos($ura,$nomenclatura)!== false){
$ura_destinos = $this->getUraDestinosIdByUraName($ura);
}else{
$ura_destinos = $this->getUraDestinosIdByUraName($ura.$nomenclatura);
}
foreach($ura_destinos as $destino){
if($destino['numero'] == strtoupper($status)){
return array(
"TIPO" => str_replace("s","",trim($destino['tipo'])),
"NOME" => $this->getNomeDirecionamento(trim($destino['tipo']), $destino['comando'])
);
}
}
return array("TIPO" => "ANUNCIO", "NOME" => CONF_AUDIO_ERROR.$nomenclatura);//DEFAULT
}
}