|
|
<?php |
|
|
|
|
|
/* |
|
|
* Diretorio de download da instalacao; |
|
|
*/ |
|
|
define("DIRETORIO_DOWNLOAD_CLIENTE", "/import/download/"); |
|
|
/* |
|
|
* Stus do cliente |
|
|
*/ |
|
|
define("CLIENTE_INEXISTENTE", "-1"); |
|
|
define("CLIENTE_HABILITADO", "2"); |
|
|
define("CLIENTE_INSTALADO", "1"); |
|
|
define("CLIENTE_CANCELADO", "9"); |
|
|
|
|
|
function GravaLogPorta($txt, $aux = '') { |
|
|
$txt = trim($txt); |
|
|
$txt .= trim($aux); |
|
|
$txt .= (stripos($txt, "Fim") !== false) ? "\n\n" : "\n"; |
|
|
$file = DIRETORIO_LOG; |
|
|
$handle = fopen($file, 'a'); |
|
|
fwrite($handle, $txt); |
|
|
fclose($handle); |
|
|
} |
|
|
|
|
|
function microtime_float() { |
|
|
list($usec, $sec) = explode(" ", microtime()); |
|
|
return ((float) $usec + (float) $sec); |
|
|
} |
|
|
|
|
|
function dbConnect($pg) { |
|
|
$conStr = sprintf("host='%s' port='%s' dbname='%s' user='%s' password='%s'", $pg["host"], $pg["port"], $pg["dbname"], $pg["user"], $pg["password"]); |
|
|
return @pg_connect($conStr); |
|
|
} |
|
|
|
|
|
function ImportaArquivo($conn, $file) { |
|
|
global $numRegImporta; |
|
|
define("NUM_REG_INSERT", 1000); |
|
|
$row = 0; |
|
|
$handle = fopen($file, "r"); |
|
|
$insert = ''; |
|
|
$numLinhas = 0; |
|
|
$numLote = 0; |
|
|
$idPorta = 0; |
|
|
$numRegImporta = 0; |
|
|
|
|
|
while (!feof($handle)) { |
|
|
$bufer = trim(fgets($handle)); |
|
|
$data = explode(",", $bufer); |
|
|
/* |
|
|
* Pula a primeira linha referente ao cabecalio |
|
|
*/ |
|
|
if ($row && $data) { |
|
|
// 0, 1, 2, 3, 4, 5, 6, 7, 8 |
|
|
// id, numero, rn1, spid, eot, data_janela, TipoNLP, motivo, tipolinha |
|
|
// 696, 3000010300, 55115, 0115, 011, "2012-11-26 22:02:08", 0, 0, 1 |
|
|
$idPorta = $data[0]; |
|
|
$tel_doadora = soNumero($data[1]); |
|
|
$tel_receptora = soNumero($data[2]); |
|
|
$spid = soNumero($data[3]); |
|
|
$eot = soNumero($data[4]); |
|
|
$dataPorta = str_replace('"', "", $data[5]); |
|
|
$tipo_nlp = 0; |
|
|
$motivo = 0; |
|
|
$tipo_linha = '1'; |
|
|
$movel = substr($spid, 1, 1) == '3'; |
|
|
|
|
|
if ($movel) { |
|
|
$numLinhas++; |
|
|
|
|
|
$insert .= sprintf("insert into portabilidade values('%s','%s','%s','%s','%s','%s','%s','%s','%s');\n", $idPorta, $tel_doadora, $tel_receptora, $spid, $eot, $dataPorta, $tipo_nlp, $motivo, $tipo_linha); |
|
|
|
|
|
/* |
|
|
* Executa os registros em lotes no banco de dados obedecendo o valor da constante NUM_REG_INSERT; |
|
|
*/ |
|
|
if ($numLinhas > NUM_REG_INSERT) { |
|
|
$result = pg_query($conn, $insert); |
|
|
$numLinhas = 0; |
|
|
if (!$result) { |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel importar portabilidade!\nLinha:[$row]\nCmd:[$insert]")); |
|
|
} |
|
|
$insert = ''; |
|
|
} |
|
|
$numRegImporta++; |
|
|
} |
|
|
} |
|
|
$numLote++; |
|
|
$row++; |
|
|
} |
|
|
|
|
|
if (($numLinhas > 0) && $result) { |
|
|
$result = pg_query($conn, $insert); |
|
|
if (!$result) { |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel importar portabilidade!\nLinha:[$row]\nCmd:[$insert]")); |
|
|
} |
|
|
$insert = ''; |
|
|
$numLinhas = 0; |
|
|
} |
|
|
fclose($handle); |
|
|
} |
|
|
|
|
|
function LoadDbFile($pg, $file) { |
|
|
$inTran = 0; |
|
|
$conn = dbConnect($pg); |
|
|
try { |
|
|
$result = pg_query($conn, 'begin'); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel iniciar uma transacao!")); |
|
|
$inTran++; |
|
|
|
|
|
/* |
|
|
* Deleta a tabela de dados antigos. |
|
|
*/ |
|
|
$query = "truncate table portabilidade_old;"; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel apagar a tabela portabilidade_old!")); |
|
|
|
|
|
$query = 'DROP INDEX "idxtelDoadoraOld"'; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel apagar idxtelDoadoraOld!")); |
|
|
|
|
|
/* |
|
|
* Copia a tabela de portabilidade para portabilidade_old. |
|
|
*/ |
|
|
$query = "insert into portabilidade_old select * from portabilidade;"; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel copiar a tabela portabilidade para portabilidade_old!")); |
|
|
|
|
|
/* |
|
|
* Deleta a tabela de dados atuais. |
|
|
*/ |
|
|
$query = "truncate table portabilidade;"; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel apagar a tabela portabilidade!")); |
|
|
|
|
|
$query = 'DROP INDEX "idxtelDoadora"'; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel apagar idxtelDoadora!")); |
|
|
|
|
|
/* |
|
|
* Importa o arquivo direto para a tabela portabilidade. |
|
|
* |
|
|
* $query = "COPY portabilidade FROM '$file' WITH DELIMITER AS ',' QUOTE '\"' CSV HEADER\n"; |
|
|
* $result = pg_query($conn, $query); |
|
|
* if(!$result) throw new Exception (GetExcept("N<EFBFBD>o foi possivel importar tabela portabilidade!")); |
|
|
*/ |
|
|
ImportaArquivo($conn, $file); |
|
|
|
|
|
$query = 'CREATE INDEX "idxtelDoadora" ON portabilidade USING btree (tel_doadora);'; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel criar indice idxtelDoadora!")); |
|
|
|
|
|
$query = 'CREATE INDEX "idxtelDoadoraOld" ON portabilidade_old USING btree (tel_doadora);'; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel criar indice idxtelDoadoraOld!")); |
|
|
|
|
|
RegistraImportacao($conn, 0); |
|
|
|
|
|
$result = pg_query($conn, 'commit'); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel finalizar a transacao!")); |
|
|
|
|
|
$msg = "Arquivo: $file importado para o banco de dados com sucesso!\n"; |
|
|
@GravaLogPorta($msg); |
|
|
return true; |
|
|
} catch (Exception $ex) { |
|
|
pg_query($conn, 'rollback'); |
|
|
$msg = "LoadDbFile\n" . $ex->getMessage(); |
|
|
RegistraImportacao($conn, 1, $msg); |
|
|
throw new Exception($msg); |
|
|
unlink(DIRETORIO_LOCAL . ARQUIVO_COMPACTADO); |
|
|
} |
|
|
@pg_close($conn); |
|
|
} |
|
|
|
|
|
function IniciaAtualizacao($pg) { |
|
|
$conn = dbConnect($pg); |
|
|
/* |
|
|
* Verifica se n<EFBFBD>o uma atuliza<EFBFBD><EFBFBD>o em andamento. |
|
|
*/ |
|
|
if (PortabAtualizando($conn)) { |
|
|
throw new Exception(GetExcept("IniciaAtualizacao: J<EFBFBD> existe uma atualiza<EFBFBD><EFBFBD>o em andamento!")); |
|
|
} |
|
|
|
|
|
/* |
|
|
* Registra uma nova atualizacao. |
|
|
*/ |
|
|
$query = "insert into atualizacoes_registro(atr_data, atr_inicio)values(now()::date, now())"; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("IniciaAtualizacao: N<EFBFBD>o foi possivel iniciar a atualizacao!")); |
|
|
|
|
|
/* |
|
|
* Verifica se a atuliza<EFBFBD><EFBFBD>es de clientes em andamento, se houver, aguarda at<EFBFBD> que finalizem; |
|
|
*/ |
|
|
$numTentativas = 0; |
|
|
while (true) { |
|
|
/* |
|
|
* Encerrado o tempo maximo que o servidor pode aguardar at<EFBFBD> que atulizacoes de clientes encerrem, |
|
|
* o sistema gera uma excecao |
|
|
*/ |
|
|
if ($numTentativas++ >= MAX_TENTIVA_INICIA_ATUALIZACAO) { |
|
|
throw new Exception(GetExcept("IniciaAtualizacao: Timeout excedido para clientes encerrarem suas atualiza<EFBFBD><EFBFBD>es!")); |
|
|
} |
|
|
|
|
|
/* |
|
|
* Query seleciona os registro de conexoes nao encerrados. |
|
|
*/ |
|
|
$query = "select '' as reg from controle_conexao where ctrc_data = now()::date and ctrc_fim is null"; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("IniciaAtualizacao: N<EFBFBD>o foi possivel verificar o encerramento de conexoes clientes!")); |
|
|
|
|
|
/* |
|
|
* Quando nao houver mais conexoes abertas libera a aplicacao. |
|
|
*/ |
|
|
if (!pg_num_rows($result)) { |
|
|
break; |
|
|
} |
|
|
|
|
|
/* |
|
|
* Dorme por um minutjo por cliclo. |
|
|
*/ |
|
|
sleep(60); |
|
|
} |
|
|
} |
|
|
|
|
|
function FinalizaAtualizacao($erro = '') { |
|
|
$numTentativas = 0; |
|
|
|
|
|
while (true) { |
|
|
/* |
|
|
* Encerrado o tempo maximo que o servidor pode aguardar at<EFBFBD> que atulizacoes de clientes encerrem, |
|
|
* o sistema gera uma excecao |
|
|
*/ |
|
|
if ($numTentativas++ >= MAX_TENTIVA_FINALIZA_ATUALIZACAO) { |
|
|
/* |
|
|
* Quando um erro e passad, e porque ja foi apanhado pelo chtch final. |
|
|
* |
|
|
*/ |
|
|
if ($erro) |
|
|
break; |
|
|
|
|
|
/* |
|
|
* Gera uma exceca que sera apanhada pelo catch final do programa. |
|
|
*/ |
|
|
throw new Exception(GetExcept("FinalizaAtualizacao: N<EFBFBD>o foi poss<EFBFBD>vel encerrar adequadamente a atualizacao!")); |
|
|
} |
|
|
$erro = trim($erro); |
|
|
$erro = $erro ? sprintf("'%s'", addslashes($erro)) : 'null'; |
|
|
$query = "update atualizacoes_registro set atr_fim = now(), atr_msg = $erro where atr_data = now()::date and atr_fim is null"; |
|
|
$result = pg_query($query); |
|
|
if ($result && pg_affected_rows($result)) { |
|
|
break; |
|
|
} |
|
|
|
|
|
sleep(60); |
|
|
} |
|
|
} |
|
|
|
|
|
function RegistraImportacao($conn, $erro = 1, $msg = '') { |
|
|
global $numRegImporta; |
|
|
$data = date("Y-m-d-his"); |
|
|
$file = DIRETORIO_LOCAL . ARQUIVO_CSV; |
|
|
$totalReg = $numRegImporta; //FileNumberLines($file); |
|
|
$dirDest = $erro ? DIRETORIO_ERRO_IMPORTACAO : DIRETORIO_IMPORTADO; |
|
|
$mvFile = sprintf('%sexporta_%s.csv', $dirDest, $data); |
|
|
$fileExporta = $mvFile; |
|
|
$result = @mv($file, $mvFile); |
|
|
if (!$result && !$erro) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel mover arquivo $file -> $mvFile!")); |
|
|
|
|
|
$file = DIRETORIO_LOCAL . ARQUIVO_COMPACTADO; |
|
|
$mvFile = sprintf('%sportabilidade_%s.tar.bz2', $dirDest, $data); |
|
|
$result = @mv($file, $mvFile); |
|
|
if (!$result && !$erro) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel mover arquivo $file -> $mvFile!")); |
|
|
|
|
|
$query = "insert into atualizacoes(nomearquivo, data, totalregistros, msg, erro)values('%s', now(), '%s', '%s', '%s');"; |
|
|
$query = sprintf($query, addslashes($fileExporta), $totalReg, addslashes($msg), $erro); |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result && !$erro) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel registrar a transacao no banco de dados!")); |
|
|
} |
|
|
|
|
|
function AtualizaCli($pg) { |
|
|
$inTran = 0; |
|
|
$conn = dbConnect($pg); |
|
|
|
|
|
try { |
|
|
$result = pg_query($conn, 'begin'); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel iniciar uma transacao!")); |
|
|
$inTran++; |
|
|
|
|
|
/* |
|
|
* Peqa id da ultima atualizacao obtida. |
|
|
*/ |
|
|
$query = "select max(idarquivo) from atualizacoes;"; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel pegar o id da atualizacao!")); |
|
|
$row = pg_fetch_row($result); |
|
|
$idArquivo = $row[0]; |
|
|
|
|
|
/* |
|
|
* Remove numeros de telefones fixos. |
|
|
|
|
|
$query = "delete from portabilidade where substring(spid::text,1,1) in('1', '2');"; |
|
|
$result = pg_query($conn, $query); |
|
|
if(!$result) throw new Exception (GetExcept("N<EFBFBD>o foi possivel deletar registros da telefonia fixa!")); |
|
|
*/ |
|
|
/* |
|
|
* Deleta registros duplicados |
|
|
*/ |
|
|
$query = " delete from portabilidade where id_reg in( select min(id_reg) from portabilidade group by tel_doadora having count(*) > 1 );"; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel deletar registros duplicados em portabilidade!")); |
|
|
|
|
|
/* |
|
|
* Insere comandos para atualiza<EFBFBD><EFBFBD>o do cliente. |
|
|
*/ |
|
|
|
|
|
/* |
|
|
* Registros inseridos, ou seja, registros que n<EFBFBD>o constavam da <EFBFBD>ltima atualiza<EFBFBD><EFBFBD>o. |
|
|
*/ |
|
|
$query = "insert into atualizacoes_itens(idarquivo, comando) |
|
|
select $idArquivo as id, 'insert into portabilidade values(' || tel_doadora::text || ',' || spid::text || ');' as cmd |
|
|
from portabilidade a |
|
|
where not exists(select '' from portabilidade_old where tel_doadora = a.tel_doadora)"; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel inserir comandos de insert em atualizacoes_itens!")); |
|
|
|
|
|
/* |
|
|
* Registro que foram removidos da portabilidade. |
|
|
*/ |
|
|
$query = "insert into atualizacoes_itens(idarquivo, comando) |
|
|
select $idArquivo as id, 'delete from portabilidade where tel_doadora = ' || tel_doadora::text || ';' as cmd |
|
|
from portabilidade_old a |
|
|
where not exists(select '' from portabilidade where tel_doadora = a.tel_doadora)"; |
|
|
|
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel inserir comandos de delete em atualizacoes_itens!")); |
|
|
|
|
|
/* |
|
|
* Registros que foram alterados desde a <EFBFBD>ltima atualiza<EFBFBD><EFBFBD>o. |
|
|
*/ |
|
|
$query = "insert into atualizacoes_itens(idarquivo, comando) |
|
|
select $idArquivo as id, 'update portabilidade set spid = ' || a.spid || ' where tel_doadora = ' || a.tel_doadora || ';' as cmd |
|
|
from portabilidade a, portabilidade_old b |
|
|
where (a.tel_doadora = b.tel_doadora and a.spid <> b.spid)"; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel inserir comandos de update em atualizacoes_itens!")); |
|
|
|
|
|
$result = pg_query($conn, 'commit'); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel finalizar a transacao!")); |
|
|
|
|
|
$msg = "Atualizacao: $idArquivo gerada com sucesso!\n"; |
|
|
@GravaLogPorta($msg); |
|
|
|
|
|
@LimpaAquivos(DIRETORIO_IMPORTADO); |
|
|
|
|
|
@GeraArquivoPortabilidade($conn); |
|
|
|
|
|
return true; |
|
|
} catch (Exception $ex) { |
|
|
pg_query($conn, 'rollback'); |
|
|
$msg = "AtualizaCli" . $ex->getMessage(); |
|
|
throw new Exception($msg); |
|
|
return false; |
|
|
} |
|
|
@pg_close($conn); |
|
|
} |
|
|
|
|
|
function LoadDbFile2($pg, $file) { |
|
|
$inTran = 0; |
|
|
$conn = dbConnect($pg); |
|
|
|
|
|
//$result = pg_query($conn, 'begin'); |
|
|
try { |
|
|
$file = DIRETORIO_LOCAL . $file; |
|
|
/* |
|
|
* Importa o arquivo direto para a tabela portabilidade. |
|
|
*/ |
|
|
if (!file_exists($file)) |
|
|
throw new Exception(GetExcept("Arquivo nao encontrado: !$file")); |
|
|
echo sprintf("Importando: %s Tempo: %s \n", $filename, date('d/m/Y h:i:s')); |
|
|
|
|
|
$query = "create temporary table portabilidade_temp( id_reg integer, tel_doadora bigint not null primary key, tel_receptora character varying(25), spid int, eot character varying(25), hora_tivacao timestamp, tipo_nlp smallint, motivo smallint, tipo_linha character varying(2));"; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("Erro ao criar tabela portabilidade_temp!\nCmd: $query")); |
|
|
echo "tabela portabilidade_temp criada\n"; |
|
|
|
|
|
$query = "COPY portabilidade_temp FROM '$file' WITH DELIMITER AS ',' QUOTE '\"' CSV HEADER"; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel importar tabela portabilidade_temp!\nCmd: $query")); |
|
|
echo "tabela registros copiados para portabilidade_temp\n"; |
|
|
|
|
|
$query = "insert into portabilidade select tel_doadora::bigint, spid::int from portabilidade_temp"; |
|
|
$result = pg_query($conn, $query); |
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o foi possivel inserir dados tabela portabilidade!\nCmd: $query")); |
|
|
echo "tabela registros inseridos para portabilidade\n"; |
|
|
|
|
|
|
|
|
$query = "drop table portabilidade_temp;"; |
|
|
$result = pg_query($conn, $query); |
|
|
|
|
|
|
|
|
if (!$result) |
|
|
throw new Exception(GetExcept("N<EFBFBD>o apagar tabela portabilidade_temp!\nCmd: $query")); |
|
|
echo sprintf("Fim.......: %s Tempo: %s \n\n", $file, date('d/m/Y h:i:s')); |
|
|
|
|
|
|
|
|
mv($file, DIRETORIO_IMPORTADO . ARQUIVO_CSV); |
|
|
|
|
|
$msg = "Arquivo: $file importado para o banco de dados com sucesso!\n"; |
|
|
@GravaLogPorta($msg); |
|
|
return true; |
|
|
} catch (Exception $ex) { |
|
|
pg_query($conn, 'rollback'); |
|
|
mv($file, DIRETORIO_ERRO_IMPORTACAO . ARQUIVO_CSV); |
|
|
throw new Exception("LoadDbFile2\n" . $ex->getMessage()); |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
function Compress($origem, $destino, $type = "gz") { |
|
|
switch ($type) { |
|
|
case "gz" : $cmd = "czvf"; |
|
|
break; |
|
|
case "bz2": $cmd = "cjvf"; |
|
|
break; |
|
|
default: $cmd = "czvf"; |
|
|
break; |
|
|
} |
|
|
$result = true; |
|
|
$cmd = sprintf(" tar %s %s %s 2>/dev/null", $cmd, $destino, $origem); |
|
|
system($cmd, $result); |
|
|
|
|
|
/* |
|
|
* Certifica que o arquivo foi criado com sucesso. |
|
|
*/ |
|
|
if (!file_exists($destino)) { |
|
|
$msg = "Erro ao compactar o arquivo!\n"; |
|
|
throw new Exception(GetExcept($msg)); |
|
|
} |
|
|
|
|
|
/* |
|
|
$origem = DIRETORIO_LOCAL . ARQUIVO_CSV; |
|
|
$cmd = sprintf("chmod 777 %s", $origem); |
|
|
@system($cmd); |
|
|
|
|
|
$cmd = sprintf("chown postgres %s", $origem); |
|
|
@system($cmd); |
|
|
* |
|
|
*/ |
|
|
|
|
|
return true; |
|
|
} |
|
|
|
|
|
function Ucompress($origem, $destino, $type = "gz") { |
|
|
switch ($type) { |
|
|
case "gz" : $cmd = "xzvf"; |
|
|
break; |
|
|
case "bz2": $cmd = "xjvf"; |
|
|
break; |
|
|
default: $cmd = "xzvf"; |
|
|
break; |
|
|
} |
|
|
$result = true; |
|
|
$cmd = sprintf("tar -%s %s -C %s 2>/dev/null", $cmd, $origem, $destino); |
|
|
|
|
|
system($cmd, $result); |
|
|
|
|
|
/* |
|
|
* Certifica que o arquivo foi criado com sucesso. |
|
|
*/ |
|
|
if (!file_exists(DIRETORIO_LOCAL . ARQUIVO_CSV)) { |
|
|
$msg = "Erro ao descompactar o arquivo!\nOrigem: $origem\nDestino: $destino\nCmd: $cmd"; |
|
|
throw new Exception(GetExcept($msg)); |
|
|
} |
|
|
|
|
|
$origem = DIRETORIO_LOCAL . ARQUIVO_CSV; |
|
|
$cmd = sprintf("chmod 777 %s", $origem); |
|
|
@system($cmd); |
|
|
|
|
|
$cmd = sprintf("chown postgres %s", $origem); |
|
|
@system($cmd); |
|
|
|
|
|
return true; |
|
|
} |
|
|
|
|
|
function ReduzFile($file) { |
|
|
$start = 0; |
|
|
$fileTemp = DIRETORIO_LOCAL . "expo_temp"; |
|
|
$handleTemp = fopen($fileTemp, "w"); |
|
|
$handle = fopen($file, "r"); |
|
|
while (!feof($handle)) { |
|
|
$bufer = trim(fgets($handle)); |
|
|
if ($start) { |
|
|
$data = explode(",", $bufer); |
|
|
$line = sprintf("%s,%s\n", $data[1], $data[3]); |
|
|
fwrite($handleTemp, $line); |
|
|
} |
|
|
$start = 1; |
|
|
} |
|
|
fclose($handleTemp); |
|
|
fclose($handle); |
|
|
|
|
|
if (!function_exists($fileTemp)) |
|
|
return false; |
|
|
return DeleteFile($file) and mv($fileTemp, $file); |
|
|
} |
|
|
|
|
|
function PartFile($fileName, $lines = 1000000, $prefix = 'exp') { |
|
|
ReduzFile($fileName); |
|
|
$files = array(); |
|
|
$numberLines = FileNumberLines($fileName); |
|
|
if ($numberLines <= $lines) { |
|
|
return ($files[] = $fileName); |
|
|
} |
|
|
$numberFiles = intval($numberLines / $lines) + (intval($numberLines % $lines) ? 1 : 0); |
|
|
|
|
|
for ($i = 0; $i < $numberFiles; $i++) { |
|
|
$files[] = sprintf("%s%s", $prefix, str_pad($i, 2, '0', STR_PAD_LEFT)); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
$dir = DIRETORIO_LOCAL; |
|
|
$cmd = "split -l $lines -d $fileName $dir$prefix"; |
|
|
@system($cmd); |
|
|
return $files; |
|
|
} |
|
|
|
|
|
function mv($oldname, $newname) { |
|
|
return rename($oldname, $newname); |
|
|
} |
|
|
|
|
|
function cp($source, $dest) { |
|
|
return copy($source, $dest); |
|
|
} |
|
|
|
|
|
function DeleteFile($filename) { |
|
|
return unlink($filename); |
|
|
} |
|
|
|
|
|
function LimpaAquivos($dir) { |
|
|
$arquivosTar = array(); |
|
|
$arquivosCsv = array(); |
|
|
$dh = opendir($dir); |
|
|
while (($arquivo = readdir($dh)) != false) { |
|
|
if (!is_dir($dir . $arquivo)) { |
|
|
$mod = filemtime($dir . $arquivo); |
|
|
if (stripos($arquivo, '.tar') !== false) |
|
|
$arquivosTar[$mod] = $dir . $arquivo; |
|
|
else if (stripos($arquivo, '.csv') !== false) |
|
|
$arquivosCsv[$mod] = $dir . $arquivo; |
|
|
} |
|
|
} |
|
|
|
|
|
ApagaArquivos(3, $arquivosTar); |
|
|
ApagaArquivos(3, $arquivosCsv); |
|
|
} |
|
|
|
|
|
function ApagaArquivos($maxPer, $arquivos) { |
|
|
/* |
|
|
* Apaga arquivos contidos no array. |
|
|
* $maxPer -> Numero m<EFBFBD>ximo de arquivos que dever permanecer no diretorio. |
|
|
* Os arquivos s<EFBFBD>o ordenados pela chave que <EFBFBD> a data do arquivo, a fun<EFBFBD>ao |
|
|
* vai apagar os aquivos passados at<EFBFBD> que restem apenas o m<EFBFBD>ximo permitido. |
|
|
* $arquivos -> Lista de aquivos a serem apagados |
|
|
*/ |
|
|
/* |
|
|
* Ordena os aquivos pela chave, que representa a data do aquivo. |
|
|
*/ |
|
|
ksort($arquivos); |
|
|
|
|
|
$quantMaxima = $maxPer; |
|
|
$quantArq = count($arquivos); |
|
|
|
|
|
if ($quantArq > $quantMaxima) { |
|
|
$quantApagar = $quantArq - $quantMaxima; |
|
|
$numDel = 0; |
|
|
foreach ($arquivos as $value) { |
|
|
unlink($value); |
|
|
if (++$numDel == $quantApagar) |
|
|
break; |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
function CountDB($db, $query) { |
|
|
$result = pg_query($db, $query); |
|
|
if (!$result) |
|
|
return false; |
|
|
|
|
|
$row = pg_fetch_row($result); |
|
|
|
|
|
return $row[0]; |
|
|
} |
|
|
|
|
|
function GeraArquivoPortabilidade($db) { |
|
|
$arquivoOper = ''; |
|
|
$arquivoPrefixo = ''; |
|
|
$arquivoPorta = ''; |
|
|
|
|
|
/* |
|
|
* Gera o arquivo de portabilidade. |
|
|
*/ |
|
|
$arquivoPorta = "portabilidade.csv"; |
|
|
$fullPath = DIRETORIO_AQRUIVOS_CLIENTE . $arquivoPorta; |
|
|
$query = sprintf("COPY portabilidade(tel_doadora, spid) TO '%s' WITH DELIMITER AS ',';", $fullPath); |
|
|
$result = pg_query($db, $query); |
|
|
|
|
|
|
|
|
/* |
|
|
* Geera tabela de prefixos |
|
|
*/ |
|
|
if (CountDB($db, "select count(*) from prefixos")) { |
|
|
$arquivoPrefixo = "prefixos.csv"; |
|
|
$fullPath = DIRETORIO_AQRUIVOS_CLIENTE . $arquivoPrefixo; |
|
|
$query = sprintf("COPY prefixos(spid, prefixo, ini, fim) TO '%s' WITH DELIMITER AS ',';", $fullPath); |
|
|
$result = pg_query($db, $query); |
|
|
} |
|
|
|
|
|
/* |
|
|
* Gera tabela de operadoras |
|
|
*/ |
|
|
if (CountDB($db, "select count(*) from routing")) { |
|
|
$arquivoOper = "operadoras.csv"; |
|
|
$fullPath = DIRETORIO_AQRUIVOS_CLIENTE . $arquivoOper; |
|
|
$query = sprintf("COPY routing(oper_id, oper_nome, oper_spid, oper_licensa, oper_numero, oper_numero_saida, oper_dono) TO '%s' WITH DELIMITER AS ',';", $fullPath); |
|
|
$result = pg_query($db, $query); |
|
|
} |
|
|
|
|
|
/* |
|
|
* Gera tabela de operadoras |
|
|
*/ |
|
|
if (CountDB($db, "select count(*) from pbx_municipios")) { |
|
|
$arquivoMun = "municipios.csv"; |
|
|
$fullPath = DIRETORIO_AQRUIVOS_CLIENTE . $arquivoMun; |
|
|
$query = sprintf("COPY pbx_municipios(id,uf,sigla_area,codigo_localidade,nome_localidade,nome_municipio,areatarifacao,prefixo,nome_operadora,faixa_inicial,faixa_final,latitude,hemisferio,longitude,sigla_area_local,codigo_ddd) TO '%s' WITH DELIMITER AS ',';", $fullPath); |
|
|
$result = pg_query($db, $query); |
|
|
} |
|
|
|
|
|
|
|
|
$dirOrig = DIRETORIO_AQRUIVOS_CLIENTE; |
|
|
$origem = " -C $dirOrig $arquivoPorta $arquivoPrefixo $arquivoOper $arquivoMun "; |
|
|
$destino = DIRETORIO_AQRUIVOS_CLIENTE . "portabilidade.tar.gz"; |
|
|
Compress($origem, $destino); |
|
|
|
|
|
DeleteFile(DIRETORIO_AQRUIVOS_CLIENTE . $arquivoPorta); |
|
|
if ($arquivoPrefixo) |
|
|
DeleteFile(DIRETORIO_AQRUIVOS_CLIENTE . $arquivoPrefixo); |
|
|
if ($arquivoOper) |
|
|
DeleteFile(DIRETORIO_AQRUIVOS_CLIENTE . $arquivoOper); |
|
|
if ($arquivoOper) |
|
|
DeleteFile(DIRETORIO_AQRUIVOS_CLIENTE . $arquivoMun); |
|
|
|
|
|
//echo "A base da portabilidade foi gerada com sucesso!\n"; |
|
|
return true; |
|
|
} |
|
|
|
|
|
function Manutencao() { |
|
|
global $debug; |
|
|
$hora = (int) date('H'); |
|
|
$diaSemana = (int) date('w'); |
|
|
if (($hora > 18) || ($hora < 6)) { |
|
|
if ($debug) |
|
|
echo "Executando a manuten<EFBFBD><EFBFBD>o na base de dados!\n"; |
|
|
$tipo = ($diaSemana == 3) || ($diaSemana == 6) ? "-f -z" : "-z"; |
|
|
if ($debug) |
|
|
$tipo .= " -v"; |
|
|
$cmd = sprintf("vacuumdb portabilidade %s\n", $tipo); |
|
|
if ($debug) |
|
|
echo "$cmd\n"; |
|
|
@system($cmd); |
|
|
} |
|
|
} |
|
|
|
|
|
function VerificaDirDownload($dir) { |
|
|
if (!file_exists($dir)) { |
|
|
system("mkdir -p $dir"); |
|
|
system("chmod 777 -R $dir"); |
|
|
} |
|
|
|
|
|
return file_exists($dir); |
|
|
} |
|
|
|
|
|
function LimpaPortabilidade() { |
|
|
|
|
|
if (file_exists(DIRETORIO_LOCAL . ARQUIVO_COMPACTADO)) { |
|
|
system(sprintf("rm -rf %s", DIRETORIO_LOCAL . ARQUIVO_COMPACTADO)); |
|
|
} |
|
|
|
|
|
if (file_exists(DIRETORIO_LOCAL . ARQUIVO_CSV)) { |
|
|
system(sprintf("rm -rf %s", DIRETORIO_LOCAL . ARQUIVO_CSV)); |
|
|
} |
|
|
} |
|
|
|
|
|
?>
|
|
|
|