forked from SimplesIP/pabx-app
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
400 lines
12 KiB
400 lines
12 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'); |
|
|
|
/* |
|
* RECEBE OS DADOS DO FORMULÁRIO E GERA O TOTAL DE LICENCA EM UM ARQUIVO CRIPTOGRAFADO |
|
* @param type $fields |
|
*/ |
|
|
|
function GerarArquivo($fields) { |
|
|
|
$info = [ |
|
'document', |
|
'razao_social', |
|
'perfil', |
|
'pa', |
|
'pa_fixo', |
|
'ramais', |
|
'supervisor', |
|
'pesquisa', |
|
'tarifador', |
|
'mesaoperadora', |
|
'manager_one' |
|
]; |
|
|
|
//LIMPA O ARRAY, SETA O PREFIXO NAS CHAVES E INSERE VALOR ZERO PARA OS VAZIOS |
|
$unfix = 'lca_'; |
|
$prefix = "clto_"; |
|
foreach ($fields as $key => $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 = "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; |
|
} |
|
|
|
/** |
|
* 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_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 pbx_grupo WHERE gp_system = 1 AND gp_id <> 43"; |
|
$resp = pg_query($query); |
|
$resp = pg_fetch_all($resp); |
|
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)); |
|
} |
|
|
|
/** |
|
* VERIFICA SE EXISTE LICENÇA CADASTRADA NO BANCO DE DADOS E RETORNA AS PERMISSÕES. |
|
*/ |
|
function existLicense($conn){ |
|
//verifica o grupo de permissoes de acordo com o tipo da licença |
|
$query = "SELECT a.fun_id |
|
FROM pbx_grupo_funcoes a |
|
INNER JOIN pbx_grupo b ON a.gp_id = b.gp_id |
|
WHERE a.gp_id IN (SELECT clto_perfil_aplicacao_id |
|
FROM pbx_controle_licenciamento |
|
) |
|
GROUP BY a.fun_id |
|
ORDER BY a.fun_id"; |
|
$result = pg_query($conn, $query); |
|
|
|
if (!pg_num_rows($result) || !validarLicenca($conn)){ |
|
$permissions = array('1', '4'); |
|
} else { |
|
while ($row = pg_fetch_assoc($result)) { |
|
$permissions[] = $row['fun_id']; |
|
} |
|
} |
|
return $permissions; |
|
} |