I want to get the status of the user on Drupal 8.

I want to get the status of the user on Drupal 8.

With the code below, if the user is online, the status is online. But if the user has been offline for more than an hour, the status is missing. Normally it should be offline.

What’s wrong with this code ?

Thank you

Here is what I added in the user.html.twig file :

<div class="bs-field-status">
{% if status == 'Online' %}
<i class="user-online fa fa-circle fa-lg"></i> Online
{% elseif status == 'Absent' %}
<i class="user-absent fa fa-circle fa-lg"></i> Absent
{% else %}
<i class="user-offline fa fa-circle fa-lg"></i> Offline
{% endif %}
</div>

bootstrap_sub.theme :

<?php
/**
* @file
* Bootstrap sub-theme.
*
* Place your custom PHP code in this file.
*/
 
use DrupalCoreDatabaseDatabase;
 
/**
* Implements hook_entity_presave().
*/
function bootstrap_sub_preprocess_user(&$variables) {
// get user object
$user = $variables['elements']['#user'];
//- The user has logged in at least once
if ($user->getLastLoginTime()) {
if (account_is_logged_in_less_then_thirty_minutes($user->id())) {
$status = 'Online';
}
else {
$status = 'Absent';
}
}
else {
$status = 'Offline';
}
$variables['status'] = $status;
}
 
/**
* @param $uid
*
* @return bool
*/
function account_is_logged_in_less_then_thirty_minutes($uid) {
$connection = Database::getConnection();
$query = $connection->select('sessions', 'sessions')
->fields('sessions', ['sid', 'uid', 'timestamp'])
->condition('sessions.uid', $uid, '=')
//- chef if the user was online in 30 minutes (60 * 30)
->condition('sessions.timestamp', Drupal::time()
->getRequestTime() - (60 * 30), '>')
->execute();
//- Get result.
$results = $query->fetchAll(PDO::FETCH_OBJ);
return (count($results) > 0) ? TRUE : FALSE;
}

Drupal version: 


Source: https://www.drupal.org/taxonomy/term/3/feed