Assign users to assignment

@return array|mixed
162629
protected function assignUsersToAssignment()
    {
        $assignment = fp_env('ACACHA_FORGE_ASSIGNMENT');
        foreach ( $this->users as $user) {
            $uri = str_replace('{assignment}', $assignment, config('forge-publish.assign_user_to_assignment_uri'));
            $uri = str_replace('{user}', $user, $uri);
            $url = config('forge-publish.url') . $uri;
            try {
                $response = $this->http->post($url, [
                    'headers' => [
                        'X-Requested-With' => 'XMLHttpRequest',
                        'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
                    ]
                ]);
            } catch (\Exception $e) {
                if ($e->getResponse()->getStatusCode() == 422) {
                    $this->error('The user is already assigned');
                    return;
                }
                $this->error('And error occurs connecting to the api url: ' . $url);
                $this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase());
                return;
            }
        }
    }
262568
public function user()
    {
        $userClassName = Config::get('auth.model');
        if (is_null($userClassName)) {
            $userClassName = Config::get('auth.providers.users.model');
        }

        return $this->belongsTo($userClassName);
    }
644331
public function bindUserToOrganization()
    {
        $limit = 250;
        $offset = 0;
        $this->log('Add organizations to users...');
        $this->objectManager->startFlushSuite();
        $countUsers = $this->objectManager->count('ClarolineCoreBundle:User');
        $default = $this->organizationManager->getDefault();
        $i = 0;

        while ($offset < $countUsers) {
            $users = $this->userRepo->findBy([], null, $limit, $offset);

            /** @var User $user */
            foreach ($users as $user) {
                $this->log('Setting user administrated organization...');

                foreach ($user->getAdministratedOrganizations() as $organization) {
                    //I know this is weird but the setter is now in this method (it used to not exist)
                    $user->addAdministratedOrganization($organization);
                }

                if (0 === count($user->getOrganizations())) {
                    ++$i;
                    $this->log('Add default organization for user '.$user->getUsername());
                    $user->addOrganization($default);
                    $this->objectManager->persist($user);

                    if (0 === $i % 250) {
                        $this->log("Flushing... [UOW = {$this->objectManager->getUnitOfWork()->size()}]");
                        $this->objectManager->forceFlush();
                    }
                } else {
                    $this->log("Organization for user {$user->getUsername()} already exists");
                }
            }

            $this->log("Flushing... [UOW = {$this->objectManager->getUnitOfWork()->size()}]");
            $this->objectManager->forceFlush();
            $default = $this->organizationManager->getDefault();

            $offset += $limit;
        }

        $this->objectManager->endFlushSuite();
    }
591478
private function create_assignments() {
        // Set up generator.
        $assigngenerator = $this->generator->get_plugin_generator('mod_assign');

        // Create assignments.
        $number = self::$paramassignments[$this->size];
        $this->log('createassignments', $number, true);
        for ($i = 0; $i < $number; $i++) {
            $record = array('course' => $this->course);
            $options = array('section' => $this->get_target_section());
            $assigngenerator->create_instance($record, $options);
            $this->dot($i, $number);
        }

        $this->end_log();
    }
40786
public function getAssignments()
    {
        //build URI
        $strURI = Product::$baseProductUri . '/tasks/' . $this->getFileName() . '/assignments/';

        //sign URI
        $signedURI = Utils::sign($strURI);

        $responseStream = Utils::processCommand($signedURI, 'GET', '', '');

        $json = json_decode($responseStream);

        if ($json->Code == 200)
            return $json->Assignments->AssignmentItem;
        else
            return false;
    }
366876
public function process_assignment($data) {
        global $DB;

        $data = (object)$data;

        // Check roleid, userid are one of the mapped ones
        if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
            return;
        }
        if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
            return;
        }
        if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
            // Only assign roles to not deleted users
            return;
        }
        if (!$contextid = $this->task->get_contextid()) {
            return;
        }

        if (empty($data->component)) {
            // assign standard manual roles
            // TODO: role_assign() needs one userid param to be able to specify our restore userid
            role_assign($newroleid, $newuserid, $contextid);

        } else if ((strpos($data->component, 'enrol_') === 0)) {
            // Deal with enrolment roles - ignore the component and just find out the instance via new id,
            // it is possible that enrolment was restored using different plugin type.
            if (!isset($this->plugins)) {
                $this->plugins = enrol_get_plugins(true);
            }
            if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
                if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
                    if (isset($this->plugins[$instance->enrol])) {
                        $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
                    }
                }
            }

        } else {
            $data->roleid    = $newroleid;
            $data->userid    = $newuserid;
            $data->contextid = $contextid;
            $dir = core_component::get_component_directory($data->component);
            if ($dir and is_dir($dir)) {
                if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
                    return;
                }
            }
            // Bad luck, plugin could not restore the data, let's add normal membership.
            role_assign($data->roleid, $data->userid, $data->contextid);
            $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
            $this->log($message, backup::LOG_WARNING);
        }
    }
1284197
public static function assign_roles($assignments) {
        global $DB;

        // Do basic automatic PARAM checks on incoming data, using params description
        // If any problems are found then exceptions are thrown with helpful error messages
        $params = self::validate_parameters(self::assign_roles_parameters(), array('assignments'=>$assignments));

        $transaction = $DB->start_delegated_transaction();

        foreach ($params['assignments'] as $assignment) {
            // Ensure correct context level with a instance id or contextid is passed.
            $context = self::get_context_from_params($assignment);

            // Ensure the current user is allowed to run this function in the enrolment context.
            self::validate_context($context);
            require_capability('moodle/role:assign', $context);

            // throw an exception if user is not able to assign the role in this context
            $roles = get_assignable_roles($context, ROLENAME_SHORT);

            if (!array_key_exists($assignment['roleid'], $roles)) {
                throw new invalid_parameter_exception('Can not assign roleid='.$assignment['roleid'].' in contextid='.$assignment['contextid']);
            }

            role_assign($assignment['roleid'], $assignment['userid'], $context->id);
        }

        $transaction->allow_commit();
    }
696492
public function listAssignees(): array
    {
        return $this->getApi()->request($this->getApi()
                                             ->sprintf('/repos/:owner/:repo/assignees', $this->getIssues()->getOwner(),
                                                 $this->getIssues()->getRepo()));
    }
267745
protected function createAssignment()
    {
        $url = config('forge-publish.url') . config('forge-publish.store_assignment_uri');
        try {
            $response = $this->http->post($url, [
                'form_params' => [
                    'name' => $this->assignmentName,
                    'repository_uri' => $this->repository_uri,
                    'repository_type' => $this->repository_type,
                    'forge_site' => $this->forge_site,
                    'forge_server' => $this->forge_server
                ],
                'headers' => [
                    'X-Requested-With' => 'XMLHttpRequest',
                    'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
                ]
            ]);
        } catch (\Exception $e) {
            $this->error('And error occurs connecting to the api url: ' . $url);
            $this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase());
            return;
        }
        $assignment = json_decode((string) $response->getBody());
        $this->addValueToEnv('ACACHA_FORGE_ASSIGNMENT', $assignment->id);
        return $assignment;
    }
154765
public function admin()
    {
        $currentuser = $this->getUser();
        $users = $this->users()->getUsers();
        $sessions = $this->accessControl()->getActiveSessions();

        foreach ($users as $name => $user) {
            if (($key = array_search(Permissions::ROLE_EVERYONE, $user['roles'], true)) !== false) {
                unset($users[$name]['roles'][$key]);
            }
        }

        $context = [
            'currentuser' => $currentuser,
            'users'       => $users,
            'sessions'    => $sessions,
        ];

        return $this->render('@bolt/users/users.twig', $context);
    }
1028100
protected function assignGroup()
    {
        if (!$this->config()->get('grant_user_access')) {
            return;
        }

        $group = $this->getUserGroup();

        // Must check if the method exists or else an error occurs when changing page type
        if ($this->hasMethod('Editors')) {
            foreach ([$this->Editors(), $this->Writers(), $this->Contributors()] as $levels) {
                foreach ($levels as $user) {
                    if (!$user->inGroup($group)) {
                        $user->Groups()->add($group);
                    }
                }
            }
        }
    }
44728
public function users()
    {
        return $this
            ->belongsToMany(
                config('laravel-auth.users.model', User::class),
                $this->getPrefix().config('laravel-auth.role-user.table', 'permission_role')
            )
            ->using(Pivots\RoleUser::class)
            ->withTimestamps();
    }
479641
protected function users()
    {
        $rows   = \Antares\Modules\SampleModule\Model\ModuleRow::query()->groupBy('user_id')->with('user')->get();
        $return = ['' => trans('antares/users::messages.statuses.all')];
        foreach ($rows as $row) {
            $return[$row->user_id] = $row->user->fullname;
        }
        return $return;
    }
766372
private function get_target_user() {

        if (!$this->fixeddataset) {
            $userid = $this->userids[rand(1, self::$paramusers[$this->size])];
        } else if ($userid = current($this->userids)) {
            // Moving pointer to the next user.
            next($this->userids);
        } else {
            // Returning to the beginning if we reached the end.
            $userid = reset($this->userids);
        }

        return $userid;
    }
81886
private function loadAssignments($userId)
    {
        if (!isset($this->_assignments[$userId])) {
            $query = (new Query)
                ->select('item_name')
                ->from($this->assignmentTable)
                ->where(['user_id' => $userId]);

            $this->_assignments[$userId] = $query->column($this->db);
        }
    }
665051
public function assign()
    {
        $app = Strata::app();
        foreach ($app->getMiddlewares() as $middleware) {
            $this->attemptMultipleRegistrations($middleware->shellCommands);
        }
    }
1031602
protected function load()
	{
		$this->assignments = [];
		$assignments = DiscHelper::loadFromFile($this->assignmentFile);
		$assignmentsMtime = @filemtime($this->assignmentFile);
		
		foreach ($assignments as $userId => $roles) {
			foreach ($roles as $role) {
				$this->assignments[$userId][$role] = new Assignment([
					'userId' => $userId,
					'roleName' => $role,
					'createdAt' => $assignmentsMtime,
				]);
			}
		}
	}