function leerColasEntrantesValidas()
 {
     //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_asterisk = new paloDB($dsnAsteriskCdr);
     $oQueue = new paloQueue($pDB_asterisk);
     $PBXQueues = $oQueue->getQueue();
     $arrQueue = array();
     if (is_array($PBXQueues)) {
         foreach ($PBXQueues as $key => $value) {
             $result = $this->_DB->getFirstRowQuery('SELECT id, queue from queue_call_entry where queue = ?', TRUE, array($value[0]));
             if (is_array($result) && count($result) > 0) {
                 // La clave debe ser cadena para que in_array en paloForm funcione
                 $arrQueue[$result['id']] = $result['queue'];
             }
         }
     }
     return $arrQueue;
 }
Beispiel #2
0
function formularioModificarCola($pDB, $smarty, $module_name, $local_templates_dir, $idCola)
{
    require_once "libs/paloSantoForm.class.php";
    require_once "libs/paloSantoQueue.class.php";
    // Si se ha indicado cancelar, volver a listado sin hacer nada más
    if (isset($_POST['cancel'])) {
        Header("Location: ?menu={$module_name}");
        return '';
    }
    $smarty->assign(array('FRAMEWORK_TIENE_TITULO_MODULO' => existeSoporteTituloFramework(), 'icon' => 'images/kfaxview.png', 'SAVE' => _tr('guardar'), 'CANCEL' => _tr('cancelar'), 'id_queue' => $idCola));
    // Leer todas las colas disponibles
    $dsnAsterisk = generarDSNSistema('asteriskuser', 'asterisk');
    $oDBAsterisk = new paloDB($dsnAsterisk);
    $oQueue = new paloQueue($oDBAsterisk);
    $arrQueues = $oQueue->getQueue();
    if (!is_array($arrQueues)) {
        $smarty->assign("mb_title", _tr('Unable to read queues'));
        $smarty->assign("mb_message", _tr('Cannot read queues') . ' - ' . $oQueue->errMsg);
        $arrQueues = array();
    }
    $oColas = new paloSantoColaEntrante($pDB);
    // Leer todos los datos de la cola entrante, si es necesario
    $arrColaEntrante = NULL;
    if (!is_null($idCola)) {
        $arrColaEntrante = $oColas->leerColas($idCola);
        if (!is_array($arrColaEntrante) || count($arrColaEntrante) == 0) {
            $smarty->assign("mb_title", _tr('Unable to read incoming queue'));
            $smarty->assign("mb_message", _tr('Cannot read incoming queue') . ' - ' . $oColas->errMsg);
            return '';
        }
    }
    /* Para nueva cola, se deben remover las colas ya usadas. Para cola 
     * modificada, sólo se muestra la cola que ya estaba asignada. */
    if (is_null($idCola)) {
        // Filtrar las colas que ya han sido usadas
        $arrFilterQueues = $oColas->filtrarColasUsadas($arrQueues);
    } else {
        // Colocar sólo la información de la cola asignada
        $arrFilterQueues = array();
        foreach ($arrQueues as $tuplaQueue) {
            if ($tuplaQueue[0] == $arrColaEntrante[0]['queue']) {
                $arrFilterQueues[] = $tuplaQueue;
            }
        }
    }
    $arrDataQueues = array();
    foreach ($arrFilterQueues as $tuplaQueue) {
        $arrDataQueues[$tuplaQueue[0]] = $tuplaQueue[1];
    }
    // Valores por omisión para primera carga
    if (is_null($idCola)) {
        if (!isset($_POST['select_queue']) && count($arrFilterQueues) > 0) {
            $_POST['select_queue'] = $arrFilterQueues[0][0];
        }
        if (!isset($_POST['rte_script'])) {
            $_POST['rte_script'] = '';
        }
    } else {
        $_POST['select_queue'] = $arrColaEntrante[0]['queue'];
        if (!isset($_POST['rte_script'])) {
            $_POST['rte_script'] = $arrColaEntrante[0]['script'];
        }
    }
    // rte_script es un HTML complejo que debe de construirse con Javascript.
    $smarty->assign("rte_script", adaptar_formato_rte($_POST['rte_script']));
    // Generación del objeto de formulario
    $form_campos = array("script" => array("LABEL" => _tr('Script'), "REQUIRED" => "yes", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "", "VALIDATION_EXTRA_PARAM" => ""), 'select_queue' => array("REQUIRED" => "yes", "LABEL" => is_null($idCola) ? _tr('Select Queue') . ' :' : _tr('Queue'), "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => $arrDataQueues, "VALIDATION_TYPE" => "numeric", "VALIDATION_EXTRA_PARAM" => ""));
    $oForm = new paloForm($smarty, $form_campos);
    // Ejecutar el guardado de los cambios
    if (isset($_POST['save'])) {
        if (!$oForm->validateForm($_POST) || (!isset($_POST['rte_script']) || $_POST['rte_script'] == '')) {
            // Falla la validación básica del formulario
            $smarty->assign("mb_title", _tr("Validation Error"));
            $arrErrores = $oForm->arrErroresValidacion;
            $strErrorMsg = "<b>" . _tr('The following fields contain errors') . ":</b><br/>";
            if (is_array($arrErrores) && count($arrErrores) > 0) {
                foreach ($arrErrores as $k => $v) {
                    $strErrorMsg .= "{$k}, ";
                }
            }
            if (!isset($_POST['rte_script']) || $_POST['rte_script'] == '') {
                $strErrorMsg .= _tr("Script");
            }
            $strErrorMsg .= "";
            $smarty->assign("mb_message", $strErrorMsg);
        } else {
            $bExito = $oColas->iniciarMonitoreoCola($_POST['select_queue'], $_POST['rte_script']);
            if (!$bExito) {
                $smarty->assign("mb_title", _tr('Unable to save incoming queue'));
                $smarty->assign("mb_message", $oColas->errMsg);
            } else {
                Header("Location: ?menu={$module_name}");
            }
        }
    }
    return $oForm->fetchForm("{$local_templates_dir}/form.tpl", is_null($idCola) ? _tr('Select Queue') : _tr('Edit Queue'), null);
}
Beispiel #3
0
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;
    }
}
Beispiel #4
0
function formEditCampaign($pDB, $smarty, $module_name, $local_templates_dir, $id_campaign = NULL)
{
    include_once "libs/paloSantoQueue.class.php";
    include_once "modules/form_designer/libs/paloSantoDataForm.class.php";
    // Si se ha indicado cancelar, volver a listado sin hacer nada más
    if (isset($_POST['cancel'])) {
        Header("Location: ?menu={$module_name}");
        return '';
    }
    $smarty->assign('FRAMEWORK_TIENE_TITULO_MODULO', existeSoporteTituloFramework());
    // Leer los datos de la campaña, si es necesario
    $arrCampaign = NULL;
    $oCamp = new paloSantoCampaignCC($pDB);
    if (!is_null($id_campaign)) {
        $arrCampaign = $oCamp->getCampaigns(null, null, $id_campaign);
        if (!is_array($arrCampaign) || count($arrCampaign) == 0) {
            $smarty->assign("mb_title", 'Unable to read campaign');
            $smarty->assign("mb_message", 'Cannot read campaign - ' . $oCamp->errMsg);
            return '';
        }
    }
    // Obtener y conectarse a base de datos de FreePBX
    $pConfig = new paloConfig("/etc", "amportal.conf", "=", "[[:space:]]*=[[:space:]]*");
    $arrConfig = $pConfig->leer_configuracion(false);
    $dsn = $arrConfig['AMPDBENGINE']['valor'] . "://" . $arrConfig['AMPDBUSER']['valor'] . ":" . $arrConfig['AMPDBPASS']['valor'] . "@" . $arrConfig['AMPDBHOST']['valor'] . "/asterisk";
    $oDB = new paloDB($dsn);
    // Leer las troncales que se han definido en FreePBX
    $arrDataTrunks = array('' => '(' . _tr('By Dialplan') . ')');
    $arrTrunks = getTrunks($oDB);
    //obtener la lista de trunks
    if (is_array($arrTrunks)) {
        foreach ($arrTrunks as $trunk) {
            $arrDataTrunks[$trunk[1]] = $trunk[1];
        }
    }
    // Leer las colas que se han definido en FreePBX, y quitar las usadas
    // en campañas entrantes.
    $arrDataQueues = array();
    $oQueue = new paloQueue($oDB);
    $arrQueues = $oQueue->getQueue();
    // Todas las colas, entrantes y salientes
    if (is_array($arrQueues)) {
        $query_call_entry = "SELECT queue FROM queue_call_entry WHERE estatus = 'A'";
        $arr_call_entry = $pDB->fetchTable($query_call_entry);
        // Las colas entrantes
        $colasEntrantes = array();
        foreach ($arr_call_entry as $row) {
            $colasEntrantes[] = $row[0];
        }
        foreach ($arrQueues as $rowQueue) {
            if (!in_array($rowQueue[0], $colasEntrantes)) {
                $arrDataQueues[$rowQueue[0]] = $rowQueue[1];
            }
        }
    }
    $arrUrlsExternos = array('' => _tr('(No external URL)')) + $oCamp->getExternalUrls();
    // Cargar la información de todos los formularios creados y activos
    $oDataForm = new paloSantoDataForm($pDB);
    $arrDataForm = $oDataForm->getFormularios(NULL, 'A');
    // Impedir mostrar el formulario si no se han definido colas o no
    // quedan colas libres para usar en campañas salientes.
    if (count($arrQueues) <= 0) {
        $formCampos = getFormCampaign($arrDataTrunks, $arrDataQueues, NULL, NULL, NULL);
        $oForm = new paloForm($smarty, $formCampos);
        $smarty->assign('no_queues', 1);
    } elseif (count($arrDataQueues) <= 0) {
        $formCampos = getFormCampaign($arrDataTrunks, $arrDataQueues, NULL, NULL, NULL);
        $oForm = new paloForm($smarty, $formCampos);
        $smarty->assign('no_outgoing_queues', 1);
    } elseif (count($arrDataForm) <= 0) {
        $formCampos = getFormCampaign($arrDataTrunks, $arrDataQueues, NULL, NULL, NULL);
        $oForm = new paloForm($smarty, $formCampos);
        $smarty->assign('no_forms', 1);
    } else {
        $smarty->assign('label_manage_trunks', _tr('Manage Trunks'));
        $smarty->assign('label_manage_queues', _tr('Manage Queues'));
        $smarty->assign('label_manage_forms', _tr('Manage Forms'));
        $smarty->assign('label_manage_external_url', _tr('Manage External URLs'));
        // Definición del formulario de nueva campaña
        $smarty->assign("REQUIRED_FIELD", _tr("Required field"));
        $smarty->assign("CANCEL", _tr("Cancel"));
        $smarty->assign("SAVE", _tr("Save"));
        $smarty->assign("APPLY_CHANGES", _tr("Apply changes"));
        $smarty->assign('LABEL_CALL_FILE', _tr('Call File'));
        // Valores por omisión para primera carga
        $arrNoElegidos = array();
        // Lista de selección de formularios elegibles
        $arrElegidos = array();
        // Lista de selección de formularios ya elegidos
        $values_form = NULL;
        // Selección hecha en el formulario
        if (is_null($id_campaign)) {
            if (!isset($_POST['nombre'])) {
                $_POST['nombre'] = '';
            }
            if (!isset($_POST["context"]) || $_POST["context"] == "") {
                $_POST["context"] = "from-internal";
            }
            if (!isset($_POST['max_canales']) || $_POST['max_canales'] == '') {
                $_POST['max_canales'] = 23;
            }
            if (!isset($_POST['reintentos']) || $_POST['reintentos'] == '') {
                $_POST['reintentos'] = 5;
            }
            if (!isset($_POST['rte_script'])) {
                $_POST['rte_script'] = '';
            }
            if (!isset($_POST['values_form'])) {
                $_POST['values_form'] = '';
            }
            //$_POST['formulario']= explode(",", $_POST['values_form']);
            $values_form = explode(",", $_POST['values_form']);
        } else {
            if (!isset($_POST['nombre'])) {
                $_POST['nombre'] = $arrCampaign[0]['name'];
            }
            if (!isset($_POST['fecha_ini'])) {
                $_POST['fecha_ini'] = date('d M Y', strtotime($arrCampaign[0]['datetime_init']));
            }
            if (!isset($_POST['fecha_fin'])) {
                $_POST['fecha_fin'] = date('d M Y', strtotime($arrCampaign[0]['datetime_end']));
            }
            $arrDateTimeInit = explode(":", $arrCampaign[0]['daytime_init']);
            $arrDateTimeEnd = explode(":", $arrCampaign[0]['daytime_end']);
            if (!isset($_POST['hora_ini_HH'])) {
                $_POST['hora_ini_HH'] = isset($arrDateTimeInit[0]) ? $arrDateTimeInit[0] : "00";
            }
            if (!isset($_POST['hora_ini_MM'])) {
                $_POST['hora_ini_MM'] = isset($arrDateTimeInit[1]) ? $arrDateTimeInit[1] : "00";
            }
            if (!isset($_POST['hora_fin_HH'])) {
                $_POST['hora_fin_HH'] = isset($arrDateTimeEnd[0]) ? $arrDateTimeEnd[0] : "00";
            }
            if (!isset($_POST['hora_fin_MM'])) {
                $_POST['hora_fin_MM'] = isset($arrDateTimeEnd[1]) ? $arrDateTimeEnd[1] : "00";
            }
            if (!isset($_POST['reintentos'])) {
                $_POST['reintentos'] = $arrCampaign[0]['retries'];
            }
            if (!isset($_POST['trunk'])) {
                $_POST['trunk'] = $arrCampaign[0]['trunk'];
            }
            if (!isset($_POST['queue'])) {
                $_POST['queue'] = $arrCampaign[0]['queue'];
            }
            if (!isset($_POST['context'])) {
                $_POST['context'] = $arrCampaign[0]['context'];
            }
            if (!isset($_POST['max_canales'])) {
                $_POST['max_canales'] = $arrCampaign[0]['max_canales'];
            }
            //$_POST['script'] = "";
            if (!isset($_POST['rte_script'])) {
                $_POST['rte_script'] = $arrCampaign[0]['script'];
            }
            //if (!isset($_POST['formulario']))           $_POST['formulario'] = "";
            //if (!isset($_POST['formularios_elegidos'])) $_POST['formularios_elegidos'] = "";
            if (!isset($_POST['values_form'])) {
                $values_form = $oCamp->obtenerCampaignForm($id_campaign);
            } else {
                $values_form = explode(",", $_POST['values_form']);
            }
            if (!isset($_POST['external_url'])) {
                $_POST['external_url'] = $arrCampaign[0]['id_url'];
            }
        }
        // rte_script es un HTML complejo que debe de construirse con Javascript.
        $smarty->assign("rte_script", adaptar_formato_rte($_POST['rte_script']));
        // Clasificar los formularios elegidos y no elegidos
        foreach ($arrDataForm as $key => $form) {
            if (in_array($form['id'], $values_form)) {
                $arrElegidos[$form['id']] = $form['nombre'];
            } else {
                $arrNoElegidos[$form['id']] = $form['nombre'];
            }
        }
        // Generación del objeto de formulario
        $formCampos = getFormCampaign($arrDataTrunks, $arrDataQueues, $arrNoElegidos, $arrElegidos, $arrUrlsExternos);
        $oForm = new paloForm($smarty, $formCampos);
        if (!is_null($id_campaign)) {
            $oForm->setEditMode();
            $smarty->assign('id_campaign', $id_campaign);
        }
        // En esta implementación el formulario trabaja exclusivamente en modo 'input'
        // y por lo tanto proporciona el botón 'save'
        $bDoCreate = isset($_POST['save']);
        $bDoUpdate = isset($_POST['apply_changes']);
        if ($bDoCreate || $bDoUpdate) {
            if (!$oForm->validateForm($_POST) || (!isset($_POST['rte_script']) || $_POST['rte_script'] == '')) {
                // Falla la validación básica del formulario
                $smarty->assign("mb_title", _tr("Validation Error"));
                $arrErrores = $oForm->arrErroresValidacion;
                $strErrorMsg = "<b>" . _tr('The following fields contain errors') . ":</b><br/>";
                if (is_array($arrErrores) && count($arrErrores) > 0) {
                    foreach ($arrErrores as $k => $v) {
                        $strErrorMsg .= "{$k}, ";
                    }
                }
                if (!isset($_POST['rte_script']) || $_POST['rte_script'] == '') {
                    $strErrorMsg .= _tr("Script");
                }
                $strErrorMsg .= "";
                $smarty->assign("mb_message", $strErrorMsg);
            } elseif ($_POST['max_canales'] <= 0) {
                $smarty->assign("mb_title", _tr("Validation Error"));
                $smarty->assign("mb_message", _tr('At least 1 used channel must be allowed.'));
            } elseif ((int) $_POST['reintentos'] <= 0) {
                $smarty->assign("mb_title", _tr("Validation Error"));
                $smarty->assign("mb_message", _tr('Campaign must allow at least one call retry'));
            } elseif ($bDoCreate && !in_array($_POST['encoding'], mb_list_encodings())) {
                $smarty->assign("mb_title", _tr('Validation Error'));
                $smarty->assign("mb_message", _tr('Invalid character encoding'));
            } elseif ($bDoCreate && empty($_FILES['phonefile']['tmp_name'])) {
                $smarty->assign("mb_title", _tr('Validation Error'));
                $smarty->assign("mb_message", _tr('Call file not specified or failed to be uploaded'));
            } else {
                $time_ini = $_POST['hora_ini_HH'] . ":" . $_POST['hora_ini_MM'];
                $time_fin = $_POST['hora_fin_HH'] . ":" . $_POST['hora_fin_MM'];
                $iFechaIni = strtotime($_POST['fecha_ini']);
                $iFechaFin = strtotime($_POST['fecha_fin']);
                $iHoraIni = strtotime($time_ini);
                $iHoraFin = strtotime($time_fin);
                if ($iFechaIni == -1 || $iFechaIni === FALSE) {
                    $smarty->assign("mb_title", _tr("Validation Error"));
                    $smarty->assign("mb_message", _tr('Unable to parse start date specification'));
                } elseif ($iFechaFin == -1 || $iFechaFin === FALSE) {
                    $smarty->assign("mb_title", _tr("Validation Error"));
                    $smarty->assign("mb_message", _tr('Unable to parse end date specification'));
                } elseif ($iHoraIni == -1 || $iHoraIni === FALSE) {
                    $smarty->assign("mb_title", _tr("Validation Error"));
                    $smarty->assign("mb_message", _tr('Unable to parse start time specification'));
                } elseif ($iHoraFin == -1 || $iHoraFin === FALSE) {
                    $smarty->assign("mb_title", _tr("Validation Error"));
                    $smarty->assign("mb_message", _tr('Unable to parse end time specification'));
                } else {
                    if (!$pDB->genQuery("SET AUTOCOMMIT=0")) {
                        $smarty->assign("mb_message", $pDB->errMsg);
                    } else {
                        $bExito = TRUE;
                        if ($bDoCreate) {
                            $id_campaign = $oCamp->createEmptyCampaign($_POST['nombre'], $_POST['max_canales'], $_POST['reintentos'], $_POST['trunk'], $_POST['context'], $_POST['queue'], date('Y-m-d', $iFechaIni), date('Y-m-d', $iFechaFin), $time_ini, $time_fin, $_POST['rte_script'], $_POST['external_url'] == '' ? NULL : (int) $_POST['external_url']);
                            if (is_null($id_campaign)) {
                                $bExito = FALSE;
                            }
                        } elseif ($bDoUpdate) {
                            $bExito = $oCamp->updateCampaign($id_campaign, $_POST['nombre'], $_POST['max_canales'], $_POST['reintentos'], $_POST['trunk'], $_POST['context'], $_POST['queue'], date('Y-m-d', $iFechaIni), date('Y-m-d', $iFechaFin), $time_ini, $time_fin, $_POST['rte_script'], $_POST['external_url'] == '' ? NULL : (int) $_POST['external_url']);
                        }
                        // Introducir o actualizar formularios
                        if ($bExito && isset($_POST['values_form'])) {
                            if ($bDoCreate) {
                                $bExito = $oCamp->addCampaignForm($id_campaign, $_POST['values_form']);
                            } elseif ($bDoUpdate) {
                                $bExito = $oCamp->updateCampaignForm($id_campaign, $_POST['values_form']);
                            }
                        }
                        // Para creación, se introduce lista de valores CSV
                        if ($bExito && !empty($_FILES['phonefile']['tmp_name'])) {
                            // Se puede tardar mucho tiempo en la inserción
                            ini_set('max_execution_time', 3600);
                            $sEncoding = $_POST['encoding'];
                            $bExito = $oCamp->addCampaignNumbersFromFile($id_campaign, $_FILES['phonefile']['tmp_name'], $sEncoding);
                            if ($bExito && $bDoUpdate && $arrCampaign[0]['estatus'] == 'T') {
                                // Agregar números a una campaña terminada debe volverla a activar
                                $oCamp->activar_campaign($id_campaign, 'A');
                            }
                        }
                        // Confirmar o deshacer la transacción según sea apropiado
                        if ($bExito) {
                            $pDB->genQuery("COMMIT");
                            header("Location: ?menu={$module_name}");
                        } else {
                            $pDB->genQuery("ROLLBACK");
                            $smarty->assign("mb_title", _tr("Validation Error"));
                            $smarty->assign("mb_message", $oCamp->errMsg);
                        }
                    }
                    $pDB->genQuery("SET AUTOCOMMIT=1");
                }
            }
        }
    }
    $smarty->assign('icon', 'images/kfaxview.png');
    $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", is_null($id_campaign) ? _tr("New Campaign") : _tr("Edit Campaign") . ' "' . $_POST['nombre'] . '"', $_POST);
    return $contenidoModulo;
}
function grafic_queue(&$pDB_ast_cdr, &$pDB_ast, $queue, $dti, $dtf)
{
    global $arrConf;
    $ancho = "700";
    $margenDerecho = "100";
    //============================================================================
    $objPalo_AST_CDR = new paloSantoExtention($pDB_ast_cdr);
    /*
     *   VALORES POR GET
     */
    $arrData = array();
    $numResults = 0;
    $arrValue = array();
    $arrTimestamp = array();
    //============================================================================
    include_once "libs/paloSantoQueue.class.php";
    $paloQueue = new paloQueue($pDB_ast);
    $arrResult = strlen($queue) != 0 ? $paloQueue->getQueue($queue) : $paloQueue->getQueue();
    //$arrResult
    //Array ( [0] => Array ( [0] => 2000 [1] => 2000 Recepcion )
    //        [1] => Array ( [0] => 5000 [1] => 5000 Soporte )
    //        [2] => Array ( [0] => 7000 [1] => 7000 Ventas )  )
    /*
     *   SE CREA UN 2 ARREGLOS DE TAMAÑO 3*X+1
     *   $arrData PARA LOS DATOS DEL EJE Y
     *   $arrayX PARA EL ARREGLO DE DATOS PARA EL EJE X
     */
    $arrayX = array();
    $num = sizeof($arrResult);
    $i = 0;
    for ($i = 1; $i <= $num; $i++) {
        $s = $arrResult[$i - 1];
        $s_0 = array(0 => "", 1 => "");
        if ($i == 1) {
            $arrData[0] = $s_0;
            $arrayX[0] = "";
        }
        $arrData[3 * ($i - 1) + 1] = $s;
        $arrayX[3 * ($i - 1) + 1] = "";
        $arrData[3 * ($i - 1) + 2] = $s;
        $arrayX[3 * ($i - 1) + 2] = $s[0];
        $arrData[3 * ($i - 1) + 3] = $s_0;
        $arrayX[3 * ($i - 1) + 3] = "";
        if ($i == $num) {
            $arrData[3 * ($i - 1) + 4] = $s_0;
            $arrayX[3 * ($i - 1) + 4] = "";
        }
    }
    //======================================================
    $graph = new Graph($ancho, 250);
    $graph->SetMargin(50, $margenDerecho, 30, 40);
    $graph->SetMarginColor('#fafafa');
    $graph->SetFrame(true, '#999999');
    $graph->legend->SetFillColor("#fafafa");
    $graph->legend->Pos(0.012, 0.5, "right", "center");
    $graph->legend->SetColor("#444444", "#999999");
    $graph->legend->SetShadow('gray@0.6', 4);
    $graph->title->SetColor("#444444");
    // Especifico la escala
    $graph->SetScale("intlin");
    $graph->title->Set(utf8_decode(_tr("Number Calls vs Queues")));
    $graph->xaxis->SetLabelFormatCallback('NameQueue');
    $graph->xaxis->SetLabelAngle(90);
    $graph->xaxis->SetColor("#666666", "#444444");
    if (is_array($arrData) && count($arrData) > 0) {
        foreach ($arrData as $k => $arrMuestra) {
            $arrTimestamp[$k] = $k;
            /* X */
            //$arr = $objPalo_AST_CDR->countQueue( $arrMuestra['id'], $dti, $dtf);
            $arr = $objPalo_AST_CDR->countQueue($arrMuestra[0], $dti, $dtf);
            $arrValue[$k] = $arr[0];
            /* Y */
        }
        if (count($arrTimestamp) > 0) {
            $numResults++;
            $line = new LinePlot($arrValue, $arrTimestamp);
            $line->SetStepStyle();
            $line->SetColor("#00cc00");
            $line->setFillColor("#00cc00");
            $line->SetLegend("# " . _tr("Calls"));
            $graph->Add($line);
            $graph->yaxis->SetColor("#00cc00");
        }
    }
    //======================================================================================
    if ($numResults > 0) {
        $graph->Stroke();
    } else {
        $graph = new CanvasGraph(500, 140, "auto");
        $title = new Text(utf8_decode(_tr("No records found")));
        $title->ParagraphAlign('center');
        $title->SetFont(FF_FONT2, FS_BOLD);
        $title->SetMargin(3);
        $title->SetAlign('center');
        $title->Center(0, 500, 70);
        $graph->AddText($title);
        $t1 = new Text(utf8_decode(_tr("There are no data to present")));
        $t1->SetBox("white", "black", true);
        $t1->ParagraphAlign("center");
        $t1->SetColor("black");
        $graph->AddText($t1);
        $graph->img->SetColor('navy');
        $graph->img->SetTextAlign('center', 'bottom');
        $graph->img->Rectangle(0, 0, 499, 139);
        $graph->Stroke();
    }
}
Beispiel #6
0
function leerColasEntrantes($pDB, $pDB_asterisk)
{
    include_once "libs/paloSantoQueue.class.php";
    $arrQueue = array();
    $oQueue = new paloQueue($pDB_asterisk);
    $PBXQueues = $oQueue->getQueue();
    if (is_array($PBXQueues)) {
        foreach ($PBXQueues as $key => $value) {
            $query = "SELECT id, queue from queue_call_entry WHERE queue = ?";
            $result = $pDB->getFirstRowQuery($query, true, array($value[0]));
            if (is_array($result) && count($result) > 0) {
                $arrQueue[$result['queue']] = $result['queue'];
            }
        }
    }
    return $arrQueue;
}