Get user role in site

@param AccountInterface $account
@param Site $site

@return SiteAccessRecord|SiteAccessRecord[]
169158
private function getUserRoleCacheValue(AccountInterface $account, Site $site = null)
    {
        $userId = $account->id();

        if (!isset($this->accessCache[$userId])) {
            $r = $this
                ->db
                ->query(
                    "
                        SELECT
                            a.uid, a.site_id, a.role, s.state AS site_state,
                            u.name, u.mail, u.status
                        FROM {ucms_site_access} a
                        JOIN {users} u
                            ON u.uid = a.uid
                        JOIN {ucms_site} s
                            ON s.id = a.site_id
                        WHERE
                            a.uid = :userId
                    ",
                    [':userId' => $userId]
                )
            ;

            $r->setFetchMode(\PDO::FETCH_CLASS, SiteAccessRecord::class);

            // Can't use fetchAllAssoc() because properties are private on the
            // objects built by PDO
            $this->accessCache[$userId] = [];
            foreach ($r->fetchAll() as $record) {
                $this->accessCache[$userId][$record->getSiteId()] = $record;
            }
        }

        if (null !== $site) {
            if (!empty($this->accessCache[$userId][$site->id])) {
                return $this->accessCache[$userId][$site->id];
            } else {
                return Access::ROLE_NONE;
            }
        }

        return $this->accessCache[$userId];
    }
1027230
public function getStringRolesFromToken(TokenInterface $token)
    {
        $roles = array();

        foreach ($token->getRoles() as $role) {
            $roles[] = $role->getRole();
        }

        return $roles;
    }
982350
public function findNotInRole(RoleInterface $role)
    {
        $callback   =   function ($permission) use ($role) {
            return $role->hasnt($permission->key);
        };
        
        return array_filter($this->findAll(), $callback);
    }
1034796
public function countUsersWithRole(Site $site, $role = null)
    {
        /* @var $q \SelectQuery */
        $q = $this->db
            ->select('ucms_site_access', 'u')
            ->condition('u.site_id', $site->id);

        if ($role) {
            $q->condition('u.role', $role);
        }

        $q->addExpression('COUNT(*)');

        /* @var $r \PDOStatement */
        $r = $q->execute();

        return $r->fetchField();
    }
708003
protected static function ctxGetCurrentAccount(ContextInterface $context): AccountInterface
    {
        assert(static::ctxHasCurrentAccount($context));

        /** @var AccountManagerInterface $manager */
        $container = static::ctxGetContainer($context);
        $manager   = $container->get(AccountManagerInterface::class);
        $account   = $manager->getAccount();

        return $account;
    }
517360
static public function getRolesForSite($nb_site) : CNabuRoleList
    {
        $nb_site_id = nb_getMixedValue($nb_site, NABU_SITE_FIELD_ID);

        if (is_numeric($nb_site_id)) {
            $retval = self::buildObjectListFromSQL(
                'nb_role_id',
                'select r.* '
                . 'from nb_role r, nb_site_role sr, nb_site s '
               . 'where r.nb_role_id=sr.nb_role_id '
                 . 'and sr.nb_site_id=s.nb_site_id '
                 . 'and s.nb_site_id=%site_id$d',
                array(
                    'site_id' => $nb_site_id
                ),
                ($nb_site instanceof CNabuSite ? $nb_site : null)
            );
        } else {
            $retval = new CNabuRoleList();
        }

        return $retval;
    }
981395
private function getUserObjectPermissionByArray($permissions, UserInterface $user)
    {
        if (empty($permissions)) {
            return [];
        }

        $userPermission = [];
        $roles = $user->getRoleObjects();
        foreach ($roles as $role) {
            $roleId = $role->getId();
            if (!isset($permissions[$roleId])) {
                continue;
            }

            $userPermission = $this->cumulatePermissions($userPermission, $permissions[$roleId]);
        }

        return $userPermission;
    }
1097882
public function sitesManagedByMember($member = null)
    {
        $member = $member ?: Member::currentUser();
        if (!$member) return array();

        $sites = Site::get();

        if (Permission::check('ADMIN')) {
            return $sites->column('ID');
        }

        $memberGroups = $member->Groups()->column('ID');
        $sites        = $sites->filter("EditorGroups.ID:ExactMatch", $memberGroups);

        return $sites->column('ID');
    }
10828
protected function convertRole(RoleInterface $role)
    {
        $roleData['id'] = $role->getId();
        $roleData['name'] = $role->getName();
        $roleData['identifier'] = $role->getIdentifier();
        $roleData['system'] = $role->getSystem();
        $roleData['permissions'] = [];

        $permissions = $role->getPermissions();
        if (!empty($permissions)) {
            foreach ($permissions as $permission) {
                /* @var Permission $permission */
                $roleData['permissions'][] = [
                    'id' => $permission->getId(),
                    'context' => $permission->getContext(),
                    'module' => $permission->getModule(),
                    'permissions' => $this->get('sulu_security.mask_converter')
                        ->convertPermissionsToArray($permission->getPermissions()),
                ];
            }
        }

        $securityType = $role->getSecurityType();
        if ($securityType) {
            $roleData['securityType'] = [
                'id' => $securityType->getId(),
                'name' => $securityType->getName(),
            ];
        }

        return $roleData;
    }
189879
public function loadWebmasterSites(AccountInterface $account)
    {
        $roles = $this->getAccess()->getUserRoles($account);

        foreach ($roles as $grant) {
            if ($grant->getRole() !== Access::ROLE_WEBMASTER) {
                unset($roles[$grant->getSiteId()]);
            }
        }

        return $this->getStorage()->loadAll(array_keys($roles));
    }
627313
public function getAccounContact(AccountInterface $account, Contact $contact)
    {
        foreach ($contact->getAccountContacts() as $accountContact) {
            /** @var AccountContact $accountContact */
            if ($accountContact->getAccount() === $account) {
                return $accountContact;
            }
        }

        return;
    }
330548
public function roleFetchSubjectRoles(SubjectInterface $subject, $permissions = true)
    {
        $query = "
            SELECT
                role_id
            FROM
                auth_subject_role
            WHERE
                subject_id = :subject_id
        ";
        $roles = [];
        $cur = $this->db->prepare($query);
        $cur->bindValue(":subject_id", $subject->id(), PDO::PARAM_INT);
        try {
            $cur->execute();
            $res = $cur->fetchAll(PDO::FETCH_OBJ);
            if (!$res) {
                return [];
            } else {
                $role_ids = array_map(
                    function ($row) {
                        return $row->role_id;
                    },
                    $res
                );
                $roles = $this->roleFetchById($role_ids);
            }
        } catch (PDOException $db_err) {
            if ($this->logger) {
                $this->logger->error("Failed to fetch roles for subject", ['exception' => $db_err]);
            }
        }
        return $roles;
    }
248267
protected function blockAccess(AccountInterface $account) {
    // If tagging is off, deny access always.
    if (!$this->tagService->active()) {
      return AccessResult::forbidden();
    }

    $route_name = $this->routeMatch->getRouteName();

    if ($route_name == 'entity.node.canonical') {
      $node = $this->routeMatch->getParameter('node');

      if ($node instanceof Node) {
        if ($node->hasField('social_tagging')) {
          if (!empty(($node->get('social_tagging')->getValue()))) {
            // We only show the block if the field contains values.
            return AccessResult::allowed();
          }
        }
      }
    }

    return AccessResult::forbidden();
  }
883879
public function userCanCreateInAnySite(AccountInterface $account, $type)
    {
        // Check for global contribs
        if ($this->userCanCreate($account, $type)) {
            return true;
        }

        // Iterate over all sites, check if type creation is possible in context
        $sites = $this->manager->loadOwnSites($account);
        foreach ($sites as $site) {
            if ($this->userCanCreateInSite($account, $type, $site)) {
                return true;
            }
        }

        return false;
    }
1139485
public function userCanReference(AccountInterface $account, NodeInterface $node)
    {
        return $node->access(Permission::VIEW, $account) && $this->manager->getAccess()->userIsWebmaster($account);
    }
986257
public function getAssignedPartyOfAccount(Account $account)
    {
        $accountIdentifier = $this->persistenceManager->getIdentifierByObject($account);

        // We need to prevent stale object references and therefore only cache the identifier.
        if (!array_key_exists($accountIdentifier, $this->accountsInPartyRuntimeCache)) {
            $party = $this->partyRepository->findOneHavingAccount($account);
            $this->accountsInPartyRuntimeCache[$accountIdentifier] = $party === null ? null : $this->persistenceManager->getIdentifierByObject($party);

            return $party;
        }

        if ($this->accountsInPartyRuntimeCache[$accountIdentifier] !== null) {
            $partyIdentifier = $this->accountsInPartyRuntimeCache[$accountIdentifier];

            return $this->persistenceManager->getObjectByIdentifier($partyIdentifier, AbstractParty::class);
        }

        return null;
    }
271206
protected function getImpersonatingUserFromRole($token, $user = null)
    {
        foreach ($token->getRoles() as $role) {
            if ($role instanceof SwitchUserRole) {
                $user = $role->getSource()->getUser();
                break;
            }
        }

        return $user;
    }