Compare commits

...

1 Commits

Author SHA1 Message Date
Rodgger a555952447 backup monitor 4 months ago
  1. 48
      .vscode/launch.json
  2. 81
      admin/css/pbx.css
  3. 111
      agente.css
  4. 108
      cadastros/cliente/clienteAnotacoes.php
  5. 76
      cadastros/cliente/clienteAudio.php
  6. 252
      cadastros/cliente/clienteContatos.php
  7. 419
      cadastros/cliente/clienteMail.php
  8. 78
      cadastros/cliente/clienteSMTP.php
  9. 13
      cadastros/cliente/config.php
  10. 1
      cadastros/cliente/contribDelete.php
  11. 146
      cadastros/cliente/contribInsert.php
  12. 357
      cadastros/cliente/contribSelect.php
  13. 304
      cadastros/cliente/contribUpdate.php
  14. 304
      cadastros/cliente/contribuinte.php
  15. 120
      cadastros/municipio/municipio.php
  16. 89
      cadastros/municipio/municipioInsert.php
  17. 100
      cadastros/municipio/municipioPrefixo.php
  18. 90
      cadastros/municipio/municipioUpdate.php
  19. 10
      configGeral.php
  20. 37
      contacteFunc.php
  21. 1
      imgSite/cpu-bad.svg
  22. 1
      imgSite/cpu-ok.svg
  23. 1
      imgSite/hd-bad.svg
  24. 1
      imgSite/hd-ok.svg
  25. 1
      imgSite/load-avg-danger.svg
  26. 1
      imgSite/ram-bad.svg
  27. 1
      imgSite/ram-ok.svg
  28. 1
      imgSite/troncoOff16.svg
  29. 1
      imgSite/troncoOn16.svg
  30. 941
      include/funcoes/shared.php
  31. BIN
      include/securimage/AHGBold.ttf
  32. 25
      include/securimage/LICENSE.txt
  33. 12
      include/securimage/README.FONT.txt
  34. 204
      include/securimage/README.txt
  35. 1899
      include/securimage/WavFile.php
  36. 1
      include/securimage/database/.htaccess
  37. 1
      include/securimage/database/index.html
  38. BIN
      include/securimage/database/securimage.sq3
  39. 207
      include/securimage/example_form.ajax.php
  40. 203
      include/securimage/example_form.php
  41. 2972
      include/securimage/securimage.php
  42. 65
      include/securimage/securimage_play.php
  43. BIN
      include/securimage/securimage_play.swf
  44. 79
      include/securimage/securimage_show.php
  45. 15457
      include/securimage/words/words.txt
  46. 222
      include/util/datas.php
  47. 2393
      include/util/funcoesApl.php
  48. 2
      include/util/funcoesLicenca.php
  49. 1396
      include/util/util.php
  50. 8
      index.php
  51. 139
      iniciaCliente.php
  52. 2
      integracao/bdApi.php
  53. 192
      integracao/funcoesApi.php
  54. 2
      integracao/index.php
  55. 6
      login.php
  56. 1046
      master.css
  57. 89
      monitorAlgar/bloqueio_algar.php
  58. 17
      monitorAlgar/enviaRelatorio.php
  59. 88
      monitorAlgar/index.php
  60. 95
      monitorAlgar/relatorioMonitoraAlgar.php
  61. 109
      monitorAlgar/script_cliente.php
  62. 12
      padroes.php
  63. 20
      router.html
  64. 10
      seguranca/grupos/grupoRevendas.php
  65. 16
      seguranca/grupos/grupoSelect.php
  66. 8
      seguranca/grupos/gruposUsuario.php
  67. 6
      seguranca/usuario.php
  68. 10
      seguranca/usuarioCad.php
  69. 261
      services/query_bd_result_monitor
  70. 24
      sites.php
  71. 32
      sites/siteInsert.php
  72. 91
      sites/siteSelect.php
  73. 30
      sites/siteUpdate.php
  74. 78
      sites/sites.php
  75. 34
      start.php
  76. 11
      templates/complementoMenu.htm
  77. 210
      templates/master.tpl
  78. 29
      templates/seguranca/grupos/grupos.tpl
  79. 1
      templates/seguranca/grupos/gruposUsuario.htm
  80. 204
      templates/vendas/monitorEvents.tpl
  81. 0
      vendas/funcoesMonitorEmail.php
  82. 470
      vendas/funcoesMonitorEvents.php
  83. 140
      vendas/funcoesMonitorHD.php
  84. 120
      vendas/funcoesMonitorTroncos.php
  85. 8
      vendas/monitorDetailsCpu.php
  86. 20
      vendas/monitorDetailsHd.php
  87. 74
      vendas/monitorDetailsRam.php
  88. 45
      vendas/monitorDetailsTroncos.php
  89. 222
      vendas/monitorEvents.php

48
.vscode/launch.json vendored

@ -0,0 +1,48 @@
{
// Use o IntelliSense para saber mais sobre os atributos possíveis.
// Focalizar para exibir as descrições dos atributos existentes.
// Para obter mais informações, acesse: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Listen for Xdebug",
"type": "php",
"request": "launch",
"port": 9010
},
{
"name": "Launch currently open script",
"type": "php",
"request": "launch",
"program": "${file}",
"cwd": "${fileDirname}",
"port": 0,
"runtimeArgs": [
"-dxdebug.start_with_request=yes"
],
"env": {
"XDEBUG_MODE": "debug,develop",
"XDEBUG_CONFIG": "client_port=${port}"
}
},
{
"name": "Launch Built-in web server",
"type": "php",
"request": "launch",
"runtimeArgs": [
"-dxdebug.mode=debug",
"-dxdebug.start_with_request=yes",
"-S",
"localhost:0"
],
"program": "",
"cwd": "${workspaceRoot}",
"port": 9003,
"serverReadyAction": {
"pattern": "Development Server \\(http://localhost:([0-9]+)\\) started",
"uriFormat": "http://localhost:%s",
"action": "openExternally"
}
}
]
}

81
admin/css/pbx.css

@ -0,0 +1,81 @@
.date {
font-weight: bold;
color: #066bb6;
}
.info {
font-size: .95em;
margin: 0px 0 0px !important;
color: #148d04;
}
.tabela {
border: 1px dashed #066bb6;
background-position: center center;
background-color: #EAEAEA;
}
.cabecalho {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
font-weight: bold;
text-transform: capitalize;
color: #066BB6;
background-image: url(../img/button03.gif);
border: none;
background-color: #EAEAEA;
}
.labels {
font-family: Arial, Helvetica, sans-serif;
font-size: 10px;
font-weight: bold;
color: #006633;
}
.caixas {
font-family: Arial, Helvetica, sans-serif;
font-size: 10px;
font-style: normal;
line-height: normal;
font-weight: bold;
font-variant: normal;
text-transform: none;
color: #333333;
border: 1px solid #666666;
}
.fr {
float: right !important;
}
.fl {
float: left !important;
}
.hidden {
display: none;
}
.headColun {
font-family: Arial, Helvetica, sans-serif;
font-size: 11px;
font-weight: bold;
border-top: 1px solid #000;
border-bottom: 1px solid #000;
}
.dados {
border: 1px solid #CCCCCC;
font-size: 11px;
font-weight: bold;
background-color: #F90;
border: 1px solid #CCCCCC;
color: #FFFFFF;
}
.dadosResult {
font-family: Arial, Helvetica, sans-serif;
font-size: 9px;
border: 1px solid #000000;
}

111
agente.css

@ -0,0 +1,111 @@
.agente
{
border-collapse: collapse;
border: 1px solid #CCCCCC;
background-color:#FFFFFF;
font-family:Arial, Helvetica, sans-serif;
text-align:center;
}
.agente th
{
border: 1px solid #CCCCCC;
font-size:11px;
font-weight:bold;
background-color:#F90;
color:#FFFFFF;
margin:0;
padding:0;
}
.agente td
{
font-size:10px;
}
.agente a:link, a:visited
{
font-size:11px;
color:#999999;
}
#mask-modal {
position:absolute;
left:0;
top:0;
z-index:9000;
background-color:#000;
border: 0;
display:none;
padding:0;
}
#boxes-modal .window-modal {
position:absolute;
left:0;
top:0;
width:440px;
height:200px;
display:none;
z-index:9999;
padding:0;
border: 0;
}
#boxes-modal #dialog {
width:550px;
height:300px;
padding:0;
background-color:#f0f0f0;
border: 3px solid #ccc;
}
#dadosDiscador
{
border-collapse: collapse;
background-color:#f0f0f0;
color: #000;
}
#dadosDiscador th
{
background-color: #F90;
font-size: small;
font-weight: bold;
color: #fff;
}
#dadosDiscador td
{
font-size: small;
font-weight: bold;
color: #000;
}
#dadosClienteDiscador
{
border-collapse: collapse;
font-size: small;
border: 1px solid #999999;
}
#dadosClienteDiscador th
{
background-color:#CCCCCC;
font-size: small;
font-weight: bold;
color: #000;
border: 1px solid #999999;
width: 20%;
}
#dadosClienteDiscador td
{
font-size: small;
background-color:#fff;
font-weight: normal;
color: #000;
border: 1px solid #999999;
width: 20%;
}

108
cadastros/cliente/clienteAnotacoes.php

@ -1,108 +0,0 @@
<?php
$tpLayout = 1;
$template = "cadastros/cliente/clienteAnotacoes.tpl";
$paramPesquisa = trim(isset($_REQUEST['paramPesquisa']) ? $_REQUEST['paramPesquisa'] : "");
$clientAnotacao = trim(isset($_REQUEST['clientAnotacao']) ? $_REQUEST['clientAnotacao'] : "");
$dataIni = isset($_REQUEST['dataIni']) ? $_REQUEST['dataIni'] : "";
$dataFim = isset($_REQUEST['dataFim']) ? $_REQUEST['dataFim'] : "";
$clientId = isset($_REQUEST['client_id']) ? $_REQUEST['client_id'] : "";
$clientOutId = isset($_REQUEST['client_out_id']) ? $_REQUEST['client_out_id'] : "0";
$ClientRazao = isset($_REQUEST['client_razao']) ? $_REQUEST['client_razao'] : "";
$msg = '';
/*
* Inserção de uma nova anotacao.
*/
if (isset($_POST["btGravar"]) && $clientAnotacao) {
$msg = "Erro ao inserir anotação!";
$query = sprintf("insert into pbx_cliente_anotacoes(client_id, cla_anotacao, user_reg)values('%s', %s, %s); ", $clientId, QuotedStr($clientAnotacao), GetMatricula());
$query .= sprintf("update pbx_cliente set user_reg = %s where client_id = %s; ", GetIdUser(), $clientId);
$result = pg_query($dbcon, $query);
if ($result && pg_affected_rows($result)) {
$msg = "Anotação inserida com sucesso!";
}
$jsStartup[] = sprintf("alert('%s');", $msg);
}
/*
* Pesquisa por palavra chave.
*/
$compl = '';
if ($paramPesquisa) {
$compl = PreparaLike($paramPesquisa, true);
$compl = sprintf("and cla_anotacao ilike %s\n", $compl);
}
/*
* Verifica se as datas foram informadas
*/
if (is_date($dataIni) && is_date($dataFim)) {
$compl .= sprintf(" and data_reg::date >= '%s' and data_reg::date <= '%s'\n", FormatDtMssql($dataIni), FormatDtMssql($dataFim));
} else if (is_date($dataIni)) {
$compl .= sprintf(" and data_reg::date >= '%s'\n", FormatDtMssql($dataIni));
} else if (is_date($dataFim)) {
$compl .= sprintf(" and data_reg::date <= '%s'\n", FormatDtMssql($dataFim));
}
$query = "SELECT cla_id, cla_anotacao, apelido, data_reg "
. "FROM pbx_cliente_anotacoes a "
. "LEFT JOIN pbx_usuarios b ON a.user_reg = b.matricula::INT "
. "WHERE client_id = '{$clientId}' $compl "
. "ORDER BY data_reg::timestamp DESC";
$sql = GetTotalRegistro($dbcon, $query);
$params = sprintf("&client_id=%s&client_razao=%s", $clientId, $ClientRazao);
$links = PaginaDados($idProg, $sql, $params, $regPagina, $offSet, $pagMostra, true);
$query .= " limit $regPagina offset $offSet";
$result = pg_query($dbcon, $query);
$dadosCliente = pg_fetch_all($result);
/*
* Captura os dados relacionados ao venda+.
*/
GetClientVendaMais($clientOutId, $dadosCliente);
$linhas = "";
foreach ($dadosCliente as $dados) {
$claId = $dados["cla_id"];
$claAnotacao = $dados["cla_anotacao"];
$dataReg = $dados["data_reg"];
$getAnotaId = ("anota_" . $claId);
$linhas .= sprintf('<tr>
<td>%s</td>
<td align="left" width="120px">%s</td>
<td align="left"><span id="%s">%s</span></td>
<td align="left" width="90px"><span>%s</span></td>
<td align="center"><img src="imgSite/anotacoes.png" width="16" heigth="16" title="Mostrar" border="0" onclick="GetAnotacaoCliente(\'%s\');"></td>
</tr>', $claId, date('d/m/Y H:i:s',strtotime($dataReg)), $getAnotaId, $claAnotacao, $dados['apelido'], $getAnotaId);
}
$smarty->assign('erro', $erro);
$smarty->assign('clientId', $clientId);
$smarty->assign('ClientRazao', $ClientRazao);
$smarty->assign('dataIni', $dataIni);
$smarty->assign('dataFim', $dataFim);
$smarty->assign("linhas", $linhas);
$smarty->assign("paramPesquisa", $paramPesquisa);
$smarty->assign("imgNovo", $imgNovo);
$smarty->assign("links", $links);
$smarty->assign("pagMostra", $pagMostra);
$smarty->assign("totalReg", $totalReg);
$smarty->assign("status", $statusAtivo);
$smarty->assign("pgn", $_REQUEST["pgn"]);
$smarty->assign("bloco", $_REQUEST["bloco"]);
$smarty->assign("pg", $_REQUEST["pg"]);
GetTemplate($smarty, $template);
function GetClientVendaMais($clientOutId, $dadosCliente) {
return;
}

76
cadastros/cliente/clienteAudio.php

@ -1,76 +0,0 @@
<?php
$client = isset($_REQUEST['client_id']) ? $_REQUEST['client_id'] : '';
$nome_cliente = isset($_REQUEST['n']) ? base64_decode($_REQUEST['n']) : '';
$tpLayout = 1;
try {
$cliente = GetAudioCliente($dbcon, $client);
foreach ($cliente as $value) {
$url = "http://{$_SERVER['SERVER_ADDR']}/integracao?method=GetAudio&login=user.api&senha=0000&uniqueid={$value["uniqueid"]}&tipo=mp3&tipoRetorno=JSON/STREAM";
$audio = "<audio controls preload='none' controlsList=\"download\" reconnect src=\"$url\"></audio>";
$data_reg = date('d/m/Y H:i:s', strtotime($value['data_reg']));
$linha .= sprintf("<tr>
<td align='center'>%s</td>
<td align='center'>{$value['src']}</td>
<td align='center'>{$value['dst']}</td>
<td align='center'>%s</td>
<td align='center'>{$value['apelido']}</td>
<td align='center'>{$value['userfield']}</td>
<td align='center'>%s</td>
<td align='center'>{$audio}</td>
</tr>", date('d/m/Y H:i:s', strtotime($value['calldate'])), SecondToStrTime($value['billsec']), tipoEncerramento($value['evento']));
$numReg++;
}
$color = 'green';
} catch (Exception $ex) {
$message = $ex->getMessage();
$color = 'red';
}
$smarty->assign("linhas", $linha ? $linha : "<td colspan='15' align='center'><b>Nenhum registro encontrado!</b></td>");
$smarty->assign("nome_cliente", $nome_cliente);
$smarty->assign("client_id", $cliente['client_id']);
$smarty->assign("contato", ($action == 'edit' ? GetContatoPorId($dbcon, $contato) : ''));
$smarty->assign("color", $color);
$smarty->assign("msgErro", $message);
GetTemplate($smarty, 'cadastros/cliente/clienteAudio.tpl');
/**
* Busca o cliente pelo seu ID.
* @param type $dbcon
* @param type $cliente
* @return type
*/
function GetAudioCliente($dbcon, $cliente) {
$query = "SELECT uniqueid, client_id, calldate, src, dst, apelido, userfield, billsec, evento, data_reg
FROM pbx_bilhetes a
INNER JOIN pbx_cliente_audio b ON a.uniqueid = b.uid
INNER JOIN pbx_eventos_dacs c ON c.uid2 = a.uniqueid
INNER JOIN pbx_usuarios d ON d.matricula = SUBSTRING(c.agente,7,4)
WHERE b.client_id = '{$cliente}'
AND evento IN('COMPLETAAGENT','COMPLETACALLER', 'TRANSFERORIG','BUSYS','NOANSWERS')
ORDER BY calldate;";
$result = pg_query($dbcon, $query);
$rows = pg_fetch_all($result);
return $rows;
}
function tipoEncerramento($evento) {
switch ($evento) {
case 'COMPLETAAGENT':
case 'COMPLETACALLER':
return "ATENDIDA";
case 'TRANSFERORIG':
return "TRANSFERIDA";
case 'BUSYS':
return "OCUPADA";
case 'NOANSWERS':
return "NÃO ATENDIDA";
}
}
?>

252
cadastros/cliente/clienteContatos.php

@ -1,252 +0,0 @@
<?php
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
$client = isset($_REQUEST['client_id']) ? $_REQUEST['client_id'] : '';
$contato = isset($_REQUEST['clc_id']) ? $_REQUEST['clc_id'] : $_SESSION['SSclc_id'];
/** ARMAZENA O REGISTRO BUSCADO * */
$_SESSION['SSclc_id'] = ($action == 'edit' ? $contato : '');
/** COLETA OS DADOS DO POST * */
$fieldspost = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);
/** ADICIONA A MATRICULA DE MODIFICACAO * */
$fieldspost['user_reg'] = GetMatricula();
$tpLayout = 1;
try {
if (isset($fieldspost['formAcaoDesc']) && $action != 'delete') {
$data = verifyDataPost($fieldspost);
if ($data) {
SetClienteContato($dbcon, $data, $contato);
flash("O cadastro foi realizado com sucesso!");
}
}
if ($contato && $action == 'delete') {
deleteContato($dbcon, $contato);
flash("O contato removido com sucesso!");
}
$contatos = GetContatoPorCliente($dbcon, $client);
$cliente = GetCliente($dbcon, $client);
foreach ($contatos as $value) {
$clc = "<a href=\"javaScript:NovaJanela('index.php?idProg=346&client_id={$value["client_id"]}&clc_id={$value["clc_id"]}&action=edit', 'contatosCliente', '900', '250', 'jhTela')\"><img src=\"imgSite/editaUser.png\" border=\"0\" width=\"16\" height=\"16\" alt=\"Contatos do cliente ID: $nomeDisp\" title=\"Contatos do cliente ID: $nomeDisp\"></a>";
$delete = "<a href=\"javaScript:NovaJanela('index.php?idProg=346&client_id={$value["client_id"]}&clc_id={$value["clc_id"]}&action=delete', 'contatosCliente', '900', '250', 'jhTela')\"><img src=\"imgSite/deletaUser.png\" border=\"0\" width=\"16\" height=\"16\" alt=\"Contatos do cliente ID: $nomeDisp\" title=\"Contatos do cliente ID: $nomeDisp\"></a>";
$data_reg = date('d/m/Y H:i:s', strtotime($value['data_reg']));
$linha .= sprintf("<tr>
<td align='center'>{$value['clc_id']}</td>
<td align='center'>{$value['clc_nome']}</td>
<td align='center'>{$value['clc_email']}</td>
<td align='center'>{$value['clc_fone']}</td>
<td align='center'>{$value['clc_sms']}</td>
<td align='center'>{$value['clc_whatsapp']}</td>
<td align='center'>{$value['clc_telegram']}</td>
<td align='center'>%s</td>
<td align='center'>%s</td>
<td align='center'>{$data_reg}</td>
<td align='center'>{$clc} {$delete}</td>
</tr>", ($value['clc_contato_principal'] ? '<img src="imgSite/Yes.png">' : '<img src="imgSite/Delete.png">'), GetUsuario($dbcon, $value['user_reg'])['apelido']);
$numReg++;
}
} catch (Exception $ex) {
flash($ex->getMessage(),'red');
}
$flash = flash();
$smarty->assign("linhas", $linha ? $linha : "<td colspan='15' align='center'><b>Nenhum registro encontrado!</b></td>");
$smarty->assign("nome_cliente", $cliente['client_nome_fantasia']);
$smarty->assign("client_id", $cliente['client_id']);
$smarty->assign("contato", ($action == 'edit' ? GetContatoPorId($dbcon, $contato) : ''));
$smarty->assign("color", $flash[1]);
$smarty->assign("msgErro", $flash[0]);
GetTemplate($smarty, 'cadastros/cliente/clienteContatos.tpl');
/**
* Funcao para atualizar ou cadastrar um novo contato e alterar seu registro principal.
*
* Para a atualização do registro é importante passar o clc_id no parametro $id.
*
* O valor do parametro $data é o retorno da funcao verifyDataPost()
* @param type $dbcon
* @param type $data
* @param type $id
* @throws Exception
*/
function SetClienteContato($dbcon, $data, $id = null) {
if ($id) {
$campos = implode(',', array_map(function ($a, $b) {
return $a . " = " . QuotedStr($b);
}, array_keys($data), array_values($data)));
$query = " UPDATE pbx_cliente_contato SET $campos WHERE clc_id = '{$id}';";
} else {
$campos = implode(',', array_keys($data));
$values = implode(',', array_map(function ($a, $b) {
return QuotedStr($b);
}, array_keys($data), array_values($data)));
$query = " INSERT INTO pbx_cliente_contato ($campos) VALUES($values);";
}
if (array_key_exists('clc_contato_principal', $data)) {
$query1 .= " UPDATE pbx_cliente_contato SET clc_contato_principal = 0 WHERE client_id = '{$data['client_id']}' ";
$query1 .= $id ? " AND clc_id <> '{$id}'; " : ';';
}
$result = pg_query($dbcon, $query1 . $query);
$contato = registraContatoPrincipal($dbcon, $data['client_id']);
SetClientePrincipal($dbcon, $contato);
if (!$result) {
throw new Exception('Não foi possível ' . ($id ? 'atualizar' : 'cadastrar') . ' o registro! Erro: ' . pg_last_error());
}
}
/**
* Adiciona um contato como principal mantendo sempre 1 como principal.
* @param type $dbcon
* @param type $id
* @return type
* @throws Exception
*/
function registraContatoPrincipal($dbcon, $id) {
$resp = GetContatoPorCliente($dbcon, $id);
$lastid = null;
$contato = null;
foreach ($resp as $v) {
if ($v['clc_contato_principal']) {
return $v;
} else {
$lastid = $v['clc_id'];
$contato = $v;
}
}
$query = "UPDATE pbx_cliente_contato SET clc_contato_principal = 1 WHERE clc_id = {$lastid};";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception('Não foi atualizar o registro principal! Erro: ' . pg_last_error());
}
return $contato;
}
/**
* Busca o contato pode o cliente;
* @param type $dbcon
* @param type $cliente
* @return type
*/
function GetContatoPorCliente($dbcon, $cliente) {
$query = "SELECT * FROM pbx_cliente_contato WHERE client_id = '{$cliente}' ORDER BY clc_nome;";
$result = pg_query($dbcon, $query);
$rows = pg_fetch_all($result);
return $rows;
}
/**
* Busca o contato por o contato_id = clc_id
* @param type $dbcon
* @param type $clc_id
* @return type
*/
function GetContatoPorId($dbcon, $clc_id) {
$query = "SELECT * FROM pbx_cliente_contato WHERE clc_id = '{$clc_id}';";
$result = pg_query($dbcon, $query);
$rows = pg_fetch_assoc($result);
return $rows;
}
/**
* Deleta o contato pelo id.
* @param type $dbcon
* @param type $contato
* @throws Exception
*/
function deleteContato($dbcon, $contato) {
$query = "DELETE FROM pbx_cliente_contato WHERE clc_id = '{$contato}';";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception('Não foi possível remover o registro! Erro: ' . pg_last_error());
}
}
/**
* Verifica os dados passados no POST conforme o tamanho do campo da tabela.
* Caso o campo seja inteiro é informado o número 0.
* @param type $fieldpost
* @return type
* @throws Exception
*/
function verifyDataPost($fieldpost) {
$fields = array(
array("field" => 'user_reg', "size" => 0, "type" => "int", "require" => true),
array("field" => 'client_id', "size" => 0, "type" => "int", "require" => true),
array("field" => 'clc_contato_principal', "size" => 0, "type" => "int", "require" => false),
array("field" => 'clc_nome', "size" => 128, "type" => "string", "require" => true, "upper" => true),
array("field" => 'clc_email', "size" => 128, "type" => "string", "require" => false),
array("field" => 'clc_fone', "size" => 32, "type" => "int", "require" => true),
array("field" => 'clc_sms', "size" => 32, "type" => "int", "require" => false),
array("field" => 'clc_whatsapp', "size" => 32, "type" => "int", "require" => false),
array("field" => 'clc_telegram', "size" => 32, "type" => "int", "require" => false)
);
$data = array();
foreach ($fields as $k => $v) {
if (array_key_exists($v['field'], $fieldpost) && ((strlen($fieldpost[$v['field']]) > 0 && strlen($fieldpost[$v['field']]) <= $v['size']) || ($v['size'] == 0))) {
if ($v['type'] == 'int') {
$data[$v['field']] = soNumero($fieldpost[$v['field']]);
} else {
$data[$v['field']] = $v['upper'] ? strtoupper($fieldpost[$v['field']]) : $fieldpost[$v['field']];
}
} else if ($v['require']) {
flash("É necessário preencher o campo " . ucfirst(str_replace('_', '', str_replace('clc_', '', $v['field']))) . "!", 'red');
return false;
}
}
return $data;
}
/**
* Busca o cliente pelo seu ID.
* @param type $dbcon
* @param type $cliente
* @return type
*/
function GetCliente($dbcon, $cliente) {
$query = "SELECT * FROM pbx_cliente WHERE client_id = '{$cliente}';";
$result = pg_query($dbcon, $query);
$rows = pg_fetch_assoc($result);
return $rows;
}
/**
* Atualiza os dados do cliente conforme o contato principal.
* @param type $dbcon
* @param type $contato
* @throws Exception
*/
function SetClientePrincipal($dbcon, $contato) {
$query = "UPDATE pbx_cliente SET client_telefone = '{$contato['clc_fone']}', "
. "client_email = '{$contato['clc_email']}', client_nome_contato = '{$contato['clc_nome']}' "
. " WHERE client_id = '{$contato['client_id']}';";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Não foi possível atualizar o contato do cliente!");
}
}
function flash($message = null, $color = 'green') {
if ($message) {
$_SESSION['SSMSGFlash'] = $message;
$_SESSION['SSMSGFlashColor'] = $color;
} else {
$message = $_SESSION['SSMSGFlash'];
$color = $_SESSION['SSMSGFlashColor'];
unset($_SESSION['SSMSGFlash'], $_SESSION['SSMSGFlashColor']);
}
return array($message, $color);
}
?>

419
cadastros/cliente/clienteMail.php

@ -1,419 +0,0 @@
<?php
/**
| STATUS DE REGISTRO status_cmpr:
|
| 0 = NAO PROCESSADA
| 1 = PROCESSADA COM SUCESSO
| 2 = PROCESSADA COM ERRO
*/
require "util/SimpleMail.php";
$tpLayout = 1;
$temp = isset($_POST['temp']) ? explode('|', $_POST['temp'])[0] : '';
$client = isset($_REQUEST['client_id']) ? $_REQUEST['client_id'] : '';
$cmp = isset($_REQUEST['cmp']) ? $_REQUEST['cmp'] : '';
$acao = isset($_GET['action']) ? $_GET['action'] : '';
$listId = isset($_GET['list_id']) ? $_GET['list_id'] : '';
define('CONF_MAIL_PATH_TEMPLATE', '/var/www/html/aplicativo/');
$queryClient = $_SESSION['SSQueryClient'];
try {
$user = GetUsuario($dbcon, GetMatricula());
if ($acao == 'finish' && $listId) {
__SetFinalizarLista($listId);
}
if ($cmp && $queryClient && isset($_POST['btnEnviar'])) {
$campanha = __createCamp();
__createListaCamp($campanha['cmp_id'], $user, $temp);
}
if (isset($_POST['btnEnviar']) && $client && !$cmp) {
sendMailToClient($client, $temp, $user);
}
} catch (Exception $ex) {
flash($ex->getMessage(), 'red');
}
if ($cmp) {
$smarty->assign("listcamp", __GetCampanhaList());
}
$dataTemplate = getTemplates(null, $temp);
$smarty->assign("flash", flash());
$smarty->assign("client_id", $client);
$smarty->assign("templates", $dataTemplate[1]);
$smarty->assign("templ", formatTemplate($user, $dataTemplate[2], $client));
$smarty->assign("cmp", $cmp);
$smarty->assign("emailfrom", (__GetAdminCampanha(GetMatricula()) ? true : false));
GetTemplate($smarty, 'cadastros/cliente/clienteMail.tpl');
/**
* - Coleto cliente e faz o envio do email para suas informações da pbx_client;
* - Anexa as informacoes no tamplate para apresentacao do conteudo enviado.
* @param type $client
* @param type $temp
* @return boolean
*/
function sendMailToClient($client, $temp, $user = null) {
$data = getClient($client);
if ($data['client_email'] && $temp) {
//$nome = $data['client_nome_contato'] ? base64_encode($data['client_nome_contato']) : '';
//$telefone = $data['client_telefone'] ? base64_encode($data['client_telefone']) : '';
//$agente = $user['nome'] ? base64_encode($user['nome']) : '';
//$linkliguegratis = "https://simplesip.com.br/email/liguegratis.php?n={$nome}&t={$telefone}&c={$agente}";
$dataTempl = array();
foreach ($data as $key => $t){
$dataTempl['{'.$key.'}'] = $t;
}
if (sendMail($data['client_email'], $dataTempl, $temp, $user['email'])) {
flash('E-mail enviado com sucesso!', 'green');
return true;
}
}
flash('Não foi possível enviar o e-mail para o solicitante!', 'red');
return false;
}
/**
* Faz o envio de email de modo unitário.
* @param type $email
* @param type $data
* @param type $template
* @return boolean
*/
function sendMail($email, $data, $template, $colabMail) {
$templ = getTemplates($template);
$param = __GetParam();
$simple = new SimpleMail($param['user_param'], $param['password_param'], utf8_encode($templ['subject_tpl']));
$simple->config($param['host_param'], $param['port_param'], utf8_encode($templ['title_tpl']));
$simple->setFrom(($colabMail ? $colabMail : $param['user_from']));
$simple->pathBodyMail(CONF_MAIL_PATH_TEMPLATE . $templ['path_tpl'], $data);
if ($simple->mailing($email)) {
return true;
}
flash('Não foi possível enviar o e-mail para o solicitante!' . $simple->getErrorSend(), 'red');
return false;
}
/**
* busca as infomacoes do cliente
* @param type $client
* @return type
*/
function getClient($client) {
global $dbcon;
$query = "SELECT * FROM pbx_cliente a
LEFT JOIN pbx_usuarios b ON a.client_user_contato = b.matricula
WHERE client_id = {$client}";
$result = pg_query($dbcon, $query);
return pg_fetch_assoc($result);
}
/**
* Retorna uma array de template associativo caso passe o parametro $tpl se não
* irá retornar um array com um select formatado em html.
* @param type $tpl
* @param type $select
* @return type
*/
function getTemplates($tpl = null, $select = null) {
global $dbcon,$user,$client;
$query = "SELECT * FROM pbx_campanha_template";
$query .= $tpl ? " WHERE id_tpl = {$tpl} " : '';
$query .= " ORDER BY nome_tpl ";
$result = pg_query($dbcon, $query);
if ($tpl) {
return pg_fetch_assoc($result);
}
$data = pg_fetch_all($result);
if ($data) {
$opt = "<select name='temp' id='selecttemplate' onclick=\"viewTemplate()\">";
foreach ($data as $vl) {
$selected = $select == $vl['id_tpl'] ? 'selected' : '';
$opt .= sprintf("<option value='{$vl['id_tpl']}|%s' $selected>{$vl['nome_tpl']}</option>", formatTemplate($user, $vl['path_tpl'], $client));
}
$opt .= "</select>";
}
return array($data, $opt, $data[0]['path_tpl']);
}
function formatTemplate($user, $template, $client = null) {
if($client){
$data = getClient($client);
} else {
$data = array('client_nome_contato' => 'CLIENTE', 'nome' => $user['nome']);
}
$json = json_encode($data);
return sprintf("mail_template.php?t=%s&d=%s", base64_encode($template), base64_encode($json));
}
function flash($message = null, $color = 'green') {
if ($message) {
$_SESSION['SSMSGFlash'] = $message;
$_SESSION['SSMSGFlashColor'] = $color;
} else {
$message = $_SESSION['SSMSGFlash'];
$color = $_SESSION['SSMSGFlashColor'];
unset($_SESSION['SSMSGFlash'], $_SESSION['SSMSGFlashColor']);
}
return array($message, $color);
}
############################################################################
######## CRIACAO DE CAMPANHA E LISTA ########
############################################################################
/**
* Cria uma nova campanha
* @param type $descricao
* @param type $dac
* @throws Exception
*/
function __createCamp() {
global $dbcon;
try {
__transaction('BEGIN;');
$query = "SELECT cmp_id FROM pbx_campanha WHERE cmp_descricao = 'CAMPANHA_SERVICE_MAIL'";
$result = pg_query($dbcon, $query);
$res = pg_fetch_assoc($result);
if (!$res['cmp_id']) {
$query = "INSERT INTO pbx_campanha(cmp_descricao, cmp_ramal, id_dac, cmp_aguarda_agente, cmp_numero_ligacoes_agente, ident_proc, cmp_status, cmp_tipo_campanha, cmp_seletiva)
VALUES(%s,'-1',%s,'1','1',%s,'2','3','1') RETURNING cmp_id;";
$query = sprintf($query, QuotedStr('CAMPANHA_SERVICE_MAIL'), QuotedStr('00'), QuotedStr('Inserido: listacampanhaemail Data: ' . date('Y-m-d H:i:s')));
$result = pg_query($dbcon, $query);
$res = pg_fetch_assoc($result);
if (!$result) {
throw new Exception("[ERROR CAMPANHA 001] - Não foi possível criar a campanha!");
}
}
__transaction('COMMIT;');
flash('Campanha criada com sucesso!', 'green');
return $res;
} catch (Exception $ex) {
__transaction('ROLLBACK;');
flash($ex->getMessage(), 'red');
}
return false;
}
/**
* Cria as listas com as informacoes dos clientes e suas expecificacoes, como, display de agente, contatos, lista de telefone e permissoes de campanha.
* Tabelas:
* > pbx_campanha
* > pbx_campanha_lista
* > pbx_campanha_contato
* > pbx_campanha_contato_fone
* > pbx_campanha_usuarios
*
* @param type $cmp_id
* @throws Exception
*/
function __createListaCamp($cmp_id, $user, $temp) {
global $dbcon;
$regfail = 0;
$regsuccess = 0;
try {
__transaction('BEGIN;');
$nomelist = "CMP-EMAIL_" . date('d-m-Y_H-i-s');
/**
* Table: pbx_campanha_lista
* CRIA UM LISTA PARA A CAMPANHA
*/
$sql = "INSERT INTO pbx_campanha_lista(cmp_id, list_nome, list_file, list_status, id_usuario, list_id_tpl) VALUES('{$cmp_id}', '{$nomelist}', '{$nomelist}', '1', '{$user['id']}', {$temp}) RETURNING list_id;";
$result = pg_query($dbcon, $sql);
if (!$result) {
__transaction('ROLLBACK;');
throw new Exception("[ERROR LIST 003] - Não foi possível criar a lista para campanha!" . pg_result_error($result));
}
$lstCamp = pg_fetch_assoc($result);
__transaction('COMMIT;');
$data = __getClientCamp();
/**
* @pbx_campanha_contato
* BUSCA TODOS OS CLIENTE PARA INSERIR NA LISTA DE CONTATO
*/
foreach ($data as $value) {
if ($value['client_email']) {
__transaction('BEGIN;');
$nomeContato = $value['client_nome_contato'] ? $value['client_nome_contato'] : '-';
$telefone = $value['client_telefone'] ? $value['client_telefone'] : ($value['client_celular'] ? $value['client_celular'] : '');
/** LOCAL PARA CRIAR REGRAS DE ENVIOS */
/** FIM DA REGRA */
/** @pbx_campanha_contato */
$query1 = sprintf(" INSERT INTO pbx_campanha_contato(cmp_id, list_id, cont_identificador, cont_param1, cont_param2, cont_param3, cont_param4, cont_status, conf_matricula_exclusiva) "
. "VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING cont_id; ",
QuotedStr($cmp_id),
QuotedStr($lstCamp['list_id']),
QuotedStr($value['client_id']),
QuotedStr($nomeContato),
QuotedStr($value['client_razao_social']),
QuotedStr($value['client_documento']),
QuotedStr($telefone),
QuotedStr(0),
QuotedStr($value['client_user_contato']));
$result = pg_query($dbcon, $query1);
if (!$result) {
__transaction('ROLLBACK;');
continue;
}
$cont_id = pg_fetch_assoc($result)['cont_id'];
/** @pbx_campanha_contato_fone */
$query2 = sprintf(" INSERT INTO pbx_campanha_contato_fone(cmp_id, list_id, cont_id, conf_fone, conf_status, conf_status_lista, conf_discado) "
. "VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING conf_id;",
QuotedStr($cmp_id),
QuotedStr($lstCamp['list_id']),
QuotedStr($cont_id),
QuotedStr($value['client_email']),
QuotedStr(0),
QuotedStr(1),
QuotedStr(0)
);
$result = pg_query($dbcon, $query2);
if (!$result) {
$regfail++;
__transaction('ROLLBACK;');
continue;
}
$conf_id = pg_fetch_assoc($result)['conf_id'];
/** @pbx_campanha_registro */
$query3 = "INSERT INTO pbx_campanha_registro (list_id, cont_id, conf_id, ctp_id, matricula_exclusiva, contato_cmpr, status_cmpr, inicio_cmpr, user_reg) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)";
$query = sprintf($query3,
QuotedStr($lstCamp['list_id']),
QuotedStr($cont_id),
QuotedStr($conf_id),
'3',
QuotedStr($value['client_user_contato']),
QuotedStr($value['client_email']),
'0',
QuotedStr(date('Y-m-d H:i:s')),
QuotedStr($user['id']));
$result = pg_query($dbcon, $query);
if (!$result) {
__transaction('ROLLBACK;');
continue;
}
$regsuccess++;
__transaction('COMMIT;');
} else {
$regfail++;
}
}
if ($regsuccess) {
flash("A campanha foi registrado com sucesso! Criados: {$regsuccess} Regeitados: {$regfail}.", 'green');
} else {
$query = "DELETE FROM pbx_campanha_lista WHERE list_id = {$lstCamp['list_id']};";
pg_query($dbcon, $query);
flash("Nenhum registro foi adicionado a campanha! Criados: {$regsuccess} Regeitados: {$regfail}", 'red');
}
} catch (Exception $ex) {
flash($ex->getMessage(), 'red');
}
}
function __GetAdminCampanha($matricula) {
$query = "SELECT * FROM pbx_fornecedor_permissao WHERE matricula_permissao = '$matricula'";
$result = pg_query($query);
$resp = pg_fetch_assoc($result);
return $resp;
}
function __getClientCamp() {
global $dbcon;
$result = pg_query($dbcon, $_SESSION['SSQueryClient']);
$data = pg_fetch_all($result);
if (!$result || !$data) {
throw new Exception('Nenhum cliente selecionado para a criação da lista!');
}
return $data;
}
function __GetParam() {
global $dbcon;
$query = "SELECT * FROM pbx_campanha_parametros";
$result = pg_query($dbcon, $query);
return pg_fetch_assoc($result);
}
function __SetFinalizarLista($listId) {
global $dbcon;
$query = "UPDATE pbx_campanha_lista SET list_status = 2 WHERE list_id = {$listId};";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception('Não foi possível para a campanha em execução!');
}
}
function __GetCampanhaList() {
global $dbcon;
$query = sprintf("SELECT b.list_id, b.data_reg, list_status, SUM(CASE WHEN(conf_discado = 1)THEN 1 ELSE 0 END) AS enviados, count(*) AS total
FROM pbx_campanha a
INNER JOIN pbx_campanha_lista b ON b.cmp_id = a.cmp_id
INNER JOIN pbx_campanha_contato c ON b.list_id = c.list_id
INNER JOIN pbx_campanha_contato_fone d ON c.cont_id = d.cont_id
INNER JOIN pbx_cliente e ON e.client_id = c.cont_identificador::INT
LEFT JOIN pbx_usuarios f ON f.matricula = e.client_user_contato
WHERE list_id_tpl IS NOT NULL
AND conf_status_lista = '1'
AND cmp_tipo_campanha = 3
%s
GROUP BY b.list_id, b.data_reg, list_status
ORDER BY list_id DESC", (!IsAdmin() ? "AND b.id_usuario = " . GetIdUser() : ''));
$result = pg_query($dbcon, $query);
$data = pg_fetch_all($result);
$tbl = "<table width=\"50%\" id=\"tblResult\" align=\"center\" cellspacing=\"0\" cellpadding=\"2\" class=\"grid\">";
$tbl .= "<tr> <th>Lista ID</th> <th>Data Hora</th> <th>Status</th> <th>Enviados</th> <th>Não Enviados</th> <th>Total</th> <th>FINALIZAR</th></tr>";
foreach ($data as $list) {
$tbl .= "<tr align=\"center\">";
$tbl .= "<td>{$list['list_id']}</td>";
$tbl .= sprintf("<td>%s</td>", date('d/m/Y H:i:s', strtotime($list['data_reg'])));
$tbl .= sprintf("<td>%s</td>", ($list['list_status'] == '2' ? "<img src='imgSite/Yes.png'>" : "<img src='imgSite/ampulheta.png'>"));
$tbl .= "<td>{$list['enviados']}</td>";
$tbl .= sprintf("<td>%s</td>", ($list['total'] - $list['enviados']));
$tbl .= "<td>{$list['total']}</td>";
$tbl .= sprintf("<td>%s</td>", ($list['list_status'] == '2' ? "<img title='ESSA CAMPANHA JÁ FOI FINALIZADA!' src='imgSite/Info.png'>" : "<a href='index.php?idProg=349&cmp=1&action=finish&list_id={$list['list_id']}'><img src='imgSite/Stop sign.png'></a>"));
$tbl .= "</tr>";
}
$tbl .= "</table>";
return $tbl;
}
function __transaction($type) {
global $dbcon;
pg_query($dbcon, $type);
}

78
cadastros/cliente/clienteSMTP.php

@ -1,78 +0,0 @@
<?php
/** @popup * */
$tpLayout = 1;
/** COLETA OS DADOS DO POST * */
$fieldspost = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);
try {
$param = GetParam();
if (isset($fieldspost['bt_gravar'])) {
SetParam($fieldspost);
}
} catch (Exception $ex) {
flash($ex->getMessage(), 'red');
}
$smarty->assign("flash", flash());
$smarty->assign("param", $param);
GetTemplate($smarty, 'cadastros/cliente/clienteSMTP.tpl');
function GetParam() {
global $dbcon;
$query = "SELECT * FROM pbx_campanha_parametros";
$result = pg_query($dbcon, $query);
return pg_fetch_assoc($result);
}
function SetParam($param) {
global $dbcon;
if (!$param['id_param']) {
$query = "INSERT INTO pbx_campanha_parametros (host_param, user_param, password_param, port_param, secure_param, charset_param, auth_param, from_param) "
. "VALUES(%s, %s, %s, %s, %s, %s, %s, %s) RETURNING id_param;";
} else {
$query = "UPDATE pbx_campanha_parametros SET "
. "host_param = %s,"
. "user_param = %s,"
. "password_param = %s,"
. "port_param = %s,"
. "secure_param = %s,"
. "charset_param = %s,"
. "auth_param = %s,"
. "from_param = %s, "
. "update_reg = '" . date('Y-m-d H:i:s') . "' WHERE id_param = {$param['id_param']}";
}
$query = sprintf($query,
QuotedStr($param['host_param']),
QuotedStr($param['user_param']),
QuotedStr($param['password_param']),
QuotedStr($param['port_param']),
QuotedStr(($param['secure_param'] ? $param['secure_param'] : 'TLS')),
QuotedStr(($param['charset_param'] ? $param['charset_param'] : 'UTF8')),
QuotedStr(($param['auth_param'] ? $param['auth_param'] : 0)),
QuotedStr($param['from_param']));
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Não foi possível " . ($param['id_param'] ? "atualizar" : "criar") . " o registro! Erro: " . pg_last_error());
}
flash("O registro foi " . ($param['id_param'] ? "atualizado" : "criado") . " com sucesso!", 'green');
}
function flash($message = null, $color = 'green') {
if ($message) {
$_SESSION['SSMSGFlash'] = $message;
$_SESSION['SSMSGFlashColor'] = $color;
} else {
$message = $_SESSION['SSMSGFlash'];
$color = $_SESSION['SSMSGFlashColor'];
unset($_SESSION['SSMSGFlash'], $_SESSION['SSMSGFlashColor']);
}
return array($message, $color);
}

13
cadastros/cliente/config.php

@ -1,13 +0,0 @@
<?php
define('CONF_MAIL_LIMIT', 50);
define('CONF_MAIL_HOST', 'mail.simplesip.com.br');
define('CONF_MAIL_PORT', '587');
define('CONF_MAIL_TITLE', 'SIMPLES IP');
define('CONF_MAIL_SENDER', 'marketing@simplesip.com.br');
define('CONF_MAIL_PASSWD', '$m@rk2t3ng_#');
define('CONF_MAIL_SUBJECT', utf8_encode('SEU PABX PODE SER UMA MAQUINA DE FAZER VENDAS, VEJA COMOO É FÁCIL!!'));
define('CONF_MAIL_PATH_TEMPLATE', '/var/www/html/aplicativo/');

1
cadastros/cliente/contribDelete.php

@ -1 +0,0 @@
<?php ?>

146
cadastros/cliente/contribInsert.php

@ -1,146 +0,0 @@
<?php
/*
*
* Prepara form
*/
$template = "contribuinte.tpl";
$tpLayout = 1;
if (GetFormAcao() == FORM_NEW) {
$tpIdent = TIPO_IDENTIFICA_CNPJ;
$acaoForm = FORM_INSERT;
$smarty->assign("client_status", GetStatusProspect($_POST["client_status"]));
$smarty->assign("client_tipo_contato", GetClientTipoContato("0"));
if ($_SESSION["txtConsulta"])
$smarty->assign("client_telefone", $_SESSION["txtConsulta"]);
} else {
$msgForm = array();
if (!validaForm($fields, $fieldsObrig, $fieldsType, $fieldsDiplay, $msgForm)) {
$acaoForm = FORM_INSERT;
$tpIdent = $_POST["client_tipo_documento"];
//formata mensagem de erro para script
$msgRet = "";
foreach ($msgForm as $value)
$msgRet .= "\\n" . $value;
$jsStartup[] = "alert('$msgRet');";
//formata mensagem de erro para o form
$msgRet = "";
foreach ($msgForm as $value)
$msgRet .= $value . " ";
//erros no form
$smarty->assign("msgErro", $msgRet);
$_POST["client_status"] = GetStatusProspect($_POST["client_status"]);
$_POST["client_tipo_contato"] = GetClientTipoContato($_POST["client_tipo_contato"]);
$smarty->assign("client_status", $_POST["client_status"]);
$smarty->assign("client_tipo_contato", $_POST["client_tipo_contato"]);
//valores no form
$smarty->assign('client_class', GetClassificacaoVendas($_POST["client_class"]));
$smarty->assign('client_agendamento', date('d/m/Y', strtotime($_POST["client_agendamento"])));
foreach ($fields as $value)
$smarty->assign($value, $_POST[$value]);
} else {
$acaoForm = FORM_INSERT;
$query = "select max(client_id) from pbx_cliente";
$result = pg_query($dbcon, $query);
$row = @pg_fetch_row($result);
$id = $row[0] ? $row[0] + 1 : 1;
$razao = QuotedStr(strtoupper($_POST["client_razao_social"]));
$documento = trim($_POST["client_documento"]);
$documento = !$documento ? "null" : QuotedStr($documento);
$email = trim($_POST["client_email"]);
$email = !$email ? "null" : QuotedStr($email);
$status = QuotedStr($_POST["client_status"]);
$contato = trim($_POST["client_nome_contato"]);
$contato = !$contato ? "null" : QuotedStr(strtoupper($_POST["client_nome_contato"]));
$tpContato = trim($_POST["client_tipo_contato"]);
$tpContato = !$tpContato ? "null" : QuotedStr($_POST["client_tipo_contato"]);
$fone = soNumero($_POST["client_telefone"]);
$fone = !$fone ? "null" : QuotedStr($fone);
$agendamento = $_POST["client_agenda"];
$agendamento = !$agendamento ? "null" : QuotedStr(FormatDtMssql($agendamento));
$classificacao = sonumero($_POST["client_class"]);
$classificacao = !$classificacao ? '0' : QuotedStr($classificacao);
$obs = trim($_POST["client_obs"]) ? QuotedStr(trim($_POST["client_obs"])) : '';
$user_contato = QuotedStr(GetMatricula());
$query = "insert into pbx_cliente(client_id, client_razao_social, client_status, client_email, client_nome_contato, client_telefone, client_tipo_contato, client_agendamento, client_class, client_documento, client_user_contato)
values( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING client_id;";
$query = sprintf($query, $id, $razao, $status, $email, $contato, $fone, $tpContato, $agendamento, $classificacao, $documento, $user_contato);
$result = pg_query($dbcon, $query);
$resp = pg_fetch_assoc($result);
if ($obs) {
$sql = "INSERT INTO pbx_cliente_anotacoes (client_id, cla_anotacao, user_reg) VALUES(%s, %s, %s);";
$sql = sprintf($sql, $resp['client_id'], $obs, $user_contato);
pg_query($dbcon, $sql);
}
$_POST["client_status"] = GetStatusProspect($_POST["client_status"]);
$_POST["client_tipo_contato"] = GetClientTipoContato($_POST["client_tipo_contato"]);
$smarty->assign("client_status", $_POST["client_status"]);
$smarty->assign("client_tipo_contato", $_POST["client_tipo_contato"]);
//valores no form
foreach ($fields as $value)
$smarty->assign($value, $value == "client_id" ? $id : $_POST[$value]);
$tpIdent = $tipo;
if ($result) {
$acaoForm = FORM_SAVE;
$msgRet = "Registro inserido com sucesso!";
$jsStartup[] = "window.opener.ResetForm();";
$_SESSION["txtConsulta"] = "";
if ($_SESSION["selContrib"]) {
$_SESSION["selContrib"] = false;
$nome = $_POST["client_razao_social"];
$_SESSION["contribRef"] = "$id - $nome";
$jsStartup[] = "window.opener.ChamSetContribuinte('$id','$nome');";
//$jsStartup[] = "window.opener.document.formGeral.txtConsulta.value = \"$id-$nome\";";
$jsStartup[] = "window.close();";
} else {
$jsStartup[] = "alert('$msgRet');";
$smarty->assign("msg", $msgRet);
}
} else {
$msgRet = "A operação não pode ser realizada!";
$jsStartup[] = "alert('$msgRet');";
$msgRet .= pg_last_error() ? " Erro: " . pg_last_error() : "";
$smarty->assign("msgErro", $msgRet);
}
}
}
function ExisteContribuinte($id, &$msg) {
$sql = "select count(*) from pbx_cliente where client_documento = '$id'";
$result = pg_query($sql);
$row = @pg_fetch_row($result);
if ($row[0] > 0) {
$msg[] = "Identificação já cadastrada!";
return true;
}
return false;
}
?>

357
cadastros/cliente/contribSelect.php

@ -1,357 +0,0 @@
<?php
$paramPesquisa = isset($_REQUEST['paramPesquisa']) ? $_REQUEST['paramPesquisa'] : '';
$filtro = trim(isset($_REQUEST["paramPesquisa"]) ? trim($_REQUEST["paramPesquisa"]) : '');
$cloid = trim(isset($_REQUEST["clo_id"]) ? trim($_REQUEST["clo_id"]) : '');
$clientTipoContato = trim(isset($_REQUEST["client_tipo_contato"]) ? trim($_REQUEST["client_tipo_contato"]) : '');
$clientEtapa = ($_REQUEST["client_etapa"] != "-1") ? trim($_REQUEST["client_etapa"]) : '1';
$clientStatus = ($_REQUEST["client_status"] != "-1") ? trim($_REQUEST["client_status"]) : '-1';
$clientUf = trim(isset($_REQUEST["client_uf"]) ? trim($_REQUEST["client_uf"]) : '');
$clientAgenda = trim(isset($_REQUEST["client_agenda"]) ? trim($_REQUEST["client_agenda"]) : '');
$dataIni = isset($_REQUEST['dataIni']) && is_date($_REQUEST['dataIni']) ? $_REQUEST['dataIni'] : '';
$dataFim = isset($_REQUEST['dataFim']) && is_date($_REQUEST['dataFim']) ? $_REQUEST['dataFim'] : '';
$tipoDataSet = isset($_REQUEST['tipoDataSet']) ? $_REQUEST['tipoDataSet'] : 'Contato';
$client_user_contato = isset($_REQUEST['client_user_contato']) ? $_REQUEST['client_user_contato'] : '';
/**
* Dados para ser passado via AJAX
*/
$action = isset($_GET['action']) ? $_GET['action'] : null;
$ajax = isset($_GET['ajax']) ? $_GET['ajax'] : null;
$data = isset($_GET['data']) ? $_GET['data'] : null;
if ($ajax && $action) {
if ($action == 'sendmail') {
echo enviarMailCampanha($data, $dbcon);
}
if ($action == 'addvendamais') {
$conn = ConectaMssql();
echo ExportaContato($conn, $data);
}
exit();
}
if (!isset($acao)) {
$acao = FORM_SELECT;
}
$filtroNovo = !isset($_REQUEST["pgn"]) ? '' : sprintf("&paramPesquisa%s&pgn=%s&bloco=%s&pg=%s", $_REQUEST["paramPesquisa"], $_REQUEST["pgn"], $_REQUEST["bloco"], $_REQUEST["pg"]);
$recontaPag = ($acao == 'inseri') || (GetFormAcao() == FORM_DELETE) || isset($_POST['pesquisa']);
$refresh = false;
if (GetFormAcao() == FORM_DELETE) {
$client_id = $_GET["id"];
$query = "delete from pbx_cliente where client_id = $client_id";
$result = pg_query($dbcon, $query);
if ($result) {
$msgRet = "Registro excluido com sucesso!";
} else {
$msgRet = "Não foi possível excluir o registro!";
}
$jsStartup[] = "alert('$msgRet')";
$refresh = true;
}
$template = 'contribuinteSelect.tpl';
$linha = "";
$numReg = 0;
$msgErro = "";
$acaoForm = FORM_SELECT;
$selContrib = (isset($_GET["selContrib"]) && $_GET["selContrib"]) || (isset($_POST["selContrib"]) && $_POST["selContrib"]);
if ($selContrib) {
$tpLayout = 1;
$wTab = "100%";
$tForm = GetNomeCadCli();
$_SESSION["selContrib"] = true;
}
$consulta = $selContrib && isset($_GET["fone"]) ? soNumero($_GET["fone"]) : $filtro;
$_SESSION["paramPesquisa"] = $filtro;
//if ((isset($_POST['pesquisa']) && $_POST['pesquisa']) || ($selContrib)) {
if ($filtro) {
$compl = PreparaLike($filtro, true);
$compl = sprintf("AND (a.client_razao_social ILIKE %s OR "
. "client_nome_contato ILIKE %s "
. "OR sonumero(a.client_telefone) ILIKE %s OR "
. "client_obs ILIKE %s OR "
. "client_municipio ILIKE %s OR "
. "apelido ILIKE %s OR "
. "client_email ILIKE %s OR "
. "client_id IN (SELECT client_id FROM pbx_cliente_anotacoes WHERE cla_anotacao ILIKE %s))\n", $compl, $compl, $compl, $compl, $compl, $compl, $compl, $compl);
}
if ($clientEtapa) {
$compl .= "\n AND a.cletp_id = '{$clientEtapa}' \n";
}
if ($clientStatus != '-1') {
$clientStatus = !$clientStatus ? '0' : $clientStatus;
$compl .= " AND client_status = '{$clientStatus}' \n";
}
if ($clientUf) {
$compl .= " AND client_uf = '{$clientUf}' \n";
}
if ($clientTipoContato) {
$compl .= " AND client_tipo_contato = '{$clientTipoContato}' \n";
}
if ($cloid) {
$compl .= " AND a.clo_id = '{$cloid}' AND cmp_id IS NOT NULL \n";
}
if ($client_user_contato) {
$compl .= " AND client_user_contato = '$client_user_contato' ";
}
if (GetMatricula()) {
$compl .= sprintf("\n AND (client_user_contato = '%s' OR b.cfr_id IN (SELECT x.cfr_id FROM pbx_fornecedor_permissao x WHERE matricula_permissao = '%s'))", GetMatricula(), GetMatricula());
}
//$tipoData = (strtoupper($tipoDataSet) == 'CONTATO') ? 'client_data_contato' : 'client_agendamento';
$tipoData = "client_update";
if (is_date($dataIni) && is_date($dataFim)) {
$compl .= sprintf(" AND {$tipoData}::DATE >= '%s' and {$tipoData}::date <= '%s' \n", FormatDtMssql($dataIni), FormatDtMssql($dataFim));
} else if (is_date($dataIni)) {
$compl .= sprintf(" AND {$tipoData}::DATE >= '%s' \n", FormatDtMssql($dataIni));
} else if (is_date($dataFim)) {
$compl .= sprintf(" AND {$tipoData}::DATE <= '%s' \n", FormatDtMssql($dataFim));
}
$query = "SELECT client_ref_id, client_out_id, client_id, client_tipo_documento, client_documento, ctst_nome, client_razao_social, client_nome_fantasia,
client_municipio, client_uf, client_telefone, client_email, client_nome_contato, client_fone_contato,
client_email_contato, client_obs, client_tipo_contato, client_data_contato, d.apelido,
client_user_contato, client_agendamento, a.cletp_id, f.cletp_descricao, client_status,
(SELECT apelido FROM pbx_usuarios WHERE id = a.user_reg) as modificado
FROM pbx_cliente a
INNER JOIN pbx_cliente_origem b ON a.clo_id = b.clo_id
INNER JOIN pbx_cliente_fornecedor c ON b.cfr_id = c.cfr_id
inner join pbx_cliente_etapa f on f.cletp_id = a.cletp_id
LEFT JOIN pbx_usuarios d on d.matricula = a.client_user_contato
LEFT JOIN pbx_campanha_contato_status e ON e.ctst_id = a.client_status::int
WHERE 1=1 $compl ORDER BY client_razao_social";
$_SESSION['SSQueryClient'] = $query;
$params = "&paramPesquisa=$filtro&client_tipo_contato=$clientTipoContato&client_etapa=$clientEtapa&client_status=$clientStatus&client_uf=$clientUf&dataIni=$dataIni&dataFim=$dataFim&client_user_contato=$client_user_contato&clo_id=$cloid";
$links = PaginaDados($idProg, $query, $params, $regPagina, $offSet, $pagMostra, true);
$query .= " LIMIT $regPagina OFFSET $offSet";
// echo $query; exit;
$result = pg_query($dbcon, $query);
while ($row = @pg_fetch_array($result)) {
$client_id = $row["client_id"];
$client_tipo_documento = $row["client_tipo_documento"];
$client_documento = $row["client_documento"];
$cletp_descricao = $row["cletp_descricao"];
$client_status = $row["ctst_nome"];
$client_data_contato = substr(FormataDBDataHora($row["client_data_contato"]), 0, 10);
$client_agendamento = FormataDBDataHora($row["client_agendamento"]);
$client_razao = $row["client_razao_social"];
$client_razao_social = GetLinkFormUpdate("&id=$client_id", "cadCliente", "", 0, 1, $row["client_razao_social"]);
$client_nome_fantasia = $row["client_nome_fantasia"];
$client_nome_contato = $row["client_nome_contato"];
$client_municipio = $row["client_municipio"];
$client_uf = $row["client_uf"];
$client_telefone = $row["client_telefone"];
$client_email = $row["client_email"];
$client_tipo_contato = $row["client_tipo_contato"];
$client_usercontato = $row["modificado"];
$client_agente = $row["apelido"];
$client_class = $row["clit_descricao"];
$acaoApaga = GetLinkFormDelete($client_id . "|" . $params, 'DeletaContribuinte');
$acaoAtualiza = GetLinkFormUpdate("&id=$client_id", 'cadCliente');
$clientOutId = ($client_status == '446') ? $row["client_out_id"] : 0;
list($nomeDisp) = explode(" ", $row["client_razao_social"]);
$discar = RemoveDddPadrao($client_telefone);
$acao = "<img src=\"imgSite/ramalOn16.png\" border=\"0\" width=\"16\" height=\"16\" alt=\"Ligar para o cliente: $nomeDisp\" title=\"Ligar para o cliente: $nomeDisp\">";
if ($row["client_email"]) {
$mailsend = "<a href=\"javaScript:NovaJanela('index.php?idProg=349&client_id={$row["client_id"]}', 'clientMail', '1250', '750', 'jhTela')\"><img src=\"imgSite/mail16.png\" border=\"0\" width=\"16\" height=\"16\" alt=\"Enviar E-mail: $nomeDisp\" title=\"Enviar E-mail: $nomeDisp\"></a>";
} else {
$mailsend = "<img src=\"imgSite/email-no.png\" border=\"0\" width=\"16\" height=\"16\" title=\"O contato Não possui email cadastrado: $nomeDisp\">";
}
if ($row["client_email"] && $row["client_telefone"] && $row["client_status"] == '13') {
$vendamais = "<a href='#' onclick=\"sendContribuiente('{$row["client_out_id"]}', 'addvendamais')\"><img src=\"imgSite/vendamais.png\" border=\"0\" width=\"16\" height=\"16\" alt=\"Exportar o registro no Venda+: $nomeDisp\" title=\"Exportar o registro no Venda+: $nomeDisp\"></a>";
} else {
$vendamais = '<img src="imgSite/vendamais-no.png" border="0" width="16" height="16" title="Contato possui pendencia para ser Exportado!">';
}
$sound = sprintf("<a href=\"javaScript:NovaJanela('index.php?idProg=347&client_id={$row["client_id"]}&n=%s', 'audioContato', '1250', '500', 'jhTela')\"><img src=\"imgSite/sound22.png\" border='0' width='16' height='16' title='Áudios do cliente!'></a>", base64_encode($row['client_nome_fantasia']));
$linkRamal = "<a href=\"javaScript:RetornaAbd('$discar',{$row["client_id"]});\">$acao</a>";
$janH = 650;
$anotacoesCliente = GetLinkFormAction("jnAnotacoes", FORM_SELECT, 46, "imgSite/Comment.png", "client_id={$client_id}&client_razao={$client_razao}&client_out_id={$clientOutId}", "");
$linha .= "<tr>
<td align=\"right\">$client_id</td>
<td align=\"left\">$client_data_contato</td>
<td align=\"left\">$client_agendamento</td>
<td align=\"left\">$client_razao_social</td>
<td align=\"left\">$cletp_descricao</td>
<td align=\"left\">$client_status</td>
<td align=\"left\">$client_municipio</td>
<td align=\"left\">$client_uf</td>
<td align=\"left\">$client_nome_contato</td>
<td align=\"left\">$client_telefone</td>
<td align=\"left\">$client_email</td>
<td align=\"left\">$client_tipo_contato</td>
<td align=\"left\">$client_agente</td>
<td align=\"left\">$client_usercontato</td>
<td width=\"20\" style=\"border-right: 0\" align=\"center\">$mailsend</td>
<td width=\"20\" style=\"border-left: 0\" align=\"center\">$vendamais</td>
<td width=\"20\" style=\"border-left: 0\" align=\"center\">$anotacoesCliente</td>
<td width=\"20\" style=\"border-left: 0\" align=\"center\">$sound</td>
<td width=\"20\" align=\"center\">$acaoAtualiza</td>
</tr>";
//<td width=\"20\" style=\"border-left: 0\" align=\"center\">$acaoApaga</td>
$numReg++;
}
$imgCampEmail = "<a href=\"javaScript:NovaJanela('index.php?idProg=349&cmp=1', 'clientMail', '1250', '750', 'jhTela')\"><img src=\"imgSite/Message.png\" border=\"0\" width=\"16\" height=\"16\" align=\"absmiddle\" alt=\"Criar campanha com a lista de contatos selecionados na tela\" title=\"Criar campanha com a lista de contatos selecionados na tela\"> Campanha Email</a>";
$imgNovo = GetLinkFormInsert("cadCliente", 'images/novo.gif', $filtroNovo, ' Novo Registro');
$imgUpdate = '<a href="javaScript:NovaJanela(\'index.php?idProg=338\', \'novaListaCliente\', \'500\', \'500\', \'jhTela\')"><img src="imgSite/Update.png" width="16px" border="0" align="absmiddle" /> Nova Lista</a>';
$smarty->assign("list_cliente", GetClienteLista($cloid));
$smarty->assign("client_tipo_contato", GetClientTipoContato($clientTipoContato));
$smarty->assign("client_etapa", GetEtapaProspect($clientEtapa));
$smarty->assign("client_status", GetStatusProspect($clientStatus, true));
$smarty->assign("client_uf", GetClientUf($clientUf, true));
$smarty->assign("tipoDataSet", $tipoDataSet);
$smarty->assign("dataIni", $dataIni);
$smarty->assign("dataFim", $dataFim);
$smarty->assign("linhas", $linha);
$smarty->assign("paramPesquisa", $paramPesquisa);
$smarty->assign("imgCampEmail", $imgCampEmail);
$smarty->assign("imgNovo", $imgNovo);
$smarty->assign("imgUpdate", $imgUpdate);
$smarty->assign("links", $links);
$smarty->assign("pagMostra", $pagMostra);
$smarty->assign("totalReg", $totalReg);
$smarty->assign("pgn", $_REQUEST["pgn"]);
$smarty->assign("bloco", $_REQUEST["bloco"]);
$smarty->assign("pg", $_REQUEST["pg"]);
$smarty->assign("agentes", (PermissaoAdminCampanha(GetMatricula()) ? AgenteCampanha($client_user_contato) : ''));
function enviarMailCampanha($mail, $dbcon) {
$params = array();
$representante = GetUsuario($dbcon, GetMatricula());
$params['email_template'] = 'campanha_vendas.html';
$params['email_conta_envio'] = "vendas@simplesip.com.br";
$params['email_senha_envio'] = "SimpleS#Root@2021";
$params['email_retorno'] = "vendas@simplesip.com.br";
$params['email_template_info'] = array('NOME' => $representante['nome']);
$params['email_html'] = 'campanha_vendas.html';
$params['email_envio'] = $mail;
$params['email_assunto'] = 'Transforme agora em seu Callcenter';
if (SendEmail($params)) {
$msg = "Email enviado com sucesso!";
sendedMail($dbcon, $mail);
} else {
$msg = "Não foi possível realizar o envio!";
}
return $msg;
}
function sendedMail($conn, $mail) {
$query = "UPDATE pbx_cliente SET client_status = '16' WHERE client_email = '{$mail}';";
pg_query($conn, $query);
}
function ExportaContato($conn, $outid) {
try {
$dados = getContatoLead($outid);
if (!$dados) {
throw new Exception("Este contato ainda possui pendencias para ser exportado!");
}
$msql = ConectaMssql();
if (!mssql_query('begin tran', $conn)) {
throw new Exception("Nao foi possivel inciar uma trasacao com o Venda+.");
}
//@dataEnvio, @VendedorId, @RazaoSocial, @Email, @Telefone, @TipoPessoa, @CGC_CPF, @RegiaoId, @uf, @municipio, @ClienteStatusId, @ClienteIdExterno, @NomeContato
$query = sprintf("EXEC dbo.sip_insert_prospect '%s','%s',%s,%s,'%s','%s','%s',%s,'%s',%s,'%s','%s', %s, '%s'",
$dados['conf_data'], $dados['vendedor_id'],
QuotedStr($dados['client_razao_social']), QuotedStr($dados['client_email']),
$dados['client_telefone'], ($dados['client_tipo_pessoa'] == "CNPJ" ? "J" : "F"),
trim($dados['client_documento']),
QuotedStr($dados['client_regiao']), $dados['client_uf'], QuotedStr($dados['client_municipio']),
"EM PROSPECÇÃO", $dados['client_id'], QuotedStr($dados['client_nome_contato']), GetMatricula());
if (!$result = mssql_query($query, $conn)) {
throw new Exception("Não foi possível exportar o contato.\n{$query}\n");
}
if (!$data = mssql_fetch_row($result)) {
throw new Exception("Não foi possível consultar o contato no VM.\n{$query}\n");
}
if (!mssql_query('commit tran', $conn)) {
throw new Exception("Nao foi possivel inciar uma trasacao com o Venda+.");
}
mssql_close($msql);
AtulizaContatoVendaMais($outid, $data[0]);
return "Contato Exportado com sucesso! Contato ID: " . $data[0];
} catch (Exception $ex) {
mssql_query('rollback tran', $conn);
return $ex->getMessage();
}
}
function getContatoLead($outid = null) {
$query = "SELECT client_data_contato, client_razao_social,
client_email_contato, client_fone_contato, client_tipo_contato, client_documento,
client_endereco, client_uf, client_municipio, client_status, client_id, client_nome_contato, client_user_contato,
(select reg_sigla from mkt_regiao_estados where reg_uf = b.client_uf) as client_regiao
FROM pbx_cliente b
WHERE client_status = '13' ";
if ($outid) {
$query .= " AND client_out_id = '$outid' ";
}
$result = pg_query($query);
$resp = pg_fetch_assoc($result);
$rs = GetCodVendedor($resp['client_user_contato']);
$resp['vendedor_id'] = $rs['cod_vendedor'];
$resp['conf_data'] = date('Y-m-d H:i:s');
return $resp;
}
function GetCodVendedor($clientUserContato) {
$query = sprintf("SELECT * FROM pbx_cliente_referencia_vendedor WHERE matricula = '%s'", $clientUserContato);
$result = pg_query($query);
$resp = pg_fetch_assoc($result);
if (!$resp) {
throw new Exception('Você não possui nenhum vendedor referenciado!');
}
return $resp;
}
function AtulizaContatoVendaMais($outid, $idvenda) {
$query = sprintf("UPDATE pbx_cliente SET client_out_id = '{$idvenda}', client_status = '21', user_reg = %s, client_update = NOW() WHERE client_out_id = '$outid';", GetIdUser());
$result = pg_query($query);
if (!$result) {
throw new Exception('Não foi possível atualizar o registro de exportação');
}
}
?>

304
cadastros/cliente/contribUpdate.php

@ -1,304 +0,0 @@
<?php
$template = "contribuinte.tpl";
$tpLayout = 1;
$offSet = 0;
$refresh = isset($_GET['refresh']) ? true : false;
define('CONF_PATH_INTEGRACAO', '/var/lib/asterisk/scripts/integracao/custom/GoogleCalendar/');
define('CONF_PATH_CLASS', 'GoogleCalendar.php');
define('CONF_PATH_CREDENTIALS', 'credentials.json');
define('CONF_PATH_TOKEN', 'token.json');
define('CONF_STATUS_EXPORTADO', 21);
include CONF_PATH_INTEGRACAO . CONF_PATH_CLASS;
if (GetFormAcao() == FORM_UPDATE) {
$acaoForm = FORM_SAVE;
$id = $_GET["id"] ? $_GET["id"] : $_POST['client_id'];
$query = "SELECT client_id,
CASE WHEN(COALESCE(client_tipo_documento, '') = '')THEN 'CNPJ' ELSE client_tipo_documento END AS client_tipo_documento,
client_documento, client_razao_social,client_municipio, client_uf, client_nome_contato, client_status, client_email,
client_telefone, client_obs, client_tipo_contato, client_agendamento, client_class, client_update, (SELECT apelido FROM pbx_usuarios WHERE id = user_reg) as modificado
FROM pbx_cliente
WHERE client_id = {$id}";
$result = pg_query($dbcon, $query);
$row = @pg_fetch_array($result, null, PGSQL_ASSOC);
list($nomeDisp) = explode(" ", $row["client_razao_social"]);
if ($row['client_agendamento']) {
$discar = RemoveDddPadrao($row['client_telefone']);
$acao = "<img src=\"imgSite/ramalOn16.png\" border=\"0\" width=\"16\" height=\"16\" alt=\"Ligar para o cliente: $nomeDisp\" title=\"Ligar para o cliente: $nomeDisp\">";
$linkRamal = "<a href=\"javaScript:RetornaAbd('$discar',{$row["client_id"]});\">$acao</a>";
}
/** ENVIAR EMAIL * */
if ($row["client_email"]) {
$mailsend = "<a href='#' onclick=\"sendContribuiente('{$row["client_email"]}','sendmail')\"><img src=\"imgSite/mail16.png\" border=\"0\" width=\"16\" height=\"16\" alt=\"Enviar E-mail: $nomeDisp\" title=\"Enviar E-mail: $nomeDisp\"></a>";
} else {
$mailsend = "<img src=\"imgSite/email-no.png\" border=\"0\" width=\"16\" height=\"16\" title=\"O contato Não possui email cadastrado: $nomeDisp\">";
}
/** CONTATOS */
$contatos = "<a href=\"javaScript:NovaJanela('index.php?idProg=346&client_id={$row["client_id"]}', 'contatosCliente', '900', '250', 'jhTela')\"><img src=\"imgSite/User group.png\" border=\"0\" width=\"16\" height=\"16\" alt=\"Contatos do cliente ID: $nomeDisp\" title=\"Contatos do cliente ID: $nomeDisp\"></a>";
$row["client_agenda"] = $row["client_agendamento"] ? date('d/m/Y H:i', strtotime($row["client_agendamento"])) : '';
$row["client_status"] = GetStatusProspect($row["client_status"], false, ($refresh || $row["client_status"] == CONF_STATUS_EXPORTADO ? TRUE : FALSE));
$row["client_tipo_contato"] = GetClientTipoContato($row["client_tipo_contato"]);
$row["client_update"] = $row["client_update"] ? date('d/m/Y H:i:s', strtotime($row["client_update"])) : '-';
/**
* TABELA ANOTAÇÃO
*/
$query1 = "SELECT cla_id, cla_anotacao, apelido, data_reg FROM pbx_cliente_anotacoes a "
. "INNER JOIN pbx_usuarios b ON b.matricula::int = a.user_reg "
. "WHERE client_id = '{$id}' ORDER BY data_reg DESC\n";
$sql = GetTotalRegistro($dbcon, $query1);
$params = sprintf("&client_id=%s&client_razao=%s", $id, $row['client_razao_social']);
$links = PaginaDados($idProg, $sql, $params, $regPagina, $offSet, $pagMostra, true);
$query1 .= " LIMIT $regPagina OFFSET $offSet";
$res = pg_query($dbcon, $query1);
$data = pg_fetch_all($res);
$tblAnota = '';
foreach ($data as $anota) {
$tblAnota .= "<tr>";
$tblAnota .= sprintf("<td>%s</td>", date('d/m/Y H:i:s', strtotime($anota['data_reg'])));
$tblAnota .= sprintf("<td>%s</td>", $anota['apelido']);
$tblAnota .= sprintf("<td>%s</td>", $anota['cla_anotacao']);
$tblAnota .= "</tr>";
}
$smarty->assign("links", $links);
$smarty->assign("pagMostra", $pagMostra);
$smarty->assign("totalReg", $totalReg);
$smarty->assign('anotacao', $tblAnota);
$smarty->assign('mailsend', $mailsend);
$smarty->assign('contatos', $contatos);
$smarty->assign('linkRamal', $linkRamal);
$smarty->assign('sound', $sound);
if ($result) {
//valores no form
foreach ($row as $key => $value) {
$smarty->assign($key, $value);
}
} else {
$acaoForm = FORM_INSERT;
$msgRet = "A operação não pode ser realizada!";
$jsStartup[] = "alert('$msgRet');";
$msgRet .= pg_last_error() ? " Erro: " . pg_last_error() : "";
$smarty->assign("msg", $msgRet);
}
} else {
$msgForm = array();
if (!validaForm($fields, $fieldsObrig, $fieldsType, $fieldsDiplay, $msgForm)) {
$acaoForm = FORM_SAVE;
//formata mensagem de erro para script
$msgRet = "";
foreach ($msgForm as $value) {
$msgRet .= "\\n" . $value;
}
$jsStartup[] = "alert('$msgRet');";
//formata mensagem de erro para o form
$msgRet = "";
foreach ($msgForm as $value) {
$msgRet .= $value . " ";
}
//erros no form
$smarty->assign("msgErro", $msgRet);
$_POST["client_status"] = GetStatusProspect($_POST["client_status"], false, $refresh);
$_POST["client_tipo_contato"] = GetClientTipoContato($_POST["client_tipo_contato"]);
//valores no form
foreach ($fields as $value) {
$smarty->assign($value, $_POST[$value]);
}
} else {
$acaoForm = FORM_SAVE;
$id = $_POST["client_id"];
$nome = QuotedStr(strtoupper($_POST["client_nome_contato"]));
$status = isset($_POST["client_status"]) ? QuotedStr($_POST["client_status"]) : null;
$tpContato = QuotedStr($_POST["client_tipo_contato"]);
$tpDoc = QuotedStr($_POST["client_tipo_documento"]);
$doc = sonumero($_POST["client_documento"]);
$doc = !$doc ? "null" : QuotedStr($doc);
$email = trim($_POST["client_email"]);
$email = !$email ? "null" : QuotedStr($email);
$fone = sonumero($_POST["client_telefone"]);
$fone = !$fone ? "null" : QuotedStr($fone);
if (!$_POST["client_agenda"]) {
$agendamento = 'null';
} else {
$agendamento = strlen($_POST["client_agenda"]) == 10 ? QuotedStr(FormatDtMssql($_POST["client_agenda"]) . " 00:00") : QuotedStr(FormatDtMssql(substr($_POST["client_agenda"], 0, 10)) . substr($_POST["client_agenda"], 10, 16));
}
$user_contato = QuotedStr(GetMatricula());
$obs = trim($_POST["client_obs"]);
$obs = !$obs ? null : QuotedStr($obs);
$user_reg = GetIdUser();
/*
* Atribui uma nova etapa de acordo com o status.
*/
$client_etapa = GetClienteEtapa($_POST["client_status"]);
$query = "update pbx_cliente
set client_tipo_documento = {$tpDoc},
client_documento = {$doc},
client_nome_contato = {$nome},$client_etapa";
if (isset($_POST["client_status"])) {
$query .= "client_status = {$status},";
}
if ($status != CONF_STATUS_EXPORTADO && $status) {
$query .= "user_reg = {$user_reg}, client_update = now(),";
}
$query .= "client_email = {$email},
client_telefone = {$fone},
client_tipo_contato = {$tpContato},
client_agendamento = {$agendamento}
where client_id = {$id} ";
$result = pg_query($dbcon, $query);
if ($obs) {
$sql = "INSERT INTO pbx_cliente_anotacoes (client_id, cla_anotacao, user_reg) VALUES(%s, %s, %s);";
$sql = sprintf($sql, $id, $obs, $user_contato);
pg_query($dbcon, $sql);
}
atualizaContato($dbcon, $_POST["client_id"], $nome, $fone, $email);
//valores no form
foreach ($fields as $value) {
if (array_search($value, $_POST) !== false) {
$smarty->assign($value, $value == "client_id" ? $id : $_POST[$value]);
}
}
if ($result) {
if ($_POST['intg_agenda'] && $_POST["client_agenda"] && $_POST['client_razao_social']) {
integCalendar($_POST["client_agenda"], $_POST['client_razao_social'], trim('desenv02@simplesip.com.br'));
}
$msgRet = "Registro alterado com sucesso!";
$jsStartup[] = "alert('$msgRet');";
$smarty->assign("msg", $msgRet);
if (!$_GET['refresh']) {
$jsStartup[] = "window.opener.ResetForm();";
}
$jsStartup[] = "window.close();";
} else {
$msgRet = "A operação não pode ser realizada!";
$jsStartup[] = "alert('$msgRet');";
$msgRet .= pg_last_error() ? (IsAdmin() ? " Erro: " . pg_last_error() : "") : "";
$smarty->assign("msg", $msgRet);
}
}
}
function atualizaContato($dbcon, $cliente, $nome, $fone, $email = 'null') {
$query = "SELECT clc_id FROM pbx_cliente_contato WHERE client_id = {$cliente} AND clc_contato_principal = 1;";
$result = pg_query($dbcon, $query);
$data = pg_fetch_assoc($result);
if ($data) {
$query = "UPDATE pbx_cliente_contato SET clc_nome = {$nome}, clc_email = {$email}, clc_fone = {$fone} WHERE clc_id = {$data['clc_id']};";
pg_query($dbcon, $query);
}
}
function integCalendar($agenda, $empresa, $email) {
if ((file_exists(CONF_PATH_INTEGRACAO . CONF_PATH_CLASS) && (file_exists(CONF_PATH_INTEGRACAO . CONF_PATH_TOKEN)) && (file_exists(CONF_PATH_INTEGRACAO . CONF_PATH_CREDENTIALS)))) {
$formtData = strlen($agenda) == 10 ? FormatDtMssql($agenda) . " 00:00" : FormatDtMssql(substr($agenda, 0, 10)) . substr($agenda, 10, 16);
$emails = GetAllMailAdmin();
$emails[]['email'] = $email;
$gg = new GoogleCalendar();
$gg->getClient();
$dataIni = date('Y-m-d\TH:i:s-04:00', strtotime($formtData));
$dataFim = date('Y-m-d\TH:i:s-04:00', strtotime($formtData . ' +1 hours'));
$link = $gg->createEventCalendar(
'APRESENTACAO COM ' . RemoveAcentos($empresa),
'AGENDAMENTO DA APRESENTACAO DOS PRODUTOS SIMPLES IP',
$dataIni,
$dataFim,
$emails
);
return $link;
}
}
function GetClienteEtapa($status) {
$query = " select ctst_nome from pbx_campanha_contato_status where ctst_id = '$status';\n";
$result = pg_query($query);
$data = pg_fetch_row($result);
$statusAtual = $data[0];
$novaEtapa = '';
switch ($statusAtual) {
case "NOVO": $novaEtapa = 'VALIDACAO';
break;
case "ATENDIDA":
case "NÃO ATENDIDA":
case "ELETRÔNICA":
case "MUDA":
case "OCUPADA":
case "DESLIGOU":
case "CLIENTE":
case "PROSPECT":
case "LEAD":
case "ENVIADO":
case "AGENDADO":
case "INTERESSE":
case "CONTABILIDADE": $novaEtapa = 'PROSPECCAO';
break;
case "NÃO ENVIAR":
case "RESPONDIDO" :
case "REPROCESSAR":
case "INVALIDO":
case "SEM INTERESSE":
case "EXCLUIR":
case "EXPORTADO":
case "REMOVER": $novaEtapa = 'FINALIZACAO';
break;
}
$query = "select cletp_id from pbx_cliente_etapa where cletp_descricao = '$novaEtapa';\n";
$result = pg_query($query);
if (!$result || !pg_num_rows($result)) {
return '';
}
$data = pg_fetch_row($result);
return sprintf("\ncletp_id = '%s',", $data[0]);
}
?>

304
cadastros/cliente/contribuinte.php

@ -1,304 +0,0 @@
<?php
/*
* variavel que vai conter o template
*/
//VerificaPerfilAcesso(SEG_CONTRIBUINTE);
$template = "contribuinteSelect.tpl";
/*
* fields correspondem aos campos retornados da consulta
*/
$fields = array("client_id", "client_tipo_documento", "client_documento", "client_razao_social", "client_municipio", "client_uf", "client_nome_contato", "client_status", "client_email", "client_telefone", "client_obs");
//$fields = array("client_id", "client_razao_social", "client_nome_contato", "client_status", "contrib_email", "client_telefone");
//
//-- DROP TABLE pbx_cliente;
//
//CREATE TABLE pbx_cliente
//(
// client_id bigserial NOT NULL,
// client_tipo_documento character varying(16) NOT NULL DEFAULT 'CPF'::character varying,
// client_documento character varying(64),
// client_status character varying(32),
// client_razao_social character varying(128) NOT NULL,
// client_razao_fantasia character varying(128),
// client_telefone character varying(32),
// client_email character varying(128),
// client_nome_contato character varying(128) NOT NULL,
// client_fone_contato character varying(32),
// client_email_contato character varying(128),
// client_obs text,
// client_data timestamp without time zone NOT NULL DEFAULT now(),
// client_update timestamp without time zone,
// CONSTRAINT pbx_cliente_pkey PRIMARY KEY (client_id)
//);
/*
* nome das colunas que vão aparecer na consulta
*/
$fieldsDiplay = array();
$fieldsDiplay["client_id"] = "ID";
$fieldsDiplay["client_tipo_documento"] = "Tipo de Documento";
$fieldsDiplay["client_documento"] = "Documento";
$fieldsDiplay["client_status"] = "Status";
$fieldsDiplay["client_razao_socia"] = "Razão Social";
$fieldsDiplay["client_nome_fantasia"] = "Nome de Fantasia";
$fieldsDiplay["client_telefone"] = "Telefone";
$fieldsDiplay["client_email"] = "Email";
$fieldsDiplay["client_nome_contato"] = "Responsável";
$fieldsDiplay["client_fone_contato"] = "Fone Responsável";
$fieldsDiplay["client_email_contato"] = "E-mail Responsável";
$fieldsDiplay["client_obs"] = "Obs";
$fieldsDiplay["client_tipo_contato"] = "Contatar";
/*
* campos obrigatorios usados na funcao validaForm
*/
$fieldsObrig = array();
$fieldsObrig["contrib_razao_social"] = 1;
//$fieldsObrig["client_status"] = 1;
//$fieldsObrig["client_documento"] = 1;
/*
* identifica o tipo do dado
*/
$fieldsType = array();
$fieldsType["client_id"] = TYPE_INTEGER;
$fieldsType["client_tipo_documento"] = TYPE_STRING;
$fieldsType["client_documento"] = TYPE_STRING;
$fieldsType["client_status"] = TYPE_STRING;
$fieldsType["client_razao_socia"] = TYPE_STRING;
$fieldsType["client_nome_fantasia"] = TYPE_STRING;
$fieldsType["client_municipio"] = TYPE_STRING;
$fieldsType["client_uf"] = TYPE_STRING;
$fieldsType["client_telefone"] = TYPE_FONE;
$fieldsType["client_email"] = TYPE_EMAIL;
$fieldsType["client_nome_contato"] = TYPE_STRING;
$fieldsType["client_fone_contato"] = TYPE_FONE;
$fieldsType["client_email_contato"] = TYPE_EMAIL;
$fieldsType["client_obs"] = TYPE_STRING;
/*
* Valores para o form
*/
$fielsValues = array();
/*
* TIPO DE INDENTIFICAÇÃO
*/
define("CONTRIB_TIPO_CPF", 'CPF');
define("CONTRIB_TIPO_CRC", 'CRC');
define("CONTRIB_TIPO_IE", 'IE');
define("CONTRIB_TIPO_CNPJ", 'CNPJ');
define("CONTRIB_TIPO_OUTROS", 'Outro');
//define tamanho da janela de cadastro
$janW = 500;
$janH = 260;
if ((GetFormAcao() == FORM_SELECT) || (GetFormAcao() == FORM_DELETE)) {
include("cadastros/cliente/contribSelect.php");
} else if ((GetFormAcao() == FORM_NEW) || (GetFormAcao() == FORM_INSERT)) {
$tpLayout = 1;
include("cadastros/cliente/contribInsert.php");
} else if ((GetFormAcao() == FORM_UPDATE) || (GetFormAcao() == FORM_SAVE)) {
$tpLayout = 1;
include("cadastros/cliente/contribUpdate.php");
}
//variaveis para o template
$smarty->assign("selContrib", isset($selContrib) ? $selContrib : "" );
$smarty->assign("tForm", isset($tForm) ? $tForm : "");
$smarty->assign("wTab", isset($wTab) ? $wTab : '' );
$smarty->assign("formAction", isset($acaoForm) ? $acaoForm : '' );
$smarty->assign("formAcaoDesc", GetFormAcaoDesc($acaoForm));
$smarty->assign("nomeCadCli", GetNomeCadCli());
/*
* Carrega o template correspondente ao cadastro
*/
GetTemplate($smarty, $template);
/**
* FUNÇÃO PARA RETORNAR A ETAPA EM QUE O LEAD SE ENCONTRA
* @param type $etapa
* @param type $semEtapa
* @return string
*/
function GetEtapaProspect($etapa, $readonly = false) {
$readonly = $readonly ? 'disabled="true"' : '';
$serv = "<select name=\"client_etapa\" id=\"client_etapa\" size=\"1\" {$readonly}>";
$sel = !$etapa ? 'selected="selected"' : "";
$serv .= sprintf('<option value="0" %s>----------------</option>', ($etapa == '0' ? : ''));
$query = "select cletp_id, cletp_descricao from pbx_cliente_etapa;";
$result = pg_query($query);
while ($dados = pg_fetch_row($result)) {
$sel = ($etapa === $dados[0]) ? 'selected="selected"' : "";
$serv .= "<option value=\"$dados[0]\" $sel>$dados[1]</option>";
}
$serv .= "</select>";
return $serv;
}
/**
* FUNÇÃO PARA RETORNAR O SELECT DOS STATUS DO CLIENTES
* @param type $status
* @param type $semStatus
* @return string
*/
function GetStatusProspect($status, $semStatus = false, $readonly = false) {
$readonly = $readonly ? 'disabled="true"' : '';
$serv = "<select name=\"client_status\" id=\"client_status\" size=\"1\" {$readonly}>";
$sel = "";
if ($semStatus) {
$serv .= sprintf('<option value="-1" %s>----------------</option>', ($status == '00' ? 'selected="selected"' : ''));
}
$query = sprintf("SELECT DISTINCT d.ctst_id, d.ctst_nome
FROM pbx_usuarios a
INNER JOIN pbx_grupo_usuario b ON a.id = b.user_id
INNER JOIN pbx_grupo_campanha_contato_status c ON b.gp_id = c.gp_id
INNER JOIN pbx_campanha_contato_status d ON c.ctst_id = d.ctst_id
WHERE matricula = '%s'
AND d.ctst_status = 1
ORDER BY ctst_nome", GetMatricula());
$result = pg_query($query);
while ($dados = pg_fetch_row($result)) {
if ($status === $dados[0]) {
$sel = "selected";
} else {
$sel = "";
}
$serv .= "<option value=\"$dados[0]\" $sel>$dados[1]</option>";
}
$serv .= "</select>";
return $serv;
}
function GetClientTipoContato($clientTipoContato) {
$tipos = array('TELEFONE', 'WHATSAPP', 'EMAIL', 'TELEGRAM', 'SMS', 'SKYPE');
$opt = "<select name=\"client_tipo_contato\" id=\"client_tipo_contato\" size=\"1\">";
$opt .= sprintf('<option value="0" %s>----------------</option>', (!$clientTipoContato ? 'selected="selected"' : ''));
foreach ($tipos as $tipo) {
$opt .= sprintf('<option value="%s" %s>%s</option>', $tipo, (($clientTipoContato == $tipo) ? 'selected="selected"' : ''), $tipo);
}
$opt .= "</select>";
return $opt;
}
function GetClientUf($clientUf) {
$tipos = array('AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MT', 'MS', 'MG', 'PA', 'PB', 'PR', 'PE', 'PI', 'RJ', 'RN', 'RS', 'RO', 'RR', 'SC', 'SP', 'SE', 'TO');
$opt = "<select name=\"client_uf\" id=\"client_tipo_contato\" size=\"1\">";
$opt .= sprintf('<option value="" %s>----------------</option>', (!$clientUf ? 'selected="selected"' : ''));
foreach ($tipos as $tipo) {
$opt .= sprintf('<option value="%s" %s>%s</option>', $tipo, (($clientUf == $tipo) ? 'selected="selected"' : ''), $tipo);
}
$opt .= "</select>";
return $opt;
}
function GetClassificacaoVendas($select = null) {
$query = "SELECT b.clit_id, b.clit_descricao, a.clas_status FROM pbx_classifica_atendimento a
INNER JOIN pbx_classifica_item b ON b.clas_id = a.clas_id
WHERE clas_descricao = 'CAMPANHA_TELEVENDAS'
AND clas_status = 1";
$result = pg_query($query);
$data = pg_fetch_all($result);
$opt = "<option value='0'>-------------</option>";
if ($data) {
foreach ($data as $clas) {
$selected = $select == $clas['clit_id'] ? 'selected' : '';
$opt .= "<option value='{$clas['clit_id']}' $selected> {$clas['clit_descricao']}</option>";
}
}
return $opt;
}
function SetDataAgendamento($id, $clientAgenda) {
$query = "UPDATE pbx_cliente SET client_agendamento = '{$clientAgenda}' WHERE client_id = {$id}";
pg_query($query);
if (pg_last_error()) {
throw new Exception('Não foi possível atualizar a DATA de Agendamento do cliente!');
}
return true;
}
function GetClienteLista($select = null) {
$query = "SELECT clo_id, clo_titulo FROM pbx_cliente_origem ";
$result = pg_query($query);
$data = pg_fetch_all($result);
$opt = "<select name=\"clo_id\" id=\"clo_id\" size=\"1\">";
$opt .= "<option value='0'>-------------</option>";
if ($data) {
foreach ($data as $clas) {
$selected = $select == $clas['clo_id'] ? 'selected' : '';
$opt .= "<option value='{$clas['clo_id']}' $selected> {$clas['clo_titulo']}</option>";
}
}
$opt .= "</select>";
return $opt;
}
function AgenteCampanha($select = null) {
$query = "SELECT DISTINCT id, nome, apelido, matricula FROM pbx_usuarios a
INNER JOIN pbx_grupo_usuario b ON a.id = b.user_id
INNER JOIN pbx_grupo_funcoes c ON c.gp_id = b.gp_id
WHERE b.gp_id IN(SELECT gp_id FROM (SELECT CASE WHEN(COUNT(gp_id) > 1) THEN gp_id END AS gp_id
FROM pbx_grupo_funcoes WHERE fun_id = 209 OR fun_id = 2
GROUP BY gp_id
ORDER BY 1) AS DATA)";
$result = pg_query($query);
$resp = pg_fetch_all($result);
$opt = "<select name=\"client_user_contato\" id=\"client_user_contato\" size=\"1\">";
$opt .= "<option value='0'>-------------</option>";
if ($resp) {
foreach ($resp as $val) {
$selected = $select == $val['matricula'] ? 'selected' : '';
$opt .= "<option value='{$val['matricula']}' $selected>{$val['apelido']}</option>";
}
}
$opt .= "</select>";
return $opt;
}
function PermissaoAdminCampanha($matricula) {
$query = "SELECT * FROM pbx_fornecedor_permissao WHERE matricula_permissao = '$matricula'";
$result = pg_query($query);
$resp = pg_fetch_assoc($result);
return $resp;
}
function GetAllMailAdmin(){
$query = "SELECT email FROM pbx_usuarios a
INNER JOIN pbx_fornecedor_permissao b ON b.matricula_permissao = a.matricula
WHERE email <> ''";
$result = pg_query($query);
$resp = pg_fetch_all($result);
return $resp;
}
function ConectaMssql() {
$dbhost = "192.168.115.28";
$dbname = "VendaMaisDB_simplesip";
$user = "sa";
$passwd = "SimpleS_root";
$conn = mssql_connect($dbhost, $user, $passwd);
mssql_select_db($dbname);
return $conn;
}
?>

120
cadastros/municipio/municipio.php

@ -1,120 +0,0 @@
<?php
//LIMPA VARIAVEIS
$Pesquisar = "";
$municipio = "";
$acao = "";
//Recebe
$Pesquisar = $_POST['pesquisar'];
$acao = $_GET['acao'];
$deletaMunicipio = 0;
//Deleta
if ($_GET['acao'] == "deletaMunicipio") {
$deletaMunicipio = 1;
$mun_id = $_GET['municipio'];
$sql = "DELETE FROM pbx_municipio_prefixo WHERE mun_id='$mun_id'";
$result = pg_query($dbcon, $sql);
$sql = "DELETE FROM pbx_municipio_classifica WHERE mun_id='$mun_id'";
$query = pg_query($dbcon, $sql);
}
//Pesquisa
if (IsPostBack() || $deletaMunicipio) {
if (isset($_POST['municipio'])) {
$_SESSION['ssMunicipioSearch'] = $_POST['municipio'];
$_SESSION['ssMunicipioUF'] = $_POST['UF'];
}
$municipio = isset($_POST['municipio']) ? $_POST['municipio'] : $_SESSION['ssMunicipioSearch'];
$recebe_uf = isset($_POST['UF']) ? $_POST['UF'] : $_SESSION['ssMunicipioUF'];
if (empty($municipio)) {
if ($recebe_uf == '0') {
$condicao = "";
} else {
$condicao = "WHERE uf='$recebe_uf'";
}
} else {
if ($recebe_uf == '0') {
$condicao = " WHERE mun_nome ILIKE '%$municipio%'";
} else {
$condicao = " WHERE mun_nome ILIKE '%$municipio%' AND uf='$recebe_uf'";
}
}
if (is_numeric($municipio)) {
if (strlen($municipio) == 2) {
$sql = pg_query($dbcon, "SELECT uf FROM pbx_municipio_classifica WHERE mun_ddd = $municipio");
while ($rowMUN = pg_fetch_array($sql)) {
$recebe_uf = $rowMUN['uf'];
}
$condicao = " WHERE mun_ddd='$municipio' AND uf='$recebe_uf'";
}
if (strlen($municipio) > 2) {
$busca = "SELECT mun_id FROM pbx_municipio_prefixo WHERE prx_prefixo ILIKE '%$municipio%' ";
$result = pg_query($dbcon, $busca);
while ($row = pg_fetch_array($result)) {
$mun_id = $row['mun_id'];
}
$condicao = "WHERE mun_id ILIKE '%$mun_id%'";
}
}
$sql = "SELECT mun_id,uf,mun_ddd,mun_nome FROM pbx_municipio_classifica $condicao ORDER BY mun_ddd,mun_nome ASC ";
} else {
$sql = "SELECT mun_id,uf,mun_ddd,mun_nome FROM pbx_municipio_classifica ORDER BY mun_ddd,mun_nome ASC ";
}
//IMPRIMI REGISTROS----
$result = pg_query($dbcon, $sql);
if (pg_num_rows($result) < 1) {
$municipio = $_POST['municipio'];
$uf = $_POST['uf'];
$busca = pg_query($dbcon, "SELECT mun_ddd FROM pbx_municipio_classifica WHERE uf='$recebe_uf'");
while ($x = pg_fetch_array($busca)) {
$ddd = $x['mun_ddd'];
}
$resultados = '
<td colspan="4" style="text-align:center;">Nenhum registro encontrado!</td>
<td colspan="2" style="text-align: center;"><a href="javaScript:NovaJanela(\'index.php?idProg=164&acao=in&ddd=' . $ddd . '&municipio=' . $municipio . '&uf=' . $recebe_uf . '\', \'CadastrodeMunicipio\', \'380\', \'220\', \'resizable=NO,scrollbars=1\');" title="Cadastrar um novo ramal"><img src="imgSite/novoUser.png" border="0"></td>';
}
$numero = 0;
while ($row = pg_fetch_array($result)) {
$numero++;
$mun_id = $row["mun_id"];
$uf = $row["uf"];
$mun_nome = $row["mun_nome"];
$mun_ddd = $row["mun_ddd"];
$sql = pg_query($dbcon, 'SELECT prx_prefixo FROM pbx_municipio_prefixo WHERE mun_id=' . $mun_id . ' ');
while ($x = pg_fetch_array($sql)) {
$prefixoX .= "$x[prx_prefixo] /";
}
$resultados .= '<tr>
<td>' . $mun_id . '</td>
<td>' . $uf . '</td>
<td>' . $mun_ddd . '</td>
<td>' . $mun_nome . '</td>
<td style="text-align: center;"><a href="javaScript:NovaJanela(\'index.php?idProg=168&acao=Mun&id=' . $mun_id . '\', \'CadastrodeMunicipio\', \'340\', \'190\', \'resizable=NO,scrollbars=1\');" title="Prefixo(s): ' . $prefixoX . '"><img src="imgSite/prefixo.jpg" width="15" height="15" border="0"></a></td>
<td style="text-align: center;"><a href="javaScript:NovaJanela(\'index.php?idProg=164&acao=in&ddd=' . $mun_ddd . '&uf=' . $uf . '\', \'CadastrodeMunicipio\', \'380\', \'220\', \'resizable=NO,scrollbars=1\');" title="Novo Municipio"><img src="imgSite/novoUser.png" border="0"></a></td>
<td style="text-align: center;"><a href="javaScript:NovaJanela(\'index.php?idProg=165&acao=up&idMunicipio=' . $mun_id . '\', \'CadastrodeMunicipio\', \'380\', \'220\', \'resizable=NO,scrollbars=1\');" title="Editar Municipio"><img src="imgSite/editaUser.png" border="0"></a></td>
<td style="text-align: center;"><a href="javaScript:DeletaMunicipio(\'' . $mun_id . '\');" title="Excluir este Municipio."><img src="imgSite/deletaUser.png" border="0"></a></td>
</tr>';
if ($numero >= 50) {
break;
}
}
//IMPRIMI COMBO UF----
$sqlUF = "SELECT uf FROM pbx_uf ORDER BY 1";
$resultUF = pg_query($dbcon, $sqlUF);
$optionUF .= "<option value=\"0\" " . ($recebe_uf == 0 ? 'selected' : '' ) . ">TODOS</option>";
while ($rowUF = pg_fetch_array($resultUF)) {
$uf_select = $rowUF["uf"];
$optionUF .= "<option value=\"" . $uf_select . "\" " . ($uf_select == $recebe_uf ? 'selected' : '' ) . ">" . $uf_select . "</option>";
}
$smarty->assign('resultados', $resultados);
$smarty->assign('optionUF', $optionUF);
$smarty->assign('municipio', $municipio);
$smarty->assign('mes', $mes);
$smarty->display("cadastros/municipio/municipio.html");
?>
<!--<input type="radio" id="online" name="online" onclick="submit()" >-->

89
cadastros/municipio/municipioInsert.php

@ -1,89 +0,0 @@
<?php
$tpLayout = 1;
//LIMPA VARIAVEIS
$uf = "";
$ddd = "";
$nome = "";
$acao = "";
//Recebe
if ($_GET['acao'] == "in") {
$ddd = $_GET['ddd'];
$uf = $_GET['uf'];
$nome = $_GET['municipio'];
} else {
$uf = $_POST['uf'];
$ddd = $_POST['ddd'];
$nome = $_POST['nome'];
}
$acao = $_GET['acao'];
//Trata Valores
function TrataValor($uf, $ddd, $nome) {
if (empty($uf) || empty($ddd) || empty($nome)) {
return "Preencha todos os campos!";
}
if (!is_numeric($ddd)) {
$erro = "2";
return "Preencha o campo DDD corretamente!";
}
if ($erro < 1) {
return 1;
}
}
//funcao insert
function ExecBanco($dbcon, $tabela, $uf, $ddd, $nome, $id) {
//verifica se ja exite municipio
$sql = "SELECT uf,mun_nome,mun_ddd FROM $tabela WHERE uf='$uf' AND mun_ddd='$ddd' AND mun_nome='$nome'";
$query = pg_query($dbcon, $sql);
if ($resultRow = pg_num_rows($query) >= 1) {
return 0;
} else {
$insert = "INSERT INTO $tabela (uf,mun_ddd,mun_nome) VALUES ('$uf','$ddd','$nome')";
$query = pg_query($dbcon, $insert);
$sql = "SELECT mun_id FROM $tabela WHERE uf='$uf' AND mun_ddd='$ddd' AND mun_nome='$nome'";
$query = pg_query($dbcon, $sql);
if (pg_num_rows($query) >= 1) {
return 1;
} else {
return 0;
}
}
}
//verifica tratamento dos valores
if (TrataValor($uf, $ddd, $nome) == 1) {
$tabela = "pbx_municipio_classifica";
$inseri = ExecBanco($dbcon, $tabela, $uf, $ddd, $nome, $id);
//retorna verdadeiro se registro for inserido
if ($inseri == 1) {
$mes = "Registro inserido com sucesso!";
} else {
$mes = "O registro já existe na base de dados!";
}
}
//
if (!is_numeric(TrataValor($uf, $ddd, $nome))) {
$mes .= TrataValor($uf, $ddd, $nome);
}
if ($_GET['acao'] == "inEX") {
$nome = $_GET['municipio'];
$uf = $_GET['uf'];
}
//IMPRIMI COMBO UF----
$sqlUF = "SELECT uf FROM pbx_uf ORDER BY 1";
$resultUF = pg_query($dbcon, $sqlUF);
while ($rowUF = pg_fetch_array($resultUF)) {
$uf_select = $rowUF["uf"];
$optionUF .= "<option value=\"" . $uf_select . "\" " . ($uf_select == $uf ? 'selected' : '' ) . ">" . $uf_select . "</option>";
}
$smarty->assign('mes', $mes);
$smarty->assign('optionUF', $optionUF);
$smarty->assign('ddd', $ddd);
$smarty->assign('nome', $nome);
$smarty->display("cadastros/municipio/municipioInsert.html");
?>

100
cadastros/municipio/municipioPrefixo.php

@ -1,100 +0,0 @@
<?php
$tpLayout = 1;
//Limpa valores
$id = "";
$finalizar = "";
//Recebe
if (empty($_GET['id'])) {
if ($_GET['acao'] == "deleta") {
$id = $_GET['prefixo'];
$id = substr($id, (strlen($id) - 5), strlen($id));
} else {
$id = $_POST['id'];
}
} else {
$id = $_GET['id'];
}
$finalizar = $_POST['finalizar'];
//Desenvolvimento
////DELETA
if ($_GET['acao'] == "deleta") {
$prefixo = $_GET['prefixo'];
$prefixo = substr($prefixo, 0, 6);
;
$sql = "DELETE FROM pbx_municipio_prefixo WHERE prx_prefixo='$prefixo'";
$query = pg_query($dbcon, $sql);
}
$sql = "SELECT a.mun_id,a.uf,a.mun_ddd,b.prx_prefixo FROM pbx_municipio_classifica a LEFT OUTER JOIN pbx_municipio_prefixo b ON a.mun_id=b.mun_id WHERE a.mun_id=$id";
$result = pg_query($dbcon, $sql);
if (pg_num_rows($result) < 1) {
$mes = 'Nenhum prefixo relacionado!';
}
while ($row = pg_fetch_array($result)) {
$id = $row['mun_id'];
$uf = $row['uf'];
$prefixoX = $row['prx_prefixo'];
$ddd = $row['mun_ddd'];
$prefixoX = substr($prefixoX, (strlen($prefixoX) - 4), strlen($prefixoX));
if (empty($prefixoX)) {
$prefixoX = "Insira um novo prefixo!! ";
}
if ($dr = 1) {
$color = '#FFFFFF';
$dr = 2;
} else {
$color = '#CCCCCC';
$dr = 1;
}
$resultados .= '
<tr>
<td bgcolor=' . $color . '>' . $uf . '/' . $ddd . '</td>
<td bgcolor=' . $color . '>' . $prefixoX . '</td>
<td style="text-align: center;"><a href="javaScript:DeletaPrefixo(\'' . $ddd . '' . $prefixoX . ',' . $id . '\');" title="Excluir este Prefixo."><img src="imgSite/deletaUser.png" border="0"></a></td>
</tr>
';
$smarty->assign('ddd', $ddd);
}
//// INSERT
if ($finalizar == "Gravar") {
$ddd = $_POST['ddd'];
$prefixo = $_POST['prefixo'];
if (empty($prefixo)) {
$mes = "Por favor preencha o campo prefixo!";
} else {
if (!is_numeric($prefixo)) {
$mes = "Por favor preencha o campo prefixo corretamente!";
} else {
$busca = "SELECT prx_prefixo FROM pbx_municipio_prefixo WHERE mun_id='$id' AND prx_prefixo='$ddd$prefixo'";
$result = pg_query($dbcon, $busca);
if (pg_num_rows($result) >= 1) {
$mes = "Prefixo ja existente!";
} else {
$insert = "INSERT INTO pbx_municipio_prefixo (mun_id,prx_prefixo) VALUES ('$id','$ddd$prefixo')";
$query = pg_query($dbcon, $insert);
$sql = "SELECT mun_id,prx_prefixo FROM pbx_municipio_prefixo WHERE mun_id='$id' AND prx_prefixo='$ddd$prefixo'";
$result = pg_query($dbcon, $sql);
if (pg_num_rows($result) < 1) {
$mes = "O prefixo nao foi inserido!";
} else {
$mes = "Prefixo inserido com sucesso!";
header("Location: index.php?idProg=168&id=$id");
}
}
}
}
$smarty->assign('prefixo', $prefixo);
}
$smarty->assign('resultados', $resultados);
$smarty->assign('mes', $mes);
$smarty->assign('id', $id);
$smarty->display("cadastros/municipio/municipioPrefixo.html");
?>

90
cadastros/municipio/municipioUpdate.php

@ -1,90 +0,0 @@
<?php
$tpLayout = 1;
//LIMPA VARIAVEIS
$uf = "";
$ddd = "";
$nome = "";
$acao = "";
//Recebe
$id = $_GET['idMunicipio'];
$acao = $_POST['concluir'];
//imprimi registro na tela
$sql = "SELECT a.mun_id,a.mun_nome,a.mun_ddd,a.uf FROM pbx_municipio_classifica a LEFT OUTER JOIN pbx_municipio_prefixo b ON a.mun_id=b.mun_id WHERE a.mun_id='$id'";
$query = pg_query($dbcon, $sql);
while ($row = pg_fetch_array($query)) {
$nome = $row['mun_nome'];
$ddd = $row['mun_ddd'];
$uf = $row['uf'];
}
$prefixo = substr($prefixo, (strlen($prefixo) - 4), strlen($prefixo));
if ($acao == "Finalizar") {
//recebe valores post
$uf = $_POST['uf'];
$nome = $_POST['nome'];
$ddd = $_POST['ddd'];
$prefixo = $_POST['prefixo'];
$id = $_POST['idMunicipio'];
//trata os valores
TrataValor($uf, $ddd, $nome);
//verifica se valores estao corretos
if (TrataValor($uf, $ddd, $nome) == 1) {
$tabela = "pbx_municipio_classifica";
$update = ExecBancoUpdate($dbcon, $tabela, $uf, $ddd, $nome, $id);
//retorna verdadeiro se registro for inserido
if ($update == 1) {
$mes = "Registro alterado com sucesso!";
} else {
$mes = "Nao foi possivel realizar a operação!";
}
}
}
//Trata Valores
function TrataValor($uf, $ddd, $nome) {
if (empty($uf) || empty($ddd) || empty($nome)) {
return "Preencha todos os campos!";
}
if (!is_numeric($ddd)) {
$erro = "2";
return "Preencha o campo DDD corretamente!";
}
if ($erro < 1) {
return 1;
}
}
//funcao update
function ExecBancoUpdate($dbcon, $tabela, $uf, $ddd, $nome, $id) {
$update = "UPDATE $tabela SET uf='$uf' , mun_ddd='$ddd' , mun_nome='$nome' WHERE mun_id='$id'";
$query = pg_query($dbcon, $update);
$sql = "SELECT mun_id FROM $tabela WHERE uf='$uf' AND mun_ddd='$ddd' AND mun_nome='$nome'";
$query = pg_query($dbcon, $sql);
if (pg_num_rows($query) >= 1) {
return 1;
} else {
return 0;
}
}
//
if (!is_numeric(TrataValor($uf, $ddd, $nome))) {
$mes .= TrataValor($uf, $ddd, $nome);
}
//IMPRIMI COMBO UF----
$sqlUF = "SELECT uf FROM pbx_uf ORDER BY 1";
$resultUF = pg_query($dbcon, $sqlUF);
while ($rowUF = pg_fetch_array($resultUF)) {
$uf_select = $rowUF["uf"];
$optionUF .= "<option value=\"" . $uf_select . "\" " . ($uf_select == $uf ? 'selected' : '' ) . ">" . $uf_select . "</option>";
}
$smarty->assign('mes', $mes);
$smarty->assign('optionUF', $optionUF);
$smarty->assign('ddd', $ddd);
$smarty->assign('nome', $nome);
$smarty->assign('id', $id);
$smarty->assign('prefixo', $prefixo);
$smarty->display("cadastros/municipio/municipioUpdate.html");
?>

10
configGeral.php

@ -256,11 +256,11 @@ if ($idSubProg == CONFIG_BASE_DADOS) {
$fields = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);
$query = sprintf("SELECT perm_licenca FROM pbx_usuarios WHERE matricula = '%s';", GetMatricula());
$result = pg_query($query);
$result = pg_query($GLOBALS["dbconn"], $query);
$infoUser = pg_fetch_assoc($result);
$mensagem = null;
if ($fields['btGerar']){
if (isset($fields['btGerar'])){
if ($fields['document'] && $fields['perfil']) {
$fields['document'] = preg_replace('/[^0-9]/', '', $fields['document']);
GerarArquivo($fields);
@ -292,8 +292,10 @@ if ($idSubProg == CONFIG_BASE_DADOS) {
}
$smarty->assign('select_perfil', $slcOpt);
foreach ($fields as $k => $v) {
$smarty->assign($k, $v);
if (isset($fields)) {
foreach ($fields as $k => $v) {
$smarty->assign($k, $v);
}
}
$smarty->assign('mensagem', $mensagem);

37
contacteFunc.php

@ -865,45 +865,8 @@ function GetIdResult($result) {
}
function GetCofigPadrao($dbcon) {
$query = "SELECT * FROM pbx_conf_padrao";
$result = pg_query($dbcon, $query);
$dados = pg_fetch_array($result);
$_SESSION[CONF_PADRAO_CAMINHO_BACK] = $dados['caminho_backup'];
$_SESSION[CONF_PADRAO_CAMINHO_PRODUCAO] = $dados['caminho_producao'];
$_SESSION[CONF_PADRAO_CAMINHO_MUSICAS] = $dados['caminho_musicas'];
$_SESSION[CONF_PADRAO_URL_MUSICAS] = $dados['url_musicas'];
$_SESSION[CONF_PADRAO_URL_ASTERISK] = $dados['url_asterisk'];
}
function IncluiAgenteFile($dbcon) {
$query = "select matricula, apelido from pbx_usuarios where delete_ = 0";
$result = pg_query($dbcon, $query);
if (!$result) {
return "Não foi possível acessar o banco de dados!";
} else {
$file = fopen(GetFileAgente(), 'w');
if (!$file) {
return "Não foi possível acessar o arquivo de dados!";
} else {
while ($row = pg_fetch_array($result)) {
$userMatricula = $row["matricula"];
$userLogin = $row["apelido"];
$conteudo = "[$userMatricula](agents)\n";
$conteudo .= "fullname = $userLogin\n";
if (fwrite($file, $conteudo) === false) {
return "Não foi possível gravar o arquivo de dados!";
}
}
fclose($file);
GetUrl(AST_INCLUI_AGENTE); // return "Não foi possível atualizar o asterisk!";
}
}
return "OK";
}

1
imgSite/cpu-bad.svg

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path fill="#ce0000" d="M176 24c0-13.3-10.7-24-24-24s-24 10.7-24 24V64c-35.3 0-64 28.7-64 64H24c-13.3 0-24 10.7-24 24s10.7 24 24 24H64v56H24c-13.3 0-24 10.7-24 24s10.7 24 24 24H64v56H24c-13.3 0-24 10.7-24 24s10.7 24 24 24H64c0 35.3 28.7 64 64 64v40c0 13.3 10.7 24 24 24s24-10.7 24-24V448h56v40c0 13.3 10.7 24 24 24s24-10.7 24-24V448h56v40c0 13.3 10.7 24 24 24s24-10.7 24-24V448c35.3 0 64-28.7 64-64h40c13.3 0 24-10.7 24-24s-10.7-24-24-24H448V280h40c13.3 0 24-10.7 24-24s-10.7-24-24-24H448V176h40c13.3 0 24-10.7 24-24s-10.7-24-24-24H448c0-35.3-28.7-64-64-64V24c0-13.3-10.7-24-24-24s-24 10.7-24 24V64H280V24c0-13.3-10.7-24-24-24s-24 10.7-24 24V64H176V24zM160 128H352c17.7 0 32 14.3 32 32V352c0 17.7-14.3 32-32 32H160c-17.7 0-32-14.3-32-32V160c0-17.7 14.3-32 32-32zm192 32H160V352H352V160z"/></svg>

After

Width:  |  Height:  |  Size: 1008 B

1
imgSite/cpu-ok.svg

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path fill="#05dc4b" d="M176 24c0-13.3-10.7-24-24-24s-24 10.7-24 24V64c-35.3 0-64 28.7-64 64H24c-13.3 0-24 10.7-24 24s10.7 24 24 24H64v56H24c-13.3 0-24 10.7-24 24s10.7 24 24 24H64v56H24c-13.3 0-24 10.7-24 24s10.7 24 24 24H64c0 35.3 28.7 64 64 64v40c0 13.3 10.7 24 24 24s24-10.7 24-24V448h56v40c0 13.3 10.7 24 24 24s24-10.7 24-24V448h56v40c0 13.3 10.7 24 24 24s24-10.7 24-24V448c35.3 0 64-28.7 64-64h40c13.3 0 24-10.7 24-24s-10.7-24-24-24H448V280h40c13.3 0 24-10.7 24-24s-10.7-24-24-24H448V176h40c13.3 0 24-10.7 24-24s-10.7-24-24-24H448c0-35.3-28.7-64-64-64V24c0-13.3-10.7-24-24-24s-24 10.7-24 24V64H280V24c0-13.3-10.7-24-24-24s-24 10.7-24 24V64H176V24zM160 128H352c17.7 0 32 14.3 32 32V352c0 17.7-14.3 32-32 32H160c-17.7 0-32-14.3-32-32V160c0-17.7 14.3-32 32-32zm192 32H160V352H352V160z"/></svg>

After

Width:  |  Height:  |  Size: 1008 B

1
imgSite/hd-bad.svg

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path fill="#d20000" d="M0 96C0 60.7 28.7 32 64 32H448c35.3 0 64 28.7 64 64V280.4c-17-15.2-39.4-24.4-64-24.4H64c-24.6 0-47 9.2-64 24.4V96zM64 288H448c35.3 0 64 28.7 64 64v64c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V352c0-35.3 28.7-64 64-64zM320 416a32 32 0 1 0 0-64 32 32 0 1 0 0 64zm128-32a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"/></svg>

After

Width:  |  Height:  |  Size: 553 B

1
imgSite/hd-ok.svg

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path fill="#00d936" d="M0 96C0 60.7 28.7 32 64 32H448c35.3 0 64 28.7 64 64V280.4c-17-15.2-39.4-24.4-64-24.4H64c-24.6 0-47 9.2-64 24.4V96zM64 288H448c35.3 0 64 28.7 64 64v64c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V352c0-35.3 28.7-64 64-64zM320 416a32 32 0 1 0 0-64 32 32 0 1 0 0 64zm128-32a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"/></svg>

After

Width:  |  Height:  |  Size: 553 B

1
imgSite/load-avg-danger.svg

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path fill="#df0000" d="M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"/></svg>

After

Width:  |  Height:  |  Size: 549 B

1
imgSite/ram-bad.svg

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path fill="#d20000" d="M64 64C28.7 64 0 92.7 0 128v7.4c0 6.8 4.4 12.6 10.1 16.3C23.3 160.3 32 175.1 32 192s-8.7 31.7-21.9 40.3C4.4 236 0 241.8 0 248.6V320H576V248.6c0-6.8-4.4-12.6-10.1-16.3C552.7 223.7 544 208.9 544 192s8.7-31.7 21.9-40.3c5.7-3.7 10.1-9.5 10.1-16.3V128c0-35.3-28.7-64-64-64H64zM576 352H0v64c0 17.7 14.3 32 32 32H80V416c0-8.8 7.2-16 16-16s16 7.2 16 16v32h96V416c0-8.8 7.2-16 16-16s16 7.2 16 16v32h96V416c0-8.8 7.2-16 16-16s16 7.2 16 16v32h96V416c0-8.8 7.2-16 16-16s16 7.2 16 16v32h48c17.7 0 32-14.3 32-32V352zM192 160v64c0 17.7-14.3 32-32 32s-32-14.3-32-32V160c0-17.7 14.3-32 32-32s32 14.3 32 32zm128 0v64c0 17.7-14.3 32-32 32s-32-14.3-32-32V160c0-17.7 14.3-32 32-32s32 14.3 32 32zm128 0v64c0 17.7-14.3 32-32 32s-32-14.3-32-32V160c0-17.7 14.3-32 32-32s32 14.3 32 32z"/></svg>

After

Width:  |  Height:  |  Size: 1005 B

1
imgSite/ram-ok.svg

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path fill="#04e11b" d="M64 64C28.7 64 0 92.7 0 128v7.4c0 6.8 4.4 12.6 10.1 16.3C23.3 160.3 32 175.1 32 192s-8.7 31.7-21.9 40.3C4.4 236 0 241.8 0 248.6V320H576V248.6c0-6.8-4.4-12.6-10.1-16.3C552.7 223.7 544 208.9 544 192s8.7-31.7 21.9-40.3c5.7-3.7 10.1-9.5 10.1-16.3V128c0-35.3-28.7-64-64-64H64zM576 352H0v64c0 17.7 14.3 32 32 32H80V416c0-8.8 7.2-16 16-16s16 7.2 16 16v32h96V416c0-8.8 7.2-16 16-16s16 7.2 16 16v32h96V416c0-8.8 7.2-16 16-16s16 7.2 16 16v32h96V416c0-8.8 7.2-16 16-16s16 7.2 16 16v32h48c17.7 0 32-14.3 32-32V352zM192 160v64c0 17.7-14.3 32-32 32s-32-14.3-32-32V160c0-17.7 14.3-32 32-32s32 14.3 32 32zm128 0v64c0 17.7-14.3 32-32 32s-32-14.3-32-32V160c0-17.7 14.3-32 32-32s32 14.3 32 32zm128 0v64c0 17.7-14.3 32-32 32s-32-14.3-32-32V160c0-17.7 14.3-32 32-32s32 14.3 32 32z"/></svg>

After

Width:  |  Height:  |  Size: 1005 B

1
imgSite/troncoOff16.svg

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path fill="#d20000" d="M576 0c17.7 0 32 14.3 32 32V480c0 17.7-14.3 32-32 32s-32-14.3-32-32V32c0-17.7 14.3-32 32-32zM448 96c17.7 0 32 14.3 32 32V480c0 17.7-14.3 32-32 32s-32-14.3-32-32V128c0-17.7 14.3-32 32-32zM352 224V480c0 17.7-14.3 32-32 32s-32-14.3-32-32V224c0-17.7 14.3-32 32-32s32 14.3 32 32zM192 288c17.7 0 32 14.3 32 32V480c0 17.7-14.3 32-32 32s-32-14.3-32-32V320c0-17.7 14.3-32 32-32zM96 416v64c0 17.7-14.3 32-32 32s-32-14.3-32-32V416c0-17.7 14.3-32 32-32s32 14.3 32 32z"/></svg>

After

Width:  |  Height:  |  Size: 701 B

1
imgSite/troncoOn16.svg

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path fill="#00dd37" d="M576 0c17.7 0 32 14.3 32 32V480c0 17.7-14.3 32-32 32s-32-14.3-32-32V32c0-17.7 14.3-32 32-32zM448 96c17.7 0 32 14.3 32 32V480c0 17.7-14.3 32-32 32s-32-14.3-32-32V128c0-17.7 14.3-32 32-32zM352 224V480c0 17.7-14.3 32-32 32s-32-14.3-32-32V224c0-17.7 14.3-32 32-32s32 14.3 32 32zM192 288c17.7 0 32 14.3 32 32V480c0 17.7-14.3 32-32 32s-32-14.3-32-32V320c0-17.7 14.3-32 32-32zM96 416v64c0 17.7-14.3 32-32 32s-32-14.3-32-32V416c0-17.7 14.3-32 32-32s32 14.3 32 32z"/></svg>

After

Width:  |  Height:  |  Size: 701 B

941
include/funcoes/shared.php

@ -9,481 +9,7 @@ define("_LOG_MSG_DISPLAY", 3);
/*
* funcoes compartilhadas
* - GetDddPadrao()($numero) -> Se passado um numero retorna concatenado com ddd padrao, se nao retorna somente o ddd.
* - GetSpid($numero) -> Faz pesquisa no banco de dadodos da portabilidade e retorna o sipid da operadora relacionada.
* - GetTipoChamada($destino, $dddPadao) -> verifica se a chamada e para fixo, movel, local ou interurbano pela analise do destino informado.
* Retorna um array contendo tipo dispositivo, tipo da chamada, numero da operadora.
*/
//Funcao verifica operadora - Amarildo Pereira 37 99669 7131
function GetSpid(&$numero) {
$flInter = substr($numero, 0, 2);
if (($flInter != '00') && (substr($numero, 0, 1) == '0'))
$numero = substr($numero, 1);
$tam = strlen($numero);
if (($tam == 8) || (($tam == 9) && (substr($numero, 0, 1) == '9'))) {
$numeroBusca = $numero;
$numeroBusca = GetDddPadrao($numeroBusca);
$tam = strlen($numeroBusca);
$prefixo = substr($numeroBusca, 0, ($tam - 4));
$sufixo = substr($numeroBusca, -4);
return GetSpidBd($numeroBusca, $prefixo, $sufixo);
} else {
/*
* Tenta achar o numero com 10 ou 11 digitos validos.
*/
$prefixo = substr($numero, 0, ($tam - 4));
$sufixo = substr($numero, -4);
$ret = GetSpidBd($numero, $prefixo, $sufixo);
if ($ret)
return $ret;
/*
* Numero fornecido com 11 digitros mas apenas os 10 ultimos seo validos.
*/
$numero = substr($numero, 1);
$tam = strlen($numero);
$prefixo = substr($numero, 0, ($tam - 4));
$sufixo = substr($numero, -4);
return GetSpidBd($numero, $prefixo, $sufixo);
}
}
function GetSpidBd($numero, $prefixo, $sufixo) {
$nonoDigito = (strlen($numero) == 11);
$numeroConsulta = $numero;
$numero_Consulta = $numero;
$ddd_ini = substr($numero, 0, 1);
if ($nonoDigito) {
$numeroConsulta = substr($numero, 0, 2) . substr($numero, 3, 8);
}
if ((strlen($numero) == 10) && (($ddd_ini != '4' ) || ($ddd_ini != '5' ))) {
$numero_Consulta = substr($numero, 0, 2) . '9' . substr($numero, 2, 8);
}
$query = "select spid from portabilidade where (tel_doadora = '$numeroConsulta' or tel_doadora = '$numero_Consulta' or tel_doadora = '$numero')";
$result = pg_query($query);
if (!$result || !pg_num_rows($result)) {
$oper = GetOperNumero($numero);
return $oper ? $oper : false;
}
$dados = pg_fetch_row($result);
return !pg_num_rows($result) ? false : $dados[0];
}
function GetOperadoraRelacionada($operadora) {
/*
* funcao busca por operadoras que se relacionam, ou seja, se a operadora
* passada estiver relacionada a outra e porque deve sair pelo tronco dessa,
* ex.: Em algumas localidades a TNL->331 dever sair pelo tronco OI->314.
* Este relacionamento deve ser configurado na aplicacao web menu:
* Ferramentas->Tarifacao/Portabilidade->Operadoras.
*/
$query = "select oper_spid from pbx_operadora_rel where oper_spid_rel = '$operadora'";
$result = pg_query($query);
$dados = pg_fetch_row($result);
/*
* Se nao encontrar uma operadora relacionada, retorna a mesma passada.
*/
return !pg_num_rows($result) ? $operadora : $dados[0];
}
function GetTipoChamada($destino, $dddPadrao = '0') {
/*
* ddd -> 65
* operadodra -> 021
* 18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01
* | | | | | | | | | | | | | | | | | |
* 9 2 8 9 3 9 1 3 -> Movel Local 08 digitos iniciado em ['6','7','8','9'].
* 9 9 2 8 9 3 9 1 3 -> Movel Local 09 digitos.
* 6 5 9 9 2 8 9 3 9 1 3 -> Movel Local 11 digitos (ddd = padrao).
* 6 5 9 2 8 9 3 9 1 3 -> Movel Local 10 digitos (ddd = padrao) + numero iniciado em ['6','7','8','9'].
* 6 7 9 2 8 9 3 9 1 3 -> Movel Interurbano 10 digitos (ddd != padrao) + numero iniciado em ['6','7','8','9'].
* 0 2 1 6 7 9 2 8 9 3 9 1 3 -> Movel Interurbano 13 digitos operadora + (ddd != padrao) + numero iniciado em ['6','7','8','9'].
* 0 2 1 6 7 9 9 2 8 9 3 9 1 3 -> Movel Interurbano 14 digitos operadora + (ddd != padrao) + numero iniciado em ['6','7','8','9'].
* 6 7 9 9 2 8 9 3 9 1 3 -> Movel Interurbano 11 digitos (ddd != padrao).
* 3 6 1 4 3 9 1 3 -> Fixo Local 08 digitos iniciado em ['2','3','4','5'].
* 6 5 3 6 1 4 3 9 1 3 -> Fixo Local 10 digitos (ddd = padrao) + numero, iniciado em ['2','3','4','5'].
* 6 7 3 6 1 4 3 9 1 3 -> Fixo Interurbano 10 digitos (ddd != padrao) + numero, iniciado em ['2','3','4','5'].
* 0 2 1 6 7 3 6 1 4 3 9 1 3 -> Fixo Interurbano 13 digitos operadora + (ddd != padrao) + numero, iniciado em ['2','3','4','5'].
*/
$destino = trim($destino);
/*
* Chamadas iniciadas com "00" indicam uma ligacao internacional.
*/
$flInter = substr($destino, 0, 2);
/*
* Nao sendo uma chamada internacional, remove o "0" zero a esquerda.
*/
if (($flInter != '00') && (substr($destino, 0, 1) == '0')) {
$destino = substr($destino, 1);
}
$tam = strlen($destino);
$arMovel = array('6', '7', '8', '9');
$arEmergencia = array('100', '128', '190', '191', '192', '193', '194', '197', '198', '199');
if ($tam == 8) {
$ch = substr($destino, 0, 1);
return array('fixo', 'local', '0');
} else if (($tam > 8) && ($flInter == '00')) {
$oper = substr($destino, 2, 2);
return array('fixo', 'ddi', $oper);
} else if ($tam == 9) {
$ch = substr($destino, 0, 1);
if ($ch == '9') {
return array('movel', 'local');
}
return array('fixo', 'local', '0');
} else if ($tam == 10) {
$dddNum = substr($destino, 0, 2);
$ch = substr($destino, 2, 1);
if (($dddNum == $dddPadrao) && (array_search($ch, $arMovel)))
return array('movel', 'local', '0');
if (($dddNum != $dddPadrao) && (array_search($ch, $arMovel)))
return array('movel', 'inter', '0');
if ($dddNum == $dddPadrao)
return array('fixo', 'local', '0');
else
return array('fixo', 'inter', '0');
}
else if ($tam == 11) {
$dddNum = substr($destino, 0, 2);
$ch = substr($destino, -9, 1);
if ($dddNum == $dddPadrao) {
if ($ch == '9') {
return array('movel', 'local', '0');
}
return array('fixo', 'local', '0');
} else {
if ($ch == '9') {
return array('movel', 'inter', '0');
}
return array('fixo', 'inter', '0');
}
} else if ($tam == 13) {
$oper = substr($destino, 0, 2);
$dddNum = substr($destino, 2, 2);
$ch = substr($destino, 4, 1);
if (($dddNum == $dddPadrao) && (array_search($ch, $arMovel)))
return array('movel', 'local', $oper);
if (($dddNum != $dddPadrao) && (array_search($ch, $arMovel)))
return array('movel', 'inter', $oper);
if ($dddNum == $dddPadrao)
return array('fixo', 'local', '0');
else
return array('fixo', 'inter', $oper);
}
else if ($tam == 14) {
$oper = substr($destino, 0, 3);
$dddNum = substr($destino, 3, 2);
if ($dddNum == $dddPadrao)
return array('movel', 'local', $oper);
else
return array('movel', 'inter', $oper);
}
else {
if ((substr($destino, 0, 4) == '0800') || (array_search($destino, $arEmergencia)) || ($tam < 8))
return array('fixo', 'local', '0');
$dddNum = substr(substr($destino, -10), 0, 2);
$ch = substr(substr($destino, -8), 0, 1);
if (($dddNum == $dddPadrao) && (array_search($ch, $arMovel)))
return array('movel', 'local', '0');
if (($dddNum != $dddPadrao) && (array_search($ch, $arMovel)))
return array('movel', 'inter', '0');
if ($dddNum == $dddPadrao)
return array('fixo', 'local', '0');
else
return array('fixo', 'inter', '0');
}
}
function Ver0800($destino) {
$destino = trim($destino);
$str = substr($destino, -11);
return substr($str, 0, 4) == '0800' ? $str : $destino;
}
function GravaLogApl($mensagem, $nome_file = '', $login = '') {
$data = date('dmY');
if (!$nome_file) {
$nome_file = 'log_apl';
}
$file = sprintf("/var/log/asterisk/%s.log", $nome_file);
$arq = fopen($file, 'a');
if ($arq) {
$start = '';
foreach ($mensagem as $linha) {
$linha = trim($linha);
if (!$start) {
$start++;
fwrite($arq, sprintf("Inicio: %s%s\n", date('d/m/Y H:i:s'), ($login ? sprintf(" Login: %s", $login) : '')));
}
fwrite($arq, $linha . "\n");
}
fwrite($arq, "Final: $start\n\n");
fclose($arq);
}
}
function GetInfoTarifa($troncoId, $numOper, $destino, $dispositivo) {
global $log;
/*
* Informacoes do contrato relacionado ao tronco tronco
*/
$query = "select a.id, a.nome, b.contr_id, b.oper_id, c.oper_numero, b.contr_dia_fechamento, b.contr_bloq_franquia
from pbx_troncos a, pbx_tarif_contrato b, pbx_operadoras c
where b.contr_id = a.contrato
and c.oper_id = b.oper_id
and a.id = '$troncoId'";
$log[] = "GetInfoTarifa[\n.";
$log[] = "Query Contrato: $query";
$result = pg_query($query);
if (!pg_num_rows($result)) {
$info['oper_numero'] = (!$numOper) ? '0' : $numOper;
$info['contr_id'] = 0;
$info['oper_id'] = 0;
$info['trr_tipo_opera'] = 0;
$info['oper_numero_dest'] = $info['oper_numero'];
$info['trr_tarifa_zero'] = 0;
$info['oper_id_dest'] = 0;
$info['contr_id_dest'] = 0;
$info['contr_dia_fechamento'] = 0;
$info['contr_bloq_franquia'] = 0;
$info['prc_id'] = 0;
$info['trr_preco_tipo'] = 0;
$info['trr_vc1'] = 0;
$info['trr_vc2'] = 0;
$info['trr_vc3'] = 0;
$info['trr_vc4'] = 0;
$info['trr_vc5'] = 0;
$info['trr_vc6'] = 0;
$info['trr_vc1_cad'] = 0;
$info['trr_vc2_cad'] = 0;
$info['trr_vc3_cad'] = 0;
$info['trr_vc4_cad'] = 0;
$info['trr_vc5_cad'] = 0;
$info['trr_vc6_cad'] = 0;
$info['trr_vc1_ext'] = 0;
$info['trr_vc2_ext'] = 0;
$info['trr_vc3_ext'] = 0;
$info['trr_vc4_ext'] = 0;
$info['trr_vc5_ext'] = 0;
$info['trr_vc6_ext'] = 0;
$info['prc_franquia'] = 0;
} else {
$dados = pg_fetch_array($result);
$info = array();
$contrId = $dados['contr_id'];
$numOperContrato = $dados['oper_numero'];
$info['oper_numero'] = $dados['oper_numero'];
$info['contr_id'] = $dados['contr_id'];
$info['oper_id'] = $dados['oper_id'];
$tipoOpera = (!$numOper) || ($numOper == $numOperContrato) ? 0 : 1;
$info['trr_tipo_opera'] = $tipoOpera;
$info['oper_numero_dest'] = $tipoOpera ? $numOper : $dados['oper_numero'];
$info['contr_dia_fechamento'] = $dados['contr_dia_fechamento'];
$info['contr_bloq_franquia'] = $dados['contr_bloq_franquia'];
$query = "select count(*) from pbx_tarif_contrato_tarifa_zero where contr_id = '$contrId' and trz_numero = '$destino'";
$result = pg_query($query);
$dados = pg_fetch_row($result);
$info['trr_tarifa_zero'] = $dados[0];
$queryPrec = "select prc_id, prc_tipo, prc_franquia, prc_franquia_movel, prc_franquia_preco, prc_preco_vc1, prc_preco_vc2,
prc_preco_vc3,prc_preco_vc4, prc_preco_vc5, prc_preco_vc6, a.prc_preco_vc1_cad, a.prc_preco_vc2_cad, a.prc_preco_vc3_cad, a.prc_preco_vc4_cad, a.prc_preco_vc5_cad,a.prc_preco_vc6_cad, a.prc_preco_vc1_ext,
a.prc_preco_vc2_ext, a.prc_preco_vc3_ext, a.prc_preco_vc4_ext, a.prc_preco_vc5_ext,a.prc_preco_vc6_ext, b.oper_id, b.contr_id
from pbx_tarif_contrato_preco a, pbx_tarif_contrato b
where b.contr_id = a.contr_id
and a.prc_id = (
select max(prc_id) as prc_id from pbx_tarif_contrato_preco
where contr_id = %s
and prc_vigencia <= now()::date
)";
if ($tipoOpera) {
$queryCompl = sprintf('select b.contr_id from pbx_operadoras a, pbx_tarif_contrato b where b.oper_id = a.oper_id and b.contr_tipo = %s and a.oper_numero = %s', QuotedStr($dispositivo), QuotedStr($numOper));
$query = sprintf($queryPrec, "($queryCompl)");
$log[] = "Query preco: $query";
$result = pg_query($query);
$dados = pg_fetch_array($result);
}
if ((!$tipoOpera) || (($tipoOpera) && (!pg_num_rows($result)))) {
$query = sprintf($queryPrec, QuotedStr($contrId));
$log[] = "Query preco: $query";
$result = pg_query($query);
$dados = pg_fetch_array($result);
}
if (!$result) {
$erro = error_get_last();
$log[] = "Erro: " . $erro['message'] . " Cmd: $query";
}
$info['oper_id_dest'] = $dados['oper_id'];
$info['contr_id_dest'] = $dados['contr_id'];
$info['prc_id'] = $dados['prc_id'];
$info['trr_preco_tipo'] = trim($dados['prc_tipo']);
$info['trr_vc1'] = $dados['prc_preco_vc1'];
$info['trr_vc2'] = $dados['prc_preco_vc2'];
$info['trr_vc3'] = $dados['prc_preco_vc3'];
$info['trr_vc4'] = $dados['prc_preco_vc4'];
$info['trr_vc5'] = $dados['prc_preco_vc5'];
$info['trr_vc6'] = $dados['prc_preco_vc6'];
$info['trr_vc1_cad'] = $dados['prc_preco_vc1_cad'];
$info['trr_vc2_cad'] = $dados['prc_preco_vc2_cad'];
$info['trr_vc3_cad'] = $dados['prc_preco_vc3_cad'];
$info['trr_vc4_cad'] = $dados['prc_preco_vc4_cad'];
$info['trr_vc5_cad'] = $dados['prc_preco_vc5_cad'];
$info['trr_vc6_cad'] = $dados['prc_preco_vc6_cad'];
$info['trr_vc1_ext'] = $dados['prc_preco_vc1_ext'];
$info['trr_vc2_ext'] = $dados['prc_preco_vc2_ext'];
$info['trr_vc3_ext'] = $dados['prc_preco_vc3_ext'];
$info['trr_vc4_ext'] = $dados['prc_preco_vc4_ext'];
$info['trr_vc5_ext'] = $dados['prc_preco_vc5_ext'];
$info['trr_vc6_ext'] = $dados['prc_preco_vc6_ext'];
$info['prc_franquia'] = $dados['prc_franquia'];
}
return $info;
}
function GetTempoPrepago($db, $contaSenha, $origem, $destino, $tronco) {
/*
* Esta funcao havalia se a origem esta incluida no sistema de prepago.
* Retorna o tempo disponivel para conversacao conforme o destino.
* Retorna -1 se nao estiver habilitado, se nao existir.
* Retorna -2 se estiver incluido no tarifa 0.
* Retorna -3 se retornar erro.
*/
$query = "select habilita_prepago, saldo_prepago, (select prm_prepago from pbx_parametros limit 1) as pre_pago from pbx_prepago where tipo = '$contaSenha' and id = '$origem'";
$result = pg_query($db, $query);
/*
* Numero inexistente ou erro na consulta.
*/
if (!$result)
return -3;
if (!pg_num_rows($result))
return -1;
$dados = pg_fetch_array($result);
/*
* Nao esta habilitado nos parametros ou a origem nao esta habilitada.
*/
if (!$dados['pre_pago'] || !$dados['habilita_prepago'])
return -1;
/*
* Nao tem saldo.
*/
$saldoPrepago = $dados['saldo_prepago'];
if (!$saldoPrepago)
return 0;
$dddPadrao = GetDddPadrao();
$tpChamada = GetTipoChamada($destino, $dddPadrao);
$dispositivo = $tpChamada[0];
$tipoChamada = $tpChamada[1];
$numOper = $tpChamada[2];
/*
* Esta funcao retorna informacoes sobre o contrato e precos
*/
$infoContrato = GetInfoTarifa($tronco, $numOper, $origem, $dispositivo);
if (($dispositivo == 'fixo') && ($tipoChamada == 'local')) {
$info['trr_vc_cad'] = $infoContrato['trr_vc1_cad'];
$info['trr_vc_ext'] = $infoContrato['trr_vc1_ext'];
$info['trr_vc'] = 'vc1';
$info['trr_preco'] = $infoContrato['trr_vc1'];
}
if (($dispositivo == 'fixo') && ($tipoChamada == 'inter')) {
$info['trr_vc_cad'] = $infoContrato['trr_vc2_cad'];
$info['trr_vc_ext'] = $infoContrato['trr_vc2_ext'];
$info['trr_vc'] = 'vc2';
$info['trr_preco'] = $infoContrato['trr_vc2'];
}
if (($dispositivo == 'fixo') && ($tipoChamada == 'ddi')) {
$info['trr_vc_cad'] = $infoContrato['trr_vc5_cad'];
$info['trr_vc_ext'] = $infoContrato['trr_vc5_ext'];
$info['trr_vc'] = 'vc5';
$info['trr_preco'] = $infoContrato['trr_vc5'];
}
if (($dispositivo == 'movel') && ($tipoChamada == 'local')) {
$info['trr_vc_cad'] = $infoContrato['trr_vc3_cad'];
$info['trr_vc_ext'] = $infoContrato['trr_vc3_ext'];
$info['trr_vc'] = 'vc3';
$info['trr_preco'] = $infoContrato['trr_vc3'];
}
if (($dispositivo == 'movel') && ($tipoChamada == 'inter')) {
$info['trr_vc_cad'] = $infoContrato['trr_vc4_cad'];
$info['trr_vc_ext'] = $infoContrato['trr_vc4_ext'];
$info['trr_vc'] = 'vc4';
$info['trr_preco'] = $infoContrato['trr_vc4'];
}
if (($dispositivo == 'movel') && ($tipoChamada == 'ddi')) {
$info['trr_vc_cad'] = $infoContrato['trr_vc6_cad'];
$info['trr_vc_ext'] = $infoContrato['trr_vc6_ext'];
$info['trr_vc'] = 'vc6';
$info['trr_preco'] = $infoContrato['trr_vc6'];
}
//$log[] = print_r($infoContrato, true);
//@GravaLogApl($log, 'pre_pago_log');
/*
* Verifica se o destino esta incluido no tarifa 0.
*/
if ($infoContrato['trr_tarifa_zero']) {
return -2;
}
/*
* Tarifacao(trr_preco_tipo) 1 por minuto tipo, 2 por chamada.
* O preco esta indicado em trr_preco.
*/
$tipoPreco = (int) $infoContrato['trr_preco_tipo'];
$tipoMinuto = ($tipoPreco == 1);
$preco = $info['trr_preco'];
if ($tipoMinuto) {
$precoMinuto = $info['trr_preco'];
$cadencia = (int) $info['trr_vc'];
if (($cadencia < 60) && ($saldoPrepago < ($precoMinuto / 2.0)))
return 0;
if (($cadencia >= 60) && ($saldoPrepago < ($precoMinuto)))
return 0;
return ((int) (($saldoPrepago / $precoMinuto) * 60)) * 1000;
}
else {
return (int) ($saldoPrepago > $preco ? 99999999 : 0);
}
}
function logStr($msg, $metodo = "", $script = "", $pathLog = "", $logErro = false) {
$data = date("Y-m-d H:i:s");
@ -532,24 +58,6 @@ function GravaLog($log, $path) {
fclose($arq);
}
function Excpt($msg, $metodo = "", $erro = '') {
//$erroSys = error_get_last();
//$msg = sprintf("%s#%s#%s#%s#%s#%s",$msg, $erroSys['type'], $erroSys['message'], $erroSys['file'], $erroSys['line'], $metodo);
$msg = sprintf("%s -> %s <- %s", (!empty($metodo)) ? "Motodo [{$metodo}] " : '', $msg, (!empty($erro)) ? "Erro: $erro" : "");
logBkp($msg);
throw new Exception($msg);
}
function logBkp($msg, $logDate = true, $echo = true) {
$log = $msg;
if ($logDate) {
$log = date('d/m/Y H:i:s') . ': ' . $msg . "\n";
if ($echo) {
echo $log;
}
}
GravaLog($log, BackupConfig::$logFile);
}
/*
@ -647,460 +155,11 @@ function ErrorGetLast($type = "message") {
return $erro[$type];
}
function GetAtualizacoes($db, $cliId) {
/*
* Esta consulta traz todos os arquivos que o cliente ainda nao atualizou na portabilidade.
*/
$query = "select idarquivo
from atualizacoes a
where erro = 0
and idarquivo > coalesce((select max(idarquivo) from clientes a, clientes_atualizacoes b where b.cli_id = a.cli_id and cli_idexterno = '$cliId'), 0)";
$result = pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("Erro ao buscar atualizacoes no servidor remoto!"));
if (!pg_num_rows($result)) {
return false;
}
$dados = array();
while ($row = pg_fetch_row($result)) {
$dados[] = $row[0];
}
return $dados;
}
function GetAtualizacoesDados($db, $idAtualiza, $limit, $offset) {
/*
* Esta consulta retorna todos o comandos que devem ser executados para atualizar a base
* da portabilidade no cliente.
*/
global $debug;
$query = "select comando from atualizacoes_itens where idarquivo = '$idAtualiza' limit $limit offset $offset";
if ($debug)
echo "Selecionando: $query\n";
$result = pg_query($db, $query);
/*
* Sinaliza que ocorreu algum erro ao consultar o banco de dados.
*/
if (!$result)
throw new Exception(GetExcept("Erro ao buscar dados de atualizacoes no servidor remoto!"));
/*
* Indica que nao exitem atualizacoes disponiveis.
*/
if (!pg_num_rows($result))
return false;
$dados = array();
while ($row = pg_fetch_row($result)) {
$dados[] = $row[0];
}
return $dados;
}
function GetNumRegAtaulizacao($dbRemoto, $idAtualiza) {
$query = "select count(*) as numero from atualizacoes_itens where idarquivo = '$idAtualiza'";
$result = pg_query($dbRemoto, $query);
if (!$result)
throw new Exception(GetExcept("Erro ao buscar numero de atualizacoes no servidor remoto! Id: $idAtualiza"));
if (!pg_num_rows($result))
return 0;
$dados = array();
$row = pg_fetch_row($result);
return $row[0];
}
function VerificaStatus($dbRemoto, $cliId) {
/*
* Verifica o status do cliente para executar a acao adequada.
* -1 -> Desativado ou excluido
* 1 -> Normal
* 2 -> Aguardando instalacao.
*/
$query = "select clie_status from clientes where cli_idexterno = '$cliId'";
$result = pg_query($dbRemoto, $query);
if (!$result)
throw new Exception(GetExcept("Nao foi possivel verificar o status do cliente!"));
$row = pg_fetch_row($result);
return $row[0];
return true;
}
function GetCliIdPorta($dbPorta, $idExt) {
$query = "select cli_id from clientes where cli_idexterno = '$idExt'";
$result = pg_query($dbPorta, $query);
/*
* Erro na consulta.
*/
if (!$result) {
return -1;
}
/*
* Nao encontrou o cliente.
*/
if (!pg_num_rows($result)) {
return 0;
}
/*
* Retorna o id do cliente cadastrado.
*/
$row = pg_fetch_array($result);
return $row[0];
}
function PortabAtualizando($db = null) {
if (!$db) {
$db = GetAlernativeDB($dbHost = '', $dbPort = '', $dbName = 'portabilidade', $dbUser = '', $dbPass = '');
}
try {
$query = "select '' as reg from atualizacoes_registro where atr_data = now()::date and atr_fim is null";
$result = pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("IniciaAtualizacao: Nao foi possivel verifica se ha uma atualizacao em andamento!"));
return pg_num_rows($result) ? true : false;
} catch (Exception $ex) {
return false;
}
}
function PortabSolicitaConexao($db, $cliIdExterno) {
define("MAX_CONN_CLIENTE_PORTAB", 3);
if (!$db) {
$db = GetAlernativeDB($dbHost = '', $dbPort = '', $dbName = 'portabilidade', $dbUser = '', $dbPass = '');
}
try {
$query = "select count(*) as reg from controle_conexao where ctrc_data = now()::date and ctrc_fim is null";
$result = pg_query($db, $query);
if (!$result)
throw new Exception(GetExcept("PortabSolicitaConexao: Nao foi possivel verifica se ha conexoes ativas!"));
$row = pg_fetch_row($result);
$connecta = MAX_CONN_CLIENTE_PORTAB > $row[0];
if ($connecta) {
$query = "insert into controle_conexao( ctrc_data, cli_id, ctrc_inicio)values(now()::date, '$cliIdExterno', now())";
$result = pg_query($db, $query);
if (!$result || !pg_affected_rows($result)) {
throw new Exception(GetExcept("PortabSolicitaConexao: Nao foi possivel registrar a conexao!"));
}
return true;
}
return false;
} catch (Exception $ex) {
return false;
}
}
function GetExcept($msg) {
$ex = error_get_last();
return sprintf("%s\nErro: %s\n", trim($msg), trim($ex['message']));
}
function GetTipoChamadaCod($destino, $dddPadrao, $tipo) {
/*
* fixo movel local inter ddi
* -- 1 -> Interna;
* -- 2 -> Entrada,
* 21 -> Entrada Fixo Local,
* 22 -> Entrada Fixo Interurbano,
* 23 -> Entrada Movel Local,
* 24 -> Entrada Movel Interurbano
* 25 -> Entrada Internacional;
* -- 3 -> Saida,
* 31 -> Saida Fixo Local,
* 32 -> Saida Fixo Interurbano,
* 33 -> Saida Movel local,
* 34 -> Saida Movel Interurbano,
* 35 -> Saida Internacional;
* -- 4 -> Emergencia;
* -- 5 -> Zero oitocentos
*
-- delete from pbx_tipo_ligacao
-- select * from pbx_tipo_ligacao
-- create table pbx_tipo_ligacao(tplg_codigo int not null primary key, tplg_descricao varchar(64) not null, tplg_tipo int not null);
insert into pbx_tipo_ligacao values( 1, 'Interna', 1);
insert into pbx_tipo_ligacao values( 2, 'Entrada', 2);
insert into pbx_tipo_ligacao values(21, 'Entrada Fixo Local', 2);
insert into pbx_tipo_ligacao values(22, 'Entrada Fixo Interurbano', 2);
insert into pbx_tipo_ligacao values(23, 'Entrada Movel Local', 2);
insert into pbx_tipo_ligacao values(24, 'Entrada Movel Interurbano', 2);
insert into pbx_tipo_ligacao values(25, 'Entrada Internacional', 2);
insert into pbx_tipo_ligacao values( 3, 'Saida', 3);
insert into pbx_tipo_ligacao values(31, 'Saida Fixo Local', 3);
insert into pbx_tipo_ligacao values(32, 'Saida Fixo Interurbano', 3);
insert into pbx_tipo_ligacao values(33, 'Saida Movel local', 3);
insert into pbx_tipo_ligacao values(34, 'Saida Movel Interurbano', 3);
insert into pbx_tipo_ligacao values(35, 'Saida Internacional', 3);
insert into pbx_tipo_ligacao values( 4, 'Emergencia', 4);
insert into pbx_tipo_ligacao values( 5, 'Zero Oitocentos', 5);
*/
/*
* $direcao -> I = Interna, E = Entrada, S = Saida.
*/
$direcao = strtoupper(trim($tipo));
if ($direcao === 'I') {
return 1;
}
/*
* Verifica chamadas de emergencia, nao tratadas adequadamente pela funcao GetTipoChamada.
*/
$arEmergencia = array('100', '128', '190', '191', '192', '193', '194', '197', '198', '199');
if (array_search($destino, $arEmergencia) !== false) {
return 4;
}
/*
* Verifica chamadas 0800, nao tratadas adequadamente pela funcao GetTipoChamada.
*/
if (substr($destino, 0, 4) == '0800') {
return 5;
}
/*
* Funcao analisa o tipo de chamada
*/
list($tpFone, $tpChamada) = GetTipoChamada($destino, $dddPadrao);
if ($direcao === 'E') {
if (($tpFone === 'fixo') && ($tpChamada === 'local')) {
return 21;
} else if (($tpFone === 'fixo') && ($tpChamada === 'inter')) {
return 22;
} else if (($tpFone === 'movel') && ($tpChamada === 'local')) {
return 23;
} else if (($tpFone === 'movel') && ($tpChamada === 'inter')) {
return 24;
} else if (($tpFone === 'fixo') && ($tpChamada === 'ddi')) {
return 25;
}
}
if ($direcao === 'S') {
if (($tpFone === 'fixo') && ($tpChamada === 'local')) {
return 31;
} else if (($tpFone === 'fixo') && ($tpChamada === 'inter')) {
return 32;
} else if (($tpFone === 'movel') && ($tpChamada === 'local')) {
return 33;
} else if (($tpFone === 'movel') && ($tpChamada === 'inter')) {
return 34;
} else if (($tpFone === 'fixo') && ($tpChamada === 'ddi')) {
return 35;
}
}
return 0;
}
function GetTipoChamadaDesc($cod) {
/*
* fixo movel local inter ddi
* -- 1 -> Interna;
* -- 2 -> Entrada,
* 21 -> Entrada Fixo Local,
* 22 -> Entrada Fixo Interurbano,
* 23 -> Entrada Movel Local,
* 24 -> Entrada Movel Interurbano
* 25 -> Entrada Internacional;
* -- 3 -> Saida,
* 31 -> Saida Fixo Local,
* 32 -> Saida Fixo Interurbano,
* 33 -> Saida Movel local,
* 34 -> Saida Movel Interurbano,
* 35 -> Saida Internacional;
* -- 4 -> Emergencia;
* -- 5 -> Zero oitocentos
*/
switch ($cod) {
case 1: return 'Interna';
case 4: return 'Emergencia';
case 5: return 'Gratuita';
case 21: return 'Local Fixo';
case 22: return 'Interurbano Fixo';
case 23: return 'Local Movel';
case 24: return 'Interurbano Movel';
case 25: return 'Internacional';
case 31: return 'Local Fixo';
case 32: return 'Interurbano Fixo';
case 33: return 'Local Movel';
case 34: return 'Interurbano Movel';
case 35: return 'Internacional';
default:
return 'NI';
}
}
function ChamadaFila($uid, $temp = 1) {
$query = sprintf("select strtoint(param2, 0) as billsec from %s where uid2 = %s and evento in('COMPLETACALLER', 'COMPLETAAGENT', 'TRANSFERORIG', 'COMPLETECALLER', 'COMPLETEAGENT', 'TRANSFER','COMPLETECALLERRAMAL')", ($temp ? 'ast_eventos_dacs' : 'pbx_eventos_dacs'), QuotedStr($uid));
$result = pg_query($query);
if (!pg_num_rows($result))
return 0;
$row = pg_fetch_row($result);
return $row[0];
}
function GetIdMunicipio($tipo, $dddPadrao, $destino, $useBanco = true) {
$tamPrefixo = 6;
$movel = ($tipo == 23) || ($tipo == 24) || ($tipo == 33) || ($tipo == 34);
/*
* ligacao Interna,Eemergencia, Gratuita(0800) e internacional nao tem municipio associado.
*/
if (($tipo == 1) || ($tipo == 4) || ($tipo == 5) || ($tipo == 25) || ($tipo == 35)) {
return '0';
}
/*
*
*/
if ($movel) {
if (strlen($destino) == 9) {
$dddCel = $dddPadrao;
} else {
$dddCel = substr(substr($destino, -11), 0, 2);
}
/*
* Procura o municipio em um array global previamente alimentado.
*/
if (!$useBanco) {
return GetIdMunicipioMovel($dddCel);
}
$query = sprintf("select id from (select min(id) as id, codigo_ddd, uf from pbx_municipios group by codigo_ddd, uf) a where codigo_ddd = %s", StrToIntDef($dddCel));
} else {
if (strlen($destino) == 8)
$destino = $dddPadrao . $destino;
$destino = soNumero(substr($destino, -10));
$prefixo = StrToIntDef(substr($destino, 0, 6));
$numero = StrToIntDef(substr($destino, -4));
/*
* Procura o municipio em um array global previamente alimentado.
*/
if (!$useBanco) {
return GetIdMunicipioFixo($prefixo, $numero);
}
$query = sprintf("select id from pbx_municipios where prefixo = '%s' and '%s' >= faixa_inicial and '%s' <= faixa_final", $prefixo, $numero, $numero);
}
$result = pg_query($query);
if (!$result || !pg_num_rows($result)) {
$codMun = -1;
} else {
$dados = pg_fetch_row($result);
$codMun = $dados[0];
}
return $codMun;
}
function PreparaConsltaMunicipio() {
global $arPrefixo, $arDddMunicipio;
$query = "select distinct prefixo, faixa_inicial, faixa_final, id, codigo_ddd from pbx_municipios";
$result = pg_query($query);
if (!$result || !pg_num_rows($result)) {
return;
}
$dddOld = '';
$prefixoAtual = '';
while ($dados = pg_fetch_array($result, null, PGSQL_ASSOC)) {
/*
* Separa os dados por prefixo para facilitar a consulta de
* prefixo por faixa.
*/
$prefixo = $dados["prefixo"];
if (($prefixo != $prefixoAtual) && $prefixoAtual) {
$arPrefixo[$prefixoAtual] = $dadosPrefixo;
$dadosPrefixo = array();
}
$dadosPrefixo[] = $dados;
$prefixoAtual = $prefixo;
/*
* Inclui um municipio por ddd para ser usado na
* consulta de uf para movel.
*/
$dddAtual = $dados["codigo_ddd"];
if (!$dddOld || ($dddOld != $dddAtual)) {
$arDddMunicipio[$dddAtual] = $dados[id];
$dddOld = $dddAtual;
}
}
if (count($dadosPrefixo)) {
$arPrefixo[$prefixo] = $dadosPrefixo;
}
}
function GetIdMunicipioMovel($ddd) {
global $arDddMunicipio;
return $arDddMunicipio[$ddd] ? $arDddMunicipio[$ddd] : '-1';
}
function GetIdMunicipioFixo($prefixo, $sufixo) {
global $arPrefixo;
$arPesquisa = $arPrefixo[$prefixo];
if (!count($arPesquisa)) {
return '-1';
}
foreach ($arPesquisa as $dados) {
$faixaInicial = $dados['faixa_inicial'];
$faixaFinal = $dados['faixa_final'];
$id = $dados['id'];
if (($sufixo >= $faixaInicial) && ($sufixo <= $faixaFinal)) {
return $id ? $id : '-1';
}
}
return -1;
}
function TrataEntrada($numero) {
$num = trim($numero);
/*
* Trata ligacoes entrantes vindas de operadoras voip, para que
* nao sejam confundidas com ligacoes internacionais.
*
*/
if (substr($num, 0, 2) == '00') {
return substr($num, 2);
}
return $num;
}
/* commnad lines
* $rows = intval(`tput lines`);
$cols = intval(`tput cols`);
$colors = intval(`tput colors`);
echo "monitor $rows x $cols with $colors colors\n";
*/
?>

BIN
include/securimage/AHGBold.ttf

Binary file not shown.

25
include/securimage/LICENSE.txt

@ -1,25 +0,0 @@
COPYRIGHT:
Copyright (c) 2011 Drew Phillips
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

12
include/securimage/README.FONT.txt

@ -1,12 +0,0 @@
AHGBold.ttf is used by Securimage under the following license:
Alte Haas Grotesk is a typeface that look like an helvetica printed in an old Muller-Brockmann Book.
These fonts are freeware and can be distributed as long as they are
together with this text file.
I would appreciate very much to see what you have done with it anyway.
yann le coroller
www.yannlecoroller.com
yann@lecoroller.com

204
include/securimage/README.txt

@ -1,204 +0,0 @@
NAME:
Securimage - A PHP class for creating captcha images and audio with many options.
VERSION:
3.5.4
AUTHOR:
Drew Phillips <drew@drew-phillips.com>
DOWNLOAD:
The latest version can always be
found at http://www.phpcaptcha.org
DOCUMENTATION:
Online documentation of the class, methods, and variables can
be found at http://www.phpcaptcha.org/Securimage_Docs/
REQUIREMENTS:
PHP 5.2 or greater
GD 2.0
FreeType (Required, for TTF fonts)
PDO (if using Sqlite, MySQL, or PostgreSQL)
SYNOPSIS:
require_once 'securimage.php';
**Within your HTML form**
<form method="post" action="">
.. form elements
<div>
<?php echo Securimage::getCaptchaHtml() ?>
</div>
</form>
**Within your PHP form processor**
// Code Validation
$image = new Securimage();
if ($image->check($_POST['captcha_code']) == true) {
echo "Correct!";
} else {
echo "Sorry, wrong code.";
}
DESCRIPTION:
What is Securimage?
Securimage is a PHP class that is used to generate and validate CAPTCHA
images.
The classes uses an existing PHP session or creates its own if
none is found to store the CAPTCHA code. In addition, a database can be
used instead of session storage.
Variables within the class are used to control the style and display of
the image. The class uses TTF fonts and effects for strengthening the
security of the image.
It also creates audible codes which are played for visually impared users.
COPYRIGHT:
Copyright (c) 2014 Drew Phillips
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
LICENSES:
The WavFile.php class used in Securimage by Drew Phillips and Paul Voegler
is used under the BSD License. See WavFile.php for details.
Many thanks to Paul Voegler (http://www.voegler.eu/) for contributing to
Securimage.
---------------------------------------------------------------------------
Flash code created by Age Bosma & Mario Romero (animario@hotmail.com)
Many thanks for releasing this to the project!
---------------------------------------------------------------------------
Portions of Securimage contain code from Han-Kwang Nienhuys' PHP captcha
Han-Kwang Nienhuys' PHP captcha
Copyright June 2007
This copyright message and attribution must be preserved upon
modification. Redistribution under other licenses is expressly allowed.
Other licenses include GPL 2 or higher, BSD, and non-free licenses.
The original, unrestricted version can be obtained from
http://www.lagom.nl/linux/hkcaptcha/
---------------------------------------------------------------------------
AHGBold.ttf (AlteHaasGroteskBold.ttf) font was created by Yann Le Coroller
and is distributed as freeware.
Alte Haas Grotesk is a typeface that look like an helvetica printed in an
old Muller-Brockmann Book.
These fonts are freeware and can be distributed as long as they are
together with this text file.
I would appreciate very much to see what you have done with it anyway.
yann le coroller
www.yannlecoroller.com
yann@lecoroller.com
---------------------------------------------------------------------------
Portions of securimage_play.swf use the PopForge flash library for
playing audio
/**
* Copyright(C) 2007 Andre Michelle and Joa Ebert
*
* PopForge is an ActionScript3 code sandbox developed by Andre Michelle
* and Joa Ebert
* http://sandbox.popforge.de
*
* PopforgeAS3Audio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* PopforgeAS3Audio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
--------------------------------------------------------------------------
Some graphics used are from the Humility Icon Pack by WorLord
License: GNU/GPL (http://findicons.com/pack/1723/humility)
http://findicons.com/icon/192558/gnome_volume_control
http://findicons.com/icon/192562/gtk_refresh
--------------------------------------------------------------------------
Background noise sound files are from SoundJay.com
http://www.soundjay.com/tos.html
All sound effects on this website are created by us and protected under
the copyright laws, international treaty provisions and other applicable
laws. By downloading sounds, music or any material from this site implies
that you have read and accepted these terms and conditions:
Sound Effects
You are allowed to use the sounds free of charge and royalty free in your
projects (such as films, videos, games, presentations, animations, stage
plays, radio plays, audio books, apps) be it for commercial or
non-commercial purposes.
But you are NOT allowed to
- post the sounds (as sound effects or ringtones) on any website for
others to download, copy or use
- use them as a raw material to create sound effects or ringtones that
you will sell, distribute or offer for downloading
- sell, re-sell, license or re-license the sounds (as individual sound
effects or as a sound effects library) to anyone else
- claim the sounds as yours
- link directly to individual sound files
- distribute the sounds in apps or computer programs that are clearly
sound related in nature (such as sound machine, sound effect
generator, ringtone maker, funny sounds app, sound therapy app, etc.)
or in apps or computer programs that use the sounds as the program's
sound resource library for other people's use (such as animation
creator, digital book creator, song maker software, etc.). If you are
developing such computer programs, contact us for licensing options.
If you use the sound effects, please consider giving us a credit and
linking back to us but it's not required.

1899
include/securimage/WavFile.php

File diff suppressed because it is too large Load Diff

1
include/securimage/database/.htaccess

@ -1 +0,0 @@
deny from all

1
include/securimage/database/index.html

@ -1 +0,0 @@

BIN
include/securimage/database/securimage.sq3

Binary file not shown.

207
include/securimage/example_form.ajax.php

@ -1,207 +0,0 @@
<?php
session_start(); // this MUST be called prior to any output including whitespaces and line breaks!
$GLOBALS['ct_recipient'] = 'YOU@EXAMPLE.COM'; // Change to your email address!
$GLOBALS['ct_msg_subject'] = 'Securimage Test Contact Form';
$GLOBALS['DEBUG_MODE'] = 1;
// CHANGE TO 0 TO TURN OFF DEBUG MODE
// IN DEBUG MODE, ONLY THE CAPTCHA CODE IS VALIDATED, AND NO EMAIL IS SENT
// Process the form, if it was submitted
process_si_contact_form();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Securimage Example Form</title>
<style type="text/css">
<!--
#success_message { border: 1px solid #000; width: 550px; text-align: left; padding: 10px 7px; background: #33ff33; color: #000; font-weight; bold; font-size: 1.2em; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; }
fieldset { width: 90%; }
legend { font-size: 24px; }
.note { font-size: 18px; }
-->
</style>
</head>
<body>
<fieldset>
<legend>Example Form</legend>
<p class="note">
This is an example PHP form that processes user information, checks for errors, and validates the captcha code.<br />
This example form also demonstrates how to submit a form to itself to display error messages.
</p>
<div id="success_message" style="display: none">Your message has been sent!<br />We will contact you as soon as possible.</div>
<form method="post" action="" id="contact_form" onsubmit="return processForm()">
<input type="hidden" name="do" value="contact" />
<p>
<strong>Name*:</strong><br />
<input type="text" name="ct_name" size="35" value="" />
</p>
<p>
<strong>Email*:</strong><br />
<input type="text" name="ct_email" size="35" value="" />
</p>
<p>
<strong>URL:</strong><br />
<input type="text" name="ct_URL" size="35" value="" />
</p>
<p>
<strong>Message*:</strong><br />
<textarea name="ct_message" rows="12" cols="60"></textarea>
</p>
<p>
<img id="siimage" style="border: 1px solid #000; margin-right: 15px" src="./securimage_show.php?sid=<?php echo md5(uniqid()) ?>" alt="CAPTCHA Image" align="left" />
<object type="application/x-shockwave-flash" data="./securimage_play.swf?bgcol=#ffffff&amp;icon_file=./images/audio_icon.png&amp;audio_file=./securimage_play.php" height="32" width="32">
<param name="movie" value="./securimage_play.swf?bgcol=#ffffff&amp;icon_file=./images/audio_icon.png&amp;audio_file=./securimage_play.php" />
</object>
&nbsp;
<a tabindex="-1" style="border-style: none;" href="#" title="Refresh Image" onclick="document.getElementById('siimage').src = './securimage_show.php?sid=' + Math.random(); this.blur(); return false"><img src="./images/refresh.png" alt="Reload Image" height="32" width="32" onclick="this.blur()" align="bottom" border="0" /></a><br />
<strong>Enter Code*:</strong><br />
<input type="text" name="ct_captcha" size="12" maxlength="8" />
</p>
<p>
<br />
<input type="submit" value="Submit Message" />
</p>
</form>
</fieldset>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$.noConflict();
function reloadCaptcha()
{
jQuery('#siimage').prop('src', './securimage_show.php?sid=' + Math.random());
}
function processForm()
{
jQuery.ajax({
url: '<?php echo $_SERVER['PHP_SELF'] ?>',
type: 'POST',
data: jQuery('#contact_form').serialize(),
dataType: 'json',
}).done(function(data) {
if (data.error === 0) {
jQuery('#success_message').show();
jQuery('#contact_form')[0].reset();
reloadCaptcha();
setTimeout("jQuery('#success_message').fadeOut()", 12000);
} else {
alert("There was an error with your submission.\n\n" + data.message);
}
});
return false;
}
</script>
</body>
</html>
<?php
// The form processor PHP code
function process_si_contact_form()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST' && @$_POST['do'] == 'contact') {
// if the form has been submitted
foreach($_POST as $key => $value) {
if (!is_array($key)) {
// sanitize the input data
if ($key != 'ct_message') $value = strip_tags($value);
$_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
}
}
$name = @$_POST['ct_name']; // name from the form
$email = @$_POST['ct_email']; // email from the form
$URL = @$_POST['ct_URL']; // url from the form
$message = @$_POST['ct_message']; // the message from the form
$captcha = @$_POST['ct_captcha']; // the user's entry for the captcha code
$name = substr($name, 0, 64); // limit name to 64 characters
$errors = array(); // initialize empty error array
if (isset($GLOBALS['DEBUG_MODE']) && $GLOBALS['DEBUG_MODE'] == false) {
// only check for errors if the form is not in debug mode
if (strlen($name) < 3) {
// name too short, add error
$errors['name_error'] = 'Your name is required';
}
if (strlen($email) == 0) {
// no email address given
$errors['email_error'] = 'Email address is required';
} else if ( !preg_match('/^(?:[\w\d-]+\.?)+@(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/i', $email)) {
// invalid email format
$errors['email_error'] = 'Email address entered is invalid';
}
if (strlen($message) < 20) {
// message length too short
$errors['message_error'] = 'Please enter a message';
}
}
// Only try to validate the captcha if the form has no errors
// This is especially important for ajax calls
if (sizeof($errors) == 0) {
require_once dirname(__FILE__) . '/securimage.php';
$securimage = new Securimage();
if ($securimage->check($captcha) == false) {
$errors['captcha_error'] = 'Incorrect security code entered';
}
}
if (sizeof($errors) == 0) {
// no errors, send the form
$time = date('r');
$message = "A message was submitted from the contact form. The following information was provided.<br /><br />"
. "Name: $name<br />"
. "Email: $email<br />"
. "URL: $URL<br />"
. "Message:<br />"
. "<pre>$message</pre>"
. "<br /><br />IP Address: {$_SERVER['REMOTE_ADDR']}<br />"
. "Time: $time<br />"
. "Browser: {$_SERVER['HTTP_USER_AGENT']}<br />";
if (isset($GLOBALS['DEBUG_MODE']) && $GLOBALS['DEBUG_MODE'] == false) {
// send the message with mail()
mail($GLOBALS['ct_recipient'], $GLOBALS['ct_msg_subject'], $message, "From: {$GLOBALS['ct_recipient']}\r\nReply-To: {$email}\r\nContent-type: text/html; charset=ISO-8859-1\r\nMIME-Version: 1.0");
}
$return = array('error' => 0, 'message' => 'OK');
die(json_encode($return));
} else {
$errmsg = '';
foreach($errors as $key => $error) {
// set up error messages to display with each field
$errmsg .= " - {$error}\n";
}
$return = array('error' => 1, 'message' => $errmsg);
die(json_encode($return));
}
} // POST
} // function process_si_contact_form()

203
include/securimage/example_form.php

@ -1,203 +0,0 @@
<?php
session_start(); // this MUST be called prior to any output including whitespaces and line breaks!
$GLOBALS['DEBUG_MODE'] = 1;
// CHANGE TO 0 TO TURN OFF DEBUG MODE
// IN DEBUG MODE, ONLY THE CAPTCHA CODE IS VALIDATED, AND NO EMAIL IS SENT
$GLOBALS['ct_recipient'] = 'YOU@EXAMPLE.COM'; // Change to your email address! Make sure DEBUG_MODE above is 0 for mail to send!
$GLOBALS['ct_msg_subject'] = 'Securimage Test Contact Form';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Securimage Example Form</title>
<style type="text/css">
<!--
div.error { display: block; color: #f00; font-weight: bold; font-size: 1.2em; }
span.error { display: block; color: #f00; font-style: italic; }
.success { color: #00f; font-weight: bold; font-size: 1.2em; }
form label { display: block; font-weight: bold; }
fieldset { width: 90%; }
legend { font-size: 24px; }
.note { font-size: 18px;
-->
</style>
</head>
<body>
<fieldset>
<legend>Example Form</legend>
<p class="note">
This is an example PHP form that processes user information, checks for errors, and validates the captcha code.<br />
This example form also demonstrates how to submit a form to itself to display error messages.
</p>
<?php
process_si_contact_form(); // Process the form, if it was submitted
if (isset($_SESSION['ctform']['error']) && $_SESSION['ctform']['error'] == true): /* The last form submission had 1 or more errors */ ?>
<div class="error">There was a problem with your submission. Errors are displayed below in red.</div><br />
<?php elseif (isset($_SESSION['ctform']['success']) && $_SESSION['ctform']['success'] == true): /* form was processed successfully */ ?>
<div class="success">The captcha was correct and the message has been sent! The captcha was solved in <?php echo $_SESSION['ctform']['timetosolve'] ?> seconds.</div><br />
<?php endif; ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING']) ?>" id="contact_form">
<input type="hidden" name="do" value="contact" />
<p>
<label for="ct_name">Name*:</label>
<?php echo @$_SESSION['ctform']['name_error'] ?>
<input type="text" name="ct_name" size="35" value="<?php echo htmlspecialchars(@$_SESSION['ctform']['ct_name']) ?>" />
</p>
<p>
<label for="ct_email">Email*:</label>
<?php echo @$_SESSION['ctform']['email_error'] ?>
<input type="text" name="ct_email" size="35" value="<?php echo htmlspecialchars(@$_SESSION['ctform']['ct_email']) ?>" />
</p>
<p>
<label for="ct_URL">URL:</label>
<?php echo @$_SESSION['ctform']['URL_error'] ?>
<input type="text" name="ct_URL" size="35" value="<?php echo htmlspecialchars(@$_SESSION['ctform']['ct_URL']) ?>" />
</p>
<p>
<label for="ct_message">Message*:</label>
<?php echo @$_SESSION['ctform']['message_error'] ?>
<textarea name="ct_message" rows="12" cols="60"><?php echo htmlspecialchars(@$_SESSION['ctform']['ct_message']) ?></textarea>
</p>
<p>
<?php
// show captcha HTML using Securimage::getCaptchaHtml()
require_once 'securimage.php';
$options = array();
$options['input_name'] = 'ct_captcha'; // change name of input element for form post
if (!empty($_SESSION['ctform']['captcha_error'])) {
// error html to show in captcha output
$options['error_html'] = $_SESSION['ctform']['captcha_error'];
}
echo Securimage::getCaptchaHtml($options);
?>
</p>
<p>
<br />
<input type="submit" value="Submit Message" />
</p>
</form>
</fieldset>
</body>
</html>
<?php
// The form processor PHP code
function process_si_contact_form()
{
$_SESSION['ctform'] = array(); // re-initialize the form session data
if ($_SERVER['REQUEST_METHOD'] == 'POST' && @$_POST['do'] == 'contact') {
// if the form has been submitted
foreach($_POST as $key => $value) {
if (!is_array($key)) {
// sanitize the input data
if ($key != 'ct_message') $value = strip_tags($value);
$_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
}
}
$name = @$_POST['ct_name']; // name from the form
$email = @$_POST['ct_email']; // email from the form
$URL = @$_POST['ct_URL']; // url from the form
$message = @$_POST['ct_message']; // the message from the form
$captcha = @$_POST['ct_captcha']; // the user's entry for the captcha code
$name = substr($name, 0, 64); // limit name to 64 characters
$errors = array(); // initialize empty error array
if (isset($GLOBALS['DEBUG_MODE']) && $GLOBALS['DEBUG_MODE'] == false) {
// only check for errors if the form is not in debug mode
if (strlen($name) < 3) {
// name too short, add error
$errors['name_error'] = 'Your name is required';
}
if (strlen($email) == 0) {
// no email address given
$errors['email_error'] = 'Email address is required';
} else if ( !preg_match('/^(?:[\w\d-]+\.?)+@(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/i', $email)) {
// invalid email format
$errors['email_error'] = 'Email address entered is invalid';
}
if (strlen($message) < 20) {
// message length too short
$errors['message_error'] = 'Your message must be longer than 20 characters';
}
}
// Only try to validate the captcha if the form has no errors
// This is especially important for ajax calls
if (sizeof($errors) == 0) {
require_once dirname(__FILE__) . '/securimage.php';
$securimage = new Securimage();
if ($securimage->check($captcha) == false) {
$errors['captcha_error'] = 'Incorrect security code entered<br />';
}
}
if (sizeof($errors) == 0) {
// no errors, send the form
$time = date('r');
$message = "A message was submitted from the contact form. The following information was provided.<br /><br />"
. "<em>Name: $name</em><br />"
. "<em>Email: $email</em><br />"
. "<em>URL: $URL</em><br />"
. "<em>Message:</em><br />"
. "<pre>$message</pre>"
. "<br /><br /><em>IP Address:</em> {$_SERVER['REMOTE_ADDR']}<br />"
. "<em>Time:</em> $time<br />"
. "<em>Browser:</em> {$_SERVER['HTTP_USER_AGENT']}<br />";
$message = wordwrap($message, 70);
if (isset($GLOBALS['DEBUG_MODE']) && $GLOBALS['DEBUG_MODE'] == false) {
// send the message with mail()
mail($GLOBALS['ct_recipient'], $GLOBALS['ct_msg_subject'], $message, "From: {$GLOBALS['ct_recipient']}\r\nReply-To: {$email}\r\nContent-type: text/html; charset=UTF-8\r\nMIME-Version: 1.0");
}
$_SESSION['ctform']['timetosolve'] = $securimage->getTimeToSolve();
$_SESSION['ctform']['error'] = false; // no error with form
$_SESSION['ctform']['success'] = true; // message sent
} else {
// save the entries, this is to re-populate the form
$_SESSION['ctform']['ct_name'] = $name; // save name from the form submission
$_SESSION['ctform']['ct_email'] = $email; // save email
$_SESSION['ctform']['ct_URL'] = $URL; // save URL
$_SESSION['ctform']['ct_message'] = $message; // save message
foreach($errors as $key => $error) {
// set up error messages to display with each field
$_SESSION['ctform'][$key] = "<span class=\"error\">$error</span>";
}
$_SESSION['ctform']['error'] = true; // set error floag
}
} // POST
}
$_SESSION['ctform']['success'] = false; // clear success value after running

2972
include/securimage/securimage.php

File diff suppressed because it is too large Load Diff

65
include/securimage/securimage_play.php

@ -1,65 +0,0 @@
<?php
/**
* Project: Securimage: A PHP class for creating and managing form CAPTCHA images<br />
* File: securimage_play.php<br />
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.<br /><br />
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.<br /><br />
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA<br /><br />
*
* Any modifications to the library should be indicated clearly in the source code
* to inform users that the changes are not a part of the original software.<br /><br />
*
* If you found this script useful, please take a quick moment to rate it.<br />
* http://www.hotscripts.com/rate/49400.html Thanks.
*
* @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
* @link http://www.phpcaptcha.org/latest.zip Download Latest Version
* @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
* @copyright 2012 Drew Phillips
* @author Drew Phillips <drew@drew-phillips.com>
* @version 3.5.2 (Feb 15, 2014)
* @package Securimage
*
*/
require_once dirname(__FILE__) . '/securimage.php';
// if using database, adjust these options as necessary and change $img = new Securimage(); to $img = new Securimage($options);
// see test.mysql.php or test.sqlite.php for examples
$options = array(
'use_database' => true,
'database_name' => '',
'database_user' => '',
'database_driver' => Securimage::SI_DRIVER_MYSQL
);
$img = new Securimage();
// Other audio settings
//$img->audio_use_sox = true;
//$img->audio_use_noise = true;
//$img->degrade_audio = false;
//$img->sox_binary_path = 'sox';
// To use an alternate language, uncomment the following and download the files from phpcaptcha.org
// $img->audio_path = $img->securimage_path . '/audio/es/';
// If you have more than one captcha on a page, one must use a custom namespace
// $img->namespace = 'form2';
// set namespace if supplied to script via HTTP GET
if (!empty($_GET['namespace'])) $img->setNamespace($_GET['namespace']);
$img->outputAudioFile();

BIN
include/securimage/securimage_play.swf

Binary file not shown.

79
include/securimage/securimage_show.php

@ -1,79 +0,0 @@
<?php
/**
* Project: Securimage: A PHP class for creating and managing form CAPTCHA images<br />
* File: securimage_show.php<br />
*
* Copyright (c) 2013, Drew Phillips
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Any modifications to the library should be indicated clearly in the source code
* to inform users that the changes are not a part of the original software.<br /><br />
*
* If you found this script useful, please take a quick moment to rate it.<br />
* http://www.hotscripts.com/rate/49400.html Thanks.
*
* @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
* @link http://www.phpcaptcha.org/latest.zip Download Latest Version
* @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
* @copyright 2013 Drew Phillips
* @author Drew Phillips <drew@drew-phillips.com>
* @version 3.5.2 (Feb 15, 2014)
* @package Securimage
*
*/
// Remove the "//" from the following line for debugging problems
// error_reporting(E_ALL); ini_set('display_errors', 1);
require_once dirname(__FILE__) . '/securimage.php';
$img = new Securimage();
// You can customize the image by making changes below, some examples are included - remove the "//" to uncomment
//$img->ttf_file = './Quiff.ttf';
//$img->captcha_type = Securimage::SI_CAPTCHA_MATHEMATIC; // show a simple math problem instead of text
//$img->case_sensitive = true; // true to use case sensitve codes - not recommended
//$img->image_height = 90; // height in pixels of the image
//$img->image_width = $img->image_height * M_E; // a good formula for image size based on the height
//$img->perturbation = .75; // 1.0 = high distortion, higher numbers = more distortion
//$img->image_bg_color = new Securimage_Color("#0099CC"); // image background color
//$img->text_color = new Securimage_Color("#EAEAEA"); // captcha text color
//$img->num_lines = 8; // how many lines to draw over the image
//$img->line_color = new Securimage_Color("#0000CC"); // color of lines over the image
//$img->image_type = SI_IMAGE_JPEG; // render as a jpeg image
//$img->signature_color = new Securimage_Color(rand(0, 64),
// rand(64, 128),
// rand(128, 255)); // random signature color
// see securimage.php for more options that can be set
// set namespace if supplied to script via HTTP GET
if (!empty($_GET['namespace'])) $img->setNamespace($_GET['namespace']);
$img->show(); // outputs the image and content headers to the browser
// alternate use:
// $img->show('/path/to/background_image.jpg');

15457
include/securimage/words/words.txt

File diff suppressed because it is too large Load Diff

222
include/util/datas.php

@ -1,222 +0,0 @@
<?php
// *
// * @author Andre Lourenco Pedroso - alp.pedroso@gmail.com
// *
// * @date 15 de Janeiro de 2007
// *
/**
*
* - Manipulacao de Data ou Hora.
*
* Operacoes: soma DIA, MES ,ANO, HORA, MINUTOS, SEGUNDOS.
* Formatos :
* Data: 15/01/2007
* Hora: 10:35:00
* Para subtrair, basta passar um valor negativo:
* Ex:
* $obj->somaDia(-10);
*
* - Calcula diferenca entre duas datas.
*
* Operacoes: difDataHora.
* Formatos :
* Data: 15/01/2007 10:35:00
* E necessario passar duas datas como parametro e o tipo de retorno desejado:
* Ex:
* $obj->difDataHora($dataMenor,$dataMaior,"m");
*
*/
class CalcDataHora {
private $data;
private $hora;
private $fmtDef = array("d" => 0, "m" => 1, "y" => 2, "h" => 0, "i" => 1, "s" => 2);
public function somaDia($dias = 1) {
$this->CalcDataHora(strftime_("%d/%m/%Y", mktime(0, 0, 0, $this->data[1], $this->data[0] +
$dias, $this->data[2])), "");
return $this->data;
}
function CalcDataHora($data = "", $hora = "") {
if ($hora == "") {
$hora = date("H:i:s");
}
if ($data == "") {
$data = date("d/m/Y");
} else if ($this->validaData($data, "d")) {
die("Padrao de data ($data) invalido! - Padrao = 15/01/2007");
}
$this->data = explode("/", $data);
$this->hora = explode(":", $hora);
}
// DATA
private function validaData($data, $op) {
switch ($op) {
case "d": // Padrao: 15/01/2007
$er = "(([0][1-9]|[1-2][0-9]|[3][0-1])\/([0][1-9]|[1][0-2])\/([0-9]{4}))";
if ( preg_match($er, $data)) {
return 0;
} else {
return 1;
}
break;
case "dh": // Padrao 15/01/2007 10:30:00
$er = "(([0][1-9]|[1-2][0-9]|[3][0-1])\/([0][1-9]|[1][0-2])\/([0-9]{4})*)";
if ( preg_match($er, $data)) {
return 0;
} else {
return 1;
}
break;
}
}
public function somaMes($meses = 1) {
$this->CalcDataHora(strftime_("%d/%m/%Y", mktime(0, 0, 0, $this->data[1] +
$meses, $this->data[0], $this->data[2])), "");
return $this->data;
}
public function somaAno($anos = 1) {
$this->CalcDataHora(strftime_("%d/%m/%Y", mktime(0, 0, 0, $this->data[1], $this->data[0], $this->data[2] +
$anos)), "");
return $this->data;
}
public function getData($fmt = '') {
if ($fmt) {
/* d/m/Y */
$fmt = substr(trim(strtolower($fmt)), 0, 5);
$fmtA = preg_split('/[\/,:, , -]/', $fmt, -1);
$zero = $this->fmtDef[$fmtA[0]];
$um = $this->fmtDef[$fmtA[1]];
$dois = $this->fmtDef[$fmtA[2]];
$sep = count(preg_split('/\//', $fmt, -1)) > 1 ? '/' : '-';
return sprintf("%s%s%s%s%s", $this->data[$zero], $sep, $this->data[$um], $sep, $this->data[$dois]);
}
return $this->data[0] . "/" . $this->data[1] . "/" . $this->data[2];
}
public function getDataHora($fmt = '') {
if ($fmt) {
/* d/m/Y H:i:s */
$fmt = substr(trim(strtolower($fmt)), 0, 11);
$fmtA = preg_split('/[\/,:, , -]/', $fmt, -1);
$zero = $this->fmtDef[$fmtA[0]];
$um = $this->fmtDef[$fmtA[1]];
$dois = $this->fmtDef[$fmtA[2]];
$tres = $this->fmtDef[$fmtA[3]];
$quatro = $this->fmtDef[$fmtA[4]];
$cinco = $this->fmtDef[$fmtA[5]];
$sep = count(preg_split('/\//', $fmt, -1)) > 1 ? '/' : '-';
return sprintf("%s$sep%s$sep%s %s:%s:%s", $this->data[$zero], $this->data[$um], $this->data[$dois], $this->hora[$tres], $this->hora[$quatro], $this->hora[$cinco]);
}
return sprintf("%s/%s/%s %s:%s:%s", $this->data[0], $this->data[1], $this->data[2], $this->hora[0], $this->hora[1], $this->hora[2]);
}
// HORA
public function somaSegundo($segundos = 1) {
$this->CalcDataHora("", strftime_("%H:%M:%S", mktime($this->hora[0], $this->hora[1], $this->hora[2] +
$segundos, 0, 0, 0)));
return $this->hora;
}
public function somaMinuto($minutos = 1) {
$this->CalcDataHora("", strftime_("%H:%M:%S", mktime($this->hora[0], $this->hora[1] +
$minutos, $this->hora[2], 0, 0, 0)));
return $this->hora;
}
public function somaHora($horas = 1) {
$this->CalcDataHora("", strftime_("%H:%M:%S", mktime($this->hora[0] +
$horas, $this->hora[1], $this->hora[2], 0, 0, 0)));
return $this->hora;
}
public function getHora() {
return $this->hora[0] . ":" . $this->hora[1] . ":" . $this->hora[2];
}
/**
*
* Retorna diferen<EFBFBD>a entre as datas em Dias, Horas ou Minutos
* Function difDataHora(data menor, [data maior],[dias horas minutos segundos])
*
* Formato 04/05/2006 12:00:00
*
* Chame a funcao com o valor NULL como 'data maior' para 'data maior' = data atual.
*
* Formatacao do retorno [dias horas minutos segundos]:
*
* "s": Segundos
* "m": Minutos
* "H": Horas
* "h": Horas arredondada
* "D": Dias
* "d": Dias arredontados
*
* Original: Gambiarra.com.br Bozo@gambiarra.com.br
*
* Modificado: Andre Lourenco Pedroso alp.pedroso@gmail.com
* Data 15/01/2007 10:00
*/
public function difDataHora($datamenor, $datamaior = "", $tipo = "") {
if ($this->validaData($datamenor, "dh")) {
die("data errada - $datamenor");
}
if ($datamaior == "") {
$datamaior = date("d/m/Y H:i:s");
}
if ($tipo == "") {
$tipo = "h";
}
list ($diamenor, $mesmenor, $anomenor, $horamenor, $minutomenor, $segundomenor) = explode("[/: ]", $datamenor);
list ($diamaior, $mesmaior, $anomaior, $horamaior, $minutomaior, $segundomaior) = explode("[/: ]", $datamaior);
$segundos = mktime($horamaior, $minutomaior, $segundomaior, $mesmaior, $diamaior, $anomaior) -
mktime($horamenor, $minutomenor, $segundomenor, $mesmenor, $diamenor, $anomenor);
$diferenca = $segundos;
switch ($tipo) {
case "s": // Segundo
$diferenca = $segundos;
break;
case "m": // Minuto
$diferenca = $segundos / 60;
break;
case "H": // Hora
$diferenca = $segundos / 3600;
break;
case "h": // Hora Arredondada
$diferenca = round($segundos / 3600);
break;
case "D": // Dia
$diferenca = $segundos / 86400;
break;
case "d": // Dia Arredondado
$diferenca = round($segundos / 86400);
break;
}
return $diferenca;
}
}

2393
include/util/funcoesApl.php

File diff suppressed because it is too large Load Diff

2
include/util/funcoesLicenca.php

@ -306,7 +306,7 @@ function __sendLicenca($dbcon, $data, $columns, $table) {
function GetPerfilApl() {
$query = "SELECT * FROM pbx_grupo WHERE gp_system = 1 AND gp_id <> 43";
$resp = pg_query($query);
$resp = pg_query($GLOBALS["dbconn"], $query);
$resp = pg_fetch_all($resp);
return $resp;
}

1396
include/util/util.php

File diff suppressed because it is too large Load Diff

8
index.php

@ -1,11 +1,16 @@
<?php
session_start();
include_once('bd.php');
$GLOBALS["dbconn"] = pg_connect(GetConectString());
/*
* Verifica o tipo de requisição e inclui
* arquivos necessários e define variáveis.
*/
include("start.php");
include("start.php");
/*
* Inicializa variaveis de sessão checa autenticação do usuario
@ -16,4 +21,5 @@ include("checaSessao.php");
* Define Templates,scripts, css para a pagina
*/
include("iniciaCliente.php");
?>

139
iniciaCliente.php

@ -1,31 +1,32 @@
<?php
if (!IsAjax()) {
// busca atualizações de publicações apenas nas outras páginas
// busca atualizações de publicações apenas nas outras páginas
$iconMaster = "<link rel=\"shortcut icon\" href=\"img/logo_ip.png\"/>"; //ícone ao lado do titulo na aba do navegador
$infoBody = $tpLayout ? "marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\" leftmargin=\"0\"" : "";
$loginOn = !$_SESSION["SSlogin"] ? 0 : $_SESSION["SSlogin"];
$aguarde = !$useAguarde ? "" : "<div id=\"aguarde\">
$iconMaster = "<link rel=\"shortcut icon\" href=\"img/logo_ip.png\"/>"; //ícone ao lado do titulo na aba do navegador
$infoBody = $tpLayout ? "marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\" leftmargin=\"0\"" : "";
$loginOn = !$_SESSION["SSlogin"] ? 0 : $_SESSION["SSlogin"];
$aguarde = !$useAguarde ? "" : "<div id=\"aguarde\">
<table width=\"150\" height=\"50\" border=\"0\" cellpadding=\"3\" cellspacing=\"0\">
<tr>
<td width=\"40\" align=\"center\" valign=\"middle\"><img src=\"".LOADING_SITE."\" width=\"33\" height=\"33\"></td>
<td width=\"40\" align=\"center\" valign=\"middle\"><img src=\"" . LOADING_SITE . "\" width=\"33\" height=\"33\"></td>
<td align=\"center\" valign=\"middle\">Aguarde...</td>
</tr>
</table>
</div>";
$jsStartup[] = "new ClipboardJS('.copyjs',{text: function(){ return document.querySelector('#linkaudio').value}});";
$jsBlok[] = GetItensMenu($tpLayout);
$jsJQuery[] = " \$('#btConsulta').click(function(){ \$('#aguarde').show(); \$('#aguarde').css('display','block');});";
//$jsJQuery[] = " \$('#tabLayout').height($(document).height());";
//adiciona um calendario nos campos data
$jsJQuery[] = GetJqCalendario('', 'dataIni');
$jsJQuery[] = GetJqCalendario('', 'dataFim');
$newLoading = !$useAguarde ? "" : "<div id=\"overlay\"></div><div id=\"loading\" alt=\"Carregando...\"></div>";
$jsStartup[] = "new ClipboardJS('.copyjs',{text: function(){ return document.querySelector('#linkaudio').value}});";
$jsBlok[] = GetItensMenu($tpLayout);
$jsJQuery[] = " \$('#btConsulta').click(function(){ \$('#aguarde').show(); \$('#aguarde').css('display','block');});";
//$jsJQuery[] = " \$('#tabLayout').height($(document).height());";
//adiciona um calendario nos campos data
$jsJQuery[] = GetJqCalendario('', 'dataIni');
$jsJQuery[] = GetJqCalendario('', 'dataFim');
$exceptDesqtaque = [6, 14, 125, 117,20, 314];
$exceptDesqtaque = [6, 14, 125, 117, 20, 314];
if (array_search($idProg, $exceptDesqtaque) === false) {
$jsJQuery[] = "\$('.grid tr').hover(
if (array_search($idProg, $exceptDesqtaque) === false) {
$jsJQuery[] = "\$('.grid tr').hover(
function(){
\$(this).addClass('destaque');
},
@ -33,59 +34,63 @@ if (!IsAjax()) {
\$(this).removeClass('destaque');
}
);";
}
}
if (!$tpLayout) {
$jsJQuery[] = GetJqTips(':text');
$jsJQuery[] = GetJqTips('input');
$jsJQuery[] = GetJqTips('span');
$jsJQuery[] = GetJqTips('img');
}
if (!$tpLayout) {
$jsJQuery[] = GetJqTips(':text');
$jsJQuery[] = GetJqTips('input');
$jsJQuery[] = GetJqTips('span');
$jsJQuery[] = GetJqTips('img');
}
$styleLayout = $tpLayout ? 'width: 100%;' : "width: 90%;";
$jsStartup[] = sprintf("function GetVersaoApl(){ return '%s'; }", GetVersao());
PosAguarde();
$styleLayout = $tpLayout ? 'width: 100%;' : "width: 90%;";
if (isset($monitorLayout)) {
$styleLayout = 'width: 95%;';
}
$jsStartup[] = sprintf("function GetVersaoApl(){ return '%s'; }", GetVersao());
PosAguarde();
$smarty->assign('tituloSite', $tituloSite);
$smarty->assign('iconMaster', $iconMaster);
$smarty->assign('screenW', GetScreenW());
$smarty->assign('screenH', GetScreenH());
$smarty->assign('tbLayoutW', GetSizeTbLayout());
$smarty->assign('upload', GetEncType($upload));
$smarty->assign('cssBlock', $cssBlock);
$smarty->assign('infoBody', $infoBody);
$smarty->assign('tpLayout', $tpLayout);
$smarty->assign('styleLayout', $styleLayout);
$smarty->assign('scriptGlobal', GetJsLink($jsGlobal));
$smarty->assign('styleFile', GetStyleLink($tpLayout));
$smarty->assign('scriptPage', GetJsLink($jsPage));
$smarty->assign('scriptBlok', GetJsBlok($jsBlok));
$smarty->assign('scriptStartup', GetJsBlok($jsStartup));
$smarty->assign('jQuery', GetJQuery($jsJQuery));
$smarty->assign('logoPrinc', GetLogoPrinc($tpLayout));
$smarty->assign('setLogo', IsUserConnect() ? 'style="height: 0;"' : '');
$smarty->assign('navHeader', GetNavHeader($tpLayout));
$smarty->assign('navLogin', GetNavLogin($tpLayout, GetDispProgSel($idProg)));
$smarty->assign('onLoad', $onLoad);
$smarty->assign('menuGeral', GetMenuUser($tpLayout));
$smarty->assign('idProg', $idProg);
$smarty->assign('idSubProg', $idSubProg);
$smarty->assign('pbxRequest', ($isPbxRequest ? '1' : '0'));
$smarty->assign('vAlineMaster', $vAlineMaster);
$smarty->assign('wAlineMaster', $wAlineMaster);
$smarty->assign('heightMasterContent', ($tpLayout ? '100%' : $heightMasterContent));
$smarty->assign('setActPage', $setActPage); //action do form
$smarty->assign('setMethod', $setMethod); //método de envio do form
// $smarty->assign('erros', "");
//$smarty->assign('erros', $siteError->GetNumError() ? $siteError->DisplayError() : "");
$smarty->assign('conteudo', $conteudo);
$smarty->assign('aguarde', $aguarde);
$smarty->assign('footer', $tpLayout ? false : $footerDisplay);
$smarty->assign('functionForm', $functionForm);
$smarty->assign('versaoApl', GetVersao());
$smarty->assign('idHand', time());
$smarty->assign('szHeaderLayout', IsUserConnect() ? "height: 60px;" : "");
$smarty->display('master.tpl');
$smarty->assign('tituloSite', $tituloSite);
$smarty->assign('iconMaster', $iconMaster);
$smarty->assign('screenW', GetScreenW());
$smarty->assign('screenH', GetScreenH());
$smarty->assign('tbLayoutW', GetSizeTbLayout());
$smarty->assign('upload', GetEncType($upload));
$smarty->assign('cssBlock', $cssBlock);
$smarty->assign('infoBody', $infoBody);
$smarty->assign('tpLayout', $tpLayout);
$smarty->assign('monitorLayout', $monitorLayout);
$smarty->assign('styleLayout', $styleLayout);
$smarty->assign('scriptGlobal', GetJsLink($jsGlobal));
$smarty->assign('styleFile', GetStyleLink($tpLayout));
$smarty->assign('scriptPage', GetJsLink($jsPage));
$smarty->assign('scriptBlok', GetJsBlok($jsBlok));
$smarty->assign('scriptStartup', GetJsBlok($jsStartup));
$smarty->assign('jQuery', GetJQuery($jsJQuery));
$smarty->assign('logoPrinc', GetLogoPrinc($tpLayout));
$smarty->assign('setLogo', IsUserConnect() ? 'style="height: 0;"' : '');
$smarty->assign('navHeader', GetNavHeader($tpLayout));
$smarty->assign('navLogin', GetNavLogin($tpLayout, GetDispProgSel($idProg)));
$smarty->assign('onLoad', $onLoad);
$smarty->assign('menuGeral', GetMenuUser($tpLayout));
$smarty->assign('idProg', $idProg);
$smarty->assign('idSubProg', $idSubProg);
$smarty->assign('pbxRequest', ($isPbxRequest ? '1' : '0'));
$smarty->assign('vAlineMaster', $vAlineMaster);
$smarty->assign('wAlineMaster', $wAlineMaster);
$smarty->assign('heightMasterContent', ($tpLayout ? '100%' : $heightMasterContent));
$smarty->assign('setActPage', $setActPage); //action do form
$smarty->assign('setMethod', $setMethod); //método de envio do form
// $smarty->assign('erros', "");
//$smarty->assign('erros', $siteError->GetNumError() ? $siteError->DisplayError() : "");
$smarty->assign('conteudo', $conteudo);
$smarty->assign('aguarde', $aguarde);
$smarty->assign('newLoading', $newLoading);
$smarty->assign('footer', $tpLayout ? false : $footerDisplay);
$smarty->assign('functionForm', $functionForm);
$smarty->assign('versaoApl', GetVersao());
$smarty->assign('idHand', time());
$smarty->assign('szHeaderLayout', IsUserConnect() ? "height: 60px;" : "");
$smarty->display('master.tpl');
}
?>

2
integracao/bdApi.php

@ -1,7 +1,7 @@
<?php
//conecta ao banco de dados
$dbcon = @pg_connect(GetConectString());
$GLOBALS["dbconn"] = $db = $dbcon = @pg_connect(GetConectString());
$_SESSION["Db_conf_ok"] = "0";
function GetConectString() {

192
integracao/funcoesApi.php

@ -1,7 +1,7 @@
<?php
//caso o display errors for ativo pode impactar no funcionamento de algumas chamadas da api.
error_reporting(0);
ini_set('display_errors',1);
ini_set('display_errors', 0);
$docApi = [];
$obsConectaAgente = "<br/> Obs: É necessário ter autenticado(\"ConectaAgente(...)\") o agente e informar o \"SIPID\" na url.";
@ -2938,7 +2938,7 @@ function ConectaAgente($dac, $nomeDac = '', $matriculaAgente = '0', $apelidoAgen
/*
* Registra login no banco de dados.
*/
$result = pg_query($db, "begin");
$result = pg_query($GLOBALS["dbconn"], "begin");
if (!$result) {
$ultMsg = "Não foi possível iniciar uma transação para registro de login no banco de dados!";
$log[] = $ultMsg;
@ -2968,7 +2968,7 @@ function ConectaAgente($dac, $nomeDac = '', $matriculaAgente = '0', $apelidoAgen
$relEvt = 0;
$query = "insert into pbx_eventos_agentes(matricula, ramal, id_dac, id_motivo_pausa, entrada_pausa, flag, relaciona_eventos)
values('$matricula', '$ramal', $dac, $motivoLogin, now(), 0, $relEvt)";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$result = $result && @pg_affected_rows($result);
}
}
@ -2980,7 +2980,7 @@ function ConectaAgente($dac, $nomeDac = '', $matriculaAgente = '0', $apelidoAgen
$ret = array();
if ($result) {
pg_query($db, "commit");
pg_query($GLOBALS["dbconn"], "commit");
$_SESSION[AGT_CONECT] = 1;
$_SESSION[SS_STATUS_AGENTE] = AGENTE_EM_PAUSA;
$ret["status"] = "OK";
@ -2990,7 +2990,7 @@ function ConectaAgente($dac, $nomeDac = '', $matriculaAgente = '0', $apelidoAgen
$log[] = "Agente logado";
} else {
if ($inTransaction)
pg_query($db, "rollback");
pg_query($GLOBALS["dbconn"], "rollback");
$_SESSION[AGT_CONECT] = 0;
$_SESSION[SS_STATUS_AGENTE] = AGENTE_LOGOFF;
$ret["status"] = "erro";
@ -3013,7 +3013,7 @@ function RegistraLogin($db, $tipoAtende, $matricula, $ramal, $dacDesc, $login, $
*/
$query = "insert into pbx_eventos_agentes(matricula, ramal, id_dac, \"login\", logoff, flag)
values('$matricula', '$ramal', $dac, now(), now(), 0)";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$result = $result && @pg_affected_rows($result);
if (!$result) {
$ultMsg = "Não foi possivel inserir o registro em \"Eventos Agentes\"";
@ -3033,7 +3033,7 @@ function RegistraLogin($db, $tipoAtende, $matricula, $ramal, $dacDesc, $login, $
relaciona_evento = '0'
where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$result = $result && @pg_affected_rows($result);
if (!$result) {
$ultMsg = "Não foi possivel atualizar informações em \"Supervisor Agentes\"";
@ -3070,13 +3070,13 @@ function DesconectaAgente()
$log[] = $ultMsg;
} else {
//Desenvolvendo
$result = pg_query($db, "begin");
$result = pg_query($GLOBALS["dbconn"], "begin");
if (!$result) {
$ultMsg = "Não iniciar transação no banco de dados!";
$log[] = $ultMsg;
} else {
$query = "delete from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if (!$result) {
$ultMsg = "Não foi possível deletar o agente em \"Supervisor Agentes\"!";
@ -3086,7 +3086,7 @@ function DesconectaAgente()
if ($result) {
$query = "update pbx_eventos_agentes set logoff = now(), flag = 2
where matricula = '$matricula' and id_dac = $dac and login = (select max(login) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = $dac)";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
}
if (!$result) {
$ultMsg = "Não foi Atualizar \"Eventos Agentes\"!";
@ -3101,13 +3101,13 @@ function DesconectaAgente()
if ($result) {
$ultMsg = "Logoff efetuado com sucesso!";
$log[] = $ultMsg;
pg_query($db, "commit");
pg_query($GLOBALS["dbconn"], "commit");
$ret["status"] = "OK";
$ret["message"] = $ultMsg;
GravaLogItgr();
SetSessionDesconect();
} else {
pg_query($db, "rollback");
pg_query($GLOBALS["dbconn"], "rollback");
$ret["status"] = "OK";
$ret["message"] = $ultMsg;
}
@ -3144,14 +3144,14 @@ function EntradaPausa($codMotivo)
$ultMsg = 'Não foi possível adicionar o agente em pausa na central!';
$log[] = $ultMsg;
} else {
$result = pg_query($db, "begin");
$result = pg_query($GLOBALS["dbconn"], "begin");
if (!$result) {
$ultMsg = 'Não foi possível iniciar uma transação com o banco de dados!';
$log[] = $ultMsg;
} else {
//pega descricao do motivo de pausa
$query = "select motivo from pbx_motivos_pausas where id = '$codMotivo'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$log[] = $query;
if (!pg_num_rows($result)) {
$ultMsg = 'Não foi possível carregar informações sobre o \"Motivo da Pausa\"!';
@ -3162,7 +3162,7 @@ function EntradaPausa($codMotivo)
//atualiza dados do supervisor
$query = "update pbx_supervisor_agentes set status = 'PAUSA', duracao = now(), id_eventos_agente = '0', motivo_pausa = '$descMotivo' where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$result = $result && @pg_affected_rows($result);
$log[] = $query;
if (!$result) {
@ -3172,7 +3172,7 @@ function EntradaPausa($codMotivo)
$relEvt = 0;
$query = "insert into pbx_eventos_agentes(matricula, ramal, id_dac, id_motivo_pausa, entrada_pausa, flag, relaciona_eventos, saida_pausa, pausa_produtiva)
values('$matricula', '$ramal', $dac, $codMotivo, now(), 0, $relEvt, now(), (select produtiva from pbx_motivos_pausas where id = '$codMotivo'))";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$result = $result && @pg_affected_rows($result);
$log[] = $query;
if (!$result) {
@ -3189,14 +3189,14 @@ function EntradaPausa($codMotivo)
if ($result) {
$ultMsg = "Agente colocado em \"Pausa\" com sucesso!";
$log[] = $ultMsg;
pg_query($db, "commit");
pg_query($GLOBALS["dbconn"], "commit");
$_SESSION[AGT_EM_PAUSA] = 1;
$_SESSION[AGT_PAUSA_MOTIVO] = $codMotivo;
$ret["status"] = "OK";
$ret["agente_status"] = AGENTE_EM_PAUSA;
$ret["message"] = $ultMsg;
} else {
pg_query($db, "rollback");
pg_query($GLOBALS["dbconn"], "rollback");
$ret["status"] = "erro";
$ret["agente_status"] = AGENTE_LIVRE;
$ret["message"] = $ultMsg;
@ -3230,7 +3230,7 @@ function SaidaPausa()
$log[] = $ultMsg;
} else {
$result = pg_query($db, "begin");
$result = pg_query($GLOBALS["dbconn"], "begin");
if (!$result) {
$ultMsg = sprintf("Nã foi possível iniciar uma transação com o banco de dados!");
$log[] = $ultMsg;
@ -3240,7 +3240,7 @@ function SaidaPausa()
where matricula = '$matricula' and id_dac = $dac
and entrada_pausa = (select max(entrada_pausa) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = $dac)";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$result = $result && @pg_affected_rows($result);
if (!$result) {
@ -3248,7 +3248,7 @@ function SaidaPausa()
$log[] = $ultMsg;
} else {
$query = "update pbx_supervisor_agentes set status = 'LIVRE', duracao = now(), motivo_pausa = '0', status_agente = '0' where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$result = $result && @pg_affected_rows($result);
if (!$result) {
@ -3263,7 +3263,7 @@ function SaidaPausa()
if ($result) {
$ultMsg = "Agente removido de \"Pausa\" com sucesso!";
$log[] = $ultMsg;
pg_query($db, "commit");
pg_query($GLOBALS["dbconn"], "commit");
$_SESSION[AGT_EM_PAUSA] = 0;
$_SESSION[AGT_PAUSA_MOTIVO] = 0;
$ret["status"] = "OK";
@ -3271,7 +3271,7 @@ function SaidaPausa()
$ret["agente_status"] = AGENTE_LIVRE;
$ret["message"] = $ultMsg;
} else {
pg_query($db, "rollback");
pg_query($GLOBALS["dbconn"], "rollback");
$ret["status"] = "OK";
$ret["result"] = "false";
$ret["agente_status"] = AGENTE_EM_PAUSA;
@ -3302,7 +3302,7 @@ function Discar($numeroDiscar)
$msgSis = "";
$query = "select status,motivo_pausa from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query); //
$result = pg_query($GLOBALS["dbconn"], $query); //
if ($result)
$row = @pg_fetch_array($result);
@ -3320,7 +3320,7 @@ function Discar($numeroDiscar)
$query = "update pbx_supervisor_agentes set status = 'OCUPADO', canal_agente = 'Agent/$matricula', origem_destino = '$numeroDiscar', duracao = now() where matricula = '$matricula'";
}
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$msgSis = "Discagem realizada com sucesso!";
} else if (empty($msgSis)) {
$msgSis = "Não foi possível discar para o número informado!";
@ -3552,11 +3552,11 @@ function AlarmeFila($numeroFila, $ramal)
$result = false;
}
$resultFila = pg_query($db, "select id,nome from pbx_dacs where numero = '{$numeroFila}'");
$resultFila = pg_query($GLOBALS["dbconn"], "select id,nome from pbx_dacs where numero = '{$numeroFila}'");
$arFila = pg_fetch_array($resultFila, null, PGSQL_ASSOC);
$sql = "SELECT b.nome from pbx_queues_membros a, pbx_ramais b where a.dispositivo = b.dispositivo and a.id_fila = '{$arFila['id']}'";
$resultado = pg_query($db, $sql);
$resultado = pg_query($GLOBALS["dbconn"], $sql);
if (($result)) {
while ($numeroDiscar = pg_fetch_array($resultado, null, PGSQL_ASSOC)) {
@ -3691,7 +3691,7 @@ function Transferir($numeroDiscar)
//atualiza dados do supervisor
$query = "select canal from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if ($result)
$row = @pg_fetch_row($result);
@ -3711,7 +3711,7 @@ function Transferir($numeroDiscar)
where matricula = '$matricula'";
if ($result)
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if ($result)
$msgSis = "Transferência realizada com sucesso!";
@ -3749,7 +3749,7 @@ function Rediscar($identificador)
//Recupera o id da lista ativar para campanha corrente
$query = "select max(list_id) as list_id from pbx_campanha_lista where cmp_id = '$dac' and list_status = 1 ";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$log[] = "$query \n Exec: " . ($result ? "ok" : "erro");
if ($result) {
$row = @pg_fetch_row($result);
@ -3757,7 +3757,7 @@ function Rediscar($identificador)
//update pbx_campanha_contato set cont_discado = '0', cont_peso = '-10' where cont_id = '502274';
$query = "update pbx_campanha_contato set cont_discado = '0', cont_peso = '-10' where cmp_id = '$dac' and list_id = '$listId' and cont_identificador = '$id'";
//$query = "update pbx_campanha_contato set cont_rediscar = 9 where cmp_id = '$dac' and list_id = '$listId' and cont_identificador = '$id'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$log[] = "$query \n Exec: " . ($result ? "ok" : "erro");
if ($result) {
$msgSis = "Operação realizada dom sucesso!";
@ -4040,7 +4040,7 @@ function EnviaSMS($troncoSainte, $numeroDestino, $texto)
. "sms_id_envio, sms_data_envio::date as sms_data_envio, sms_data_envio::time as sms_hora_envio "
. "from pbx_sms_send "
. "where sms_sip_id = '$sms'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if (pg_num_rows($result)) {
$dados = pg_fetch_array($result);
@ -4748,6 +4748,7 @@ $docApi['ResourcesMonitor'] = MetodoApi(
'JSON'
);
function ResourcesMonitor(
$timestamp,
$upstartInformation,
@ -4759,13 +4760,33 @@ function ResourcesMonitor(
) {
$pathLog = '/var/log/asterisk/monitor_recursos_api.log';
$errorMsg = "Não foi possivel realizar a operação!";
try {
include 'vendas/funcoesMonitorEvents.php';
$timestamp_valid_up = (time() + 20) > $timestamp;
$timestamp_valid_down = (time() - 20) < $timestamp;
$timestamp_valid_interval = IntervalEventValid( $IP);
if (!$timestamp_valid_up || !$timestamp_valid_down ){
$errorMsg = "Timestamp não válido";
GeraExcept($errorMsg);
}
if (!$timestamp_valid_interval) {
$errorMsg = "O intervalo de requisição deve ser no mínimo 20 seg";
GeraExcept($errorMsg);
}
$cpuPercentageBusy = $cpu['percent'];
$ramTotal = $ram['total'];
$cpuCores = $cpu['cores'];
$loadAverage = $cpu['loadavg'];
$ramPercentageBusy = $ram['percent'];
$db = $GLOBALS['dbcon'];
$troncosTotal = count($troncos);
$troncosFalhas = _tratatroncos($troncos);
$idServidor = getidServidorFromIp($IP);
$timestampNew = strval(date('Y-m-d H:i:s', $timestamp));
if ($idServidor) {
$errorMsg = "Não foi possivel realizar a insercao no banco de dados!";
@ -4777,6 +4798,10 @@ function ResourcesMonitor(
ram_total,
ram_percentage_busy,
upstart_information,
cpu_cores,
load_average,
troncos_total,
troncos_falhas,
event_timestamp
) VALUES (
$idServidor,
@ -4785,12 +4810,16 @@ function ResourcesMonitor(
$ramTotal,
$ramPercentageBusy,
$upstartInformation,
to_timestamp($timestamp)
$cpuCores,
$loadAverage,
$troncosTotal,
$troncosFalhas,
'$timestampNew'
) RETURNING id;
";
pg_query($db, "BEGIN");
$resultInsertEvents = pg_query($db, $queryEvents);
pg_query($GLOBALS["dbconn"], "BEGIN");
$resultInsertEvents = pg_query($GLOBALS["dbconn"], $queryEvents);
if ($resultInsertEvents) {
$idEvents = pg_fetch_result($resultInsertEvents, 0, 0);
@ -4818,7 +4847,7 @@ function ResourcesMonitor(
}
$queryTroncos = "INSERT INTO vds_events_troncos (id_event, name, status) VALUES $valuesTroncos;";
$resultInsertTroncos = pg_query($db, $queryTroncos);
$resultInsertTroncos = pg_query($GLOBALS["dbconn"], $queryTroncos);
//manipula os dados dos hds para o insert
$valuesHds = '';
@ -4844,18 +4873,19 @@ function ResourcesMonitor(
}
}
$queryHds = "INSERT INTO vds_events_hd (id_event, filesystem, hd_busy, hd_total, hd_percentage_busy) VALUES $valuesHds;";
$resultInsertHds = pg_query($db, $queryHds);
$queryHds = "INSERT INTO vds_events_hd (id_event, hd ) VALUES ($idEvents, '".json_encode($hds)."');";
$resultInsertHds = pg_query($GLOBALS["dbconn"], $queryHds);
if ($resultInsertTroncos && $resultInsertHds) {
// require_once "vendas/funcoesMonitorEvents.php";
pg_query($db, "COMMIT");
pg_query($GLOBALS["dbconn"], "COMMIT");
$ret['status'] = 'OK';
$ret['result'] = 'true';
$ret['mensagem'] = 'Registros inseridos ao banco de dados com sucesso!';
require_once 'vendas/funcoesMonitorEvents.php';
//chama para enviar o email.
require_once "vendas/funcoesMonitorEvents.php";
$resultInsertHds = pg_query($GLOBALS["dbconn"], "SELECT refresh_show_events('".$IP."');");
//chama para enviar o email.
$needToSend = needToSend($db, $idServidor);
if ($needToSend) {
echo "<pre>";
@ -4868,8 +4898,8 @@ function ResourcesMonitor(
return ResultToJSON($ret);
}
$errorMsg =
GeraExcept($errorMsg);
$errorMsg =
GeraExcept($errorMsg);
}
}
GeraExcept($errorMsg);
@ -4878,7 +4908,7 @@ function ResourcesMonitor(
GeraExcept($errorMsg);
} catch (Exception $ex) {
$msgEx = $ex->getMessage();
pg_query($db, "ROLLBACK");
pg_query($GLOBALS["dbconn"], "ROLLBACK");
WriteLog(sprintf("[ERRO] - [SERVIDOR]: %s - Msg: %s - [DATA]: " . date('Y-m-d H:i:s'), $IP, $msgEx), $pathLog);
$ret['status'] = 'Erro';
$ret['result'] = 'false';
@ -4887,6 +4917,19 @@ function ResourcesMonitor(
}
}
function _tratatroncos($data)
{
$troncos_data = $data;
$troncos_failed = 0;
foreach ($troncos_data as $value) {
if (strpos($value['status'], "OK") === false) {
$troncos_failed++;
}
}
return $troncos_failed;
}
/* FUNCOES AUXILIARES PARA O WEBSERVICES */
function GravaArquivo($file, $dados, $mode = 'a', $replaceText = '')
{
@ -4963,7 +5006,7 @@ function GetRamaisNome()
$ret = array();
$db = $GLOBALS['dbcon'];
$query = "select nome, callerid from pbx_sip_ramais where coalesce(callerid,'') <> ''";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if (!$result)
throw new Exception("Não foi possível acesso o banco de dados!");
@ -5765,7 +5808,7 @@ function GetRamalSip($dbcon, $ramalAgente)
function GetMotivoLogin($db)
{
$query = "select id from pbx_motivos_pausas where upper(motivo) = 'LOGIN'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$row = @pg_fetch_array($result);
$_SESSION["motivoLogin"] = $row[0];
return $row[0];
@ -5774,7 +5817,7 @@ function GetMotivoLogin($db)
function GetMotivoAusente($db)
{
$query = "select id from pbx_motivos_pausas where upper(motivo) = 'AUSENTE'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$row = @pg_fetch_array($result);
$_SESSION["motivoLogin"] = $row[0];
return $row[0];
@ -5821,7 +5864,7 @@ function UpdatePausa($db)
$dac = GetIdDac();
$query = "update pbx_eventos_agentes set saida_pausa = now(), flag = 1 where matricula = '$matricula' and id_dac = $dac
and entrada_pausa = (select max(entrada_pausa) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = $dac)";
pg_query($db, $query);
pg_query($GLOBALS["dbconn"], $query);
}
function UpdateLogoff($db)
@ -5830,11 +5873,11 @@ function UpdateLogoff($db)
$matricula = GetMatriculaAgente();
$query = "update pbx_supervisor_agentes set logado = now() where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$query = "update pbx_eventos_agentes set logoff = now(), flag = 1 where matricula = '$matricula' and id_dac = $dac
and login = (select max(login) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = $dac)";
pg_query($db, $query);
pg_query($GLOBALS["dbconn"], $query);
}
function SetSessionDesconect()
@ -5889,7 +5932,7 @@ function getReturnMethod($paramUrl)
function getRequestMethod($paramUrl)
{
$dataJson = getJsonDataResquest();
file_put_contents("/var/log/asterisk/123", $paramUrl);
if ($paramUrl["method"]) {
return $paramUrl["method"];
}
@ -5910,7 +5953,6 @@ function ValidaMetodos($paramUrl)
$methodApi = getRequestMethod($paramUrl);
if (array_key_exists($methodApi, $metodos)) {
file_put_contents("/var/log/asterisk/123asd", "PASSOUO !ValidaMetodos");
$key = $methodApi;
foreach ($metodosParam[$key] as $params) {
/*
@ -5968,7 +6010,7 @@ function GetTipoFila($db, $dac)
try {
//$senha = '0987';
$query = "select count(*) as num from pbx_campanha where cmp_id = '$dac' ";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if (!$result)
throw new Exception('');
@ -6107,7 +6149,7 @@ function AgentePresente($db, $matricula)
$i = 0;
while ($i++ < 10) {
$query = "select count(*) from pbx_supervisor_agentes where matricula = '$matricula' and upper(status) = 'PAUSA' ";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$row = @pg_fetch_row($result);
$result = $row[0] ? true : false;
if ($result)
@ -6122,7 +6164,7 @@ function GetRamalAgenteLogado($db)
{
$matricula = GetMatriculaAgente();
$query = "select ramal from pbx_supervisor_agentes where matricula = '$matricula' ";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$row = pg_fetch_row($result);
return $row[0];
}
@ -6130,7 +6172,7 @@ function GetRamalAgenteLogado($db)
function VerificaDac($db, $idDac)
{
$query = "select count(*) from pbx_dacs where id = '$idDac' ";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$row = pg_fetch_row($result);
return $row[0];
}
@ -6138,7 +6180,7 @@ function VerificaDac($db, $idDac)
function VerificaCampanha($db, $nomeCampanha)
{
$query = "select cmp_id from pbx_campanha where cmp_descricao = '$nomeCampanha'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if (!$result)
throw new Exception("Não foi possível verificar a \"Campanha\"!");
if (!pg_num_rows($result))
@ -6154,7 +6196,7 @@ function CampanhaAtiva($db, $existeCampanha)
return false;
$query = "select count(*) from pbx_campanha where cmp_id = '$existeCampanha' and cmp_status = '1' ";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if (!$result)
throw new Exception("Não foi possível verificar o \"Status da Campanha\"!");
@ -6166,7 +6208,7 @@ function CampanhaAtiva($db, $existeCampanha)
function VerificaCampanhaLista($db, $nomeLista)
{
$query = "select list_id from pbx_campanha_lista where list_nome = '$nomeLista'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if (!$result)
throw new Exception("Não foi possível verificar a \"Lista\"!");
@ -6180,7 +6222,7 @@ function VerificaCampanhaLista($db, $nomeLista)
function GetContatoFone($db, $existeCampanha, $listId, $codCliente)
{
$query = "select cont_id from pbx_campanha_contato where cmp_id = '$existeCampanha' and list_id = '$listId' and cont_identificador = '$codCliente'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if (!$result)
throw new Exception("Não foi possível verificar o \"Contato\"!");
@ -6211,7 +6253,7 @@ function StatusCampanha($idCampanha, $status)
$ativar = $status == 1;
$db = $GLOBALS['dbcon'];
$result = pg_query($db, 'begin');
$result = pg_query($GLOBALS["dbconn"], 'begin');
if (!$result)
throw new Exception('Nao foi possível \"Iniciar a Operação\"!');
$inTran = 1;
@ -6220,7 +6262,7 @@ function StatusCampanha($idCampanha, $status)
* Seleciona informações sobre a campanha informada.
*/
$query = " select cmp_id, cmp_descricao, cmp_aguarda_agente, cmp_numero_ligacoes_agente, coalesce(cmp_pid, 0) as cmp_pid from pbx_campanha where (cmp_id::text = '$idCampanha' or cmp_descricao = '$idCampanha')";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if (!$result || !pg_num_rows($result))
throw new Exception("Não foi possível obter informações sobre a \"Campanha\"!");
@ -6237,13 +6279,13 @@ function StatusCampanha($idCampanha, $status)
*/
$query = "update pbx_campanha set cmp_status = '%s' where cmp_id = '%s' ";
$query = sprintf($query, $fieldsForm['cmp_status'], $idCampanha);
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if (!$result)
throw new Exception('A operação não pode ser realizada!');
if ($ativar) {
$query = "select count(*) as lista from pbx_campanha_lista where cmp_id = '$idCampanha' and list_status = '1'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if (!$result)
throw new Exception("Não foi possível verificar o \"Status da Lista\"!");
$row = @pg_fetch_row($result);
@ -6258,7 +6300,7 @@ function StatusCampanha($idCampanha, $status)
$query = "select cmp_pid from pbx_campanha where cmp_id = '$id$idCampanha'";
while ($i++ < 10) {
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if (!$result)
throw new Exception("Não foi possível verificar o serviço de \"Discagem\"!");
@ -6285,7 +6327,7 @@ function StatusCampanha($idCampanha, $status)
}
$result = pg_query($db, 'commit');
$result = pg_query($GLOBALS["dbconn"], 'commit');
if (!$result)
throw new Exception('Nao foi possível \"Finalizar a Operação\"!');
@ -6296,7 +6338,7 @@ function StatusCampanha($idCampanha, $status)
$ret["message"] = $msg;
return ResultToXml($ret);
} catch (Exception $ex) {
pg_query($db, 'rollback');
pg_query($GLOBALS["dbconn"], 'rollback');
return GetErro("StatusCampanha", $ex);
}
}
@ -6304,7 +6346,7 @@ function StatusCampanha($idCampanha, $status)
function ExecutaComando($comando, $db)
{
$query = "SELECT usuario_servidor, senha_servidor, porta_servidor FROM pbx_conf_padrao";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$dados = pg_fetch_array($result);
$usuario_servidor = $dados['usuario_servidor'];
@ -6324,7 +6366,7 @@ function VerificaRamalLogado($db, &$dac, &$agente)
{
$ramal = GetRamalAgente();
$query = "select dac, nome, count(*) from pbx_supervisor_agentes where ramal = '$ramal' group by dac, nome";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$row = pg_fetch_array($result);
if (pg_num_rows($result)) {
@ -6339,17 +6381,17 @@ function VerficaAgenteLogado($db)
{
$matricula = GetMatriculaAgente();
$query = "select count(*) from pbx_supervisor_agentes where matricula = '$matricula' ";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$row = pg_fetch_row($result);
$ret = $row[0];
if ($ret) {
$query = "select extract(epoch from (now() - logado))::int , trim(ramal) from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$dados = pg_fetch_row($result);
if (empty($dados[1]) || ($dados[0] >= 60)) {
$query = "delete from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
$ret = false;
}
}
@ -6370,7 +6412,7 @@ function VerificaMaxAgenteLogado($db)
* Verifico a quantidade de PAs logado.
*/
$query = "select (count(*) + 1) as num_total_pa from pbx_supervisor_agentes";
$result = pg_query($db, $query);
$result = pg_query($GLOBALS["dbconn"], $query);
if ($result) {
$row = pg_fetch_row($result);
return ($row[0] > $numAgt);

2
integracao/index.php

@ -8,6 +8,8 @@ if (isset($_REQUEST["SIPID"])) {
session_id($_REQUEST["SIPID"]);
}
session_start();
require("util/constantes.php");
require("util/funcoesAmi.php");
require("util/util.php");

6
login.php

@ -1,6 +1,8 @@
<?php
include "util/funcoesLicenca.php";
$_SESSION["SSmatriculaUser"] = "";
/**
* Conexao com banco de dados
*/
@ -97,10 +99,6 @@ if (!isset($_POST["loginUser"])) {
SetHosts($dbcon);
// caminhos para gravar arquivos
GetCofigPadrao($dbcon);
/*
* expiracao de senha
*/

1046
master.css

File diff suppressed because it is too large Load Diff

89
monitorAlgar/bloqueio_algar.php

@ -1,89 +0,0 @@
#!/usr/bin/php -q
<?php
function adiciona_coluna($bdcon) {
$query = "select bloqueio_verificado from pbx_bilhetes limit 1";
if (!pg_query($bdcon, $query)) {
$queryColuna = "alter table pbx_bilhetes add column bloqueio_verificado integer";
pg_query($bdcon, $queryColuna);
}
}
function registra_log($msg) {
$fp = fopen('/var/log/asterisk/bloq_algar.log', 'a');
$now = date('Y-m-d H:i:s', time()-3600);
$sNow = "[{$now}] ";
if ($fp) {
fwrite($fp, $sNow.$msg."\n");
fclose($fp);
}
}
$bdcon = pg_connect("host=algar.simplesip.com.br port=5432 dbname=pbx user=contacte password=ctepgSQL");
if (!$bdcon) {
registra_log("Erro ao conectar ao banco de dados da algar, script encerrado.");
exit(0);
}
$queryEmpresas = "select emp_cnpj, emp_vpn from vds_empresas where emp_status = 0";
if (!($resourceEmpresa = pg_query($queryEmpresas))) {
registra_log("Erro ao buscar empresas no banco de dados da algar, script encerrado.");
exit(0);
}
$empresas = pg_fetch_all($resourceEmpresa);
foreach ($empresas as $empresa) {
$bdcon0 = pg_connect("host={$empresa['emp_vpn']} port=5432 dbname=pbx user=contacte password=ctepgSQL connect_timeout=10");
if (!$bdcon0) {
continue;
}
adiciona_coluna($bdcon0);
$caminhoPadrao = "/var/lib/asterisk/sounds/appsounds/";
$bloqueios = ["ligacaoinvalidaanatel", "horarionaopermitidoanatel", "limitdiarioanatel", "limitemensalanatel"];
$queryChamadas = "select uniqueid, bloqueio_verificado from pbx_bilhetes where lastapp = 'Playback' "
. "and (bloqueio_verificado is null or bloqueio_verificado = -1) "
. "and lastdata in ('{$caminhoPadrao}{$bloqueios[0]}', "
. "'{$caminhoPadrao}{$bloqueios[1]}', "
. "'{$caminhoPadrao}{$bloqueios[2]}', "
. "'{$caminhoPadrao}{$bloqueios[3]}')";
if (!($resChamadas = pg_query($bdcon0, $queryChamadas))) {
registra_log("Falha ao procurar audios na tabela pbx_bilhetes do banco de dados do cliente {$empresa['emp_cnpj']}");
continue;
}
if(!($chamadasCliente = pg_fetch_all($resChamadas))) {
continue;
}
foreach ($chamadasCliente as $chamada) {
$updateChamada = "update vds_chamadas set bloqueio_anatel = 1 where uid = '{$chamada['uniqueid']}'";
$queryChamada = pg_query($bdcon, $updateChamada);
if ($queryChamada) {
$updateCliente = "update pbx_bilhetes set bloqueio_verificado = 1 where uniqueid = '{$chamada['uniqueid']}'";
$queryCliente = pg_query($bdcon0, $updateCliente);
if (!queryCliente) {
$msg = "Erro ao atualizar bloqueio_verificado = 1 para a chamada de uid {$chamada['uniqueid']} na tabela pbx_bilhetes do banco de dados da empresa {$empresa['emp_cnpj']} apesar de ter sido atualizado no banco de dados da algar";
registra_log($msg);
}
} else {
if ($chamada['bloqueio_verificado'] == '-1') {
$updateCliente = "update pbx_bilhetes set bloqueio_verificado = 2 where uniqueid = '{$chamada['uniqueid']}'";
if(!(pg_query($bdcon0, $updateCliente))) {
$msg = "Erro ao atualizar bloqueio_verificado = 2 do audio {$chamada['uniqueid']} na tabela pbx_bilhetes do banco de dados do cliente {$empresa['emp_cnpj']}";
registra_log($msg);
} else {
$msg = "O audio {$chamada['uniqueid']} foi atualizado para bloqueio_verificado = 2 no banco de dados do cliente {$empresa['emp_cnpj']},"
. " ou seja, foi marcado como erro e precisa ser analisado.";
registra_log($msg);
}
} else if ($chamada['bloqueio_verificado'] == NULL) {
$updateCliente = "update pbx_bilhetes set bloqueio_verificado = -1 where uniqueid = '{$chamada['uniqueid']}'";
if (!pg_query($bdcon0, $updateCliente)) {
$msg = "Erro ao atualizar o audio {$chamada['uniqueid']} para bloqueio_verificado = -1 na tabela pbx_bilhetes do banco de dados do cliente {$empresa['emp_cnpj']}";
registra_log($msg);
}
}
$msg = "Erro ao atualizar a chamada de uid {$chamada['uniqueid']} para bloqueio_anatel = 1 da empresa de cnpj {$empresa['emp_cnpj']} no banco de dados da algar.";
registra_log($msg);
}
}
}
?>

17
monitorAlgar/enviaRelatorio.php

@ -1,17 +0,0 @@
<?php
$file = basename(dirname(__FILE__));
envia_sms("65992893913", sprintf(sprintf("http://repositorio.simplesip.com.br/%s/relatorioMonitoraAlgar.php", $file)));
function envia_sms($telefone, $mensagem) {
$res = curl_init("https://www.iagentesms.com.br/webservices/http.php?metodo=envio"
. "&usuario=desenvolvimento@simplesip.com.br"
. "&senha=SimpleS_root"
. "&celular={$telefone}"
. "&mensagem={$mensagem}");
//curl_setopt($res, CURLOPT_RETURNTRANSFER, true);
curl_setopt($res, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($res, CURLOPT_SSL_VERIFYHOST, false);
curl_exec($res);
curl_close($res);
return $res;
}

88
monitorAlgar/index.php

@ -1,88 +0,0 @@
<?php
header("Content-Type: application/json");
function seleciona_emp_id($banco, $cnpj_consulta) {
$con = pg_connect($banco);
if ($con) {
$query = "select emp_id from vds_empresas where emp_cnpj = '".$cnpj_consulta."'";
$realiza_query = pg_query($con, $query);
if ($realiza_query) {
$emp_id = pg_fetch_assoc($realiza_query);
return $emp_id['emp_id'];
} else {
echo "Falha ao executar query";
exit(0);
}
} else {
echo "Falha ao conectar ao banco de dados";
exit(0);
}
}
function consulta_audios($banco, $emp_id) {
$con = pg_connect($banco);
if ($con) {
$query = "select vds_chamadas.*, vds_classificacoes.clas_descricao from "
. "vds_chamadas inner join "
. "vds_classificacoes on vds_chamadas.uid = vds_classificacoes.uid "
. "where vds_classificacoes.clas_descricao = 'VENDA' "
. "and vds_chamadas.emp_id = '".$emp_id."' "
. "limit 10";
$seleciona_audios = pg_query($con, $query);
if ($seleciona_audios) {
return pg_fetch_all($seleciona_audios);
} else {
echo "Falha ao executar query";
exit(0);
}
} else {
echo "Falha ao conectar ao banco de dados";
exit(0);
}
}
$filename = "/var/spool/asterisk/monitor/";
$cnpj_consulta = $_GET["cnpj"]; //12324775000797
$db0 = "host=192.168.115.65 port=5432 dbname=pbx_old user=contacte password=ctepgSQL";
$emp_id = seleciona_emp_id($db0, $cnpj_consulta);
$db1 = "host=algar.simplesip.com.br port=5432 dbname=pbx user=contacte password=ctepgSQL";
$array = consulta_audios($db1, $emp_id);
$initime = microtime(true);
/*
$dir = opendir("/var/spool/asterisk/monitor");
$array_audios = [];
if ($dir) {
while (($item = readdir($dir)) !== false) {
if ($item == '.' || $item == '..') {
continue;
}
$array_audios[] = $item;
}
closedir($dir);
}
*/
$filename = "/var/spool/asterisk/monitor/";
if ($array) {
foreach ($array as $key => $chamada) {
if(file_exists($filename.$chamada['chm_userfield'])) {
$array[$key]["enviado"] = 1;
} else {
$array[$key]["enviado"] = 0;
}
}
echo json_encode($array);
} else {
$array = [];
echo json_encode($array);
}
$fim_time = microtime(true);
echo $fim_time - $initime;

95
monitorAlgar/relatorioMonitoraAlgar.php

@ -1,95 +0,0 @@
#!/usr/bin/php -q
<?php
function relatorio_audios($info_array) {
$relatorio = '';
foreach ($info_array as $empresa) {
$relatorio .= "Foram encontrados {$empresa['qt_audios']} audios desatualizados para a empresa {$empresa['emp_cnpj']}(cnpj) na data {$empresa['data_bilhete']}(informacoes na tabela vds_audios_desatualizados).\n";
}
return $relatorio;
}
function relatorio_serv($info_array) {
$relatorio = '';
foreach ($info_array as $empresa) {
$relatorio .= "Foram encontrados {$empresa['qt_registros']} registros de dias nao monitorados para a empresa {$empresa['emp_cnpj']}(cnpj). O servidor pode estar ficando desligado.(informacoes na tabela vds_nao_monitorado).\n";
}
return $relatorio;
}
function envia_sms($telefone, $mensagem) {
$res = curl_init("https://www.iagentesms.com.br/webservices/http.php?metodo=envio"
. "&usuario=desenvolvimento@simplesip.com.br"
. "&senha=SimpleS_root"
. "&celular={$telefone}"
. "&mensagem={$mensagem}");
curl_setopt($res, CURLOPT_RETURNTRANSFER, true);
curl_setopt($res, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($res);
return $res;
}
//$bdcon = pg_connect("host=177.69.220.78 port=5432 dbname=pbx user=contacte password=ctepgSQL");
$bdcon = pg_connect("host=algar.simplesip.com.br port=5432 dbname=pbx user=contacte password=ctepgSQL");
if (!$bdcon) {
exit(0);
}
$query_audios = "select count(id_audio) as qt_audios, emp_cnpj, data_bilhete from vds_audios_desatualizados where data_bilhete = now()::date - 1 group by emp_cnpj, data_bilhete";
$query_clientes = "select count(id_problema) as qt_registros, emp_cnpj from vds_nao_monitorado group by emp_cnpj";
$resQueryAudio = pg_query($bdcon, $query_audios);
$resQueryClientes = pg_query($bdcon, $query_clientes);
if (!($resQueryAudio)) {
exit(0);
}
if (!$resQueryClientes) {
exit(0);
}
if ($rel_audios = pg_fetch_all($resQueryAudio)) {
envia_sms("65993625396", urlencode(relatorio_audios($rel_audios)));
}
if ($rel_clientes = pg_fetch_all($resQueryClientes)) {
envia_sms("65993625396", substr(relatorio_serv($rel_clientes), 0, 20));
}
?>
<html>
<head>
<meta charset="UTF-8"/>
<title>Relatório</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<h1>Servidores sem conxexão</h1>
<table>
<tr> <th>Empresa</th> <th>Qt. de dias sem conexão</th></tr>
<?php
foreach ($rel_clientes as $conn) {
echo "<tr><td>{$conn['emp_cnpj']}</td><td>{$conn['qt_registros']}</td></tr>";
}
?>
</table>
<h1>Audios desatualizados </h1>
<table>
<tr><th>Empresa</th><th>Audios desatualizados ontem</th></tr>
<?php foreach ($rel_audios as $audio) {
echo "<tr><td>{$audio['emp_cnpj']}</td><td>{$audio['qt_audios']}</td></tr>";
}
?>
</table>
</body>
</html>

109
monitorAlgar/script_cliente.php

@ -1,109 +0,0 @@
#!/usr/bin/php -q
<?php
function inicia_empresas($bdcon) {
$sQuery = "select * from vds_nao_monitorado where data_script = now()::date - 1";
$query = pg_query($bdcon, $sQuery);
if (pg_num_rows($query) == 0) {
$valida_dia = "insert into vds_nao_monitorado "
. "(emp_cnpj, data_script) "
. "values ('00000000000000', now()::date - 1)";
pg_query($bdcon, $valida_dia);
$sEmpresas = "select emp_cnpj, emp_vpn, emp_status from vds_empresas where emp_vpn <> ''";
$res = pg_fetch_all(pg_query($bdcon, $sEmpresas));
foreach($res as $empresa) {
if (!$empresa['emp_status']) {
$query = "insert into vds_nao_monitorado "
. "(emp_cnpj, emp_vpn, data_script) "
. "values ('{$empresa['emp_cnpj']}', '{$empresa['emp_vpn']}', now()::date - 1)";
pg_query($bdcon, $query);
}
}
}
}
function deleta_script($cnpj, $data, $bdcon) {
return pg_query($bdcon, "delete from vds_nao_monitorado where emp_cnpj = '{$cnpj}' and data_script = '{$data}'");
}
$problema_con = [];
//$bdcon1 = pg_connect("host=127.0.0.1 port=5432 dbname=pbx user=contacte password=ctepgSQL");
$bdcon = pg_connect("host=algar.simplesip.com.br port=5432 dbname=pbx user=contacte password=ctepgSQL");
if (!$bdcon) {
exit(0);
}
inicia_empresas($bdcon);
$sel_script = "select emp_cnpj, emp_vpn, data_script from vds_nao_monitorado";
$scripts = pg_fetch_all(pg_query($bdcon, $sel_script));
foreach($scripts as $script) {
if (!in_array($script['emp_cnpj'], $problema_con)) {
$bdcon0 = pg_connect("host={$script['emp_vpn']} port=5432 dbname=pbx user=contacte password=ctepgSQL connect_timeout=10");
if (!$bdcon0) {
$problema_con[] = $script['emp_cnpj'];
continue;
}
$invertida = implode("-", array_reverse(explode('-', $script['data_script'])));
$datas[0] = "'{$script['data_script']}'";
$datas[1] = "&DATA={$invertida}";
$query = "select a.uniqueid, a.protoparceiro, b.userfield "
. "as arquivo_audio, b.data_bilhete, "
. "case when(length(a.protoparceiro) = 12)then 1 else 0 end as status_protocolo "
. "from pbx_protocolo_reg a, pbx_bilhetes b, pbx_classifica_reg c, pbx_classifica_atendimento d "
. "where b.uniqueid = a.uniqueid and c.id_bilhetes = a.uniqueid and d.clas_id = c.clas_id "
. "and a.protointegrado = 1 and d.clas_descricao = 'VENDA' and b.lastapp <> 'Transferred Call' "
. "and b.billsec > '0'and b.data_bilhete = {$datas[0]}";
$audiosQuery = pg_query($bdcon0, $query);
if (!$audiosQuery) {
continue;
}
$audiosCliente = pg_fetch_all($audiosQuery);
if (!$audiosCliente) {
$del = deleta_script($script['emp_cnpj'], $script['data_script'], $bdcon);
continue;
}
$ch = curl_init("https://algar.simplesip.com.br/apl/integracao/?method=DisponibilizaAudios&CNPJ=".$script['emp_cnpj']."{$datas[1]}&login=admin&senha=SiP1029384756&tipoRetorno=json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$obj = json_decode(curl_exec($ch));
if (!(gettype($obj) == "array")) {
continue;
}
$audios_algar[] = '';
foreach ($obj as $value) {
if ($value -> enviado) {
$audios_algar[] = $value -> chm_userfield;
}
}
$controle = true;
foreach ($audiosCliente as $value) {
if (!(in_array($value['arquivo_audio'], $audios_algar))) {
$insereAudio = "insert into vds_audios_desatualizados "
. "(uniqueid, userfield, data_bilhete, emp_cnpj) "
. "select * from "
. "(select '".$value["uniqueid"]."' as uniqueid, '".$value['arquivo_audio']."' as userfield, DATE '".$value['data_bilhete']."' as data_bilhete, '{$script['emp_cnpj']}' as emp_cnpj) as tmp "
. "where not exists (select * from vds_audios_desatualizados where uniqueid = '".$value["uniqueid"]."' "
. "and userfield = '".$value['arquivo_audio']."' and data_bilhete = DATE '".$value['data_bilhete']."')"
. " limit 1";
pg_query($bdcon, $insereAudio);
if (!$bdcon) {
$controle = false;
}
}
}
if ($controle) {
$del = deleta_script($script['emp_cnpj'], $script['data_script'], $bdcon);
}
}
}
?>

12
padroes.php

@ -1,12 +0,0 @@
<?php
$query = "SELECT * FROM pbx_conf_padrao";
$result = pg_query($dbcon, $query);
$dados = pg_fetch_array($result);
$caminho_back = $dados['caminho_backup'];
$caminho_producao = $dados['caminho_producao'];
$caminho_musicas = $dados['caminho_musicas'];
$url_musicas = $dados['url_musicas'];
$url_asterisk = $dados['url_asterisk'];
$path_som = $dados['path_som'];

20
router.html

@ -1,20 +0,0 @@
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
</head>
<body>
<form action="http://177.124.120.8:8098" method="post" enctype="multipart/form-data" name="form1">
<div>TODO write content</div><br>
<input name="arquivo" type="file" class="caixas" id="arquivo2" />
<input name="Submit" type="submit" class="labels" value="Salvar">
</form>
</body>
</html>

10
seguranca/grupos/grupoRevendas.php

@ -19,7 +19,7 @@ $fieldsForm['erro'] = "";
if (isset($fieldsForm['btInclui'])) {
if (empty($fieldsForm['listaRevendasDisponiveis'])) {
$fieldsForm['erro'] = fmtMsg('Selecione um ramal!');
$fieldsForm['erro'] = fmtMsg('Selecione uma revenda!');
} else {
try {
$result = pg_query($dbcon, 'begin');
@ -96,7 +96,8 @@ foreach ($fieldsForm as $key => $value) {
GetTemplate($smarty, $templateName);
function GetRevendasDisponiveis($dbcon, $codGp, $codSel, $size = 1, $tamPx = "200", $desabilita = 0, $multiple = 0) {
function GetRevendasDisponiveis($dbcon, $codGp, $codSel, $size = 1, $tamPx = "200", $desabilita = 0, $multiple = 0)
{
if (strpos($codGp, '|') !== false) {
$codG = explode('|', $codGp);
$codGp = $codG[0];
@ -127,7 +128,8 @@ function GetRevendasDisponiveis($dbcon, $codGp, $codSel, $size = 1, $tamPx = "20
return $lista;
}
function GetRevendasIncluidos($dbcon, $codGp, $codSel, $size = 1, $tamPx = "200", $desabilita = 0, $multiple = 0) {
function GetRevendasIncluidos($dbcon, $codGp, $codSel, $size = 1, $tamPx = "200", $desabilita = 0, $multiple = 0)
{
if (strpos($codGp, '|') !== false) {
$codG = explode('|', $codGp);
$codGp = $codG[0];
@ -156,5 +158,3 @@ function GetRevendasIncluidos($dbcon, $codGp, $codSel, $size = 1, $tamPx = "200"
$lista .= "</select>\n";
return $lista;
}
?>

16
seguranca/grupos/grupoSelect.php

@ -53,14 +53,8 @@ $restringLgpd = " and a.gp_id not in(select gp_id from pbx_grupo where gp_nome i
* Libera apenas para quem tiver acesso atribuido a administracao da lgpd.
*/
$liberaLgpd = '';
if (VerificaPerfilAcesso($dbcon, GetIdProgFromNomeMenu('mnLgpdAdm'))) {
$liberaLgpd = "\nunion\nselect gp_id, gp_nome, gp_status, user_id, 1 as gp_lgpd, case when(user_id = 0)then 0 else 1 end as ord from pbx_grupo a where gp_nome ilike 'LGPD_%_%_%'\n";
}
$acessoAudio = VerificaPerfilAcesso($dbcon, GetIdProgFromNomeArq('audio.php'));
$colspan = 4;
$colspan = $acessoAudio ? $colspan + 1 : $colspan;
$colspan = UseModVendas() ? $colspan + 2 : $colspan;
$compl = '';
if (isset($_REQUEST['paramPesquisa']) && $_REQUEST['paramPesquisa']) {
@ -139,7 +133,7 @@ if (!empty($mensagemErro)) {
$linha = GetLinhaInfo("Nenhum registro encontrado!", $colspan);
}
$smarty->assign('erro', $erro);
$smarty->assign('erro', "");
$smarty->assign("linhas", $linha);
$smarty->assign("paramPesquisa", $paramPesquisa);
$smarty->assign("cols", $colspan);
@ -147,9 +141,9 @@ $smarty->assign("imgNovo", $imgNovo);
$smarty->assign("links", $links);
$smarty->assign("pagMostra", $pagMostra);
$smarty->assign("totalReg", $totalReg);
$smarty->assign("pgn", $_REQUEST["pgn"]);
$smarty->assign("bloco", $_REQUEST["bloco"]);
$smarty->assign("pg", $_REQUEST["pg"]);
$smarty->assign("pgn", isset($_REQUEST["pgn"]) ? $_REQUEST["pgn"] : "" );
$smarty->assign("bloco", isset($_REQUEST["bloco"]) ? $_REQUEST["bloco"] : "" );
$smarty->assign("pg", isset($_REQUEST["pg"]) ? isset($_REQUEST["pg"]) : "" );
GetTemplate($smarty, $tpl);
/*

8
seguranca/grupos/gruposUsuario.php

@ -14,10 +14,8 @@ if (isset($fieldsForm['gp_id']) && (strpos($fieldsForm['gp_id'], '|') !== false)
$fieldsForm['gp_id'] = str_replace($search, '', $fieldsForm['gp_id']);
}
$isLgpd = $fieldsForm["gp_lgpd"];
//Id da campanha
$idCampanha = $fieldsForm['cmp_id'];
$fieldsForm['erro'] = "";
if (isset($fieldsForm['btIncAgente'])) {
@ -38,9 +36,7 @@ if (isset($fieldsForm['btIncAgente'])) {
/*
* Valida se o usuario ja não pertence a outro grupo lgpd.
*/
if ($isLgpd && ($jaLgpd = JaInseridoLgps($idUser))) {
throw new Exception($jaLgpd);
}
$query = "insert into pbx_grupo_usuario(user_id, gp_id)values(%s, '%s')";
$query = sprintf($query, $idUser, $fieldsForm['gp_id']);
$result = pg_query($dbcon, $query);

6
seguranca/usuario.php

@ -179,9 +179,9 @@ $smarty->assign("links", $links);
$smarty->assign("pagMostra", $pagMostra);
$smarty->assign("totalReg", $totalReg);
$smarty->assign("status", $statusAtivo);
$smarty->assign("pgn", $_REQUEST["pgn"]);
$smarty->assign("bloco", $_REQUEST["bloco"]);
$smarty->assign("pg", $_REQUEST["pg"]);
$smarty->assign("pgn", isset($_REQUEST["pgn"]) ? $_REQUEST["pgn"] : "" );
$smarty->assign("bloco", isset($_REQUEST["bloco"]) ? $_REQUEST["bloco"] : "");
$smarty->assign("pg", isset($_REQUEST["pg"]) ? $_REQUEST["pg"] : "");
GetTemplate($smarty, $tpl);
?>

10
seguranca/usuarioCad.php

@ -73,7 +73,6 @@ if (isset($_GET["idUser"]) && $_GET["idUser"] == 0) {
//$userAdm = $_POST["userAdm"] ? "" : "";
$userStatus = isset($_POST["userStatus"]) ? "checked" : "";
$acaoUser = $_POST["btGravar"];
$dacPadraoSel = $_POST["listaDacs"] ? $_POST["listaDacs"] : "0";
$userExpiraSenha = $_POST["userExpiraSenha"] ? $_POST["userExpiraSenha"] : 0;
if (empty($msg) && ($_POST["btGravar"] == 'Incluir')) {
@ -83,15 +82,14 @@ if (isset($_GET["idUser"]) && $_GET["idUser"] == 0) {
if ($result) {
$userMatricula = GetMatriculaAgente($dbcon);
$query = "insert into pbx_usuarios(nome, apelido, matricula, flag, \"admin\", senha, supervisor, agente, email, status, penalidade, dac_padrao, check_vl, senha_dias_expira)
values(%s, lower(%s), %s, %s, %s, md5(%s), %s, %s, %s, %s, %s, %s, md5(lower(%s)), %s)";
$query = sprintf($query, QuotedStr($userNome), QuotedStr($userLogin), QuotedStr($userMatricula), 1, $userAdm == "checked" ? 'true' : 'false', QuotedStr($userPassword), $userSuper == "checked" ? 'true' : 'false', $userAgente == "checked" ? 'true' : 'false', QuotedStr($userEmail), $userStatus == "checked" ? 'true' : 'false', $penalidade, QuotedStr($dacPadraoSel), QuotedStr($userLogin), $userExpiraSenha);
$query = sprintf($query, QuotedStr($userNome), QuotedStr($userLogin), QuotedStr($userMatricula), 1, $userAdm == "checked" ? 'true' : 'false', QuotedStr($userPassword), $userSuper == "checked" ? 'true' : 'false', $userAgente == "checked" ? 'true' : 'false', QuotedStr($userEmail), $userStatus == "checked" ? 'true' : 'false', 0, 0, QuotedStr($userLogin), $userExpiraSenha);
$result = pg_query($dbcon, $query);
if ($result) {
$ret = IncluiAgenteFile($dbcon);
$result = strtoupper($ret) == "OK";
}
/*
* Inclui usuario como grupo.

261
services/query_bd_result_monitor

@ -0,0 +1,261 @@
CREATE OR REPLACE FUNCTION refresh_show_events(ip_filter VARCHAR)
RETURNS VOID AS $$
BEGIN
INSERT INTO resultado_events (
id,
empresa,
ip_vpn,
hd,
troncos_total,
troncos_fail,
event_timestamp,
upstart_information,
load_average,
cpu_cores,
cpu_percentage_busy,
ram_percentage_busy,
ram_total
)
SELECT
vemp.emp_id AS id,
vemp.emp_nome_fantasia AS empresa,
ve.ip_address_central AS ip_vpn,
veh.hd,
COALESCE(troncos_total, 0) AS troncos_total,
COALESCE(troncos_falhas, 0) AS troncos_fail,
MAX(ve.event_timestamp) AS event_timestamp,
upstart_information,
load_average,
cpu_cores,
cpu_percentage_busy,
ram_percentage_busy,
ram_total
FROM
vds_events ve
INNER JOIN vds_events_hd veh ON ve.id = veh.id_event
INNER JOIN vds_empresas vemp ON ve.ip_address_central = vemp.emp_vpn
WHERE
ve.ip_address_central = ip_filter
GROUP BY
vemp.emp_id,
vemp.emp_nome_fantasia,
ve.ip_address_central,
troncos_total,
troncos_fail,
veh.hd,
upstart_information,
load_average,
cpu_cores,
cpu_percentage_busy,
ram_percentage_busy,
ram_total
ORDER BY
event_timestamp DESC
LIMIT 1
ON CONFLICT (id) DO UPDATE
SET
empresa = EXCLUDED.empresa,
ip_vpn = EXCLUDED.ip_vpn,
hd = EXCLUDED.hd,
troncos_total = EXCLUDED.troncos_total,
troncos_fail = EXCLUDED.troncos_fail,
event_timestamp = EXCLUDED.event_timestamp,
upstart_information = EXCLUDED.upstart_information,
load_average = EXCLUDED.load_average,
cpu_cores = EXCLUDED.cpu_cores,
cpu_percentage_busy = EXCLUDED.cpu_percentage_busy,
ram_percentage_busy = EXCLUDED.ram_percentage_busy,
ram_total = EXCLUDED.ram_total;
END;
$$ LANGUAGE plpgsql;
DO $$
DECLARE
rec RECORD;
result RECORD;
BEGIN
FOR rec IN
SELECT DISTINCT emp_id, emp_vpn, emp_nome_fantasia, count(emp_id) AS count_emp
FROM vds_empresas
GROUP BY emp_id
LOOP
-- Adicionar notificação para depuração
RAISE NOTICE 'Processing emp_id: %', rec.emp_id;
FOR result IN
-- HD
WITH base_query_hd AS (
SELECT
veh.filesystem,
veh.hd_percentage_busy,
ve.event_timestamp,
ve.upstart_information,
ve.load_average,
ve.cpu_cores,
ve.cpu_percentage_busy,
ve.ram_percentage_busy,
ve.ram_total,
vpa.hd_percentage_busy AS alert_threshold,
ROW_NUMBER() OVER (PARTITION BY veh.filesystem ORDER BY ve.event_timestamp DESC) AS rn
FROM
(SELECT * FROM ( SELECT * FROM vds_events ORDER BY event_timestamp DESC LIMIT rec.count_emp ) AS vde WHERE vde.id_servidor IN ( SELECT DISTINCT id_servidor FROM vds_events ) ) vde
INNER JOIN vds_events_hd veh ON ve.id = veh.id_event
INNER JOIN (
SELECT
vemp.emp_id,
vemp.emp_nome_fantasia,
vs.id AS id_server,
vs.address,
pgr.gp_id
FROM
vds_empresas vemp
INNER JOIN vds_servidores vs ON
vs.address = vemp.emp_vpn
INNER JOIN pbx_grupo_revendas pgr ON
pgr.emp_id = vemp.emp_id
WHERE vemp.emp_id = rec.emp_id
) servers ON ve.id_servidor = servers.id_server
INNER JOIN vds_params_alerts vpa ON
vpa.id_group = servers.gp_id
AND vpa.status = 1
),
last_event AS (
SELECT
filesystem,
hd_percentage_busy,
alert_threshold,
event_timestamp,
upstart_information,
load_average,
cpu_cores,
cpu_percentage_busy,
ram_percentage_busy,
ram_total
FROM
base_query_hd
WHERE
rn = 1
),
unique_filesystem_count AS (
SELECT COUNT(DISTINCT filesystem) AS count
FROM last_event
),
-- TRONCO
base_query_troncos AS (
WITH latest_events AS (
SELECT
vet.name,
vet.status,
ROW_NUMBER() OVER (PARTITION BY vet.name ORDER BY ve.event_timestamp DESC) AS rn
FROM
vds_events ve
INNER JOIN vds_events_troncos vet ON ve.id = vet.id_event
INNER JOIN (
SELECT
vemp.emp_id,
vemp.emp_nome_fantasia,
vs.id AS id_server,
vs.address,
pgr.gp_id
FROM
vds_empresas vemp
INNER JOIN vds_servidores vs ON
vs.address = vemp.emp_vpn
INNER JOIN pbx_grupo_revendas pgr ON
pgr.emp_id = vemp.emp_id
WHERE
vemp.emp_id = rec.emp_id
) servers ON ve.id_servidor = servers.id_server
INNER JOIN vds_params_alerts vpa ON
vpa.id_group = servers.gp_id
AND vpa.status = 1
)
SELECT
COUNT(*) AS troncos_total,
SUM(CASE WHEN le.status NOT LIKE '%OK%' THEN 1 ELSE 0 END) AS troncos_fail
FROM
latest_events le
WHERE
le.rn = 1
)
SELECT
json_agg(
json_build_object(
'filesystem', filesystem,
'status', CASE WHEN le.hd_percentage_busy > le.alert_threshold THEN 1 ELSE 0 END
)
) AS hd_total,
SUM(CASE WHEN le.hd_percentage_busy > le.alert_threshold THEN 1 ELSE 0 END) AS hd_fail,
COALESCE((SELECT troncos_total FROM base_query_troncos), 0) AS troncos_total,
COALESCE((SELECT troncos_fail FROM base_query_troncos), 0) AS troncos_fail,
MAX(event_timestamp) AS event_timestamp,
MAX(TO_TIMESTAMP(upstart_information::bigint)) AS upstart_information,
MAX(load_average) AS load_average,
MAX(cpu_cores) AS cpu_cores,
MAX(cpu_percentage_busy) AS cpu_percentage_busy,
MAX(ram_percentage_busy) AS ram_percentage_busy,
MAX(ram_total) AS ram_total
FROM
last_event le
CROSS JOIN
unique_filesystem_count ufc
GROUP BY
ufc.count
LOOP
-- Notificação para depuração
RAISE NOTICE 'Inserting for emp_id: %s, hd_total: %s, event_timestamp: %s, upstart_information: %s',
rec.emp_id, result.hd_total, result.event_timestamp, result.upstart_information;
INSERT INTO resultado_events (
id,
empresa,
ip_vpn,
hd_total,
hd_fail,
troncos_total,
troncos_fail,
event_timestamp,
upstart_information,
load_average,
cpu_cores,
cpu_percentage_busy,
ram_percentage_busy,
ram_total
)
VALUES (
rec.emp_id,
rec.emp_nome_fantasia,
rec.emp_vpn,
result.hd_total,
result.hd_fail,
result.troncos_total,
result.troncos_fail,
result.event_timestamp,
result.upstart_information,
result.load_average,
result.cpu_cores,
result.cpu_percentage_busy,
result.ram_percentage_busy,
result.ram_total
) ON CONFLICT (id) DO
UPDATE
SET
hd_total = EXCLUDED.hd_total,
ip_vpn = EXCLUDED.ip_vpn,
hd_fail = EXCLUDED.hd_fail,
empresa = EXCLUDED.empresa,
troncos_total = EXCLUDED.troncos_total,
troncos_fail = EXCLUDED.troncos_fail,
event_timestamp = EXCLUDED.event_timestamp,
upstart_information = EXCLUDED.upstart_information,
load_average = EXCLUDED.load_average,
cpu_cores = EXCLUDED.cpu_cores,
cpu_percentage_busy = EXCLUDED.cpu_percentage_busy,
ram_percentage_busy = EXCLUDED.ram_percentage_busy,
ram_total = EXCLUDED.ram_total;
END LOOP;
END LOOP;
END $$;

24
sites.php

@ -1,24 +0,0 @@
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$janW = 500;
$janH = 400;
$tpl = 'templates/site.tpl';
$imgNovo = "<img src=\"imgSite/novoUser.png\" width=\"16\" height=\"16\" border=\"0\" title=\"Inclui novo site\">";
$imgNovo = "<a href=\"javaScript:NovaJanela('index.php?idProg=105&idSite=0', 'siteCad', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\">$imgNovo</a>";
$isPostBack = true;
print_r($_POST);
$smarty->assign('erro', $erro);
$smarty->assign("linhas", $linha);
$smarty->assign("txtConsulta", $param);
GetTemplate($smarty, $tpl);
?>

32
sites/siteInsert.php

@ -1,32 +0,0 @@
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$acaoForm = FORM_INSERT;
$erro = IsPostBack() ? ValidaSite($fields, $fieldsName) : "";
if (IsPostBack() && empty($erro)) {
$query = "insert into pbx_sites(host, usuario, senha, basedados, porta, descricao, status) values(%s, %s, %s, %s, %s, %s, %s)";
$query = sprintf($query, QuotedStr($host), QuotedStr($usuario), QuotedStr($senha), QuotedStr($basedados), QuotedStr($porta), QuotedStr($descricao), $status);
$result = pg_query($dbcon, $query);
if ($result) {
$erro = "Registro inserido com sucesso!";
$jsStartup[] = "window.opener.ResetForm();";
$id = 0;
$status = 1;
$porta = '5432';
$host = '';
$senha = '';
$basedados = '';
$descricao = '';
$usuario = '';
} else
$erro = "A operação não pode ser realizada! " . (IsAdmin() ? ("Erro: " . pg_last_error($dbcon)) : "");
}
?>

91
sites/siteSelect.php

@ -1,91 +0,0 @@
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$janW = 500;
$janH = 300;
$paramPesquisa = isset($_REQUEST['paramPesquisa']) ? $_REQUEST['paramPesquisa'] : '';
$filtro = isset($_REQUEST["paramPesquisa"]) ? trim($_REQUEST["paramPesquisa"]) : '';
$filtroNovo = !isset($_REQUEST["pgn"]) ? '' : sprintf("&paramPesquisa%s&pgn=%s&bloco=%s&pg=%s", $_REQUEST["paramPesquisa"], $_REQUEST["pgn"], $_REQUEST["bloco"], $_REQUEST["pg"]);
$recontaPag = ($acao == 'inseri') || (GetFormAcao() == FORM_DELETE) || isset($_POST['pesquisa']);
$tpl = 'siteConsulta.tpl';
$imgNovo = GetLinkFormInsert("siteCad", 'images/novo.gif', $filtroNovo, ' Novo Site');
$linha = "";
if (GetFormAcao() == FORM_DELETE) {
$id = $_GET["id"] ?? "0";
$erro = DeletaSite($dbcon, $id);
}
$compl = '';
if (isset($_REQUEST['paramPesquisa']) && $_REQUEST['paramPesquisa']) {
$compl = PreparaLike($filtro, true);
$compl = sprintf("and (a.descricao ilike %s or a.host ilike %s or a.basedados ilike %s)", $compl, $compl, $compl);
}
$query = "select id, host, usuario, senha,
basedados, porta, descricao, status
from pbx_sites a where 1=1 $compl order by descricao";
$params = "&paramPesquisa=$filtro";
$links = PaginaDados($idProg, $query, $params, $regPagina, $offSet, $pagMostra, true);
$query .= " limit $regPagina offset $offSet";
$result = pg_query($dbcon, $query);
while ($row = pg_fetch_array($result)) {
$id = $row["id"];
$host = $row["host"];
$usuario = $row["usuario"];
$basedados = $row["basedados"];
$porta = $row["porta"];
$descricao = $row["descricao"];
$status = $row["status"];
$imgStatus = $status ? "<img src=\"imgSite/ledOn.gif\" width=\"16\" height=\"16\" border=\"0\" title=\"Ativo\">" : "<img src=\"imgSite/ledOff.gif\" width=\"16\" height=\"16\" border=\"0\" title=\"Inativo\">";
$urlEdita = "&id=$id";
//9903-2104
$descricao = GetLinkFormUpdate($urlEdita, "cadSites", "", 0, 1, $descricao);
$imgEdita = GetLinkFormUpdate($urlEdita, "cadSites");
$imgDel = GetLinkFormDelete($id . '|' . $params, "DeletaSite");
$linha .= " <tr class=\"headData\">
<td align=\"right\">$id</td>
<td align=\"left\" nowrap>$descricao</td>
<td align=\"left\">$host</td>
<td align=\"left\">$usuario</td>
<td align=\"left\">$basedados</td>
<td align=\"left\">$porta</td>
<td align=\"center\" width=\"20\" style=\"border-right: 0\">$imgEdita</td>
<td align=\"center\" width=\"20\" style=\"border-left: 0; border-right: 0\">$imgDel</td>
<td align=\"center\" width=\"20\" style=\"border-left: 0\">$imgStatus</td>
</tr>";
}
$smarty->assign('erro', $erro);
$smarty->assign("linhas", $linha);
$smarty->assign("paramPesquisa", $paramPesquisa);
$smarty->assign("imgNovo", $imgNovo);
$smarty->assign("links", $links);
$smarty->assign("pagMostra", $pagMostra);
$smarty->assign("totalReg", $totalReg);
$smarty->assign("pgn", $_REQUEST["pgn"]);
$smarty->assign("bloco", $_REQUEST["bloco"]);
$smarty->assign("pg", $_REQUEST["pg"]);
GetTemplate($smarty, $tpl);
function DeletaSite($db, $id) {
$query = "delete from pbx_sites where id = $id";
$result = pg_query($db, $query);
if ($result)
return "Registro deletado com sucesso!";
else
return "A operação não pode ser realizada! " . (IsAdmin() ? ("Erro: " . pg_last_error($dbcon)) : "");
}
?>

30
sites/siteUpdate.php

@ -1,30 +0,0 @@
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$acaoForm = FORM_SAVE;
$erro = IsPostBack() ? ValidaSite($fields, $fieldsName) : "";
if (IsPostBack() && empty($erro)) {
$query = "update pbx_sites
set host = %s,
usuario = %s,
senha = %s,
basedados = %s,
porta = %s,
descricao = %s,
status = %s
where id = %s ";
$query = sprintf($query, QuotedStr($host), QuotedStr($usuario), QuotedStr($senha), QuotedStr($basedados), QuotedStr($porta), QuotedStr($descricao), $status, $id);
$result = pg_query($dbcon, $query);
if ($result) {
$erro = "Registro alterado com sucesso!";
$jsStartup[] = "window.opener.ResetForm();";
} else
$erro = "A operação não pode ser realizada! " . (IsAdmin() ? ("Erro: " . pg_last_error($dbcon)) : "");
}
?>

78
sites/sites.php

@ -1,78 +0,0 @@
<?php
/*
* variavel que vai conter o template
*/
$janW = 500;
$janH = 250;
$fields = array('host', 'usuario', 'senha', 'basedados', 'porta', 'descricao');
$fieldsName = array('Host', 'Usuário', 'Senha', 'Base de Dados', 'Porta', 'Nome');
$erro = "";
if ((GetFormAcao() == FORM_SELECT) || (GetFormAcao() == FORM_DELETE)) {
include("sites/siteSelect.php");
} else {
$tpl = 'site.tpl';
$tpLayout = 1;
if (IsPostBack()) {
$id = $_POST["idSite"];
$host = $_POST["host"];
$usuario = isset($_POST["usuario"]) ? $_POST["usuario"] : 'manager';
$senha = isset($_POST["senha"]) ? $_POST["senha"] : 'manager007';
$basedados = $_POST["basedados"];
$porta = $_POST["porta"];
$descricao = $_POST["descricao"];
$status = isset($_POST["status"]) ? 1 : 0;
} else {
if (GetFormAcao() == FORM_UPDATE) {
$id = $_GET["id"] ?? "0";
$query = "select id, host, usuario, senha,
basedados, porta, descricao, status
from pbx_sites where id = $id";
$result = pg_query($dbcon, $query);
$row = pg_fetch_array($result);
foreach ($row as $key => $value) {
$GLOBALS[$key] = $value;
}
} else {
$id = 0;
$status = 1;
$porta = '5432';
}
}
if ((GetFormAcao() == FORM_NEW) || (GetFormAcao() == FORM_INSERT)) {
include("siteInsert.php");
} else if ((GetFormAcao() == FORM_UPDATE) || (GetFormAcao() == FORM_SAVE)) {
include("siteUpdate.php");
}
$smarty->assign('msgErro', $erro);
$smarty->assign('host', $host);
$smarty->assign('usuario', $usuario);
$smarty->assign('senha', $senha);
$smarty->assign('basedados', $basedados);
$smarty->assign('porta', $porta);
$smarty->assign('descricao', $descricao);
$smarty->assign('status', $status ? "checked" : "");
$smarty->assign('idSite', $id);
$smarty->assign("formAction", $acaoForm);
$smarty->assign("formAcaoDesc", GetFormAcaoDesc($acaoForm));
GetTemplate($smarty, $tpl);
}
function ValidaSite($fields, $fieldsName) {
foreach ($fields as $key => $value) {
if (empty($_POST[$value]))
return $fieldsName[$key] . " é um campo de preenchimento obrigatório!";
}
return "";
}
?>

34
start.php

@ -20,32 +20,18 @@ $isPbxRequest = (isset($_GET["pbxRequest"]) && $_GET["pbxRequest"]) || ((isset($
* Seção insere todos os arquivo necessáros
* para funcionamento das aplicações
*/
include("nocache.php");
require("util/Browser.php");
require("util/util.php");
include("util/cnvrtFunctions.php");
require("util/datas.php");
require("util/funcoesDataHora.php");
require("contacteFunc.php");
include('bd.php');
include_once('bd.php');
require("util/funcoesApl.php");
require("util/funcoesLgpd.php");
include("startSession.php");
require('configs/config.php');
require("libs/Smarty.class.php");
include_once('util/funcoesAmi.php');
if ($isPbxRequest) {
include_once('admin/funcoes.php');
}
require("contacteFunc.php");
require('util/chamadaApi.php');
if (!$isPbxRequest) {
include('cadastros/funcoesCadastro.php');
}
if ($isPbxRequest) {
include_once('admin/padroes.php');
}
require("autoload/autoload.php");
//Ffiltra strings na entrada
FiltraString();
@ -76,11 +62,6 @@ $setMethod = "Post";
*/
$smarty = IsAjax() ? null : new smarty();
/*
* Detecta informações do Browser
* e palataforma
*/
$infoDispositivo = new Browser();
/*
@ -146,12 +127,7 @@ $_SESSION["SSLegendaFontSize"] = false;
$_SESSION["SSLegendaPosTop"] = false;
$_SESSION["SSLegendaPosLeft"] = false;
/*
* Guarda o ultimo dac logado na interface do agente.
*/
if (!isset($_SESSION["SS_ultimo_dac_agente"])) {
$_SESSION["SS_ultimo_dac_agente"] = '';
}
/*
* Scriptis inseridos para uma pagina em particular

11
templates/complementoMenu.htm

@ -11,14 +11,5 @@
<div class="menuComp">{$links}</div></td>
</tr>
</table>
{$agrupa}
{if $erro}
<table>
<tr>
<td>{$erro}</td>
</tr>
</table>
</td></tr></table>
{/if}
{/capture}

210
templates/master.tpl

@ -1,115 +1,119 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>{$smarty.const.TITLE_SITE} {$versaoApl}</title>
{if $smarty.const.FAVICON_SITE}<link rel="shortcut icon" href="{$smarty.const.FAVICON_SITE}">{/if}
{$styleFile}
<head>
<title>{$smarty.const.TITLE_SITE} {$versaoApl}</title>
{if $smarty.const.FAVICON_SITE}
<link rel="shortcut icon" href="{$smarty.const.FAVICON_SITE}">{/if}
{$styleFile}
{if $scriptGlobal}{$scriptGlobal}{/if}
{if $scriptPage}{$scriptPage}{/if}
{if $scriptBlok}{$scriptBlok}{/if}
{$cssBlock}
{if $scriptPage}{$scriptPage}{/if}
{if $scriptBlok}{$scriptBlok}{/if}
{$cssBlock}
</head>
<body {$onLoad} {$infoBody}>
<form id="formGeral"
name="formGeral" {if $setActPage != null} action="{$setActPage}" {if $functionForm}{$functionForm}{/if} {$upload} {/if}
method="{if $setMethod != null}{$setMethod}{else}post{/if}">
<input name="idProg" type="hidden" value="{$idProg}">
<input name="idSubProg" type="hidden" value="{$idSubProg}">
<input name="pbxRequest" type="hidden" value="{$pbxRequest}">
<input name="idHand" type="hidden" value="{$idHand}">
<input name="screenW" id="screenW" type="hidden" value="{$screenW}">
<input name="screenH" id="screenH" type="hidden" value="{$screenH}">
<input name="tbLayout" id="tbLayout" type="hidden" value="{$tbLayout}">
<div id="tabLayout" width="760" height="100%" bgcolor="#FFFFFF" style="{$styleLayout}" align="center"
cellpadding="0" cellspacing="0" border="0">
<table width="100%" cellpadding="0">
{if !$tpLayout}
<tr class="noprint">
<td class="headSite" valign="top">
<table width="100%" class="headSite" align="center" cellpadding="0" cellspacing="0" border="0" style="border: 1px solid #e9e9e9; border-radius: 4px;">
<tr>
<td>{$navLogin}</td>
</tr>
<tr>
<td {$setLogo}>{$logoPrinc}</td>
</tr>
<tr>
<td>{$menuGeral}</td>
</tr>
</table>
</td>
</tr>
{/if}
{if $idProg != 14}
<form id="formGeral" name="formGeral" {if $setActPage != null} action="{$setActPage}"
{if $functionForm}{$functionForm}{/if} {$upload} {/if}
method="{if $setMethod != null}{$setMethod}{else}post{/if}">
<input name="idProg" type="hidden" value="{$idProg}">
<input name="idSubProg" type="hidden" value="{$idSubProg}">
<input name="pbxRequest" type="hidden" value="{$pbxRequest}">
<input name="idHand" type="hidden" value="{$idHand}">
<input name="screenW" id="screenW" type="hidden" value="{$screenW}">
<input name="screenH" id="screenH" type="hidden" value="{$screenH}">
<div id="tabLayout" bgcolor="#FFFFFF" style="{$styleLayout}" align="center" cellpadding="0" cellspacing="0"
border="0">
<table width="100%" cellpadding="0">
{if !$tpLayout}
<tr class="noprint">
<td class="headSite" valign="top">
<table width="100%" class="headSite" align="center" cellpadding="0" cellspacing="0" border="0"
style="border: 1px solid #e9e9e9; border-radius: 4px;">
<tr>
<td>{$navLogin}</td>
</tr>
<tr>
<td {$setLogo}>{$logoPrinc}</td>
</tr>
<tr>
<td>{$menuGeral}</td>
</tr>
</table>
</td>
</tr>
{/if}
{if $idProg != 14 && $idProg != 370}
<tr>
<td>&nbsp;</td>
</tr>
{else}
{literal}<script>
$('#tabLayout').css({"top": '0px'})
</script>{/literal}
{/if}
<tr>
<td>&nbsp;</td>
<td id="conteudoSite" valign="top">
<div id="content" class="content">
<table width="100%" height="{$heightMasterContent}" border="0" cellpadding="0">
<tr>
<td>
{if $smarty.capture.display}{$smarty.capture.display}{else}{$conteudo}{/if}
</td>
</tr>
</table>
</div>
</td>
</tr>
{else}
{literal}<script>$('#tabLayout').css({"top": '0px'})</script>{/literal}
{/if}
<tr>
<td id="conteudoSite" valign="top">
<div id="content" class="content">
<table width="100%" height="{$heightMasterContent}" border="0"
align="{if $alineMaster ne null}{$alineMaster}{else}center{/if}" cellspacing="0"
cellpadding="0">
<tr>
<td align="{if !$wAlineMaster}left{else}{$wAlineMaster}{/if}"
valign="{if $vAlineMaster ne null}{$vAlineMaster}{else}middle{/if}">
{if $smarty.capture.display}{$smarty.capture.display}{else}{$conteudo}{/if}
{if $footer}
<tr class="noprint">
<td style="height: 50px">
<div id="rodapeSite">
<table width="100%" border="0" cellspacing="5" cellpadding="5">
<tr>
<td width="159" valign="middle" align="center"><img
src="{$smarty.const.LOGO_FOOTER_SITE}" alt="{$smarty.const.NOME_SITE}"
title="{$smarty.const.NOME_SITE}" align="bottom"></td>
<td valign="middle" align="left" style="color: #ababab">
Tel.: {$smarty.const.TELEFONE_SITE1} - Email: {$smarty.const.EMAIL_SITE1} <br />
{$smarty.const.POWERED_BY}
</td>
<td width="159" align="right">&nbsp</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</td>
</tr>
{/if}
</table>
<!-- ALTERAÇÃO MODAL LUCAS -->
<div id="myModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">&times;</span>
<h3>{$smarty.const.NOME_SITE}</h3>
</div>
<div class="modal-body">
<div class="myIframe">
<iframe id="iframe" src='' style="border: none;"></iframe>
</div>
{if $footer}
<tr class="noprint">
<td style="height: 50px">
<div id="rodapeSite">
<table width="100%" border="0" cellspacing="5" cellpadding="5">
<tr>
<td width="159" valign="middle" align="center"><img src="{$smarty.const.LOGO_FOOTER_SITE}" alt="{$smarty.const.NOME_SITE}" title="{$smarty.const.NOME_SITE}" align="bottom"></td>
<td valign="middle" align="left" style="color: #ababab">
Tel.: {$smarty.const.TELEFONE_SITE1} - Email: {$smarty.const.EMAIL_SITE1} <br/>
{$smarty.const.POWERED_BY}
</td>
<td width="159" align="right">&nbsp</td>
</tr>
</table>
<div class="paginacao" style="display:none;">
<span id="prev">&laquo; Voltar</span> &nbsp;&nbsp;
<span id="next">Seguir &raquo;</span>
</div>
</div>
</div>
</td>
</tr>
{/if}
</table>
<!-- ALTERAÇÃO MODAL LUCAS -->
<div id="myModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">&times;</span>
<h3>{$smarty.const.NOME_SITE}</h3>
</div>
<div class="modal-body">
<div class="myIframe">
<iframe id="iframe" src='' style="border: none;"></iframe>
</div>
<div class="paginacao" style="display:none;">
<span id="prev">&laquo; Voltar</span> &nbsp;&nbsp;
<span id="next">Seguir &raquo;</span>
</div>
</div>
</div>
</div>
</div>
{$aguarde}
</form>
<script src="scriptApl/modal.js"></script>
<script src="scriptApl/supervisorchat.js"></script>
{$jQuery}
{$scriptStartup}
</body>
</html>
{$newLoading}
</form>
<script src="scriptApl/modal.js"></script>
<script src="scriptApl/supervisorchat.js"></script>
{$jQuery}
{$scriptStartup}
</body>
</html>

29
templates/seguranca/grupos/grupos.tpl

@ -3,37 +3,44 @@
<input name="pgn" type="hidden" value="{$pgn}" />
<input name="bloco" type="hidden" value="{$bloco}" />
<input name="pg" type="hidden" value="{$pg}" />
<table width="99%" align="center" border="0" cellspacing="0" cellpadding="2" >
<table width="99%" align="center" border="0" cellspacing="0" cellpadding="2">
<tr>
<td>
<table class="filtro" width="99%" border="0" cellpadding="2" cellspacing="0">
<table class="filtro" width="99%" border="0" cellpadding="2" cellspacing="0">
<tr>
<td colspan="2">Palavra Chave</td>
</tr>
<tr>
<tr>
<td>
<input name="paramPesquisa" type="text" id="paramPesquisa" size="20" value="{$paramPesquisa}"/>
<input name="paramPesquisa" type="text" id="paramPesquisa" size="20" value="{$paramPesquisa}" />
<input name="btConsulta" type="submit" id="btConsulta" value="Consultar">
</td>
<td align="right" nowrap="nowrap">
<td align="right" nowrap="nowrap">
{$imgNovo}
</td>
</tr>
</table>
</table>
</td>
</tr>
<tr>
<td>
<table width="100%" class="grid" border="0" cellspacing="0" cellpadding="2">
<table width="100%" class="grid" border="0" cellspacing="0" cellpadding="2">
<tr>
<th align="right">Id</th>
<th align="left" nowrap>Nome</th>
<th align="left" nowrap>Status</th>
<th colspan="{$cols}" align="center">Opera&ccedil;&otilde;es</th>
</tr>
{$linhas}
<tr>
<th align="center" colspan="9"><table width="100%" class="grid" border="0" cellspacing="0" cellpadding="2"><tr><th align="center" style="width: 90%; border:0;">{$links}</th><th align="right" style="width: 10%; border:0;">{$pagMostra}/{$totalReg}</th></tr></table></th>
{$linhas}
<tr>
<th align="center" colspan="10">
<table width="100%" class="grid" border="0" cellspacing="0" cellpadding="2">
<tr>
<th align="center" style="width: 90%; border:0;">{$links}</th>
<th align="right" style="width: 10%; border:0;">{$pagMostra}/{$totalReg}</th>
</tr>
</table>
</th>
</tr>
</table>
</td>
@ -47,4 +54,4 @@
</table>
{/if}
{/capture}
{/capture}

1
templates/seguranca/grupos/gruposUsuario.htm

@ -1,7 +1,6 @@
{capture name="display"}
<input name="gp_id" value="{$gp_id}" type="hidden">
<input name="gp_nome" value="{$gp_nome}" type="hidden">
<input name="gp_lgpd" value="{$gp_lgpd}" type="hidden">
<table class="filtro" border="0" cellpadding="2" cellspacing="0" width="100%">
<tbody>
<tr>

204
templates/vendas/monitorEvents.tpl

@ -1,98 +1,118 @@
{capture name="display" assign="display"}
<table width="100%" cellspacing="2" cellpadding="2" align="center">
<tr>
<td align="center">
<table class="filtro" width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td>
<table align="center">
<tr>
<th>Data Inicial </th>
<td>&nbsp;</td>
<th>Data Final</th>
<td>&nbsp;</td>
<th>Empresa</th>
<table width="100%" cellspacing="2" cellpadding="2" align="center">
<tr>
<td align="center">
<table class="filtro" width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td>
<table align="center">
{* Nome dos filtros *}
<tr>
<td>&nbsp;</td>
<th class="font-filters">Filtrar alertas</th>
<td>&nbsp;</td>
<th class="font-filters">Empresa</th>
<td>&nbsp;</td>
</tr>
{* Conteudo dos filtros *}
<tr>
<td>&nbsp;</td>
<td>
<div class="divs-filters inputs-filters">
<label for="filtroDangerOn"> Sim </label>
<input class="inputs-filters" name="filtroDanger" id="filtroDangerOn"
class="clean" type="radio" value='1' {if $filtroDanger == 1 } checked {/if}
autocomplete="off"/>
<label for="filtroDangerOff"> Não</label>
<input class="inputs-filters" name="filtroDanger" id="filtroDangerOff"
class="clean" type="radio" value='0' {if $filtroDanger == 0 } checked {/if}
autocomplete="off" />
</div>
</td>
<td>&nbsp;</td>
<td>
<div class="divs-filters">
<select class="inputs-filters" name="empresas">
{$empresas}
</select>
<div>
</td>
<td>&nbsp;</td>
<th class="font-filters">Tempo de atualização (minutos): </th>
<td>
<div class="divs-filters">
<input class="inputs-filters" type="text" name="refresh" id="refresh" size="5"
maxlength="5" value="{$refresh}">
<div>
</td>
<td>&nbsp;</td>
<div class="divs-filters">
<td>
<input class="inputs-filters" type="submit" name="btConsulta" id="btConsulta"
value="Consultar" />
</td>
<div>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="100%" class="grid" id="grid" cellspacing="4" cellpadding="4">
{$eventRows}
{if $mensagem}
<tr>
<td colspan="11" align="center">
<strong>{$mensagem}</strong>
</td>
</tr>
{/if}
</table>
</td>
</tr>
</table>
<script>
const valorFiltro = {$filtroDanger};
{literal}
$(function() {
// Obter o horário do cliente
let horarioCliente = new Date().toLocaleTimeString();
let textoHorario = 'Última atualização: ' + horarioCliente;
$('#horario-update').text(textoHorario);
updateData(valorFiltro);
})
</tr>
<tr>
<td style="white-space: nowrap;"><input name="dataIni" id="dataIni" type="text"
size="15" maxlength="10" value="{$dataIni}" onkeyup="formataData(this)"
title="dd/mm/aaaa"></td>
<td>&nbsp;</td>
function updateData(valorFiltro) {
let refresh = $('#refresh').val() * 100000; //converte minuto em milisegundos
<td style="white-space: nowrap;"><input name="dataFim" id="dataFim" type="text"
size="15" maxlength="10" value="{$dataFim}" onkeyup="formataData(this)"
title="dd/mm/aaaa"></td>
<td>&nbsp;</td>
setInterval(function() {
let horarioUpdated = new Date().toLocaleTimeString();
let filtroDanger = valorFiltro;
let idEmpresa = $('select[name="empresas"]').val();
let textoHorario = 'Última atualização: ' + horarioUpdated;
<td>
<select name="empresas">
{$empresas}
</select>
</td>
<td>&nbsp;</td>
<th style="white-space: nowrap;">Tempo de atualização (minutos): </th>
<td align="center">
<input type="text" name="refresh" id="refresh" size="5" maxlength="5"
value="{$refresh}">
</td>
<td>
<input type="submit" name="btConsulta" id="btConsulta" value="Consultar" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="100%" class="grid" id="grid" cellspacing="4" cellpadding="4">
{$eventRows}
{if $mensagem}
<tr>
<td colspan="11" align="center">
<strong>{$mensagem}</strong>
</td>
</tr>
{/if}
</table>
</td>
</tr>
</table>
{literal}
<script>
$(function () {
updateData()
})
function updateData() {
let refresh = $('#refresh').val() * 60000; //converte minuto em milisegundos
setInterval(function () {
let dataIni = $('#dataIni').val();
let dataFim = $('#dataFim').val();
let idEmpresa = $('select[name="empresas"]').val();
$.ajax({
url: 'index.php?idProg=370&ajax=1',
method: 'POST',
data: {
dataIni: dataIni,
dataFim: dataFim,
idEmpresa: idEmpresa
},
success: function (response) {
$('#eventRows').empty();
$('#grid').html(response.eventRows);
}
$.ajax({
url: 'index.php?idProg=370&ajax=1',
method: 'POST',
data: {
filtroDanger: filtroDanger,
idEmpresa: idEmpresa,
},
success: function(response) {
$('#eventRows').empty();
$('#grid').html(response.eventRows);
$('#horario-update').text(textoHorario);
}
});
}, refresh);
}
document.getElementById("formGeral").addEventListener("submit", function() {
document.getElementById("overlay").style.display = "block";
document.getElementById("loading").style.display = "block";
});
}, refresh);
}
</script>
{/literal}
</script>
{/literal}
{/capture}

0
vendas/funcoesMonitorEmail.php

470
vendas/funcoesMonitorEvents.php

@ -1,5 +1,108 @@
<?php
function getParamAlerts( ){
$idUser = GetIdUser();
$condicional = IsAdmin() ? '' : "AND pgu.user_id = $idUser";
$query = "SELECT
hd_percentage_busy,
cpu_percentage_busy,
ram_percentage_busy
FROM vds_params_alerts vpa
INNER JOIN pbx_grupo_usuario pgu ON pgu.gp_id = vpa.id_group
WHERE vpa.status = 1 $condicional";
$result = pg_query($GLOBALS["dbconn"], $query);
if( !$result ){
return "";
}
return pg_fetch_assoc( $result );
}
function IntervalEventValid($ip){
$query = "SELECT EXTRACT(EPOCH FROM MAX(data_reg)) AS last_event FROM vds_events ve WHERE ip_address_central = '$ip'; ";
$result = pg_query($GLOBALS["dbconn"], $query);
if (!$result) {
return true;
}
$event = pg_fetch_assoc($result);
if (empty($event)) {
return true;
}
$atual = time();
return ($event["last_event"] + 20) < $atual;
}
function rowsHeader(){
$rowsHeader = "<tr class=\"headColun\">";
$rowsHeader .= "<th align=\"center\" style=\"white-space: nowrap;\">
Empresa
</th>";
$rowsHeader .= "<th align=\"center\" style=\"white-space: nowrap;\">
IP / VPN
</th>";
$rowsHeader .= "<th class=\"head-table\" align=\"center\">
<span>CONSUMO CPU</span>
</th>";
$rowsHeader .= "<th class=\"head-table\" align=\"center\">
<span>LOAD AVERAGE</span>
</th>";
$rowsHeader .= "<th class=\"head-table\" align=\"center\">
<span> CPU (núcleos)</span>
</th>";
$rowsHeader .= "<th class=\"head-table\" align=\"center\">
<span>RAM DISPONÍVEL</span>
</th>";
$rowsHeader .= "<th class=\"head-table\" align=\"center\">
<span>CONSUMO RAM</span>
</th>";
$rowsHeader .= "<th class=\"head-table\" align=\"center\">
<span>MEMÓRIA RAM</span>
</th>";
$rowsHeader .= "<th class=\"head-table\" align=\"center\">
<span>ALERTAS TRONCOS</span>
</th>";
$rowsHeader .= "<th class=\"head-table\" align=\"center\">
<span>HDS</span>
</th>";
$rowsHeader .= "<th class=\"head-table\" align=\"center\">
<span>TEMPO LIGADO</span>
</th>";
$rowsHeader .= "<th class=\"head-table\" align=\"center\">
<span>DATA DO ÚLTIMO EVENTO</span>
</th>";
$rowsHeader .= "</tr>";
return $rowsHeader;
}
function create_QueryPrepared( $prepared_name, $query ){
$result = pg_prepare( $GLOBALS["dbconn"], $prepared_name, $query );
if( !$result ){
throw new Exception('Ocorreu um erro na consulta que gera o select de pesquisas.');
}
return $prepared_name;
}
/*
* CRIA COMBO COM AS EMPRESAS DISPONÍVEIS PARA O USUÁRIO
*/
@ -10,7 +113,7 @@ function getEmpresasFromIdUser($dbcon, $idEmpresa = null)
$opt = "<option value=\"\">------------------------</option>";
$condicional = IsAdmin() ? '' : "WHERE pgu.user_id = $idUser";
$query = "SELECT vemp.emp_id, vemp.emp_nome_fantasia
$query = "SELECT vemp.emp_id, vemp.emp_nome_fantasia, vemp.emp_vpn
FROM vds_events ve
INNER JOIN vds_servidores vs ON ve.id_servidor = vs.id
INNER JOIN vds_empresas vemp ON vemp.emp_vpn = vs.address
@ -18,7 +121,7 @@ function getEmpresasFromIdUser($dbcon, $idEmpresa = null)
INNER JOIN pbx_grupo_usuario pgu ON pgr.gp_id = pgu.gp_id
$condicional
GROUP BY vemp.emp_id, vemp.emp_nome_fantasia
ORDER BY vemp.emp_nome_fantasia
ORDER BY vemp.emp_vpn
";
$result = pg_query($dbcon, $query);
@ -29,7 +132,7 @@ function getEmpresasFromIdUser($dbcon, $idEmpresa = null)
foreach ($empresas as $empresa) {
$id = $empresa['emp_id'];
$nome = $empresa['emp_nome_fantasia'];
$nome = $empresa['emp_vpn']." - ".$empresa['emp_nome_fantasia'] ;
$selected = $id == $idEmpresa ? "selected" : '';
$opt .= "<option value=\"$id\" $selected >$nome</option>";
}
@ -52,54 +155,29 @@ function getDataEvents($dbcon)
$dataFim = FormatDtMssql($filtros['dataFim']);
$query = " SELECT
ve.id,
ve.ip_address_central,
ve.cpu_percentage_busy,
ve.ram_total,
ve.ram_percentage_busy,
ve.upstart_information,
ve.event_timestamp,
ve.data_reg,
vs.id AS id_server,
vemp.emp_id,
vemp.emp_nome_fantasia,
pgr.gp_id,
vpa.cpu_percentage_busy as param_cpu,
vpa.ram_percentage_busy as param_ram,
vpa.hd_percentage_busy as param_hd
FROM (
SELECT
ve.*,
ROW_NUMBER() OVER(PARTITION BY ve.id_servidor ORDER BY ve.event_timestamp DESC) AS rn
FROM vds_events ve
WHERE ve.event_timestamp::DATE BETWEEN '$dataIni' AND '$dataFim'
) ve
INNER JOIN vds_servidores vs ON ve.id_servidor = vs.id
DISTINCT re.id,
re.empresa,
re.ip_vpn,
re.cpu_cores,
re.load_average,
re.troncos_total,
re.troncos_fail,
re.cpu_percentage_busy,
re.ram_total,
re.hd,
re.ram_percentage_busy,
re.upstart_information,
re.event_timestamp
FROM
resultado_events re
INNER JOIN vds_servidores vs ON re.ip_vpn = vs.address
INNER JOIN vds_empresas vemp ON vemp.emp_vpn = vs.address
INNER JOIN pbx_grupo_revendas pgr ON pgr.emp_id = vemp.emp_id
INNER JOIN pbx_grupo_revendas pgr ON pgr.emp_id = re.id
INNER JOIN pbx_grupo_usuario pgu ON pgr.gp_id = pgu.gp_id
INNER JOIN vds_params_alerts vpa ON vpa.id_group = pgr.gp_id AND vpa.status = 1
WHERE ve.rn = 1
$condicional
GROUP BY
ve.id,
ve.ip_address_central,
ve.cpu_percentage_busy,
ve.ram_total,
ve.ram_percentage_busy,
ve.upstart_information,
ve.event_timestamp,
ve.data_reg,
vs.id,
vemp.emp_id,
vemp.emp_nome_fantasia,
pgr.gp_id,
vpa.cpu_percentage_busy,
vpa.ram_percentage_busy,
vpa.hd_percentage_busy
ORDER BY ve.event_timestamp DESC
;";
//echo "<pre>" . $query;
$result = pg_query($dbcon, $query);
if ($result) {
@ -145,62 +223,7 @@ function getCountEvents($dbcon, $idEmpresa)
ve.id_servidor = servers.id_server
INNER JOIN vds_params_alerts vpa ON
vpa.id_group = servers.gp_id
WHERE ve.event_timestamp::DATE BETWEEN '$dataIni' AND '$dataFim'
AND vpa.status = 1;";
try {
$result = pg_query($dbcon, $query);
if ($result) {
return pg_fetch_assoc($result);
}
throw new Exception('Ocorreu um erro na consulta.');
} catch (Exception $exception) {
$log = $exception->getMessage();
return false;
}
}
/**
* Seleciona a quantidade de eventos relacionados aos troncos que ocorreram no periodo
*/
function getCountEventsTroncos($dbcon, $idEmpresa)
{
$filtros = getFilters();
$dataIni = FormatDtMssql($filtros['dataIni']);
$dataFim = FormatDtMssql($filtros['dataFim']);
$query = " SELECT
SUM(CASE WHEN vet.status not like ('%OK%') THEN 1 ELSE 0 END) AS total_status_tronco_events
FROM
vds_events ve
INNER JOIN vds_events_troncos vet ON ve.id = vet.id_event
INNER JOIN
(
SELECT
vemp.emp_id,
vemp.emp_nome_fantasia,
vs.id AS id_server,
vs.address,
pgr.gp_id
FROM
vds_empresas vemp
INNER JOIN vds_servidores vs ON
vs.address = vemp.emp_vpn
INNER JOIN pbx_grupo_revendas pgr ON
pgr.emp_id = vemp.emp_id
WHERE
vemp.emp_id = $idEmpresa
) servers
ON
ve.id_servidor = servers.id_server
INNER JOIN vds_params_alerts vpa ON
vpa.id_group = servers.gp_id
WHERE ve.event_timestamp::DATE BETWEEN '$dataIni' AND '$dataFim'
AND vpa.status = 1;";
//echo "<pre>" . $query;
WHERE vpa.status = 1;";
try {
$result = pg_query($dbcon, $query);
@ -216,228 +239,30 @@ function getCountEventsTroncos($dbcon, $idEmpresa)
}
/**
* Seleciona a quantidade de eventos relacionados aos hds que ocorreram no periodo
*/
function getCountEventsHds($dbcon, $idEmpresa)
{
$filtros = getFilters();
$dataIni = FormatDtMssql($filtros['dataIni']);
$dataFim = FormatDtMssql($filtros['dataFim']);
$query = " SELECT
veh.filesystem,
SUM(CASE WHEN veh.hd_percentage_busy > vpa.hd_percentage_busy THEN 1 ELSE 0 END) AS total_status_tronco_events
FROM
vds_events ve
INNER JOIN vds_events_hd veh ON ve.id = veh.id_event
INNER JOIN
(
SELECT
vemp.emp_id,
vemp.emp_nome_fantasia,
vs.id AS id_server,
vs.address,
pgr.gp_id
FROM
vds_empresas vemp
INNER JOIN vds_servidores vs ON
vs.address = vemp.emp_vpn
INNER JOIN pbx_grupo_revendas pgr ON
pgr.emp_id = vemp.emp_id
WHERE vemp.emp_id = $idEmpresa
) servers
ON
ve.id_servidor = servers.id_server
INNER JOIN vds_params_alerts vpa ON
vpa.id_group = servers.gp_id
WHERE ve.event_timestamp::DATE BETWEEN '$dataIni' AND '$dataFim'
AND vpa.status = 1
GROUP BY veh.filesystem;";
//echo "<pre> " . $query;
try {
$result = pg_query($dbcon, $query);
if ($result) {
return pg_fetch_all($result);
}
throw new Exception('Ocorreu um erro na consulta.');
} catch (Exception $exception) {
$log = $exception->getMessage();
return false;
}
}
/**
* Seleciona o ultimo status de cada tronco,
* serve para saber se existe algum tronco com falha no momento da ultima consulta
*/
function getStatusTroncos($dbcon, $idEmpresa)
{
$filtros = getFilters();
$dataIni = FormatDtMssql($filtros['dataIni']);
$dataFim = FormatDtMssql($filtros['dataFim']);
$query = " SELECT
vet.name,
MAX(vet.status) AS ultimo_status
FROM
(
SELECT
vet.name,
vet.status,
ROW_NUMBER() OVER(PARTITION BY vet.name ORDER BY ve.event_timestamp DESC) AS rn
FROM
vds_events ve
INNER JOIN vds_events_troncos vet ON ve.id = vet.id_event
INNER JOIN
(
SELECT
vemp.emp_id,
vemp.emp_nome_fantasia,
vs.id AS id_server,
vs.address,
pgr.gp_id
FROM
vds_empresas vemp
INNER JOIN vds_servidores vs ON
vs.address = vemp.emp_vpn
INNER JOIN pbx_grupo_revendas pgr ON
pgr.emp_id = vemp.emp_id
WHERE
vemp.emp_id = $idEmpresa
) servers
ON
ve.id_servidor = servers.id_server
INNER JOIN vds_params_alerts vpa ON
vpa.id_group = servers.gp_id
WHERE ve.event_timestamp::DATE BETWEEN '$dataIni' AND '$dataFim'
AND vpa.status = 1
) vet
WHERE
vet.rn = 1
GROUP BY
vet.name;";
try {
$result = pg_query($dbcon, $query);
if ($result) {
return pg_fetch_all($result);
}
throw new Exception('Ocorreu um erro na consulta.');
} catch (Exception $exception) {
$log = $exception->getMessage();
return false;
}
}
/**
* Seleciona o ultimo status de cada hd,
* serve para saber se existe algum hd com falha no momento da ultima consulta
*/
function getStatusHds($dbcon, $idEmpresa)
{
$filtros = getFilters();
$dataIni = FormatDtMssql($filtros['dataIni']);
$dataFim = FormatDtMssql($filtros['dataFim']);
$query = " SELECT
veh.filesystem,
MAX(veh.hd_percentage_busy) AS ultimo_status
FROM
(
SELECT
veh.filesystem,
veh.hd_percentage_busy,
ROW_NUMBER() OVER(PARTITION BY veh.filesystem ORDER BY ve.event_timestamp DESC) AS rn
FROM
vds_events ve
INNER JOIN vds_events_hd veh ON ve.id = veh.id_event
INNER JOIN
(
SELECT
vemp.emp_id,
vemp.emp_nome_fantasia,
vs.id AS id_server,
vs.address,
pgr.gp_id
FROM
vds_empresas vemp
INNER JOIN vds_servidores vs ON
vs.address = vemp.emp_vpn
INNER JOIN pbx_grupo_revendas pgr ON
pgr.emp_id = vemp.emp_id
WHERE
vemp.emp_id = $idEmpresa
) servers
ON
ve.id_servidor = servers.id_server
INNER JOIN vds_params_alerts vpa ON
vpa.id_group = servers.gp_id
WHERE ve.event_timestamp::DATE BETWEEN '$dataIni' AND '$dataFim'
AND vpa.status = 1
) veh
WHERE
veh.rn = 1
GROUP BY
veh.filesystem;";
//echo "<pre> " . $query;
function getDataParam( $between, $param ){
try {
$result = pg_query($dbcon, $query);
$date = new DateTime();
if ($result) {
return pg_fetch_all($result);
}
$date->modify($param);
throw new Exception('Ocorreu um erro na consulta.');
} catch (Exception $exception) {
$log = $exception->getMessage();
return false;
}
return $date->format('d/m/Y');
}
function getEventsHdsHtml($data)
{
$rows = '';
foreach ($data as $hd) {
$nome = $hd['filesystem'];
$hdBusy = $hd['hd_busy'];
$hdTotal = $hd['hd_total'];
$hdPercentageBusy = $hd['hd_percentage_busy'];
$servidor = $hd['address'];
$rows .= "<tr>";
$rows .= "<td align=\"center\"><a target=\"_blank\" href=\"http://{$servidor}\">{$servidor}</a></td>";
$rows .= "<td align=\"center\">" . $nome . "</td>";
$rows .= "<td align=\"center\">" . $hdTotal . "</td>";
$rows .= "<td align=\"center\">" . $hdBusy . "</td>";
$rows .= "<td align=\"center\">" . $hdPercentageBusy . "</td>";
$rows .= "</tr>";
}
$rows .= "<tr><th colspan='9'></th></tr>";
return $rows;
}
function getFilters()
{
$dataIni = isset($_POST["dataIni"]) && !empty($_POST["dataIni"]) ? $_POST["dataIni"] : date("d/m/Y");
$dataIni = isset($_POST["dataIni"]) && !empty($_POST["dataIni"]) ? $_POST["dataIni"] : getDataParam("/", '-1 month');
$dataFim = isset($_POST["dataFim"]) && !empty($_POST["dataFim"]) ? $_POST["dataFim"] : date("d/m/Y");
$idEmpresa = isset($_POST['empresas']) ? $_POST['empresas'] : $_SESSION["SSstorageFiltros"]['idEmpresa'];
$idEmpresa = isset($_POST['empresas']) ? $_POST['empresas'] : "";
$filtroDanger = ( isset($_POST["filtroDanger"]) && !empty($_POST["filtroDanger"])) ? $_POST["filtroDanger"] : 0;
return array(
'dataIni' => $dataIni,
'dataFim' => $dataFim,
'idEmpresa' => $idEmpresa,
'filtroDanger' => $filtroDanger,
);
}
@ -448,26 +273,19 @@ function getFilters()
*/
function timestampConvert($timestamp)
{
$timestamp = intval($timestamp); // Converte a string para um número (timestamp)
$dataAtual = time();
$tempoDecorrido = $dataAtual - $timestamp; // Calcula a diferença em segundos entre os timestamps
$event = date_create( "@".$timestamp );
$dataini = date_create("@0"); // começa do zero até o $event e pega a diferença percorrido diff
// Calcula o tempo decorrido em dias, horas, minutos e segundos
$dias = floor($tempoDecorrido / (3600 * 24)); // 1 dia = 24 horas * 3600 segundos
$tempoDecorrido -= $dias * 3600 * 24;
$horas = floor($tempoDecorrido / 3600); // 1 hora = 3600 segundos
$tempoDecorrido -= $horas * 3600;
$minutos = floor($tempoDecorrido / 60); // 1 minuto = 60 segundos
$segundos = $tempoDecorrido % 60; // Restante são os segundos
$tempo_decorrido = $event->diff( $dataini );
return sprintf("%d dia(s) %02d:%02d:%02d", $dias, $horas, $minutos, $segundos);
return $tempo_decorrido->format('%a dia(s) %H:%I:%S');
}
/**
* Recebe um valor em segundos e converte para dias horas minutos e segundos.
*/
function calcularDiferencaTempo($diferencaSegundos) {
function calcularDiferencaTempo($diferencaSegundos)
{
$dias = floor($diferencaSegundos / (60 * 60 * 24));
$diferencaSegundos %= (60 * 60 * 24);
@ -573,7 +391,7 @@ function checkSendAlert($dbcon, $idServidor)
AND vpa.alert_frequency < EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - vsa.event_timestamp)) / 3600
LIMIT 1;
";
//echo "<pre>" . $query;
try {
$result = pg_query($dbcon, $query);
@ -647,7 +465,7 @@ function sendAlert($dbcon, $idServidor)
// . " Hds: " . $countAlertsHds . "\n"
// . " Total Eventos: " . $countAlertsTotal . "\n";]
$dataSendMail = "testeeeeee";
$dataSendMail = "";
$sendMail = sendMail($mailToSend, $dataSendMail);
// if ($sendMail){
@ -723,7 +541,6 @@ function getDataEventSend($dbcon, $idServidor)
ve.event_timestamp DESC;
";
//echo "<pre>" . $query;
try {
$result = pg_query($dbcon, $query);
@ -751,7 +568,6 @@ function getEventsTroncosFromIdEvent($dbcon, $idEvent)
WHERE vet.id_event = $idEvent;
";
//echo "<pre>" . $query;
try {
$result = pg_query($dbcon, $query);
@ -781,7 +597,6 @@ function getEventsHdsFromIdEvent($dbcon, $idEvent)
WHERE veh.id_event = $idEvent;
";
//echo "<pre>" . $query;
try {
$result = pg_query($dbcon, $query);
@ -814,7 +629,6 @@ function getEmpresasFromIdServer($dbcon, $idServidor)
vs.id = $idServidor;
";
//echo "<pre>" . $query;
try {
$result = pg_query($dbcon, $query);

140
vendas/funcoesMonitorHD.php

@ -0,0 +1,140 @@
<?php
function query_CountEventsHds(){
return " SELECT
veh.filesystem,
SUM(CASE WHEN veh.hd_percentage_busy > vpa.hd_percentage_busy THEN 1 ELSE 0 END) AS total_status_tronco_events
FROM
vds_events ve
INNER JOIN vds_events_hd veh ON ve.id = veh.id_event
INNER JOIN
(
SELECT
vemp.emp_id,
vemp.emp_nome_fantasia,
vs.id AS id_server,
vs.address,
pgr.gp_id
FROM
vds_empresas vemp
INNER JOIN vds_servidores vs ON
vs.address = vemp.emp_vpn
INNER JOIN pbx_grupo_revendas pgr ON
pgr.emp_id = vemp.emp_id
WHERE vemp.emp_id = $1
) servers
ON
ve.id_servidor = servers.id_server
INNER JOIN vds_params_alerts vpa ON
vpa.id_group = servers.gp_id
AND vpa.status = 1
GROUP BY veh.filesystem;";
}
function getCountEventsHds($prepared_name, $param){
try {
$result = pg_execute($GLOBALS["dbconn"], $prepared_name, $param);
if ($result) {
return pg_fetch_all($result);
}
throw new Exception('Ocorreu um erro na consulta.');
} catch (Exception $exception) {
$log = $exception->getMessage();
return false;
}
}
function getStatusHds($prepared_name, $param){
try {
$result = pg_execute($GLOBALS["dbconn"], $prepared_name, $param);
if ($result) {
return pg_fetch_all($result);
}
throw new Exception('Ocorreu um erro na consulta.');
} catch (Exception $exception) {
$log = $exception->getMessage();
return false;
}
}
function query_StatusHds(){
return " SELECT
veh.filesystem,
MAX(veh.hd_percentage_busy) AS ultimo_status
FROM
(
SELECT
veh.filesystem,
veh.hd_percentage_busy,
ROW_NUMBER() OVER(PARTITION BY veh.filesystem ORDER BY ve.event_timestamp DESC) AS rn
FROM
vds_events ve
INNER JOIN vds_events_hd veh ON ve.id = veh.id_event
INNER JOIN
(
SELECT
vemp.emp_id,
vemp.emp_nome_fantasia,
vs.id AS id_server,
vs.address,
pgr.gp_id
FROM
vds_empresas vemp
INNER JOIN vds_servidores vs ON
vs.address = vemp.emp_vpn
INNER JOIN pbx_grupo_revendas pgr ON
pgr.emp_id = vemp.emp_id
WHERE
vemp.emp_id = $1
) servers
ON
ve.id_servidor = servers.id_server
INNER JOIN vds_params_alerts vpa ON
vpa.id_group = servers.gp_id
AND vpa.status = 1
) veh
WHERE
veh.rn = 1
GROUP BY
veh.filesystem;";
}
function getEventsHdsHtml($data)
{
$rows = '';
foreach ($data as $hd) {
$nome = $hd['filesystem'];
$hdBusy = $hd['hd_busy'];
$hdTotal = $hd['hd_total'];
$hdPercentageBusy = $hd['hd_percentage_busy'];
$servidor = $hd['address'];
$rows .= "<tr>";
$rows .= "<td align=\"center\"><a target=\"_blank\" href=\"http://{$servidor}\">{$servidor}</a></td>";
$rows .= "<td align=\"center\">" . $nome . "</td>";
$rows .= "<td align=\"center\">" . $hdTotal . "</td>";
$rows .= "<td align=\"center\">" . $hdBusy . "</td>";
$rows .= "<td align=\"center\">" . $hdPercentageBusy . "</td>";
$rows .= "</tr>";
}
$rows .= "<tr><th colspan='9'></th></tr>";
return $rows;
}

120
vendas/funcoesMonitorTroncos.php

@ -0,0 +1,120 @@
<?php
function query_StatusTroncos(){
return " SELECT
vet.name,
MAX(vet.status) AS ultimo_status
FROM
(
SELECT
vet.name,
vet.status,
ROW_NUMBER() OVER(PARTITION BY vet.name ORDER BY ve.event_timestamp DESC) AS rn
FROM
vds_events ve
INNER JOIN vds_events_troncos vet ON ve.id = vet.id_event
INNER JOIN
(
SELECT
vemp.emp_id,
vemp.emp_nome_fantasia,
vs.id AS id_server,
vs.address,
pgr.gp_id
FROM
vds_empresas vemp
INNER JOIN vds_servidores vs ON
vs.address = vemp.emp_vpn
INNER JOIN pbx_grupo_revendas pgr ON
pgr.emp_id = vemp.emp_id
WHERE
vemp.emp_id = $1
) servers
ON
ve.id_servidor = servers.id_server
INNER JOIN vds_params_alerts vpa ON
vpa.id_group = servers.gp_id
AND vpa.status = 1
) vet
WHERE
vet.rn = 1
GROUP BY
vet.name;";
}
/**
* Seleciona o ultimo status de cada tronco,
* serve para saber se existe algum tronco com falha no momento da ultima consulta
*/
function getStatusTroncos($prepared_name, $param)
{
try {
$result = pg_execute($GLOBALS["dbconn"], $prepared_name, $param);
if ($result) {
return pg_fetch_all($result);
}
throw new Exception('Ocorreu um erro na consulta.');
} catch (Exception $exception) {
$log = $exception->getMessage();
return false;
}
}
function query_CountEventsTroncos(){
return "SELECT
SUM(CASE WHEN vet.status not like ('%OK%') THEN 1 ELSE 0 END) AS total_status_tronco_events
FROM
vds_events ve
INNER JOIN vds_events_troncos vet ON ve.id = vet.id_event
INNER JOIN
(
SELECT
vemp.emp_id,
vemp.emp_nome_fantasia,
vs.id AS id_server,
vs.address,
pgr.gp_id
FROM
vds_empresas vemp
INNER JOIN vds_servidores vs ON
vs.address = vemp.emp_vpn
INNER JOIN pbx_grupo_revendas pgr ON
pgr.emp_id = vemp.emp_id
WHERE
vemp.emp_id = $1
) servers
ON
ve.id_servidor = servers.id_server
INNER JOIN vds_params_alerts vpa ON
vpa.id_group = servers.gp_id
AND vpa.status = 1;";
}
/**
* Seleciona a quantidade de eventos relacionados aos troncos que ocorreram no periodo
*/
function getCountEventsTroncos($prepared_name, $param)
{
try {
$result = pg_execute( $GLOBALS["dbconn"], $prepared_name, $param );
if ($result) {
return pg_fetch_assoc($result);
}
throw new Exception('Ocorreu um erro na consulta.');
} catch (Exception $exception) {
$log = $exception->getMessage();
return false;
}
}

8
vendas/monitorDetailsCpu.php

@ -5,6 +5,9 @@ $tpLayout = 1;
$fieldsForm = array();
$fieldsForm = IsPostBack() ? $_POST : $_GET;
$fieldsForm['dataIni'] = rawurldecode($fieldsForm['dataIni']);
$fieldsForm['dataFim'] = rawurldecode($fieldsForm['dataFim']);
$dataEventsCpu = getDataCpuFromServer($dbcon, $fieldsForm);
$eventCpuRows = getEventsCpuHtml($dataEventsCpu);
@ -70,10 +73,13 @@ function getEventsCpuHtml($data)
{
$rows = '';
$alertsOverParams = '';
if ($data) {
$alertsOverParams = getDurationAlerts($data);
}
$rowsHeader = '';
if ($alertsOverParams) {
$servidor = $data[0]['address'];
@ -111,6 +117,8 @@ function getEventsCpuHtml($data)
</tr>";
$rows .= "<tr>";
$rows .= "<tr><td align=\"center\" colspan=\"11\">Nenhum registro encontrado!</td></tr>";
$rowsOrderDesc = '';
}
$rows .= "<tr><th colspan='11'></th></tr>";

20
vendas/monitorDetailsHd.php

@ -16,17 +16,18 @@ function getDataHdFromServer($dbcon, $fieldsForm)
$dataFim = FormatDtMssql($fieldsForm['dataFim']);
$query = " SELECT
veh.filesystem
, veh.hd_busy
, veh.hd_total
, veh.hd_percentage_busy
hd_element ->> 'busy' AS hd_busy,
hd_element ->> 'total' AS hd_total,
hd_element ->> 'percent' AS hd_percentage_busy,
hd_element ->> 'filesystem' AS filesystem
, vpa.hd_percentage_busy AS param_alarms
, vs.address
, ve.event_timestamp
, LEAD(veh.hd_percentage_busy) OVER (PARTITION BY ve.id_servidor ORDER BY ve.event_timestamp) AS proximo_evento
, LEAD(hd_element ->> 'percent') OVER (PARTITION BY ve.id_servidor ORDER BY ve.event_timestamp) AS proximo_evento
, LEAD(ve.event_timestamp) OVER (PARTITION BY ve.id_servidor ORDER BY ve.event_timestamp) AS timestamp_proximo_evento
FROM
vds_events_hd veh
CROSS JOIN jsonb_array_elements(hd) AS hd_element
INNER JOIN
vds_events ve ON ve.id = veh.id_event
INNER JOIN
@ -40,7 +41,7 @@ function getDataHdFromServer($dbcon, $fieldsForm)
WHERE
vemp.emp_id = $idEmpresa
AND
veh.filesystem = '$filesystem'
hd_element ->> 'filesystem' = '$filesystem'
AND
ve.event_timestamp::DATE BETWEEN '$dataIni' AND '$dataFim'
ORDER BY
@ -66,9 +67,12 @@ function getDataHdFromServer($dbcon, $fieldsForm)
function getEventsHdHtml($data)
{
$rows = '';
$rowsHeader= '';
$rowsOrderDesc='';
$alertsOverParams = '';
if ($data) {
$alertsOverParams = getDurationAlerts($data);
$alertsOverParams = getDurationAlertsHD($data);
}
if ($alertsOverParams) {
@ -130,7 +134,7 @@ function getEventsHdHtml($data)
* Retorna a duração de cada evento, contabilizando desde o momento
* em que o valor excedeu o parametro definido nas configurações de alertas de eventos.
*/
function getDurationAlerts($data)
function getDurationAlertsHD($data)
{
$startAlert = null;
$finishAlert = null;

74
vendas/monitorDetailsRam.php

@ -63,52 +63,62 @@ function getDataRamFromServer($dbcon, $fieldsForm)
}
}
function without_events_ram(){
$rows = "<tr class=\"headColun\">
<th colspan=\"11\" align=\"center\"> INFORMAÇÃO!</th>
</tr>";
$rows .= "<tr>";
$rows .= "<tr><td align=\"center\" colspan=\"11\">Nenhum registro encontrado!</td></tr>";
return $rows;
}
function getEventsRamHtml($data)
{
$rows = '';
$servidor = $data[0]['address'];
if ($data) {
$alertsOverParams = getDurationAlerts($data);
if (empty($data)) {
return without_events_ram();
}
$alertsOverParams = getDurationAlertsRAM($data);
if( empty($alertsOverParams) ){
return without_events_ram();
}
if ($alertsOverParams) {
$rowsHeader = "<tr class=\"headColun\">
$servidor = $data[0]['address'];
$rowsHeader = '';
$rowsOrderDesc = null;
$rowsHeader = "<tr class=\"headColun\">
<th colspan=\"9\" align=\"center\"> RAM DO SERVIDOR: <a target=\"_blank\" style=\"color: white;\" href=\"http://{$servidor}\">{$servidor}</a></th>
</tr>";
$rowsHeader .= "<tr class=\"headColun\">
$rowsHeader .= "<tr class=\"headColun\">
<th align=\"center\">CONSUMO %</th>
<th align=\"center\">INÍCIO DO EVENTO</th>
<th align=\"center\">FIM DO EVENTO</th>
<th align=\"center\">DURAÇÃO DO EVENTO</th>";
$rowsHeader .= "</tr>";
$rowsOrderDesc = null;
foreach ($alertsOverParams as $ram) {
$rampercentagebusy = $ram['ram_percentage_busy'];
$eventTimestamp = date('d/m/Y H:i:s', strtotime($ram['event_timestamp']));
$eventTimestampFinish = $ram['event_timestamp_finish'];
$durationAlert = $ram['duration_alert'];
$rows = "<tr>";
$rows .= "<td align=\"center\">" . $rampercentagebusy . "</td>";
$rows .= "<td align=\"center\">" . $eventTimestamp . "</td>";
$rows .= "<td align=\"center\">" . $eventTimestampFinish . "</td>";
$rows .= "<td align=\"center\">" . $durationAlert . "</td>";
$rows .= "</tr>";
$rowsOrderDesc = $rows . $rowsOrderDesc;
}
$rows = null;
} else {
$rows .= "<tr class=\"headColun\">
<th colspan=\"11\" align=\"center\"> INFORMAÇÃO!</th>
</tr>";
$rows .= "<tr>";
$rows .= "<tr><td align=\"center\" colspan=\"11\">Nenhum registro encontrado!</td></tr>";
$rowsHeader .= "</tr>";
foreach ($alertsOverParams as $ram) {
$rampercentagebusy = $ram['ram_percentage_busy'];
$eventTimestamp = date('d/m/Y H:i:s', strtotime($ram['event_timestamp']));
$eventTimestampFinish = $ram['event_timestamp_finish'];
$durationAlert = $ram['duration_alert'];
$rows = "<tr>";
$rows .= "<td align=\"center\">" . $rampercentagebusy . "</td>";
$rows .= "<td align=\"center\">" . $eventTimestamp . "</td>";
$rows .= "<td align=\"center\">" . $eventTimestampFinish . "</td>";
$rows .= "<td align=\"center\">" . $durationAlert . "</td>";
$rows .= "</tr>";
$rowsOrderDesc = $rows . $rowsOrderDesc;
}
$rows = null;
$rows .= "<tr><th colspan='11'></th></tr>";
$rowsTable = $rowsHeader . $rowsOrderDesc . $rows;
@ -120,7 +130,7 @@ function getEventsRamHtml($data)
* Retorna a duração de cada evento, contabilizando desde o momento
* em que o valor excedeu o parametro definido nas configurações de alertas de eventos.
*/
function getDurationAlerts($data)
function getDurationAlertsRAM($data)
{
$startAlert = null;
$finishAlert = null;

45
vendas/monitorDetailsTroncos.php

@ -47,13 +47,30 @@ function getDataTroncosFromServer($dbcon, $fieldsForm)
}
}
function without_events_tronco(){
$rows = "<tr class=\"headColun\">
<th colspan=\"11\" align=\"center\"> INFORMAÇÃO!</th>
</tr>";
$rows .= "<tr>";
$rows .= "<tr><td align=\"center\" colspan=\"11\">Nenhum registro encontrado!</td></tr>";
return $rows;
}
function getEventsTroncosHtml($data)
{
$rows = '';
if ($data) {
$alertsOverParams = getDurationAlerts($data);
$rowsHeader = '';
$rowsOrderDesc='';
if(empty($data)){
return without_events_tronco();
}
$alertsOverParams = getDurationAlertsTronco($data);
if(empty($alertsOverParams)){
return without_events_tronco();
}
if ($alertsOverParams) {
@ -90,13 +107,7 @@ function getEventsTroncosHtml($data)
$rowsOrderDesc = $rows . $rowsOrderDesc;
}
$rows = null;
} else {
$rows .= "<tr class=\"headColun\">
<th colspan=\"11\" align=\"center\"> INFORMAÇÃO!</th>
</tr>";
$rows .= "<tr>";
$rows .= "<tr><td align=\"center\" colspan=\"11\">Nenhum registro encontrado!</td></tr>";
}
}
$rows .= "<tr><th colspan='11'></th></tr>";
$rowsTable = $rowsHeader . $rowsOrderDesc . $rows;
@ -108,9 +119,14 @@ function getEventsTroncosHtml($data)
* Retorna a duração de cada evento, contabilizando desde o momento
* em que o valor excedeu o parametro definido nas configurações de alertas de eventos.
*/
function getDurationAlerts($data)
function getDurationAlertsTronco($data)
{
$troncoNames = getNomesTroncosFromServer($data);
if(empty( $data )){
return;
}
$troncoNames = getNomesTroncosFromServer($data)[0];
$allAlertsOverParams = [];
foreach ($troncoNames as $tronco) {
@ -157,7 +173,7 @@ function getDurationAlerts($data)
}
$allAlertsOverParams = array_merge($allAlertsOverParams, $alertsOverParams);
}
// Ordena o array usando a função compararPorTimestamp
usort($allAlertsOverParams, 'compararPorTimestamp');
@ -174,8 +190,9 @@ function getNomesTroncosFromServer($data)
$columnNames = array_column($data, "name");
$uniqueNames = array_unique($columnNames);
$troncoNames = array_values($uniqueNames);
//echo "<pre>"; print_r($troncoNames);
return $troncoNames;
//echo "<pre>";
//print_r($troncoNames);
return array($troncoNames, count($troncoNames));
}
// Função de comparação para ordenar pelo campo 'event_timestamp' em ordem decrescente

222
vendas/monitorEvents.php

@ -1,9 +1,15 @@
<?php
require_once "vendas/funcoesMonitorEvents.php";
require_once "vendas/funcoesMonitorHD.php";
require_once "vendas/funcoesMonitorTroncos.php";
ini_set('display_errors', 1 );
$monitorLayout = 1;
$ajax = isset($_REQUEST["ajax"]) ? $_REQUEST["ajax"] : '';
$addessServer = isset($_POST['ip_vpn']) ? $_POST['ip_vpn'] : '';
$refresh = isset($_POST['refresh']) ? $_POST['refresh'] : $_SESSION["SSstorageFiltros"]['refresh'];
$refresh = isset($_POST['refresh']) ? $_POST['refresh'] : "";
$pathLog = '/var/log/asterisk/monitor_recursos.log';
if ($refresh < 1) {
@ -14,7 +20,6 @@ if ($refresh < 1) {
$refresh = intval($refresh);
}
$mensagem = "";
$totalVersao = array();
$filtros = getFilters();
@ -23,7 +28,8 @@ $_SESSION["SSstorageFiltros"] = array(
'dataIni' => $filtros['dataIni'],
'dataFim' => $filtros['dataFim'],
'idEmpresa' => $filtros['idEmpresa'],
'refresh' => $refresh
'refresh' => $refresh,
'filtroDanger' => $filtros['filtroDanger'],
);
try {
@ -45,10 +51,10 @@ if ($ajax) {
'dataIni' => $filtros['dataIni'],
'dataFim' => $filtros['dataFim'],
'idEmpresa' => $filtros['idEmpresa'],
'filtroDanger' => $filtros['filtroDanger'],
'refresh' => $refresh,
'mensagem' => $mensagem,
'eventRows' => $eventRows,
'eventHdsRows' => $eventHdsRows,
);
header('Content-Type: application/json; charset=UTF-8');
@ -57,16 +63,28 @@ if ($ajax) {
echo $response;
exit;
} else {
$smarty->assign('dataIni', $filtros['dataIni']);
$smarty->assign('dataFim', $filtros['dataFim']);
$smarty->assign('empresas', $empresas);
$smarty->assign('filtroDanger', $filtros['filtroDanger']);
$smarty->assign('refresh', $refresh);
$smarty->assign('mensagem', $mensagem);
$smarty->assign('eventRows', $eventRows);
$smarty->assign('eventHdsRows', $eventHdsRows);
GetTemplate($smarty, 'vendas/monitorEvents.tpl');
}
function verificaInatividade($eventTime)
{
$inativo = false;
$dateAtual = new DateTime();
$dateEvento = DateTime::createFromFormat('d/m/Y H:i:s', $eventTime);
$diferenca = $dateAtual->diff($dateEvento);
$diferencaMinutos = ($diferenca->days * 24 * 60) + ($diferenca->h * 60) + $diferenca->i;
if ($diferencaMinutos > 5) {
$inativo = true;
} else {
$inativo = false;
}
return $inativo;
}
/**
* retorna o html que irá exibir os dados da tabela principal
@ -77,164 +95,136 @@ function getEventsHtml($dbcon, $data)
$rowsHeader = '';
$updated = date('d/m/Y H:i:s');
$filtros = getFilters();
$habFiltroDanger = $filtros['filtroDanger'];
$dataIni = urlencode($filtros['dataIni']);
$dataFim = urlencode($filtros['dataFim']);
if ($data) {
$rowsHeader .= "<tr>";
$rowsHeader .= " <th colspan=\"11\" align=\"center\">
Ultima atualização: {$updated}
</th>";
$rowsHeader .= "</tr>";
$rowsHeader .= "<tr class=\"headColun\">";
$rowsHeader .= "<th align=\"center\" style=\"white-space: nowrap;\">
Empresa
</th>";
$rowsHeader .= "<th align=\"center\" style=\"white-space: nowrap;\">
IP / VPN
</th>";
$rowsHeader .= "<th align=\"center\">
CONSUMO CPU %
</th>";
$rowsHeader .= "<th align=\"center\">
QTD ALERTAS CPU
</th>";
$rowsHeader .= "<th align=\"center\">
RAM DISPONÍVEL GB
</th>";
$rowsHeader .= "<th align=\"center\">
CONSUMO RAM %
</th>";
$rowsHeader .= "<th align=\"center\">
QTD ALERTAS RAM
</th>";
$rowsHeader .= "<th align=\"center\">
QTD ALERTAS TRONCOS
</th>";
$rowsHeader .= "<th colspan=\"\"align=\"center\">
QTD ALERTAS HDS
</th>";
$rowsHeader .= "<th align=\"center\">
TEMPO LIGADO
</th>";
$rowsHeader .= "<th align=\"center\">
DATA DO ULTIMO EVENTO
</th>";
$rowsHeader .= "</tr>";
$rowsHeader = rowsHeader();
$param_alerts = getParamAlerts( );
foreach ($data as $server) {
$upstartInformation = timestampConvert($server['upstart_information']);
$eventTimestamp = FormataDBDataHora($server['event_timestamp']);
$idEmpresa = $server['emp_id'];
$countAlerts = getCountEvents($dbcon, $idEmpresa);
$countAlertsTroncos = getCountEventsTroncos($dbcon, $idEmpresa);
$countAlertsHds = getCountEventsHds($dbcon, $idEmpresa);
$idEmpresa = $server['id'];
$cpuCores = intval($server['cpu_cores']);
$loadAverage = $server['load_average'];
$cpuPercentage = $server['cpu_percentage_busy'];
$ramPercentage = $server['ram_percentage_busy'];
$paramCpu = $server['param_cpu'];
$paramRam = $server['param_ram'];
$paramHd = $server['param_hd'];
$troncoStatus = getStatusTroncos($dbcon, $idEmpresa);
$hdStatus = getStatusHds($dbcon, $idEmpresa);
$paramCpu = $server['cpu_cores'];
$paramRam = $server['ram_total'];
$paramHd = json_decode($server['hd'], true);
$dangerAux = false;
$troncosTotal = intval($server['troncos_total']);
$troncosFalhas = intval($server['troncos_fail']);
//icone do cpu
$titlecpu = " title=\"possui {$countAlerts['total_cpu_percentage_busy_events']} alerta(s)\"";
$cpuIcon = $cpuPercentage > $paramCpu
? "<img align=\"center\" src = \"imgSite/cpu-bad.png\" width=\"25\" height=\"25\" $titlecpu>"
: "<img align=\"center\" src = \"imgSite/cpu-ok.png\" width=\"25\" height=\"25\" $titlecpu>";
$cpuIcon = $cpuPercentage > $param_alerts["cpu_percentage_busy"]
? "<img class=\"icon-img-danger\" align=\"center\" src = \"imgSite/cpu-bad.svg\" width=\"26\" height=\"26\">"
: "<img align=\"center\" src = \"imgSite/cpu-ok.svg\" width=\"26\" height=\"26\">";
//icone da ram
$titleram = " title=\"possui {$countAlerts['total_ram_percentage_busy_events']} alerta(s)\"";
$ramIcon = $ramPercentage > $paramRam
? "<img align=\"center\" src = \"imgSite/ram-bad.png\" width=\"30\" height=\"14\" $titleram>"
: "<img align=\"center\" src = \"imgSite/ram-ok.png\" width=\"30\" height=\"14\" $titleram>";
$ramIcon = $ramPercentage > $param_alerts["ram_percentage_busy"]
? "<img class=\"icon-img-danger\" align=\"center\" src = \"imgSite/ram-bad.svg\" width=\"26\" height=\"26\">"
: "<img align=\"center\" src = \"imgSite/ram-ok.svg\" width=\"26\" height=\"26\">";
$troncOn = true;
foreach ($troncoStatus as $tronco) {
if (strpos($tronco['ultimo_status'], "OK") === false) {
$troncOn = false;
}
}
//icone do tronco
$titleTronco = " title=\"possui {$countAlertsTroncos['total_status_tronco_events']} alerta(s)\"";
$troncoIcon = $troncOn
? "<img align=\"center\" src = \"imgSite/troncoOn16.png\" width=\"20\" height=\"15\" $titleTronco>"
: "<img align=\"center\" src = \"imgSite/troncoOff16.png\" width=\"20\" height=\"15\" $titleTronco>";
$troncoIcon = !$troncosFalhas
? "<img align=\"center\" src = \"imgSite/troncoOn16.svg\" width=\"23\" height=\"23\">"
: "<img class=\"icon-img-danger\" align=\"center\" src = \"imgSite/troncoOff16.svg\" width=\"23\" height=\"23\">";
//icone dos hds
$hdLink = '';
foreach ($countAlertsHds as $hd) {
$filesystem = $hd['filesystem'];
$total = $hd['total_status_tronco_events'];
$titleHd = "title=\"$filesystem possui $total alerta(s)\"";
$hdLink = '';
$hd_danger = false;
foreach ($paramHd as $hd) {
$filesystem = $hd['filesystem'];
$hdOn = true;
foreach ($hdStatus as $status) {
if ($status['filesystem'] == $filesystem) {
if ($status['ultimo_status'] >= $paramHd) {
$hdOn = false;
}
if ($hd['filesystem'] == $filesystem) {
if ($hd['percent'] >= $param_alerts["hd_percentage_busy"]) {
$hdOn = false;
$hd_danger = true;
}
}
$hradDiskIco = $hdOn
? "<img align=\"center\" src = \"imgSite/hd-ok.png\" width=\"25\" height=\"25\" $titleHd>"
: "<img align=\"center\" src = \"imgSite/hd-bad.png\" width=\"25\" height=\"25\" $titleHd>";
? "<img align=\"center\" src = \"imgSite/hd-ok.svg\" width=\"26\" height=\"26\">"
: "<img class=\"icon-img-danger\" align=\"center\" src = \"imgSite/hd-bad.svg\" width=\"22\" height=\"22\">";
$hdInfo = " $hradDiskIco - " . $total . " </br>";
$hdLink .= "<a style=\"color: black; line-height: 2; text-decoration: none;\" href=\"javaScript:NovaJanela('index.php?idProg=374&idEmpresa=$idEmpresa&filesystem=$filesystem&dataIni=$dataIni&dataFim=$dataFim', 'jnDetailsHd', '700', '900', 'resizable=NO,scrollbars=NO');\">$hdInfo</a>";
$hdInfo = $hradDiskIco . " </br>";
$hdLink .= "<div class=\"tooltip\" onclick=\"javaScript:NovaJanela('index.php?idProg=374&idEmpresa=$idEmpresa&filesystem=$filesystem&dataIni=$dataIni&dataFim=$dataFim', 'jnDetailsHd', '500', '600', 'resizable=NO,scrollbars=NO');\"> $hdInfo <span class=\"tooltiptext\">Disco $filesystem</span></div>";
}
$cpu_danger = ($cpuPercentage > $paramCpu);
$ram_danger = ($ramPercentage > $paramRam);
if ($cpu_danger || $ram_danger || $hd_danger || $troncosFalhas || ($loadAverage > 80)) {
$dangerAux = true;
}
if (!$dangerAux && $habFiltroDanger) {
continue;
}
$rows .= "<tr>";
$inatividade = verificaInatividade($eventTimestamp);
($inatividade) ? $rows .= "<tr class=\"inativo\">" : $rows .= "<tr class=\"row\">";
$rows .= "<td style=\"white-space: nowrap;\">
{$server['emp_nome_fantasia']}
</td>";
{$server['empresa']}
</td>";
$rows .= "<td align=\"center\" style=\"white-space: nowrap;\">
<a target=\"_blank\" style=\"color: black;\" href=\"http://{$server['ip_address_central']}\">
{$server['ip_address_central']}
</a>
<div class=\"tooltip\">
<a target=\"_blank\" href=\"http://{$server['ip_vpn']}\">
{$server['ip_vpn']}
</a>
<span class=\"tooltiptext\">Clique para acessar o servidor</span>
</div>
</td>";
$rows .= "<td align=\"center\"> $cpuPercentage %</td>";
$rows .= "<td style=\"padding-left: 2%\" align=\"left\">
<a style=\"color: black; text-decoration: none; line-height: 2;\" href=\"javaScript:NovaJanela('index.php?idProg=373&idEmpresa=" . urlencode($idEmpresa) . "&dataIni=" . urlencode($dataIni) . "&dataFim=" . urlencode($dataFim) . "', 'jnDetailsCpu', '700', '900', 'resizable=NO,scrollbars=NO');\">
$cpuIcon - {$countAlerts['total_cpu_percentage_busy_events']}
</a>
$rows .= "<td align=\"center\"> <div class=\"cpu-porc\">$cpuPercentage %</td> </div>";
$rows .= "<td align=\"center\"> <div class=\"load-avg tooltip\" style=\"cursor:default\">" . ($loadAverage > 80 ? "<div>" . ($loadAverage . "%" . "</div>" . "<div><span class=\"tooltiptext\"> Risco de empilhamento de processos</span><img class=\"icon-img-danger\" src=\"imgSite/load-avg-danger.svg\" width=\"20\" height=\"20\"></div>") : ("<div>$loadAverage%</div>")) . "</div></td>";
$rows .= "<td align=\"center\">
<div class=\"cpu-class\" onclick=\"javaScript:NovaJanela('index.php?idProg=373&idEmpresa=" . urlencode($idEmpresa) . "&dataIni=" . urlencode($dataIni) . "&dataFim=" . urlencode($dataFim) . "', 'jnDetailsCpu', '700', '900', 'resizable=NO,scrollbars=NO');\">
<div class=\"tooltip\" style =\"margin: 0 5px\"> $cpuIcon <span class=\"tooltiptext\"> Exibir detalhes da CPU </span></div>
<div class=\"tronco-total tooltip\"> $cpuCores <span class=\"tooltiptext\"> Total de núcleos</span></div>
</div>
</td>";
$rows .= "<td align=\"center\"> {$server['ram_total']} Gb</td>";
$rows .= "<td align=\"center\"> {$server['ram_total']} GB</td>";
$rows .= "<td align=\"center\">$ramPercentage %</td>";
$rows .= "<td style=\"padding-left: 2%\" align=\"left\">
<a style=\"color: black; text-decoration: none; \"line-height: 2;\" \"
href=\"javaScript:NovaJanela('index.php?idProg=372&idEmpresa=$idEmpresa&dataIni=$dataIni&dataFim=$dataFim', 'jnDetailsRam', '700', '900', 'resizable=NO,scrollbars=NO');\">
$ramIcon - {$countAlerts['total_ram_percentage_busy_events']}
</a>
$rows .= "<td align=\"center\">
<div class=\"memory-class tooltip\">
<span class=\"tooltiptext\">Exibir avisos de memória RAM</span>
<a href=\"javaScript:NovaJanela('index.php?idProg=372&idEmpresa=$idEmpresa&dataIni=$dataIni&dataFim=$dataFim', 'jnDetailsRam', '500', '600', 'resizable=NO,scrollbars=NO');\">
$ramIcon</a>
</div>
</td>";
$rows .= "<td style=\"padding-left: 3%\" align=\"left\">
<a style=\"color: black; text-decoration: none; \"
href=\"javaScript:NovaJanela('index.php?idProg=371&idEmpresa=$idEmpresa&dataIni=$dataIni&dataFim=$dataFim', 'jnDetailsTroncos', '700', '900', 'resizable=NO,scrollbars=NO');\">
$troncoIcon - {$countAlertsTroncos['total_status_tronco_events']}
</a>
$rows .= "<td align=\"center\">
<div class=\"tronco-class\" style=\"color: black; text-decoration: none; \"
onclick=\"javaScript:NovaJanela('index.php?idProg=371&idEmpresa=$idEmpresa&dataIni=$dataIni&dataFim=$dataFim', 'jnDetailsTroncos', '500', '600', 'resizable=NO,scrollbars=NO');\">
<div class=\"tooltip\"><span class=\"tooltiptext\">Exibir avisos de troncos SIP/IAX</span>
$troncoIcon</div> <div class=\"tronco-total tooltip\"><span class=\"tooltiptext\">Total de troncos</span>$troncosTotal</div> <div class=\"tronco-falhas tooltip\"><span class=\"tooltiptext\">Troncos sem resposta</span>$troncosFalhas</div>
</div>
</td>";
$rows .= "<td style=\"padding-left: 2%\" align=\"left\">$hdLink</td>";
$rows .= "<td class=\"hd-class\">$hdLink</td>";
$rows .= "<td align=\"center\">{$upstartInformation}</td>";
$rows .= "<td align=\"center\">{$eventTimestamp}</td>";
$rows .= "</tr>";
}
} else {
$rowsHeader .= "<tr>";
$rowsHeader .= "<th colspan=\"11\" align=\"center\">Informação!</th>";
$rowsHeader .= "<th colspan=\"12\" align=\"center\">Informação!</th>";
$rowsHeader .= "</tr>";
$rows = "<tr><td align=\"center\" colspan=\"11\">Nenhum registro encontrado!</td></tr>";
$rows = "<tr><td align=\"center\" colspan=\"12\">Nenhum registro encontrado!</td></tr>";
}
$rows .= "<tr><th colspan='11'></th></tr>";
$rows .= "<tr><th colspan='12'></th></tr>";
return $rowsHeader . $rows;
}

Loading…
Cancel
Save