Back to Access class

Method getAuthorisedViewLevels

public static array
getAuthorisedViewLevels
(mixed $userId)
Method to return a list of view levels for which the user is authorised.
Parameters
  • int $userId Id of the user for which to get the list of authorised view levels.
Returns
  • array List of view levels for which the user is authorised.
Since
  • 1.7.0
Class: Access
Project: Joomla

Method getAuthorisedViewLevels - Source code

/**
 * Method to return a list of view levels for which the user is authorised.
 *
 * @param   integer  $userId  Id of the user for which to get the list of authorised view levels.
 *
 * @return  array    List of view levels for which the user is authorised.
 *
 * @since   1.7.0
 */
public static function getAuthorisedViewLevels($userId)
{
    // Only load the view levels once.
    if (empty(self::$viewLevels)) {
        // Get a database object.
        $db = Factory::getDbo();
        // Build the base query.
        $query = $db->getQuery(true)->select($db->quoteName(['id', 'rules']))->from($db->quoteName('#__viewlevels'));
        // Set the query for execution.
        $db->setQuery($query);
        // Build the view levels array.
        foreach ($db->loadAssocList() as $level) {
            self::$viewLevels[$level['id']] = (array) json_decode($level['rules']);
        }
    }
    // Initialise the authorised array.
    $authorised = array(1);
    // Check for the recovery mode setting and return early.
    $user = User::getInstance($userId);
    $root_user = Factory::getApplication()->get('root_user');
    if ($user->username && $user->username == $root_user || is_numeric($root_user) && $user->id > 0 && $user->id == $root_user) {
        // Find the super user levels.
        foreach (self::$viewLevels as $level => $rule) {
            foreach ($rule as $id) {
                if ($id > 0 && self::checkGroup($id, 'core.admin')) {
                    $authorised[] = $level;
                    break;
                }
            }
        }
        return array_values(array_unique($authorised));
    }
    // Get all groups that the user is mapped to recursively.
    $groups = self::getGroupsByUser($userId);
    // Find the authorised levels.
    foreach (self::$viewLevels as $level => $rule) {
        foreach ($rule as $id) {
            if ($id < 0 && $id * -1 == $userId) {
                $authorised[] = $level;
                break;
            } elseif ($id >= 0 && \in_array($id, $groups)) {
                $authorised[] = $level;
                break;
            }
        }
    }
    return array_values(array_unique($authorised));
}