function _moduleContent(&$smarty, $module_name) { //include module files include_once "modules/{$module_name}/configs/default.conf.php"; include_once "modules/{$module_name}/libs/paloSantoCallsDetail.class.php"; include_once "modules/agent_console/getinfo.php"; global $arrConf; load_language_module($module_name); //folder path for custom templates $base_dir = dirname($_SERVER['SCRIPT_FILENAME']); $templates_dir = isset($arrConfig['templates_dir']) ? $arrConfig['templates_dir'] : 'themes'; $local_templates_dir = "{$base_dir}/modules/{$module_name}/" . $templates_dir . '/' . $arrConf['theme']; // added by Tri Do $sAction = getParameter('action'); switch ($sAction) { case 'viewNote': return viewNote(); break; case 'viewDelivery': return view_delivery(); break; default: break; } // Cadenas estáticas de Smarty $smarty->assign(array("Filter" => _tr('Filter'), "SHOW" => _tr("Show"))); $bElastixNuevo = method_exists('paloSantoGrid', 'setURL'); // Variables iniciales para posición de grid $offset = 0; $limit = 50; $total = 0; // Para poder consultar las colas activas $pConfig = new paloConfig("/etc", "amportal.conf", "=", "[[:space:]]*=[[:space:]]*"); $ampconfig = $pConfig->leer_configuracion(false); $ampdsn = $ampconfig['AMPDBENGINE']['valor'] . "://" . $ampconfig['AMPDBUSER']['valor'] . ":" . $ampconfig['AMPDBPASS']['valor'] . "@" . $ampconfig['AMPDBHOST']['valor'] . "/asterisk"; $oQueue = new paloQueue($ampdsn); $listaColas = $oQueue->getQueue(); if (!is_array($listaColas)) { $smarty->assign("mb_title", _tr("Error when connecting to database")); $smarty->assign("mb_message", $oQueue->errMsg); } // Para poder consultar los agentes de campañas $pDB = new paloDB($cadena_dsn); $oCallsDetail = new paloSantoCallsDetail($pDB); $listaAgentes = $oCallsDetail->getAgents(); // Para llenar el select de agentes $urlVars = array('menu' => $module_name); $arrFormElements = createFieldFilter($listaAgentes, $listaColas); $oFilterForm = new paloForm($smarty, $arrFormElements); // Validar y aplicar las variables de filtro $paramLista = NULL; $paramFiltro = array(); foreach (array('date_start', 'date_end', 'calltype', 'agent', 'queue', 'phone') as $k) { $paramFiltro[$k] = getParameter($k); } if (!isset($paramFiltro['date_start'])) { $paramFiltro['date_start'] = date("d M Y"); } if (!isset($paramFiltro['date_end'])) { $paramFiltro['date_end'] = date("d M Y"); } if (!$oFilterForm->validateForm($paramFiltro)) { // Hay un error al validar las variables del filtro $smarty->assign("mb_title", _tr("Validation Error")); $arrErrores = $oFilterForm->arrErroresValidacion; $strErrorMsg = "<b>" . _tr('The following fields contain errors') . ":</b><br>"; $strErrorMsg = implode(', ', array_keys($arrErrores)); $smarty->assign("mb_message", $strErrorMsg); } else { $urlVars = array_merge($urlVars, $paramFiltro); $paramLista = $paramFiltro; $paramLista['date_start'] = translateDate($paramFiltro['date_start']) . " 00:00:00"; $paramLista['date_end'] = translateDate($paramFiltro['date_end']) . " 23:59:59"; } $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $paramFiltro); // Inicio de objeto grilla y asignación de filtro $oGrid = new paloSantoGrid($smarty); $oGrid->enableExport(); // enable export. $oGrid->showFilter($htmlFilter); $bExportando = $bElastixNuevo ? $oGrid->isExportAction() : isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes' || isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' || isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes'; // Ejecutar la consulta con las variables ya validadas $arrData = array(); $total = 0; if (is_array($paramLista)) { $total = $oCallsDetail->contarDetalleLlamadas($paramLista); if (is_null($total)) { $smarty->assign("mb_title", _tr("Error when connecting to database")); $smarty->assign("mb_message", $oCallsDetail->errMsg); $total = 0; } else { // Habilitar la exportación de todo el contenido consultado if ($bExportando) { $limit = $total; } // Calcular el offset de la petición de registros if ($bElastixNuevo) { $oGrid->setLimit($limit); $oGrid->setTotal($total); $offset = $oGrid->calculateOffset(); } else { // Si se quiere avanzar a la sgte. pagina if (isset($_GET['nav']) && $_GET['nav'] == "end") { // Mejorar el sgte. bloque. if ($total % $limit == 0) { $offset = $total - $limit; } else { $offset = $total - $total % $limit; } } // Si se quiere avanzar a la sgte. pagina if (isset($_GET['nav']) && $_GET['nav'] == "next") { $offset = $_GET['start'] + $limit - 1; } // Si se quiere retroceder if (isset($_GET['nav']) && $_GET['nav'] == "previous") { $offset = $_GET['start'] - $limit - 1; } } // Ejecutar la consulta de los datos en el offset indicado $recordset = $oCallsDetail->leerDetalleLlamadas($paramLista, $limit, $offset); // add STT for ($i = 0; $i < count($recordset); $i++) { $recordset[$i]['stt'] = $i + 1; } if (!is_array($recordset)) { $smarty->assign("mb_title", _tr("Error when connecting to database")); $smarty->assign("mb_message", $oCallsDetail->errMsg); $total = 0; } else { function _calls_detail_map_recordset($cdr) { $mapaEstados = array('abandonada' => 'Bỏ nhỡ', 'Abandoned' => 'Bỏ nhỡ', 'terminada' => 'Đã nghe', 'Success' => 'Đã nghe', 'fin-monitoreo' => _tr('End Monitor'), 'Failure' => _tr('Failure'), 'NoAnswer' => _tr('NoAnswer'), 'OnQueue' => _tr('OnQueue'), 'Placing' => _tr('Placing'), 'Ringing' => _tr('Ringing'), 'ShortCall' => _tr('ShortCall'), 'activa' => 'Đang gọi'); return array($cdr['stt'], $cdr[0], htmlentities($cdr[1], ENT_COMPAT, "UTF-8"), substr($cdr[2], 0, 10), substr($cdr[2], 11, 8), substr($cdr[3], 0, 10), substr($cdr[3], 11, 8), is_null($cdr[4]) ? '-' : formatoSegundos($cdr[4]), is_null($cdr[5]) ? '-' : formatoSegundos($cdr[5]), $cdr[6], $cdr[8], $cdr[9], isset($mapaEstados[$cdr[10]]) ? $mapaEstados[$cdr[10]] : _tr($cdr[10]), is_null($cdr[12]) || trim($cdr[12] == '') ? '' : '<a href="javascript:void(0)" onclick="view_note(\'' . $cdr[11] . '\')">Xem</a>'); } $arrData = array_map('_calls_detail_map_recordset', $recordset); } } } $arrColumnas = array('STT', 'Số Agent', 'Nhân viên', _tr("Start Date"), _tr("Start Time"), _tr("End Date"), _tr("End Time"), "Thời lượng", _tr("Thời gian chờ"), _tr("Queue"), _tr("Số điện thoại"), _tr("Chuyển máy"), _tr("Status"), 'Nội dung'); if ($bElastixNuevo) { $oGrid->setURL(construirURL($urlVars, array("nav", "start"))); $oGrid->setData($arrData); $oGrid->setColumns($arrColumnas); $oGrid->setTitle('Chi tiết cuộc gọi Call Center'); $oGrid->pagingShow(true); $oGrid->setNameFile_Export(_tr("Calls Detail")); return $oGrid->fetchGrid(); } else { global $arrLang; $url = construirURL($urlVars, array("nav", "start")); function _map_name($s) { return array('name' => $s); } $arrGrid = array("title" => _tr("Calls Detail"), "url" => $url, "icon" => "images/user.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $offset + $limit <= $total ? $offset + $limit : $total, "total" => $total, "columns" => array_map('_map_name', $arrColumnas)); if (isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes' && method_exists($oGrid, 'fetchGridPDF')) { return $oGrid->fetchGridPDF($arrGrid, $arrData); } if (isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' && method_exists($oGrid, 'fetchGridXLS')) { return $oGrid->fetchGridXLS($arrGrid, $arrData); } if ($bExportando) { header("Cache-Control: private"); header("Pragma: cache"); // Se requiere para HTTPS bajo IE6 header('Content-disposition: inline; filename="calls_detail.csv"'); header("Content-Type: text/csv; charset=UTF-8"); } if ($bExportando) { return $oGrid->fetchGridCSV($arrGrid, $arrData); } $sContenido = $oGrid->fetchGrid($arrGrid, $arrData, $arrLang); if (strpos($sContenido, '<form') === FALSE) { $sContenido = "<form method=\"POST\" style=\"margin-bottom:0;\" action=\"{$url}\">{$sContenido}</form>"; } return $sContenido; } }
function reportReportCall($smarty, $module_name, $local_templates_dir, &$pDB_cdr, &$pDB_billing, $arrConf, $arrLang) { $pReportCall = new paloSantoReportCall($pDB_cdr, $pDB_billing); //PARAMETERS $type = getParameter("option_fil"); $value_tmp = getParameter("value_fil"); $date_ini_tmp = getParameter("date_from"); $date_end_tmp = getParameter("date_to"); $order_by_tmp = getParameter("order_by"); $order_type_tmp = getParameter("order_type"); $action = getParameter("nav"); $start = getParameter("start"); $value = isset($value_tmp) ? $value_tmp : ""; $order_by = isset($order_by_tmp) ? $order_by_tmp : 1; $order_type = isset($order_type_tmp) ? $order_type_tmp : "asc"; $date_from = isset($date_ini_tmp) ? $date_ini_tmp : date("d M Y"); $date_to = isset($date_end_tmp) ? $date_end_tmp : date("d M Y"); $date_ini = translateDate($date_from) . " 00:00:00"; $date_end = translateDate($date_to) . " 23:59:59"; //********************************** //begin grid parameters $oGrid = new paloSantoGrid($smarty); $limit = 40; $total = $pReportCall->ObtainNumberDevices($type, $value); $oGrid->setLimit($limit); $oGrid->setTotal($total); $oGrid->calculatePagination($action, $start); $offset = $oGrid->getOffsetValue(); $end = $oGrid->getEnd(); $urlFields = array('menu' => $module_name, 'option_fil' => $type, 'value_fil' => $value, 'date_from' => $date_from, 'date_to' => $date_to); $url = construirUrl($urlFields, array('nav', 'start')); $urlFields['order_by'] = $order_by; $urlFields['order_type'] = $order_type; $smarty->assign("order_by", $order_by); $smarty->assign("order_type", $order_type); $arrData = null; $arrResult = $pReportCall->ObtainReportCall($limit, $offset, $date_ini, $date_end, $type, $value, $order_by, $order_type); $order_type = $order_type == "desc" ? "asc" : "desc"; if (is_array($arrResult) && $total > 0) { foreach ($arrResult as $key => $val) { $ext = $val['extension']; $arrTmp[0] = $ext; $arrTmp[1] = $val['user_name']; $arrTmp[2] = $val['num_incoming_call']; $arrTmp[3] = $val['num_outgoing_call']; $arrTmp[4] = "<label style='color: green;' title='{$val['duration_incoming_call']} {$arrLang['seconds']}'>" . $pReportCall->Sec2HHMMSS($val['duration_incoming_call']) . "</label>"; $arrTmp[5] = "<label style='color: green;' title='{$val['duration_outgoing_call']} {$arrLang['seconds']}'>" . $pReportCall->Sec2HHMMSS($val['duration_outgoing_call']) . "</label>"; $arrTmp[6] = "<a href='javascript: popup_ventana(\"?menu={$module_name}&action=graph&rawmode=yes&ext={$ext}&dini={$date_ini}&dfin={$date_end}\");'>" . "" . $arrLang['Call Details'] . "</a>"; $arrData[] = $arrTmp; } } $img = "<img src='images/flecha_{$order_type}.png' border='0' align='absmiddle'>"; $leyend_1 = "<a class='link_summary_off' href='{$url}&order_by=1&order_type=asc'>{$arrLang["Extension"]}</a>"; $leyend_2 = "<a class='link_summary_off' href='{$url}&order_by=2&order_type=asc'>{$arrLang["User name"]}</a>"; $leyend_3 = "<a class='link_summary_off' href='{$url}&order_by=3&order_type=asc'>{$arrLang["Num. Incoming Calls"]}</a>"; $leyend_4 = "<a class='link_summary_off' href='{$url}&order_by=4&order_type=asc'>{$arrLang["Num. Outgoing Calls"]}</a>"; $leyend_5 = "<a class='link_summary_off' href='{$url}&order_by=5&order_type=asc'>{$arrLang["Sec. Incoming Calls"]}</a>"; $leyend_6 = "<a class='link_summary_off' href='{$url}&order_by=6&order_type=asc'>{$arrLang["Sec. Outgoing Calls"]}</a>"; if ($order_by == 1) { $leyend_1 = "<a class='link_summary_on' href='{$url}&order_by=1&order_type={$order_type}'>{$arrLang["Extension"]} {$img}</a>"; } else { if ($order_by == 2) { $leyend_2 = "<a class='link_summary_on' href='{$url}&order_by=2&order_type={$order_type}'>{$arrLang["User name"]} {$img}</a>"; } else { if ($order_by == 3) { $leyend_3 = "<a class='link_summary_on' href='{$url}&order_by=3&order_type={$order_type}'>{$arrLang["Num. Incoming Calls"]} {$img}</a>"; } else { if ($order_by == 4) { $leyend_4 = "<a class='link_summary_on' href='{$url}&order_by=4&order_type={$order_type}'>{$arrLang["Num. Outgoing Calls"]} {$img}</a>"; } else { if ($order_by == 5) { $leyend_5 = "<a class='link_summary_on' href='{$url}&order_by=5&order_type={$order_type}'>{$arrLang["Sec. Incoming Calls"]} {$img}</a>"; } else { if ($order_by == 6) { $leyend_6 = "<a class='link_summary_on' href='{$url}&order_by=6&order_type={$order_type}'>{$arrLang["Sec. Outgoing Calls"]} {$img}</a>"; } } } } } } $arrGrid = array("title" => $arrLang["Summary by Extension"], "icon" => "images/list.png", "width" => "100%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $end, "total" => $total, "url" => $urlFields, "columns" => array(0 => array("name" => $leyend_1, "property1" => ""), 1 => array("name" => $leyend_2, "property1" => ""), 2 => array("name" => $leyend_3, "property1" => ""), 3 => array("name" => $leyend_4, "property1" => ""), 4 => array("name" => $leyend_5, "property1" => ""), 5 => array("name" => $leyend_6, "property1" => ""), 6 => array("name" => $arrLang["Details"], "property1" => ""))); //begin section filter $arrFormFilterReportCall = createFieldForm($arrLang); $oFilterForm = new paloForm($smarty, $arrFormFilterReportCall); $_POST['option_fil'] = $type; $_POST['value_fil'] = $value; $_POST['date_from'] = $date_from; $_POST['date_to'] = $date_to; $smarty->assign("SHOW", $arrLang["Show"]); if ($_POST["date_from"] === "") { $_POST["date_from"] = " "; } if ($_POST['date_to'] === "") { $_POST['date_to'] = " "; } $oGrid->addFilterControl(_tr("Filter applied: ") . _tr("Start Date") . " = " . $date_from . ", " . _tr("End Date") . " = " . $date_to, $_POST, array("date_from" => date("d M Y"), "date_to" => date("d M Y")), true); $valueType = ""; if (!is_null($type)) { if ($type == "Ext") { $valueType = _tr("Extension"); } else { $valueType = _tr("User"); } } $oGrid->addFilterControl(_tr("Filter applied: ") . $valueType . " = " . $value, $_POST, array("option_fil" => "Ext", "value_fil" => "")); $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_POST); //end section filter $oGrid->showFilter(trim($htmlFilter)); $contenidoModulo = $oGrid->fetchGrid($arrGrid, $arrData, $arrLang); return $contenidoModulo; }
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; }
function reportReportsBreak($smarty, $module_name, $local_templates_dir, &$pDB) { // Obtener rango de fechas de consulta. Si no existe, se asume día de hoy $sFechaInicio = date('d M Y'); if (isset($_GET['txt_fecha_init'])) { $sFechaInicio = $_GET['txt_fecha_init']; } if (isset($_POST['txt_fecha_init'])) { $sFechaInicio = $_POST['txt_fecha_init']; } $sFechaFinal = date('d M Y'); if (isset($_GET['txt_fecha_end'])) { $sFechaFinal = $_GET['txt_fecha_end']; } if (isset($_POST['txt_fecha_end'])) { $sFechaFinal = $_POST['txt_fecha_end']; } $arrFilterExtraVars = array("txt_fecha_init" => $sFechaInicio, "txt_fecha_end" => $sFechaFinal); $arrFormElements = createFieldFilter(); $oFilterForm = new paloForm($smarty, $arrFormElements); // Validación de las fechas recogidas if (!$oFilterForm->validateForm($arrFilterExtraVars)) { $smarty->assign("mb_title", _tr("Validation Error")); $arrErrores = $oFilterForm->arrErroresValidacion; $strErrorMsg = '<b>' . _tr('The following fields contain errors') . '</b><br/>'; foreach ($arrErrores as $k => $v) { $strErrorMsg .= "{$k}, "; } $smarty->assign("mb_message", $strErrorMsg); $arrFilterExtraVars = array("txt_fecha_init" => date('d M Y'), "txt_fecha_end" => date('d M Y')); } $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $arrFilterExtraVars); // Obtener fechas en formato yyyy-mm-dd $sFechaInicio = translateDate($arrFilterExtraVars['txt_fecha_init']); $sFechaFinal = translateDate($arrFilterExtraVars['txt_fecha_end']); $oReportsBreak = new paloSantoReportsBreak($pDB); //begin grid parameters $bElastixNuevo = method_exists('paloSantoGrid', 'setURL'); $oGrid = new paloSantoGrid($smarty); $oGrid->enableExport(); // enable export. $oGrid->showFilter($htmlFilter); $arrColumnas = array(_tr('Agent Number'), _tr('Agent Name')); $bExportando = $bElastixNuevo ? $oGrid->isExportAction() : isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes' || isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' || isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes'; $datosBreaks = $oReportsBreak->getReportesBreak($sFechaInicio, $sFechaFinal); $mapa = array(); // Columna del break dado su ID $sTagInicio = !$bExportando ? '<b>' : ''; $sTagFinal = $sTagInicio != '' ? '</b>' : ''; $filaTotales = array($sTagInicio . _tr('Total') . $sTagFinal, ''); foreach ($datosBreaks['breaks'] as $idBreak => $sNombreBreak) { $mapa[$idBreak] = count($arrColumnas); $arrColumnas[] = $sNombreBreak; $filaTotales[] = 0; // Total de segundos usado por todos los agentes en este break } $mapa['TOTAL'] = count($arrColumnas); $filaTotales[] = 0; // Total de segundos usado por todos los agentes en todos los breaks $arrColumnas[] = _tr('Total'); $arrData = array(); foreach ($datosBreaks['reporte'] as $infoAgente) { $filaAgente = array($infoAgente['numero_agente'], $infoAgente['nombre_agente']); $iTotalAgente = 0; // Total de segundos usados por agente en breaks // Valor inicial de todos los breaks es 0 segundos foreach (array_keys($datosBreaks['breaks']) as $idBreak) { $filaAgente[$mapa[$idBreak]] = '00:00:00'; } // Asignar duración del break para este agente y break foreach ($infoAgente['breaks'] as $tuplaBreak) { $sTagInicio = !$bExportando && $tuplaBreak['duracion'] > 0 ? '<font color="green">' : ''; $sTagFinal = $sTagInicio != '' ? '</font>' : ''; $filaAgente[$mapa[$tuplaBreak['id_break']]] = $sTagInicio . formatoSegundos($tuplaBreak['duracion']) . $sTagFinal; $iTotalAgente += $tuplaBreak['duracion']; $filaTotales[$mapa[$tuplaBreak['id_break']]] += $tuplaBreak['duracion']; $filaTotales[$mapa['TOTAL']] += $tuplaBreak['duracion']; } // Total para todos los breaks de este agente $filaAgente[$mapa['TOTAL']] = formatoSegundos($iTotalAgente); $arrData[] = $filaAgente; } $sTagInicio = !$bExportando ? '<b>' : ''; $sTagFinal = $sTagInicio != '' ? '</b>' : ''; foreach ($mapa as $iPos) { $filaTotales[$iPos] = $sTagInicio . formatoSegundos($filaTotales[$iPos]) . $sTagFinal; } $arrData[] = $filaTotales; if ($bElastixNuevo) { $oGrid->setURL(construirURL($arrFilterExtraVars)); $oGrid->setData($arrData); $oGrid->setColumns($arrColumnas); $oGrid->setTitle(_tr("Reports Break")); $oGrid->pagingShow(false); $oGrid->setNameFile_Export(_tr("Reports Break")); $smarty->assign("SHOW", _tr("Show")); return $oGrid->fetchGrid(); } else { $url = construirURL($arrFilterExtraVars); $offset = 0; $total = count($datosBreaks['reporte']) + 1; $limit = $total; function _map_name($s) { return array('name' => $s); } $arrGrid = array("title" => _tr('Reports Break'), "url" => $url, "icon" => "images/list.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $offset + $limit <= $total ? $offset + $limit : $total, "total" => $total, "columns" => array_map('_map_name', $arrColumnas)); if (isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes' && method_exists($oGrid, 'fetchGridPDF')) { return $oGrid->fetchGridPDF($arrGrid, $arrData); } if (isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' && method_exists($oGrid, 'fetchGridXLS')) { return $oGrid->fetchGridXLS($arrGrid, $arrData); } if ($bExportando) { $title = $sFechaInicio . "-" . $sFechaFinal; header("Cache-Control: private"); header("Pragma: cache"); header('Content-Type: text/csv; charset=utf-8; header=present'); header("Content-disposition: attachment; filename=\"" . $title . ".csv\""); } if ($bExportando) { return $oGrid->fetchGridCSV($arrGrid, $arrData); } $sContenido = $oGrid->fetchGrid($arrGrid, $arrData); if (strpos($sContenido, '<form') === FALSE) { $sContenido = "<form method=\"POST\" style=\"margin-bottom:0;\" action=\"{$url}\">{$sContenido}</form>"; } return $sContenido; } }
function _moduleContent(&$smarty, $module_name) { include_once "libs/paloSantoGrid.class.php"; include_once "libs/paloSantoConfig.class.php"; include_once "libs/paloSantoACL.class.php"; include_once "libs/paloSantoForm.class.php"; require_once "libs/misc.lib.php"; include_once "lib/paloSantoVoiceMail.class.php"; //include module files include_once "modules/{$module_name}/configs/default.conf.php"; $lang = get_language(); $base_dir = dirname($_SERVER['SCRIPT_FILENAME']); $lang_file = "modules/{$module_name}/lang/{$lang}.lang"; if (file_exists("{$base_dir}/{$lang_file}")) { include_once "{$lang_file}"; } else { include_once "modules/{$module_name}/lang/en.lang"; } //global variables global $arrConf; global $arrConfModule; global $arrLang; global $arrLangModule; $arrConf = array_merge($arrConf, $arrConfModule); $arrLang = array_merge($arrLang, $arrLangModule); //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']; //segun el usuario que esta logoneado consulto si tiene asignada extension para buscar los voicemails $pDB = new paloDB($arrConf['elastix_dsn']['acl']); $pConfig = new paloConfig("/etc", "amportal.conf", "=", "[[:space:]]*=[[:space:]]*"); $arrAMP = $pConfig->leer_configuracion(false); $dsnAsterisk = $arrAMP['AMPDBENGINE']['valor'] . "://" . $arrAMP['AMPDBUSER']['valor'] . ":" . $arrAMP['AMPDBPASS']['valor'] . "@" . $arrAMP['AMPDBHOST']['valor'] . "/asterisk"; $pDB_ast = new paloDB($dsnAsterisk); if (!empty($pDB->errMsg)) { echo "ERROR DE DB: {$pDB->errMsg} <br>"; } $arrData = array(); $pACL = new paloACL($pDB); if (!empty($pACL->errMsg)) { echo "ERROR DE ACL: {$pACL->errMsg} <br>"; } $arrVoiceData = array(); $inicio = $fin = $total = 0; $extension = $pACL->getUserExtension($_SESSION['elastix_user']); $ext = $extension; $esAdministrador = $pACL->isUserAdministratorGroup($_SESSION['elastix_user']); $bandCustom = true; if (is_null($ext) || $ext == "") { $bandCustom = false; if (!$esAdministrador) { $smarty->assign("mb_message", "<b>" . $arrLang["contact_admin"] . "</b>"); return ""; } } if ($esAdministrador) { $extension = "[[:digit:]]+"; } $smarty->assign("menu", "voicemail"); $smarty->assign("Filter", $arrLang['Show']); //formulario para el filtro $arrFormElements = createFieldFormVoiceList($arrLang); $oFilterForm = new paloForm($smarty, $arrFormElements); // Por omision las fechas toman el sgte. valor (la fecha de hoy) $date_start = date("Y-m-d") . " 00:00:00"; $date_end = date("Y-m-d") . " 23:59:59"; $dateStartFilter = getParameter('date_start'); $dateEndFilter = getParameter('date_end'); $report = false; if (getParameter('filter')) { if ($oFilterForm->validateForm($_POST)) { // Exito, puedo procesar los datos ahora. $date_start = translateDate($dateStartFilter) . " 00:00:00"; $date_end = translateDate($dateEndFilter) . " 23:59:59"; $arrFilterExtraVars = array("date_start" => $dateStartFilter, "date_end" => $dateEndFilter); } else { // Error $smarty->assign("mb_title", $arrLang["Validation Error"]); $arrErrores = $oFilterForm->arrErroresValidacion; $strErrorMsg = "<b>{$arrLang['The following fields contain errors']}:</b><br>"; foreach ($arrErrores as $k => $v) { $strErrorMsg .= "{$k}, "; } $strErrorMsg .= ""; $smarty->assign("mb_message", $strErrorMsg); } if ($dateStartFilter == "") { $dateStartFilter = " "; } if ($dateEndFilter == "") { $dateEndFilter = " "; } //se añade control a los filtros $report = true; $arrDate = array('date_start' => $dateStartFilter, 'date_end' => $dateEndFilter); $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_POST); } else { if (isset($dateStartFilter) and isset($dateEndFilter)) { $report = true; $date_start = translateDate($dateStartFilter) . " 00:00:00"; $date_end = translateDate($dateEndFilter) . " 23:59:59"; $arrDate = array('date_start' => $dateStartFilter, 'date_end' => $dateEndFilter); $arrFilterExtraVars = array("date_start" => $dateStartFilter, "date_end" => $dateEndFilter); $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_GET); } else { $report = true; //se añade control a los filtros $arrDate = array('date_start' => date("d M Y"), 'date_end' => date("d M Y")); $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", array('date_start' => date("d M Y"), 'date_end' => date("d M Y"))); } } $oGrid = new paloSantoGrid($smarty); if ($report) { $oGrid->addFilterControl(_tr("Filter applied ") . _tr("Start Date") . " = " . $arrDate['date_start'] . ", " . _tr("End Date") . " = " . $arrDate['date_end'], $arrDate, array('date_start' => date("d M Y"), 'date_end' => date("d M Y")), true); } if (getParameter('submit_eliminar')) { borrarVoicemails(); if ($oFilterForm->validateForm($_POST)) { // Exito, puedo procesar los datos ahora. $date_start = translateDate($_POST['date_start']) . " 00:00:00"; $date_end = translateDate($_POST['date_end']) . " 23:59:59"; $arrFilterExtraVars = array("date_start" => $_POST['date_start'], "date_end" => $_POST['date_end']); } $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_POST); } if (getParameter('config')) { if (!(is_null($ext) || $ext == "")) { return form_config($smarty, $module_name, $local_templates_dir, $arrLang, $ext, $pDB_ast); } } if (getParameter('save')) { if (!save_config($smarty, $module_name, $local_templates_dir, $arrLang, $ext, $pDB_ast)) { return form_config($smarty, $module_name, $local_templates_dir, $arrLang, $ext, $pDB_ast); } } if (getParameter('action') == "display_record") { $file = getParameter("name"); $ext = getParameter("ext"); $user = isset($_SESSION['elastix_user']) ? $_SESSION['elastix_user'] : ""; $extension = $pACL->getUserExtension($user); $esAdministrador = $pACL->isUserAdministratorGroup($user); $path = "/var/spool/asterisk/voicemail/default"; $voicemailPath = "{$path}/{$ext}/INBOX/" . base64_decode($file); $tmpfile = basename($voicemailPath); $filetmp = "{$path}/{$ext}/INBOX/{$tmpfile}"; if (!is_file($filetmp)) { die("<b>404 " . $arrLang["no_file"] . "</b>"); } if (!$esAdministrador) { if ($extension != $ext) { die("<b>404 " . $arrLang["no_file"] . "</b>"); } $voicemailPath = "{$path}/{$extension}/INBOX/" . base64_decode($file); } if (isset($file) && preg_match("/^[[:alpha:]]+[[:digit:]]+\\.(wav|WAV|Wav|mp3|gsm)\$/", base64_decode($file))) { if (!is_file($voicemailPath)) { die("<b>404 " . $arrLang["no_file"] . "</b>"); } $sContenido = ""; $name = basename($voicemailPath); $format = substr(strtolower($name), -3); // This will set the Content-Type to the appropriate setting for the file $ctype = ''; switch ($format) { case "mp3": $ctype = "audio/mpeg"; break; case "wav": $ctype = "audio/x-wav"; break; case "Wav": $ctype = "audio/x-wav"; break; case "WAV": $ctype = "audio/x-wav"; break; case "gsm": $ctype = "audio/x-gsm"; break; // not downloadable // not downloadable default: die("<b>404 " . $arrLang["no_file"] . "</b>"); break; } if ($sContenido == "") { $session_id = session_id(); } $sContenido = <<<contenido <embed src='index.php?menu={$module_name}&action=download&ext={$ext}&name={$file}&rawmode=yes&elastixSession={$session_id}' width=300, height=20 autoplay=true loop=false type="{$ctype}"></embed><br> contenido; $smarty->assign("CONTENT", $sContenido); $smarty->display("_common/popup.tpl"); } else { die("<b>404 " . $arrLang["no_file"] . "</b>"); } return; } if (getParameter('action') == "download") { $user = isset($_SESSION['elastix_user']) ? $_SESSION['elastix_user'] : ""; $extension = $pACL->getUserExtension($user); $esAdministrador = $pACL->isUserAdministratorGroup($user); $record = getParameter("name"); $ext = getParameter("ext"); if (!preg_match("/^[[:digit:]]+\$/", $ext)) { Header("HTTP/1.1 404 Not Found"); die("<b>404 " . $arrLang["no_file"] . "</b>"); } $record = base64_decode($record); $path = "/var/spool/asterisk/voicemail/default"; $voicemailPath = "{$path}/{$ext}/INBOX/" . $record; //"$path/$record"; $tmpfile = basename($voicemailPath); $filetmp = "{$path}/{$ext}/INBOX/{$tmpfile}"; if (!is_file($filetmp)) { die("<b>404 " . $arrLang["no_file"] . "</b>"); } if (!$esAdministrador) { if ($extension != $ext) { Header("HTTP/1.1 404 Not Found"); die("<b>404 " . $arrLang["no_extension"] . "</b>"); } $voicemailPath = "{$path}/{$extension}/INBOX/" . $record; } if (isset($record) && preg_match("/^[[:alpha:]]+[[:digit:]]+\\.(wav|WAV|Wav|mp3|gsm)\$/", $record)) { // See if the file exists if (!is_file($voicemailPath)) { Header("HTTP/1.1 404 Not Found"); die("<b>404 " . $arrLang["no_file"] . "</b>"); } // Gather relevent info about file $size = filesize($voicemailPath); $name = basename($voicemailPath); //$extension = strtolower(substr(strrchr($name,"."),1)); $extension = substr(strtolower($name), -3); // This will set the Content-Type to the appropriate setting for the file $ctype = ''; switch ($extension) { case "mp3": $ctype = "audio/mpeg"; break; case "wav": $ctype = "audio/x-wav"; break; case "Wav": $ctype = "audio/x-wav"; break; case "WAV": $ctype = "audio/x-wav"; break; case "gsm": $ctype = "audio/x-gsm"; break; // not downloadable // not downloadable default: die("<b>404 " . $arrLang["no_file"] . "</b>"); break; } // need to check if file is mislabeled or a liar. $fp = fopen($voicemailPath, "rb"); if ($size && $ctype && $fp) { header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: public"); header("Content-Description: wav file"); header("Content-Type: " . $ctype); header("Content-Disposition: attachment; filename=" . $name); header("Content-Transfer-Encoding: binary"); header("Content-length: " . $size); fpassthru($fp); } } else { Header("HTTP/1.1 404 Not Found"); die("<b>404 " . $arrLang["no_file"] . "</b>"); } return; } $end = 0; $url = array('menu' => $module_name); //si tiene extension consulto sino, muestro un mensaje de que no tiene asociada extension $archivos = array(); if (!(is_null($ext) || $ext == "") || $esAdministrador) { if (is_null($ext) || $ext == "") { $smarty->assign("mb_message", "<b>" . $arrLang["no_extension_assigned"] . "</b>"); } $path = "/var/spool/asterisk/voicemail/default"; $folder = "INBOX"; if ($esAdministrador) { if ($handle = opendir($path)) { while (false !== ($dir = readdir($handle))) { if ($dir != "." && $dir != ".." && ereg($extension, $dir, $regs) && is_dir($path . "/" . $dir)) { $directorios[] = $dir; } } } } else { $directorios[] = $extension; } //if($esAdministrador) $arrData = array(); foreach ($directorios as $directorio) { $voicemailPath = "{$path}/{$directorio}/{$folder}"; if (file_exists($voicemailPath)) { if ($handle = opendir($voicemailPath)) { $bExito = true; while (false !== ($file = readdir($handle))) { //no tomar en cuenta . y .. //buscar los archivos de texto (txt) que son los que contienen los datos de las llamadas if ($file != "." && $file != ".." && ereg("(.+)\\.[txt|TXT]", $file, $regs)) { //leer la info del archivo $pConfig = new paloConfig($voicemailPath, $file, "=", "[[:space:]]*=[[:space:]]*"); $arrVoiceMailDes = array(); $arrVoiceMailDes = $pConfig->leer_configuracion(false); //verifico que tenga datos if (is_array($arrVoiceMailDes) && count($arrVoiceMailDes) > 0 && isset($arrVoiceMailDes['origtime']['valor'])) { //uso las fechas del filtro //si la fecha de llamada esta dentro del rango, la muestro $fecha = date("Y-m-d", $arrVoiceMailDes['origtime']['valor']); $hora = date("H:i:s", $arrVoiceMailDes['origtime']['valor']); if (strtotime("{$fecha} {$hora}") <= strtotime($date_end) && strtotime("{$fecha} {$hora}") >= strtotime($date_start)) { $arrTmp[0] = "<input type='checkbox' name='" . utf8_encode("voc-" . $file) . ",{$directorio}' />"; $arrTmp[1] = $fecha; $arrTmp[2] = $hora; $arrTmp[3] = $arrVoiceMailDes['callerid']['valor']; $arrTmp[4] = $arrVoiceMailDes['origmailbox']['valor']; $arrTmp[5] = $arrVoiceMailDes['duration']['valor'] . ' sec.'; $pathRecordFile = base64_encode($regs[1] . '.wav'); $recordingLink = "<a href='#' onClick=\"javascript:popUp('index.php?menu={$module_name}&action=display_record&ext={$directorio}&name={$pathRecordFile}&rawmode=yes',350,100); return false;\">{$arrLang['Listen']}</a> "; $recordingLink .= "<a href='?menu={$module_name}&action=download&ext={$directorio}&name={$pathRecordFile}&rawmode=yes'>{$arrLang['Download']}</a>"; $arrTmp[6] = $recordingLink; $arrData[] = $arrTmp; } } } } closedir($handle); } } else { // No vale la ruta } } /* function sort_voicemails_hora_desc($a, $b) { return ($a[2] == $b[2]) ? 0 : (($a[2] < $b[2]) ? 1 : -1); } function sort_voicemails_fecha_desc($a, $b) { return ($a[1] == $b[1]) ? 0 : (($a[1] < $b[1]) ? 1 : -1); } usort($arrData, 'sort_voicemails_hora_desc'); usort($arrData, 'sort_voicemails_fecha_desc'); */ $fechas = array(); $horas = array(); foreach ($arrData as $llave => $fila) { $fechas[$llave] = $fila[1]; $horas[$llave] = $fila[2]; } array_multisort($fechas, SORT_DESC, $horas, SORT_DESC, $arrData); //Paginacion $limit = 15; $total = count($arrData); $oGrid->setLimit($limit); $oGrid->setTotal($total); $offset = $oGrid->calculateOffset(); $end = $offset + $limit <= $total ? $offset + $limit : $total; // Construyo el URL base if (isset($arrFilterExtraVars) && is_array($arrFilterExtraVars) and count($arrFilterExtraVars) > 0) { $url = array_merge($url, $arrFilterExtraVars); } //Fin Paginacion $arrVoiceData = array_slice($arrData, $offset, $limit); } else { $smarty->assign("mb_message", "<b>" . $arrLang["contact_admin"] . "</b>"); } $arrGrid = array("title" => $arrLang["Voicemail List"], "url" => $url, "icon" => "/modules/{$module_name}/images/pbx_voicemail.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $end, "total" => $total, "columns" => array(0 => array("name" => "", "property1" => ""), 1 => array("name" => $arrLang["Date"], "property1" => ""), 2 => array("name" => $arrLang["Time"], "property1" => ""), 3 => array("name" => $arrLang["CallerID"], "property1" => ""), 4 => array("name" => $arrLang["Extension"], "property1" => ""), 5 => array("name" => $arrLang["Duration"], "property1" => ""), 6 => array("name" => $arrLang["Message"], "property1" => ""))); if ($bandCustom == true) { $oGrid->customAction("config", _tr("Configuration")); } $oGrid->deleteList(_tr("Are you sure you wish to delete voicemails?"), "submit_eliminar", _tr("Delete")); $oGrid->showFilter($htmlFilter); $contenidoModulo = $oGrid->fetchGrid($arrGrid, $arrVoiceData, $arrLang); if (strpos($contenidoModulo, '<form') === FALSE) { $contenidoModulo = "<form style='margin-bottom:0;' method='POST' action='?menu={$module_name}'>{$contenidoModulo}</form>"; } return $contenidoModulo; }
function listadoLoginLogout($pDB, $smarty, $module_name, $local_templates_dir) { $oCalls = new paloSantoLoginLogout($pDB); $smarty->assign(array('SHOW' => _tr('Show'), 'Filter' => _tr('Find'))); $arrFormElements = array('date_start' => array('LABEL' => _tr('Date Init'), '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('Date End'), 'REQUIRED' => 'yes', 'INPUT_TYPE' => 'DATE', 'INPUT_EXTRA_PARAM' => '', 'VALIDATION_TYPE' => 'ereg', 'VALIDATION_EXTRA_PARAM' => '^[[:digit:]]{1,2}[[:space:]]+[[:alnum:]]{3}[[:space:]]+[[:digit:]]{4}$'), 'detailtype' => array('LABEL' => _tr('Tipo'), 'REQUIRED' => 'no', 'INPUT_TYPE' => 'SELECT', 'INPUT_EXTRA_PARAM' => array('D' => _tr('Detallado'), 'G' => _tr('General')), 'VALIDATION_TYPE' => 'text', 'VALIDATION_EXTRA_PARAM' => ''), 'queue' => array('LABEL' => _tr('Incoming Queue'), 'REQUIRED' => 'no', 'INPUT_TYPE' => 'SELECT', 'INPUT_EXTRA_PARAM' => generarComboColasEntrantes($oCalls), 'VALIDATION_TYPE' => 'text', 'VALIDATION_EXTRA_PARAM' => '^\\d+$')); $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'), 'detailtype' => 'D', 'queue' => ''); foreach (array_keys($paramFiltro) as $k) { if (!is_null(getParameter($k))) { $paramFiltro[$k] = getParameter($k); } } $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; } // 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'; // Consulta y recorte de registros $recordset = $oCalls->leerRegistrosLoginLogout($paramFiltro['detailtype'], $paramFiltro['date_start'], $paramFiltro['date_end'], trim($paramFiltro['queue']) == '' ? NULL : $paramFiltro['queue']); if (!is_array($recordset)) { $smarty->assign(array('mb_title' => _tr('Query Error'), 'mb_message' => $oCalls->errMsg)); $recordset = array(); } $oGrid = new paloSantoGrid($smarty); $bExportando = $oGrid->isExportAction(); $oGrid->setLimit(LIMITE_PAGINA); $oGrid->setTotal(count($recordset)); $offset = $oGrid->calculateOffset(); // Formato del arreglo de datos a mostrar $arrData = array(); $sTagInicio = !$bExportando ? '<b>' : ''; $sTagFinal = $sTagInicio != '' ? '</b>' : ''; $recordSlice = $bExportando ? $recordset : array_slice($recordset, $offset, LIMITE_PAGINA); foreach ($recordSlice as $tupla) { $arrData[] = array($tupla['number'], $tupla['name'], $tupla['datetime_init'], $tupla['estado'] == 'ONLINE' ? $sTagInicio . $tupla['datetime_end'] . $sTagFinal : $tupla['datetime_end'], format_time($tupla['duration']), format_time($tupla['total_incoming']), format_time($tupla['total_outgoing']), format_time($tupla['total_incoming'] + $tupla['total_outgoing']), number_format(100.0 * ($tupla['duration'] <= 0 ? 0 : ($tupla['total_incoming'] + $tupla['total_outgoing']) / $tupla['duration']), 2), _tr($tupla['estado'])); } // Calcular totales de pie de página $ktotales = array('duration', 'total_incoming', 'total_outgoing'); $totales = array_combine($ktotales, array_fill(0, count($ktotales), 0)); foreach ($recordset as $tupla) { foreach ($ktotales as $k) { $totales[$k] += $tupla[$k]; } } $arrData[] = array($sTagInicio . _tr('Total') . $sTagFinal, '', '', '', $sTagInicio . format_time($totales['duration']) . $sTagFinal, $sTagInicio . format_time($totales['total_incoming']) . $sTagFinal, $sTagInicio . format_time($totales['total_outgoing']) . $sTagFinal, $sTagInicio . format_time($totales['total_incoming'] + $totales['total_outgoing']) . $sTagFinal, '', ''); $oGrid->enableExport(); $oGrid->setURL($url); $oGrid->setData($arrData); $arrColumnas = array(_tr('Agente'), _tr('Nombre'), _tr('Date Init'), _tr('Date End'), _tr('Total Login'), _tr('Llamadas entrantes'), _tr('Llamadas salientes'), _tr('Tiempo en Llamadas'), _tr('Service(%)'), _tr('Estado')); $oGrid->setColumns($arrColumnas); $oGrid->setTitle(_tr('Login Logout')); $oGrid->pagingShow(true); $oGrid->setNameFile_Export(_tr('Login Logout')); $oGrid->showFilter($htmlFilter); return $oGrid->fetchGrid(); }
function _moduleContent(&$smarty, $module_name) { include_once "libs/paloSantoGrid.class.php"; include_once "libs/paloSantoDB.class.php"; include_once "libs/paloSantoForm.class.php"; include_once "libs/paloSantoConfig.class.php"; include_once "libs/paloSantoCDR.class.php"; require_once "libs/misc.lib.php"; include_once "libs/paloSantoRate.class.php"; include_once "libs/paloSantoTrunk.class.php"; include_once "libs/paloSantoGraphImage.lib.php"; //include module files include_once "modules/{$module_name}/configs/default.conf.php"; $lang = get_language(); $base_dir = dirname($_SERVER['SCRIPT_FILENAME']); $lang_file = "modules/{$module_name}/lang/{$lang}.lang"; if (file_exists("{$base_dir}/{$lang_file}")) { include_once "{$lang_file}"; } else { include_once "modules/{$module_name}/lang/en.lang"; } //global variables global $arrConf; global $arrConfModule; global $arrLang; global $arrLangModule; $arrConf = array_merge($arrConf, $arrConfModule); $arrLang = array_merge($arrLang, $arrLangModule); //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']; $MAX_DAYS = 60; $arrData = array(); $smarty->assign("menu", "dest_distribution"); $smarty->assign("Filter", $arrLang['Filter']); $arrFormElements = array("date_start" => array("LABEL" => $arrLang["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" => $arrLang["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}\$"), "criteria" => array("LABEL" => $arrLang["Criteria"], "REQUIRED" => "yes", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => array("minutes" => $arrLang["Distribution by Time"], "num_calls" => $arrLang["Distribution by Number of Calls"], "charge" => $arrLang["Distribution by Cost"]), "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => "")); $oFilterForm = new paloForm($smarty, $arrFormElements); // Por omision las fechas toman el sgte. valor (la fecha de hoy) $date_start = date("Y-m-d") . " 00:00:00"; $date_end = date("Y-m-d") . " 23:59:59"; $value_criteria = "minutes"; if (isset($_POST['filter'])) { if ($oFilterForm->validateForm($_POST)) { // Exito, puedo procesar los datos ahora. $date_start = translateDate($_POST['date_start']) . " 00:00:00"; $date_end = translateDate($_POST['date_end']) . " 23:59:59"; //valido que no exista diferencia mayor de 31 dias entre las fechas $inicio = strtotime($date_start); $fin = strtotime($date_end); $num_dias = ($fin - $inicio) / 86400; if ($num_dias > $MAX_DAYS) { $_POST['date_start'] = date("d M Y"); $_POST['date_end'] = date("d M Y"); $date_start = date("Y-m-d") . " 00:00:00"; $date_end = date("Y-m-d") . " 23:59:59"; $smarty->assign("mb_title", $arrLang["Validation Error"]); $smarty->assign("mb_message", "{$arrLang['Date Range spans maximum number of days']}:{$MAX_DAYS}"); } $value_criteria = $_POST['criteria']; $arrFilterExtraVars = array("date_start" => $_POST['date_start'], "date_end" => $_POST['date_end'], "criteria" => $_POST['criteria']); } else { // Error $smarty->assign("mb_title", $arrLang["Validation Error"]); $arrErrores = $oFilterForm->arrErroresValidacion; $strErrorMsg = "<b>{$arrLang['The following fields contain errors']}:</b><br>"; foreach ($arrErrores as $k => $v) { $strErrorMsg .= "{$k}, "; } $strErrorMsg .= ""; $smarty->assign("mb_message", $strErrorMsg); } $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/dest_dist_filter.tpl", "", $_POST); } else { if (isset($_GET['date_start']) && isset($_GET['date_end'])) { //valido que no exista diferencia mayor de 31 dias entre las fechas $date_start = translateDate($_GET['date_start']) . " 00:00:00"; $date_end = translateDate($_GET['date_end']) . " 23:59:59"; $inicio = strtotime($date_start); $fin = strtotime($date_end); $num_dias = ($fin - $inicio) / 86400; if ($num_dias > $MAX_DAYS) { $_GET['date_start'] = date("d M Y"); $_GET['date_end'] = date("d M Y"); $date_start = date("Y-m-d") . " 00:00:00"; $date_end = date("Y-m-d") . " 23:59:59"; $smarty->assign("mb_title", $arrLang["Validation Error"]); $smarty->assign("mb_message", "{$arrLang['Date Range spans maximum number of days']}:{$MAX_DAYS}"); } $value_criteria = $_GET['criteria']; $arrFilterExtraVars = array("date_start" => $_GET['date_start'], "date_end" => $_GET['date_end'], "criteria" => $_GET['criteria']); $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/dest_dist_filter.tpl", "", $_GET); } else { $date_start = date("Y-m-d") . " 00:00:00"; $date_end = date("Y-m-d") . " 23:59:59"; $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/dest_dist_filter.tpl", "", array('date_start' => date("d M Y"), 'date_end' => date("d M Y"), 'criteria' => 'minutes')); } } if (isset($_GET['action']) && $_GET['action'] == 'image') { ejecutarGrafico($value_criteria, $date_start, $date_end); return ''; } //obtener los datos a mostrar $type_graph = $value_criteria; //consulto cuales son los trunks de salida $data_graph = leerDatosGrafico($type_graph, $date_start, $date_end); $title_sumary = $data_graph['title_sumary']; //contruir la tabla de sumario $smarty->assign('URL_GRAPHIC', construirURL(array('module' => $module_name, 'rawmode' => 'yes', 'action' => 'image', 'criteria' => $value_criteria, 'date_start' => date('d M Y', strtotime($date_start)), 'date_end' => date('d M Y', strtotime($date_end))))); if (count($data_graph["values"]) > 0) { $mostrarSumario = TRUE; $total_valores = array_sum($data_graph["values"]); $resultados = $data_graph["values"]; foreach ($resultados as $pos => $valor) { $results[] = array($data_graph['legend'][$pos], number_format($valor, 2), number_format($valor / $total_valores * 100, 2)); } if (count($results) > 1) { $results[] = array("<b>Total<b>", "<b>" . number_format($total_valores, 2) . "<b>", "<b>" . number_format(100, 2) . "<b>"); } $smarty->assign("Rate_Name", $arrLang["Rate Name"]); $smarty->assign("Title_Criteria", $title_sumary); $smarty->assign("results", $results); } else { $mostrarSumario = FALSE; } $smarty->assign("mostrarSumario", $mostrarSumario); $smarty->assign("contentFilter", $htmlFilter); $smarty->assign("title", $arrLang['Destination Distribution']); $smarty->assign("icon", "images/bardoc.png"); return $smarty->fetch("file:{$local_templates_dir}/dest_distribution.tpl"); }
function report_Extention($smarty, $module_name, $local_templates_dir, $pDB_cdr, $pDB_ext) { $arrFormElements = array("date_from" => array("LABEL" => _tr("Start date"), "REQUIRED" => "yes", "INPUT_TYPE" => "DATE", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "date_to" => array("LABEL" => _tr("End date"), "REQUIRED" => "no", "INPUT_TYPE" => "DATE", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "extensions" => array("LABEL" => _tr("Number"), "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => loadExtentions($pDB_ext), "VALIDATION_TYPE" => "text", "EDITABLE" => "yes", "VALIDATION_EXTRA_PARAM" => ""), "classify_by" => array("LABEL" => "", "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => array("Number" => _tr('Extension (Number)'), "Queue" => _tr('Queue'), "Trunk" => _tr('Trunk')), "VALIDATION_TYPE" => "text", "EDITABLE" => "yes", "VALIDATION_EXTRA_PARAM" => "", 'ONCHANGE' => 'show_elements();'), "call_to" => array("LABEL" => _tr("Number"), "REQUIRED" => "yes", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => array("id" => 'call_to'), "VALIDATION_TYPE" => "text", "EDITABLE" => "yes", "VALIDATION_EXTRA_PARAM" => ""), "trunks" => array("LABEL" => "Trunk", "REQUIRED" => "no", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => loadTrunks($pDB_ext), "VALIDATION_TYPE" => "text", "EDITABLE" => "yes", "VALIDATION_EXTRA_PARAM" => "")); $oFilterForm = new paloForm($smarty, $arrFormElements); $smarty->assign("SHOW", _tr("Show")); $smarty->assign("HERE", _tr("Here")); $date_ini = getParameter("date_from"); $date_fin = getParameter("date_to"); $ext = getParameter("call_to"); $date_ini2 = translateDate($date_ini); $date_fin2 = translateDate($date_fin); $ext2 = $ext; $option = ""; if (isset($_POST["classify_by"])) { $option = $_POST["classify_by"]; $smarty->assign("classify_by", $option); } if (getAction() == "show") { $smarty->assign("date_from", $date_ini); $smarty->assign("date_1", $date_ini); $smarty->assign("date_to", $date_fin); $smarty->assign("date_2", $date_fin); $date_ini2 = translateDate($date_ini); $date_fin2 = translateDate($date_fin); } else { $_POST["date_from"] = date("d M Y"); $_POST["date_to"] = date("d M Y"); $date_ini = date("d M Y"); $date_fin = date("d M Y"); $date_ini2 = translateDate($date_ini); $date_fin2 = translateDate($date_fin); } $_POST["extensions"] = $ext; $smarty->assign("value_2", $date_ini); $smarty->assign("module_name", $module_name); $pExtention = new paloSantoExtention($pDB_cdr); $ruta_img = array(); $error = false; if ($option == "Number") { if (!preg_match("/^[1-9]{1}[[:digit:]]*\$/", $ext) && isset($ext)) { $error = true; $smarty->assign("mb_title", _tr("Validation Error")); $smarty->assign("mb_message", _tr("The extension must be numeric and can not start with zero")); } $smarty->assign("SELECTED_1", "selected"); $smarty->assign("SELECTED_2", ""); $smarty->assign("SELECTED_3", ""); $numIn = 0; $numOut = 0; $numTot = 0; $result = $pExtention->countCallsByExtension($date_ini2, $date_fin2, $ext); if (is_array($result)) { $numIn = $result['num_incoming_call']; $numOut = $result['num_outgoing_call']; $numTot = $numIn + $numOut; } if ($numIn != 0) { $VALUE = (int) (100 * ($numIn / $numTot)); } else { $VALUE = 0; } $ruta_img = array("?menu={$module_name}&action=grafic&du={$VALUE}%&in={$numIn}&out={$numOut}&ext={$ext2}&tot={$numTot}&rawmode=yes"); } else { if ($option == "Queue") { $smarty->assign("SELECTED_1", ""); $smarty->assign("SELECTED_2", "selected"); $smarty->assign("SELECTED_3", ""); $ruta_img = array("?menu={$module_name}&action=grafic_queue&queue={$ext2}&dti={$date_ini2}&dtf={$date_fin2}&rawmode=yes"); } else { if ($option == "Trunk") { $smarty->assign("SELECTED_1", ""); $smarty->assign("SELECTED_2", ""); $smarty->assign("SELECTED_3", "selected"); $trunkT = getParameter("trunks"); $smarty->assign("trunks", $trunkT); $ruta_img = array("?menu={$module_name}&action=grafic_trunk&trunk={$trunkT}&dti={$date_ini2}&dtf={$date_fin2}&rawmode=yes", "?menu={$module_name}&action=grafic_trunk2&trunk={$trunkT}&dti={$date_ini2}&dtf={$date_fin2}&rawmode=yes"); } } } for ($i = 0; $i < count($ruta_img); $i++) { $ruta_img[$i] = "<img src='" . $ruta_img[$i] . "' border='0'>"; } if (count($ruta_img) > 0 && !$error) { $smarty->assign("ruta_img", "<tr class='letra12'><td align='center'>" . implode(' ', $ruta_img) . '<td></tr>'); } else { $smarty->assign("ruta_img", "<tr class='letra12'><td align='center'><td></tr>"); } $smarty->assign("icon", "modules/{$module_name}/images/reports_graphic_reports.png"); $htmlForm = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", _tr("Graphic Report"), $_POST); $contenidoModulo = "<form method='POST' style='margin-bottom:0;' action='?menu={$module_name}'>" . $htmlForm . "</form>"; return $contenidoModulo; }
function listadoHoldTime($pDB, $smarty, $module_name, $local_templates_dir, &$oGrid, &$arrGrid, &$arrData) { $arrData = array(); $oCalls = new paloSantoHoldTime($pDB); $fecha_init = date("d M Y"); $fecha_end = date("d M Y"); // preguntamos por el TIPO del filtro (Entrante/Saliente) if (!isset($_POST['cbo_tipos']) || $_POST['cbo_tipos'] == "") { $_POST['cbo_tipos'] = "E"; //por defecto las consultas seran de Llamadas Entrantes } $tipo = 'E'; $entrantes = 'T'; $salientes = 'T'; if (isset($_POST['cbo_tipos'])) { $tipo = $_POST['cbo_tipos']; } if (isset($_POST['cbo_estado_entrantes'])) { $entrantes = $_POST['cbo_estado_entrantes']; } if (isset($_POST['cbo_estado_salientes'])) { $salientes = $_POST['cbo_estado_salientes']; } //validamos la fecha if (isset($_POST['txt_fecha_init']) && isset($_POST['txt_fecha_end'])) { $fecha_init_actual = $_POST['txt_fecha_init']; $fecha_end_actual = $_POST['txt_fecha_end']; } elseif (isset($_GET['txt_fecha_init']) && isset($_GET['txt_fecha_end'])) { $fecha_init_actual = $_GET['txt_fecha_init']; $fecha_end_actual = $_GET['txt_fecha_end']; } else { $fecha_init_actual = $fecha_init; $fecha_end_actual = $fecha_end; } $sValidacion = "^[[:digit:]]{1,2}[[:space:]]+[[:alnum:]]{3}[[:space:]]+[[:digit:]]{4}\$"; if (isset($_POST['submit_fecha']) || isset($_POST['cbo_tipos'])) { // si se ha presionado el boton pregunto si hay una fecha de inicio elegida if (isset($_POST['txt_fecha_init']) && $_POST['txt_fecha_init'] != "" && isset($_POST['txt_fecha_end']) && $_POST['txt_fecha_end'] != "") { // sihay una fecha de inicio pregunto si es valido el formato de la fecha if (ereg($sValidacion, $_POST['txt_fecha_init'])) { // si el formato es valido procedo a convertir la fecha en un arreglo que contiene // el anio , mes y dia seleccionados $fecha_init = $fecha_init_actual; //$_POST['txt_fecha_init']; $arrFecha_init = explode('-', translateDate($fecha_init)); } else { // si la fecha esta en un formato no valido se envia un mensaje de error $smarty->assign("mb_title", _tr("Error")); $smarty->assign("mb_message", _tr("Debe ingresar una fecha valida")); } // pregunto si es valido el formato de la fecha final if (ereg($sValidacion, $_POST['txt_fecha_end'])) { // si el formato es valido procedo a convertir la fecha en un arreglo que contiene // el anio , mes y dia seleccionados $fecha_end = $fecha_end_actual; //$_POST['txt_fecha_end']; $arrFecha_end = explode('-', translateDate($fecha_end)); } else { // si la fecha esta en un formato no valido se envia un mensaje de error $smarty->assign("mb_title", _tr("Error")); $smarty->assign("mb_message", _tr("Debe ingresar una fecha valida")); } //PRUEBA $arrFilterExtraVars = array("cbo_tipos" => $tipo, "cbo_estado_entrantes" => $entrantes, "cbo_estado_salientes" => $salientes, "txt_fecha_init" => $_POST['txt_fecha_init'], "txt_fecha_end" => $_POST['txt_fecha_end']); //PRUEBA } elseif (isset($_GET['txt_fecha_init']) && $_GET['txt_fecha_init'] != "" && isset($_GET['txt_fecha_end']) && $_GET['txt_fecha_end'] != "") { if (ereg($sValidacion, $_GET['txt_fecha_init'])) { // si el formato es valido procedo a convertir la fecha en un arreglo que contiene // el anio , mes y dia seleccionados $fecha_init = $fecha_init_actual; //$_POST['txt_fecha_init']; $arrFecha_init = explode('-', translateDate($fecha_init)); } else { // si la fecha esta en un formato no valido se envia un mensaje de error $smarty->assign("mb_title", _tr("Error")); $smarty->assign("mb_message", _tr("Debe ingresar una fecha valida")); } // pregunto si es valido el formato de la fecha final if (ereg($sValidacion, $_GET['txt_fecha_end'])) { // si el formato es valido procedo a convertir la fecha en un arreglo que contiene // el anio , mes y dia seleccionados $fecha_end = $fecha_end_actual; //$_POST['txt_fecha_end']; $arrFecha_end = explode('-', translateDate($fecha_end)); } else { // si la fecha esta en un formato no valido se envia un mensaje de error $smarty->assign("mb_title", _tr("Error")); $smarty->assign("mb_message", _tr("Debe ingresar una fecha valida")); } $tipo = $_GET['cbo_tipos']; $entrantes = $_GET['cbo_estado_entrantes']; $salientes = $_GET['cbo_estado_salientes']; $arrFilterExtraVars = array("cbo_tipos" => $_GET['cbo_tipos'], "cbo_estado_entrantes" => $_GET['cbo_estado_entrantes'], "cbo_estado_salientes" => $_GET['cbo_estado_salientes'], "txt_fecha_init" => $_GET['txt_fecha_init'], "txt_fecha_end" => $_GET['txt_fecha_end']); } elseif (!isset($fecha_init) && !isset($fecha_end)) { // si se ha presionado el boton para listar por fechas, y no se ha ingresado una fecha // se le muestra al usuario un mensaje de error $smarty->assign("mb_title", _tr("Error")); $smarty->assign("mb_message", _tr("Debe ingresar una fecha inicio/fin")); } } $bElastixNuevo = method_exists('paloSantoGrid', 'setURL'); $bExportando = $bElastixNuevo ? $oGrid->isExportAction() : isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes' || isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' || isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes'; //para el pagineo // LISTADO $limit = 50; $offset = 0; //numero de registros $arrCallsTmp = $oCalls->getHoldTime($tipo, $entrantes, $salientes, translateDate($fecha_init), translateDate($fecha_end), $limit, $offset); $totalCalls = $arrCallsTmp['NumRecords']; if ($bElastixNuevo) { $oGrid->setLimit($limit); $oGrid->setTotal($totalCalls); $offset = $oGrid->calculateOffset(); } else { // Si se quiere avanzar a la sgte. pagina if (isset($_GET['nav']) && $_GET['nav'] == "end") { // Mejorar el sgte. bloque. if ($totalCalls % $limit == 0) { $offset = $totalCalls - $limit; } else { $offset = $totalCalls - $totalCalls % $limit; } } // Si se quiere avanzar a la sgte. pagina if (isset($_GET['nav']) && $_GET['nav'] == "next") { $offset = $_GET['start'] + $limit - 1; } // Si se quiere retroceder if (isset($_GET['nav']) && $_GET['nav'] == "previous") { $offset = $_GET['start'] - $limit - 1; } } // Construyo el URL base $url = array('menu' => $module_name); if (isset($arrFilterExtraVars) && is_array($arrFilterExtraVars) && count($arrFilterExtraVars) > 0) { $url = array_merge($url, $arrFilterExtraVars); } //fin de pagineo //llamamos a la función que hace la consulta a la base según los criterios de búsqueda $arrCalls = $oCalls->getHoldTime($tipo, $entrantes, $salientes, translateDate($fecha_init), translateDate($fecha_end), $limit, $offset); //Llenamos el contenido de las columnas $arrTmp = array(); $sTagInicio = !$bExportando ? '<b>' : ''; $sTagFinal = $sTagInicio != '' ? '</b>' : ''; if (is_array($arrCalls)) { $end = $arrCalls['NumRecords']; foreach ($arrCalls['Data'] as $calls) { $arrTmp[0] = $calls['cola']; //primeramente enceramos los valores de horas $arrTmp[1] = ""; $arrTmp[2] = ""; $arrTmp[3] = ""; $arrTmp[4] = ""; $arrTmp[5] = ""; $arrTmp[6] = ""; $arrTmp[7] = ""; $arrTmp[8] = ""; $arrTmp[9] = ""; foreach ($calls as $intervalo => $num_veces) { if ($intervalo == '0') { $arrTmp[1] = $num_veces; } elseif ($intervalo == '1') { $arrTmp[2] = $num_veces; } elseif ($intervalo == '2') { $arrTmp[3] = $num_veces; } elseif ($intervalo == '3') { $arrTmp[4] = $num_veces; } elseif ($intervalo == '4') { $arrTmp[5] = $num_veces; } elseif ($intervalo == '5') { $arrTmp[6] = $num_veces; } elseif ($intervalo == "6") { $arrTmp[7] = $num_veces; } elseif ($intervalo == 'tiempo_promedio') { //tiempo promedio de espera en segundos $arrTmp[8] = number_format($num_veces, 0); } elseif ($intervalo == 'nuevo_valor_maximo') { //valor mayor en segundos $arrTmp[9] = $num_veces; } $arrTmp[10] = sumNumCalls($arrTmp); } $arrData[] = $arrTmp; } $arrTmp[0] = $sTagInicio . _tr("Total") . $sTagFinal; for ($j = 1; $j <= 8; $j++) { $sum = 0; for ($i = 0; $i < count($arrData); $i++) { $sum = $sum + $arrData[$i][$j]; } $arrTmp[$j] = $sTagInicio . $sum . $sTagFinal; } $sumTotalCalls = $maxTimeWait = 0; for ($i = 0; $i < count($arrData); $i++) { $maxTimeWait = $oCalls->getMaxWait($maxTimeWait, $arrData[$i][9]); $sumTotalCalls = $sumTotalCalls + $arrData[$i][10]; } $arrTmp[10] = $sTagInicio . $sumTotalCalls . $sTagFinal; $arrTmp[9] = $sTagInicio . $maxTimeWait . $sTagFinal; $arrData[] = $arrTmp; } //Para el combo de tipos $tipos = array("E" => _tr("Ingoing"), "S" => _tr("Outgoing")); $combo_tipos = "<select name='cbo_tipos' id='cbo_tipos' onChange='submit();'>" . combo($tipos, $_POST['cbo_tipos']) . "</select>"; //para el combo de entrantes if (isset($_POST['cbo_estado_entrantes'])) { $cbo_estado_entrates = $_POST['cbo_estado_entrantes']; } elseif (isset($_GET['cbo_estado_entrantes'])) { $cbo_estado_entrates = $_GET['cbo_estado_entrantes']; } else { $cbo_estado_entrates = 'T'; } $estados_entrantes = array("T" => _tr("Todas"), "E" => _tr("Exitosas"), "A" => _tr("Abandonadas")); $combo_estados_entrantes = "<select name='cbo_estado_entrantes' id='cbo_estado_entrantes' >" . combo($estados_entrantes, $cbo_estado_entrates) . "</select>"; //para el combo de salientes if (isset($_POST['cbo_estado_salientes'])) { $cbo_estado_salientes = $_POST['cbo_estado_salientes']; } elseif (isset($_GET['cbo_estado_salientes'])) { $cbo_estado_salientes = $_GET['cbo_estado_salientes']; } else { $cbo_estado_salientes = 'T'; } $estados_salientes = array("T" => _tr("Todas"), "E" => _tr("Exitosas"), "N" => _tr("No Realizadas"), "A" => _tr("Abandonadas")); $combo_estados_salientes = "<select name='cbo_estado_salientes' id='cbo_estado_salientes' >" . combo($estados_salientes, $cbo_estado_salientes) . "</select>"; //validamos que combo se cargará segun lo electo en combo TIPO, al principio le seteamos por defecto el de ENTRANTES $td = "<td class='letra12' align='right'>" . _tr("Estado") . "</td><td>{$combo_estados_entrantes}</td>"; if (isset($_POST['cbo_tipos']) && $_POST['cbo_tipos'] == "E") { $td = "<td class='letra12' align='left'>" . _tr("Estado") . "</td><td>{$combo_estados_entrantes}</td>"; } elseif (isset($_POST['cbo_tipos']) && $_POST['cbo_tipos'] == "S") { $td = "<td class='letra12' align='left'>" . _tr("Estado") . "</td><td>{$combo_estados_salientes}</td>"; } $oGrid->showFilter(insertarCabeceraCalendario() . "\n\n <table width='100%' border='0'>\n <tr>\n <td align='left'>\n <table>\n <tr>\n <td class='letra12'>\n " . _tr("Date Init") . "\n <span class='required'>*</span>\n </td>\n <td>\n " . insertarDateInit($fecha_init_actual) . "\n </td>\n <td class='letra12'>\n \n </td>\n <td class='letra12'>\n " . _tr("Date End") . "\n <span class='required'>*</span>\n </td>\n <td>\n " . insertarDateEnd($fecha_end_actual) . "\n </td>\n\n </tr>\n\n <tr>\n <td class='letra12' align='left'>" . _tr("Tipo") . "</td>\n <td>{$combo_tipos}</td>\n <td class='letra12'>\n \n </td>\n " . $td . "\n <td>\n <input type='submit' name='submit_fecha' value=" . _tr("Find") . " class='button'>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n\n "); $oGrid->enableExport(); if ($bElastixNuevo) { $oGrid->setURL($url); $oGrid->setData($arrData); $arrColumnas = array(_tr("Cola"), "0 - 10", "11 - 20", "21 - 30", "31 - 40", "41 - 50", "51 - 60", "61 >", _tr("Tiempo Promedio Espera(Seg)"), _tr("Espera Mayor(seg)"), _tr("Total Calls")); $oGrid->setColumns($arrColumnas); $oGrid->setTitle(_tr("Hold Time")); $oGrid->pagingShow(true); $oGrid->setNameFile_Export(_tr("Hold Time")); $smarty->assign("SHOW", _tr("Show")); return $oGrid->fetchGrid(); } else { global $arrLang; $offset = 0; $limit = $totalCalls; //Llenamos las cabeceras $url = construirURL($url, array("nav", "start")); $arrGrid = array("title" => _tr("Hold Time"), "url" => $url, "icon" => "images/list.png", "width" => "99%", "start" => $end == 0 ? 0 : $offset + 1, "end" => $offset + $limit <= $end ? $offset + $limit : $end, "total" => $end, "columns" => array(0 => array("name" => _tr("Cola"), "property1" => ""), 1 => array("name" => "0 - 10", "property1" => ""), 2 => array("name" => "11 - 20", "property1" => ""), 3 => array("name" => "21 - 30", "property1" => ""), 4 => array("name" => "31 - 40", "property1" => ""), 5 => array("name" => "41 - 50", "property1" => ""), 6 => array("name" => "51 - 60", "property1" => ""), 7 => array("name" => "61 >", "property1" => ""), 8 => array("name" => _tr("Tiempo Promedio Espera(Seg)"), "property1" => ""), 9 => array("name" => _tr("Espera Mayor(seg)"), "property1" => ""), 10 => array("name" => _tr("Total Calls"), "property1" => ""))); if (isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes' && method_exists($oGrid, 'fetchGridPDF')) { return $oGrid->fetchGridPDF($arrGrid, $arrData); } if (isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' && method_exists($oGrid, 'fetchGridXLS')) { return $oGrid->fetchGridXLS($arrGrid, $arrData); } if ($bExportando) { $fechaActual = date("d M Y"); header("Cache-Control: private"); header("Pragma: cache"); header('Content-Type: application/octec-stream'); $title = "\"" . $fechaActual . ".csv\""; header("Content-disposition: inline; filename={$title}"); header('Content-Type: application/force-download'); } if ($bExportando) { return $oGrid->fetchGridCSV($arrGrid, $arrData); } $sContenido = $oGrid->fetchGrid($arrGrid, $arrData, $arrLang); if (strpos($sContenido, '<form') === FALSE) { $sContenido = "<form method=\"POST\" style=\"margin-bottom:0;\" action=\"{$url}\">{$sContenido}</form>"; } return $sContenido; } }
function _moduleContent(&$smarty, $module_name) { include_once "libs/paloSantoGrid.class.php"; include_once "libs/paloSantoDB.class.php"; include_once "libs/paloSantoForm.class.php"; include_once "libs/paloSantoConfig.class.php"; require_once "libs/misc.lib.php"; //Incluir librería de lenguaje load_language_module($module_name); //include module files include_once "modules/{$module_name}/configs/default.conf.php"; include_once "modules/{$module_name}/libs/paloSantoCallPerAgent.class.php"; global $arrConf; global $arrLang; $arrCallsAgentTmp = 0; //folder path for custom templates $base_dir = dirname($_SERVER['SCRIPT_FILENAME']); $templates_dir = isset($arrConfig['templates_dir']) ? $arrConfig['templates_dir'] : 'themes'; $local_templates_dir = "{$base_dir}/modules/{$module_name}/" . $templates_dir . '/' . $arrConf['theme']; $pConfig = new paloConfig("/etc", "amportal.conf", "=", "[[:space:]]*=[[:space:]]*"); $arrConfig = $pConfig->leer_configuracion(false); $pDB = new paloDB($cadena_dsn); $arrData = array(); $oCallsAgent = new paloSantoCallsAgent($pDB); $urlVars = array('menu' => $module_name); $smarty->assign("menu", "calls_per_agent"); $smarty->assign("Filter", _tr('Query')); $arrFormElements = createFieldFilter(); $oFilterForm = new paloForm($smarty, $arrFormElements); // Por omision las fechas toman el sgte. valor (la fecha de hoy) $date_start = date("Y-m-d") . " 00:00:00"; $date_end = date("Y-m-d") . " 23:59:59"; $arrFilterExtraVars = null; $fieldPat = array(); if (isset($_POST['filter'])) { if ($oFilterForm->validateForm($_POST)) { // Exito, puedo procesar los datos ahora. $date_start = translateDate($_POST['date_start']) . " 00:00:00"; $date_end = translateDate($_POST['date_end']) . " 23:59:59"; if (!empty($_POST['field_pattern'])) { $fieldPat[$_POST['field_name']][] = $_POST['field_pattern']; } if (!empty($_POST['field_pattern_1'])) { $fieldPat[$_POST['field_name_1']][] = $_POST['field_pattern_1']; } $arrFilterExtraVars = array("date_start" => $_POST['date_start'], "date_end" => $_POST['date_end'], "field_name" => $_POST['field_name'], "field_pattern" => $_POST['field_pattern'], "field_name_1" => $_POST['field_name_1'], "field_pattern_1" => $_POST['field_pattern_1']); } else { // Error $smarty->assign("mb_title", _tr("Validation Error")); $arrErrores = $oFilterForm->arrErroresValidacion; $strErrorMsg = "<b>" . _tr('The following fields contain errors') . ":</b><br>"; foreach ($arrErrores as $k => $v) { $strErrorMsg .= "{$k}, "; } $strErrorMsg .= ""; $smarty->assign("mb_message", $strErrorMsg); } $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_POST); } else { if (isset($_GET['date_start']) and isset($_GET['date_end'])) { $date_start = translateDate($_GET['date_start']) . " 00:00:00"; $date_end = translateDate($_GET['date_end']) . " 23:59:59"; if (!empty($_GET['field_pattern'])) { $fieldPat[$_GET['field_name']][] = $_GET['field_pattern']; } if (!empty($_GET['field_pattern_1'])) { $fieldPat[$_GET['field_name_1']][] = $_GET['field_pattern_1']; } $arrFilterExtraVars = array("date_start" => $_GET['date_start'], "date_end" => $_GET['date_end']); $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_GET); } else { $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", array('date_start' => date("d M Y"), 'date_end' => date("d M Y"), 'field_name' => 'agent', 'field_pattern' => '', 'field_name_1' => 'agent', 'field_pattern_1' => '')); } } $bElastixNuevo = method_exists('paloSantoGrid', 'setURL'); $oGrid = new paloSantoGrid($smarty); $oGrid->enableExport(); // enable export. $oGrid->showFilter($htmlFilter); $bExportando = $bElastixNuevo ? $oGrid->isExportAction() : isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes' || isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' || isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes'; $offset = 0; $limit = 20; if (isset($fieldPat['type'])) { $fieldPat['type'] = array_map('strtoupper', $fieldPat['type']); } $arrCallsAgentTmp = $oCallsAgent->obtenerCallsAgent($date_start, $date_end, $fieldPat); if (!is_array($arrCallsAgentTmp)) { $smarty->assign(array('mb_title' => _tr('ERROR'), 'mb_message' => $oCallsAgent->errMsg)); $arrCallsAgentTmp = array(); } $totalCallsAgents = count($arrCallsAgentTmp); // Si se quiere avanzar a la sgte. pagina if ($bElastixNuevo) { $oGrid->setLimit($limit); $oGrid->setTotal($totalCallsAgents + 1); $offset = $oGrid->calculateOffset(); } else { if (isset($_GET['nav']) && $_GET['nav'] == "end") { // Mejorar el sgte. bloque. if ($totalCallsAgents % $limit == 0) { $offset = $totalCallsAgents - $limit; } else { $offset = $totalCallsAgents - $totalCallsAgents % $limit; } } // Si se quiere avanzar a la sgte. pagina if (isset($_GET['nav']) && $_GET['nav'] == "next") { $offset = $_GET['start'] + $limit - 1; } // Si se quiere retroceder if (isset($_GET['nav']) && $_GET['nav'] == "previous") { $offset = $_GET['start'] - $limit - 1; } } // Bloque comun $arrCallsAgent = array_slice($arrCallsAgentTmp, $offset, $limit); $arrData = array(); $sumCallAnswered = $sumDuration = $timeMayor = 0; foreach ($arrCallsAgent as $cdr) { $arrData[] = array($cdr['agent_number'], htmlentities($cdr['agent_name'], ENT_COMPAT, 'UTF-8'), $cdr['type'], $cdr['queue'], $cdr['num_answered'], formatoSegundos($cdr['sum_duration']), formatoSegundos($cdr['avg_duration']), formatoSegundos($cdr['max_duration'])); $sumCallAnswered += $cdr['num_answered']; // Total de llamadas contestadas $sumDuration += $cdr['sum_duration']; // Total de segundos en llamadas $timeMayor = $timeMayor < $cdr['max_duration'] ? $cdr['max_duration'] : $timeMayor; } $sTagInicio = !$bExportando ? '<b>' : ''; $sTagFinal = $sTagInicio != '' ? '</b>' : ''; $arrData[] = array($sTagInicio . _tr('Total') . $sTagFinal, '', '', '', $sTagInicio . $sumCallAnswered . $sTagFinal, $sTagInicio . formatoSegundos($sumDuration) . $sTagFinal, $sTagInicio . formatoSegundos($sumCallAnswered > 0 ? $sumDuration / $sumCallAnswered : 0) . $sTagFinal, $sTagInicio . formatoSegundos($timeMayor) . $sTagFinal); // Construyo el URL base if (isset($arrFilterExtraVars) && is_array($arrFilterExtraVars) && count($arrFilterExtraVars) > 0) { $urlVars = array_merge($urlVars, $arrFilterExtraVars); } if ($bElastixNuevo) { $oGrid->setURL(construirURL($urlVars, array("nav", "start"))); $oGrid->setData($arrData); $arrColumnas = array(_tr("No.Agent"), _tr("Agent"), _tr("Type"), _tr("Queue"), _tr("Calls answered"), _tr("Duration"), _tr("Average"), _tr("Call longest")); $oGrid->setColumns($arrColumnas); $oGrid->setTitle(_tr("Calls per Agent")); $oGrid->pagingShow(true); $oGrid->setNameFile_Export(_tr("Calls per Agent")); $smarty->assign("SHOW", _tr("Show")); return $oGrid->fetchGrid(); } else { $url = construirURL($urlVars, array("nav", "start")); $offset = 0; $total = count($arrData); $limit = $total; $arrGrid = array("title" => _tr("Calls per Agent"), "url" => $url, "icon" => "images/user.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $offset + $limit <= $total ? $offset + $limit : $total, "total" => $total, "columns" => array(0 => array("name" => _tr("No.Agent"), "property" => ""), 1 => array("name" => _tr("Agent"), "property" => ""), 2 => array("name" => _tr("Type"), "property" => ""), 3 => array("name" => _tr("Queue"), "property" => ""), 4 => array("name" => _tr("Calls answered"), "property" => ""), 5 => array("name" => _tr("Duration"), "property" => ""), 6 => array("name" => _tr("Average"), "property" => ""), 7 => array("name" => _tr("Call longest"), "property" => ""))); if (isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes' && method_exists($oGrid, 'fetchGridPDF')) { return $oGrid->fetchGridPDF($arrGrid, $arrData); } if (isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' && method_exists($oGrid, 'fetchGridXLS')) { return $oGrid->fetchGridXLS($arrGrid, $arrData); } if ($bExportando) { header("Cache-Control: private"); header("Pragma: cache"); header('Content-Type: application/octet-stream'); header('Content-disposition: inline; filename="calls_per_agent.csv"'); header('Content-Type: application/force-download'); } if ($bExportando) { return $oGrid->fetchGridCSV($arrGrid, $arrData); } $sContenido = $oGrid->fetchGrid($arrGrid, $arrData, $arrLang); if (strpos($sContenido, '<form') === FALSE) { $sContenido = "<form method=\"POST\" style=\"margin-bottom:0;\" action=\"{$url}\">{$sContenido}</form>"; } return $sContenido; } }
function generarReporte($smarty, $fecha_actual_init, $fecha_actual_end, $oReportsCalls, &$arrGrid = null, $bElastixNuevo, $bExportando, &$oGrid, $url, $htmlFilter) { $fecha_init = translateDate($fecha_actual_init) . " 00:00:00"; $fecha_end = translateDate($fecha_actual_end) . " 23:59:59"; $limit = 50; $offset = 0; // instancio una objeto de la clase paloSantoReports Calls $arrQueues = $oReportsCalls->getQueueCallEntry(null, $offset); $total = count($arrQueues); if ($bElastixNuevo) { $oGrid->setLimit($limit); $oGrid->setTotal($total); $offset = $oGrid->calculateOffset(); } else { // Si se quiere avanzar a la sgte. pagina if (isset($_GET['nav']) && $_GET['nav'] == "end") { $totalQueues = count($arrQueues); // Mejorar el sgte. bloque. if ($totalQueues % $limit == 0) { $offset = $totalQueues - $limit; } else { $offset = $totalQueues - $totalQueues % $limit; } } // Si se quiere avanzar a la sgte. pagina if (isset($_GET['nav']) && $_GET['nav'] == "next") { $offset = $_GET['start'] + $limit - 1; } // Si se quiere retroceder if (isset($_GET['nav']) && $_GET['nav'] == "previous") { $offset = $_GET['start'] - $limit - 1; } } // lamo al metodo que me genera el reporte $arrDatosReporte = $oReportsCalls->getCall($arrQueues, $fecha_init, $fecha_end); // obtengo la cantidad de registros que apareceran en el reporte $arrQueues = $oReportsCalls->getQueueCallEntry($limit, $offset); $end = count($arrQueues); //defino el esqueleto del reporte $indice = 0; // comienzo a llenar el arreglo $arrTmp con los datos que se mostraran en el reporte $arrData = array(); foreach ($arrQueues as $queue) { // $arrTmp[0] = $queue['queue']; $arrTmp[1] = $arrDatosReporte['Success'][$indice]; $arrTmp[2] = $arrDatosReporte['Left'][$indice]; $arrTmp[3] = $arrDatosReporte['WaitTime'][$indice]; $arrTmp[4] = $arrTmp[1] + $arrTmp[2]; $arrData[] = $arrTmp; $indice++; } $sumExitosa = $sumAbandonada = $sumTotalCall = 0; $sumWait = "00:00:00"; for ($i = 0; $i < count($arrData); $i++) { $sumExitosa = $sumExitosa + $arrData[$i][1]; $sumAbandonada = $sumAbandonada + $arrData[$i][2]; $sumWait = $oReportsCalls->getTotalWaitTime($sumWait, $arrData[$i][3]); $sumTotalCall = $sumTotalCall + $arrData[$i][4]; } $sTagInicio = !$bExportando ? '<b>' : ''; $sTagFinal = $sTagInicio != '' ? '</b>' : ''; $arrTmp[0] = $sTagInicio . _tr("Total") . $sTagFinal; $arrTmp[1] = $sTagInicio . $sumExitosa . $sTagFinal; $arrTmp[2] = $sTagInicio . $sumAbandonada . $sTagFinal; $arrTmp[3] = $sTagInicio . $sumWait . $sTagFinal; $arrTmp[4] = $sTagInicio . $sumTotalCall . $sTagFinal; $arrData[] = $arrTmp; $oGrid->enableExport(); $oGrid->showFilter($htmlFilter); if ($bElastixNuevo) { $oGrid->setURL($url); $oGrid->setData($arrData); $arrColumnas = array(_tr("Queue"), _tr("Successful"), _tr("Left"), _tr("Time Hopes"), _tr("Total Calls")); $oGrid->setColumns($arrColumnas); $oGrid->setTitle(_tr("Ingoing Calls Success")); $oGrid->pagingShow(true); $oGrid->setNameFile_Export(_tr("Ingoing Calls Success")); $smarty->assign("SHOW", _tr("Show")); return $oGrid->fetchGrid(); } else { global $arrLang; $offset = 0; $total = count($arrQueues) + 1; $limit = $total; $arrGrid = array("title" => _tr("List Calls"), "url" => $url, "icon" => "images/list.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $offset + $limit <= $total ? $offset + $limit : $total, "total" => $total, "columns" => array(0 => array('name' => _tr("Queue"), 'property1' => ''), 1 => array('name' => _tr("Successful"), 'property1' => ''), 2 => array('name' => _tr("Left"), 'property1' => ''), 3 => array('name' => _tr("Time Hopes"), 'property1' => ''), 4 => array('name' => _tr("Total Calls"), 'property1' => ''))); if ($bExportando) { // ----------- cabeceras necesarias para enviar la data a un archivo. ----------- // // para que los datos de un formulario no se pierdan header("Cache-Control: private"); // obliga a la pagina a que sea cacheada header("Pragma: cache"); // origina de un flujo de datos. header('Content-Type: application/octec-stream'); // nombre del archivo del reporte a generarse, en base a la fecha seleccionada del reporte. $title = "\"" . $fecha_actual_init . " a " . $fecha_actual_end . ".csv\""; // hace que la data se guarde en un archivo con el nombre especificado en el parametro filename header("Content-disposition: inline; filename={$title}"); // fuerza a que el archivo sea download header('Content-Type: application/force-download'); } if ($bExportando) { return $oGrid->fetchGridCSV($arrGrid, $arrData); } $sContenido = $oGrid->fetchGrid($arrGrid, $arrData, $arrLang); if (strpos($sContenido, '<form') === FALSE) { $sContenido = "<form method=\"POST\" style=\"margin-bottom:0;\" action=\"{$url}\">{$sContenido}</form>"; } return $sContenido; } }
function saveTime($smarty, $module_name, $local_templates_dir, $sZonaActual) { $date = getParameter("date"); $date = translateDate($date); $date = explode("-", $date); $month = ""; $year = ""; $day = ""; if (isset($date[0]) && isset($date[1]) && isset($date[2])) { $month = $date[1]; $day = $date[2]; $year = $date[0]; } // Validación básica $listaVars = array('ServerDate_Hour' => '^[[:digit:]]{1,2}$', 'ServerDate_Minute' => '^[[:digit:]]{1,2}$', 'ServerDate_Second' => '^[[:digit:]]{1,2}$'); $bValido = TRUE; foreach ($listaVars as $sVar => $sReg) { if (!ereg($sReg, $_POST[$sVar])) { $bValido = FALSE; } } if (!ereg('^[[:digit:]]{4}$', $year)) { $bValido = FALSE; } if (!ereg('^[[:digit:]]{1,2}$', $month)) { $bValido = FALSE; } if (!ereg('^[[:digit:]]{1,2}$', $day)) { $bValido = FALSE; } if ($bValido && !checkdate($month, $day, $year)) { $bValido = FALSE; } // Validación de zona horaria nueva $sZonaNueva = $_POST['TimeZone']; $listaZonas = leeZonas(); if (!in_array($sZonaNueva, $listaZonas)) { $sZonaNueva = $sZonaActual; } if (!$bValido) { // TODO: internacionalizar $smarty->assign("mb_message", _tr('Date not valid')); } else { if ($sZonaNueva != $sZonaActual) { $sComando = '/usr/bin/elastix-helper dateconfig' . ' --timezone ' . $sZonaNueva . ' 2>&1'; $output = $ret = NULL; exec($sComando, $output, $ret); if ($ret != 0) { $smarty->assign('mb_message', _tr('Failed to change timezone') . ' - ' . implode('<br/>', $output)); $bValido = FALSE; } } if ($bValido) { $sZonaActual = $sZonaNueva; $fecha = sprintf('%04d-%02d-%02d %02d:%02d:%02d', $year, $month, $day, $_POST['ServerDate_Hour'], $_POST['ServerDate_Minute'], $_POST['ServerDate_Second']); $cmd = "/usr/bin/elastix-helper dateconfig --datetime '{$fecha}' 2>&1"; $output = $ret_val = ""; exec($cmd, $output, $ret_val); if ($ret_val == 0) { $smarty->assign('mb_message', _tr('System time changed successfully')); } else { $smarty->assign('mb_message', _tr('System time can not be changed') . " - <br/>" . implode('<br/>', $output)); } } } return formTime($smarty, $module_name, $local_templates_dir, $listaZonas, $sZonaActual); }
function reportbilling_report($smarty, $module_name, $local_templates_dir, &$pDBSet, &$pDB, &$pRate, &$pDBTrunk, &$pDBSQLite, &$oCDR, $arrConf, $arrLang, $arrConfig) { $pbilling_report = new paloSantobilling_report($pDB); $filter_field = getParameter("filter_field"); //combo $filter_value = getParameter("filter_value"); //textfield $start_date_tmp = getParameter("date_start"); $end_date_tmp = getParameter("date_end"); $horas = getParameter("horas"); $minutos = getParameter("minutos"); $segundos = getParameter("segundos"); $action = getParameter("nav"); $start = getParameter("start"); $arrColumns = ""; $hourToSec = ""; $minToSec = ""; $style_time = ""; $style_text = ""; $filter_value_tmp = ""; $time = 0; if ($filter_field == 'duration') { $filter_value = ""; if (isset($horas)) { $hourToSec = $horas * 3600; $_POST['horas'] = $horas; } else { $hourToSec = 0; $_POST['horas'] = $hourToSec; } if (isset($minutos)) { $minToSec = $minutos * 60; $_POST['minutos'] = $minutos; } else { $minToSec = 0; $_POST['minutos'] = $minToSec; } if (isset($segundos)) { $_POST['segundos'] = $segundos; } else { $segundos = 0; $_POST['segundos'] = $segundos; } $time = $hourToSec + $minToSec + $segundos; $_POST['filter_value'] = $filter_value; $style_time = "style='display: block;'"; $style_text = "style='display: none;'"; } else { $horas = ""; $minutos = ""; $segundos = ""; $_POST['horas'] = $horas; $_POST['minutos'] = $minutos; $_POST['segundos'] = $segundos; $_POST['filter_value'] = $filter_value; if ($filter_field == "dst" || $filter_field == "rate_applied" || $filter_field == "dstchannel") { if ($filter_value != "") { $filter_value_tmp = $pDB->DBCAMPO('%' . $filter_value . '%'); } else { $filter_value_tmp = ""; } } else { if ($filter_value != "") { $filter_value_tmp = $pDB->DBCAMPO($filter_value); } else { $filter_value_tmp = ""; } } $style_time = "style='display: none;'"; $style_text = "style='display: block;'"; } if (isset($start_date_tmp)) { $start_date = translateDate($start_date_tmp) . " 00:00:00"; $_POST['date_start'] = $start_date_tmp; } else { $start_date = date("Y-m-d") . " 00:00:00"; $_POST['date_start'] = date("d M Y"); } if (isset($end_date_tmp)) { $end_date = translateDate($end_date_tmp) . " 23:59:59"; $_POST['date_end'] = $end_date_tmp; } else { $end_date = date("Y-m-d") . " 23:59:59"; $_POST['date_end'] = date("d M Y"); } $smarty->assign("style_time", $style_time); $smarty->assign("style_text", $style_text); //begin grid parameters $oGrid = new paloSantoGrid($smarty); $arrData = array(); $arrData = null; $extension = ""; $totalbilling_report = $pbilling_report->obtainNumReport($filter_field, $filter_value_tmp, $start_date, $end_date, $pDBSQLite, $time, "ANSWERED", "outgoing", $arrConfig); $url = array('menu' => $module_name, 'filter_field' => $filter_field, 'filter_value' => $filter_value, 'date_start' => $_POST['date_start'], 'date_end' => $_POST['date_end'], 'horas' => $horas, 'minutos' => $minutos, 'segundos' => $segundos); $oGrid->enableExport(); // enable csv export. $oGrid->pagingShow(true); // show paging section. $oGrid->setTitle(_tr("Billing Report")); $oGrid->setNameFile_Export("Billing_Report"); $oGrid->setURL($url); $arr_rates = $pbilling_report->getRates($pDBSQLite); if ($oGrid->isExportAction()) { $limit = $totalbilling_report; $offset = 0; $arrResult = $pbilling_report->obtainReport($limit, $offset, $filter_field, $filter_value_tmp, $start_date, $end_date, $pDBSQLite, $time, "ANSWERED", "outgoing", $arrConfig); $arrData = array(); // obteniendo tarifa default $rates_default = $pbilling_report->getDefaultRate($pDBSQLite); $rate = $rates_default['rate']; $sum_cost = 0; $rate_offset_default = $rates_default['rate_offset']; if (is_array($arrResult) && $totalbilling_report > 0) { foreach ($arrResult as $key => $value) { $arrTmp[0] = $value['Date']; $hidden_digits = $value['digits']; if ($value['Rate_applied'] == null) { $arrRateTmp = getRate($arr_rates, $value); $value['Rate_applied'] = $arrRateTmp['Rate_applied']; $value['Rate_value'] = $arrRateTmp['Rate_value']; $value['Offset'] = $arrRateTmp['Offset']; $hidden_digits = $arrRateTmp['digits']; } if ($value['Rate_applied'] == null) { $rate_applied = $arrLang['default']; } else { $rate_applied = $value['Rate_applied']; } $arrTmp[1] = $rate_applied; if ($value['Rate_value'] == null) { $rate_value = $rate; } else { $rate_value = $value['Rate_value']; } if ($value['Offset'] == null) { $rate_offset = $rate_offset_default; } else { $rate_offset = $value['Offset']; } if ($hidden_digits == 0) { $destination = $value['Destination']; } else { $size_destination = strlen($value['Destination']); if ($hidden_digits < $size_destination) { $hide = getCharsAsterisk($hidden_digits); $destination = substr($value['Destination'], 0, -$hidden_digits) . $hide; } else { $size_destination = strlen($value['Destination']); $destination = getCharsAsterisk($size_destination); } } $arrTmp[2] = $rate_value; $arrTmp[3] = $value['Src']; $arrTmp[4] = $destination; $arrTmp[5] = $value['Dst_channel']; $arrTmp[6] = $value['accountcode']; $iDuracion = $value['duration']; $iSec = $iDuracion % 60; $iDuracion = (int) (($iDuracion - $iSec) / 60); $iMin = $iDuracion % 60; $iDuracion = (int) (($iDuracion - $iMin) / 60); $sTiempo = $value['duration'] . "s"; if ($value['duration'] >= 60) { if ($iDuracion > 0) { $sTiempo .= " ({$iDuracion}h {$iMin}m {$iSec}s)"; } elseif ($iMin > 0) { $sTiempo .= " ({$iMin}m {$iSec}s)"; } } $arrTmp[7] = $sTiempo; $charge = $value['duration'] / 60 * $rate_value + $rate_offset; $arrTmp[8] = number_format($charge, 3); $sum_cost = $sum_cost + $arrTmp[8]; $arrTmp[9] = $sum_cost; $arrData[] = $arrTmp; } } $arrColumns = array(_tr("Date"), _tr("Rate Applied"), _tr("Rate Value"), _tr("Source"), _tr("Destination"), _tr("Dst. Channel"), _tr("Account Code"), _tr("Duration"), _tr("Cost"), _tr("Summary Cost")); } else { $limit = 20; $oGrid->setLimit($limit); $oGrid->setTotal($totalbilling_report); $offset = $oGrid->calculateOffset(); $arrResult = $pbilling_report->obtainReport($limit, $offset, $filter_field, $filter_value_tmp, $start_date, $end_date, $pDBSQLite, $time, "ANSWERED", "outgoing", $arrConfig); $arrData = array(); // obteniendo tarifa default $rates_default = $pbilling_report->getDefaultRate($pDBSQLite); $rate = $rates_default['rate']; $sum_cost = 0; $rate_offset_default = $rates_default['rate_offset']; if (is_array($arrResult) && $totalbilling_report > 0) { foreach ($arrResult as $key => $value) { $arrTmp[0] = $value['Date']; $hidden_digits = $value['digits']; if ($value['Rate_applied'] == null) { $arrRateTmp = getRate($arr_rates, $value); $value['Rate_applied'] = $arrRateTmp['Rate_applied']; $value['Rate_value'] = $arrRateTmp['Rate_value']; $value['Offset'] = $arrRateTmp['Offset']; $hidden_digits = $arrRateTmp['digits']; } if ($value['Rate_applied'] == null) { $rate_applied = $arrLang['default']; } else { $rate_applied = $value['Rate_applied']; } $arrTmp[1] = $rate_applied; if ($value['Rate_value'] == null) { $rate_value = $rate; } else { $rate_value = $value['Rate_value']; } if ($value['Offset'] == null) { $rate_offset = $rate_offset_default; } else { $rate_offset = $value['Offset']; } if ($hidden_digits == 0) { $destination = $value['Destination']; } else { $size_destination = strlen($value['Destination']); if ($hidden_digits < $size_destination) { $hide = getCharsAsterisk($hidden_digits); $destination = substr($value['Destination'], 0, -$hidden_digits) . $hide; } else { $size_destination = strlen($value['Destination']); $destination = getCharsAsterisk($size_destination); } } $arrTmp[2] = $rate_value; $arrTmp[3] = $value['Src']; $arrTmp[4] = $destination; $arrTmp[5] = $value['Dst_channel']; $arrTmp[6] = $value['accountcode']; $iDuracion = $value['duration']; $iSec = $iDuracion % 60; $iDuracion = (int) (($iDuracion - $iSec) / 60); $iMin = $iDuracion % 60; $iDuracion = (int) (($iDuracion - $iMin) / 60); $sTiempo = $value['duration'] . "s"; if ($value['duration'] >= 60) { if ($iDuracion > 0) { $sTiempo .= " ({$iDuracion}h {$iMin}m {$iSec}s)"; } elseif ($iMin > 0) { $sTiempo .= " ({$iMin}m {$iSec}s)"; } } $arrTmp[7] = $sTiempo; $charge = $value['duration'] / 60 * $rate_value + $rate_offset; $arrTmp[8] = number_format($charge, 3); $sum_cost = $sum_cost + $arrTmp[8]; $arrTmp[9] = $sum_cost; $arrData[] = $arrTmp; } } $arrColumns = array(_tr("Date"), _tr("Rate Applied"), _tr("Rate Value"), _tr("Source"), _tr("Destination"), _tr("Dst. Channel"), _tr("Account Code"), _tr("Duration"), _tr("Cost"), _tr("Summary Cost")); } $oGrid->setColumns($arrColumns); $oGrid->setData($arrData); //begin section filter $arrFormFilterbilling_report = createFieldFilter($arrLang); if ($_POST['date_start'] === "") { $_POST['date_start'] = " "; } if ($_POST['date_end'] === "") { $_POST['date_end'] = " "; } $oGrid->addFilterControl(_tr("Filter applied: ") . _tr("Start Date") . " = " . $_POST['date_start'] . ", " . _tr("End Date") . " = " . $_POST['date_end'], $_POST, array('date_start' => date("d M Y"), 'date_end' => date("d M Y")), true); if (!is_null($filter_field)) { $valueFilterField = $arrFormFilterbilling_report['filter_field']["INPUT_EXTRA_PARAM"][$filter_field]; } else { $valueFilterField = ""; } if (!is_null($filter_field)) { if ($filter_field == "duration") { $oGrid->addFilterControl(_tr("Filter applied: ") . $valueFilterField . " = " . $_POST['horas'] . "H:" . $_POST['minutos'] . "M:" . $_POST['segundos'] . "S", $_POST, array('filter_field' => "dst", 'horas' => "", "minutos" => "", "segundos" => "")); } else { $oGrid->addFilterControl(_tr("Filter applied: ") . $valueFilterField . " = " . $filter_value, $_POST, array('filter_field' => "src", 'filter_value' => "")); } } $oFilterForm = new paloForm($smarty, $arrFormFilterbilling_report); $smarty->assign("SHOW", _tr("Show")); $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_POST); $oGrid->showFilter(trim($htmlFilter)); $content = $oGrid->fetchGrid(); return $content; }
function _moduleContent(&$smarty, $module_name) { global $arrConf; global $arrConfModule; //include module files include_once "modules/{$module_name}/configs/default.conf.php"; include_once "modules/{$module_name}/libs/paloSantoTiempoConexiondeAgentes.class.php"; include_once "libs/paloSantoConfig.class.php"; $arrConf = array_merge($arrConf, $arrConfModule); // Obtengo la ruta del template a utilizar para generar el filtro. $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']; load_language_module($module_name); //conexion resource $pConfig = new paloConfig("/etc", "amportal.conf", "=", "[[:space:]]*=[[:space:]]*"); $arrConfig = $pConfig->leer_configuracion(false); $dsnAsteriskCdr = $arrConfig['AMPDBENGINE']['valor'] . "://" . $arrConfig['AMPDBUSER']['valor'] . ":" . $arrConfig['AMPDBPASS']['valor'] . "@" . $arrConfig['AMPDBHOST']['valor'] . "/asterisk"; $pDB = new paloDB($arrConf['dsn_conn_database']); $pDB_asterisk = new paloDB($dsnAsteriskCdr); $oCallsAgent = new paloSantoTiempoConexiondeAgentes($pDB); // Variables estáticas asignadas vía Smarty $smarty->assign(array("Filter" => _tr('Show'))); $bElastixNuevo = method_exists('paloSantoGrid', 'setURL'); $oGrid = new paloSantoGrid($smarty); $bExportando = $bElastixNuevo ? $oGrid->isExportAction() : isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes'; // Estas son las colas entrantes disponibles en el sistema $arrQueue = leerColasEntrantes($pDB, $pDB_asterisk); $t = array_keys($arrQueue); if (count($t) <= 0) { // TODO: internacionalizar y poner en plantilla return <<<NO_QUEUE_END <p><b>No queues have been defined for incoming calls.</b></p> <p>For proper operation and reporting, it is necessary to configure at least one queue. You can add queues <a href="?menu=pbxconfig&display=queues">here</a>. In addition, the queue must be registered for use by incoming calls by clicking <a href="?menu=queues">here</a>.</p> NO_QUEUE_END; } $sColaOmision = $t[0]; //Esto es para validar cuando recien se entra al modulo, para q aparezca seteado un numero de agente en el textbox // TODO: reemplazar con lista desplegable de agentes en cola elegida $sAgenteOmision = $oCallsAgent->obtener_agente(); $arrFormElements = createFieldFilter($arrQueue); $oFilterForm = new paloForm($smarty, $arrFormElements); // Valores iniciales de las variables $paramConsulta = array('date_start' => date('d M Y'), 'date_end' => date('d M Y'), 'queue' => $sColaOmision, 'agent' => $sAgenteOmision); foreach (array_keys($paramConsulta) as $k) { if (isset($_GET[$k])) { $paramConsulta[$k] = $_GET[$k]; } if (isset($_POST[$k])) { $paramConsulta[$k] = $_POST[$k]; } } if ($oFilterForm->validateForm($paramConsulta)) { // Exito, puedo procesar los datos ahora. } else { // Error $smarty->assign("mb_title", _tr("Validation Error")); $arrErrores = $oFilterForm->arrErroresValidacion; $strErrorMsg = "<b>" . _tr('Required field') . ":</b><br/>"; foreach ($arrErrores as $k => $v) { $strErrorMsg .= "{$k}, "; } $strErrorMsg .= ""; $smarty->assign("mb_message", $strErrorMsg); $paramConsulta = array('date_start' => date('d M Y'), 'date_end' => date('d M Y'), 'queue' => $sColaOmision, 'agent' => $sAgenteOmision); } // Se genera el filtro con las variables ya validadas $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $paramConsulta); // Consultar los datos y generar la matriz del reporte $sFechaInicial = translateDate($paramConsulta['date_start']); $sFechaFinal = translateDate($paramConsulta['date_end']); $r = $oCallsAgent->reportarBreaksAgente($paramConsulta['agent'], $paramConsulta['queue'], $sFechaInicial, $sFechaFinal); $b = $bExportando ? array('', '') : array('<b>', '</b>'); $ub = $bExportando ? array('', '') : array('<u><b>', '</b></u>'); $arrData = array(); if (is_array($r) && count($r) > 0) { $tempTiempos = array('monitoreadas' => 0, 'llamadas_por_hora' => 0, 'duracion_llamadas' => 0, 'promedio_duracion' => 0, 'total_llamadas' => 0); foreach ($r['tiempos_llamadas'] as $tupla) { $tempTiempos['llamadas_por_hora'] = $tempTiempos['total_llamadas'] += $tupla['N']; $tempTiempos['duracion_llamadas'] += $tupla['tiempo_llamadas_entrantes']; if ($tupla['status'] == 'terminada') { $tempTiempos['monitoreadas'] = $tupla['N']; $tempTiempos['promedio_duracion'] = $tupla['promedio_sobre_monitoreadas']; } } if ($r['tiempo_conexion'] > 0) { $tempTiempos['llamadas_por_hora'] /= $r['tiempo_conexion'] / 3600; } $sFormatoMonitoreadas = sprintf('%d %s(s) (%d %s, %d %s)', $tempTiempos['total_llamadas'], _tr('Call'), $tempTiempos['monitoreadas'], _tr('Monitored'), $tempTiempos['total_llamadas'] - $tempTiempos['monitoreadas'], _tr('Unmonitored')); $arrData = array(array($b[0] . strtoupper(_tr('Agent name')) . $b[1], $r['name'], "", ""), array($b[0] . strtoupper(_tr('Conecction Data')) . $b[1], "", "", ""), array(_tr('First Conecction'), $r['primera_conexion'], "", ""), array(_tr('Last Conecction'), $r['ultima_conexion'], "", ""), array(_tr('Time Conecction'), formatoSegundos($r['tiempo_conexion']), "", ""), array(_tr('Count Conecction'), $r['conteo_conexion'], "", ""), array($b[0] . strtoupper(_tr('Calls Entry')) . $b[1], "", "", ""), array(_tr('Count Calls Entry'), $sFormatoMonitoreadas, "", ""), array(_tr('Calls/h'), number_format($tempTiempos['llamadas_por_hora'], 2), "", ""), array(_tr('Time Call Entry'), formatoSegundos($tempTiempos['duracion_llamadas']), "", ""), array(_tr('Average Calls Entry'), $tempTiempos['promedio_duracion'] . " (" . _tr('Monitored only') . ')', "", ""), array($b[0] . strtoupper(_tr('Reason No Ready')) . $b[1], "", "", ""), array($ub[0] . _tr('Break') . $ub[1], $ub[0] . _tr('Count') . $ub[1], $ub[0] . _tr('Hour') . $ub[1], $ub[0] . _tr('Porcent compare whit time not ready') . $ub[1])); $tempBreaks = array(); $iTotalSeg = 0; foreach ($r['tiempos_breaks'] as $tupla) { $tempBreaks[] = array($tupla['name'], $tupla['N'], formatoSegundos($tupla['total_break']), $tupla['total_break']); $iTotalSeg += $tupla['total_break']; } for ($i = 0; $i < count($tempBreaks); $i++) { $tempBreaks[$i][3] = number_format(100.0 * ($tempBreaks[$i][3] / $iTotalSeg), 2) . ' %'; $arrData[] = $tempBreaks[$i]; } } else { if (!is_array($r)) { $smarty->assign("mb_title", _tr("Database Error")); $smarty->assign("mb_message", $oCallsAgent->errMsg); } $arrData[] = array($b[0] . _tr("There aren't records to show") . $b[1], '', '', ''); } // Creo objeto de grid $oGrid->enableExport(); $oGrid->showFilter($htmlFilter); // La definición del grid $paramConsulta['menu'] = $module_name; if ($bElastixNuevo) { $oGrid->setURL(construirURL($paramConsulta)); $oGrid->setData($arrData); $arrColumnas = array("", "", "", ""); $oGrid->setColumns($arrColumnas); $oGrid->setTitle(_tr("Agent Information")); $oGrid->pagingShow(false); $oGrid->setNameFile_Export(_tr("Agent Information")); $smarty->assign("SHOW", _tr("Show")); return $oGrid->fetchGrid(); } else { global $arrLang; $total = $end = count($arrData); $offset = 0; $url = construirUrl($paramConsulta); $arrGrid = array("title" => _tr("Time conecction of agents"), "icon" => "images/list.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $end, "total" => $total, "url" => $url, "columns" => array(0 => array("name" => "", "property" => ""), 1 => array("name" => "", "property" => ""), 2 => array("name" => "", "property" => ""), 3 => array("name" => "", "property" => ""))); if ($bExportando) { $fechaActual = date("d M Y"); header("Cache-Control: private"); header("Pragma: cache"); $title = $fechaActual; header('Content-Type: text/csv; charset=utf-8; header=present'); header("Content-disposition: attachment; filename=\"" . $title . ".csv\""); } if ($bExportando) { return $oGrid->fetchGridCSV($arrGrid, $arrData); } $sContenido = $oGrid->fetchGrid($arrGrid, $arrData, $arrLang); if (strpos($sContenido, '<form') === FALSE) { $sContenido = "<form method=\"POST\" style=\"margin-bottom:0;\" action=\"{$url}\">{$sContenido}</form>"; } return $sContenido; } }
echo "</div>"; echo "<br />"; echo "<div class='form-group'>"; echo "<input name='submit' type='submit' class='form-control' value='Envoyer' />"; echo "</div>"; echo "</form>"; $html = file_get_html($url); $annonces = array(); echo "<a href='{$url}' target='_blank' title='{$url}'>Voir cette recherche sur Le Bon Coin .fr</a>"; echo "<hr />"; foreach ($html->find('.list-lbc a') as $annonce) { $annonce_id = parse_url($annonce->href); $annonce_id = $annonce_id['path']; $annonce_id = preg_match_all('!\\d+!', $annonce_id, $matches); $annonce_id = $matches[0][0]; $annonces[] = array('id' => $annonce_id, 'title' => trim($annonce->find('.lbc .detail .title', 0)->plaintext), 'url' => $annonce->href, 'timestamp' => translateDate(trim(strip_tags($annonce->find('.lbc .date', 0)->innertext))), 'price' => trim($annonce->find('.lbc .detail .price', 0)->plaintext), 'image' => trim($annonce->find('.lbc .image .image-and-nb img', 0)->src)); } $last_annonce = $annonces[0]['timestamp']; $annonces_new = $annonces; $annonces_old = unserialize(file_get_contents('datas/annonces.txt')); function udiffCompare($a, $b) { return $a['id'] - $b['id']; } $diff = array_udiff($annonces_new, $annonces_old, 'udiffCompare'); if (!empty($diff) or $_GET["viewold"] == "1") { $i = 1; if ($_GET["viewold"] == "1") { $diff = $annonces; } echo "<div class='container-fluid'>";
function _moduleContent(&$smarty, $module_name) { //include module files include_once "libs/paloSantoForm.class.php"; include_once "modules/{$module_name}/configs/default.conf.php"; load_language_module($module_name); //global variables 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']; $smarty->assign("TIME_TITULO", _tr("Date and Time Configuration")); $smarty->assign("INDEX_HORA_SERVIDOR", _tr("Current Datetime")); $smarty->assign("TIME_NUEVA_FECHA", _tr("New Date")); $smarty->assign("TIME_NUEVA_HORA", _tr("New Time")); $smarty->assign("TIME_NUEVA_ZONA", _tr("New Timezone")); $smarty->assign("INDEX_ACTUALIZAR", _tr("Apply changes")); $smarty->assign("TIME_MSG_1", _tr("The change of date and time can concern important system processes.") . ' ' . _tr("Are you sure you wish to continue?")); $arrForm = array(); $oForm = new paloForm($smarty, $arrForm); /* Para cambiar la zona horaria: 1) Abrir y mostrar columna 3 de /usr/share/zoneinfo/zone.tab que muestra todas las zonas horarias. 2) Al elegir fila de columna 3, verificar que sea de la forma abc/def y que existe el directorio /usr/share/zoneinfo/abc/def . Pueden haber N elementos en la elección, separados por / , incluyendo uno solo (sin / alguno) 3) Si existe /etc/localtime, borrarlo 4) Copiar archivo /usr/share/zoneinfo/abc/def a /etc/localtime 5) Si existe /var/spool/postfix/etc/localtime , removerlo y sobreescribr con el mismo archivo copiado a /etc/localtime Luego de esto, ejecutar cambio de hora local */ // Abrir el archivo /usr/share/zoneinfo/zone.tab y cargar la columna 3 // Se ignoran líneas que inician con # $listaZonas = NULL; $hArchivo = fopen('/usr/share/zoneinfo/zone.tab', 'r'); if ($hArchivo) { $listaZonas = array(); while ($tupla = fgetcsv($hArchivo, 2048, "\t")) { if (count($tupla) >= 3 && $tupla[0][0] != '#') { $listaZonas[] = $tupla[2]; } } fclose($hArchivo); sort($listaZonas); } // Cargar de /etc/sysconfig/clock la supuesta zona horaria configurada. // El resto de contenido del archivo se preserva, y la clave ZONE se // escribirá como la última línea en caso de actualizar $sZonaActual = "America/New_York"; $infoZona = NULL; $hArchivo = fopen('/etc/sysconfig/clock', 'r'); if ($hArchivo) { $infoZona = array(); while (!feof($hArchivo)) { $s = fgets($hArchivo); $regs = NULL; if (ereg('^ZONE="(.*)"', $s, $regs)) { $sZonaActual = $regs[1]; } else { $infoZona[] = $s; } } fclose($hArchivo); } if (isset($_POST['Actualizar'])) { // print '<pre>';print_r($_POST);print '</pre>'; $date = getParameter("date"); $date = translateDate($date); $date = explode("-", $date); $month = ""; $year = ""; $day = ""; if (isset($date[0]) && isset($date[1]) && isset($date[2])) { $month = $date[1]; $day = $date[2]; $year = $date[0]; } // Validación básica $listaVars = array('ServerDate_Hour' => '^[[:digit:]]{1,2}$', 'ServerDate_Minute' => '^[[:digit:]]{1,2}$', 'ServerDate_Second' => '^[[:digit:]]{1,2}$'); $bValido = TRUE; foreach ($listaVars as $sVar => $sReg) { if (!ereg($sReg, $_POST[$sVar])) { $bValido = FALSE; } } if (!ereg('^[[:digit:]]{4}$', $year)) { $bValido = FALSE; } if (!ereg('^[[:digit:]]{1,2}$', $month)) { $bValido = FALSE; } if (!ereg('^[[:digit:]]{1,2}$', $day)) { $bValido = FALSE; } if ($bValido && !checkdate($month, $day, $year)) { $bValido = FALSE; } // Validación de zona horaria nueva $sZonaNueva = $_POST['TimeZone']; if (!in_array($sZonaNueva, $listaZonas)) { $sZonaNueva = $sZonaActual; } if (!$bValido) { // TODO: internacionalizar $smarty->assign("mb_message", _tr('Date not valid')); } else { if ($sZonaNueva != $sZonaActual) { $sComando = '/usr/bin/elastix-helper dateconfig' . ' --timezone ' . $sZonaNueva . ' 2>&1'; $output = $ret = NULL; exec($sComando, $output, $ret); if ($ret != 0) { $smarty->assign('mb_message', _tr('Failed to change timezone') . ' - ' . implode('<br/>', $output)); $bValido = FALSE; } } if ($bValido) { $sZonaActual = $sZonaNueva; $fecha = sprintf('%04d-%02d-%02d %02d:%02d:%02d', $year, $month, $day, $_POST['ServerDate_Hour'], $_POST['ServerDate_Minute'], $_POST['ServerDate_Second']); $cmd = "/usr/bin/elastix-helper dateconfig --datetime '{$fecha}' 2>&1"; $output = $ret_val = ""; exec($cmd, $output, $ret_val); if ($ret_val == 0) { $smarty->assign('mb_message', _tr('System time changed successfully')); } else { $smarty->assign('mb_message', _tr('System time can not be changed') . " - <br/>" . implode('<br/>', $output)); } } } } $sContenido = ''; $mes = date("m", time()); $mes = (int) $mes - 1; $smarty->assign("CURRENT_DATETIME", strftime("%Y,{$mes},%d,%H,%M,%S", time())); $smarty->assign('LISTA_ZONAS', $listaZonas); $smarty->assign('ZONA_ACTUAL', $sZonaActual); $smarty->assign("CURRENT_DATE", strftime("%d %b %Y", time())); $smarty->assign("icon", "modules/{$module_name}/images/system_preferences_datetime.png"); $sContenido .= $oForm->fetchForm("{$local_templates_dir}/time.tpl", _tr('Date and Time Configuration'), $_POST); return $sContenido; }