Пример #1
0
function preview_form($pDB, $smarty, $module_name, $local_templates_dir, $formCampos, $oForm)
{
    $smarty->assign('FRAMEWORK_TIENE_TITULO_MODULO', existeSoporteTituloFramework());
    $oForm->setViewMode();
    // Esto es para activar el modo "preview"
    if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
        return false;
    }
    $oDataForm = new paloSantoDataForm($pDB);
    $arrDataForm = $oDataForm->getFormularios($_GET['id']);
    $arrFieldForm = $oDataForm->obtener_campos_formulario($_GET['id']);
    // Conversion de formato
    $arrTmp['form_nombre'] = $arrDataForm[0]['nombre'];
    $arrTmp['form_description'] = $arrDataForm[0]['descripcion'];
    $smarty->assign("title", _tr('Form'));
    $smarty->assign("form_name_lbl", _tr('Form Name'));
    $smarty->assign("form_description_lbl", _tr('Form Description'));
    $smarty->assign("form_name_val", $arrTmp['form_nombre']);
    $smarty->assign("form_description_val", $arrTmp['form_description']);
    $smarty->assign("id_formulario_actual", $_GET['id']);
    $smarty->assign("style_field", "style='display:none;'");
    $smarty->assign("formulario", $arrFieldForm);
    $smarty->assign('icon', 'images/kfaxview.png');
    $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/preview.tpl", _tr('Form'), $arrTmp);
    // hay que pasar el arreglo
    return $contenidoModulo;
}
Пример #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);
}
Пример #3
0
function manejarSesionActiva_HTML($module_name, &$smarty, $sDirLocalPlantillas, $oPaloConsola, $estado)
{
    $bInactivarBotonColgar = FALSE;
    $bPuedeConfirmarContacto = FALSE;
    // Acciones para mostrar la pantalla principal, fuera de cualquier acción AJAX
    for ($i = 0; $i < 24; $i++) {
        $ii = sprintf('%02d', $i);
        $comboHora[$ii] = $ii;
    }
    for ($i = 0; $i < 60; $i++) {
        $ii = sprintf('%02d', $i);
        $comboMinuto[$ii] = $ii;
    }
    $smarty->assign(array('FRAMEWORK_TIENE_TITULO_MODULO' => existeSoporteTituloFramework(), 'icon' => 'modules/' . $module_name . '/images/call_center.png', 'title' => _tr('Agent Console') . ': ' . $_SESSION['callcenter']['agente_nombre'], 'BTN_COLGAR_LLAMADA' => _tr('Hangup'), 'BTN_TRANSFER' => _tr('Transfer'), 'BTN_VTIGERCRM' => _tr('Mobivi Ticket'), 'BTN_FINALIZAR_LOGIN' => _tr('End session'), 'TITLE_BREAK_DIALOG' => _tr('Select break type'), 'BTN_CONFIRMAR_CONTACTO' => _tr('Confirm contact'), 'LBL_CONTACTO_TELEFONO' => _tr('Phone number'), 'LBL_CONTACTO_SELECT' => _tr('Contact'), 'LBL_CONTACTO_NOMBRES' => _tr('Names'), 'TEXTO_CONTACTO_NOMBRES' => '', 'TEXTO_CONTACTO_TELEFONO' => '', 'BTN_AGENDAR_LLAMADA' => _tr('Schedule call'), 'TITLE_TRANSFER_DIALOG' => _tr('Select extension to transfer to'), 'LBL_TRANSFER_BLIND' => _tr('Blind transfer'), 'LBL_TRANSFER_ATTENDED' => _tr('Attended transfer'), 'TITLE_SCHEDULE_CALL' => _tr('Schedule call'), 'LBL_SCHEDULE_CAMPAIGN_END' => _tr('Call at end of campaign'), 'LBL_SCHEDULE_BYDATE' => _tr('Schedule at date'), 'LBL_SCHEDULE_DATE_START' => _tr('Start date'), 'LBL_SCHEDULE_DATE_END' => _tr('End date'), 'LBL_SCHEDULE_TIME_START' => _tr('Start time'), 'LBL_SCHEDULE_TIME_END' => _tr('End time'), 'LBL_SCHEDULE_SAME_AGENT' => _tr('Schedule to same agent'), 'SCHEDULE_TIME_HH' => $comboHora, 'SCHEDULE_TIME_MM' => $comboMinuto, 'TAB_LLAMADA_INFO' => _tr('Thông tin cuộc gọi'), 'TAB_LLAMADA_SCRIPT' => _tr('Kiến thức cơ bản'), 'TAB_LLAMADA_FORM' => _tr('Mẫu trình ticket'), 'CRONOMETRO' => '00:00:00', 'LISTA_BREAKS' => $oPaloConsola->listarBreaks(), 'CONTENIDO_LLAMADA_INFORMACION' => '', 'CONTENIDO_LLAMADA_SCRIPT' => '<iframe src="http://192.168.11.28/phpmyfaq/index.php" width="100%" height="500" frameborder="0" ></iframe>', 'CONTENIDO_LLAMADA_FORMULARIO' => '', 'CALLINFO_CALLTYPE' => '', 'BTN_HOLD' => $estado['onhold'] ? _tr('End Hold') : _tr('Hold')));
    $estadoInicial = array('onhold' => $estado['onhold'], 'break_id' => is_null($estado['pauseinfo']) ? NULL : $estado['pauseinfo']['pauseid'], 'calltype' => NULL, 'campaign_id' => NULL, 'callid' => NULL, 'timer_seconds' => 0, 'url' => NULL, 'urlopentype' => NULL);
    // Decidir estado del break a mostrar
    if (!is_null($estado['pauseinfo'])) {
        $_SESSION['callcenter']['break_iniciado'] = $estado['pauseinfo']['pausestart'];
        $iDuracionPausaActual = time() - strtotime($estado['pauseinfo']['pausestart']);
        $iDuracionPausa = $iDuracionPausaActual + $_SESSION['callcenter']['break_acumulado'];
        $smarty->assign(array('CLASS_BOTON_BREAK' => 'elastix-callcenter-boton-unbreak', 'CLASS_ESTADO_AGENTE_INICIAL' => 'elastix-callcenter-class-estado-break', 'BTN_BREAK' => _tr('End Break'), 'TEXTO_ESTADO_AGENTE_INICIAL' => _tr('On break') . ': ' . $estado['pauseinfo']['pausename'], 'CRONOMETRO' => sprintf('%02d:%02d:%02d', ($iDuracionPausa - $iDuracionPausa % 3600) / 3600, ($iDuracionPausa - $iDuracionPausa % 60) / 60 % 60, $iDuracionPausa % 60)));
        $estadoInicial['timer_seconds'] = $iDuracionPausa;
    } else {
        if (!is_null($_SESSION['callcenter']['break_iniciado'])) {
            /* Si esta condición se cumple, entonces se ha perdido el evento 
             * pauseexit durante la espera en manejarSesionActiva_checkStatus().
             * Se hace la suposición de que el refresco ocurre poco después de
             * que termina el break, y que por lo tanto el error al usar time()
             * como fin del break es pequeño. 
             */
            $_SESSION['callcenter']['break_acumulado'] += time() - strtotime($_SESSION['callcenter']['break_iniciado']);
        }
        $smarty->assign(array('CLASS_BOTON_BREAK' => 'elastix-callcenter-boton-break', 'BTN_BREAK' => _tr('Take Break'), 'CLASS_ESTADO_AGENTE_INICIAL' => 'elastix-callcenter-class-estado-ocioso', 'TEXTO_ESTADO_AGENTE_INICIAL' => _tr('No active call')));
        $_SESSION['callcenter']['break_iniciado'] = NULL;
    }
    // Cambios según agente conectado a una llamada versus ocioso
    if (!is_null($estado['callinfo'])) {
        // Información sobre la llamada conectada
        $infoLlamada = $oPaloConsola->leerInfoLlamada($estado['callinfo']['calltype'], $estado['callinfo']['campaign_id'], $estado['callinfo']['callid']);
        if ($estado['callinfo']['calltype'] == 'incoming' && is_null($estado['callinfo']['campaign_id'])) {
            $infoCampania['queue'] = $infoLlamada['queue'];
            $infoCampania['script'] = $oPaloConsola->leerScriptCola($infoCampania['queue']);
            $infoCampania['forms'] = NULL;
        } else {
            $infoCampania = $oPaloConsola->leerInfoCampania($estado['callinfo']['calltype'], $estado['callinfo']['campaign_id']);
        }
        if (is_null($infoCampania['script']) || $infoCampania['script'] == '') {
            $infoCampania['script'] = _tr('(No script available)');
        }
        // Almacenar para regenerar formulario
        $_SESSION['callcenter']['ultimo_calltype'] = $estado['callinfo']['calltype'];
        $_SESSION['callcenter']['ultimo_callid'] = $estado['callinfo']['callid'];
        $_SESSION['callcenter']['ultimo_callsurvey']['call_survey'] = $infoLlamada['call_survey'];
        $_SESSION['callcenter']['ultimo_campaignform']['forms'] = $infoCampania['forms'];
        // Fecha completa de la llamada
        $iDuracionLlamada = time() - strtotime($estado['callinfo']['linkstart']);
        // Asignaciones independientes del tipo de llamada
        $bInactivarBotonColgar = false;
        // Se usa para botón hangup y botón transfer
        $smarty->assign(array('CLASS_ESTADO_AGENTE_INICIAL' => 'elastix-callcenter-class-estado-activo', 'TEXTO_ESTADO_AGENTE_INICIAL' => _tr('Đang có cuộc gọi đến'), 'TEXTO_CONTACTO_TELEFONO' => $estado['callinfo']['callnumber'], 'CALLINFO_CALLTYPE' => $estado['callinfo']['calltype'], 'CRONOMETRO' => sprintf('%02d:%02d:%02d', ($iDuracionLlamada - $iDuracionLlamada % 3600) / 3600, ($iDuracionLlamada - $iDuracionLlamada % 60) / 60 % 60, $iDuracionLlamada % 60), 'CONTENIDO_LLAMADA_INFORMACION' => manejarSesionActiva_HTML_generarInformacion($smarty, $sDirLocalPlantillas, $infoLlamada, $infoCampania), 'CONTENIDO_LLAMADA_FORMULARIO' => manejarSesionActiva_HTML_generarFormulario($smarty, $sDirLocalPlantillas, $infoLlamada, $infoCampania), 'CONTENIDO_LLAMADA_SCRIPT' => '<iframe src="http://192.168.11.28/phpmyfaq/index.php" width="100%" height="500" frameborder="0" ></iframe>'));
        $estadoInicial['timer_seconds'] = $iDuracionLlamada;
        $estadoInicial['calltype'] = $estado['callinfo']['calltype'];
        $estadoInicial['campaign_id'] = $estado['callinfo']['campaign_id'];
        $estadoInicial['callid'] = $estado['callinfo']['callid'];
        $estadoInicial['urlopentype'] = isset($infoCampania['urlopentype']) ? $infoCampania['urlopentype'] : NULL;
        $estadoInicial['url'] = is_null($estadoInicial['urlopentype']) ? NULL : construirUrlExterno($infoCampania['urltemplate'], $infoLlamada + array('callnumber' => $estado['callinfo']['callnumber'], 'callid' => $infoLlamada['call_id'], 'agent_number' => $estado['callinfo']['agent_number'], 'remote_channel' => $estado['callinfo']['remote_channel']));
        // Asignaciones específicas para llamadas entrantes
        if ($estado['callinfo']['calltype'] == 'incoming') {
            $comboContactos = array();
            foreach ($infoLlamada['matching_contacts'] as $idContacto => $tuplaContacto) {
                $infoContactoViejo = array();
                $sDescripcionContacto = '';
                foreach ($tuplaContacto as $attrContacto) {
                    $sDescripcionContacto .= $attrContacto['value'] . ' ';
                    if (in_array($attrContacto['label'], array('first_name', 'last_name', 'cedula_ruc'))) {
                        $infoContactoViejo[$attrContacto['label']] = $attrContacto['value'];
                    }
                }
                if (count($infoContactoViejo) == 3) {
                    $comboContactos[$idContacto] = $infoContactoViejo['cedula_ruc'] . ' - ' . $infoContactoViejo['first_name'] . ' ' . $infoContactoViejo['last_name'];
                } else {
                    /* TODO: dar formato adecuado para cuando contactos de llamadas 
                     * entrantes puedan tener atributos arbitrarios */
                    $comboContactos[$idContacto] = $sDescripcionContacto;
                }
            }
            if (count($comboContactos) == 0) {
                $comboContactos[''] = _tr('(no matching contacts)');
            }
            $smarty->assign(array('LISTA_CONTACTOS' => $comboContactos));
            $bPuedeConfirmarContacto = count($comboContactos) > 1;
        }
        // Asignaciones específicas para llamadas salientes
        if ($estado['callinfo']['calltype'] == 'outgoing') {
            /* TODO: el siguiente código asume que el atributo 1 es el nombre
             * del cliente. Esta suposición se hereda del callcenter anterior.
             * Se debe de idear un método para dar formato al nombre del cliente
             * a partir de cualquier combinación de columnas */
            $sNombreCliente = isset($infoLlamada['call_attributes'][1]) ? $infoLlamada['call_attributes'][1]['value'] : _tr('(unavailable)');
            $smarty->assign(array('TEXTO_CONTACTO_NOMBRES' => $sNombreCliente));
        }
    } else {
        $bInactivarBotonColgar = true;
        // Se usa para botón hangup y botón transfer
        $smarty->assign(array('CONTENIDO_LLAMADA_FORMULARIO' => is_null($_SESSION['callcenter']['ultimo_calltype']) ? '' : manejarSesionActiva_HTML_generarFormulario($smarty, $sDirLocalPlantillas, $_SESSION['callcenter']['ultimo_callsurvey'], $_SESSION['callcenter']['ultimo_campaignform'])));
    }
    $json = new Services_JSON();
    $smarty->assign(array('APPLY_UI_STYLES' => $json->encode(array('break_commit' => _tr('Take Break'), 'break_dismiss' => _tr('Dismiss'), 'transfer_commit' => _tr('Transfer'), 'transfer_dismiss' => _tr('Dismiss'), 'schedule_commit' => _tr('Schedule'), 'schedule_dismiss' => _tr('Dismiss'), 'external_url_tab' => _tr('External site'), 'schedule_call_error_msg_missing_date' => _tr('Start and end date are required for date scheduling.'), 'no_call' => $bInactivarBotonColgar, 'can_confirm_contact' => $bPuedeConfirmarContacto)), 'INITIAL_CLIENT_STATE' => $json->encode($estadoInicial)));
    return $smarty->fetch("{$sDirLocalPlantillas}/agent_console.tpl");
}
Пример #4
0
function agent_monitoring_HTML($module_name, $smarty, $sDirLocalPlantillas, $oPaloConsola)
{
    global $arrLang;
    $smarty->assign(array('FRAMEWORK_TIENE_TITULO_MODULO' => existeSoporteTituloFramework(), 'icon' => 'modules/' . $module_name . '/images/realtime.png', 'title' => 'Giám Sát & Quản Lý Tổng Đài Viên'));
    /* check if user login via agent console
    	 if (!isset($_SESSION['callcenter']['agente'])) {
            $smarty->assign(array(
                'mb_title'  =>  'ERROR',
                'mb_message'    =>  'Đăng nhập tại <a href="index.php?menu=agent_console">Agent Console</a> trước khi sử dụng tính năng này',
            ));
    		  return '';
        } */
    $estadoMonitor = $oPaloConsola->listarEstadoMonitoreoAgentes();
    //echo '<pre>' . print_r($estadoMonitor,1) . '</pre>';die;
    if (!is_array($estadoMonitor)) {
        $smarty->assign(array('mb_title' => 'ERROR', 'mb_message' => $oPaloConsola->errMsg));
        return '';
    }
    ksort($estadoMonitor);
    //echo '<pre>' . print_r($estadoMonitor,1) . '</pre>';die;
    $jsonData = contructDataJSON(mergeQueueAgent($estadoMonitor));
    // convert to Smarty data
    $sThemeDir = "modules/{$module_name}/themes/default";
    $arrSmartyData = array();
    foreach ($jsonData as $jsonKey => $jsonRow) {
        $arrSmartyData[$jsonKey] = $jsonRow;
        // show time format hh:mm:ss base on last-status
        $arrSmartyData[$jsonKey]['status_time'] = timestamp_format($jsonRow['sec_laststatus']);
        // show time format hh:mm:ss base on last-status
        $arrSmartyData[$jsonKey]['sec_calls_time'] = timestamp_format($jsonRow['sec_calls']);
        switch ($jsonRow['agentstatus']) {
            case 'offline':
                // image status with title information
                $arrSmartyData[$jsonKey]['img_status'] = "{$sThemeDir}/images/status_offline-ic.png";
                $arrSmartyData[$jsonKey]['img_status_title'] = "{$jsonKey}: Chưa sẵn sàng";
                // status time (count from sec_laststatus)
                $arrSmartyData[$jsonKey]['status_time_label'] = 'Offline:';
                break;
            case 'online':
                // image status with title information
                $arrSmartyData[$jsonKey]['img_status'] = "{$sThemeDir}/images/status_free-ic.png";
                $arrSmartyData[$jsonKey]['img_status_title'] = "{$jsonKey}: Đang sẵn sàng";
                // status time (count from sec_laststatus)
                $arrSmartyData[$jsonKey]['status_time_label'] = 'Online:';
                break;
            case 'oncall':
                // image status with title information
                $arrSmartyData[$jsonKey]['img_status'] = "{$sThemeDir}/images/status_on_call-ic.png";
                $arrSmartyData[$jsonKey]['img_status_title'] = "{$jsonKey}: Đang gọi - Tại kênh: " . $jsonRow['linkqueue'];
                // status time (count from sec_laststatus)
                $arrSmartyData[$jsonKey]['status_time_label'] = 'Đang gọi: ';
                // get customer information
                $agentState = getAgentState($jsonRow['agent_number']);
                $arrSmartyData[$jsonKey]['callnumber'] = $agentState['callnumber'];
                $arrSmartyData[$jsonKey]['callid'] = $agentState['callid'];
                $customer = getCustomer($arrSmartyData[$jsonKey]['callnumber']);
                $arrSmartyData[$jsonKey]['customer'] = $customer ? $customer : $arrSmartyData[$jsonKey]['callnumber'];
                break;
            case 'paused':
                // image status with title information
                $arrSmartyData[$jsonKey]['img_status'] = "{$sThemeDir}/images/status_away-ic.png";
                $arrSmartyData[$jsonKey]['img_status_title'] = "{$jsonKey}: Đang tạm nghỉ";
                // status time (count from sec_laststatus)
                $arrSmartyData[$jsonKey]['status_time_label'] = 'Tạm nghỉ:';
                break;
            default:
        }
    }
    // history call
    global $arrConf;
    $oCallHistory = new getInfoMainConsole();
    $oCallHistory->callcenter_db_connect($arrConf['cadena_dsn']);
    $arrHistory = $oCallHistory->getCallHistoryArray();
    $oCallHistory->callcenter_db_disconnect();
    //$oQueueStatus = new queue_waiting();
    //$arrQueue = $oQueueStatus->showQueue();
    //echo '<pre>' . print_r($res,1) . '</pre>';die;
    //smarty template assign
    $smarty->assign(array('AGENT_STATUS' => $arrSmartyData, 'SUPERVISOR_NUMBER' => $_SESSION['callcenter']['extension'], 'THEME_PATH' => $sThemeDir, 'CALL_HISTORY' => $arrHistory, 'ITEM_LIMIT' => 6));
    //echo '<pre>' . print_r($arrTicket,1) . '</pre>';die;
    $sContent = $smarty->fetch("{$sDirLocalPlantillas}/realtime_monitor.tpl");
    //initilize with jsonData
    foreach (array_keys($jsonData) as $k) {
        unset($jsonData[$k]['agentname']);
    }
    // Extraer la información que el navegador va a usar para actualizar
    $estadoCliente = array();
    foreach (array_keys($jsonData) as $k) {
        $estadoCliente[$k] = array('agentstatus' => $jsonData[$k]['agentstatus'], 'oncallupdate' => $jsonData[$k]['oncallupdate'], 'linkqueue' => $jsonData[$k]['linkqueue']);
    }
    $estadoHash = generarEstadoHash($module_name, $estadoCliente);
    $json = new Services_JSON();
    $INITIAL_CLIENT_STATE = $json->encode($jsonData);
    $sJsonInitialize = <<<JSON_INITIALIZE
<script type="text/javascript">
\$(function() {
    initialize_client_state({$INITIAL_CLIENT_STATE}, '{$estadoHash}');\t
});
</script>
JSON_INITIALIZE;
    return $sContent . $sJsonInitialize;
}
Пример #5
0
function mostrarFormularioModificarBreak(&$smarty, $module_name, $pDB, $local_templates_dir, $id_break)
{
    $bNuevoBreak = is_null($id_break);
    $smarty->assign(array('SAVE' => $bNuevoBreak ? _tr('Save') : _tr('Apply Changes')));
    if (isset($_POST['cancel'])) {
        Header("Location: ?menu={$module_name}");
        return '';
    }
    $smarty->assign('FRAMEWORK_TIENE_TITULO_MODULO', existeSoporteTituloFramework());
    // Para modificación, se lee la información del break
    $oBreaks = new PaloSantoBreaks($pDB);
    if (!$bNuevoBreak) {
        $_POST['id_break'] = $id_break;
        $infoBreak = $oBreaks->getBreaks($id_break);
        if (!is_array($infoBreak)) {
            // No se puede recuperar información actual del break
            $smarty->assign("mb_title", _tr("ERROR"));
            $smarty->assign("mb_message", $pDB->errMsg);
        } elseif (count($infoBreak) <= 0) {
            // El break no se encuentra
            Header("Location: ?menu={$module_name}");
            return '';
        } else {
            // Se asignan los valores a POST a menos que ya se encuentren valores
            if (!isset($_POST['nombre'])) {
                $_POST['nombre'] = $infoBreak[0]['name'];
            }
            if (!isset($_POST['descripcion'])) {
                $_POST['descripcion'] = $infoBreak[0]['description'];
            }
        }
    }
    $formCampos = array("nombre" => array("LABEL" => _tr("Name Break"), "REQUIRED" => "yes", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => array("size" => "40"), "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), "descripcion" => array("LABEL" => _tr("Description Break"), "REQUIRED" => "yes", "INPUT_TYPE" => "TEXTAREA", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => "", "ROWS" => "2", "COLS" => "33"), 'id_break' => array('LABEL' => 'id_break', 'REQUIRED' => 'no', 'INPUT_TYPE' => 'HIDDEN', "VALIDATION_TYPE" => "ereg", "VALIDATION_EXTRA_PARAM" => "^[[:digit:]]+\$"));
    $oForm = new paloForm($smarty, $formCampos);
    $oForm->setEditMode();
    // Procesar los cambios realizados
    if (isset($_POST['save'])) {
        if (!$oForm->validateForm($_POST)) {
            $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) {
                $strErrorMsg .= implode(', ', array_keys($arrErrores));
            }
            $smarty->assign("mb_message", $strErrorMsg);
        } else {
            $exito = $bNuevoBreak ? $oBreaks->createBreak($_POST['nombre'], $_POST['descripcion']) : $oBreaks->updateBreak($id_break, $_POST['nombre'], $_POST['descripcion']);
            if ($exito) {
                header("Location: ?menu={$module_name}");
            } else {
                $smarty->assign("mb_title", _tr("Validation Error"));
                $smarty->assign("mb_message", $oBreak->errMsg);
            }
        }
    }
    // Mostrar el formulario con los valores
    $smarty->assign('icon', 'images/kfaxview.png');
    $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", $bNuevoBreak ? _tr('New Break') : _tr('Edit Break'), $_POST);
    return $contenidoModulo;
}
Пример #6
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;
}
Пример #7
0
function formEditAgent($pDB, $smarty, $module_name, $local_templates_dir, $id_agent)
{
    // 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
    $arrAgente = NULL;
    $oAgentes = new Agentes($pDB);
    if (!is_null($id_agent)) {
        $arrAgente = $oAgentes->getAgents($id_agent);
        if (!is_array($arrAgente) || count($arrAgente) == 0) {
            $smarty->assign("mb_title", 'Unable to read agent');
            $smarty->assign("mb_message", 'Cannot read agent - ' . $oAgentes->errMsg);
            return '';
        }
    }
    require_once "libs/paloSantoForm.class.php";
    $arrFormElements = getFormAgent($smarty, !is_null($id_agent));
    // Valores por omisión para primera carga
    if (is_null($id_agent)) {
        // Creación de nuevo agente
        if (!isset($_POST['extension'])) {
            $_POST['extension'] = '';
        }
        if (!isset($_POST['description'])) {
            $_POST['description'] = '';
        }
        if (!isset($_POST['password1'])) {
            $_POST['password1'] = '';
        }
        if (!isset($_POST['password2'])) {
            $_POST['password2'] = '';
        }
        if (!isset($_POST['eccpwd1'])) {
            $_POST['eccpwd1'] = '';
        }
        if (!isset($_POST['eccpwd2'])) {
            $_POST['eccpwd2'] = '';
        }
    } else {
        // Modificación de agente existente
        if (!isset($_POST['extension'])) {
            $_POST['extension'] = $arrAgente['number'];
        }
        if (!isset($_POST['description'])) {
            $_POST['description'] = $arrAgente['name'];
        }
        if (!isset($_POST['password1'])) {
            $_POST['password1'] = $arrAgente['password'];
        }
        if (!isset($_POST['password2'])) {
            $_POST['password2'] = $arrAgente['password'];
        }
        if (!isset($_POST['eccpwd1'])) {
            $_POST['eccpwd1'] = $arrAgente['eccp_password'];
        }
        if (!isset($_POST['eccpwd2'])) {
            $_POST['eccpwd2'] = $arrAgente['eccp_password'];
        }
        // Volver opcional el cambio de clave de acceso
        $arrFormElements['password1']['REQUIRED'] = 'no';
        $arrFormElements['password2']['REQUIRED'] = 'no';
    }
    $oForm = new paloForm($smarty, $arrFormElements);
    if (!is_null($id_agent)) {
        $oForm->setEditMode();
        $smarty->assign("id_agent", $id_agent);
    }
    $bDoCreate = isset($_POST['submit_save_agent']);
    $bDoUpdate = isset($_POST['submit_apply_changes']);
    if ($bDoCreate || $bDoUpdate) {
        if (!$oForm->validateForm($_POST)) {
            // 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>";
            foreach ($arrErrores as $k => $v) {
                $strErrorMsg .= "{$k}, ";
            }
            $strErrorMsg .= "";
            $smarty->assign("mb_message", $strErrorMsg);
        } else {
            foreach (array('extension', 'password1', 'password2', 'description', 'eccpwd1', 'eccpwd2') as $k) {
                $_POST[$k] = trim($_POST[$k]);
            }
            if ($_POST['password1'] != $_POST['password2'] || $bDoCreate && $_POST['password1'] == '') {
                $smarty->assign("mb_title", _tr("Validation Error"));
                $smarty->assign("mb_message", _tr("The passwords are empty or don't match"));
            } elseif ($_POST['eccpwd1'] != $_POST['eccpwd2']) {
                $smarty->assign("mb_title", _tr("Validation Error"));
                $smarty->assign("mb_message", _tr("ECCP passwords don't match"));
            } elseif (!ereg('^[[:digit:]]+$', $_POST['password1'])) {
                $smarty->assign("mb_title", _tr("Validation Error"));
                $smarty->assign("mb_message", _tr("The passwords aren't numeric values"));
            } elseif (!ereg('^[[:digit:]]+$', $_POST['extension'])) {
                $smarty->assign("mb_title", _tr("Validation Error"));
                $smarty->assign("mb_message", _tr("Error Agent Number"));
            } else {
                $bExito = TRUE;
                if ($bDoUpdate && $_POST['password1'] == '') {
                    $_POST['password1'] = $arrAgente['password'];
                }
                $agente = array(0 => $_POST['extension'], 1 => $_POST['password1'], 2 => $_POST['description'], 3 => $_POST['eccpwd1']);
                if ($bDoCreate) {
                    $bExito = $oAgentes->addAgent($agente);
                    if (!$bExito) {
                        $smarty->assign("mb_message", "" . _tr("Error Insert Agent") . " " . $oAgentes->errMsg);
                    }
                } elseif ($bDoUpdate) {
                    $bExito = $oAgentes->editAgent($agente);
                    if (!$bExito) {
                        $smarty->assign("mb_message", "" . _tr("Error Update Agent") . " " . $oAgentes->errMsg);
                    }
                }
                if ($bExito) {
                    header("Location: ?menu={$module_name}");
                }
            }
        }
    }
    $smarty->assign('icon', 'images/user.png');
    $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/new.tpl", is_null($id_agent) ? _tr("New agent") : _tr('Edit agent') . ' "' . $_POST['description'] . '"', $_POST);
    return $contenidoModulo;
}
Пример #8
0
function newCalls($pDB, $smarty, $module_name, $local_templates_dir, $formCampos, $oForm)
{
    $fContenido = "";
    $msgResultado = "";
    $smarty->assign('FRAMEWORK_TIENE_TITULO_MODULO', existeSoporteTituloFramework());
    if (isset($_FILES['file_number'])) {
        if ($_FILES['file_number']['name'] != "") {
            $file = $_FILES['file_number'];
            $cargaDatos = new Cargar_File($file);
            if (is_object($cargaDatos)) {
                $nameFile = $cargaDatos->getFileName();
                $flag = $cargaDatos->guardarDatosCallsFromFile($pDB, $nameFile);
            } else {
                $smarty->assign("mb_title", _tr('Error'));
                $smarty->assign("mb_message", _tr('Error when is loading file'));
            }
        } else {
            $msgResultado = _tr('Please select any file');
        }
    } elseif (isset($_POST["txt_new_number"])) {
        if ($_POST["txt_new_number"] != "") {
            $new_number = $_POST["txt_new_number"];
            if (is_numeric($new_number) && $new_number > 0) {
                $msgResultado = registrarNuevoNumero($pDB, $new_number);
            } else {
                $msgResultado = _tr('Number phone is not numeric value');
            }
        } else {
            $msgResultado = _tr('Please enter a number phone');
        }
    }
    $oForm->setViewMode();
    if ($msgResultado == "") {
        header("Location: ?menu=dont_call_list");
    } else {
        $smarty->assign("mb_title", _tr('Result'));
        $smarty->assign("mb_message", $msgResultado);
    }
    $smarty->assign('icon', 'images/list.png');
    $fContenido = $oForm->fetchForm("{$local_templates_dir}/new.tpl", _tr('Load File'), null);
    return $fContenido;
}
Пример #9
0
function formEditURL($pDB, $smarty, $module_name, $local_templates_dir, $id_url)
{
    // 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());
    $urls = new externalUrl($pDB);
    $tuplaURL = NULL;
    if (!is_null($id_url)) {
        $tuplaURL = $urls->getURL($id_url);
        if (!is_array($tuplaURL) || count($tuplaURL) == 0) {
            $smarty->assign("mb_title", _tr('Unable to read URL'));
            $smarty->assign("mb_message", _tr('Cannot read URL') . ' - ' . $urls->errMsg);
            return '';
        }
    }
    $formCampos = array('description' => array("LABEL" => _tr('URL Description'), "REQUIRED" => "yes", "INPUT_TYPE" => "TEXTAREA", "INPUT_EXTRA_PARAM" => "", 'ROWS' => 6, 'COLS' => 50, "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), 'urltemplate' => array("LABEL" => _tr('URL Template'), "REQUIRED" => "yes", "INPUT_TYPE" => "TEXT", "INPUT_EXTRA_PARAM" => array('size' => 64, 'title' => _tr('TEMPLATE_DESC')), "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), 'active' => array("LABEL" => _tr('Enable use of this template'), "REQUIRED" => "yes", "INPUT_TYPE" => "CHECKBOX", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""), 'opentype' => array("LABEL" => _tr('Open URL in'), "REQUIRED" => "yes", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => descOpenType(), "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""));
    $oForm = new paloForm($smarty, $formCampos);
    if (!is_null($id_url)) {
        $oForm->setEditMode();
        $smarty->assign('id_url', $id_url);
    }
    if (!is_null($tuplaURL)) {
        if (!isset($_POST['description'])) {
            $_POST['description'] = $tuplaURL['description'];
        }
        if (!isset($_POST['urltemplate'])) {
            $_POST['urltemplate'] = $tuplaURL['urltemplate'];
        }
        if (!isset($_POST['opentype'])) {
            $_POST['opentype'] = $tuplaURL['opentype'];
        }
        if (!isset($_POST['active'])) {
            $_POST['active'] = $tuplaURL['active'] ? 'on' : 'off';
        }
    } else {
        if (!isset($_POST['active'])) {
            $_POST['active'] = 'on';
        }
    }
    // 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)) {
            // 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}, ";
                }
            }
            $smarty->assign("mb_message", $strErrorMsg);
        } else {
            if ($bDoCreate) {
                $bExito = $urls->createURL($_POST['urltemplate'], $_POST['description'], $_POST['opentype']);
            } elseif ($bDoUpdate) {
                $urls->enableURL($id_url, $_POST['active'] != 'off');
                $bExito = $urls->updateURL($id_url, $_POST['urltemplate'], $_POST['description'], $_POST['opentype']);
            }
            if ($bExito) {
                header("Location: ?menu={$module_name}");
            } else {
                $smarty->assign("mb_title", _tr("Validation Error"));
                $smarty->assign("mb_message", $urls->errMsg);
            }
        }
    }
    $smarty->assign(array('SAVE' => _tr('Save'), 'CANCEL' => _tr('Cancel'), 'APPLY_CHANGES' => _tr('Apply Changes')));
    return $oForm->fetchForm("{$local_templates_dir}/new.tpl", is_null($id_url) ? _tr("New URL") : _tr("Edit URL"), $_POST);
}
Пример #10
0
function _moduleContent(&$smarty, $module_name)
{
    include_once "modules/{$module_name}/configs/config.php";
    require_once "modules/{$module_name}/libs/paloSantoUploadFile.class.php";
    // Obtengo la ruta del template a utilizar para generar el filtro.
    $base_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    $templates_dir = isset($config['templates_dir']) ? $config['templates_dir'] : 'themes';
    $local_templates_dir = "{$base_dir}/modules/{$module_name}/" . $templates_dir . '/' . $arrConfig['theme'];
    load_language_module($module_name);
    $smarty->assign('FRAMEWORK_TIENE_TITULO_MODULO', existeSoporteTituloFramework());
    $smarty->assign('icon', 'images/list.png');
    $smarty->assign("MODULE_NAME", $module_name);
    $smarty->assign("LABEL_MESSAGE", _tr('Select file upload'));
    $smarty->assign("Format_File", _tr('Format File'));
    $smarty->assign("File", _tr('File'));
    $smarty->assign('ETIQUETA_SUBMIT', _tr('Upload'));
    $smarty->assign('ETIQUETA_DOWNLOAD', _tr('Download contacts'));
    $smarty->assign('Format_Content', _tr('"Phone","Identification Card","Name","Last Name"'));
    $form_campos = array('file' => array("LABEL" => _tr('File'), "REQUIRED" => "yes", "INPUT_TYPE" => "FILE", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""));
    $oForm = new paloForm($smarty, $form_campos);
    $fContenido = $oForm->fetchForm("{$local_templates_dir}/form.tpl", _tr('Load File'), $_POST);
    if (isset($_POST['cargar_datos'])) {
        $infoArchivo = $_FILES['fileCRM'];
        if ($infoArchivo['error'] != 0) {
            $smarty->assign("mb_title", _tr('Error'));
            $smarty->assign("mb_message", _tr('Error while loading file'));
        } else {
            $sNombreTemp = $infoArchivo['tmp_name'];
            $pDB = new paloDB($arrConfig['cadena_dsn']);
            $oCarga = new paloSantoUploadFile($pDB);
            $sEncoding = NULL;
            $bExito = $oCarga->addCampaignNumbersFromFile($sNombreTemp, $sEncoding);
            if (!$bExito) {
                $smarty->assign("mb_title", _tr('Error'));
                $smarty->assign("mb_message", _tr('Error while loading file') . ': ' . $oCarga->errMsg);
            } else {
                $r = $oCarga->obtenerContadores();
                $smarty->assign("mb_title", _tr('Result'));
                $smarty->assign("mb_message", _tr('Inserted records') . ': ' . $r[0] . '<br/>' . _tr('Updated records') . ': ' . $r[1] . '<br/>' . _tr('Detected charset') . ': ' . $sEncoding);
            }
        }
    } elseif (isset($_GET['action']) && $_GET['action'] == 'csvdownload') {
        $pDB = new paloDB($arrConfig['cadena_dsn']);
        $oCarga = new paloSantoUploadFile($pDB);
        $r = $oCarga->leerContactos();
        if (!is_array($r)) {
            $smarty->assign("mb_title", _tr('Error'));
            $smarty->assign("mb_message", $oCarga->errMsg);
            return $oCarga->errMsg;
        } else {
            header("Cache-Control: private");
            header("Pragma: cache");
            header('Content-Type: text/csv; charset=UTF-8; header=present');
            header("Content-disposition: attachment; filename=\"contacts.csv\"");
            $fContenido = '';
            foreach ($r as $tuplaDatos) {
                $fContenido .= join(',', array_map('csv_replace', $tuplaDatos)) . "\r\n";
            }
        }
    }
    return $fContenido;
}
Пример #11
0
function manejarMonitoreo_HTML($module_name, $smarty, $sDirLocalPlantillas, $oPaloConsola)
{
    global $arrLang;
    $smarty->assign(array('FRAMEWORK_TIENE_TITULO_MODULO' => existeSoporteTituloFramework(), 'icon' => 'modules/' . $module_name . '/images/call.png', 'title' => _tr('Agent Monitoring')));
    /*
     * Un agente puede pertenecer a múltiples colas, y puede o no estar 
     * atendiendo una llamada, la cual puede haber llegado de como máximo una
     * cola. Hay 3 cronómetros que se pueden actualizar:
     * 
     * último estado:   el tiempo transcurrido desde el último cambio de estado
     * total de login:  el tiempo durante el cual el agente ha estado logoneado
     * total de llamadas: el tiempo que el agente pasa atendiendo llamadas
     * 
     * Para el monitoreo de este módulo, los estados en que puede estar
     * una fila (que muestra un agente en una cola) pueden ser los siguientes:
     * 
     * offline: el tiempo total de login y el tiempo de llamadas no se 
     *  actualizan. Si el cliente estuvo en otro estado previamente 
     *  (lastsessionend) entonces se actualiza regularmente el cronómetro de
     *  último estado. De otro modo el cronómetro de último estado está vacío.
     * online: se actualiza el tiempo total de login y el tiempo de último 
     *  estado, y el tiempo total de llamadas no se actualiza. El cronómetro de
     *  último estado cuenta desde el inicio de sesión.
     * paused: igual que online, pero el cronómentro de último estado cuenta
     *  desde el inicio de la pausa.
     * oncall: se actualiza el tiempo total de login. El cronómetro de último 
     *  estado cuenta desde el inicio de la llamada únicamente para la cola que 
     *  proporcionó la llamada que atiende el agente actualmente. De otro modo 
     *  el cronómetro no se actualiza. De manera similar, el total de tiempo de
     *  llamadas se actualiza únicamente para la cola que haya proporcionado la
     *  llamada que atiende el agente.
     * 
     * El estado del cliente consiste en un arreglo de tantos elementos como
     * agentes haya pertenecientes a cada cola. Si un agente pertenece a más de
     * una cola, hay un elemento por cada pertenencia del mismo agente a cada
     * cola. Cada elemento es una estructura que contiene los siguientes 
     * valores:
     * 
     * status:          {offline|online|oncall|paused}
     * sec_laststatus:  integer|null
     * sec_calls:       integer
     * logintime:       integer
     * num_calls:       integer
     * oncallupdate:    boolean
     * 
     * Cada elemento del arreglo se posiciona por 'queue-{NUM_COLA}-member-{NUM_AGENTE}'
     * 
     * El estado enviado por el cliente para detectar cambios es también un 
     * arreglo con el mismo número de elementos que el arreglo anterior, 
     * posicionado de la misma manera. Cada elemento es una estructura que 
     * contiene los siguientes valores:
     * 
     * status:          {offline|online|oncall|paused}
     * oncallupdate:    boolean
     */
    $estadoMonitor = $oPaloConsola->listarEstadoMonitoreoAgentes();
    if (!is_array($estadoMonitor)) {
        $smarty->assign(array('mb_title' => 'ERROR', 'mb_message' => $oPaloConsola->errMsg));
        return '';
    }
    ksort($estadoMonitor);
    $jsonData = construirDatosJSON($estadoMonitor);
    $arrData = array();
    $tuplaTotal = NULL;
    $sPrevQueue = NULL;
    foreach ($jsonData as $jsonKey => $jsonRow) {
        list($d1, $sQueue, $d2, $sTipoAgente, $sNumeroAgente) = explode('-', $jsonKey);
        $sEstadoTag = '(unimplemented)';
        switch ($jsonRow['status']) {
            case 'offline':
                $sEstadoTag = _tr('LOGOUT');
                break;
            case 'online':
                $sEstadoTag = '<img src="modules/' . $module_name . '/images/ready.png" border="0" alt="' . _tr('READY') . '"/>';
                break;
            case 'oncall':
                $sEstadoTag = '<img src="modules/' . $module_name . '/images/call.png" border="0" alt="' . _tr('CALL') . '"/>';
                break;
            case 'paused':
                $sEstadoTag = '<img src="modules/' . $module_name . '/images/break.png" border="0" alt="' . _tr('BREAK') . '"/>';
                break;
        }
        $sEstadoTag = '<span id="' . $jsonKey . '-statuslabel">' . $sEstadoTag . '</span>';
        $sEstadoTag .= '&nbsp;<span id="' . $jsonKey . '-sec_laststatus">';
        if (!is_null($jsonRow['sec_laststatus'])) {
            $sEstadoTag .= timestamp_format($jsonRow['sec_laststatus']);
        }
        $sEstadoTag .= '</span>';
        // Estado a mostrar en HTML se deriva del estado JSON
        if ($sPrevQueue != $sQueue) {
            if (!is_null($tuplaTotal)) {
                // Emitir fila de totales para la cola ANTERIOR
                $jsTotalKey = 'queue-' . $sPrevQueue;
                $arrData[] = array('<b>' . _tr('TOTAL') . '</b>', '&nbsp;', '<b>' . _tr('Agents') . ': ' . $tuplaTotal['num_agents'] . '</b>', '&nbsp;', '<b><span id="' . $jsTotalKey . '-num_calls">' . $tuplaTotal['num_calls'] . '</span></b>', '<b><span id="' . $jsTotalKey . '-logintime">' . timestamp_format($tuplaTotal['logintime']) . '</span></b>', '<b><span id="' . $jsTotalKey . '-sec_calls">' . timestamp_format($tuplaTotal['sec_calls']) . '</span></b>');
            }
            // Reiniciar totales aquí
            $tuplaTotal = array('num_agents' => 0, 'logintime' => 0, 'num_calls' => 0, 'sec_calls' => 0);
        }
        $tuplaTotal['num_agents']++;
        $tuplaTotal['logintime'] += $jsonRow['logintime'];
        $tuplaTotal['num_calls'] += $jsonRow['num_calls'];
        $tuplaTotal['sec_calls'] += $jsonRow['sec_calls'];
        $tupla = array($sPrevQueue == $sQueue ? '' : $sQueue, $jsonRow['agentchannel'], htmlentities($jsonRow['agentname'], ENT_COMPAT, 'UTF-8'), $sEstadoTag, '<span id="' . $jsonKey . '-num_calls">' . $jsonRow['num_calls'] . '</span>', '<span id="' . $jsonKey . '-logintime">' . timestamp_format($jsonRow['logintime']) . '</span>', '<span id="' . $jsonKey . '-sec_calls">' . timestamp_format($jsonRow['sec_calls']) . '</span>');
        $arrData[] = $tupla;
        $sPrevQueue = $sQueue;
    }
    // Emitir fila de totales para la cola ÚLTIMA
    $jsTotalKey = 'queue-' . $sPrevQueue;
    $arrData[] = array('<b>' . _tr('TOTAL') . '</b>', '&nbsp;', '<b>' . _tr('Agents') . ': ' . $tuplaTotal['num_agents'] . '</b>', '&nbsp;', '<b><span id="' . $jsTotalKey . '-num_calls">' . $tuplaTotal['num_calls'] . '</span></b>', '<b><span id="' . $jsTotalKey . '-logintime">' . timestamp_format($tuplaTotal['logintime']) . '</span></b>', '<b><span id="' . $jsTotalKey . '-sec_calls">' . timestamp_format($tuplaTotal['sec_calls']) . '</span></b>');
    // No es necesario emitir el nombre del agente la inicialización JSON
    foreach (array_keys($jsonData) as $k) {
        unset($jsonData[$k]['agentname']);
    }
    // Extraer la información que el navegador va a usar para actualizar
    $estadoCliente = array();
    foreach (array_keys($jsonData) as $k) {
        $estadoCliente[$k] = array('status' => $jsonData[$k]['status'], 'oncallupdate' => $jsonData[$k]['oncallupdate']);
    }
    $estadoHash = generarEstadoHash($module_name, $estadoCliente);
    $oGrid = new paloSantoGrid($smarty);
    $json = new Services_JSON();
    $INITIAL_CLIENT_STATE = $json->encode($jsonData);
    $sJsonInitialize = <<<JSON_INITIALIZE
<script type="text/javascript">
\$(function() {
    initialize_client_state({$INITIAL_CLIENT_STATE}, '{$estadoHash}');
});
</script>
JSON_INITIALIZE;
    return $oGrid->fetchGrid(array('title' => _tr('Agents Monitoring'), 'icon' => _tr('images/list.png'), 'width' => '99%', 'start' => 1, 'end' => 1, 'total' => 1, 'url' => array('menu' => $module_name), 'columns' => array(array('name' => _tr('Queue')), array('name' => _tr('Number')), array('name' => _tr('Agent')), array('name' => _tr('Current status')), array('name' => _tr('Total calls')), array('name' => _tr('Total login time')), array('name' => _tr('Total talk time')))), $arrData, $arrLang) . $sJsonInitialize;
}
Пример #12
0
function edit_form($pDB, $smarty, $module_name, $local_templates_dir, $formCampos, $oForm)
{
    $smarty->assign('FRAMEWORK_TIENE_TITULO_MODULO', existeSoporteTituloFramework());
    // Tengo que recuperar los datos del formulario
    $oDataForm = new paloSantoDataForm($pDB);
    $arrDataForm = $oDataForm->getFormularios($_GET['id']);
    $arrFieldForm = $oDataForm->obtener_campos_formulario($_GET['id']);
    $arrTmp['form_nombre'] = $arrDataForm[0]['nombre'];
    $arrTmp['form_description'] = $arrDataForm[0]['descripcion'];
    $oForm = new paloForm($smarty, $formCampos);
    $oForm->setEditMode();
    $smarty->assign("id_formulario_actual", $_GET['id']);
    $html_campos = html_campos_formulario($arrFieldForm);
    $smarty->assign("solo_contenido_en_vista", $html_campos);
    $smarty->assign('icon', 'images/kfaxview.png');
    $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/form.tpl", _tr('Edit Form') . " \"" . $arrTmp['form_nombre'] . "\"", $arrTmp);
    return $contenidoModulo;
}
Пример #13
0
function form_Configuration(&$oDB, $smarty, $module_name, $local_templates_dir)
{
    global $arrConfig;
    $smarty->assign('FRAMEWORK_TIENE_TITULO_MODULO', existeSoporteTituloFramework());
    $arrFormConference = createFieldForm();
    $oForm = new paloForm($smarty, $arrFormConference);
    $smarty->assign("SAVE", _tr("Save"));
    $smarty->assign("REQUIRED_FIELD", _tr("Required field"));
    $smarty->assign("icon", "images/list.png");
    $objConfig =& new PaloSantoConfiguration($oDB);
    $listaConf = $objConfig->ObtainConfiguration();
    //    print_r($listaConf);
    $camposConocidos = array('asterisk.asthost' => 'asterisk_asthost', 'asterisk.astuser' => 'asterisk_astuser', 'asterisk.astpass' => 'asterisk_astpass_1', 'asterisk.duracion_sesion' => 'asterisk_duracion_sesion', 'dialer.llamada_corta' => 'dialer_llamada_corta', 'dialer.tiempo_contestar' => 'dialer_tiempo_contestar', 'dialer.debug' => 'dialer_debug', 'dialer.allevents' => 'dialer_allevents', 'dialer.overcommit' => 'dialer_overcommit', 'dialer.qos' => 'dialer_qos', 'dialer.predictivo' => 'dialer_predictivo', 'dialer.timeout_originate' => 'dialer_timeout_originate', 'dialer.timeout_inactivity' => 'dialer_timeout_inactivity');
    $valoresForm = array('asterisk_asthost' => '127.0.0.1', 'asterisk_astuser' => '', 'asterisk_astpass_1' => '', 'asterisk_astpass_2' => '', 'asterisk_duracion_sesion' => '0', 'dialer_llamada_corta' => '10', 'dialer_tiempo_contestar' => '8', 'dialer_debug' => 'off', 'dialer_allevents' => 'off', 'dialer_overcommit' => 'off', 'dialer_qos' => '0.97', 'dialer_predictivo' => 'on', 'dialer_timeout_originate' => '0', 'dialer_timeout_inactivity' => '15');
    foreach ($camposConocidos as $dbfield => $formfield) {
        if (isset($listaConf[$dbfield])) {
            if (in_array($dbfield, array('dialer.debug', 'dialer.allevents', 'dialer.overcommit', 'dialer.predictivo'))) {
                $valoresForm[$formfield] = $listaConf[$dbfield] ? 'on' : 'off';
            } else {
                $valoresForm[$formfield] = $listaConf[$dbfield];
            }
        } else {
        }
    }
    if (count($_POST) > 0) {
        if (!isset($_POST['asterisk_astuser']) || trim($_POST['asterisk_astuser']) == '') {
            $_POST['asterisk_astuser'] = '';
            $_POST['asterisk_astpass_1'] = '';
            $_POST['asterisk_astpass_2'] = '';
        }
        foreach ($camposConocidos as $dbfield => $formfield) {
            if (isset($_POST[$formfield])) {
                if (in_array($dbfield, array('dialer.debug', 'dialer.allevents', 'dialer.overcommit', 'dialer.predictivo'))) {
                    $valoresForm[$formfield] = $_POST[$formfield] == 'on' ? 'on' : 'off';
                } else {
                    $valoresForm[$formfield] = $_POST[$formfield];
                }
            }
        }
        $action = getAction();
        if ($action == 'save') {
            if (!$oForm->validateForm($_POST)) {
                $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}, ";
                    }
                }
                $smarty->assign("mb_message", $strErrorMsg);
            } elseif ($_POST['dialer_qos'] < 0 || $_POST['dialer_qos'] >= 100) {
                $smarty->assign("mb_title", _tr("Validation Error"));
                $arrErrores = array('Service Percent' => 'Not in range 1..99');
                $strErrorMsg = "<b>" . _tr('The following fields contain errors') . ":</b><br/>";
                if (is_array($arrErrores) && count($arrErrores) > 0) {
                    foreach ($arrErrores as $k => $v) {
                        $strErrorMsg .= "{$k}, ";
                    }
                }
                $smarty->assign("mb_message", $strErrorMsg);
            } elseif ($_POST['asterisk_astpass_1'] != $_POST['asterisk_astpass_2']) {
                $smarty->assign("mb_title", _tr("Validation Error"));
                $strErrorMsg = _tr('Password and confirmation do not match.');
                $smarty->assign("mb_message", $strErrorMsg);
            } else {
                // Esto asume implementación PDO
                $oDB->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $oDB->conn->beginTransaction();
                $bContinuar = TRUE;
                $strErrorMsg = '';
                $config = array();
                foreach ($camposConocidos as $dbfield => $formfield) {
                    if ($dbfield == 'asterisk.astpass' && $_POST[$formfield] == '') {
                        continue;
                    }
                    if (in_array($dbfield, array('dialer.debug', 'dialer.allevents', 'dialer.overcommit', 'dialer.predictivo'))) {
                        $config[$dbfield] = $_POST[$formfield] == 'on' ? 1 : 0;
                    } else {
                        $config[$dbfield] = $_POST[$formfield];
                    }
                }
                if (!isset($config['asterisk.astuser']) || $config['asterisk.astuser'] == '') {
                    $config['asterisk.astpass'] = '';
                }
                $bContinuar = $objConfig->SaveConfiguration($config);
                if (!$bContinuar) {
                    $strErrorMsg = $objConfig->errMsg;
                    $smarty->assign("mb_title", _tr('Internal DB error'));
                    $strErrorMsg = _tr('Could not save changes!') . ' ' . $strErrorMsg;
                    $smarty->assign("mb_message", $strErrorMsg);
                }
                if ($bContinuar) {
                    $bContinuar = $oDB->conn->commit();
                    if (!$bContinuar) {
                        $smarty->assign("mb_title", _tr('Internal DB error'));
                        $strErrorMsg = _tr('Could not commit changes!');
                        $smarty->assign("mb_message", $strErrorMsg);
                    }
                }
                if (!$bContinuar) {
                    $oDB->conn->rollBack();
                }
            }
        }
    }
    unset($valoresForm['asterisk_astpass_1']);
    unset($valoresForm['asterisk_astpass_2']);
    $htmlForm = $oForm->fetchForm("{$local_templates_dir}/form.tpl", _tr("Configuration"), $valoresForm);
    $contenidoModulo = "<form  method='POST' style='margin-bottom:0;' action='?menu={$module_name}'>" . $htmlForm . "</form>";
    return $contenidoModulo;
}
Пример #14
0
function formEditUser($pDB, $smarty, $module_name, $local_templates_dir, $id_user)
{
    // 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
    $arrAgente = NULL;
    $oAgentes = new UsuariosECCP($pDB);
    if (!is_null($id_user)) {
        $arrAgente = $oAgentes->listarUsuarios($id_user);
        if (!is_array($arrAgente) || count($arrAgente) == 0) {
            $smarty->assign("mb_title", 'Unable to read agent');
            $smarty->assign("mb_message", 'Cannot read agent - ' . $oAgentes->errMsg);
            return '';
        }
        $arrAgente = $arrAgente[0];
    }
    $arrFormElements = getFormUser($smarty);
    // Valores por omisión para primera carga
    if (is_null($id_user)) {
        // Creación de nuevo agente
        if (!isset($_POST['username'])) {
            $_POST['username'] = '';
        }
        if (!isset($_POST['password1'])) {
            $_POST['password1'] = '';
        }
        if (!isset($_POST['password2'])) {
            $_POST['password2'] = '';
        }
    } else {
        // Modificación de agente existente
        if (!isset($_POST['username'])) {
            $_POST['username'] = $arrAgente['username'];
        }
        if (!isset($_POST['password1'])) {
            $_POST['password1'] = '';
        }
        if (!isset($_POST['password2'])) {
            $_POST['password2'] = '';
        }
        // Volver opcional el cambio de clave de acceso
        $arrFormElements['password1']['REQUIRED'] = 'no';
        $arrFormElements['password2']['REQUIRED'] = 'no';
    }
    $oForm = new paloForm($smarty, $arrFormElements);
    if (!is_null($id_user)) {
        $oForm->setEditMode();
        $smarty->assign("id_user", $id_user);
    }
    $bDoCreate = isset($_POST['submit_save']);
    $bDoUpdate = isset($_POST['submit_apply_changes']);
    if ($bDoCreate || $bDoUpdate) {
        if (!$oForm->validateForm($_POST)) {
            // 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>";
            foreach ($arrErrores as $k => $v) {
                $strErrorMsg .= "{$k}, ";
            }
            $strErrorMsg .= "";
            $smarty->assign("mb_message", $strErrorMsg);
        } else {
            foreach (array('password1', 'password2', 'username') as $k) {
                $_POST[$k] = trim($_POST[$k]);
            }
            if ($_POST['password1'] != $_POST['password2'] || $bDoCreate && $_POST['password1'] == '') {
                $smarty->assign("mb_title", _tr('Validation Error'));
                $smarty->assign("mb_message", _tr('The passwords are empty or dont match'));
            } else {
                $bExito = TRUE;
                if ($bDoUpdate && $_POST['password1'] == '') {
                    $_POST['password1'] = NULL;
                }
                if ($bDoCreate) {
                    $bExito = $oAgentes->crearUsuario($_POST['username'], $_POST['password1']);
                    if (!$bExito) {
                        $smarty->assign("mb_message", "" . _tr('Error on user creation') . " " . $oAgentes->errMsg);
                    }
                } elseif ($bDoUpdate) {
                    $bExito = $oAgentes->editarUsuario($id_user, $_POST['username'], $_POST['password1']);
                    if (!$bExito) {
                        $smarty->assign("mb_message", "" . _tr('Error on user update') . " " . $oAgentes->errMsg);
                    }
                }
                if ($bExito) {
                    header("Location: ?menu={$module_name}");
                }
            }
        }
    }
    $smarty->assign('icon', 'images/user.png');
    $contenidoModulo = $oForm->fetchForm("{$local_templates_dir}/edit-users.tpl", is_null($id_user) ? _tr('New user') : _tr('Edit user') . ' "' . $_POST['username'] . '"', $_POST);
    return $contenidoModulo;
}