Example #1
0
 public function sesion_exit()
 {
     session_id('uid');
     session_start();
     session_destroy();
     session_commit();
 }
Example #2
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();
}
 public function actions()
 {
     $return = [];
     $module_token = Yii::$app->request->post('module_token');
     $this_module_token = \fec\helpers\CModule::getToken();
     if ($module_token != $this_module_token) {
         $return['ack'] = false;
         $return['ack_description'] = "modules token is not right";
         $return['content'] = $module_token . '#' . $this_module_token;
         echo json_encode($return);
         exit;
     }
     $r = $this->getControllerAndAction();
     $t_controller = $r['controller'];
     $t_action = $r['action'];
     $current_remote_function_param_array = Yii::$app->request->post('current_remote_function_param_array');
     $current_remote_function_param_array = unserialize($current_remote_function_param_array);
     $param = !empty($current_remote_function_param_array) && is_array($current_remote_function_param_array) ? $current_remote_function_param_array : [];
     $current_namespace = $this->_name_space;
     $module_o_dir = str_replace("\\controllers", "\\o", $current_namespace);
     $function_exec = $module_o_dir . "\\" . $t_controller . "::" . $t_action;
     $data = \call_user_func_array($function_exec, $param);
     $data = json_decode($data);
     $return['ack'] = true;
     $return['ack_description'] = "success";
     $return['content'] = $data;
     # 把模块更新的session更新到redis上面,以供其他模块使用
     session_commit();
     echo json_encode($return);
     exit;
 }
 public function bookDetails(Request $request)
 {
     $book_id = $request->input("book");
     $book_id = trim($book_id);
     $book = Book::where('book_id', $book_id)->get();
     if (count($book) > 0) {
         $latitude = trim($request->input("latitude"));
         $longitude = trim($request->input("longitude"));
         if (session_id() == "" || !isset($_SESSION['latitude'])) {
             session_start();
             $_SESSION['latitude'] = $latitude;
             $_SESSION['longitude'] = $longitude;
         } else {
             unset($_SESSION['longitude']);
             unset($_SESSION['latitude']);
             $_SESSION['latitude'] = $latitude;
             $_SESSION['longitude'] = $longitude;
         }
         session_commit();
         $message = ["code" => 100, "message" => "success"];
     } else {
         $message = ["code" => 101, "message" => "fail"];
     }
     return $message;
 }
Example #5
0
 public static function execute($commande, $params)
 {
     session_start();
     $endpoint=new static();
     
     $commande = "API_".$commande;
     
     
     $endpointReflx = new ReflectionObject($endpoint);
     $methodReflx = $endpointReflx->getMethod($commande);
     try{
         $result =$methodReflx->invokeArgs($endpoint, $params);
         
         $result = [
             'status'=>'success',
             'value'=>$result
         ];
         
     }
     catch(ErrorException $ex)
     {
         $result = [
             'status'=>'error',
             'value'=>$ex->getMessage()
         ];
     }
     session_commit();
     return $result;
 }
Example #6
0
 public function createResult()
 {
     $payload = json_encode($this->requestObject);
     $res = $this->connection->post('/calculation/', $payload);
     $object = json_decode($res);
     $_SESSION['cascoResultId'] = $object->id;
     session_commit();
 }
Example #7
0
 public static function sessionDestroy($sessionName = null)
 {
     if (isset($sessionName)) {
         unset($sessionName);
     }
     session_destroy();
     session_commit();
 }
Example #8
0
 public function testSessionDestroy()
 {
     $this->assertFalse(session_destroy());
     $_SESSION['foo'] = 'bar';
     session_start();
     session_commit();
     $this->assertTrue(session_destroy());
     $file = sprintf('%s/sess_%s', sys_get_temp_dir(), session_id());
     $this->assertFalse(file_exists($file));
 }
Example #9
0
 public static function updateSession($user)
 {
     $_SESSION['userinfo'] = serialize($user);
     if (isset($_REQUEST['rememberMe']) && ($_REQUEST['rememberMe'] === "true" || $_REQUEST['rememberMe'] === "on")) {
         $_SESSION['rememberMe'] = true;
     } else {
         $_SESSION['rememberMe'] = false;
     }
     session_commit();
 }
Example #10
0
function dldc_die($message = 0)
{
    try {
        session_commit();
    } catch (Exception $e) {
        # TODO: SESSIONS ARE WEIRD
    }
    dldc_restore_db();
    die($message);
}
 /**
  * Gets RSA Public Key.
  *
  * @return Keypair|NULL
  */
 public function getRsaPublicKey()
 {
     $keyPair = null;
     $backend = Backend\BackendFactory::getBackend();
     if ($backend !== null) {
         $keyPair = $backend->createNewKeyPair();
         $storage = Storage\StorageFactory::getStorage();
         $storage->put($keyPair->getPrivateKey());
         session_commit();
     }
     return $keyPair;
 }
 public function Logout()
 {
     $noheader = new NoHeader();
     $noheader->noheader();
     if (isset($_SESSION['authUser'])) {
         unset($_SESSION['authUser']);
         $_SESSION = array();
         session_destroy();
         session_commit();
     }
     //echo HOME;
     header("Location:" . HOME . 'index.php');
 }
 public function test_session_handler_clean()
 {
     $_SESSION['name'] = 'Fredrik';
     session_commit();
     $session_handler = WP_Sessions::instance()->get_session_handler();
     $this->assertSame('name|s:7:"Fredrik";', $session_handler->read(session_id()));
     global $wpdb;
     $table = $wpdb->prefix . 'sessions';
     $wpdb->update($table, ['timestamp' => time() - HOUR_IN_SECONDS * 25], ['id' => session_id()], ['%d'], ['%s']);
     $this->assertSame('name|s:7:"Fredrik";', $session_handler->read(session_id()));
     $session_handler->clean();
     $this->assertEmpty($session_handler->read(session_id()));
 }
 public static function auth($nomeDeUsuario, $senha)
 {
     $con = Connection::get();
     $prepared = $con->prepare("SELECT codigo FROM Contas WHERE nomeDeUsuario='{$nomeDeUsuario}' AND senha=md5('{$senha}')");
     $prepared->execute();
     $result = $prepared->fetch(PDO::FETCH_ASSOC);
     if ($result && !is_null($result['codigo'])) {
         $_SESSION['cod_user'] = (int) $result['codigo'];
         session_commit();
         return true;
     } else {
         return false;
     }
 }
 static function verffyOrg()
 {
     $noheader = new NoHeader();
     $noheader->noheader();
     if (isset($_SESSION['authUser'])) {
         if ($_SESSION['authUser']->organizador) {
             return;
         }
     }
     unset($_SESSION['authUser']);
     $_SESSION = array();
     session_destroy();
     session_commit();
     header("Location:" . HOME . 'index.php');
 }
Example #16
0
 public function test_session_garbage_collection()
 {
     global $wpdb;
     $_SESSION['foo'] = 'bar';
     session_commit();
     $this->assertEquals(1, $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->pantheon_sessions}"));
     $current_val = ini_get('session.gc_maxlifetime');
     ini_set('session.gc_maxlifetime', 100000000);
     _pantheon_session_garbage_collection(ini_get('session.gc_maxlifetime'));
     $this->assertEquals(1, $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->pantheon_sessions}"));
     ini_set('session.gc_maxlifetime', 0);
     _pantheon_session_garbage_collection(ini_get('session.gc_maxlifetime'));
     $this->assertEquals(0, $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->pantheon_sessions}"));
     ini_set('session.gc_maxlifetime', $current_val);
 }
Example #17
0
 /**
  * Gets RSA Public Key.
  *
  * @param array $parameters Parameters (not used)
  * @param \TYPO3\CMS\Core\Http\AjaxRequestHandler $parent The calling parent AJAX object
  * @return void
  */
 public function getRsaPublicKey(array $parameters, \TYPO3\CMS\Core\Http\AjaxRequestHandler $parent)
 {
     $backend = BackendFactory::getBackend();
     if ($backend !== NULL) {
         $keyPair = $backend->createNewKeyPair();
         $storage = \TYPO3\CMS\Rsaauth\Storage\StorageFactory::getStorage();
         $storage->put($keyPair->getPrivateKey());
         session_commit();
         $parent->addContent('publicKeyModulus', $keyPair->getPublicKeyModulus());
         $parent->addContent('exponent', sprintf('%x', $keyPair->getExponent()));
         $parent->setContentFormat('json');
     } else {
         $parent->setError('No OpenSSL backend could be obtained for rsaauth.');
     }
 }
Example #18
0
 function progress($curl, $data)
 {
     $len = fwrite($this->file, $data);
     $this->progress += $len;
     session_start();
     // Bu kismi ben ekledim. Islemin iptali icin..
     if ($_SESSION['devam'] == 1) {
         curl_close($curl);
         fclose($this->file);
         session_destroy();
     }
     $_SESSION['inen'] = $this->progress;
     $_SESSION['toplam'] = curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
     session_commit();
     return $len;
 }
 /**
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @return ResponseInterface
  */
 public function processRequest(ServerRequestInterface $request, ResponseInterface $response)
 {
     /** @var \TYPO3\CMS\Rsaauth\Backend\AbstractBackend $backend */
     $backend = BackendFactory::getBackend();
     if ($backend === null) {
         // add a HTTP 500 error code, if an error occurred
         return $response->withStatus(500);
     }
     $keyPair = $backend->createNewKeyPair();
     $storage = StorageFactory::getStorage();
     $storage->put($keyPair->getPrivateKey());
     session_commit();
     $content = $keyPair->getPublicKeyModulus() . ':' . sprintf('%x', $keyPair->getExponent()) . ':';
     $response->getBody()->write($content);
     return $response;
 }
Example #20
0
function getHeadJS()
{
    global $g, $use_loader_tab_gif;
    if (!$use_loader_tab_gif) {
        $loader_gif = "/themes/{$g['theme']}/images/misc/loader.gif";
    } else {
        $loader_gif = "/themes/{$g['theme']}/images/misc/loader_tab.gif";
    }
    $headjs = "\n    var input_errors = '';\n    jQuery(document).ready(init);\n  ";
    if (!session_id()) {
        session_start();
    }
    $_SESSION['NO_AJAX'] == "True" ? $noajax = "var noAjaxOnSubmit = true;" : ($noajax = "var noAjaxOnSubmit = false;");
    session_commit();
    $headjs .= "\n    {$noajax}\n\n    function init() {\n      if(jQuery('#submit') && ! noAjaxOnSubmit) {\n        // debugging helper\n        //alert('adding observe event for submit button');\n        \n        jQuery(\"#submit\").click(submit_form);\n        jQuery('#submit').click(function() {return false;});\n        var to_insert = \"<div style='visibility:hidden' id='loading' name='loading'><img src='{$loader_gif}' alt='loader' \\/><\\/div>\";\n        jQuery('#submit').before(to_insert);\n      }\n    }\n    \n    function submit_form(e){\n      // debugging helper\n      //alert(Form.serialize(\$('iform')));\n\n      if(jQuery('#inputerrors'))\n        jQuery('#inputerrors').html('<center><b><i>Loading...<\\/i><\\/b><\\/center>');\n        \n      /* dsh: Introduced because pkg_edit tries to set some hidden fields\n       *      if executing submit's onclick event. The click gets deleted\n       *      by Ajax. Hence using onkeydown instead.\n       */\n      if(jQuery('#submit').prop('keydown')) {\n        jQuery('#submit').keydown();\n        jQuery('#submit').css('visibility','hidden');\n      }\n      if(jQuery('#cancelbutton'))\n        jQuery('#cancelbutton').css('visibility','hidden');\n      jQuery('#loading').css('visibility','visible');\n      // submit the form using Ajax\n    }\n   \n    function formSubmitted(resp) {\n      var responseText = resp.responseText;\n      \n      // debugging helper\n      // alert(responseText);\n      \n      if(responseText.indexOf('html') > 0) {\n        /* somehow we have been fed an html page! */\n        //alert('Somehow we have been fed an html page! Forwarding to /.');\n        document.location.href = '/';\n      }\n      \n      eval(responseText);\n    }\n    \n    /* this function will be called if an HTTP error will be triggered */\n    function formFailure(resp) {\n\t    showajaxmessage(resp.responseText);\n\t\tif(jQuery('#submit'))\n\t\t  jQuery('#submit').css('visibility','visible');\n\t\tif(jQuery('#cancelbutton'))\n\t\t  jQuery('#cancelbutton').css('visibility','visible');\n\t\tif(jQuery('#loading'))\n\t\t  jQuery('#loading').css('visibility','hidden');\n\n    }\n    \n    function showajaxmessage(message) {\n      var message_html;\n\n      if (message == '') {\n        NiftyCheck();\n        Rounded(\"div#redbox\",\"all\",\"#FFF\",\"#990000\",\"smooth\");\n        Rounded(\"td#blackbox\",\"all\",\"#FFF\",\"#000000\",\"smooth\");\n\n        if(jQuery('#submit'))\n          jQuery('#submit').css('visibility','visible');\n        if(jQuery('#cancelbutton'))\n          jQuery('#cancelbutton').css('visibility','visible');\n        if(jQuery('#loading'))\n          jQuery('#loading').css('visibility','hidden');\n\n        return;\n      }\n\n      message_html = '<table height=\"32\" width=\"100%\" summary=\"redbox\"><tr><td>';\n      message_html += '<div style=\"background-color:#990000\" id=\"redbox\">';\n      message_html += '<table width=\"100%\" summary=\"message\"><tr><td width=\"8%\">';\n      message_html += '<img style=\"vertical-align:center\" src=\"/themes/{$g['theme']}/images/icons/icon_exclam.gif\" width=\"28\" height=\"32\" alt=\"exclamation\" \\/>';\n      message_html += '<\\/td><td width=\"70%\"><font color=\"white\">';\n      message_html += '<b>' + message + '<\\/b><\\/font><\\/td>';\n\n      if(message.indexOf('apply') > 0) {\n        message_html += '<td>';\n        message_html += '<input name=\"apply\" type=\"submit\" class=\"formbtn\" id=\"apply\" value=\"" . gettext("Apply changes") . "\" \\/>';\n        message_html += '<\\/td>';\n      }\n\n      message_html += '<\\/tr><\\/table><\\/div><\\/td><\\/table><br \\/>';\n      jQuery('#inputerrors').html(message_html);\n\n      NiftyCheck();\n      Rounded(\"div#redbox\",\"all\",\"#FFF\",\"#990000\",\"smooth\");\n      Rounded(\"td#blackbox\",\"all\",\"#FFF\",\"#000000\",\"smooth\");\n\n      if(jQuery('#submit'))\n        jQuery('#submit').css('visibility','visible');\n      if(jQuery('#cancelbutton'))\n        jQuery('#cancelbutton').css('visibility','visible');\n      if(jQuery('#loading'))\n        jQuery('#loading').css('visibility','hidden');\n      if(jQuery('#inputerrors'))\n        window.scrollTo(0, 0);\n    }\n  ";
    return $headjs;
}
Example #21
0
 /**
  * Autenticacao do funcionario
  * 
  * @return void
  */
 public function logar()
 {
     if ($_POST) {
         $sql = "SELECT nome FROM " . self::TABELA . " WHERE email = ? AND senha = ?";
         $this->extrairDadosPost();
         $this->criptografarSenha();
         $valores = array($this->obj_ModelData->email, $this->obj_ModelData->senha);
         $funcionario = $this->obj_Banco->consultarSQL($sql, $valores);
         if (count($funcionario)) {
             $_SESSION['funcionarios']['email'] = $funcionario[0]->email;
             $_SESSION['funcionarios']['nome'] = $funcionario[0]->nome;
             session_commit();
         } else {
             Mensagem::set("E-mail e/ou senha inválidos!", 'error');
         }
     }
     @header("Location: {$_SERVER['HTTP_REFERER']}");
 }
Example #22
0
 public function fetch($obj_data, $req_data = [])
 {
     if (!is_array($req_data)) {
         $message = 'fetch($obj_data,$req_data),$req_data must be array';
         throw new \yii\web\HttpException(406, $message);
     }
     $data = '';
     if (is_array($obj_data) && !empty($obj_data)) {
         $modules = $obj_data[0];
         $file = $obj_data[1];
         $function = $obj_data[2];
         $is_remote = $obj_data[3];
         if ($modules && $file && $function) {
             $ModulesConfig = $this->getModulesConfig();
             if (isset($ModulesConfig[$modules])) {
                 $moduleConfig = $ModulesConfig[$modules];
                 if ($is_remote) {
                     # 远程
                     # 把模块更新的session更新到redis上面,以供其他模块使用
                     session_commit();
                     $data = $this->getRemotePostData($modules, $moduleConfig, $file, $function, $req_data, $timeout = 20);
                 } else {
                     # 本地
                     $file = str_replace("/", "\\", $file);
                     $function_exec = $moduleConfig['moduleDir'] . "\\o\\" . $file;
                     $function_exec .= "::" . $function;
                     $data = \call_user_func_array($function_exec, $req_data);
                     $data = CFunc::object_to_array(json_decode($data));
                 }
             } else {
                 $message = "!! Get Data From Local Module <{$modules}> Error: Module is not config in Profile.";
                 throw new \yii\web\HttpException(406, $message);
             }
         } else {
             $message = "!! Get Data From Local Module <{$modules}> Error: param:obj_data must is array and count >= 3.";
             throw new \yii\web\HttpException(406, $message);
         }
     } else {
         $message = "!! Get Data From Local Module <{$modules}> Error: param:obj_data is Empty OR is not Array .";
         throw new \yii\web\HttpException(406, $message);
     }
     return $data;
 }
Example #23
0
 public static function shutdown_handler()
 {
     if (is_array($_SESSION) && count($_SESSION) > 0) {
         if (!self::$sessionStarted) {
             // the _SESSION superglobal gets overwritten by session_start
             // so we save the contents in a temp var
             $tmp = $_SESSION;
             session_start();
             $_SESSION = $tmp;
             self::$sessionStarted = true;
             echo "starting new session ...<br>";
         } else {
             echo "starting existing session ...<br>";
         }
         session_commit();
         echo '$_SESSION not empty, commit session (' . session_id() . ')<br>';
         var_dump($_SESSION);
     } else {
         self::clearSession();
     }
 }
Example #24
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();
}
Example #25
0
function putSession($data)
{
    session_commit();
    ini_set("session.use_cookies", "0");
    if (session_start()) {
        $_SESSION = $data;
        session_commit();
    }
}
 function ForceDisconnect()
 {
     // Set session message to disconnect, and allow other servers to die.
     $this->Disconnect();
     session_commit();
     sleep(2);
     session_start();
     unset($_SESSION[IrcClientManager::$SessionName]);
 }
                        <table width="100%" border="0" cellpadding="6" cellspacing="0" summary="main area">
                                <tr>
<?php 
if (!session_id()) {
    session_start();
}
?>
                                        <td colspan="2" valign="top" class="listtopic"><?php 
echo $_SESSION['Username'];
?>
's <?php 
echo gettext("Password");
?>
</td>
<?php 
session_commit();
?>
                                </tr>
                                <tr>
                                        <td width="22%" valign="top" class="vncell" rowspan="2"><?php 
echo gettext("Password");
?>
</td>
                                        <td width="78%" class="vtable">
                                                <input name="passwordfld1" type="password" class="formfld pwd" id="passwordfld1" size="20" />
                                        </td>
                                </tr>
                                <tr>
                                        <td width="78%" class="vtable">
                                                <input name="passwordfld2" type="password" class="formfld pwd" id="passwordfld2" size="20" />
                                                &nbsp;<?php 
Example #28
0
 /**
  * Gets a MD5 challenge.
  *
  * @param array $parameters Parameters (not used)
  * @param \TYPO3\CMS\Core\Http\AjaxRequestHandler $parent The calling parent AJAX object
  * @return void
  */
 public function getChallenge(array $parameters, \TYPO3\CMS\Core\Http\AjaxRequestHandler $parent)
 {
     session_start();
     $_SESSION['login_challenge'] = md5(uniqid('', TRUE) . getmypid());
     session_commit();
     $parent->addContent('challenge', $_SESSION['login_challenge']);
     $parent->setContentFormat('json');
 }
Example #29
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();
}
function updVSTRule()
{
    // this is used for making throwing an invalid argument exception easier.
    function updVSTRule_get_named_param($name, $haystack, &$last_used_name)
    {
        $last_used_name = $name;
        return isset($haystack[$name]) ? $haystack[$name] : NULL;
    }
    global $port_role_options, $sic;
    $taglist = genericAssertion('taglist', 'array0');
    assertUIntArg('mutex_rev', TRUE);
    $data = genericAssertion('template_json', 'json');
    $rule_no = 0;
    try {
        $last_field = '';
        foreach ($data as $rule) {
            $rule_no++;
            if (!isInteger(updVSTRule_get_named_param('rule_no', $rule, $last_field)) or !isPCRE(updVSTRule_get_named_param('port_pcre', $rule, $last_field)) or NULL === updVSTRule_get_named_param('port_role', $rule, $last_field) or !array_key_exists(updVSTRule_get_named_param('port_role', $rule, $last_field), $port_role_options) or NULL === updVSTRule_get_named_param('wrt_vlans', $rule, $last_field) or !preg_match('/^[ 0-9\\-,]*$/', updVSTRule_get_named_param('wrt_vlans', $rule, $last_field)) or NULL === updVSTRule_get_named_param('description', $rule, $last_field)) {
                throw new InvalidRequestArgException($last_field, $rule[$last_field], "rule #{$rule_no}");
            }
        }
        commitUpdateVSTRules($_REQUEST['vst_id'], $_REQUEST['mutex_rev'], $data);
    } catch (Exception $e) {
        // Every case that is soft-processed in process.php, will have the working copy available for a retry.
        if ($e instanceof InvalidRequestArgException or $e instanceof RTDatabaseError) {
            startSession();
            $_SESSION['vst_edited'] = $data;
            session_commit();
        }
        throw $e;
    }
    rebuildTagChainForEntity('vst', $_REQUEST['vst_id'], buildTagChainFromIds($taglist), TRUE);
    showFuncMessage(__FUNCTION__, 'OK');
}