Пример #1
0
function listarColaFax_json($smarty, $module_name, $local_templates_dir)
{
    //TODO: falta ahcer un filtrado de los trabajos pendientes por organizaionc
    //      esto se puede hacer si se identifica a que modem pertence cada trajado
    //      en la cola. Cada trabajo listado tiene un correspondiente archivo
    //      en donde se describe a que modem pertenece. Seria de ller ese archivo
    //      si el trbajo es de envio se encuentra en /var/spool/hylafax/sendq/
    //      si el trabjo es de envio se encuentra en /var/spool/hylafax/recvq/
    //      el nombre del archivo seria qJID donde JID ES DE ID DEL JOB
    session_commit();
    $oldhash = getParameter('outputhash');
    $html = NULL;
    $startTime = time();
    do {
        $listaColaFax = enumerarFaxesPendientes();
        $newhash = md5(serialize($listaColaFax));
        if ($oldhash == $newhash) {
            usleep(2 * 1000000);
        } else {
            $html = listarColaFax_raw($smarty, $module_name, $local_templates_dir, $listaColaFax);
        }
    } while ($oldhash == $newhash && time() - $startTime < 30);
    $jsonObject = new PalosantoJSON();
    $jsonObject->set_status($oldhash != $newhash ? 'CHANGED' : 'NOCHANGED');
    $jsonObject->set_message(array('html' => $html, 'outputhash' => $newhash));
    Header('Content-Type: application/json');
    return $jsonObject->createJSON();
}
Пример #2
0
function listRepositories($smarty, $module_name, $local_templates_dir, $arrConf)
{
    $oRepositories = new PaloSantoRepositories();
    $arrReposActivos = array();
    $typeRepository = getParameter("typeRepository");
    if (isset($_POST['submit_aceptar'])) {
        foreach ($_POST as $key => $value) {
            if (substr($key, 0, 5) == 'repo-') {
                $arrReposActivos[] = substr($key, 5);
            }
        }
        $oRepositories->setRepositorios($arrConf['ruta_repos'], $arrReposActivos, $typeRepository, $arrConf["main_repos"]);
    }
    $option["main"] = "";
    $option["others"] = "";
    $option["all"] = "";
    $arrRepositorios = $oRepositories->getRepositorios($arrConf['ruta_repos'], $typeRepository, $arrConf["main_repos"]);
    $limit = 40;
    $total = count($arrRepositorios);
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->setLimit($limit);
    $oGrid->setTotal($total);
    $offset = $oGrid->calculateOffset();
    $end = $oGrid->getEnd();
    $arrData = array();
    $version = $oRepositories->obtenerVersionDistro();
    $arch = $oRepositories->obtenerArquitectura();
    if (is_array($arrRepositorios)) {
        for ($i = $offset; $i < $end; $i++) {
            $activo = "";
            if ($arrRepositorios[$i]['activo']) {
                $activo = "checked='checked'";
            }
            $arrData[] = array("<input {$activo} name='repo-" . $arrRepositorios[$i]['id'] . "' type='checkbox' id='repo-{$i}' />", $valor = str_replace(array("\$releasever", "\$basearch"), array($version, $arch), $arrRepositorios[$i]['name']));
        }
    }
    if (isset($typeRepository)) {
        $oGrid->setURL("?menu={$module_name}&typeRepository={$typeRepository}");
        $_POST["typeRepository"] = $typeRepository;
    } else {
        $oGrid->setURL("?menu={$module_name}");
        $_POST["typeRepository"] = "main";
    }
    $arrGrid = array("title" => _tr("Repositories"), "icon" => "web/apps/{$module_name}/images/system_updates_repositories.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $end, "total" => $total, "columns" => array(0 => array("name" => _tr("Active"), "property1" => ""), 1 => array("name" => _tr("Name"), "property1" => "")));
    $oGrid->customAction('submit_aceptar', _tr('Save/Update'));
    $oGrid->addButtonAction("default", _tr('Default'), null, "defaultValues({$total},'{$version}','{$arch}')");
    $FilterForm = new paloForm($smarty, createFilter());
    $arrOpt = array("main" => _tr('Main'), "others" => _tr('Others'), "all" => _tr('All'));
    if (isset($arrOpt[$typeRepository])) {
        $valorfiltro = $arrOpt[$typeRepository];
    } else {
        $valorfiltro = _tr('Main');
    }
    $oGrid->addFilterControl(_tr("Filter applied ") . _tr("Repo") . " = " . $valorfiltro, $_POST, array("typeRepository" => "main"), true);
    $htmlFilter = $FilterForm->fetchForm("{$local_templates_dir}/new.tpl", "", $_POST);
    $oGrid->showFilter($htmlFilter);
    $contenidoModulo = $oGrid->fetchGrid($arrGrid, $arrData);
    return $contenidoModulo;
}
Пример #3
0
function performDelete()
{
    validateUser();
    withStatement("DELETE FROM DATA WHERE id=?", function ($statement) {
        $id = getParameter(PARAMETER_ID, PARAMETER_REQUIRED);
        $statement->bind_param("s", $id);
        executeStatement($statement);
    });
}
Пример #4
0
function transferSessionIdToCookieAndRedirect()
{
    $sessionId = getParameter("sessionId");
    if (isValidSessionId($sessionId)) {
        debug("setting session cookie");
        setcookie(COOKIE_SESSION_ID, $sessionId, time() + 60 * 60 * 24, "/", getDomainName());
        $baseUrl = getBaseUrl();
        debug("redirecting to: " . $baseUrl);
        header("Location: " . $baseUrl . "/");
    } else {
        performLogout();
    }
}
Пример #5
0
function display_form($smarty, $module_name, $local_templates_dir)
{
    require_once "libs/paloSantoForm.class.php";
    if (getParameter('csvupload') != '') {
        upload_csv($smarty, $module_name);
    }
    if (getParameter('delete_all') != '') {
        delete_extensions($smarty, $module_name);
    }
    $smarty->assign(array('MODULE_NAME' => $module_name, 'LABEL_FILE' => _tr("File"), 'LABEL_UPLOAD' => _tr('Save'), 'LABEL_DOWNLOAD' => _tr("Download Extensions"), 'LABEL_DELETE' => _tr('Delete All Extensions'), 'CONFIRM_DELETE' => _tr("Are you really sure you want to delete all the extensions in this server?"), 'HeaderFile' => _tr("Header File Extensions Batch"), 'AboutUpdate' => _tr("About Update Extensions Batch")));
    $oForm = new paloForm($smarty, array());
    return $oForm->fetchForm("{$local_templates_dir}/extension.tpl", _tr('Extensions Batch'), $_POST);
}
Пример #6
0
 public function __construct()
 {
     function getParameter($name, $defaultValue)
     {
         if (isset($_GET[$name])) {
             return urldecode($_GET[$name]);
         } else {
             return $defaultValue;
         }
     }
     $version = intval(getParameter('v', '0'));
     $androidId = getParameter('aid', '');
     $statistics = new StatisticRepository();
     $statistics->increaseVisits(StatisticRepository::REST_API, date('Y-m-d'), $version, $androidId);
 }
Пример #7
0
function getData()
{
    $tmpName = $_FILES['file']['tmp_name'];
    assertNotEmpty($tmpName, "missing file");
    $imageWidth = getParameter("imageWidth");
    $imageHeight = getParameter("imageHeight");
    $contentType = getContentType();
    debug($contentType);
    if (($contentType == "image/jpeg" || $contentType == "image/x-png" || $contentType == "image/png" || $contentType == "image/gif") && !empty($imageWidth) && !empty($imageHeight)) {
        resizeImage($tmpName, $imageWidth, $imageHeight);
    }
    $fp = fopen($tmpName, 'r');
    $length = filesize($tmpName);
    debug("File size: {$length}");
    $content = fread($fp, $length);
    fclose($fp);
    return $content;
}
Пример #8
0
function listarColaFax_json($smarty, $module_name, $local_templates_dir)
{
    session_commit();
    $oldhash = getParameter('outputhash');
    $html = NULL;
    $startTime = time();
    do {
        $listaColaFax = enumerarFaxesPendientes();
        $newhash = md5(serialize($listaColaFax));
        if ($oldhash == $newhash) {
            usleep(2 * 1000000);
        } else {
            $html = listarColaFax_raw($smarty, $module_name, $local_templates_dir, $listaColaFax);
        }
    } while ($oldhash == $newhash && time() - $startTime < 30);
    $jsonObject = new PalosantoJSON();
    $jsonObject->set_status($oldhash != $newhash ? 'CHANGED' : 'NOCHANGED');
    $jsonObject->set_message(array('html' => $html, 'outputhash' => $newhash));
    Header('Content-Type: application/json');
    return $jsonObject->createJSON();
}
Пример #9
0
function _moduleContent(&$smarty, $module_name)
{
    //include module files
    include_once "modules/{$module_name}/configs/default.conf.php";
    global $arrConf;
    load_language_module($module_name);
    $arrConf = array_merge($arrConf, $arrConfig);
    //folder path for custom templates
    $base_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    $templates_dir = isset($arrConfig['templates_dir']) ? $arrConfig['templates_dir'] : 'themes';
    $local_templates_dir = "{$base_dir}/modules/{$module_name}/" . $templates_dir . '/' . $arrConf['theme'];
    // Conexión a la base de datos CallCenter
    $pDB = new paloDB($arrConf['cadena_dsn']);
    switch (getParameter('action')) {
        case 'new_user':
            return nuevoUsuario($pDB, $smarty, $module_name, $local_templates_dir);
        case 'edit_user':
            return editarUsuario($pDB, $smarty, $module_name, $local_templates_dir);
        case 'list_user':
        default:
            return listarUsuarios($pDB, $smarty, $module_name, $local_templates_dir);
    }
}
Пример #10
0
function getAction()
{
    if (getParameter("save_new")) {
        //Get parameter by POST (submit)
        return "save_new";
    } else {
        if (getParameter("save_edit")) {
            return "save_edit";
        } else {
            if (getParameter("delete")) {
                return "delete";
            } else {
                if (getParameter("new_open")) {
                    return "view_form";
                } else {
                    if (getParameter("action") == "view") {
                        //Get parameter by GET (command pattern, links)
                        return "view_form";
                    } else {
                        if (getParameter("action") == "view_edit") {
                            return "view_form";
                        } else {
                            if (getParameter("action") == "call") {
                                return "call";
                            } else {
                                if (getParameter("action") == "loadBoxes") {
                                    return "loadBoxes";
                                } else {
                                    if (getParameter("action") == "voicemail") {
                                        return "voicemail";
                                    } else {
                                        if (getParameter("action") == "hangup") {
                                            return "hangup";
                                        } else {
                                            if (getParameter("action") == "getAllData") {
                                                return "getAllData";
                                            } else {
                                                if (getParameter("action") == "refresh") {
                                                    return "refresh";
                                                } else {
                                                    if (getParameter("action") == "savechange") {
                                                        return "savechange";
                                                    } else {
                                                        if (getParameter("action") == "savechange2") {
                                                            return "savechange2";
                                                        } else {
                                                            if (getParameter("action") == "saveresize") {
                                                                return "saveresize";
                                                            } else {
                                                                if (getParameter("action") == "loadArea") {
                                                                    return "loadArea";
                                                                } else {
                                                                    if (getParameter("action") == "saveEdit") {
                                                                        return "saveEdit";
                                                                    } else {
                                                                        if (getParameter("action") == "addExttoQueue") {
                                                                            return "addExttoQueue";
                                                                        } else {
                                                                            return "report";
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    //cancel
}
Пример #11
0
function getAction()
{
    global $arrPermission;
    if (getParameter("update_hosts")) {
        //Get parameter by POST (submit)
        return in_array('edit', $arrPermission) ? 'save' : 'show';
    } else {
        return "show";
    }
    //cancel
}
Пример #12
0
function getAction()
{
    global $arrPermission;
    if (getParameter("create_tg")) {
        return in_array('create', $arrPermission) ? 'new_tg' : 'report';
    } else {
        if (getParameter("save_new")) {
            //Get parameter by POST (submit)
            return in_array('create', $arrPermission) ? 'save_new' : 'report';
        } else {
            if (getParameter("save_edit")) {
                return in_array('edit', $arrPermission) ? 'save_edit' : 'report';
            } else {
                if (getParameter("delete")) {
                    return in_array('delete', $arrPermission) ? 'delete' : 'report';
                } else {
                    if (getParameter("action") == "edit") {
                        //Get parameter by GET (command pattern, links)
                        return "edit";
                    } else {
                        if (getParameter("action") == "reloadAsterisk") {
                            return "reloadAasterisk";
                        } else {
                            return "report";
                        }
                    }
                }
            }
        }
    }
    //cancel
}
 function isExportAction()
 {
     if (getParameter("exportcsv") == "yes") {
         return true;
     } else {
         if (getParameter("exportpdf") == "yes") {
             return true;
         } else {
             if (getParameter("exportspreadsheet") == "yes") {
                 return true;
             } else {
                 return false;
             }
         }
     }
 }
Пример #14
0
function uninstallPaquete($arrConf)
{
    $oPackages = new PaloSantoPackages($arrConf['ruta_yum']);
    $paquete = getParameter("paquete");
    $resultado = $oPackages->uninstallPackage($paquete);
    $jsonObject = new PaloSantoJSON();
    $jsonObject->set_status($resultado);
    return $jsonObject->createJSON();
}
Пример #15
0
<?php

include_once 'session_check.php';
include_once '../scripts/myErrorHandler.php';
include_once '../scripts/Database.php';
include_once '../scripts/utils.php';
$addResultText = "";
$code = getParameter('code');
if ($code != null) {
    $code = strtoupper($_GET['code']);
    $db = new Database();
    if ($db->updateUserAccount($uid, $code) == true) {
        $addResultText = "Dzi&#x119;kujemy za zakup<br/>";
        include 'session_check.php';
    } else {
        $addResultText = "Podany kod jest niew&#x142;a&#x15b;ciwy<br/>";
    }
    $db->destroy();
}
$user_login = "******";
// -1 aby nie proponować gościowi piosenki za darochę
$user_coins = -1;
if ($uid != null) {
    $user_login = $rowUser['login'];
    $user_coins = $rowUser['coins'];
}
trigger_error("user_coins: " . $user_coins, E_USER_NOTICE);
trigger_error("{$rowUser['coins']}: " . $rowUser['coins'], E_USER_NOTICE);
$wap_title = "mobiKAR";
include "add_head.php";
?>
Пример #16
0
function assign_TicketDelivery(&$pDB)
{
    // collect parameters
    $sTicketId = trim(getParameter('ticket_id'));
    $sUserId = trim(getParameter('user_id'));
    $sNote = trim(getParameter('note'));
    $response = array('action' => 'assign', 'message' => 'Phân công mã giao vé ' . $sTicketId . ' thành công');
    $pTicket_Delivery = new Ticket_Delivery($pDB);
    $result = $pTicket_Delivery->assignDelivery($sTicketId, $sUserId, $sNote);
    // return json
    if (!$result) {
        $response['action'] = 'error';
        $response['message'] = 'Lỗi: ' . $pTicket_Delivery->errMsg;
    }
    $json = new Services_JSON();
    Header('Content-Type: application/json');
    return $json->encode($response);
}
Пример #17
0
function createActivity($userId, $timezone)
{
    //Check
    if (!parameterExists(APIKeys::$ACTIVITY_NAME) && !parameterExists(APIKeys::$ACTIVITY_DURATION)) {
        displayError("Create Activity: Please supply an activity name and activty duration as part of the request");
    } else {
        if (!parameterExists(APIKeys::$ACTIVITY_NAME)) {
            displayError("Create Activity: Please supply an activity name as part of the request");
        } else {
            if (!parameterExists(APIKeys::$ACTIVITY_DURATION)) {
                displayError("Create Activity: Please supply an activity duration as part of the request");
            }
        }
    }
    //Get values
    $activityName = getParameter(APIKeys::$ACTIVITY_NAME);
    $activityDuration = getParameter(APIKeys::$ACTIVITY_DURATION);
    //Create activity
    $result = APIDb::createActivity($userId, $activityName, $activityDuration, $timezone);
    //Show Response
    response($result);
}
Пример #18
0
function getAction()
{
    if (getParameter("edit")) {
        return "edit";
    } else {
        if (getParameter("commit")) {
            return "commit";
        } else {
            if (getParameter("show")) {
                return "show";
            } else {
                if (getParameter("delete")) {
                    return "delete";
                } else {
                    if (getParameter("new")) {
                        return "new";
                    } else {
                        if (getParameter("save")) {
                            return "save";
                        } else {
                            if (getParameter("delete")) {
                                return "delete";
                            } else {
                                if (getParameter("action") == "show") {
                                    return "show";
                                } else {
                                    if (getParameter("action") == "edit") {
                                        return "edit";
                                    } else {
                                        if (getParameter("action") == "download_csv") {
                                            return "download_csv";
                                        } else {
                                            if (getParameter("action") == "call2phone") {
                                                return "call2phone";
                                            } else {
                                                if (getParameter("action") == "transfer_call") {
                                                    return "transfer_call";
                                                } else {
                                                    if (getParameter("action") == "getImage") {
                                                        return "getImage";
                                                    } else {
                                                        return "report";
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Пример #19
0
function getAction()
{
    global $arrPermission;
    if (getParameter("save_new")) {
        //Get parameter by POST (submit)
        //preguntar si el usuario puede hacer accion
        return in_array('edit', $arrPermission) ? 'save_new' : 'report';
    } else {
        return "report";
    }
    //cancel
}
Пример #20
0
function getAction()
{
    global $arrPermission;
    if (getParameter("new_emaillist")) {
        //Get parameter by POST (submit)
        return in_array('create_list', $arrPermission) ? 'new_emaillist' : 'report';
    } elseif (getParameter("save_newList")) {
        return in_array('create_list', $arrPermission) ? 'save_newList' : 'report';
    } elseif (getParameter("delete")) {
        return in_array('delete_list', $arrPermission) ? 'delete' : 'report';
    } elseif (getParameter("action") == "view_list") {
        return "view_list";
    } elseif (getParameter("save_mailmail_admin")) {
        return in_array('edit_list', $arrPermission) ? 'saveMailmanSettings' : 'report';
    } elseif (getParameter("action") == "mailman_settings") {
        return in_array('edit_list', $arrPermission) ? 'mailman_settings' : 'report';
    } elseif (getParameter("action") == "export") {
        return "export";
    } elseif (getParameter("return")) {
        return "report";
    } elseif (getParameter("new_memberlist")) {
        return in_array('edit_list', $arrPermission) ? 'new_memberlist' : 'report';
    } elseif (getParameter("save_newMember")) {
        return in_array('edit_list', $arrPermission) ? 'save_newMember' : 'report';
    } elseif (getParameter("remove_memberlist")) {
        return in_array('edit_list', $arrPermission) ? 'remove_memberlist' : 'report';
    } elseif (getParameter("action") == "view_memberlist" || getParameter("show")) {
        return "view_memberlist";
    } else {
        return "report";
    }
    //cancel
}
Пример #21
0
function viewNote()
{
    $sNoteId = trim(getParameter('view_note_id'));
    if ($sNoteId == '' || is_null($sNoteId)) {
        $response = 'Không có note id!';
        $json = new Services_JSON();
        Header('Content-Type: application/json');
        return $json->encode($response);
    }
    global $arrConf;
    $oCustomer = new getInfoMainConsole();
    $oCustomer->callcenter_db_connect($arrConf['cadena_dsn']);
    $result = $oCustomer->getNote($sNoteId);
    // return json
    if (!$result) {
        $response['content'] = 'Lỗi: ' . $oCustomer->errMsg;
    } else {
        $response['note_id'] = $sNoteId;
        $response['content'] = $result['note'];
        //check permission
    }
    $json = new Services_JSON();
    Header('Content-Type: application/json');
    return $json->encode($response);
}
Пример #22
0
function modificarCola($pDB, $smarty, $module_name, $local_templates_dir)
{
    $idCola = getParameter('id_queue');
    if (is_null($idCola)) {
        Header("Location: ?menu={$module_name}");
        return '';
    }
    return formularioModificarCola($pDB, $smarty, $module_name, $local_templates_dir, $idCola);
}
Пример #23
0
#!/bin/php
<?php 
/*
 * This file is part of fgrosse/gitlab-api.
 *
 * Copyright © Friedrich Große <*****@*****.**>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
use Gitlab\Client\GitlabGuzzleClient;
use Gitlab\Client\HttpGitlabClient;
include __DIR__ . '/../vendor/autoload.php';
include __DIR__ . '/cli_helper.php';
$baseUrl = getParameter('base-url', $argv);
$token = getParameter('token', $argv);
$project = getParameter('project', $argv);
try {
    $guzzleClient = GitlabGuzzleClient::factory(['base_url' => $baseUrl, 'api_token' => $token]);
    $client = new HttpGitlabClient($guzzleClient);
    $mergeRequests = $client->listMergeRequests($project, $state = 'closed', $order = 'updated_at', $sort = 'asc', $page = 1, $perPage = 5);
    foreach ($mergeRequests as $mergeRequest) {
        echo $mergeRequest . PHP_EOL;
    }
} catch (Exception $exception) {
    printError('An Exception of type ' . get_class($exception) . ' occurred:');
    printError($exception->getMessage());
    exit(1);
}
Пример #24
0
function manejarMonitoreo_checkStatus($module_name, $smarty, $sDirLocalPlantillas)
{
    $respuesta = array();
    ignore_user_abort(true);
    set_time_limit(0);
    // Estado del lado del cliente
    $estadoHash = getParameter('clientstatehash');
    if (!is_null($estadoHash)) {
        $estadoCliente = isset($_SESSION[$module_name]['estadoCliente']) ? $_SESSION[$module_name]['estadoCliente'] : array();
    } else {
        $estadoCliente = getParameter('clientstate');
        if (!is_array($estadoCliente)) {
            return;
        }
    }
    // Modo a funcionar: Long-Polling, o Server-sent Events
    $sModoEventos = getParameter('serverevents');
    $bSSE = !is_null($sModoEventos) && $sModoEventos;
    if ($bSSE) {
        Header('Content-Type: text/event-stream');
        printflush("retry: 1\n");
    } else {
        Header('Content-Type: application/json');
    }
    // Verificar hash correcto
    if (!is_null($estadoHash) && $estadoHash != $_SESSION[$module_name]['estadoClienteHash']) {
        $respuesta['estadoClienteHash'] = 'mismatch';
        $respuesta['hashRecibido'] = $estadoHash;
        jsonflush($bSSE, $respuesta);
        return;
    }
    $oPaloConsola = new PaloSantoConsola();
    // Estado del lado del servidor
    $estadoCampania = $oPaloConsola->leerEstadoCampania($estadoCliente['campaigntype'], $estadoCliente['campaignid']);
    if (!is_array($estadoCampania)) {
        $respuesta['error'] = $oPaloConsola->errMsg;
        jsonflush($bSSE, $respuesta);
        $oPaloConsola->desconectarTodo();
        return;
    }
    // Acumular inmediatamente las filas que son distintas en estado
    $respuesta = crearRespuestaVacia();
    // Cuenta de estados
    foreach (array_keys($estadoCliente['statuscount']) as $k) {
        // Actualización de valores de contadores
        if ($estadoCliente['statuscount'][$k] != $estadoCampania['statuscount'][$k]) {
            $respuesta['statuscount']['update'][$k] = $estadoCampania['statuscount'][$k];
            $estadoCliente['statuscount'][$k] = $estadoCampania['statuscount'][$k];
        }
    }
    // Estado de llamadas no conectadas
    foreach (array_keys($estadoCliente['activecalls']) as $k) {
        // Llamadas que cambiaron de estado o ya no están sin agente
        if (!isset($estadoCampania['activecalls'][$k])) {
            // Llamada ya no está esperando agente
            $respuesta['activecalls']['remove'][] = array('callid' => $estadoCliente['activecalls'][$k]['callid']);
            unset($estadoCliente['activecalls'][$k]);
        } elseif ($estadoCliente['activecalls'][$k]['callstatus'] != $estadoCampania['activecalls'][$k]['callstatus']) {
            // Llamada ha cambiado de estado
            $respuesta['activecalls']['update'][] = formatoLlamadaNoConectada($estadoCampania['activecalls'][$k]);
            $estadoCliente['activecalls'][$k] = $estadoCampania['activecalls'][$k];
        }
    }
    foreach (array_keys($estadoCampania['activecalls']) as $k) {
        // Llamadas nuevas
        if (!isset($estadoCliente['activecalls'][$k])) {
            $respuesta['activecalls']['add'][] = formatoLlamadaNoConectada($estadoCampania['activecalls'][$k]);
            $estadoCliente['activecalls'][$k] = $estadoCampania['activecalls'][$k];
        }
    }
    // Estado de agentes de campaña
    foreach (array_keys($estadoCliente['agents']) as $k) {
        // Agentes que cambiaron de estado o desaparecieron (???)
        if (!isset($estadoCampania['agents'][$k])) {
            // Agente ya no aparece (???)
            $respuesta['agents']['remove'][] = array('agent' => $estadoCliente['agents'][$k]['agentchannel']);
            unset($estadoCliente['agents'][$k]);
        } elseif ($estadoCliente['agents'][$k] != $estadoCampania['agents'][$k]) {
            // Agente ha cambiado de estado
            $respuesta['agents']['update'][] = formatoAgente($estadoCampania['agents'][$k]);
            $estadoCliente['agents'][$k] = $estadoCampania['agents'][$k];
        }
    }
    foreach (array_keys($estadoCampania['agents']) as $k) {
        // Agentes nuevos (???)
        if (!isset($estadoCliente['agents'][$k])) {
            $respuesta['agents']['add'][] = formatoAgente($estadoCampania['agents'][$k]);
            $estadoCliente['agents'][$k] = $estadoCampania['agents'][$k];
        }
    }
    unset($estadoCampania);
    $oPaloConsola->escucharProgresoLlamada(TRUE);
    $iTimeoutPoll = PaloSantoConsola::recomendarIntervaloEsperaAjax();
    do {
        $oPaloConsola->desconectarEspera();
        // Se inicia espera larga con el navegador...
        $iTimestampInicio = time();
        while (connection_status() == CONNECTION_NORMAL && esRespuestaVacia($respuesta) && time() - $iTimestampInicio < $iTimeoutPoll) {
            session_commit();
            $listaEventos = $oPaloConsola->esperarEventoSesionActiva();
            if (is_null($listaEventos)) {
                $respuesta['error'] = $oPaloConsola->errMsg;
                jsonflush($bSSE, $respuesta);
                $oPaloConsola->desconectarTodo();
                return;
            }
            @session_start();
            /* Si el navegador elige otra campaña mientras se espera la primera
             * campaña, entonces esta espera es inválida, y el navegador ya ha
             * iniciado otra sesión comet. */
            if (isset($_SESSION[$module_name]) && !($estadoCliente['campaigntype'] === $_SESSION[$module_name]['estadoCliente']['campaigntype'] && $estadoCliente['campaignid'] === $_SESSION[$module_name]['estadoCliente']['campaignid'])) {
                $respuesta['estadoClienteHash'] = 'invalidated';
                jsonflush($bSSE, $respuesta);
                $oPaloConsola->desconectarTodo();
                return;
            }
            $iTimestampActual = time();
            foreach ($listaEventos as $evento) {
                $sCanalAgente = isset($evento['agent_number']) ? $evento['agent_number'] : NULL;
                switch ($evento['event']) {
                    case 'agentloggedin':
                        if (isset($estadoCliente['agents'][$sCanalAgente])) {
                            /* Se ha logoneado agente que atiende a esta campaña.
                             * ATENCIÓN: sólo se setean suficientes campos para la
                             * visualización. Otros campos quedan con sus valores
                             * antiguos, si tenían */
                            $estadoCliente['agents'][$sCanalAgente]['status'] = 'online';
                            $estadoCliente['agents'][$sCanalAgente]['callnumber'] = NULL;
                            $estadoCliente['agents'][$sCanalAgente]['pausestart'] = NULL;
                            $estadoCliente['agents'][$sCanalAgente]['linkstart'] = NULL;
                            $estadoCliente['agents'][$sCanalAgente]['trunk'] = NULL;
                            $respuesta['agents']['update'][] = formatoAgente($estadoCliente['agents'][$sCanalAgente]);
                        }
                        break;
                    case 'agentloggedout':
                        if (isset($estadoCliente['agents'][$sCanalAgente])) {
                            /* Se ha deslogoneado agente que atiende a esta campaña.
                             * ATENCIÓN: sólo se setean suficientes campos para la
                             * visualización. Otros campos quedan con sus valores
                             * antiguos, si tenían */
                            $estadoCliente['agents'][$sCanalAgente]['status'] = 'offline';
                            $estadoCliente['agents'][$sCanalAgente]['callnumber'] = NULL;
                            $estadoCliente['agents'][$sCanalAgente]['pausestart'] = NULL;
                            $estadoCliente['agents'][$sCanalAgente]['linkstart'] = NULL;
                            $estadoCliente['agents'][$sCanalAgente]['trunk'] = NULL;
                            $respuesta['agents']['update'][] = formatoAgente($estadoCliente['agents'][$sCanalAgente]);
                        }
                        break;
                    case 'callprogress':
                        $bProcesar = $estadoCliente['campaigntype'] == 'incomingqueue' ? $estadoCliente['campaignid'] == $evento['queue'] && is_null($evento['campaign_id']) : $estadoCliente['campaignid'] == $evento['campaign_id'] && $estadoCliente['campaigntype'] == $evento['call_type'];
                        if ($bProcesar) {
                            // Llamada corresponde a cola monitoreada
                            $callid = $evento['call_id'];
                            // Para llamadas entrantes, cada llamada en cola aumenta el total
                            if ($evento['call_type'] == 'incoming' && $evento['new_status'] == 'OnQueue') {
                                agregarContadorLlamada('total', $estadoCliente, $respuesta);
                            }
                            if (in_array($evento['new_status'], array('Failure', 'Abandoned', 'NoAnswer'))) {
                                if (isset($estadoCliente['activecalls'][$callid])) {
                                    restarContadorLlamada($estadoCliente['activecalls'][$callid]['callstatus'], $estadoCliente, $respuesta);
                                    agregarContadorLlamada($evento['new_status'], $estadoCliente, $respuesta);
                                    // Quitar de las llamadas que esperan un agente
                                    $respuesta['activecalls']['remove'][] = array('callid' => $callid);
                                    unset($estadoCliente['activecalls'][$callid]);
                                }
                            } elseif (in_array($evento['new_status'], array('OnHold', 'OffHold'))) {
                                // Se supone que una llamada en hold ya fue asignada a un agente
                            } else {
                                if (isset($estadoCliente['activecalls'][$callid])) {
                                    restarContadorLlamada($estadoCliente['activecalls'][$callid]['callstatus'], $estadoCliente, $respuesta);
                                    $estadoCliente['activecalls'][$callid]['callstatus'] = $evento['new_status'];
                                    $estadoCliente['activecalls'][$callid]['trunk'] = $evento['trunk'];
                                    if ($evento['new_status'] == 'OnQueue') {
                                        $estadoCliente['activecalls'][$callid]['queuestart'] = $evento['datetime_entry'];
                                    }
                                    $respuesta['activecalls']['update'][] = formatoLlamadaNoConectada($estadoCliente['activecalls'][$callid]);
                                } else {
                                    // Valores sólo para satisfacer formato
                                    $estadoCliente['activecalls'][$callid] = array('callid' => $callid, 'callnumber' => $evento['phone'], 'callstatus' => $evento['new_status'], 'dialstart' => $evento['datetime_entry'], 'dialend' => NULL, 'queuestart' => $evento['datetime_entry'], 'trunk' => $evento['trunk']);
                                    $respuesta['activecalls']['add'][] = formatoLlamadaNoConectada($estadoCliente['activecalls'][$callid]);
                                }
                                agregarContadorLlamada($evento['new_status'], $estadoCliente, $respuesta);
                            }
                            $respuesta['log'][] = formatoLogCampania(array('id' => $evento['id'], 'new_status' => $evento['new_status'], 'datetime_entry' => $evento['datetime_entry'], 'campaign_type' => $evento['call_type'], 'campaign_id' => $evento['campaign_id'], 'call_id' => $evento['call_id'], 'retry' => $evento['retry'], 'uniqueid' => $evento['uniqueid'], 'trunk' => $evento['trunk'], 'phone' => $evento['phone'], 'queue' => $evento['queue'], 'agentchannel' => $sCanalAgente, 'duration' => NULL));
                        }
                        break;
                    case 'pausestart':
                        if (isset($estadoCliente['agents'][$sCanalAgente])) {
                            // Agente ha entrado en pausa
                            $estadoCliente['agents'][$sCanalAgente]['status'] = 'paused';
                            $estadoCliente['agents'][$sCanalAgente]['pausestart'] = $evento['pause_start'];
                            $respuesta['agents']['update'][] = formatoAgente($estadoCliente['agents'][$sCanalAgente]);
                        }
                        break;
                    case 'pauseend':
                        if (isset($estadoCliente['agents'][$sCanalAgente])) {
                            // Agente ha salido de pausa
                            $estadoCliente['agents'][$sCanalAgente]['status'] = is_null($estadoCliente['agents'][$sCanalAgente]['linkstart']) ? 'online' : 'oncall';
                            $estadoCliente['agents'][$sCanalAgente]['pausestart'] = NULL;
                            $respuesta['agents']['update'][] = formatoAgente($estadoCliente['agents'][$sCanalAgente]);
                        }
                        break;
                    case 'agentlinked':
                        // Si la llamada estaba en lista activa, quitarla
                        $callid = $evento['call_id'];
                        if (isset($estadoCliente['activecalls'][$callid])) {
                            restarContadorLlamada($estadoCliente['activecalls'][$callid]['callstatus'], $estadoCliente, $respuesta);
                            $respuesta['activecalls']['remove'][] = array('callid' => $estadoCliente['activecalls'][$callid]['callid']);
                            unset($estadoCliente['activecalls'][$callid]);
                        }
                        // Si el agente es uno de los de la campaña, modificar
                        if (isset($estadoCliente['agents'][$sCanalAgente])) {
                            $estadoCliente['agents'][$sCanalAgente]['status'] = is_null($estadoCliente['agents'][$sCanalAgente]['pausestart']) ? 'oncall' : 'paused';
                            $estadoCliente['agents'][$sCanalAgente]['callnumber'] = $evento['phone'];
                            $estadoCliente['agents'][$sCanalAgente]['linkstart'] = $evento['datetime_linkstart'];
                            $estadoCliente['agents'][$sCanalAgente]['trunk'] = $evento['trunk'];
                            $respuesta['agents']['update'][] = formatoAgente($estadoCliente['agents'][$sCanalAgente]);
                            $respuesta['log'][] = formatoLogCampania(array('id' => $evento['campaignlog_id'], 'new_status' => 'Success', 'datetime_entry' => $evento['datetime_linkstart'], 'campaign_type' => $evento['call_type'], 'campaign_id' => $evento['campaign_id'], 'call_id' => $evento['call_id'], 'retry' => $evento['retries'], 'uniqueid' => $evento['uniqueid'], 'trunk' => $evento['trunk'], 'phone' => $evento['phone'], 'queue' => $evento['queue'], 'agentchannel' => $sCanalAgente, 'duration' => NULL));
                            agregarContadorLlamada('Success', $estadoCliente, $respuesta);
                        }
                        break;
                    case 'agentunlinked':
                        // Si el agente es uno de los de la campaña, modificar
                        if (isset($estadoCliente['agents'][$sCanalAgente])) {
                            /* Es posible que se reciba un evento agentunlinked luego
                             * del evento agentloggedout si el agente se desconecta con
                             * una llamada activa. */
                            if ($estadoCliente['agents'][$sCanalAgente]['status'] != 'offline') {
                                $estadoCliente['agents'][$sCanalAgente]['status'] = is_null($estadoCliente['agents'][$sCanalAgente]['pausestart']) ? 'online' : 'paused';
                            }
                            $estadoCliente['agents'][$sCanalAgente]['callnumber'] = NULL;
                            $estadoCliente['agents'][$sCanalAgente]['linkstart'] = NULL;
                            $estadoCliente['agents'][$sCanalAgente]['trunk'] = NULL;
                            $respuesta['agents']['update'][] = formatoAgente($estadoCliente['agents'][$sCanalAgente]);
                            $respuesta['log'][] = formatoLogCampania(array('id' => $evento['campaignlog_id'], 'new_status' => $evento['shortcall'] ? 'ShortCall' : 'Hangup', 'datetime_entry' => $evento['datetime_linkend'], 'campaign_type' => $evento['call_type'], 'campaign_id' => $evento['campaign_id'], 'call_id' => $evento['call_id'], 'retry' => NULL, 'uniqueid' => NULL, 'trunk' => NULL, 'phone' => $evento['phone'], 'queue' => NULL, 'agentchannel' => $sCanalAgente, 'duration' => $evento['duration']));
                            if ($evento['call_type'] == 'incoming') {
                                restarContadorLlamada('Success', $estadoCliente, $respuesta);
                                agregarContadorLlamada('Finished', $estadoCliente, $respuesta);
                                agregarContadorLlamada('Total', $estadoCliente, $respuesta);
                                $respuesta['duration'] = $evento['duration'];
                            } else {
                                if ($evento['shortcall']) {
                                    restarContadorLlamada('Success', $estadoCliente, $respuesta);
                                    agregarContadorLlamada('ShortCall', $estadoCliente, $respuesta);
                                } else {
                                    // Se actualiza Finished para actualizar estadísticas
                                    agregarContadorLlamada('Finished', $estadoCliente, $respuesta);
                                    $respuesta['duration'] = $evento['duration'];
                                }
                            }
                            if (isset($respuesta['duration'])) {
                                $estadoCliente['stats']['total_sec'] += $respuesta['duration'];
                                if ($estadoCliente['stats']['max_duration'] < $respuesta['duration']) {
                                    $estadoCliente['stats']['max_duration'] = $respuesta['duration'];
                                }
                            }
                        }
                        break;
                }
            }
        }
        $estadoHash = generarEstadoHash($module_name, $estadoCliente);
        $respuesta['estadoClienteHash'] = $estadoHash;
        jsonflush($bSSE, $respuesta);
        $respuesta = crearRespuestaVacia();
    } while ($bSSE && connection_status() == CONNECTION_NORMAL);
    $oPaloConsola->desconectarTodo();
}
Пример #25
0
function manejarSesionActiva_checkStatus($module_name, $smarty, $sDirLocalPlantillas, $oPaloConsola, $estado)
{
    $respuesta = array();
    ignore_user_abort(true);
    set_time_limit(0);
    $sNombrePausa = NULL;
    $iDuracionLlamada = NULL;
    $iDuracionPausa = $iDuracionPausaActual = NULL;
    $estadoCliente = getParameter('clientstate');
    // Validación del estado del cliente:
    // onhold break_id calltype campaign_id callid
    $estadoCliente['onhold'] = isset($estadoCliente['onhold']) ? $estadoCliente['onhold'] == 'true' : false;
    foreach (array('break_id', 'calltype', 'campaign_id', 'callid') as $k) {
        if (!isset($estadoCliente[$k]) || $estadoCliente[$k] == 'null') {
            $estadoCliente[$k] = NULL;
        }
    }
    if (is_null($estadoCliente['calltype'])) {
        $estadoCliente['campaign_id'] = $estadoCliente['callid'] = NULL;
    } elseif (is_null($estadoCliente['callid'])) {
        $estadoCliente['campaign_id'] = $estadoCliente['calltype'] = NULL;
    } elseif (is_null($estadoCliente['campaign_id']) && $estadoCliente['calltype'] != 'incoming') {
        $estadoCliente['calltype'] = $estadoCliente['callid'] = NULL;
    }
    // Modo a funcionar: Long-Polling, o Server-sent Events
    $sModoEventos = getParameter('serverevents');
    $bSSE = !is_null($sModoEventos) && $sModoEventos;
    if ($bSSE) {
        Header('Content-Type: text/event-stream');
        printflush("retry: 1\n");
    } else {
        Header('Content-Type: application/json');
    }
    // Respuesta inmediata si el agente ya no está logoneado
    if ($estado['estadofinal'] != 'logged-in') {
        // Respuesta inmediata si el agente ya no está logoneado
        jsonflush($bSSE, array('event' => 'logged-out'));
        return;
    }
    // Verificación de la consistencia del estado de break
    if (!is_null($estado['pauseinfo'])) {
        $sNombrePausa = $estado['pauseinfo']['pausename'];
        $iDuracionPausaActual = time() - strtotime($estado['pauseinfo']['pausestart']);
        $iDuracionPausa = $iDuracionPausaActual + $_SESSION['callcenter']['break_acumulado'];
    } else {
        /* 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. 
         */
        if (!is_null($_SESSION['callcenter']['break_iniciado'])) {
            $_SESSION['callcenter']['break_acumulado'] += time() - strtotime($_SESSION['callcenter']['break_iniciado']);
        }
        $_SESSION['callcenter']['break_iniciado'] = NULL;
    }
    if (!is_null($estado['pauseinfo']) && (is_null($estadoCliente['break_id']) || $estadoCliente['break_id'] != $estado['pauseinfo']['pauseid'])) {
        // La consola debe de entrar en break
        $respuesta[] = construirRespuesta_breakenter($estado['pauseinfo']['pauseid']);
    } elseif (!is_null($estadoCliente['break_id']) && is_null($estado['pauseinfo'])) {
        // La consola debe de salir del break
        $respuesta[] = construirRespuesta_breakexit();
    }
    // Verificación de la consistencia del estado de hold
    if (!$estadoCliente['onhold'] && $estado['onhold']) {
        // La consola debe de entrar en hold
        $respuesta[] = construirRespuesta_holdenter();
    } elseif ($estadoCliente['onhold'] && !$estado['onhold']) {
        // La consola debe de salir de hold
        $respuesta[] = construirRespuesta_holdexit();
    }
    if (!is_null($estado['callinfo'])) {
        $iDuracionLlamada = time() - strtotime($estado['callinfo']['linkstart']);
    }
    // Verificación de atención a llamada
    if (!is_null($estado['callinfo']) && (is_null($estadoCliente['calltype']) || $estadoCliente['calltype'] != $estado['callinfo']['calltype'] || $estadoCliente['campaign_id'] != $estado['callinfo']['campaign_id'] || $estadoCliente['callid'] != $estado['callinfo']['callid'])) {
        // Información sobre la llamada conectada
        $infoLlamada = $oPaloConsola->leerInfoLlamada($estado['callinfo']['calltype'], $estado['callinfo']['campaign_id'], $estado['callinfo']['callid']);
        // Leer información del formulario de la campaña
        if ($estado['callinfo']['calltype'] == 'incoming' && is_null($estado['callinfo']['campaign_id'])) {
            $infoCampania['forms'] = NULL;
        } else {
            $infoCampania = $oPaloConsola->leerInfoCampania($estado['callinfo']['calltype'], $estado['callinfo']['campaign_id']);
        }
        // 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'];
        $respuesta[] = construirRespuesta_agentlinked($smarty, $sDirLocalPlantillas, $oPaloConsola, $estado['callinfo'], $infoLlamada, $infoCampania);
    } elseif (!is_null($estadoCliente['calltype']) && is_null($estado['callinfo'])) {
        // La consola dejó de atender una llamada
        $respuesta[] = construirRespuesta_agentunlinked();
    }
    // Ciclo de verificación para Server-sent Events
    $sAgente = 'Agent/' . $_SESSION['callcenter']['agente'];
    $iTimeoutPoll = PaloSantoConsola::recomendarIntervaloEsperaAjax();
    $bReinicioSesion = FALSE;
    do {
        $oPaloConsola->desconectarEspera();
        // Se inicia espera larga con el navegador...
        session_commit();
        $iTimestampInicio = time();
        $respuestaEventos = array();
        while (connection_status() == CONNECTION_NORMAL && count($respuestaEventos) <= 0 && count($respuesta) <= 0 && time() - $iTimestampInicio < $iTimeoutPoll) {
            $listaEventos = $oPaloConsola->esperarEventoSesionActiva();
            if (is_null($listaEventos)) {
                // Ocurrió una excepción al esperar eventos
                @session_start();
                $respuesta[] = array('event' => 'logged-out');
                // Eliminar la información de login
                $_SESSION['callcenter'] = generarEstadoInicial();
                $bReinicioSesion = TRUE;
                break;
            }
            foreach ($listaEventos as $evento) {
                if (isset($evento['agent_number']) && $evento['agent_number'] == $sAgente) {
                    switch ($evento['event']) {
                        case 'agentloggedout':
                            // Reiniciar la sesión para poder modificar las variables
                            @session_start();
                            $respuesta[] = array('event' => 'logged-out');
                            // Eliminar la información de login
                            $_SESSION['callcenter'] = generarEstadoInicial();
                            $bReinicioSesion = TRUE;
                            break;
                        case 'pausestart':
                            unset($respuestaEventos[$evento['pause_class']]);
                            switch ($evento['pause_class']) {
                                case 'break':
                                    if (is_null($estadoCliente['break_id']) || $estadoCliente['break_id'] != $evento['pause_type']) {
                                        $sNombrePausa = $evento['pause_name'];
                                        $respuestaEventos['break'] = construirRespuesta_breakenter($evento['pause_type']);
                                    }
                                    @session_start();
                                    $iDuracionPausaActual = time() - strtotime($evento['pause_start']);
                                    $iDuracionPausa = $iDuracionPausaActual + $_SESSION['callcenter']['break_acumulado'];
                                    $_SESSION['callcenter']['break_iniciado'] = $evento['pause_start'];
                                    break;
                                case 'hold':
                                    if (!$estadoCliente['onhold']) {
                                        $respuestaEventos['hold'] = construirRespuesta_holdenter();
                                    }
                                    break;
                            }
                            break;
                        case 'pauseend':
                            unset($respuestaEventos[$evento['pause_class']]);
                            switch ($evento['pause_class']) {
                                case 'break':
                                    if (!is_null($estadoCliente['break_id'])) {
                                        $respuestaEventos['break'] = construirRespuesta_breakexit();
                                    }
                                    @session_start();
                                    $_SESSION['callcenter']['break_acumulado'] += $evento['pause_duration'];
                                    $_SESSION['callcenter']['break_iniciado'] = NULL;
                                    break;
                                case 'hold':
                                    if ($estadoCliente['onhold']) {
                                        $respuestaEventos['hold'] = construirRespuesta_holdexit();
                                    }
                                    break;
                            }
                            break;
                        case 'agentlinked':
                            unset($respuestaEventos['llamada']);
                            /* Actualizar la interfaz si entra una nueva llamada, o si 
                             * la llamada activa anterior es reemplazada. */
                            if (is_null($estadoCliente['calltype']) || $estadoCliente['calltype'] != $evento['call_type'] || $estadoCliente['campaign_id'] != $evento['campaign_id'] || $estadoCliente['callid'] != $evento['call_id']) {
                                $nuevoEstado = array('calltype' => $evento['call_type'], 'campaign_id' => $evento['campaign_id'], 'linkstart' => $evento['datetime_linkstart'], 'callid' => $evento['call_id'], 'callnumber' => $evento['phone']);
                                $iDuracionLlamada = time() - strtotime($nuevoEstado['linkstart']);
                                // Leer información del formulario de la campaña
                                if ($nuevoEstado['calltype'] == 'incoming' && is_null($nuevoEstado['campaign_id'])) {
                                    $infoCampania['forms'] = NULL;
                                } else {
                                    $infoCampania = $oPaloConsola->leerInfoCampania($nuevoEstado['calltype'], $nuevoEstado['campaign_id']);
                                }
                                // Almacenar para regenerar formulario
                                @session_start();
                                $_SESSION['callcenter']['ultimo_calltype'] = $nuevoEstado['calltype'];
                                $_SESSION['callcenter']['ultimo_callid'] = $nuevoEstado['callid'];
                                $_SESSION['callcenter']['ultimo_callsurvey']['call_survey'] = $evento['call_survey'];
                                $_SESSION['callcenter']['ultimo_campaignform']['forms'] = $infoCampania['forms'];
                                $respuestaEventos['llamada'] = construirRespuesta_agentlinked($smarty, $sDirLocalPlantillas, $oPaloConsola, $nuevoEstado, $evento, $infoCampania);
                            }
                            break;
                        case 'agentunlinked':
                            unset($respuestaEventos['llamada']);
                            if (!is_null($estadoCliente['calltype'])) {
                                $respuestaEventos['llamada'] = construirRespuesta_agentunlinked();
                            }
                            break;
                    }
                }
            }
        }
        // while(...)
        // Sólo debe haber hasta un evento de llamada, de break, de hold
        if (isset($respuestaEventos['break'])) {
            $respuesta[] = $respuestaEventos['break'];
        }
        if (isset($respuestaEventos['hold'])) {
            $respuesta[] = $respuestaEventos['hold'];
        }
        if (isset($respuestaEventos['llamada'])) {
            $respuesta[] = $respuestaEventos['llamada'];
        }
        // Agregar los textos a cambiar en la interfaz
        $sDescInicial = describirEstadoBarra($estadoCliente);
        $estadoFinal = $estadoCliente;
        foreach ($respuesta as $evento) {
            switch ($evento['event']) {
                case 'holdenter':
                    $estadoCliente['onhold'] = TRUE;
                    break;
                case 'holdexit':
                    $estadoCliente['onhold'] = FALSE;
                    break;
                case 'breakenter':
                    $estadoFinal['break_id'] = $evento['break_id'];
                    $estadoCliente['break_id'] = $evento['break_id'];
                    break;
                case 'breakexit':
                    $estadoFinal['break_id'] = NULL;
                    $estadoCliente['break_id'] = NULL;
                    break;
                case 'agentlinked':
                    $estadoFinal['calltype'] = $evento['calltype'];
                    $estadoCliente['calltype'] = $evento['calltype'];
                    $estadoCliente['campaign_id'] = $evento['campaign_id'];
                    $estadoCliente['callid'] = $evento['callid'];
                    break;
                case 'agentunlinked':
                    $estadoFinal['calltype'] = NULL;
                    $estadoCliente['calltype'] = NULL;
                    $estadoCliente['campaign_id'] = NULL;
                    $estadoCliente['callid'] = NULL;
                    break;
            }
        }
        $sDescFinal = describirEstadoBarra($estadoFinal);
        $iPosEvento = count($respuesta) - 1;
        if ($iPosEvento >= 0 && $sDescInicial != $sDescFinal) {
            switch ($sDescFinal) {
                case 'llamada':
                    $respuesta[$iPosEvento]['txt_estado_agente_inicial'] = _tr('Đang có cuộc gọi đến');
                    $respuesta[$iPosEvento]['class_estado_agente_inicial'] = 'elastix-callcenter-class-estado-activo';
                    $respuesta[$iPosEvento]['timer_seconds'] = $iDuracionLlamada;
                    break;
                case 'break':
                    $respuesta[$iPosEvento]['txt_estado_agente_inicial'] = _tr('On break') . ': ' . $sNombrePausa;
                    $respuesta[$iPosEvento]['class_estado_agente_inicial'] = 'elastix-callcenter-class-estado-break';
                    $respuesta[$iPosEvento]['timer_seconds'] = $iDuracionPausa;
                    break;
                case 'ocioso':
                    $respuesta[$iPosEvento]['txt_estado_agente_inicial'] = _tr('No active call');
                    $respuesta[$iPosEvento]['class_estado_agente_inicial'] = 'elastix-callcenter-class-estado-ocioso';
                    $respuesta[$iPosEvento]['timer_seconds'] = '';
                    break;
            }
        }
        jsonflush($bSSE, $respuesta);
        $respuesta = array();
    } while ($bSSE && !$bReinicioSesion && connection_status() == CONNECTION_NORMAL);
    $oPaloConsola->desconectarTodo();
}
Пример #26
0
function getAction()
{
    if (getParameter("action") == "view_bodymail") {
        return "view_bodymail";
    } elseif (getParameter("action") == "mv_msg_to_folder") {
        return "mv_msg_to_folder";
    } elseif (getParameter("action") == "mark_msg_as") {
        return "mark_msg_as";
    } elseif (getParameter("action") == "delete_msg_trash") {
        return "delete_msg_trash";
    } elseif (getParameter("action") == "toggle_important") {
        return "toggle_important";
    } elseif (getParameter("action") == "create_mailbox") {
        return "create_mailbox";
    } elseif (getParameter("action") == "download_attach") {
        return "download_attach";
    } elseif (getParameter("action") == "get_inline_attach") {
        return "get_inline_attach";
    } elseif (getParameter("action") == "get_templateEmail") {
        return "get_templateEmail";
    } elseif (getParameter("action") == "compose_email") {
        return "compose_email";
    } elseif (getParameter("action") == "attach_file") {
        return "attach_file";
    } elseif (getParameter("action") == "deattach_file") {
        return "deattach_file";
    } elseif (getParameter("action") == "forwardGetAttachs") {
        return "forwardGetAttachs";
    } elseif (getParameter("action") == "refreshMail") {
        return "refreshMail";
    } else {
        return "report";
    }
}
Пример #27
0
            hangup($agent);
            break;
        case 'spycall':
            $agent = getParameter('agent');
            $supervisor = getParameter('supervisor');
            if (getParameter('whisper') == 'true') {
                $whisper = true;
            } else {
                $whisper = false;
            }
            spycall($agent, $supervisor, $whisper);
            break;
        case 'transfer':
            $agent = getParameter('agent');
            $dest = '8';
            $dest .= getParameter('extension');
            transfer($agent, $dest);
            break;
        case 'addnote':
            $agent = getParameter('agent');
            $note_ext = getParameter('extension');
            $note = getParameter('note');
            addnote($agent, $note_ext, $note);
            break;
        default:
            break;
    }
}
$json = new Services_JSON();
Header('Content-Type: application/json');
echo $json->encode($response);
Пример #28
0
function getAction()
{
    global $arrPermission;
    if (getParameter("save")) {
        return in_array('edit', $arrPermission) ? 'save_config' : 'report';
    } else {
        return "report";
    }
    //cancel
}
Пример #29
0
function modificarArchivo($module_name, $smarty, $local_templates_dir, $sDirectorio, $sAccion)
{
    $sNombreArchivo = '';
    $sMensajeStatus = '';
    if (isset($_POST['Reload'])) {
        $parameters = array('Command' => "module reload");
        $result = AsteriskManagerAPI("Command", $parameters, true);
        if ($result) {
            $smarty->assign("mb_title", "MESSAGE");
            $smarty->assign("mb_message", _tr("Asterisk has been reloaded"));
        } else {
            $smarty->assign("mb_title", "ERROR");
            $smarty->assign("mb_message", _tr("Error when connecting to Asterisk Manager"));
        }
    }
    if ($sAccion == 'new') {
        $smarty->assign('LABEL_COMPLETADO', '.conf');
        if (isset($_POST['Guardar'])) {
            if (!isset($_POST['basename']) || trim($_POST['basename']) == '') {
                $sMensajeStatus .= _tr('Please write the file name') . '<br/>';
            } else {
                $sNombreArchivo = basename($_POST['basename'] . '.conf');
                /* Los datos del archivo se envían desde el navegador con líneas
                     separadas por CRLF que debe ser convertido a LF para estilo Unix
                   */
                if (file_put_contents($sDirectorio . $sNombreArchivo, str_replace("\r\n", "\n", $_POST['content'])) === FALSE) {
                    $sMensajeStatus .= _tr("This file doesn't have permisses to write") . '<br/>';
                } else {
                    $sMensajeStatus .= _tr("The changes was saved in the file") . '<br/>';
                }
            }
        }
    } elseif ($sAccion == 'edit') {
        $sNombreArchivo = basename(getParameter('file'));
        if (is_null($sNombreArchivo) || !file_exists($sDirectorio . $sNombreArchivo)) {
            Header("Location: ?menu={$module_name}");
            return '';
        }
        if (isset($_POST['Guardar'])) {
            /* Los datos del archivo se envían desde el navegador con líneas
                 separadas por CRLF que debe ser convertido a LF para estilo Unix
               */
            if (!is_writable($sDirectorio . $sNombreArchivo) || file_put_contents($sDirectorio . $sNombreArchivo, str_replace("\r\n", "\n", $_POST['content'])) === FALSE) {
                $sMensajeStatus .= _tr("This file doesn't have permisses to write") . '<br/>';
            } else {
                $sMensajeStatus .= _tr("The changes was saved in the file") . '<br/>';
            }
        } else {
            if (!is_writable($sDirectorio . $sNombreArchivo)) {
                $sMensajeStatus .= _tr("This file doesn't have permisses to write") . '<br/>';
            }
        }
        $sContenido = file_get_contents($sDirectorio . $sNombreArchivo);
        if ($sContenido === FALSE) {
            $sMensajeStatus .= _tr("This file doesn't have permisses to read") . '<br/>';
        }
        if (!isset($_POST['content'])) {
            $_POST['content'] = $sContenido;
        }
        $_POST['basename'] = basename($sNombreArchivo);
    }
    $oForm = new paloForm($smarty, array('basename' => array('LABEL' => _tr('File'), 'REQUIRED' => 'yes', 'INPUT_TYPE' => 'TEXT', 'INPUT_EXTRA_PARAM' => '', 'VALIDATION_TYPE' => 'text', 'VALIDATION_EXTRA_PARAM' => '', 'EDITABLE' => $sAccion == 'new' ? 'yes' : 'no'), 'content' => array('LABEL' => _tr('Content'), 'REQUIRED' => 'no', 'INPUT_TYPE' => 'TEXTAREA', 'INPUT_EXTRA_PARAM' => '', 'VALIDATION_TYPE' => 'text', 'VALIDATION_EXTRA_PARAM' => '', 'ROWS' => 25, 'COLS' => 100)));
    $oForm->setEditMode();
    $smarty->assign('url_edit', construirURL(array('menu' => $module_name, 'action' => $sAccion, 'file' => $sNombreArchivo)));
    $smarty->assign('url_back', construirURL(array('menu' => $module_name), array('action', 'file', 'nav' => getParameter('nav'), 'page' => getParameter('page'))));
    $smarty->assign('search', getParameter('search'));
    $smarty->assign('LABEL_SAVE', _tr('Save'));
    $smarty->assign('RELOAD_ASTERISK', _tr('Reload Asterisk'));
    $smarty->assign('LABEL_BACK', _tr('Back'));
    $smarty->assign('msg_status', $sMensajeStatus);
    $smarty->assign('icon', "images/user.png");
    return $oForm->fetchForm("{$local_templates_dir}/file_editor.tpl", _tr("File Editor"), $_POST);
}
Пример #30
-1
    function exportHTML2PDF($orientation, $pageFormats, $baseImgPath, $header = '')
    {
        ob_start();
        ?>

        <style type="text/css">
            .gt-table {
                border: solid 0px #000000;
                border-left:1px; 
                border-top:1px;
                width: 50%;
            }

            .gt-table th {
                background-color: #eeeeee;
                border-right:1px; border-bottom:1px;
            }

            .gt-table td {
                border-right:1px; border-bottom:1px;
            }

            .gt-inner {
                width: 50%;
            }

            .gt-inner-right {
                text-align : right;
            }


        </style>

        <?php 
        $template_style = ob_get_clean();
        $_pageD = '10mm';
        $tableHTML = getParameter('__gt_html');
        //$headS = strpos($tableHTML, '<!-- gt : head start  -->')+strlen('<!-- gt : head start  -->');
        $headE = strpos($tableHTML, '<!-- gt : head end  -->') + strlen('<!-- gt : head end  -->');
        $tableStartHTML = substr($tableHTML, 0, $headE);
        /* PUNTO DE ENTRADA PARA AGREGAR MAS HTML */
        $tableHTML = $header . str_replace('.gt-grid ', '', $tableHTML);
        $tableHTML = str_replace('<!-- gt : page separator  -->', '</tbody></table></page><page backtop="' . $_pageD . '" backbottom="' . $_pageD . '">' . $tableStartHTML . '<tbody>', $tableHTML);
        //debug ( $template_style );
        //debug ("----------------\n");
        //debug ( $tableHTML );
        ////////////////////////////////////////////////////////////////////////
        //begin !!the following lines exist for enhance exporting performance
        ////////////////////////////////////////////////////////////////////////
        preg_match_all('/\\.([a-z0-9_\\-]+)\\s+\\{(.*?)display:none;(.*?)\\}/', $tableHTML, $result, PREG_SET_ORDER);
        $patternArray = array();
        $replaceArray = array();
        for ($matchi = 0; $matchi < count($result); $matchi++) {
            $patternArray[$matchi] = '/<td\\s+class="([a-z0-9_\\-]+\\s+)*' . $result[$matchi][1] . '(\\s+[a-z0-9_\\-]+)*\\s*"[^>]*>(.*?)<\\/td>/';
            //debug($patternArray[$matchi] ."\n");
            $replaceArray[$matchi] = '';
        }
        $tableHTML = preg_replace($patternArray, $replaceArray, $tableHTML);
        ////////////////////////////////////////////////////////////////////////
        //end !!
        ////////////////////////////////////////////////////////////////////////
        //debug ("----------------\n");
        //debug ( $tableHTML );
        $page_content = '<page backtop="' . $_pageD . '" backbottom="' . $_pageD . '">' . $template_style . $tableHTML . '</page>';
        $pdf = new HTML2PDF($orientation, $pageFormats, 'en', false, $baseImgPath);
        $pdf->WriteHTML($page_content, false);
        $pdf->pdf->Output($this->exportFileName . '.pdf', 'D');
    }