forked from Claudio/integracao
Simples IP Desenvolvimento
2 years ago
32 changed files with 6774 additions and 260 deletions
@ -0,0 +1,7 @@
|
||||
<?php |
||||
|
||||
require_once "Movidesk.php"; |
||||
|
||||
$movidesk = new Movidesk(); |
||||
|
||||
$movidesk->startCanceledCall($id, $queueId, $clientNumber, $branchLine, $callDate, $canceledDate); |
@ -0,0 +1,432 @@
|
||||
<?php |
||||
|
||||
require_once 'phpagi/phpagi.php'; |
||||
require_once 'IntegracaoDataBase.php'; |
||||
require_once 'Logger.php'; |
||||
require_once 'SimpleMail.php'; |
||||
require_once 'conf.php'; |
||||
// include("util/util.php"); |
||||
|
||||
/* |
||||
|************************************************************************* |
||||
| SISTEMA UNICO DE INTEGRACAO * |
||||
|************************************************************************* |
||||
*/ |
||||
|
||||
/** |
||||
* Classe para implementacao das integracoes da Simples IP |
||||
* @author Lucas Awade |
||||
* @Desenvolvedor |
||||
* @SimplesIP |
||||
* @version 1.1.1 |
||||
*/ |
||||
class Integracao { |
||||
|
||||
protected $log; |
||||
protected $mail; |
||||
private $agi; |
||||
private $db; |
||||
|
||||
######################################################################## |
||||
## CONSTANTES DA CLASSE ## |
||||
######################################################################## |
||||
|
||||
const PATH_SOUND = '/var/lib/asterisk/sounds/customizados/'; |
||||
const AGI_ERROR_HANDLER = false; |
||||
|
||||
######################################################################## |
||||
## FUNCOES UTILITARIAS ## |
||||
######################################################################## |
||||
|
||||
/** |
||||
* - Retorno é os dados referentes ao retornado da API |
||||
* - Params são os dados que serão disponibilizados na tela do agente. |
||||
* |
||||
* @param array $retorno |
||||
* @param array $params |
||||
*/ |
||||
public function integracaoAgente($retorno, $params) { |
||||
$registros = 0; |
||||
$data = $this->db()->getRegistros(); |
||||
$retorno_cliente = "{$data['reg_uniqueid']}|{$data['reg_fone']}|{$data['id']}|"; |
||||
foreach ($retorno as $key => $value) { |
||||
if (in_array($key, $params)) { |
||||
$registros++; |
||||
$retorno_cliente .= sprintf("%s:%s", |
||||
strtoupper(str_replace("_", " ", $key)), |
||||
strtoupper(str_replace("|", "", $value))); |
||||
if (count($params) > $registros) { |
||||
$retorno_cliente .= "|"; |
||||
} |
||||
} |
||||
} |
||||
$this->db()->setRegistros(array('retorno_cliente' => $retorno_cliente)); |
||||
} |
||||
|
||||
/** |
||||
* Converte um CPF ou CNPJ com marcara referente a cada modelo. |
||||
* |
||||
* @param string $string |
||||
* @return boolean|string |
||||
*/ |
||||
protected function mask_cpf_cnpj($string) { |
||||
if (!empty($string)) { |
||||
if (strlen($string) == 11) { |
||||
$mask = "%s%s%s.%s%s%s.%s%s%s-%s%s"; |
||||
} elseif (strlen($string) == 14) { |
||||
$mask = "%s%s.%s%s%s.%s%s%s/%s%s%s%s-%s%s"; |
||||
} |
||||
return vsprintf($mask, str_split($string)); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Retorna telefone com o (DDD)Numero de acordo com o parametro passado caso nao possua DDD sera o padrao da central. |
||||
* @param string $telefone |
||||
* @return array |
||||
*/ |
||||
protected function mask_phone_tel($telefone) { |
||||
$retorno = array('telefone' => '', 'type' => ''); |
||||
if (strlen($telefone) == 11) { |
||||
$numero_1 = substr($telefone, 2, 5); |
||||
$numero_2 = substr($telefone, 7, 4); |
||||
$ddd = substr($telefone, 0, 2); |
||||
$telefone = "({$ddd}) " . $numero_1 . '-' . $numero_2; |
||||
$retorno['telefone'] = $telefone; |
||||
$retorno['type'] = 'celular'; |
||||
} else if (strlen($telefone) == 12) { |
||||
$ddd = substr($telefone, 1, 2); |
||||
$numero = substr($telefone, 3, 10); |
||||
$telefone = sprintf("(%s) %s", $ddd, $numero); |
||||
$retorno['telefone'] = $telefone; |
||||
$retorno['type'] = 'telefone'; |
||||
} else if (strlen($telefone) == 13) { |
||||
$ddd = substr($telefone, 2, 2); |
||||
$numero = substr($telefone, 4, 10); |
||||
$telefone = "(" . $ddd . ") " . $numero; |
||||
$retorno['telefone'] = $telefone; |
||||
$retorno['type'] = 'celular'; |
||||
} else if (strlen($telefone) == 10) { |
||||
$numero_1 = substr($telefone, 2, 4); |
||||
$numero_2 = substr($telefone, 6, 9); |
||||
$ddd = substr($telefone, 0, 2); |
||||
$telefone = "({$ddd}) " . $numero_1 . '-' . $numero_2; |
||||
$retorno['telefone'] = $telefone; |
||||
$retorno['type'] = 'fixo'; |
||||
} else { |
||||
return null; |
||||
} |
||||
return $retorno; |
||||
} |
||||
|
||||
/** |
||||
* Verifica se todos os parametros passados foram completados. |
||||
* |
||||
* @param array $args |
||||
* @return true|false |
||||
*/ |
||||
protected function getArgs($args) { |
||||
foreach ($args as $value) { |
||||
if (!$value) { |
||||
return false; |
||||
} |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
/** |
||||
* Verifica a diferenca em dias entre a data de entrada e a data atual. |
||||
* |
||||
* @param type $dateParam |
||||
* @return type |
||||
*/ |
||||
public function dateDiff($dateParam) { |
||||
$dateIni = strtotime(date('Y-m-d')); |
||||
|
||||
if (strstr($dateParam, "/")) { |
||||
$dateParam = date(strtotime(str_replace('/', '-', $dateParam))); |
||||
} else { |
||||
$dateParam = date(strtotime($dateParam)); |
||||
} |
||||
|
||||
$diff = ($dateIni - $dateParam); |
||||
$days = (int) floor($diff / (60 * 60 * 24)); |
||||
|
||||
return $days; |
||||
} |
||||
|
||||
/** |
||||
* Realiza a conversao de datas no formato brasileiro para a Defualt. |
||||
* @param string $data |
||||
* @return string|boolean |
||||
*/ |
||||
public function convertDateDefault($data) { |
||||
if ($data) { |
||||
$data = explode('/', $data); |
||||
return "{$data[2]}-{$data[1]}-{$data[0]}"; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Realiza a validação de pendencia financeira de acordo com a data informada |
||||
* |
||||
* OBS: O array deve possui nível = array( array('data' => 'yyyy-mm-dd')) |
||||
* OBS: O indice deve ser o nome do valor onde se encontra a data. |
||||
* @param array $array |
||||
* @param string $indice |
||||
* @param string $datavalida |
||||
* @return boolean |
||||
*/ |
||||
public function verificaDataPendencia($array, $indice, $datavalida = null) { |
||||
if (!$datavalida) { |
||||
$datavalida = strototime(date('Y-m-d')); |
||||
} else { |
||||
$datavalida = strtotime($datavalida); |
||||
} |
||||
|
||||
foreach ($array as $value) { |
||||
if (strtotime($value[$indice]) < $datavalida) { |
||||
return false; |
||||
} |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
/** |
||||
* Adiciona mascara no telefone para realizar a consulta |
||||
* |
||||
* @param type $value |
||||
* @return boolean |
||||
*/ |
||||
protected function phoneMask($value) { |
||||
if (!empty($value)) { |
||||
if (strlen($value) == 10) { |
||||
$mask = '(%s%s)%s%s%s%s-%s%s%s%s'; |
||||
} elseif (strlen($value) == 11) { |
||||
$mask = '(%s%s)%s%s%s%s%s-%s%s%s%s'; |
||||
} |
||||
return vsprintf($mask, str_split($value)); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Verifica se um servidor esta dando resposta de ping |
||||
* @param type $ip |
||||
* @return boolean |
||||
*/ |
||||
public function verificaLatencia($ip) { |
||||
$ping = explode(",", shell_exec("ping -c 4 $ip")); |
||||
$latencia = substr($ping[1], 1, 2); //resposta do ping |
||||
if ($latencia >= 2) { |
||||
return true; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Verbaliza digitos |
||||
* @param string|int $string |
||||
*/ |
||||
public function verbaliza($string) { |
||||
$vocaliza = str_split($string); |
||||
foreach ($vocaliza as $value) { |
||||
$this->agi()->say_digits($value); |
||||
} |
||||
} |
||||
|
||||
/* |
||||
* Objetct to array |
||||
*/ |
||||
|
||||
public function objectToArray($d) { |
||||
if (is_object($d)) { |
||||
$d = get_object_vars($d); |
||||
} |
||||
if (is_array($d)) { |
||||
return array_map($this->objectToArray(), $d); |
||||
} else { |
||||
return $d; |
||||
} |
||||
} |
||||
|
||||
############################################################################ |
||||
######## CONFIGURACAO DE EMAIL ######## |
||||
############################################################################ |
||||
|
||||
/** |
||||
* Inicia a instanciacao da Classe para envio de Email |
||||
* @param string $email |
||||
* @param string $password |
||||
* @param string $subject |
||||
*/ |
||||
public function SimpleMail($email, $password, $subject) { |
||||
$this->mail = new SimpleMail($email, $password, $subject); |
||||
$this->log->debug("Instanciacao SimpleMail : " . ($this->mail ? "SUCCESS" : "FAIL"), debug_backtrace()); |
||||
} |
||||
|
||||
/** |
||||
* Configura o servidor de Envio dos Emails. |
||||
* @param string $host |
||||
* @param string|int $port |
||||
* @param string $title |
||||
* @return boolean |
||||
*/ |
||||
public function confSMTP($host, $port, $title, $smtpAuth = true, $smtpSecure = 'TLS', $charset = 'UTF8') { |
||||
$this->log->debug("Configuracao SMTP", debug_backtrace()); |
||||
if ($this->mail) { |
||||
$this->mail->config($host, $port, $title, $smtpAuth, $smtpSecure, $charset); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
public function geraProtocoloSimples($uid){ |
||||
$connPG = $this->db()->getConnection(); |
||||
$protoAgente = GeraProtocolo($connPG, $uid); |
||||
return $protoAgente; |
||||
} |
||||
######################################################################## |
||||
## FUNCOES IMPORTANTES ## |
||||
######################################################################## |
||||
|
||||
/** |
||||
* Instancia um objeto de Logger. |
||||
* |
||||
* @param Logger $log |
||||
*/ |
||||
protected function setLog($log = false) { |
||||
if (!$this->log) { |
||||
$this->log = new Logger(CONF_LOGGER_PATH . CONF_NOME_EMPRESA, $log); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Retorna o objeto de Log. |
||||
* @return string |
||||
*/ |
||||
public function log() { |
||||
return $this->log; |
||||
} |
||||
|
||||
/** |
||||
* Instancia um objeto de AGI para se conectar com as informações do Asterisk. |
||||
* |
||||
* @return AGI |
||||
*/ |
||||
public function agi() { |
||||
if (!$this->agi) { |
||||
$data = $this->db()->getAuthAgi(); |
||||
$config = array(); |
||||
$config['phpagi']['error_handler'] = self::AGI_ERROR_HANDLER; |
||||
$config['asmanager']['server'] = $data['host_sck']; |
||||
$config['asmanager']['port'] = $data['porta_sck']; |
||||
$config['asmanager']['username'] = $data['usuario_sck']; |
||||
$config['asmanager']['secret'] = $data['senha_sck']; |
||||
$agi = new AGI('phpagi.conf', $config); |
||||
$this->agi = $agi; |
||||
return $agi; |
||||
} |
||||
return $this->agi; |
||||
} |
||||
|
||||
private function readAgiVariable() { |
||||
ob_implicit_flush(true); |
||||
set_time_limit(6); |
||||
$in = fopen("php://stdin", "r"); |
||||
$input = str_replace("\n", "", fgets($in, 4096)); |
||||
fclose($in); |
||||
$this->log->debug("Reading: " . $input); |
||||
return $input; |
||||
} |
||||
|
||||
public function getAgiVariable($variable = null) { |
||||
$this->log->debug("Executing...", debug_backtrace()); |
||||
while ($env = $this->readAgiVariable()) { |
||||
$s = explode(": ", $env); |
||||
$agi[str_replace("agi_", "", $s[0])] = trim($s[1]); |
||||
$this->log->debug("Data: " . print_r($agi, true), debug_backtrace()); |
||||
if (($env == "") || ($env == "\n")) { |
||||
break; |
||||
} |
||||
} |
||||
$this->log->debug("Reading: " . print_r($agi, true)); |
||||
if (!$variable || $agi[$variable]) { |
||||
return !$variable ? $agi : $agi[$variable]; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Instancia um objeto de IntegracaoDataBase para se conectar com dados do |
||||
* Banco de dados e credenciais do Manager. |
||||
* |
||||
* @return IntegracaoDataBase |
||||
*/ |
||||
public function db() { |
||||
if (!$this->db) { |
||||
$db = new IntegracaoDataBase(); |
||||
$this->db = $db; |
||||
} |
||||
return $this->db; |
||||
} |
||||
|
||||
protected function audioError() { |
||||
$this->log->debug('Audio de error'); |
||||
$exten = $this->db()->getAnuncio(); |
||||
$this->log->error('Encaminhando para áudio alternativo de Erros', debug_backtrace()); |
||||
$this->agi()->exec_goto($exten); |
||||
exit(); |
||||
} |
||||
|
||||
protected function integracaoReg(){ |
||||
global $ura, $tronco, $uid, $idMetodo, $uidOld, $numero; |
||||
$registros = array( |
||||
"id" => '', |
||||
"reg_ura" => $ura, |
||||
"reg_tronco" => $tronco, |
||||
"reg_uniqueid" => $uid, |
||||
"reg_id_metodo" => $idMetodo, |
||||
"reg_uniqueid" => $uid, |
||||
"reg_uniqueid_old" => $uidOld, |
||||
"reg_fone" => $numero, |
||||
"reg_status_exec" => '1', |
||||
"reg_inicio" => date()); |
||||
|
||||
$this->db()->setRegistros($registros); |
||||
|
||||
if (CONF_AUDIO_ERROR) { |
||||
$this->db()->setIdAudioError($this->db()->getAnuncioIdByName(strtoupper(CONF_AUDIO_ERROR.CONF_NOME_EMPRESA.CONF_VERSAO))); |
||||
} |
||||
} |
||||
|
||||
public function executarFluxo($tipo, $nome){ |
||||
#INEGRACAO DE TELA |
||||
if(CONF_INTEGRACAO_TELA){ |
||||
$parametrosTela = unserialize(CONF_PARAMETROS_TELA); |
||||
|
||||
$itgcTela = array(); |
||||
$itgcTelaNomes = array(); |
||||
|
||||
foreach($parametrosTela as $parametro){ |
||||
$itgcTela[$parametro] = str_replace(array("|",":"),"-",utf8_decode($this->agi()->get_variable($parametro, true))); |
||||
$itgcTelaNomes[] = "$parametro"; |
||||
|
||||
} |
||||
|
||||
$this->integracaoAgente($itgcTela, $itgcTelaNomes); |
||||
|
||||
} |
||||
|
||||
$dbFunction = "get".ucfirst(strtolower($tipo));//CONTRUIR NOME FUNCAO BUSCAR ID |
||||
$this->agi()->exec_goto($this->db()->$dbFunction(strtoupper($nome)));//REDIRECIONAR FLUXO |
||||
|
||||
|
||||
$this->db()->atualizaIntegracao(); |
||||
} |
||||
} |
||||
|
@ -0,0 +1,929 @@
|
||||
<?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çõ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ém de gravar logs de registros de dados, |
||||
* e qualquer erro é repassado a classe que está 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á 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(); |
||||
} |
||||
|
||||
######################################################################## |
||||
#### 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 DESTINO ######################### |
||||
/* |
||||
* 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; |
||||
} |
||||
|
||||
######################### 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){ |
||||
$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 |
||||
} |
||||
} |
||||
|
@ -0,0 +1,157 @@
|
||||
<?php |
||||
|
||||
/** |
||||
* Classe para utilizar |
||||
* |
||||
* @documentation: |
||||
* @author Lucas Awade |
||||
* @function developer |
||||
* @company SimplesIP |
||||
* @version 1.0.0 |
||||
*/ |
||||
class Logger { |
||||
/* |
||||
* GENERATE LOG |
||||
*/ |
||||
|
||||
private $active; |
||||
private $log; |
||||
private $type; |
||||
private $text; |
||||
|
||||
/* |
||||
* CONF. FILE LOG |
||||
*/ |
||||
private $file; |
||||
private $path; |
||||
private $name; |
||||
|
||||
/* |
||||
* CONST. MESSAGE TYPE |
||||
*/ |
||||
|
||||
const LOG_SUCCESS = "SUCCESS"; |
||||
const LOG_DEBUG = "DEBUG"; |
||||
const LOG_INFO = "INFO"; |
||||
const LOG_WARNING = "WARNING"; |
||||
const LOG_ERROR = "ERROR"; |
||||
|
||||
public function __construct($nameLog, $active = false, $path = "/var/log/asterisk/") { |
||||
$this->name = $nameLog; |
||||
$this->path = $path; |
||||
$this->active = $active; |
||||
$this->config($nameLog); |
||||
} |
||||
|
||||
######################################################################## |
||||
## TYPES ## |
||||
######################################################################## |
||||
|
||||
public function success($log, $debug_trace = null) { |
||||
$this->type = self::LOG_SUCCESS; |
||||
$this->text = $log; |
||||
$this->header($log, $debug_trace ? $debug_trace : debug_backtrace()); |
||||
$this->write(); |
||||
} |
||||
|
||||
public function debug($log, $debug_trace = null) { |
||||
$this->type = self::LOG_DEBUG; |
||||
$this->text = $log; |
||||
$this->header($log, $debug_trace ? $debug_trace : $this->name); |
||||
$this->write(); |
||||
} |
||||
|
||||
public function info($log, $debug_trace = null) { |
||||
$this->type = self::LOG_INFO; |
||||
$this->text = $log; |
||||
$this->header($log, $debug_trace ? $debug_trace : $this->name); |
||||
$this->write(); |
||||
} |
||||
|
||||
public function error($log, $debug_trace = null) { |
||||
$this->type = self::LOG_ERROR; |
||||
$this->text = $log; |
||||
$this->header($log, $debug_trace ? $debug_trace : $this->name); |
||||
$this->write(); |
||||
} |
||||
|
||||
public function warning($log, $debug_trace = null) { |
||||
$this->type = self::LOG_WARNING; |
||||
$this->text = $log; |
||||
$this->header($log, $debug_trace ? $debug_trace : $this->name); |
||||
$this->write(); |
||||
} |
||||
|
||||
######################################################################## |
||||
## IMPORTANT ## |
||||
######################################################################## |
||||
|
||||
private function write() { |
||||
if ($this->active) { |
||||
file_put_contents($this->file, $this->log, FILE_APPEND); |
||||
} |
||||
} |
||||
|
||||
private function header($log, $debug_trace) { |
||||
$this->log = "________________________________________________________________________________________\n"; |
||||
if(is_array($debug_trace)){ |
||||
$method = $debug_trace[0]['class'] ? "{$debug_trace[0]['class']}::{$debug_trace[0]['function']}" : $debug_trace[0]['function']; |
||||
$args = null; |
||||
|
||||
if(count($debug_trace[0]['args']) > 0){ |
||||
foreach($debug_trace[0]['args'] as $key => $arg){ |
||||
$x++; |
||||
$args .= $arg; |
||||
if(count($debug_trace[0]['args']) != $x){ |
||||
$args .= ","; |
||||
} |
||||
} |
||||
} |
||||
$this->log .= sprintf("\n[ %s ][ LINE %s ][ %s ][ ARGS ($args) ][ %s ]\n\n", date('d/m/Y H:i:s'), $debug_trace[0]['line'], $method, $this->type); |
||||
} else { |
||||
$this->log .= sprintf("\n[ %s ][ %s ][ %s ]\n\n", date('d/m/Y H:i:s'), $debug_trace, $this->type); |
||||
} |
||||
$this->log .= "> " . $log; |
||||
$this->log .= "\n\n ---------------------------------- [ FINISH LOGGER ] ----------------------------------\n\n"; |
||||
} |
||||
|
||||
public function openLog() { |
||||
//$file = fopen($this->file, 'rb'); |
||||
} |
||||
|
||||
public function locateLog() { |
||||
echo "\n\n {$this->file} \n\n"; |
||||
} |
||||
|
||||
######################################################################## |
||||
## CONFIGS ## |
||||
######################################################################## |
||||
|
||||
public function config($name, $exten = ".log", $prefix = null) { |
||||
if (file_exists($this->file)) { |
||||
$contents = file_get_contents($this->file); |
||||
} |
||||
|
||||
$this->file = trim($this->path . $prefix . ($name ? $name : $this->name) . $exten); |
||||
file_put_contents($this->file, $contents ? $contents : "", FILE_APPEND); |
||||
} |
||||
|
||||
public function getType() { |
||||
return $this->type; |
||||
} |
||||
|
||||
public function getText(){ |
||||
return $this->text; |
||||
} |
||||
|
||||
public function setLogger($active) { |
||||
if ($this->active === true) { |
||||
$this->active = $active; |
||||
} else if ($active === false) { |
||||
$this->active = $active; |
||||
} else { |
||||
$this->active = true; |
||||
} |
||||
} |
||||
|
||||
} |
@ -0,0 +1,431 @@
|
||||
<?php |
||||
|
||||
require_once 'Integracao.php'; |
||||
include_once 'config.php'; |
||||
|
||||
/** |
||||
* DESCRICAO DO DESENVOLVEDOR |
||||
* @documentation https://atendimento.movidesk.com/kb/pt-br/article/32178/api-do-movidesk-telefonia-sem-controle-da-fila |
||||
* @documentation https://atendimento.movidesk.com/kb/pt-br/article/18625/api-do-movidesk-telefonia |
||||
* @author Lucas Awade |
||||
* @function developer |
||||
* @company SimplesIP |
||||
* @version 1.0.0 |
||||
*/ |
||||
class Movidesk extends Integracao { |
||||
|
||||
private $token; |
||||
private $url; |
||||
private $metodo; |
||||
private $query; |
||||
private $curl; |
||||
private $debug; |
||||
private $params = array(); |
||||
|
||||
######################################################################## |
||||
## FUNCOES DA API ## |
||||
######################################################################## |
||||
|
||||
/** |
||||
* Inicia a transferencia para o ramal! |
||||
* Request = GET |
||||
* OBS: Sem Controle de Fila |
||||
* @param string $id = uniqueid da Chamada |
||||
* @param string $queueId = Id da Fila |
||||
* @param string $clientNumber = Numero de Origem |
||||
* @param string $branchLine = Ramal do agente para qual a chamada foi transferida. |
||||
* @param timestamp $callDate = Data da ligacao | Formato -> [2020-01-01 00:00:00] |
||||
* @param timestamp $transferDate = Data da transferencia | Formato -> [2020-01-01 00:00:00] |
||||
* @return boolean |
||||
*/ |
||||
public function startTransferedCall($id, $queueId, $clientNumber, $branchLine, $callDate, $transferDate) { |
||||
$this->debug = debug_backtrace(); |
||||
$this->log->debug("uniqueid: $id,$queueId, $clientNumber, $branchLine, $callDate, $transferDate"); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->setMetodo("asterisk_startTransferedCall"); |
||||
$this->request('GET'); |
||||
$this->params['queueId'] = $queueId; |
||||
$this->params['clientNumber'] = $clientNumber; |
||||
$this->params['id'] = $id; |
||||
$this->params['branchLine'] = $branchLine; |
||||
$this->params['callDate'] = $this->dateUTC($callDate); |
||||
$this->params['transferDate'] = $this->dateUTC($transferDate); |
||||
return $this->setParams(); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Informa que a chamada foi abandonada/cancelada |
||||
* Request = GET |
||||
* OBS: Sem Controle de Fila |
||||
* @param string $id = uniqueid da Chamada |
||||
* @param string $queueId = Id da Fila |
||||
* @param string $clientNumber = Numero de Origem |
||||
* @param timestamp $callDate = Data da ligacao | Formato -> [2020-01-01 00:00:00] |
||||
* @param timestamp $canceledDate = Data da transferencia | Formato -> [2020-01-01 00:00:00] |
||||
* @return boolean |
||||
*/ |
||||
public function startCanceledCall($id, $queueId, $clientNumber, $callDate, $canceledDate) { |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->setMetodo("asterisk_startCanceledCall"); |
||||
$this->request('GET'); |
||||
$this->params['queueId'] = $queueId; |
||||
$this->params['clientNumber'] = $clientNumber; |
||||
$this->params['id'] = $id; |
||||
$this->params['callDate'] = $this->dateUTC($callDate); |
||||
$this->params['canceledDate'] = $this->dateUTC($canceledDate); |
||||
return $this->setParams(); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Informa que a chamada foi recebida |
||||
* Request = POST |
||||
* OBS: Com Controle de Fila |
||||
* |
||||
* @param string $id = uniqueid da Chamada |
||||
* @param string $queueId = Id da Fila |
||||
* @param string $clientNumber = Numero de Origem |
||||
* @param string $branchLine = Ramal do agente para qual a chamada foi transferida. |
||||
* @param timestamp $callDate = Data da ligacao | Formato -> [2020-01-01 00:00:00] |
||||
* @param string $request |
||||
* @return boolean |
||||
*/ |
||||
public function receivedCall($id, $queueId, $clientNumber, $branchLine, $callDate) { |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->setMetodo("asterisk_receivedCall"); |
||||
$this->request("POST"); |
||||
$this->params['queueId'] = $queueId; |
||||
$this->params['clientNumber'] = $clientNumber; |
||||
$this->params['id'] = $id; |
||||
$this->params['branchLine'] = $branchLine; |
||||
$this->params['callDate'] = $this->dateUTC($callDate); |
||||
return $this->setParams(); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Informa que a chamada foi transferida |
||||
* Request = POST |
||||
* OBS: Com Controle de Fila |
||||
* @param string $id = uniqueid da Chamada |
||||
* @param string $queueId = Id da Fila |
||||
* @param string $branchLine = Ramal do agente para qual a chamada foi transferida. |
||||
* @param timestamp $transferDate = Data da ligacao | Formato -> [2020-01-01 00:00:00] |
||||
* @return boolean |
||||
*/ |
||||
public function transferedCall($id, $queueId, $branchLine, $transferDate) { |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->setMetodo("asterisk_transferedCall"); |
||||
$this->request('POST'); |
||||
$this->params['queueId'] = $queueId; |
||||
$this->params['id'] = $id; |
||||
$this->params['branchLine'] = $branchLine; |
||||
$this->params['transferDate'] = $this->dateUTC($transferDate); |
||||
return $this->setParams(); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Informa que a chamada foi Completada |
||||
* Request = POST |
||||
* OBS: Com Controle de Fila |
||||
* @param string $id = uniqueid da Chamada |
||||
* @param string $link = link do audio da Chamada |
||||
* @param string $completedDate = Data da ligacao | Formato -> [2020-01-01 00:00:00] |
||||
* @return boolean |
||||
*/ |
||||
public function completedCall($id, $completedDate, $link = '', $request = 'GET') { |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->setMetodo("asterisk_completedCall"); |
||||
$this->request(strtoupper($request) == 'GET' ? strtoupper($request) : strtoupper("POST")); |
||||
$this->params['link'] = $link; |
||||
$this->params['id'] = $id; |
||||
$this->params['completedDate'] = $this->dateUTC($completedDate); |
||||
return $this->setParams(); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Informa que a chamada foi Perdida |
||||
* Request = POST |
||||
* OBS: Com Controle de Fila |
||||
* @param string $id = uniqueid da Chamada |
||||
* @param string $link = link do audio da Chamada |
||||
* @param string $completedDate = Data da ligacao | Formato -> [2020-01-01 00:00:00] |
||||
* @return boolean |
||||
*/ |
||||
public function lostCall($id, $link, $completedDate) { |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->setMetodo("asterisk_lostCall"); |
||||
$this->request('POST'); |
||||
$this->params['link'] = $link; |
||||
$this->params['id'] = $id; |
||||
$this->params['transferDate'] = $this->dateUTC($completedDate); |
||||
return $this->setParams(); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Informa que a chamada foi cancelada |
||||
* Request = POST |
||||
* OBS: Com Controle de Fila |
||||
* @param string $id = uniqueid |
||||
* @param string $canceledDate = Data da ligacao | Formato -> [2020-01-01 00:00:00] |
||||
* @return boolean |
||||
*/ |
||||
public function canceledCall($id, $canceledDate) { |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->setMetodo("asterisk_canceledCall"); |
||||
$this->request('POST'); |
||||
$this->params['id'] = $id; |
||||
$this->params['transferDate'] = $this->dateUTC($canceledDate); |
||||
return $this->setParams(); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Cria um ticket na plataforma de acordo com os dados passados. |
||||
* @param int $id |
||||
* @param int $type |
||||
* @param string $status |
||||
* @param string $email |
||||
* @param string $telefone |
||||
* @param string $descricao |
||||
* @return boolean|array |
||||
*/ |
||||
public function createTicket($id, $type, $status, $personType, $profileType, $email, $telefone, $descricao) { |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->setMetodo("tickets"); |
||||
$this->request('POST'); |
||||
$this->params['type'] = $type; |
||||
$this->params['urgency'] = $status; |
||||
$this->params['origin'] = 9; |
||||
$this->params['createdBy'] = array("id" => $id); |
||||
$this->params['clients'] = array( |
||||
array( |
||||
"id" => $id, |
||||
"personType" => $personType, |
||||
"profileType" => $profileType, |
||||
"businessName" => $id, |
||||
"email" => $email, |
||||
"phone" => $telefone |
||||
) |
||||
); |
||||
|
||||
$this->params['actions'] = array( |
||||
array( |
||||
"type" => $type, |
||||
"origin" => 9, |
||||
"description" => $descricao |
||||
) |
||||
); |
||||
|
||||
return $this->setParams(); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
######################################################################## |
||||
## FUNCOES DEFAULT DA CLASSE ## |
||||
######################################################################## |
||||
|
||||
/** |
||||
* Coleta as informacoes iniciais para o inicio da integracao com a API. |
||||
* |
||||
* @param string $token |
||||
* @param string $url |
||||
* @param boolean $log |
||||
*/ |
||||
public function __construct() { |
||||
$this->token = CONF_TOKEN_API; |
||||
$this->url = CONF_URL_API ; |
||||
$this->setLog(CONF_LOGGER_ATIVO); |
||||
$this->integracaoReg(); |
||||
$this->log->info("Iniciando integracao", debug_backtrace()); |
||||
} |
||||
|
||||
private function dateUTC($data) { |
||||
$dt = new DateTime($data); |
||||
$dt->setTimeZone(new DateTimeZone('UTC')); |
||||
return $dt->format('Y-m-d\TH:i:s'); |
||||
} |
||||
|
||||
/** |
||||
* Informa o tipo de requisicao que sera feita pela cURL |
||||
* @param bool $request |
||||
*/ |
||||
private function request($request = null) { |
||||
if (!$this->request || $request) { |
||||
$this->request = (strtoupper($request) == 'POST' ? strtoupper($request) : "GET"); |
||||
} |
||||
$this->log->debug("HTTP Request: " . $this->request, debug_backtrace()); |
||||
return $this->request; |
||||
} |
||||
|
||||
/** |
||||
* Parametriza o metodo utilizado para a consulta. |
||||
* |
||||
* @param type $metodo |
||||
*/ |
||||
private function setMetodo($metodo) { |
||||
$this->metodo = $metodo; |
||||
} |
||||
|
||||
/** |
||||
* Escreve a query para ser passada para o curl |
||||
* |
||||
* @param string $query |
||||
*/ |
||||
private function setQuery($query) { |
||||
return $this->query .= $query; |
||||
} |
||||
|
||||
/** |
||||
* retorna a string pronta da query do curl e limpa a variavel. |
||||
* |
||||
* @return string $query |
||||
*/ |
||||
private function getQuery() { |
||||
$query = $this->query; |
||||
unset($this->query); |
||||
return $query; |
||||
} |
||||
|
||||
/** |
||||
* Constroi de forma dinamica a string para ser passada para a execucao do Curl |
||||
* |
||||
* @void |
||||
*/ |
||||
private function curl() { |
||||
$this->log->debug("Query: " . $this->query, debug_backtrace()); |
||||
$header = array('Content-Type: application/json; charset=utf-8'); |
||||
$this->curl = curl_init(); |
||||
curl_setopt($this->curl, CURLOPT_URL, $this->url . $this->metodo . ($this->request() == "GET" ? $this->getQuery() : null)); |
||||
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1); |
||||
if ($this->request() == "POST") { |
||||
curl_setopt($this->curl, CURLOPT_POST, 1); |
||||
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->getQuery()); |
||||
$header[] = "token: " . $this->token; |
||||
} |
||||
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); |
||||
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false); |
||||
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header); |
||||
/* |
||||
* Final da linha para pegar os dados da variavel |
||||
*/ |
||||
$this->log->debug("Curl: {$this->curl}", debug_backtrace()); |
||||
} |
||||
|
||||
/** |
||||
* Recebe array de forma de indice e valor |
||||
* |
||||
* @example array("qtype" => 'test_api', "query" => '123', "oper" => '=') |
||||
* |
||||
* @obs sempre chamar a função debug_backtrace() para ser disponível em log |
||||
* |
||||
* @param type $params |
||||
* @debug_track function debug_backtrace() |
||||
*/ |
||||
private function setParams() { |
||||
|
||||
$x = 0; |
||||
if ($this->request() == "POST") { |
||||
$this->setQuery("{"); |
||||
foreach ($this->params as $key => $param) { |
||||
$x++; |
||||
if (is_array($param[0])) { |
||||
$this->log->debug("Data: " . print_r($param[0], true), debug_backtrace()); |
||||
$this->setQuery(sprintf('"%s": [%s]', $key, json_encode($param[0]))); |
||||
} else if (is_array($param)) { |
||||
$this->setQuery(sprintf('"%s" : {', $key)); |
||||
foreach($param as $k => $val){ |
||||
$this->setQuery(sprintf('"%s": %s', $k, $val)); |
||||
} |
||||
$this->setQuery("}"); |
||||
} else { |
||||
$this->setQuery("\"{$key}\": \"$param\""); |
||||
} |
||||
if ($x == count($this->params)) { |
||||
$this->setQuery("} "); |
||||
} else { |
||||
$this->setQuery(","); |
||||
} |
||||
unset($param); |
||||
} |
||||
} else { |
||||
if ($this->params) { |
||||
$this->setQuery("?token={$this->token}&"); |
||||
foreach ($this->params as $key => $value) { |
||||
$this->setQuery("{$key}=$value"); |
||||
if (count($this->params) != ++$x) { |
||||
$this->setQuery("&"); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
unset($this->params); |
||||
$response = $this->exec(); |
||||
return $this->response($response); |
||||
} |
||||
|
||||
/** |
||||
* Recebe as informações e realiza a execucao da API |
||||
* |
||||
* @void |
||||
*/ |
||||
private function exec() { |
||||
$respondeCurl = array(); |
||||
$this->curl(); |
||||
$response = curl_exec($this->curl); |
||||
if (curl_errno($this->curl)) { |
||||
$this->log->error(curl_error($this->curl), debug_backtrace()); |
||||
curl_close($this->curl); |
||||
// $this->audioError(); |
||||
return false; |
||||
} |
||||
$respondeCurl['execute'] = json_decode($response, true); |
||||
$respondeCurl['curl_response'] = curl_getinfo($this->curl, CURLINFO_HTTP_CODE); |
||||
curl_close($this->curl); |
||||
return $respondeCurl; |
||||
} |
||||
|
||||
/** |
||||
* Prepara dos dados para ser transmitidos para o metodo a ser retornado a |
||||
* integracao. |
||||
* |
||||
* @return array |
||||
*/ |
||||
private function response($data) { |
||||
$this->log->debug("Reponse API: " . print_r($data, true), $this->debug); |
||||
if ($data) { |
||||
return $data; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
} |
||||
|
@ -0,0 +1,258 @@
|
||||
<?php |
||||
|
||||
/** |
||||
* Classe para implementacao envio de Emails em Massa ou único! |
||||
* |
||||
* @author Lucas Awade |
||||
* @Desenvolvedor |
||||
* @version 1.1.0 |
||||
*/ |
||||
require("phpmailer/class.phpmailer.php"); |
||||
|
||||
class SimpleMail { |
||||
######################################################################## |
||||
## CONFIGURACOES CLASSE ## |
||||
######################################################################## |
||||
|
||||
private $log; |
||||
private $limit; |
||||
private $sended = 0; |
||||
private $mailer; |
||||
|
||||
######################################################################## |
||||
## CONFIGURACOES MAIL ## |
||||
######################################################################## |
||||
private $host; |
||||
private $port; |
||||
private $smtpAuth; |
||||
private $smtpSecure; |
||||
private $charset; |
||||
private $mail; |
||||
private $passwd; |
||||
private $title; |
||||
private $subject; |
||||
|
||||
######################################################################## |
||||
## CONFIGURACOES DEFAULT ## |
||||
######################################################################## |
||||
|
||||
public function __construct($mail, $passwd, $subject, $logger = false) { |
||||
$this->log = new Logger('simplesmailer', $logger, "/var/log/"); |
||||
if ($mail && $passwd && $subject) { |
||||
$this->mail = $mail; |
||||
$this->passwd = $passwd; |
||||
$this->subject = $subject; |
||||
$this->phpMailer(); |
||||
} else { |
||||
$this->log->error('Nao foi possivel instanciar a Classe SimplesMail,informacoes incompletas!', debug_backtrace()); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Metodo de configuração do Host de Envio; |
||||
* @param string $host |
||||
* @param string|int $port |
||||
* @param string $title |
||||
* @param boolean $smtpAuth |
||||
* @param string $smtpSecure |
||||
* @param string $charset |
||||
*/ |
||||
public function config($host, $port, $title, $smtpAuth = true, $smtpSecure = 'TLS', $charset = 'UTF8') { |
||||
$this->host = $host; |
||||
$this->port = $port; |
||||
$this->title = $title; |
||||
$this->smtpAuth = $smtpAuth; |
||||
$this->smtpSecure = $smtpSecure; |
||||
$this->charset = $charset; |
||||
$this->phpMailer(); |
||||
} |
||||
|
||||
/** |
||||
* Informa um limite de email em massa a ser enviado. |
||||
* |
||||
* @param int $limit |
||||
*/ |
||||
public function limitSend($limit) { |
||||
$this->log->debug('Limite de Email: ' . $limit, debug_backtrace()); |
||||
$this->limit = $limit; |
||||
} |
||||
|
||||
/** |
||||
* Mensagem escrito em HTML para envio de um email elaborado. |
||||
* |
||||
* Os dados em $data devem ser em formato array como o exemplo: |
||||
* array("MSG_HEADER" => 'Seja Bem vindo', "MSG_FOOTER" => 'Volte Sempre'); |
||||
* |
||||
* @param string $path |
||||
* @param array $data |
||||
*/ |
||||
public function pathBodyMail($path, $data) { |
||||
$this->log->info('Path HTML Body: ' . $path, debug_backtrace()); |
||||
$contents = file_get_contents($path); |
||||
foreach ($data as $key => $value) { |
||||
$contents = str_replace($key, $value, $contents); |
||||
} |
||||
$this->mailer->Body = $contents; |
||||
} |
||||
|
||||
/** |
||||
* Mensagem simples para o envio rapido de um email. |
||||
* |
||||
* @param string $message |
||||
*/ |
||||
public function bodyMessage($message) { |
||||
$this->mailer->Body = $message; |
||||
} |
||||
|
||||
/** |
||||
* Adiciona no email anexos para serem enviados |
||||
* @param array|string $files |
||||
*/ |
||||
public function setAddAttachment($files) { |
||||
if ($files) { |
||||
if (is_array($files)) { |
||||
foreach ($files as $name => $file) { |
||||
$this->mailer->AddAttachment($file, (is_numeric($name) ? '' : $name)); |
||||
} |
||||
} else { |
||||
$this->mailer->AddAttachment($files); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Adiciona no email imagens para visualizadas. |
||||
* |
||||
* #=> Caso o paramtro for um array seu corpo deve ser enviado da seguinte forma: |
||||
* $cid = array('minha_img_jpg' => 'img/path/mail/header.jpg'); |
||||
* |
||||
* #=> Caso for uma string deve se passar o cid caso contrario gera um cid randomico; |
||||
* |
||||
* @param array|string $images |
||||
*/ |
||||
public function setAddEmbeddedImage($images, $cid = null) { |
||||
if ($images) { |
||||
if (is_array($images)) { |
||||
foreach ($images as $name => $image) { |
||||
$this->mailer->AddEmbeddedImage($image, $name); |
||||
} |
||||
} else { |
||||
$cid = $cid ? $cid : rand(100, 999999); |
||||
$this->mailer->AddEmbeddedImage($image, $cid); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Esta funcao envia os email em massa ou unicos. |
||||
* |
||||
* Email em massa é necessario passar um array com os emails seu indice que representa o email. |
||||
* |
||||
* Email unico so é preciso passar o email na variavel $data; |
||||
* |
||||
* @param array|string $data |
||||
* @param string $indice |
||||
* @return array|boolean |
||||
*/ |
||||
public function mailing($data, $indice = '') { |
||||
if (is_array($data)) { |
||||
$invalid = array(); |
||||
foreach ($data as $mail) { |
||||
if ($this->sended <= $this->limit) { |
||||
$mail = $indice ? $mail[$indice] : $mail; |
||||
$this->setSended(); |
||||
if (!$this->send($mail)) { |
||||
$invalid[] = $mail; |
||||
} |
||||
} |
||||
} |
||||
return $invalid; |
||||
} else { |
||||
if ($this->send($data)) { |
||||
$this->setSended(); |
||||
return true; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
} |
||||
|
||||
public function getErrorSend(){ |
||||
return $this->mailer->ErrorInfo; |
||||
} |
||||
|
||||
######################################################################## |
||||
## ENVIO MAIL ## |
||||
######################################################################## |
||||
|
||||
/** |
||||
* Gerencia a quantidade de email que esta sendo enviado. |
||||
*/ |
||||
private function setSended() { |
||||
$this->sended++; |
||||
} |
||||
|
||||
/** |
||||
* Gerencia o envio do email para estar sempre no limite de envio. |
||||
* |
||||
* @return boolean |
||||
*/ |
||||
public function getSended() { |
||||
$this->log->debug("Sended: " . $this->sended, debug_backtrace()); |
||||
if ($this->sended < $this->limit) { |
||||
return true; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Metodo responsavel para realizar o envio do email. |
||||
* |
||||
* @param string $mailFrom |
||||
* @return boolean |
||||
*/ |
||||
private function send($mailFrom) { |
||||
if (!$this->mailer) { |
||||
$this->log->error("Objeto nao criado!", debug_backtrace()); |
||||
return false; |
||||
} |
||||
|
||||
try { |
||||
$this->mailer->setFrom($this->mail, $this->title); |
||||
$this->mailer->addAddress($mailFrom, $this->title); |
||||
$this->mailer->send(); |
||||
$this->mailer->clearAllRecipients(); |
||||
$this->log->success("Mail: {$mailFrom} | Send Queue: {$this->sended}", debug_backtrace()); |
||||
return true; |
||||
} catch (Exception $ex) { |
||||
if ($this->mailer->ErrorInfo) { |
||||
$this->log->error("ErrorInfo Mail: " . $this->mailer->ErrorInfo . " | Exception Mail: {$mailFrom} >> " . $ex->getMessage(), debug_backtrace()); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Cria as configurações e parametros para ser implementado e enviado os emails. |
||||
* |
||||
* @void null |
||||
*/ |
||||
private function phpMailer() { |
||||
$this->log->debug("Instanciando objeto PHPMailer", debug_backtrace()); |
||||
$this->mailer = new PHPMailer(true); |
||||
$this->mailer->isSMTP(); |
||||
$this->mailer->Host = $this->host; |
||||
$this->mailer->SMTPAuth = $this->smtpAuth; |
||||
$this->mailer->isHTML(true); |
||||
|
||||
if ($this->smtpAuth) { |
||||
$this->mailer->SMTPSecure = $this->smtpSecure; |
||||
$this->mailer->Username = $this->mail; |
||||
$this->mailer->Password = $this->passwd; |
||||
} |
||||
|
||||
$this->mailer->CharSet = $this->charset; |
||||
$this->mailer->Port = $this->port; |
||||
$this->mailer->Subject = $this->subject; |
||||
} |
||||
} |
@ -0,0 +1,553 @@
|
||||
#!/usr/bin/php -Cq |
||||
<?php |
||||
/* * *************************************************************************************** |
||||
* |
||||
* REGISTRO DE CHAMADAS ABANDONADAS |
||||
* Autor |
||||
* Amarildo Pereira |
||||
* |
||||
* *************************************************************************************** |
||||
* Definições do Projeto |
||||
* Nome: Registro de Abandonada |
||||
* Data início: 02/08/2018 |
||||
* Equipe: Amarildo Pereira |
||||
* Descrição: |
||||
* O objetivo do script é registrar o abandono das chamadas na fila a fim de prover infor- |
||||
* mações para que sejam retornadas posteriormente e tenha seus status atualizados adequa- |
||||
* damente. No memento do abandono a tabela "pbx_abandonadas_semretorno" será populada com |
||||
* as seguinte informações: |
||||
* 1 - abdsr_uniqueid: Identificador da chamada. |
||||
* 2 - abdsr_fila: Fila em que a chamada foi abandonada. |
||||
* 3 - abdsr_numero: O número do telefone que abandonou. |
||||
* 4 - abdsr_agt_logado: Número de agentes logados no momento do abandono. |
||||
* 5 - abdsr_agt_pausa: Número de agentes em pausa no momento do abandono. |
||||
* 6 - abdsr_agt_ocupado: Número de agentes que estavam em atendimento no momento do |
||||
* abandono. |
||||
* 7 - abdsr_agt_indisponivel: Número de agentes que estavam com a opção indisponível |
||||
* para fila marcada. |
||||
* 8 - abdsr_agt_nao_classificado: Número de agentes que não podiam receber chamadas |
||||
* porque não classificaram a chamada quando a fila tem classificação obrigatória. |
||||
* |
||||
* A tabela a tabela "pbx_abandonadas_status" será populada com detalhes sobre os agentes |
||||
* logados na fila e conterá as seguinte informações: |
||||
* 1 - uniqueid: Identificador da chamada usada para relacionamento com a tabela |
||||
* "pbx_abandonadas_semretorno" |
||||
* 2 - matricula: Identificação do agente no sistema. |
||||
* 3 - id_evt_agt: Id único da tabela. |
||||
* 4 - status: Status do agente no momento do abandono. |
||||
* 5 - motivo_pausa: Se o agente estiver em pausa qual o motivo informado. |
||||
* 6 - ramal: O número do ramal que o agente usou no atendimento. |
||||
* 7 - disponivel: Indica se o agente estava com a opção disponível para fila marcada. |
||||
* 8 - classificado: Indica que o agente não está apto a receber chamadas, por não ter |
||||
* classificado seu último atendimento. |
||||
* |
||||
* Quando uma chamada é retornada pelo processo automático ou manual por um agente loga- |
||||
* do na fila correspondente ou ainda pelo atendimento posterior realizado para o mesmo |
||||
* número a tabela "pbx_abandonadas_semretorno" é atualizada para indicar que a chamada já |
||||
* foi retornada com os seguintes dados: |
||||
* 1 - abdsr_data_hora_retorno: Indica a data e hora do retorno. |
||||
* 2 - abdsr_data_retorno: Data d retorno. |
||||
* 3 - abdsr_ramal: Ramal do agente que realizou o atendimento. |
||||
* 4 - abdsr_agente: Ramal do agente que realizou o atendimento. |
||||
* 5 - abdsr_uniqueid_ret: Identificador da chamada que retornou. |
||||
* |
||||
* Quando ocorre um retorno consideramos a última chamada do número abandonado, entretanto |
||||
* caso haja outras chamadas do mesmo número abandonadas anteriormente estas também são |
||||
* marcadas como retornadas atualizando a tabela "pbx_abandonadas_semretorno" da seguinte |
||||
* maneira: |
||||
* 1 - abdsr_data_hora_retorno: Data e hora em que foi realizado o retorno. |
||||
* 2 - abdsr_data_retorno: Data do retorno. |
||||
* 3 - abdsr_ramal: Contém a descrição 'RET' indica um retorno indireto. |
||||
* 4 - abdsr_agente: Matrícula do agente que realizou o atendimento. |
||||
* 5 - abdsr_uniqueid_ret: Identificador da chamada que realizou o retorno. |
||||
* 6 - abdsr_log: Identificador da ultima chamada abandonada que serviu de referência |
||||
* para o retorno. |
||||
* Para a atualização das camadas anteriores são considerados dois parâmetros: |
||||
* 1 - abdsr_numero: Número do telefone que realizou o abandono. |
||||
* 2 - abdsr_data_hora_retorno: Indica que não houve retorno para a chamada então |
||||
* consideramos todas as chamadas do mesmo número em que o valor deste campo é null; |
||||
* *************************************************************************************** |
||||
* Copyright (c) 2018, Simples IP |
||||
* *************************************************************************************** */ |
||||
|
||||
|
||||
error_reporting(E_ERROR); |
||||
ini_set('display_errors', 0); |
||||
include 'util/util.php'; |
||||
include 'funcoes/shared.php'; |
||||
include 'util/agiApl.php'; |
||||
include('configAcesso.php'); |
||||
include("util/funcoesAgi.php"); |
||||
require '/var/lib/asterisk/scripts/integracao/serverFunctions.php'; |
||||
|
||||
/* |
||||
include 'util/util.php'; |
||||
include '/var/lib/asterisk/scripts/integracao/constServerIntegra.php'; |
||||
include '/var/lib/asterisk/scripts/integracao/localDataBase.php'; |
||||
include 'funcoes/shared.php'; |
||||
include("util/funcoesAgi.php"); |
||||
*/ |
||||
|
||||
/* |
||||
* Caminho para o arquivo de log do script. |
||||
*/ |
||||
$pathLog = sprintf('/var/log/asterisk/abd_agi-%s.log', date("Y-m-d")); |
||||
|
||||
/* |
||||
* Captura variaveis do asterisk. |
||||
*/ |
||||
$agi = GetAgi(); |
||||
|
||||
/* |
||||
* Configuração do banco de dados. Deixe a variável $str para pegar o valor padrao |
||||
*/ |
||||
$str = ''; |
||||
//$str = sprintf( "host='%s' port='%s' dbname='%s' user='%s' password='%s'","192.168.115.65", "5432", "pbx", "contacte", "ctepgSQL" ); |
||||
if (!$str) { |
||||
$str = GetDBString(); |
||||
} |
||||
|
||||
/* |
||||
* Realiza a conexao ao banco de daodos. |
||||
*/ |
||||
pg_connect($str); |
||||
|
||||
/* |
||||
* Nome do script em ececucao. |
||||
*/ |
||||
$scrpt = trim($argv[0]); |
||||
|
||||
/* |
||||
* Identificador gerado para chamda corrente na central. |
||||
*/ |
||||
$uid = trim($argv[1]); |
||||
|
||||
/* |
||||
* Identifica a fila de entrada para qual a chamada foi encaminhada. |
||||
*/ |
||||
$dac = trim($argv[2]); |
||||
|
||||
|
||||
try { |
||||
/* |
||||
* Verifica se a ligacao foi recebida na fila. |
||||
*/ |
||||
if ($dac) { |
||||
/* |
||||
* Origem/Destino da chamda. |
||||
*/ |
||||
$numero = $argv[3]; |
||||
$numero = AcrescentaDDD(trim($numero)); |
||||
|
||||
/* |
||||
* RAMAL ABANDONO DA CHAMADA - CHAMADA RAMAL |
||||
*/ |
||||
$ramal = $agi->get_variable('CDR(ramal_origem)', true); |
||||
|
||||
/* |
||||
* Matricula do agente logado. |
||||
*/ |
||||
$matricula = ValidaMatricula(trim($argv[4])); |
||||
|
||||
/* |
||||
* Verifica se a chamada é sainte ou entrante. |
||||
*/ |
||||
$direcao = $agi->get_variable('CDR(direcao)', true); |
||||
|
||||
/* |
||||
* Eventos da fila na chamada de saida. |
||||
*/ |
||||
$evento = $agi->get_variable('EVENTO', true); |
||||
|
||||
/* |
||||
* Entrante na fila atendica. |
||||
*/ |
||||
$atendidaFila = trim($agi->get_variable('ATENDIDA_FILA', true)); |
||||
|
||||
/* |
||||
* Verifica se a chamada foi atendida. |
||||
*/ |
||||
if ($direcao == 'S') { |
||||
$chamadaAtendida = ($evento == 'COMPLETAAGENT') || ($evento == 'COMPLETACALLER') || ($evento == 'COMPLETACALLERRAMAL') || ($evento == 'COMPLETEAGENT') || ($evento == 'COMPLETEAGENTRAMAL') || ($evento == 'COMPLETECALLER') || ($evento == 'COMPLETECALLERRAMAL') || ($evento == 'ATENDIDA'); |
||||
} else { |
||||
$chamadaAtendida = $atendidaFila == 'SIM'; |
||||
} |
||||
|
||||
|
||||
|
||||
/* |
||||
* Marca o inicio da execucao do script. |
||||
* GravaLog(sprintf(": %s\n", $ ,date('Y-m-d H:i:s')), $pathLog); |
||||
*/ |
||||
GravaLog(sprintf("Inicia Execucao: [Uid: %s Dac: %s Num: %s Mat: %s Evt: %s Atd_fila: %s] %s\n", $uid, $dac, $numero, $matricula, $evento, $atendidaFila, date('Y-m-d H:i:s')), $pathLog); |
||||
|
||||
|
||||
if ((!$chamadaAtendida) && ($direcao == 'E')) { |
||||
|
||||
/* |
||||
* Inicio do tratamento para chamadas abandonadas. |
||||
* Recuperando informacoes da fila. |
||||
*/ |
||||
$query = "select sum(1) as logado, |
||||
SUM(case when( a.status in('OCUPADO', 'CHAMANDO'))then 1 else 0 end) as ocupado, |
||||
SUM(case when( a.status = 'LIVRE')then 1 else 0 end) as livre, |
||||
SUM(case when( a.status = 'PAUSA')then 1 else 0 end) as pausa, |
||||
SUM(case when( a.disponivel_atendimento = 0)then 1 else 0 end) as indisponivel, |
||||
SUM(case when( b.exige_classificacao = 0)then 0 else case when(a.chamada_classificado = 1)then 0 else 1 end end) as nao_classificado |
||||
from pbx_supervisor_agentes a, pbx_queues_grupos b |
||||
where b.nome = a.dac |
||||
and a.dac = '$dac'"; |
||||
$result = pg_query($query); |
||||
if (!$result) { |
||||
RaiseExcept("Erro ao obter informacoes sobre a fila.", true); |
||||
} |
||||
$infoFila = pg_fetch_array($result, null, PGSQL_ASSOC); |
||||
|
||||
/* |
||||
* Inserindo informacoes sobre a chamada e a fila no momento do abandono. |
||||
*/ |
||||
if ($numero) { |
||||
$query = "insert into pbx_abandonadas_semretorno(abdsr_uniqueid,abdsr_fila,abdsr_numero,abdsr_agt_logado,abdsr_agt_pausa,abdsr_agt_ocupado,abdsr_agt_indisponivel,abdsr_agt_nao_classificado)" |
||||
. "values(%s,%s,%s,%s,%s,%s,%s,%s)"; |
||||
$query = sprintf($query, QuotedStr($uid), QuotedStr($dac), QuotedStr($numero), QuotedStr(($infoFila['logado'] ? $infoFila['logado'] : '0')), QuotedStr(($infoFila['pausa'] ? $infoFila['pausa'] : '0')), QuotedStr(($infoFila['ocupado'] ? $infoFila['ocupado'] : '0')), QuotedStr(($infoFila['indisponivel'] ? $infoFila['indisponivel'] : '0')), QuotedStr(($infoFila['nao_classificado']) ? $infoFila['nao_classificado'] : '0')); |
||||
|
||||
GravaLog(sprintf("Insert Abandon:\n%s\n[%s]\n", $query, date('Y-m-d H:i:s')), $pathLog); |
||||
$result = pg_query($query); |
||||
if (!$result) { |
||||
RaiseExcept("Erro ao gravar informacoes sobre a chamada.", true); |
||||
} |
||||
} else { |
||||
GravaLog(sprintf("[ PROCESS ]\n", 'Nao foi possivel encontrar o numero passado pela central', date('Y-m-d H:i:s')), $pathLog); |
||||
} |
||||
|
||||
/* |
||||
* Obtendo informacoes sobre os agentes no momento do abandono. |
||||
* a.chamada_classificad = 2 -> Indica o status inicial quando a classificação é obgrigatória |
||||
* tendo portato o mesmo efeito que 1 que é classificado. |
||||
*/ |
||||
$query = "select a.matricula, |
||||
a.ramal, |
||||
case when( a.status in('OCUPADO', 'CHAMANDO'))then 'OCUPADO' else a.status end as status, |
||||
case when( b.exige_classificacao = 0)then -1 else a.chamada_classificado end as chamada_classificado, |
||||
a.disponivel_atendimento, c.id as id_evt_agente, c.login, c.logoff, case when( a.status = 'PAUSA')then a.motivo_pausa else '-' end as motivo_pausa |
||||
from pbx_supervisor_agentes a, pbx_queues_grupos b, pbx_eventos_agentes c |
||||
where b.nome = a.dac |
||||
and c.id_dac = b.id |
||||
and c.matricula = a.matricula |
||||
and c.login = (select max(login) from pbx_eventos_agentes where matricula = a.matricula) |
||||
and a.dac = '$dac' order by a.matricula;"; |
||||
$result = pg_query($query); |
||||
if (!$result) { |
||||
RaiseExcept("Erro ao obter informacoes sobre os agentes.", true); |
||||
} |
||||
|
||||
/* /var/lib/asterisk/scripts/integracao/abdAgi.php,1531320618.20,FINANCEIRO,4002, |
||||
* Inserindo informacoes sobre os agentes no momento da chamada. |
||||
*/ |
||||
if (pg_num_rows($result)) { |
||||
while ($infoAgente = pg_fetch_array($result, null, PGSQL_ASSOC)) { |
||||
$query = "insert into pbx_abandonadas_status(uniqueid,matricula,id_evt_agt,status, motivo_pausa,ramal,disponivel,classificado)" |
||||
. "values(%s,%s,%s,%s,%s,%s,%s,%s)"; |
||||
$query = sprintf($query, QuotedStr($uid), QuotedStr($infoAgente['matricula']), QuotedStr($infoAgente['id_evt_agente']), QuotedStr($infoAgente['status']), QuotedStr($infoAgente['motivo_pausa']), QuotedStr($infoAgente['ramal']), QuotedStr($infoAgente['disponivel_atendimento']), QuotedStr($infoAgente['chamada_classificado']) |
||||
); |
||||
GravaLog(sprintf("Insert Abandon Status:\n%s\n[%s]\n", $query, date('Y-m-d H:i:s')), $pathLog); |
||||
if (!pg_query($query)) { |
||||
RaiseExcept("Erro ao gravar informacoes sobre os agentes no momento da chamada.", true); |
||||
} |
||||
} |
||||
} else { |
||||
/* Sem agente logado na fila */ |
||||
$query = "insert into pbx_abandonadas_status(uniqueid,matricula,id_evt_agt,status, motivo_pausa,ramal,disponivel,classificado)values(%s,'0','0','0','0',%s,'0','0')"; |
||||
$query = sprintf($query, QuotedStr($uid), $ramal ? QuotedStr($ramal) : '0', QuotedStr($infoAgente['matricula'])); |
||||
GravaLog(sprintf("Insert Abandon Status:\n%s\n[%s]\n", $query, date('Y-m-d H:i:s')), $pathLog); |
||||
if (!pg_query($query)) { |
||||
RaiseExcept("Erro ao gravar informacoes sobre os agentes no momento da chamada.", true); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/* |
||||
* Localiza a ultima chamada abandonada sem retorno pelo numero de origem e a data de verificacao |
||||
* que é a dataAtual - $diasAbandon. |
||||
*/ |
||||
if ($argv[3] && $chamadaAtendida && ($numero != $ramal)) { |
||||
$diasAbandon = GetDiasAbandonada(); |
||||
|
||||
$numero = $dac ? $numero : $ramal; |
||||
|
||||
$query = "SELECT abdsr_uniqueid |
||||
FROM pbx_abandonadas_semretorno |
||||
WHERE abdsr_data_hora_retorno IS NULL |
||||
AND abdsr_numero like '%$numero' |
||||
AND abdsr_data >= (now()::date - $diasAbandon) |
||||
AND abdsr_data_hora_inicio = |
||||
(SELECT max(abdsr_data_hora_inicio) |
||||
FROM pbx_abandonadas_semretorno |
||||
WHERE abdsr_data >= (now()::DATE - $diasAbandon) |
||||
AND abdsr_numero like '%$numero' |
||||
AND abdsr_data_hora_retorno IS NULL)"; |
||||
|
||||
$res = pg_query($query); |
||||
GravaLog(sprintf("Select Abandon:\n%s\n[%s]\n", $query, date('Y-m-d H:i:s')), $pathLog); |
||||
|
||||
if (!$res) { |
||||
RaiseExcept("Erro ao consultar informacoes sobre a chamada abandonada", true); |
||||
} |
||||
|
||||
/* |
||||
* Se o numero tiver registro de chamda sem retorno atualiza as informacoes. |
||||
*/ |
||||
if (pg_num_rows($res)) { |
||||
$infoChamada = pg_fetch_array($res, null, PGSQL_ASSOC); |
||||
$uidAbandon = $infoChamada['abdsr_uniqueid']; |
||||
$agenteMatricula = $matricula; |
||||
|
||||
$query = "update pbx_abandonadas_semretorno |
||||
set abdsr_data_hora_retorno = now(), |
||||
abdsr_data_retorno = now()::date, |
||||
abdsr_ramal = '$ramal', |
||||
abdsr_agente = '$agenteMatricula', |
||||
abdsr_uniqueid_ret = '$uid' |
||||
where abdsr_uniqueid = '$uidAbandon'"; |
||||
$result = pg_query($query); |
||||
if (!$result) { |
||||
RaiseExcept("Erro ao atualizar informacoes sobre a chamada abandonada", true); |
||||
} |
||||
|
||||
/* |
||||
* Atualiza chamdas anteriores para o mesmo numero marcando como retornada |
||||
*/ |
||||
$query = "update pbx_abandonadas_semretorno |
||||
set abdsr_data_hora_retorno = now(), |
||||
abdsr_data_retorno = now()::date, |
||||
abdsr_ramal = 'RET', |
||||
abdsr_agente = '$agenteMatricula', |
||||
abdsr_uniqueid_ret = '$uid', |
||||
abdsr_log = '$uidAbandon' |
||||
where abdsr_numero = '$numero' |
||||
and abdsr_data_hora_retorno is null"; |
||||
$result = pg_query($query); |
||||
if (!$result) { |
||||
RaiseExcept("Erro ao atualizar informacoes sobre a chamada abandonada anteriores a atual", true); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
} catch (Exception $ex) { |
||||
/* |
||||
* Grava erros gerados durante a execucao. |
||||
*/ |
||||
GravaLog(sprintf("Erro:%s File: %s Line: %s \ncmd: %s\n %s\n", $ex->getMessage(), $ex->getFile(), $ex->getLine(), $query, date('Y-m-d H:i:s')), $pathLog); |
||||
} |
||||
|
||||
/* |
||||
* Marca o fim da execucao do script. |
||||
*/ |
||||
GravaLog(sprintf("Finaliza Execucao: %s\n\n", date('Y-m-d H:i:s')), $pathLog); |
||||
|
||||
function GetVarFila() { |
||||
$varFila = array('QUEUESTATUS', 'QUEUESRVLEVELPERF', 'QUEUESRVLEVEL', 'QUEUEABANDONED', 'QUEUECOMPLETED', 'QUEUETALKTIME', 'QUEUEHOLDTIME', 'QUEUECALLS', 'QUEUESTRATEGY', 'QUEUEMAX', 'QUEUENAME', 'QEORIGINALPOS', 'QEHOLDTIME', 'MEMBERREALTIME', 'MEMBERDYNAMIC', 'MEMBERPENALTY', 'MEMBERLASTCALL', 'MEMBERCALLS', 'MEMBERNAME', 'MEMBERINTERFACE'); |
||||
$vars = array(); |
||||
foreach ($varFila as $varName) { |
||||
$vars[$varName] = AgiGetVariable($varName); |
||||
} |
||||
|
||||
return $vars; |
||||
} |
||||
|
||||
function AcrescentaDDD($str) { |
||||
$numero = ltrim($str, '0'); |
||||
$tam = strlen($numero); |
||||
|
||||
if (($tam == 8) || (($tam == 9) && (substr($numero, 0, 1) == '9'))) { |
||||
return GetDddPadrao($numero); |
||||
} |
||||
|
||||
return $numero; |
||||
} |
||||
|
||||
function ValidaMatricula($matricula) { |
||||
$query = "select matricula from pbx_usuarios where matricula = '$matricula'"; |
||||
$result = pg_query($query); |
||||
return pg_num_rows($result) ? $matricula : ''; |
||||
} |
||||
|
||||
/* |
||||
* Cria um controle para retorno de chamadas abandonadas, |
||||
* as chamadas vão sendo inseridas na tabela e removidas |
||||
* conformem forem sendo retornadas pelos agentes da fila |
||||
* aonde foram abandonadas. |
||||
|
||||
-- Table: pbx_abandonadas_semretorno |
||||
-- DROP TABLE pbx_abandonadas_semretorno; |
||||
|
||||
CREATE TABLE pbx_abandonadas_semretorno |
||||
( |
||||
abdsr_uniqueid character varying(32) not null primary key, |
||||
abdsr_data date NOT NULL default now()::date, |
||||
abdsr_fila character varying(64), |
||||
abdsr_numero character varying(32) NOT NULL, |
||||
abdsr_data_hora_inicio timestamp without time zone NOT NULL default now(), |
||||
abdsr_data_hora_retorno timestamp without time zone, |
||||
abdsr_data_retorno date, |
||||
abdsr_ramal character varying(32), |
||||
abdsr_agente character varying(32), |
||||
abdsr_agt_logado int, |
||||
abdsr_agt_pausa int, |
||||
abdsr_agt_ocupado int, |
||||
abdsr_agt_indisponivel int, |
||||
abdsr_agt_nao_classificado int, |
||||
abdsr_uniqueid_ret character varying(32) |
||||
); |
||||
-- Index: "idxPbxAbdsrDataNumero" |
||||
-- DROP INDEX "idxPbxAbdsrDataNumero"; |
||||
CREATE INDEX "idxPbxAbdsrDataNumero" |
||||
ON pbx_abandonadas_semretorno |
||||
USING btree |
||||
(abdsr_data, abdsr_fila, abdsr_numero); |
||||
|
||||
CREATE INDEX "idxPbxAbdsrUid" |
||||
ON pbx_abandonadas_semretorno |
||||
USING btree |
||||
(abdsr_uniqueid); |
||||
|
||||
-- DROP TABLE pbx_abandonadas_status; |
||||
CREATE TABLE pbx_abandonadas_status |
||||
( |
||||
uniqueid character varying(32) not null, |
||||
matricula character varying(16) not null, |
||||
id_evt_agt int, |
||||
status varchar(32), |
||||
ramal varchar(32), |
||||
disponivel int, |
||||
classificado int, |
||||
constraint "pkPbxAbandonadasStatus" primary key(uniqueid, matricula) |
||||
); |
||||
* |
||||
*/ |
||||
|
||||
|
||||
/* |
||||
* Função Chamada Ramal da API. |
||||
*/ |
||||
include_once '/var/lib/asterisk/scripts/integracao/constServerIntegra.php'; |
||||
include_once '/var/lib/asterisk/scripts/integracao/localDataBase.php'; |
||||
|
||||
$scrpt = $argv[0]; |
||||
$UNIQUEID = $argv[1]; |
||||
|
||||
$userfield = $agi->get_variable('MONITOR_FILENAME', true); |
||||
$userfield = trim($userfield) ? $userfield : 'AUDIO.WAV'; |
||||
|
||||
$path = '/var/log/asterisk/encerra_chamada_satelitenorte.log'; |
||||
$query = sprintf("select a.chdr_id from pbx_chamada_ramal a where a.uniqueid = '%s' and a.chdr_fim is null", $UNIQUEID); |
||||
$result = pg_query($query); |
||||
|
||||
|
||||
if (pg_num_rows($result)) { |
||||
GravaLog($query . "\n AUDIO: " . $userfield . "\n", $path); |
||||
$dados = pg_fetch_array($result, null, PGSQL_ASSOC); |
||||
$chdr_id = $dados['chdr_id']; |
||||
$audio = str_ireplace('.WAV', '.MP3', $userfield); |
||||
|
||||
$token = '026d3a4b331078aa09d096d11e495215'; |
||||
$parametros = array('method' => 'terminachamada', 'audio' => $audio, 'id_chamada' => $UNIQUEID, 'token' => $token, 'login' => 'admin', 'senha' => 'SiP1029384756', 'tipoRetorno' => 'JSON'); |
||||
//$parametros = array('audio' => $audio, 'id_chamada' => $UNIQUEID, 'token' => $token); |
||||
|
||||
$ch = curl_init(); |
||||
curl_setopt($ch, CURLOPT_URL, "http://satelitenorte.xpro.me/gestaodeleads/terminachamada"); |
||||
//curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1/aplicativo/integracao/index.php"); |
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); |
||||
curl_setopt($ch, CURLOPT_TIMEOUT, 10); |
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $parametros); |
||||
$content = trim(curl_exec($ch)); |
||||
curl_close($ch); |
||||
$retorno = json_decode($content, true); |
||||
|
||||
$log = sprintf("Status: %s Msg: %s", $retorno["status"], $retorno["mensagem"]); |
||||
$query = sprintf("update pbx_chamada_ramal set chdr_fim = now(), chdr_log = %s where chdr_id = '%s'", QuotedStr($log), $chdr_id); |
||||
GravaLog($query . "\n", $path); |
||||
$result = pg_query($query); |
||||
if (!$result) { |
||||
GravaLog($query . "\n", $path); |
||||
} |
||||
} |
||||
|
||||
$integra = $agi->get_variable('INTEGRA-SAIDA', true); |
||||
if ($integra == 'SAIDA') { |
||||
|
||||
$intMetodo = $agi->get_variable('INTEGRA-METODO', true); |
||||
$intUniqueid = $agi->get_variable('UNIQUEID', true); |
||||
$intTelefone = $agi->get_variable('INTEGRA-FONE', true); |
||||
$intFone = str_replace('@', '|', $intTelefone); |
||||
$intRegIni = $agi->get_variable('INTEGRA-REGINI', true); |
||||
$intRegFim = $agi->get_variable('INTEGRA-REGFIM', true); |
||||
$intRetCliente = $agi->get_variable('INTEGRA-RETCLI', true); |
||||
$intRetCli = str_replace('@', '|', $intRetCliente); |
||||
$intRamal = $agi->get_variable('INTEGRA-RAMAL', true); |
||||
$intUra = $agi->get_variable('INTEGRA-URA', true); |
||||
|
||||
$sql = "INSERT INTO pbx_integracao_reg(" |
||||
. "reg_id_metodo," |
||||
. "reg_uniqueid," |
||||
. "reg_uniqueid_old," |
||||
. "reg_fone," |
||||
. "reg_retorno," |
||||
. "reg_inicio," |
||||
. "reg_fim," |
||||
. "reg_msg," |
||||
. "reg_status_exec," |
||||
. "reg_status," |
||||
. "retorno_cliente," |
||||
. "reg_ramal," |
||||
. "reg_ura) " |
||||
. "VALUES($intMetodo,'$intUniqueid','$intUniqueid','$intFone','$intFone','$intRegIni','$intRegFim','INTEGRACAO-ATIVO-SAIDA'," |
||||
. "1,0,'$intRetCli','$intRamal','$intUra');"; |
||||
@pg_query($sql); |
||||
$pgError = pg_last_error(); |
||||
if ($pgError) { |
||||
GravaLog($sql, '/var/log/asterisk/integracao_ativa_sainte.log'); |
||||
GravaLog($pgError, '/var/log/asterisk/integracao_ativa_sainte.log'); |
||||
} |
||||
} |
||||
|
||||
$ligueme = $agi->get_variable('LIGUE-ME', true); |
||||
if ($ligueme) { |
||||
$ligueUniq = $agi->get_variable('UNIQUEID', true); |
||||
$sipid = GetSIPIDCall(); |
||||
$sqligueme = sprintf("UPDATE pbx_ligueme_gratis SET uid_contato = %s WHERE sipid_contato = '%s'", $ligueUniq, GetSIPIDCall()); |
||||
$sqligueme .= $sipid ? "sipid_contato = '$sipid'" : "telefone_contato = '$ligueme'"; |
||||
@pg_query($sqligueme); |
||||
} |
||||
|
||||
|
||||
############################################################################ |
||||
#### INTEGRACAO ENCERRAMENTO DO ABDAGI #### |
||||
############################################################################ |
||||
|
||||
/* |
||||
* Verifica se o tipo de execução é custom, se for desvia a execução |
||||
* para um script customizado para integração, capturando antes os |
||||
* parametros de entrada. O programas ou scripts ficam localizados |
||||
* no diretorio /var/lib/asterisk/scripts/integracao/custom. |
||||
*/ |
||||
$query = "SELECT itgm_id FROM pbx_integracao_reg a, pbx_integracao_metodo b WHERE b.itgm_id_pai = a.reg_id_metodo AND b.evento = 2 AND a.reg_uniqueid = '{$arg1}'"; |
||||
$result = pg_query($query); |
||||
$idMetodo = pg_fetch_assoc($result)['itgm_id']; |
||||
|
||||
$pathIntegra = "/var/lib/asterisk/scripts/integracao/custom/"; |
||||
|
||||
if ($idMetodo && ExecuteCustom($idMetodo, $nomeMetodo)) { |
||||
__logStr("ExecuteCustom", $nomeMetodo, 'serverAgi', true); |
||||
|
||||
/** Movidesk **/ |
||||
__logStr("abdAgi.php", file_exists($pathIntegra . "Movidesk.php") . " | " . $chamadaAtendida, true); |
||||
if (file_exists($pathIntegra . "Movidesk.php") && !$chamadaAtendida) { |
||||
include $pathIntegra . "AbandonadaChamada.php"; |
||||
} |
||||
|
||||
include($nomeMetodo); |
||||
|
||||
exit; |
||||
} |
||||
?> |
@ -0,0 +1,16 @@
|
||||
<?php |
||||
|
||||
require_once "Movidesk.php"; |
||||
|
||||
$movidesk = new Movidesk(); |
||||
|
||||
$protocolo = $movidesk->agi()->get_variable('PROTOCOLO_REG', true); |
||||
|
||||
$response = $movidesk->createTicket( |
||||
$movidesk->agi()->get_variable('CODCLIENTE', true), |
||||
2,'Urgente', 2, 2, |
||||
$email, |
||||
$numero, |
||||
"Ticket aberto via URA Plantao Procolo [ {$protocolo} ]"); |
||||
|
||||
$movidesk->executarFluxo('ANUNCIO', 'MUDO'); |
@ -0,0 +1,9 @@
|
||||
<?php |
||||
|
||||
require_once "Movidesk.php"; |
||||
|
||||
$host_central_interno = '192.168.56.14'; |
||||
|
||||
$movidesk = new Movidesk(); |
||||
|
||||
$movidesk->completedCall($uid, date('Y-m-d H:i:s'), "http://{$host_central_interno}/fileurl.php?url=" . base64_encode("integracao/?method=GetAudio&uniqueid=$uid&tipo=mp3&login=user.api&senha=0000&tipoRetorno=JSON/STREAM")); |
@ -0,0 +1,355 @@
|
||||
<?php |
||||
|
||||
$provedores = [ |
||||
########################## |
||||
/** @IXCSoftware */ |
||||
########################## |
||||
'IXC' => [ |
||||
'CREDENCIAIS' => |
||||
[ |
||||
'TOKEN' => '', |
||||
'URL' => '' |
||||
], |
||||
'INTEGRACAO_TELA' => [ |
||||
'STATUS' => '1', |
||||
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"] |
||||
], |
||||
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'PARADA_TECNICA', 'ABRE_ATENDIMENTO'] |
||||
], |
||||
########################## |
||||
/** @ISPIntegrator */ |
||||
########################## |
||||
'ISP' => [ |
||||
'CREDENCIAIS' => |
||||
[ |
||||
'USER' => '', |
||||
'PASSWORD' => '', |
||||
'URL' => '' |
||||
], |
||||
'INTEGRACAO_TELA' => [ |
||||
'STATUS' => '1', |
||||
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"] |
||||
], |
||||
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'PARADA_TECNICA', 'ABRE_ATENDIMENTO'] |
||||
], |
||||
########################## |
||||
/** @HUBSoft */ |
||||
########################## |
||||
'HUBSOFT' => [ |
||||
'CREDENCIAIS' => |
||||
[ |
||||
'CLIENT_ID' => '', |
||||
'CLIENT_SECRET' => '', |
||||
'USERNAME' => '', |
||||
'PASSWORD' => '', |
||||
'URL' => '' |
||||
], |
||||
'INTEGRACAO_TELA' => [ |
||||
'STATUS' => '1', |
||||
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"] |
||||
], |
||||
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'PARADA_TECNICA', 'ABRE_ATENDIMENTO'] |
||||
], |
||||
########################## |
||||
/** @MKSolution */ |
||||
########################## |
||||
'MK' => [ |
||||
'CREDENCIAIS' => |
||||
[ |
||||
'TOKEN' => '', |
||||
'URL' => '', |
||||
'CONTRASENHA' => '' |
||||
], |
||||
'INTEGRACAO_TELA' => [ |
||||
'STATUS' => '1', |
||||
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"] |
||||
], |
||||
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'PARADA_TECNICA', 'ABRE_ATENDIMENTO'] |
||||
], |
||||
########################## |
||||
/** @SGP */ |
||||
########################## |
||||
'SGP' => [ |
||||
'CREDENCIAIS' => |
||||
[ |
||||
'TOKEN' => '', |
||||
'URL' => '', |
||||
'APP' => '' |
||||
], |
||||
'INTEGRACAO_TELA' => [ |
||||
'STATUS' => '1', |
||||
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"] |
||||
], |
||||
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE'] |
||||
], |
||||
########################## |
||||
/** @CNTSistemas */ |
||||
########################## |
||||
'CNT' => [ |
||||
'CREDENCIAIS' => |
||||
[ |
||||
'TOKEN' => '', |
||||
'URL' => '' |
||||
], |
||||
'INTEGRACAO_TELA' => [ |
||||
'STATUS' => '1', |
||||
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"] |
||||
], |
||||
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'ABRE_ATENDIMENTO'] |
||||
], |
||||
########################## |
||||
/** @Routerbox */ |
||||
########################## |
||||
'RBX' => [ |
||||
'CREDENCIAIS' => |
||||
[ |
||||
'TOKEN' => '', |
||||
'URL' => '' |
||||
], |
||||
'INTEGRACAO_TELA' => [ |
||||
'STATUS' => '1', |
||||
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"] |
||||
], |
||||
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'ABRE_ATENDIMENTO'] |
||||
], |
||||
########################## |
||||
/** @TopSapp */ |
||||
########################## |
||||
'TOPSAPP' => [ |
||||
'CREDENCIAIS' => |
||||
[ |
||||
'USUARIO' => '', |
||||
'SENHA' => '', |
||||
'URL' => '' |
||||
], |
||||
'INTEGRACAO_TELA' => [ |
||||
'STATUS' => '1', |
||||
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"] |
||||
], |
||||
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'PARADA_TECNICA'] |
||||
], |
||||
########################## |
||||
/** @Gerenet */ |
||||
########################## |
||||
'GERENET' => [ |
||||
'CREDENCIAIS' => |
||||
[ |
||||
'TOKEN' => '', |
||||
'URL' => '' |
||||
], |
||||
'INTEGRACAO_TELA' => [ |
||||
'STATUS' => '1', |
||||
'PARAMETROS' => ["DOCUMENTO", "NOME", "ENDERECO"] |
||||
], |
||||
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE'] |
||||
], |
||||
########################## |
||||
/** @Synsuite */ |
||||
########################## |
||||
'SYNSUITE' => [ |
||||
'CREDENCIAIS' => |
||||
[ |
||||
'TOKEN' => '', |
||||
'URL' => '' |
||||
], |
||||
'INTEGRACAO_TELA' => [ |
||||
'STATUS' => '1', |
||||
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"] |
||||
], |
||||
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'ABRE_ATENDIMENTO'] |
||||
], |
||||
########################## |
||||
/** @Altarede */ |
||||
########################## |
||||
'ALTAREDE' => [ |
||||
'CREDENCIAIS' => |
||||
[ |
||||
'TOKEN' => '', |
||||
'URL' => '', |
||||
'APPKEY' => '' |
||||
], |
||||
'INTEGRACAO_TELA' => [ |
||||
'STATUS' => '1', |
||||
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"] |
||||
], |
||||
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'ABRE_ATENDIMENTO'] |
||||
] |
||||
]; |
||||
|
||||
/** |
||||
* Configuracoes do Desenvolvedor |
||||
*/ |
||||
$configs = [ |
||||
'FATURA' => [ |
||||
'FATURA_DIAS_ANTES' => 30, |
||||
'FATURA_DIAS_APOS' => 5 |
||||
], |
||||
'LOGGER' => [ |
||||
'LOGGER_PATH' => 'integracao', |
||||
'LOGGER_ATIVO' => true, |
||||
'LOGGER_DB_ATIVO' => false |
||||
], |
||||
'EMAIL' => [ |
||||
'EMAIL_TITLE', '[NO-REPLY] Envio de Fatura', |
||||
'EMAIL_SUBTITLE' => 'Estamos enviando o pedido de Segunda Via da sua Fatura!', |
||||
'SENDER_EMAIL_USER' => '', |
||||
'SENDER_EMAIL_PASSWORD' => '', |
||||
'SMTP_HOST' => '', |
||||
'SMTP_PORT' => '587', |
||||
'SMTP_SECURE' => 'TLS', |
||||
'SMTP_AUTH' => true |
||||
], |
||||
'CONF' => [ |
||||
'NOMENCLATURA' => 'INT' |
||||
] |
||||
]; |
||||
|
||||
define('CONF_URA', 'ura'); |
||||
define('CONF_FILAS', 'filas'); |
||||
define('CONF_ANUNCIOS', 'anuncios'); |
||||
define('CONF_HORARIO', 'horarios'); |
||||
define('CONF_INTEGRACAO', 'integativa'); |
||||
define('CONF_LOGGER_DB_ATIVO', true); |
||||
|
||||
|
||||
/** |
||||
* Cadastro de Anuncios |
||||
*/ |
||||
$anuncios = [ |
||||
'SAUDACAO' => [ |
||||
CONF_URA => 'IDENTIFICACAO' |
||||
], |
||||
'AGRADECIMENTO' => [], |
||||
'CADASTRO_SUCESSO' => [ |
||||
CONF_INTEGRACAO => 'CONSULTA_PENDENCIA', |
||||
CONF_URA => 'AUTOMATIZADA' |
||||
], |
||||
'CADASTRO_FALHA' => [ |
||||
CONF_URA => 'IDENTIFICACAO' |
||||
], |
||||
'NAO_IDENTIFICADO' => [ |
||||
CONF_ANUNCIOS => 'AGRADECIMENTO' |
||||
], |
||||
'PENDENCIA' => [ |
||||
CONF_URA => 'AUTOMATIZADA' |
||||
], |
||||
'DESBLOQUEIA_SUCESSO' => [ |
||||
CONF_URA => 'VOLTA_MENU' |
||||
], |
||||
'DESBLOQUEIA_FALHA' => [ |
||||
CONF_URA => 'VOLTA_MENU' |
||||
], |
||||
'FATURA_SUCESSO' => [ |
||||
CONF_URA => 'VOLTA_MENU' |
||||
], |
||||
'FATURA_FALHA' => [ |
||||
CONF_URA => 'VOLTA_MENU' |
||||
], |
||||
'PRE_SUPORTE' => [ |
||||
CONF_HORARIO => 'ATENDIMENTO' |
||||
], |
||||
'TRANSFERE_ATENDENTE' => [], |
||||
'PARADA_TECNICA' => [ |
||||
CONF_URA => 'ATENDIMENTO' |
||||
], |
||||
'FORA_DE_HORARIO' => [ |
||||
CONF_ANUNCIOS => 'AGRADECIMENTO' |
||||
], |
||||
'INTEGRACAO_ERRO' => [ |
||||
CONF_HORARIO => 'ATENDIMENTO' |
||||
] |
||||
]; |
||||
|
||||
/* |
||||
* Configuração de Uras |
||||
*/ |
||||
$ura = [ |
||||
'AUTOMATIZADA' => [ |
||||
"ITENS" => [ |
||||
['numero' => '1', 'sequencia' => '1', 'acao' => [CONF_INTEGRACAO => 'ENVIA_FATURA']], |
||||
['numero' => '2', 'sequencia' => '2', 'acao' => [CONF_INTEGRACAO => 'DESBLOQUEIA_CLIENTE']], |
||||
['numero' => '3', 'sequencia' => '3', 'acao' => [CONF_INTEGRACAO => 'PARADA_TECNICA', CONF_URA => 'ATENDIMENTO']] |
||||
], |
||||
"TIMEOUT" => [ |
||||
|
||||
] |
||||
], |
||||
'IDENTIFICACAO' => [ |
||||
"ITENS" => [ |
||||
['numero' => '_X.', 'sequencia' => '0', 'acao' => [CONF_INTEGRACAO => 'CONSULTA_CLIENTE']], |
||||
['numero' => '9', 'sequencia' => '9', 'acao' => [CONF_HORARIO => 'ATENDIMENTO']] |
||||
], |
||||
"TIMEOUT" => [ |
||||
|
||||
] |
||||
], |
||||
'VOLTA_MENU' => [ |
||||
"ITENS" => [ |
||||
['numero' => '9', 'sequencia' => '9', 'acao' => [CONF_URA => 'AUTOMATIZADA']] |
||||
], |
||||
"TIMEOUT" => [ |
||||
CONF_ANUNCIOS => "AGRADECIMENTO" |
||||
] |
||||
], |
||||
'ATENDIMENTO' => [ |
||||
"ITENS" => [ |
||||
['numero' => '1', 'sequencia' => '1', 'acao' => [CONF_HORARIO => 'ATENDIMENTO']], |
||||
['numero' => '2', 'sequencia' => '2', 'acao' => [CONF_ANUNCIOS => 'PRE_SUPORTE']], |
||||
['numero' => '3', 'sequencia' => '3', 'acao' => [CONF_HORARIO => 'ATENDIMENTO']] |
||||
], |
||||
"TIMEOUT" => [ |
||||
|
||||
] |
||||
] |
||||
]; |
||||
|
||||
/* |
||||
* Configuração de Uras Redirecionamento |
||||
*/ |
||||
$ura_redir = [ |
||||
'REDIR_CONSULTA_CLIENTE' => [ |
||||
'SUCESSO' => [CONF_ANUNCIOS => 'CADASTRO_SUCESSO'], |
||||
'FALHA' => [CONF_ANUNCIOS => 'CADASTRO_FALHA'], |
||||
'ALTERNATIVO' => [CONF_ANUNCIOS => 'NAO_IDENTIFICADO'] |
||||
], |
||||
'REDIR_CONSULTA_PENDENCIA' => [ |
||||
'SUCESSO' => [CONF_ANUNCIOS => 'PENDENCIA'], |
||||
'FALHA' => [CONF_URA => 'AUTOMATIZADA'], |
||||
'ALTERNATIVO' => [] |
||||
], |
||||
'REDIR_ENVIA_FATURA' => [ |
||||
'SUCESSO' => [CONF_ANUNCIOS => 'FATURA_SUCESSO'], |
||||
'FALHA' => [CONF_ANUNCIOS => 'FATURA_FALHA'], |
||||
'ALTERNATIVO' => [] |
||||
], |
||||
'REDIR_DESBLOQUEIA_CLIENTE' => [ |
||||
'SUCESSO' => [CONF_ANUNCIOS => 'DESBLOQUEIA_SUCESSO'], |
||||
'FALHA' => [CONF_ANUNCIOS => 'DESBLOQUEIA_FALHA'], |
||||
'ALTERNATIVO' => [] |
||||
], |
||||
'REDIR_PARADA_TECNICA' => [ |
||||
'SUCESSO' => [CONF_ANUNCIOS => 'PARADA_TECNICA'], |
||||
'FALHA' => [CONF_URA => 'ATENDIMENTO'], |
||||
'ALTERNATIVO' => [] |
||||
], |
||||
'REDIR_ABRE_ATENDIMENTO' => [ |
||||
'SUCESSO' => [], |
||||
'FALHA' => [], |
||||
'ALTERNATIVO' => [] |
||||
] |
||||
]; |
||||
|
||||
/* |
||||
* Configuração de Horario |
||||
*/ |
||||
|
||||
$horarioPadrao = [ |
||||
"ATENDIMENTO" => [ |
||||
"ITENS" => [ |
||||
["HORARIO_INICIAL" => "08:00", "HORARIO_FINAL" => "18:00", "DIA_SEMANA_INICIO" => "mon", "DIA_SEMANA_FIM" => "fri"], |
||||
["HORARIO_INICIAL" => "08:00", "HORARIO_FINAL" => "12:00", "DIA_SEMANA_INICIO" => "sat", "DIA_SEMANA_FIM" => "sat"] |
||||
], |
||||
"FORA_HORARIO" => [CONF_ANUNCIOS => "FORA_DE_HORARIO"] |
||||
] |
||||
]; |
||||
|
@ -0,0 +1,6 @@
|
||||
<?php |
||||
|
||||
$anuncioos = [ |
||||
|
||||
]; |
||||
|
@ -0,0 +1,82 @@
|
||||
<?php |
||||
|
||||
########################################################################### |
||||
##### ##### |
||||
##### ARQUIVO PARA A CONFIGURACAO DE ACESSO API ##### |
||||
##### ----------------------------------------- ##### |
||||
##### CREDENCIAIS DE ACESSO ##### |
||||
########################################################################### |
||||
|
||||
define('CONF_ID_CREDENCIAIS', ''); |
||||
define('CONF_TOKEN_API', '09dc9dfa-c068-48bc-99a0-ffc4fdd5e397'); |
||||
define('CONF_URL_API', 'https://api.movidesk.com/public/v1/'); |
||||
define('CONF_USER_API', 'SIMPLESIP'); |
||||
define('CONF_PASSWORD_API', '25RH0QELJF'); |
||||
define('CONF_USERID_API', '-445847518'); |
||||
|
||||
########################################################################### |
||||
##### CONFIGURACOES ##### |
||||
########################################################################### |
||||
|
||||
define("CONF_INTEGRACAO_TELA", true); |
||||
define("CONF_PARAMETROS_TELA", serialize(array("NOME", "PLANO", "ENDERECO", "IP", "STATUS", "OBSERVACOES"))); |
||||
|
||||
/** @CONF_NOME_EMPRESA => colocar _EMPRESA */ |
||||
define('CONF_NOME_EMPRESA', ''); |
||||
|
||||
/** @CONF_AUDIO_ERROR => ID Áudio */ |
||||
define('CONF_AUDIO_ERROR', ''); |
||||
|
||||
define('CONF_LOGGER_PATH', 'integracao'); |
||||
define('CONF_LOGGER_ATIVO', true); |
||||
define('CONF_LOGGER_DB_ATIVO', false); |
||||
|
||||
define('CONF_FATURA_DIAS_ANTES', 30); |
||||
define('CONF_FATURA_DIAS_APOS', 5); |
||||
|
||||
define('CONF_AUDIO_ERROR', 'INTEGRACAO_ERRO_INT'); |
||||
|
||||
########################################################################### |
||||
##### CREDENCIAIS DE ENVIO DE EMAIL ##### |
||||
########################################################################### |
||||
|
||||
define('CONF_EMAIL_TITLE_INVOICE', '[NO-REPLY] Envio de Fatura'); |
||||
define('CONF_EMAIL_SUBTITLE_INVOICE', 'Estamos enviando o pedido de Segunda Via da sua Fatura!'); |
||||
define('CONF_SENDER_EMAIL_USER', ''); |
||||
define('CONF_SENDER_EMAIL_PASSWORD', ''); |
||||
define('CONF_SMTP_HOST', ''); |
||||
define('CONF_SMTP_POST', '587'); |
||||
|
||||
|
||||
############################################################################ |
||||
##### CONF. KING CAMPANHA ##### |
||||
############################################################################ |
||||
|
||||
define('CONF_CAMP_LOGIN', "novahelp"); |
||||
define('CONF_CAMP_DATAINI', date('Y-m-d 08:00:00')); |
||||
define('CONF_CAMP_DATAFIM', date('Y-m-d 18:00:00')); |
||||
define('CONF_CAMP_RAMAL', "2000"); |
||||
define('CONF_CAMP_FLUXO', 0); |
||||
define('CONF_CAMP_PAUSA', 1); |
||||
define('CONF_CAMP_NUMREDISCAGEM', 1); |
||||
define('CONF_CAMP_MAXCALL', 10); |
||||
define('CONF_CAMP_RINGTIME', 45); |
||||
define('CONF_CAMP_INTERVALO', 1); |
||||
define('CONF_CAMP_AMD', 0); |
||||
define('CONF_CAMP_NDS', 0); |
||||
define('CONF_CAMP_PRIOMOVEL', 0); |
||||
define('CONF_CAMP_MAXCALLAGENT', 3); |
||||
|
||||
|
||||
############################################################################ |
||||
##### CONF. INTEGRACAO DE TELA ##### |
||||
############################################################################ |
||||
|
||||
define("CONF_INTEGRACAO_TELA", false); |
||||
define("CONF_PARAMETROS_TELA", serialize(array("DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"))); |
||||
|
||||
########################################################################### |
||||
##### CONFIGURACAO DE PARADA TECNICA HUBSOFT ##### |
||||
########################################################################### |
||||
|
||||
define('CONF_PARADA_TECNICA_MSG', "PROBLEMA MASSIVO"); |
@ -0,0 +1,33 @@
|
||||
<meta charset="UTF-8"> |
||||
<table align="center" width="60%" style="border: 1px solid #ddd; background-color: #fff;border-radius: 8px;"> |
||||
<tr> |
||||
<td> |
||||
<br /> |
||||
<h2 style="text-align: center;">$titulo</h2> |
||||
<hr style="border: 0.05px solid rgb(241, 241, 241);" /> |
||||
</td> |
||||
|
||||
</tr> |
||||
<tr> |
||||
<td> |
||||
<div style="margin: auto;margin-left: 20px"> |
||||
<p>Olá $nome, estamos enviando a segunda via de sua fatura, |
||||
para mais informação entre em contato com nosso atendimento. |
||||
</p> |
||||
<p><b>Para visualizar seu Boleto clique em visualizar para abrir ou verifique nos anexos!</b></p> |
||||
<p>$link</p> |
||||
</div> |
||||
</td> |
||||
</tr> |
||||
<tr> |
||||
<td> |
||||
<br/> |
||||
<hr style="border: 0.05px solid rgb(241, 241, 241);" /> |
||||
<div style="width: 80%; margin: auto;"> |
||||
<p style="text-align: center;"><b>Este é uma mensagem gerada automaticamente, pedimos que não responda essa mensagem!</b></p> |
||||
<p style="text-align: center;"><i><b>A agradeçemos o seu contato!</b></i></p> |
||||
</div> |
||||
<br/> |
||||
</td> |
||||
</tr> |
||||
</table> |
@ -0,0 +1,33 @@
|
||||
<?php |
||||
$url = isset($_GET['url']) ? base64_decode($_GET['url']) : null; |
||||
|
||||
if ($url) { |
||||
$redirect = "http://{$_SERVER['SERVER_NAME']}/" . $url; |
||||
} |
||||
?> |
||||
<!DOCTYPE html> |
||||
<html> |
||||
<head> |
||||
<title>Simples IP</title> |
||||
<script> |
||||
setTimeout(redirectPage, 1); |
||||
function redirectPage() { |
||||
window.location.href = '<?= $redirect ?>';
|
||||
} |
||||
</script> |
||||
</head> |
||||
<body> |
||||
<table align="center" width="70%"> |
||||
<tr align="center"> |
||||
<td> |
||||
<h4>Você está sendo redirecionado!</h4> |
||||
</td> |
||||
</tr> |
||||
<tr align="center"> |
||||
<td> |
||||
<h5>Aguarde alguns segundos...</h5> |
||||
</td> |
||||
</tr> |
||||
</table> |
||||
</body> |
||||
</html> |
@ -0,0 +1,38 @@
|
||||
<?php //004fb
|
||||
if(!extension_loaded('ionCube Loader')){$__oc=strtolower(substr(php_uname(),0,3));$__ln='ioncube_loader_'.$__oc.'_'.substr(phpversion(),0,3).(($__oc=='win')?'.dll':'.so');if(function_exists('dl')){@dl($__ln);}if(function_exists('_il_exec')){return _il_exec();}$__ln='/ioncube/'.$__ln;$__oid=$__id=realpath(ini_get('extension_dir'));$__here=dirname(__FILE__);if(strlen($__id)>1&&$__id[1]==':'){$__id=str_replace('\\','/',substr($__id,2));$__here=str_replace('\\','/',substr($__here,2));}$__rd=str_repeat('/..',substr_count($__id,'/')).$__here.'/';$__i=strlen($__rd);while($__i--){if($__rd[$__i]=='/'){$__lp=substr($__rd,0,$__i).$__ln;if(file_exists($__oid.$__lp)){$__ln=$__lp;break;}}}if(function_exists('dl')){@dl($__ln);}}else{die('The file '.__FILE__." is corrupted.\n");}if(function_exists('_il_exec')){return _il_exec();}echo("Site error: the ".(php_sapi_name()=='cli'?'ionCube':'<a href="http://www.ioncube.com">ionCube</a>')." PHP Loader needs to be installed. This is a widely used PHP extension for running ionCube protected PHP code, website security and malware blocking.\n\nPlease visit ".(php_sapi_name()=='cli'?'get-loader.ioncube.com':'<a href="http://get-loader.ioncube.com">get-loader.ioncube.com</a>')." for install assistance.\n\n");exit(199); |
||||
?> |
||||
HR+cPxhIp+/P/zSqmAHYMione+iRnoY4a70d9+8HPphABKodPgg0LX0dNWmmTf72PvrODl8tXoOx |
||||
OnWnWY3bPCMgpYCiEM3wfUHndT57oH5oEBYX6kOIpTLdjIyzSYdY0UdmoIQGCk6c5EhQJmG1jZsF |
||||
0oRkySYvdyJ1js9ahyjLZa8G/obBAiaRSTQZ2mlHkrC64JvbAnwyFdenV0AuwAvMqnmNkGaS8M7v |
||||
z2grtgdWyPjADXcceTNqEwY+3aE7nqPuxMKGagfkogbsovoqZjnNUji0JEHvFsXeIq53QS2IaJ2l |
||||
DJnUB5fZ4sH84kjvnPL3RM7vKkLIZFmWJSzw9164W2EY1b7uCcU9kDWOrTWSJzuEV1HemIvKc4MH |
||||
UlhIVJ9XayEVz6YZu/CP9WjuHVwdM7eKveGggfPc/ng4w0kZu0kHuhZitTPnSvRicljxV0b9uJ7A |
||||
w6wMuAyW3+YcMCIfnS1ShqRWEUJIVaC5UCfAGJQGUONWGvqvmTf56+6ORxZr2M4BKEiHB3q2pA/F |
||||
FzLxctyTzYUtvQ5OUngSAcMZ0XTGZFpRqU1G26tK5YlZzzV1v3en3zI8L+I9PXcRDSsASRjvfGTM |
||||
u0oIb2IRDs0UtJ9hmNiiUdVoUuUbMyh0vBGNb+sOknIKjma0BqrZ6/yZ1cHWJs6YrsREn2U0/CML |
||||
q8OJ7NJQ1uday1ykQOMNYYpJN89LDkMDuGqIvk6ZM4rFzcxMv5HfzvrDaXhqz7FxffC2VfhpzHUE |
||||
8qXnq/nWzlOd1WPg0x9TryAQNOmBYwY/x8yEEolQIUEH8lgAWsiPNEJDVK7ztflpl6dMV/Wx6SFm |
||||
KJOVytSfT92u0+qgyXbpnjKJcVzYaqsv4sauH/3pBcCp2MqCLhWnZ4HA7QFUQI3X03TnrOtGOicM |
||||
sbGXQdYlilAYWJ717/99bXtJSTK+XF4OAmSEotRqumZgRnu4Z95FS1M7Vt8MvsZvTlcRZANANIXy |
||||
M3uB7BNqkBTacby8//XwY0biMhGBPtNG94Rynw7HgXJ3Kc1AmmI1wYepcQUTS6bzSoA84G9f4iTl |
||||
I4wIMdeh3ed0cN7C4zoDmTYdUM301+6eBAQoYTb7gid0so5hr8w053zfdWR6ZL8OjcwsKZbgsYt6 |
||||
fDnHGOikBtxJUfWgUZMP85YkADE7dFg4MfBrf+qw2e6e8AfjvD5EwQORsN4geE+ukyI3nfx5/H0n |
||||
Ch1QFygKU/XE13jnrIvYdWwRmVkEzOzt9gJBfwwWcwulm1xTnakzgK65ABtdYXr/kq0JdIh/p1uW |
||||
T3EU+nAANJhbfaySZztYAR3QokMofdITUiFRgFcrIsZxGShc6vzPQY5Y523yp3i+EnblY94Za9W8 |
||||
BnLp/ZEGLhk22gl03l0+1hwEjm28u5Fp6Y3bFJCIlvKdfakKI9kQIKslNy+IGz4QFNkZA0tpqG8g |
||||
TBwgQQQvDkUMTT2GI2dnr16Qia5uWSdCjac1s7ISUYrbT6q0KM96hW9y+5AfifsOCUJgDhbmTQlK |
||||
dEWGn4nIFVnR7nuVE+6gtPd8nQX1JDBysT2+8cC4Y4AsdE16bY1IU0GEvFH2/zfO749Lc/w3mRZt |
||||
/ji3jjj84KEkwn+Fw88E+qX1kIQdMDcj1KVCdRPi/imJun8oq/ruvQrc8XOVSXXFP/XjtovtMBta |
||||
Wucl8ONepSzHhOsWZu5h1lP+wGQrH1aEFtmZlZGR7Cd8+OmLEB0qi2NwNVmhZKLTxHvTqSOKhknX |
||||
KwTdpYUpTUs+NCt8fNLVR2fUWmgXfjBAsO+Nz74wGaCYBEVzt14pZyLju/XgA924KKUj7Bj7qqMs |
||||
wXLAmnidmyNXWlHfsgbvcnxU+jiUhRueFTe8bVZsXewgPzD8mTWZHDpYB18CNb0g42BRHOEHLgZP |
||||
3OnI/ESTnETpEb1Hc5HZmQzJpgDQEf7dr8iQQ5U2foDRj0+JXh9YqhWBYxdhjVe9HNYzc0WdYCfn |
||||
mtmirlofGz3zms3gSOsPyc0i7yrk1Ux/Hwlcz8n7uj1DjLk6gpu84Wq1J2lEYUHtAVKpFlgAuMKn |
||||
54rUGsZypuG5WaIMRTxRAa1HmfCHWTcWX+FaVgUdqvEtb+5ErJJS1mgwxcFQzC1SzRrMglgqT3k8 |
||||
B5pZ5intC9AKj3VgrmH8PR3cE1OCJN4d1IvQI+XBZa0cO5DruT7CVQ3sNdW+HUANpyGoudGOWdsb |
||||
lulnanyXy3rbKBpQKkLs+7GmLKuSJnL+VLIJ27w+dA0lEW2V5xY0cq0GiOAl4SMCHkATJh/yMG/4 |
||||
yniLu469jmUAUVbUn5rCw1Ozt4gnR8O3ZC+mFKh9HQjIp7DXwKMXckUgrV0KOfDUGHL43+raQla1 |
||||
cr+MQsWsRdQeUAX8jro/kQUkdnwOXqISEloB4fmXiZK8arMBWSXS+R3Zr9wxhC5m5zn1+3A9/aY4 |
||||
XAGZcL/+RwWgeJh7/sn2tdqqBu+GU4/fNoS6/4TH1qumKHesaZ8kOwXzSjhLmARLENJrPZYJna5d |
||||
ZdrDSfiGnq7wfGG5bGdN4JuPMBw1CasfiXQFzuBQjHXJPjKUXqheadxvyv7M7WFE/7gUa4eiJFV3 |
||||
nGFpKMHUWd0GlKHV2Ym= |
@ -0,0 +1,518 @@
|
||||
#!/usr/bin/php -q |
||||
<?php |
||||
include_once 'conf.php'; |
||||
include_once 'config.php'; |
||||
require_once 'IntegracaoDataBase.php'; |
||||
include_once("util/util.php"); |
||||
include_once '/var/www/html/aplicativo/admin/funcoes.php'; |
||||
include_once 'util/funcoesAmi.php'; |
||||
|
||||
error_reporting(E_ALL); |
||||
ini_set('display_errors', 1); |
||||
/** |
||||
* CONEXAO COM BANCO DE DADOS |
||||
*/ |
||||
$db = new IntegracaoDataBase(); |
||||
|
||||
/** |
||||
* APRESENTA OS PROVEDORES DISPONIVEIS |
||||
*/ |
||||
apresentaProvedoresDisponiveis($provedores); |
||||
|
||||
/** |
||||
* AGUARDA O COLABORADOR INFORMAR O SISTEMA A SER USADO! |
||||
*/ |
||||
$provedor = informaSistemaProvedor($provedores); |
||||
|
||||
/** |
||||
* INFORMA A EMPRESA CASO FOR CLOUD |
||||
*/ |
||||
$empresa = informaEmpresa(); |
||||
|
||||
/** |
||||
* INFORMA A FILA A SER INSTALADA |
||||
*/ |
||||
$queue = informaFilas(); |
||||
$filasInput = explode(",", $queue); |
||||
$filas = validaFilas($filasInput); |
||||
|
||||
$horarios = $filas; |
||||
|
||||
|
||||
/** |
||||
* COLETA A VERSAO DO BANCO DE DADOS |
||||
*/ |
||||
$version = installIntegracaoAtiva($provedor, $empresa); |
||||
|
||||
$db->beginTransaction(); |
||||
if ($version) { |
||||
|
||||
#############CADASTRO################ |
||||
echo "Integracao install init...\n"; |
||||
//ANUNCIOS |
||||
if(installAnuncio($empresa, $version)){ |
||||
echo "Anuncio install [ OK ]\n"; |
||||
} else { |
||||
echo "Anuncio install [ FAIL ]\n"; |
||||
$db->rollbackTransaction(); |
||||
} |
||||
//URAS |
||||
if(installURA($empresa, $version)){ |
||||
echo "URA install [ OK ]\n"; |
||||
}else{ |
||||
echo "URA install [ FAIL ]\n"; |
||||
$db->rollbackTransaction(); |
||||
} |
||||
//HORARIOS |
||||
if(installHorario($empresa, $version)){ |
||||
echo "Horario install [ OK ]\n"; |
||||
}else{ |
||||
echo "Horario install [ FAIL ]\n"; |
||||
$db->rollbackTransaction(); |
||||
} |
||||
//URA REDIR |
||||
if(installURARedir($provedor, $empresa, $version)){ |
||||
echo "URA Redir install [ OK ]\n"; |
||||
}else{ |
||||
echo "URA Redir install [ FAIL ]\n"; |
||||
$db->rollbackTransaction(); |
||||
} |
||||
|
||||
#########CONFIGURA FLUXO################ |
||||
echo "Integracao config init...\n"; |
||||
//ANUNCIO |
||||
if(configuraFluxoAnuncio($provedor, $empresa, $version)){ |
||||
echo "Anuncio fluxo config [ OK ]\n"; |
||||
}else{ |
||||
echo "Anuncio fluxo config [ FAIL ]\n"; |
||||
$db->rollbackTransaction(); |
||||
} |
||||
//URA |
||||
if(configuraFluxoUra($provedor, $empresa, $version)){ |
||||
echo "Ura fluxo config [ OK ]\n"; |
||||
}else{ |
||||
echo "Ura fluxo config [ FAIL ]\n"; |
||||
$db->rollbackTransaction(); |
||||
} |
||||
//HORARIO |
||||
if(configuraFluxoHorario($provedor, $empresa, $version)){ |
||||
echo "Horario fluxo config [ OK ]\n"; |
||||
}else{ |
||||
echo "Horario fluxo config [ FAIL ]\n"; |
||||
$db->rollbackTransaction(); |
||||
} |
||||
//URA REDIR |
||||
if(configuraFluxoUraRedir($provedor, $empresa, $version)){ |
||||
echo "Ura Redir fluxo config [ OK ]\n"; |
||||
}else{ |
||||
echo "Ura Redir fluxo config [ FAIL ]\n"; |
||||
$db->rollbackTransaction(); |
||||
} |
||||
|
||||
atualizaAsterisk(); |
||||
|
||||
$db->commitTransaction(); |
||||
} else { |
||||
$db->rollbackTransaction(); |
||||
} |
||||
|
||||
############################################################################ |
||||
#### FUNCOES INSTALACAO #### |
||||
############################################################################ |
||||
|
||||
function installIntegracaoAtiva($provedor, $empresa) { |
||||
global $provedores, $configs, $db; |
||||
try { |
||||
$db->findIntegracaoCustom(); |
||||
$versao = $db->findVersion($empresa)['versao'] + 1; |
||||
$version = $versao ? $versao : 1; |
||||
$metodos = $provedores[$provedor]['METODOS']; |
||||
foreach ($metodos as $metodo) { |
||||
$nome = $metodo . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$comando = ($empresa ? $empresa . '/' : '') . $provedor . '/' . lcfirst(str_replace(' ', '', ucwords(strtolower(str_replace('_', ' ', $metodo))))) . '.php'; |
||||
$db->createIntegracaoAtiva($nome, $version, $comando); |
||||
} |
||||
return $version; |
||||
} catch (Exception $ex) { |
||||
echo $ex->getMessage(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function installAnuncio($empresa, $version) { |
||||
global $anuncios, $configs, $db; |
||||
try { |
||||
foreach ($anuncios as $key => $val) { |
||||
$nome = $key . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$musica = strtolower($key . "_" . $configs['CONF']['NOMENCLATURA']) . ".ulaw"; |
||||
$db->addAnuncio($nome, $musica, null, null); |
||||
} |
||||
return true; |
||||
} catch (Exception $ex) { |
||||
echo $ex->getMessage(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function installURA($empresa, $version) { |
||||
global $ura, $configs, $db; |
||||
try { |
||||
foreach ($ura as $key => $val) { |
||||
$nome = $key . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$musica = strtolower($key . "_" . $configs['CONF']['NOMENCLATURA']) . ".ulaw"; |
||||
$db->addUra($nome, $musica); |
||||
} |
||||
return true; |
||||
} catch (Exception $ex) { |
||||
echo $ex->getMessage(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function installHorario($empresa, $version) { |
||||
global $horarios, $db, $configs; |
||||
try { |
||||
foreach ($horarios as $val) { |
||||
$nome = $val . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$db->addHorario($nome); |
||||
} |
||||
return true; |
||||
} catch (Exception $ex) { |
||||
echo $ex->getMessage(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function installURARedir($provedor, $empresa, $version) { |
||||
global $provedores, $ura_redir, $configs, $db; |
||||
$metodos = $provedores[$provedor]['METODOS']; |
||||
try { |
||||
foreach ($ura_redir as $key => $val) { |
||||
if(in_array(str_replace("REDIR_", "", $key), $metodos)){ |
||||
$nome = $key . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$musica = "silencio_int.ulaw"; |
||||
$db->addUra($nome, $musica); |
||||
} |
||||
} |
||||
return true; |
||||
} catch (Exception $ex) { |
||||
echo $ex->getMessage(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
############################################################################ |
||||
#### FUNCOES CONFIGURA FLUXO #### |
||||
############################################################################ |
||||
|
||||
|
||||
/* |
||||
* Configuração de Anuncios |
||||
*/ |
||||
function configuraFluxoAnuncio($provedor, $empresa, $version) { |
||||
global $provedores, $anuncios, $configs, $db, $horarios; |
||||
$metodos = $provedores[$provedor]['METODOS']; |
||||
|
||||
try { |
||||
foreach ($anuncios as $key => $val) { |
||||
$direcaoTipo = null; |
||||
$direcaoNome = null; |
||||
foreach($val as $tipo => $nome){ |
||||
if(in_array($nome, $metodos)){//PRIORIZAR INTEGRACAO CASO O PROVEDOR TIVER |
||||
$direcaoTipo = $tipo; |
||||
$direcaoNome = $nome; |
||||
|
||||
break; |
||||
}else if($tipo != CONF_INTEGRACAO){//CASO NAO EXISTIR INTEGRACAO DO PROVEDOR, NAO PODE PEGAR INTEGRACAO, POIS O PROXIMO PODE SER UMA INTEGRACAO NAO EXISTENTE |
||||
$direcaoTipo = $tipo; |
||||
$direcaoNome = $nome; |
||||
if($tipo == CONF_HORARIO){ |
||||
$direcaoNome = $horarios[0]; |
||||
} |
||||
|
||||
break; |
||||
} |
||||
} |
||||
|
||||
$nome = $direcaoNome . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$key .= "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
|
||||
$idAnuncio = $db->getAnuncioIdByName($key); |
||||
$idAcao = $db->getIdDirecionamento($direcaoTipo, $nome); |
||||
|
||||
$db->updateAnuncio($direcaoTipo, $idAcao, $idAnuncio); |
||||
|
||||
} |
||||
return true; |
||||
} catch (Exception $ex) { |
||||
echo $ex->getMessage(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
|
||||
/* |
||||
* Configuração de Horarios |
||||
*/ |
||||
function configuraFluxoHorario($provedor, $empresa, $version) { |
||||
global $filas, $configs, $db, $horarios, $horarioPadrao; |
||||
|
||||
try { |
||||
foreach ($horarios as $horarioNome) { |
||||
|
||||
$nome = $horarioNome . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$horarioId = $db->getHorarioIdByName($nome); |
||||
$fila = $filas[0] . ($empresa ? '_'.$empresa: ''); |
||||
|
||||
foreach($horarioPadrao as $horarioPadraoItem){ |
||||
foreach ($horarioPadraoItem as $tipo => $dado){ |
||||
|
||||
switch ($tipo) { |
||||
case "ITENS": |
||||
foreach($dado as $itens){ |
||||
$horario_ini = $itens['HORARIO_INICIAL']; |
||||
$horario_fim = $itens['HORARIO_FINAL']; |
||||
$dias_semana = 0; |
||||
$semana = $itens['DIA_SEMANA_INICIO']; |
||||
$semana_fim = $itens['DIA_SEMANA_FIM']; |
||||
$opcao = CONF_FILAS; |
||||
$acao = $fila; |
||||
$idAcao = $db->getIdDirecionamento($opcao, $acao); |
||||
|
||||
$db->addHorarioItens($horarioId, $horario_ini, $horario_fim, $dias_semana, $semana, $semana_fim, $opcao, $idAcao); |
||||
} |
||||
break; |
||||
|
||||
case "FORA_HORARIO": |
||||
foreach($dado as $tipo => $nome){ |
||||
$nome = $nome . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$idAcao = $db->getIdDirecionamento($tipo, $nome); |
||||
$db->updateHorario($horarioId, $tipo, $idAcao); |
||||
} |
||||
break; |
||||
|
||||
default: |
||||
break; |
||||
} |
||||
|
||||
} |
||||
} |
||||
} |
||||
return true; |
||||
} catch (Exception $ex) { |
||||
echo $ex->getMessage(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
|
||||
/* |
||||
* Configuração de Uras |
||||
*/ |
||||
function configuraFluxoUra($provedor, $empresa, $version) { |
||||
global $provedores, $ura, $configs, $db, $horarios; |
||||
$metodos = $provedores[$provedor]['METODOS']; |
||||
|
||||
try { |
||||
foreach ($ura as $key => $val) { |
||||
$key .= "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$uraId = $db->getUraIdByName($key); |
||||
foreach($val as $key => $itens){ |
||||
switch ($key) { |
||||
case "ITENS": |
||||
|
||||
foreach ($itens as $item){ |
||||
$direcaoTipo = null; |
||||
$direcaoNome = null; |
||||
foreach ($item['acao'] as $tipo => $nome) { |
||||
if(in_array($nome, $metodos)){//PRIORIZAR INTEGRACAO CASO O PROVEDOR TIVER |
||||
$direcaoTipo = $tipo; |
||||
$direcaoNome = $nome; |
||||
|
||||
break; |
||||
}else if($tipo != CONF_INTEGRACAO){//CASO NAO EXISTIR INTEGRACAO DO PROVEDOR, NAO PODE PEGAR INTEGRACAO, POIS O PROXIMO PODE SER UMA INTEGRACAO NAO EXISTENTE |
||||
$direcaoTipo = $tipo; |
||||
$direcaoNome = $nome; |
||||
if($tipo == CONF_HORARIO){ |
||||
$direcaoNome = $horarios[0]; |
||||
} |
||||
|
||||
break; |
||||
} |
||||
} |
||||
|
||||
$nome = $direcaoNome . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$idAcao = $db->getIdDirecionamento($direcaoTipo, $nome); |
||||
$db->addUraDestino($uraId, $item['numero'], $tipo, $idAcao, $item['sequencia'], $nome) ; |
||||
|
||||
} |
||||
|
||||
break; |
||||
|
||||
case "TIMEOUT": |
||||
$direcaoTipo = null; |
||||
$direcaoNome = null; |
||||
|
||||
foreach ($itens as $tipo => $nome){//PRIORIZAR INTEGRACAO CASO O PROVEDOR TIVER |
||||
if(in_array($nome, $metodos)){ |
||||
$direcaoTipo = $tipo; |
||||
$direcaoNome = $nome; |
||||
|
||||
break; |
||||
}else if($tipo != CONF_INTEGRACAO){//CASO NAO EXISTIR INTEGRACAO DO PROVEDOR, NAO PODE PEGAR INTEGRACAO, POIS O PROXIMO PODE SER UMA INTEGRACAO NAO EXISTENTE |
||||
$direcaoTipo = $tipo; |
||||
$direcaoNome = $nome; |
||||
if($tipo == CONF_HORARIO){ |
||||
$direcaoNome = $horarios[0]; |
||||
} |
||||
|
||||
break; |
||||
} |
||||
} |
||||
|
||||
$nome = $direcaoNome . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$idAcao = $db->getIdDirecionamento($direcaoTipo, $nome); |
||||
$db->updateUra($uraId, $direcaoTipo, $idAcao) ; |
||||
break; |
||||
|
||||
default: |
||||
break; |
||||
} |
||||
|
||||
|
||||
} |
||||
} |
||||
return true; |
||||
} catch (Exception $ex) { |
||||
echo $ex->getMessage(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
|
||||
/* |
||||
* Configuração de Uras Redirecionamento |
||||
*/ |
||||
function configuraFluxoUraRedir($provedor, $empresa, $version) { |
||||
global $provedores, $ura_redir, $configs, $db, $horarios; |
||||
$metodos = $provedores[$provedor]['METODOS']; |
||||
|
||||
try { |
||||
foreach ($ura_redir as $key => $val) { |
||||
$key .= "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$uraId = $db->getUraIdByName($key); |
||||
$sequencia=1; |
||||
foreach($val as $key => $item){ |
||||
$sequencia+=1; |
||||
if(!empty($item)){ |
||||
$direcaoTipo = null; |
||||
$direcaoNome = null; |
||||
foreach ($item as $tipo => $nome){ |
||||
if($tipo != CONF_INTEGRACAO){//NAO PODE TER REDIRECIONAMENTO PARA INTEGRACAO |
||||
$direcaoTipo = $tipo; |
||||
$direcaoNome = $nome; |
||||
if($tipo == CONF_HORARIO){ |
||||
$direcaoNome = $horarios[0]; |
||||
} |
||||
|
||||
break; |
||||
} |
||||
} |
||||
|
||||
$nome = $direcaoNome . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version; |
||||
$idAcao = $db->getIdDirecionamento($direcaoTipo, $nome); |
||||
$db->addUraDestino($uraId, $key, $tipo, $idAcao, $sequencia, $nome); |
||||
}else{ |
||||
$db->addUraDestino($uraId, $key, '', null, $sequencia, null); |
||||
} |
||||
|
||||
} |
||||
} |
||||
return true; |
||||
} catch (Exception $ex) { |
||||
echo $ex->getMessage(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
############################################################################ |
||||
#### FUNCOES IMPORTANTES #### |
||||
############################################################################ |
||||
|
||||
function apresentaProvedoresDisponiveis($provedores, $select = null) { |
||||
$prov = "Sistemas de provedores disponiveis: \n\n"; |
||||
foreach ($provedores as $key => $val) { |
||||
$prov .= sprintf(" - [ %s ] \n", $key); |
||||
if (strtoupper($select) == $key) { |
||||
return true; |
||||
} |
||||
} |
||||
if (!$select) { |
||||
echo $prov; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
function informaSistemaProvedor($provedores) { |
||||
do { |
||||
echo "\n --------------------------------- \n"; |
||||
echo "\nSelecione o sistema de provedor: \n"; |
||||
echo "\n --------------------------------- \n"; |
||||
$input = strtoupper(trim(fgets(STDIN))); |
||||
$resp = apresentaProvedoresDisponiveis($provedores, $input); |
||||
} while (!$resp); |
||||
return $input; |
||||
} |
||||
|
||||
function informaEmpresa() { |
||||
echo "\n --------------------------------- \n"; |
||||
echo "\nInforme a empresa: \n"; |
||||
echo "\n OBS: APENAS PARA EMPRESAS NO CLOUD \n"; |
||||
echo "\n --------------------------------- \n"; |
||||
$empresa = strtoupper(trim(fgets(STDIN))); |
||||
return $empresa; |
||||
} |
||||
|
||||
function informaFilas() { |
||||
echo "\n --------------------------------- \n"; |
||||
echo "\nInforme as que seram utilizadas na integracao: \n"; |
||||
echo "\n OBS: FILAS DEVEM SER SEPADADAS POR Virgulas(,) \n"; |
||||
echo "\n --------------------------------- \n"; |
||||
$queue = strtoupper(trim(fgets(STDIN))); |
||||
return $queue; |
||||
} |
||||
|
||||
function validaFilas($filas){ |
||||
global $db, $empresa; |
||||
$filaValidada = []; |
||||
foreach ($filas as $value) { |
||||
$fila = $value . ($empresa ? '_'.$empresa: ''); |
||||
$filaId = $db->getFilaNumeroByName($fila); |
||||
|
||||
if(empty($filaId)){ |
||||
|
||||
echo "\n --------------------------------- \n"; |
||||
echo "\n Fila $value nao existe \n"; |
||||
echo "\n --------------------------------- \n"; |
||||
exit(); |
||||
return null; |
||||
} |
||||
array_push($filaValidada, $value); |
||||
|
||||
} |
||||
|
||||
return $filaValidada; |
||||
} |
||||
|
||||
function atualizaAsterisk(){ |
||||
global $db; |
||||
gera_arquivos($db->getConnection(), 'ANUNCIOS'); |
||||
gera_arquivos($db->getConnection(), 'TESTES'); |
||||
|
||||
gera_arquivos($db->getConnection(), 'URA'); |
||||
gera_arquivos($db->getConnection(), 'TESTES'); |
||||
|
||||
gera_arquivos($db->getConnection(), 'HORARIOS'); |
||||
gera_arquivos($db->getConnection(), 'TESTES'); |
||||
} |
@ -0,0 +1,33 @@
|
||||
<?php |
||||
/* |
||||
* Verifica se o tipo de execução é custom, se for desvia a execução |
||||
* para um script customizado para integração, capturando antes os |
||||
* parametros de entrada. O programas ou scripts ficam localizados |
||||
* no diretorio /var/lib/asterisk/scripts/integracao/custom. |
||||
*/ |
||||
|
||||
if ($agi->get_variable('MEMBERINTERFACE', true) || $evento == 'ABANDON') { |
||||
$query = "SELECT itgm_id FROM pbx_integracao_reg a, pbx_integracao_metodo b WHERE b.itgm_id_pai = a.reg_id_metodo AND b.evento = 2 AND a.reg_uniqueid = '{$arg1}'"; |
||||
$result = pg_query($query); |
||||
$idMetodo = pg_fetch_assoc($result)['itgm_id']; |
||||
|
||||
$pathIntegra = "/var/lib/asterisk/scripts/integracao/custom/"; |
||||
|
||||
if ($idMetodo && ExecuteCustom($idMetodo, $nomeMetodo)) { |
||||
__logStr("ExecuteCustom", $nomeMetodo, 'serverAgi', true); |
||||
|
||||
/** Movidesk * */ |
||||
if (file_exists($pathIntegra . "Movidesk.php") && $evento == 'ABANDON') { |
||||
include $pathIntegra . "abandonadaChamada.php"; |
||||
} else { |
||||
include($nomeMetodo); |
||||
} |
||||
|
||||
exit; |
||||
} |
||||
} |
||||
|
||||
|
||||
|
||||
|
||||
?> |
@ -0,0 +1,9 @@
|
||||
<?php |
||||
|
||||
require_once "Movidesk.php"; |
||||
|
||||
$movidesk = new Movidesk(); |
||||
$protocolo = $movidesk->geraProtocoloSimples($uid); |
||||
$movidesk->agi()->set_variable('PROTOCOLO_REG', $protocolo); |
||||
$movidesk->executarFluxo('ANUNCIO', 'MUDO'); |
||||
|
@ -0,0 +1,8 @@
|
||||
#!/usr/bin/php -q |
||||
<?php |
||||
|
||||
include("util/util.php"); |
||||
include '/var/www/html/aplicativo/admin/funcoes.php'; |
||||
|
||||
gera_arquivos($dbcon, 'ANUNCIOS'); |
||||
gera_arquivos($dbcon, 'TESTES'); |
@ -0,0 +1,12 @@
|
||||
<?php |
||||
|
||||
require_once "Movidesk.php"; |
||||
|
||||
$movidesk = new Movidesk(); |
||||
|
||||
if (isset($argv[8]) && isset($argv[10])) { |
||||
$movidesk->log()->debug("argv: " . $uid, explode('-', $argv[8])[0], $argv[5], $argv[4], $argv[10], date('Y-m-d H:i:s')); |
||||
$resp = $movidesk->startTransferedCall($uid, explode('-', $argv[8])[0], $argv[5], $argv[4], $argv[10], date('Y-m-d H:i:s')); |
||||
$movidesk->log()->debug("Response: " . print_r($resp, true)); |
||||
} |
||||
|
@ -0,0 +1,432 @@
|
||||
<?php |
||||
|
||||
require_once 'phpagi/phpagi.php'; |
||||
require_once 'IntegracaoDataBase.php'; |
||||
require_once 'Logger.php'; |
||||
require_once 'SimpleMail.php'; |
||||
require_once 'conf.php'; |
||||
// include("util/util.php"); |
||||
|
||||
/* |
||||
|************************************************************************* |
||||
| SISTEMA UNICO DE INTEGRACAO * |
||||
|************************************************************************* |
||||
*/ |
||||
|
||||
/** |
||||
* Classe para implementacao das integracoes da Simples IP |
||||
* @author Lucas Awade |
||||
* @Desenvolvedor |
||||
* @SimplesIP |
||||
* @version 1.1.1 |
||||
*/ |
||||
class Integracao { |
||||
|
||||
protected $log; |
||||
protected $mail; |
||||
private $agi; |
||||
private $db; |
||||
|
||||
######################################################################## |
||||
## CONSTANTES DA CLASSE ## |
||||
######################################################################## |
||||
|
||||
const PATH_SOUND = '/var/lib/asterisk/sounds/customizados/'; |
||||
const AGI_ERROR_HANDLER = false; |
||||
|
||||
######################################################################## |
||||
## FUNCOES UTILITARIAS ## |
||||
######################################################################## |
||||
|
||||
/** |
||||
* - Retorno é os dados referentes ao retornado da API |
||||
* - Params são os dados que serão disponibilizados na tela do agente. |
||||
* |
||||
* @param array $retorno |
||||
* @param array $params |
||||
*/ |
||||
public function integracaoAgente($retorno, $params) { |
||||
$registros = 0; |
||||
$data = $this->db()->getRegistros(); |
||||
$retorno_cliente = "{$data['reg_uniqueid']}|{$data['reg_fone']}|{$data['id']}|"; |
||||
foreach ($retorno as $key => $value) { |
||||
if (in_array($key, $params)) { |
||||
$registros++; |
||||
$retorno_cliente .= sprintf("%s:%s", |
||||
strtoupper(str_replace("_", " ", $key)), |
||||
strtoupper(str_replace("|", "", $value))); |
||||
if (count($params) > $registros) { |
||||
$retorno_cliente .= "|"; |
||||
} |
||||
} |
||||
} |
||||
$this->db()->setRegistros(array('retorno_cliente' => $retorno_cliente)); |
||||
} |
||||
|
||||
/** |
||||
* Converte um CPF ou CNPJ com marcara referente a cada modelo. |
||||
* |
||||
* @param string $string |
||||
* @return boolean|string |
||||
*/ |
||||
protected function mask_cpf_cnpj($string) { |
||||
if (!empty($string)) { |
||||
if (strlen($string) == 11) { |
||||
$mask = "%s%s%s.%s%s%s.%s%s%s-%s%s"; |
||||
} elseif (strlen($string) == 14) { |
||||
$mask = "%s%s.%s%s%s.%s%s%s/%s%s%s%s-%s%s"; |
||||
} |
||||
return vsprintf($mask, str_split($string)); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Retorna telefone com o (DDD)Numero de acordo com o parametro passado caso nao possua DDD sera o padrao da central. |
||||
* @param string $telefone |
||||
* @return array |
||||
*/ |
||||
protected function mask_phone_tel($telefone) { |
||||
$retorno = array('telefone' => '', 'type' => ''); |
||||
if (strlen($telefone) == 11) { |
||||
$numero_1 = substr($telefone, 2, 5); |
||||
$numero_2 = substr($telefone, 7, 4); |
||||
$ddd = substr($telefone, 0, 2); |
||||
$telefone = "({$ddd}) " . $numero_1 . '-' . $numero_2; |
||||
$retorno['telefone'] = $telefone; |
||||
$retorno['type'] = 'celular'; |
||||
} else if (strlen($telefone) == 12) { |
||||
$ddd = substr($telefone, 1, 2); |
||||
$numero = substr($telefone, 3, 10); |
||||
$telefone = sprintf("(%s) %s", $ddd, $numero); |
||||
$retorno['telefone'] = $telefone; |
||||
$retorno['type'] = 'telefone'; |
||||
} else if (strlen($telefone) == 13) { |
||||
$ddd = substr($telefone, 2, 2); |
||||
$numero = substr($telefone, 4, 10); |
||||
$telefone = "(" . $ddd . ") " . $numero; |
||||
$retorno['telefone'] = $telefone; |
||||
$retorno['type'] = 'celular'; |
||||
} else if (strlen($telefone) == 10) { |
||||
$numero_1 = substr($telefone, 2, 4); |
||||
$numero_2 = substr($telefone, 6, 9); |
||||
$ddd = substr($telefone, 0, 2); |
||||
$telefone = "({$ddd}) " . $numero_1 . '-' . $numero_2; |
||||
$retorno['telefone'] = $telefone; |
||||
$retorno['type'] = 'fixo'; |
||||
} else { |
||||
return null; |
||||
} |
||||
return $retorno; |
||||
} |
||||
|
||||
/** |
||||
* Verifica se todos os parametros passados foram completados. |
||||
* |
||||
* @param array $args |
||||
* @return true|false |
||||
*/ |
||||
protected function getArgs($args) { |
||||
foreach ($args as $value) { |
||||
if (!$value) { |
||||
return false; |
||||
} |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
/** |
||||
* Verifica a diferenca em dias entre a data de entrada e a data atual. |
||||
* |
||||
* @param type $dateParam |
||||
* @return type |
||||
*/ |
||||
public function dateDiff($dateParam) { |
||||
$dateIni = strtotime(date('Y-m-d')); |
||||
|
||||
if (strstr($dateParam, "/")) { |
||||
$dateParam = date(strtotime(str_replace('/', '-', $dateParam))); |
||||
} else { |
||||
$dateParam = date(strtotime($dateParam)); |
||||
} |
||||
|
||||
$diff = ($dateIni - $dateParam); |
||||
$days = (int) floor($diff / (60 * 60 * 24)); |
||||
|
||||
return $days; |
||||
} |
||||
|
||||
/** |
||||
* Realiza a conversao de datas no formato brasileiro para a Defualt. |
||||
* @param string $data |
||||
* @return string|boolean |
||||
*/ |
||||
public function convertDateDefault($data) { |
||||
if ($data) { |
||||
$data = explode('/', $data); |
||||
return "{$data[2]}-{$data[1]}-{$data[0]}"; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Realiza a validação de pendencia financeira de acordo com a data informada |
||||
* |
||||
* OBS: O array deve possui nível = array( array('data' => 'yyyy-mm-dd')) |
||||
* OBS: O indice deve ser o nome do valor onde se encontra a data. |
||||
* @param array $array |
||||
* @param string $indice |
||||
* @param string $datavalida |
||||
* @return boolean |
||||
*/ |
||||
public function verificaDataPendencia($array, $indice, $datavalida = null) { |
||||
if (!$datavalida) { |
||||
$datavalida = strototime(date('Y-m-d')); |
||||
} else { |
||||
$datavalida = strtotime($datavalida); |
||||
} |
||||
|
||||
foreach ($array as $value) { |
||||
if (strtotime($value[$indice]) < $datavalida) { |
||||
return false; |
||||
} |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
/** |
||||
* Adiciona mascara no telefone para realizar a consulta |
||||
* |
||||
* @param type $value |
||||
* @return boolean |
||||
*/ |
||||
protected function phoneMask($value) { |
||||
if (!empty($value)) { |
||||
if (strlen($value) == 10) { |
||||
$mask = '(%s%s)%s%s%s%s-%s%s%s%s'; |
||||
} elseif (strlen($value) == 11) { |
||||
$mask = '(%s%s)%s%s%s%s%s-%s%s%s%s'; |
||||
} |
||||
return vsprintf($mask, str_split($value)); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Verifica se um servidor esta dando resposta de ping |
||||
* @param type $ip |
||||
* @return boolean |
||||
*/ |
||||
public function verificaLatencia($ip) { |
||||
$ping = explode(",", shell_exec("ping -c 4 $ip")); |
||||
$latencia = substr($ping[1], 1, 2); //resposta do ping |
||||
if ($latencia >= 2) { |
||||
return true; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Verbaliza digitos |
||||
* @param string|int $string |
||||
*/ |
||||
public function verbaliza($string) { |
||||
$vocaliza = str_split($string); |
||||
foreach ($vocaliza as $value) { |
||||
$this->agi()->say_digits($value); |
||||
} |
||||
} |
||||
|
||||
/* |
||||
* Objetct to array |
||||
*/ |
||||
|
||||
public function objectToArray($d) { |
||||
if (is_object($d)) { |
||||
$d = get_object_vars($d); |
||||
} |
||||
if (is_array($d)) { |
||||
return array_map($this->objectToArray(), $d); |
||||
} else { |
||||
return $d; |
||||
} |
||||
} |
||||
|
||||
############################################################################ |
||||
######## CONFIGURACAO DE EMAIL ######## |
||||
############################################################################ |
||||
|
||||
/** |
||||
* Inicia a instanciacao da Classe para envio de Email |
||||
* @param string $email |
||||
* @param string $password |
||||
* @param string $subject |
||||
*/ |
||||
public function SimpleMail($email, $password, $subject) { |
||||
$this->mail = new SimpleMail($email, $password, $subject); |
||||
$this->log->debug("Instanciacao SimpleMail : " . ($this->mail ? "SUCCESS" : "FAIL"), debug_backtrace()); |
||||
} |
||||
|
||||
/** |
||||
* Configura o servidor de Envio dos Emails. |
||||
* @param string $host |
||||
* @param string|int $port |
||||
* @param string $title |
||||
* @return boolean |
||||
*/ |
||||
public function confSMTP($host, $port, $title, $smtpAuth = true, $smtpSecure = 'TLS', $charset = 'UTF8') { |
||||
$this->log->debug("Configuracao SMTP", debug_backtrace()); |
||||
if ($this->mail) { |
||||
$this->mail->config($host, $port, $title, $smtpAuth, $smtpSecure, $charset); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
public function geraProtocoloSimples($uid){ |
||||
$connPG = $this->db()->getConnection(); |
||||
$protoAgente = GeraProtocolo($connPG, $uid); |
||||
return $protoAgente; |
||||
} |
||||
######################################################################## |
||||
## FUNCOES IMPORTANTES ## |
||||
######################################################################## |
||||
|
||||
/** |
||||
* Instancia um objeto de Logger. |
||||
* |
||||
* @param Logger $log |
||||
*/ |
||||
protected function setLog($log = false) { |
||||
if (!$this->log) { |
||||
$this->log = new Logger(CONF_LOGGER_PATH . CONF_NOME_EMPRESA, $log); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Retorna o objeto de Log. |
||||
* @return string |
||||
*/ |
||||
public function log() { |
||||
return $this->log; |
||||
} |
||||
|
||||
/** |
||||
* Instancia um objeto de AGI para se conectar com as informações do Asterisk. |
||||
* |
||||
* @return AGI |
||||
*/ |
||||
public function agi() { |
||||
if (!$this->agi) { |
||||
$data = $this->db()->getAuthAgi(); |
||||
$config = array(); |
||||
$config['phpagi']['error_handler'] = self::AGI_ERROR_HANDLER; |
||||
$config['asmanager']['server'] = $data['host_sck']; |
||||
$config['asmanager']['port'] = $data['porta_sck']; |
||||
$config['asmanager']['username'] = $data['usuario_sck']; |
||||
$config['asmanager']['secret'] = $data['senha_sck']; |
||||
$agi = new AGI('phpagi.conf', $config); |
||||
$this->agi = $agi; |
||||
return $agi; |
||||
} |
||||
return $this->agi; |
||||
} |
||||
|
||||
private function readAgiVariable() { |
||||
ob_implicit_flush(true); |
||||
set_time_limit(6); |
||||
$in = fopen("php://stdin", "r"); |
||||
$input = str_replace("\n", "", fgets($in, 4096)); |
||||
fclose($in); |
||||
$this->log->debug("Reading: " . $input); |
||||
return $input; |
||||
} |
||||
|
||||
public function getAgiVariable($variable = null) { |
||||
$this->log->debug("Executing...", debug_backtrace()); |
||||
while ($env = $this->readAgiVariable()) { |
||||
$s = explode(": ", $env); |
||||
$agi[str_replace("agi_", "", $s[0])] = trim($s[1]); |
||||
$this->log->debug("Data: " . print_r($agi, true), debug_backtrace()); |
||||
if (($env == "") || ($env == "\n")) { |
||||
break; |
||||
} |
||||
} |
||||
$this->log->debug("Reading: " . print_r($agi, true)); |
||||
if (!$variable || $agi[$variable]) { |
||||
return !$variable ? $agi : $agi[$variable]; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Instancia um objeto de IntegracaoDataBase para se conectar com dados do |
||||
* Banco de dados e credenciais do Manager. |
||||
* |
||||
* @return IntegracaoDataBase |
||||
*/ |
||||
public function db() { |
||||
if (!$this->db) { |
||||
$db = new IntegracaoDataBase(); |
||||
$this->db = $db; |
||||
} |
||||
return $this->db; |
||||
} |
||||
|
||||
protected function audioError() { |
||||
$this->log->debug('Audio de error'); |
||||
$exten = $this->db()->getAnuncio(); |
||||
$this->log->error('Encaminhando para áudio alternativo de Erros', debug_backtrace()); |
||||
$this->agi()->exec_goto($exten); |
||||
exit(); |
||||
} |
||||
|
||||
protected function integracaoReg(){ |
||||
global $ura, $tronco, $uid, $idMetodo, $uidOld, $numero; |
||||
$registros = array( |
||||
"id" => '', |
||||
"reg_ura" => $ura, |
||||
"reg_tronco" => $tronco, |
||||
"reg_uniqueid" => $uid, |
||||
"reg_id_metodo" => $idMetodo, |
||||
"reg_uniqueid" => $uid, |
||||
"reg_uniqueid_old" => $uidOld, |
||||
"reg_fone" => $numero, |
||||
"reg_status_exec" => '1', |
||||
"reg_inicio" => date()); |
||||
|
||||
$this->db()->setRegistros($registros); |
||||
|
||||
if (CONF_AUDIO_ERROR) { |
||||
$this->db()->setIdAudioError($this->db()->getAnuncioIdByName(strtoupper(CONF_AUDIO_ERROR.CONF_NOME_EMPRESA.CONF_VERSAO))); |
||||
} |
||||
} |
||||
|
||||
public function executarFluxo($tipo, $nome){ |
||||
#INEGRACAO DE TELA |
||||
if(CONF_INTEGRACAO_TELA){ |
||||
$parametrosTela = unserialize(CONF_PARAMETROS_TELA); |
||||
|
||||
$itgcTela = array(); |
||||
$itgcTelaNomes = array(); |
||||
|
||||
foreach($parametrosTela as $parametro){ |
||||
$itgcTela[$parametro] = str_replace(array("|",":"),"-",utf8_decode($this->agi()->get_variable($parametro, true))); |
||||
$itgcTelaNomes[] = "$parametro"; |
||||
|
||||
} |
||||
|
||||
$this->integracaoAgente($itgcTela, $itgcTelaNomes); |
||||
|
||||
} |
||||
|
||||
$dbFunction = "get".ucfirst(strtolower($tipo));//CONTRUIR NOME FUNCAO BUSCAR ID |
||||
$this->agi()->exec_goto($this->db()->$dbFunction(strtoupper($nome)));//REDIRECIONAR FLUXO |
||||
|
||||
|
||||
$this->db()->atualizaIntegracao(); |
||||
} |
||||
} |
||||
|
@ -0,0 +1,929 @@
|
||||
<?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çõ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ém de gravar logs de registros de dados, |
||||
* e qualquer erro é repassado a classe que está 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á 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(); |
||||
} |
||||
|
||||
######################################################################## |
||||
#### 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 DESTINO ######################### |
||||
/* |
||||
* 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; |
||||
} |
||||
|
||||
######################### 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){ |
||||
$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 |
||||
} |
||||
} |
||||
|
@ -0,0 +1,157 @@
|
||||
<?php |
||||
|
||||
/** |
||||
* Classe para utilizar |
||||
* |
||||
* @documentation: |
||||
* @author Lucas Awade |
||||
* @function developer |
||||
* @company SimplesIP |
||||
* @version 1.0.0 |
||||
*/ |
||||
class Logger { |
||||
/* |
||||
* GENERATE LOG |
||||
*/ |
||||
|
||||
private $active; |
||||
private $log; |
||||
private $type; |
||||
private $text; |
||||
|
||||
/* |
||||
* CONF. FILE LOG |
||||
*/ |
||||
private $file; |
||||
private $path; |
||||
private $name; |
||||
|
||||
/* |
||||
* CONST. MESSAGE TYPE |
||||
*/ |
||||
|
||||
const LOG_SUCCESS = "SUCCESS"; |
||||
const LOG_DEBUG = "DEBUG"; |
||||
const LOG_INFO = "INFO"; |
||||
const LOG_WARNING = "WARNING"; |
||||
const LOG_ERROR = "ERROR"; |
||||
|
||||
public function __construct($nameLog, $active = false, $path = "/var/log/asterisk/") { |
||||
$this->name = $nameLog; |
||||
$this->path = $path; |
||||
$this->active = $active; |
||||
$this->config($nameLog); |
||||
} |
||||
|
||||
######################################################################## |
||||
## TYPES ## |
||||
######################################################################## |
||||
|
||||
public function success($log, $debug_trace = null) { |
||||
$this->type = self::LOG_SUCCESS; |
||||
$this->text = $log; |
||||
$this->header($log, $debug_trace ? $debug_trace : debug_backtrace()); |
||||
$this->write(); |
||||
} |
||||
|
||||
public function debug($log, $debug_trace = null) { |
||||
$this->type = self::LOG_DEBUG; |
||||
$this->text = $log; |
||||
$this->header($log, $debug_trace ? $debug_trace : $this->name); |
||||
$this->write(); |
||||
} |
||||
|
||||
public function info($log, $debug_trace = null) { |
||||
$this->type = self::LOG_INFO; |
||||
$this->text = $log; |
||||
$this->header($log, $debug_trace ? $debug_trace : $this->name); |
||||
$this->write(); |
||||
} |
||||
|
||||
public function error($log, $debug_trace = null) { |
||||
$this->type = self::LOG_ERROR; |
||||
$this->text = $log; |
||||
$this->header($log, $debug_trace ? $debug_trace : $this->name); |
||||
$this->write(); |
||||
} |
||||
|
||||
public function warning($log, $debug_trace = null) { |
||||
$this->type = self::LOG_WARNING; |
||||
$this->text = $log; |
||||
$this->header($log, $debug_trace ? $debug_trace : $this->name); |
||||
$this->write(); |
||||
} |
||||
|
||||
######################################################################## |
||||
## IMPORTANT ## |
||||
######################################################################## |
||||
|
||||
private function write() { |
||||
if ($this->active) { |
||||
file_put_contents($this->file, $this->log, FILE_APPEND); |
||||
} |
||||
} |
||||
|
||||
private function header($log, $debug_trace) { |
||||
$this->log = "________________________________________________________________________________________\n"; |
||||
if(is_array($debug_trace)){ |
||||
$method = $debug_trace[0]['class'] ? "{$debug_trace[0]['class']}::{$debug_trace[0]['function']}" : $debug_trace[0]['function']; |
||||
$args = null; |
||||
|
||||
if(count($debug_trace[0]['args']) > 0){ |
||||
foreach($debug_trace[0]['args'] as $key => $arg){ |
||||
$x++; |
||||
$args .= $arg; |
||||
if(count($debug_trace[0]['args']) != $x){ |
||||
$args .= ","; |
||||
} |
||||
} |
||||
} |
||||
$this->log .= sprintf("\n[ %s ][ LINE %s ][ %s ][ ARGS ($args) ][ %s ]\n\n", date('d/m/Y H:i:s'), $debug_trace[0]['line'], $method, $this->type); |
||||
} else { |
||||
$this->log .= sprintf("\n[ %s ][ %s ][ %s ]\n\n", date('d/m/Y H:i:s'), $debug_trace, $this->type); |
||||
} |
||||
$this->log .= "> " . $log; |
||||
$this->log .= "\n\n ---------------------------------- [ FINISH LOGGER ] ----------------------------------\n\n"; |
||||
} |
||||
|
||||
public function openLog() { |
||||
//$file = fopen($this->file, 'rb'); |
||||
} |
||||
|
||||
public function locateLog() { |
||||
echo "\n\n {$this->file} \n\n"; |
||||
} |
||||
|
||||
######################################################################## |
||||
## CONFIGS ## |
||||
######################################################################## |
||||
|
||||
public function config($name, $exten = ".log", $prefix = null) { |
||||
if (file_exists($this->file)) { |
||||
$contents = file_get_contents($this->file); |
||||
} |
||||
|
||||
$this->file = trim($this->path . $prefix . ($name ? $name : $this->name) . $exten); |
||||
file_put_contents($this->file, $contents ? $contents : "", FILE_APPEND); |
||||
} |
||||
|
||||
public function getType() { |
||||
return $this->type; |
||||
} |
||||
|
||||
public function getText(){ |
||||
return $this->text; |
||||
} |
||||
|
||||
public function setLogger($active) { |
||||
if ($this->active === true) { |
||||
$this->active = $active; |
||||
} else if ($active === false) { |
||||
$this->active = $active; |
||||
} else { |
||||
$this->active = true; |
||||
} |
||||
} |
||||
|
||||
} |
@ -1,260 +0,0 @@
|
||||
<?php |
||||
|
||||
require_once "Http.php"; |
||||
require_once "WebHeader.php"; |
||||
require_once "Positus.php"; |
||||
|
||||
/** |
||||
* Description of Middleware Positus |
||||
* |
||||
* @author Lucas Awade |
||||
*/ |
||||
class Middleware extends Http { |
||||
|
||||
/** @class Positus */ |
||||
private $positus; |
||||
|
||||
/** @var return Positus request */ |
||||
private $request; |
||||
|
||||
/** @var agente in conversation */ |
||||
private $agente; |
||||
|
||||
/** @class WebHeader */ |
||||
private $header; |
||||
|
||||
/** @var Link local downloads image|document|video|sticker|audio */ |
||||
private $link = "http://voip.simplesip.com.br:8080/Positus/"; |
||||
|
||||
public function __construct($config = null) { |
||||
$this->header = new WebHeader($config); |
||||
$this->positus = new Positus(); |
||||
$this->hook(); |
||||
$this->router(); |
||||
} |
||||
|
||||
/** |
||||
* Start API headers |
||||
* @param array $config |
||||
*/ |
||||
public function api() { |
||||
$this->header->API(); |
||||
} |
||||
|
||||
/** |
||||
* Instance class Positus |
||||
* @return Positus |
||||
*/ |
||||
public function positus() { |
||||
return $this->positus; |
||||
} |
||||
|
||||
/** |
||||
* Set new link download |
||||
* @param string $link |
||||
*/ |
||||
public function setLink($link) { |
||||
$this->link = $link; |
||||
$this->formatLink(); |
||||
} |
||||
|
||||
/** |
||||
* Get link download |
||||
* @return string |
||||
*/ |
||||
public function getLink() { |
||||
$this->formatLink(); |
||||
return $this->link; |
||||
} |
||||
|
||||
private function router() { |
||||
$this->baseUri(); |
||||
switch (strtolower($this->param()[1])) { |
||||
case 'download': |
||||
$this->getLinkDownload(); |
||||
return null; |
||||
case 'message': |
||||
$this->message(); |
||||
return null; |
||||
default: |
||||
$this->header->response(301); |
||||
$this->header->redirect(); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Read input requests |
||||
*/ |
||||
private function hook() { |
||||
$this->request = file_get_contents('php://input'); |
||||
$this->positus()->log()->debug($this->request); |
||||
$this->request = json_decode($this->request, true); |
||||
} |
||||
|
||||
/** |
||||
* Create file and download in browser |
||||
*/ |
||||
private function getLinkDownload($link = null) { |
||||
if ($link) { |
||||
return $this->getLink() . "download/{$this->getId()}/{$this->getMimetype()}"; |
||||
} |
||||
|
||||
if ($this->header && strtolower($this->param()[1]) == 'download' && $this->param()[2] && $this->param()[3]) { |
||||
$file = $this->positus->baixarMidia($this->param()[2]); |
||||
$this->positus()->log()->debug("Name: " . $this->param()[2] . " | file: " . $file . " | Mime: " . base64_decode($this->param()[3])); |
||||
$this->header->fileTransfer($this->param()[2], $file, base64_decode($this->param()[3])); |
||||
exit(0); |
||||
} |
||||
} |
||||
|
||||
######################################################################## |
||||
##### POSITUS RESPONSE ##### |
||||
######################################################################## |
||||
|
||||
/**s |
||||
* Send the file to the active contact |
||||
* |
||||
* @return null |
||||
*/ |
||||
private function message() { |
||||
switch ($this->getType()) { |
||||
case 'text': |
||||
$this->positus()->log()->debug("Message: " . $this->getMessage() . " | Type: " . $this->getType() . " | Agente: " . $this->agente); |
||||
$this->positus->enviarMsg($this->agente, "*{$this->getProfile()}*: " . $this->getMessage()); |
||||
return null; |
||||
case 'image': |
||||
$this->positus->enviaImagem($this->agente, $this->getLinkDownload(1)); |
||||
return null; |
||||
case 'sticker': |
||||
$this->positus->enviaSticker($this->agente, $this->getLinkDownload(1)); |
||||
return null; |
||||
case 'video': |
||||
$this->positus->enviaVideo($this->agente, $this->getLinkDownload(1)); |
||||
return null; |
||||
case 'voice': |
||||
case 'audio': |
||||
$this->positus->enviaAudio($this->agente, $this->getLinkDownload(1)); |
||||
return null; |
||||
case 'document': |
||||
$this->positus->enviaDocumento($this->agente, $this->getLinkDownload(1)); |
||||
return null; |
||||
case 'contacts': |
||||
$this->positus->enviarContato($this->agente, $this->getContactFormatted(), $this->getContactPhone()); |
||||
return null; |
||||
case 'location': |
||||
$this->positus->enviarLocalizacao($this->agente, $this->getGeolocation('longitude'), $this->getGeolocation('latitude')); |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Profile WhatsApp |
||||
* @return string |
||||
*/ |
||||
public function getProfile() { |
||||
return $this->request['contacts'][0]['profile']['name']; |
||||
} |
||||
|
||||
/** |
||||
* Returns the type of the message |
||||
* @return string|boolean |
||||
*/ |
||||
public function getType() { |
||||
if ($this->request) { |
||||
return $this->request['messages'][0]['type']; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Returns the mime of the message |
||||
* @return string|boolean |
||||
*/ |
||||
public function getMimetype() { |
||||
if ($this->request['messages'][0][$this->getType()]['mime_type']) { |
||||
return base64_encode($this->request['messages'][0][$this->getType()]['mime_type']); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Returns the id of the message |
||||
* @return string|boolean |
||||
*/ |
||||
public function getId() { |
||||
if ($this->request && $this->getType()) { |
||||
return $this->request['messages'][0][$this->getType()]['id']; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Returns the (text, body) of the message |
||||
* @return string|boolean |
||||
*/ |
||||
public function getMessage() { |
||||
$message = $this->request['messages'][0]['text']['body']; |
||||
return ($message ? $message : false); |
||||
} |
||||
|
||||
/** |
||||
* Returns the name of the contact |
||||
* @return string|boolean |
||||
*/ |
||||
public function getContactFormatted() { |
||||
$formatted = $this->request['messages'][0]['contacts'][0]['name']['formatted_name']; |
||||
if ($formatted) { |
||||
return $formatted; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Returns the phone of the contact |
||||
* @return string|boolean |
||||
*/ |
||||
public function getContactPhone() { |
||||
$contact = $this->request['messages'][0]['contacts'][0]['phones'][0]['wa_id']; |
||||
if ($contact) { |
||||
return $contact; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Returns the latitude|longitude of the location |
||||
* @return string|boolean |
||||
*/ |
||||
public function getGeolocation($type) { |
||||
$geolocation = $this->request['messages'][0]['location'][strtolower($type)]; |
||||
if ($geolocation) { |
||||
return $geolocation; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
public function setAgente($agente) { |
||||
$this->agente = $agente; |
||||
} |
||||
|
||||
public function getAgente() { |
||||
$this->positus->db()->buscarAgenteDisponivel(); |
||||
return $this->agente; |
||||
} |
||||
|
||||
######################################################################## |
||||
##### FUNCTION UTIL ##### |
||||
######################################################################## |
||||
|
||||
private function formatLink() { |
||||
$link = str_split($this->link); |
||||
|
||||
if (strpos($this->link, 'http://') === false && strpos($this->link, 'http://') === false) { |
||||
$this->link = "http://" . $this->link; |
||||
} |
||||
|
||||
if (end($link) != "/") { |
||||
$this->link .= "/"; |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,333 @@
|
||||
<?php |
||||
|
||||
//include 'config.php'; |
||||
include 'RequestURL.php'; |
||||
include 'Logger.php'; |
||||
|
||||
class Positus |
||||
{ |
||||
|
||||
private $token; |
||||
private $url; |
||||
private $metodo; |
||||
|
||||
######################################################################## |
||||
## VARIAVEIS DA CLASSE ## |
||||
######################################################################## |
||||
private $query; |
||||
private $requestType; |
||||
private $request; |
||||
private $params = array(); |
||||
|
||||
######################################################################## |
||||
## RECURSOS DA API ## |
||||
######################################################################## |
||||
|
||||
function enviarMsg($whatsapp, $mensagem) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "text", |
||||
"text" => array("body" => "$mensagem") |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function enviarContato($whatsapp, $nome, $contato) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "contacts", |
||||
"contacts" => array( |
||||
array( |
||||
"name" => array( |
||||
"first_name" => "$nome", |
||||
"formatted_name" => "$nome" |
||||
), |
||||
"phones" => array( |
||||
array( |
||||
"phone" => "+$contato", |
||||
"type" => "CELL", |
||||
"wa_id" => "$contato" |
||||
) |
||||
) |
||||
) |
||||
) |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function enviarLocalizacao($whatsapp, $longitude, $latitude, $nome = null, $endereco = null) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "location", |
||||
"location" => array( |
||||
"longitude" => "$longitude", |
||||
"latitude" => "$latitude", |
||||
"name" => "$nome", |
||||
"address" => utf8_encode("$endereco") |
||||
) |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function enviaDocumento($whatsapp, $link, $titulo) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "document", |
||||
"document" => array("link" => "$link", "caption" => "$titulo") |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function enviaImagem($whatsapp, $link, $titulo = null) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "image", |
||||
"image" => array("link" => "$link", "caption" => "$titulo") |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function enviaSticker($whatsapp, $link) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "sticker", |
||||
"sticker" => array("link" => "$link") |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function enviaVideo($whatsapp, $link, $titulo = null) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "video", |
||||
"video" => array("link" => "$link", "caption" => "$titulo") |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function enviaAudio($whatsapp, $link) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "audio", |
||||
"audio" => array("link" => "$link") |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function baixarMidia($name) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->requestType("GET"); |
||||
$this->setMetodo('media/' . $name); |
||||
$file = $this->storage . $name; |
||||
file_put_contents($file, $this->exec()); |
||||
if (file_exists($file)) { |
||||
return $file; |
||||
} |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function enviarHSM($numero, $namespace, $nameTemplate, $parametrosHeader = [], $parametrosBody = []) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
$this->params = array( |
||||
'to' => "+$numero", |
||||
'type' => 'template', |
||||
'template' => |
||||
array( |
||||
'namespace' => $namespace, |
||||
'language' => |
||||
array( |
||||
'policy' => 'deterministic', |
||||
'code' => 'pt_BR', |
||||
), |
||||
'name' => $nameTemplate, |
||||
'components' => |
||||
array( |
||||
0 => |
||||
array( |
||||
'type' => 'header', |
||||
'parameters' => $parametrosHeader, |
||||
), |
||||
1 => |
||||
array( |
||||
'type' => 'body', |
||||
'parameters' => $parametrosBody, |
||||
), |
||||
), |
||||
), |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
|
||||
|
||||
######################################################################## |
||||
## FUNCOES DO SISTEMA ## |
||||
######################################################################## |
||||
|
||||
function __construct() |
||||
{ |
||||
$this->token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiMjZmNWQ5OGZhOGMzMWEwMzc1Yzg2NzlhOWEwZGUxZGEzNzYzMDRiNzY0NDYxY2Q0YjBiOWZjOWUxZmM3ZDc4N2ZmNmYzMTZmYTc2OGQ3OGYiLCJpYXQiOjE2NTYzNTcxODQuNTU2MjI3LCJuYmYiOjE2NTYzNTcxODQuNTU2MjMsImV4cCI6MTY4Nzg5MzE4NC41NTQzNDksInN1YiI6IjQxMTgiLCJzY29wZXMiOltdfQ.S3D4kVgJprt3Ez_GzWdTgWf8zlm6dy9C4Fvcb_eHzZnRfyIffCQLcLsH2RqZ8oJOdNk2vB58SRBZ-iIg7wa2diIObbEi0UWtDEUPa1Z7kw3rD8z3fvxCy8MF4dOmGarQKxA3qm2rdu-zYOcKMPKS6YY2aCx6iy8jEp_7hEdS1sUhU8LvZ2TzfZ7EOJ3VaauF1qxQa6cBSxLR9zIdce9u6SQmRhQQlYivUxdwWP2KL3lFl6LjQoIL6yvZX63X1xaq8btjaWK1TkxfRlL7JdCrQH5daQD5K5eI6bJxl4-4EqpJMpXTctaye5jBjEvcyPxBcYCY-N4LAjgMUGkz88hNKb-7lWUC5-GryB3DxvV9VGbTR7T4bHEwuvo_YlMK1Wo06hOMq2T60-7S4fJr2CHYNaR-PLRC7LOTFfPqGt_8ssIcXFbdRnNGyhcgoxC_oFbPjY9oaFEYaUx3EXgUAYNHNFSj7-k2IRdeW9nnV2t2AX_uDFAmgSq6wBSE1O1MoXPAVULMR5pSonY199ylSkYVYwEqURuRdgNPKi_TnMl2JOllBWcU0ivp4fNCqTH1tAEJ1Rcz24MyVErWiwmmZRoaV3zg_N4hcp5LiPPB0NQY3SveFTxu1dtek3tF90jxCHweI2gnug7aVJHRyHgxzXgM5c9fIXDEYowIovhE8A-gTk0"; |
||||
$this->url = "https://api.positus.global/v2/whatsapp/numbers/4661066a-43a3-4ccd-9bb8-eafdd04f85e8/"; |
||||
$this->request = new RequestURL(); |
||||
} |
||||
|
||||
private function setMetodo($metodo) |
||||
{ |
||||
$this->metodo = $metodo; |
||||
} |
||||
|
||||
/** |
||||
* Escreve a query para ser passada para o curl |
||||
* |
||||
* @param string $query |
||||
*/ |
||||
private function setQuery($query) |
||||
{ |
||||
return $this->query .= $query; |
||||
} |
||||
|
||||
/** |
||||
* retorna a string pronta da query do curl e limpa a variavel. |
||||
* |
||||
* @return string $query |
||||
*/ |
||||
private function getQuery() |
||||
{ |
||||
$query = $this->query; |
||||
$this->log()->debug('QUERY:' . $query); |
||||
unset($this->query); |
||||
return $query; |
||||
} |
||||
|
||||
/** |
||||
* Verifica se todos os parametros passados foram completados. |
||||
* |
||||
* @param array $args |
||||
* @return true|false |
||||
*/ |
||||
private function getArgs($args) |
||||
{ |
||||
foreach ($args as $value) { |
||||
if (!$value) { |
||||
return false; |
||||
} |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
/** |
||||
* Recebe o tipo de Requisição GET/POST |
||||
* |
||||
* @return boolean |
||||
*/ |
||||
private function requestType($req = null) |
||||
{ |
||||
if (!$req) { |
||||
return $this->requestType; |
||||
} |
||||
|
||||
if (strtoupper($req) == "GET") { |
||||
return $this->requestType = "GET"; |
||||
} else if (strtoupper($req) == "POST") { |
||||
return $this->requestType = "POST"; |
||||
} |
||||
} |
||||
|
||||
private function exec() |
||||
{ |
||||
$this->setQuery(json_encode($this->params)); //SET QUERY |
||||
$this->request->setUrl($this->url . $this->metodo); |
||||
|
||||
$this->log()->debug('URL QUERY:' . $this->url . $this->metodo); |
||||
|
||||
$header = array(); |
||||
$header[] = "Authorization: Bearer {$this->token}"; |
||||
if ($this->requestType == 'POST') { |
||||
$header[] = 'Content-Type: application/json'; |
||||
$this->request->post_field($this->getQuery(), true); |
||||
} |
||||
$this->request->header($header); |
||||
$this->request->method_request($this->requestType); |
||||
|
||||
$response = $this->request->exec_request(); |
||||
return $this->response($response); |
||||
} |
||||
|
||||
private function response($result) |
||||
{ |
||||
if ($result) { |
||||
if (json_decode($result, true) !== null) { |
||||
return json_decode($result, true); |
||||
} |
||||
return $result; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
private function log() |
||||
{ |
||||
return new Logger('integracao'); |
||||
} |
||||
} |
@ -0,0 +1,101 @@
|
||||
<?php |
||||
|
||||
class RequestURL |
||||
{ |
||||
|
||||
private $method; |
||||
private $curl; |
||||
private $ssl; |
||||
private $post_field; |
||||
private $header; |
||||
|
||||
const CONF_TIMEOUT = 30; |
||||
|
||||
public function setUrl($url, $ssl = true) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
$this->curl = curl_init($url); |
||||
$this->ssl = is_bool($ssl) ? $ssl : true; |
||||
} |
||||
|
||||
public function header($header) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if (is_array($header)) { |
||||
$this->header = $header; |
||||
} else { |
||||
$this->header = array($header); |
||||
} |
||||
} |
||||
|
||||
public function post_field($data, $json = false) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($json) { |
||||
$this->post_field = $data; |
||||
} else { |
||||
$this->post_field = http_build_query($data); |
||||
} |
||||
} |
||||
|
||||
public function method_request($method = 'GET') |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
$this->method = strtoupper($method); |
||||
} |
||||
|
||||
public function exec_request() |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
$this->conf_request(); |
||||
|
||||
if (curl_error($this->curl)) { |
||||
return false; |
||||
} |
||||
$this->response = curl_exec($this->curl); |
||||
curl_close($this->curl); |
||||
return $this->response($this->response); |
||||
} |
||||
|
||||
public function convert_xml_to_object() |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if (!$this->response) { |
||||
return false; |
||||
} |
||||
return simplexml_load_string($this->response); |
||||
} |
||||
|
||||
private function response($result) |
||||
{ |
||||
// logger('deburguer')->info(print_r($result, true)); |
||||
if ($result) { |
||||
if (json_decode($result, true) !== null) { |
||||
return json_decode($result, true); |
||||
} |
||||
return $result; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
############################################################################ |
||||
### CONFIG. CURL ### |
||||
############################################################################ |
||||
|
||||
private function conf_request() |
||||
{ |
||||
curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); |
||||
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header); |
||||
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $this->method); |
||||
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); |
||||
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, $this->ssl); |
||||
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, $this->ssl); |
||||
|
||||
if ($this->post_field) { |
||||
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->post_field); |
||||
} |
||||
|
||||
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, self::CONF_TIMEOUT); |
||||
curl_setopt($this->curl, CURLOPT_TIMEOUT, self::CONF_TIMEOUT); |
||||
} |
||||
} |
@ -0,0 +1,258 @@
|
||||
<?php |
||||
|
||||
/** |
||||
* Classe para implementacao envio de Emails em Massa ou único! |
||||
* |
||||
* @author Lucas Awade |
||||
* @Desenvolvedor |
||||
* @version 1.1.0 |
||||
*/ |
||||
require("phpmailer/class.phpmailer.php"); |
||||
|
||||
class SimpleMail { |
||||
######################################################################## |
||||
## CONFIGURACOES CLASSE ## |
||||
######################################################################## |
||||
|
||||
private $log; |
||||
private $limit; |
||||
private $sended = 0; |
||||
private $mailer; |
||||
|
||||
######################################################################## |
||||
## CONFIGURACOES MAIL ## |
||||
######################################################################## |
||||
private $host; |
||||
private $port; |
||||
private $smtpAuth; |
||||
private $smtpSecure; |
||||
private $charset; |
||||
private $mail; |
||||
private $passwd; |
||||
private $title; |
||||
private $subject; |
||||
|
||||
######################################################################## |
||||
## CONFIGURACOES DEFAULT ## |
||||
######################################################################## |
||||
|
||||
public function __construct($mail, $passwd, $subject, $logger = false) { |
||||
$this->log = new Logger('simplesmailer', $logger, "/var/log/"); |
||||
if ($mail && $passwd && $subject) { |
||||
$this->mail = $mail; |
||||
$this->passwd = $passwd; |
||||
$this->subject = $subject; |
||||
$this->phpMailer(); |
||||
} else { |
||||
$this->log->error('Nao foi possivel instanciar a Classe SimplesMail,informacoes incompletas!', debug_backtrace()); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Metodo de configuração do Host de Envio; |
||||
* @param string $host |
||||
* @param string|int $port |
||||
* @param string $title |
||||
* @param boolean $smtpAuth |
||||
* @param string $smtpSecure |
||||
* @param string $charset |
||||
*/ |
||||
public function config($host, $port, $title, $smtpAuth = true, $smtpSecure = 'TLS', $charset = 'UTF8') { |
||||
$this->host = $host; |
||||
$this->port = $port; |
||||
$this->title = $title; |
||||
$this->smtpAuth = $smtpAuth; |
||||
$this->smtpSecure = $smtpSecure; |
||||
$this->charset = $charset; |
||||
$this->phpMailer(); |
||||
} |
||||
|
||||
/** |
||||
* Informa um limite de email em massa a ser enviado. |
||||
* |
||||
* @param int $limit |
||||
*/ |
||||
public function limitSend($limit) { |
||||
$this->log->debug('Limite de Email: ' . $limit, debug_backtrace()); |
||||
$this->limit = $limit; |
||||
} |
||||
|
||||
/** |
||||
* Mensagem escrito em HTML para envio de um email elaborado. |
||||
* |
||||
* Os dados em $data devem ser em formato array como o exemplo: |
||||
* array("MSG_HEADER" => 'Seja Bem vindo', "MSG_FOOTER" => 'Volte Sempre'); |
||||
* |
||||
* @param string $path |
||||
* @param array $data |
||||
*/ |
||||
public function pathBodyMail($path, $data) { |
||||
$this->log->info('Path HTML Body: ' . $path, debug_backtrace()); |
||||
$contents = file_get_contents($path); |
||||
foreach ($data as $key => $value) { |
||||
$contents = str_replace($key, $value, $contents); |
||||
} |
||||
$this->mailer->Body = $contents; |
||||
} |
||||
|
||||
/** |
||||
* Mensagem simples para o envio rapido de um email. |
||||
* |
||||
* @param string $message |
||||
*/ |
||||
public function bodyMessage($message) { |
||||
$this->mailer->Body = $message; |
||||
} |
||||
|
||||
/** |
||||
* Adiciona no email anexos para serem enviados |
||||
* @param array|string $files |
||||
*/ |
||||
public function setAddAttachment($files) { |
||||
if ($files) { |
||||
if (is_array($files)) { |
||||
foreach ($files as $name => $file) { |
||||
$this->mailer->AddAttachment($file, (is_numeric($name) ? '' : $name)); |
||||
} |
||||
} else { |
||||
$this->mailer->AddAttachment($files); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Adiciona no email imagens para visualizadas. |
||||
* |
||||
* #=> Caso o paramtro for um array seu corpo deve ser enviado da seguinte forma: |
||||
* $cid = array('minha_img_jpg' => 'img/path/mail/header.jpg'); |
||||
* |
||||
* #=> Caso for uma string deve se passar o cid caso contrario gera um cid randomico; |
||||
* |
||||
* @param array|string $images |
||||
*/ |
||||
public function setAddEmbeddedImage($images, $cid = null) { |
||||
if ($images) { |
||||
if (is_array($images)) { |
||||
foreach ($images as $name => $image) { |
||||
$this->mailer->AddEmbeddedImage($image, $name); |
||||
} |
||||
} else { |
||||
$cid = $cid ? $cid : rand(100, 999999); |
||||
$this->mailer->AddEmbeddedImage($image, $cid); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Esta funcao envia os email em massa ou unicos. |
||||
* |
||||
* Email em massa é necessario passar um array com os emails seu indice que representa o email. |
||||
* |
||||
* Email unico so é preciso passar o email na variavel $data; |
||||
* |
||||
* @param array|string $data |
||||
* @param string $indice |
||||
* @return array|boolean |
||||
*/ |
||||
public function mailing($data, $indice = '') { |
||||
if (is_array($data)) { |
||||
$invalid = array(); |
||||
foreach ($data as $mail) { |
||||
if ($this->sended <= $this->limit) { |
||||
$mail = $indice ? $mail[$indice] : $mail; |
||||
$this->setSended(); |
||||
if (!$this->send($mail)) { |
||||
$invalid[] = $mail; |
||||
} |
||||
} |
||||
} |
||||
return $invalid; |
||||
} else { |
||||
if ($this->send($data)) { |
||||
$this->setSended(); |
||||
return true; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
} |
||||
|
||||
public function getErrorSend(){ |
||||
return $this->mailer->ErrorInfo; |
||||
} |
||||
|
||||
######################################################################## |
||||
## ENVIO MAIL ## |
||||
######################################################################## |
||||
|
||||
/** |
||||
* Gerencia a quantidade de email que esta sendo enviado. |
||||
*/ |
||||
private function setSended() { |
||||
$this->sended++; |
||||
} |
||||
|
||||
/** |
||||
* Gerencia o envio do email para estar sempre no limite de envio. |
||||
* |
||||
* @return boolean |
||||
*/ |
||||
public function getSended() { |
||||
$this->log->debug("Sended: " . $this->sended, debug_backtrace()); |
||||
if ($this->sended < $this->limit) { |
||||
return true; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Metodo responsavel para realizar o envio do email. |
||||
* |
||||
* @param string $mailFrom |
||||
* @return boolean |
||||
*/ |
||||
private function send($mailFrom) { |
||||
if (!$this->mailer) { |
||||
$this->log->error("Objeto nao criado!", debug_backtrace()); |
||||
return false; |
||||
} |
||||
|
||||
try { |
||||
$this->mailer->setFrom($this->mail, $this->title); |
||||
$this->mailer->addAddress($mailFrom, $this->title); |
||||
$this->mailer->send(); |
||||
$this->mailer->clearAllRecipients(); |
||||
$this->log->success("Mail: {$mailFrom} | Send Queue: {$this->sended}", debug_backtrace()); |
||||
return true; |
||||
} catch (Exception $ex) { |
||||
if ($this->mailer->ErrorInfo) { |
||||
$this->log->error("ErrorInfo Mail: " . $this->mailer->ErrorInfo . " | Exception Mail: {$mailFrom} >> " . $ex->getMessage(), debug_backtrace()); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Cria as configurações e parametros para ser implementado e enviado os emails. |
||||
* |
||||
* @void null |
||||
*/ |
||||
private function phpMailer() { |
||||
$this->log->debug("Instanciando objeto PHPMailer", debug_backtrace()); |
||||
$this->mailer = new PHPMailer(true); |
||||
$this->mailer->isSMTP(); |
||||
$this->mailer->Host = $this->host; |
||||
$this->mailer->SMTPAuth = $this->smtpAuth; |
||||
$this->mailer->isHTML(true); |
||||
|
||||
if ($this->smtpAuth) { |
||||
$this->mailer->SMTPSecure = $this->smtpSecure; |
||||
$this->mailer->Username = $this->mail; |
||||
$this->mailer->Password = $this->passwd; |
||||
} |
||||
|
||||
$this->mailer->CharSet = $this->charset; |
||||
$this->mailer->Port = $this->port; |
||||
$this->mailer->Subject = $this->subject; |
||||
} |
||||
} |
@ -0,0 +1,82 @@
|
||||
<?php |
||||
|
||||
########################################################################### |
||||
##### ##### |
||||
##### ARQUIVO PARA A CONFIGURACAO DE ACESSO API ##### |
||||
##### ----------------------------------------- ##### |
||||
##### CREDENCIAIS DE ACESSO ##### |
||||
########################################################################### |
||||
|
||||
define('CONF_ID_CREDENCIAIS', ''); |
||||
define('CONF_TOKEN_API', 'KZojmoAm6YEArEYMBNO7s9dWYcp7tuz9BWnxrmAX'); |
||||
define('CONF_URL_API', 'https://api.redesmartnet.hubsoft.com.br/'); |
||||
define('CONF_USER_API', 'api@simplesip.com.br'); |
||||
define('CONF_PASSWORD_API', '^x7j#ivjzrC9&Fuaqu'); |
||||
define('CONF_USERID_API', '5'); |
||||
|
||||
########################################################################### |
||||
##### CONFIGURACOES ##### |
||||
########################################################################### |
||||
|
||||
define("CONF_INTEGRACAO_TELA", true); |
||||
define("CONF_PARAMETROS_TELA", serialize(array("NOME", "PLANO", "ENDERECO", "IP", "STATUS", "OBSERVACOES"))); |
||||
|
||||
/** @CONF_NOME_EMPRESA => colocar _EMPRESA */ |
||||
define('CONF_NOME_EMPRESA', ''); |
||||
|
||||
/** @CONF_AUDIO_ERROR => ID Áudio */ |
||||
define('CONF_AUDIO_ERROR', ''); |
||||
|
||||
define('CONF_LOGGER_PATH', 'integracao'); |
||||
define('CONF_LOGGER_ATIVO', true); |
||||
define('CONF_LOGGER_DB_ATIVO', false); |
||||
|
||||
define('CONF_FATURA_DIAS_ANTES', 30); |
||||
define('CONF_FATURA_DIAS_APOS', 5); |
||||
|
||||
define('CONF_AUDIO_ERROR', 'INTEGRACAO_ERRO_INT'); |
||||
|
||||
########################################################################### |
||||
##### CREDENCIAIS DE ENVIO DE EMAIL ##### |
||||
########################################################################### |
||||
|
||||
define('CONF_EMAIL_TITLE_INVOICE', '[NO-REPLY] Envio de Fatura'); |
||||
define('CONF_EMAIL_SUBTITLE_INVOICE', 'Estamos enviando o pedido de Segunda Via da sua Fatura!'); |
||||
define('CONF_SENDER_EMAIL_USER', ''); |
||||
define('CONF_SENDER_EMAIL_PASSWORD', ''); |
||||
define('CONF_SMTP_HOST', ''); |
||||
define('CONF_SMTP_POST', '587'); |
||||
|
||||
|
||||
############################################################################ |
||||
##### CONF. KING CAMPANHA ##### |
||||
############################################################################ |
||||
|
||||
define('CONF_CAMP_LOGIN', "novahelp"); |
||||
define('CONF_CAMP_DATAINI', date('Y-m-d 08:00:00')); |
||||
define('CONF_CAMP_DATAFIM', date('Y-m-d 18:00:00')); |
||||
define('CONF_CAMP_RAMAL', "2000"); |
||||
define('CONF_CAMP_FLUXO', 0); |
||||
define('CONF_CAMP_PAUSA', 1); |
||||
define('CONF_CAMP_NUMREDISCAGEM', 1); |
||||
define('CONF_CAMP_MAXCALL', 10); |
||||
define('CONF_CAMP_RINGTIME', 45); |
||||
define('CONF_CAMP_INTERVALO', 1); |
||||
define('CONF_CAMP_AMD', 0); |
||||
define('CONF_CAMP_NDS', 0); |
||||
define('CONF_CAMP_PRIOMOVEL', 0); |
||||
define('CONF_CAMP_MAXCALLAGENT', 3); |
||||
|
||||
|
||||
############################################################################ |
||||
##### CONF. INTEGRACAO DE TELA ##### |
||||
############################################################################ |
||||
|
||||
define("CONF_INTEGRACAO_TELA", true); |
||||
define("CONF_PARAMETROS_TELA", serialize(array("DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"))); |
||||
|
||||
########################################################################### |
||||
##### CONFIGURACAO DE PARADA TECNICA HUBSOFT ##### |
||||
########################################################################### |
||||
|
||||
define('CONF_PARADA_TECNICA_MSG', "PROBLEMA MASSIVO"); |
@ -0,0 +1,33 @@
|
||||
<meta charset="UTF-8"> |
||||
<table align="center" width="60%" style="border: 1px solid #ddd; background-color: #fff;border-radius: 8px;"> |
||||
<tr> |
||||
<td> |
||||
<br /> |
||||
<h2 style="text-align: center;">$titulo</h2> |
||||
<hr style="border: 0.05px solid rgb(241, 241, 241);" /> |
||||
</td> |
||||
|
||||
</tr> |
||||
<tr> |
||||
<td> |
||||
<div style="margin: auto;margin-left: 20px"> |
||||
<p>Olá $nome, estamos enviando a segunda via de sua fatura, |
||||
para mais informação entre em contato com nosso atendimento. |
||||
</p> |
||||
<p><b>Para visualizar seu Boleto clique em visualizar para abrir ou verifique nos anexos!</b></p> |
||||
<p>$link</p> |
||||
</div> |
||||
</td> |
||||
</tr> |
||||
<tr> |
||||
<td> |
||||
<br/> |
||||
<hr style="border: 0.05px solid rgb(241, 241, 241);" /> |
||||
<div style="width: 80%; margin: auto;"> |
||||
<p style="text-align: center;"><b>Este é uma mensagem gerada automaticamente, pedimos que não responda essa mensagem!</b></p> |
||||
<p style="text-align: center;"><i><b>A agradeçemos o seu contato!</b></i></p> |
||||
</div> |
||||
<br/> |
||||
</td> |
||||
</tr> |
||||
</table> |
@ -0,0 +1,8 @@
|
||||
<?php |
||||
|
||||
include "Positus.php"; |
||||
|
||||
$positus = new Positus(); |
||||
$positus->enviarHSM('556581282842', 'bd4a396f_11b1_4986_8efd_6442eaf2e52a', 'apresentacao_com_botao'); |
||||
|
||||
?> |
@ -0,0 +1,378 @@
|
||||
<?php |
||||
|
||||
namespace app\Providers; |
||||
|
||||
use app\Interfaces\IApiMedia; |
||||
|
||||
class Positus extends Requests implements IApiMedia |
||||
{ |
||||
/** @var string $hook resposta do webhook */ |
||||
private $hook; |
||||
|
||||
function getContentType() |
||||
{ |
||||
return "application/json; charset=UTF-8"; |
||||
} |
||||
|
||||
public function getchannel() |
||||
{ |
||||
return CONF_WHATSAPP_CHANNEL; |
||||
} |
||||
|
||||
function setHook($hook) |
||||
{ |
||||
$this->hook = json_decode($hook, true); |
||||
} |
||||
|
||||
function enviarMedia($whatsapp, $link, $type, $titulo = null) |
||||
{ |
||||
$tipos = []; |
||||
$tipos['link'] = $link; |
||||
if (!empty($titulo)) { |
||||
$tipos['caption'] = $titulo; |
||||
} |
||||
$this->debug = debug_backtrace(); |
||||
$this->params = [ |
||||
"to" => "+$whatsapp", |
||||
"type" => "$type", |
||||
"$type" => $tipos |
||||
]; |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
|
||||
function enviarMsg($whatsapp, $mensagem, $encode = true) |
||||
{ |
||||
if ($encode) { |
||||
$mensagem = utf8_encode($mensagem); |
||||
} |
||||
$this->debug = debug_backtrace(); |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "text", |
||||
"text" => array("body" => "$mensagem") |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
|
||||
function enviarHSM($numero, $namespace, $nameTemplate, $parametrosHeader = [], $parametrosBody = []) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
$this->params = array( |
||||
'to' => "+$numero", |
||||
'type' => 'template', |
||||
'template' => |
||||
array( |
||||
'namespace' => $namespace, |
||||
'language' => |
||||
array( |
||||
'policy' => 'deterministic', |
||||
'code' => 'pt_BR', |
||||
), |
||||
'name' => $nameTemplate, |
||||
'components' => |
||||
array( |
||||
0 => |
||||
array( |
||||
'type' => 'header', |
||||
'parameters' => $parametrosHeader, |
||||
), |
||||
1 => |
||||
array( |
||||
'type' => 'body', |
||||
'parameters' => $parametrosBody, |
||||
), |
||||
), |
||||
), |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
|
||||
function enviarMsgIterativaLista($whatsapp, $mensagem, $nomeButton, $lista, $prex = '') |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "interactive", |
||||
"interactive" => array( |
||||
"type" => "list", |
||||
"body" => array( |
||||
"text" => utf8_encode($mensagem) |
||||
), |
||||
"action" => array( |
||||
"button" => utf8_encode($nomeButton), |
||||
"sections" => $this->montaSection($lista, $prex) |
||||
) |
||||
) |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
$ret = $this->exec(); |
||||
return $ret; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function montaSection($lista, $prex = '') |
||||
{ |
||||
$sections = []; |
||||
for ($i = 0; $i < count($lista); $i++) { |
||||
array_push( |
||||
$sections, |
||||
array( |
||||
"id" => "$prex$i", |
||||
"title" => utf8_encode("{$lista[$i]['title']}"), |
||||
"description" => utf8_encode("{$lista[$i]['sub']}") |
||||
) |
||||
); |
||||
} |
||||
return array( |
||||
array( |
||||
"title" => utf8_encode("Comandos"), |
||||
"rows" => $sections |
||||
), |
||||
|
||||
); |
||||
} |
||||
|
||||
function enviarMsgIterativaBotao($whatsapp, $mensagem, $buttons) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "interactive", |
||||
"recipient_type" => "individual", |
||||
"interactive" => array( |
||||
"type" => "button", |
||||
"body" => array( |
||||
"text" => utf8_encode($mensagem) |
||||
), |
||||
"action" => array( |
||||
"buttons" => $buttons |
||||
) |
||||
) |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
$ret = $this->exec(); |
||||
return $ret; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function enviarContato($whatsapp, $nome, $contato) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($whatsapp) { |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "contacts", |
||||
"contacts" => array( |
||||
array( |
||||
"name" => array( |
||||
"first_name" => "$nome", |
||||
"formatted_name" => "$nome" |
||||
), |
||||
"phones" => array( |
||||
array( |
||||
"phone" => "+$contato", |
||||
"type" => "CELL", |
||||
"wa_id" => "$contato" |
||||
) |
||||
) |
||||
) |
||||
) |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function enviarLocalizacao($whatsapp, $longitude, $latitude, $nome = null, $endereco = null) |
||||
{ |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->params = array( |
||||
"to" => "+$whatsapp", |
||||
"type" => "location", |
||||
"location" => array( |
||||
"longitude" => "$longitude", |
||||
"latitude" => "$latitude", |
||||
"name" => "$nome", |
||||
"address" => utf8_encode("$endereco") |
||||
) |
||||
); |
||||
$this->requestType("POST"); |
||||
$this->setMetodo('messages'); |
||||
return $this->exec(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
function baixarMidia() |
||||
{ |
||||
if (in_array($this->getType(), ['location', 'contacts', 'text'])) { |
||||
return true; |
||||
} |
||||
$name = $this->getId(); |
||||
$this->debug = debug_backtrace(); |
||||
if ($this->getArgs(func_get_args())) { |
||||
$this->requestType("GET"); |
||||
$this->setMetodo('media/' . $name); |
||||
$pathfile = $this->storage . $name; |
||||
$retorno = $this->exec(); |
||||
file_put_contents($pathfile, $retorno); |
||||
if (file_exists($pathfile)) { |
||||
return true; |
||||
} |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Profile WhatsApp |
||||
* @return string |
||||
*/ |
||||
public function getProfile() |
||||
{ |
||||
return $this->hook['contacts'][0]['profile']['name']; |
||||
} |
||||
|
||||
/** |
||||
* Phone WhatsApp |
||||
* @return string |
||||
*/ |
||||
public function getPhone() |
||||
{ |
||||
return $this->hook['contacts'][0]['wa_id']; |
||||
} |
||||
|
||||
/** |
||||
* Returns the type of the message |
||||
* @return string|boolean |
||||
*/ |
||||
public function getType() |
||||
{ |
||||
if ($this->hook) { |
||||
return $this->hook['messages'][0]['type']; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Returns the mime of the message |
||||
* @return string|boolean |
||||
*/ |
||||
public function getMimetype() |
||||
{ |
||||
if ($this->hook['messages'][0][$this->getType()]['mime_type']) { |
||||
return $this->hook['messages'][0][$this->getType()]['mime_type']; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Returns the id of the message |
||||
* @return string|boolean |
||||
*/ |
||||
public function getId() |
||||
{ |
||||
if ($this->hook && $this->getType()) { |
||||
if ($this->getType() == 'text') { |
||||
return $this->hook['messages'][0]['id']; |
||||
} |
||||
return $this->hook['messages'][0][$this->getType()]['id']; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Returns the (text, body) of the message |
||||
* @return string|boolean |
||||
*/ |
||||
public function getIsValidMessage() |
||||
{ |
||||
return $this->hook['contacts']; |
||||
} |
||||
|
||||
/** |
||||
* Returns the (text, body) of the message |
||||
* @return string|boolean |
||||
*/ |
||||
public function getMessage() |
||||
{ |
||||
if ($this->hook['messages'][0]['interactive']) { |
||||
if ($this->hook['messages'][0]['interactive']['list_reply']) { |
||||
$id = $this->hook['messages'][0]['interactive']['list_reply']['id']; |
||||
if (strpos($id, 'P') === 0) { |
||||
return $this->hook['messages'][0]['interactive']['list_reply']['description']; |
||||
} |
||||
return $this->hook['messages'][0]['interactive']['list_reply']['title']; |
||||
} else { |
||||
return $this->hook['messages'][0]['interactive']['button_reply']['title']; |
||||
} |
||||
} |
||||
$message = $this->hook['messages'][0]['text']['body']; |
||||
return ($message ? $message : false); |
||||
} |
||||
public function setMessage($msg) |
||||
{ |
||||
$this->hook['messages'][0]['text']['body'] = $msg; |
||||
} |
||||
/** |
||||
* Returns the name of the contact |
||||
* @return string|boolean |
||||
*/ |
||||
public function getContactFormatted() |
||||
{ |
||||
$formatted = $this->hook['messages'][0]['contacts'][0]['name']['formatted_name']; |
||||
if ($formatted) { |
||||
return $formatted; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Returns the phone of the contact |
||||
* @return string|boolean |
||||
*/ |
||||
public function getContactPhone() |
||||
{ |
||||
$contact = $this->hook['messages'][0]['contacts'][0]['phones'][0]['wa_id']; |
||||
if ($contact) { |
||||
return $contact; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Returns the latitude|longitude of the location |
||||
* @return string|boolean |
||||
*/ |
||||
public function getGeolocation($type) |
||||
{ |
||||
$geolocation = $this->hook['messages'][0]['location'][strtolower($type)]; |
||||
if ($geolocation) { |
||||
return $geolocation; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
|
||||
public function retornaTituloDocument() |
||||
{ |
||||
if ($this->hook['messages'][0]['document']) { |
||||
return $this->hook['messages'][0]['document']['filename']; |
||||
} |
||||
return null; |
||||
} |
||||
} |
@ -0,0 +1,144 @@
|
||||
<?php |
||||
|
||||
namespace app\Providers; |
||||
|
||||
class Requests |
||||
{ |
||||
/** @var string $token token de autenticação das requesições */ |
||||
protected $token; |
||||
|
||||
/** @var string $url url base das requsições */ |
||||
protected $url; |
||||
|
||||
/** @var string $metodo endpoint da requsição */ |
||||
protected $metodo; |
||||
|
||||
/** @var string $query query da requsição */ |
||||
protected $query; |
||||
|
||||
/** @var string $query tipo da requsição */ |
||||
protected $requestType; |
||||
|
||||
/** @var array $params parametros da request */ |
||||
protected $params = array(); |
||||
|
||||
/** @var RequestURL $request description */ |
||||
protected $request; |
||||
|
||||
/** @var string $contentType tipo da requsição */ |
||||
protected $contentType; |
||||
|
||||
/** @var string $storage caminho dos arquivos */ |
||||
public $storage = CONF_PATH_FILES; |
||||
|
||||
function __construct() |
||||
{ |
||||
$this->request = new RequestURL(); |
||||
$this->setToken(); |
||||
$this->setUrl(CONF_WHATSAPP_AUTH_URL); |
||||
} |
||||
|
||||
function response($result) |
||||
{ |
||||
if ($result) { |
||||
if (json_decode($result, true) !== null) { |
||||
return json_decode($result, true); |
||||
} |
||||
return $result; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
function exec($typeAuth = 'Bearer') |
||||
{ |
||||
$this->setQuery(json_encode($this->params)); //SET QUERY |
||||
$this->request->setUrl($this->url . $this->metodo, false); |
||||
|
||||
$header = array(); |
||||
|
||||
$header[] = "Authorization: $typeAuth {$this->token}"; |
||||
|
||||
|
||||
if ($this->requestType == 'POST') { |
||||
$header[] = 'Content-Type: application/json'; |
||||
$this->request->post_field($this->getQuery(), true); |
||||
} |
||||
$this->request->header($header); |
||||
$this->request->method_request($this->requestType); |
||||
logger('request')->info(print_r($header, true)); |
||||
logger('request')->info($this->requestType); |
||||
return $this->request->exec_request(); |
||||
} |
||||
|
||||
/** |
||||
* Recebe o tipo de Requisi��o GET/POST |
||||
* |
||||
* @return boolean |
||||
*/ |
||||
function requestType($req = null) |
||||
{ |
||||
if (!$req) { |
||||
return $this->requestType; |
||||
} |
||||
|
||||
if (strtoupper($req) == "GET") { |
||||
return $this->requestType = "GET"; |
||||
} else if (strtoupper($req) == "POST") { |
||||
return $this->requestType = "POST"; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Verifica se todos os parametros passados foram completados. |
||||
* |
||||
* @param array $args |
||||
* @return true|false |
||||
*/ |
||||
function getArgs($args) |
||||
{ |
||||
foreach ($args as $value) { |
||||
if (!$value) { |
||||
return false; |
||||
} |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
function setMetodo($metodo) |
||||
{ |
||||
$this->metodo = $metodo; |
||||
} |
||||
|
||||
/** |
||||
* Escreve a query para ser passada para o curl |
||||
* |
||||
* @param string $query |
||||
*/ |
||||
function setQuery($query) |
||||
{ |
||||
return $this->query .= $query; |
||||
} |
||||
|
||||
/** |
||||
* retorna a string pronta da query do curl e limpa a variavel. |
||||
* |
||||
* @return string $query |
||||
*/ |
||||
function getQuery() |
||||
{ |
||||
$query = $this->query; |
||||
unset($this->query); |
||||
return $query; |
||||
} |
||||
|
||||
function setToken($token = CONF_WHATSAPP_AUTH_TOKEN) |
||||
{ |
||||
$this->token = $token; |
||||
} |
||||
|
||||
public function setUrl($url) |
||||
{ |
||||
$this->url = $url; |
||||
} |
||||
} |
Loading…
Reference in new issue