\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 .= "";
}
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 crialo
*/
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();
$result = pg_query($db, "SELECT prm_max_ramal FROM pbx_parametros");
$numRamais = pg_fetch_row($result);
if ((int) $numRamais[0] === 0) {
return false;
}
$query = "select count(*) as num_total_ramais from pbx_ramais";
$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úmero de operadoras locais devem começar em 900 para não conflitarem com o cadastro da operadoras oficiais
* feitos no servidor.
*/
$operSpid = 900;
$query .= "select coalesce(max(oper_spid), 0) as max_spid from pbx_operadoras where oper_spid >= '$operSpid'";
$result = pg_query($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);
while ($row = pg_fetch_array($result)) {
$spid = $row[$fildId];
$oper = $row["oper_nome"];
if ($spid == $id)
$sel = "selected";
else
$sel = "";
$item .= "";
}
return $item;
}
function PbxContratos($id) {
$db = $GLOBALS["dbcon"];
$sel = '';
if (!$id) {
$sel = "selected";
}
$item = "";
$query = "select contr_id, contr_descricao from pbx_tarif_contrato where contr_id <> 0 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 .= "";
}
return $item;
}
function GetTipoCobranca($idTipo = 1) {
$tipoCobranca = array("Minuto" => 1, "Chamada" => "2");
$item = '';
foreach ($tipoCobranca as $key => $value) {
$sel = $idTipo == $value ? "selected=\"selected\"" : "";
$item .= "";
}
return $item;
}
function GravaConfigDb($config) {
$template = ' \'%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çã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\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) {
$query = "select count(*) from $table where $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("%s %s", $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);
/*
* Alteração em homologação em substituicao a query acima.
$query = "drop table if exists tmp_bilhetes_dacs;
create temporary table tmp_bilhetes_dacs(calldate timestamp, data_bilhete date, src varchar(32), uid2 varchar(32), fila varchar(32), evento varchar(32));
insert into tmp_bilhetes_dacs
select a.calldate, a.data_bilhete, a.src, b.uid2, b.fila, b.evento
from ast_bilhetes a, ast_eventos_dacs b
where b.uid2 = a.uniqueid
and a.data_bilhete = now()::date
and b.evento in('ABANDON')
and a.lastapp <> 'Transferred Call';
select a.fila, count(*) as qtde_fila
from tmp_bilhetes_dacs a
where 1 = CASE WHEN(a.evento = 'ABANDON')then (case when(not exists(select '' from ast_eventos_dacs where uid2 = a.uid2 and evento = 'TRANSBORDANDO' and fila = a.fila)) then 1 else 0 end) else 1 end
and not exists(
select ''
from ast_bilhetes d, ast_eventos_dacs e
where e.uid2 = d.uniqueid
and d.data_bilhete = a.data_bilhete
and e.fila = a.fila
and (d.src = a.src or d.dst = a.src)
and d.calldate > a.calldate
and d.lastapp <> 'Transferred Call'
and e.evento in('COMPLETAAGENT','COMPLETACALLER','COMPLETECALLERRAMAL','COMPLETAAGENTRAMAL', 'COMPLETEAGENT','COMPLETECALLER','COMPLETECALLERRAMAL','COMPLETEAGENTRAMAL')
)
group by a.fila;";
*/
$query = "select b.fila, count(distinct a.abdsr_uniqueid) as qtde_fila
from pbx_abandonadas_semretorno a
inner join ast_eventos_dacs b on b.uid2 = a.abdsr_uniqueid and and b.fila = a.absr_fila and b.evento = 'ABANDON'
inner join ast_bilhetes c on c.uniqueid = b.uid2
where a.abdsr_data_hora_retorno is null
and a.abdsr_data >= (now()::date - $diasAbandon)
group by b.fila
order by 1";
$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);
// $query = "select b.fila, count(*) as qtde_fila
// from pbx_abandonadas_semretorno a
// inner join ast_eventos_dacs b on b.uid2 = a.abdsr_uniqueid and b.evento = 'ABANDON'
// inner join ast_bilhetes c on c.uniqueid = b.uid2
// where a.abdsr_data_hora_retorno is null
// and a.abdsr_data >= (now()::date - $diasAbandon)
// group by b.fila
// order by 1";
$result = pg_query($dbcon, $query);
while ($dados = pg_fetch_row($result)) {
$dac = $dados[0];
$arRetornoAbandonadas[$dac] = $dados[1];
}
}
function GetStyleLink($links) {
$lkText = "";
$lkText .= "\n";
$lkText .= "\n";
$lkText .= "\n";
$lkText .= " \n";
$lkText .= "\n";
//$lkText .= "\n";
$lkText .= "\n";
//$lkText .= "\n";
//$lkText .= "\n";
$lkText .= "\n";
$lkText .= "\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 .= "" . "\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 ? "\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ã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"];
$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
)values(%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)
);
$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ã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("", $url);
}
function PbxAlert($msg) {
echo "";
}
function GravaFull($__idProg = 0, $uniqueid = '', $msg = '', $param = '') {
if (IsUserConnect() || $param) {
global $idProg;
$dir = '/var/log/asterisk/audita';
if (!file_exists($dir)) {
system("mkdir -p $dir");
system("chmod 777 -R $dir");
}
if ($__idProg) {
$idProg = $__idProg;
}
$path = $dir . sprintf('/simplesFull-%s.log', date('Y-m-d'));
$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)values(%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));
pg_query($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ção verifica se o ramal existe, e retorna o canal se o ramal é 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.
*/
$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($query);
if ($result && pg_num_rows($result)) {
$acessAudio = 1;
}
return $acessAudio;
$_SESSION['SSAcessoAudio'] = $acessAudio;
}
function GetAcessoAudio($dac) {
$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($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ção verifica se o ramal é válido, retornando ok caso afirmativo.
*/
$canalMonitorar = ValidaRamalApl($ramalMonitorar);
/*
* Ramal inválido retorna falso.
*/
if ($canalMonitorar === false) {
GeraExcept("Erro;Ramal inválido!");
}
if (!SetCookieApl($nomeRamalMonitorar, $ramalMonitorar)) {
GeraExcept("Erro;Não foi possível registrar o \"Ramal\"!");
}
if (!SetCookieApl($nomecanalMonitorar, $canalMonitorar)) {
GeraExcept("Erro;Não foi possí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 = "";
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 = "
";
$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('%s', $cmpAtv);
$contatos = sprintf('%s', $conts);
$discados = sprintf('%s', $disc);
$lkCamp = ($cmpAtv == 0) ? $cmp : sprintf("%s", $cmpAtv);
$linha = "$table
$lkCamp
$contatos
$discados
";
return $retArray ? $dados : $linha;
}
}
return false;
}
function GetDiscadorRestantes($dac, $matricula, $idCampanha = null) {
$lista = '';
$cmplCamp = '';
/**
* Verifica se a campanha é 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çã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;
/*
* O objetivo da função é retornar o total de registro que a consulta ira
* conter para calcular a paginação.
*/
$md5Sql = md5($sql);
$idxPagina = "SSPaginacaoTotalReg_" . $idProg;
$idxPaginaMD5 = "SSPaginacaoMD5_" . $idProg;
/*
* Um hash md5 da consulta é gravado em uma variavel de sessão para
* verificar se houve alteração na mesma, retorna o valor recuperado
* na primeira consulta efetuada se não sofreu alteração.
*/
if (!$recontaPag && isset($_SESSION[$idxPaginaMD5]) && ($_SESSION[$idxPaginaMD5] == $md5Sql)) {
return $_SESSION[$idxPagina];
}
/*
* Esta função prepara a consulta original para trazer apenas um count.
*/
$query = $force ? $sql : PaginacaoSql($sql);
$result = pg_query($query);
$row = $force ? pg_num_rows($result) : pg_fetch_row($result);
/*
* Grava o md5 da consulta para comparaçãoo posterior e também a quantidade de
* registros para retornar a aplicaçã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ão mostrados no rodape.
*/
$tamBloco = PAGINACAO_TAMANHO_BLOCO;
/*
* Quantas linhas são mostradas por página.
*/
$regPagina = StrToIntDef(PaginacaoRegPagina(), 20);
/*
* Calcula o total de registros a serem recuperados.
* Em alguns casos o total de registros é passado direto
* na variavel $sql como um inteiro.
*/
$totalReg = is_numeric($sql) ? $sql : PaginacaoTotalReg($sql, $idProg, $force);
/*
* Calcula o número total de paginas tendo com base o nú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úmero total de blocos necessário para exibir todas as paginas.
*/
$numBlocos = (((int) ($paginas / $tamBloco)) + (($paginas % $tamBloco) > 0 ? 1 : 0)) - 1;
/*
* Indica a navegaçã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úmero de paginas na deleção
*/
if ($pgAtu >= $paginas) {
$pgAtu = $paginas - 1;
}
/*
* A página atual a ser listada.
*/
$offSet = abs($regPagina * $pgAtu);
/*
* Variavel usada para mostar o numero de registros em relação ao total(de até)
*/
$pagMostra = !$totalReg ? 0 : ( (($pgAtu + 1) == $paginas) ? $totalReg : ($regPagina * ($pgAtu + 1)) );
$pgs = '';
$tamIcone = 8;
$imgPrior = sprintf("", !$bloco ? 'priorOff.png' : 'prior.png');
$imgPrevious = sprintf("", !$bloco ? 'previousOff.png' : 'previous.png');
$linkPrior = !$bloco ? $imgPrior : sprintf('%s ', $idProg, $params, $imgPrior);
$linkPrev = !$bloco ? $imgPrevious : sprintf('%s ', $idProg, $params, $bloco, $imgPrevious);
$link = sprintf("
", $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("", 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ã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ã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 .= '';
}
return $listaMes;
}
function GetAno($ano, $head = 0, $sql = '') {
$combo = '';
if ($head) {
$combo .= '';
}
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ó" 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 "
" . print_r($data, true) . "
";
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úncio for selecionado a acao será 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úncio poderia estar cadastro com esse nome)
* @param int $totaldep O número de dependências identificadas para o recurso corrente.
* @return String
*/
function GetLinkDependenciaRecurso($opcao, $acao, $recursoTipo, $nomeRecurso, $totaldep) {
return !$totaldep ? "" : sprintf("", $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 = "";
} else {
$resp = "";
}
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 .= "";
}
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íodo nã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ão foi possível consultar o ramal informado!");
}
if (!pg_num_rows($result)) {
throw new Exception("O ramal informado nã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çãso 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"];
}