0

The function _calcular_tiempo_usuario isn't called, and is not saving anything in the $_SESSION variable.

<?php
function proyecto_estadisticas_menu(){
  $items['admin/settings/proyecto_estadisticas/batchapi'] = array(
    'title' => t('Proceso batchapi para calcular tiempo medio en la página'),
    'page callback' => '_proyecto_estadisticas_tiempo',

    'access arguments' => array('administer site configuration'),
    'file'  => 'proyecto_estadisticas.batch.inc',
    'type'  => MENU_NORMAL_ITEM,  
  );
  return $items;
  }


//archivo de php para los procesos de batch.api
/**
 * Esta función es la que empieza montando todo el proceso de batch api.
 * 
 * name proyecto_comienzo_batch
 * 
 */
function proyecto(){

  //llamamos a la función de batch
  batch_set(_cargar_usuarios());

  batch_process('node');

  /
}

function _cargar_usuarios(){
  //$date = date('Y-m-d',strtotime('yesterday'));
  $date = '2011-09-12';
  $valoresfechas = _get_valores_fechas($date);
  $usuarios = array();
  //se ejecuta correctamente. se ha comprobado.
  $usuarios = _crear_array_usuarios_tiempos( $valoresfechas);

  $operations = array();
  foreach($usuarios as $key => $value){
    $operations[] = array('_calcular_tiempo_usuario', array($key, $value, $valoresfechas));
  }

  $batch = array(
    'operations' => $operations,
    'finished' => 'funcion_final',
    'title' => t('Calculando tiempo de usuarios'),
    'init_message' => t('Comienza el cálculo de tiempos.'),
  );
  return $batch; 
} 

/**
 *
 * Esta función es parte de la batch api que llama a todos los usuarios para recorrer el resultado y hacer el sumatorio.
 * _calcular_tiempo_usuario
 * 151 (Array, 8 elements)
 *   0 (String, 17 characters ) opened 1315836623
 *   1 (String, 17 characters ) closed 1315836924
 * 
 * name _calcular_tiempo_usuario
 * @param $usuario es un array con todos los resultados de opened y closed del usuario que se pasas
 * @return el resultado de la suma.
 * 
 */ 

function _calcular_tiempo_usuario($uid, $usuario, $valoresfechas, &$context){
  $_SESSION['metricas'][$uid] = $uid;
  //contamos la cantidad de elementos del array para los for.
  $cantidad = count($usuario);

  //Comprobamos cual es el primer elemento, opened or closed
  if(preg_match("/^opened/", $usuario[0])){
    $si = 0;
  }else {
    $si = 1; 
  }
  //si $si == 1, quiere decir que el array empiza con un cloused, y el segundo valor(1) es un opened.
  if($si == 1){
    //calculamos el primer valor que es un cloused
    $suma +=  str_replace('closed','',$usuario[0])- $valoresfechas['antes'] ;
    //recorremos el bucle para sacar todas las relaciones
    for($si; $si <= $cantidad; $si=$si+2){
      if($usuario[$si+1]){
        $suma += str_replace('closed','',$usuario[$si+1])-str_replace('opened','',$usuario[$si]);
      }
      if( !($usuario[$si+1]) && (preg_match("/^opened/", $usuario[$si])) ){
        //el ultimo registro, si es open, quiere decir que la sesión ha permanecido abierta all llegar a la media noche, por lo 
        //tanto el close es fecha hasta.
        $suma += $valoresfechas['despues'] -str_replace('opened','',$usuario[$si]);
      }
    }
  }
  //si $si== 0 es que la primera entrada es opened
  if($si == 0){
    //recorremos el bucle para sacar todas las relaciones
    for($si; $si <= $cantidad; $si=$si+2){
      if($usuario[$si+1]){
        $suma += str_replace('closed','',$usuario[$si+1])-str_replace('opened','',$usuario[$si]);
      }
      if( !($usuario[$si+1]) && (preg_match("/^opened/", $usuario[$si])) ){
        //el ultimo registro, si es open, quiere decir que la sesión ha permanecido abierta all llegar a la media noche, por lo 
        //tanto el close es fecha hasta.
        $suma += $valoresfechas['despues'] -str_replace('opened','',$usuario[$si]);
      }
    }
  }
    // Store some result for post-processing in the finished callback.
  $context['results'][] = $uid ;

  // Optional message displayed under the progressbar.
  $context['message'] = t('Loading @uid', array('@uid' => $uid));

  $context['results']['metricas'][$uid]= $suma;
}

/**
 * Batch 'finished' callback 
 */
function funcion_final($success, $results, $operations) {
  if ($success) {
    // Here we could do something meaningful with the results.
    // We just display the number of nodes we processed...
    $message = count($results) . ' processed.';
  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    $message = 'An error occurred while processing ' . $error_operation[0] . ' with arguments :' . print_r($error_operation[0], TRUE);
  }
  drupal_set_message($message);

}

/**
 * Esta función crea un gran array con todos los usuarios y sus registros 
 * de aperturas y cierres de sesión.
 * 
 * name: _crear_array_usuarios_tiempos
 * @param $valoresfechas
 * @return un array con todos los usuarios, menos administradores, y 
 * sus aperturas y cierras de sesión
 * 
 */ 

function _crear_array_usuarios_tiempos( $valoresfechas){

    $sql = db_query("
  SELECT DISTINCT(wid), type, message, uid, timestamp
        FROM watchdog
        WHERE type = 'user'
        AND timestamp > %d
        AND timestamp < %d     
        AND ( message like '%%Session opened for%%' OR message like '%%Session closed for%%')
        AND uid NOT IN (".db_placeholders(ADMINISTRADORES,'int').")
        ORDER BY timestamp ASC",
        $valoresfechas['antes'],
        $valoresfechas['despues'], ADMINISTRADORES  
        );
    while ($result = db_fetch_object($sql)){
      $usuarios[$result->uid][] = limpiar_mensaje($result->message). $result->timestamp;

    }

  return $usuarios;
}
?>
2
  • Oskar, could you please explain more what you expect this code to achieve?
    – LLub
    Sep 15, 2011 at 12:50
  • Are there any warnings , notifications or errors ?
    – LLub
    Sep 15, 2011 at 12:51

1 Answer 1

0

The reasong of why the _calcular_tiempo_usuario() is not being called or why the $_SESSION variable is not being saved is following:

On the hook_menu(), the callback function is _proyecto_estadisticas_tiempo, but is the proyecto() function which starts the batch process.

Sometimes when you work with batch API you don't see any errors, to confirm that, always check the admin/reports/dblog page.

I couldn't find where do you use the values that should be stored by the $_SESSION variable, but I suggest you to use:

  • $context['sandbox'][values you need to store] to store and use those values during batch process.

  • $context['results'][values you need to store] to use the values after batch process is finished.

You can check it at the Batch API docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.