Validate userids and return usernames

@param array $versionids int[] List of policy version ids to process.
@param array $userids
@param string $action accept|decline|revoke
@return array (userid=>username)
974031
protected function validate_and_get_users($versionids, $userids, $action) {
        global $DB;

        $usernames = [];
        list($sql, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
        $params['usercontextlevel'] = CONTEXT_USER;
        $users = $DB->get_records_sql("SELECT u.id, " . get_all_user_name_fields(true, 'u') . ", " .
                \context_helper::get_preload_record_columns_sql('ctx') .
            " FROM {user} u JOIN {context} ctx ON ctx.contextlevel=:usercontextlevel AND ctx.instanceid = u.id
            WHERE u.id " . $sql, $params);

        foreach ($userids as $userid) {
            if (!isset($users[$userid])) {
                throw new \dml_missing_record_exception('user', 'id=?', [$userid]);
            }
            $user = $users[$userid];
            if (isguestuser($user)) {
                throw new \moodle_exception('noguest');
            }
            \context_helper::preload_from_record($user);
            if ($action === 'revoke') {
                api::can_revoke_policies($versionids, $userid, true);
            } else if ($action === 'accept') {
                api::can_accept_policies($versionids, $userid, true);
            } else if ($action === 'decline') {
                api::can_decline_policies($versionids, $userid, true);
            }
            $usernames[$userid] = fullname($user);
        }
        return $usernames;
    }
852427
public static function actionFilename($action, $dirs = null, $useNamespaces = false)
    {
        $dirs = self::path($dirs ?: self::get('atomik.dirs.actions'));
        if (($filename = self::findFile("$action.php", $dirs, $useNamespaces)) === false) {
            return $useNamespaces ? false : self::findFile("$action/index.php", $dirs);
        }
        return $filename;
    }
1003158
public function listVersionsForUser($userId, $status = VersionInfo::STATUS_DRAFT)
    {
        $query = $this->queryBuilder->createVersionInfoFindQuery();
        $query->where(
            $query->expr->lAnd(
                $query->expr->eq(
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject_version'),
                    $query->bindValue($status, null, \PDO::PARAM_INT)
                ),
                $query->expr->eq(
                    $this->dbHandler->quoteColumn('creator_id', 'ezcontentobject_version'),
                    $query->bindValue($userId, null, \PDO::PARAM_INT)
                )
            )
        );

        return $this->listVersionsHelper($query);
    }
44539
private function getValidOwnerIds()
    {
        $userRepo = $this->repository->getEntityManager()->getRepository(Entity\Users::class);
        $query = $userRepo->createQueryBuilder()
            ->select('id')
            ->where('enabled = :enabled')
            ->setParameter('enabled', true)
        ;
        $userRecords = $query->execute()->fetchAll(\PDO::FETCH_COLUMN);

        return $userRecords;
    }
501014
public static function fetchUserCapabilities(string $userId): array
    {
        $entities = [];

        if (array_key_exists($userId, static::$userCapabilities)) {
            return static::$userCapabilities[$userId];
        }

        $table = TableRegistry::get('RolesCapabilities.Capabilities');
        Assert::isInstanceOf($table, CapabilitiesTable::class);

        $userGroups = $table->getUserGroups($userId);
        if (empty($userGroups)) {
            return $entities;
        }

        $userRoles = $table->getGroupsRoles($userGroups);
        if (empty($userRoles)) {
            return $entities;
        }

        static::$userCapabilities[$userId] = $table->getUserRolesEntities($userRoles);

        return static::$userCapabilities[$userId];
    }
799731
private function getModelIds(EnvironmentInterface $environment, Action $action, $submitAction)
    {
        $valueKey = \in_array($submitAction, ['edit', 'override']) ? 'properties' : 'models';
        $modelIds = (array) $environment->getInputProvider()->getValue($valueKey);

        if (!empty($modelIds)) {
            $modelIds = \array_map(
                function ($modelId) {
                    return ModelId::fromSerialized($modelId);
                },
                $modelIds
            );

            $event = new PrepareMultipleModelsActionEvent($environment, $action, $modelIds, $submitAction);
            $environment->getEventDispatcher()->dispatch($event::NAME, $event);

            $modelIds = $event->getModelIds();
        }

        return $modelIds;
    }
605122
public function batchUntagUsers($tagId, array $userIds = [], array $partyIds = [])
    {
        $params = [
            'tagid'     => $tagId,
            'userlist'  => $userIds,
            'partylist' => $partyIds,
        ];

        return $this->parseJSON('json', [self::API_MEMBER_BATCH_UNTAG, $params]);
    }
521767
public function listVersionsForUser($userId, $status = VersionInfo::STATUS_DRAFT)
    {
        try {
            return $this->innerGateway->listVersionsForUser($userId, $status);
        } catch (DBALException $e) {
            throw new RuntimeException('Database error', 0, $e);
        } catch (PDOException $e) {
            throw new RuntimeException('Database error', 0, $e);
        }
    }
556622
public function version($versionId, $reset = false)
    {
        $versions = $this->versions($reset);
        if (empty($versions[$versionId])) {
            return null;
        }

        return $versions[$versionId];
    }
28351
public function listRepositories($userId = null)
    {
        $parameters = [];
        if ($userId) {
            $parameters['user_id'] = $userId;
        }

        return $this->get('/installation/repositories', $parameters);
    }
173338
protected function getRules($action, $merge = null)
	{
		$method = 'get' . ucfirst($action) . 'Rules';

		if (method_exists($this, $method)) {
			$rules = $this->$method();
		} else {
			$rules = [];
		}

		if ($merge === null) {
			$merge = $this->merge;
		}

		if ($merge) {
			$rules = array_merge_recursive($this->getCommonRules(), $rules);
		}

		return $rules;
	}
1145195
public function getUserIDs($itemsToGet = 100, $offset = 0)
    {
        $this->createQuery();
        $userIDs = array();
        $r = parent::get($itemsToGet, intval($offset));
        foreach ($r as $row) {
            $userIDs[] = $row['uID'];
        }

        return $userIDs;
    }
1200273
public function resolveEmailsFromUserId(string $userId, int $mode)
    {
        $gmailUser = $this->getGmailDomain()->findGmailUserById($userId);

        if (!($gmailUser instanceof GmailUserInterface)) {
            return [];
        }

        switch ($mode) {
            case self::MODE_RESOLVE_PRIMARY_ONLY:
                return [$gmailUser->getPrimaryEmailAddress()];

            case self::MODE_RESOLVE_ALIASES_ONLY:
                return $gmailUser->getEmailAliases();

            case self::MODE_RESOLVE_PRIMARY_PLUS_ALIASES:
                return $gmailUser->getAllEmailAddresses();

            default:
                throw new \InvalidArgumentException();
        }
    }
488332
private function getSchemaVariationName($userData, $variations)
    {
        foreach ($variations as $variationName => $expressions) {
            $results = array_map(
                function ($expression) use ($userData) {
                    return $this->jmesRuntime->__invoke($expression, $userData);
                },
                $expressions
            );

            $results = array_unique($results);

            if (count($results) == 1 && $results[0] === true) {
                return $variationName;
            }
        }

        return null;
    }
354341
public function get_context_ids_for_author_ids(array $authorids) : array {
        $db = $this->get_db();
        [$insql, $params] = $db->get_in_or_equal($authorids);
        $sql = "SELECT instanceid, id FROM {context} WHERE contextlevel = ? AND instanceid {$insql}";
        $records = $db->get_records_sql($sql, array_merge([CONTEXT_USER], $params));
        return array_reduce($authorids, function($carry, $id) use ($records) {
            $carry[$id] = isset($records[$id]) ? (int) $records[$id]->id : null;
            return $carry;
        }, []);
    }
560343
public function get_user_ids($roleids) {

        // We need to index by ra.id as a user may have more than 1 $roles role.
        $records = get_role_users($roleids, $this->get_context(), true, 'ra.id, u.id AS userid, r.id AS roleid', 'ra.id ASC');

        // If a user have more than 1 $roles role array_combine will discard the duplicate.
        $callable = array($this, 'filter_user_id');
        $userids = array_values(array_map($callable, $records));
        return array_combine($userids, $userids);
    }
844294
protected function getReferencesValues($versionInfo, array $references, $step)
    {
        $refs = array();

        foreach ($references as $reference) {
            switch ($reference['attribute']) {
                case 'version_no':
                    $value = $versionInfo->versionNo;
                    break;
                case 'version_status':
                    $value = $this->versionStatusToHash($versionInfo->status);
                    break;
                default:
                    // NB: this will generate an error if the user tries to seta  ref to a field value
                    $value = reset(parent::getReferencesValues($versionInfo, array($references), $step));
            }

            $refs[$reference['identifier']] = $value;
        }

        return $refs;
    }