How can I get the the number of all logged webuser (or manager, but not all types together). Is it possible with ModX API? Or is it necessary to inspect the DB table modx_session - but how is "data" column to readable?
I want to show a user counter, who is online (like in a forum).
I will try to solve it myself. Kind of solution:
Write a plugin that track events and persist it in database or somewhere else: OnWebLogin and OnWebLogout. Then read the count of logged in users.
Created a db table "modx_weblogin_session" (manually) userid, timestamp.
Created a Plugin:
if (isset($modx) && isset($user)) {
$eventName = $modx->event->name;
$isBackend = ($modx->context->key == 'mgr') ? true : false;
$errorMsg = '';
$userId = $user->get('id');
$output = 'WebLoginCountSession-Plugin: ' . $eventName . ' user-id: ' . $userId;
$logout = function ($userId) {
global $modx;
//Custom Mysqli Class
if (MySQLiDB::isConnected()) {
$mysqli = MySQLiDB::getConnection();
if ($mysqli instanceof mysqli) {
try {
$sql = "DELETE FROM `modx_weblogin_session` WHERE userid = ?";
$prep_state = $mysqli->prepare($sql);
$prep_state->bind_param('i', $userId);
$prep_state->execute();
} catch (Exception $e) {
//$modx->log(modX::LOG_LEVEL_ERROR, ...)
}
}
}
};
$login = function ($userId) {
global $modx;
if (MySQLiDB::isConnected()) {
$mysqli = MySQLiDB::getConnection();
if ($mysqli instanceof mysqli) {
try {
$sql = "REPLACE INTO `modx_weblogin_session` (`userid`) VALUES (?)";
$prep_state = $mysqli->prepare($sql);
$prep_state->bind_param('i', $userId);
$prep_state->execute();
} catch (Exception $e) {
//$modx->log(modX::LOG_LEVEL_ERROR, ...)
}
}
}
};
if (!$isBackend && !empty($userId)) {
switch ($eventName) {
case ('OnWebLogin'):
$output .= ' - login';
$login($userId);
break;
case ('OnWebLogout'):
$output .= ' - logout';
$logout($userId);
break;
}
}
if ($debug === true) {
return $output . ' ' . $errorMsg;
}
}