Update users

@param array $users
@return null
@since Moodle 2.2
327655
public static function update_users($users) {
        global $CFG, $DB, $USER;
        require_once($CFG->dirroot."/user/lib.php");
        require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
        require_once($CFG->dirroot.'/user/editlib.php');

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

        $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));

        $filemanageroptions = array('maxbytes' => $CFG->maxbytes,
                'subdirs'        => 0,
                'maxfiles'       => 1,
                'accepted_types' => 'web_image');

        $transaction = $DB->start_delegated_transaction();

        foreach ($params['users'] as $user) {
            // First check the user exists.
            if (!$existinguser = core_user::get_user($user['id'])) {
                continue;
            }
            // Check if we are trying to update an admin.
            if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
                continue;
            }
            // Other checks (deleted, remote or guest users).
            if ($existinguser->deleted or is_mnet_remote_user($existinguser) or isguestuser($existinguser->id)) {
                continue;
            }
            // Check duplicated emails.
            if (isset($user['email']) && $user['email'] !== $existinguser->email) {
                if (!validate_email($user['email'])) {
                    continue;
                } else if (empty($CFG->allowaccountssameemail)) {
                    // Make a case-insensitive query for the given email address and make sure to exclude the user being updated.
                    $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid AND id <> :userid';
                    $params = array(
                        'email' => $user['email'],
                        'mnethostid' => $CFG->mnet_localhost_id,
                        'userid' => $user['id']
                    );
                    // Skip if there are other user(s) that already have the same email.
                    if ($DB->record_exists_select('user', $select, $params)) {
                        continue;
                    }
                }
            }

            user_update_user($user, true, false);

            $userobject = (object)$user;

            // Update user picture if it was specified for this user.
            if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
                $userobject->deletepicture = null;

                if ($user['userpicture'] == 0) {
                    $userobject->deletepicture = true;
                } else {
                    $userobject->imagefile = $user['userpicture'];
                }

                core_user::update_picture($userobject, $filemanageroptions);
            }

            // Update 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);
            }

            // Update user 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);
            }

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

            // Preferences.
            if (!empty($user['preferences'])) {
                $userpref = clone($existinguser);
                foreach ($user['preferences'] as $preference) {
                    $userpref->{'preference_'.$preference['type']} = $preference['value'];
                }
                useredit_update_user_preference($userpref);
            }
            if (isset($user['suspended']) and $user['suspended']) {
                \core\session\manager::kill_user_sessions($user['id']);
            }
        }

        $transaction->allow_commit();

        return null;
    }
834976
public function update($user, User $userToManage)
    {
        if ($userToManage->id == $user->id || $userToManage->superAdmin()) {
            return false;
        }

        $user = User::findOrFail($user->id);

        return $user->hasPermission('laralum::users.update') || $user->superAdmin();
    }
1256593
public function update(LoggedUserUpdate $request)
    {
        $user = Auth::user();
        $user->update($request->only(['name','email','password']));

        return $user;
    }
1332270
public function update(array $fields = []) {
        $query = new UpdateQuery($this->getTable());
        $query->fields(!empty($fields)? $fields : $this->getFields());
        $query->whereConditionGroup($this->getWhereConditionGroup());
        return $this->connection->exec($query);
    }
1259998
public function update_user($values, $username = null)
	{
		// if no username is given, fetch the current user's namd
		$username = $username ?: $this->user->username;

		// get the current user record
		$current_values = \Model\Auth_User::query()
			->select(\Config::get('ormauth.table_columns', array()))
			->where('username', '=', $username)
			->get_one();

		// and bail out if it doesn't exist
		if (empty($current_values))
		{
			throw new \SimpleUserUpdateException('Username not found', 4);
		}

		// validate the values passed and assume the update array
		$update = array();
		if (array_key_exists('username', $values))
		{
			throw new \SimpleUserUpdateException('Username cannot be changed.', 5);
		}
		if (array_key_exists('password', $values))
		{
			if (empty($values['old_password'])
				or $current_values->password != $this->hash_password(trim($values['old_password'])))
			{
				throw new \SimpleUserWrongPassword('Old password is invalid');
			}

			$password = trim(strval($values['password']));
			if ($password === '')
			{
				throw new \SimpleUserUpdateException('Password can\'t be empty.', 6);
			}
			$update['password'] = $this->hash_password($password);
			unset($values['password']);
		}
		if (array_key_exists('old_password', $values))
		{
			unset($values['old_password']);
		}
		if (array_key_exists('email', $values))
		{
			$email = filter_var(trim($values['email']), FILTER_VALIDATE_EMAIL);
			if ( ! $email)
			{
				throw new \SimpleUserUpdateException('Email address is not valid', 7);
			}

			$matches = \Model\Auth_User::query()
				->select(\Config::get('ormauth.table_columns', array()))
				->where('email', '=', $email)
				->where('id', '!=', $current_values->id)
				->get_one();

			if ($matches)
			{
				throw new \SimpleUserUpdateException('Email address is already in use', 11);
			}

			$update['email'] = $email;
			unset($values['email']);
		}
		// deal with some simpleauth compatibility
		if (array_key_exists('group', $values))
		{
			array_key_exists('group_id', $values) or $values['group_id'] = $values['group'];
			unset($values['group']);
		}
		if (array_key_exists('group_id', $values))
		{
			if (is_numeric($values['group_id']))
			{
				$update['group_id'] = (int) $values['group_id'];
			}
			unset($values['group_id']);
		}

		// load the updated values into the object
		$current_values->from_array($update);

		$updated = false;

		// any values remaining?
		if ( ! empty($values))
		{
			// set them as EAV values
			foreach ($values as $key => $value)
			{
				if ( ! isset($current_values->{$key}) or $current_values->{$key} != $value)
				{
					if ($value === null)
					{
						unset($current_values->{$key});
					}
					else
					{
						$current_values->{$key} = $value;
					}

					// mark we've updated something
					$updated = true;
				}
			}
		}

		// check if this has changed anything
		if ($updated or $updated = $current_values->is_changed())
		{
			// and only save if it did
			$current_values->save();
		}

		// return the updated status
		return $updated;
	}
728083
public function activateUsers(array $ids): void
	{
		if ($this->isAjax()) {
			$users = $this->orm->users->findById($ids);
			foreach ($users as $user) {
				$user->active = true;
				$this->orm->users->persist($user);
			}
			$this->orm->flush();
			$this['userList']->reload();
		} else {
			$this->terminate();
		}
	}
104877
public function update($vals, $userid = null)
	{
		$this->debug->groupCollapsed(__METHOD__);
		$return = array(
			'success'	=> true,
			'errorDesc'	=> '',
		);
		$vals = array_change_key_case($vals);
		$this->debug->log('vals', $vals);
		$vals_auth = array();
		$current_user = true;
		if (isset($userid) && $userid != $this->userid) {
			$current_user = false;
		} else {
			$userid = $this->userid;
		}
		foreach (array('username','password') as $k) {
			if (isset($vals[$k])) {
				$vals_auth[$k] = $vals[$k];
				unset($vals[$k]);
			}
		}
		if (!empty($vals)) {
			$noQuoteCols = array();
			foreach ($vals as $k => $v) {
				if (isset($this->cfg['userForeignKeys'][$k])) {
					$fka = $this->cfg['userForeignKeys'][$k];
					$k_new = $fka['userCol'];
					$v_new = Str::quickTemp('('.$fka['getValQuery'].')', array('value'=>$this->db->quoteValue($v)));
					unset($vals[$k]);
					$vals[$k_new] = $v_new;
					$noQuoteCols[] = $k_new;
				}
			}
			if (!empty($vals['lastactivity']) && preg_match('/\w+\(.*?\)/', $vals['lastactivity'])) {
				$noQuoteCols[] = 'lastactivity';
			}
			$this->debug->log('vals', $vals);
			$result = $this->db->rowMan('user', $vals, array('userid' => $userid), $noQuoteCols);
			if ($result === false) {
				$return['success'] = false;
				$return['errorDesc'] = $this->db->error;
				$this->debug->warn('errors', $this->db->errors);
				$this->debug->warn('error', $this->db->resource->error);
			} elseif ($current_user) {
				unset($vals['lastactivity']);	// we don't want to overwrite the current session's value
				$this->user = array_merge($this->user, $vals);
			}
		}
		if ($return['success'] && !empty($vals_auth)) {
			if (isset($vals_auth['password'])) {
				$vals_auth['password'] = $this->hashPassword($vals_auth['password']);
				$this->log('pwChange', $userid);
			}
			// try update first
			$result = $this->db->rowMan('user_auth', $vals_auth, array('userid' => $userid));
			$this->debug->log('result', $result);
			if ($result === 0) {
				// no rows affected -> try insert
				$vals_auth['userid'] = $userid;
				$result = $this->db->rowMan('user_auth', $vals_auth);
				$this->debug->log('result', $result);
			}
			if ($result === false) {
				$return['success'] = false;
				$return['errorDesc'] = $this->db->error;
			}
		}
		$this->debug->groupEnd();
		return $return;
	}
833582
public function postUpdateUser(User $user)
    {
        $userData = array_filter(Binput::only(['username', 'email', 'password', 'level']));

        try {
            $user->update($userData);
        } catch (ValidationException $e) {
            return cachet_redirect('dashboard.team.edit', [$user->id])
                ->withInput($userData)
                ->withTitle(sprintf('%s %s', trans('dashboard.notifications.whoops'), trans('dashboard.team.edit.failure')))
                ->withErrors($e->getMessageBag());
        }

        return cachet_redirect('dashboard.team.edit', [$user->id])
            ->withSuccess(sprintf('%s %s', trans('dashboard.notifications.awesome'), trans('dashboard.team.edit.success')));
    }
113071
public function update(array $themes) {
        foreach($themes as $themeId => $label) {
            $this->remove($themeId);
            $this->register($themeId, $label);
        }
        $this->logInfo('Item themes updated: ' . implode(',', array_keys($themes)));
        return true;
    }
1102963
public function updateAddress(array $data, $user)
    {
        $this->getEventManager()->trigger('updateInfo.pre', $this, array('user' => $user, 'data' => $data));

        $form  = $this->getServiceManager()->get('playgrounduser_address_form');
        $form->bind($user);
        $form->setData($data);

        $filter = $user->getInputFilter();
        $filter->remove('password');
        $filter->remove('passwordVerify');
        $filter->remove('dob');

        $form->setInputFilter($filter);

        if ($form->isValid()) {
            $user = $this->getUserMapper()->update($user);
            $this->getEventManager()->trigger('updateInfo.post', $this, array('user' => $user, 'data' => $data));

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

        return false;
    }
1153184
public function massUpdate(UsersRequest $request, User $users)
    {
        $this->authorize('otherUpdate', User::class);

        $data = $request->except('_token', 'updated_at', 'image', 'submit');
        $users = $users->whereIn('id', $data['users']);
        $messages = [];

        switch ($data['mass_action']) {
            case 'mass_activate':
                // if (! $users->update(['approve' => 1])) {
                //     $messages[] = '!mass_activate';
                // }
                break;
            case 'mass_lock':
                // if (! $users->update(['approve' => 0])) {
                //     $messages[] = '!mass_lock';
                // }
                break;
            case 'mass_delete':
                $usersTemp = $users->get();
                foreach ($usersTemp as $user) {
                    if (! $user->delete()) {
                        $messages[] = '!mass_delete';
                    }
                }
                break;
            case 'mass_delete_inactive':
                // if (! $users->update(['on_mainpage' => 1])) {
                //     $messages[] = '!mass_delete_inactive';
                // }
                break;
        }

        $message = empty($messages) ? 'msg.complete' : 'msg.complete_but_null';

        return $this->makeRedirect(true, 'admin.users.index', $message);
    }
46674
protected function update(array $values, array $wheres = [], array $place_holders = [], array $where_format = [], $table = ''){
        if( empty($table) ){
            extract($this->get_default_values($values, $table, $place_holders));
        }
        if( empty($where_format) && !empty($this->default_placeholder) ){
            foreach($wheres as $column => $valud){
                if( isset($this->default_placeholder[$column]) ){
                    $where_format[] = $this->default_placeholder[$column];
                }
            }
        }
        return $this->db->update($table, $values, $wheres, $place_holders, $where_format);
    }
587165
public function updateUser(array $data)
    {
        $result = $this->httpRaw(self::WECHAT_USER_UPDATE_PREFIX, $data, [
            'access_token' => $this->getAccessToken()
        ]);
        return isset($result['errcode']) && !$result['errcode'];
    }
793819
public function update($username, array $data) {
        $cond = array();
        unset($data[$this->params['id']]);
		unset($data[$this->params['password']]);

        if($this->params['token']) {
            unset($data[$this->params['token']]);
        }

        if($this->params['created']) {
            unset($data[$this->params['created']]);
        }

        if($this->params['last_login']) {
            unset($data[$this->params['last_login']]);
        }


        foreach($data as $k => $v) {
            $cond[] = sprintf("`%s` = %s", str_replace(array('\\',"\0" ,'`'), '', $k), $this->pdo->quote($v));
        }


        if(is_numeric($username)) {
            $key = 'id';
        }
        else {
            $key = 'username';
        }

        $query = sprintf(self::UPDATE_QUERY,
            $this->params['table'],
            implode(', ', $cond),
            $this->params[$key],
            $this->pdo->quote($username));

        $stmt = $this->pdo->query($query);

        if($stmt === FALSE) {
            throw new UserException(json_encode($this->pdo->errorInfo()));
        }

    }
945619
public function setVoters(array $voters): void
    {
        $this->voters = array_filter(
            $voters,
            static function (VisibilityVoterInterface $voter): bool {
                return true;
            }
        );
    }
213590
public function update(array $values)
	{
		$bindings = array_values(array_merge($values, $this->bindings));

		$sql = $this->grammar->compileUpdate($this, $values);

		return $this->connection->update($sql, $this->cleanBindings($bindings));
	}
541594
public function selfUpdate(array $properties)
  {
    $this->execute("clientupdate", $properties);

    foreach($properties as $ident => $value)
    {
      $this->whoamiSet($ident, $value);
    }
  }