예제 #1
0
파일: index.php 프로젝트: hardikk/HNH
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);
}
예제 #2
0
파일: index.php 프로젝트: hardikk/HNH
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;
}