|
|
<?php |
|
|
|
|
|
/* * *************************************************************************** |
|
|
* * |
|
|
* Web Application Development with PHP * |
|
|
* by * |
|
|
* Tobias Ratschiller and Till Gerken * |
|
|
* * |
|
|
* Copyright (c) 2000, Tobias Ratschiller and Till Gerken * |
|
|
* * |
|
|
* **************************************************************************** |
|
|
* * |
|
|
* $Title: String validation routines $ * |
|
|
* $Chapter: Basic Web Application Strategies $ * |
|
|
* $Executable: false $ * |
|
|
* * |
|
|
* $Description: * |
|
|
* This file contains some routines useful for form validation and string * |
|
|
* checking: * |
|
|
* - is_alpha() * * |
|
|
* - is_alphanumeric() * |
|
|
* - is_email() * |
|
|
* - is_clean_text() * |
|
|
* - contains_bad_words() * |
|
|
* - contains_phone_number() |
|
|
* - GetJsLink() * |
|
|
* teeteteterererereree * |
|
|
* *************************************************************************** */ |
|
|
/* |
|
|
* Descomente a linha abaixo para ativar o log de eventos do php, |
|
|
* o mesmo sera gravado no arquivo /var/log/asterisk/display_erros.log. |
|
|
*/ |
|
|
include_once("util/display_errors.php"); |
|
|
|
|
|
function _is_valid($string, $min_length, $max_length, $regex) |
|
|
{ |
|
|
// Check if the string is empty |
|
|
$str = trim($string); |
|
|
if (empty($str)) { |
|
|
return (false); |
|
|
} |
|
|
|
|
|
// Does the string entirely consist of characters of $type? |
|
|
if (!preg_match("^$regex$", $string)) { |
|
|
return (false); |
|
|
} |
|
|
|
|
|
// Check for the optional length specifiers |
|
|
$strlen = strlen($string); |
|
|
if (($min_length != 0 && $strlen < $min_length) || ($max_length != 0 && $strlen > $max_length)) { |
|
|
return (false); |
|
|
} |
|
|
|
|
|
// Passed all tests |
|
|
return (true); |
|
|
} |
|
|
|
|
|
/* |
|
|
* bool is_alpha(string string[, int min_length[, int max_length]]) |
|
|
* Check if a string consists of alphabetic characters only. Optionally |
|
|
* check if it has a minimum length of min_length characters and/or a |
|
|
* maximum length of max_length characters. |
|
|
*/ |
|
|
|
|
|
function is_alpha($string, $min_length = 0, $max_length = 0) |
|
|
{ |
|
|
$ret = _is_valid($string, $min_length, $max_length, "[[:alpha:]]+"); |
|
|
|
|
|
return ($ret); |
|
|
} |
|
|
|
|
|
/* |
|
|
* bool is_alphanumeric(string string[, int min_length[, int max_length]]) |
|
|
* Check if a string consists of alphanumeric characters only. Optionally |
|
|
* check if it has a minimum length of min_length characters and/or a |
|
|
* maximum length of max_length characters. |
|
|
*/ |
|
|
|
|
|
function is_alphanumeric($string, $min_length = 0, $max_length = 0) |
|
|
{ |
|
|
$ret = _is_valid($string, $min_length, $max_length, "[[:alnum:]]+"); |
|
|
|
|
|
return ($ret); |
|
|
} |
|
|
|
|
|
/* |
|
|
* bool is_email(string string[, int min_length[, int max_length]]) |
|
|
* Check if a string is a syntactically valid mail address. Optionally |
|
|
* check if it has a minimum length of min_length characters and/or a |
|
|
* maximum length of max_length characters. |
|
|
*/ |
|
|
|
|
|
function is_email($string) |
|
|
{ |
|
|
// Remove whitespace |
|
|
$str = trim($string); |
|
|
|
|
|
$ret = preg_match( |
|
|
'/^([a-z0-9_]|\\-|\\.)+' . |
|
|
'@' . |
|
|
'(([a-z0-9_]|\\-)+\\.)+' . |
|
|
'[a-z]{2,4}$/', |
|
|
$str |
|
|
); |
|
|
|
|
|
return ($ret); |
|
|
} |
|
|
|
|
|
/* |
|
|
* bool contains_bad_words(string string) |
|
|
* Check if a string contains bad words, as defined in the array below |
|
|
*/ |
|
|
|
|
|
function contains_bad_words($string) |
|
|
{ |
|
|
// This array contains words which trigger the "meep" feature of this function |
|
|
// (ie. if one of the array elements is found in the string, the function will |
|
|
// return true). Please note that these words do not constitute a rating of their |
|
|
// meanings - they're used for a first indication if the string might contain |
|
|
// inapropiate language. |
|
|
$bad_words = array( |
|
|
'bicha', 'merda', 'bosta', 'buceta', 'caralho', |
|
|
'porra', 'caga', 'cagar', 'biscate', 'puta', 'filha da puta', |
|
|
'gay' |
|
|
); |
|
|
|
|
|
// Check for bad words |
|
|
for ($i = 0; $i < count($bad_words); $i++) { |
|
|
if (strstr(strtoupper($string), strtoupper($bad_words[$i]))) { |
|
|
return (true); |
|
|
} |
|
|
} |
|
|
|
|
|
// Passed the test |
|
|
return (false); |
|
|
} |
|
|
|
|
|
/* |
|
|
* bool contains_phone_number(string string) |
|
|
* Check if a string contains a phone number (any 10+-digit sequence, |
|
|
* optionally separated by "(", " ", "-" or "/"). |
|
|
*/ |
|
|
|
|
|
function contains_phone_number($string) |
|
|
{ |
|
|
// Check for phone number |
|
|
if (preg_match("[[:digit:]]{3,10}[\. /\)\(-]*[[:digit:]]{6,10}", $string)) { |
|
|
return (true); |
|
|
} |
|
|
|
|
|
// Passed the test |
|
|
return (false); |
|
|
} |
|
|
|
|
|
|
|
|
/* |
|
|
* dd/mm/yyyy |
|
|
* dd/mm/yyyy HH:mm |
|
|
*/ |
|
|
function is_date($date) |
|
|
{ |
|
|
|
|
|
/* <EFBFBD> chamada tamb<EFBFBD>m com esse formato |
|
|
* dd/mm/yyyy HH:mm |
|
|
* Portanto precisa ser mantido o < 10 |
|
|
* 10 verifica se tem o m<EFBFBD>nimo para procurar |
|
|
*/ |
|
|
|
|
|
if (strlen($date) < 10) |
|
|
return (False); |
|
|
else { |
|
|
// Check if the date is valid |
|
|
$dt = preg_split('~/~', $date); |
|
|
return (checkdate((int)$dt[1], (int)$dt[0], (int)$dt[2])); |
|
|
} |
|
|
} |
|
|
|
|
|
function checkDateType($date) |
|
|
{ |
|
|
/* |
|
|
* Valida se a date esta no formato padrao para date ou datetime. |
|
|
*/ |
|
|
$size = strlen($date = trim($date)); |
|
|
if (($size > 19) || ($size < 8)) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
$format = ($size <= 10) ? 'Y-m-d' : 'Y-m-d H:i:s'; |
|
|
|
|
|
$d = DateTime::createFromFormat($format, $date); |
|
|
return ($d && $d->format($format) === $date) ? (($size <= 10) ? 'date' : 'datetime') : false; |
|
|
} |
|
|
|
|
|
//retorna uma string sem acentos |
|
|
function RemoveAcentos($str, $upper = False) |
|
|
{ |
|
|
$text = array('<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>'); |
|
|
$subs = array('A', 'A', 'A', 'A', 'A', 'A', 'A', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'U', 'P', 'B', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'o', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y'); |
|
|
$str = trim($str); |
|
|
for ($i = 0; $i < strlen($str); $i++) { |
|
|
$j = array_search($str[$i], $text); |
|
|
if ($j) |
|
|
$str[$i] = $subs[$j]; |
|
|
} |
|
|
|
|
|
$str = str_replace(['~', '^', '`', '<EFBFBD>', '\''], '', $str); |
|
|
if ($upper && ($upper === -1)) { |
|
|
$str = mb_strtolower($str); |
|
|
} else if ($upper) { |
|
|
$str = mb_strtoupper($str); |
|
|
} |
|
|
return ($str); |
|
|
} |
|
|
|
|
|
//retorna uma string sem acentos |
|
|
function TextToHtml($str) |
|
|
{ |
|
|
$text = array('<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '&'); |
|
|
$subs = array('á', 'é', 'í', 'ó', 'ú', 'â', 'ê', 'ô', 'ã', 'õ', 'à', 'ç', 'Á', 'É', 'Í', 'Ó', 'Ú', 'Â', 'Ê', 'Ô', 'Ã', 'Õ', 'À', 'Ç', '&'); |
|
|
|
|
|
for ($i = 0; $i < strlen($str); $i++) { |
|
|
$j = array_search($str[$i], $text); |
|
|
if ($j !== false) { |
|
|
$str[$i] = $subs[$j]; |
|
|
} |
|
|
} |
|
|
return ($str); |
|
|
} |
|
|
|
|
|
function RemoveChar($str) |
|
|
{ |
|
|
|
|
|
$num = ""; |
|
|
for ($i = 0; $i < strlen($str); $i++) { |
|
|
if (($str[$i] >= '0') && ($str[$i] <= '9')) |
|
|
$num .= $str[$i]; |
|
|
} |
|
|
|
|
|
return ($num); |
|
|
} |
|
|
|
|
|
function FormatDtMssql($dt, $useQoted = false) |
|
|
{ |
|
|
$data = explode('/', $dt); |
|
|
$data = ($data[2] . "-" . $data[1] . "-" . $data[0]); |
|
|
return $useQoted ? QuotedStr($data) : $data; |
|
|
} |
|
|
|
|
|
function FormatDtHoraBD($dt) |
|
|
{ |
|
|
$data = preg_split('/[\/" ":]/', $dt); |
|
|
return ($data[2] . "-" . $data[1] . "-" . $data[0] . " " . ($data[3] ? $data[3] : "00") . ":" . ($data[4] ? $data[4] : "00") . ":" . ($data[5] ? $data[5] : "00")); |
|
|
} |
|
|
|
|
|
function FormatDateHour($dt) |
|
|
{ |
|
|
$hour = explode(' ', $dt); |
|
|
$date = explode('/', $hour[0]); |
|
|
$strDateHour = implode('-', $date) . " " . $hour[1]; |
|
|
return $strDateHour; |
|
|
} |
|
|
|
|
|
function FormataDBDataHora($dt, $sepData = "/", $sepHora = ":") |
|
|
{ |
|
|
if (!$dt) |
|
|
return ""; |
|
|
$dt = trim(substr($dt, 0, 19)); |
|
|
$data = preg_split('/[-" ":\/]/', $dt); |
|
|
//$data = explode('-', trim($dt)); |
|
|
|
|
|
$result = (isset($data[2]) ? $data[2] : "") . $sepData . (isset($data[1]) ? $data[1] : "") . $sepData . $data[0]; |
|
|
if (isset($data[3]) && $data[3]) { |
|
|
$result .= " " . $data[3] . $sepHora; |
|
|
$result .= ($data[4] ? $data[4] : "00"); |
|
|
$result .= $sepHora . ($data[5] ? $data[5] : "00"); |
|
|
} |
|
|
return $result; |
|
|
} |
|
|
|
|
|
function FormataDataDbDataDisplay($data) |
|
|
{ |
|
|
if (!$data) |
|
|
return ""; |
|
|
$data = explode('-', substr($data, 0, 10)); |
|
|
return sprintf("%s/%s/%s", $data[2], $data[1], $data[0]); |
|
|
} |
|
|
|
|
|
function htmlBreak() |
|
|
{ |
|
|
return "<div style=\"page-break-before:always;\"></div>\n"; |
|
|
} |
|
|
|
|
|
function SecondToStrTime($sec) |
|
|
{ |
|
|
$seconds = $sec; |
|
|
$hours = floor($seconds / 3600); |
|
|
$seconds -= $hours * 3600; |
|
|
$minutes = floor($seconds / 60); |
|
|
$seconds -= $minutes * 60; |
|
|
|
|
|
$hours = strlen($hours) == 1 ? "0" . $hours : $hours; |
|
|
$minutes = strlen($minutes) == 1 ? "0" . $minutes : $minutes; |
|
|
$seconds = strlen($seconds) == 1 ? "0" . $seconds : $seconds; |
|
|
|
|
|
return "$hours:$minutes:$seconds"; |
|
|
} |
|
|
|
|
|
function IsNull($value, $def, $quoted = 0) |
|
|
{ |
|
|
$value = isset($value) ? trim($value) : ''; |
|
|
return empty($value) ? ($quoted ? QuotedStr($def) : $def) : ($quoted ? QuotedStr($value) : $value); |
|
|
} |
|
|
|
|
|
function NullDb($value) |
|
|
{ |
|
|
/* |
|
|
* Var nao esta setado eh empty |
|
|
* Zero eh empty |
|
|
* String vazia '' eh empty |
|
|
* String vazia "" eh empty |
|
|
* Espaco " " nao eh empty |
|
|
* False eh empty |
|
|
* Array vazio eh empty |
|
|
*/ |
|
|
|
|
|
/* Valores empty que nao serao considerados nulos para o banco de dados */ |
|
|
if (is_numeric($value) && (((int) $value) === 0)) |
|
|
return QuotedStr($value); |
|
|
return empty($value) ? 'null' : QuotedStr($value); |
|
|
} |
|
|
|
|
|
function GetSequenciaDb($db, $sequencia) |
|
|
{ |
|
|
$row = array(false); |
|
|
$query = "select currval('$sequencia')"; |
|
|
$result = pg_query($db, $query); |
|
|
if ($result) |
|
|
$row = @pg_fetch_row($result); |
|
|
return $row[0]; |
|
|
} |
|
|
|
|
|
function soNumero($str, $expt = array()) |
|
|
{ |
|
|
$strNum = ""; |
|
|
$ch = ''; |
|
|
$numeros = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); |
|
|
if (!empty($expt)) { |
|
|
$numeros = array_merge($numeros, $expt); |
|
|
} |
|
|
for ($i = 0; $i < strlen($str); $i++) { |
|
|
$ch = substr($str, $i, 1); |
|
|
if (array_search($ch, $numeros) !== false) |
|
|
$strNum .= $ch; |
|
|
} |
|
|
return $strNum; |
|
|
} |
|
|
|
|
|
function soTexto($str) |
|
|
{ |
|
|
$strNum = ""; |
|
|
$ch = ''; |
|
|
$numeros = array('-1', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); |
|
|
for ($i = 0; $i < strlen($str); $i++) { |
|
|
$ch = substr($str, $i, 1); |
|
|
if (array_search($ch, $numeros) === false) |
|
|
$strNum .= $ch; |
|
|
} |
|
|
return $strNum; |
|
|
} |
|
|
|
|
|
function QuotedStr($str) |
|
|
{ |
|
|
include_once('bd.php'); |
|
|
$dbcon = pg_connect(GetConectString()); |
|
|
return sprintf("'%s'", pg_escape_string($dbcon, trim($str))); |
|
|
} |
|
|
|
|
|
function FormataFone($numero) |
|
|
{ |
|
|
$numero = soNumero($numero); |
|
|
$tam = strlen($numero); |
|
|
|
|
|
if (($tam < 8) || ($tam > 11)) |
|
|
return $numero; |
|
|
|
|
|
switch ($tam) { |
|
|
case 8: |
|
|
return substr($numero, 0, 4) . "-" . substr($numero, 4, 4); |
|
|
case 9: |
|
|
return substr($numero, 0, 5) . "-" . substr($numero, 5, 4); |
|
|
case 10: |
|
|
return "(" . substr($numero, 0, 2) . ")" . substr($numero, 2, 4) . "-" . substr($numero, 6, 4); |
|
|
case 11: |
|
|
return "(" . substr($numero, 0, 2) . ")" . substr($numero, 2, 5) . "-" . substr($numero, 7, 4); |
|
|
} |
|
|
|
|
|
if (strlen($numero) == 8) |
|
|
return !(strlen($numero) == 10) ? $numero : "(" . substr($numero, 0, 2) . ")" . substr($numero, 2, 4) . "-" . substr($numero, 6, 4); |
|
|
} |
|
|
|
|
|
function is_time($time) |
|
|
{ |
|
|
if (empty($time)) { |
|
|
$time = "00:00"; |
|
|
} |
|
|
$hora = explode(":", $time); |
|
|
$hora[0] = (int) $hora[0]; |
|
|
$hora[1] = (int) $hora[1]; |
|
|
|
|
|
return (!$hora[0] && !$hora[1]) ? true : (($hora[0] > 23) || ($hora[1] > 59) ? false : true); |
|
|
} |
|
|
|
|
|
function FormataHoraDbApl($data) |
|
|
{ |
|
|
return ""; |
|
|
} |
|
|
|
|
|
function LimpaString($str, $toUpeer = true, $removeSpace = true) |
|
|
{ |
|
|
if (!isset($str) || !$str) { |
|
|
return ''; |
|
|
} else |
|
|
if (!is_string($str)) { |
|
|
return $str; |
|
|
} |
|
|
$string = trim($str); |
|
|
$array1 = array('<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>', '<EFBFBD>'); |
|
|
$array2 = array('A', 'A', 'A', 'A', 'A', 'A', 'A', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'U', 'P', 'B', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'o', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y'); |
|
|
$string = str_replace($array1, $array2, $string); |
|
|
$newstring = preg_replace(($removeSpace ? "/[^a-zA-Z0-9_.]/" : "/[^a-zA-Z0-9\s_.]/"), "", $string); |
|
|
return $toUpeer ? strtoupper($newstring) : $newstring; |
|
|
} |
|
|
|
|
|
function GetFileExt($nomeArq) |
|
|
{ |
|
|
$getExt = explode('.', $nomeArq); |
|
|
return $getExt[abs(count($getExt)) - 1]; |
|
|
} |
|
|
|
|
|
function RemoveEspaco($txt, $ch = '') |
|
|
{ |
|
|
|
|
|
|
|
|
return str_replace(' ', $ch, $txt); |
|
|
|
|
|
$str = ''; |
|
|
for ($i = 0; $i < strlen($txt); $i++) { |
|
|
if (!(substr($txt, $i, 1) == ' ')) |
|
|
$str .= substr($txt, $i, 1); |
|
|
} |
|
|
|
|
|
return $str; |
|
|
} |
|
|
|
|
|
function GetHtmlSelect($name, $text = "---------------", $compl = "", $soOpt = 0) |
|
|
{ |
|
|
if ($soOpt) |
|
|
return "<option value=\"0\" selected>$text</option>\n"; |
|
|
|
|
|
$clas = "<select name=\"$name\" id=\"$name\" $compl\">\n"; |
|
|
$clas .= "<option value=\"0\" selected>$text</option>\n"; |
|
|
$clas .= "</select>"; |
|
|
|
|
|
return $clas; |
|
|
} |
|
|
|
|
|
function FormataValor($number, $dec = 2, $decPoint = ',', $thousandsSep = ".") |
|
|
{ |
|
|
if (!is_numeric($number)) { |
|
|
return $number; |
|
|
} |
|
|
return number_format($number, $dec, $decPoint, $thousandsSep); |
|
|
} |
|
|
|
|
|
function FormataValorBd($valor) |
|
|
{ |
|
|
$valor = str_replace('.', '', $valor); |
|
|
return str_replace(',', '.', $valor); |
|
|
} |
|
|
|
|
|
function GetDateFromString($data, $date = false) |
|
|
{ |
|
|
if (!$date) { |
|
|
$data = FormatDtMssql($data); |
|
|
} |
|
|
|
|
|
return strtotime($data); |
|
|
} |
|
|
|
|
|
function DefEmpty() |
|
|
{ |
|
|
if (empty($var)) |
|
|
echo "<font color=\"#ff0000\">Var nao esta setado <EFBFBD> empty</font> <br>"; |
|
|
else |
|
|
echo "Var nao esta setado n<EFBFBD>o <EFBFBD> empty <br>"; |
|
|
$var = 0; |
|
|
if (empty($var)) |
|
|
echo "<font color=\"#ff0000\">Zero <EFBFBD> empty </font><br>"; |
|
|
else |
|
|
echo "Zero n<EFBFBD>o <EFBFBD> empty <br>"; |
|
|
|
|
|
$var = ''; |
|
|
if (empty($var)) |
|
|
echo "<font color=\"#ff0000\">String vazia '' <EFBFBD> empty</font> <br>"; |
|
|
else |
|
|
echo "String vazia '' nao <EFBFBD> empty <br>"; |
|
|
|
|
|
$var = ""; |
|
|
if (empty($var)) |
|
|
echo "<font color=\"#ff0000\">String vazia \"\" <EFBFBD> empty</font> <br>"; |
|
|
else |
|
|
echo "String vazia \"\" n<EFBFBD>o <EFBFBD> empty <br>"; |
|
|
|
|
|
$var = " "; |
|
|
if (empty($var)) |
|
|
echo "<font color=\"#ff0000\">Espa<EFBFBD>o \" \" <EFBFBD> empty</font> <br>"; |
|
|
else |
|
|
echo "Espa<EFBFBD>o \" \" nao <EFBFBD> empty <br>"; |
|
|
|
|
|
$var = false; |
|
|
if (empty($var)) |
|
|
echo "<font color=\"#ff0000\">False <EFBFBD> empty</font> <br>"; |
|
|
else |
|
|
echo "false n<EFBFBD>o <EFBFBD> empty <br>"; |
|
|
|
|
|
$var = array(); |
|
|
if (empty($var)) |
|
|
echo "<font color=\"#ff0000\">Array vazio <EFBFBD> empty</font> <br>"; |
|
|
else |
|
|
echo "array vazio n<EFBFBD>o <EFBFBD> empty <br>"; |
|
|
} |
|
|
|
|
|
function StrToIntDef($str, $def = 0) |
|
|
{ |
|
|
return is_numeric($str) ? $str : $def; |
|
|
} |
|
|
|
|
|
function GetDddPadrao($numero = '') |
|
|
{ |
|
|
$query = "select prm_ddd_padrao from pbx_parametros where id = 1\n"; |
|
|
$result = pg_query($query); |
|
|
|
|
|
if (pg_num_rows($result)) { |
|
|
$dados = pg_fetch_row($result); |
|
|
return $dados[0] . $numero; |
|
|
} |
|
|
return $numero; |
|
|
} |
|
|
|
|
|
function RemoveDddPadrao($numeroDiscar, $ddd = '') |
|
|
{ |
|
|
$numero = ltrim($numeroDiscar, '0'); |
|
|
$tam = strlen($numero); |
|
|
$dddPadrao = $ddd ? $ddd : GetDddPadrao(); |
|
|
if ((($tam == 10) || ($tam == 11)) && ($dddPadrao == substr($numero, 0, 2))) { |
|
|
return str_replace('+', '', substr($numero, 2)); |
|
|
} |
|
|
|
|
|
return $numeroDiscar; |
|
|
} |
|
|
|
|
|
function IsAjax() |
|
|
{ |
|
|
return isset($_REQUEST['ajax']) && ($_REQUEST['ajax'] = 1); |
|
|
} |
|
|
|
|
|
function IsPostBack() |
|
|
{ |
|
|
return count($_POST); |
|
|
} |
|
|
|
|
|
function IsWin() |
|
|
{ |
|
|
return (strtoupper(substr(PHP_OS, 0, 3)) == "WIN") && (trim(getenv("OS")) != ''); |
|
|
} |
|
|
|
|
|
function GetServerApi() |
|
|
{ |
|
|
include "configBd.php"; |
|
|
return sprintf("%s%s", $hostApi, ($portaApi ? ":{$portaApi}" : "")); |
|
|
} |
|
|
|
|
|
function GetDefStrDb() |
|
|
{ |
|
|
include "configBd.php"; |
|
|
return "host='$dbHost' port='$dbPort' dbname='$dbName' user='$dbUser' password='$dbPassword'"; |
|
|
} |
|
|
|
|
|
function GetSckConnect() |
|
|
{ |
|
|
|
|
|
$path = "bd"; |
|
|
$arq = @fopen($path, 'r', true); |
|
|
if (!$arq) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
$arConf = array(); |
|
|
while (!feof($arq)) { |
|
|
$line = trim(fgets($arq)); |
|
|
if ($line && stripos($line, "SCK")) { |
|
|
list($name, $value) = explode("=", $line); |
|
|
$arConf[] = str_replace("\"", "", $value); |
|
|
} |
|
|
} |
|
|
|
|
|
@fclose($arq); |
|
|
|
|
|
return $arConf; |
|
|
//Inclusao dos troncos no monitor de ramais |
|
|
} |
|
|
|
|
|
function ConvertUt8ToIso($str) |
|
|
{ |
|
|
return $str; |
|
|
return (mb_detect_encoding($str) == 'UTF-8') ? utf8_decode($str) : $str; |
|
|
/* |
|
|
foreach ($_POST as $key => $value) |
|
|
{ |
|
|
if(mb_detect_encoding($value) == 'UTF-8') |
|
|
{ |
|
|
$strDecode = utf8_decode($value); |
|
|
$_POST[$key] = $strDecode; //<EFBFBD>udio, a<EFBFBD><EFBFBD>o anota<EFBFBD><EFBFBD>es, refer<EFBFBD>ncia |
|
|
} |
|
|
} |
|
|
* |
|
|
*/ |
|
|
} |
|
|
|
|
|
function ConvertUt8($arSource) |
|
|
{ |
|
|
$arDecode = array(); |
|
|
$utfAvalible = IsAjax() && IsPostBack() && ('POST' == $_POST['ajaxTipo']); |
|
|
if ($utfAvalible) { |
|
|
foreach ($arSource as $key => $value) { |
|
|
$arDecode[$key] = utf8_decode($value); |
|
|
} |
|
|
return $arDecode; |
|
|
} |
|
|
return $arSource; |
|
|
} |
|
|
|
|
|
function GeraExcept($msg) |
|
|
{ |
|
|
throw new Exception($msg); |
|
|
} |
|
|
|
|
|
function RaiseExcept($msg, $dbError = false) |
|
|
{ |
|
|
if ($dbError) { |
|
|
$msg .= " DB: " . pg_last_error(); |
|
|
} |
|
|
GeraExcept($msg . "\n"); |
|
|
} |
|
|
|
|
|
function WriteLog($log, $path = '') |
|
|
{ |
|
|
if (!$path) { |
|
|
$path = '/var/log/asterisk/log_geral.log'; |
|
|
} |
|
|
$arq = fopen($path, 'a'); |
|
|
fwrite($arq, trim($log) . "\n"); |
|
|
fclose($arq); |
|
|
} |
|
|
|
|
|
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); |
|
|
|
|
|
if ($mes == 1) |
|
|
$ano--; |
|
|
$mes = $mes == 1 ? 12 : ($mes - 1); |
|
|
|
|
|
|
|
|
$finalMes = GetLastDayofMonth($ano, $mes); |
|
|
if (++$diaFecha > $finalMes) |
|
|
$diaFecha = $finalMes; |
|
|
|
|
|
return sprintf("%s-%s-%s", str_pad($ano, 2, '0', STR_PAD_LEFT), str_pad($mes, 2, '0', STR_PAD_LEFT), str_pad($diaFecha, 2, '0', STR_PAD_LEFT)); |
|
|
} |
|
|
|
|
|
function GetDataFimFatura($ano, $mes, $diaFecha) |
|
|
{ |
|
|
//$ano . "-" . ($mes) . "-" . ($diaFecha); |
|
|
$finalMes = GetLastDayofMonth($ano, $mes); |
|
|
if ($diaFecha > $finalMes) |
|
|
$diaFecha = $finalMes; |
|
|
return sprintf("%s-%s-%s", str_pad($ano, 2, '0', STR_PAD_LEFT), str_pad($mes, 2, '0', STR_PAD_LEFT), str_pad($diaFecha, 2, '0', STR_PAD_LEFT)); |
|
|
} |
|
|
|
|
|
function downloadFile($url, $path) |
|
|
{ |
|
|
$newfname = $path; |
|
|
$file = fopen($url, "rb"); |
|
|
$contents = stream_get_contents($file); |
|
|
fclose($file); |
|
|
|
|
|
$newf = fopen($newfname, "wb"); |
|
|
fwrite($newf, $contents); |
|
|
fclose($newf); |
|
|
|
|
|
if (file_exists($newfname)) { |
|
|
if (filesize($newfname) > 100) { |
|
|
return true; |
|
|
} |
|
|
} |
|
|
return false; |
|
|
|
|
|
|
|
|
$newfname = $path; |
|
|
$file = fopen($url, "rb"); |
|
|
if ($file) { |
|
|
$newf = fopen($newfname, "wb"); |
|
|
|
|
|
if ($newf) |
|
|
while (!feof($file)) { |
|
|
fwrite($newf, fread($file, 1024 * 8), 1024 * 8); |
|
|
} |
|
|
} |
|
|
|
|
|
if ($file) { |
|
|
fclose($file); |
|
|
} |
|
|
|
|
|
if ($newf) { |
|
|
fclose($newf); |
|
|
} |
|
|
|
|
|
if (file_exists($newfname)) { |
|
|
if (filesize($newfname) > 100) { |
|
|
return true; |
|
|
} |
|
|
} |
|
|
return false; |
|
|
} |
|
|
|
|
|
function GetFileByStr($workDir, $str) |
|
|
{ |
|
|
$files = scandir($workDir); |
|
|
|
|
|
foreach ($files as $file) { |
|
|
if (stripos($file, $str) !== false) { |
|
|
return $file; |
|
|
} |
|
|
} |
|
|
|
|
|
return false; |
|
|
} |
|
|
|
|
|
function GetArrayKey($ar, $sep = ",", $needle = false) |
|
|
{ |
|
|
|
|
|
|
|
|
if (!$needle) { |
|
|
return implode($sep, array_keys($ar)); |
|
|
} |
|
|
|
|
|
$str = ''; |
|
|
$numKeys = count($ar); |
|
|
for ($i = 0; $i < $numKeys; $i++) { |
|
|
$str .= !$str ? "%s" : ",%s"; |
|
|
} |
|
|
|
|
|
return $str; |
|
|
} |
|
|
|
|
|
function GetLasterror() |
|
|
{ |
|
|
$erro = error_get_last(); |
|
|
return trim($erro['message']); |
|
|
} |
|
|
|
|
|
function vai_comando($comando) |
|
|
{ |
|
|
return CnvrtFileExec($comando); |
|
|
} |
|
|
|
|
|
function LimitFranquia($contrId, $tipoFranquia, $tipoDispositivo, $franquia, &$totalFranquia, &$totalUtilizado, $franquiaMovel = 0, $diaFecha = 1) |
|
|
{ |
|
|
/* |
|
|
* Tipos de franquia: Fixo/Movel -> 4, Movel -> 3, Fixo -> 2, Compartilhada -> 1, Desbilidadta -> 0 |
|
|
*/ |
|
|
global $log; |
|
|
$log[] = sprintf("LimitFranquia contrId: %s Tipo: %s Dispositivo: %s Franquia: %s Franquia Movel: %s\n", $contrId, $tipoFranquia, $tipoDispositivo, $franquia, $franquiaMovel); |
|
|
$ano = date("Y"); |
|
|
$mes = date("m"); |
|
|
$dataIni = GetDataIniFatura($ano, $mes, $diaFecha); |
|
|
if ($tipoFranquia == 4) { |
|
|
$totalFranquia = $tipoDispositivo == 'fixo' ? $franquia : $franquiaMovel; |
|
|
$query = "select sum(trr_duracao) / 60 as minutos from pbx_tarif_registra where contr_id = $contrId and trr_data >= '$dataIni' and trr_data <= now()::date and trr_tipo_dispositivo = '$tipoDispositivo'"; |
|
|
} else if ($tipoFranquia == 3) { |
|
|
/* |
|
|
* Se for ligacao fixa libera. |
|
|
*/ |
|
|
if ($tipoDispositivo == 'fixo') { |
|
|
return false; |
|
|
} |
|
|
$totalFranquia = $franquiaMovel; |
|
|
$query = "select sum(trr_duracao) / 60 as minutos from pbx_tarif_registra where contr_id = $contrId and trr_data >= '$dataIni' and trr_data <= now()::date and trr_tipo_dispositivo = 'movel'"; |
|
|
} else if ($tipoFranquia == 2) { |
|
|
/* |
|
|
* Se for ligacaoo movel libera. |
|
|
*/ |
|
|
if ($tipoDispositivo == 'movel') { |
|
|
return false; |
|
|
} |
|
|
$totalFranquia = $franquia; |
|
|
$query = "select sum(trr_duracao) / 60 as minutos from pbx_tarif_registra where contr_id = $contrId and trr_data >= '$dataIni' and trr_data <= now()::date and trr_tipo_dispositivo = 'fixo'"; |
|
|
} else if ($tipoFranquia == 1) { |
|
|
$totalFranquia = $franquia; |
|
|
$query = "select sum(trr_duracao) / 60 as minutos from pbx_tarif_registra where contr_id = $contrId and trr_data >= '$dataIni' and trr_data <= now()::date"; |
|
|
} else { |
|
|
/* |
|
|
* franquia desabilitada. |
|
|
*/ |
|
|
$log[] = "Franquia Desabilitada tipoFranquia = 0."; |
|
|
return false; |
|
|
} |
|
|
|
|
|
|
|
|
$result = pg_query($query); |
|
|
|
|
|
$log[] = sprintf("LimitFranquia tipoFranquia: %s \nQuery: %s\n", $tipoFranquia, $query); |
|
|
if (!pg_num_rows($result)) { |
|
|
$log[] = sprintf("Registro n<EFBFBD>o encontrado deixa a opera<EFBFBD><EFBFBD>o prosseguir %s\n", ''); |
|
|
return false; |
|
|
} |
|
|
|
|
|
$row = pg_fetch_row($result); |
|
|
$totalUtilizado = $row[0] ? $row[0] : 0; |
|
|
|
|
|
$log[] = sprintf("Limite-> Total Franquia: %s Total Utilizado: %s", $totalFranquia, $totalUtilizado); |
|
|
|
|
|
return $totalFranquia > $totalUtilizado; |
|
|
} |
|
|
|
|
|
function VerificaLimiteFranquia($trcId, $destino, $gravaLog = 0, $encerraScrp = 0, $nomeLog = '') |
|
|
{ |
|
|
/* |
|
|
* VerificaLimiteFranquia(17, $numero, 1, 1, ''); |
|
|
* Autor: Amarildo Pereira. |
|
|
* Data: 17/09/2015. |
|
|
* Objetivo: Verificar se o limite da franquia cadastrado para determinado contrato foi |
|
|
* atingido e encerrar a chamada caso verdadeiro. O parametro bloquear franquia deve |
|
|
* estar habilitado no cadastro do contrato para este comportamento. |
|
|
* Parametros: |
|
|
* - $trcId: Numero do tronco que estara associado a um contrato. |
|
|
* - $gravaLog: Qdo 0 grava apenas se houver algum erro do contr<EFBFBD>rio grava outras informa<EFBFBD><EFBFBD>es. |
|
|
* - $encerraScrp: Qdo 1 chama a funcao exit para encerra o script. |
|
|
* - $nomeLog: Qdo vazio assume "verifica_franquia", se preferir outro nome passe sem extens<EFBFBD>o |
|
|
* pois a extens<EFBFBD>o .log ser<EFBFBD> adicionada automaticamente, os logs ser<EFBFBD>o gradados em /var/log/asterisk. |
|
|
* Data Ult. Mod: - |
|
|
*/ |
|
|
|
|
|
include_once('bd.php'); |
|
|
include_once('funcoes/shared.php'); |
|
|
include_once("util/funcoesAgi.php"); |
|
|
|
|
|
global $log; |
|
|
$log[] = "ExitChamada "; |
|
|
$pathLog = $nomeLog ? $nomeLog : 'verifica_franquia'; |
|
|
$utilizaBloqueio = false; |
|
|
|
|
|
/* |
|
|
* Arquivo de audio que informa o operador que seu limite de franquia |
|
|
* foi atingido e que nao sera possivel realizar a chamada. |
|
|
*/ |
|
|
//$pathSom = '/var/lib/asterisk/sounds/customizados/franquia_bloqueada'; |
|
|
$pathSom = '/var/lib/asterisk/sounds/appsounds/franquia_excedida'; |
|
|
|
|
|
try { |
|
|
$dddPadrao = GetDddPadrao(); |
|
|
$tpChamada = GetTipoChamada($destino, $dddPadrao); |
|
|
$dispositivo = $tpChamada[0]; |
|
|
//$tipoChamada = $tpChamada[1]; |
|
|
//$numOper = $tpChamada[2]; |
|
|
|
|
|
/* |
|
|
* Consulta informacoes do contrato ligado ao troco utilizadao para chamada. |
|
|
*/ |
|
|
$query = "select a.id, a.nome, b.contr_id, b.oper_id, c.oper_numero, b.contr_dia_fechamento, b.contr_descricao, |
|
|
b.contr_bloq_franquia, b.contr_tipo_franquia, d.prc_franquia, d.prc_franquia_movel |
|
|
from pbx_troncos a, pbx_tarif_contrato b, pbx_operadoras c, pbx_tarif_contrato_preco d |
|
|
where b.contr_id = a.contrato |
|
|
and c.oper_id = b.oper_id |
|
|
and d.contr_id = b.contr_id |
|
|
and d.prc_vigencia = (select max(prc_vigencia) from pbx_tarif_contrato_preco aa where contr_id = b.contr_id and prc_vigencia <= now()::date) |
|
|
and a.id = '$trcId'"; |
|
|
$result = pg_query($query); |
|
|
$log[] = sprintf("Query executada: %s", $query); |
|
|
|
|
|
/* |
|
|
* Valida<EFBFBD><EFBFBD>es de integridade da consulta. |
|
|
*/ |
|
|
if (!$result) { |
|
|
GeraExcept("Erro ao consultar banco de dados: $query"); |
|
|
} |
|
|
if (!pg_num_rows($result)) { |
|
|
GeraExcept("Os dados referente ao contrato n<EFBFBD>o foram encontrados: $query"); |
|
|
} |
|
|
|
|
|
/* |
|
|
* Recupera os dados do contrato para a variavel $row. |
|
|
*/ |
|
|
$row = pg_fetch_array($result); |
|
|
|
|
|
/* |
|
|
* Parametro verdadeiro indica que a verifica<EFBFBD><EFBFBD>o do bloqueio se o limite da franquia for atingido. |
|
|
*/ |
|
|
$utilizaBloqueio = $row['contr_bloq_franquia']; |
|
|
|
|
|
/* |
|
|
* Usado para verifica se <EFBFBD> necessario encerrar a execu<EFBFBD><EFBFBD>o do script. |
|
|
*/ |
|
|
$encerra = false; |
|
|
|
|
|
$totalFranquia = 0; |
|
|
$totalUtilizado = 0; |
|
|
|
|
|
/* |
|
|
* Verifica se o bloqueio foi configurado e o limite da frqnquia. |
|
|
*/ |
|
|
if ($utilizaBloqueio && !LimitFranquia($row['contr_id'], $row['contr_tipo_franquia'], $dispositivo, $row['prc_franquia'], $totalFranquia, $totalUtilizado, $row['prc_franquia_movel'], $row['contr_dia_fechamento'])) { |
|
|
$log[] = sprintf("A fun<EFBFBD><EFBFBD>o LimitFranquia(%s,%s,%s,%s,%s) verificou quo o limite <EFBFBD> insuficiente para realizar a chamada.", $row['contr_id'], $row['contr_tipo_franquia'], $dispositivo, $row['prc_franquia'], $row['prc_franquia_movel']); |
|
|
|
|
|
if ($utilizaBloqueio == 1) { |
|
|
/* |
|
|
* Interage com o asterisk, por funcoes agi. |
|
|
*/ |
|
|
$agi = GetAgi(); |
|
|
|
|
|
/* |
|
|
* Executa audio padrao para o cliente na ura. |
|
|
*/ |
|
|
//$agi->stream_file($pathSom); |
|
|
if ($gravaLog) { |
|
|
GravaLogApl($log, $pathLog); |
|
|
} |
|
|
/* |
|
|
* Encerra a chamada. |
|
|
*/ |
|
|
$agi->exec("Goto s,franquia"); |
|
|
} else { |
|
|
$log[] = sprintf("A fun<EFBFBD><EFBFBD>o LimitFranquia(%s,%s,%s,%s,%s) verificou quo o limite <EFBFBD> insuficiente para realizar o um aviso ser<EFBFBD> enviado", $row['contr_id'], $row['contr_tipo_franquia'], $dispositivo, $row['prc_franquia'], $row['prc_franquia_movel']); |
|
|
AvisaLimitFranquiaExcedido($row['nome'], $row['contr_descricao'], $totalFranquia, $totalUtilizado); |
|
|
} |
|
|
|
|
|
/* |
|
|
* Encerra a execucao do script ou nao com base no parametro $encerraScrp. |
|
|
*/ |
|
|
$encerra = $encerraScrp; |
|
|
} |
|
|
|
|
|
$log[] = !$utilizaBloqueio ? "Bloqueio de franquia nao configurado para este contrato!" : sprintf("A fun<EFBFBD><EFBFBD>o LimitFranquia(%s,%s,%s,%s,%s) verificou quo o limite <EFBFBD> suficiente e permitiu realizar a chamada.", $row['contr_id'], $row['contr_tipo_franquia'], $dispositivo, $row['prc_franquia'], $row['prc_franquia_movel']); |
|
|
|
|
|
/* |
|
|
* Grava o logo de chamdas se assim configurado. |
|
|
*/ |
|
|
if ($gravaLog) { |
|
|
GravaLogApl($log, $pathLog); |
|
|
} |
|
|
if ($encerra) { |
|
|
exit(); |
|
|
} |
|
|
} catch (Exception $ex) { |
|
|
$log[] = sprintf("Ocorreram erros durante a execucao da funcao: VerificaLimiteFranquia!\nMensagem: %s.\nErro Sistema: %s.", $ex->getMessage(), GetLasterror()); |
|
|
GravaLogApl($log, $pathLog); |
|
|
} |
|
|
} |
|
|
|
|
|
function AvisaLimitFranquiaExcedido($tronco, $contrato, $totalFranquia, $totalUtilizado) |
|
|
{ |
|
|
|
|
|
include_once('bd.php'); |
|
|
include_once('funcoes/shared.php'); |
|
|
|
|
|
try { |
|
|
$log[] = "AvisaLimitFranquiaExcedido "; |
|
|
|
|
|
if (VerificaAvisoFranquia($contrato)) { |
|
|
return true; |
|
|
} |
|
|
|
|
|
$query = "select wkf_smtp, wkf_smtp_user, wkf_smtp_senha, wkf_smtp_port, wkf_smtp_requer_aut from pbx_workflow_parametros;"; |
|
|
$result = pg_query($query); |
|
|
list($smtp, $user, $senha, $porta, $aut) = pg_fetch_row($result); |
|
|
|
|
|
|
|
|
$query = "select wkf_email from pbx_workflow_emails where upper(wkf_nome) = 'AVISO FRANQUIA' and wkf_status = '0';"; |
|
|
$result = pg_query($query); |
|
|
$paramEmail = pg_fetch_all($result); |
|
|
|
|
|
foreach ($paramEmail as $param) { |
|
|
|
|
|
$params = array( |
|
|
'email_smtp' => $smtp, |
|
|
'email_auth' => true, |
|
|
'email_conta_envio' => $user, |
|
|
'email_senha_envio' => $senha, |
|
|
'email_port' => $porta, |
|
|
'email_retorno' => 'noreply@simplesip.com.br', |
|
|
'email_retorno_nome' => '', |
|
|
'email_envio' => $param['wkf_email'], |
|
|
'email_envio_nome' => '', |
|
|
'email_html' => true, |
|
|
'email_assunto' => 'Aviso Limite de Franquia', |
|
|
'email_charset' => 'iso-8859-1', |
|
|
'email_body' => '', |
|
|
'email_template' => 'aviso-franquia.html', |
|
|
'email_template_info' => array('TRONCO' => $tronco, 'CONTRATO' => $contrato, 'LIMITE_FRANQUIA' => $totalFranquia, 'LIMITE_UTILIZADO' => $totalUtilizado) |
|
|
); |
|
|
|
|
|
$envSendMail = SendEmail($params); |
|
|
if ($envSendMail !== true) { |
|
|
RaiseExcept($envSendMail); |
|
|
} |
|
|
AvisoFranquiaReg($contrato); |
|
|
return true; |
|
|
} |
|
|
} catch (Exception $ex) { |
|
|
|
|
|
$log[] = $ex->getMessage(); |
|
|
$log[] = print_r($params, true); |
|
|
GravaLogApl($log, 'avisa_limite_franquia'); |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
function VerificaAvisoFranquia($contrato) |
|
|
{ |
|
|
/* |
|
|
* Retorna verdadeiro caso ja tenha enviado um aviso no dia. |
|
|
*/ |
|
|
try { |
|
|
$log[] = 'VerificaAvisoFranquia'; |
|
|
$query = sprintf("select '' from pbx_aviso_franquia_reg where contrato = %s and data_aviso = '%s'", QuotedStr($contrato), date("Y-m-d")); |
|
|
$result = pg_query($query); |
|
|
if (!$result) { |
|
|
GeraExcept(ErrorGetLast()); |
|
|
} |
|
|
return pg_num_rows($result) ? true : false; |
|
|
} catch (Exception $ex) { |
|
|
$log[] = sprintf("Erro ao registrar aviso de limite de franquia: %s Data: %s", $ex->getMessage(), date("Y-m-d H:i:s")); |
|
|
GravaLogApl($log, 'avisa_limite_franquia'); |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
function AvisoFranquiaReg($contrato) |
|
|
{ |
|
|
try { |
|
|
$log[] = 'AvisoFranquiaReg'; |
|
|
$query = sprintf("insert into pbx_aviso_franquia_reg(contrato, data_aviso)values(%s,now());", QuotedStr($contrato)); |
|
|
if (!pg_query($query)) { |
|
|
GeraExcept(ErrorGetLast()); |
|
|
} |
|
|
return true; |
|
|
} catch (Exception $ex) { |
|
|
$log[] = sprintf("Erro ao registrar aviso de limite de franquia: %s Data: %s", $ex->getMessage(), date("Y-m-d H:i:s")); |
|
|
GravaLogApl($log, 'avisa_limite_franquia'); |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
function ExecStart($fileExec) |
|
|
{ |
|
|
if (file_exists($fileExec)) { |
|
|
exit; |
|
|
} |
|
|
|
|
|
/* |
|
|
* Cria o arquivo caso ele n<EFBFBD>o exista. |
|
|
*/ |
|
|
$arq = fopen($fileExec, 'w'); |
|
|
fclose($arq); |
|
|
} |
|
|
|
|
|
function ExecEnd($fileExec, $exit = true) |
|
|
{ |
|
|
unlink($fileExec); |
|
|
if ($exit) { |
|
|
exit; |
|
|
} |
|
|
} |
|
|
|
|
|
function CompressFile($origem, $dirDestino = '', $nomeDestino = '') |
|
|
{ |
|
|
/* |
|
|
* Diretorio de origem. |
|
|
*/ |
|
|
$dirOrigem = SetEndChar(pathinfo($origem, PATHINFO_DIRNAME)); |
|
|
|
|
|
/* |
|
|
* Nome do arquivo sem extensao. |
|
|
*/ |
|
|
$nome = pathinfo($origem, PATHINFO_FILENAME); |
|
|
|
|
|
/* |
|
|
* Nome do aquivo com extensao. |
|
|
*/ |
|
|
$nomeOrigem = pathinfo($origem, PATHINFO_BASENAME); |
|
|
|
|
|
/* |
|
|
* Se passao um diretorio para o destino o usa, se nao, usa o diretorio de origem. |
|
|
*/ |
|
|
$dirDestino = SetEndChar($dirDestino ? $dirDestino : $dirOrigem); |
|
|
|
|
|
/* |
|
|
* Se nao for passado um nome para o arquivo de destino usao o nome de origem com a extensao tar.gz |
|
|
*/ |
|
|
$nomeDestino = $nomeDestino ? $nomeDestino : $nome . ".tar.gz"; |
|
|
|
|
|
/* |
|
|
* Monta comando para compactar o arquivo. |
|
|
*/ |
|
|
$cmd = sprintf(" tar czvf %s%s -C %s %s 2>/dev/null", $dirDestino, $nomeDestino, $dirOrigem, $nomeOrigem); |
|
|
system($cmd, $result); |
|
|
|
|
|
/* |
|
|
* Certifica que o arquivo foi criado com sucesso. |
|
|
*/ |
|
|
return file_exists($dirDestino . $nomeDestino); |
|
|
} |
|
|
|
|
|
function UcompressFile($origem, $arqDestino, $destino = './') |
|
|
{ |
|
|
$result = true; |
|
|
$cmd = sprintf("tar -xzvf %s -C %s", $origem, $destino); |
|
|
//$cmd = sprintf("tar -xzf %s -C %s 2>/dev/null", $origem, $destino); |
|
|
system($cmd, $result); |
|
|
|
|
|
return file_exists($arqDestino); |
|
|
/* |
|
|
* Certifica que o arquivo foi criado com sucesso. |
|
|
*/ |
|
|
//return file_exists(destino); |
|
|
} |
|
|
|
|
|
function GetEndChar($str) |
|
|
{ |
|
|
return substr($str, -1); |
|
|
} |
|
|
|
|
|
function SetEndChar($str, $end = '/') |
|
|
{ |
|
|
return GetEndChar($str) === $end ? $str : ($str . $end); |
|
|
} |
|
|
|
|
|
function GetAlernativeDB($hostDb = '', $portDb = '', $nameDb = '', $userDb = '', $passDb = '') |
|
|
{ |
|
|
include "configBd.php"; |
|
|
$portDb = $portDb ? $dbPort : $dbPort; |
|
|
$hostDb = $hostDb ? $hostDb : $dbHost; |
|
|
$nameDb = $nameDb ? $nameDb : $dbName; |
|
|
$userDb = $userDb ? $userDb : $dbUser; |
|
|
$passDb = $passDb ? $passDb : $dbPassword; |
|
|
|
|
|
$str = "host='$hostDb' port='$portDb' dbname='$nameDb' user='$userDb' password='$passDb'"; |
|
|
|
|
|
return @pg_connect($str, PGSQL_CONNECT_FORCE_NEW); |
|
|
} |
|
|
|
|
|
function FileNumberLines($filename) |
|
|
{ |
|
|
if (!file_exists($filename)) |
|
|
return false; |
|
|
$outShell = trim(shell_exec("wc -l $filename")); |
|
|
if ($outShell) { |
|
|
$outShellAr = explode(' ', $outShell); |
|
|
$outShell = trim($outShellAr[0]); |
|
|
return $outShell; |
|
|
} |
|
|
return -1; |
|
|
} |
|
|
|
|
|
function DisplayDebub($msg) |
|
|
{ |
|
|
global $debug; |
|
|
|
|
|
if ($debug) { |
|
|
echo $msg; |
|
|
} |
|
|
} |
|
|
|
|
|
function GetOperNumero($numero) |
|
|
{ |
|
|
|
|
|
$numero = substr($numero, -11); |
|
|
$prefixo = substr($numero, 0, -4); |
|
|
$sufixo = substr($numero, -4); |
|
|
|
|
|
$query = "select spid from prefixos where prefixo = '$prefixo' and ini <= '$sufixo' and fim >= '$sufixo'"; |
|
|
$result = pg_query($query); |
|
|
if (!$result || !pg_num_rows($result)) { |
|
|
return 00; |
|
|
} |
|
|
|
|
|
$row = pg_fetch_row($result); |
|
|
return $row[0]; |
|
|
|
|
|
/* |
|
|
* funcao modificada para usar o cadup. |
|
|
*/ |
|
|
$sercontel = 343; |
|
|
$oi = 314; |
|
|
$vivo = 320; |
|
|
$claro = 321; |
|
|
$tim = 341; |
|
|
$telemig = 323; |
|
|
$amcel = 324; |
|
|
$tnl = 331; |
|
|
$unicel = 337; |
|
|
$nextel = 377; |
|
|
|
|
|
$numero = substr($numero, -11); |
|
|
$ddd = substr($numero, 0, 2); |
|
|
$num8 = substr($numero, -8); |
|
|
$iniCel = substr($num8, 0, 2); |
|
|
|
|
|
|
|
|
if (($ddd >= 21) && ($ddd <= 28)) { |
|
|
if (($iniCel >= 96) && ($iniCel <= 99)) { |
|
|
return $vivo; |
|
|
} else if (($iniCel >= 91) && ($iniCel <= 94)) { |
|
|
return $claro; |
|
|
} else if (($iniCel >= 87) && ($iniCel <= 88)) { |
|
|
return $oi; |
|
|
} else if (($iniCel >= 80) && ($iniCel <= 83)) { |
|
|
return $tim; |
|
|
} |
|
|
} else if (($ddd >= 91) && ($ddd <= 99)) { |
|
|
if (($iniCel >= 96) && ($iniCel <= 99)) { |
|
|
return $amcel; |
|
|
} else if (($iniCel >= 91) && ($iniCel <= 94)) { |
|
|
return $vivo; |
|
|
} else if (($iniCel >= 87) && ($iniCel <= 88)) { |
|
|
return $oi; |
|
|
} else if (($iniCel >= 80) && ($iniCel <= 83)) { |
|
|
return $tim; |
|
|
} |
|
|
} else if (($ddd >= 31) && ($ddd <= 38)) { |
|
|
if (($iniCel >= 96) && ($iniCel <= 99)) { |
|
|
return $telemig; |
|
|
} else if (($iniCel >= 91) && ($iniCel <= 94)) { |
|
|
return $tim; |
|
|
} else if (($iniCel >= 87) && ($iniCel <= 88)) { |
|
|
return $oi; |
|
|
} else if (($iniCel >= 81) && ($iniCel <= 84)) { |
|
|
return $claro; |
|
|
} |
|
|
} else if (($ddd >= 71) && ($ddd <= 79)) { |
|
|
if (($iniCel >= 96) && ($iniCel <= 99)) { |
|
|
return $vivo; |
|
|
} else if (($iniCel >= 91) && ($iniCel <= 94)) { |
|
|
return $tim; |
|
|
} else if (($iniCel >= 87) && ($iniCel <= 88)) { |
|
|
return $oi; |
|
|
} else if (($iniCel >= 81) && ($iniCel <= 83)) { |
|
|
return $claro; |
|
|
} |
|
|
} else if (($ddd >= 81) && ($ddd <= 89)) { |
|
|
if (($iniCel >= 96) && ($iniCel <= 99)) { |
|
|
return $tim; |
|
|
} else if (($iniCel >= 91) && ($iniCel <= 94)) { |
|
|
return $claro; |
|
|
} else if (($iniCel >= 87) && ($iniCel <= 88)) { |
|
|
return $oi; |
|
|
} else if (($iniCel >= 80) && ($iniCel <= 89)) { |
|
|
return $vivo; |
|
|
} |
|
|
} else if (($ddd >= 41) && ($ddd <= 49)) { |
|
|
if (($iniCel >= 96) && ($iniCel <= 99)) { |
|
|
return $tim; |
|
|
} else if (($iniCel >= 91) && ($iniCel <= 94)) { |
|
|
return $vivo; |
|
|
} else if (($iniCel >= 87) && ($iniCel <= 88)) { |
|
|
return $claro; |
|
|
} else if (($iniCel >= 84) && ($iniCel <= 85)) { |
|
|
return $oi; |
|
|
} |
|
|
} else if (($ddd >= 51) && ($ddd <= 55)) { |
|
|
if (($iniCel >= 96) && ($iniCel <= 99)) { |
|
|
return $vivo; |
|
|
} else if (($iniCel >= 91) && ($iniCel <= 94)) { |
|
|
return $claro; |
|
|
} else if (($iniCel >= 81) && ($iniCel <= 82)) { |
|
|
return $tim; |
|
|
} else if (($iniCel >= 84) && ($iniCel <= 85)) { |
|
|
return $oi; |
|
|
} |
|
|
} else if (($ddd >= 61) && ($ddd <= 69)) { |
|
|
if (($iniCel >= 96) && ($iniCel <= 99)) { |
|
|
return $vivo; |
|
|
} else if (($iniCel >= 91) && ($iniCel <= 94)) { |
|
|
return $claro; |
|
|
} else if (($iniCel >= 81) && ($iniCel <= 82)) { |
|
|
return $tim; |
|
|
} else if (($iniCel >= 84) && ($iniCel <= 85)) { |
|
|
return $oi; |
|
|
} |
|
|
} else if (($ddd >= 11) && ($ddd <= 19)) { |
|
|
if (($iniCel >= 96) && ($iniCel <= 99)) { |
|
|
return $vivo; |
|
|
} else if (($iniCel >= 91) && ($iniCel <= 94)) { |
|
|
return $claro; |
|
|
} else if (($iniCel >= 81) && ($iniCel <= 87)) { |
|
|
return $tim; |
|
|
} else if (($iniCel >= 80) && ($iniCel <= 89)) { |
|
|
return $oi; |
|
|
} else if (($iniCel >= 71) && ($iniCel <= 74)) { |
|
|
return $vivo; |
|
|
} |
|
|
} |
|
|
|
|
|
return 00; |
|
|
//stado (DDD) Banda A (96 a 99) Banda B (91 a 94) Banda D (8) Banda E (8) |
|
|
} |
|
|
|
|
|
function IncluiDDD($numero) |
|
|
{ |
|
|
$num = ltrim(soNumero($numero), '0'); |
|
|
if ((strlen($num) >= 8) && (strlen($num) <= 9)) { |
|
|
return GetDddPadrao($num); |
|
|
} |
|
|
|
|
|
return $numero; |
|
|
} |
|
|
|
|
|
function RmPadraoInternacional($numero) |
|
|
{ |
|
|
|
|
|
if (substr($numero, 0, 3) == '+55') { |
|
|
return substr($numero, 3); |
|
|
} |
|
|
return $numero; |
|
|
} |
|
|
|
|
|
function RemovePontoExt($arquivo) |
|
|
{ |
|
|
$tam = strlen($arquivo); |
|
|
$ponto = 0; |
|
|
$str = ''; |
|
|
for ($i = ($tam - 1); $i >= 0; $i--) { |
|
|
$str .= (substr($arquivo, $i, 1) == '.') && ($ponto++ > 0) ? '' : substr($arquivo, $i, 1); |
|
|
} |
|
|
|
|
|
return strrev($str); |
|
|
} |
|
|
|
|
|
function ConvertSize($bytes) |
|
|
{ |
|
|
$b = ($bytes / 1073741824.0); |
|
|
if ($b >= 1) |
|
|
return round($b) . "TB"; |
|
|
$b = ($bytes / 1048576.0); |
|
|
if ($b >= 1) |
|
|
return round($b) . "MB"; |
|
|
$b = ($bytes / 1024.0); |
|
|
if ($b >= 1) |
|
|
return round($b) . "kB"; |
|
|
|
|
|
return $bytes . "B"; |
|
|
} |
|
|
|
|
|
function CreateDir($path, $modo = 0777, $recursive = true) |
|
|
{ |
|
|
if (file_exists($path)) |
|
|
return true; |
|
|
|
|
|
return mkdir($path, $modo, $recursive); |
|
|
} |
|
|
|
|
|
function GetLocalIP() |
|
|
{ |
|
|
if (isset($_SERVER["SERVER_ADDR"])) { |
|
|
return $_SERVER["SERVER_ADDR"]; |
|
|
} |
|
|
|
|
|
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); |
|
|
socket_connect($sock, "8.8.8.8", 53); |
|
|
socket_getsockname($sock, $name); // $name passed by reference |
|
|
return $name; |
|
|
} |
|
|
|
|
|
function CorrigeAbandonTransbordo($dbcon) |
|
|
{ |
|
|
|
|
|
$path = '/var/log/asterisk/corrige_abandon_transbordo.log'; |
|
|
|
|
|
$query = "-- Procura todas os transbordos que foram gerados pelo asterisk. EXITWITHTIMEOUT |
|
|
drop table if exists transbordo_saida; |
|
|
create temporary table transbordo_saida as |
|
|
select distinct a.fila, a.uniqueid, a.trbd_origem_destino as fila_destino |
|
|
from pbx_eventos_transbordo a, ast_eventos_dacs b |
|
|
where b.fila = a.trbd_origem_destino |
|
|
and b.uid2 = a.uniqueid |
|
|
and a.data_reg::date = now()::date |
|
|
and a.trbd_aplicacao = 'EXITWITHTIMEOUT' |
|
|
and a.trbd_origem_destino_tipo = 'filas' |
|
|
and trbd_tipo = 'S'; |
|
|
|
|
|
-- Insere o evento TRANSBORDANDO na fila que a chamdada saiu. |
|
|
insert into ast_eventos_dacs(uid1,uid2,fila,evento) |
|
|
select trunc(uniqueid::numeric),uniqueid,fila, 'TRANSBORDANDO' as evento from transbordo_saida a where not exists(select '' from ast_eventos_dacs where fila = a.fila and uid2 = a.uniqueid and evento = 'TRANSBORDANDO'); |
|
|
|
|
|
|
|
|
-- Insere o evento TRANSBORDADO na fila que a chamdada entrou(Destino do Transbordo). EXITWITHTIMEOUT faz transbordo mas n<EFBFBD>o insere o evento na fila de destino. |
|
|
insert into ast_eventos_dacs(uid1,uid2,fila,evento) |
|
|
select trunc(uniqueid::numeric),uniqueid,fila_destino, 'TRANSBORDADO' as evento from transbordo_saida a where not exists(select '' from ast_eventos_dacs where fila = a.fila_destino and uid2 = a.uniqueid and evento = 'TRANSBORDADO'); |
|
|
|
|
|
|
|
|
-- Procura todas os transbordos que foram gerados de forma assistida pela aplicacao. |
|
|
drop table if exists transbordo_saida; |
|
|
create temporary table transbordo_saida as |
|
|
select distinct a.fila, a.uniqueid, a.trbd_origem_destino as fila_destino |
|
|
from pbx_eventos_transbordo a, ast_eventos_dacs b |
|
|
where b.fila = a.trbd_origem_destino |
|
|
and b.uid2 = a.uniqueid |
|
|
and a.data_reg::date = now()::date |
|
|
and a.trbd_aplicacao <> 'EXITWITHTIMEOUT' |
|
|
and a.trbd_origem_destino_tipo = 'filas' |
|
|
and trbd_tipo = 'S'; |
|
|
|
|
|
-- Todas as chamadas transbordadas pelo transbordo assistido gera um evento abandon que precisa ser removido. |
|
|
delete from ast_eventos_dacs a |
|
|
where exists(select '' from transbordo_saida where uniqueid = a.uid2 and fila = a.fila) |
|
|
and a.evento = 'ABANDON'; |
|
|
|
|
|
-- Insere o evento TRANSBORDANDO na fila que a chamdada saiu caso nao exista. |
|
|
insert into ast_eventos_dacs(uid1,uid2,fila,evento) |
|
|
select trunc(uniqueid::numeric),uniqueid,fila, 'TRANSBORDANDO' as evento from transbordo_saida a where not exists(select '' from ast_eventos_dacs where fila = a.fila and uid2 = a.uniqueid and evento = 'TRANSBORDANDO'); |
|
|
|
|
|
|
|
|
-- Insere o evento TRANSBORDADO na fila que a chamdada entrou(Destino do Transbordo) caso nao exista. EXITWITHTIMEOUT faz transbordo mas n<EFBFBD>o insere o evento na fila de destino. |
|
|
insert into ast_eventos_dacs(uid1,uid2,fila,evento) |
|
|
select trunc(uniqueid::numeric),uniqueid,fila_destino, 'TRANSBORDADO' as evento from transbordo_saida a where not exists(select '' from ast_eventos_dacs where fila = a.fila_destino and uid2 = a.uniqueid and evento = 'TRANSBORDADO'); |
|
|
|
|
|
|
|
|
--Procura todos os transbordo que foram gerados para um dispositivo diferente de uma fila. |
|
|
drop table if exists transbordo_saida; |
|
|
create temporary table transbordo_saida as |
|
|
select distinct a.fila, a.uniqueid |
|
|
from pbx_eventos_transbordo a |
|
|
where a.data_reg::date = now()::date |
|
|
and a.trbd_origem_destino_tipo <> 'filas' |
|
|
and trbd_tipo = 'S'; |
|
|
|
|
|
|
|
|
-- Todas as chamadas transbordadas pelo transbordo assistido gera um evento abandon que precisa ser removido. |
|
|
delete from ast_eventos_dacs a |
|
|
where exists(select '' from transbordo_saida where uniqueid = a.uid2 and fila = a.fila) |
|
|
and a.evento = 'ABANDON'; |
|
|
|
|
|
-- Insere o evento transbordando caso o mesmo nao exista na fila de origem. |
|
|
insert into ast_eventos_dacs(uid1,uid2,fila,evento) |
|
|
select trunc(uniqueid::numeric),uniqueid,fila, 'TRANSBORDANDO' as evento from transbordo_saida a where not exists(select '' from ast_eventos_dacs where fila = a.fila and uid2 = a.uniqueid and evento = 'TRANSBORDANDO'); |
|
|
|
|
|
|
|
|
-- Apaga o evento \"EXITWITHTIMEOUT\" gerado pelo transbordo nativo. |
|
|
delete from ast_eventos_dacs b using ast_bilhetes a where b.uid2 = a.uniqueid and a.calldate::date = now()::date and b.evento = 'EXITWITHTIMEOUT';"; |
|
|
|
|
|
try { |
|
|
|
|
|
BeginTran($dbcon); |
|
|
|
|
|
if (!pg_query($query)) { |
|
|
RaiseExcept("Erro ao corrigir transbordo por timeout!", true); |
|
|
} |
|
|
|
|
|
CommitTran($dbcon); |
|
|
} catch (Exception $ex) { |
|
|
WriteLog($ex->getMessage(), $path); |
|
|
RollbackTran($dbcon); |
|
|
} |
|
|
} |
|
|
|
|
|
function LimpaAbandonadas($dbcon) |
|
|
{ |
|
|
|
|
|
$path = '/var/log/asterisk/limpa_abandonadas.log'; |
|
|
$query = "delete from pbx_abandonadas_semretorno where abdsr_data_hora_inicio < (now() - (interval '120 second' )) and abdsr_uniqueid not in(select uid2 from ast_eventos_dacs where evento = 'ABANDON');"; |
|
|
|
|
|
try { |
|
|
if (!pg_query($query)) { |
|
|
RaiseExcept("Erro ao corrigir transbordo por timeout!", true); |
|
|
} |
|
|
} catch (Exception $ex) { |
|
|
WriteLog($ex->getMessage(), $path); |
|
|
} |
|
|
} |
|
|
|
|
|
function FechaPendenciaDiscador() |
|
|
{ |
|
|
$path = '/var/log/asterisk/fecha_pendencia_discador.log'; |
|
|
$query = "update pbx_campanha_operacao |
|
|
set cmpo_status = 1 |
|
|
where cmpo_status = 2 |
|
|
and (matricula not in(select matricula from pbx_supervisor_agentes) |
|
|
and matricula not in(select b.matricula as num_reg |
|
|
from pbx_campanha_contato_fone a, pbx_campanha_operacao b |
|
|
where b.cont_id = a.cont_id |
|
|
and b.cmpo_status in(0,2) |
|
|
and a.conf_discado = 1 |
|
|
and a.conf_status = '0'))"; |
|
|
$result = pg_query($query); |
|
|
if (!$result) { |
|
|
$log = GetLasterror(); |
|
|
WriteLog($log, $path); |
|
|
} |
|
|
} |
|
|
|
|
|
function ApagaBilheteDuplTransfer($dbcon) |
|
|
{ |
|
|
/* |
|
|
* Esta funcao apaga bilhetes que estao duplicatos na transferencia. |
|
|
*/ |
|
|
$path = '/var/log/asterisk/apaga_bilhetes_transfer.log'; |
|
|
|
|
|
$query = "delete from ast_bilhetes a where rtrim(disposition) in('NO ANSWER', 'BUSY', 'FAILED') and exists(select '' from ast_bilhetes where uniqueid = a.uniqueid and rtrim(disposition) = 'ANSWERED');"; |
|
|
|
|
|
if (!pg_query($dbcon, $query)) { |
|
|
$log = sprintf("Data: %s Cmd: Erro: %s\n", date('Y-m-d H:i:s'), $query, GetLasterror()); |
|
|
WriteLog($log, $path); |
|
|
} |
|
|
|
|
|
$query = "drop table if exists bilhetes_dupl; |
|
|
create table bilhetes_dupl as |
|
|
select uniqueid, min(sequence) as sequence from ast_bilhetes where calldate::date = now()::date group by uniqueid having count(*) > 1; |
|
|
delete from ast_bilhetes a using bilhetes_dupl b where b.uniqueid = a.uniqueid and a.sequence not in(select sequence from bilhetes_dupl);"; |
|
|
|
|
|
if (!pg_query($dbcon, $query)) { |
|
|
$log = sprintf("Data: %s Cmd: Erro: %s\n", date('Y-m-d H:i:s'), $query, GetLasterror()); |
|
|
WriteLog($log, $path); |
|
|
} |
|
|
} |
|
|
|
|
|
function PixelToMM($pixelPerInch, $pixelSize) |
|
|
{ |
|
|
|
|
|
$POLEGADA_MM = 25.4; |
|
|
|
|
|
try { |
|
|
//(1024 / 300) * 2,5 = 8,5 cm |
|
|
return round((($pixelSize / $pixelPerInch) * $POLEGADA_MM)); |
|
|
} catch (Exception $e) { |
|
|
return -1; |
|
|
} |
|
|
} |
|
|
|
|
|
function MMToPixex($pixelPerInch, $mmSize) |
|
|
{ |
|
|
$POLEGADA_MM = 25.4; |
|
|
|
|
|
try { |
|
|
// (29,7 * 300) / 2,5 = 3.564 px |
|
|
return trunc(($mmSize * $pixelPerInch) / $POLEGADA_MM); |
|
|
} catch (Exception $e) { |
|
|
return -1; |
|
|
} |
|
|
} |
|
|
|
|
|
function trunc($value) |
|
|
{ |
|
|
return floor(abs($value)); |
|
|
} |
|
|
|
|
|
function GetArHour($isLabel = false) |
|
|
{ |
|
|
$ar = array(); |
|
|
for ($i = 0; $i < 24; $i++) |
|
|
$ar[$i] = $isLabel ? $i : 0; |
|
|
return $ar; |
|
|
} |
|
|
|
|
|
function GetArrayAssoc($ar) |
|
|
{ |
|
|
$arRet = array(); |
|
|
foreach ($ar as $key => $value) { |
|
|
if (!is_numeric($key)) { |
|
|
$arRet[$key] = $value; |
|
|
} |
|
|
} |
|
|
|
|
|
return $arRet; |
|
|
} |
|
|
|
|
|
function GetArrayIndex($ar) |
|
|
{ |
|
|
$arRet = array(); |
|
|
foreach ($ar as $key => $value) { |
|
|
if (is_numeric($key)) { |
|
|
$arRet[$key] = $value; |
|
|
} |
|
|
} |
|
|
|
|
|
return $arRet; |
|
|
} |
|
|
|
|
|
function EncodeVar($params) |
|
|
{ |
|
|
return base64_encode(serialize($params)); |
|
|
} |
|
|
|
|
|
function DecodeVar($params) |
|
|
{ |
|
|
return unserialize(base64_decode($params)); |
|
|
} |
|
|
|
|
|
function GetParamLgpd($param) |
|
|
{ |
|
|
if (!$param || !is_numeric($param)) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
$query = "select lgpdm_matricula_supervisor, lgpdm_matricula_monitorado, lgpdm_content from pbx_lgpd_monitora where lgpdm_id = '{$param}'"; |
|
|
$result = pg_query($query); |
|
|
if ($result && pg_num_rows($result)) { |
|
|
$dados = pg_fetch_array($result, null, PGSQL_ASSOC); |
|
|
return array("lgpdm_matricula_supervisor" => $dados["lgpdm_matricula_supervisor"], "lgpdm_matricula_monitorado" => $dados["lgpdm_matricula_monitorado"], "lgpdm_content" => DecodeVar($dados["lgpdm_content"])); |
|
|
} |
|
|
|
|
|
return false; |
|
|
} |
|
|
|
|
|
function GetDiasAbandonada($conn = null) |
|
|
{ |
|
|
$query = "select prm_abandonada_semretorno from pbx_parametros"; |
|
|
$result = $conn ? pg_query($conn, $query) : pg_query($query); |
|
|
if (!$result || !pg_num_rows($result)) { |
|
|
return 0; |
|
|
} |
|
|
$data = pg_fetch_row($result); |
|
|
|
|
|
return $data[0]; |
|
|
} |
|
|
|
|
|
function GetFilePath($arq = '') |
|
|
{ |
|
|
return $arq ? (dirname($arq) . '/') : (dirname(__FILE__) . '/'); |
|
|
} |
|
|
|
|
|
/** |
|
|
* Converte um timestamp do banco de dados para um formato humanizado de data e hora |
|
|
* @param string $timestamp |
|
|
* @param string $show Tipo do retorno: <ul><li><b>DT (default)</b> = 01/01/2000 23:59:59</li><li>D = 01/01/2000</li><li>T/H = 23:59:59</li></ul> |
|
|
* |
|
|
* @return null|string |
|
|
*/ |
|
|
function ParseDbTimestamp($timestamp, $show = 'DT') |
|
|
{ |
|
|
|
|
|
if (!isset($timestamp)) { |
|
|
return null; |
|
|
} |
|
|
$show = strtoupper($show); |
|
|
$data = FormataDBDataHora(substr($timestamp, 0, 10)); |
|
|
$data = trim($data); |
|
|
$hora = substr($timestamp, 10, 9); |
|
|
$hora = trim($hora); |
|
|
$return = null; |
|
|
switch ($show) { |
|
|
case 'DT': |
|
|
$return = "{$data} {$hora}"; |
|
|
break; |
|
|
case 'D': |
|
|
$return = $data; |
|
|
break; |
|
|
case 'T': |
|
|
case 'H': |
|
|
$return = $hora; |
|
|
break; |
|
|
} |
|
|
return $return; |
|
|
} |
|
|
|
|
|
function insert_padrao($conexao, $uniqueid, $direcao, $destino, $conta = 'null', $id_usuario = 'null', $agente = 'null', $dac = 'null') |
|
|
{ |
|
|
/* |
|
|
* Verifica se a direcao ainda nao foi gravada para o uniqueid, para evitar duplicidade. |
|
|
*/ |
|
|
$query = sprintf("select '' from ast_bilhetes_complemento where uniqueid2 = '%s' and direcao = '%s' limit 1", $uniqueid, $direcao); |
|
|
$result = pg_query($conexao, $query); |
|
|
|
|
|
if (!pg_num_rows($result)) { |
|
|
$query = "insert into ast_bilhetes_complemento (uniqueid2,direcao,destino,conta,id_usuario,agente,dac) values (%s,%s,%s,%s,%s,%s,%s)"; |
|
|
$query = sprintf( |
|
|
$query, |
|
|
get_quote($uniqueid), |
|
|
get_quote($direcao), |
|
|
get_quote($destino), |
|
|
get_quote($conta), |
|
|
get_quote($id_usuario), |
|
|
get_quote($agente), |
|
|
get_quote($dac) |
|
|
); |
|
|
return pg_query($conexao, $query) ? true : false; |
|
|
} |
|
|
return true; |
|
|
} |
|
|
|
|
|
function get_quote($value) |
|
|
{ |
|
|
return ($value === 'null') ? $value : QuotedStr($value); |
|
|
} |
|
|
|
|
|
function TarifaChamada($tipoTarifa, $duracaoSegundos, $precoMinuto, $fator, $cadencia) |
|
|
{ |
|
|
/* |
|
|
* Cadencia esta relacionada com a maneira como <EFBFBD> tarifador o primeiro minuto. |
|
|
* ex.: |
|
|
* fator/Cad<EFBFBD>ncia |
|
|
* 30 + 6 |
|
|
* 1) Entre 3 a 30 segundos a chamada dever<EFBFBD> ser tarifada pela metade do valor, ou seja: Tarifa / 2. |
|
|
* 2) Entre 30 a 60 segundos a chamada dever<EFBFBD> ser cobrada conforme item 2 (Tarifa / 2) acrescida do valor da tarifa (Tarifa / 10) a cada 6 segundos. |
|
|
* 3) Acima de 60 segundos a chamada dever<EFBFBD> ser cobrada com o pre<EFBFBD>o cheio (60s = tarifa) e a acrescida do valor da tarifa (Tarifa / 10) a cada 6 segundos. |
|
|
*/ |
|
|
$MINUTO = 60; |
|
|
$operatorModule = true; |
|
|
/* |
|
|
* Tarifa<EFBFBD><EFBFBD>o tipo 2 tem o preco definido por chamada. |
|
|
*/ |
|
|
if ($tipoTarifa == 2) |
|
|
return round($precoMinuto, 2); |
|
|
|
|
|
/* |
|
|
* Chamadas <= 3 segundos n<EFBFBD>o ser<EFBFBD>o tarifadas. |
|
|
*/ |
|
|
if ($duracaoSegundos <= 3) |
|
|
return 0; |
|
|
|
|
|
$fatorCalculo = (int) Divide($MINUTO, $fator); |
|
|
$fatorCadencia = (int) Divide($MINUTO, $cadencia); |
|
|
|
|
|
if (($fatorCalculo == 1) && ($fatorCadencia == 1)) { |
|
|
/* |
|
|
* Tarifa<EFBFBD><EFBFBD>o cheia ou seja 61 segundos <EFBFBD> tarifado como 120 |
|
|
*/ |
|
|
$minutos = (int) Divide($duracaoSegundos, $MINUTO); |
|
|
$quebraMinuto = Divide($duracaoSegundos, $MINUTO, $operatorModule) ? 1 : 0; |
|
|
return round((($precoMinuto * $minutos) + ($precoMinuto * $quebraMinuto)), 2); |
|
|
} else if (($duracaoSegundos) <= Divide($MINUTO, $fatorCalculo)) { |
|
|
/* |
|
|
* Aqui ser<EFBFBD> tarifado por exemplo chamadas entre 3 e 30 segundos quando |
|
|
* cadencia 30+6 ou entre 3 e 60 quando cadencia 60+6 |
|
|
*/ |
|
|
return round(Divide($precoMinuto, $fatorCalculo), 2); |
|
|
} else if ($duracaoSegundos < $MINUTO) { |
|
|
/* |
|
|
* Aqui sera tarifado chamada que estiver entre 31 e 59 segundos |
|
|
* quando cadencia 30+6 |
|
|
*/ |
|
|
$duracaoCadencia = $duracaoSegundos - Divide($MINUTO, $fatorCalculo); |
|
|
$precoCadencia = Divide($precoMinuto, $fatorCalculo); |
|
|
$resto = Divide($duracaoCadencia, $cadencia, $operatorModule); |
|
|
$numCadencia = (int) Divide($duracaoCadencia, $cadencia) + ($resto ? 1 : 0); |
|
|
$valorCadencia = Divide($precoMinuto, $fatorCadencia); |
|
|
return round(($precoCadencia + ($numCadencia * $valorCadencia)), 2); |
|
|
} else { |
|
|
/* |
|
|
* Chamada acima de um minuto. |
|
|
*/ |
|
|
$minutos = (int) Divide($duracaoSegundos, $MINUTO); |
|
|
$segundosCandencia = Divide($duracaoSegundos, $MINUTO, $operatorModule); |
|
|
$numCadencia = (int) Divide($segundosCandencia, $cadencia) + (Divide($segundosCandencia, $cadencia, $operatorModule) ? 1 : 0); |
|
|
$valorCadencia = Divide($precoMinuto, $fatorCadencia); |
|
|
return round((($precoMinuto * $minutos) + ($valorCadencia * $numCadencia)), 2); |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Esta fun<EFBFBD><EFBFBD>o <EFBFBD> utilizada para verificar se o dividendo ou o divisor <EFBFBD> igual a ZERO antes de realizar a divis<EFBFBD>o. |
|
|
*/ |
|
|
function Divide($dividend, $divider, $operator = false) |
|
|
{ |
|
|
if ($dividend && $divider) { |
|
|
return ($operator ? $dividend % $divider : $dividend / $divider); |
|
|
} |
|
|
return 0; |
|
|
} |
|
|
|
|
|
function SaveVarToFile($var, $fileName) |
|
|
{ |
|
|
return file_put_contents($fileName, serialize($var)); |
|
|
} |
|
|
|
|
|
function ReadVarFile($fileName) |
|
|
{ |
|
|
return file_exists($fileName) ? unserialize(file_get_contents($fileName)) : false; |
|
|
} |
|
|
|
|
|
function GenerateCsvFromArray($data, $delimiter = ',', $enclosure = '"') |
|
|
{ |
|
|
$fh = fopen('php://memory', 'rw'); |
|
|
fputcsv($fh, $data, $delimiter, $enclosure); |
|
|
|
|
|
rewind($fh); |
|
|
$contents = stream_get_contents($fh); |
|
|
fclose($fh); |
|
|
return $contents; |
|
|
} |
|
|
|
|
|
function GetProto($db, $uniqueId, $protoParceiro = '') |
|
|
{ |
|
|
try { |
|
|
$query = "select prm_agente_proto, prm_use_proto_parceiro from pbx_parametros where id = 1"; |
|
|
$result = pg_query($db, $query); |
|
|
if (!$result || !pg_num_rows($result)) { |
|
|
GeraExcept("N<EFBFBD>o foi poss<EFBFBD>vel consultar os parametros do sistema!"); |
|
|
} |
|
|
|
|
|
$row = pg_fetch_row($result); |
|
|
$useProtocolo = $row[0]; |
|
|
$useProtoParceiro = $row[1]; |
|
|
|
|
|
if (!$useProtocolo) { |
|
|
return '99'; |
|
|
} |
|
|
|
|
|
/* |
|
|
* Verifica se o protocolo j<EFBFBD> existe protocolo |
|
|
*/ |
|
|
$anoAtu = date('Y'); |
|
|
$query = " select ano::text || '-' || lpad(numproto::text,6,'0') as protocolo, protoparceiro from pbx_protocolo_reg where uniqueid = '$uniqueId'"; |
|
|
$result = pg_query($db, $query); |
|
|
if (!$result) { |
|
|
GeraExcept("N<EFBFBD>o foi poss<EFBFBD>vel consultar protocolos existentes!"); |
|
|
} |
|
|
|
|
|
/* |
|
|
* Se o protocolo j<EFBFBD> foi geradao em uma URA ou antes de uma transferencia ou transbordo |
|
|
* devera permanecer com o mesmo numero, caso esteja habilitado para usar protocolo do |
|
|
* parceiro este <EFBFBD> retornado. |
|
|
*/ |
|
|
if (pg_num_rows($result)) { |
|
|
$row = pg_fetch_row($result); |
|
|
$numProto = $row[0]; |
|
|
$numProtoParceiro = trim($row[1]); |
|
|
|
|
|
if ($useProtoParceiro && $numProtoParceiro) { |
|
|
return $numProtoParceiro; |
|
|
} |
|
|
|
|
|
return $numProto; |
|
|
} |
|
|
|
|
|
/* |
|
|
* Gera um novo protocolo. |
|
|
*/ |
|
|
$protoParceiro = $useProtoParceiro ? trim($protoParceiro) : ''; |
|
|
$anoAtu = date('Y'); |
|
|
$query = "select max(numProto) from pbx_protocolo_reg where ano = '$anoAtu'"; |
|
|
$result = pg_query($db, $query); |
|
|
|
|
|
if ($result) { |
|
|
$row = pg_fetch_row($result); |
|
|
$numProto = $row[0] ? $row[0] + 1 : 1; |
|
|
|
|
|
$proto = $anoAtu . str_pad($numProto, 6, '0', STR_PAD_LEFT); |
|
|
$protoAgt = $anoAtu . '-' . str_pad($numProto, 6, '0', STR_PAD_LEFT); |
|
|
$protoParceiro = $protoParceiro && $useProtoParceiro ? QuotedStr($protoParceiro) : 'null'; |
|
|
|
|
|
//return $protoAgt; |
|
|
$query = "insert into pbx_protocolo_reg |
|
|
( uniqueid, ano, numProto, protocolo, protoparceiro) |
|
|
values('$uniqueId', '$anoAtu', '$numProto', '$proto', $protoParceiro)"; |
|
|
$result = pg_query($db, $query); |
|
|
|
|
|
if (!$result) { |
|
|
GeraExcept("N<EFBFBD>o foi poss<EFBFBD>vel registrar o protocolo!"); |
|
|
} |
|
|
return $protoParceiro !== 'null' ? $protoParceiro : $protoAgt; |
|
|
} |
|
|
} catch (Exception $exc) { |
|
|
$errodb = @pg_last_error($db); |
|
|
$log = sprintf("Data: %s Msg: %s Sys: %s Uid: %s\n;", date('Y-m-d H:i:s'), $exc->getMessage(), $errodb, $uniqueId); |
|
|
GravaLog($log, '/var/log/asterisk/gera_protocolo.log'); |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
function array_key_iexists($key, $ar) |
|
|
{ |
|
|
return array_key_exists(strtolower($key), array_change_key_case($ar)); |
|
|
} |
|
|
|
|
|
function VerificaClassificacao($db, $fila, $matricula, $ramal, $uniqueid, $classifica, $tipochamada) |
|
|
{ |
|
|
|
|
|
/* |
|
|
* Trata classifica<EFBFBD><EFBFBD>o |
|
|
* Verifica se a classifica<EFBFBD><EFBFBD>o esta ativa |
|
|
* Verifica se <EFBFBD> exigida a classifica<EFBFBD><EFBFBD>o |
|
|
*/ |
|
|
$query = "select a.prm_agente_classifica, b.exige_classificacao |
|
|
from pbx_parametros a, pbx_queues_grupos b |
|
|
where b.nome = '$fila' |
|
|
and a.id = 1 "; |
|
|
$result = pg_query($db, $query); |
|
|
$dados = pg_fetch_row($result); |
|
|
if ($dados[0] && $dados[1]) { |
|
|
|
|
|
if ($classifica == 0) { |
|
|
|
|
|
if ($tipochamada == 'ENTRANTE') { |
|
|
write("SET VARIABLE __CLASSIFICADA NAO"); |
|
|
read(); |
|
|
exit; |
|
|
} else if ($tipochamada == 'SAINTE') { |
|
|
write("EXEC Playback appsounds/chamada_nao_classificada"); |
|
|
read(); |
|
|
write("HANGUP"); |
|
|
read(); |
|
|
exit; |
|
|
} |
|
|
} |
|
|
|
|
|
/* |
|
|
* Atualiza o supervisor se a opera<EFBFBD><EFBFBD>o for bem sucedida coloca o agente em pausa |
|
|
*/ |
|
|
$query = "update pbx_supervisor_agentes set chamada_classificado = 0 where matricula = '$matricula' "; |
|
|
$result = pg_query($db, $query); |
|
|
if ($result && pg_affected_rows($result)) { |
|
|
/* |
|
|
* Registra a obrigatoriedade da classifica<EFBFBD><EFBFBD>o para o agente logado quando configurado. |
|
|
*/ |
|
|
$query = "insert into pbx_registra_classificacao(id_dac, matricula, rgc_entrada, uid, id_login, reg_proc)values((select id from pbx_dacs where nome = '$fila'), '$matricula', now(), '$uniqueid', (select max(id) from pbx_eventos_agentes where matricula = '$matricula' ), 'pbx_complemento.php')"; |
|
|
pg_query($db, $query); |
|
|
|
|
|
// write("EXEC PauseQueueMember |Agent/$matricula"); |
|
|
write("EXEC PauseQueueMember ,Local/$ramal@app-callcenter/n"); |
|
|
read(); |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
function GeraProtocolo($db, $uniqueid) |
|
|
{ |
|
|
|
|
|
/* |
|
|
* Fun<EFBFBD><EFBFBD>o retorna numero de Protocolo de Atendimento para o agente |
|
|
*/ |
|
|
$tentativa = 0; |
|
|
while (true) { |
|
|
$proto = @GetProto($db, $uniqueid); |
|
|
if ($proto == '99') { |
|
|
$proto = '0000-000000'; |
|
|
break; |
|
|
} |
|
|
|
|
|
if (!empty($proto) || $tentativa >= NUM_TENTATIVAS_GERA_PROTO) { |
|
|
break; |
|
|
} |
|
|
$tentativa++; |
|
|
} |
|
|
return $proto; |
|
|
} |
|
|
|
|
|
function IsPhp6() |
|
|
{ |
|
|
$versao = (int) soNumero(PHP_VERSION); |
|
|
return $versao >= 560; |
|
|
} |
|
|
|
|
|
function EchoLog($log) |
|
|
{ |
|
|
global $debugLocal; |
|
|
if (!$debugLocal) { |
|
|
return !isset($log) ? null : $log[0]; |
|
|
} |
|
|
|
|
|
if (!isset($log)) { |
|
|
echo sprintf("Valor: %s Data: %s\n", "Null", date("Y-m-d H:i:s")); |
|
|
return null; |
|
|
} |
|
|
|
|
|
|
|
|
foreach ($log as $key => $value) { |
|
|
if (!is_array($value)) { |
|
|
echo sprintf("Data: %s | %s:%s\n", date("Y-m-d H:i:s"), (is_numeric($key) ? "Valor" : $key), $value); |
|
|
} else { |
|
|
EchoLog($value); |
|
|
} |
|
|
} |
|
|
|
|
|
return $log[0]; |
|
|
} |
|
|
|
|
|
function Tar($origem, $destino, $type = "gz") |
|
|
{ |
|
|
switch ($type) { |
|
|
case "gz": |
|
|
$cmd = "czvf"; |
|
|
break; |
|
|
case "bz2": |
|
|
$cmd = "cjvf"; |
|
|
break; |
|
|
default: |
|
|
$cmd = "cvf"; |
|
|
break; |
|
|
} |
|
|
$result = true; |
|
|
$cmd = sprintf(" tar %s %s %s 2>/dev/null", $cmd, $destino, $origem); |
|
|
system($cmd, $result); |
|
|
|
|
|
/* |
|
|
* Certifica que o arquivo foi criado com sucesso. |
|
|
*/ |
|
|
if (!file_exists($destino)) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
return true; |
|
|
} |
|
|
|
|
|
function UnTar($origem, $destino, $type = "gz") |
|
|
{ |
|
|
switch ($type) { |
|
|
case "gz": |
|
|
$cmd = "xzvf"; |
|
|
break; |
|
|
case "bz2": |
|
|
$cmd = "xjvf"; |
|
|
break; |
|
|
default: |
|
|
$cmd = "xvf"; |
|
|
break; |
|
|
} |
|
|
$result = true; |
|
|
$cmd = sprintf("tar -%s %s -C %s 2>/dev/null", $cmd, $origem, $destino); |
|
|
|
|
|
system($cmd); |
|
|
|
|
|
/* |
|
|
* Certifica que o arquivo foi criado com sucesso. |
|
|
*/ |
|
|
return file_exists($destino); |
|
|
} |
|
|
|
|
|
function ReduzFile($file) |
|
|
{ |
|
|
$start = 0; |
|
|
$fileTemp = DIRETORIO_LOCAL . "expo_temp"; |
|
|
$handleTemp = fopen($fileTemp, "w"); |
|
|
$handle = fopen($file, "r"); |
|
|
while (!feof($handle)) { |
|
|
$bufer = trim(fgets($handle)); |
|
|
if ($start) { |
|
|
$data = explode(",", $bufer); |
|
|
$line = sprintf("%s,%s\n", $data[1], $data[3]); |
|
|
fwrite($handleTemp, $line); |
|
|
} |
|
|
$start = 1; |
|
|
} |
|
|
fclose($handleTemp); |
|
|
fclose($handle); |
|
|
|
|
|
if (!function_exists($fileTemp)) |
|
|
return false; |
|
|
return DeleteFile($file) and mv($fileTemp, $file); |
|
|
} |
|
|
|
|
|
function PartFile($fileName, $lines = 1000000, $prefix = 'exp') |
|
|
{ |
|
|
ReduzFile($fileName); |
|
|
$files = array(); |
|
|
$numberLines = FileNumberLines($fileName); |
|
|
if ($numberLines <= $lines) { |
|
|
return ($files[] = $fileName); |
|
|
} |
|
|
$numberFiles = intval($numberLines / $lines) + (intval($numberLines % $lines) ? 1 : 0); |
|
|
|
|
|
for ($i = 0; $i < $numberFiles; $i++) { |
|
|
$files[] = sprintf("%s%s", $prefix, str_pad($i, 2, '0', STR_PAD_LEFT)); |
|
|
} |
|
|
|
|
|
$dir = DIRETORIO_LOCAL; |
|
|
$cmd = "split -l $lines -d $fileName $dir$prefix"; |
|
|
@system($cmd); |
|
|
return $files; |
|
|
} |
|
|
|
|
|
function TruncFile($filename) |
|
|
{ |
|
|
$fp = fopen($filename); |
|
|
$result = ftruncate($fp, 0); |
|
|
fclose($fp); |
|
|
|
|
|
return $result; |
|
|
} |
|
|
|
|
|
function ListaNegraNaoPerturbe($conn) |
|
|
{ |
|
|
|
|
|
try { |
|
|
$query = "select '' from pbx_listanegra where nome = 'NAO PERTURBE'"; |
|
|
if (!$result = pg_query($conn, $query)) { |
|
|
GeraExcept("N<EFBFBD>o poss<EFBFBD>vel consultar a Lista Negra n<EFBFBD>o perturpe!"); |
|
|
} |
|
|
$result = pg_num_rows($result); |
|
|
|
|
|
if (!$result) { |
|
|
$query = "INSERT INTO pbx_listanegra (nome,numero,entrada,saida,opcao,acao) |
|
|
VALUES ('NAO PERTURBE','0','0','0','','')"; |
|
|
if (!pg_query($conn, $query)) { |
|
|
GeraExcept("N<EFBFBD>o foi poss<EFBFBD>vel inserir a lista!"); |
|
|
} |
|
|
} |
|
|
|
|
|
$query = "select id from pbx_listanegra where nome = 'NAO PERTURBE'"; |
|
|
$result = pg_query($conn, $query); |
|
|
$dados = pg_fetch_row($result); |
|
|
$idPai = $dados[0]; |
|
|
|
|
|
$query = "delete from pbx_listanegra where id_pai = '$idPai'"; |
|
|
$result = pg_query($conn, $query); |
|
|
|
|
|
$query = "insert into pbx_listanegra(numero, id_pai)" |
|
|
. "select numero, '$idPai' as id_pai from pbx_nao_perturbe"; |
|
|
|
|
|
if (!pg_query($conn, $query)) { |
|
|
GeraExcept("N<EFBFBD>o foi poss<EFBFBD>vel inserir n<EFBFBD>mero a nova lista!"); |
|
|
} |
|
|
return true; |
|
|
} catch (Exception $ex) { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/* |
|
|
* Funcoes auxiliares para banco de dados. |
|
|
*/ |
|
|
$transactionInit = false; |
|
|
|
|
|
function BeginTran($dbcon, $silent = false) |
|
|
{ |
|
|
global $transactionInit; |
|
|
if (!pg_query($dbcon, 'begin')) { |
|
|
return $silent ? true : GeraExcept('N<EFBFBD>o foi poss<EFBFBD>vel inciar a opera<EFBFBD><EFBFBD>o!'); |
|
|
} |
|
|
return ($transactionInit = true); |
|
|
} |
|
|
|
|
|
function CommitTran($dbcon, $silent = false) |
|
|
{ |
|
|
global $transactionInit; |
|
|
if ($transactionInit && !pg_query($dbcon, 'commit')) { |
|
|
return $silent ? true : GeraExcept('N<EFBFBD>o foi poss<EFBFBD>vel concluir a opera<EFBFBD><EFBFBD>o!'); |
|
|
} |
|
|
return true; |
|
|
} |
|
|
|
|
|
function RollbackTran($dbcon) |
|
|
{ |
|
|
global $transactionInit; |
|
|
if ($transactionInit && !pg_query($dbcon, 'rollback')) { |
|
|
return false; |
|
|
} |
|
|
return true; |
|
|
} |
|
|
|
|
|
function GetCurrVal($tableName) |
|
|
{ |
|
|
$query = "select replace(column_default, 'nextval', 'currval' ) as seq_name |
|
|
from information_schema.columns |
|
|
where table_name = '$tableName' |
|
|
and column_default like '%nextval%'"; |
|
|
|
|
|
$result = pg_query($query); |
|
|
/* |
|
|
* Procura a sequencia pelo nome da tabela |
|
|
* caso tenha algum problema retorna false. |
|
|
*/ |
|
|
if (!$result || !pg_num_rows($result)) |
|
|
return false; |
|
|
|
|
|
$row = pg_fetch_row($result); |
|
|
$seqName = $row[0]; |
|
|
$query = "select $seqName "; |
|
|
$result = pg_query($query); |
|
|
|
|
|
if (!$result) |
|
|
return false; |
|
|
|
|
|
$row = pg_fetch_row($result); |
|
|
$seq = $row[0]; |
|
|
return StrToIntDef($seq, 0) > 0 ? ((int) $seq) : false; |
|
|
} |
|
|
|
|
|
function GetFilaFromNumero($conn, $numeroFila) |
|
|
{ |
|
|
$query = "select nome from pbx_queues_grupos where numero = '{$numeroFila}'"; |
|
|
|
|
|
$result = pg_query($conn, $query); |
|
|
/* |
|
|
* Procura a sequencia pelo nome da tabela |
|
|
* caso tenha algum problema retorna false. |
|
|
*/ |
|
|
if (!$result || !pg_num_rows($result)) |
|
|
return $numeroFila; |
|
|
|
|
|
return pg_fetch_row($result)[0]; |
|
|
} |
|
|
|
|
|
function GetDbField($result, $idxField = 0) |
|
|
{ |
|
|
/* |
|
|
* Retorna o campo pelo indice passado. |
|
|
*/ |
|
|
if (!$f = pg_fetch_row($result)) { |
|
|
return false; |
|
|
} |
|
|
return $f[$idxField]; |
|
|
} |
|
|
|
|
|
function GetDbFields($result, $assoc = 1, $idx = '') |
|
|
{ |
|
|
|
|
|
if ($assoc) { |
|
|
if (!$f = pg_fetch_array($result, null, PGSQL_ASSOC)) { |
|
|
return false; |
|
|
} |
|
|
return $idx ? $f[$idx] : $f; |
|
|
} |
|
|
|
|
|
if (!$f = pg_fetch_row($result)) { |
|
|
return false; |
|
|
} |
|
|
return $idx ? $f[$idx] : $f; |
|
|
} |
|
|
|
|
|
function ConectaManager($arConnect) |
|
|
{ |
|
|
list($host, $porta, $usuario, $senha) = $arConnect; |
|
|
$timeout = 5; |
|
|
$socket = fsockopen($host, $porta, $errno, $errstr, $timeout); |
|
|
//$socket = fsockopen($host,$porta); |
|
|
|
|
|
if ($socket) { |
|
|
$actionid = rand(000000000, 9999999999); |
|
|
fwrite($socket, "action: login\r\n"); |
|
|
fwrite($socket, "username: $usuario\r\n"); |
|
|
fwrite($socket, "secret: $senha\r\n"); |
|
|
fwrite($socket, "events: off\r\n"); |
|
|
fwrite($socket, "ActionID: " . $actionid . "\r\n\r\n"); |
|
|
|
|
|
|
|
|
$i = 0; |
|
|
$ret = false; |
|
|
while (!feof($socket)) { |
|
|
$buffer = fgets($socket); |
|
|
|
|
|
if (stristr($buffer, "Authentication accepted")) { |
|
|
return $socket; |
|
|
} |
|
|
|
|
|
if (stristr($buffer, "Authentication failed")) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
if ($buffer === false) { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
return false; |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
function DesativaLista($db, $idCampanha, $listId = 0) |
|
|
{ |
|
|
$query = "update pbx_campanha_lista set list_status = 2 where cmp_id = '$idCampanha' and list_status = 1"; |
|
|
$result = pg_query($db, $query); |
|
|
if (!$result) |
|
|
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel desativar a \"Lista\"!"); |
|
|
|
|
|
//Desativa listas de contatos existents |
|
|
$query = "update pbx_campanha_contato set cont_status = -1 where cmp_id = '$idCampanha' and cont_status = 0" . ($listId ? " and list_id <> '{$listId}'" : ""); |
|
|
$result = pg_query($db, $query); |
|
|
if (!$result) |
|
|
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel destativar a \"Lista de Contatos\"!"); |
|
|
|
|
|
//Desativa listas de contatos existents |
|
|
$query = "update pbx_campanha_contato_fone set conf_status = '-1' where cmp_id = '$idCampanha' and conf_status = '0'" . ($listId ? " and list_id <> '{$listId}'" : ""); |
|
|
$result = pg_query($db, $query); |
|
|
if (!$result) |
|
|
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel destativar a \"Lista de Telefones\"!"); |
|
|
} |
|
|
|
|
|
function PendenciasDiscador($dbcon, $idCampanha) |
|
|
{ |
|
|
$query = "select count(*) as lista from pbx_campanha_lista a, pbx_campanha_operacao b where b.cmp_id = a.cmp_id and a.list_id = b.list_id and b.cmpo_status = 0 and a.cmp_id = '$idCampanha' and list_status = '1'"; |
|
|
$result = pg_query($dbcon, $query); |
|
|
$row = pg_fetch_array($result); |
|
|
$statuslista = $row['lista']; |
|
|
|
|
|
if ($statuslista) |
|
|
throw new Exception('Para concluir a campanha <EFBFBD> necess<EFBFBD>rio finalizar o atendimento de todos os contatos!'); |
|
|
} |
|
|
|
|
|
function GravaLogGlobal($label = '') |
|
|
{ |
|
|
global $debug; |
|
|
|
|
|
if (!$debug) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
$tmp = time(); |
|
|
$pathLog = isset($GLOBALS["pathLog"]) ? $GLOBALS["pathLog"] : '/var/log/asterisk/log_global.log'; |
|
|
$strLog = ''; |
|
|
WriteLog(sprintf("%sData: %s\n", ($label ? "$label " : ''), date("Y-m-d H:i:s")), $pathLog); |
|
|
|
|
|
foreach ($GLOBALS as $key => $value) { |
|
|
$strLog .= "{$key}: $value\n"; |
|
|
} |
|
|
|
|
|
WriteLog($strLog, $pathLog); |
|
|
WriteLog(sprintf("Fim: %ss\n", (time() - $tmp)), $pathLog); |
|
|
|
|
|
return true; |
|
|
} |
|
|
|
|
|
function SessaoEncerrada() |
|
|
{ |
|
|
if (GetRegId() === false) { |
|
|
return true; |
|
|
} |
|
|
$query = sprintf("select case when(acs_data_fim is null)then 0 else 1 end as sessao_expirada from pbx_controle_acesso where acs_id = '%s'", GetRegId()); |
|
|
$result = pg_query($query); |
|
|
$row = pg_fetch_row($result); |
|
|
return $row[0] ? true : false; |
|
|
} |
|
|
|
|
|
function SetRegId($regId) |
|
|
{ |
|
|
$_SESSION["SSRegAcessoId"] = $regId; |
|
|
} |
|
|
|
|
|
function GetRegId() |
|
|
{ |
|
|
return isset($_SESSION["SSRegAcessoId"]) ? $_SESSION["SSRegAcessoId"] : false; |
|
|
} |
|
|
|
|
|
function validaCPF($cpf) |
|
|
{ |
|
|
$soma = 0; |
|
|
|
|
|
if (strlen($cpf) <> 11) |
|
|
return false; |
|
|
|
|
|
// Verifica 1<EFBFBD> digito |
|
|
for ($i = 0; $i < 9; $i++) { |
|
|
$soma += (($i + 1) * $cpf[$i]); |
|
|
} |
|
|
|
|
|
$d1 = ($soma % 11); |
|
|
|
|
|
if ($d1 == 10) { |
|
|
$d1 = 0; |
|
|
} |
|
|
|
|
|
$soma = 0; |
|
|
|
|
|
// Verifica 2<EFBFBD> digito |
|
|
for ($i = 9, $j = 0; $i > 0; $i--, $j++) { |
|
|
$soma += ($i * $cpf[$j]); |
|
|
} |
|
|
|
|
|
$d2 = ($soma % 11); |
|
|
|
|
|
if ($d2 == 10) { |
|
|
$d2 = 0; |
|
|
} |
|
|
|
|
|
if ($d1 == $cpf[9] && $d2 == $cpf[10]) { |
|
|
return true; |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
// VERFICA CNPJ |
|
|
function validaCNPJ($cnpj) |
|
|
{ |
|
|
|
|
|
if (strlen($cnpj) <> 14) |
|
|
return false; |
|
|
|
|
|
$soma = 0; |
|
|
|
|
|
$soma += ($cnpj[0] * 5); |
|
|
$soma += ($cnpj[1] * 4); |
|
|
$soma += ($cnpj[2] * 3); |
|
|
$soma += ($cnpj[3] * 2); |
|
|
$soma += ($cnpj[4] * 9); |
|
|
$soma += ($cnpj[5] * 8); |
|
|
$soma += ($cnpj[6] * 7); |
|
|
$soma += ($cnpj[7] * 6); |
|
|
$soma += ($cnpj[8] * 5); |
|
|
$soma += ($cnpj[9] * 4); |
|
|
$soma += ($cnpj[10] * 3); |
|
|
$soma += ($cnpj[11] * 2); |
|
|
|
|
|
$d1 = $soma % 11; |
|
|
$d1 = $d1 < 2 ? 0 : 11 - $d1; |
|
|
|
|
|
$soma = 0; |
|
|
$soma += ($cnpj[0] * 6); |
|
|
$soma += ($cnpj[1] * 5); |
|
|
$soma += ($cnpj[2] * 4); |
|
|
$soma += ($cnpj[3] * 3); |
|
|
$soma += ($cnpj[4] * 2); |
|
|
$soma += ($cnpj[5] * 9); |
|
|
$soma += ($cnpj[6] * 8); |
|
|
$soma += ($cnpj[7] * 7); |
|
|
$soma += ($cnpj[8] * 6); |
|
|
$soma += ($cnpj[9] * 5); |
|
|
$soma += ($cnpj[10] * 4); |
|
|
$soma += ($cnpj[11] * 3); |
|
|
$soma += ($cnpj[12] * 2); |
|
|
|
|
|
|
|
|
$d2 = $soma % 11; |
|
|
$d2 = $d2 < 2 ? 0 : 11 - $d2; |
|
|
|
|
|
if ($cnpj[12] == $d1 && $cnpj[13] == $d2) { |
|
|
return true; |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
function SendEmail($params) |
|
|
{ |
|
|
require_once("phpmailer/class.phpmailer.php"); |
|
|
$paramsDef = array( |
|
|
'email_smtp' => 'mail.simplesip.com.br', |
|
|
'email_auth' => true, |
|
|
'email_conta_envio' => 'marketing@simplesip.com.br', |
|
|
'email_senha_envio' => '$m@rk2t3ng_#', |
|
|
'email_port' => '587', |
|
|
'email_retorno' => 'comercial@simplesip.com.br', |
|
|
'email_retorno_nome' => '', |
|
|
'email_envio' => null, |
|
|
'email_envio_nome' => '', |
|
|
'email_html' => true, |
|
|
'email_assunto' => 'Simples IP', |
|
|
'email_charset' => 'iso-8859-1', |
|
|
'email_body' => '', |
|
|
'email_template' => '', |
|
|
'email_template_info' => array() |
|
|
); |
|
|
|
|
|
$GetBodyEmail = function ($template, $info, $isFile) { |
|
|
$pathTpl = "/var/www/html/aplicativo/templates/sendmail/" . $template; |
|
|
$tpl = $isFile ? file_get_contents($pathTpl) : $template; |
|
|
|
|
|
foreach ($info as $key => $value) { |
|
|
$tpl = str_replace('{' . $key . '}', $value, $tpl); |
|
|
} |
|
|
|
|
|
return $tpl; |
|
|
}; |
|
|
|
|
|
$SetParamsDef = function ($paramsDef, $params) { |
|
|
foreach ($paramsDef as $key => $value) { |
|
|
if ($value && !$params[$key]) { |
|
|
$params[$key] = $value; |
|
|
} |
|
|
} |
|
|
|
|
|
/* |
|
|
* Valida dados. |
|
|
*/ |
|
|
if (!is_email($params['email_envio'])) { |
|
|
GeraExcept("Email: \"" . $params['email_envio'] . "\" inv<EFBFBD>lido!"); |
|
|
} |
|
|
|
|
|
if (!is_email($params['email_retorno'])) { |
|
|
GeraExcept("Email de retorno: \"" . $params['email_retorno'] . "\" inv<EFBFBD>lido!"); |
|
|
} |
|
|
|
|
|
if (is_email($params['email_auth']) && !$params['email_conta_envio']) { |
|
|
GeraExcept("Informe a conta de autentica<EFBFBD><EFBFBD>o!"); |
|
|
} |
|
|
|
|
|
if (is_email($params['email_auth']) && !$params['email_senha_envio']) { |
|
|
GeraExcept("Senha de autentica<EFBFBD><EFBFBD>o <EFBFBD> obrigat<EFBFBD>ria!"); |
|
|
} |
|
|
|
|
|
if (!$params['email_smtp']) { |
|
|
GeraExcept("Iforme O SMTP!"); |
|
|
} |
|
|
|
|
|
return $params; |
|
|
}; |
|
|
|
|
|
$mail = new PHPMailer(true); |
|
|
try { |
|
|
$params = $SetParamsDef($paramsDef, $params); |
|
|
//Configura<EFBFBD><EFBFBD>es do Servidor |
|
|
$mail->SMTPDebug = 0; // Enable verbose debug output |
|
|
$mail->isSMTP(); // Set mailer to use SMTP |
|
|
$mail->Host = $params['email_smtp']; // Specify main and backup SMTP servers |
|
|
$mail->SMTPAuth = $params['email_auth']; // Enable SMTP authentication |
|
|
if ($params['email_auth']) { |
|
|
$mail->Username = $params['email_conta_envio']; // SMTP username |
|
|
$mail->Password = $params['email_senha_envio']; // SMTP password |
|
|
} |
|
|
//$mail->SMTPSecure = 'TLS'; // Enable TLS encryption, `ssl` also accepted |
|
|
$mail->Port = $params['email_port']; // TCP port to connect to |
|
|
//Remetente |
|
|
$mail->setFrom($params['email_retorno'], $params['email_retorno_nome']); |
|
|
|
|
|
//Recebedores |
|
|
$mail->addAddress($params['email_envio'], $params['email_envio_nome']); |
|
|
|
|
|
//Conteudo |
|
|
$mail->isHTML($params['email_html']); // Set email format to HTML |
|
|
$mail->Subject = $params['email_assunto']; |
|
|
$mail->CharSet = $params['email_charset']; |
|
|
$mail->Body = !empty($params['email_body']) ? $params['email_body'] : $GetBodyEmail($params['email_template'], $params['email_template_info'], $params['email_html']); |
|
|
if (!$mail->send()) { |
|
|
GeraExcept($mail->ErrorInfo); |
|
|
} |
|
|
return true; |
|
|
} catch (Exception $e) { |
|
|
return $e->getMessage(); |
|
|
} |
|
|
} |
|
|
|
|
|
function pgGetError($dbcon) |
|
|
{ |
|
|
if (pg_last_error($dbcon)) { |
|
|
GeraExcept("N<EFBFBD>o foi poss<EFBFBD>vel realizar a convers<EFBFBD>o da lista! PG_" . pg_last_error()); |
|
|
} |
|
|
} |
|
|
|
|
|
function SendSMS($paramsEnvio) |
|
|
{ |
|
|
return "Funcao nao implementada"; |
|
|
} |
|
|
|
|
|
function SendTelegram($paramsEnvio) |
|
|
{ |
|
|
return "Funcao nao implementada"; |
|
|
} |
|
|
|
|
|
function SendWhatsapp($paramsEnvio) |
|
|
{ |
|
|
return "Funcao nao implementada"; |
|
|
} |
|
|
|
|
|
function IsLocalServer() |
|
|
{ |
|
|
return (stripos($_SERVER['SERVER_NAME'], 'localhost') !== false) || (stripos($_SERVER['SERVER_NAME'], '127.0.0.1') !== false); |
|
|
} |
|
|
|
|
|
function VerificaPerfilAplicacao() |
|
|
{ |
|
|
$query = "select '' from pbx_parametros where prm_perfil_verificado = '1'"; |
|
|
$result = pg_query($query); |
|
|
return pg_num_rows($result); |
|
|
} |
|
|
|
|
|
function AjustaPerfil() |
|
|
{ |
|
|
$query = "delete from pbx_funcoes a where not exists(select '' from pbx_grupo_funcoes where fun_id = a.fun_id and gp_id = 67) |
|
|
"; |
|
|
} |
|
|
|
|
|
|
|
|
/* A fun<EFBFBD><EFBFBD>o strftime foi descontinuada, portanto essa fun<EFBFBD><EFBFBD>o ser<EFBFBD> chamada. |
|
|
* Cada chamada ser<EFBFBD> mudada para strftime_ |
|
|
* Para n<EFBFBD>o precisar modificar cada c<EFBFBD>digo, resolvemos mudar apenas o nome. |
|
|
* |
|
|
* \warning Essa fun<EFBFBD><EFBFBD>o n<EFBFBD>o deve ser usado para novos c<EFBFBD>digos. Deve ser evitado |
|
|
* strftime e strftime_ |
|
|
* |
|
|
* \param format De acordo php.net/manual/en/datatime.format.php |
|
|
* \param time par<EFBFBD>metro <EFBFBD> um int Unix timestamp |
|
|
* \return mesmo que strftime (fun<EFBFBD><EFBFBD>o deprecated) |
|
|
*/ |
|
|
function strftime_($format, $timestamp = null) |
|
|
{ |
|
|
|
|
|
$date_immutable = new DateTimeImmutable(); |
|
|
|
|
|
if ($timestamp) { |
|
|
$date_immutable = $date_immutable->setTimestamp($timestamp); |
|
|
} |
|
|
|
|
|
|
|
|
/* tratar string */ |
|
|
$str_converted = convert_format_strftime($format); |
|
|
return $date_immutable->format($str_converted); |
|
|
} |
|
|
|
|
|
|
|
|
/* Converter<EFBFBD> a string de strftime(descontinuado) para fomat DataTimeImmutable:format |
|
|
* Isso ser<EFBFBD> usado para fun<EFBFBD><EFBFBD>o strftime para converter essa string que n<EFBFBD>o s<EFBFBD>o compat<EFBFBD>veis |
|
|
* |
|
|
* \param format strftime |
|
|
* \return retorna a string para DataTimeImmutable |
|
|
*/ |
|
|
function convert_format_strftime($format) |
|
|
{ |
|
|
|
|
|
$id = 0; |
|
|
|
|
|
/* formato strftime */ |
|
|
$patterns = array( |
|
|
/* day */ |
|
|
'/%a/', '/%A/', '/%d/', '/%e/', '/%j/', '/%u/', '/%w/', |
|
|
/* Week */ |
|
|
'/%U/', '/%V/', '/%W/', |
|
|
/* Month */ |
|
|
'/%b/', '/%B/', '/%h/', '/%m/', |
|
|
/* Year */ |
|
|
'/%C/', '/%g/', '/%G/', '/%y/', '/%Y/', |
|
|
/* Time */ |
|
|
'/%H/', '/%k/', '/%I/', '/%l/', '/%M/', '/%p/', '/%P/', '/%r/', '/%R/', '/%S/', |
|
|
'/%T/', '/%X/', '/%z/', '/%Z/', |
|
|
/* Time and Date Stamps */ |
|
|
'/%c/', '/%D/', '/%F/', '/%s/', '/%x/', '/%n/', |
|
|
'/%t/', '/%%/' |
|
|
); |
|
|
|
|
|
/* valores similares de strftime |
|
|
* para DateTime |
|
|
* |
|
|
*/ |
|
|
$replacements = array( |
|
|
/* day */ |
|
|
'D', 'l', 'd', 'j', 'z', 'N', 'w', |
|
|
/* Week */ |
|
|
'W', '', '', |
|
|
/* mounth */ |
|
|
'M', 'F', 'M', 'm', |
|
|
/* Year */ |
|
|
'', 'y', 'o', 'y', 'o', |
|
|
/* Time */ |
|
|
'H', 'G', 'h', ' g', 'i', 'A', 'a', '', '', 's', |
|
|
'', '', '', '', |
|
|
/* Time and Date Stamps */ |
|
|
'', '', '', '', '', '', |
|
|
' ', '%' |
|
|
); |
|
|
|
|
|
return preg_replace($patterns, $replacements, $format); |
|
|
} |
|
|
|
|
|
/** |
|
|
* Verifica a existencia de uma tabela no banco de dados do sistema. |
|
|
* @param string $table |
|
|
* @return bool |
|
|
*/ |
|
|
function ExistsTableInDb($dbcon, string $table) |
|
|
{ |
|
|
$query = "SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = '$table')"; |
|
|
$result = ExecQueryDb($dbcon, $query); |
|
|
$true = 't'; |
|
|
|
|
|
if (!$result) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
$row = pg_fetch_row($result); |
|
|
$existsTable = $row[0]; |
|
|
|
|
|
if ($existsTable == $true) { |
|
|
return true; |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Executa query no banco de dados. |
|
|
* @param conexao $dbcon |
|
|
* @param string $query |
|
|
*/ |
|
|
function ExecQueryDb($dbcon, string $query, string $pathLog = null) |
|
|
{ |
|
|
$exception = "\n Falha ao executar a query: \n" . $query; |
|
|
|
|
|
try { |
|
|
$begin = BeginTransactionDb($dbcon); |
|
|
if (!$begin) { |
|
|
GeraExcept($exception, true); |
|
|
} |
|
|
|
|
|
$result = pg_query($dbcon, $query); |
|
|
if (!$result) { |
|
|
GeraExcept($exception, true); |
|
|
} |
|
|
|
|
|
$commit = CommitTransactionDb($dbcon); |
|
|
if (!$commit) { |
|
|
GeraExcept($exception, true); |
|
|
} |
|
|
|
|
|
return $result; |
|
|
} catch (Exception $ex) { |
|
|
if ($pathLog) { |
|
|
WriteLog($ex->getMessage(), $pathLog); |
|
|
} |
|
|
RollbackTransactionDb($dbcon); |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Inicia transa<EFBFBD><EFBFBD>o com o banco |
|
|
* @param conexao $dbcon |
|
|
* @return bollean |
|
|
*/ |
|
|
function BeginTransactionDb($dbcon, string $pathLog = null) |
|
|
{ |
|
|
try { |
|
|
$result = pg_query($dbcon, 'begin'); |
|
|
|
|
|
if (!$result) { |
|
|
GeraExcept("\n Falha ao iniciar a transa<EFBFBD><EFBFBD>o com o banco! \n", true); |
|
|
} |
|
|
|
|
|
return true; |
|
|
} catch (Exception $ex) { |
|
|
if ($pathLog) { |
|
|
WriteLog($ex->getMessage(), $pathLog); |
|
|
} |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* realiza commit da transa<EFBFBD><EFBFBD>o com o banco |
|
|
* @param conexao $dbcon |
|
|
* @return bollean |
|
|
*/ |
|
|
function CommitTransactionDb($dbcon, string $pathLog = null) |
|
|
{ |
|
|
try { |
|
|
$result = pg_query($dbcon, 'commit'); |
|
|
|
|
|
if (!$result) { |
|
|
GeraExcept("\n Falha ao realizar commit da transa<EFBFBD><EFBFBD>o com o banco! \n", true); |
|
|
} |
|
|
|
|
|
return true; |
|
|
} catch (Exception $ex) { |
|
|
if ($pathLog) { |
|
|
WriteLog($ex->getMessage(), $pathLog); |
|
|
} |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* realiza rollback da transa<EFBFBD><EFBFBD>o com o banco |
|
|
* @param conexao $dbcon |
|
|
* @return bollean |
|
|
*/ |
|
|
function RollbackTransactionDb($dbcon, string $pathLog = null) |
|
|
{ |
|
|
try { |
|
|
$result = pg_query($dbcon, 'rollback'); |
|
|
|
|
|
if (!$result) { |
|
|
GeraExcept("\n Falha ao realizar rollback da transa<EFBFBD><EFBFBD>o com o banco! \n", true); |
|
|
} |
|
|
|
|
|
return true; |
|
|
} catch (Exception $ex) { |
|
|
if ($pathLog) { |
|
|
WriteLog($ex->getMessage(), $pathLog); |
|
|
} |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* realiza rollback da transa<EFBFBD><EFBFBD>o com o banco |
|
|
* @return string $query |
|
|
*/ |
|
|
function GetQueryCreateTableCdr() |
|
|
{ |
|
|
$query = "CREATE TABLE cdr ( |
|
|
id SERIAL NOT NULL PRIMARY KEY, |
|
|
accountcode character varying(32), |
|
|
src character varying(128), |
|
|
dst character varying(128), |
|
|
dcontext character varying(128), |
|
|
clid character varying(128), |
|
|
channel character varying(128), |
|
|
dstchannel character varying(128), |
|
|
lastapp character varying(128), |
|
|
lastdata character varying(256), |
|
|
calldate timestamp without time zone NOT NULL, |
|
|
answerdate timestamp without time zone, |
|
|
hangupdate timestamp without time zone, |
|
|
duration integer DEFAULT 0 NOT NULL, |
|
|
billsec integer DEFAULT 0 NOT NULL, |
|
|
disposition character varying(128), |
|
|
amaflags character varying(256), |
|
|
uniqueid character varying(32), |
|
|
userfield character varying(256));"; |
|
|
|
|
|
return $query; |
|
|
}
|
|
|
|