Unenrol user from course,
the last unenrolment removes all remaining roles.

@param stdClass $instance
@param int $userid
@return void
485771
public function unenrol_user(stdClass $instance, $userid) {
        global $CFG, $USER, $DB;
        require_once("$CFG->dirroot/group/lib.php");

        $name = $this->get_name();
        $courseid = $instance->courseid;

        if ($instance->enrol !== $name) {
            throw new coding_exception('invalid enrol instance!');
        }
        $context = context_course::instance($instance->courseid, MUST_EXIST);

        if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
            // weird, user not enrolled
            return;
        }

        // Remove all users groups linked to this enrolment instance.
        if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) {
            foreach ($gms as $gm) {
                groups_remove_member($gm->groupid, $gm->userid);
            }
        }

        role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
        $DB->delete_records('user_enrolments', array('id'=>$ue->id));

        // add extra info and trigger event
        $ue->courseid  = $courseid;
        $ue->enrol     = $name;

        $sql = "SELECT 'x'
                  FROM {user_enrolments} ue
                  JOIN {enrol} e ON (e.id = ue.enrolid)
                 WHERE ue.userid = :userid AND e.courseid = :courseid";
        if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
            $ue->lastenrol = false;

        } else {
            // the big cleanup IS necessary!
            require_once("$CFG->libdir/gradelib.php");

            // remove all remaining roles
            role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);

            //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
            groups_delete_group_members($courseid, $userid);

            grade_user_unenrol($courseid, $userid);

            $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));

            $ue->lastenrol = true; // means user not enrolled any more
        }
        // Trigger event.
        $event = \core\event\user_enrolment_deleted::create(
                array(
                    'courseid' => $courseid,
                    'context' => $context,
                    'relateduserid' => $ue->userid,
                    'objectid' => $ue->id,
                    'other' => array(
                        'userenrolment' => (array)$ue,
                        'enrol' => $name
                        )
                    )
                );
        $event->trigger();

        // User enrolments have changed, so mark user as dirty.
        mark_user_dirty($userid);

        // Check if courrse contacts cache needs to be cleared.
        core_course_category::user_enrolment_changed($courseid, $ue->userid, ENROL_USER_SUSPENDED);

        // reset current user enrolment caching
        if ($userid == $USER->id) {
            if (isset($USER->enrol['enrolled'][$courseid])) {
                unset($USER->enrol['enrolled'][$courseid]);
            }
            if (isset($USER->enrol['tempguest'][$courseid])) {
                unset($USER->enrol['tempguest'][$courseid]);
                remove_temp_course_roles($context);
            }
        }
    }
1292944
public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
        global $DB;

        if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_UNENROL) {
            // Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers.
            return;
        }
        if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
            $this->enrol_user($instance, $userid, null, 0, 0, ENROL_USER_SUSPENDED);
        }
    }
445550
public function unassign($role, UserInterface $user)
    {
        $roles = is_array($role) ? $role : [ $role ];

        $count = 0;

        foreach ($roles as $singleRole) {
            $count += $this->unassignSingleRole($singleRole, $user) ? 1 : 0;
        }

        if ($count !== count($roles)) {
            // @codeCoverageIgnoreStart
            return false;
            // @codeCoverageIgnoreEnd
        }

        $this->fireUserPermissionChangeEvent($user);
        return true;
    }
118585
public function ungrantFrom($user): void
    {
        $userModel = config('auth.providers.users.model');

        if (is_int($user) && !$userModel::find($user)) {
            return;
        }

        $this->users()->detach($user);
    }
279514
public function revoke($role, $userId) {
		$userId = $this->getId($userId);
		$entity = \App::$domain->account->login->oneById($userId);
		$this->model->deleteAll(['user_id' => $userId, 'item_name' => $role]);
	}
861513
public static function delete_instance($contextlevel, $instanceid) {
        global $DB;

        // double check the context still exists
        if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
            $context = context::create_instance_from_record($record);
            $context->delete();
        } else {
            // we should try to purge the cache anyway
        }
    }
83140
public function deleteReview($userId, $reviewId)
    {
        $review = $this->getReviewById($reviewId);

        $this->validateUserPermissionsToManageReview($review, $userId);

        $review->delete();
    }
1024728
public function delete(Group $group, $userId = null)
    {
        $this->dispatch($group, 'preDelete', [], $userId);

        $this->database->delete('ucms_group')->condition('id', $group->getId())->execute();

        $this->dispatch($group, 'delete', [], $userId);
    }
496445
public static function clearDeletedInstances() {
		if( !isset(static::$instances[static::getClass()]) ) {
			return;
		}
		$instances = &static::$instances[static::getClass()];
		foreach( $instances as $id => $obj ) {
			/* @var static $obj */
			if( $obj->isDeleted() ) {
				unset($instances[$id]);
			}
		}
	}
55420
protected static function delete_user_data(int $userid) {
        global $DB;
        // Delete this user's subscriptions first.
        subscription_manager::delete_user_subscriptions($userid);
        // Because we only use user contexts the instance ID is the user ID.
        // Get the rules and check if this user has the capability to delete them.
        $rules = $DB->get_records('tool_monitor_rules', ['userid' => $userid]);
        foreach ($rules as $ruledata) {
            $rule = rule_manager::get_rule($ruledata);
            // If no-one is suscribed to the rule then it is safe to delete.
            if ($rule->can_manage_rule($userid) && subscription_manager::count_rule_subscriptions($rule->id) == 0) {
                $rule->delete_rule();
            }
        }
    }
691319
protected static function delete_user_data(int $userid, \context $context) {
        global $DB;

        // Delete password history.
        $DB->delete_records('user_password_history', ['userid' => $userid]);
        // Delete last access.
        $DB->delete_records('user_lastaccess', ['userid' => $userid]);
        // Delete password resets.
        $DB->delete_records('user_password_resets', ['userid' => $userid]);
        // Delete user devices.
        $DB->delete_records('user_devices', ['userid' => $userid]);
        // Delete user course requests.
        $DB->delete_records('course_request', ['requester' => $userid]);
        // Delete sessions.
        $DB->delete_records('sessions', ['userid' => $userid]);
        // Do I delete user preferences? Seems like the right place to do it.
        $DB->delete_records('user_preferences', ['userid' => $userid]);

        // Delete all of the files for this user.
        $fs = get_file_storage();
        $fs->delete_area_files($context->id, 'user');

        // For the user record itself we only want to remove unnecessary data. We still need the core data to keep as a record
        // that we actually did follow the request to be forgotten.
        $user = \core_user::get_user($userid);
        // Update fields we wish to change to nothing.
        $user->deleted = 1;
        $user->idnumber = '';
        $user->emailstop = 0;
        $user->icq = '';
        $user->skype = '';
        $user->yahoo = '';
        $user->aim = '';
        $user->msn = '';
        $user->phone1 = '';
        $user->phone2 = '';
        $user->institution = '';
        $user->department = '';
        $user->address = '';
        $user->city = '';
        $user->country = '';
        $user->lang = '';
        $user->calendartype = '';
        $user->theme = '';
        $user->timezone = '';
        $user->firstaccess = 0;
        $user->lastaccess = 0;
        $user->lastlogin = 0;
        $user->currentlogin = 0;
        $user->lastip = 0;
        $user->secret = '';
        $user->picture = '';
        $user->url = '';
        $user->description = '';
        $user->descriptionformat = 0;
        $user->mailformat = 0;
        $user->maildigest = 0;
        $user->maildisplay = 0;
        $user->autosubscribe = 0;
        $user->trackforums = 0;
        $user->timecreated = 0;
        $user->timemodified = 0;
        $user->trustbitmask = 0;
        $user->imagealt = '';
        $user->lastnamephonetic = '';
        $user->firstnamephonetic = '';
        $user->middlename = '';
        $user->alternatename = '';
        $DB->update_record('user', $user);
    }
329641
public function remove_submission($userid) {
        global $USER;

        if (!$this->can_edit_submission($userid, $USER->id)) {
            print_error('nopermission');
        }

        if ($this->get_instance()->teamsubmission) {
            $submission = $this->get_group_submission($userid, 0, false);
        } else {
            $submission = $this->get_user_submission($userid, false);
        }

        if (!$submission) {
            return false;
        }

        // Tell each submission plugin we were saved with no data.
        $plugins = $this->get_submission_plugins();
        foreach ($plugins as $plugin) {
            if ($plugin->is_enabled() && $plugin->is_visible()) {
                $plugin->remove($submission);
            }
        }

        if ($submission->userid != 0) {
            \mod_assign\event\submission_status_updated::create_from_submission($this, $submission)->trigger();
        }
        return true;
    }
788318
public function deleteUser($userId)
    {
        $user = $this->userService->loadUser($userId);

        if ($user->id == $this->repository->getCurrentUser()->id) {
            throw new Exceptions\ForbiddenException('Currently authenticated user cannot be deleted');
        }

        $this->userService->deleteUser($user);

        return new Values\NoContent();
    }
1078247
public void clearCredential(String userId) throws AuthException {
        try {
            authorizationCodeFlow.getCredentialDataStore().delete(userId);
        } catch (IOException e) {
            throw new AuthException("Unable to clear credential.", e);
        }
    }
868929
public function revokeRole($role, $user_id)
    {
        $user = \App\User::findorfail($user_id);

        $user->removeRole(str_slug($role, ' '));

        return redirect('scaffold-users/edit/'.$user_id);
    }
720111
protected static function sync_course_instances($courseid, $userid) {
        global $DB;

        static $preventrecursion = false;

        // does anything want to sync with this parent?
        if (!$enrols = $DB->get_records('enrol', array('customint1'=>$courseid, 'enrol'=>'meta'), 'id ASC')) {
            return;
        }

        if ($preventrecursion) {
            return;
        }

        $preventrecursion = true;

        try {
            foreach ($enrols as $enrol) {
                self::sync_with_parent_course($enrol, $userid);
            }
        } catch (Exception $e) {
            $preventrecursion = false;
            throw $e;
        }

        $preventrecursion = false;
    }
638126
public function unassignAllRoles($userId)
    {
        $user = $this->model->find($userId);
        $user->roles()->detach();
    }