PABX da Simples IP
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.
 
 
 
 
 
 

371 lines
12 KiB

#!/usr/bin/php -q
<?php
error_reporting(E_ERROR);
ini_set('display_errors', "Off");
define("DIRETORIO_DOWNLOAD_CLIENTE", "/import/download/");
include 'configCliente.php';
//include 'funcoes.php';
//include('util/util.php');
//include 'funcoes/shared.php';
$query = '';
$cliId = 0;
$inTran = 0;
$idAtualiza = 0;
try {
/*
* Verifica se existe o diretorio para download, se não existir tenta cria-lo!
*/
if (!VerificaDirDownload(DIRETORIO_DOWNLOAD_CLIENTE)) {
throw new Exception(GetExcept("Não foi possivel acessar o diretório de download!\n"));
}
/*
* Verificando informacoes do cliente na portabilidade, e obtendo informacoes
* sobre a atualizacao.
*/
IniciaInstalacao();
$filePorta = DIRETORIO_DOWNLOAD_CLIENTE . "/portabilidade.tar.gz";
if (!file_exists($filePorta)) {
echo "Baixando o arquivo!\n";
$url = "http://$serverApi/integracao/index.php?method=GetArquivoPortabilidade&cliid=$cliIdExterno&login=$loginApi&senha=$senhaApi&SIPID=0&tipoRetorno=XML";
if (!downloadFile($url, $filePorta))
throw new Exception(GetExcept("Não foi possível copiar o arquivo remoto!"));
}
echo "Descompactando o arquivo!\n";
$destino = DIRETORIO_DOWNLOAD_CLIENTE;
if (!Desconpacta($filePorta, $destino)) {
unlink($filePorta);
throw new Exception(GetExcept("Não foi possível descompactar o arquivo remoto!"));
}
CarregaArquivos($pg_local);
FinalizaInstalacao();
} catch (Exception $ex) {
echo $ex->getMessage();
}
function Desconpacta($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);
$arquivoPorta = "portabilidade.csv";
return file_exists($destino . $arquivoPorta);
}
function CarregaArquivos($pgLocal) {
$db = dbConnect($pgLocal);
@pg_query($db, 'begin');
/*
* Deleta a tabela de dados atuais.
*/
echo "Apagando a tabela de portabilidade!\n";
$query = "truncate table portabilidade;";
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel apagar a tabela portabilidade!"));
$query = 'DROP INDEX "idxPortabilidadeTel"';
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel apagar idxtelDoadora!"));
/*
* Importando a tabela portabilidade.
*/
echo "Importando a tabela de portabilidade!\n";
$file = DIRETORIO_DOWNLOAD_CLIENTE . "portabilidade.csv";
system("chown postgres:postgres $file");
$query = "COPY portabilidade FROM '$file' WITH DELIMITER AS ',' QUOTE '\"' CSV\n";
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel importar tabela portabilidade!"));
$query = 'CREATE INDEX "idxPortabilidadeTel" ON portabilidade USING btree (tel_doadora);';
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel criar indice idxtelDoadora!"));
/*
* Importando a tabela prefixos.
*/
$file = DIRETORIO_DOWNLOAD_CLIENTE . "prefixos.csv";
if (file_exists($file)) {
echo "Apagando a tabela de prefixos!\n";
$query = "truncate table prefixos;";
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel apagar a tabela prefixos!"));
echo "Importando a tabela de prefixos!\n";
$query = "COPY prefixos FROM '$file' WITH DELIMITER AS ',' QUOTE '\"' CSV\n";
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel importar tabela prefixos!"));
}
/*
* Importando a tabela municipio ; "operadoras.csv"; .
*/
$file = DIRETORIO_DOWNLOAD_CLIENTE . "municipios.csv";
if (file_exists($file)) {
echo "Apagando a tabela de municipios!\n";
$query = "truncate table pbx_municipios;";
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel apagar a tabela municipios!"));
echo "Importando a tabela de municipios!\n";
$query = "COPY pbx_municipios FROM '$file' WITH DELIMITER AS ',' QUOTE '\"' CSV\n";
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel importar tabela municipios!"));
echo "Apagando a tabela de pbx_consulta_ddd!\n";
$query = "truncate table pbx_consulta_ddd;";
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel apagar a tabela pbx_consulta_ddd!"));
echo "Importando a tabela de pbx_consulta_ddd!\n";
$query = "insert
into pbx_consulta_ddd
(id, codigo_ddd, nome_municipio, uf, prefixo, inicial, final)
select id, codigo_ddd, nome_municipio, uf, prefixo, faixa_inicial, faixa_final
from pbx_municipios;";
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel atualizar a tabela pbx_consulta_ddd!"));
}
/*
* Importando a tabela operadoras.
*/
$file = DIRETORIO_DOWNLOAD_CLIENTE . "operadoras.csv";
if (file_exists($file)) {
echo "Carregando registros de operadoras existentes!\n";
$query = "drop table if exists operadoras";
$result = @pg_query($db, $query);
/*
* Salvando as operadoras atuais.
*/
$query = "select * into operadoras from pbx_operadoras where 1=2";
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel importar tabela operadoras atual!"));
echo "Importando a tabela de operadoras!\n";
$query = "COPY operadoras FROM '$file' WITH DELIMITER AS ',' QUOTE '\"' CSV\n";
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel importar tabela operadoras!"));
/*
* Recuperando as modificacoes locais.
*/
//$query = "update pbx_operadoras set oper_numero_saida = operadoras.oper_numero_saida from operadoras where operadoras.oper_id = pbx_operadoras.oper_id and operadoras.oper_dono = 'R'";
//$query = "insert into pbx_operadoras select * from operadoras where oper_spid not in(select oper_spid from pbx_operadoras)";
$query = "insert
into pbx_operadoras(
oper_nome, oper_spid, oper_licensa, oper_numero, oper_numero_saida, oper_dono
)
select oper_nome, oper_spid, oper_licensa, oper_numero, oper_numero_saida, oper_dono
from operadoras
where oper_spid not in(select oper_spid from pbx_operadoras)";
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel atualizar as informacoes locais!"));
/*
* Atualiza o id.
*/
$query = "SELECT setval('public.pbx_operadoras_oper_id_seq', (select max(oper_id) from pbx_operadoras), true)";
$result = @pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Não foi possivel atualizar o id da tabela de operadoras!"));
/*
* Apaga operadoras remotas
$query = "delete from pbx_operadoras where oper_dono = 'R'";
$result = @pg_query($db, $query);
if(!$result) throw new Exception (GetExcept("Não foi possivel apagar operadoras existentes!"));
*/
}
@pg_query($db, 'commit');
}
function IniciaInstalacao() {
global $cliIdExterno, $cliId, $idAtualiza, $serverApi, $loginApi, $senhaApi;
echo "Obtendo informacoes sobre atualizacoes.\n";
$url = "http://$serverApi/integracao?method=PortabInstall&cliIdExterno=$cliIdExterno&login=$loginApi&senha=$senhaApi&SIPID=0&tipoRetorno=XML";
$xml = simplexml_load_string(file_get_contents($url));
$statusTran = trim($xml->status);
if ($statusTran != 'OK')
throw new Exception(GetExcept($xml->message));
$idAtualiza = $xml->idarquivo;
$cliId = $xml->cli_id;
$cliStatus = $xml->clie_status;
if ($cliStatus != 2)
throw new Exception(GetExcept("O cliente nao esta habilitado para instalacao!\n"));
}
function FinalizaInstalacao() {
global $idAtualiza, $cliId, $serverApi, $loginApi, $senhaApi, $filePorta;
echo "Registrando a instalacao no servidor de portabilidade";
$url = "http://$serverApi/integracao?method=PortabInstallReg&cliId=$cliId&idArquivo=$idAtualiza&login=$loginApi&senha=$senhaApi&SIPID=0&tipoRetorno=XML";
$xml = simplexml_load_string(file_get_contents($url));
$statusTran = trim($xml->status);
if ($statusTran != 'OK')
throw new Exception(GetExcept($xml->message));
unlink($filePorta);
}
/*
* Funcoes deverão ser removidas em outra versao,
* todas existem na unit util ou shared; foram
* introduzidas aqui apenas para garantir que
* funcionem em qualque versão.
*/
function ExecStart($fileExec) {
return true;
if (file_exists($fileExec)) {
exit;
}
/*
* Cria o arquivo caso ele não exista.
*/
$arq = fopen($fileExec, 'w');
fclose($arq);
}
function ExecEnd($fileExec) {
return true;
unlink($fileExec);
exit;
}
function DisplayDebub($msg) {
global $debug;
if ($debug) {
echo $msg;
}
}
function GravaLogPorta($txt, $aux = '') {
$txt = trim($txt);
$txt .= trim($aux);
$txt .= (stripos($txt, "Fim") !== false) ? "\n\n" : "\n";
$file = "/var/log/asterisk/portabilidade.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 VerificaDirDownload($dir) {
if (!file_exists($dir)) {
system("mkdir -p $dir");
system("chmod 777 -R $dir");
}
return file_exists($dir);
}
function downloadFile($url, $path) {
$newfname = $path;
$file = fopen($url, "rb");
$contents = stream_get_contents($file);
fclose($file);
$newf = fopen($newfname, "wb");
fwrite($newf, $contents);
fclose($newf);
if (file_exists($newfname)) {
if (filesize($newfname) > 100) {
return true;
}
}
return false;
$newfname = $path;
$file = fopen($url, "rb");
if ($file) {
$newf = fopen($newfname, "wb");
if ($newf)
while (!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
if (file_exists($newfname)) {
if (filesize($newfname) > 100) {
return true;
}
}
return false;
}
function UcompressFile($origem, $arqDestino, $destino = './') {
$result = true;
$cmd = sprintf("tar -xzvf %s -C %s", $origem, $destino);
//$cmd = sprintf("tar -xzf %s -C %s 2>/dev/null", $origem, $destino);
system($cmd, $result);
return file_exists($arqDestino);
/*
* Certifica que o arquivo foi criado com sucesso.
*/
//return file_exists(destino);
}
function GetExcept($msg) {
$ex = error_get_last();
return sprintf("%s\nErro: %s\n", trim($msg), trim($ex['message']));
}
?>