You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5123 lines
198 KiB

<?php
function VerificaPerfilAcesso($db, $idProg, &$info = null)
{
$acesso = "SSAcesso_$idProg";
$acessoInfo = "SSAcessoInfo_$idProg";
if (isset($_SESSION[$acesso]) && $_SESSION[$acesso]) {
if (isset($info))
$info = $_SESSION[$acessoInfo];
return true;
/*
* Usado para nao autenticar o acesso no banco a todo instante
*/
}
$idUser = GetIdUser();
if (IsAdmin()) {
$query = "select e.arquivo, e.exit from pbx_funcoes d, pbx_funcoes_internas e where e.id_prog_pai = d.id_prog and e.id_prog = %s
union all
select b.arquivo, b.exit from pbx_funcoes a, pbx_funcoes_internas b where b.id_prog_pai = a.id_prog and fun_public = 1 and b.id_prog = %s and b.status = 9";
$query = sprintf($query, QuotedStr($idProg), QuotedStr($idProg));
} else {
$query = "select e.arquivo, e.exit from pbx_usuarios a, pbx_grupo_usuario b, pbx_grupo_funcoes c, pbx_funcoes d, pbx_funcoes_internas e
where b.user_id = a.id and c.gp_id = b.gp_id and d.fun_id = c.fun_id and e.id_prog_pai = d.id_prog and a.id = %s
and e.id_prog = %s
union all
select b.arquivo, b.exit from pbx_funcoes a, pbx_funcoes_internas b
where b.id_prog_pai = a.id_prog and fun_public = 1 and b.id_prog = %s"; // and b.status = 9
$query = sprintf($query, QuotedStr($idUser), QuotedStr($idProg), QuotedStr($idProg));
}
$result = pg_query($db, $query);
if ($result && isset($info)) {
$info = pg_fetch_array($result);
$_SESSION[$acesso] = 1;
$_SESSION[$acessoInfo] = $info;
}
return IsAdmin() | (($result) && (pg_num_rows($result) > 0));
}
function GetIdUser()
{
if (IsAdmin()) {
return 0;
}
return isset($_SESSION["SSidUser"]) ? $_SESSION["SSidUser"] : 0;
}
function VerificaCadastroMenu($conn)
{
global $alturaTabelaAgente;
/*
* Esta funcao verifica se o menus estao cadastrdos corretamente
* e recria se for necessario
TABLE pbx_funcoes( fun_id serial NOT NULL,
fun_nome character varying(50) NOT NULL,
fun_menu integer NOT NULL DEFAULT 0,
fun_menu_text character varying(50),
fun_menu_url character varying(1024),
fun_menu_img character varying(1024),
fun_id_pai integer,
fun_status integer NOT NULL DEFAULT 1,
fun_public integer NOT NULL DEFAULT 0,
CONSTRAINT "pkFuncId" PRIMARY KEY (fun_id),
CONSTRAINT "idxFunNome" UNIQUE (fun_nome)
)
*/
$nomeModCli = GetNomeCadCli();
$menuUsuario[] = array('1', 'mnSistema', '1', 'Sistema', 'index.php?idProg=58&idMenu=1&menuNome=Sistema', '', '', '1', '0', 1, '58');
$link = GetLinkNovaJanela(840, $alturaTabelaAgente, 'index.php?idProg=14', 'AgenteCallcenter');
$menuUsuario[] = array('2', 'mnAgente', '1', 'Agente', $link, '', '1', '1', '0', '', '14');
//$menuUsuario[] = array('2','mnAgente' ,'1','Agente', 'index.php?idProg=14','','1','1','0','','14');
$menuUsuario[] = array('3', 'mnAudio', '1', '<EFBFBD>udio', 'index.php?idProg=23', '', '1', '1', '0', '', '23');
$menuUsuario[] = array('4', 'mnConfiguracao', '1', 'Configura<EFBFBD><EFBFBD>es', 'index.php?idProg=20', '', '1', '1', '0', '', '20');
$menuUsuario[] = array('5', 'mnGrupoUsuario', '1', 'Grupo/Usu<EFBFBD>rios', 'index.php?idProg=36', '', '1', '1', '0', '', '36');
//$menuUsuario[] = array('6','mnMonitor','1','Monitor do Sistema','index.php?idProg=82','','1','1','0');
$menuUsuario[] = array('7', 'mnSites', '1', 'Sites', 'index.php?idProg=105', '', '1', '1', '0', '', '105');
$menuUsuario[] = array('8', 'mnSupervisor', '1', 'Supervisor', 'index.php?idProg=6', '', '1', '1', '0', '', '6');
$link = GetLinkNovaJanela(550, 200, 'index.php?idProg=16', 'trocaSenha');
$menuUsuario[] = array('9', 'mnTrocaSenha', '1', 'Trocar Senha', $link, '', '1', '1', '1', '', '16');
//grupo de cadastro
$menuUsuario[] = array('10', 'mnCadastro', '1', 'Cadastro', 'index.php?idProg=58&idMenu=10&menuNome=Cadastro', '', '', '1', '0', 2, '58');
$menuUsuario[] = array('11', 'mnClassificacao', '1', 'Classifica<EFBFBD><EFBFBD>o', 'index.php?idProg=27', '', '10', '1', '0', '', '27');
$menuUsuario[] = array('12', 'mnContribuinte', '1', $nomeModCli, 'index.php?idProg=45', '', '209', '1', '0', '', '45');
$menuUsuario[] = array('13', 'mnGrupos', '1', 'Grupos de Usu<EFBFBD>rios', 'index.php?idProg=84', '', '10', '1', '0', '', '84');
// $menuUsuario[] = array('14', 'mnIndisponibilidade', '1', 'Indisponibilidade', 'index.php?idProg=46', '', '10', '1', '0', '', '46');
$menuUsuario[] = array('15', 'mnMotivosPausa', '1', 'Motivos de Pausas', 'index.php?idProg=86', '', '10', '1', '0', '', '86');
$menuUsuario[] = array('16', 'mnUsuario', '1', 'Usu<EFBFBD>rios', 'index.php?idProg=21', '', '10', '1', '0', '', '21');
//relatorios
$menuUsuario[] = array('17', 'mnRelatorio', '1', 'Relat<EFBFBD>rio', 'index.php?idProg=58&idMenu=17&menuNome=Relat<EFBFBD>rio', '', '', '1', '0', '4', '58');
$menuUsuario[] = array('18', 'mnCallCenter', '1', 'Call Center', 'index.php?idProg=58&idMenu=18&menuNome=Call Center', '', '17', '1', '0', '', '58');
$menuUsuario[] = array('19', 'mnRelAbandonadaFila', '1', 'Abandonada na Fila', 'index.php?idProg=91', '', '18', '1', '0', '', '91');
//$menuUsuario[] = array('20','mnRelAbandonadaUra','1','Abandonadas na Ura','index.php?idProg=93','','18','1','0');
$menuUsuario[] = array('21', 'mnChamForaHorario', '1', 'Chamadas Fora do Hor<EFBFBD>rio', 'index.php?idProg=49', '', '55', '1', '0', '', '49');
$menuUsuario[] = array('22', 'mnRelDesligamento', '1', 'Chamadas Desligadas A/B', 'index.php?idProg=108', '', '18', '1', '0', '', '108');
$menuUsuario[] = array('23', 'mnRelRecebidasDDD', '1', 'Chamadas Totalizadas por DDD', 'index.php?idProg=95', '', '18', '1', '0', '', '95');
$menuUsuario[] = array('24', 'mnRelClassifica', '1', 'Classifica<EFBFBD><EFBFBD>o de Atendimento', 'index.php?idProg=51', '', '18', '1', '0', '', '51');
// $menuUsuario[] = array('25', 'mnRelContribuinte', '1', 'Relat<EFBFBD>rio de ' . $nomeModCli, 'index.php?idProg=52', '', '18', '1', '0', '', '52');
$menuUsuario[] = array('27', 'mnRelDesempenhoOperacao', '1', 'Desempenho/Opera<EFBFBD><EFBFBD>o', 'index.php?idProg=97', '', '18', '1', '0', '', '97');
$menuUsuario[] = array('28', 'mnRelMetas', '1', 'Metas', 'index.php?idProg=58&idMenu=28&menuNome=Metas', '', '18', '1', '0', '', '58');
$menuUsuario[] = array('29', 'mnMetaMensal', '1', 'Meta Mensal', 'index.php?idProg=32', '', '28', '1', '0', '', '32');
//$menuUsuario[] = array('30','mnMetaMensaAneel','1','Meta Mensal Anal<EFBFBD>tico','index.php?idProg=1','','28','1','0','','1');
$menuUsuario[] = array('31', 'mnMetaDiaria', '1', 'Meta Di<EFBFBD>ria', 'index.php?idProg=33', '', '28', '1', '0', '', '33');
//$menuUsuario[] = array('32', 'mnMetaDiariaAneel', '1', 'Meta Di<EFBFBD>ria Aneel', 'index.php?idProg=2', '', '28', '1', '0', '', '2');
$menuUsuario[] = array('33', 'mnRelOriginadasAgente', '1', 'Originadas/Agente', 'index.php?idProg=89', '', '18', '1', '0', '', '89');
$menuUsuario[] = array('34', 'mnRelProdAgente', '1', 'Produ<EFBFBD><EFBFBD>o/Agente', 'index.php?idProg=0', '', '18', '1', '0', '', '0');
// $menuUsuario[] = array('35','mnRamlRamal','1','Ramal/Ramal','index.php?idProg=47','','18','0','0');
$menuUsuario[] = array('36', 'mnRechamadas', '1', 'Rechamadas', 'index.php?idProg=110', '', '18', '1', '0', '', '110');
//$menuUsuario[] = array('37','mnResumoFone','1','Resumo/Fone','index.php?idProg=8','','18','1','0','','8');
//$menuUsuario[] = array('38','mnRelTotalTipoLigacaoUsuario','1','Totalizador Tipo de Liga<EFBFBD><EFBFBD>o/Usu<EFBFBD>rio','index.php?idProg=87','','18','1','0');
$menuUsuario[] = array('39', 'mnRelTransAgente', '1', 'Transfer<EFBFBD>ncia/Agente', 'index.php?idProg=12', '', '18', '1', '0', '', '12');
$menuUsuario[] = array('40', 'mnTransferencia', '1', 'Transfer<EFBFBD>ncia', 'index.php?idProg=7', '', '18', '1', '0', '', '7');
$menuUsuario[] = array('41', 'mnPbx', '1', 'PBX', 'index.php?idProg=58&idMenu=41&menuNome=PBX', '', '17', '1', '0', '', '58');
$menuUsuario[] = array('42', 'mnChamadasSaintes', '1', 'Chamadas Saintes', 'index.php?idProg=58&idMenu=42&menuNome=Chamadas Saintes', '', '41', '1', '0', '', '58');
$menuUsuario[] = array('43', 'mnRelChamSaintesRamal', '1', 'Chamadas Saintes/Ramal', 'index.php?idProg=37', '', '42', '1', '0', '', '37');
$menuUsuario[] = array('44', 'mnRelChamSaintesConta', '1', 'Chamadas Saintes/Conta', 'index.php?idProg=39', '', '42', '1', '0', '', '39');
$menuUsuario[] = array('45', 'mnRelTotalSaintesRamal', '1', 'Totalizador Chamadas Saintes/Ramal', 'index.php?idProg=41', '', '42', '1', '0', '', '41');
$menuUsuario[] = array('46', 'mnRelChamSaintesCentroCusto', '1', 'Chamadas Saintes/Centro Custo', 'index.php?idProg=67', '', '42', '1', '0', '', '67');
$menuUsuario[] = array('47', 'mnRelSaintesTipoLigacao', '1', 'Chamadas Saintes/Tipo de Liga<EFBFBD><EFBFBD>o', 'index.php?idProg=70', '', '42', '1', '0', '', '70');
$menuUsuario[] = array('48', 'mnRelSaintesMaisDiscados', '1', 'Chamadas Saintes/Mais Discados', 'index.php?idProg=74', '', '42', '1', '0', '', '74');
$menuUsuario[] = array('108', 'mnRelTotalTipoLigacaoUsuario', '1', 'Totalizador Tipo de Liga<EFBFBD><EFBFBD>o/Usu<EFBFBD>rio', 'index.php?idProg=87', '', '42', '1', '0', '', '87');
$menuUsuario[] = array('49', 'mnChamadasEntrantes', '1', 'Chamadas Entrantes', 'index.php?idProg=58&idMenu=49&menuNome=Chamadas Entrantes', '', '41', '1', '0', '', '58');
// $menuUsuario[] = array('50', 'mnRelEntrantesCaixaPostal', '1', 'Encaminhadas/Caixa Postal', 'index.php?idProg=76', '', '49', '1', '0', '', '76');
// $menuUsuario[] = array('51', 'mnRelEntrantesNaoAtendida', '1', 'N<EFBFBD>o Atendidas', 'index.php?idProg=78', '', '49', '1', '0', '', '78');
$menuUsuario[] = array('52', 'mnRelChamEntrantesGeral', '1', 'Chamadas Entrantes Geral', 'index.php?idProg=59', '', '49', '1', '0', '', '59');
$menuUsuario[] = array('53', 'mnRelEntrantesTipoLigacao', '1', 'Tipo de Liga<EFBFBD><EFBFBD>o', 'index.php?idProg=72', '', '49', '1', '0', '', '72');
$menuUsuario[] = array('54', 'mnRelTotalEntrantesRamal', '1', 'Totalizador', 'index.php?idProg=63', '', '49', '1', '0', '', '63');
$menuUsuario[] = array('55', 'mnRelPbxGeral', '1', 'Geral', 'index.php?idProg=58&idMenu=55&menuNome=Geral', '', '41', '1', '0', '', '58');
$menuUsuario[] = array('56', 'mnRelRmalRamal', '1', 'Chamadas Ramal/Ramal', 'index.php?idProg=43', '', '55', '1', '0', '', '43');
//$menuUsuario[] = array('57', 'mnRelListaSigameExterna', '1', 'Lista Sigame Externa', 'index.php?idProg=80', '', '55', '1', '0', '', '80');
$menuUsuario[] = array('58', 'mnRelListaUsuarios', '1', 'Listagem de Usuarios', 'index.php?idProg=65', '', '55', '1', '0', '', '65');
// $menuUsuario[] = array('59','mnDiscador','1','Discador','','','','1','0', 3);
// $menuUsuario[] = array('60','mnCampanha','1','Campanha','index.php?idProg=112','','59','1','0');
$menuUsuario[] = array('61', 'mnPbxPbx', '1', 'Pbx', 'index.php?idProg=58&idMenu=61&menuNome=PBX', '', '', '1', '0', '5', '58');
$menuUsuario[] = array('62', 'mnPbxChamadas', '1', 'Chamadas', 'index.php?idProg=58&idMenu=62&menuNome=Chamadas', '', '61', '1', '0', '', '58');
$menuUsuario[] = array('63', 'mnPbxChamadasPrioridadeAtendimento', '1', 'Prioridade de Atendimento', 'index.php?idProg=10035&pbxRequest=1', '', '62', '1', '0', '', '10035');
$menuUsuario[] = array('64', 'mnPbxChamadasConferencias', '1', 'Confer<EFBFBD>ncias', 'index.php?idProg=10036&pbxRequest=1', '', '62', '1', '0', '', '10036');
$link = GetLinkNovaJanela(600, 280, 'index.php?idProg=10037&pbxRequest=1&acao=inseri', 'estacionamentoTransf');
$menuUsuario[] = array('65', 'mnPbxChamadasEstacionamentoTransferencia', '1', 'Estacionamento e Transfer<EFBFBD>ncia', $link, '', '62', '1', '0', '', '10037');
//Menu Cadastros
$menuUsuario[] = array('66', 'mnPbxCadastro', '1', 'Cadastro', 'index.php?idProg=58&idMenu=66&menuNome=Cadastro', '', '61', '1', '0', '', '58');
//$menuUsuario[] = array('67','mnPbxAgenda','1','Agenda','index.php?idProg=10004&pbxRequest=1','','66','1','0','','10004');
//$menuUsuario[] = array('68','mnPbxAgente','1','Agente','index.php?idProg=10001&pbxRequest=1','','66','1','0','','10001');
$menuUsuario[] = array('69', 'mnPbxAnuncio', '1', 'An<EFBFBD>ncio', 'index.php?idProg=10007&pbxRequest=1', '', '66', '1', '0', '', '10007');
$menuUsuario[] = array('70', 'mnPbxCallback', '1', 'Callback', 'index.php?idProg=10020&pbxRequest=1', '', '66', '1', '0', '', '10020');
$menuUsuario[] = array('71', 'mnPbxDisa', '1', 'Disa', 'index.php?idProg=10019&pbxRequest=1', '', '66', '1', '0', '', '10019');
$menuUsuario[] = array('72', 'mnPbxFacilidade', '1', 'Facilidades', 'index.php?idProg=10008&pbxRequest=1', '', '66', '1', '0', '', '10008');
$menuUsuario[] = array('73', 'mnPbxFila', '1', 'Fila', 'index.php?idProg=10002&pbxRequest=1', '', '66', '1', '0', '', '10002');
// $menuUsuario[] = array('74','mnPbxGrupos','1','Grupos','index.php?idProg=10023&pbxRequest=1','','66','1','0','','10023');
$menuUsuario[] = array('75', 'mnPbxMusicaEspera', '1', 'M<EFBFBD>sica em Espera', 'index.php?idProg=10022&pbxRequest=1', '', '66', '1', '0', '', '10022');
$menuUsuario[] = array('76', 'mnPbxOutros', '1', 'Outros', 'index.php?idProg=58&idMenu=76&menuNome=Outros', '', '66', '1', '0', '', '58');
$menuUsuario[] = array('77', 'mnPbxOutrosEmpresas', '1', 'Empresas', 'index.php?idProg=10024&pbxRequest=1', '', '76', '1', '0', '', '10024');
$menuUsuario[] = array('78', 'mnPbxOutrosDepartamentos', '1', 'Departamentos', 'index.php?idProg=10025&pbxRequest=1', '', '76', '1', '0', '', '10025');
//$menuUsuario[] = array('79','mnPbxOutrosHosts','1','Hosts','index.php?idProg=10026&pbxRequest=1','','76','1','0','','10026');
$menuUsuario[] = array('80', 'mnPbxOutrosContextos', '1', 'Contextos', 'index.php?idProg=10027&pbxRequest=1', '', '76', '1', '0', '', '10027');
$menuUsuario[] = array('81', 'mnPbxOutrosContaSenha', '1', 'Conta e Senha', 'index.php?idProg=10028&pbxRequest=1', '', '76', '1', '0', '', '10028');
$menuUsuario[] = array('82', 'mnPbxOutrosListaNegra', '1', 'Lista Negra', 'index.php?idProg=10029&pbxRequest=1', '', '76', '1', '0', '', '10029');
$menuUsuario[] = array('83', 'mnPbxOutrosGruposCaptura', '1', 'Grupos de Captura', 'index.php?idProg=10030&pbxRequest=1', '', '76', '1', '0', '', '10030');
//$menuUsuario[] = array('84', 'mnPbxRamais', '1', 'Ramais', 'index.php?idProg=58&idMenu=84&menuNome=Ramais', '', '66', '1', '0', '', '58');
//$menuUsuario[] = array('85', 'mnPbxRamaisSip', '1', 'SIP', 'index.php?idProg=10009&pbxRequest=1', '', '84', '1', '0', '', '10009');
$menuUsuario[] = array('84', 'mnPbxRamais', '1', 'Ramais Sip', 'index.php?idProg=10009&pbxRequest=1', '', '66', '1', '0', '', '10009');
$menuUsuario[] = array('86', 'mnPbxRamaisIax', '1', 'Ramais Iax', 'index.php?idProg=10010&pbxRequest=1', '', '66', '1', '0', '', '10010');
//$menuUsuario[] = array('87', 'mnPbxRamaisDgv', '1', 'DGV', 'index.php?idProg=10011&pbxRequest=1', '', '84', '1', '0', '', '10011');
//$menuUsuario[] = array('88', 'mnPbxRamaisPbX', '1', 'PBX', 'index.php?idProg=10012&pbxRequest=1', '', '84', '1', '0', '', '10012');
$menuUsuario[] = array('89', 'mnPbxRotas', '1', 'Rotas', 'index.php?idProg=58&idMenu=89&menuNome=Rotas', '', '66', '1', '0', '', '58');
$menuUsuario[] = array('90', 'mnPbxRotasEntrada', '1', 'Entrada', 'index.php?idProg=10017&pbxRequest=1', '', '89', '1', '0', '', '10017');
$menuUsuario[] = array('91', 'mnPbxRotasSaida', '1', 'Sa<EFBFBD>da', 'index.php?idProg=10018&pbxRequest=1', '', '89', '1', '0', '', '10018');
$menuUsuario[] = array('92', 'mnPbxTroncos', '1', 'Troncos', 'index.php?idProg=58&idMenu=92&menuNome=Troncos', '', '66', '1', '0', '', '58');
$menuUsuario[] = array('93', 'mnPbxTroncosSIP', '1', 'SIP', 'index.php?idProg=10014&pbxRequest=1', '', '92', '1', '0', '', '10014');
$menuUsuario[] = array('94', 'mnPbxTroncosIAX', '1', 'IAX', 'index.php?idProg=10015&pbxRequest=1', '', '92', '1', '0', '', '10015');
//$menuUsuario[] = array('95', 'mnPbxTroncosDGV', '1', 'DGV', 'index.php?idProg=10016&pbxRequest=1', '', '92', '1', '0', '', '10016');
$menuUsuario[] = array('96', 'mnPbxUra', '1', 'Ura', 'index.php?idProg=10031&pbxRequest=1', '', '66', '1', '0', '', '10031');
$menuUsuario[] = array('97', 'mnPbxVoiceMail', '1', 'Voicemail', 'index.php?idProg=10032&pbxRequest=1', '', '66', '1', '0', '', '10032');
$menuUsuario[] = array('98', 'mnPbxHorarios', '1', 'Hor<EFBFBD>rios', 'index.php?idProg=10033&pbxRequest=1', '', '66', '1', '0', '', '10033');
$menuUsuario[] = array('99', 'mnPbxConfiguracoes', '1', 'Configuracoes', 'index.php?idProg=58&idMenu=99&menuNome=Configura<EFBFBD><EFBFBD>es', '', '61', '1', '0', '', '58');
$link = GetLinkNovaJanela(500, 250, 'index.php?idProg=10038&pbxRequest=1&acao=inseri', 'bilhetes');
$menuUsuario[] = array('100', 'mnPbxConfiguracoesBilhetes', '1', 'Bilhetes', $link, '', '99', '1', '0', '', '10038');
$link = GetLinkNovaJanela(600, 280, 'index.php?idProg=10039&pbxRequest=1&acao=inseri', 'CadConfPadrao');
$menuUsuario[] = array('101', 'mnPbxConfiguracoesConfiguracoesPadrao', '1', 'Configura<EFBFBD><EFBFBD>es Padr<EFBFBD>o', $link, '', '99', '1', '0', '', '10039');
$menuUsuario[] = array('102', 'mnPbxConfiguracoesConfiguracaoEmail', '1', 'Configura<EFBFBD><EFBFBD>es de Email', 'index.php?idProg=10040&pbxRequest=1', '', '99', '1', '0', '', '10040');
//$menuUsuario[] = array('103', 'mnPbxConfiguracoesDigivoice', '1', 'Digivoice', 'index.php?idProg=10041&pbxRequest=1', '', '99', '1', '0', '', '10041');
// $menuUsuario[] = array('104','mnPbxConfiguracoesServicos','1','Servi<EFBFBD>os','index.php?idProg=10042&pbxRequest=1','','99','1','0','','10042');
$menuUsuario[] = array('105', 'mnPbxConfiguracoesArquivosSom', '1', 'Arquivos de Som', 'index.php?idProg=10043&pbxRequest=1', '', '99', '1', '0', '', '10043');
$link = GetLinkNovaJanela(700, 550, 'index.php?idProg=10034&pbxRequest=1', 'MonitorSistma');
$menuUsuario[] = array('106', 'mnPbxMonitor', '1', 'Monitor', 'index.php?idProg=10034&pbxRequest=1', '', '127', '1', '0', '', '10034');
//$menuUsuario[] = array('106', 'mnPbxMonitor', '1', 'Monitor', $link, '', '127', '1', '0', '', '10034');
$menuUsuario[] = array('107', 'mnPbxTroncosKHOMP', '1', 'KHOMP', 'index.php?idProg=10048&pbxRequest=1', '', '92', '1', '0', '', '10048');
$menuUsuario[] = array('109', 'mnDiscador', '1', 'Discador', 'index.php?idProg=58&idMenu=109&menuNome=Discador', '', '', '1', '0', '6', '58');
$menuUsuario[] = array('110', 'mnCampanha', '1', 'Campanha', 'index.php?idProg=112', '', '109', '1', '0', '', '112');
$menuUsuario[] = array('111', 'mnRetornoCampanha', '1', 'Arquivo de Retorno', 'index.php?idProg=125', '', '109', '1', '0', '', '125');
$menuUsuario[] = array('113', 'mnProcessaListaCampanha', '1', 'Processar Lista de Campanha', 'index.php?idProg=132', '', '109', '1', '0', '', '132');
//$menuUsuario[] = array('113','mnDesempenhoCampanha','1','Relat<EFBFBD>rio de Desempenho','index.php?idProg=132','','109','1','0','','132');
$menuUsuario[] = array('114', 'mnRamaisAgenda', '1', 'Agenda', 'index.php?idProg=58&idMenu=114&menuNome=Agenda', '', '', '1', '0', '7', '58');
$menuUsuario[] = array('115', 'mnDeptoRamal', '1', 'Departamentos', 'index.php?idProg=139', '', '114', '1', '0', '', '139');
$menuUsuario[] = array('116', 'mnRamal', '1', 'Ramais', 'index.php?idProg=140', '', '114', '1', '0', '', '140');
$menuUsuario[] = array('117', 'mnRelClassificaDetalhes', '1', 'Classifica<EFBFBD><EFBFBD>o Por Agente', 'index.php?idProg=150', '', '18', '1', '0', '', '150');
$menuUsuario[] = array('118', 'mmMetricasAnual', '1', 'Meta Anual Anal<EFBFBD>tico', 'index.php?idProg=152', '', '28', '1', '0', '', '152');
$menuUsuario[] = array('119', 'mnRelClassificaMensal', '1', 'Classifica<EFBFBD><EFBFBD>o Mensal', 'index.php?idProg=154', '', '18', '1', '0', '', '154');
//$link = GetLinkNovaJanela(630, 460, 'index.php?idProg=156', 'AgenteCallcenterRT');
//$menuUsuario[] = array('120', 'mnAgenteRt', '1', 'Agente Desenv ', $link, '', '1', '1', '0', '', '156');
// $menuUsuario[] = array('121', 'mnPbxRamaisDahdi', '1', 'DAHDI', 'index.php?idProg=10044&pbxRequest=1', '', '84', '1', '0', '', '10044');
$menuUsuario[] = array('122', 'mnReltotalizadorSaintesCentroCusto', '1', 'Totalizador/Centro Custo', 'index.php?idProg=159', '', '42', '1', '0', '', '159');
// $menuUsuario[] = array('123','mnCadastroMunicipio','1','Munic<EFBFBD>pios','index.php?idProg=163','','10','1','0','','163');
// $menuUsuario[] = array('124','mnRelClassificaMensalMunicipio','1','Classifica<EFBFBD><EFBFBD>o Mensal/Munic<EFBFBD>pio','index.php?idProg=166','','18','1','0','','166');
$menuUsuario[] = array('125', 'mnPbxResumoFone', '1', 'Detalhamento de Chamadas', 'index.php?idProg=172', '', '55', '1', '0', '', '172');
$menuUsuario[] = array('126', 'mnPausasDetalhado', '1', 'Detalhamento de Pausas', 'index.php?idProg=175', '', '18', '1', '0', '', '175');
/*
* Ferramentas do sistema
*/
// $menuUsuario[] = array('61','mnPbxPbx', '1', 'Pbx', '','','','1','0', 5);
//Menu Cadastros
// $menuUsuario[] = array('66','mnPbxCadastro', '1', 'Cadastro','','','61','1','0');
$menuUsuario[] = array('127', 'mnFerramentas', '1', 'Ferramentas', 'index.php?idProg=58&idMenu=127&menuNome=Ferramentas', '', '', '1', '0', '8', '58');
//$link = GetLinkNovaJanela(700, 680, 'index.php?idProg=10045&pbxRequest=1', 'MonitorE1');
//$menuUsuario[] = array('128', 'mnPbxMonitorE1', '1', 'Monitor E1', 'index.php?idProg=10045&pbxRequest=1', '', '127', '1', '0', '', '10045');
//$menuUsuario[] = array('128', 'mnPbxMonitorE1', '1', 'Monitor E1', $link, '', '127', '1', '0', '', '10045');
$menuUsuario[] = array('129', 'mnWorkflow', '1', 'Workflow', 'index.php?idProg=178', '', '127', '1', '0', '', '178');
$menuUsuario[] = array('130', 'mnPesquisaMenu', '1', 'Pesquisa', 'index.php?idProg=58&idMenu=130&menuNome=Pesquisa', '', '127', '1', '0', '', '58');
$menuUsuario[] = array('131', 'mnPesquisa', '1', 'Cadastro Pesquisa', 'index.php?idProg=181', '', '130', '1', '0', '', '181');
$menuUsuario[] = array('132', 'mnpesquisaLibera', '1', 'Pesquisa/Libera<EFBFBD><EFBFBD>o', 'index.php?idProg=185', '', '130', '1', '0', '', '185');
$menuUsuario[] = array('135', 'mnIntegAtiva', '1', 'Integra<EFBFBD><EFBFBD>o Ativa', 'index.php?idProg=190', '', '127', '1', '0', '', '190');
// $menuUsuario[] = array('136','mnRelatorioCobranca','1','Relat<EFBFBD>rio de Cobranca','index.php?idProg=193','','109','1','0','','193');
$menuUsuario[] = array('137', 'mnTarifacao', '1', 'Tarifa<EFBFBD><EFBFBD>o', 'index.php?idProg=58&idMenu=137&menuNome=Tarifa<EFBFBD><EFBFBD>o', '', '127', '1', '0', '', '58');
$menuUsuario[] = array('138', 'mnTarifacaoContrado', '1', 'Contratro/Operadora', 'index.php?idProg=197', '', '137', '1', '0', '', '197');
//$menuUsuario[] = array('139','mnTarifacaoParametros','1','Parametros','index.php?idProg=198','','137','1','0','','198');
$menuUsuario[] = array('140', 'mnTarifacaoOperadoras', '1', 'Operadoras', 'index.php?idProg=199', '', '137', '1', '0', '', '199');
$menuUsuario[] = array('141', 'mnPbxOutrosCcRamais', '1', 'Centro Custo/Ramais', 'index.php?idProg=10046&pbxRequest=0', '', '76', '1', '0', '', '10046');
//Menu Tarifa<EFBFBD><EFBFBD>o abaixo de relatorios
$menuUsuario[] = array('142', 'mnRelTarifacao', '1', 'Tarifa<EFBFBD><EFBFBD>o', 'index.php?idProg=58&idMenu=142&menuNome=Relat<EFBFBD>rios/Tarifa<EFBFBD><EFBFBD>o', '', '17', '1', '0', '', '58');
$menuUsuario[] = array('143', 'mnTarifaRamal', '1', 'Tarifa<EFBFBD><EFBFBD>o/Ramal', 'index.php?idProg=205', '', '142', '1', '0', '', '205');
$menuUsuario[] = array('144', 'mnTarifaConta', '1', 'Tarifa<EFBFBD><EFBFBD>o/Conta', 'index.php?idProg=206', '', '142', '1', '0', '', '206');
$menuUsuario[] = array('145', 'mnTarifaFatura', '1', 'Tarifa<EFBFBD><EFBFBD>o/Fatura', 'index.php?idProg=207', '', '142', '1', '0', '', '207');
$menuUsuario[] = array('146', 'mnRelPesquisa', '1', 'Pesquisa', 'index.php?idProg=58&idMenu=146&menuNome=Pesquisa', '', '17', '1', '0', '', '58');
$menuUsuario[] = array('147', 'mnpesquisaRel', '1', 'Relat<EFBFBD>rio Pesquisa', 'index.php?idProg=187', '', '146', '1', '0', '', '187');
$menuUsuario[] = array('148', 'mnpesquisaRelAgente', '1', 'Relat<EFBFBD>rio Pesquisa/Agente', 'index.php?idProg=188', '', '146', '1', '0', '', '188');
$menuUsuario[] = array('149', 'mnpesquisaAudio', '1', 'Relat<EFBFBD>rio Pesquisa/<EFBFBD>udio', 'index.php?idProg=208', '', '146', '1', '0', '', '208');
// (fun_id,fun_nome,fun_menu,fun_menu_text,fun_menu_url, fun_menu_img, fun_id_pai, fun_status, fun_public,ord, id_prog)
$menuUsuario[] = array('150', 'mnPrePago', '1', 'Pr<EFBFBD>-pago', 'index.php?idProg=58&idMenu=150&menuNome=Pr<EFBFBD>-Pago', '', '127', '1', '0', '', '58');
$menuUsuario[] = array('151', 'mnPrePagoRamal', '1', 'Lan<EFBFBD>amentos/Ramal', 'index.php?idProg=212', '', '150', '1', '0', '', '212');
$menuUsuario[] = array('152', 'mnPrePagoConta', '1', 'Lan<EFBFBD>amentos/Conta', 'index.php?idProg=213', '', '150', '1', '0', '', '213');
//$menuUsuario[] = array('153', 'mnPbxRamaisKhomp', '1', 'KHOMP', 'index.php?idProg=10047&pbxRequest=1', '', '84', '1', '0', '', '10047');
// id, nome menu, menu display menu url->idprog img, pai, st, public, ord, idprog
//$menuUsuario[] = array('154', 'mnPortabilidade', '1', 'Portabilidade', 'index.php?idProg=58&idMenu=154&menuNome=Portabilidade', '', '127', '1', '0', '', '58');
//$menuUsuario[] = array('155', 'mnMonitorPortabilidade', '1', 'Monitor da Portabilidade', 'index.php?idProg=217', '', '154', '1', '0', '', '217');
$menuUsuario[] = array('156', 'mnBackup', '1', 'Backup', 'index.php?idProg=58&idMenu=156&menuNome=Backup', '', '127', '1', '0', '', '58');
$menuUsuario[] = array('157', 'mnBkpDestino', '1', 'Destino do Backup', 'index.php?idProg=219', '', '156', '1', '0', '', '219');
$menuUsuario[] = array('158', 'mnBkpConfig', '1', 'Configura<EFBFBD><EFBFBD>es do Backup', 'index.php?idProg=221', '', '156', '1', '0', '', '221');
$menuUsuario[] = array('159', 'mnBkpMonitor', '1', 'Monitor do Backup', 'index.php?idProg=223', '', '156', '1', '0', '', '223');
$menuUsuario[] = array('160', 'mnDac', '1', 'DAC', 'index.php?idProg=58&idMenu=160&menuNome=DAC', '', '17', '1', '0', '', '58');
$menuUsuario[] = array('161', 'mnChamadasRamal', '1', 'Chamadas Ramal', 'index.php?idProg=225', '', '160', '1', '0', '', '225');
$menuUsuario[] = array('162', 'mnRecebidasAgente', '1', 'Recebidas por Agente', 'index.php?idProg=227', '', '18', '1', '0', '', '227');
$menuUsuario[] = array('163', 'mnSaintesGeral', '1', 'Chamadas Saintes Geral', 'index.php?idProg=163', '', '42', '1', '0', '', '163');
//$menuUsuario[] = array('164', 'mnPbxTroncosDahdi', '1', 'DAHDI', 'index.php?idProg=10049&pbxRequest=1', '', '92', '1', '0', '', '10049');
//$menuUsuario[] = array('165', 'mnDispoDahdi', '1', 'Dispositivo DAHDI', 'index.php?idProg=10050&pbxRequest=1', '', '66', '1', '0', '', '10050');
$menuUsuario[] = array('166', 'mnRelMetasdiaSemana', '1', 'Metas Dia da Semana', 'index.php?idProg=266', '', '28', '1', '0', '', '266');
//$menuUsuario[] = array('186','mnIndicadoresMP','1','Indicadores MP','index.php?idProg=262','','28','1','0','','262');
$menuUsuario[] = array('167', 'mnTarifaRefatura', '1', 'ReTarifa<EFBFBD><EFBFBD>o de Chamadas', 'index.php?idProg=270', '', '137', '1', '0', '', '270');
//$menuUsuario[] = array('3','mnAudio','1','<EFBFBD>udio','index.php?idProg=23','','1','1','0','','23');
$menuUsuario[] = array('168', 'mnAudioDownload', '0', 'Download de <EFBFBD>udio', 'index.php?idProg=271', '', '1', '1', '0', '', '271');
$menuUsuario[] = array('169', 'mnRelAgenteHoras', '1', 'Agente/Horas Trabalhadas', 'index.php?idProg=273', '', '18', '1', '0', '', '273');
$menuUsuario[] = array('170', 'mnCampanhaContatoStatus', '1', 'Status dos Contatos', 'index.php?idProg=274', '', '109', '1', '0', '', '274');
//$menuUsuario[] = array('171', 'mnTeste', '1', 'Paginacao', 'index.php?idProg=277', '', '109', '1', '0', '', '277');
$menuUsuario[] = array('172', 'mnServicosChamadas', '1', 'Servi<EFBFBD>os de Chamadas', 'index.php?idProg=278', '', '10', '1', '0', '', '278');
//Modulo de consolida<EFBFBD><EFBFBD>o de vendas.
if (UseModVendas()) {
$nomeMenuVendas = MenuVendas();
$menuUsuario[] = array('173', 'mnConsolidaVendas', '1', $nomeMenuVendas, 'index.php?idProg=58&idMenu=173&menuNome=' . $nomeMenuVendas, '', '', '1', '0', '6', '58');
$menuUsuario[] = array('174', 'mnConsolidaVendasFunil', '1', 'Funil de Vendas', 'index.php?idProg=280', '', '173', '1', '0', '', '280');
}
/*
* Mesa operadora web.
*/
//$menuUsuario[] = array('175', 'mnAgenteMesa', '1', 'Mesa Operadora', 'index.php?idProg=284', '', '1', '1', '0', '', '284');
if (UseModVendas()) {
$menuUsuario[] = array('176', 'mnGrupoVendas', '1', 'Regionais', 'index.php?idProg=285', '', '173', '1', '0', '', '285');
}
$menuUsuario[] = array('177', 'mnCustomizados', '1', 'Customizados', 'index.php?idProg=58&idMenu=177&menuNome=Customizados', '', '17', '1', '0', '', '58');
$menuUsuario[] = array('178', 'mnRelChamadasGeral', '1', 'Chamadas Geral', 'index.php?idProg=366', '', '177', '1', '0', '', '366');
// $menuUsuario[] = array('177', 'mnAnalysis', '1', 'Gr<EFBFBD>ficos', 'index.php?idProg=58&idMenu=177&menuNome=Analysis', '', '17', '1', '0', '', '58');
// $menuUsuario[] = array('178', 'mnResumoOperacao', '1', 'Resumo Chamadas/DAC', 'index.php?idProg=289', '', '177', '1', '0', '', '289');
// $menuUsuario[] = array('179', 'mnResumoOperacaoServico', '1', 'Resumo Chamadas/Servi<EFBFBD>os', 'index.php?idProg=290', '', '177', '1', '0', '', '290');
// $menuUsuario[] = array('180', 'mnIndicesDac', '1', '<EFBFBD>ndices/DAC', 'index.php?idProg=291', '', '177', '1', '0', '', '291');
// $menuUsuario[] = array('181', 'mnIndicesServ', '1', '<EFBFBD>ndices/Servi<EFBFBD>os', 'index.php?idProg=292', '', '177', '1', '0', '', '292');
// $menuUsuario[] = array('182', 'mnMetaMensalServ', '1', 'Meta Mensal/Servi<EFBFBD>o', 'index.php?idProg=293', '', '28', '1', '0', '', '293');
// $menuUsuario[] = array('183', 'mnMetaDiariaServ', '1', 'Meta Di<EFBFBD>ria/Servi<EFBFBD>o', 'index.php?idProg=294', '', '28', '1', '0', '', '294');
// $menuUsuario[] = array('184', 'mnDesempenhoDac', '1', 'Desempenho por DAC', 'index.php?idProg=300', '', '177', '1', '0', '', '300');
// $menuUsuario[] = array('185', 'mnDesempenhoServ', '1', 'Desempenho por Servi<EFBFBD>o', 'index.php?idProg=301', '', '177', '1', '0', '', '301');
$menuUsuario[] = array('186', 'mnUra', '1', 'URA', 'index.php?idProg=58&idMenu=186&menuNome=URA', '', '17', '1', '0', '', '58');
$menuUsuario[] = array('187', 'mnUraGeral', '1', 'URA Geral', 'index.php?idProg=302', '', '186', '1', '0', '', '302');
$menuUsuario[] = array('188', 'mnFilaContexto', '1', 'Entradas Fila/Contexto', 'index.php?idProg=303', '', '18', '1', '0', '', '303');
/*
* Adiciona ao modulo de Auditoria ao de ferramentas.
*/
$menuUsuario[] = array('189', 'mnAuditoria', '1', 'Auditoria', 'index.php?idProg=58&idMenu=189&menuNome=Auditoria', '', '127', '1', '0', '', '58');
$menuUsuario[] = array('190', 'mnLogFull', '1', 'Consulta Atividades', 'index.php?idProg=304', '', '189', '1', '0', '', '304');
$menuUsuario[] = array('191', 'mnMonitorChamadas', '1', 'Monitor Chamadas', 'index.php?idProg=307&pbxRequest=1', '', '127', '1', '0', '', '307');
//$menuUsuario[] = array('192', 'mnResumoDAC', '1', 'Resumo Geral/DAC', 'index.php?idProg=308', '', '177', '1', '0', '', '308');
$menuUsuario[] = array('193', 'mnEntrantesDDD', '1', 'Entrantes por DDD', 'index.php?idProg=309', '', '49', '1', '0', '', '309');
/**
* Manuais do sistema
*/
$menuUsuario[] = array('194', 'mnManUsuario', '1', 'Ajuda', 'index.php?idProg=314&idMenu=314&menuNome=Ajuda', '', '', '1', '0', '9', '314');
// $menuUsuario[] = array('195','mnManAgente','1','Agente','index.php?idProg=315','','194','1','0','','315');
/*
* Menu ferramentas de Atualiza<EFBFBD><EFBFBD>o das centrais
*/
$menuUsuario[] = array('196', 'mnCentralAtualizacao', '1', 'Controle de Atualiza<EFBFBD><EFBFBD>o', 'index.php?idProg=58&idMenu=196&menuNome=CentralAtualizacao', '', '127', '1', '0', '', '58');
$menuUsuario[] = array('197', 'mnCentrais', '1', 'Centrais', 'index.php?idProg=316', '', '196', '1', '0', '', '316');
$menuUsuario[] = array('198', 'mnHomologacoes', '1', 'Homologa<EFBFBD><EFBFBD>es', 'index.php?idProg=317', '', '196', '1', '0', '', '317');
/*
* Adciona o modulo de Administra<EFBFBD><EFBFBD>o ao de Ferramentas.
*
$menuUsuario[] = array('195', 'mnAdministrativo', '1', 'Asministra<EFBFBD><EFBFBD>o', 'index.php?idProg=58&idMenu=195&menuNome=Administra<EFBFBD><EFBFBD>o', '', '127', '1', '0', '', '58');
$menuUsuario[] = array('196', 'mnAcompanhaContrado', '1', 'Acompanhamento de Contratos', 'index.php?idProg=317', '', '195', '1', '0', '', '317');
*/
/*
* RELATORIO PBX SEM RETORNO
*/
$menuUsuario[] = array('199', 'mnRelSemRetorno', '1', 'Chamadas sem retorno', 'index.php?idProg=320', '', '55', '1', '0', '', '320');
/*
* RELATORIO URA
*/
$menuUsuario[] = array('200', 'mnRelUraDesempenho', '1', 'URA Desempenho', 'index.php?idProg=321', '', '186', '1', '0', '', '321');
//Modulo de consolida<EFBFBD><EFBFBD>o de vendas.
if (UseModVendas()) {
$menuUsuario[] = array('201', 'mnAudiosVendas', '1', '<EFBFBD>udios ' . MenuVendas(), 'index.php?idProg=327', '', '173', '1', '0', '', '327');
$menuUsuario[] = array('206', 'mnRelChamadas', '1', 'Relat<EFBFBD>rio Chamadas', 'index.php?idProg=336', '', '173', '1', '0', '', '336');
$menuUsuario[] = array('207', 'mnRelChamadasVenda', '1', 'Relat<EFBFBD>rio Chamadas Venda', 'index.php?idProg=337', '', '173', '1', '0', '', '337');
}
//RELATORIO TRANSBORDO
$menuUsuario[] = array('202', 'mnRelTransbordo', '1', 'Transbordo', 'index.php?idProg=324', '', '18', '1', '0', '', '324');
$menuUsuario[] = array('203', 'mnCorrecoes', '1', 'Corre<EFBFBD><EFBFBD>es', 'index.php?idProg=325', '', '196', '1', '0', '', '325');
$menuUsuario[] = array('204', 'mnNaoPerturbe', '1', 'N<EFBFBD>o Perturbe', 'index.php?idProg=328', '', '109', '1', '0', '', '328');
$menuUsuario[] = array('205', 'mnListaDiscador', '1', 'Lista Discador', 'index.php?idProg=331', '', '109', '1', '0', '', '331');
// ------------------- '206' -- ESTA EM USO ALGAR
// ------------------- '207' -- ESTA EM USO ALGAR
// $menuUsuario[] = array('208', 'mnPrevendaLista', '1', 'Lista Pr<EFBFBD>-venda', 'index.php?idProg=338', 'Lista Pr<EFBFBD>-Venda', '209', '1', '0', '', '338');
// $menuUsuario[] = array('209', 'mnPreVenda', '1', 'Pr<EFBFBD>-Venda', 'index.php?idProg=58&idMenu=209&menuNome=' . 'Pr<EFBFBD>-Venda', '', '', '1', '0', '6', '58');
// $menuUsuario[] = array('210', 'mnPreVendaPermissao', '1', 'Pr<EFBFBD>-Venda Permiss<EFBFBD>o', 'index.php?idProg=338&prmPopup=1', '', '209', '1', '0', '6', '340');
// $menuUsuario[] = array('211', 'mnRelPreVenda', '1', 'Relat<EFBFBD>rios Pr<EFBFBD>-Venda', 'index.php?idProg=351', 'Relat<EFBFBD>rio Pr<EFBFBD>-Venda', '209', '1', '0', '6', '340');
// $menuUsuario[] = array('212', 'mnRelComissao', '1', 'Relat<EFBFBD>rios Comiss<EFBFBD>o', 'index.php?idProg=352', 'Relat<EFBFBD>rios Comiss<EFBFBD>o', '209', '1', '0', '6', '340');
if (UseModVendas()) {
$menuUsuario[] = array('215', 'mnDashboard', '1', 'Dashboard ' . MenuVendas(), 'index.php?idProg=358', '', '173', '1', '0', '', '358');
}
$menuUsuario[] = array('214', 'mnSimplesChat', '1', 'ChannelChat', 'index.php?idProg=355', '', '1', '1', '0', '', '355');
$menuUsuario[] = array('217', 'mnSimplesChatAdm', '0', 'Administrador SimplesChat', 'index.php?idProg=359', '', '1', '1', '0', '', '359');
$menuUsuario[] = array('218', 'mnSimplesChatSup', '0', 'Supervisor SimplesChat', 'index.php?idProg=360', '', '1', '1', '0', '', '360');
$menuUsuario[] = array('219', 'mnSimplesChatAgt', '0', 'Agente SimplesChat', 'index.php?idProg=361', '', '1', '1', '0', '', '361');
$menuUsuario[] = array('220', 'mnLgpdAdm', '0', 'Administra LGPD', 'index.php?idProg=364', '', '1', '1', '0', '', '364');
$menuUsuario[] = array('221', 'mnpermEditaClassificado', '0', 'Permite Editar Classifica<EFBFBD><EFBFBD>o', 'index.php?idProg=368', '', '1', '1', '0', '', '368');
$menuUsuario[] = array('222', 'mnOrganizacao', '1', 'Organiza<EFBFBD><EFBFBD>o', 'index.php?idProg=369', '', '10', '1', '0', '', '369');
$menuUsuario[] = array('112', 'mnSair', '1', 'Sair', 'index.php?idProg=-1&DEBUG=0', '', '', '1', '1', '10', '-1');
$query = "select count(*) from pbx_funcoes";
$result = pg_query($conn, $query);
$row = pg_fetch_row($result);
if ($row[0] != count($menuUsuario) || IsAdmin()) {
$result = pg_query($conn, 'begin');
//transacao iniciada com sucesso
if ($result) {
$query = "truncate table pbx_funcoes_internas";
$result = pg_query($conn, $query);
$query = "truncate table pbx_funcoes";
if ($result) {
$result = pg_query($conn, $query);
}
//registro apgados com sucesso
if ($result) {
$permissions = existLicense($conn);
foreach ($menuUsuario as $key => $value) {
if (!in_array($value[0], $permissions) && ($value[0] != '112')) {
unset($menuUsuario[$key]);
}
}
//recria o menu no banco de dados
foreach ($menuUsuario as $key => $value) {
$query = "insert into pbx_funcoes(fun_id, fun_nome, fun_menu, fun_menu_text, fun_menu_url, fun_menu_img, fun_id_pai, fun_status, fun_public, ord, id_prog)
values( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )";
//pega valores do menu
$vMenu = $menuUsuario[$key];
//Verifica se <EFBFBD> um link para nova janela
//$novaJan = (stripos($vMenu[4], 'NovaJanela') !== false);
$query = sprintf(
$query,
QuotedStr($vMenu[0]),
empty($vMenu[1]) ? 'null' : QuotedStr($vMenu[1]),
empty($vMenu[2]) ? '0' : QuotedStr($vMenu[2]),
empty($vMenu[3]) ? 'null' : QuotedStr(($vMenu[3])), //utf8_encode
empty($vMenu[4]) ? 'null' : QuotedStr($vMenu[4]),
empty($vMenu[5]) ? 'null' : QuotedStr($vMenu[5]),
empty($vMenu[6]) ? 'null' : QuotedStr($vMenu[6]),
empty($vMenu[7]) ? '0' : QuotedStr($vMenu[7]),
empty($vMenu[8]) ? '0' : QuotedStr($vMenu[8]),
empty($vMenu[9]) ? 'null' : QuotedStr($vMenu[9]),
QuotedStr($vMenu[10])
);
$result = pg_query($conn, $query);
if (!$result) {
break;
}
}
/*
* Relaciona as funcoes internas
*/
include("util/funcoesInternas.php");
/*
* Cria m<EFBFBD>dulo de sincroniza<EFBFBD><EFBFBD>o
*/
if (IsServerMaster()) {
CriaPerfilSincronizacao($conn);
}
}
}
/*
* Cria perfil default
*/
//$result = $result && CriaPerfil($conn, 'administrador', 'pbx_administrador_funcoes');
//$result = $result && CriaPerfil($conn, 'supervisor', 'pbx_supervisor_funcoes');
//$result = $result && CriaPerfil($conn, 'agente', 'pbx_agente_funcoes');
if ($result) {
pg_query($conn, 'commit');
} else {
//echo sprintf("Cmd: %s\nMetodo: %s\n", $query, GetErrorLast('Funcoes') ); exit;
pg_query($conn, 'rollback');
}
}
if (IsAdmin()) {
CriaUserApi($conn);
}
}
function CriaPerfilSincronizacao($conn)
{
$result = true;
$query = "delete from pbx_grupo_funcoes where gp_id = (select gp_id from pbx_grupo where gp_nome = 'SincContaSenha' )";
$result = $result && pg_query($conn, $query);
$query = "delete from pbx_grupo_usuario where gp_id = (select gp_id from pbx_grupo where gp_nome = 'SincContaSenha')";
$result = $result && pg_query($conn, $query);
$query = "delete from pbx_grupo where gp_nome = 'SincContaSenha'";
$result = $result && pg_query($conn, $query);
$query = "delete from pbx_usuarios where apelido = 'sinccontasenha'";
$result = $result && pg_query($conn, $query);
$senhaSinc = md5("s3ncC0nt@S2nh@");
$checkVl = md5("sinccontasenha");
$query = "INSERT INTO pbx_usuarios (nome, apelido, matricula, flag, admin, senha, supervisor, agente, email, status, delete_, def_senha, senha_expira, senha_dias_expira, check_vl)
VALUES ('sincContaSenha', 'sinccontasenha', '0000', 1, false, '$senhaSinc', false, false, '', true, 0, 0, 0, 0, '$checkVl' )";
$result = $result && pg_query($conn, $query);
$query = "INSERT INTO pbx_grupo (gp_nome, gp_status, gp_user) VALUES ('SincContaSenha', 1, 0)";
$result = $result && pg_query($conn, $query);
$query = "INSERT INTO pbx_grupo_usuario (user_id, gp_id)
values (
(select id from pbx_usuarios where apelido = 'sinccontasenha'),
(select gp_id from pbx_grupo where gp_nome = 'SincContaSenha')
)";
$result = $result && pg_query($conn, $query);
$query = " insert into pbx_grupo_funcoes(gp_id, fun_id)
select (select gp_id from pbx_grupo where gp_nome = 'SincContaSenha' ) as gp_id, fun_id
from pbx_funcoes
where fun_nome in('mnPbxPbx','mnPbxCadastro','mnPbxOutros','mnPbxOutrosEmpresas','mnPbxOutrosDepartamentos','mnPbxOutrosContaSenha')";
return ($result && pg_query($conn, $query));
}
//function CriaPerfil($conn, $grupo, $tableFuncoes) {
// /*
// * Apaga perfil existente
// */
// $query = "delete from pbx_grupo_funcoes where gp_id = (select gp_id from pbx_grupo where upper(gp_nome) = upper('$grupo'))";
// $result = pg_query($conn, $query);
// if (!$result)
// return false;
//
// /*
// * Insere novo perfil com base a funcoes pre-cadastradas nas tableas pbx_administrador_funcoes, pbx_supervisor_funcoes, pbx_agente_funcoes
// */
// $query = "insert into pbx_grupo_funcoes(gp_id, fun_id)
// select (select gp_id from pbx_grupo where upper(gp_nome) = upper('$grupo') ) as gp_id,
// fun_id
// from pbx_funcoes
// where fun_nome in(select fun_nome from $tableFuncoes)";
// $result = pg_query($conn, $query);
// if (!$result)
// return false;
//
// return true;
//}
function GetLinkNovaJanela($width, $height, $link, $nomeJan, $atrib = '')
{
SetDimensoes($width, $height);
$janW = round($GLOBALS["janW"]);
$janH = round($GLOBALS["janH"]);
$atrib = trim($atrib);
if (empty($atrib))
$atrib = 'resizable=YES,scrollbars=YES';
$link = sprintf("javaScript:NovaJanela(\\'%s&janH=%s\\', \\'%s\\',\\'%s\\',\\'%s\\', \\'%s\\')", $link, $janH, $nomeJan, $janW, $janH, $atrib);
return $link;
}
function IsSuper()
{
return ($_SESSION["SSsuper"] == 1);
}
function IsUserAdmin()
{
$org_id = GetOrganizacao();
$query = sprintf("SELECT count(*) FROM pbx_grupo_usuario
WHERE gp_id = (SELECT gp_id FROM pbx_grupo WHERE gp_nome = 'ADMINISTRADOR' AND org_id = {$org_id})
AND user_id = '%s'", GetIdUser());
$result = pg_query($query);
$row = @pg_fetch_row($result);
return $row[0] ? true : false;
}
function IsAdmin()
{
return strtoupper(GetLogin()) == 'ADMIN';
}
function AgenteON($idUser = null)
{
if ($idUser != null) {
$query = sprintf("SELECT '' FROM pbx_supervisor_agentes a
INNER JOIN pbx_usuarios b ON a.matricula = b.matricula
WHERE b.id = '%s'", $idUser);
return pg_num_rows(pg_query($query));
} else {
$query = sprintf("SELECT '' FROM pbx_supervisor_agentes WHERE matricula = '%s' AND ramal = '%s' ", GetMatricula(), GetRamalMonitorar(RAMAL_MONITOR_AGENTE));
return pg_num_rows(pg_query($query));
}
//return GetStatusAgente() && pg_num_rows(pg_query($query));
//return isset($_SESSION[SS_AGENTE_CONECTADO]) && $_SESSION[SS_AGENTE_CONECTADO];
}
function GetMaxAgentePausa($dac = 0)
{
if ($dac) {
$query = "select max_agente_pausa from pbx_queues_grupos where id = '$dac'";
$result = pg_query($query);
$row = @pg_fetch_row($result);
return $row[0];
}
return isset($_SESSION['prm_max_agente_pausa']) ? $_SESSION['prm_max_agente_pausa'] : 0;
}
function VerificaRamalConectado($nome)
{
$query = "select count(*) from pbx_supervisor_agentes where ramal = '$nome' ";
$result = pg_query($query);
$row = @pg_fetch_row($result);
return $row[0];
}
function VerificaMaxAgentePausa($dac)
{
/*
* Busca a configura<EFBFBD><EFBFBD>o da fila
*/
$percPausa = GetMaxAgentePausa($dac);
/*
* Se n<EFBFBD>o tiver configura<EFBFBD><EFBFBD>o na fila pega config
*/
//if(!$percPausa){ $percPausa = GetMaxAgentePausa(0); }
/*
* Se n<EFBFBD>o houver configura<EFBFBD><EFBFBD>o Padr<EFBFBD>o retorna false. N<EFBFBD>o vai calcular o bloqueio!
*/
if (!$percPausa)
return false;
//if(IsAdmin()) echo "calc max pausa " . GetPercAgentePausa() . "<br>";
return GetPercAgentePausa($dac) >= $percPausa;
}
function GetPercAgentePausa($dac)
{
$query = "select count(*) as total, coalesce(sum(case when(status = 'PAUSA')then 1 else 0 end), 0) as pausa from pbx_supervisor_agentes where dac = (select nome from pbx_dacs where id = '$dac')";
//if(IsAdmin()) echo $query;
$result = pg_query($query);
$row = @pg_fetch_array($result);
$total = $row['total'];
$pausa = $row['pausa'];
//if(IsAdmin()) echo "toal = " . $total . " pausa = " . $pausa . "calc = " . ($pausa * 100.0) / $total ."roud = " . round(($pausa * 100.0) / $total);
return !$total ? 0 : round(($pausa * 100.0) / $total);
}
function IsSysAdmin($user = '')
{
if (!empty($user))
return strtoupper($user) == 'ADMINISTRADOR';
else
return strtoupper(GetLogin()) == 'ADMINISTRADOR';
}
function GetIdSysAdmin($dbcon)
{
$query = "select id from pbx_usuarios where upper(apelido) = 'ADMINISTRADOR'";
$result = pg_query($dbcon, $query);
$row = @pg_fetch_row($result);
return $row[0];
}
function __GetLoginFromId($id)
{
if ($id && $id < 0) {
$gpId = abs($id);
$query = "select gp_nome from pbx_grupo where gp_id = '$gpId'";
} else {
$query = "select apelido from pbx_usuarios where id = '$id'";
}
$result = pg_query($query);
$row = @pg_fetch_row($result);
return $row[0];
}
function GetIdFromLogin($dbcon, $login)
{
$query = "select id from pbx_usuarios where upper(apelido) = upper('$login') and delete_ = 0";
$result = pg_query($dbcon, $query);
$row = @pg_fetch_row($result);
return $row[0];
}
function CriaUserApi($dbcon)
{
$query = "select id from pbx_usuarios where upper(apelido) = upper('user.api')";
$result = pg_query($dbcon, $query);
if ($result && !pg_num_rows($result)) {
$query = "insert into pbx_usuarios(nome,apelido,matricula, check_vl)
values ('USERAPI', 'user.api', (select (max(matricula::int) + 1)::text from pbx_usuarios), md5(lower('user.api')))";
pg_query($dbcon, $query);
}
}
function _Menu($dbcon)
{
// fun_id, fun_nome, fun_menu, fun_menu_text, fun_menu_url, fun_menu_img, fun_id_pai, fun_status, fun_public
// 2;"mnAgente";1;"Agente";"index.php?idProg=14";"";1;1;0
$idUsuario = GetIdUser();
if (!$idUsuario)
return;
$startMenu = 0;
$makeMenu = " var MENU_ITEMS = [\n";
$queryNivel1 = GetQueryMenu($idUsuario, 0, 1);
$result = pg_query($dbcon, $queryNivel1);
while ($row = pg_fetch_array($result)) {
/*
* Nivel 1
*/
$makeMenu .= (!$startMenu ? "" : ", ") . sprintf("[%s, %s, %s,", IsNull($row["fun_menu_text"], 'null', 1), IsNull($row["fun_menu_url"], 'null', 1), 'null', 'null');
$startMenu++;
/*
* Nivel 2
*/
$idPai = $row["fun_id"];
$queryNivel2 = GetQueryMenu($idUsuario, $idPai);
$resultNivel2 = pg_query($dbcon, $queryNivel2);
$existeNivel2 = pg_num_rows($resultNivel2) > 0;
if ($existeNivel2) {
$makeMenu .= "\n";
$startMenu2 = 0;
while ($rowNivel2 = pg_fetch_array($resultNivel2)) {
$makeMenu .= (!$startMenu2 ? "" : ", ");
$startMenu2++;
$makeMenu .= sprintf(" [%s, %s, %s,", IsNull($rowNivel2["fun_menu_text"], 'null', 1), IsNull($rowNivel2["fun_menu_url"], 'null', 1), 'null'); //print nivel 2
$idPai = $rowNivel2["fun_id"];
$queryNivel3 = GetQueryMenu($idUsuario, $idPai);
$resultNivel3 = pg_query($dbcon, $queryNivel3);
$existeNivel3 = pg_num_rows($resultNivel3) > 0;
if ($existeNivel3) {
$makeMenu .= "\n";
$startMenu3 = 0;
while ($rowNivel3 = pg_fetch_array($resultNivel3)) {
$makeMenu .= (!$startMenu3 ? "" : ", ");
$startMenu3++;
$makeMenu .= sprintf(" [%s, %s, %s, ", IsNull($rowNivel3["fun_menu_text"], 'null', 1), IsNull($rowNivel3["fun_menu_url"], 'null', 1), 'null');
$idPai = $rowNivel3["fun_id"];
$queryNivel4 = GetQueryMenu($idUsuario, $idPai);
$resultNivel4 = pg_query($dbcon, $queryNivel4);
$existeNivel4 = pg_num_rows($resultNivel4) > 0;
if ($existeNivel4) {
$makeMenu .= "\n";
$startMenu4 = 0;
while ($rowNivel4 = pg_fetch_array($resultNivel4)) {
$makeMenu .= (!$startMenu4 ? "" : ", ");
$startMenu4++;
$makeMenu .= sprintf(" [%s, %s, %s,", IsNull($rowNivel4["fun_menu_text"], 'null', 1), IsNull($rowNivel4["fun_menu_url"], 'null', 1), 'null');
$idPai = $rowNivel4["fun_id"];
$queryNivel5 = GetQueryMenu($idUsuario, $idPai);
$resultNivel5 = pg_query($dbcon, $queryNivel5);
$existeNivel5 = pg_num_rows($resultNivel5) > 0;
if ($existeNivel5) {
$makeMenu .= "\n";
$startMenu5 = 0;
while ($rowNivel5 = pg_fetch_array($resultNivel4)) {
$makeMenu .= (!$startMenu5 ? "" : ", ");
$startMenu5++;
$makeMenu .= sprintf(" [%s, %s, %s, null]\n", IsNull($rowNivel5["fun_menu_text"], 'null', 1), IsNull($rowNivel5["fun_menu_url"], 'null', 1), 'null');
}
}
$makeMenu .= ($existeNivel5 ? " ]\n" : "null]\n"); //fim topo
}
}
$makeMenu .= ($existeNivel4 ? " ]\n" : "null]\n"); //fim topo
}
}
$makeMenu .= ($existeNivel3 ? " ]\n" : "null]\n"); //nivel 2
}
}
$makeMenu .= ($existeNivel2 ? "]\n" : "null]\n"); //fim topo
}
$makeMenu .= "];";
return $makeMenu;
}
function GetQueryMenu($idUsuario, $idPai, $menuBase = 0)
{
$query = IsAdmin() ? " select * from pbx_funcoes where coalesce(fun_id_pai, 0) = $idPai and fun_staus = 1 order by ord" :
" select distinct a.fun_id, a.fun_nome, a.fun_menu, a.fun_menu_text, a.fun_menu_url, a.fun_menu_img, a.fun_id_pai, a.fun_status, a.fun_public, a.ord
from(
select a.fun_id, a.fun_nome, a.fun_menu, a.fun_menu_text, a.fun_menu_url, a.fun_menu_img, a.fun_id_pai, a.fun_status, a.fun_public, a.ord
from pbx_funcoes a
union all
select c.fun_id, c.fun_nome, c.fun_menu, c.fun_menu_text, c.fun_menu_url, c.fun_menu_img, c.fun_id_pai, c.fun_status, c.fun_public, c.ord
from pbx_funcoes b, pbx_funcoes c
where c.fun_id_pai = b.fun_id
) a, pbx_grupo_usuario b, pbx_grupo_funcoes c, pbx_usuarios d
where b.user_id = d.id
and c.gp_id = b.gp_id
and a.fun_id = c.fun_id
and d.id = '$idUsuario'
and a.fun_id_pai = '$idPai' and b.fun_status = 1 and c.fun_stasus = 1 " .
(!$menuBase ? "" :
" union all
select a.fun_id, a.fun_nome, a.fun_menu, a.fun_menu_text, a.fun_menu_url, a.fun_menu_img, a.fun_id_pai, a.fun_status, a.fun_public, a.ord
from pbx_funcoes a
where fun_public = 1
and (coalesce(fun_id_pai, 0) = 0)
and fun_status = 1
order by ord
");
return $query;
}
function GetItensMenu($tpLayout = 0)
{
/*
"mnAudio" ;"mnSupervisor" ;"mnConfiguracao" ;"mnCadastro" ;"mnSistema" ;"mnAgente" ;"mnUsuario" ;
"mnClassificacao" ;"mnRelatorio" ;"mnRelProdAgente" ;"mnRelTransAgente" ;"mnMetaMensal" ;"mnMetaMensaAneel" ;
"mnMetaDiaria" ;"mnMetaDiariaAneel" ;"mnTransferencia" ;"mnResumoFone" ;"mnTrocaSenha" ; "mnGrupoUsuario" ;
*/
if ($tpLayout == 1) {
return "";
} else {
$_SESSION["SStreView"] = 0;
//return Menu($GLOBALS["dbcon"]);
return MontaMenu(0, GetIdUser(), 1, 0);
}
}
function GetJqToolTip($obj, $text)
{
return "\$('#$obj')
.hover(
function(){
\$('<div class=\"tooltip\"><b>$text</b></div>').prependTo(this);
},
function(){\$('.tooltip')._remove();
}
);";
}
function GetJqTips($obj)
{
//return "$('$obj').tooltip();";
return "$('$obj').easyTooltip();";
}
function GetJQuery($j)
{
$result = "<script type=\"text/javascript\">\n
//<![CDATA[ \n";
$result .= "$(document).ready(function() { \n";
foreach ($j as $value)
$result .= $value . " \n";
$result .= "}); \n";
$result .= "// ]]> \n
</script> \n";
return $result;
}
function GetJqCalendario($obj, $tgt)
{
//return "\$('#$obj').click(function(){\$(this).calendario({target:'#$tgt'});})";
return sprintf('$(function() { $( "#%s" ).datepicker({ '
. 'autoSize: true,'
. 'showOn: "button", '
. 'buttonImage: "%s", '
. 'buttonImageOnly: true, '
. 'dateFormat: "dd/mm/yy", '
. 'buttonText: "Select date",'
. 'monthNames: [ "Janeiro", "Fevereiro", "Mar<EFBFBD>o", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" ],'
. 'dayNames: [ "Domingo", "Segunda", "Ter<EFBFBD>a", "Quarta", "Quita", "Sexta", "Sabado" ], '
. 'dayNamesMin: [ "D", "S", "T", "Q", "Q", "S", "S" ]'
. '}); });', ($tgt ? $tgt : 'datepicker'), ($obj ? $obj : 'images/calendar.gif'));
}
function SubsPVirgula($str)
{
return str_replace(";", "{#}", $str);
}
function GetLogoPrinc($tpLayout = 0)
{
$path = "/";
return ($tpLayout == 1) || IsUserConnect() ? "" : "<div id=\"title\">
<table width=\"100%\" border=\"0\" cellspacing=\"10\" cellpadding=\"2\">
<tr>
<td align=\"center\"><img src=\"" . LOGO_HEADER_SITE . "\"></td>
</tr>
</table>
</div> ";
//<a href=\"$path\"><img src=\"imgSite/help48.png\" alt=\"Manual do Sistema\" title=\"Manual do Sistema\" border=\"0\"></a>
//<a href=\"$path\" ><img src=\"imgSite/connection48.png\" alt=\"Quem Somos\" title=\"Quem Somos\" border=\"0\"></a>
}
function GetNavHeader($tpLayout = 0)
{
return $tpLayout == 1 ? "" : "<div id=\"nav_header\"></div>";
}
function GetNavLogin($tpLayout = 0, $dispProgSel = PRM_DEF_SLOGAN)
{
$login = GetLogin();
$matricula = GetMatricula() ? "| Matricula: " . GetMatricula() : '';
$imgUser = IsUserConnect() ? "userOn16.png" : null;
$imgAlt = IsUserConnect() ? "alt=\"Usu<EFBFBD>rio Conectado\" title=\"Usu<EFBFBD>rio Conectado\"" : null;
$img = IsUserConnect() ? "Usu&aacute;rio: <img src=\"imgSite/$imgUser\" $imgAlt align=\"absmiddle\"> $login $matricula" : '';
$selMenu = IsUserConnect() ? "Home /" : '';
return $tpLayout == 1 ? "" : "<div id=\"color_bar\" style=\"width: 100%;border-top-left-radius: 8px;border-top-right-radius: 8px;height: 40px;background: linear-gradient(45deg, #266cfa, #FF1472);\" >
<table width=\"100%\" style=\"width: 100%;\" border=\"0\" cellspacing=\"7\" cellpadding=\"5\">
<tr>
<td valign=\"middle\" align=\"right\" id=\"nav_login\">$img</td>
<td valign=\"middle\" align=\"left\" id=\"dispProg\">$selMenu $dispProgSel</td>
</tr>
</table>
</div>";
}
function GetDispProgSel($idProg)
{
/*
* Display do programa corrente
*/
$idMenu = isset($_REQUEST['idMenu']) ? $_REQUEST['idMenu'] : 0;
$isMenu = 0;
if (($idProg == 58) && ($idMenu)) {
$idProg = $idMenu;
$isMenu = 1;
}
$dispProgSel = array();
$dispProgSel[0] = "Relat<EFBFBD>rio Produ<EFBFBD><EFBFBD>o Agente";
$dispProgSel[1] = $isMenu ? "Sistema" : "Relat<EFBFBD>rio de Meta Mensal Anal<EFBFBD>tico";
$dispProgSel[2] = "Relat<EFBFBD>rio de Meta Di<EFBFBD>ria Aneel";
$dispProgSel[3] = "Relat<EFBFBD>rio Produ<EFBFBD><EFBFBD>o Agente";
$dispProgSel[4] = "Relat<EFBFBD>rio de Meta Mensal";
$dispProgSel[5] = "Relat<EFBFBD>rio de Meta Di<EFBFBD>ria";
$dispProgSel[6] = "Supervisor";
$dispProgSel[7] = "Relat<EFBFBD>rio de Transfer<EFBFBD>ncia";
$dispProgSel[8] = "Relat<EFBFBD>rio de Resumo Fone";
$dispProgSel[9] = "Relat<EFBFBD>rio de Transfer<EFBFBD>ncia"; //ipr
$dispProgSel[10] = $isMenu ? "Cadastro" : "Relat<EFBFBD>rio de Resumo Fone"; //ipr
$dispProgSel[11] = "Resumo Transfer<EFBFBD>ncia Ramal"; //inativo
$dispProgSel[12] = "Relat<EFBFBD>rio de Transfer<EFBFBD>ncia por Agente";
$dispProgSel[13] = "Relat<EFBFBD>rio de Transfer<EFBFBD>ncia por Agente";
$dispProgSel[14] = "Agente";
$dispProgSel[15] = "Agente"; //direciona para tela inicial de agente
$dispProgSel[16] = "Troca de Senha";
$dispProgSel[17] = $isMenu ? "Relat<EFBFBD>rio" : "Bloco de Notas";
$dispProgSel[18] = $isMenu ? "Relat<EFBFBD>rio Call Center" : "Agenda";
$dispProgSel[19] = "Hist<EFBFBD>rico do Agente";
$dispProgSel[20] = "Configura<EFBFBD><EFBFBD>es do Sistema";
$dispProgSel[21] = "Cadastro de Usu<EFBFBD>rio";
$dispProgSel[22] = "Cadastro de Usu<EFBFBD>rio"; //operacoes de banco
$dispProgSel[23] = "<EFBFBD>udio";
$dispProgSel[24] = "Consulta de Dacs"; //inativo
$dispProgSel[25] = "Tranfer<EFBFBD>ncia Agente Detalhe";
$dispProgSel[26] = "Comunica<EFBFBD><EFBFBD>o Asterisk";
$dispProgSel[27] = "Classifica<EFBFBD><EFBFBD>o de Atendimento";
$dispProgSel[28] = $isMenu ? "Relat<EFBFBD>rio Call Center - Metas" : "Classifica<EFBFBD><EFBFBD>o de Atendimento";
$dispProgSel[29] = "Classifica<EFBFBD><EFBFBD>o de Atendimento ";
$dispProgSel[30] = "Classifica<EFBFBD><EFBFBD>o de Atendimento ";
$dispProgSel[31] = "Classifica<EFBFBD><EFBFBD>o de Atendimento ";
$dispProgSel[32] = "Meta Mensal";
$dispProgSel[33] = "Meta Di<EFBFBD>ria";
$dispProgSel[34] = "Meta Mensal";
$dispProgSel[35] = "Meta Di<EFBFBD>ria";
$dispProgSel[36] = "Administra<EFBFBD><EFBFBD>o de Permiss<EFBFBD>es";
$dispProgSel[284] = "Mesa Operadora";
$dispProgSel[37] = "Chamadas Saintes Ramal";
$dispProgSel[38] = "Chamadas Saintes Ramal";
$dispProgSel[39] = "Chamadas Saintes Conta";
$dispProgSel[40] = "Chamadas Saintes Conta";
$dispProgSel[41] = "Totalizador Chamadas Saintes Ramal";
$dispProgSel[42] = "Menu Chamadas Saintes";
$dispProgSel[43] = "Chamadas Ramal a Ramal";
$dispProgSel[44] = "Chamadas Ramal a Ramal";
$dispProgSel[45] = GetNomeCadCli();
$dispProgSel[46] = "Indisponibilidade";
$dispProgSel[47] = "Ramal a Ramal";
$dispProgSel[48] = "Ramal a Ramal";
$dispProgSel[49] = "Chamadas Fora do Hor<EFBFBD>rio";
$dispProgSel[50] = "Chamadas Fora do Hor<EFBFBD>rio";
$dispProgSel[51] = "Classifica<EFBFBD><EFBFBD>o de Atendimento";
// $dispProgSel[52] = "Relat<EFBFBD>rio de " . GetNomeCadCli();
$dispProgSel[53] = "Relat<EFBFBD>rio de " . GetNomeCadCli();
$dispProgSel[54] = GetNomeCadCli() . " Detalhes";
$dispProgSel[55] = "Cadastro Geral";
$dispProgSel[56] = "Verifica<EFBFBD><EFBFBD>o de Acesso";
$dispProgSel[57] = "Chamadas Saintes";
$dispProgSel[58] = "Chamadas Entrantes";
$dispProgSel[59] = "Chamadas Entrantes Geral";
$dispProgSel[60] = "Chamadas Entrantes Ramal";
$dispProgSel[61] = $isMenu ? "PABX" : "Chamadas Entrantes Conta";
$dispProgSel[62] = $isMenu ? "PABX Chamadas" : "Chamadas Entrantes Conta";
$dispProgSel[63] = "Totalizador de Chamadas Entrantes";
$dispProgSel[64] = "Totalizador de Chamadas Entrantes";
$dispProgSel[65] = "Lista Usu<EFBFBD>rios";
$dispProgSel[66] = $isMenu ? "PABX Cadastro" : "Lista Usu<EFBFBD>rios";
$dispProgSel[67] = "Chamadas Saintes por Centro de Custo";
$dispProgSel[68] = "Chamadas Saintes por Centro de Custo";
$dispProgSel[69] = "Chamadas Saintes por Centro de Custo";
$dispProgSel[70] = "Chamadas Saintes por Tipo de Liga<EFBFBD><EFBFBD>o";
$dispProgSel[71] = "Chamadas Saintes por Tipo de Liga<EFBFBD><EFBFBD>o";
$dispProgSel[101] = "Relat<EFBFBD>rio Saintes por Tipo de Liga<EFBFBD><EFBFBD>o";
$dispProgSel[72] = "Chamadas Entrantes por Tipo de Liga<EFBFBD><EFBFBD>o";
$dispProgSel[103] = "Chamadas Entrantes por Tipo de Liga<EFBFBD><EFBFBD>o";
$dispProgSel[73] = "Chamadas Entrantes por Tipo de Liga<EFBFBD><EFBFBD>o";
$dispProgSel[74] = "Chamadas Saintes Mais Discados";
$dispProgSel[75] = "Chamadas Entrantes Mais Discados";
$dispProgSel[76] = $isMenu ? "PABX/Outros" : "Chamadas Encaminhadas Caixa Postal";
$dispProgSel[77] = "Chamadas Encaminhadas Caixa Postal";
$dispProgSel[78] = "Chamadas Entrantes N<EFBFBD>o Atendidas";
$dispProgSel[79] = "Chamadas Entrantes N<EFBFBD>o Atendidas";
$dispProgSel[80] = "Lista Chamadas para Siga-me Externo";
$dispProgSel[81] = "Lista Chamadas para Siga-me Externo";
$dispProgSel[82] = "Monitor de Opera<EFBFBD><EFBFBD>es";
$dispProgSel[83] = "...";
$dispProgSel[84] = $isMenu ? "PABX Ramais" : "Grupos de Usu<EFBFBD>rios";
$dispProgSel[85] = "...";
$dispProgSel[86] = "Motivos de Pausas";
$dispProgSel[278] = "Servi<EFBFBD>os de Chamadas";
$dispProgSel[87] = "Totalizador Tipo de Liga<EFBFBD><EFBFBD>o Usu<EFBFBD>rio";
$dispProgSel[88] = "Totalizador Tipo de Liga<EFBFBD><EFBFBD>o Usu<EFBFBD>rio";
$dispProgSel[89] = $isMenu ? "PABX Rotas" : "Chamadas Originadas por Agente";
$dispProgSel[90] = "Chamadas Originadas por Agente";
$dispProgSel[91] = "Chamadas Abandonadas na Fila";
$dispProgSel[92] = $isMenu ? "PABX Troncos" : "Chamadas Abandonadas na Fila";
$dispProgSel[93] = "Chamadas Abandonadas na Ura";
$dispProgSel[94] = "Chamadas Abandonadas na Ura";
$dispProgSel[95] = "Chamadas Totalizadas por DDD";
$dispProgSel[96] = "Chamadas Totalizadas por DDD";
$dispProgSel[97] = "Desempenho de Opera<EFBFBD><EFBFBD>o";
$dispProgSel[98] = "Desempenho de Opera<EFBFBD><EFBFBD>o";
$dispProgSel[99] = "PABX Configura<EFBFBD><EFBFBD>es";
$dispProgSel[105] = "Manuten<EFBFBD><EFBFBD>o de Sites";
$dispProgSel[108] = "Chamadas Desligadas A/B";
$dispProgSel[109] = $isMenu ? "Discador" : "Chamadas Desligadas A/B";
$dispProgSel[110] = "Rechamadas";
$dispProgSel[111] = "Rechamadas";
$dispProgSel[114] = "Agenda";
$dispProgSel[112] = "Cadastro de Campanhas";
$dispProgSel[121] = "Administra<EFBFBD><EFBFBD>o de Permiss<EFBFBD>es";
$dispProgSel[125] = "Campanha Retorno";
$dispProgSel[127] = "Ferramentas";
$dispProgSel[130] = "Pesquisa";
$dispProgSel[132] = "Pr<EFBFBD>-processamento de lista";
$dispProgSel[137] = "Tarifa<EFBFBD><EFBFBD>o Portabilidade";
$dispProgSel[139] = "Agenda Departamentos";
$dispProgSel[140] = "Agenda Ramais";
$dispProgSel[150] = $isMenu ? "Pr<EFBFBD>-Pago" : "Relat<EFBFBD>rio de Classifica<EFBFBD><EFBFBD>o por Agente";
$dispProgSel[152] = "Relat<EFBFBD>rio de Meta Anual Anal<EFBFBD>tico";
$dispProgSel[154] = $isMenu ? "Portabilidade" : "Relat<EFBFBD>rio de Classifica<EFBFBD><EFBFBD>o Mensal";
$dispProgSel[156] = "Backup";
$dispProgSel[190] = "Cadastro de Integra<EFBFBD><EFBFBD>o";
$dispProgSel[159] = "Totalizador por Centro de Custo";
$dispProgSel[160] = "Totalizador por Centro de Custo";
$dispProgSel[161] = "Totalizador por Centro de Custo";
$dispProgSel[169] = "Totalizador por Centro de Custo";
$dispProgSel[171] = "Totalizador por Centro de Custo";
$dispProgSel[163] = "Chamadas Saintes Geral";
$dispProgSel[165] = "Relat<EFBFBD>rio de Classifica<EFBFBD><EFBFBD>o por Munic<EFBFBD>pio";
$dispProgSel[166] = "Relat<EFBFBD>rio de Classifica<EFBFBD><EFBFBD>o por Munic<EFBFBD>pio";
$dispProgSel[172] = "Detalhamento de Chamadas";
$dispProgSel[175] = "Relat<EFBFBD>rio de Pausas Detalhado";
$dispProgSel[176] = "Relat<EFBFBD>rio de Pausas Detalhado";
$dispProgSel[178] = "Parametriza<EFBFBD><EFBFBD>o do Workflow";
$dispProgSel[193] = "Relat<EFBFBD>rio de Cobran<EFBFBD>a";
$dispProgSel[181] = "Pesquisa ACW";
$dispProgSel[185] = "Pesquisa Libera<EFBFBD><EFBFBD>o";
$dispProgSel[187] = "Relat<EFBFBD>rio Pesquisa";
$dispProgSel[188] = "Relat<EFBFBD>rio Pesquisa Agente";
$dispProgSel[197] = "Contratos Operadora";
$dispProgSel[198] = "Tarifa<EFBFBD><EFBFBD>o Parametros";
$dispProgSel[199] = "Operadoras Dispon<EFBFBD>veis";
$dispProgSel[205] = "Tarifa<EFBFBD><EFBFBD>o por Ramal";
$dispProgSel[206] = "Tarifa<EFBFBD><EFBFBD>o por Conta";
$dispProgSel[207] = "Tarifa<EFBFBD><EFBFBD>o por Fatura";
$dispProgSel[208] = "Relat<EFBFBD>rio Pesquisa <EFBFBD>udio";
$dispProgSel[212] = "Pr<EFBFBD>-pago Ramal";
$dispProgSel[213] = "Pr<EFBFBD>-pago Conta";
$dispProgSel[214] = "Pr<EFBFBD>-pago Ramal";
$dispProgSel[215] = "Pr<EFBFBD>-pago Conta";
$dispProgSel[216] = "Portabilidade";
$dispProgSel[217] = "Monitor da Portabilidade";
$dispProgSel[218] = "Backup";
$dispProgSel[219] = "Backup Destino";
$dispProgSel[220] = "Backup Destino";
$dispProgSel[221] = "Backup Configura<EFBFBD><EFBFBD>es";
$dispProgSel[222] = "Backup Configura<EFBFBD><EFBFBD>es";
$dispProgSel[223] = "Backup Monitor";
$dispProgSel[224] = "Backup Manual";
$dispProgSel[225] = "Relat<EFBFBD>rio de Chamadas Ramal";
$dispProgSel[226] = "Relat<EFBFBD>rio de Chamadas Ramal";
$dispProgSel[229] = "Relat<EFBFBD>rio de Chamadas Abandonadas na Fila";
$dispProgSel[227] = "Relat<EFBFBD>rio de Recebidas Agente";
$dispProgSel[262] = "Relat<EFBFBD>rio de Indicadores MP";
$dispProgSel[266] = "Relat<EFBFBD>rio Metas Dia da Semana";
$dispProgSel[270] = "Retarifa<EFBFBD><EFBFBD>o de Chamadas";
$dispProgSel[273] = "Agentes Horas Trabalhadas";
$dispProgSel[274] = "Status dos Contatos Discados";
$dispProgSel[280] = "Funil de Vendas";
$dispProgSel[285] = "Regionais";
$dispProgSel[289] = "Resumo das Chamadas por Dac";
$dispProgSel[290] = "Resumo das Chamadas Servi<EFBFBD>o";
$dispProgSel[291] = "<EFBFBD>ndices de Atendimento por DAC";
$dispProgSel[292] = "<EFBFBD>ndices de Atendimento por Servi<EFBFBD>os";
$dispProgSel[293] = "Metas Mensais por Servi<EFBFBD>o";
$dispProgSel[294] = "Metas Di<EFBFBD>ria por Servi<EFBFBD>o";
$dispProgSel[300] = "Desempenho por DAC";
$dispProgSel[301] = "Desempenho por Servi<EFBFBD>o";
$dispProgSel[302] = "Relat<EFBFBD>rio Geral de URA";
$dispProgSel[303] = "Entradas Fila e Contextos";
$dispProgSel[304] = "Consulta Atividades";
$dispProgSel[306] = "Detalhamento URA";
$dispProgSel[307] = "Monitor Chamadas";
$dispProgSel[308] = "Resumo Geral DAC";
$dispProgSel[309] = "Entrantes por DDD";
$dispProgSel[314] = "Manuais do Sistema";
$dispProgSel[316] = "Centrais";
$dispProgSel[317] = "Atualiza<EFBFBD><EFBFBD>es Homologadas";
$dispProgSel[320] = "Relat<EFBFBD>rio Sem Retorno";
$dispProgSel[321] = "URA Desempenho";
$dispProgSel[323] = "Relat<EFBFBD>rio URA Detalhes";
$dispProgSel[324] = "Relat<EFBFBD>rio Transbordo";
$dispProgSel[325] = "Corre<EFBFBD><EFBFBD>es";
$dispProgSel[327] = "<EFBFBD>udios " . MenuVendas();
$dispProgSel[328] = "N<EFBFBD>o Perturbe";
$dispProgSel[329] = "N<EFBFBD>o Perturbe";
$dispProgSel[331] = "Lista Discador";
$dispProgSel[332] = "Lista Discador Arquivo";
$dispProgSel[336] = "Relat<EFBFBD>rio de Chamadas";
$dispProgSel[338] = "Lista Pr<EFBFBD>-venda";
$dispProgSel[351] = "Relat<EFBFBD>rio Pr<EFBFBD>-venda";
$dispProgSel[352] = 'Relat<EFBFBD>rios Comiss<EFBFBD>o';
$dispProgSel[353] = 'Atendimento WhatsApp';
$dispProgSel[355] = 'Simples WhatsApp';
$dispProgSel[356] = 'Simples Chat';
$dispProgSel[358] = 'Dashboard';
$dispProgSel[365] = 'Recebidas Agente e Servi<EFBFBD>os';
$dispProgSel[366] = 'Relat<EFBFBD>rio Chamadas Geral';
$dispProgSel[369] = 'Cadastro Organiza<EFBFBD><EFBFBD>o';
$dispProgSel[10001] = "Cadastro de Agentes PBX";
$dispProgSel[10002] = "Cadastro de Filas";
$dispProgSel[10004] = "Cadastro de Agenda";
$dispProgSel[11004] = "Cadastro de Agenda";
$dispProgSel[10006] = "Fila Grupos";
$dispProgSel[10007] = "Cadastro de An<EFBFBD>ncios";
$dispProgSel[11007] = "Cadastro de An<EFBFBD>ncios";
$dispProgSel[10009] = "Cadastro de Ramais Sip";
$dispProgSel[11009] = "Cadastro de Ramais Sip";
//$dispProgSel[10010] = "Cadastro de Ramais Iax";
//$dispProgSel[11010] = "Cadastro de Ramais Iax";
//$dispProgSel[10011] = "Cadastro de Ramais Dgv";
//$dispProgSel[11011] = "Cadastro de Ramais Dgv";
//$dispProgSel[10012] = "Cadastro de Ramais Pbx";
//$dispProgSel[11012] = "Cadastro de Ramais Pbx";
$dispProgSel[10014] = "Cadastro de Troncos Sip";
$dispProgSel[11014] = "Cadastro de Troncos Sip";
$dispProgSel[10015] = "Cadastro de Troncos Iax";
$dispProgSel[11015] = "Cadastro de Troncos Iax";
//$dispProgSel[10016] = "Cadastro de Troncos Dgv";
//$dispProgSel[11016] = "Cadastro de Troncos Dgv";
$dispProgSel[10017] = "Cadastro de Rotas de Entrada";
$dispProgSel[11017] = "Cadastro de Rotas de Entrada";
$dispProgSel[10018] = "Cadastro de Rotas de Sa<EFBFBD>da";
$dispProgSel[11018] = "Cadastro de Rotas de Sa<EFBFBD>da";
$dispProgSel[10019] = "Cadastro de Disa";
$dispProgSel[11019] = "Cadastro de Disa";
$dispProgSel[10020] = "Cadastro de Callback";
$dispProgSel[11020] = "Cadastro de Callback";
$dispProgSel[10022] = "Cadastro de M<EFBFBD>sicas em Espera";
$dispProgSel[11022] = "Cadastro de M<EFBFBD>sicas em Espera";
$dispProgSel[10023] = "Cadastro de Grupos";
$dispProgSel[11023] = "Cadastro de Grupos";
$dispProgSel[10024] = "Cadastro de Empresas";
$dispProgSel[11024] = "Cadastro de Empresas";
$dispProgSel[10025] = "Cadastro de Departamentos";
$dispProgSel[11025] = "Cadastro de Departamentos";
$dispProgSel[10026] = "Cadastro de Hosts";
$dispProgSel[11026] = "Cadastro de Hosts";
$dispProgSel[10027] = "Cadastro de Contextos";
$dispProgSel[11027] = "Cadastro de Contextos";
$dispProgSel[10028] = "Cadastro de Conta e Senha";
$dispProgSel[11028] = "Cadastro de Conta e Senha";
$dispProgSel[10029] = "Cadastro de Lista Negra";
$dispProgSel[11029] = "Cadastro de Lista Negra";
$dispProgSel[10030] = "Cadastro de Grupos de Captura";
$dispProgSel[11030] = "Cadastro de Grupos de Captura";
$dispProgSel[10031] = "Cadastro de Ura";
$dispProgSel[11031] = "Cadastro de Ura";
$dispProgSel[10032] = "Cadastro de Voicemail";
$dispProgSel[11032] = "Cadastro de Voicemail";
$dispProgSel[10033] = "Cadastro de Hor<EFBFBD>rios";
$dispProgSel[11033] = "Cadastro de Hor<EFBFBD>rios";
$dispProgSel[10034] = "Monitor de Ramais Troncos";
$dispProgSel[10035] = "Cadastro de Prioridades";
$dispProgSel[11035] = "Cadastro de Prioridades";
$dispProgSel[10036] = "Cadastro de Confer<EFBFBD>ncias";
$dispProgSel[11036] = "Cadastro de Confer<EFBFBD>ncias";
$dispProgSel[10040] = "Configura<EFBFBD><EFBFBD>es de Email";
$dispProgSel[11040] = "Configura<EFBFBD><EFBFBD>es de Email";
//$dispProgSel[10041] = "Configura<EFBFBD><EFBFBD>es de Digivoice";
$dispProgSel[11041] = "Configura<EFBFBD><EFBFBD>es de Digivoice";
$dispProgSel[11042] = "Cadastro de Servi<EFBFBD>os";
$dispProgSel[10043] = "Arquivos de Som";
//$dispProgSel[10044] = "Cadastro de Ramais Dahdi";
$dispProgSel[11043] = "Cadastro de Arquivos de Som";
//$dispProgSel[10045] = "Monitor E1";
$dispProgSel[10046] = "Centro de Custo Ramais";
$dispProgSel[11046] = "Centro de Custo Ramais";
//$dispProgSel[10047] = "Ramais Khomp";
//$dispProgSel[11047] = "Ramais Khomp";
$dispProgSel[10048] = "Troncos Khomp";
//$dispProgSel[10049] = "Troncos Dahdi";
//$dispProgSel[10050] = "Dispositivos Dahdi";
$dispProgSel[10052] = "Monitor Chamadas";
$dispProgSel[12000] = "depend<EFBFBD>ncias dos Recursos";
$disp = $dispProgSel;
return (strtoupper($_SESSION["SSaut"]) == "OK") ? (isset($dispProgSel[$idProg]) ? $dispProgSel[$idProg] : PRM_DEF_SLOGAN) : GetSlogan();
}
function GetMenuUser($tpUser)
{
if (!IsUserConnect()) {
return "";
}
$empresas = GetAllOrganizacao();
$strEmpresa = null;
if (count($empresas) > 1) {
$strEmpresa = '<select id="perfil" name="perfil" class="selectPerfil">';
foreach ($empresas as $v) {
$sel = $_SESSION['SSEmpresaPadrao'] == $v['id'] ? "selected" : null;
$strEmpresa .= sprintf("<option value='%s' $sel>%s</option>", $v['id'], $v['nome']);
}
$strEmpresa .= '</select>';
}
$menu = "&nbsp;";
$menu = "<script language=\"JavaScript\">\n";
$menu .= "<!--//\n";
$menu .= " new menu (MENU_ITEMS, MENU_TPL);\n";
$menu .= "//-->\n";
$menu .= "</script>\n";
$menuGeral = "<table class=\"menuGeral\" border=\"0\" cellspacing=\"0\" cellpadding=\"1\">
<tr>
<td valign=\"middle\" style=\"height:30px;margin:0;\">
<div class=\"menuGeral\" style=\"position:relative;\">$menu
$strEmpresa
</div>
</td>
</tr>
</table>";
//<th width=\"30%\" align=\"center\" nowrap><img src=\"imgSite/setaRreen.png\" align=\"absmiddle\"> $dispProgSel</th>
/*
* $tpUser == 1 Indica uma janela popup n<EFBFBD>o ir<EFBFBD> aparecer o menu
*/
return $tpUser == 1 ? "" : $menuGeral;
}
function IsUserConnect()
{
if (!isset($_SESSION["SSaut"])) {
return false;
}
return strtoupper($_SESSION["SSaut"]) == "OK";
}
function GetDisponivelFila()
{
return $_SESSION["prm_disponivel_fila"];
}
function GetLogin()
{
return IsUserConnect() ? $_SESSION["SSlogin"] : "Desconectado";
}
function GetOrganizacao()
{
global $dbcon;
if (empty($_SESSION['SSEmpresaPadrao']) && IsUserConnect()) {
$query = "SELECT po.id AS org_id
FROM pbx_organizacao po
INNER JOIN pbx_organizacao_usuarios pou ON po.id = pou.id_organizacao
INNER JOIN pbx_usuarios pu ON pu.id = pou.id_usuario
WHERE id_usuario = %s
AND (org_padrao = po.id OR po.id = (SELECT MAX(id_organizacao) FROM pbx_organizacao_usuarios WHERE id_usuario = pu.id))";
$query = sprintf($query, $_SESSION['SSidUser']);
$result = pg_query($dbcon, $query);
$res = pg_fetch_assoc($result);
$_SESSION['SSEmpresaPadrao'] = $res['org_id'];
}
return $_SESSION['SSEmpresaPadrao'];
}
function GetAllOrganizacao()
{
global $dbcon;
$query = "SELECT po.id, po.nome, master
FROM pbx_organizacao po
INNER JOIN pbx_organizacao_usuarios pou ON pou.id_organizacao = po.id
WHERE pou.id_usuario = {$_SESSION['SSidUser']}
AND status = 1";
$result = pg_query($dbcon, $query);
if ($result) {
return pg_fetch_all($result);
}
return false;
}
function GetExigeClas($db = null, $dac = 0)
{
$dacOn = empty($_SESSION[SS_DAC_CODIGO]) ? false : $_SESSION[SS_DAC_CODIGO];
$dacAgente = trim($dac ? $dac : $dacOn);
if (!$dacAgente) {
return false;
}
$query = "Select exige_classificacao from pbx_queues_grupos where id = '$dacAgente' ";
$result = $db ? pg_query($db, $query) : pg_query($query);
if ($result) {
$row = pg_fetch_row($result);
return $row[0];
}
return false;
}
function SupervisorClass($dac)
{
$exige = array();
if (isset($_SESSION["SSSuperExigeClass"]) && $_SESSION["SSSuperExigeClass"])
$exige = $_SESSION["SSSuperExigeClass"];
if (!isset($exige[$dac])) {
$db = $GLOBALS['dbcon'];
$query = "Select exige_classificacao from pbx_queues_grupos where nome = '$dac' ";
$result = pg_query($db, $query);
if ($result) {
$row = pg_fetch_row($result);
$exige[$dac] = $row[0];
$_SESSION["SSSuperExigeClass"] = $exige;
}
}
return $exige[$dac];
}
function ExibePesquisa()
{
return $_SESSION["prm_modulo_pesquisa"];
}
function HabilitaPortabilidade()
{
return $_SESSION["prm_portabilidade"];
}
function HabilitaTarifacao()
{
return $_SESSION["prm_tarifacao"];
}
function HabilitaPrepago()
{
return $_SESSION["prm_prepago"];
}
function GetExigeClassStatusTxt($st)
{
switch ($st) {
case 0:
return "N<EFBFBD>o";
case 1:
return "Sim";
case 2:
return "...";
default:
return "...";
}
}
function GetExigeClassStatus($st, $dac = '', $super = 0)
{
if (!GetExigeClas() && !$super)
return true;
if (!SupervisorClass($dac) && $super)
return true;
switch ($st) {
case 0:
return false;
case 1:
case 2:
return true;
}
}
function GetNomeCadCli()
{
return isset($_SESSION["prm_cadastro_atendidos"]) ? $_SESSION["prm_cadastro_atendidos"] : 'Cliente';
}
function GetSlogan()
{
return isset($_SESSION[SS_PRM_SLOGAN]) ? $_SESSION[SS_PRM_SLOGAN] : PRM_DEF_SLOGAN;
}
function LimpaVarRelatorio()
{
$id = (int) isset($_GET["idProg"]) ? $_GET["idProg"] : 0;
switch ($id) {
case 3:
case 4:
case 5:
case 6:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 16:
case 17:
case 18:
case 19:
case 20:
case 23:
case 34:
case 35:
case 38:
case 40:
case 42:
case 44:
case 46:
case 48:
case 50:
case 53:
case 60:
case 64:
case 65:
case 66:
case 69:
case 71:
case 73:
case 75:
case 77:
case 79:
case 81:
case 88:
case 90:
case 91:
case 92:
case 94:
case 96:
case 98:
case 101:
case 102:
case 103:
case 104:
case 106:
case 109:
case 110:
case 111:
case 118:
case 119:
case 159:
case 160:
case 163:
case 166:
case 171:
case 226:
$id = 0;
break;
default:
$id = 1;
}
//funcao desabilidata para havaliacao
$id = 0;
if ($id) {
$_SESSION["listaDacs"] = null;
$_SESSION["listaMes"] = null;
$_SESSION["listaAno"] = null;
$_SESSION["data"] = null;
$_SESSION["dataIni"] = null;
$_SESSION["dataFim"] = null;
$_SESSION["dadosRamalRamal"] = null;
$_SESSION["dadosForaHorario"] = null;
$_SESSION["ramal"] = null;
$_SESSION["conta"] = null;
$_SESSION["usuario"] = null;
$_SESSION["gpConta"] = null;
$_SESSION["gpRamal"] = null;
$_SESSION["gpCentroCusto"] = null;
$_SESSION["SSsiteDesc"] = null;
$_SESSION["SSLinhas"] = null;
$_SESSION["ramal"] = null;
$_SESSION["nomeAgente"] = null;
$_SESSION["listaAgente"] = null;
$_SESSION["SSresumo"] = null;
$_SESSION["SSmediaDia"] = null;
$_SESSION["SSsomaDia"] = null;
$_SESSION["tipoLigacao"] = null;
$_SESSION["setQuery"] = null;
}
}
function IndexaMenu($dbcon, $queryHead, $queryItens, $idUser, $hiddeLink, $param = null)
{
// fun_id, fun_nome, fun_menu, fun_menu_text, fun_menu_url, fun_menu_img, fun_id_pai, fun_status, fun_public
/*
* Verifica se <EFBFBD> uma referencia a arvore de Permiss<EFBFBD>es ou menu
*/
$isTree = $_SESSION["SStreView"];
$modMenu = 121;
$dadosMenu = array();
$menu = array();
$indexMenu = array(); //Guanda referncia para os menus
$absId = 0;
$idPai = 0;
$absIdFind = 0;
$idUser = empty($idUser) ? GetIdUser() : $idUser;
$query = empty($queryHead) ? QueryMenuHead($idUser) : $queryHead;
$result = pg_query($dbcon, $query);
if ($isTree) {
while ($row = pg_fetch_array($result)) {
$link = $hiddeLink ? "" : sprintf("index.php?idProg=%s&funId=%s&acao=%s", $modMenu, $row["fun_id"], $_SESSION["SSperfilAcao"]);
$values = array("fun_menu_text" => $row["fun_menu_text"], "fun_menu_url" => $link);
$menu[$row["fun_id"]] = $values;
}
} else {
/*
* Resgata valores referente ao m<EFBFBD>dulo da tabela pb_funcoes
* para formar os menus de primeiro n<EFBFBD>vel
*/
while ($row = pg_fetch_array($result)) {
$link = $hiddeLink ? "" : $row["fun_menu_url"];
$values = array("fun_menu_text" => $row["fun_menu_text"], "fun_menu_url" => $link, "fun_menu_img" => $row["fun_menu_img"]);
$menu[$row["fun_id"]] = $values;
}
}
/*
* Carrega valores para os sub-n<EFBFBD>veis de menu a partir
* da tabela
*/
$query = empty($queryItens) ? QueryMenuItens($idUser, 0, 0, $param) : $queryItens;
$result = pg_query($dbcon, $query);
$i = 0;
while ($row = pg_fetch_array($result)) {
$dadosMenu[$i] = $row;
$idxMenu[$row["fun_id"]] = $i;
$i++;
}
$dadosMenuFind = $dadosMenu;
foreach ($dadosMenu as $key => $value) {
$absId = $value["fun_id"];
$start = 0;
$menuRef = array();
$idPai = $value["fun_id_pai"];
while ($idPai) {
$arRef = @$dadosMenuFind[$idxMenu[$idPai]];
$menuRef[] = $arRef["fun_id"];
$idPai = $arRef["fun_id_pai"];
$idFind = $arRef["fun_id"];
}
if ($menuRef) {
krsort($menuRef);
$indexMenu[$absId] = $menuRef;
}
}
foreach ($dadosMenu as $value) {
$absId = $value["fun_id"];
$str = '';
if ($isTree) {
$link = $hiddeLink ? "" : sprintf("index.php?idProg=%s&funId=%s&acao=%s", $modMenu, $value["fun_id"], $_SESSION["SSperfilAcao"]);
$values = array("fun_menu_text" => $value["fun_menu_text"], "fun_menu_url" => $link);
} else {
$link = $hiddeLink ? "" : $value["fun_menu_url"];
$values = array("fun_menu_text" => $value["fun_menu_text"], "fun_menu_url" => $link, "fun_menu_img" => $value["fun_menu_img"]);
}
$arRef = isset($indexMenu[$absId]) ? $indexMenu[$absId] : array();
if ($arRef) {
foreach ($arRef as $valRef) {
$str .= '[' . $valRef . ']';
}
$str = "\$menu$str" . '[' . $absId . ']' . " = \$values;";
eval($str);
}
};
return $menu;
}
function GetQtdeDigitoConta()
{
return $_SESSION["prm_digitos_conta"];
}
function GetQtdeDigitoSenha()
{
return $_SESSION["prm_digitos_senha"];
}
function GeraContaAuto()
{
return $_SESSION["prm_gera_conta"];
}
function IsServerMaster()
{
return isset($_SESSION["SStpServer"]) ? $_SESSION["SStpServer"] : 0;
}
function GetServerName()
{
return $_SESSION["SSserverName"];
}
function SincContaSenha()
{
return isset($_SESSION["SSsincContaSenha"]) ? $_SESSION["SSsincContaSenha"] : 0;
}
function GetServerMaster()
{
return isset($_SESSION["SShostMaster"]) ? $_SESSION["SShostMaster"] : null;
}
function SetDefaultSite($dbcon)
{
$query = "select min(id) from pbx_sites ";
$result = pg_query($dbcon, $query);
$row = pg_fetch_row($result);
$_SESSION["SSDefaultSite"] = $row[0];
}
function GetSequenciaLocal($dbcon, $nomeTable)
{
$result = pg_query($dbcon, 'begin');
if (!$result)
return 0;
$query = "select id from pbx_sequencia where name_table = '$nomeTable'";
$result = pg_query($dbcon, $query);
if (!$result)
return 0;
$existeTable = pg_num_rows($result);
if ($existeTable) {
$dados = pg_fetch_array($result);
$seq = $dados['id'] + 1;
} else {
$query = "insert into pbx_sequencia(name_table, id)values('$nomeTable', 0)";
$result = pg_query($dbcon, $query);
$seq = 1;
}
$query = "update pbx_sequencia set id = $seq where name_table = '$nomeTable'";
$result = pg_query($dbcon, $query);
if (!$result) {
pg_query($dbcon, 'rollback');
return 0;
} else {
$result = pg_query($dbcon, 'commit');
if (!$result) {
return 0;
}
return $seq;
}
}
function GetModeloApl()
{
return $_SESSION['Modelo'];
}
function GetModeloRamais()
{
return $_SESSION['Ramais'];
}
function GetModeloPa()
{
return $_SESSION['PA'];
}
function GetParametrosLicensa()
{
/*
* Carrega informa<EFBFBD><EFBFBD>es sobre a licensa
* [Product-Name] => SimplesIP
* [Registered-To] => Simples IP
* [Expires] => Never
* [Hardware-Locked] => No
* [Modelo] => SCE
* [PA] => 6
* [Ramais] => 24
* [Produced-By] => Simples IP
*/
//if(strtoupper(substr(PHP_OS, 0, 3)) == "WIN")
if (true) {
$lic_info = array('Product-Name' => 'SimplesIP', 'Registered-To' => 'Simples IP', 'Expires' => 'Never', 'Hardware-Locked' => 'No', 'Modelo' => 'SCE', 'PA' => '6', 'Ramais' => '24', 'Produced-By' => 'Simples IP');
} else {
$lic_info = zend_loader_file_licensed();
}
foreach ($lic_info as $key => $value) {
$_SESSION[$key] = $value;
}
}
function GetDadosOrganizacao($db)
{
$query = sprintf("SELECT u.nome, matricula, po.id, po.nome as nome_fantasia, po.master, po.status, u.org_padrao, prm_logo_relatorio
FROM pbx_usuarios u
INNER JOIN pbx_organizacao_usuarios pou ON pou.id_usuario = u.id
INNER JOIN pbx_organizacao po ON po.id = pou.id_organizacao
LEFT JOIN pbx_parametros pp ON pp.org_id = po.id
WHERE matricula = '%s'
AND po.status = 1", GetMatricula());
$result = pg_query($db, $query);
$resp = pg_fetch_all($result);
return $resp;
}
function GetParametros($db)
{
$org_id = GetOrganizacao();
$fields = array(
'prm_id', 'prm_slogan', 'prm_path_audio', 'prm_path_arq_agente', 'prm_logo_relatorio', 'prm_relatorio_head', 'prm_relatorio_linha1', 'prm_relatorio_linha2', 'prm_msg_senha_def',
'prm_msg_senha_exp', 'prm_url_asterisk', 'prm_agente_classifica', 'prm_agente_proto', 'prm_agente_contribuinte', 'prm_ddd_padrao', 'path_som', 'prm_mun_padrao', 'prm_uf_padrao',
'prm_cadastro_atendidos', 'prm_super_atualiza', 'prm_agente_atualiza', 'prm_sk_host', 'prm_sk_port', 'prm_sk_login', 'prm_sk_password', 'prm_digitos_conta', 'prm_digitos_senha',
'prm_gera_conta', 'prm_super_alerta_atende', 'prm_super_alerta_pausa', 'prm_super_alerta_livre', 'prm_pausa_grupo', 'prm_atende_auto', 'prm_atende_manual', 'prm_atende_preferencial',
'prm_classifica_municipio', 'prm_max_agente_pausa', 'prm_disponivel_fila', 'prm_boloco_notas_key', 'caminho_producao', 'prm_exige_classificacao', 'prm_obs_pausaprod', 'prm_modulo_pesquisa',
'prm_portabilidade', 'prm_tarifacao', 'prm_prepago', 'prm_use_discador', 'prm_tempo_sessao', 'prm_agente_nova_janela', 'prm_label_protoco_pesquisa', 'prm_label_protoco_texto', 'prm_label_protoco_grid',
'prm_registro_pagina', 'prm_use_vendas', 'prm_nome_vendas', 'prm_exige_proto_vendas', 'prm_alerta_classificacao', 'prm_ativa_integracao', 'prm_select_integracao', 'prm_aviso_desconnect', 'prm_link_audio',
'prm_ocultar_telefone', 'prm_ocultar_email', 'prm_ocultar_documento', 'prm_sk_host_chat', 'prm_chat_api', 'prm_chat_url_client', 'prm_sk_api_centrais', 'prm_max_licenca', 'prm_max_ramal', 'prm_max_licenca_fixo', 'prm_media_simultaneo',
'prm_ativa_complemento_campanha', 'prm_relatorio_servico', 'prm_aviso_lgpd_monitoria', 'prm_log_dias'
);
$query = "SELECT id AS prm_id, prm_slogan, prm_path_audio, prm_path_arq_agente, prm_logo_relatorio, prm_relatorio_head, prm_relatorio_linha1,
prm_relatorio_linha2,
CASE WHEN(COALESCE(prm_agente_atualiza, 5) = 0)THEN 5 ELSE COALESCE(prm_agente_atualiza, 5) END AS prm_agente_atualiza,
CASE WHEN(COALESCE(prm_super_atualiza, 10) = 0)THEN 10 ELSE COALESCE(prm_super_atualiza, 10) END AS prm_super_atualiza,
COALESCE(prm_agente_classifica, 0) AS prm_agente_classifica, prm_msg_senha_def, prm_msg_senha_exp, prm_url_asterisk,
prm_agente_proto, prm_agente_contribuinte, prm_ddd_padrao, (SELECT min(path_som) FROM pbx_conf_padrao) AS path_som,
prm_mun_padrao, prm_uf_padrao, prm_cadastro_atendidos, prm_sk_host, prm_sk_port, prm_sk_login, prm_sk_password,
prm_digitos_conta, prm_digitos_senha, prm_gera_conta, prm_super_alerta_atende, prm_super_alerta_pausa, prm_super_alerta_livre,
prm_pausa_grupo, prm_atende_auto, prm_atende_manual, prm_atende_preferencial, prm_classifica_municipio, prm_max_agente_pausa,
prm_disponivel_fila, prm_boloco_notas_key, (SELECT min(caminho_producao) FROM pbx_conf_padrao) AS caminho_producao,
prm_exige_classificacao, prm_obs_pausaprod, prm_modulo_pesquisa, prm_portabilidade, prm_tarifacao, prm_prepago, prm_use_discador,
prm_tempo_sessao, prm_agente_nova_janela, prm_label_protoco_pesquisa, prm_label_protoco_texto, prm_label_protoco_grid,
prm_registro_pagina, prm_use_vendas, prm_nome_vendas, prm_exige_proto_vendas, prm_alerta_classificacao, prm_ativa_integracao, prm_select_integracao, prm_aviso_desconnect,
prm_link_audio, prm_ocultar_telefone, prm_ocultar_email, prm_ocultar_documento, prm_sk_host_chat, prm_chat_api, prm_chat_url_client, prm_sk_api_centrais, prm_max_licenca,
prm_max_ramal, prm_max_licenca_fixo, prm_media_simultaneo, prm_ativa_complemento_campanha, prm_relatorio_servico, prm_aviso_lgpd_monitoria, prm_log_dias
from pbx_parametros
where org_id = {$org_id}";
$result = pg_query($db, $query);
$numReg = pg_num_rows($result);
if ($numReg) {
$row = pg_fetch_array($result);
if (!empty($row["prm_agente_atualiza"])) {
foreach ($fields as $value) {
$_SESSION[$value] = $row[$value];
}
}
}
}
function SetDimensoes($width, $height)
{
//agente '580','300'
/*
* A fun<EFBFBD><EFBFBD>o ajusta as medidas para diferentes Browsers e plataformas
* tendo com base as medidas criadas para o ie7>
*/
$browser = $GLOBALS["infoDispositivo"];
/*
* Parametroza<EFBFBD><EFBFBD>o de acordo com plataforma/browser da
* quantidade em percentual para ajuste.
*/
$arParam[Browser::PLATFORM_LINUX][Browser::BROWSER_FIREFOX] = array('width' => '4', 'height' => '2');
$arParam[Browser::PLATFORM_WINDOWS][Browser::BROWSER_FIREFOX] = array('width' => '4', 'height' => '2');
$arParam[Browser::PLATFORM_LINUX][Browser::BROWSER_CHROME] = array('width' => '0', 'height' => '2');
$arParam[Browser::PLATFORM_WINDOWS][Browser::BROWSER_CHROME] = array('width' => '0', 'height' => '2');
$arParam[Browser::PLATFORM_LINUX][Browser::BROWSER_OPERA] = array('width' => '0', 'height' => '2');
$arParam[Browser::PLATFORM_WINDOWS][Browser::BROWSER_OPERA] = array('width' => '0', 'height' => '2');
/*
* Identifica as medidas a serem ajustada de acordo com a plataforma/browser
$medidas = $arParam[$browser->getPlatform()][$browser->getBrowser()];
if(!empty($medidas))
{
// if($medidas['width']) { $width += ($width * ($medidas['width'] / 100.0)); }
// if($medidas['height']) { $height += ($height * ($medidas['height'] / 100.0)); }
}
*/
//echo sprintf("Width: %s [%s] Height: %s Browser: %s [%s] Plataforma: %s [%s] ", $width, $medidas['width'], $height, $browser->getBrowser(), Browser::BROWSER_FIREFOX, $browser->getPlatform(), Browser::PLATFORM_LINUX );
$GLOBALS["janW"] = $width;
$GLOBALS["janH"] = $height;
}
function roundUp($value, $precision = 2)
{
// If the precision is 0 then default the factor to 1, otherwise
// use 10^$precision. This effectively shifts the decimal point to the
// right.
if ($precision == 0) {
$precisionFactor = 1;
} else {
$precisionFactor = pow(10, $precision);
}
// ceil doesn't have any notion of precision, so by multiplying by
// the right factor and then dividing by the same factor we
// emulate a precision
return ceil($value * $precisionFactor) / $precisionFactor;
}
function UsePausaGrupo()
{
return $_SESSION["prm_pausa_grupo"];
}
function AgenteOcupado($dbcon, $matricula)
{
$query = "Select count(*) from pbx_supervisor_agentes where matricula = '$matricula' and upper(status) = 'OCUPADO' ";
$result = pg_query($dbcon, $query);
$dados = pg_fetch_row($result);
return $dados[0];
}
function GetErrorLast($message, $display = 0, $html = 0)
{
$error = error_get_last();
$erro = $error["message"];
$line = $error["line"];
$src = $error["file"];
if (stripos($erro, "deprecated") !== false)
$erro = "";
if ($display && $erro) {
$break = $html ? "<br />\n" : "\n";
$message = sprintf("%s%sErro: %s%sScript: %s%sLinha: %s", $message, $break, $erro, $break, $src, $break, $line);
}
return $message;
}
/**
*
function GetLastDayofMonth($year, $month) {
for ($day=31; $day>=28; $day--) {
if (checkdate($month, $day, $year)) {
return $day;
}
}
}
function GetDataIniFatura($ano, $mes, $diaFecha)
{
// $ano . "-" . ($mes - 1) . "-" . ($diaFecha + 1);
$finalMes = GetLastDayofMonth($ano, $mes);
if($diaFecha >= $finalMes)
return sprintf("%s-%s-01", $ano, $mes);
$mes = mes == 1 ? 12 : ($mes -1);
if(mes == 1)$ano--;
$finalMes = GetLastDayofMonth($ano, $mes);
if(++$diaFecha > $finalMes)$diaFecha = $finalMes;
return sprintf("%s-%s-%s", $ano, $mes, $diaFecha);
}
function GetDataFimFatura($ano, $mes, $diaFecha)
{
//$ano . "-" . ($mes) . "-" . ($diaFecha);
$finalMes = GetLastDayofMonth($ano, $mes);
if($diaFecha > $finalMes)$diaFecha = $finalMes;
return sprintf("%s-%s-%s", $ano, $mes, $diaFecha);
}
*/
function GetContextoRamal($db, $ramal)
{
$query = "select contexto from pbx_ramais where nome = '$ramal'";
$result = pg_query($db, $query);
$row = pg_fetch_row($result);
return $row[0];
}
function ChamdaClassificadaAgente($db, $matricula)
{
$query = "select chamada_classificado from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
$row = pg_fetch_row($result);
return $row[0];
}
function GetRamalLogado($db, $matricula)
{
$query = "select ramal from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
$row = pg_fetch_row($result);
return $row[0];
}
function ClassificacaoExigidaLiberada($db, $uid)
{
/*
* Se a classifica<EFBFBD><EFBFBD>o n<EFBFBD>o <EFBFBD> obrigat<EFBFBD>ria retorna true do contr<EFBFBD>rio
* verifica sa a mesa j<EFBFBD> foi realizada.
*/
if (!GetExigeClas()) {
return true;
}
return ChamdaClassificada($db, $uid);
}
function IsAgenteDisponivel($db, $matricula)
{
$query = "select disponivel_atendimento from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
$row = pg_fetch_row($result);
return pg_num_rows($result) && $row[0];
}
function GetOrdenacaoRelatorio($db, $idRel)
{
$colunas = array();
$ordem = '';
$query = "select distinct a.ord_nome_coluna, ords_seq, case when(b.ords_ordem = 0)then 'asc' else 'desc' end as ordem, b.ords_ordem as ordem_num
from pbx_relatorio_ordena a, pbx_relatorio_ordena_set b
where b.ord_id = a.ord_id
and a.ord_rel_id = '$idRel'
order by ords_seq\n\n";
$result = pg_query($db, $query);
//echo $query;
while ($row = pg_fetch_array($result)) {
$colunas[$row['ord_nome_coluna']] = $row['ordem_num'];
$str = sprintf('%s %s', $row['ord_nome_coluna'], $row['ordem']);
$ordem .= empty($ordem) ? $str : ", $str";
}
return array($ordem, $colunas);
}
function SetOrdenanacaoColunas($smarty, $arOrdem)
{
foreach ($arOrdem as $key => $value) {
$img = sprintf('<img src="imgSite/%s" align="absmiddle" width="12" height="12" alt="%s" title="%s" />', ($value ? "ordenaDesc12.png" : "ordenaAsc12.png"), ($value ? "Ordena<EFBFBD><EFBFBD>o Descendente" : "Ordena<EFBFBD><EFBFBD>o Ascendente"), ($value ? "Ordena<EFBFBD><EFBFBD>o Descendente" : "Ordena<EFBFBD><EFBFBD>o Ascendente"));
$smarty->assign($key, $img);
}
}
function GetUfs($db, $uf = '')
{
$sel = '';
if ($uf == '') {
$sel = "selected";
}
$item = "<option value=\"0\" $sel>------------</option>";
$query = "select uf from pbx_uf order by 1";
$result = pg_query($db, $query);
while ($row = pg_fetch_array($result)) {
$ufBd = $row["uf"];
if ($ufBd == $uf)
$sel = "selected";
else
$sel = "";
$item .= "<option value=\"$ufBd\" $sel>$ufBd</option>";
}
return $item;
}
function GetPermitAtendManual()
{
if ($_SESSION["prm_atende_manual"])
return true;
if ($_SESSION["prm_atende_auto"])
return false;
return $_SESSION["prm_atende_preferencial"] ? true : false;
}
function GetPermitAtendAuto()
{
if ($_SESSION["prm_atende_auto"])
return true;
if ($_SESSION["prm_atende_manual"])
return false;
return !$_SESSION["prm_atende_preferencial"] ? true : false;
}
function GetAnotacoesKey()
{
// 1 - telefone 2 - Protocolo
return $_SESSION["prm_boloco_notas_key"];
}
function SetModuAtendimentoDefault()
{
//Modo de atendimento default
$moduAtd = $_SESSION["prm_atende_preferencial"];
$agentIsLogged = AgenteON();
if (!$agentIsLogged) {
$_SESSION[SS_MODO_ATENDIMENTO_COD] = $moduAtd && GetPermitAtendManual() ? '**50' : '**60';
$_SESSION[SS_MODO_ATENDIMENTO] = $_SESSION[SS_MODO_ATENDIMENTO_COD] === ATENDIMENTO_MANUAL ? "Manual" : "Autom<EFBFBD>tico";
};
}
function GetVersao()
{
return "1.9.0";
}
function GetEncType($upload)
{
if ($upload == 1)
return "enctype=\"multipart/form-data\"";
if ($upload == 2)
return "enctype=\"application/x-www-form-urlencoded\"";
return "";
return "enctype=\"text/plain\"";
}
function InsereRotasRamais($dbcon, $rotas, $ramal)
{
foreach ($rotas as $rota) {
global $idProg;
$dadosRotas = explode(";", $rota);
$tipoAcesso = $dadosRotas[0];
$id = $dadosRotas[1];
$query = "update pbx_rotas_saida_ramais set tipo_acesso = '$tipoAcesso' where id_rota = '$id' and ramal = '$ramal';
insert into pbx_rotas_saida_ramais(id_rota, ramal, tipo_acesso)
select '$id', '$ramal', '$tipoAcesso'
where not exists(select '' from pbx_rotas_saida_ramais where id_rota = '$id' and ramal = '$ramal');";
$novo = array('id_rota' => $id, 'ramal' => $ramal, 'tipo_acesso' => $tipoAcesso);
GrvAudita($dbcon, $idProg, 'pbx_rotas_saida_ramais', 'INS', array(), $novo, array('id_rota', 'ramal', 'tipo_acesso'), array('id_rota'), true);
pg_query($dbcon, $query);
}
}
function InsereRamaisRotas($dbcon, $ramais, $rota)
{
foreach ($ramais as $key => $info) {
global $idProg;
$dadosRamais = explode(";", $info);
$ramal = soNumero($key);
$tipoAcesso = $dadosRamais[0];
$query = "update pbx_rotas_saida_ramais set tipo_acesso = '$tipoAcesso' where id_rota = '$rota' and ramal = '$ramal';
insert into pbx_rotas_saida_ramais(id_rota, ramal, tipo_acesso)
select '$rota', '$ramal', '$tipoAcesso'
where not exists(select '' from pbx_rotas_saida_ramais where id_rota = '$rota' and ramal = '$ramal');";
$novo = array('id_rota' => $rota, 'ramal' => $ramal, 'tipo_acesso' => $tipoAcesso);
GrvAudita($dbcon, $idProg, 'pbx_rotas_saida_ramais', 'INS', array(), $novo, array('id_rota', 'ramal', 'tipo_acesso'), array('id_rota'), true);
pg_query($dbcon, $query);
}
}
function GetPrefixoSenha($db)
{
$query = "select prm_prefixo_sennha_ramal from pbx_parametros where id = 1";
$result = pg_query($db, $query);
$row = pg_fetch_array($result);
return $row['prm_prefixo_sennha_ramal'];
}
function GetObsProdAgente($db = null, $dac = 0)
{
if ($dac && $db) {
$query = "Select justificativa_pausa from pbx_queues_grupos where id = '$dac' ";
$result = pg_query($db, $query);
if ($result) {
$row = pg_fetch_row($result);
return $row[0];
}
}
if (isset($_SESSION[SS_JUSTIFICATIVA_PAUSA]) && !is_null($_SESSION[SS_JUSTIFICATIVA_PAUSA]))
return $_SESSION[SS_JUSTIFICATIVA_PAUSA];
return $_SESSION["prm_obs_pausaprod"];
}
/*
* Chefe Secret<EFBFBD>ria
*/
function InsereRamaisChf($conn, $ramal)
{
$excecoes = $_POST['ramalSecExcecoesInc'];
$query = "delete from pbx_chefe_secretaria where numero = '$ramal'";
pg_query($conn, $query);
foreach ($excecoes as $exc) {
global $idProg;
$query = "insert into pbx_chefe_secretaria(numero, excecao)values('$ramal', '$exc');";
pg_query($conn, $query);
$novo = array('numero' => $ramal, 'excecao' => $exc);
GrvAudita($conn, $idProg, 'pbx_chefe_secretaria', 'INS', array(), $novo, array('numero', 'excecao'), array('numero'), true);
}
}
function GetClienteClassifica($db, $fone)
{
$query = "select distinct a.contrib_id, b.contrib_nome
from pbx_classifica_reg a, pbx_contribuinte b
where b.contrib_id = a.contrib_id
and contrib_fone = '$fone' limit 1";
$result = pg_query($db, $query);
if (!$result | (pg_num_rows($result) == 0))
return "";
$dados = @pg_fetch_array($result);
$contribId = trim($dados["contrib_id"]);
$contribNome = trim($dados["contrib_nome"]);
if (!$contribId | !$contribNome) {
return "";
}
return sprintf("%s-%s", $contribId, $contribNome);
}
function GetClienteIntegra($db, $uniqueid)
{
$query = "select distinct a.int_dados
from pbx_integracao_dados a, pbx_integracao_reg b
where a.int_id = b.reg_retorno
and b.reg_uniqueid = '$uniqueid' limit 1";
$result = pg_query($db, $query);
if (!$result | (pg_num_rows($result) == 0))
return "";
$dados = @pg_fetch_array($result);
$param = explode("|", $dados[0]);
return sprintf("%s - %s", $param[0], $param[1]);
}
function dropTemporaryTable($db, $nomeTable)
{
$query = "select isTmpTable('$nomeTable');";
$result = pg_query($db, $query);
$row = pg_fetch_row($result);
if ($row[0]) {
$query = "drop table $nomeTable;";
return pg_query($db, $query);
}
return false;
}
function InsertDb($db, $nomeTable, $content, $getSequencia = false)
{
$fields = "";
$values = "";
foreach ($content as $key => $value) {
$fields .= !$fields ? $key : ", $key";
$values .= !$values ? sprintf("%s", NullDb($value)) : sprintf(", %s", NullDb($value));
}
$query = sprintf("insert into %s(%s)values(%s)", $nomeTable, $fields, $values);
$result = pg_query($db, $query);
if ($result && $getSequencia) {
return GetSequenciaDb($db, $getSequencia);
}
return $result;
}
function UpdateDb($db, $nomeTable, $content, $where)
{
$query = "";
$values = "";
foreach ($content as $key => $value) {
$values .= !$values ? sprintf("%s = %s", $key, NullDb($value)) : sprintf(",%s = %s", $key, NullDb($value));
}
$query .= sprintf("update %s set %s where %s", $nomeTable, $values, $where);
$result = pg_query($db, $query);
//echo $query;
return $result;
}
function MoveFile($file, $nameOrig, $newName, $ulaw, &$msgErro)
{
$msgErro = '';
$path_som = $_SESSION["path_som"];
$db = $GLOBALS["dbcon"];
$nameConvert = explode('.', $newName);
$nameConvert = VerificaCharFinal($path_som) . $nameConvert[0];
$nameMove = $newName;
$newName = VerificaCharFinal($path_som) . $newName;
/*
* Move o arquivo para o destino
*/
$cmd = "TmpFile: $file NewFila: $newName";
$result = move_uploaded_file($file, $newName);
/*
* Convert os arquivos mp3 para ulaw
*/
$cmd = "ffmpeg -y -i $newName -ar 8000 -ac 1 -ab 64 -f mulaw $nameConvert.ulaw";
if ($result && $ulaw) {
$result = (ExecutaComando($cmd, $db) !== false);
//@system($cmd);
$result = file_exists("$nameConvert.ulaw");
if (!$result)
$msgErro = sprintf("N<EFBFBD>o foi poss<EFBFBD>vel converter o arquivo: %s!", $newName);
}
/*
* Verifica se existe o diretorio para mp3
*/
$dirMp3 = VerificaCharFinal($path_som) . "mp3/";
if ($result && !file_exists($dirMp3)) {
$cmd = "mkdir $dirMp3";
$result = (ExecutaComando($cmd, $db) !== false);
if (!$result)
$msgErro = sprintf("N<EFBFBD>o foi poss<EFBFBD>vel criar o diret<EFBFBD>rios: %s!", $dirMp3);
}
/*
* Move os arquivos mp3 para o didretorio mp3
*/
$cmd = "mv -f $newName $dirMp3/$nameMove";
if ($result && $ulaw) {
$result = (ExecutaComando($cmd, $db) !== false);
if (!$result)
$msgErro = sprintf("N<EFBFBD>o foi poss<EFBFBD>vel mover o arquivo: %s o diret<EFBFBD>rios: %s!", $newName, $dirMp3);
}
if (!$result && ($msgErro == ''))
$msgErro = sprintf("N<EFBFBD>o foi poss<EFBFBD>vel gravar o arquivo: %s!", $nameOrig);
return $result;
}
function GetCaminhoProducao()
{
return $_SESSION['caminho_producao'];
}
function GetPesquisaDisponivel($db, $dac)
{
$sel = '';
$sel = "selected";
$item = "<option value=\"0\" $sel>------------</option>";
$query = "select distinct b.pl_id, b.pl_descricao
from pbx_pesquisa_liberacao_dacs a, pbx_pesquisa_liberacao b
where b.pl_id = a.pl_id
and a.id_dac = '$dac'
and ( (now()::date >= b.pl_data_inicio) or (b.pl_data_inicio is null))
and ( (now()::date <= b.pl_data_fim) or (b.pl_data_fim is null))
and b.pl_ativa = 1 order by 2";
$result = pg_query($db, $query);
while ($row = pg_fetch_array($result)) {
$pl_id = $row["pl_id"];
$pl_desc = $row["pl_descricao"];
$item .= "<option value=\"$pl_id\">$pl_desc</option>";
}
return $item;
}
function GetLinksFromLink($db, $link)
{
$idUser = GetIdUser();
if (!$link)
$link = 0;
$query = IsAdmin() ? " select distinct d.fun_id, d.fun_nome, d.fun_menu, d.fun_menu_text, d.fun_menu_url, d.fun_menu_img, d.fun_id_pai, (select count(*) from pbx_funcoes where fun_id_pai = d.fun_id) as filhos
from pbx_funcoes d
where fun_id_pai = $link order by 4" : "select *
from (
select distinct d.fun_id, d.fun_nome, d.fun_menu, d.fun_menu_text, d.fun_menu_url, d.fun_menu_img, d.fun_id_pai, (select count(*) from pbx_funcoes where fun_id_pai = d.fun_id) as filhos
from pbx_usuarios a, pbx_grupo_usuario b, pbx_grupo_funcoes c, pbx_funcoes d
where b.user_id = a.id
and c.gp_id = b.gp_id
and d.fun_id = c.fun_id
and a.id = coalesce($idUser, a.id) order by d.fun_id
) a where fun_id_pai = $link order by 4";
$result = pg_query($db, $query);
$ret = "<ul class=\"menuComp\">\n";
while ($row = pg_fetch_array($result)) {
$url = $row["fun_menu_url"];
$url = (strpos($url, "\\'") !== false) ? str_replace("\\'", "'", $url) : $url;
$link = ($row["filhos"] > 0) ? $row["fun_menu_text"] : sprintf('<a href="%s" target="_top">%s</a>', $url, $row["fun_menu_text"]);
$ret .= "<li>$link</li>\n";
if ($row["filhos"] > 0)
$ret .= GetLinksFromLink($db, $row["fun_id"]);
}
$ret .= "</ul>\n";
return $ret;
}
function FiltraString()
{
if (isset($_POST)) {
foreach ($_POST as $key => $value) {
if (!is_array($_POST[$key])) {
$_POST[$key] = htmlspecialchars($value, ENT_NOQUOTES, 'ISO8859-1');
}
}
}
if (isset($_GET)) {
foreach ($_GET as $key => $value) {
if (!is_array($_GET[$key])) {
$_GET[$key] = htmlspecialchars($value, ENT_NOQUOTES, 'ISO8859-1');
}
}
}
if (isset($_REQUEST)) {
foreach ($_REQUEST as $key => $value) {
if (!is_array($_REQUEST[$key])) {
$_REQUEST[$key] = htmlspecialchars($value, ENT_NOQUOTES, 'ISO8859-1');
}
}
}
}
function GetDadosPost(&$fields, $arSource)
{
foreach ($arSource as $key => $value) {
if (array_key_exists($key, $fields)) {
$fields[$key] = $value;
}
}
}
function GetOpcaoAlt($db, $opcao)
{
include_once('admin/opcoes.php');
return _GetOpcoes($db, $opcao, 0, 0);
}
function GetAcaoAlt($db, $opcao, $acao)
{
$_getAcoes_ = 1;
include_once('admin/popula.php');
return _GetAcoes($db, 0, $acao, $opcao, 0, 0, PROTO_TXT);
}
function GetItegEvento($codEvt = 0)
{
$eventos[] = array('-----------------------------', '0');
// $eventos[] = array('Fila', '1');
$eventos[] = array('Encerramento', '2');
$eventos[] = array('Atendimento', '3');
foreach ($eventos as $evento) {
$cod = $evento[1];
$desc = $evento[0];
$sel = $codEvt == $cod ? 'selected=selected' : '';
$ret .= "<option value=\"$cod\" $sel>$desc</option>";
}
return $ret;
}
function IsNullQuoted($value, $def = 'null')
{
$value = trim($value);
return empty($value) ? (($def == 'null') ? $def : QuotedStr($def)) : QuotedStr($value);
}
function DownloadAudio($file, $filepath, $tipo = 'wav', $protocolo = '', $dataAudio = '')
{
ob_clean();
$isMp3 = (strtolower($tipo) == 'mp3');
/*
* Renomeia com o protocolo da chamada.
*/
$file = $protocolo ? $protocolo . '_' . $dataAudio . "." . strtoupper($tipo) : $file;
if ($isMp3) {
$dirMp3 = '/var/www/html/aplicativo/audio/';
$pathFileWav = sprintf("%s%s", $dirMp3, $file);
$patFileMp3 = str_ireplace('.WAV', '.MP3', $pathFileWav);
/*
* Renomeia o file para mostrar corretamente.
*/
$file = str_ireplace('.WAV', '.MP3', $file);
/*
* Cria o arquivo wav localmente.
*/
@file_put_contents($pathFileWav, @file_get_contents($filepath));
/*
* Convert para mp3.
*/
ConvertWavToMp3($pathFileWav, $patFileMp3);
/*
* Pega o tamanho do arquivo mp3 criado.
*/
$fsize = filesize($patFileMp3);
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Content-Type: ' . GetMimeContentType($file));
if ($fsize)
header('Content-Length: ' . $fsize);
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Connection: close');
readfile($patFileMp3);
unlink($pathFileWav);
unlink($patFileMp3);
exit;
} else {
$ftemp = "/tmp/$file";
@file_put_contents($ftemp, @file_get_contents($filepath));
$fsize = filesize($ftemp);
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Content-Type: ' . GetMimeContentType($file));
if ($fsize)
header('Content-Length: ' . $fsize);
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Connection: close');
readfile($filepath);
unlink($ftemp);
exit;
}
}
function CreateDownloadStream($nome)
{
$diretorio = "/var/www/html/aplicativo/audio/";
$arquivoWav = $diretorio . $nome . ".WAV";
$arquivoMp3 = $diretorio . $nome . ".MP3";
CnvrtWavToMp3($arquivoWav, $arquivoMp3);
$fsize = filesize($arquivoMp3);
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Content-Type: ' . GetMimeContentType($nome . ".MP3"));
header('Content-Length: ' . $fsize);
header('Content-Disposition: attachment; filename="' . $nome . ".MP3" . '"');
header('Connection: close');
readfile($arquivoMp3);
unlink($arquivoWav);
unlink($arquivoMp3);
exit;
}
function DownloadAudioAlgar($files)
{
try {
$baseAudio = '/var/www/html/aplicativo/audio/';
$numFiles = count($files);
foreach ($files as $key => $value) {
$nomeZip = sprintf("%s.zip", strstr($key, "_", true));
$pathWav = $value;
$nomeMp3 = str_ireplace('.WAV', '.MP3', $key);
$pathMp3 = $baseAudio . $nomeMp3;
$pathZip = $baseAudio . $nomeZip;
if (!CnvrtWavToMp3($pathWav, $pathMp3)) {
GeraExcept(GetLasterror());
}
$filesEncode[] = $nomeMp3;
}
if ($numFiles > 1) {
$cmd = sprintf("cd %s && zip %s %s", $baseAudio, $nomeZip, implode(' ', $filesEncode));
exec($cmd);
}
$downloadFile = ($numFiles > 1) ? $pathZip : $pathMp3;
$nomeDownloadFile = ($numFiles > 1) ? $nomeZip : $nomeMp3;
$fsize = filesize($downloadFile);
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Content-Type: ' . GetMimeContentType($nomeDownloadFile));
header('Content-Length: ' . $fsize);
header('Content-Disposition: attachment; filename="' . $nomeDownloadFile . '"');
header('Connection: close');
readfile($downloadFile);
unlink($downloadFile);
exit;
} catch (Exception $ex) {
GeraExcept($ex->getMessage());
}
}
function DownloadNaoPerturbe($npId)
{
$query = "select np_nome, np_path from pbx_nao_perturbe_controle where np_id = '{$npId}'";
$result = pg_query($query);
$dadosFile = pg_fetch_array($result);
$nome = basename($dadosFile["np_path"]);
$file = $dadosFile["np_path"];
$fsize = filesize($file);
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Content-Type: ' . GetMimeContentType($nome));
header('Content-Length: ' . $fsize);
header('Content-Disposition: attachment; filename="' . $nome . '"');
header('Connection: close');
readfile($file);
exit();
}
function DownloadListaDiscador($ldId)
{
$query = "select ld_nome, ld_path from pbx_lista_discador where ld_id = '{$ldId}'";
$result = pg_query($query);
$dadosFile = pg_fetch_array($result);
$nome = basename($dadosFile["ld_path"]);
$file = $dadosFile["ld_path"];
$fsize = filesize($file);
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Content-Type: ' . GetMimeContentType($nome));
header('Content-Length: ' . $fsize);
header('Content-Disposition: attachment; filename="' . $nome . '"');
header('Connection: close');
readfile($file);
exit();
}
function ConvertWavToMp3($fileOrig, $fileDest)
{
$cmd = sprintf("ffmpeg -y -i %s -acodec libmp3lame %s", $fileOrig, $fileDest);
//ExecutaComando($comando);
exec($cmd);
}
function RegistraLog($log, $file = "aplSimples.log")
{
$mensagem = $log;
$gravaLog = true;
if ($gravaLog && count($mensagem)) {
$pathFull = "/var/log/asterisk/";
/*
* Verifica se o diretorio existe
* se nao existir tenta cria-lo
*/
if (!file_exists($pathFull)) {
mkdir($pathFull);
}
/*
* Arquivo para gravar o log
*/
//$file = sprintf('%s%s_%s_%s.log', $pathFull, $bar, $login, $data);
$file = sprintf('%s%s', $pathFull, $file);
// $file = sprintf('log/_%s_%s.log', $login, $data);
$arq = fopen($file, 'a');
if ($arq) {
foreach ($mensagem as $linha) {
fwrite($arq, "$linha\n");
}
fclose($arq);
$log = array();
}
}
}
function MaxRamaisPermite($db, $qtde)
{
//GetModeloRamais();
$org_id = GetOrganizacao();
$result = pg_query($db, "SELECT prm_max_ramal FROM pbx_parametros WHERE org_id = $org_id;");
$numRamais = pg_fetch_row($result);
if ((int) $numRamais[0] === 0) {
return false;
}
$query = "SELECT count(*) AS num_total_ramais FROM pbx_ramais WHERE org_id = $org_id;";
$result = pg_query($db, $query);
if ($result) {
$row = pg_fetch_row($result);
$numTotalRamais = $qtde + $row[0];
return ($numTotalRamais > $numRamais[0]);
}
return true;
}
function GetNumeroRamalFromId($id)
{
$db = $GLOBALS['dbcon'];
$query = "SELECT nome FROM pbx_ramais WHERE id = '$id'";
$result = pg_query($db, $query);
if ($result && (pg_num_rows($result) > 0)) {
$row = pg_fetch_row($result);
return $row[0];
}
return '0';
}
function GetCrc32Code($tableName, $params)
{
$strCode = $tableName . implode($params);
return abs(crc32($strCode));
}
function GetCrc32CodeExiste($tableName, $code)
{
$db = $GLOBALS['dbcon'];
$query = "SELECT case when(
exists(select '' from $tableName where id_rel = '$code')
)then 1 else 0 end as existe ";
$result = pg_query($db, $query);
$row = pg_fetch_row($result);
return $row[0];
}
function GetIpServer()
{
return $_SERVER['SERVER_ADDR'];
}
function ValidaAutenticaHost()
{
$_GET['autenticaHost'];
return true;
}
function EncodeParam($param)
{
$ret = serialize($param);
$ret = base64_encode($ret);
$ret = urlencode($ret);
return $ret;
}
function GerOperSpid()
{
/*
* n<EFBFBD>mero de operadoras locais devem come<EFBFBD>ar em 900 para n<EFBFBD>o conflitarem com o cadastro da operadoras oficiais
* feitos no servidor.
*/
$db = $GLOBALS['dbcon'];
$operSpid = 900;
$query = "select coalesce(max(oper_spid), 0) as max_spid from pbx_operadoras where oper_spid >= '$operSpid'";
$result = pg_query($db, $query);
$row = pg_fetch_array($result);
$operSpidBd = $row[0];
return !$operSpidBd ? $operSpid : ++$operSpidBd;
}
function PbxOperadoras($id, $eliminaHabilita = 0, $fildId = 'oper_spid')
{
$db = $GLOBALS["dbcon"];
$habilita = $eliminaHabilita ? $eliminaHabilita : HabilitaPortabilidade();
$sel = '';
$query = "select 0 as ord, 0 as $fildId, 'Sem Portabilidade' as oper_nome union all ";
$query .= "select 1 as ord, $fildId, oper_nome || '(' || oper_numero || ')' from pbx_operadoras where 1=$habilita and oper_numero <> '0' order by 1,3";
$result = pg_query($db, $query);
$item = "";
while ($row = pg_fetch_array($result)) {
$spid = $row[$fildId];
$oper = $row["oper_nome"];
if ($spid == $id) {
$sel = "selected";
} else {
$sel = "";
}
$item .= "<option value=\"$spid\" $sel>$oper</option>";
}
return $item;
}
function PbxContratos($id)
{
$db = $GLOBALS["dbcon"];
$org_id = GetOrganizacao();
$sel = '';
if (!$id) {
$sel = "selected";
}
$item = "<option value=\"0\" $sel>------------</option>";
$query = "SELECT contr_id, contr_descricao FROM pbx_tarif_contrato WHERE contr_id <> 0 AND org_id = {$org_id} ORDER BY 2";
$result = pg_query($db, $query);
while ($row = pg_fetch_array($result)) {
$spid = $row["contr_id"];
$oper = $row["contr_descricao"];
if ($spid == $id) {
$sel = "selected";
} else {
$sel = "";
}
$item .= "<option value=\"$spid\" $sel>$oper</option>";
}
return $item;
}
function GetTipoCobranca($idTipo = 1)
{
$tipoCobranca = array("Minuto" => 1, "Chamada" => "2");
$item = '';
foreach ($tipoCobranca as $key => $value) {
$sel = $idTipo == $value ? "selected=\"selected\"" : "";
$item .= "<option value=\"$value\" $sel>$key</option>";
}
return $item;
}
function GravaConfigDb($config)
{
$template = '<?php
/*
* configura<EFBFBD><EFBFBD>o para acesso ao banco de dados principal da aplica<EFBFBD><EFBFBD>o.
*/
$dbPort = getenv(\'DB_PORT\') ? getenv(\'DB_PORT\') : \'%s\';
$dbHost = getenv(\'DB_HOST\') ? getenv(\'DB_HOST\') : \'%s\';
$dbName = getenv(\'DB_BASE\') ? getenv(\'DB_BASE\') : \'%s\';
$dbUser = getenv(\'DB_USER\') ? getenv(\'DB_USER\') : \'%s\';
$dbPassword = getenv(\'DB_PASSWD\') ? getenv(\'DB_PASSWD\') : \'%s\';
/*
* Esta configura<EFBFBD><EFBFBD>o define se o servidor ser<EFBFBD> Master
* e se havera sincroniza<EFBFBD><EFBFBD>o da conta/senha entre os multiplos sites.
* Obs.: Quando n<EFBFBD>o utilizar sincroniza<EFBFBD><EFBFBD>o de conta/senha o valor de
* master deve ser 1.
*/
$master = %s;
$sincContaSenha = %s;
/*
* Quando o arquivo for configurado para slave(master=0) no parametro hostMaster deve ser
* informado o Ip do servidor master.
*/
$hostMaster = \'%s\';
/*
*Informe uma identifica<EFBFBD><EFBFBD>o para o servidor
*/
$serverName = \'%s\';
/*
* Configura<EFBFBD><EFBFBD>es para acesso a api.
*
*/
$hostApi = \'%s\';
$portaApi = \'%s\';
/*
* Acesso ao mysql para real-time.
*
*/
$myParams = array(\'myPort\' => \'%s\',
\'myHost\' => \'%s\',
\'myDatabase\' => \'%s\',
\'myUser\' => \'%s\',
\'myPassword\' => \'%s\'
);
?>';
include DB_CONFIG_FILE;
$_SESSION["SStpServer"] = (!isset($master) | !$master) ? 0 : $master;
$_SESSION["SSsincContaSenha"] = (!isset($sincContaSenha) | !$sincContaSenha) ? 0 : $sincContaSenha;
$_SESSION["SShostMaster"] = (!isset($hostMaster) | !$hostMaster) ? '127.0.0.1' : $hostMaster;
$_SESSION["SSserverName"] = (!isset($serverName) | !$serverName) ? 'MASTER_SERVER' : $serverName;
$config["master"] = $master;
$config["sincContaSenha"] = $sincContaSenha;
$config["hostMaster"] = $hostMaster;
$config["serverName"] = $serverName;
/*
* Incluido manualmente.
*/
$confManual['hostApi'] = $hostApi ? $hostApi : '127.0.0.1';
$confManual['portaApi'] = $portaApi ? $portaApi : '';
$confManual['myPort'] = $myParams['myPort'] ? $myParams['myPort'] : '3306';
$confManual['myHost'] = $myParams['myHost'] ? $myParams['myHost'] : '127.0.0.1';
$confManual['myDatabase'] = $myParams['myDatabase'] ? $myParams['myDatabase'] : 'pabx';
$confManual['myUser'] = $myParams['myUser'] ? $myParams['myUser'] : 'root';
$confManual['myPassword'] = $myParams['myPassword'] ? $myParams['myPassword'] : 'SimpleS_root';
$conteudo = sprintf(
$template,
$config["dbPort"],
$config["dbHost"],
$config["dbName"],
$config["dbUser"],
$config["dbPassword"],
$config["master"],
$config["sincContaSenha"],
$config["hostMaster"],
$config["serverName"],
$confManual['hostApi'],
$confManual['portaApi'],
$confManual['myPort'],
$confManual['myHost'],
$confManual['myDatabase'],
$confManual['myUser'],
$confManual['myPassword']
);
$file = fopen(DB_CONFIG_FILE, 'w', 1);
fwrite($file, $conteudo);
fclose($file);
}
function GravaLogAgente($mensagem)
{
$data = date('dmY');
$file = "/var/log/asterisk/agente_analisa_$data.log";
$arq = fopen($file, 'a');
if ($arq) {
$start = '';
foreach ($mensagem as $linha) {
$linha = trim($linha);
if (!$start) {
$start = $linha;
$linha = "Inicio: " . $linha;
}
fwrite($arq, $linha . "\n");
}
fwrite($arq, "Final: $start\n\n");
fclose($arq);
}
}
function VerificaContrato($dbcon, $contrato, $id)
{
/*
* Foi desabilitado esta verifica<EFBFBD><EFBFBD>o, pois o contrato pode estar ligado a mais de um tronco.
*/
return false;
if (!$contrato)
return false;
if ($id)
$query = "select count(*) from pbx_troncos where contrato = '$contrato' and id <> '$id'";
else
$query = "select count(*) from pbx_troncos where contrato = '$contrato'";
$result = pg_query($dbcon, $query);
// echo $query;
if (!$result)
return true;
$dados = pg_fetch_row($result);
return $dados[0] ? true : false;
}
function VerificaDefaults($db)
{
/*
* Insere contrato padrao
*/
$query = "select count(*) from pbx_tarif_contrato where contr_id = 0";
$result = pg_query($db, $query);
$row = pg_fetch_row($result);
if ($result && !$row[0]) {
$query = "insert into pbx_operadoras values(0, 'Simples IP', 0, '-', 0)";
pg_query($db, $query);
$query = "insert into pbx_tarif_contrato(contr_id, oper_id, empresa, contr_numero, contr_descricao, contr_dia_fechamento, contr_tipo, contr_tipo_franquia) values( 0, '0', '1', '0', 'sem trarifa', '1', 'fixo', '0')";
pg_query($db, $query);
$query = "insert into pbx_tarif_contrato_preco (prc_id,contr_id, prc_vigencia, prc_tipo_opera, prc_tipo, prc_franquia, prc_franquia_movel, prc_franquia_preco, prc_preco_vc1, prc_preco_vc2, prc_preco_vc3, prc_preco_vc4, prc_preco_vc1_cad, prc_preco_vc2_cad, prc_preco_vc3_cad, prc_preco_vc4_cad, prc_preco_vc1_ext, prc_preco_vc2_ext, prc_preco_vc3_ext, prc_preco_vc4_ext)
values('0','0','2013-10-17','0','1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0')";
pg_query($db, $query);
}
/*
* Insere municipio 0, referencia chamadas internas, emergencia e internacional
*/
$query = "select count(*) from pbx_municipios where id = 0";
$result = pg_query($db, $query);
$row = pg_fetch_row($result);
if ($result && !$row[0]) {
$query = "insert into pbx_municipios(id, uf, nome_localidade, nome_municipio, prefixo, faixa_inicial, faixa_final, codigo_ddd)
values(0, 'LC', 'CHAMADAS INTERNAS/EMERGENCIA/INTERNACIONAL', 'CHAMADAS INTERNAS/EMERGENCIA/INTERNACIONAL', 0,0,0,0)";
pg_query($db, $query);
}
/*
* Insere municipio -1, referencia chamadas nao identificadas
*/
$query = "select count(*) from pbx_municipios where id = -1";
$result = pg_query($db, $query);
$row = pg_fetch_row($result);
if ($result && !$row[0]) {
$query = "insert into pbx_municipios(id, uf, nome_localidade, nome_municipio, prefixo, faixa_inicial, faixa_final, codigo_ddd)
values(-1, 'NI', 'CHAMADAS NAO IDENTIFICADAS', 'CHAMADAS NAO IDENTIFICADAS', 0,0,0,0)";
pg_query($db, $query);
}
}
function GetRelativePathScript($__FILE__)
{
$docRoot = $_SERVER['DOCUMENT_ROOT'];
if (IsWin()) {
$docRoot = (str_replace('/', '\\', $_SERVER['DOCUMENT_ROOT'])) . "simplesip";
$docRoot = str_replace($docRoot, '', ($__FILE__));
$docRoot = str_replace('\\', '/', $docRoot);
return $docRoot;
}
return str_replace($docRoot, '', ($__FILE__));
}
function GetFechamentoContrato($ano, $mes, $dia)
{
$finalMes = GetLastDayofMonth($ano, $mes);
if ($dia > $finalMes)
return $finalMes;
return $dia;
}
function PosAguarde()
{
global $cssBlock, $janH, $tpLayout;
$def = (($janH - 50) <= 0) | !$tpLayout;
$height = $def ? '300' : ($janH - 50);
if (!$def)
$height = (int) ($height / 2);
$cssBlock .= sprintf("\n<style type=\"text/css\">
#aguarde
{
position:absolute;
border: 3px solid transparent;
border-radius: 5px;
border-image: linear-gradient(to bottom right, #266CFA, #266EFF) 10;
border-image-slice: 1;
background: #F7F7F7;
width: 150px;
height: 50px;
left: %s;
top: %spx;
margin-left: -75px;
margin-top:-25px;
display:none;
text-align:center;
font-family:Arial, Helvetica, sans-serif;
font-size: 16px;
font-weight:bold;
color:#266CFA;
}\n</style>\n", '50%', $height);
}
/**
*
* @param resource $db
* @param string $query
* @return type
*/
function RegistroInc($db, $query)
{
$result = $db ? pg_query($db, $query) : pg_query($query);
$dados = pg_fetch_row($result);
return $dados[0];
}
function ExisteRegistro($db, $table, $where, $id, $queryParam = null)
{
$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' ";
if ($queryParam) {
$query .= " AND {$queryParam} ";
}
$result = pg_query($db, $query);
$dados = pg_fetch_row($result);
return $dados[0];
}
function GetDacFromCampanha($db, $id)
{
$query = "select id_dac from pbx_campanha where cmp_id = '$id'";
$result = pg_query($db, $query);
$dados = pg_fetch_row($result);
return $dados[0];
}
function GetIdCampanhaFromNome($db, $nomeCampanha)
{
$query = "select cmp_id from pbx_campanha where cmp_descricao = '$nomeCampanha'";
$result = pg_query($db, $query);
$dados = pg_fetch_row($result);
return $dados[0];
}
function GetDataRelatorio()
{
if (!IsUserConnect()) {
$ini['DATA_CORTE']["dataCorteRelatorio"] = 0;
} else if (isset($_SESSION['SSRelDataCorte'])) {
$ini = $_SESSION['SSRelDataCorte'];
} else {
$ini = parse_ini_file("configs/config.ini", true);
$_SESSION['SSRelDataCorte'] = $ini;
}
return $ini['DATA_CORTE']["dataCorteRelatorio"];
}
function LimpaToExcel($str)
{
return $str;
return preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i", '<$1$2>', $str);
/*
/ # Start Pattern
< # Match '<' at beginning of tags
( # Start Capture Group $1 - Tag Name
[a-z] # Match 'a' through 'z'
[a-z0-9]* # Match 'a' through 'z' or '0' through '9' zero or more times
) # End Capture Group
[^>]*? # Match anything other than '>', Zero or More times, not-greedy (wont eat the /)
(\/?) # Capture Group $2 - '/' if it is there
> # Match '>'
/i # End Pattern - Case Insensitive
*/
}
function EnviaExcel($nomeFile, $str)
{
ob_end_clean();
ob_start();
$file = $nomeFile;
header("Pragma: public");
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Accept-Ranges: bytes');
header('Content-Type: ' . GetMimeContentType($file));
header('Content-Disposition: attachment; filename="' . $file . '";');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
print($str);
ob_flush();
exit;
}
function GetDirArqSom($conexao)
{
$dir = function_exists('GetPathSom') ? (GetPathSom() . 'arquivos_mp3/') : ($_SESSION["path_som"] . 'arquivos_mp3/');
if (!file_exists($dir)) {
$comando = "mkdir $dir";
vai_comando($comando, $conexao);
$comando = "chown pbx:pbx $dir";
vai_comando($comando, $conexao);
if (!file_exists($dir))
return false;
}
return 'arquivos_mp3/';
}
function GetMimeContentType($file)
{
$filetype = strtolower(substr(strrchr($file, '.'), 1));
$mimetypes = array(
"ez" => "application/andrew-inset",
"rar" => "application/archive-rar",
"atom" => "application/atom+xml",
"ccad" => "application/clariscad",
"drw" => "application/drafting",
"tsp" => "application/dsptype",
"dxf" => "application/dxf",
"unv" => "application/i-deas",
"hqx" => "application/mac-binhex40",
"cpt" => "application/mac-compactpro",
"pps" => "application/mspowerpoint",
"doc" => "application/msword",
"bin" => "application/octet-stream",
"oda" => "application/oda",
"pdf" => "application/pdf",
"ps" => "application/postscript",
"prt" => "application/pro_eng",
"set" => "application/set",
"smil" => "application/smil",
"sol" => "application/solids",
"vda" => "application/vda",
"mif" => "application/vnd.mif",
"xls" => "application/vnd.ms-excel",
"xlsx" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"wbxml" => "application/vnd.wap.wbxml",
"wmlc" => "application/vnd.wap.wmlc",
"wmlsc" => "application/vnd.wap.wmlscriptc",
"bcpio" => "application/x-bcpio",
"vcd" => "application/x-cdlink",
"pgn" => "application/x-chess-pgn",
"cpio" => "application/x-cpio",
"csh" => "application/x-csh",
"dxr" => "application/x-director",
"dvi" => "application/x-dvi",
"pre" => "application/x-freelance",
"spl" => "application/x-futuresplash",
"gtar" => "application/x-gtar",
"gz" => "application/x-gzip",
"hdf" => "application/x-hdf",
"php" => "application/x-httpd-php",
"phps" => "application/x-httpd-php-source",
"ipx" => "application/x-ipix",
"ips" => "application/x-ipscript",
"js" => "application/x-javascript",
"skp" => "application/x-koan",
"latex" => "application/x-latex",
"lsp" => "application/x-lisp",
"scm" => "application/x-lotusscreencam",
"cdf" => "application/x-netcdf",
"sh" => "application/x-sh",
"shar" => "application/x-shar",
"flv" => "application/x-shockwave-flash",
"sit" => "application/x-stuffit",
"sv4cpio" => "application/x-sv4cpio",
"sv4crc" => "application/x-sv4crc",
"tar" => "application/x-tar",
"tcl" => "application/x-tcl",
"tex" => "application/x-tex",
"texinfo" => "application/x-texinfo",
"t" => "application/x-troff",
"man" => "application/x-troff-man",
"me" => "application/x-troff-me",
"ms" => "application/x-troff-ms",
"ustar" => "application/x-ustar",
"src" => "application/x-wais-source",
"xhtml" => "application/xhtml+xml",
"zip" => "application/zip",
"tsi" => "audio/TSP-audio",
"au" => "audio/basic",
"mid" => "audio/midi",
"mpga" => "audio/mpeg",
"aiff" => "audio/x-aiff",
"m3u" => "audio/x-mpegurl",
"ram" => "audio/x-pn-realaudio",
"rpm" => "application/x-rpm",
"ra" => "audio/x-realaudio",
"wav" => "audio/x-wav",
"wma" => "audio/x-wma",
"pdb" => "chemical/x-pdb",
"xyz" => "chemical/x-xyz",
"bmp" => "image/bmp",
"gif" => "image/gif",
"ief" => "image/ief",
"jpg" => "image/jpeg",
"png" => "image/png",
"tiff" => "image/tiff",
"djv" => "image/vnd.djvu",
"wbmp" => "image/vnd.wap.wbmp",
"ras" => "image/x-cmu-raster",
"pnm" => "image/x-portable-anymap",
"pbm" => "image/x-portable-bitmap",
"pgm" => "image/x-portable-graymap",
"ppm" => "image/x-portable-pixmap",
"rgb" => "image/x-rgb",
"xbm" => "image/x-xbitmap",
"xpm" => "image/x-xpixmap",
"xwd" => "image/x-xwindowdump",
"igs" => "model/iges",
"silo" => "model/mesh",
"wrl" => "model/vrml",
"css" => "text/css",
"htm" => "text/html",
"c" => "text/plain",
"rtx" => "text/richtext",
"rtf" => "text/rtf",
"sgml" => "text/sgml",
"tsv" => "text/tab-separated-values",
"wml" => "text/vnd.wap.wml",
"wmls" => "text/vnd.wap.wmlscript",
"etx" => "text/x-setext",
"xml" => "text/xml",
"mpg" => "video/mpeg",
"qt" => "video/quicktime",
"mxu" => "video/vnd.mpegurl",
"fli" => "video/x-fli",
"wmv" => "video/x-msvideo",
"movie" => "video/x-sgi-movie",
"ice" => "x-conference/x-cooltalk",
"exe" => "application/octet-stream",
"csv" => "application/octet-stream",
"txt" => "text/plain"
);
return $mimetypes[$filetype];
}
function RetornaAbandon($db, $fila, $ramal, $origem = "agente", $lb = "Sem Retorno:", $absr = 0)
{
global $arRetornoAbandonadas, $statusServer;
$qtd = $statusServer ? $absr : (isset($arRetornoAbandonadas[$fila]) ? $arRetornoAbandonadas[$fila] : 0);
return ($qtd < 1) ? "$lb 0" : sprintf("<a href=\"javaScript:NovaJanela('index.php?idProg=230&dac=%s&ramal=%s&origem=%s&tpLayout=2', 'agtRelSupAbandonada', '900', '500', 'scrollbars=YES');\" title=\"Abandonadas Sem Retorno!\"><span style=\"%scolor:%s\">%s %s</span></a>", $fila, $ramal, $origem, ($origem == 'agente' ? "font-size:10px;" : ""), ($qtd ? 'red' : 'balck'), $lb, $qtd);
}
function SetAbandonasFila()
{
global $arRetornoAbandonadas, $statusServer, $dbcon;
if ($statusServer)
return;
$diasAbandon = GetDiasAbandonada($dbcon);
$query = sprintf("SELECT b.fila, count(*) as qtde
FROM pbx_abandonadas_semretorno a
INNER JOIN ast_eventos_dacs b ON a.abdsr_uniqueid = b.uid2 AND b.fila = a.abdsr_fila
INNER JOIN ast_bilhetes c ON a.abdsr_uniqueid = c.uniqueid AND c.calldate = (SELECT MAX(calldate) FROM ast_bilhetes WHERE uniqueid = a.abdsr_uniqueid)
WHERE a.abdsr_data_hora_retorno is null
AND a.abdsr_data >= (now()::date - %s)
AND b.evento = 'ABANDON'
GROUP BY b.fila
ORDER BY 1", $diasAbandon);
$result = pg_query($dbcon, $query);
while ($dados = pg_fetch_row($result)) {
$dac = $dados[0];
$arRetornoAbandonadas[$dac] = $dados[1];
}
}
function GetStyleLink($links)
{
$lkText = "";
$lkText .= "<link rel=\"stylesheet\" href=\"master.css\" type=\"text/css\" />\n";
$lkText .= "<link rel=\"stylesheet\" href=\"scriptApl/menu.css\" type=\"text/css\" />\n";
$lkText .= "<link rel=\"stylesheet\" href=\"agente.css\" type=\"text/css\" />\n";
$lkText .= "<link href=\"relProdAgenteGrid.css\" type=\"text/css\" rel=\"stylesheet\" /> \n";
$lkText .= "<link href=\"cadGeral.css\" type=\"text/css\" rel=\"stylesheet\" />\n";
//$lkText .= "<link href=\"jqueryCalendario.css\" type=\"text/css\" rel=\"stylesheet\" />\n";
$lkText .= "<link href=\"admin/css/pbx.css\" type=\"text/css\" rel=\"stylesheet\" />\n";
//$lkText .= "<link href=\"admin/css/print.css\" type=\"text/css\" rel=\"stylesheet\" />\n";
//$lkText .= "<link href=\"admin/utils/popups.css\" type=\"text/css\" rel=\"stylesheet\" />\n";
$lkText .= "<link rel=\"stylesheet\" href=\"jquery-ui/jquery-ui.min.css\" type=\"text/css\" />\n";
$lkText .= "<link rel=\"stylesheet\" href=\"jquery-ui/jquery-ui.theme.min.css\" type=\"text/css\" />\n";
return $lkText;
}
function GetJsLink($links)
{
/*
* retornas links passados no array como string
* para ser inserida no head da pagina
*/
$lkText = "";
foreach ($links as $value) {
$idHand = "?idHand=" . time();
if (!empty($value))
$lkText .= "<script type=\"text/javascript\" src=\"$value$idHand\"></script>" . "\n";
}
return $lkText;
}
function GetJsBlok($command, $incTag = true)
{
/*
* retornas links passados no array como string
* para ser inserida no head da pagina
*/
//if(count($command) == 0) return "";
$lkText = $incTag ? "<script language=\"JavaScript\" type=\"text/javascript\"> \n <!-- \n" : "";
foreach ($command as $value) {
if (!empty($value))
$lkText .= " $value\n";
}
$lkText .= $incTag ? " //-->\n </script>\n" : "";
return $lkText;
}
function __GetApi($url, $params = array(), $type = 'POST')
{
/*
* Para arquivos passe o parametro no formato indicado:
* "'file_contents'=>'@'.$file_name_with_full_path";
* Exemplo array params:
* array('extra_info' => '123456','file_contents'=>'@'.$file_name_with_full_path);
*/
$server_output = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
return $server_output;
}
function GetIpUsuario()
{
return $_SERVER['REMOTE_ADDR'];
}
function RegistraAcesso($login, $id)
{
try {
$infoDispositivo = new Browser();
$logAcess = "Browser:%s|Platform:%s|Version:%s|Agent:%s|Mobile:%s|Robot:%s";
$logAcess = sprintf(
$logAcess,
$infoDispositivo->getBrowser(),
$infoDispositivo->getPlatform(),
$infoDispositivo->getVersion(),
$infoDispositivo->getUserAgent(),
$infoDispositivo->isMobile() ? '1' : '0',
$infoDispositivo->isRobot() ? '1' : '0'
);
$query = "update pbx_controle_acesso set acs_data_fim = coalesce(acs_data_ultacess, now()) where acs_login = %s and acs_data_fim is null;";
$query = sprintf($query, QuotedStr($login));
pg_query($query);
$query = "insert into pbx_controle_acesso(acs_ip, acs_sessao, acs_login, acs_user_id, acs_log ) values(%s,%s,%s,%s,%s)";
$query = sprintf($query, QuotedStr(GetIpUsuario()), QuotedStr(session_id()), QuotedStr($login), QuotedStr($id), QuotedStr($logAcess));
$result = pg_query($query);
if (!$result) {
throw new Exception("Erro ao registrar acesso ao sistema!");
}
$_SESSION["SSRegAcessoId"] = GetCurrVal("pbx_controle_acesso");
return true;
} catch (Exception $ex) {
GravaLogForms($ex->getMessage(), "RegistraAcesso");
return false;
}
}
function RegistraAcessoItem($idProg)
{
try {
if (IsAjax()) {
return true;
}
$_SESSION['UltimaRequisicao'] = $_SERVER['REQUEST_URI'];
if (!$_SESSION["SSRegAcessoId"]) {
throw new Exception("Registro de acesso n<EFBFBD>o iniciado!");
}
$query = "insert into pbx_controle_acesso_item(acs_id, acsi_prog)values(%s,%s)";
$query = sprintf($query, QuotedStr($_SESSION["SSRegAcessoId"]), QuotedStr($idProg));
$result = pg_query($query);
if (!$result) {
throw new Exception("Erro ao registrar acesso ao sistema!");
}
$query = "update pbx_controle_acesso set acs_data_ultacess = now(), acs_prog_ultacess = %s where acs_id = %s";
$query = sprintf($query, QuotedStr($idProg), QuotedStr($_SESSION["SSRegAcessoId"]));
$result = pg_query($query);
if (!$result) {
throw new Exception("Erro ao atualizar acesso ao sistema!");
}
return true;
} catch (Exception $ex) {
GravaLogForms($ex->getMessage(), "RegistraAcessoItem");
return false;
}
}
function RegistraErroAcesso($login, $senha)
{
try {
$infoDispositivo = new Browser();
$logAcess = "Login:%s|Senha:%s|Browser:%s|Platform:%s|Version:%s|Agent:%s|Mobile:%s|Robot:%s";
$logAcess = sprintf(
$logAcess,
$login,
$senha,
$infoDispositivo->getBrowser(),
$infoDispositivo->getPlatform(),
$infoDispositivo->getVersion(),
$infoDispositivo->getUserAgent(),
stripos($infoDispositivo->getUserAgent(), "Mobile") !== false ? 1 : 0,
$infoDispositivo->isRobot() ? '1' : '0'
);
//$infoDispositivo->isMobile() ? '1' : '0',
$id = '-1';
$login = substr($login, 0, 32);
$query = "insert into pbx_controle_acesso(acs_ip, acs_sessao, acs_login, acs_user_id, acs_log, acs_erro ) values(%s,%s,%s,%s,%s, '1')";
$query = sprintf($query, QuotedStr(GetIpUsuario()), QuotedStr(session_id()), QuotedStr($login), QuotedStr($id), QuotedStr($logAcess));
$result = pg_query($query);
if (!$result) {
throw new Exception("Erro ao registrar acesso ao sistema!");
}
return true;
} catch (Exception $ex) {
GravaLogForms($ex->getMessage(), "RegistraErroAcesso");
return false;
}
}
function GetTempoSessao()
{
if ($_SESSION["prm_tempo_sessao"]) {
return $_SESSION["prm_tempo_sessao"];
}
$query = "select prm_tempo_sessao from pbx_parametros";
$result = pg_query($query);
$row = pg_fetch_row($result);
return $row[0];
}
function SessionExpire()
{
if (!IsUserConnect()) {
return false;
}
$sessionTime = GetTempoSessao() ? GetTempoSessao() : 20;
$maxSession = $sessionTime * 60;
$hStart = (int) $_SESSION["SSTimeOut"];
$hAtu = time();
$tSessin = $hAtu - $hStart;
if ($tSessin > $maxSession) {
return true;
}
$_SESSION["SSTimeOut"] = $hAtu;
return false;
}
function GetFileFromIdProg($idProg, $coluna = 'arquivo')
{
if (!isset($idProg)) {
global $idProg;
}
$query = " select * from pbx_funcoes_internas where id_prog = '$idProg'";
$result = pg_query($query);
if (!$result)
return "$idProg";
$row = pg_fetch_array($result);
return $row[$coluna];
}
function GetFieldFromIdProg($idProg, $field)
{
return GetFileFromIdProg($idProg, $field);
}
function GetIdProgFromNomeArq($nomeArq)
{
$query = "select id_prog from pbx_funcoes_internas where arquivo like '%$nomeArq' ";
$result = pg_query($query);
if (!$result || !pg_num_rows($result)) {
return false;
}
$row = pg_fetch_array($result);
return $row['id_prog'];
}
function GetIdProgFromNomeMenu($nomeMenu)
{
$query = "select id_prog from pbx_funcoes where fun_nome = '{$nomeMenu}';";
$result = pg_query($query);
if (!$result || !pg_num_rows($result)) {
return false;
}
$row = pg_fetch_array($result);
return $row['id_prog'];
}
function GravaLogForms($mensagem, $metodo = "padrao", $erro = 1)
{
global $idProg;
$connect = pg_connect(GetConectString(), PGSQL_CONNECT_FORCE_NEW);
$data = date('dmY');
$login = GetLogin();
$path = GetFileFromIdProg($idProg);
$scrp = basename($path);
$datadb = date('Y-m-d H:i:s');
$file = sprintf("/var/log/asterisk/log_forms_%s_%s.log", $erro ? "erro" : "reg", $data);
$arq = fopen($file, 'a');
if ($arq) {
$linha = sprintf("Data: %s User: %s File: %s Metodo: %s \n", $data, $login, $scrp, $metodo);
fwrite($arq, $linha);
$linha = sprintf("Mensagem: %s\n", $mensagem);
fwrite($arq, $linha);
$erroSys = error_get_last();
$linha = sprintf("Sistema:\n[type: %s File: %s Line: %s]\nMsg: %s\n\n", $erroSys['type'], $erroSys['file'], $erroSys['line'], $erroSys['message']);
fwrite($arq, $linha);
fclose($arq);
}
$filesys = str_replace('\\', '/', $erroSys['file']);
$mensagem = str_replace('\"', '"', $mensagem);
$query = sprintf("insert into pbx_log_forms(log_msg, log_msg_sys, log_type_sys, log_file_sys, log_line_sys, log_file_form, id_prog, log_usuario, log_data)
values(%s,%s,%s,%s,%s,%s,%s,%s,%s)", QuotedStr($mensagem), QuotedStr($erroSys['message']), QuotedStr($erroSys['type']), QuotedStr($filesys), QuotedStr($erroSys['line']), QuotedStr($scrp), QuotedStr($idProg), QuotedStr($login), QuotedStr($datadb));
pg_query($connect, $query);
}
function GrvAudita($db, $idProg, $nomeTabela, $tipoOper, $velho, $novo, $campoNome, $keyTable = array('id'), $silent = false)
{
try {
$aud_uid = time();
$data = date("Y-m-d H:i:s");
$login = GetLogin();
$aud_ip = $_SERVER['REMOTE_ADDR'];
$reg_id = $_SESSION["SSRegAcessoId"];
$org_id = GetOrganizacao();
$sql = "INSERT INTO pbx_audita(id_prog, aud_ip, aud_tabela, aud_campo, aud_campo_display, aud_operacao, aud_valor_antigo, aud_valor_novo, reg_id, user_reg, aud_uid, org_id)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);";
$update = $novo;
//if($tipoOper == 'DEL'){ $update = $velho; }
if ($tipoOper == 'INS') {
$velho = array();
}
foreach ($update as $key => $value) {
$campo = $key;
$valorVelho = isset($velho[$key]) ? $velho[$key] : '';
$valorNovo = isset($novo[$key]) ? $novo[$key] : '';
$aud_campo_display = isset($campoNome[$key]) ? $campoNome[$key] : $key;
/*
* Grava log apenas para valores alterados.
*/
if (($valorVelho != $valorNovo) || (array_search($key, $keyTable) !== false)) {
$query = sprintf(
$sql,
QuotedStr($idProg),
QuotedStr($aud_ip),
QuotedStr($nomeTabela),
QuotedStr($campo),
QuotedStr($aud_campo_display),
QuotedStr($tipoOper),
IsNullQuoted($valorVelho),
IsNullQuoted($valorNovo),
QuotedStr($reg_id),
QuotedStr($login),
QuotedStr($aud_uid),
$org_id
);
$result = pg_query($db, $query);
if (!$result) {
throw new Exception("GrvAudita|Login=$login|Data=$data|CMD=[$query]");
}
}
}
if ($silent) {
return true;
}
} catch (Exception $ex) {
GravaLogForms($ex->getMessage());
if ($silent)
return false;
GeraExcept("N<EFBFBD>o foi possivel gravar a auditoria!");
}
}
function GrvLog($grvLog)
{
$data = date("Y-m-d");
$dir = "/var/log/asterisk/pbx_audita/";
if (!file_exists($dir)) {
system(sprintf("mkdir -p %s", $dir));
}
$file = sprintf("%s/%s.log", $dir, $data);
$arq = fopen($file, 'a');
if ($arq) {
fwrite($arq, $grvLog);
fclose($arq);
}
}
function SetDadosOld($arOld = array())
{
$_SESSION['SSoldDados'] = $arOld;
}
function GetDadosOld()
{
return isset($_SESSION['SSoldDados']) ? $_SESSION['SSoldDados'] : array();
}
function PbxFechaPopup($url = '')
{
echo sprintf("<script type=\"text/javascript\">fecha_popup('0','%s');</script>", $url);
}
function PbxAlert($msg)
{
echo "<script type=\"text/javascript\">alert('" . $msg . "');</script>";
}
function GravaFull($__idProg = 0, $uniqueid = '', $msg = '', $param = '')
{
if (IsUserConnect() || $param) {
global $idProg, $dbcon;
$dir = '/var/log/asterisk/audita';
if (!file_exists($dir)) {
system("mkdir -p $dir");
system("chmod 777 -R $dir");
}
if ($__idProg) {
$idProg = $__idProg;
}
$org_id = GetOrganizacao();
$path = $dir . sprintf('/simplesFull.log');
$uid = $uniqueid ? $uniqueid : time();
$login = ($param ? $param : GetLogin());
$ip = GetIpUsuario();
if (empty($param)) {
$programa = explode("/", GetFileFromIdProg($idProg));
$programa = $programa[(count($programa) - 1)];
} else {
$programa = 'login.php';
}
$data = date('Y-m-d H:i:s');
$arAudita = array('uid' => $uid, 'ip' => $ip, 'data' => $data, 'login' => $login, 'prog' => $programa, 'msg' => $msg, 'request' => $_REQUEST, 'session' => $_SESSION);
$log = json_encode($arAudita, JSON_INVALID_UTF8_SUBSTITUTE);
if (!file_exists($path)) {
$file = @fopen($path, 'w+');
} else {
$file = @fopen($path, 'a');
}
if (is_readable($path) && ($file !== null)) {
fwrite($file, ($log . "\n"));
fclose($file);
}
$uid = time();
/*
* Log no banco de dados.
*/
$query = "INSERT INTO pbx_audita_full(login,id_prog,full_ip,full_uid,full_prog_nome,full_tipo,full_log,org_id) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)";
$query = sprintf($query, QuotedStr($login), QuotedStr($idProg), QuotedStr($ip), QuotedStr($uid), QuotedStr($programa), QuotedStr(IsPostBack() ? 'POST' : 'GET'), QuotedStr($log), $org_id);
pg_query($dbcon, $query);
}
}
function CommandoAmi($params)
{
list($sckHost, $sckPort, $sckUser, $sckPass) = GetSckConnect();
$socket = ConectaAmi($sckHost, $sckPort, $sckUser, $sckPass);
if ($socket) {
return ExecutaAmi($socket, $params);
}
return false;
}
function SetCookieApl($name, $value, $expire = -1)
{
if ($expire === -1) {
$expire = time() + 60 * 60 * 24 * 300;
}
return setcookie($name, $value, $expire);
}
function GetCookieApl($name)
{
if (!isset($_COOKIE[$name])) {
return false;
}
$_SESSION[$name] = $_COOKIE[$name];
return $_COOKIE[$name];
}
function GetRamalMonitorar($name)
{
return isset($_SESSION[$name]) ? $_SESSION[$name] : null;
}
function ValidaRamalApl($ramal)
{
/*
* Esta fun<EFBFBD><EFBFBD>o verifica se o ramal existe, e retorna o canal se o ramal <EFBFBD> valido.
*/
global $dbcon;
$query = "select dispositivo from pbx_ramais where nome = '$ramal'";
$result = pg_query($dbcon, $query);
if (!$result || !pg_num_rows($result)) {
return false;
}
$row = @pg_fetch_row($result);
return $row[0];
}
function SetAcessoAudio($dac)
{
/*
* Desativado o uso de sessoes.
*/
global $dbcon;
$acessAudio = 0;
$idUser = GetIdUser();
//$query = "select '' from pbx_fila_audios x, pbx_grupo_usuario y where y.gp_id = x.gp_id and y.user_id = $idUser and x.id = '$dac'";
$query = "select '' from pbx_fila_audios x, pbx_grupo_usuario y, pbx_dacs z where y.gp_id = x.gp_id and z.id = x.id and y.user_id = '$idUser' and z.nome = '$dac'";
$result = pg_query($dbcon, $query);
if ($result && pg_num_rows($result)) {
$acessAudio = 1;
}
return $acessAudio;
$_SESSION['SSAcessoAudio'] = $acessAudio;
}
function GetAcessoAudio($dac)
{
global $dbcon;
$idUser = GetIdUser();
//$query = "select '' from pbx_fila_audios x, pbx_grupo_usuario y where y.gp_id = x.gp_id and y.user_id = $idUser and x.id = '$dac'";
$query = "select '' from pbx_fila_audios x, pbx_grupo_usuario y, pbx_dacs z where y.gp_id = x.gp_id and z.id = x.id and y.user_id = '$idUser' and z.nome = '$dac'";
$result = pg_query($dbcon, $query);
if ($result && pg_num_rows($result)) {
return 1;
}
return 0;
/*
return SetAcessoAudio($dac);
if(isset($_SESSION['SSAcessoAudio']))
{
return $_SESSION['SSAcessoAudio'];
}
SetAcessoAudio($dac);
return $_SESSION['SSAcessoAudio'];
*
*/
}
function ConfigRamalMonitorar()
{
try {
$nomeRamalMonitorar = ($_REQUEST['nomeRamalMonitorar']);
$nomecanalMonitorar = ($_REQUEST['nomeCanalMonitorar']);
$ramalMonitorar = $_REQUEST['ramalMonitorar'];
/*
* fun<EFBFBD><EFBFBD>o verifica se o ramal <EFBFBD> v<EFBFBD>lido, retornando ok caso afirmativo.
*/
$canalMonitorar = ValidaRamalApl($ramalMonitorar);
/*
* Ramal inv<EFBFBD>lido retorna falso.
*/
if ($canalMonitorar === false) {
GeraExcept("Erro;Ramal inv<EFBFBD>lido!");
}
if (!SetCookieApl($nomeRamalMonitorar, $ramalMonitorar)) {
GeraExcept("Erro;N<EFBFBD>o foi poss<EFBFBD>vel registrar o \"Ramal\"!");
}
if (!SetCookieApl($nomecanalMonitorar, $canalMonitorar)) {
GeraExcept("Erro;N<EFBFBD>o foi poss<EFBFBD>vel registrar o \"Canal\"!");
}
$_SESSION[$nomeRamalMonitorar] = $ramalMonitorar;
$_SESSION[$nomecanalMonitorar] = $canalMonitorar;
echo "OK;$ramalMonitorar";
} catch (Exception $ex) {
echo $ex->getMessage();
}
}
function GetIdentRota($dbcon, $codServ = 0, $wdt = 160)
{
$codSel = $codServ;
$width = $wdt ? "style=\"max-width: {$wdt}px\"" : "";
$serv = "<select name=\"listaServico\" id=\"listaServico\" size=\"1\" $width>";
$sel = $codSel == '0' ? "selected" : "";
$serv .= "<option value=\"0\" $sel>Todos</option>";
$org_id = GetOrganizacao();
$cont = 0;
$i = 0;
$query = "SELECT serv_id AS identificador FROM pbx_servicos WHERE serv_status = 1 AND org_id = $org_id ORDER BY 1";
$result = pg_query($dbcon, $query);
while ($dados = pg_fetch_row($result)) {
if ($codSel === $dados[0]) {
$sel = "selected";
} else {
$sel = "";
}
$serv .= "<option value=\"$dados[0]\" $sel>$dados[0]</option>";
}
$serv .= "</select>";
return $serv;
}
function AtualizaLinkAgente()
{
global $alturaTabelaAgente;
$query = "select prm_agente_nova_janela, prm_use_discador from pbx_parametros";
$result = pg_query($query);
$dados = pg_fetch_array($result, null, PGSQL_ASSOC);
$novaJanela = $dados['prm_agente_nova_janela'];
$useDiscador = $dados['prm_use_discador'];
$link = 'index.php?idProg=14';
$alturaJanAgt = 540;
if ($novaJanela) {
$link = GetLinkNovaJanela(840, ($useDiscador ? $alturaJanAgt : $alturaTabelaAgente), 'index.php?idProg=14', 'AgenteCallcenter');
}
$query = sprintf("update pbx_funcoes set fun_menu_url = %s where fun_nome = 'mnAgente'", QuotedStr($link));
$result = pg_query($query);
return $result ? true : false;
}
function AtualizaMenuVendas($status)
{
if (!$status) {
$_SESSION['prm_use_vendas'] = $status;
$query = sprintf("delete from pbx_funcoes where fun_nome in(%s, %s)", QuotedStr('mnConsolidaVendas'), QuotedStr('mnConsolidaVendasFunil'));
$result = pg_query($query);
}
}
function GetInfoCampanha($dac, $retArray = 0)
{
$table = "<table style=\"border:0\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\">";
$query = "select count(distinct a.cmp_id) as cmp_ativa, count(*) as numero_contatos, sum(case when(c.cont_discado = 1)then 1 else 0 end) as numero_discado
from pbx_campanha a
inner join pbx_campanha_lista b on b.cmp_id = a.cmp_id and b.list_status = 1
inner join pbx_campanha_contato c on c.list_id = b.list_id
where a.id_dac = (select id from pbx_dacs where nome = '$dac')
and a.cmp_status in(1,2)";
$result = pg_query($query);
if ($result) {
$linha = '';
if ($dados = pg_fetch_array($result, null, PGSQL_ASSOC)) {
$cmpAtv = $dados["cmp_ativa"] ? $dados["cmp_ativa"] : 0;
$conts = $dados["numero_contatos"] ? $dados["numero_contatos"] : 0;
$disc = $dados["numero_discado"] ? $dados["numero_discado"] : 0;
$cmp = sprintf('<span title="Campanhas Ativas!">%s</span>', $cmpAtv);
$contatos = sprintf('<span title="Contatos da Lista!">%s</span>', $conts);
$discados = sprintf('<span title="Contatos Discados">%s</span>', $disc);
$lkCamp = ($cmpAtv == 0) ? $cmp : sprintf("<a href=\"javaScript:NovaJanela('index.php?idProg=275&dac=$dac&tpLayout=2', 'jnRelSupRecebidas', '900', '500', 'scrollbars=YES');\" title=\"Campanhas Ativas/Detalhamento!\" style=\"color:black;\" >%s</a>", $cmpAtv);
$linha = "$table<tr><td style=\"border:0; width: 20%;\" align=\"right\">$lkCamp</td><td style=\"border:0; width: 40%;\" align=\"right\">$contatos</td><td style=\"border:0; width: 40%;\" align=\"right\">$discados</td></tr></table>";
return $retArray ? $dados : $linha;
}
}
return false;
}
function GetDiscadorRestantes($dac, $matricula, $idCampanha = null)
{
$lista = '';
$cmplCamp = '';
/**
* Verifica se a campanha <EFBFBD> exclusiva
*/
if ($idCampanha) {
$sql = "SELECT cmp_seletiva FROM pbx_campanha WHERE cmp_id = {$idCampanha}";
$res = pg_query($sql);
$cmpExclusiva = pg_fetch_assoc($res);
if ($cmpExclusiva['cmp_seletiva'] == 1) {
$cmplCamp .= " AND conf_matricula_exclusiva = '{$matricula}' ";
}
}
/*
* Pega a lista de status da Opera<EFBFBD><EFBFBD>o.
*/
$query = "select count(*) as quantidade_contatos,
count(*) - sum(case when(c.cont_discado = 0)then 0 else 1 end) as contatos_restantes
from pbx_campanha_usuarios u
inner join pbx_campanha a on a.cmp_id = u.cmp_id and a.cmp_status = 1 and a.id_dac = '$dac'
inner join pbx_campanha_lista b on b.cmp_id = a.cmp_id and b.list_status = 1
inner join pbx_campanha_contato c on c.list_id = b.list_id $cmplCamp
where u.matricula = '$matricula'";
$result = pg_query($query);
if (!$result || !pg_num_rows($result)) {
return array("quantidade_contatos" => "0", "quantidade_discados" => "0", "contatos_restantes" => "0");
}
$dados = @pg_fetch_row($result);
return array("quantidade_contatos" => $dados[0], "quantidade_discados" => ($dados[0] - $dados[1]), "contatos_restantes" => $dados[1]);
}
function PaginacaoRegPagina()
{
return $_SESSION['prm_registro_pagina'];
}
function PaginacaoSql($sql)
{
/*
* Prepara a query para countar a quantidade todal de registros.
*/
$inicio = stripos($sql, "from") + 4;
$fim = stripos($sql, "order by") ? stripos($sql, "order by") - 1 : stripos($sql, "limit") - 1;
if ($fim <= 0) {
$fim = strlen($sql);
}
$sql = "select count(*) from " . substr($sql, $inicio, $fim - $inicio);
return $sql;
}
function PaginacaoTotalReg($sql, $idProg, $force)
{
global $recontaPag, $dbcon;
/*
* O objetivo da fun<EFBFBD><EFBFBD>o <EFBFBD> retornar o total de registro que a consulta ira
* conter para calcular a pagina<EFBFBD><EFBFBD>o.
*/
$md5Sql = md5($sql);
$idxPagina = "SSPaginacaoTotalReg_" . $idProg;
$idxPaginaMD5 = "SSPaginacaoMD5_" . $idProg;
/*
* Um hash md5 da consulta <EFBFBD> gravado em uma variavel de sess<EFBFBD>o para
* verificar se houve altera<EFBFBD><EFBFBD>o na mesma, retorna o valor recuperado
* na primeira consulta efetuada se n<EFBFBD>o sofreu altera<EFBFBD><EFBFBD>o.
*/
if (!$recontaPag && isset($_SESSION[$idxPaginaMD5]) && ($_SESSION[$idxPaginaMD5] == $md5Sql)) {
return $_SESSION[$idxPagina];
}
/*
* Esta fun<EFBFBD><EFBFBD>o prepara a consulta original para trazer apenas um count.
*/
$query = $force ? $sql : PaginacaoSql($sql);
$result = pg_query($dbcon, $query);
$row = $force ? pg_num_rows($result) : pg_fetch_row($result);
/*
* Grava o md5 da consulta para compara<EFBFBD><EFBFBD>oo posterior e tamb<EFBFBD>m a quantidade de
* registros para retornar a aplica<EFBFBD><EFBFBD>o.
*/
$_SESSION[$idxPaginaMD5] = $md5Sql;
return ($_SESSION[$idxPagina] = $force ? $row : $row[0]);
}
function PaginaDados($idProg, &$sql, &$params, &$regPagina, &$offSet, &$pagMostra, $force = false)
{
global $totalReg;
/*
* Quantas paginas s<EFBFBD>o mostrados no rodape.
*/
$tamBloco = PAGINACAO_TAMANHO_BLOCO;
/*
* Quantas linhas s<EFBFBD>o mostradas por p<EFBFBD>gina.
*/
$regPagina = StrToIntDef(PaginacaoRegPagina(), 20);
/*
* Calcula o total de registros a serem recuperados.
* Em alguns casos o total de registros <EFBFBD> passado direto
* na variavel $sql como um inteiro.
*/
$org_id = GetOrganizacao();
// if (strpos($sql, 'org_id') === false && strpos($sql, 'id_organizacao') === false) {
// if (strpos($sql, 'where') !== false) {
// $sql = str_replace("where", "where org_id = {$org_id} and", $sql);
// } else if (strpos($sql, 'WHERE') !== false) {
// $sql = str_replace("WHERE", "WHERE org_id = {$org_id} AND", $sql);
// }
// }
if (strpos($sql, 'org_id') === false && strpos($sql, 'id_organizacao') === false) {
$org_condition = "org_id = {$org_id}";
// Substituir todas as ocorr<EFBFBD>ncias de 'where' ou 'WHERE' pela condi<EFBFBD><EFBFBD>o com 'AND'
10 months ago
$sql = str_replace(array('where', 'WHERE'), "WHERE $org_condition AND", $sql);
}
$totalReg = is_numeric($sql) ? $sql : PaginacaoTotalReg($sql, $idProg, $force);
/*
* Calcula o n<EFBFBD>mero total de paginas tendo com base o n<EFBFBD>mero total
* de registros a set recuperado pelo numero de linhas por pagina.
*/
$addPage = ($totalReg % $regPagina) > 0 ? 1 : 0;
$paginas = ((int) ($totalReg / $regPagina)) + (($totalReg % $regPagina) > 0 ? 1 : 0);
/*
* O n<EFBFBD>mero total de blocos necess<EFBFBD>rio para exibir todas as paginas.
*/
$numBlocos = (((int) ($paginas / $tamBloco)) + (($paginas % $tamBloco) > 0 ? 1 : 0)) - 1;
/*
* Indica a navega<EFBFBD><EFBFBD>o pelos blocos.
*/
$pgn = $_REQUEST['pgn'] ?? 0;
/*
* O bloco atual.
*/
$bloco = StrToIntDef($_REQUEST['bloco'] ?? '0') + StrToIntDef($pgn);
/*
* A pagina atual a ser mostrada
*/
$pgAtu = StrToIntDef($_REQUEST['pg'] ?? 0);
if ($pgn) {
$pgAtu = $bloco * $tamBloco;
}
/*
* Corrige o n<EFBFBD>mero de paginas na dele<EFBFBD><EFBFBD>o
*/
if ($pgAtu >= $paginas) {
$pgAtu = $paginas - 1;
}
/*
* A p<EFBFBD>gina atual a ser listada.
*/
$offSet = abs($regPagina * $pgAtu);
/*
* Variavel usada para mostar o numero de registros em rela<EFBFBD><EFBFBD>o ao total(de at<EFBFBD>)
*/
$pagMostra = !$totalReg ? 0 : ((($pgAtu + 1) == $paginas) ? $totalReg : ($regPagina * ($pgAtu + 1)));
$pgs = '';
$tamIcone = 8;
$imgPrior = sprintf("<img src=\"imgSite/%s\" width=\"$tamIcone\" height=\"$tamIcone\" border=\"0\">", !$bloco ? 'priorOff.png' : 'prior.png');
$imgPrevious = sprintf("<img src=\"imgSite/%s\" width=\"$tamIcone\" height=\"$tamIcone\" border=\"0\">", !$bloco ? 'previousOff.png' : 'previous.png');
$linkPrior = !$bloco ? $imgPrior : sprintf('<a class="pagina" href="index.php?idProg=%s%s&pgn=0&pg=0&bloco=0">%s</a> ', $idProg, $params, $imgPrior);
$linkPrev = !$bloco ? $imgPrevious : sprintf('<a class="pagina" href="index.php?idProg=%s%s&pgn=-1&bloco=%s">%s</a> ', $idProg, $params, $bloco, $imgPrevious);
$link = sprintf("<table class=\"pagina\"><tr style=\"background-color: transparent !important;\"><td style=\"width: 8px\">%s</td><td style=\"width: 8px\">%s</td>", $linkPrior, $linkPrev);
$i = 0;
while ($i < $tamBloco) {
$pg = $i + ($bloco * $tamBloco);
if (($pg * $regPagina) < $totalReg)
$pgs .= sprintf(
"<td>%s</td>",
($pg == $pgAtu) ? ('<span class="pagina" >' . ($pg + 1) . '</span>') : sprintf('<a class="pagina" href="index.php?idProg=%s%s&pgn=0&bloco=%s&pg=%s">%s</a>', $idProg, $params, $bloco, $pg, $pg + 1)
);
if ($pg == $pgAtu) {
$params = sprintf("%s&pgn=0&bloco=%s&pg=%s", $params, $bloco, $pg);
}
$i++;
}
$imgNext = sprintf("<img src=\"imgSite/%s\" width=\"$tamIcone\" height=\"$tamIcone\" border=\"0\">", $bloco >= $numBlocos ? 'nextOff.png' : 'pgnext.png');
$imgLast = sprintf("<img src=\"imgSite/%s\" width=\"$tamIcone\" height=\"$tamIcone\" border=\"0\">", $bloco >= $numBlocos ? 'lastOff.png' : 'pglast.png');
$linkNext = sprintf('<a class="pagina" href="index.php?idProg=%s%s&pgn=1&bloco=%s">%s</a>', $idProg, $params, $bloco, $imgNext);
$linkLast = sprintf('<a class="pagina" href="index.php?idProg=%s%s&pgn=0&pg=%s&bloco=%s">%s</a>', $idProg, $params, $paginas - 1, $numBlocos, $imgLast);
$linkNext = ($bloco >= $numBlocos) ? $imgNext : $linkNext;
$linkLast = ($bloco >= $numBlocos) ? $imgLast : $linkLast;
$link .= $pgs . sprintf("<td style=\"width: 8px\">%s</td><td style=\"width: 8px\">%s</td></tr></table>", $linkNext, $linkLast);
return $link;
}
function PreparaLike($valor, $useQuted = false)
{
$val = explode(" ", $valor);
$str = "%";
foreach ($val as $value) {
$str .= $value . "%";
}
return $useQuted ? QuotedStr($str) : $str;
}
function Alert($msg, $pbx = 0)
{
global $jsStartup;
$arReplace = array("^", "~", "`", "'", "'", "\n");
if ($pbx) {
echo sprintf("<script>alert('%s');</script>", trim(str_replace($arReplace, "", RemoveAcentos($msg))));
} else {
$jsStartup[] = sprintf("alert('%s');", trim(str_replace($arReplace, "", RemoveAcentos($msg))));
}
}
function GetRevendasUsuario($db, $grpId, $text = true)
{
$idUser = GetIdUser();
$query = " select distinct e.emp_id
from vds_grupos a
inner join vds_grupos_empresas b on b.grp_id = a.grp_id
inner join pbx_grupo_revendas c on c.emp_id = b.emp_id
inner join pbx_grupo_usuario d on d.gp_id = c.gp_id
inner join vds_empresas e on e.emp_id = c.emp_id\n
where 1=1\n";
$query .= IsAdmin() ? '' : " and d.user_id = '$idUser'\n";
$query .= !$grpId ? '' : " and a.grp_id = '$grpId'\n";
$query .= " order by e.emp_id\n";
$result = pg_query($db, $query);
if (!$result || !pg_num_rows($result))
return $text ? '' : array();
$retArray = array();
while ($dados = pg_fetch_array($result)) {
$retArray[] = $dados['emp_id'];
}
return $text ? implode(",", $retArray) : $retArray;
}
function GetRevendasGrupo($db, $grpId)
{
$query = "select emp_id from vds_grupos_empresas where grp_id = '$grpId'";
$result = pg_query($db, $query);
if (!$result || !pg_num_rows($result)) {
return array();
}
$retArray = array();
while ($dados = pg_fetch_array($result)) {
$retArray[] = $dados['emp_id'];
}
return $retArray;
}
function UseModVendas()
{
return $_SESSION['prm_use_vendas'];
}
function GetLinkAudio()
{
$server = array_key_exists('SERVER_ADDR', $_SERVER) ? $_SERVER['SERVER_ADDR'] : $_SERVER['SERVER_NAME'];
return !$_SESSION['prm_link_audio'] ? $server : $_SESSION['prm_link_audio'];
}
function ExigeProtoVendas()
{
return $_SESSION['prm_exige_proto_vendas'];
}
function MenuVendas()
{
return isset($_SESSION['prm_nome_vendas']) ? $_SESSION['prm_nome_vendas'] : 'Vendas';
}
function GetAtivaIntegracao()
{
return $_SESSION['prm_ativa_integracao'];
}
function GetMetodoIntegracao()
{
return $_SESSION['prm_select_integracao'];
}
function GetProtoExternoReg($uniqueid, $clas)
{
$query = sprintf("select '' from pbx_classifica_atendimento where clas_id = %s and clas_descricao = 'VENDA'", QuotedStr(strtoupper($clas)));
$result = pg_query($query);
if (!pg_num_rows($result)) {
return true;
}
$query = sprintf("select '' from pbx_protocolo_reg where uniqueid = %s and protoparceiro is not null", QuotedStr($uniqueid));
$result = pg_query($query);
return pg_num_rows($result) ? true : false;
}
function GetRejeitadosVendas($dacAtv)
{
$query = "select count(distinct protocolo) from pbx_protocolo_reg a, ast_eventos_dacs b where b.uid2 = a.uniqueid and b.fila = '$dacAtv' and a.protointegrado = '9' and a.\"dataReg\"::date = now()::date";
$result = pg_query($query);
if (!$result) {
return 0;
}
$row = pg_fetch_row($result);
return $row[0];
}
function GetVendasAgente($dac, $matricula)
{
if (!AgenteON() || !UseModVendas()) {
return 0;
}
$query = "select count(distinct a.id_bilhetes) from pbx_classifica_reg a, pbx_classifica_atendimento b
where b.clas_id = a.clas_id
and upper(b.clas_descricao) = 'VENDA'
and a.id_dac = '$dac'
and matricula = '$matricula'
and data_reg::date = now()::date";
$result = pg_query($query);
if (!$result) {
return 0;
}
$row = pg_fetch_row($result);
return $row[0];
}
function ocultarCampo($campo, $key, &$array)
{
if (strpos($campo, '*') !== false) {
$pos = explode('*', $campo);
$array[$key] = $pos[1];
return $pos[0];
}
return $campo;
}
function ocultarLGPD($campo, $position)
{
if ($campo && $position) {
return substr_replace($campo, '****', 0, $position);
}
return $campo;
}
function ocultarTelefone($tel, $pos = 0)
{
$telefone = filter_var($tel, FILTER_SANITIZE_NUMBER_INT);
$position = ($pos ? $pos : $_SESSION['prm_ocultar_telefone']);
if (strlen($telefone) >= 6 && $telefone && $position) {
return substr_replace($telefone, '*****', 0, $position);
}
return $tel;
}
function ocultarEmail($mail, $position = 0)
{
$posicao = $position ? $position : $_SESSION['prm_ocultar_email'];
if ($posicao <= 0) {
return $mail;
}
$email = explode('@', $mail);
return substr_replace($email[0], '*****', 0, $posicao) . '@' . $email[1];
}
function ocultarCpf($doc, $position = 0)
{
$documento = filter_var($doc, FILTER_SANITIZE_NUMBER_INT);
$posicao = $position ? $position : $_SESSION['prm_ocultar_documento'];
if ((strlen($documento) == 14 || strlen($documento) == 11) && $documento && $posicao) {
return substr_replace($documento, '*****', 0, $posicao);
}
return $doc;
}
function cryptOpenSSL($string, $chave = CONF_CRYPT_KEY, $iv = CONF_CRYPT_IV, $alg = "AES-256-CBC")
{
return openssl_encrypt($string, $alg, $chave, OPENSSL_RAW_DATA, $iv);
}
function descryptOpenSSL($string, $chave = CONF_CRYPT_KEY, $iv = CONF_CRYPT_IV, $alg = "AES-256-CBC")
{
return openssl_encrypt($string, $alg, $chave, OPENSSL_RAW_DATA, $iv);
}
function SetResScreen($w, $h, $tbLayout)
{
$_SESSION['SSScreenW'] = $w;
$_SESSION['SSScreenH'] = $h;
$_SESSION['SStbLayout'] = $tbLayout;
}
function GetScreenW()
{
return isset($_SESSION['SSScreenW']) ? $_SESSION['SSScreenW'] : (isset($_REQUEST['screenW']) ? $_REQUEST['screenW'] : 800);
}
function GetScreenH()
{
return isset($_SESSION['SSScreenH']) ? $_SESSION['SSScreenH'] : (isset($_REQUEST['screenH']) ? $_REQUEST['screenH'] : 600);
}
function GetSizeTbLayout()
{
return (isset($_SESSION['SStbLayout']) ? $_SESSION['SStbLayout'] : null);
}
function GetNomeDac($dac)
{
/*
* O valor zero representa que todos os dacs est<EFBFBD>o selecionados.
*/
if (!$dac) {
return 'Todos';
}
$query = "select nome from pbx_dacs where id = '$dac'";
$result = pg_query($query);
/*
* Retorna vazio em caso de erro ou o dac n<EFBFBD>o existir.
*/
if (!$result || !pg_num_rows($result)) {
return "";
}
/*
* Dac encontrado retorna o nome.
*/
$row = pg_fetch_row($result);
return $row[0];
}
function GetMes($mes = 0, $incTodos = 0, $head = 0)
{
global $meses;
$listaMes = '';
if ($head) {
$listaMes .= '<select name="listaMes" id="listaMes" size="1">';
}
for ($i = $incTodos ? 0 : 1; $i <= 12; $i++) {
$sel = ((int) $i == (int) $mes) ? "selected" : "";
$listaMes .= "<option value=\"$i\" $sel>$meses[$i]</option>\n";
}
if ($head) {
$listaMes .= '</select>';
}
return $listaMes;
}
function GetAno($ano, $head = 0, $sql = '')
{
$combo = '';
if ($head) {
$combo .= '<select name="listaAno" id="listaAno" size="1">';
}
$query = $sql ? $sql : "select date_part('year', min(data_bilhete) ), date_part('year', max(data_bilhete) ) from pbx_bilhetes";
$result = pg_query($query);
$dados = @pg_fetch_row($result);
$min = !$dados[0] ? date("Y") : $dados[0];
$max = !$dados[1] ? date("Y") : $dados[1];
while ($max >= $min) {
$sel = ($max == $ano) ? "selected" : "";
$combo .= "<option value=\"$max\" $sel>$max</option>";
$max--;
}
if ($head) {
$combo .= '</select>';
}
return $combo;
}
function GetPausaAusente($dbcon, $matricula)
{
$query = "select '' from pbx_supervisor_agentes a where matricula = '$matricula' and status = 'PAUSA' and upper(motivo_pausa) in('AUSENTE','RECUSADA')";
$result = pg_query($dbcon, $query);
return pg_num_rows($result);
}
function Menu($dbcon, $queryHead = "", $queryItens = "", $idUser = 0, $hiddeLink = 0, $param = null)
{
//$menu = $_SESSION["SSmenuSistema"];
//$indexMenu = $_SESSION["SSidxMenuSistema"];
//$dadosMenu = $_SESSION["SSdadosMenuSistema"];
$isTree = $_SESSION["SStreView"];
$nomeRoot = isset($_SESSION["SStreRoot"]) ? $_SESSION["SStreRoot"] : null;
$menu = IndexaMenu($dbcon, $queryHead, $queryItens, $idUser, $hiddeLink, $param);
$i = 0;
$indexRoot = isset($_SESSION["SSperfilAcao"]) && ($_SESSION["SSperfilAcao"] == "rem") ? "" : "index.php?idProg=121&funId=0&acao=upd";
$makeMenu = !$isTree ? " var MENU_ITEMS = [\n" : " var MENU_ITEMS = [['$nomeRoot', '$indexRoot',\n";
foreach ($menu as $itemMenu) {
$makeMenu .= ExtratItens($itemMenu, $i);
++$i;
}
$makeMenu .= !$isTree ? "];\n" : "]];\n";
return $makeMenu;
}
function ExtratItens($itensMenu, $numMod)
{
$makeMenu = '';
$makeMenu .= $numMod ? "\n,[" : "\n[";
$i = 0;
foreach ($itensMenu as $key => $val) {
if (is_array($val)) {
$makeMenu .= ',' . ExtratItens($val, 0);
} else {
$novaJan = (stripos($val, 'NovaJanela') !== false);
$makeMenu .= ($i ? ',' : '') . IsNull($novaJan ? "'" . $val . "'" : $val, 'null', $novaJan ? 0 : 1);
}
$i++;
}
$makeMenu .= "]";
return $makeMenu;
}
function QueryMenuHead($idUser, $public = 0)
{
if ($idUser < 0) {
$idGrupo = abs($idUser);
$permUser = GetGrupoUserPermissoes($idGrupo);
return sprintf("select distinct 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, b.fun_public, b.ord
from pbx_funcoes b
where coalesce(b.fun_id_pai, 0) = 0
and b.fun_id in(select gf.fun_id from pbx_grupo_funcoes gf where gf.gp_id = %s)
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, b.fun_public, b.ord
from pbx_funcoes b where coalesce(b.fun_id_pai, 0) = 0 and (b.fun_public = 1 or (exists(select '' from pbx_funcoes where fun_id_pai = b.fun_id and fun_public = 1)) )
%s
order by ord ", QuotedStr($idGrupo), $permUser);
}
if (IsAdmin() && !$idUser) {
return 'select distinct fun_id, fun_nome, fun_menu, fun_menu_text, fun_menu_url, fun_menu_img, coalesce(fun_id_pai, 0) as fun_id_pai, fun_status, fun_public, ord from pbx_funcoes where coalesce(fun_id_pai, 0) = 0 and fun_status = 1 order by ord';
}
return "select distinct d.fun_id, d.fun_nome, d.fun_menu, d.fun_menu_text, d.fun_menu_url, d.fun_menu_img, d.fun_id_pai, d.fun_public, d.ord
from pbx_usuarios a, pbx_grupo_usuario b, pbx_grupo_funcoes c, pbx_funcoes d
where b.user_id = a.id
and c.gp_id = b.gp_id
and d.fun_id = c.fun_id
and coalesce(d.fun_id_pai, 0) = 0
and d.fun_status = 1
and a.id = coalesce('$idUser', a.id)
union
select distinct fun_id, fun_nome, fun_menu, fun_menu_text, fun_menu_url, fun_menu_img, fun_id_pai, fun_public, ord
from pbx_funcoes b
where (b.fun_public = 1 or (exists(select '' from pbx_funcoes where fun_id_pai = b.fun_id and fun_public = 1)) )
and coalesce(fun_id_pai, 0) = 0
and b.fun_status = 1
order by ord ";
}
function QueryMenuItens($idUser, $idMenu = 0, $notMenu = 0, $param = null)
{
if ($idUser < 0) {
$idGrupo = abs($idUser);
$permUser = GetGrupoUserPermissoes($idGrupo, $idMenu, 1);
return sprintf("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 b.fun_id_pai = %s
and ( b.fun_public = 1 or b.fun_id in(select g.fun_id from pbx_grupo_funcoes g where g.gp_id = %s))
%s
order by fun_menu_text
", QuotedStr($idMenu), QuotedStr($idGrupo), $permUser);
}
$ord = ($idMenu ? "fun_menu_text" : "fun_id");
$ord = "fun_menu_text";
$notMenu = (!$notMenu ? 'and d.fun_menu <> 0' : '');
$idMenu = ($idMenu ? "and d.fun_id_pai = '$idMenu' " : "");
if (IsAdmin() && !$idUser) {
return sprintf('select fun_id, fun_nome, fun_menu, fun_menu_text, fun_menu_url, fun_menu_img, coalesce(fun_id_pai, 0) as fun_id_pai, fun_status, fun_public from pbx_funcoes d where fun_status = 1 %s %s order by %s', $idMenu, $notMenu, $ord);
}
$query = sprintf("select distinct d.fun_id, d.fun_nome, d.fun_menu, d.fun_menu_text, d.fun_menu_url, d.fun_menu_img, d.fun_id_pai, d.fun_public
from pbx_usuarios a, pbx_grupo_usuario b, pbx_grupo_funcoes c, pbx_funcoes d
where b.user_id = a.id
and c.gp_id = b.gp_id
and d.fun_id = c.fun_id
and a.id = coalesce(%s, a.id)
and d.fun_status = 1
%s
%s
union
select distinct d.fun_id, d.fun_nome, d.fun_menu, d.fun_menu_text, d.fun_menu_url, d.fun_menu_img, d.fun_id_pai, d.fun_public
from pbx_funcoes d
where d.fun_status = 1
%s
%s
and d.fun_public = 1 ", $idUser, $notMenu, $idMenu, $notMenu, $idMenu);
if ($param) {
$query .= "union
(select ('999' || floor(random() * 10 + 1)::varchar || d.fun_id::varchar)::int as fun_id, d.fun_nome, 0 as fun_menu, 'GRUPO - ' || gp_nome as fun_menu_text, fun_menu_url, fun_menu_img, d.fun_id as fun_id_pai, fun_public
from pbx_grupo_usuario a
inner join pbx_grupo_funcoes b on b.gp_id = a.gp_id
inner join pbx_grupo c on c.gp_id = a.gp_id
inner join pbx_funcoes d on d.fun_id = b.fun_id
where a.user_id = $idUser
and d.fun_status = 1
and id_prog not in (-1, 58)
$notMenu
$idMenu) ";
}
$query .= "order by fun_id";
return $query;
}
function GetLinkMenu($linkMenu, $funId = 0, $url = '', $acao = 'upd')
{
switch ($linkMenu) {
case 0:
return "#";
case 1:
return $url;
default:
return sprintf("index.php?idProg=%s&funId=%s&acao=%s", GetGerPerfil(), $funId, $acao);
};
}
function MontaMenu($idMenu, $userId, $linkMenu = 1, $notMenu = 0, $acao = "upd")
{
global $dbcon;
/*
* Funcao retorna menu para aplicacao.
* -$idMenu -> Indica que a raiz da arvore de menu, a partir deste "n<EFBFBD>" retorna o restante da arvore.
* -$userId -> Id do usuario para qual sera retornado o menu.
* -$linkMenu -> A forma de retornar o link:
* 0 -> Nao retorna link(usado para mostrar a arvore de permissao do usuario);
* 1 -> Menu da aplicacao(acesso as funcoes com base nas permissoes do usuario);
* 2 -> Arvore de permissoes(Monta as arvores Grupo/Usuarios);
* -$notMenu -> O perfil verifica acesso as funcoes apenas pelo item principal por exemplo se
* o usuario tem acesso a tela de usuario, este tera todas as permissoes, de maneira que so po-
* demos restringir um item de menu. Para contornar este problema incluimos usamos o parametro
* fun_menu da tabela pbx_funcoes com valor 0 que informa que e uma permissao mas que nao deve
* ser listada com um item de menu, entao, a mesma consta na arvore de permissoes mas nao no
* menu.
* -$acao -> Usado como parametro para chamar o script perfilfuncoesGrupo.php que adiciona ou
* remove funcionalidades para o usuario. upd -> atualiza a tela rem -> remove a funcao passada
* add -> adiciona a funcao ao usuario.
*/
global $dbcon;
$addNull = ($linkMenu == 1) ? ",'null'" : "";
if (!$idMenu) {
$urlPerfil = ($acao == "rem") ? "" : sprintf("index.php?idProg=%s&funId=0&acao=upd", GetGerPerfil());
$menuHead = ($linkMenu < 2) ? " var MENU_ITEMS = [\n" : sprintf(" var MENU_ITEMS = [['%s', '%s',\n", ($acao == 'add' ? GetLogin() : __GetLoginFromId($userId)), $urlPerfil);
$menu = '';
$query = QueryMenuHead($userId);
$result = pg_query($dbcon, $query);
while ($dados = pg_fetch_array($result)) {
$menu .= !$menu ? "[" : ",\n[";
$menu .= sprintf("'%s','%s'%s", $dados['fun_menu_text'], GetLinkMenu($linkMenu, $dados['fun_id'], $dados['fun_menu_url'], $acao), $addNull);
$menu .= MontaMenu($dados['fun_id'], $userId, $linkMenu, $notMenu, $acao);
$menu .= "\n]";
}
$menu = $menuHead . $menu . (($linkMenu < 2) ? "];\n" : "]];\n");
return $menu;
} else {
$query = QueryMenuItens($userId, $idMenu, $notMenu);
$result = pg_query($dbcon, $query);
$menu = '';
while ($dados = pg_fetch_array($result)) {
$menu .= ",\n[";
$menu .= sprintf("'%s','%s'%s", $dados['fun_menu_text'], GetLinkMenu($linkMenu, $dados['fun_id'], $dados['fun_menu_url'], $acao), $addNull);
$menu .= MontaMenu($dados['fun_id'], $userId, $linkMenu, $notMenu, $acao);
$menu .= "]";
}
return $menu;
}
}
function GetGerPerfil()
{
/*
* Esta funcao retorna o id do script perfilfuncoesGrupo.php que eh
* responsavel por adicionar e remover permissoes aos usuarios.
*/
return "121";
}
function GetGrupoUserPermissoes($idGrupo, $idMenu = 0, $itens = 0)
{
$query = "select user_id from pbx_grupo a where gp_id = '$idGrupo' ";
$result = pg_query($query);
$row = pg_fetch_row($result);
$userId = $row[0];
if (!$userId) {
return '';
}
if (!$itens) {
return sprintf(" Union
select distinct d.fun_id, d.fun_nome, d.fun_menu, d.fun_menu_text, d.fun_menu_url, d.fun_menu_img, d.fun_id_pai, d.fun_public, d.ord
from pbx_usuarios a, pbx_grupo_usuario b, pbx_grupo_funcoes c, pbx_funcoes d
where b.user_id = a.id
and c.gp_id = b.gp_id
and d.fun_id = c.fun_id
and coalesce(d.fun_id_pai, 0) = 0
and d.fun_status = 1
and a.id = coalesce(%s, a.id) ", QuotedStr($userId));
}
return sprintf(" Union
select distinct d.fun_id, d.fun_nome, d.fun_menu, d.fun_menu_text, d.fun_menu_url, d.fun_menu_img, d.fun_id_pai
from pbx_usuarios a, pbx_grupo_usuario b, pbx_grupo_funcoes c, pbx_funcoes d
where b.user_id = a.id
and c.gp_id = b.gp_id
and d.fun_id = c.fun_id
and d.fun_id_pai = %s
and a.id = coalesce(%s, a.id)
and d.fun_status = 1 ", QuotedStr($idMenu), QuotedStr($userId));
}
function printPre($data, $exit = false)
{
echo "<pre>" . print_r($data, true) . "</pre>";
if ($exit) {
exit;
}
}
function truncate($string, $length = 80)
{
if (!isset($string) || empty($string)) {
return "";
}
if (strlen($string) >= $length) {
return $string;
}
return substr($string, 0, $length) . "...";
}
function IsLogado()
{
return (isset($_SESSION['SSidUser']) && !empty($_SESSION['SSidUser']));
}
function ArrayDotNotation($arr)
{
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($arr),
RecursiveIteratorIterator::SELF_FIRST
);
$path = [];
$flatArray = [];
foreach ($iterator as $key => $value) {
$path[$iterator->getDepth()] = $key;
if (!is_array($value)) {
$flatArray[implode('.', array_slice($path, 0, $iterator->getDepth() + 1))] = $value;
}
}
return $flatArray;
}
function PodePublicarMural($idProg, $info)
{
global $dbcon;
$isPopup = (getRequest('window', INPUT_GET));
$naoPublicarPelasPaginas = [14, 6];
$podePublicar = (IsLogado() && (IsAdmin() || IsSuper()) && VerificaPerfilAcesso($dbcon, 6, $info));
if (in_array($idProg, $naoPublicarPelasPaginas) || ($isPopup !== null)) {
$podePublicar = false;
}
return $podePublicar;
}
function GetRetornoAbandonadas($hora, $nro, $dac)
{
$query = "select
ret_agente,
ret_calldate as data
from tmp_retornado
where upper(ret_fila) = upper('$dac')
and ret_calldate >= '$hora'
and (ret_src = '$nro' or ret_dst = '$nro')
order by 2 limit 1";
$result = pg_query($query);
while ($row = @pg_fetch_array($result)) {
$dados = $row[0] . ";" . $row[1];
}
return $dados;
}
function GetTotalDependencias($recurso, $key)
{
if ($recurso == 'voice') {
$key = sprintf("%s/%%", $key);
}
$query = "select count(*) from (
select '' from pbx_anuncios where opcao = '$recurso' and acao like '$key'
union all
select '' from pbx_callback where opcao = '$recurso' and acao like '$key'
union all
select '' from pbx_callback where opcao1 = '$recurso' and acao1 = '$key'
union all
select '' from pbx_contextos where opcao = '$recurso' and acao like '$key'
union all
select '' from pbx_contextos a, pbx_contextos_opcoes b where b.id_contexto = a.id and b.opcao = '$recurso' and b.acao like '$key'
union all
select '' from pbx_disa where opcao = '$recurso' and acao like '$key'
union all
select '' from pbx_grupos where opcao = '$recurso' and acao like '$key'
union all
select '' from pbx_horarios where opcao_nao = '$recurso' and acao_nao = '$key'
union all
select '' from pbx_horarios a, pbx_horarios_itens b where b.id_horario = a.id and b.opcao = '$recurso' and b.acao like '$key'
union all
select '' from pbx_integracao_configuracao where opcao = '$recurso' and acao like '$key'
union all
select '' from pbx_listanegra where id_pai is null and opcao = '$recurso' and acao like '$key'
union all
select '' from pbx_queues_grupos where opcao = '$recurso' and acao like '$key'
union all
select '' from pbx_rotas_entrada where opcao = '$recurso' and acao like '$key'
union all
select '' from pbx_ura where opcao = '$recurso' and acao like '$key'
union all
(select '' from pbx_ura a, pbx_ura_destino b where b.id_ura = a.id and b.tipo = '$recurso' and b.comando like '$key' limit 1)
union all
select '' from pbx_campanha a, pbx_dacs b where a.id_dac = b.id and b.numero = '$key' and cmp_status in (1,2)
union all
select '' from pbx_pesquisa_liberacao a, pbx_pesquisa_liberacao_dacs b, pbx_dacs c, pbx_pesquisa d where a.pl_id = b.pl_id and b.id_dac = c.id and d.pp_id = a.pp_id and c.numero = '$key'";
if ($recurso == 'ramal') {
$query .= " union all
select '' from pbx_disa where ramal_saida = '$key'
union all
select '' from pbx_monitoramento_ramais where ramal = '$key'
union all
select '' from pbx_queues_membros a, pbx_dacs b, pbx_ramais c where a.id_fila = b.id and c.dispositivo = a.dispositivo and c.nome = '$key'
union all
select '' from pbx_voicemail_usuarios where numero_ramal = '$key'
union all
select '' from pbx_pbx_centro_custo_ramais a, pbx_centro_custo b where b.cc_id = a.cc_id and a.ramal = '$key'
union all
select '' from pbx_grupos_atendimento a, pbx_grupos_atendimento_ramais b where id_grupo = a.id and b.ramal = '$key'
union all
select '' from pbx_digivoice_ramais_fxs a, pbx_digivoice_grupos b where b.group = a.id_grupo and ramal = '$key' ";
}
if ($recurso == 'contextos') {
$query .= " union all
select '' from pbx_queues_grupos where context = '$key'
union all
select '' from pbx_ramais where contexto = '$key'
union all
select '' from pbx_troncos where context = '$key' ";
}
if ($recurso == 'troncos') {
$query .= "union all
select '' from pbx_rotas_entrada a, pbx_rotas_entrada_troncos b where b.id_rota = a.id and id_tronco = '$key'
union all
select '' from pbx_rotas_saida a, pbx_rotas_saida_canais b, pbx_troncos c where b.id_rota = a.id and c.nome = b.canal and c.id = '$key'
union all
select '' from pbx_contextos_canais a, pbx_troncos b, pbx_contextos c where a.canal = b.nome and a.id_contexto = c.id and b.id = '$key'";
}
$query .= " ) as redir; ";
//echo $query; exit;
$result = pg_query($query);
if (!$result) {
return false;
}
$dados = pg_fetch_row($result);
return $dados[0];
}
/**
*
* @param string $opcao Identificador de um recurso, ex: Anuncio = anuncios
* @param string $acao O valor atribuido referente a "opcao" selecionada ou seja a "acao", por exemplo se um recurso tipo an<EFBFBD>ncio for selecionado a acao ser<EFBFBD> seu id.
* @param string $recursoTipo Tipo do recurso para o qual vamos pesquisar as depend?ncias, ex.: URA, Anuncio, Ramal
* @param string $nomeRecurso A descricao ou nome do recurso para o qual vamos pesquisar as depend?ncias, ex.: Boa Noite(Um an<EFBFBD>ncio poderia estar cadastro com esse nome)
* @param int $totaldep O n<EFBFBD>mero de depend<EFBFBD>ncias identificadas para o recurso corrente.
* @return String
*/
function GetLinkDependenciaRecurso($opcao, $acao, $recursoTipo, $nomeRecurso, $totaldep)
{
return !$totaldep ? "<img src = \"imgSite/troncoOff16.png\" title=\"Este recurso n<EFBFBD>o possui registros dependentes!\">" : sprintf("<a href=\"#\" onclick=\"NovaJanela('index.php?idProg=12000&opcao=%s&acao=%s&recursoTipo=%s&nomeRecurso=%s', 'ListaDependenicas', '500', '400', 'resizable=YES,scrollbars=YES');\"><img src=\"imgSite/troncoOn16.png\" title=\"Este recurso possui %s registros dependentes,Clique para consultar!\"></a>", $opcao, $acao, $recursoTipo, $nomeRecurso, $totaldep);
}
function GetManagerParams()
{
$query = "select prm_sk_host, prm_sk_port, prm_sk_login, prm_sk_password from pbx_parametros";
$result = pg_query($query);
if ($result) {
$dados = pg_fetch_array($result);
return array("servidor" => $dados['prm_sk_host'], "porta" => $dados['prm_sk_port'], "usuario" => $dados['prm_sk_login'], "senha" => $dados['prm_sk_password']);
}
return false;
}
function SetIntegracaoContato($retorno_cliente)
{
$matricula = GetMatricula();
$ramal = GetRamalMonitorar(RAMAL_MONITOR_AGENTE);
$query = sprintf("update pbx_supervisor_agentes set cont_identificador = %s where matricula = %s\n", QuotedStr($retorno_cliente), QuotedStr($matricula));
pg_query($query);
// $query = "INSERT INTO pbx_integracao_saida (matricula,ramal,itgs_dados) VALUES('$matricula','$ramal','$retorno_cliente'); ";
// pg_query($query);
}
function GetMetodoIntegra($idMetodo)
{
$query = "select a.itgm_tipo, a.itgm_comando, itgm_retorno, a.opcao as opcao_metodo, a.stored_params,
c.itgp_prefix, b.itgc_host, b.itgc_port, b.itgc_database, b.itgc_user, b.itgc_password,
b.itgc_timeout, b.opcao, b.acao, coalesce(a.evento, 0) as evento
from pbx_integracao_metodo a, pbx_integracao_configuracao b, pbx_integracao_protocolo c
where b.itgc_id = a.itgc_id
and c.itgp_id = b.itgp_id
and a.itgm_id = '$idMetodo'";
$result = pg_query($query);
if ($result) {
$row = pg_fetch_assoc($result);
return $row;
}
return false;
}
function GetCodecs($useVideo = false)
{
$video = array('h261', 'h263', 'h263p', 'h264', 'vp8', 'vp9');
$som = array('adpcm', 'alaw', 'ulaw', 'g719', 'g722', 'g723', 'g726', 'g726aal2', 'g729', 'gsm', 'ilbc', 'lpc10', 'silk', 'speex', 'slin');
return !$useVideo ? $som : array_merge($som, $video);
}
function GetStatusModulo($status, $param = "A")
{
$resp = "";
if ($status == $param) {
$resp = "<img src=\"imgSite/ledOn.gif\" width=\"16\" border=\"0\" title=\"Ativo\">";
} else {
$resp = "<img src=\"imgSite/ledOff.gif\" width=\"16\" border=\"0\" title=\"Inativo\">";
}
return $resp;
}
function GetSelectValProto($param = null)
{
$query = "SELECT prm_validacao_protocolo FROM pbx_parametros";
$result = pg_query($query);
$validacao = pg_fetch_assoc($result);
$opt = "";
if ($param == 'result') {
return $validacao['prm_validacao_protocolo'];
}
foreach ($_SESSION['SSValidaFuncoesProtocolo'] as $valida) {
$sel = $valida == $validacao['prm_validacao_protocolo'] ? "selected" : '';
$opt .= "<option value='$valida' $sel>$valida</option>";
}
return $opt;
}
function GetMaxDaysRel()
{
$query = "SELECT prm_max_dias_relatorio FROM pbx_parametros";
$result = pg_query($query);
$maxdays = pg_fetch_assoc($result);
return $maxdays['prm_max_dias_relatorio'];
}
function GetRestringeAudio()
{
$query = "SELECT prm_restringe_audio FROM pbx_parametros";
$result = pg_query($query);
$resp = pg_fetch_assoc($result);
return $resp['prm_restringe_audio'];
}
function MaxDaysRel($dataIni, $dataFim)
{
if (GetMaxDaysRel() != 0) {
if (strtotime(FormatDateHour($dataFim)) > strtotime(FormatDateHour($dataIni) . "+" . GetMaxDaysRel() . "days")) {
return "O per<EFBFBD>odo n<EFBFBD>o pode ultrapassar " . GetMaxDaysRel() . " dias!";
}
return null;
}
}
function DownloadImg($file)
{
$fsize = filesize($file);
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Content-Type: image/jpeg');
if ($fsize) {
header('Content-Length: ' . $fsize);
}
header('Content-Disposition: attachment; filename= imagens');
header('Connection: close');
readfile($file);
exit;
$fsize = filesize($file);
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Content-Type: image/jpg');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
if ($fsize) {
header('Content-Length: ' . $fsize);
}
header('Connection: close');
readfile($file);
exit;
}
function MostraSenhaRamal($idProg, $ramal)
{
$query = "select * from (select dispositivo, secret, nome from pbx_sip_ramais
union all
select dispositivo, secret, nome from pbx_iax_pbx) a
where nome = '$ramal'";
$log = "insert into pbx_audita_full(login, id_prog, full_ip, full_tipo, full_log, full_prog_nome)
values(%s, %s, %s, 'GET', %s, (select substring(arquivo, laststr('/',arquivo)+1) from pbx_funcoes_internas where id_prog = '$idProg'));";
try {
$ip = GetIpUsuario();
$login = GetLogin();
if (!$result = pg_query($query)) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel consultar o ramal informado!");
}
if (!pg_num_rows($result)) {
throw new Exception("O ramal informado n<EFBFBD>o foi encontrado!");
}
/*
* Pega a senha descriptografada.
*/
$data = pg_fetch_array($result);
$pass = $data['secret'];
/*
* Registra o acesso a senha do ramal.
*/
$reg = "A senha do ramal: $ramal foi visualizada pelo usuario: $login Data: " . date("Y-m-d H:i:s");
$log = sprintf($log, QuotedStr($login), QuotedStr($idProg), QuotedStr($ip), QuotedStr($reg));
if (!pg_query($log)) {
throw new Exception("Opera<EFBFBD><EFBFBD>o cancelada devido a um erro durante o registro!");
}
return sprintf("OK;%s", $pass);
} catch (Exception $ex) {
return "ERRO;" . $ex->getMessage();
}
}
function ComplementoCampanhaAtivo()
{
return $_SESSION['prm_ativa_complemento_campanha'];
}
function VerificaUsoServicos()
{
if (!isset($_SESSION["SSUsoServico"])) {
$query = "select case when( exists( select '' from pbx_servicos a, pbx_servicos_registra b where b.serv_id = a.serv_id))then 1 else 0 end as existe_servico";
$result = pg_query($query);
$row = pg_fetch_row($result);
$_SESSION["SSUsoServico"] = $row[0] ? true : false;
}
return $_SESSION["SSUsoServico"];
}
function GetUsoServico()
{
return $_SESSION["prm_relatorio_servico"];
}
function GetAvisoLgpdMonitoria()
{
return $_SESSION["prm_aviso_lgpd_monitoria"];
}