Create a user and assign roles to it.

@param array $data
@param array $users
1546
public function createWithUsers(array $data, $users)
    {
        $role = $this->create((array) $data);

        if (! empty($users)) {
            $role->users()->attach($users);
        }
    }
499089
public static function setUserdata($data = '', $value = NULL)
    {
        if (is_array($data)) {
            foreach ($data as $key => &$value) {
                $_SESSION[$key] = $value;
            }

            return;
        }

        $_SESSION[$data] = $value;
    }
1374929
public function createUser()
    {
        $data['name']     = $this->ask('Administrator name');
        $data['email']    = $this->ask('Administrator email');
        $data['password'] = bcrypt($this->secret('Administrator password'));
        $data['role_id']  = 1;
        User::create($data);
        $this->info('User has been created');
    }
304311
protected function create(array $data)
    {
        $user = UserModel::create($data);
        return User::find($user->id);
    }
445506
public function createUser($user, $roles = [])
    {
        // Create the new user
        $password = [
            'password' => bcrypt(Str::random(10)),
        ];

        $user = array_merge($password, $user);
        $user = $this->user->create($user);

        if (! $user) {
            return $user;
        }

        // Fire the creating event.
        event(new UserCreating($user));

        // Add the extra details needed to finish them.
        // Add the user details.
        $this->userDetails->create($this->getUserDetailsFromRequest($user));

        // Assign the user to the default group
        if (is_array($roles) || $roles instanceof Collection) {
            $user->syncRoles($roles);
        }

        // the user should always have the default role.
        if (empty($roles) || $roles === '') {
            $user->assignRole(config('jumpgate.users.default_role'));
        }

        // If we do not require activation, set the user as active.
        if (! config('jumpgate.users.require_email_activation')) {
            $user->updateActivationDetails();
        }

        // New user needs to set their password.
        $user->generateNewUserPasswordResetToken();

        // Fire the created event.
        event(new UserCreated($user));

        return $user;
    }
1003981
public static function userAuthorize(array $data) {
		$_SESSION['numbers']['user'] = $data;
		// flag as authorized
		$_SESSION['numbers']['flag_authorized'] = true;
		// add authorized role
		$roles = \Object\ACL\Resources::getStatic('user_roles', 'authorized', 'data');
		self::roleGrant($roles);
	}
1296036
protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'token' => $this->userRepository->createToken(),
            'active' => 1,
        ]);
    }
493596
public function createUser($username, $password, array $data = [])
    {
        /** @var UserInterface|EloquentUser $user */
        $user = $this->sentinel->registerAndActivate([
            'email'    => $username,
            'password' => $password,
        ]);

        if ( ! $user) {
            // @codeCoverageIgnoreStart
            throw new \Exception("Failed to create user '{$username}'");
            // @codeCoverageIgnoreEnd
        }

        $user->update($data);

        return $user;
    }
1105230
public function createUser(array $data)
    {
        $result = $this->httpRaw(self::WECHAT_USER_CREATE_PREFIX, $data, [
            'access_token' => $this->getAccessToken()
        ]);
        return isset($result['errcode']) && !$result['errcode'];
    }
221207
public static function create_users($users) {
        global $CFG, $DB;
        require_once($CFG->dirroot."/lib/weblib.php");
        require_once($CFG->dirroot."/user/lib.php");
        require_once($CFG->dirroot."/user/editlib.php");
        require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.

        // Ensure the current user is allowed to run this function.
        $context = context_system::instance();
        self::validate_context($context);
        require_capability('moodle/user:create', $context);

        // 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::create_users_parameters(), array('users' => $users));

        $availableauths  = core_component::get_plugin_list('auth');
        unset($availableauths['mnet']);       // These would need mnethostid too.
        unset($availableauths['webservice']); // We do not want new webservice users for now.

        $availablethemes = core_component::get_plugin_list('theme');
        $availablelangs  = get_string_manager()->get_list_of_translations();

        $transaction = $DB->start_delegated_transaction();

        $userids = array();
        foreach ($params['users'] as $user) {
            // Make sure that the username, firstname and lastname are not blank.
            foreach (array('username', 'firstname', 'lastname') as $fieldname) {
                if (trim($user[$fieldname]) === '') {
                    throw new invalid_parameter_exception('The field '.$fieldname.' cannot be blank');
                }
            }

            // Make sure that the username doesn't already exist.
            if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
                throw new invalid_parameter_exception('Username already exists: '.$user['username']);
            }

            // Make sure auth is valid.
            if (empty($availableauths[$user['auth']])) {
                throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
            }

            // Make sure lang is valid.
            if (empty($availablelangs[$user['lang']])) {
                throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
            }

            // Make sure lang is valid.
            if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
                                                                                     // so no default value
                                                                                     // We need to test if the client sent it
                                                                                     // => !empty($user['theme']).
                throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
            }

            // Make sure we have a password or have to create one.
            $authplugin = get_auth_plugin($user['auth']);
            if ($authplugin->is_internal() && empty($user['password']) && empty($user['createpassword'])) {
                throw new invalid_parameter_exception('Invalid password: you must provide a password, or set createpassword.');
            }

            $user['confirmed'] = true;
            $user['mnethostid'] = $CFG->mnet_localhost_id;

            // Start of user info validation.
            // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
            if (!validate_email($user['email'])) {
                throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
            } else if (empty($CFG->allowaccountssameemail)) {
                // Make a case-insensitive query for the given email address.
                $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid';
                $params = array(
                    'email' => $user['email'],
                    'mnethostid' => $user['mnethostid']
                );
                // If there are other user(s) that already have the same email, throw an error.
                if ($DB->record_exists_select('user', $select, $params)) {
                    throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
                }
            }
            // End of user info validation.

            $createpassword = !empty($user['createpassword']);
            unset($user['createpassword']);
            $updatepassword = false;
            if ($authplugin->is_internal()) {
                if ($createpassword) {
                    $user['password'] = '';
                } else {
                    $updatepassword = true;
                }
            } else {
                $user['password'] = AUTH_PASSWORD_NOT_CACHED;
            }

            // Create the user data now!
            $user['id'] = user_create_user($user, $updatepassword, false);

            $userobject = (object)$user;

            // Set user interests.
            if (!empty($user['interests'])) {
                $trimmedinterests = array_map('trim', explode(',', $user['interests']));
                $interests = array_filter($trimmedinterests, function($value) {
                    return !empty($value);
                });
                useredit_update_interests($userobject, $interests);
            }

            // Custom fields.
            if (!empty($user['customfields'])) {
                foreach ($user['customfields'] as $customfield) {
                    // Profile_save_data() saves profile file it's expecting a user with the correct id,
                    // and custom field to be named profile_field_"shortname".
                    $user["profile_field_".$customfield['type']] = $customfield['value'];
                }
                profile_save_data((object) $user);
            }

            if ($createpassword) {
                setnew_password_and_mail($userobject);
                unset_user_preference('create_password', $userobject);
                set_user_preference('auth_forcepasswordchange', 1, $userobject);
            }

            // Trigger event.
            \core\event\user_created::create_from_userid($user['id'])->trigger();

            // Preferences.
            if (!empty($user['preferences'])) {
                $userpref = (object)$user;
                foreach ($user['preferences'] as $preference) {
                    $userpref->{'preference_'.$preference['type']} = $preference['value'];
                }
                useredit_update_user_preference($userpref);
            }

            $userids[] = array('id' => $user['id'], 'username' => $user['username']);
        }

        $transaction->allow_commit();

        return $userids;
    }
974128
public function create($data)
	{
		$this->getResponse()
			->setStatusCode(Response::STATUS_CODE_201);
		
		$request = $this->getRequest();
		$content = $request->getContent();
		$content = !empty($content) ? Json::decode($content, Json::TYPE_ARRAY) : array();
		$post = array_merge_recursive(
			$request->getPost()->toArray(),
			$content
		);
		
		// Inject user data if connected checking if it is not the admin
		// write better this part, peraphs in some service or using doctrine
		$main = $this->getServiceLocator()->get('neobazaar.service.main');
		$userRepository = $main->getUserEntityRepository();
		if($this->zfcUserAuthentication()->hasIdentity()) {
			$identity = $this->zfcUserAuthentication()->getIdentity();
			$userModel = new UserModel($identity, $this->getServiceLocator());
			$classifiedId = 
				isset($post['document']) && isset($post['document']['id']) ? 
				$post['document']['id'] : 
				null;
			
			// Set identity values in any case!!
			$post['user'] = array (
				'email' => $identity->getEmail(),
				'name' => $identity->getName(),
				'id' => $userRepository->getEncryptedId($identity->getUserId())
			);
			
			// admin that want to edit other user classified, 
			// set the correct user to the data.
			if($userModel->isAdmin && null !== $classifiedId) {
				// must check if the classified owner is the admin
				$documentRepository = $main->getDocumentEntityRepository();
				$classified = $documentRepository->findByEncryptedId($classifiedId, 'documentId'); 
				if(null !== $classified) {
					if($classified->getUser()->getUserId() == $identity->getUserId()) {
						$name = $identity->getName();
						$post['user'] = array(
							'email' => $identity->getEmail(),
							'name' => strlen($name) > 2 ? $name : 'xx',
							'id' => $userRepository->getEncryptedId($identity->getUserId())
						);
					} else {
						$user = $userRepository->find($classified->getUser()->getUserId());
						$name = $user->getName();
						$post['user'] = array(
							'email' => $user->getEmail(),
							'name' => strlen($name) > 2 ? $name : 'xx',
							'id' => $userRepository->getEncryptedId($user->getUserId())
						);
					}
				}
			}
		}
		
		try {
			$classifiedService = $this->getServiceLocator()->get('document.service.classified');
			$document = $classifiedService->save($post);
			$data = array(
				'status' => 'success',
				'message' => $document->getDocumentId()
			);
		} catch(\Exception $e) {
			$this->getResponse()
				->setStatusCode(Response::STATUS_CODE_500);
			$data = @unserialize($e->getMessage());
			
			if(!is_array($data)) {
				$data = array(
					'status' => 'danger',
					'message' => $e->getMessage()
				);
			}
		}
		
		return new JsonModel($data);
	}
204287
public function setLoginData(array $data)
    {
        $data = Helpers::parseLoginData($data);
        $this->getUser()->setLoginData($data[User::ID_LOGIN], $data[User::ID_ROLE], $data[User::ID_UNIT], $data[User::LOGOUT_DATE]);
    }
863426
public function set_users(array $users) {
        $this->users = $users;
        $hasbulkops = !empty($this->bulkoperations);
        foreach ($users as $userid=>$user) {
            $user = (array)$user;
            $row = new html_table_row();
            $row->attributes = array('class' => 'userinforow');
            $row->id = 'user_'.$userid;
            $row->cells = array();
            if ($hasbulkops) {
                // Add a checkbox into the first column.
                $input = html_writer::empty_tag('input', array('type' => 'checkbox', 'name' => 'bulkuser[]', 'value' => $userid));
                $row->cells[] = new html_table_cell($input);
            }
            foreach ($this->fields as $field => $label) {
                if (is_array($label)) {
                    $bits = array();
                    foreach (array_keys($label) as $subfield) {
                        if (array_key_exists($subfield, $user)) {
                            $bits[] = html_writer::tag('div', $user[$subfield], array('class'=>'subfield subfield_'.$subfield));
                        }
                    }
                    if (empty($bits)) {
                        $bits[] = '&nbsp;';
                    }
                    $row->cells[] = new html_table_cell(join(' ', $bits));
                } else {
                    if (!array_key_exists($field, $user)) {
                        $user[$field] = '&nbsp;';
                    }
                    $row->cells[] = new html_table_cell($user[$field]);
                }
            }
            $this->data[] = $row;
        }
    }
1125649
public void setUsers(java.util.Collection<UserData> users) {
        if (users == null) {
            this.users = null;
            return;
        }

        this.users = new java.util.ArrayList<UserData>(users);
    }
1277269
public function find($username, array $data = [])
    {
        $response = $this->request->get(sprintf("users/%s", $username), $data);
        return new User($this->master, $response);
    }
1009795
public function createUserFromOAuth($data)
    {
        $user = $this->createUser();
        $user->setAuthDataByProvider($data['provider'], ['id' => $data['id'], 'token' => $data['token']]);
        $user->setAuthProvider($data['provider']);
        $user->setFirstAuthProvider($data['provider']);
        $user->setUsername($data['email']);
        $user->setEmail($data['email']);
        $user->setPassword('none');
        $user->setEnabled(true);
        $user->setContact(new Contact);

        return $user;
    }
338696
public function initializePermissions(array $nodes, array $roles)
    {
        $this->om->startFlushSuite();

        foreach ($nodes as $node) {
            foreach ($roles as $role) {
                $type = $node->getResourceType();
                $this->editPerms(
                    $type->getDefaultMask(),
                    $role,
                    $node,
                    false
                );
            }
        }

        $this->om->endFlushSuite();
    }