Esempio n. 1
0
function leerDatosGrafico($type_graph, $date_start, $date_end)
{
    global $arrConf;
    global $arrConfModule;
    global $arrLang;
    $MAX_SLICES = 10;
    $pConfig = new paloConfig("/etc", "amportal.conf", "=", "[[:space:]]*=[[:space:]]*");
    $arrConfig = $pConfig->leer_configuracion(false);
    $pDBSQLite = new paloDB($arrConfModule['dsn_conn_database_2']);
    if (!empty($pDBSQLite->errMsg)) {
        echo "{$arrLang['ERROR']}: {$pDBSQLite->errMsg} <br>";
    }
    $pRate = new paloRate($pDBSQLite);
    if (!empty($pRate->errMsg)) {
        echo "{$arrLang['ERROR']}: {$pRate->errMsg} <br>";
    }
    $pDBSet = new paloDB($arrConf['elastix_dsn']['settings']);
    $pDBTrunk = new paloDB($arrConfModule['dsn_conn_database_1']);
    $oTrunk = new paloTrunk($pDBTrunk);
    $grupos = NULL;
    $troncales = $oTrunk->getExtendedTrunksBill($grupos, $arrConfig['ASTETCDIR']['valor'] . '/chan_dahdi.conf');
    //ej array("DAHDI/1","DAHDI/2");
    $dsn = $arrConfig['AMPDBENGINE']['valor'] . "://" . $arrConfig['AMPDBUSER']['valor'] . ":" . $arrConfig['AMPDBPASS']['valor'] . "@" . $arrConfig['AMPDBHOST']['valor'] . "/asteriskcdrdb";
    $pDB = new paloDB($dsn);
    $oCDR = new paloSantoCDR($pDB);
    $arrCDR = $oCDR->obtenerCDRs("", 0, $date_start, $date_end, "", "", "ANSWERED", "outgoing", $troncales);
    $total = $arrCDR['NumRecords'][0];
    $num_calls = array();
    $minutos = array();
    $val_charge = array();
    $nombre_rate = array();
    $title_sumary = NULL;
    if ($total > 0) {
        foreach ($arrCDR['Data'] as $cdr) {
            if (eregi("^DAHDI/([[:digit:]]+)", $cdr[4], $regs3)) {
                $trunk = 'DAHDI/g' . $grupos[$regs3[1]];
            } else {
                $trunk = str_replace(strstr($cdr[4], '-'), '', $cdr[4]);
            }
            //tengo que buscar la tarifa para el numero de telefono
            $numero = $cdr[2];
            $tarifa = array();
            $rate_name = "";
            $charge = 0;
            $bExito = $pRate->buscarTarifa($numero, $tarifa, $trunk);
            if (!count($tarifa) > 0 && $bExito) {
                $bExito = $pRate->buscarTarifa($numero, $tarifa, 'None');
            }
            if (!$bExito) {
                echo "{$arrLang['ERROR']}: {$pRate->errMsg} <br>";
            } else {
                //verificar si tiene tarifa
                if (count($tarifa) > 0) {
                    foreach ($tarifa as $id_tarifa => $datos_tarifa) {
                        $rate_name = $datos_tarifa['name'];
                        $id_rate = $datos_tarifa['id'];
                        $charge = $cdr[8] / 60 * $datos_tarifa['rate'] + $datos_tarifa['offset'];
                    }
                } else {
                    $rate_name = $arrLang["default"];
                    $id_rate = 0;
                    //no tiene tarifa buscar tarifa por omision
                    //por ahora para probar $1 el minuto
                    $rate = get_key_settings($pDBSet, "default_rate");
                    $rate_offset = get_key_settings($pDBSet, "default_rate_offset");
                    $charge = $cdr[8] / 60 * $rate + $rate_offset;
                }
                $nombre_rate[$id_rate] = $rate_name;
                if (!isset($minutos[$id_rate])) {
                    $minutos[$id_rate] = 0;
                }
                if (!isset($num_calls[$id_rate])) {
                    $num_calls[$id_rate] = 0;
                }
                if (!isset($val_charge[$id_rate])) {
                    $val_charge[$id_rate] = 0;
                }
                $minutos[$id_rate] += $cdr[8] / 60;
                $num_calls[$id_rate]++;
                $val_charge[$id_rate] += $charge;
            }
        }
        //ordenar los valores a mostrar
        arsort($num_calls);
        arsort($minutos);
        arsort($val_charge);
        //verificar que los valores no excedan el numero de slices del pie
        //numero de llamadas
        if (count($num_calls) > $MAX_SLICES) {
            $i = 1;
            foreach ($num_calls as $id_rate => $valor) {
                if ($i > $MAX_SLICES - 1) {
                    if (!isset($valores_num_calls['otros'])) {
                        $valores_num_calls['otros'] = 0;
                    }
                    $valores_num_calls['otros'] += $valor;
                } else {
                    $valores_num_calls[$id_rate] = $valor;
                }
                $i++;
            }
        } else {
            $valores_num_calls = $num_calls;
        }
        //minutos
        if (count($minutos) > $MAX_SLICES) {
            $i = 1;
            foreach ($minutos as $id_rate => $valor) {
                if ($i > $MAX_SLICES - 1) {
                    if (!isset($valores_minutos['otros'])) {
                        $valores_minutos['otros'] = 0;
                    }
                    $valores_minutos['otros'] += $valor;
                } else {
                    $valores_minutos[$id_rate] = $valor;
                }
                $i++;
            }
        } else {
            $valores_minutos = $minutos;
        }
        //charge
        if (count($val_charge) > $MAX_SLICES) {
            $i = 1;
            foreach ($val_charge as $id_rate => $valor) {
                if ($i > $MAX_SLICES - 1) {
                    if (!isset($valores_charge['otros'])) {
                        $valores_charge['otros'] = 0;
                    }
                    $valores_charge['otros'] += $valor;
                } else {
                    $valores_charge[$id_rate] = $valor;
                }
                $i++;
            }
        } else {
            $valores_charge = $val_charge;
        }
        if ($type_graph == "minutes") {
            $titulo = $arrLang["Distribution by Time"];
            $valores_grafico = $valores_minutos;
            $title_sumary = $arrLang["Minutes"];
        } elseif ($type_graph == "charge") {
            $titulo = $arrLang["Distribution by Cost"];
            $valores_grafico = $valores_charge;
            $title_sumary = $arrLang["Cost"];
        } else {
            $titulo = $arrLang["Distribution by Number of Calls"];
            $valores_grafico = $valores_num_calls;
            $title_sumary = $arrLang["Number of Calls"];
        }
        //nombres de tarifas para leyenda
        foreach ($valores_grafico as $id => $valor) {
            $nombres_tarifas[] = isset($nombre_rate[$id]) ? $nombre_rate[$id] : $arrLang["others"];
        }
        $data = array_values($valores_grafico);
    } else {
        if ($type_graph == "minutes") {
            $titulo = $arrLang["Distribution by Time"];
        } elseif ($type_graph == "charge") {
            $titulo = $arrLang["Distribution by Cost"];
        } else {
            $titulo = $arrLang["Distribution by Number of Calls"];
        }
        $nombres_tarifas = $data = array();
    }
    //formar la estructura a pasar al pie
    $data_graph = array("values" => $data, "legend" => $nombres_tarifas, "title" => $titulo, "title_sumary" => $title_sumary);
    return $data_graph;
}
Esempio n. 2
0
function _moduleContent(&$smarty, $module_name)
{
    require_once "modules/{$module_name}/libs/ringgroup.php";
    //include module files
    include_once "modules/{$module_name}/configs/default.conf.php";
    load_language_module($module_name);
    global $arrConf;
    global $arrConfModule;
    $arrConf = array_merge($arrConf, $arrConfModule);
    //folder path for custom templates
    $base_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    $templates_dir = isset($arrConf['templates_dir']) ? $arrConf['templates_dir'] : 'themes';
    $local_templates_dir = "{$base_dir}/modules/{$module_name}/" . $templates_dir . '/' . $arrConf['theme'];
    // DSN para consulta de cdrs
    $dsn = generarDSNSistema('asteriskuser', 'asteriskcdrdb');
    $pDB = new paloDB($dsn);
    $oCDR = new paloSantoCDR($pDB);
    $pDBACL = new paloDB($arrConf['elastix_dsn']['acl']);
    if (!empty($pDBACL->errMsg)) {
        return "ERROR DE DB: {$pDBACL->errMsg}";
    }
    $pACL = new paloACL($pDBACL);
    if (!empty($pACL->errMsg)) {
        return "ERROR DE ACL: {$pACL->errMsg}";
    }
    $exten = '6868';
    //$pACL->getUserExtension($_SESSION['elastix_user']);
    $isAdministrator = true;
    //$pACL->isUserAdministratorGroup($_SESSION['elastix_user']);
    if (is_null($exten) || $exten == "") {
        if (!$isAdministrator) {
            $smarty->assign('mb_message', "<b>" . _tr("contact_admin") . "</b>");
            return "";
        } else {
            $smarty->assign('mb_message', "<b>" . _tr("no_extension") . "</b>");
        }
    }
    // Para usuarios que no son administradores, se restringe a los CDR de la
    // propia extensión
    $sExtension = $isAdministrator ? '' : $pACL->getUserExtension($_SESSION['elastix_user']);
    // DSN para consulta de ringgroups
    $dsn_asterisk = generarDSNSistema('asteriskuser', 'asterisk');
    $pDB_asterisk = new paloDB($dsn_asterisk);
    $oRG = new RingGroup($pDB_asterisk);
    $dataRG = $oRG->getRingGroup();
    $dataRG[''] = _tr('(Any ringgroup)');
    // Cadenas estáticas en la plantilla
    $smarty->assign(array("Filter" => _tr("Filter")));
    $arrFormElements = array("date_start" => array("LABEL" => _tr("Start Date"), "REQUIRED" => "yes", "INPUT_TYPE" => "DATE", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "ereg", "VALIDATION_EXTRA_PARAM" => "^[[:digit:]]{1,2}[[:space:]]+[[:alnum:]]{3}[[:space:]]+[[:digit:]]{4}\$"), "date_end" => array("LABEL" => _tr("End Date"), "REQUIRED" => "yes", "INPUT_TYPE" => "DATE", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "ereg", "VALIDATION_EXTRA_PARAM" => "^[[:digit:]]{1,2}[[:space:]]+[[:alnum:]]{3}[[:space:]]+[[:digit:]]{4}\$"), "field_name" => array("LABEL" => _tr("Field Name"), "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => array("dst" => _tr("Destination"), "src" => _tr("Source"), "channel" => _tr("Src. Channel"), "accountcode" => _tr("Account Code"), "dstchannel" => _tr("Dst. Channel")), "VALIDATION_TYPE" => "ereg", "VALIDATION_EXTRA_PARAM" => "^(dst|src|channel|dstchannel|accountcode)\$"), "field_pattern" => array("LABEL" => _tr("Field"), "REQUIRED" => "no", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "ereg", "VALIDATION_EXTRA_PARAM" => "^[\\*|[:alnum:]@_\\.,/\\-]+\$"), "status" => array("LABEL" => _tr("Status"), "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => array("ALL" => _tr("ALL"), "ANSWERED" => _tr("ANSWERED"), "BUSY" => _tr("BUSY"), "FAILED" => _tr("FAILED"), "NO ANSWER " => _tr("NO ANSWER")), "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "ringgroup" => array("LABEL" => _tr("Ring Group"), "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => $dataRG, "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""));
    $oFilterForm = new paloForm($smarty, $arrFormElements);
    // Parámetros base y validación de parámetros
    $url = array('menu' => $module_name);
    $paramFiltroBase = $paramFiltro = array('date_start' => date("d M Y"), 'date_end' => date("d M Y"), 'field_name' => 'dst', 'field_pattern' => '', 'status' => 'ALL', 'ringgroup' => '');
    foreach (array_keys($paramFiltro) as $k) {
        if (!is_null(getParameter($k))) {
            $paramFiltro[$k] = getParameter($k);
        }
    }
    $oGrid = new paloSantoGrid($smarty);
    if ($paramFiltro['date_start'] === "") {
        $paramFiltro['date_start'] = " ";
    }
    if ($paramFiltro['date_end'] === "") {
        $paramFiltro['date_end'] = " ";
    }
    $valueFieldName = $arrFormElements['field_name']["INPUT_EXTRA_PARAM"][$paramFiltro['field_name']];
    $valueStatus = $arrFormElements['status']["INPUT_EXTRA_PARAM"][$paramFiltro['status']];
    $valueRingGRoup = $arrFormElements['ringgroup']["INPUT_EXTRA_PARAM"][$paramFiltro['ringgroup']];
    $oGrid->addFilterControl(_tr("Filter applied: ") . _tr("Start Date") . " = " . $paramFiltro['date_start'] . ", " . _tr("End Date") . " = " . $paramFiltro['date_end'], $paramFiltro, array('date_start' => date("d M Y"), 'date_end' => date("d M Y")), true);
    $oGrid->addFilterControl(_tr("Filter applied: ") . $valueFieldName . " = " . $paramFiltro['field_pattern'], $paramFiltro, array('field_name' => "dst", 'field_pattern' => ""));
    $oGrid->addFilterControl(_tr("Filter applied: ") . _tr("Status") . " = " . $valueStatus, $paramFiltro, array('status' => 'ALL'), true);
    $oGrid->addFilterControl(_tr("Filter applied: ") . _tr("Ring Group") . " = " . $valueRingGRoup, $paramFiltro, array('ringgroup' => ''));
    $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $paramFiltro);
    if (!$oFilterForm->validateForm($paramFiltro)) {
        $smarty->assign(array('mb_title' => _tr('Validation Error'), 'mb_message' => '<b>' . _tr('The following fields contain errors') . ':</b><br/>' . implode(', ', array_keys($oFilterForm->arrErroresValidacion))));
        $paramFiltro = $paramFiltroBase;
        unset($_POST['delete']);
        // Se aborta el intento de borrar CDRs, si había uno.
    }
    // Tradudir fechas a formato ISO para comparación y para API de CDRs.
    $url = array_merge($url, $paramFiltro);
    $paramFiltro['date_start'] = translateDate($paramFiltro['date_start']) . ' 00:00:00';
    $paramFiltro['date_end'] = translateDate($paramFiltro['date_end']) . ' 23:59:59';
    // Valores de filtrado que no se seleccionan mediante filtro
    if ($sExtension != '') {
        $paramFiltro['extension'] = $sExtension;
    }
    // Ejecutar el borrado, si se ha validado.
    if (isset($_POST['delete'])) {
        if ($isAdministrator) {
            if ($paramFiltro['date_start'] <= $paramFiltro['date_end']) {
                $r = $oCDR->borrarCDRs($paramFiltro);
                if (!$r) {
                    $smarty->assign(array('mb_title' => _tr('ERROR'), 'mb_message' => $oCDR->errMsg));
                }
            } else {
                $smarty->assign(array('mb_title' => _tr('ERROR'), 'mb_message' => _tr("Please End Date must be greater than Start Date")));
            }
        } else {
            $smarty->assign(array('mb_title' => _tr('ERROR'), 'mb_message' => _tr("Only administrators can delete CDRs")));
        }
    }
    $oGrid->setTitle(_tr("CDR Report"));
    $oGrid->pagingShow(true);
    // show paging section.
    $oGrid->enableExport();
    // enable export.
    $oGrid->setNameFile_Export(_tr("CDRReport"));
    $oGrid->setURL($url);
    //if($isAdministrator)
    //$oGrid->deleteList("Are you sure you wish to delete CDR(s) Report(s)?","delete",_tr("Delete"));
    $arrData = null;
    if (!isset($sExtension) || $sExtension == "" && !$isAdministrator) {
        $total = 0;
    } else {
        $total = $oCDR->contarCDRs($paramFiltro);
    }
    if ($oGrid->isExportAction()) {
        $limit = $total;
        $offset = 0;
        $arrColumns = array(_tr("Date"), _tr("Source"), _tr("Ring Group"), _tr("Destination"), _tr("Src. Channel"), _tr("Account Code"), _tr("Dst. Channel"), _tr("Status"), _tr("Duration"));
        $oGrid->setColumns($arrColumns);
        $arrResult = $oCDR->listarCDRs($paramFiltro, $limit, $offset);
        if (is_array($arrResult['cdrs']) && $total > 0) {
            foreach ($arrResult['cdrs'] as $key => $value) {
                $arrTmp[0] = date("d-m-Y H:i:s", strtotime($value[0]));
                $arrTmp[1] = $value[1];
                $arrTmp[2] = $value[11];
                $arrTmp[3] = $value[3];
                $arrTmp[4] = $value[9];
                $arrTmp[5] = $value[5];
                $iDuracion = $value[8];
                $iSec = $iDuracion % 60;
                $iDuracion = (int) (($iDuracion - $iSec) / 60);
                $iMin = $iDuracion % 60;
                $iDuracion = (int) (($iDuracion - $iMin) / 60);
                $sTiempo = "{$value[6]}s";
                if ($value[6] >= 60) {
                    if ($iDuracion > 0) {
                        $sTiempo .= " ({$iDuracion}h {$iMin}m {$iSec}s)";
                    } elseif ($iMin > 0) {
                        $sTiempo .= " ({$iMin}m {$iSec}s)";
                    }
                }
                $arrTmp[7] = $sTiempo;
                $arrData[] = $arrTmp;
            }
        }
        if (!is_array($arrResult)) {
            $smarty->assign(array('mb_title' => _tr('ERROR'), 'mb_message' => $oCDR->errMsg));
        }
    } else {
        $limit = 20;
        $oGrid->setLimit($limit);
        $oGrid->setTotal($total);
        $offset = $oGrid->calculateOffset();
        $arrResult = $oCDR->listarCDRs($paramFiltro, $limit, $offset);
        $arrColumns = array('STT', _tr("Date"), _tr("Source"), _tr("Destination"), _tr("Src. Channel"), _tr("Dst. Channel"), _tr("Status"), _tr("Duration"));
        $oGrid->setColumns($arrColumns);
        if (is_array($arrResult['cdrs']) && $total > 0) {
            $index = 0;
            foreach ($arrResult['cdrs'] as $key => $value) {
                $arrTmp[0] = $index;
                $arrTmp[1] = date("d-m-Y H:i:s", strtotime($value[0]));
                $arrTmp[2] = $value[1];
                $arrTmp[3] = $value[2];
                $arrTmp[4] = channel_lookup($pDB_asterisk, $value[3]);
                $arrTmp[5] = channel_lookup($pDB_asterisk, $value[4]);
                $arrTmp[6] = $value[5];
                $iDuracion = $value[8];
                $iSec = $iDuracion % 60;
                $iDuracion = (int) (($iDuracion - $iSec) / 60);
                $iMin = $iDuracion % 60;
                $iDuracion = (int) (($iDuracion - $iMin) / 60);
                $sTiempo = "{$value[8]}s";
                if ($value[7] >= 60) {
                    if ($iDuracion > 0) {
                        $sTiempo .= " ({$iDuracion}h {$iMin}m {$iSec}s)";
                    } elseif ($iMin > 0) {
                        $sTiempo .= " ({$iMin}m {$iSec}s)";
                    }
                }
                $arrTmp[7] = $sTiempo;
                $arrData[] = $arrTmp;
                $index++;
            }
        }
        if (!is_array($arrResult)) {
            $smarty->assign(array('mb_title' => _tr('ERROR'), 'mb_message' => $oCDR->errMsg));
        }
    }
    $oGrid->setData($arrData);
    $smarty->assign("SHOW", _tr("Show"));
    $oGrid->showFilter($htmlFilter);
    $content = $oGrid->fetchGrid();
    return $content;
}
Esempio n. 3
0
function deleteCDR($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $credentials)
{
    //solo el superadmin tiene permito borrar resgistros del CDR
    if ($credentials['userlevel'] != 'superadmin') {
        $smarty->assign("mb_title", _tr('Error'));
        $smarty->assign("mb_message", _tr("You are not authorized to perform this action"));
        return reportCDR($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $credentials);
    }
    $arrCDR = getParameter("crdDel");
    if (!is_array($arrCDR) || count($arrCDR) == 0) {
        $smarty->assign("mb_title", _tr('Error'));
        $smarty->assign("mb_message", _tr("You must select at least one record"));
        return reportCDR($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $credentials);
    }
    $pCDR = new paloSantoCDR($pDB);
    $pDB->beginTransaction();
    if ($pCDR->borrarCDRs($arrCDR)) {
        $pDB->commit();
        $smarty->assign("mb_title", _tr('Message'));
        $smarty->assign("mb_message", _tr("CDR record(s) were deleted successfully"));
    } else {
        $pDB->rollBack();
        $smarty->assign("mb_title", _tr('Error'));
        $smarty->assign("mb_message", $pCDR->errMsg);
    }
    return reportCDR($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $credentials);
}