Enrol a user in a course.

@param \stdclass $tool The tool object (retrieved using self::get_lti_tool() or self::get_lti_tools())
@param int $userid The user id
@return bool|string returns true if successful, else an error code
182852
public static function enrol_user($tool, $userid) {
        global $DB;

        // Check if the user enrolment exists.
        if (!$DB->record_exists('user_enrolments', array('enrolid' => $tool->enrolid, 'userid' => $userid))) {
            // Check if the maximum enrolled limit has been met.
            if ($tool->maxenrolled) {
                if ($DB->count_records('user_enrolments', array('enrolid' => $tool->enrolid)) >= $tool->maxenrolled) {
                    return self::ENROLMENT_MAX_ENROLLED;
                }
            }
            // Check if the enrolment has not started.
            if ($tool->enrolstartdate && time() < $tool->enrolstartdate) {
                return self::ENROLMENT_NOT_STARTED;
            }
            // Check if the enrolment has finished.
            if ($tool->enrolenddate && time() > $tool->enrolenddate) {
                return self::ENROLMENT_FINISHED;
            }

            $timeend = 0;
            if ($tool->enrolperiod) {
                $timeend = time() + $tool->enrolperiod;
            }

            // Finally, enrol the user.
            $instance = new \stdClass();
            $instance->id = $tool->enrolid;
            $instance->courseid = $tool->courseid;
            $instance->enrol = 'lti';
            $instance->status = $tool->status;
            $ltienrol = enrol_get_plugin('lti');

            // Hack - need to do this to workaround DB caching hack. See MDL-53977.
            $timestart = intval(substr(time(), 0, 8) . '00') - 1;
            $ltienrol->enrol_user($instance, $userid, null, $timestart, $timeend);
        }

        return self::ENROLMENT_SUCCESSFUL;
    }
635565
public static function get_contexts_for_userid(int $userid) : contextlist {
        list($join, $where, $params) = \core_completion\privacy\provider::get_course_completion_join_sql($userid, 'cc', 'c.id');
        $sql = "SELECT ctx.id
                FROM {context} ctx
                JOIN {course} c ON ctx.instanceid = c.id AND ctx.contextlevel = :contextcourse
                {$join}
                WHERE {$where}";
        $params['contextcourse'] = CONTEXT_COURSE;
        $contextlist = new contextlist();
        $contextlist->add_from_sql($sql, $params);

        \core_favourites\privacy\provider::add_contexts_for_userid($contextlist, $userid, 'core_course', 'courses');

        return $contextlist;
    }
747663
public static function get_user_grade($lessonid, $userid = null) {
        global $CFG, $USER;
        require_once($CFG->libdir . '/gradelib.php');

        $params = array(
            'lessonid' => $lessonid,
            'userid' => $userid,
        );
        $params = self::validate_parameters(self::get_user_grade_parameters(), $params);
        $warnings = array();

        list($lesson, $course, $cm, $context, $lessonrecord) = self::validate_lesson($params['lessonid']);

        // Default value for userid.
        if (empty($params['userid'])) {
            $params['userid'] = $USER->id;
        }

        // Extra checks so only users with permissions can view other users attempts.
        if ($USER->id != $params['userid']) {
            self::check_can_view_user_data($params['userid'], $course, $cm, $context);
        }

        $grade = null;
        $formattedgrade = null;
        $grades = lesson_get_user_grades($lesson, $params['userid']);
        if (!empty($grades)) {
            $grade = $grades[$params['userid']]->rawgrade;
            $params = array(
                'itemtype' => 'mod',
                'itemmodule' => 'lesson',
                'iteminstance' => $lesson->id,
                'courseid' => $course->id,
                'itemnumber' => 0
            );
            $gradeitem = grade_item::fetch($params);
            $formattedgrade = grade_format_gradevalue($grade, $gradeitem);
        }

        $result = array();
        $result['grade'] = $grade;
        $result['formattedgrade'] = $formattedgrade;
        $result['warnings'] = $warnings;
        return $result;
    }
1013229
public function loadPoliciesByUserId($userId)
    {
        try {
            return $this->innerGateway->loadPoliciesByUserId($userId);
        } catch (DBALException $e) {
            throw new RuntimeException('Database error', 0, $e);
        } catch (PDOException $e) {
            throw new RuntimeException('Database error', 0, $e);
        }
    }
1280835
public static function create($quizid, $userid = null) {
        global $DB;

        $quiz = quiz_access_manager::load_quiz_and_settings($quizid);
        $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST);
        $cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id, false, MUST_EXIST);

        // Update quiz with override information.
        if ($userid) {
            $quiz = quiz_update_effective_access($quiz, $userid);
        }

        return new quiz($quiz, $cm, $course);
    }
456206
public static function get_users_courses($userid, $returnusercount = true) {
        global $CFG, $USER, $DB;

        require_once($CFG->dirroot . '/course/lib.php');
        require_once($CFG->libdir . '/completionlib.php');

        // 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::get_users_courses_parameters(),
                ['userid' => $userid, 'returnusercount' => $returnusercount]);
        $userid = $params['userid'];
        $returnusercount = $params['returnusercount'];

        $courses = enrol_get_users_courses($userid, true, '*');
        $result = array();

        // Get user data including last access to courses.
        $user = get_complete_user_data('id', $userid);
        $sameuser = $USER->id == $userid;

        // Retrieve favourited courses (starred).
        $favouritecourseids = array();
        if ($sameuser) {
            $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
            $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');

            if ($favourites) {
                $favouritecourseids = array_flip(array_map(
                    function($favourite) {
                        return $favourite->itemid;
                    }, $favourites));
            }
        }

        foreach ($courses as $course) {
            $context = context_course::instance($course->id, IGNORE_MISSING);
            try {
                self::validate_context($context);
            } catch (Exception $e) {
                // current user can not access this course, sorry we can not disclose who is enrolled in this course!
                continue;
            }

            if (!$sameuser and !course_can_view_participants($context)) {
                // we need capability to view participants
                continue;
            }

            if ($returnusercount) {
                list($enrolledsqlselect, $enrolledparams) = get_enrolled_sql($context);
                $enrolledsql = "SELECT COUNT('x') FROM ($enrolledsqlselect) enrolleduserids";
                $enrolledusercount = $DB->count_records_sql($enrolledsql, $enrolledparams);
            }

            $displayname = external_format_string(get_course_display_name_for_list($course), $context->id);
            list($course->summary, $course->summaryformat) =
                external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', null);
            $course->fullname = external_format_string($course->fullname, $context->id);
            $course->shortname = external_format_string($course->shortname, $context->id);

            $progress = null;
            $completed = null;
            $completionhascriteria = false;
            $completionusertracked = false;

            // Return only private information if the user should be able to see it.
            if ($sameuser || completion_can_view_data($userid, $course)) {
                if ($course->enablecompletion) {
                    $completion = new completion_info($course);
                    $completed = $completion->is_course_complete($userid);
                    $completionhascriteria = $completion->has_criteria();
                    $completionusertracked = $completion->is_tracked_user($userid);
                    $progress = \core_completion\progress::get_course_progress_percentage($course, $userid);
                }
            }

            $lastaccess = null;
            // Check if last access is a hidden field.
            $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
            $canviewlastaccess = $sameuser || !isset($hiddenfields['lastaccess']);
            if (!$canviewlastaccess) {
                $canviewlastaccess = has_capability('moodle/course:viewhiddenuserfields', $context);
            }

            if ($canviewlastaccess && isset($user->lastcourseaccess[$course->id])) {
                $lastaccess = $user->lastcourseaccess[$course->id];
            }

            $hidden = false;
            if ($sameuser) {
                $hidden = boolval(get_user_preferences('block_myoverview_hidden_course_' . $course->id, 0));
            }

            // Retrieve course overview used files.
            $courselist = new core_course_list_element($course);
            $overviewfiles = array();
            foreach ($courselist->get_course_overviewfiles() as $file) {
                $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
                                                                        $file->get_filearea(), null, $file->get_filepath(),
                                                                        $file->get_filename())->out(false);
                $overviewfiles[] = array(
                    'filename' => $file->get_filename(),
                    'fileurl' => $fileurl,
                    'filesize' => $file->get_filesize(),
                    'filepath' => $file->get_filepath(),
                    'mimetype' => $file->get_mimetype(),
                    'timemodified' => $file->get_timemodified(),
                );
            }

            $courseresult = [
                'id' => $course->id,
                'shortname' => $course->shortname,
                'fullname' => $course->fullname,
                'displayname' => $displayname,
                'idnumber' => $course->idnumber,
                'visible' => $course->visible,
                'summary' => $course->summary,
                'summaryformat' => $course->summaryformat,
                'format' => $course->format,
                'showgrades' => $course->showgrades,
                'lang' => clean_param($course->lang, PARAM_LANG),
                'enablecompletion' => $course->enablecompletion,
                'completionhascriteria' => $completionhascriteria,
                'completionusertracked' => $completionusertracked,
                'category' => $course->category,
                'progress' => $progress,
                'completed' => $completed,
                'startdate' => $course->startdate,
                'enddate' => $course->enddate,
                'marker' => $course->marker,
                'lastaccess' => $lastaccess,
                'isfavourite' => isset($favouritecourseids[$course->id]),
                'hidden' => $hidden,
                'overviewfiles' => $overviewfiles,
            ];
            if ($returnusercount) {
                $courseresult['enrolledusercount'] = $enrolledusercount;
            }
            $result[] = $courseresult;
        }

        return $result;
    }
832026
public function findByUserId($userId)
    {
        $select = $this->getSelect();
        $select->where(array('user_id' => $userId));

        return $this->select($select);
    }
404152
public function userGet(int $user_id)
    {
        $value = get_user_meta($user_id, $this->getName(), true);

        if (! empty($value)) {
            $this->setValue($value);
        }
    }
994240
public static function get_user_timers($lessonid, $userid = null) {
        global $USER;

        $params = array(
            'lessonid' => $lessonid,
            'userid' => $userid,
        );
        $params = self::validate_parameters(self::get_user_timers_parameters(), $params);
        $warnings = array();

        list($lesson, $course, $cm, $context, $lessonrecord) = self::validate_lesson($params['lessonid']);

        // Default value for userid.
        if (empty($params['userid'])) {
            $params['userid'] = $USER->id;
        }

        // Extra checks so only users with permissions can view other users attempts.
        if ($USER->id != $params['userid']) {
            self::check_can_view_user_data($params['userid'], $course, $cm, $context);
        }

        $timers = $lesson->get_user_timers($params['userid']);

        $result = array();
        $result['timers'] = $timers;
        $result['warnings'] = $warnings;
        return $result;
    }
101315
public static function get_grades($workshopid, $userid = 0) {
        global $USER;

        $params = array(
            'workshopid' => $workshopid,
            'userid' => $userid,
        );
        $params = self::validate_parameters(self::get_grades_parameters(), $params);
        $warnings = array();

        list($workshop, $course, $cm, $context) = self::validate_workshop($params['workshopid']);

        // Extra checks so only users with permissions can view other users plans.
        if (empty($params['userid']) || $params['userid'] == $USER->id) {
            $userid = $USER->id;
        } else {
            require_capability('mod/workshop:viewallassessments', $context);
            $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
            core_user::require_active_user($user);
            if (!$workshop->check_group_membership($user->id)) {
                throw new moodle_exception('notingroup');
            }
            $userid = $user->id;
        }

        $finalgrades = $workshop->get_gradebook_grades($userid);

        $result = array('warnings' => $warnings);
        if ($finalgrades !== false) {
            if (!empty($finalgrades->submissiongrade)) {
                if (is_numeric($finalgrades->submissiongrade->grade)) {
                    $result['submissionrawgrade'] = $finalgrades->submissiongrade->grade;
                }
                $result['submissionlongstrgrade'] = $finalgrades->submissiongrade->str_long_grade;
                $result['submissiongradehidden'] = $finalgrades->submissiongrade->hidden;
            }
            if (!empty($finalgrades->assessmentgrade)) {
                if (is_numeric($finalgrades->assessmentgrade->grade)) {
                    $result['assessmentrawgrade'] = $finalgrades->assessmentgrade->grade;
                }
                $result['assessmentlongstrgrade'] = $finalgrades->assessmentgrade->str_long_grade;
                $result['assessmentgradehidden'] = $finalgrades->assessmentgrade->hidden;
            }
        }

        return $result;
    }
172079
public static function check_lti_id($linkid, $course, $toolproxy) {
        global $DB;
        // Check if lti type is zero or not (comes from a backup).
        $sqlparams1 = array();
        $sqlparams1['linkid'] = $linkid;
        $sqlparams1['course'] = $course;
        $ltiactivity = $DB->get_record('lti', array('id' => $linkid, 'course' => $course));
        if ($ltiactivity->typeid == 0) {
            $tool = lti_get_tool_by_url_match($ltiactivity->toolurl, $course);
            if (!$tool) {
                $tool = lti_get_tool_by_url_match($ltiactivity->securetoolurl, $course);
            }
            return (($tool) && ($toolproxy == $tool->toolproxyid));
        } else {
            $sqlparams2 = array();
            $sqlparams2['linkid'] = $linkid;
            $sqlparams2['course'] = $course;
            $sqlparams2['toolproxy'] = $toolproxy;
            $sql = 'SELECT lti.*
                      FROM {lti} lti
                INNER JOIN {lti_types} typ ON lti.typeid = typ.id
                     WHERE lti.id = ?
                           AND lti.course = ?
                           AND typ.toolproxyid = ?';
            return $DB->record_exists_sql($sql, $sqlparams2);
        }
    }
874572
public function isUserInRoleById(int $userId): bool
    {
        if (isset($this->users[$userId])) {
            return true;
        }

        return false;
    }
345428
public static function export_user_preferences(int $userid) {
        $preffilter = get_user_preferences(tool_helper::PREF_REQUEST_FILTERS, null, $userid);
        if ($preffilter !== null) {
            $filters = json_decode($preffilter);
            $descriptions = [];
            foreach ($filters as $filter) {
                list($category, $value) = explode(':', $filter);
                $option = new stdClass();
                switch($category) {
                    case tool_helper::FILTER_TYPE:
                        $option->category = get_string('requesttype', 'tool_dataprivacy');
                        $option->name = tool_helper::get_shortened_request_type_string($value);
                        break;
                    case tool_helper::FILTER_STATUS:
                        $option->category = get_string('requeststatus', 'tool_dataprivacy');
                        $option->name = tool_helper::get_request_status_string($value);
                        break;
                    case tool_helper::FILTER_CREATION:
                        $option->category = get_string('requestcreation', 'tool_dataprivacy');
                        $option->name = tool_helper::get_request_creation_method_string($value);
                        break;
                }
                $descriptions[] = get_string('filteroption', 'tool_dataprivacy', $option);
            }
            // Export the filter preference as comma-separated values and text descriptions.
            $values = implode(', ', $filters);
            $descriptionstext = implode(', ', $descriptions);
            writer::export_user_preference('tool_dataprivacy', tool_helper::PREF_REQUEST_FILTERS, $values, $descriptionstext);
        }

        $prefperpage = get_user_preferences(tool_helper::PREF_REQUEST_PERPAGE, null, $userid);
        if ($prefperpage !== null) {
            writer::export_user_preference('tool_dataprivacy', tool_helper::PREF_REQUEST_PERPAGE, $prefperpage,
                get_string('privacy:metadata:preference:tool_dataprivacy_request-perpage', 'tool_dataprivacy'));
        }
    }
1045470
public static function count_proficient_competencies_in_course_for_user($courseid, $userid) {
        static::require_enabled();
        // Check the user have access to the course.
        self::validate_course($courseid);

        // First we do a permissions check.
        $context = context_course::instance($courseid);

        $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
        if (!has_any_capability($capabilities, $context)) {
             throw new required_capability_exception($context, 'moodle/competency:coursecompetencyview', 'nopermissions', '');
        }

        // OK - all set.
        return user_competency_course::count_proficient_competencies($courseid, $userid);
    }
618525
public function removeUserById($userId)
    {
        $updtableProperties = Updatable::getInstance()
            ->table($this->getUserPropertiesDefinition()->table())
            ->where(
                "{$this->getUserPropertiesDefinition()->getUserid()} = :id",
                [
                    "id" => $userId
                ]
            );
        $this->propertiesRepository->deleteByQuery($updtableProperties);

        $this->userRepository->delete($userId);

        return true;
    }
533399
public static function count_user_subscriptions_for_course($courseid, $userid = 0) {
        global $DB, $USER;
        if ($userid == 0) {
            $userid = $USER->id;
        }
        $sql = self::get_subscription_join_rule_sql(true);
        $sql .= "WHERE s.courseid = :courseid AND s.userid = :userid";

        return $DB->count_records_sql($sql, array('courseid' => $courseid, 'userid' => $userid));
    }
577967
public function GetByUserID($UserID) {
      return $this->SQL->Select()
         ->From('Role')
         ->Join('UserRole', 'Role.RoleID = UserRole.RoleID')
         ->Where('UserRole.UserID', $UserID)
         ->Get();
   }