$value) { $key = str_replace($unfix, '', $key); if (in_array($key, $info)) { $data[$prefix . $key] = empty($value) ? '0' : $value; } } $data['clto_server_registro'] = 0; $data['clto_contrato_numero'] = 0; $data['clto_date_record'] = date('Y-m-d'); $fileName = $data['clto_razao_social'] . $data['clto_document']; $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 * @param type $dbcon * @param type $data * @return boolean * @throws Exception */ function __validLicenca($dbcon, $data) { if (!$data['clto_document']) { throw new Exception("As informações do arquivo está corrompido!"); } $respbx = __getLicencaPBX($dbcon); $table = 'pbx_controle_licenciamento'; $where = 'clto_cnpj'; $filter = $data['clto_document']; $columns = array( 'clto_cnpj', 'clto_razao_social', 'clto_perfil_aplicacao_id', 'clto_licenca_pa', 'clto_licenca_pa_fixo', 'clto_licenca_ramal', //'clto_licenca_supervisor', //'clto_licenca_pesquisa', //'clto_licenca_tarifador', //'clto_licenca_mesaoperadora', //'clto_licenca_manager_one', 'clto_server_registro', 'clto_contrato_numero', 'clto_data_registro', 'clto_data_log' ); try { if (!pg_query($dbcon, 'BEGIN')) { throw new Exception("Não foi possivel iniciar a transação!"); } recordParams($dbcon, $data); if ($respbx['clto_cnpj'] == $data['clto_document']) { __updateLicenca($dbcon, $data, $columns, $table, $where, $filter); } else { __sendLicenca($dbcon, $data, $columns, $table, $where, $filter); } if (!pg_query($dbcon, 'COMMIT')) { throw new Exception("Não foi possivel realizar o commit da transação!"); } return true; } catch (Exception $ex) { pg_query($dbcon, 'ROLLBACK'); $GLOBALS['jsStartup'][] = sprintf("alert('%s');", $ex->getMessage()); throw new Exception($ex->getMessage()); } } function __updateLicenca($dbcon, $data, $columns, $table, $where, $filter) { $values = array_combine($columns, $data); foreach ($values as $key => $value) { $values[$key] = " {$key} = '{$value}'"; } $query = sprintf("UPDATE %s SET %s WHERE %s = '%s'", $table, implode(',', $values), $where, $filter); $result = pg_query($dbcon, $query); if (!$result) { throw new Exception("Não foi possível atualizar as informações da licença!"); } } function __sendLicenca($dbcon, $data, $columns, $table, $where, $filter) { $values = array_values($data); $query = sprintf("INSERT INTO %s (%s) VALUES('%s');", $table, implode(',', $columns), implode("','", $values)); if (!pg_query($dbcon, $query)) { throw new Exception("Não foi possível inserir as informações da licença no [Simples IP]!"); } } function GetPerfilApl() { $query = "SELECT * FROM sip_perfil_aplicacao"; $resp = __execSQLServer($query); return $resp; } /* * REALIZA A INSERÇÃO DAS INFORMAÇÕES DA LICENÇA NA TABELA DE PARAMETROS DO SISTEMA */ function recordParams($dbcon, $data) { $columns = array( 'prm_max_licenca', 'prm_max_licenca_fixo', 'prm_max_ramal' ); $values = array( $data['clto_pa'], $data['clto_pa_fixo'], $data['clto_ramais'] ); $table = 'pbx_parametros'; $where = 'id'; $filter = '1'; managePaFixo($dbcon, $data); if (!VerificaRamaisCriados($data['clto_ramais'])) { throw new Exception("O número de ramais criados é superior ao parametro informado na licença!"); } __updateLicenca($dbcon, $values, $columns, $table, $where, $filter); $_SESSION['prm_max_licenca_fixo'] = $data['clto_pa_fixo']; } /* * RESPONSÁVEL POR GERENCIAR AS LICENÇAS PA FIXO */ function managePaFixo($dbcon, $data) { $query = "SELECT COUNT(*) AS qtd_pa_fixo FROM pbx_licenca_pa_fixo WHERE id_user IS NOT NULL"; $result = pg_query($dbcon, $query); $result = pg_fetch_assoc($result); if ($data['clto_pa_fixo'] < $result['qtd_pa_fixo']) { throw new Exception("O número de P.A. fixos criados é superior ao parametro informado na licença!"); } else { $query = "DELETE FROM pbx_licenca_pa_fixo WHERE id_user IS NULL"; if (!pg_query($dbcon, $query)) { throw new Exception('A operação não pode ser realizada!'); } $rows = $data['clto_pa_fixo'] - $result['qtd_pa_fixo']; for ($cont = 0; $cont < $rows; $cont++) { $query = sprintf("INSERT INTO pbx_licenca_pa_fixo (licenca) VALUES ('%s')", generateRandomKey()); if (!pg_query($dbcon, $query)) { throw new Exception('A operação não pode ser realizada!'); } } } } /* * GERADOR DE CHAVES ALEATÓRIAS UTILIZADOS PARA LICENÇA PA FIXO */ function generateRandomKey() { return bin2hex(random_bytes(10)); } ######################################## #### CONEXÃO VENDA+ #### ######################################## 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; } /** * 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; }