S
S
Sergey Miller2021-01-27 12:43:25
MODX
Sergey Miller, 2021-01-27 12:43:25

Modx Revo api how to make online/offline status in user select?

//выборка
$query = $modx->newQuery('modUser');
$users = $modx->getCollection('modUser', $query);

// цикл по пользователям
foreach ($users as $user) {
$name = $user->get('username');
$uid = $user->get('id');
$isOnline = $modx->getLoginUserName(); //берет текущего пользователя (то есть админа)
if($isOnline){
$status= "Онлайн";
}
else{
$status= "Оффлайн";
}

...
echo '.$status.';
...


}


Tried, did not help:

$isOnline = $user-> isAuthenticated();
$isOnline = $user-> hasSessionContext('web');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Lunegov, 2021-01-27
@blackseabreathe

Sergey Miller , unfortunately there is no out-of-the-box solution in MODX to show whether a user is online. Since you want to do it through the API, and not with third-party add-ons (UsersOnline), you will have to try. First you need to define what "user online" means? After all, there may be different behaviors. The user opened a page on the site and walked away from the computer without closing the browser, or switched to another tab. Is he online? Or opened the page and immediately closed the browser, how to find out that it is no longer online. The simplest and probably the most common way is to store in the database the exact time the user last loaded any page and assume that if this happened recently (5 or 10 minutes ago), then the user is still active.
To do this, create a plugin, for exampleuserLastAction and connect the OnLoadWebDocument system event to it (the code is partly taken from Vasily Naumkin ):

<?php
switch ($modx->event->name) {
  case 'OnLoadWebDocument':
    // Сохраняем дату открытия любой страницы сайта, если пользователь авторизован
    if ($modx->user->isAuthenticated($modx->context->key)) {
      // Здесь мы работаем с текущим пользователем — у него профиль уже загружен
      $profile = $modx->user->Profile;
      // Сохраняем дату и время в поле факс (а зачем еще это поле?) профиля пользователя
      $profile->set('fax', date('Y-m-d H:i:s'));
      $profile->save();
    }
    break;
}

Now, when any page of the site is opened by any user, the exact time of this action, linked to the user profile, will be saved. It remains only when forming the list to check whether the user has performed an action on the site for a long time.
For example, I wrote the following userOnline snippet :
<?php
$output = '';
// Если есть ID пользователя
if ($input) {
    $userId = (int)$input;
    // Если в параметрах не установлено через какое количество секунд считать пользователя "офлайн", то берем 10 минут
    $idleTime = $options ? (int)$options : 600;
    // Получаем объект пользователя по ID
    $user = $modx->getObject('modUser', $userId);
    if (!empty($user)) { // Если пользователь существует, то...
        // Получаем его профиль
        $profile = $user->getOne('Profile');
        // Получаем время его последнего действия
        $userLastAction = $profile->get('fax');
        if (!empty($userLastAction)) {
            // Если есть время в базе, то проверяем меньше ли оно установленного нами времени признания пользователя активным
            if (date('U') - date('U', strtotime($userLastAction)) < $idleTime) {
                // Если да, будем выводить слово "online"
                $output = 'online';
            } else {
                // Если нет, то — время его последнего действия
                $output = $userLastAction;
            }
        }
    }
}
// Выводим результат
return $output;

You will have to rework it for yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question