Browse Source

correcao empresa cadastros

spr_change_address_bd
Lucas Awade 12 months ago
parent
commit
5a99d48c7a
  1. 33
      cadastros/ServicosChamadas/servicosChamadas.php
  2. 29
      cadastros/classificaAtendimento/classificaAtendimento.php
  3. 104
      cadastros/classificaAtendimento/classificaDac.php
  4. 14
      cadastros/classificaAtendimento/classificaDetIns.php
  5. 7
      cadastros/classificaAtendimento/classificaIns.php
  6. 20
      cadastros/motivosPausa/motivosPausaInsert.php
  7. 21
      cadastros/motivosPausa/motivosPausaSelect.php
  8. 20
      contacteFunc.php
  9. 13
      include/util/funcoesApl.php
  10. 6
      projeto/base/sql/versao-1.9.0.sql
  11. 24
      seguranca/grupos/grupoInsert.php
  12. 19
      seguranca/grupos/grupoSelect.php
  13. 19
      seguranca/grupos/gruposAudiosRamais.php
  14. 81
      seguranca/grupos/gruposUsuario.php
  15. 41
      seguranca/licencaUsuarioFixo.php
  16. 92
      seguranca/perfil/perfilGrupo.php
  17. 50
      seguranca/usuario.php
  18. 130
      seguranca/usuarioCad.php

33
cadastros/ServicosChamadas/servicosChamadas.php

@ -9,6 +9,7 @@ $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"]); $filtroNovo = !isset($_REQUEST["pgn"]) ? '' : sprintf("&paramPesquisa%s&pgn=%s&bloco=%s&pg=%s", $_REQUEST["paramPesquisa"], $_REQUEST["pgn"], $_REQUEST["bloco"], $_REQUEST["pg"]);
$recontaPag = ($acao == 'novo') || (GetFormAcao() == 'apagar') || isset($_POST['pesquisa']); $recontaPag = ($acao == 'novo') || (GetFormAcao() == 'apagar') || isset($_POST['pesquisa']);
$imgNovo = sprintf('<a href="#" onclick="ServicosChmadasIncluir(%s);" ><img src="images/novo.gif" width="16" height="16" border="0" title="Inclui novo Status" align="absmiddle">Novo Serviço</a>', QuotedStr($filtroNovo)); $imgNovo = sprintf('<a href="#" onclick="ServicosChmadasIncluir(%s);" ><img src="images/novo.gif" width="16" height="16" border="0" title="Inclui novo Status" align="absmiddle">Novo Serviço</a>', QuotedStr($filtroNovo));
$org_id = GetOrganizacao();
if ($acao == 'apagar') { if ($acao == 'apagar') {
$serv_id = strtoupper(trim($_REQUEST['serv_id'])); $serv_id = strtoupper(trim($_REQUEST['serv_id']));
@ -21,10 +22,11 @@ if ($acao == 'apagar') {
GeraExcept("Desvincule o serviço das rotas de entrada para desativa-lo!"); GeraExcept("Desvincule o serviço das rotas de entrada para desativa-lo!");
} }
$query = sprintf("update pbx_servicos set serv_status = $status where serv_id = %s", QuotedStr($serv_id)); $query = sprintf("UPDATE pbx_servicos SET serv_status = $status WHERE serv_id = %s", QuotedStr($serv_id));
$result = pg_query($query); $result = pg_query($dbcon, $query);
if (!$result) if (!$result) {
GeraExcept("Erro ao realizar a operação!"); GeraExcept("Erro ao realizar a operação!");
}
$jsStartup[] = sprintf("alert('%s');", 'Operação realizada com sucesso!'); $jsStartup[] = sprintf("alert('%s');", 'Operação realizada com sucesso!');
} catch (Exception $ex) { } catch (Exception $ex) {
@ -39,11 +41,11 @@ if ($acao == 'apagar') {
GeraExcept("Serviço já cadastrado!"); GeraExcept("Serviço já cadastrado!");
} }
$query = sprintf("INSERT INTO pbx_servicos(serv_id, org_id) VALUES(%s, %s)", QuotedStr($serv_id), $org_id);
$query = sprintf("insert into pbx_servicos(serv_id)values(%s)", QuotedStr($serv_id)); $result = pg_query($dbcon, $query);
$result = pg_query($query); if (!$result) {
if (!$result)
GeraExcept("Erro ao realizar a operação!"); GeraExcept("Erro ao realizar a operação!");
}
$jsStartup[] = sprintf("alert('%s');", 'Operação realizada com sucesso!'); $jsStartup[] = sprintf("alert('%s');", 'Operação realizada com sucesso!');
} catch (Exception $ex) { } catch (Exception $ex) {
@ -57,7 +59,7 @@ if (isset($_REQUEST['paramPesquisa']) && $_REQUEST['paramPesquisa']) {
$compl = sprintf("and (a.serv_id ilike %s)", $compl); $compl = sprintf("and (a.serv_id ilike %s)", $compl);
} }
switch($filtroStatus){ switch ($filtroStatus) {
case 'A': case 'A':
$compl .= 'AND serv_status = 1'; $compl .= 'AND serv_status = 1';
break; break;
@ -66,7 +68,7 @@ switch($filtroStatus){
break; break;
} }
$query = "select serv_id, serv_status from pbx_servicos a where 1=1 $compl order by 1"; $query = "SELECT serv_id, serv_status FROM pbx_servicos WHERE 1=1 $compl order by 1";
$linha = ""; $linha = "";
$params = "&paramPesquisa=$filtro"; $params = "&paramPesquisa=$filtro";
$links = PaginaDados($idProg, $query, $params, $regPagina, $offSet, $pagMostra, true); $links = PaginaDados($idProg, $query, $params, $regPagina, $offSet, $pagMostra, true);
@ -105,12 +107,15 @@ $smarty->assign('filtroStatus', $filtroStatus);
GetTemplate($smarty, $tpl); GetTemplate($smarty, $tpl);
function ServicosRotas($serv_id) { function ServicosRotas($serv_id)
$query = sprintf("select id, nome from pbx_rotas_entrada where serv_id = %s order by nome", QuotedStr($serv_id)); {
$result = pg_query($query); global $dbcon;
$query = sprintf("SELECT id, nome FROM pbx_rotas_entrada WHERE serv_id = %s ORDER BY nome", QuotedStr($serv_id));
$result = pg_query($dbcon, $query);
if (!$result || !pg_num_rows($result)) if (!$result || !pg_num_rows($result)) {
return ''; return '';
}
$str = 'Rotas associadas a este serviço: '; $str = 'Rotas associadas a este serviço: ';
while ($dados = pg_fetch_array($result)) { while ($dados = pg_fetch_array($result)) {
$str .= $dados['id'] . '-' . $dados['nome'] . '; '; $str .= $dados['id'] . '-' . $dados['nome'] . '; ';
@ -118,5 +123,3 @@ function ServicosRotas($serv_id) {
return $str; return $str;
} }
?>

29
cadastros/classificaAtendimento/classificaAtendimento.php

@ -1,8 +1,6 @@
<?php <?php
require("classificaDetalhe.php"); require("classificaDetalhe.php");
//$imgClass = "<img id=\"incClass\" src=\"images/novo.gif\" width=\"16\" height=\"16\" border=\"0\" align=\"absmiddle\" title=\"Inclui nova classificação\">" ;
//$imgClass = "<a href=\"javaScript:NovaJanela('index.php?idProg=30&clas_id=$codItem&descitem=$descricao', 'clasCad', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\">$imgClass Novo Item</a>";
$janW = 510; $janW = 510;
$janH = 35; $janH = 35;
$acao = isset($acao) ? $acao : FORM_SELECT; $acao = isset($acao) ? $acao : FORM_SELECT;
@ -13,6 +11,7 @@ $recontaPag = ($acao == 'inseri') || (GetFormAcao() == FORM_DELETE) || isset($_P
$imgNovo = "<img id=\"incClass\" src=\"images/novo.gif\" width=\"16\" height=\"16\" border=\"0\" align=\"absmiddle\" title=\"Inclui nova classificação\">"; $imgNovo = "<img id=\"incClass\" src=\"images/novo.gif\" width=\"16\" height=\"16\" border=\"0\" align=\"absmiddle\" title=\"Inclui nova classificação\">";
$imgClass = "<a href=\"javaScript:NovaJanela('index.php?idProg=28$filtroNovo', 'clasCad', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\">$imgNovo Nova Classificação</a>"; $imgClass = "<a href=\"javaScript:NovaJanela('index.php?idProg=28$filtroNovo', 'clasCad', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\">$imgNovo Nova Classificação</a>";
$filtroStatus = isset($_POST['status']) ? $_POST['status'] : 'A'; $filtroStatus = isset($_POST['status']) ? $_POST['status'] : 'A';
$org_id = GetOrganizacao();
if (!IsAjax()) { if (!IsAjax()) {
@ -28,7 +27,7 @@ if (!IsAjax()) {
$linhaDados = ""; $linhaDados = "";
$codDetalhe = 0; $codDetalhe = 0;
switch($filtroStatus){ switch ($filtroStatus) {
case 'A': case 'A':
$compl .= "AND clas_status = '1'"; $compl .= "AND clas_status = '1'";
break; break;
@ -37,12 +36,12 @@ if (!IsAjax()) {
break; break;
} }
$query = "select clas_id as id, clas_descricao as desc, clas_status as status from pbx_classifica_atendimento a where 1=1 $compl order by 2"; $query = "SELECT clas_id AS id, clas_descricao AS desc, clas_status AS status FROM pbx_classifica_atendimento a WHERE 1=1 $compl ORDER BY 2";
$params = "&paramPesquisa=$filtro"; $params = "&paramPesquisa=$filtro";
$links = PaginaDados($idProg, $query, $params, $regPagina, $offSet, $pagMostra, true); $links = PaginaDados($idProg, $query, $params, $regPagina, $offSet, $pagMostra, true);
$query .= " limit $regPagina offset $offSet"; $query .= " limit $regPagina offset $offSet";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
While ($row = pg_fetch_array($result)) { while ($row = pg_fetch_array($result)) {
$codigo = $row["id"]; $codigo = $row["id"];
$descricao = $row["desc"]; $descricao = $row["desc"];
@ -84,9 +83,10 @@ if (IsAjax()) {
$desc = $_GET["desc"]; $desc = $_GET["desc"];
} }
$query = "select clit_id as id, clas_id, clit_descricao as desc, clit_status as status $query = "SELECT clit_id AS id, clas_id, clit_descricao AS desc, clit_status AS status
from pbx_classifica_item FROM pbx_classifica_item
where clas_id = '$codItem' "; WHERE clas_id = '$codItem'
AND org_id = $org_id ";
$imgItem = "<img id=\"incClass\" src=\"images/novo.gif\" width=\"16\" height=\"16\" border=\"0\" align=\"absmiddle\" title=\"Inclui nova classificação\">"; $imgItem = "<img id=\"incClass\" src=\"images/novo.gif\" width=\"16\" height=\"16\" border=\"0\" align=\"absmiddle\" title=\"Inclui nova classificação\">";
$imgItem = "<a href=\"javaScript:NovaJanela('index.php?idProg=30&clas_id=$codItem&descitem={$desc}{$filtroNovo}', 'clasCad', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\">$imgItem Novo Item</a>"; $imgItem = "<a href=\"javaScript:NovaJanela('index.php?idProg=30&clas_id=$codItem&descitem={$desc}{$filtroNovo}', 'clasCad', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\">$imgItem Novo Item</a>";
@ -94,19 +94,15 @@ $totalDet = 0;
$descDet = ""; $descDet = "";
$linhaDet = GetDetalhes($query, $codItem); $linhaDet = GetDetalhes($query, $codItem);
if (IsAjax()) { if (IsAjax()) {
echo GetHtmlDetalhe($linhaDet, $imgItem) . "#" . "[" . $codItem . " - " . $_REQUEST["desc"] . "]"; echo GetHtmlDetalhe($linhaDet, $imgItem) . "#" . "[" . $codItem . " - " . $_REQUEST["desc"] . "]";
exit; exit;
} else { } else {
//$jsJQuery[] = "\$('#dataIni').change(function(){GetAgtFromTransfer();}) "; $jsJQuery[] = "$('input').click(function() {
$('input').removeClass('btSelect');
$jsJQuery[] = "\$('input').click( $(this).addClass('btSelect');
function() { }
\$('input').removeClass('btSelect');
\$(this).addClass('btSelect');
}
);"; );";
$smarty->assign("linhas", $linhaDados); $smarty->assign("linhas", $linhaDados);
@ -127,4 +123,3 @@ if (IsAjax()) {
$smarty->assign('filtroStatus', $filtroStatus); $smarty->assign('filtroStatus', $filtroStatus);
GetTemplate($smarty, 'cadastros/classificaAtendimento/classificaItem.tpl'); GetTemplate($smarty, 'cadastros/classificaAtendimento/classificaItem.tpl');
} }
?>

104
cadastros/classificaAtendimento/classificaDac.php

@ -4,17 +4,17 @@ $tpLayout = 1;
$clasId = $_REQUEST["clas_id"]; $clasId = $_REQUEST["clas_id"];
$clasDesc = $_REQUEST["clas_descricao"]; $clasDesc = $_REQUEST["clas_descricao"];
if (isset($_POST["btIncDac"])) { if (isset($_POST["btIncDac"])) {
$dacs = $_POST["dacs"]; $dacs = $_POST["dacs"];
pg_query($dbcon, 'begin'); pg_query($dbcon, 'begin');
foreach ($dacs as $idDac) { foreach ($dacs as $idDac) {
$query = "insert into pbx_classifica_dacs(clas_id, id_dac ) $query = "INSERT INTO pbx_classifica_dacs(clas_id, id_dac )
select '$clasId', '$idDac' SELECT '$clasId', '$idDac'
where not exists(select '' from pbx_classifica_dacs where id_dac = '$idDac' and clas_id = '$clasId')"; WHERE NOT EXISTS(SELECT '' FROM pbx_classifica_dacs WHERE id_dac = '$idDac' AND clas_id = '$clasId')";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
if (!$result) if (!$result) {
break; break;
}
} }
if ($result) { if ($result) {
@ -29,10 +29,11 @@ if (isset($_POST["btIncDac"])) {
$dacs = $_POST["dacsInc"]; $dacs = $_POST["dacsInc"];
pg_query($dbcon, 'begin'); pg_query($dbcon, 'begin');
foreach ($dacs as $idDac) { foreach ($dacs as $idDac) {
$query = "delete from pbx_classifica_dacs where id_dac = '$idDac' and clas_id = '$clasId' "; $query = "DELETE FROM pbx_classifica_dacs WHERE id_dac = '$idDac' AND clas_id = '$clasId' ";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
if (!$result) if (!$result) {
break; break;
}
} }
if ($result) { if ($result) {
@ -45,13 +46,11 @@ if (isset($_POST["btIncDac"])) {
} }
} }
$dacs = GetDacClas($dbcon, $clasId); $dacs = GetDacClas($dbcon, $clasId);
$dacsIncs = GetDacClasInc($dbcon, $clasId); $dacsIncs = GetDacClasInc($dbcon, $clasId);
GetDac($dbcon, $codDac); GetDac($dbcon, $codDac);
$smarty->assign("clas_id", $clasId); $smarty->assign("clas_id", $clasId);
$smarty->assign("clas_descricao", $clasDesc); $smarty->assign("clas_descricao", $clasDesc);
$smarty->assign("dacs", $dacs); $smarty->assign("dacs", $dacs);
@ -59,97 +58,50 @@ $smarty->assign("dacsIncs", $dacsIncs);
$smarty->assign("erro", $msg); $smarty->assign("erro", $msg);
GetTemplate($smarty, 'cadastros/classificaAtendimento/classificacaoDacs.htm'); GetTemplate($smarty, 'cadastros/classificaAtendimento/classificacaoDacs.htm');
function GetDacClas($dbcon, $clasId) { function GetDacClas($dbcon, $clasId)
{
/* /*
* Carrega lista de dacs disponivel * Carrega lista de dacs disponivel
* para ser inserdo entre as tags <select></select> * para ser inserdo entre as tags <select></select>
*/ */
$org_id = GetOrganizacao();
$query = "SELECT DISTINCT id, nome AS nome, 'Receptivo' AS tipo
FROM pbx_queues_grupos d
WHERE status = 'A'
AND org_id = $org_id
AND id NOT IN(SELECT id_dac FROM pbx_classifica_dacs WHERE clas_id = $clasId)
ORDER BY 2";
$isAdm = (IsAdmin() && !$matricula);
$idUser = !$matricula ? GetIdUser() : GetIdUserFromMatricula($dbcon, $matricula);
$matricula = GetMatricula();
$query = "select distinct id, nome as nome, 'Receptivo' as tipo
from pbx_dacs d
where status = 'A'
and id not in(select id_dac from pbx_classifica_dacs where clas_id = $clasId)
order by 2";
/*
if($isAdm)
{
}
else
{
$query = "select distinct d.id, d.nome, 'Receptivo' as tipo, 'false' as padrao
from pbx_usuarios a, pbx_grupo_usuario b, pbx_fila_grupos c, pbx_dacs d
where b.user_id = a.id
and c.gp_id = b.gp_id
and d.id = c.id
and lower(a.matricula) = lower('$matricula')
and d.id in (select id_dac from pbx_classifica_dacs where clas_id = $clasId)
and d.status = 'A'
order by 1, 2 ";
} */
// echo $query;
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
$dacs = "<select name=\"dacs[]\" id=\"dacs\" size=\"6\" multiple=\"multiple\" style=\"width:250px;\" >"; $dacs = "<select name=\"dacs[]\" id=\"dacs\" size=\"6\" multiple=\"multiple\" style=\"width:250px;\" >";
while ($dados = pg_fetch_row($result)) { while ($dados = pg_fetch_row($result)) {
$dacs .= "<option value=\"$dados[0]\" $sel>$dados[1]</option>"; $dacs .= "<option value=\"$dados[0]\">$dados[1]</option>";
$cont++;
} }
$dacs .= "</select>"; $dacs .= "</select>";
return $dacs; return $dacs;
} }
function GetDacClasInc($dbcon, $clasId) { function GetDacClasInc($dbcon, $clasId)
{
/* /*
* Carrega lista de dacs disponivel * Carrega lista de dacs disponivel
* para ser inserdo entre as tags <select></select> * para ser inserdo entre as tags <select></select>
*/ */
$org_id = GetOrganizacao();
$query = "SELECT DISTINCT id, nome AS nome, 'Receptivo' AS tipo
FROM pbx_queues_grupos d
WHERE status = 'A'
AND org_id = $org_id
AND id IN(SELECT id_dac FROM pbx_classifica_dacs WHERE clas_id = $clasId)
ORDER BY 2";
$isAdm = (IsAdmin() && !$matricula);
$matricula = GetMatricula();
$query = "select distinct id, nome as nome, 'Receptivo' as tipo
from pbx_dacs d
where status = 'A'
and id in(select id_dac from pbx_classifica_dacs where clas_id = $clasId)
order by 2";
/*
if($isAdm)
{
}
else
{
$query = "select distinct d.id, d.nome, 'Receptivo' as tipo, 'false' as padrao
from pbx_usuarios a, pbx_grupo_usuario b, pbx_fila_grupos c, pbx_dacs d
where b.user_id = a.id
and c.gp_id = b.gp_id
and d.id = c.id
and lower(a.matricula) = lower('$matricula')
and d.id not in (select id_dac from pbx_classifica_dacs where clas_id = $clasId)
and d.status = 'A'
order by 1, 2 ";
} */
//echo $query;
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
$dacs = "<select name=\"dacsInc[]\" id=\"dacsInc\" size=\"6\" multiple=\"multiple\" style=\"width:250px;\" >"; $dacs = "<select name=\"dacsInc[]\" id=\"dacsInc\" size=\"6\" multiple=\"multiple\" style=\"width:250px;\" >";
while ($dados = pg_fetch_row($result)) { while ($dados = pg_fetch_row($result)) {
$dacs .= "<option value=\"$dados[0]\" $sel>$dados[1]</option>"; $dacs .= "<option value=\"$dados[0]\">$dados[1]</option>";
$cont++;
} }
$dacs .= "</select>"; $dacs .= "</select>";
return $dacs; return $dacs;
} }
?>

14
cadastros/classificaAtendimento/classificaDetIns.php

@ -1,17 +1,13 @@
<?php <?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$tpLayout = 1; $tpLayout = 1;
$clasMsg = "msgWarn"; $clasMsg = "msgWarn";
$desc = isset($_POST["clas_descricao"]) ? $_POST["clas_descricao"] : ""; $desc = isset($_POST["clas_descricao"]) ? $_POST["clas_descricao"] : "";
//$status = isset($_POST["btGravar"]) $_POST["btGravar"] ? "checked" : "" ? : "";
$clas_id = isset($_GET["clas_id"]) ? $_GET["clas_id"] : $_POST["clas_id"]; $clas_id = isset($_GET["clas_id"]) ? $_GET["clas_id"] : $_POST["clas_id"];
$acaoUser = "Incluir"; $acaoUser = "Incluir";
$descitem = isset($_GET["descitem"]) ? $_GET["descitem"] : $_POST["descitem"]; $descitem = isset($_GET["descitem"]) ? $_GET["descitem"] : $_POST["descitem"];
$msg = ''; $msg = '';
$org_id = GetOrganizacao();
if (isset($_POST["btGravar"])) { if (isset($_POST["btGravar"])) {
if (empty($desc)) { if (empty($desc)) {
@ -20,8 +16,8 @@ if (isset($_POST["btGravar"])) {
$jsStartup[] = "alert('$msg');"; $jsStartup[] = "alert('$msg');";
} else { } else {
$desc = mb_strtoupper(RemoveAcentos($desc)); $desc = mb_strtoupper(RemoveAcentos($desc));
$query = "insert into pbx_classifica_item(clas_id, clit_descricao, clit_status)values(%s, %s, %s)"; $query = "INSERT INTO pbx_classifica_item(clas_id, clit_descricao, clit_status, org_id) VALUES(%s, %s, %s, %s)";
$query = sprintf($query, $clas_id, QuotedStr($desc), '1'); $query = sprintf($query, $clas_id, QuotedStr($desc), '1', $org_id);
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
if ($result) { if ($result) {
$desc = ""; $desc = "";
@ -45,8 +41,4 @@ $smarty->assign("msg", $msg);
$smarty->assign("clas_id", $clas_id); $smarty->assign("clas_id", $clas_id);
$smarty->assign("descitem", $descitem); $smarty->assign("descitem", $descitem);
GetTemplate($smarty, 'cadastros/classificaAtendimento/classificaCad.tpl'); GetTemplate($smarty, 'cadastros/classificaAtendimento/classificaCad.tpl');
?>

7
cadastros/classificaAtendimento/classificaIns.php

@ -3,8 +3,8 @@
$tpLayout = 1; $tpLayout = 1;
$clasMsg = "msgWarn"; $clasMsg = "msgWarn";
$desc = isset($_POST["clas_descricao"]) ? $_POST["clas_descricao"] : ""; $desc = isset($_POST["clas_descricao"]) ? $_POST["clas_descricao"] : "";
//$status = isset($_POST["btGravar"]) $_POST["btGravar"] ? "checked" : "" ? : "";
$acaoUser = "Incluir"; $acaoUser = "Incluir";
$org_id = GetOrganizacao();
if (isset($_POST["btGravar"])) { if (isset($_POST["btGravar"])) {
if (empty($desc)) { if (empty($desc)) {
@ -13,8 +13,8 @@ if (isset($_POST["btGravar"])) {
$jsStartup[] = "alert('$msg');"; $jsStartup[] = "alert('$msg');";
} else { } else {
$desc = mb_strtoupper(RemoveAcentos($desc)); $desc = mb_strtoupper(RemoveAcentos($desc));
$query = "insert into pbx_classifica_atendimento(clas_descricao, clas_status)values(%s, %s)"; $query = "INSERT INTO pbx_classifica_atendimento(clas_descricao, clas_status, org_id) VALUES(%s, %s, %s)";
$query = sprintf($query, QuotedStr($desc), '1'); $query = sprintf($query, QuotedStr($desc), '1', $org_id);
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
if ($result) { if ($result) {
$desc = ""; $desc = "";
@ -37,4 +37,3 @@ $smarty->assign("msg", $msg);
GetTemplate($smarty, 'cadastros/classificaAtendimento/classificaCad.tpl'); GetTemplate($smarty, 'cadastros/classificaAtendimento/classificaCad.tpl');
?>

20
cadastros/motivosPausa/motivosPausaInsert.php

@ -25,6 +25,7 @@ $id = 0;
$flag = 0; $flag = 0;
$motivo = ""; $motivo = "";
$produtiva = 0; $produtiva = 0;
$org_id = GetOrganizacao();
/* /*
* Verifica se o usuario pressionou o botão para inserir * Verifica se o usuario pressionou o botão para inserir
@ -40,8 +41,7 @@ if ($formAction == FORM_NEW) {
$msgUser = sprintf("alert('O \"Motivo: %s\" já existe na base de dados!');", $_POST["motivo"]); $msgUser = sprintf("alert('O \"Motivo: %s\" já existe na base de dados!');", $_POST["motivo"]);
} else { } else {
//string para inserção do registro //string para inserção do registro
$query = "insert into pbx_motivos_pausas(motivo, flag, produtiva, tempo_alerta) $query = "INSERT INTO pbx_motivos_pausas(motivo, flag, produtiva, tempo_alerta, org_id) VALUES(%s, %s, %s, %s, %s)";
values(%s, %s, %s, %s)";
GetGpValues(); GetGpValues();
@ -50,13 +50,14 @@ if ($formAction == FORM_NEW) {
if ($result) { if ($result) {
//Prepara a query para inserir o registro no banco //Prepara a query para inserir o registro no banco
$query = sprintf($query, QuotedStr($motivo), QuotedStr($flag), QuotedStr($produtiva), QuotedStr($tempo_alerta)); $query = sprintf($query, QuotedStr($motivo), QuotedStr($flag), QuotedStr($produtiva), QuotedStr($tempo_alerta), $org_id);
//Executa a query no banco //Executa a query no banco
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
if ($result) if ($result) {
$result = pg_query($dbcon, "commit"); $result = pg_query($dbcon, "commit");
}
} }
if ($result) { if ($result) {
$acaoUser = 'Incluir'; $acaoUser = 'Incluir';
@ -74,8 +75,9 @@ if ($formAction == FORM_NEW) {
} }
} }
if (!empty($msgUser)) if (!empty($msgUser)) {
$jsStartup[] = $msgUser; $jsStartup[] = $msgUser;
}
$smarty->assign("id", $id); $smarty->assign("id", $id);
$smarty->assign("motivo", $motivo); $smarty->assign("motivo", $motivo);
@ -88,7 +90,8 @@ $smarty->assign("erro", $msgErro);
GetTemplate($smarty, 'cadastros/motivosPausa/motivosPausaCadastro.tpl'); GetTemplate($smarty, 'cadastros/motivosPausa/motivosPausaCadastro.tpl');
function LimpaGpVar() { function LimpaGpVar()
{
$GLOBALS["motivo"] = ""; $GLOBALS["motivo"] = "";
$GLOBALS["flag"] = 1; $GLOBALS["flag"] = 1;
$GLOBALS["id"] = 0; $GLOBALS["id"] = 0;
@ -96,12 +99,11 @@ function LimpaGpVar() {
$GLOBALS["tempo_alerta"] = 0; $GLOBALS["tempo_alerta"] = 0;
} }
function GetGpValues() { function GetGpValues()
{
$GLOBALS["id"] = $_POST["id"]; $GLOBALS["id"] = $_POST["id"];
$GLOBALS["motivo"] = mb_strtoupper(RemoveAcentos($_POST["motivo"])); $GLOBALS["motivo"] = mb_strtoupper(RemoveAcentos($_POST["motivo"]));
$GLOBALS["flag"] = $_POST["flag"] ? 1 : 0; $GLOBALS["flag"] = $_POST["flag"] ? 1 : 0;
$GLOBALS["produtiva"] = $_POST["produtiva"]; $GLOBALS["produtiva"] = $_POST["produtiva"];
$GLOBALS["tempo_alerta"] = $_POST["tempo_alerta"] * 60; $GLOBALS["tempo_alerta"] = $_POST["tempo_alerta"] * 60;
} }
?>

21
cadastros/motivosPausa/motivosPausaSelect.php

@ -32,10 +32,14 @@ if (isset($_REQUEST['paramPesquisa']) && $_REQUEST['paramPesquisa']) {
$compl = sprintf("and (a.motivo ilike %s )", $compl); $compl = sprintf("and (a.motivo ilike %s )", $compl);
} }
$query = "select id, motivo, flag, produtiva,tempo_alerta from pbx_motivos_pausas a \n"; $query = "SELECT id, motivo, flag, produtiva,tempo_alerta
$query .= "where 1=1 and upper(motivo) not in('AUSENTE', 'LOGIN', 'RECUSADA') $compl"; FROM pbx_motivos_pausas
$query .= " and flag = '$active' "; WHERE 1=1
$query .= " order by motivo"; AND upper(motivo)
NOT IN('AUSENTE', 'LOGIN', 'RECUSADA')
$compl
AND flag = '$active'
ORDER BY motivo";
$params = "&paramPesquisa=$filtro"; $params = "&paramPesquisa=$filtro";
$links = PaginaDados($idProg, $query, $params, $regPagina, $offSet, $pagMostra, true); $links = PaginaDados($idProg, $query, $params, $regPagina, $offSet, $pagMostra, true);
@ -57,12 +61,12 @@ while (($result) && ($dados = @pg_fetch_array($result))) {
$imgEdit = GetLinkFormUpdate("&id=$id", "updMotivosPausa"); $imgEdit = GetLinkFormUpdate("&id=$id", "updMotivosPausa");
$status = $dados["flag"] ? $imgYes : $imgNo; $status = $dados["flag"] ? $imgYes : $imgNo;
if($dados["flag"] == 0){ if ($dados["flag"] == 0) {
$delete = "<a href=\"javaScript:DeltetaMotivoPausa('$id', '&paramPesquisa=&pgn=0&bloco=0&pg=0');\"><img src='imgSite/Sync.png' width='16' height='16' border='0' title='Ative este registro!'></a>"; $delete = "<a href=\"javaScript:DeltetaMotivoPausa('$id', '&paramPesquisa=&pgn=0&bloco=0&pg=0');\"><img src='imgSite/Sync.png' width='16' height='16' border='0' title='Ative este registro!'></a>";
} else { } else {
$delete = GetLinkFormDelete($id . '|' . $params, 'DeltetaMotivoPausa'); $delete = GetLinkFormDelete($id . '|' . $params, 'DeltetaMotivoPausa');
} }
SetDimensoes(610, 275); SetDimensoes(610, 275);
$pausaGrupo = "<a style=\"color: #000;\" href=\"javaScript:NovaJanela('index.php?idProg=130&id=$id', 'pausasGrupos', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\"> $imgPausaGrupo</a>"; $pausaGrupo = "<a style=\"color: #000;\" href=\"javaScript:NovaJanela('index.php?idProg=130&id=$id', 'pausasGrupos', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\"> $imgPausaGrupo</a>";
$pausaGrupo = UsePausaGrupo() ? "<td width=\"20\" align=\"center\">$pausaGrupo</td>" : ""; $pausaGrupo = UsePausaGrupo() ? "<td width=\"20\" align=\"center\">$pausaGrupo</td>" : "";
@ -109,8 +113,7 @@ GetTemplate($smarty, $tpl);
* Apresenta uma informação ao usuário ou um mensagem de erro * Apresenta uma informação ao usuário ou um mensagem de erro
*/ */
function GetLinhaInfo($mensagem, $colspan) { function GetLinhaInfo($mensagem, $colspan)
{
return " <tr><td colspan=\"$colspan\" align=\"center\">$mensagem</td></tr>"; return " <tr><td colspan=\"$colspan\" align=\"center\">$mensagem</td></tr>";
} }
?>

20
contacteFunc.php

@ -84,7 +84,8 @@ function GetDac($dbcon, $codDac, $disableb = "", $incTodos = 0, $soAtivo = 1, $i
function GetDacs($dbcon, $codDac, $disableb = "", $incTodos = 1, $soAtivo = 1) function GetDacs($dbcon, $codDac, $disableb = "", $incTodos = 1, $soAtivo = 1)
{ {
$query = "select distinct id, nome as nome from pbx_dacs d where 1=1 " . ($soAtivo ? " and status = 'A' " : "") . " order by 2"; $org_id = GetOrganizacao();
$query = "SELECT DISTINCT id, nome as nome FROM pbx_queues_grupos WHERE org_id = $org_id " . ($soAtivo ? " AND status = 'A' " : "") . " ORDER BY 2";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
$codSel = $codDac; $codSel = $codDac;
@ -2387,25 +2388,21 @@ function GetCampanhas($dbcon, $codDac = -1, $matricula = 0, $dataIni = '', $data
$dacs = "<select name=\"listaDacs\" id=\"listaDacs\" $mult size=\"$size\" $disableb style=\"width:300px;\">"; //onchange=\"GetCampanhaLista();\" $dacs = "<select name=\"listaDacs\" id=\"listaDacs\" $mult size=\"$size\" $disableb style=\"width:300px;\">"; //onchange=\"GetCampanhaLista();\"
$dacs .= "<option value=\"0\" $sel>--------------------</option>"; $dacs .= "<option value=\"0\" $sel>--------------------</option>";
$cont = 0; $cont = 0;
$i = 0;
while ($dados = pg_fetch_array($result)) { while ($dados = pg_fetch_array($result)) {
if ($codSel == $dados[0]) { if ($codSel == $dados[0]) {
$sel = "selected"; $sel = "selected";
$i = 1;
} else { } else {
$sel = ""; $sel = "";
} }
$dacs .= "<option value=\"$dados[0]-$dados[2]\" $sel>$dados[1]</option>"; $dacs .= "<option value=\"$dados[0]-$dados[2]\" $sel>$dados[1]</option>";
$cont++; $cont++;
} }
// if((!$cont || !$i))$dacs .= "<option value=\"\" selected>-------------------</option>";
$dacs .= "</select>"; $dacs .= "</select>";
return $dacs; return $dacs;
} }
function _VerificaNomeTronco($db, $nome) function _VerificaNomeTronco($db, $nome)
{ {
$sql = "select '' from pbx_troncos where upper(nome) = upper('$nome')"; $sql = "select '' from pbx_troncos where upper(nome) = upper('$nome')";
$result = pg_query($db, $sql); $result = pg_query($db, $sql);
if (pg_num_rows($result)) { if (pg_num_rows($result)) {
@ -2418,21 +2415,14 @@ function _VerificaNomeTronco($db, $nome)
if (pg_num_rows($result)) { if (pg_num_rows($result)) {
return "Este \"Nome\" já esta associado a um \"Ramal\"!"; return "Este \"Nome\" já esta associado a um \"Ramal\"!";
} }
return false; return false;
} }
function base64ToFile($base64) function base64ToFile($base64)
{ {
$file = tempnam(sys_get_temp_dir(), time()); $file = tempnam(sys_get_temp_dir(), time());
// open the output file for writing
$ifp = fopen($file, 'wb'); $ifp = fopen($file, 'wb');
// we could add validation here with ensuring count( $data ) > 1
fwrite($ifp, base64_decode($base64)); fwrite($ifp, base64_decode($base64));
// clean up the file resource
fclose($ifp); fclose($ifp);
return $file; return $file;
@ -2444,7 +2434,11 @@ function base64ToFile($base64)
function GetNotExistsDacUser($dacPadraoSel, $idUser) function GetNotExistsDacUser($dacPadraoSel, $idUser)
{ {
$query = sprintf("select '' from pbx_fila_grupos where id = %s and gp_id in(select gp_id from pbx_grupo_usuario where user_id = %s);", QuotedStr($dacPadraoSel), QuotedStr($idUser)); $query = sprintf(
"SELECT '' FROM pbx_fila_grupos WHERE id = %s AND gp_id IN(SELECT gp_id FROM pbx_grupo_usuario WHERE user_id = %s);",
QuotedStr($dacPadraoSel),
QuotedStr($idUser)
);
$result = pg_query($query); $result = pg_query($query);
return pg_num_rows($result) ? true : false; return pg_num_rows($result) ? true : false;
} }

13
include/util/funcoesApl.php

@ -3024,7 +3024,16 @@ function RegistroInc($db, $query)
function ExisteRegistro($db, $table, $where, $id, $queryParam = null) function ExisteRegistro($db, $table, $where, $id, $queryParam = null)
{ {
$query = "select count(*) from $table where $where = '$id' "; $org_id = GetOrganizacao();
$compl = "";
$join = "";
if ($table == 'pbx_usuarios') {
$join = "a INNER JOIN pbx_organizacao_usuarios b ON b.id_usuario = a.id ";
$compl = " 1=1 AND id_organizacao = $org_id AND ";
}
$query = "SELECT count(*) FROM $table $join WHERE $compl $where = '$id' ";
echo $query;
if ($queryParam) { if ($queryParam) {
$query .= " and {$queryParam} "; $query .= " and {$queryParam} ";
@ -4077,7 +4086,7 @@ function PaginaDados($idProg, &$sql, &$params, &$regPagina, &$offSet, &$pagMostr
*/ */
$org_id = GetOrganizacao(); $org_id = GetOrganizacao();
if (strpos($sql, 'org_id') === false) { if (strpos($sql, 'org_id') === false && strpos($sql, 'id_organizacao') === false) {
if (strpos($sql, 'where') !== false) { if (strpos($sql, 'where') !== false) {
$sql = str_replace("where", "where org_id = {$org_id} and", $sql); $sql = str_replace("where", "where org_id = {$org_id} and", $sql);
} else if (strpos($sql, 'WHERE') !== false) { } else if (strpos($sql, 'WHERE') !== false) {

6
projeto/base/sql/versao-1.9.0.sql

@ -54,3 +54,9 @@ ALTER TABLE pbx_facilidades ADD COLUMN id SERIAL PRIMARY KEY;
ALTER TABLE pbx_features_general ADD COLUMN id SERIAL PRIMARY KEY; ALTER TABLE pbx_features_general ADD COLUMN id SERIAL PRIMARY KEY;
ALTER TABLE pbx_features_featuremap ADD COLUMN id SERIAL PRIMARY KEY; ALTER TABLE pbx_features_featuremap ADD COLUMN id SERIAL PRIMARY KEY;
ALTER TABLE pbx_voicemail_general ADD COLUMN id SERIAL PRIMARY KEY; ALTER TABLE pbx_voicemail_general ADD COLUMN id SERIAL PRIMARY KEY;
ALTER TABLE pbx_usuarios DROP CONSTRAINT pbx_usuarios_new_matricula_key;
DROP INDEX "pbx_usuarios_matricula_key";
DROP INDEX "idxUsuariosApelido";
ALTER TABLE pbx_grupo DROP CONSTRAINT "idxGrupNome";
DROP INDEX "idxGrupNome";
ALTER TABLE pbx_grupo_usuario DROP CONSTRAINT "pkGpUserId";

24
seguranca/grupos/grupoInsert.php

@ -11,6 +11,7 @@ $msgErro = "";
$setFocus = "document.getElementById('gp_nome').focus();"; $setFocus = "document.getElementById('gp_nome').focus();";
$jsStartup[] = $setFocus; $jsStartup[] = $setFocus;
$org_id = GetOrganizacao();
/* /*
* Verifica se o usuario pressionou o botão para inserir * Verifica se o usuario pressionou o botão para inserir
@ -24,8 +25,7 @@ if ($formAction == FORM_NEW) {
$msgUser = "alert('O nome do grupo é campo de preenchimento obrigatório!');"; $msgUser = "alert('O nome do grupo é campo de preenchimento obrigatório!');";
} else { } else {
//string para inserção do registro //string para inserção do registro
$query = "insert into pbx_grupo(gp_nome, gp_status, gp_user, gp_system) $query = "INSERT INTO pbx_grupo(gp_nome, gp_status, gp_user, gp_system, org_id) VALUES(%s, %s, %s, '0', $org_id)";
values(%s, %s, %s, '0')";
GetGpValues(); GetGpValues();
@ -41,26 +41,26 @@ if ($formAction == FORM_NEW) {
if (!IsAdmin() && $result) { if (!IsAdmin() && $result) {
//Insere o grupo para o criador e seus antecessores na ordem inversa de criação //Insere o grupo para o criador e seus antecessores na ordem inversa de criação
$query = "select max(gp_id) from pbx_grupo"; $query = "SELECT max(gp_id) FROM pbx_grupo WHERE org_id = $org_id";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
$row = @pg_fetch_row($result); $row = @pg_fetch_row($result);
$idGrupo = $row[0]; $idGrupo = $row[0];
$idUser = GetIdUser(); $idUser = GetIdUser();
/* /*
* Usuario administrador não é inserido no grupo. * Usuario administrador não é inserido no grupo.
*/ */
if ($result && !IsUserAdmin()) { if ($result && !IsUserAdmin()) {
$query = " insert into pbx_grupo_usuario(user_id, gp_id)values(%s, %s)"; $query = " INSERT INTO pbx_grupo_usuario(user_id, gp_id, org_id)values(%s, %s, %s)";
$query = sprintf($query, $idUser, $idGrupo); $query = sprintf($query, $idUser, $idGrupo, $org_id);
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
} }
if ($result) { if ($result) {
$query = " insert into pbx_grupo_usuario(user_id, gp_id)values(%s, %s)"; $query = "INSERT INTO pbx_grupo_usuario(user_id, gp_id, org_id)values(%s, %s, %s)";
$idUser = GetIdSysAdmin($dbcon); $idUser = GetIdSysAdmin($dbcon);
$query = sprintf($query, $idUser, $idGrupo); $query = sprintf($query, $idUser, $idGrupo, $org_id);
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
} }
} }
@ -97,16 +97,16 @@ $smarty->assign("erro", $msgErro);
GetTemplate($smarty, 'seguranca/grupos/gruposCadastro.tpl'); GetTemplate($smarty, 'seguranca/grupos/gruposCadastro.tpl');
function LimpaGpVar() { function LimpaGpVar()
{
$GLOBALS["gp_nome"] = ""; $GLOBALS["gp_nome"] = "";
$GLOBALS["gp_status"] = 1; $GLOBALS["gp_status"] = 1;
$GLOBALS["gp_id"] = 0; $GLOBALS["gp_id"] = 0;
} }
function GetGpValues() { function GetGpValues()
{
$GLOBALS["gp_nome"] = mb_strtoupper(RemoveAcentos($_POST["gp_nome"])); $GLOBALS["gp_nome"] = mb_strtoupper(RemoveAcentos($_POST["gp_nome"]));
$GLOBALS["gp_status"] = $_POST["gp_status"]; $GLOBALS["gp_status"] = $_POST["gp_status"];
$GLOBALS["gp_id"] = $_POST["gp_id"]; $GLOBALS["gp_id"] = $_POST["gp_id"];
} }
?>

19
seguranca/grupos/grupoSelect.php

@ -24,7 +24,7 @@ $paramPesquisa = isset($_REQUEST['paramPesquisa']) ? $_REQUEST['paramPesquisa']
$filtro = isset($_REQUEST["paramPesquisa"]) ? trim($_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"]); $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']); $recontaPag = ($acao == 'inseri') || (GetFormAcao() == FORM_DELETE) || isset($_POST['pesquisa']);
$org_id = GetOrganizacao();
/* /*
* Se o usuario nao for admimistrador carrega apenas * Se o usuario nao for admimistrador carrega apenas
* os grupos ao qual o mesmo pertence * os grupos ao qual o mesmo pertence
@ -66,8 +66,10 @@ if (isset($_REQUEST['paramPesquisa']) && $_REQUEST['paramPesquisa']) {
$compl = sprintf("and (a.gp_nome ilike %s)", $compl); $compl = sprintf("and (a.gp_nome ilike %s)", $compl);
} }
$query = "select gp_id, gp_nome, gp_status, user_id, 0 as gp_lgpd, case when(user_id = 0)then 0 else 1 end as ord from pbx_grupo a\n"; $compl .= "AND org_id = $org_id ";
$query .= "where a.gp_system = '0' $compl $gpCompl $restringLgpd $liberaLgpd $permissoesAdmin order by 5, gp_nome";
$query = "SELECT gp_id, gp_nome, gp_status, user_id, 0 as gp_lgpd, case when(user_id = 0)then 0 else 1 end as ord FROM pbx_grupo a\n";
$query .= "WHERE a.gp_system = '0' $compl $gpCompl $restringLgpd $liberaLgpd $permissoesAdmin order by 5, gp_nome";
$params = "&paramPesquisa=$filtro"; $params = "&paramPesquisa=$filtro";
$links = PaginaDados($idProg, $query, $params, $regPagina, $offSet, $pagMostra, true); $links = PaginaDados($idProg, $query, $params, $regPagina, $offSet, $pagMostra, true);
@ -149,13 +151,16 @@ GetTemplate($smarty, $tpl);
* Apresenta uma informação ao usuário ou um mensagem de erro * Apresenta uma informação ao usuário ou um mensagem de erro
*/ */
function GetLinhaInfo($mensagem, $colspan) { function GetLinhaInfo($mensagem, $colspan)
{
return " <tr><td colspan=\"$colspan\" align=\"center\">$mensagem</td></tr>"; return " <tr><td colspan=\"$colspan\" align=\"center\">$mensagem</td></tr>";
} }
function GetCampanhaPrevenda($grupo, $userGrupo) { function GetCampanhaPrevenda($grupo, $userGrupo)
{
global $dbcon;
$query = "SELECT * FROM pbx_grupo_funcoes WHERE fun_id = 209 AND gp_id = {$grupo}"; $query = "SELECT * FROM pbx_grupo_funcoes WHERE fun_id = 209 AND gp_id = {$grupo}";
$result = pg_query($query); $result = pg_query($dbcon, $query);
$linkGrupo = "<a href=\"javaScript:NovaJanela('index.php?idProg=342&gp_id=%s&gp_nome=%s', 'jnCampanhaVenda', '550', '280', 'resizable=NO,scrollbars=NO');\">%s</a>"; $linkGrupo = "<a href=\"javaScript:NovaJanela('index.php?idProg=342&gp_id=%s&gp_nome=%s', 'jnCampanhaVenda', '550', '280', 'resizable=NO,scrollbars=NO');\">%s</a>";
$img = "<img src=\"imgSite/%s\" width=\"16\" height=\"16\" border=\"0\" title=\"Status da Campanha Pré-venda!\"/>"; $img = "<img src=\"imgSite/%s\" width=\"16\" height=\"16\" border=\"0\" title=\"Status da Campanha Pré-venda!\"/>";
@ -171,5 +176,3 @@ function GetCampanhaPrevenda($grupo, $userGrupo) {
return $link; return $link;
} }
?>

19
seguranca/grupos/gruposAudiosRamais.php

@ -5,7 +5,7 @@ $templateName = 'seguranca/grupos/gruposAudioRamal.htm';
//define tipo de formulario //define tipo de formulario
$tpLayout = 1; $tpLayout = 1;
$upload = 1; $upload = 1;
$org_id = GetOrganizacao();
$fieldsForm = array(); $fieldsForm = array();
$fieldsForm = IsPostBack() ? $_POST : $_GET; $fieldsForm = IsPostBack() ? $_POST : $_GET;
@ -27,8 +27,8 @@ if (isset($fieldsForm['btInclui'])) {
if ($result) { if ($result) {
$cont = 0; $cont = 0;
foreach ($fieldsForm['listaRamaisDisponiveis'] as $ramal) { foreach ($fieldsForm['listaRamaisDisponiveis'] as $ramal) {
$query = "insert into pbx_grupo_audio_ramal(nome, gp_id)values('%s', '%s')"; $query = "INSERT INTO pbx_grupo_audio_ramal(nome, gp_id, org_id)values('%s', '%s', %s)";
$query = sprintf($query, $ramal, $fieldsForm['gp_id']); $query = sprintf($query, $ramal, $fieldsForm['gp_id'], $org_id);
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
if (!$result) if (!$result)
break; break;
@ -97,16 +97,19 @@ foreach ($fieldsForm as $key => $value) {
GetTemplate($smarty, $templateName); GetTemplate($smarty, $templateName);
function GetRamaisDisponiveis($dbcon, $codGp, $codSel, $size = 1, $tamPx = "200", $desabilita = 0, $multiple = 0) { function GetRamaisDisponiveis($dbcon, $codGp, $codSel, $size = 1, $tamPx = "200", $desabilita = 0, $multiple = 0) {
$org_id = GetOrganizacao();
if (strpos($codGp, '|') !== false) { if (strpos($codGp, '|') !== false) {
$codG = explode('|', $codGp); $codG = explode('|', $codGp);
$codGp = $codG[0]; $codGp = $codG[0];
} }
$nomeLista = 'listaRamaisDisponiveis'; $nomeLista = 'listaRamaisDisponiveis';
$query = "select nome, (coalesce(callerid, nome) || case when(callerid = nome)then '' else ( ' [ ' || nome || ' ]') end) as nome_ramal $query = "SELECT nome, (coalesce(callerid, nome) || case when(callerid = nome)then '' else ( ' [ ' || nome || ' ]') end) as nome_ramal
from pbx_ramais_mesa a FROM pbx_ramais_mesa a
where tipo = 0 WHERE tipo = 0
and not exists(select '' from pbx_grupo_audio_ramal where nome = a.nome and gp_id = '$codGp')"; AND org_id = $org_id
AND not exists(select '' from pbx_grupo_audio_ramal where nome = a.nome and gp_id = '$codGp')";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
$cont = 0; $cont = 0;
@ -158,5 +161,3 @@ function GetRamaisIncluidos($dbcon, $codGp, $codSel, $size = 1, $tamPx = "200",
$lista .= "</select>\n"; $lista .= "</select>\n";
return $lista; return $lista;
} }
?>

81
seguranca/grupos/gruposUsuario.php

@ -2,10 +2,9 @@
require('funcoesFormulario.php'); require('funcoesFormulario.php');
$templateName = 'seguranca/grupos/gruposUsuario.htm'; $templateName = 'seguranca/grupos/gruposUsuario.htm';
//define tipo de formulario
$tpLayout = 1; $tpLayout = 1;
$upload = 1; $upload = 1;
$org_id = GetOrganizacao();
$fieldsForm = array(); $fieldsForm = array();
$fieldsForm = IsPostBack() ? $_POST : $_GET; $fieldsForm = IsPostBack() ? $_POST : $_GET;
@ -16,7 +15,6 @@ if (isset($fieldsForm['gp_id']) && (strpos($fieldsForm['gp_id'], '|') !== false)
$isLgpd = $fieldsForm["gp_lgpd"]; $isLgpd = $fieldsForm["gp_lgpd"];
//Id da campanha
$idCampanha = $fieldsForm['cmp_id']; $idCampanha = $fieldsForm['cmp_id'];
$fieldsForm['erro'] = ""; $fieldsForm['erro'] = "";
@ -27,7 +25,7 @@ if (isset($fieldsForm['btIncAgente'])) {
try { try {
$result = pg_query($dbcon, 'begin'); $result = pg_query($dbcon, 'begin');
$query = sprintf('select count(*) from pbx_grupo_usuario a, pbx_grupo b where b.gp_id = a.gp_id and b.user_id > 0 and b.gp_id = %s', $fieldsForm['gp_id']); $query = sprintf('SELECT count(*) FROM pbx_grupo_usuario a, pbx_grupo b WHERE b.gp_id = a.gp_id AND b.user_id > 0 AND b.gp_id = %s', $fieldsForm['gp_id']);
if (RegistroInc($dbcon, $query)) { if (RegistroInc($dbcon, $query)) {
throw new Exception('Operação inválida, "Usuários" só podem ser vinculados a "Grupos"!'); throw new Exception('Operação inválida, "Usuários" só podem ser vinculados a "Grupos"!');
} }
@ -41,11 +39,12 @@ if (isset($fieldsForm['btIncAgente'])) {
if ($isLgpd && ($jaLgpd = JaInseridoLgps($idUser))) { if ($isLgpd && ($jaLgpd = JaInseridoLgps($idUser))) {
throw new Exception($jaLgpd); throw new Exception($jaLgpd);
} }
$query = "insert into pbx_grupo_usuario(user_id, gp_id)values(%s, '%s')"; $query = "INSERT INTO pbx_grupo_usuario(user_id, gp_id, org_id) VALUES(%s, '%s', $org_id)";
$query = sprintf($query, $idUser, $fieldsForm['gp_id']); $query = sprintf($query, $idUser, $fieldsForm['gp_id']);
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
if (!$result) if (!$result) {
break; break;
}
$cont++; $cont++;
} }
} }
@ -67,20 +66,17 @@ if (isset($fieldsForm['btIncAgente'])) {
$fieldsForm['erro'] = fmtMsg('Selecione um agente!'); $fieldsForm['erro'] = fmtMsg('Selecione um agente!');
} else { } else {
try { try {
$result = pg_query($dbcon, 'begin'); $result = pg_query($dbcon, 'begin');
if ($result) { if ($result) {
$userAdmin = IsAdmin() || IsUserAdmin() ? 1 : 0; $userAdmin = IsAdmin() || IsUserAdmin() ? 1 : 0;
$cont = 0; $cont = 0;
foreach ($fieldsForm['user_inc'] as $idUser) { foreach ($fieldsForm['user_inc'] as $idUser) {
$query = "delete from pbx_grupo_usuario" $query = "DELETE from pbx_grupo_usuario
. "\nwhere user_id = '%s'" WHERE user_id = '%s'
. "\nand gp_id = '%s'" AND gp_id = '%s'
. "\nand user_id <> (select id from pbx_usuarios where apelido = 'administrador')" // Não permite remover o administrador. AND user_id <> (SELECT id FROM pbx_usuarios WHERE apelido = 'administrador')
. "and not exists(select '' from pbx_grupo where gp_id = '%s' and gp_user = case when(%s=0)then '%s' else -1 end)\n"; //Nao permite o usuario remover o pai do grupo(quem criou). AND not exists(select '' from pbx_grupo WHERE gp_id = '%s' AND gp_user = CASE WHEN(%s=0)THEN '%s' ELSE -1 END)"; //Nao permite o usuario remover o pai do grupo(quem criou).
$query = sprintf($query, $idUser, $fieldsForm['gp_id'], $fieldsForm['gp_id'], $userAdmin, $idUser); $query = sprintf($query, $idUser, $fieldsForm['gp_id'], $fieldsForm['gp_id'], $userAdmin, $idUser);
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
if (!$result) if (!$result)
break; break;
@ -89,7 +85,6 @@ if (isset($fieldsForm['btIncAgente'])) {
} }
$result = $result && pg_query($dbcon, 'commit'); $result = $result && pg_query($dbcon, 'commit');
if (!$result) { if (!$result) {
throw new Exception('A operação não pode ser realizada!'); throw new Exception('A operação não pode ser realizada!');
} }
@ -102,7 +97,6 @@ if (isset($fieldsForm['btIncAgente'])) {
} }
} }
$fieldsForm['user_id'] = GetUser($dbcon, $fieldsForm['gp_id'], $fieldsForm['user_id'], 8, "user_id", "240", 0, 1); $fieldsForm['user_id'] = GetUser($dbcon, $fieldsForm['gp_id'], $fieldsForm['user_id'], 8, "user_id", "240", 0, 1);
$fieldsForm['listaGrupo'] = GetGrupoUser($dbcon, $fieldsForm['gp_id'], 0, 8, "user_inc", "240", 0, 1); $fieldsForm['listaGrupo'] = GetGrupoUser($dbcon, $fieldsForm['gp_id'], 0, 8, "user_inc", "240", 0, 1);
@ -114,20 +108,19 @@ foreach ($fieldsForm as $key => $value) {
} }
GetTemplate($smarty, $templateName); GetTemplate($smarty, $templateName);
function GetGrupoUser($dbcon, $codGp, $codSel, $size = 1, $nomeLista = "user_id", $tamPx = "200", $desabilita = 0, $multiple = 0)
function GetGrupoUser($dbcon, $codGp, $codSel, $size = 1, $nomeLista = "user_id", $tamPx = "200", $desabilita = 0, $multiple = 0) { {
if (strpos($codGp, '|') !== false) { if (strpos($codGp, '|') !== false) {
$codG = explode('|', $codGp); $codG = explode('|', $codGp);
$codGp = $codG[0]; $codGp = $codG[0];
} }
$query = "select b.id, b.nome || (case when( (select count(*) from pbx_grupo where gp_id = a.gp_id and gp_user = a.user_id) > 0)then '*' else '' end) as apelido, b.matricula, a.gp_id from pbx_grupo_usuario a, pbx_usuarios b where b.id = a.user_id and a.gp_id = $codGp order by 2"; $query = "SELECT b.id, b.nome || (CASE WHEN( (SELECT count(*) FROM pbx_grupo WHERE gp_id = a.gp_id AND gp_user = a.user_id) > 0)THEN '*' ELSE '' END) AS apelido, b.matricula, a.gp_id FROM pbx_grupo_usuario a, pbx_usuarios b WHERE b.id = a.user_id AND a.gp_id = $codGp ORDER BY 2";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
$cont = 0; $cont = 0;
$sel = ""; $sel = "";
$lista = '<select name="%s%s" id="%s" size="%s" style="width:%spx;" %s>%s'; $lista = '<select name="%s%s" id="%s" size="%s" style="width:%spx;" %s>%s';
$lista = sprintf($lista, $nomeLista, ($multiple ? "[]" : ""), $nomeLista, $size, $tamPx, ($multiple ? 'multiple="multiple"' : ''), "\n"); $lista = sprintf($lista, $nomeLista, ($multiple ? "[]" : ""), $nomeLista, $size, $tamPx, ($multiple ? 'multiple="multiple"' : ''), "\n");
while (($row = @pg_fetch_array($result))) { while (($row = @pg_fetch_array($result))) {
@ -142,21 +135,26 @@ function GetGrupoUser($dbcon, $codGp, $codSel, $size = 1, $nomeLista = "user_id"
return $lista; return $lista;
} }
function GetUser($dbcon, $codGrupo, $codSel, $size = 1, $nomeLista = "user_id", $tamPx = "200", $desabilita = 0, $multiple = 0) { function GetUser($dbcon, $codGrupo, $codSel, $size = 1, $nomeLista = "user_id", $tamPx = "200", $desabilita = 0, $multiple = 0)
{
$sel = ""; $sel = "";
$org_id = GetOrganizacao();
if (strpos($codGrupo, '|') !== false) { if (strpos($codGrupo, '|') !== false) {
$codG = explode('|', $codGrupo); $codG = explode('|', $codGrupo);
$codGrupo = $codG[0]; $codGrupo = $codG[0];
} }
$query = "select id, nome, apelido, matricula $query = "SELECT a.id, nome, apelido, matricula
from pbx_usuarios FROM pbx_usuarios a
where status = true INNER JOIN pbx_organizacao_usuarios b ON b.id_usuario = a.id
and delete_ = 0 WHERE status = true
and id not in(select user_id from pbx_grupo_usuario where gp_id = '$codGrupo') AND delete_ = 0
and upper(apelido) <> 'ADMIN' AND a.id NOT IN(SELECT user_id FROM pbx_grupo_usuario WHERE gp_id = '$codGrupo')
and upper(apelido) <> 'SINCCONTASENHA' AND upper(apelido) <> 'ADMIN'
order by 2 "; AND upper(apelido) <> 'SINCCONTASENHA'
AND b.id_organizacao = $org_id
ORDER BY 2 ";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
$lista = '<select name="%s%s" id="%s" size="%s" style="width:%spx" %s >%s'; $lista = '<select name="%s%s" id="%s" size="%s" style="width:%spx" %s >%s';
@ -166,24 +164,25 @@ function GetUser($dbcon, $codGrupo, $codSel, $size = 1, $nomeLista = "user_id",
$cod = $row["id"]; $cod = $row["id"];
$desc = $row["nome"] . "-" . $row["matricula"]; $desc = $row["nome"] . "-" . $row["matricula"];
$sel = ($codSel == $cod) ? "selected" : ""; $sel = ($codSel == $cod) ? "selected" : "";
$lista .= "<option value=\"$cod\" $sel>$desc</option>\n"; $lista .= "<option value=\"$cod\" $sel>$desc</option>\n";
$cont++;
} }
$lista .= "</select>\n"; $lista .= "</select>\n";
return $lista; return $lista;
} }
function JaInseridoLgps($userId) { function JaInseridoLgps($userId)
{
global $dbcon;
$org_id = GetOrganizacao();
$query = "SELECT c.id, c.matricula, c.nome, b.gp_id, b.gp_nome
FROM pbx_grupo_usuario a
INNER JOIN pbx_grupo b ON b.gp_id = a.gp_id
INNER JOIN pbx_usuarios c ON c.id = a.user_id
WHERE b.gp_nome ilike 'LGPD_%_%_%'
AND a.user_id = '{$userId}'
AND org_id = $org_id;";
$query = "select c.id, c.matricula, c.nome, b.gp_id, b.gp_nome $result = pg_query($dbcon, $query);
from pbx_grupo_usuario a, pbx_grupo b, pbx_usuarios c
where b.gp_id = a.gp_id
and c.id = a.user_id
and b.gp_nome ilike 'LGPD_%_%_%'
and a.user_id = '{$userId}';";
$result = pg_query($query);
if (!pg_num_rows($result)) { if (!pg_num_rows($result)) {
return false; return false;
@ -192,5 +191,3 @@ function JaInseridoLgps($userId) {
$row = pg_fetch_array($result); $row = pg_fetch_array($result);
return sprintf("O usuário: %s-%s já esta incluido no grupo %s da LGDP!", $row["matricula"], $row["nome"], $row["gp_nome"]); return sprintf("O usuário: %s-%s já esta incluido no grupo %s da LGDP!", $row["matricula"], $row["nome"], $row["gp_nome"]);
} }
?>

41
seguranca/licencaUsuarioFixo.php

@ -35,11 +35,11 @@ foreach ($fieldsForm as $key => $value) {
GetTemplate($smarty, $templateName); GetTemplate($smarty, $templateName);
function AtualizaLicenca($dbcon, $field, $status) { function AtualizaLicenca($dbcon, $field, $status)
{
try { try {
if (!$field) { if (!$field) {
//fmtMsg('Selecione um usuário!');
throw new Exception('Selecione um usuário'); throw new Exception('Selecione um usuário');
} }
@ -54,11 +54,11 @@ function AtualizaLicenca($dbcon, $field, $status) {
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
if ($result && pg_num_rows($result) > 0) { if ($result && pg_num_rows($result) > 0) {
$result = pg_fetch_assoc($result); $result = pg_fetch_assoc($result);
$limitUpdate = strtotime($result['limit_update']); $limitUpdate = strtotime($result['limit_update']);
$freeUpadate = strtotime($result['last_update'] . '+24 hours'); $freeUpadate = strtotime($result['last_update'] . '+24 hours');
$currentTime = strtotime($result['current_time']); $currentTime = strtotime($result['current_time']);
if ($currentTime > $limitUpdate && $currentTime < $freeUpadate) { if ($currentTime > $limitUpdate && $currentTime < $freeUpadate) {
throw new Exception('Não é possível realizar a alteração neste momento, tente novamente mais tarde!'); throw new Exception('Não é possível realizar a alteração neste momento, tente novamente mais tarde!');
} }
@ -77,7 +77,7 @@ function AtualizaLicenca($dbcon, $field, $status) {
$query = sprintf("UPDATE pbx_licenca_pa_fixo SET id_user = %s, last_update = NOW(), limit_update = NOW() + INTERVAL '5 MINUTE' ", $status == 1 ? "'" . $idUser . "'" : 'NULL'); $query = sprintf("UPDATE pbx_licenca_pa_fixo SET id_user = %s, last_update = NOW(), limit_update = NOW() + INTERVAL '5 MINUTE' ", $status == 1 ? "'" . $idUser . "'" : 'NULL');
$status == 1 ? $query .= "WHERE id = (SELECT id FROM pbx_licenca_pa_fixo WHERE id_user IS NULL ORDER BY id LIMIT 1)" : $status == 1 ? $query .= "WHERE id = (SELECT id FROM pbx_licenca_pa_fixo WHERE id_user IS NULL ORDER BY id LIMIT 1)" :
$query .= sprintf("WHERE id_user = '%s' ", $idUser); $query .= sprintf("WHERE id_user = '%s' ", $idUser);
if (!pg_query($dbcon, $query)) { if (!pg_query($dbcon, $query)) {
throw new Exception('A operação não pode ser realizada!'); throw new Exception('A operação não pode ser realizada!');
@ -98,13 +98,15 @@ function AtualizaLicenca($dbcon, $field, $status) {
} }
} }
function AtualizaLicencaX($dbcon, $field, $status) { function AtualizaLicencaX($dbcon, $field, $status)
{
$cont = 0; $cont = 0;
$org_id = GetOrganizacao();
try { try {
if ($status == 1) { if ($status == 1) {
$query = "SELECT COUNT(*) AS qtd_pa_fixo FROM pbx_licenca_pa_fixo WHERE matricula IS NOT NULL;"; $query = "SELECT COUNT(*) AS qtd_pa_fixo FROM pbx_licenca_pa_fixo WHERE matricula IS NOT NULL AND org_id = $org_id;";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
$result = pg_fetch_assoc($result); $result = pg_fetch_assoc($result);
@ -122,7 +124,7 @@ function AtualizaLicencaX($dbcon, $field, $status) {
@pg_query($dbcon, 'begin'); @pg_query($dbcon, 'begin');
foreach ($field as $id) { foreach ($field as $id) {
$query = "update pbx_usuarios set pa_fixo = {$status} where id = {$id};"; $query = "UPDATE pbx_usuarios SET pa_fixo = {$status} WHERE id = {$id};";
$result = @pg_query($dbcon, $query); $result = @pg_query($dbcon, $query);
$cont++; $cont++;
} }
@ -140,10 +142,16 @@ function AtualizaLicencaX($dbcon, $field, $status) {
} }
} }
function GetGrupoUser($dbcon, $codSel, $infos) { function GetGrupoUser($dbcon, $codSel, $infos)
{
$org_id = GetOrganizacao();
$sel = ""; $sel = "";
$infos['name'] = $infos['name'] . "rm"; $infos['name'] = $infos['name'] . "rm";
$query = "SELECT * FROM pbx_usuarios WHERE pa_fixo = 1 ORDER BY apelido;"; $query = "SELECT * FROM pbx_usuarios a
INNER JOIN pbx_organizacao_usuarios b on b.id_usuario = a.id
WHERE pa_fixo = 1
AND b.id_organizacao = $org_id
ORDER BY apelido;";
$result = @pg_query($dbcon, $query); $result = @pg_query($dbcon, $query);
$lista = '<select name="%s%s" id="%s" size="%s" style="width:%spx;" %s>%s'; $lista = '<select name="%s%s" id="%s" size="%s" style="width:%spx;" %s>%s';
@ -157,10 +165,17 @@ function GetGrupoUser($dbcon, $codSel, $infos) {
return $lista; return $lista;
} }
function GetUser($dbcon, $codSel, $infos) { function GetUser($dbcon, $codSel, $infos)
{
$org_id = GetOrganizacao();
$sel = ""; $sel = "";
$infos['name'] = $infos['name'] . "inc"; $infos['name'] = $infos['name'] . "inc";
$query = "SELECT * FROM pbx_usuarios WHERE pa_fixo = 0 AND id NOT IN(342,341,356,357,466) ORDER BY apelido;"; $query = "SELECT * FROM pbx_usuarios a
INNER JOIN pbx_organizacao_usuarios b on b.id_usuario = a.id
WHERE pa_fixo = 0
AND a.id NOT IN(342,341,356,357,466)
AND b.id_organizacao = $org_id
ORDER BY apelido;";
$result = @pg_query($dbcon, $query); $result = @pg_query($dbcon, $query);
$lista = '<select name="%s%s" id="%s" size="%s" style="width:%spx" %s >%s'; $lista = '<select name="%s%s" id="%s" size="%s" style="width:%spx" %s >%s';
@ -173,5 +188,3 @@ function GetUser($dbcon, $codSel, $infos) {
$lista .= "</select>\n"; $lista .= "</select>\n";
return $lista; return $lista;
} }
?>

92
seguranca/perfil/perfilGrupo.php

@ -1,9 +1,5 @@
<?php <?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
if (IsPostBack()) { if (IsPostBack()) {
$dadosGrupo = Explode('|', $_POST["lstGrupo"]); $dadosGrupo = Explode('|', $_POST["lstGrupo"]);
$codGp = $dadosGrupo[0]; $codGp = $dadosGrupo[0];
@ -15,6 +11,7 @@ if (IsPostBack()) {
$_SESSION["lstGrupo"] = $codGp; $_SESSION["lstGrupo"] = $codGp;
$_SESSION["nameGrupo"] = $nomeGp; $_SESSION["nameGrupo"] = $nomeGp;
} }
$codUser = 0; $codUser = 0;
$sizeUser = 12; $sizeUser = 12;
$sizeGpUser = 10; $sizeGpUser = 10;
@ -39,9 +36,11 @@ $smarty->assign("nameGrupo", $nomeGp);
GetTemplate($smarty, 'seguranca/perfilGrupos.tpl'); GetTemplate($smarty, 'seguranca/perfilGrupos.tpl');
function GetGrupoDef($dbcon, &$codGp, &$nomeGp, $idUser) { function GetGrupoDef($dbcon, &$codGp, &$nomeGp, $idUser)
{
$org_id = GetOrganizacao();
$flagSystem = (IsAdmin() && IsLocalServer()) ? '1=1' : " gp_system = '0' "; $flagSystem = (IsAdmin() && IsLocalServer()) ? '1=1' : " gp_system = '0' ";
$query = "select gp_id, gp_nome from pbx_grupo g where $flagSystem and gp_status = 1 {REST} order by gp_nome limit 1"; $query = "SELECT gp_id, gp_nome FROM pbx_grupo g WHERE $flagSystem and gp_status = 1 {REST} AND org_id = $org_id ORDER BY gp_nome LIMIT 1";
//restricao se o usuario nao for admin //restricao se o usuario nao for admin
$query = strtoupper(GetLogin()) == "ADMIN" ? str_replace("{REST}", "", $query) : str_replace("{REST}", " and exists(select '' from pbx_grupo_usuario where gp_id = g.gp_id and user_id = $idUser)", $query); $query = strtoupper(GetLogin()) == "ADMIN" ? str_replace("{REST}", "", $query) : str_replace("{REST}", " and exists(select '' from pbx_grupo_usuario where gp_id = g.gp_id and user_id = $idUser)", $query);
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
@ -50,12 +49,21 @@ function GetGrupoDef($dbcon, &$codGp, &$nomeGp, $idUser) {
$nomeGp = $row["gp_nome"]; $nomeGp = $row["gp_nome"];
} }
function GetGrupo($dbcon, $codGp, $size = 1) { function GetGrupo($dbcon, $codGp, $size = 1)
{
$org_id = GetOrganizacao();
$flagSystem = (IsAdmin() && IsLocalServer()) ? '1=1' : " gp_system = '0' "; $flagSystem = (IsAdmin() && IsLocalServer()) ? '1=1' : " gp_system = '0' ";
$idUser = GetIdUser(); $idUser = GetIdUser();
//$query = "select gp_id, gp_nome from pbx_grupo g where $flagSystem and gp_status = 1 {REST} order by 2"; $query = "SELECT gp_id,
$query = "select gp_id, case when(gp_system = 1)then (gp_nome || '#') else case when(user_id = 0)then gp_nome else (gp_nome || '**') end end gp_nome, case when(user_id = 0)then 0 else 1 end as ord from pbx_grupo g where $flagSystem and gp_status = 1 {REST} order by 3,2"; CASE WHEN(gp_system = 1) THEN (gp_nome || '#')
//restricao se o usuario nao for admin ELSE
CASE WHEN(user_id = 0)THEN gp_nome
ELSE (gp_nome || '**') END END gp_nome,
CASE WHEN(user_id = 0)THEN 0 ELSE 1 END AS ord
FROM pbx_grupo g
WHERE $flagSystem
AND org_id = $org_id
AND gp_status = 1 {REST} ORDER BY 3,2";
$query = strtoupper(GetLogin()) == "ADMIN" ? str_replace("{REST}", "", $query) : str_replace("{REST}", " and exists(select '' from pbx_grupo_usuario where gp_id = g.gp_id and user_id = $idUser)", $query); $query = strtoupper(GetLogin()) == "ADMIN" ? str_replace("{REST}", "", $query) : str_replace("{REST}", " and exists(select '' from pbx_grupo_usuario where gp_id = g.gp_id and user_id = $idUser)", $query);
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
$sel = ""; $sel = "";
@ -72,27 +80,17 @@ function GetGrupo($dbcon, $codGp, $size = 1) {
return $lista; return $lista;
} }
function GetFunc($dbcon, $idGrupo, $notMenu = 0) { function GetFunc($dbcon, $idGrupo, $notMenu = 0)
//$dadosMenu = Menu($dbcon, QueryPerfilHead($idGrupo), QueryPerfilItens($idGrupo)); {
$_SESSION["SStreRoot"] = GetLogin(); $_SESSION["SStreRoot"] = GetLogin();
$_SESSION["SStreView"] = 1; $_SESSION["SStreView"] = 1;
$_SESSION["SSperfilAcao"] = "add"; $_SESSION["SSperfilAcao"] = "add";
$idUser = GetIdUser(); $idUser = GetIdUser();
//$dadosMenu = Menu($dbcon, QueryMenuHead($idUser), QueryMenuItens($idUser, true));
$dadosMenu = MontaMenu(0, $idUser, 2, $notMenu, "add"); $dadosMenu = MontaMenu(0, $idUser, 2, $notMenu, "add");
$dadosMenu = str_replace("MENU_ITEMS", "TREE_ITEMS", $dadosMenu); $dadosMenu = str_replace("MENU_ITEMS", "TREE_ITEMS", $dadosMenu);
$GLOBALS["jsBlok"][] = $dadosMenu; $GLOBALS["jsBlok"][] = $dadosMenu;
/*
$menu = "<div class=\"menuGeral\" style=\"position:relative\">\n";
$menu .= "<script language=\"JavaScript\">\n";
$menu .= "<!--//\n";
$menu .= " new menu (TREE_ITEMS, MENU_TPL);\n";
$menu .= "//-->\n";
$menu .= "</script>\n";
$menu .= "</div>\n";
*/
$menu = "<div style=\"width:300px;height:800px;position:relative;\">\n"; $menu = "<div style=\"width:300px;height:800px;position:relative;\">\n";
$menu .= "<script language=\"JavaScript\">\n"; $menu .= "<script language=\"JavaScript\">\n";
$menu .= "<!--//\n"; $menu .= "<!--//\n";
@ -104,43 +102,33 @@ function GetFunc($dbcon, $idGrupo, $notMenu = 0) {
return $menu; return $menu;
} }
function GetGrupoFunc($dbcon, $idGrupo) { function QueryPerfilHead($idGrupo)
{
return $lista;
}
function QueryPerfilHead($idGrupo) {
$idUser = GetIdUser(); $idUser = GetIdUser();
$query = "select b.fun_id, b.fun_nome, b.fun_menu, b.fun_menu_text, b.fun_menu_url, b.fun_menu_img, b.fun_id_pai $query = "SELECT b.fun_id, b.fun_nome, b.fun_menu, b.fun_menu_text, b.fun_menu_url, b.fun_menu_img, b.fun_id_pai
from pbx_funcoes b FROM pbx_funcoes b
where coalesce(b.fun_id_pai, 0) = 0 "; WHERE coalesce(b.fun_id_pai, 0) = 0 ";
// and b.fun_id not in(select b.fun_id from pbx_grupo_funcoes a, pbx_funcoes b where b.fun_id = a.fun_id and a.gp_id = '$idGrupo') ";
if (!IsAdmin())
$query .= " and b.fun_id in(select gf.fun_id from pbx_grupo_funcoes gf, pbx_grupo_usuario gu where gf.gp_id = gu.gp_id and gu.user_id = '$idUser' order by 1) ";
$query .= "Union select b.fun_id, b.fun_nome, b.fun_menu, b.fun_menu_text, b.fun_menu_url, b.fun_menu_img, b.fun_id_pai
from pbx_funcoes b where coalesce(b.fun_id_pai, 0) = 0 and fun_public = 1";
$query .= " order by 1 ";
if (!IsAdmin()) {
$query .= " AND b.fun_id in(select gf.fun_id from pbx_grupo_funcoes gf, pbx_grupo_usuario gu WHERE gf.gp_id = gu.gp_id and gu.user_id = '$idUser' order by 1) ";
}
$query .= "UNION SELECT b.fun_id, b.fun_nome, b.fun_menu, b.fun_menu_text, b.fun_menu_url, b.fun_menu_img, b.fun_id_pai
FROM pbx_funcoes b WHERE coalesce(b.fun_id_pai, 0) = 0 and fun_public = 1";
$query .= " ORDER BY 1 ";
return $query; return $query;
} }
function QueryPerfilItens($idGrupo) { function QueryPerfilItens($idGrupo)
{
$idUser = GetIdUser(); $idUser = GetIdUser();
$query = "select b.fun_id, b.fun_nome, b.fun_menu, b.fun_menu_text, b.fun_menu_url, b.fun_menu_img, b.fun_id_pai $query = "SELECT b.fun_id, b.fun_nome, b.fun_menu, b.fun_menu_text, b.fun_menu_url, b.fun_menu_img, b.fun_id_pai
from pbx_funcoes b FROM pbx_funcoes b
where coalesce(b.fun_id_pai, 0) > 0 "; WHERE coalesce(b.fun_id_pai, 0) > 0 ";
// and b.fun_id not in(select b.fun_id from pbx_grupo_funcoes a, pbx_funcoes b where b.fun_id = a.fun_id and a.gp_id = '$idGrupo') "; if (!IsAdmin()) {
$query .= "AND b.fun_id in(select gf.fun_id from pbx_grupo_funcoes gf, pbx_grupo_usuario gu where gf.gp_id = gu.gp_id and gu.user_id = '$idUser' order by 1) ";
if (!IsAdmin()) }
$query .= " and b.fun_id in(select gf.fun_id from pbx_grupo_funcoes gf, pbx_grupo_usuario gu where gf.gp_id = gu.gp_id and gu.user_id = '$idUser' order by 1) ";
$query .= " order by b.fun_id ";
$query .= "ORDER BY b.fun_id ";
return $query; return $query;
} }
?>

50
seguranca/usuario.php

@ -2,21 +2,19 @@
$param = ''; $param = '';
$erro = ''; $erro = '';
// echo VerificaAgenteLogadoAstrisk('elvis') ? 'Deslogado' : 'Logado';
$janW = 500; $janW = 500;
$janH = 285; $janH = 285;
$tpl = 'seguranca/usuarioConsulta.tpl'; $tpl = 'seguranca/usuarioConsulta.tpl';
$paramPesquisa = isset($_REQUEST['paramPesquisa']) ? $_REQUEST['paramPesquisa'] : ''; $paramPesquisa = isset($_REQUEST['paramPesquisa']) ? $_REQUEST['paramPesquisa'] : '';
$filtro = isset($_REQUEST["paramPesquisa"]) ? trim($_REQUEST["paramPesquisa"]) : ''; $filtro = isset($_REQUEST["paramPesquisa"]) ? trim($_REQUEST["paramPesquisa"]) : '';
$filtroNovo = !isset($_REQUEST["pgn"]) ? '' : sprintf("&paramPesquisa%s&pgn=%s&bloco=%s&pg=%s&status=%s", $_REQUEST["paramPesquisa"], $_REQUEST["pgn"], $_REQUEST["bloco"], $_REQUEST["pg"],$_REQUEST["status"]); $filtroNovo = !isset($_REQUEST["pgn"]) ? '' : sprintf("&paramPesquisa%s&pgn=%s&bloco=%s&pg=%s&status=%s", $_REQUEST["paramPesquisa"], $_REQUEST["pgn"], $_REQUEST["bloco"], $_REQUEST["pg"], $_REQUEST["status"]);
$recontaPag = (GetFormAcao() == FORM_DELETE) || isset($_POST['pesquisa']); $recontaPag = (GetFormAcao() == FORM_DELETE) || isset($_POST['pesquisa']);
$statusAtivo = isset($_REQUEST["status"]) ? trim($_REQUEST["status"]) : 'A'; $statusAtivo = isset($_REQUEST["status"]) ? trim($_REQUEST["status"]) : 'A';
$imgNovo = "<img src=\"images/novo.gif\" width=\"16\" height=\"16\" align=\"absmiddle\" border=\"0\" title=\"Inclui novo usuário\">"; $imgNovo = "<img src=\"images/novo.gif\" width=\"16\" height=\"16\" align=\"absmiddle\" border=\"0\" title=\"Inclui novo usuário\">";
$imgNovo = "<a href=\"javaScript:NovaJanela('index.php?idProg=22&idUser=0$filtroNovo', 'usuarioCad', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\">$imgNovo Novo Usuário</a>"; $imgNovo = "<a href=\"javaScript:NovaJanela('index.php?idProg=22&idUser=0$filtroNovo', 'usuarioCad', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\">$imgNovo Novo Usuário</a>";
$org_id = GetOrganizacao();
if (IsAdmin()){ if (IsAdmin()) {
$imgLcFixo = "<img src=\"images/global.gif\" width=\"16\" height=\"16\" align=\"absmiddle\" border=\"0\" title=\"Licença Painel Atendimento Fixo\">"; $imgLcFixo = "<img src=\"images/global.gif\" width=\"16\" height=\"16\" align=\"absmiddle\" border=\"0\" title=\"Licença Painel Atendimento Fixo\">";
$imgLcFixo = "<a href=\"javaScript:NovaJanela('index.php?idProg=362', 'usuarioCad', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\">$imgLcFixo Licença Usuário</a>"; $imgLcFixo = "<a href=\"javaScript:NovaJanela('index.php?idProg=362', 'usuarioCad', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\">$imgLcFixo Licença Usuário</a>";
} }
@ -34,7 +32,7 @@ if (IsPostBack() || (isset($_GET["idDelete"])) || (isset($_GET["idReset"]))) {
/* /*
* Pega o codigo do grupo do usuario; * Pega o codigo do grupo do usuario;
*/ */
$query = "select gp_id from pbx_grupo where user_id = $id"; $query = "SELECT gp_id FROM pbx_grupo WHERE user_id = $id";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
$row = pg_fetch_row($result); $row = pg_fetch_row($result);
$gpIdUser = QuotedStr($row[0]); $gpIdUser = QuotedStr($row[0]);
@ -46,7 +44,7 @@ if (IsPostBack() || (isset($_GET["idDelete"])) || (isset($_GET["idReset"]))) {
/* /*
* Preserva apenas o grupo reservado do ususario. * Preserva apenas o grupo reservado do ususario.
*/ */
$query = "delete from pbx_grupo_usuario where user_id = {$id} and gp_id <> {$gpIdUser}"; $query = "DELETE FROM pbx_grupo_usuario where user_id = {$id} and gp_id <> {$gpIdUser}";
if (!pg_query($dbcon, $query)) { if (!pg_query($dbcon, $query)) {
GeraExcept("Não foi possível remover o usuário dos grupos relacionados!"); GeraExcept("Não foi possível remover o usuário dos grupos relacionados!");
} }
@ -54,7 +52,7 @@ if (IsPostBack() || (isset($_GET["idDelete"])) || (isset($_GET["idReset"]))) {
/* /*
* Apaga as funcoes exclusivas do usuario. * Apaga as funcoes exclusivas do usuario.
*/ */
$query = " delete from pbx_grupo_funcoes where gp_id = {$gpIdUser}"; $query = " DELETE FROM pbx_grupo_funcoes where gp_id = {$gpIdUser}";
if (!pg_query($dbcon, $query)) { if (!pg_query($dbcon, $query)) {
GeraExcept("Não foi possível remover o perfil exclusido do usuário!"); GeraExcept("Não foi possível remover o perfil exclusido do usuário!");
} }
@ -62,7 +60,7 @@ if (IsPostBack() || (isset($_GET["idDelete"])) || (isset($_GET["idReset"]))) {
/* /*
* Deleta restricoes de audio criadas para o grupo do usuario. * Deleta restricoes de audio criadas para o grupo do usuario.
*/ */
$query = "delete from pbx_grupo_audio_ramal where gp_id = {$gpIdUser}"; $query = "DELETE FROM pbx_grupo_audio_ramal where gp_id = {$gpIdUser}";
if (!pg_query($dbcon, $query)) { if (!pg_query($dbcon, $query)) {
GeraExcept("Não foi possível remover as restrições de áudio dos ramais para o usuário!"); GeraExcept("Não foi possível remover as restrições de áudio dos ramais para o usuário!");
} }
@ -70,7 +68,7 @@ if (IsPostBack() || (isset($_GET["idDelete"])) || (isset($_GET["idReset"]))) {
/* /*
* Deleta restricoes de audio criadas para o grupo do usuario. * Deleta restricoes de audio criadas para o grupo do usuario.
*/ */
$query = "delete from pbx_fila_audios where gp_id = {$gpIdUser}"; $query = "DELETE FROM pbx_fila_audios where gp_id = {$gpIdUser}";
if (!pg_query($dbcon, $query)) { if (!pg_query($dbcon, $query)) {
GeraExcept("Não foi possível remover as restrições de áudio das filas para usuário!"); GeraExcept("Não foi possível remover as restrições de áudio das filas para usuário!");
} }
@ -78,17 +76,17 @@ if (IsPostBack() || (isset($_GET["idDelete"])) || (isset($_GET["idReset"]))) {
/* /*
* Deleta permissao de acesso a revendas. * Deleta permissao de acesso a revendas.
*/ */
$query = "delete from pbx_grupo_revendas where gp_id = {$gpIdUser}"; $query = "DELETE FROM pbx_grupo_revendas where gp_id = {$gpIdUser}";
if (!pg_query($dbcon, $query)) { if (!pg_query($dbcon, $query)) {
GeraExcept("Não foi possível remover as revendas ligadas ao usuário!"); GeraExcept("Não foi possível remover as revendas ligadas ao usuário!");
} }
$query = "update pbx_usuarios set senha = md5('1234'), def_senha = 1 where id = $id;"; $query = "UPDATE pbx_usuarios set senha = md5('1234'), def_senha = 1 where id = $id;";
if (!pg_query($dbcon, $query)) { if (!pg_query($dbcon, $query)) {
GeraExcept("Não foi possível atualizar a senha padrão do usuário!"); GeraExcept("Não foi possível atualizar a senha padrão do usuário!");
} }
$query = "update pbx_usuarios set status = false where id = $id"; $query = "UPDATE pbx_usuarios set status = false where id = $id";
if (!pg_query($dbcon, $query)) { if (!pg_query($dbcon, $query)) {
GeraExcept("Não foi possível atualizar o status do usuário!"); GeraExcept("Não foi possível atualizar o status do usuário!");
} }
@ -111,12 +109,13 @@ if (IsPostBack() || (isset($_GET["idDelete"])) || (isset($_GET["idReset"]))) {
$id = $_GET["idReset"]; $id = $_GET["idReset"];
$param = $_SESSION["SSparamUser"]; $param = $_SESSION["SSparamUser"];
$query = "update pbx_usuarios set senha = md5('1234'), def_senha = 1 where id = $id; "; $query = "UPDATE pbx_usuarios SET senha = md5('1234'), def_senha = 1 where id = $id; ";
$query .= "UPDATE pbx_controle_acesso SET acs_erro = 2 WHERE acs_user_id = $id AND acs_erro = 1; "; $query .= "UPDATE pbx_controle_acesso SET acs_erro = 2 WHERE acs_user_id = $id AND acs_erro = 1; ";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
if ($result) if ($result) {
@pg_affected_rows($result); @pg_affected_rows($result);
}
if ($result) { if ($result) {
$msg = "alert('Senha redefinida com sucesso!');"; $msg = "alert('Senha redefinida com sucesso!');";
@ -127,13 +126,14 @@ if (IsPostBack() || (isset($_GET["idDelete"])) || (isset($_GET["idReset"]))) {
} }
} }
$compl = ''; $compl = '';
if (isset($_REQUEST['paramPesquisa']) && $_REQUEST['paramPesquisa']) { if (isset($_REQUEST['paramPesquisa']) && $_REQUEST['paramPesquisa']) {
$compl = PreparaLike($filtro, true); $compl = PreparaLike($filtro, true);
$compl = sprintf("and (a.nome ilike %s or a.apelido ilike %s or a.matricula ilike %s)", $compl, $compl, $compl); $compl = sprintf("and (a.nome ilike %s or a.apelido ilike %s or a.matricula ilike %s)", $compl, $compl, $compl);
} }
$compl .= " AND b.id_organizacao = $org_id ";
if ($statusAtivo == "A") { if ($statusAtivo == "A") {
$statusAtv = 'true'; $statusAtv = 'true';
} else if ($statusAtivo == "I") { } else if ($statusAtivo == "I") {
@ -142,10 +142,12 @@ if ($statusAtivo == "A") {
$statusAtv = $statusAtivo ? "and status = $statusAtv" : ''; $statusAtv = $statusAtivo ? "and status = $statusAtv" : '';
$query = "select id, nome, apelido, matricula, flag, coalesce(\"admin\", false)::int as adm , senha, coalesce(supervisor, false)::int as supervisor, $query = "SELECT a.id, nome, apelido, matricula, flag, coalesce(\"admin\", false)::int as adm , senha, coalesce(supervisor, false)::int as supervisor,
coalesce(agente,false)::int as agente, email, coalesce(status,true)::int as status from pbx_usuarios a "; coalesce(agente,false)::int as agente, email, coalesce(status,true)::int as status
$query .= "where apelido <> 'sinccontasenha' $statusAtv $compl " FROM pbx_usuarios a
. "and upper(apelido) <> 'ADMIN' order by nome"; INNER JOIN pbx_organizacao_usuarios b ON b.id_usuario = a.id
WHERE apelido <> 'sinccontasenha' $statusAtv $compl
AND upper(apelido) <> 'ADMIN' ORDER BY nome";
$params = "&paramPesquisa={$filtro}&status=$statusAtivo"; $params = "&paramPesquisa={$filtro}&status=$statusAtivo";
$links = PaginaDados($idProg, $query, $params, $regPagina, $offSet, $pagMostra, true); $links = PaginaDados($idProg, $query, $params, $regPagina, $offSet, $pagMostra, true);
@ -156,7 +158,7 @@ while ($dados = @pg_fetch_array($result)) {
$apelido = $dados["apelido"]; $apelido = $dados["apelido"];
$imgEdit = "<img src=\"imgSite/editaUser.png\" width=\"16\" height=\"16\" border=\"0\" title=\"Edita o usuário: $apelido\">"; $imgEdit = "<img src=\"imgSite/editaUser.png\" width=\"16\" height=\"16\" border=\"0\" title=\"Edita o usuário: $apelido\">";
$imgReset = "<img src=\"imgSite/redefineSenha.png\" width=\"16\" height=\"16\" border=\"0\" title=\"Define senha padrão para o usuário: $apelido\">"; $imgReset = "<img src=\"imgSite/redefineSenha.png\" width=\"16\" height=\"16\" border=\"0\" title=\"Define senha padrão para o usuário: $apelido\">";
$imgDelete = sprintf("<img src=\"imgSite/%s\" width=\"16\" height=\"16\" border=\"0\" title=\" %s\">", ($dados['status'] == 1 ? 'deletaUser.png' : 'deletaUserOff.png'), ( $dados['status'] == 1 ? "Desabilita e remove todo o perfil do usuário: $apelido" : "O usuário: $apelido foi desativado e seu perfil removido!")); $imgDelete = sprintf("<img src=\"imgSite/%s\" width=\"16\" height=\"16\" border=\"0\" title=\" %s\">", ($dados['status'] == 1 ? 'deletaUser.png' : 'deletaUserOff.png'), ($dados['status'] == 1 ? "Desabilita e remove todo o perfil do usuário: $apelido" : "O usuário: $apelido foi desativado e seu perfil removido!"));
$imgPerfil = "<img src=\"imgSite/userOn16.png\" width=\"16\" height=\"16\" border=\"0\" title=\"Mostra o perifil do usuário: $apelido\">"; $imgPerfil = "<img src=\"imgSite/userOn16.png\" width=\"16\" height=\"16\" border=\"0\" title=\"Mostra o perifil do usuário: $apelido\">";
$id = $dados["id"]; $id = $dados["id"];
$nome = $dados["nome"]; $nome = $dados["nome"];
@ -167,11 +169,8 @@ while ($dados = @pg_fetch_array($result)) {
$matricula = $dados["matricula"]; $matricula = $dados["matricula"];
$flag = $dados["flag"]; $flag = $dados["flag"];
//$admin = $dados["adm"] ? $imgYes : $imgNo;
$senha = $dados["senha"]; $senha = $dados["senha"];
//$supervisor = $dados["supervisor"] ? $imgYes : $imgNo;
//$agente = $dados["agente"] ? $imgYes : $imgNo;
$email = !empty($dados["email"]) ? ocultarEmail($dados["email"]) : "&nbsp;"; $email = !empty($dados["email"]) ? ocultarEmail($dados["email"]) : "&nbsp;";
$status = GetStatusModulo($dados['status'], true); $status = GetStatusModulo($dados['status'], true);
$delete = $dados['status'] == 1 ? "<a href=\"javaScript:DeletaUser('" . $dados["id"] . "', '$params');\">" . $imgDelete . "</a>" : $imgDelete; $delete = $dados['status'] == 1 ? "<a href=\"javaScript:DeletaUser('" . $dados["id"] . "', '$params');\">" . $imgDelete . "</a>" : $imgDelete;
@ -204,4 +203,3 @@ $smarty->assign("bloco", $_REQUEST["bloco"]);
$smarty->assign("pg", $_REQUEST["pg"]); $smarty->assign("pg", $_REQUEST["pg"]);
GetTemplate($smarty, $tpl); GetTemplate($smarty, $tpl);
?>

130
seguranca/usuarioCad.php

@ -1,9 +1,5 @@
<?php <?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
require_once("util/constantes.php"); require_once("util/constantes.php");
$tpLayout = 1; $tpLayout = 1;
$limpaVar = 0; $limpaVar = 0;
@ -15,9 +11,7 @@ $userAgente = "";
$userSuper = ""; $userSuper = "";
$userAdm = ""; $userAdm = "";
$userStatus = isset($_POST["userStatus"]) ? "checked" : ""; $userStatus = isset($_POST["userStatus"]) ? "checked" : "";
$org_id = GetOrganizacao();
// $listaDacs = GetDac($dbcon, isSet($_POST["listaDacs"]) ? $_POST["listaDacs"] : 0, "", 0, 1);
//novo usuario
if (isset($_GET["idUser"]) && $_GET["idUser"] == 0) { if (isset($_GET["idUser"]) && $_GET["idUser"] == 0) {
$acaoUser = 'Incluir'; $acaoUser = 'Incluir';
@ -28,53 +22,47 @@ if (isset($_GET["idUser"]) && $_GET["idUser"] == 0) {
} else if (isset($_GET["idUser"]) && $_GET["idUser"] > 0) { } else if (isset($_GET["idUser"]) && $_GET["idUser"] > 0) {
$msgLogin = "disabled"; $msgLogin = "disabled";
$acaoUser = 'Alterar'; $acaoUser = 'Alterar';
$query = "select id, nome, apelido, matricula, flag, coalesce(\"admin\", false)::int as adm , senha, coalesce(supervisor, false)::int as supervisor, coalesce(agente,false)::int as agente, email, coalesce(status,true)::int as status, penalidade, senha_dias_expira from pbx_usuarios \n"; $query = "SELECT id, nome, apelido, matricula, flag, coalesce(\"admin\", false)::int as adm , senha, coalesce(supervisor, false)::int as supervisor, coalesce(agente,false)::int as agente, email, coalesce(status,true)::int as status, penalidade, senha_dias_expira FROM pbx_usuarios \n";
$query .= "where id = $idUser"; $query .= "WHERE id = $idUser";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
if ($result) if ($result) {
$dados = pg_fetch_array($result); $dados = pg_fetch_array($result);
}
$userNome = $dados["nome"]; $userNome = $dados["nome"];
$userLogin = $dados["apelido"]; $userLogin = $dados["apelido"];
$userMatricula = $dados["matricula"]; $userMatricula = $dados["matricula"];
$userPassword = DEFAULT_MASC_PASSWORD; // $dados["senha"]; $userPassword = DEFAULT_MASC_PASSWORD;
$userEmail = $dados["email"]; $userEmail = $dados["email"];
$userExpiraSenha = $dados["senha_dias_expira"]; $userExpiraSenha = $dados["senha_dias_expira"];
//$userAgente = $dados["agente"] ? "checked" : "";
// $userSuper = $dados["supervisor"] ? "checked" : "";
// $userAdm = $dados["adm"] ? "checked" : "";
$userStatus = $dados["status"] ? "checked" : ""; $userStatus = $dados["status"] ? "checked" : "";
$penalidade = $dados["penalidade"]; $penalidade = $dados["penalidade"];
$dacAgente = GetIdDacPadrao($dbcon, $idUser); $dacAgente = GetIdDacPadrao($dbcon, $idUser);
$dacPadrao = GetDacs($dbcon, $dacAgente, "", 0, 1); $dacPadrao = GetDacs($dbcon, $dacAgente, "", 0, 1);
} else if ((isset($_POST["btGravar"]))) { } else if ((isset($_POST["btGravar"]))) {
$msg = ""; $msg = "";
if (empty($_POST["userNome"])) if (empty($_POST["userNome"])) {
$msg = "alert('Informe o nome do Usuário!');"; $msg = "alert('Informe o nome do Usuário!');";
else if (($_POST["btGravar"] != "Alterar") && empty($_POST["userLogin"])) } else if (($_POST["btGravar"] != "Alterar") && empty($_POST["userLogin"])) {
$msg = "alert('Informe um apelido!');"; $msg = "alert('Informe um apelido!');";
else if (empty($_POST["userPassword"])) } else if (empty($_POST["userPassword"])) {
$msg = "alert('Informe a senha');"; $msg = "alert('Informe a senha');";
else if (($_POST["btGravar"] != "Alterar") && ExisteRegistro($dbcon, "pbx_usuarios", "apelido", (strtolower($_POST["userLogin"])))) } else if (($_POST["btGravar"] != "Alterar") && ExisteRegistro($dbcon, "pbx_usuarios", "apelido", (strtolower($_POST["userLogin"])))) {
$msg = "alert('Login já cadastrado!');"; $msg = "alert('Login já cadastrado!');";
else if (($_POST["btGravar"] != "Alterar") && ExisteRegistro($dbcon, "pbx_usuarios", "matricula", ($_POST["userMatriculaH"]))) } else if (($_POST["btGravar"] != "Alterar") && ExisteRegistro($dbcon, "pbx_usuarios", "matricula", ($_POST["userMatriculaH"]))) {
$msg = "alert('Matrícula já cadastrada!');"; $msg = "alert('Matrícula já cadastrada!');";
else if ($_POST["userEmail"] && !is_email($_POST["userEmail"])) } else if ($_POST["userEmail"] && !is_email($_POST["userEmail"])) {
$msg = "alert('Email Inválido!');"; $msg = "alert('Email Inválido!');";
else if (ExisteRegistro($dbcon, "pbx_usuarios", "email", (strtolower($_POST["userEmail"])), ($idUser ? "id <> {$idUser}" : ''))) } else if (ExisteRegistro($dbcon, "pbx_usuarios", "email", (strtolower($_POST["userEmail"])), ($idUser ? "id <> {$idUser}" : ''))) {
$msg = "alert('O e-mail informado já foi registrado!');"; $msg = "alert('O e-mail informado já foi registrado!');";
else if ($_POST["userExpiraSenha"] < 0) } else if ($_POST["userExpiraSenha"] < 0) {
$msg = "alert('O tempo de expiração deve ser maior ou igual 0 'zero');"; $msg = "alert('O tempo de expiração deve ser maior ou igual 0 'zero');";
}
$userNome = mb_strtoupper(RemoveAcentos($_POST["userNome"])); $userNome = mb_strtoupper(RemoveAcentos($_POST["userNome"]));
$userLogin = mb_strtolower(RemoveAcentos(RemoveEspaco( $_POST["btGravar"] != "Alterar" ? $_POST["userLogin"] : $_POST["userLoginH"]), -1)); $userLogin = mb_strtolower(RemoveAcentos(RemoveEspaco($_POST["btGravar"] != "Alterar" ? $_POST["userLogin"] : $_POST["userLoginH"]), -1));
$userMatricula = $_POST["userMatriculaH"]; $userMatricula = $_POST["userMatriculaH"];
$userPassword = ($_POST["userPassword"]); $userPassword = ($_POST["userPassword"]);
$userEmail = RemoveAcentos(strtolower($_POST["userEmail"])); $userEmail = RemoveAcentos(strtolower($_POST["userEmail"]));
//$userAgente = $_POST["userAgente"] ? "" : "";
// $userSuper = $_POST["userSuper"] ? "" : "";
//$userAdm = $_POST["userAdm"] ? "" : "";
$userStatus = isset($_POST["userStatus"]) ? "checked" : ""; $userStatus = isset($_POST["userStatus"]) ? "checked" : "";
$acaoUser = $_POST["btGravar"]; $acaoUser = $_POST["btGravar"];
$penalidade = $_POST["penalidade"] ? soNumero($_POST["penalidade"]) : "0"; $penalidade = $_POST["penalidade"] ? soNumero($_POST["penalidade"]) : "0";
@ -83,44 +71,51 @@ if (isset($_GET["idUser"]) && $_GET["idUser"] == 0) {
$userExpiraSenha = $_POST["userExpiraSenha"] ? $_POST["userExpiraSenha"] : 0; $userExpiraSenha = $_POST["userExpiraSenha"] ? $_POST["userExpiraSenha"] : 0;
if (empty($msg) && ($_POST["btGravar"] == 'Incluir')) { if (empty($msg) && ($_POST["btGravar"] == 'Incluir')) {
$result = pg_query($dbcon, "begin"); $result = pg_query($dbcon, "begin");
if ($result) { if ($result) {
$userMatricula = GetMatriculaAgente($dbcon); $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)
$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) RETURNING id;";
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', $penalidade, QuotedStr($dacPadraoSel), QuotedStr($userLogin), $userExpiraSenha);
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
if ($result) { if ($result) {
$user = pg_fetch_assoc($result);
$ret = IncluiAgenteFile($dbcon); $ret = IncluiAgenteFile($dbcon);
$result = strtoupper($ret) == "OK"; $result = strtoupper($ret) == "OK";
} }
$query = sprintf("INSERT INTO pbx_organizacao_usuarios (id_usuario, id_organizacao, updated_at) VALUES (%s,%s,'%s')", $user['id'], $org_id, date('Y-m-d H:i:s'));
$result1 = $result && pg_query($dbcon, $query);
echo pg_last_error() . "<br>";
/* /*
* Inclui usuario como grupo. * Inclui usuario como grupo.
*/ */
$query = sprintf("insert into pbx_grupo(gp_nome, gp_status, user_id, gp_user) select apelido, 1, id, id from pbx_usuarios where apelido = %s", QuotedStr($userLogin)); $query = sprintf("INSERT INTO pbx_grupo(gp_nome, gp_status, user_id, gp_user, org_id)
$result = $result && pg_query($dbcon, $query); SELECT apelido, 1, id, id, $org_id FROM pbx_usuarios WHERE apelido = %s", QuotedStr($userLogin));
$result2 = $result && pg_query($dbcon, $query);
echo pg_last_error() . "<br>";
/* /*
* Insere o usuario no mesmo grupo criado com seu login. * Insere o usuario no mesmo grupo criado com seu login.
*/ */
$query = sprintf("insert into pbx_grupo_usuario(user_id, gp_id) select user_id, gp_id from pbx_grupo where gp_nome = %s", QuotedStr($userLogin)); $query = sprintf("INSERT INTO pbx_grupo_usuario(user_id, gp_id, org_id)
$result = $result && pg_query($dbcon, $query); SELECT user_id, gp_id, $org_id FROM pbx_grupo WHERE gp_nome = %s", QuotedStr($userLogin));
$result3 = $result && pg_query($dbcon, $query);
echo pg_last_error() . "<br>";
/* /*
* Se o dac for selecionado no cadastro do usuario, o mesmo sera atribuido para o proprio usuario. * Se o dac for selecionado no cadastro do usuario, o mesmo sera atribuido para o proprio usuario.
*/ */
if ($dacPadraoSel) { if ($dacPadraoSel) {
$query = sprintf("insert into pbx_fila_grupos(id, gp_id) select $dacPadraoSel, gp_id from pbx_grupo where gp_nome = %s", QuotedStr($userLogin)); $query = sprintf("INSERT INTO pbx_fila_grupos(id, gp_id, org_id)
$result = $result && pg_query($dbcon, $query); SELECT $dacPadraoSel, gp_id, $org_id FROM pbx_grupo WHERE gp_nome = %s", QuotedStr($userLogin));
$result4 = $result && pg_query($dbcon, $query);
} }
echo pg_last_error() . "<br>";
/* /*
* Finaliza a transacao. * Finaliza a transacao.
*/ */
@ -133,13 +128,12 @@ if (isset($_GET["idUser"]) && $_GET["idUser"] == 0) {
$limpaVar = 1; $limpaVar = 1;
$acaoUser = 'Incluir'; $acaoUser = 'Incluir';
$idUser = 0; $idUser = 0;
$userMatricula = GetMatriculaAgente($dbcon) - 1;
$msg = "alert('Usuário: $userLogin matricula: $userMatricula, incluido com sucesso');";
$userMatricula = GetMatriculaAgente($dbcon); $userMatricula = GetMatriculaAgente($dbcon);
$msg = "alert('Usuário: $userLogin matricula: $userMatricula, incluido com sucesso');";
$userPassword = "1234"; $userPassword = "1234";
$penalidade = 0; $penalidade = 0;
$jsStartup[] = "window.opener.ResetForm();"; $jsStartup[] = "window.opener.ResetForm();";
$jsStartup[] = 'window.close()'; // $jsStartup[] = 'window.close()';
} else { } else {
$erroBd = @pg_last_error($dbcon); $erroBd = @pg_last_error($dbcon);
pg_query($dbcon, "rollback"); pg_query($dbcon, "rollback");
@ -156,18 +150,18 @@ if (isset($_GET["idUser"]) && $_GET["idUser"] == 0) {
$updSenha = DEFAULT_MASC_PASSWORD !== $userPassword; $updSenha = DEFAULT_MASC_PASSWORD !== $userPassword;
$result = pg_query($dbcon, "begin"); $result = pg_query($dbcon, "begin");
$query = "update pbx_usuarios $query = "UPDATE pbx_usuarios
set nome = %s, SET nome = %s,
%s %s
email = %s, email = %s,
status = %s, status = %s,
penalidade = %s, penalidade = %s,
dac_padrao = %s, dac_padrao = %s,
senha_dias_expira = %s senha_dias_expira = %s
where id = %s "; WHERE id = %s ";
if ($updSenha) { if ($updSenha) {
$updSenha = sprintf(" senha = md5(%s), ", QuotedStr($userPassword)); $updSenha = sprintf(" senha = md5(%s), ", QuotedStr($userPassword));
$queryAlt = sprintf("UPDATE pbx_controle_acesso SET acs_erro = 2 WHERE acs_login = '%s' AND acs_erro = 1;", $userLogin); $queryAlt = sprintf("UPDATE pbx_controle_acesso SET acs_erro = 2 WHERE acs_login = '%s' AND acs_erro = 1;", $userLogin);
pg_query($dbcon, $queryAlt); pg_query($dbcon, $queryAlt);
} else { } else {
@ -181,7 +175,7 @@ if (isset($_GET["idUser"]) && $_GET["idUser"] == 0) {
* Se o dac for selecionado no cadastro do usuario, o mesmo sera atribuido para o proprio usuario. * Se o dac for selecionado no cadastro do usuario, o mesmo sera atribuido para o proprio usuario.
*/ */
if ($dacPadraoSel && !GetNotExistsDacUser($dacPadraoSel, $idUser)) { if ($dacPadraoSel && !GetNotExistsDacUser($dacPadraoSel, $idUser)) {
$query = sprintf("insert into pbx_fila_grupos(id, gp_id) select $dacPadraoSel, gp_id from pbx_grupo where gp_nome = %s", QuotedStr($userLogin)); $query = sprintf("INSERT INTO pbx_fila_grupos(id, gp_id) select $dacPadraoSel, gp_id from pbx_grupo where gp_nome = %s", QuotedStr($userLogin));
$result = $result && pg_query($dbcon, $query); $result = $result && pg_query($dbcon, $query);
} }
@ -202,13 +196,11 @@ if (isset($_GET["idUser"]) && $_GET["idUser"] == 0) {
} else { } else {
$msgAgt = trim($msgAgt); $msgAgt = trim($msgAgt);
$erroBd = @pg_last_error($dbcon); $erroBd = @pg_last_error($dbcon);
// $msDisp = empty($msgAgt) ? ("A operação não pode ser realizada!" . ($erroBd ? " Erro: " . $erroBd : "")) : $msgAgt;
$msg = sprintf("alert('%s');", (empty($msgAgt) ? "A operação não pode ser realizada!" : $msgAgt)); $msg = sprintf("alert('%s');", (empty($msgAgt) ? "A operação não pode ser realizada!" : $msgAgt));
pg_query($dbcon, "rollback"); pg_query($dbcon, "rollback");
$acaoUser = 'Alterar'; $acaoUser = 'Alterar';
} }
} }
$jsStartup[] = $msg; $jsStartup[] = $msg;
} }
@ -220,11 +212,7 @@ $smarty->assign("userMatricula", $userMatricula);
$smarty->assign("msgMatricula", $msgMatricula); $smarty->assign("msgMatricula", $msgMatricula);
$smarty->assign("userPassword", $userPassword); $smarty->assign("userPassword", $userPassword);
$smarty->assign("userEmail", $limpaVar ? "" : $userEmail); $smarty->assign("userEmail", $limpaVar ? "" : $userEmail);
//$smarty->assign("userAgente", $limpaVar ? "" : $userAgente);
//$smarty->assign("userSuper", $limpaVar ? "" : $userSuper);
//$smarty->assign("userAdm", $limpaVar ? "" : $userAdm);
$smarty->assign("habAdm", IsAdmin() ? "" : "disabled"); $smarty->assign("habAdm", IsAdmin() ? "" : "disabled");
$smarty->assign("userStatus", $limpaVar ? "checked" : $userStatus); $smarty->assign("userStatus", $limpaVar ? "checked" : $userStatus);
$smarty->assign("acaoUser", $acaoUser); $smarty->assign("acaoUser", $acaoUser);
$smarty->assign("idUser", $idUser); $smarty->assign("idUser", $idUser);
@ -236,15 +224,21 @@ $jsJQuery[] = "\$('#penalidade').keyup(function(){somenteNumeros(this);}) ";
GetTemplate($smarty, 'seguranca/usuario.tpl'); GetTemplate($smarty, 'seguranca/usuario.tpl');
function GetMatriculaAgente($db) { function GetMatriculaAgente($db)
$query = "select max(matricula) from pbx_usuarios"; {
$org_id = GetOrganizacao();
$query = "SELECT MAX(matricula)
FROM pbx_usuarios a
INNER JOIN pbx_organizacao_usuarios b ON b.id_usuario = a.id
WHERE b.id_organizacao = $org_id";
$result = pg_query($db, $query); $result = pg_query($db, $query);
if ($result) if ($result)
$dados = @pg_fetch_array($result); $dados = @pg_fetch_array($result);
return ($dados[0] + 1); return ($dados[0] + 1);
} }
function ValidaPassword($password) { function ValidaPassword($password)
{
$match = preg_match_all('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[$*&@#_!.%?])[0-9a-zA-Z$_*&@#]{8,}$/', $password); $match = preg_match_all('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[$*&@#_!.%?])[0-9a-zA-Z$_*&@#]{8,}$/', $password);
if (empty($password) || !$match) { if (empty($password) || !$match) {
@ -253,14 +247,16 @@ function ValidaPassword($password) {
return true; return true;
} }
function VerificaEmailExists($dbcon, $email) { function VerificaEmailExists($dbcon, $email)
{
$query = "select email from pbx_usuarios where email = '$email';"; $query = "select email from pbx_usuarios where email = '$email';";
$result = pg_query($dbcon, $query); $result = pg_query($dbcon, $query);
$res = pg_fetch_assoc($result); $res = pg_fetch_assoc($result);
return $res; return $res;
} }
function getEmailUser($dbcon, $email, $id = null) { function getEmailUser($dbcon, $email, $id = null)
{
$query = "SELECT count(*) FROM pbx_usuarios WHERE email = '$email' "; $query = "SELECT count(*) FROM pbx_usuarios WHERE email = '$email' ";
if ($id) { if ($id) {
$query .= " AND id <> $id "; $query .= " AND id <> $id ";
@ -274,5 +270,3 @@ function getEmailUser($dbcon, $email, $id = null) {
} }
return true; return true;
} }
?>

Loading…
Cancel
Save