You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

452 lines
16 KiB

<?php
include "util/Crypt.php";
define("CONF_KEY_LICENCA", md5("S1MPL3S_IP"));
define("CONF_FILE_PATH", "/var/www/html/aplicativo/cadastros/licenca/");
define("CONF_FILE_UUID", 'uuid.lca');
/**
* COLETA AS INFORMAÇÕES DO VENDA MAIS E GERA O TOTAL DE LICENCA EM UM ARQUIVO CRIPTOGRAFADO
* @param type $licenca
* @param type $perfil
*/
function GerarArquivo($licenca, $perfil) {
$company = [
"perfil_aplicacao_id" => $perfil,
];
/** ARRAY PARA GUARDAR INFORMACOES DOS CONTRATOS * */
$info = [
'licenca_pa' => 0,
'licenca_ramal' => 0,
'licenca_supervisor' => 0,
'licenca_discador_preview' => 0,
'licenca_discador_powerdial' => 0,
'licenca_discador_predictive' => 0,
'licenca_pesquisa' => 0,
'licenca_tarifador' => 0,
'licenca_whatsapp' => 0,
'licenca_workflow' => 0,
'licenca_mesaoperadora' => 0,
'licenca_mult_channel' => 0,
'licenca_helpdesk' => 0,
'licenca_crm' => 0,
'licenca_manager_one' => 0,
'licenca_help_custom' => 0,
'data_registro' => date('Y-m-d'),
'user_registro' => 0,
'server_registro' => 0,
'confirma_registro' => date('Y-m-d')
];
$clto_data = ["contrato_assinatura", "contrato_inicio", "contrato_fim"];
$data = [];
$prefix = "clto_";
foreach ($licenca as $clto) {
foreach ($clto as $k => $v) {
$data[$prefix . $k] = $v;
if (array_key_exists($k, $company)) {
$data[$prefix . $k] = $company[$k];
}
if (array_key_exists($k, $info) && is_int($v)) {
$data[$prefix . $k] += $v;
}
if (in_array($k, $clto_data)) {
$data[$prefix . $k] = date('Y-d-m', strtotime($v));
}
}
}
$fileName = $data['clto_razao_social'] . $data['clto_cnpj'];
$file = criarArquivo($fileName, $data);
DownloadArquivo($file);
}
/**
* GERA UM ARQUIVO COM AS INFORMACOES DA MAQUINA
* >> CASO PASSE $tmp GERA UM ARQUIVO TEMPORARIO PARA A CONSULTA DO UUID EM TEMPO REAL
* @param type $tmp
* @return string
*/
function GerarUUID($tmp = false) {
$file = CONF_FILE_PATH . ($tmp ? '/tmp/' . md5(date('Y-m-d') . CONF_KEY_LICENCA) . "_" : '') . CONF_FILE_UUID;
if (!file_exists($file) && $tmp) {
foreach (glob('*_' . CONF_FILE_UUID) as $f) {
unlink($f);
}
}
if (file_exists($file) && $tmp) {
return $file;
}
CnvrtFileExec('dmidecode -t system | grep UUID: > ' . $file);
CnvrtFileExec('chown pbx:pbx ' . $file);
$contents = __readFile($file, false);
$uid = explode(':', trim($contents));
__writeFile($file, ['uuid' => trim($uid[1]), 'genereted' => date('Y-m-d H:i:s'), 'contract' => md5(trim($uid[1]))], false);
return $tmp ? $file : trim($uid[1]);
}
/**
* CRIA O ARQUIVO DE LICENCA COM O NOME E DOCUMENTO EM MD5 JUNTAMENTE COM AS INFORMACOES GERADAS DA FUNCAO GERAARQUIVO
* @param type $filename
* @param array $data
* @return string
*/
function criarArquivo($filename, $data) {
$file = CONF_FILE_PATH . md5($filename) . ".lca";
$data['clto_data_log'] = $file;
__createFile($file, preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $data));
return $file;
}
/**
* INFORMA OS DADOS DE CONTRATO E UUID PARA O ARQUIVO DE LICENCA QUANDO FIZER O UPLOAD NO SITE
* @param type $file
* @return boolean
*/
function validarArquivo($file) {
$file_lca = CONF_FILE_PATH . $file['conf']['name'];
$tmpFileLocal = $file['conf']['tmp_name'];
$tmpFileName = $file['conf']['name'];
move_uploaded_file($tmpFileLocal, $file_lca);
$content = __readFile($file_lca);
if (explode('.', $tmpFileName)[1] == 'lca') {
$uuid = GerarUUID();
__writeFile($file_lca, ['clto_server_registro' => $uuid, 'clto_contrato_numero' => md5($uuid)]);
$content = __readFile($file_lca);
return $content;
}
return false;
}
/**
* DOWNLOAD DO ARQUIVO REGISTRADO NO VENDAMAIS
* @param type $nomeArquivo
* @return type
*/
function DownloadArquivo($nomeArquivo) {
try {
ob_clean();
$nome = basename($nomeArquivo);
$linhas = file_get_contents($nomeArquivo);
header("Pragma: public");
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Accept-Ranges: bytes');
header('Content-Type: ' . GetMimeContentType($nome));
header('Content-Disposition: attachment; filename="' . $nome . '";');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
echo $linhas;
ob_flush();
unlink($nomeArquivo);
exit;
} catch (Exception $ex) {
return $ex->getMessage();
}
}
/**
* VALIDA A LICENCA DURANTE O PRIMEIRO LOGIN COM AS INFORMACOES DO ARQUIVO TEMPORARIO| BANCO SIMPLES E ARQUIVO DE LICENCA
* @param type $dbcon
* @return boolean
*/
function validarLicenca($dbcon) {
$db = __getLicencaPBX($dbcon);
if (!$db) {
return false;
}
$f = GerarUUID(true);
if ($f) {
$uid = __readFile($f);
}
$content = __readFile($db['clto_data_log']);
$uuid = __readFile(CONF_FILE_PATH . CONF_FILE_UUID);
if ($content['clto_server_registro'] != $uid['uuid'] || $db['clto_server_registro'] != $uid['uuid']) {
return false;
}
if ($uuid['contract'] != $db['clto_contrato_numero']) {
return false;
}
return true;
}
########################################
#### FUNCOES ESCRITA/LEITURA ####
########################################
function __createFile($file, $dados) {
$crypt = new Crypt(CONF_KEY_LICENCA);
$dataCrypt = $crypt->encrypt(json_encode($dados, true));
file_put_contents($file, $dataCrypt);
}
function __readFile($file, $encrypeted = true) {
$crypt = new Crypt(CONF_KEY_LICENCA);
$content = file_get_contents($file);
if ($encrypeted) {
$content = $crypt->decrypt($content);
}
$json = json_decode($content, true);
if ($json) {
return $json;
}
return $content;
}
function __writeFile($file, $dados = null, $append = true) {
$crypt = new Crypt(CONF_KEY_LICENCA);
$content = __readFile($file);
if ($dados) {
if (!$append) {
file_put_contents($file, $crypt->encrypt(json_encode($dados, true)));
return;
}
foreach ($dados as $k => $v) {
$content[$k] = $v;
}
file_put_contents($file, $crypt->encrypt(json_encode($content, true)));
return;
}
file_put_contents($file, $crypt->encrypt(json_encode($content, true)));
}
########################################
#### BANCO DE DADOS ####
########################################
function __getLicencaPBX($dbcon) {
$query = sprintf("SELECT clto_cnpj, clto_data_log, clto_server_registro, clto_contrato_numero FROM pbx_controle_licenciamento;");
$result = pg_query($dbcon, $query);
$res = pg_fetch_assoc($result);
return $res;
}
function __getLicencaVMais($document) {
$query = sprintf("SELECT clto_cnpj, clto_data_log, clto_server_registro, clto_contrato_numero FROM sip_controle_licenciamento WHERE clto_cnpj = '$document';");
$resp = __execSQLServer($query);
return $resp;
}
/**
* INSERE AS INFORMACOES PASSADAS NO ARQUIVO DE LICENCA PARA O BANCO DO SIMPLESIP E VENDA MAIS
* @param type $dbcon
* @param type $data
* @return boolean
* @throws Exception
*/
function __validLicenca($dbcon, $data) {
if (!$data['clto_cnpj']) {
throw new Exception("As informações do arquivo está corrompido!");
}
$respbx = __getLicencaPBX($dbcon);
$resVmais = __getLicencaVMais($data['clto_cnpj']);
$vendamais = $resVmais['clto_cnpj'] == $data['clto_cnpj'] ? 'vendamais' : '';
if ($respbx['clto_cnpj'] == $data['clto_cnpj'] || $vendamais) {
__updateLicenca($dbcon, $data, $vendamais);
return true;
}
if (__sendLicenca($dbcon, $data)) {
return true;
}
return false;
}
function __updateLicenca($dbcon, $data, $t = null) {
$msql = ConectaMssql();
$info = "";
foreach ($data as $k => $v) {
$info .= "$k = '$v',";
}
$set = substr($info, 0, -1);
$table = ["pbx" => 'pbx_controle_licenciamento', "vendamais" => 'sip_controle_licenciamento'];
foreach ($table as $k => $v) {
$query = sprintf("UPDATE $v SET %s WHERE clto_cnpj = '%s';", $set, $data['clto_cnpj']);
if ($k == 'pbx' && (empty($t) || $t == $k)) {
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Não foi possível atualizar as informações da licença!");
}
}
if ($k == 'vendamais' && (empty($t) || $t == $k)) {
__execSQLServer($query, false);
}
}
return true;
}
function __sendLicenca($dbcon, $data) {
$column = array_keys($data);
$values = array_values($data);
$table = ["pbx" => 'pbx_controle_licenciamento', "vendamais" => 'sip_controle_licenciamento'];
foreach ($table as $k => $v) {
$query = sprintf("INSERT INTO {$v} (%s) VALUES('%s');", implode(',', $column), implode("','", $values));
if ($k == 'pbx') {
if (!pg_query($dbcon, $query)) {
throw new Exception("Não foi possível inserir as informações da licença no [Simples IP]!");
}
} else {
__execSQLServer($query, false);
}
}
return true;
}
function GetPerfilApl() {
$query = "SELECT * FROM sip_perfil_aplicacao";
$resp = __execSQLServer($query);
return $resp;
}
function __dadosLicenca($document, $contracts = []) {
$ctact = implode("','", $contracts);
$data = date('Y-m-d');
$query = "select a.CGC_CPF as cnpj,
d.Numero as contrato_numero,
upper(dbo.sip_remove_acentos(RazaoSocial)) razao_social,
upper(dbo.sip_remove_acentos(Fantasia)) nome_fantasia,
c.Descricao as atividade_empresa,
f.Cidade as cidade_empresa,
f.Uf as uf_empresa,
b.ContatoId as contato_id,
upper( dbo.sip_remove_acentos(b.PrimeiroNome)) as contato_nome,
lower( dbo.sip_remove_acentos(coalesce(b.Email1, b.Email2, Email))) as contato_email,
coalesce(b.Celular, b.TelefoneComercial, b.TelefoneResidencial, a.Telefone) as contato_fone,
0 as perfil_aplicacao_id,
dbo.FormataData(d.DataAssinatura) as contrato_assinatura,
dbo.FormataData(d.DataInicio) as contrato_inicio,
dbo.FormataData(d.DataFim) as contrato_fim,
isnull((
select sum( cast(ContratosItens.Quantidade as int))
from ContratosItens
inner join Produtos on Produtos.ProdutoId = ContratosItens.ProdutoId
inner join Linhas on Linhas.LinhaId = Produtos.LinhaId and Linhas.LinhaId = 32
inner join Divisoes on Divisoes.DivisaoId = Linhas.DivisaoId and Divisoes.DivisaoId = 11
where ContratosItens.ContratoId = d.ContratoId
and Produtos.Referencia like '%AG-P%(%PA)%' OR Produtos.Referencia like '%ISP-P%(%PA)%' OR Produtos.Referencia like '%SX-P%(%PA)%' OR Produtos.Referencia like '%SMT-P%(%PA)%'
),0) as licenca_pa,
isnull((
select sum( cast(ContratosItens.Quantidade as int))
from ContratosItens
inner join Produtos on Produtos.ProdutoId = ContratosItens.ProdutoId
inner join Linhas on Linhas.LinhaId = Produtos.LinhaId and Linhas.LinhaId = 32
inner join Divisoes on Divisoes.DivisaoId = Linhas.DivisaoId and Divisoes.DivisaoId = 11
where ContratosItens.ContratoId = d.ContratoId
and Produtos.Referencia like '%AG-R%(%RAMAL)%' OR Produtos.Referencia like '%ISP-R%(%RAMAL)%' OR Produtos.Referencia like '%SX-R%(%RAMAL)%' OR Produtos.Referencia like '%SMT-R%(%RAMAL)%'), 0) as licenca_ramal,
isnull ((select sum( cast(ContratosItens.Quantidade as int))
from ContratosItens
inner join Produtos on Produtos.ProdutoId = ContratosItens.ProdutoId
inner join Linhas on Linhas.LinhaId = Produtos.LinhaId and Linhas.LinhaId = 32
inner join Divisoes on Divisoes.DivisaoId = Linhas.DivisaoId and Divisoes.DivisaoId = 11
where ContratosItens.ContratoId = d.ContratoId
and Produtos.Referencia like '%LICENCA DE SUPERVISOR%'), 0) as licenca_supervisor,
0 as licenca_discador_preview,
0 as licenca_discador_powerdial,
0 as licenca_discador_predictive,
0 as licenca_pesquisa,
0 as licenca_tarifador,
0 as licenca_whatsapp,
0 as licenca_workflow,
0 as licenca_mesaoperadora,
0 as mult_channel,
0 as licenca_helpdesk,
0 as licenca_crm,
0 as licenca_manager_one,
0 as licenca_help_custom,
'$data' as data_registro,
0 as user_registro,
0 as server_registro,
'$data' as confirma_registro
from Clientes a
inner join Contatos b on b.ClienteId = a.ClienteId
inner join RamosDeAtividade c on c.RamoDeAtividadeId = a.RamoDeAtividadeId
inner join Contratos d on d.ClienteId = a.ClienteId
inner join ClientesEnderecos f on f.ClienteId = a.ClienteId and f.TipoDeEnderecoId = (select min(TipoDeEnderecoId) from ClientesEnderecos where ClienteId = a.ClienteId)
where a.AtivoCliente = 1
and b.ContatoPrincipal = 1
and d.status = 1
and a.CGC_CPF = '$document'
and d.Numero in('$ctact')
group by a.ClienteId,
d.ContratoId,
d.Numero,
b.ContatoId,
a.CGC_CPF,
upper(dbo.sip_remove_acentos(a.RazaoSocial)),
upper(dbo.sip_remove_acentos(a.Fantasia)),
c.Descricao,
dbo.FormataData(d.DataAssinatura),
dbo.FormataData(d.DataInicio),
dbo.FormataData(d.DataFim),
f.Cidade,
f.Uf,
dbo.NumToText(isnull(d.ValorMensal,0)),
upper( dbo.sip_remove_acentos(b.PrimeiroNome)),
coalesce(b.Celular,
b.TelefoneComercial,
b.TelefoneResidencial, a.Telefone),
lower(dbo.sip_remove_acentos(coalesce(b.Email1, b.Email2, Email)));";
$resp = __execSQLServer($query);
return $resp;
}
########################################
#### CONEXÃO VENDA+ ####
########################################
/**
* Realiza conexao com o banco do venda+
* @return type
*/
function ConectaMssql() {
$dbhost = "vendas.simplesip.com.br";
$dbname = "VendaMaisDB_simplesip";
$user = "sa";
$passwd = "SimpleS_root";
$conn = mssql_connect($dbhost, $user, $passwd);
mssql_select_db($dbname);
return $conn;
}
function __execSQLServer($query, $return = true) {
$msql = ConectaMssql();
$result = mssql_query($query, $msql);
if ($return) {
$resp = [];
while ($data = mssql_fetch_array($result)) {
$resp[] = $data;
}
}
mssql_close($msql);
return $resp ? $resp : $result;
}