Combines the review options from a number of different quiz attempts.

@param int $quizid quiz instance id
@param int $userid user id (empty for current user)
@return array of warnings and the review options
@since Moodle 3.1
339002
public static function get_combined_review_options($quizid, $userid = 0) {
        global $DB, $USER;

        $warnings = array();

        $params = array(
            'quizid' => $quizid,
            'userid' => $userid,
        );
        $params = self::validate_parameters(self::get_combined_review_options_parameters(), $params);

        list($quiz, $course, $cm, $context) = self::validate_quiz($params['quizid']);

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

        $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
        core_user::require_active_user($user);

        // Extra checks so only users with permissions can view other users attempts.
        if ($USER->id != $user->id) {
            require_capability('mod/quiz:viewreports', $context);
        }

        $attempts = quiz_get_user_attempts($quiz->id, $user->id, 'all', true);

        $result = array();
        $result['someoptions'] = [];
        $result['alloptions'] = [];

        list($someoptions, $alloptions) = quiz_get_combined_reviewoptions($quiz, $attempts);

        foreach (array('someoptions', 'alloptions') as $typeofoption) {
            foreach ($$typeofoption as $key => $value) {
                $result[$typeofoption][] = array(
                    "name" => $key,
                    "value" => (!empty($value)) ? $value : 0
                );
            }
        }

        $result['warnings'] = $warnings;
        return $result;
    }
179524
protected static function validate_quiz($quizid) {
        global $DB;

        // Request and permission validation.
        $quiz = $DB->get_record('quiz', array('id' => $quizid), '*', MUST_EXIST);
        list($course, $cm) = get_course_and_cm_from_instance($quiz, 'quiz');

        $context = context_module::instance($cm->id);
        self::validate_context($context);

        return array($quiz, $course, $cm, $context);
    }
832026
public function findByUserId($userId)
    {
        $select = $this->getSelect();
        $select->where(array('user_id' => $userId));

        return $this->select($select);
    }
966882
public static function count_proficient_competencies($courseid, $userid) {
        global $DB;

        $sql = 'SELECT COUNT(comp.id)
                  FROM {' . self::TABLE . '} usercoursecomp
                  JOIN {' . course_competency::TABLE . '} cc
                    ON usercoursecomp.competencyid = cc.competencyid AND cc.courseid = usercoursecomp.courseid
                  JOIN {' . competency::TABLE . '} comp
                    ON usercoursecomp.competencyid = comp.id
                 WHERE usercoursecomp.courseid = ? AND usercoursecomp.userid = ? AND usercoursecomp.proficiency = ?';
        $params = array($courseid, $userid, true);

        $results = $DB->count_records_sql($sql, $params);

        return $results;
    }
1180802
public static function list_competencies($planid, $userid) {
        global $DB;

        $sql = 'SELECT c.*
                  FROM {' . competency::TABLE . '} c
                  JOIN {' . self::TABLE . '} ucp
                    ON ucp.competencyid = c.id
                   AND ucp.userid = :userid
                 WHERE ucp.planid = :planid
              ORDER BY ucp.sortorder ASC,
                       ucp.id ASC';
        $params = array('userid' => $userid, 'planid' => $planid);

        $results = $DB->get_recordset_sql($sql, $params);
        $instances = array();
        foreach ($results as $key => $result) {
             $instances[$key] = new competency(0, $result);
        }
        $results->close();

        return $instances;
    }
542901
public function getUserVoted($userId)
    {
        return (new Query())->from('{{%podium_poll_vote}}')->where([
            'poll_id' => $this->id,
            'caster_id' => $userId
        ])->count('id') ? true : false;
    }
205073
protected function get_graders($userid) {
        // Potential graders should be active users only.
        $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade", null, 'u.*', null, null, null, true);

        $graders = array();
        if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) {
            if ($groups = groups_get_all_groups($this->get_course()->id, $userid, $this->get_course_module()->groupingid)) {
                foreach ($groups as $group) {
                    foreach ($potentialgraders as $grader) {
                        if ($grader->id == $userid) {
                            // Do not send self.
                            continue;
                        }
                        if (groups_is_member($group->id, $grader->id)) {
                            $graders[$grader->id] = $grader;
                        }
                    }
                }
            } else {
                // User not in group, try to find graders without group.
                foreach ($potentialgraders as $grader) {
                    if ($grader->id == $userid) {
                        // Do not send self.
                        continue;
                    }
                    if (!groups_has_membership($this->get_course_module(), $grader->id)) {
                        $graders[$grader->id] = $grader;
                    }
                }
            }
        } else {
            foreach ($potentialgraders as $grader) {
                if ($grader->id == $userid) {
                    // Do not send self.
                    continue;
                }
                // Must be enrolled.
                if (is_enrolled($this->get_course_context(), $grader->id)) {
                    $graders[$grader->id] = $grader;
                }
            }
        }
        return $graders;
    }
1297941
public static function user_competency_request_review($userid, $competencyid) {
        $params = self::validate_parameters(self::user_competency_request_review_parameters(), array(
            'userid' => $userid,
            'competencyid' => $competencyid,
        ));

        $context = context_user::instance($params['userid']);
        self::validate_context($context);

        return api::user_competency_request_review($userid, $competencyid);
    }
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;
    }
1214149
public function get_user_enrolments($userid) {
        global $DB;
        list($instancessql, $params, $filter) = $this->get_instance_sql();
        $params['userid'] = $userid;
        $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
        $instances = $this->get_enrolment_instances();
        $plugins = $this->get_enrolment_plugins(false);
        $inames = $this->get_enrolment_instance_names();
        foreach ($userenrolments as &$ue) {
            $ue->enrolmentinstance     = $instances[$ue->enrolid];
            $ue->enrolmentplugin       = $plugins[$ue->enrolmentinstance->enrol];
            $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
        }
        return $userenrolments;
    }
23514
public static function get_contexts_for_userid(int $userid) : contextlist {
        global $DB;

        $contextlist = new contextlist();

        // Messages are in the user context.
        // For the sake of performance, there is no need to call add_from_sql for each of the below cases.
        // It is enough to add the user's context as soon as we come to the conclusion that the user has some data.
        // Also, the order of checking is sorted by the probability of occurrence (just by guess).
        // There is no need to check the message_user_actions table, as there needs to be a message in order to be a message action.
        // There is no need to check the message_conversation_actions table, as there needs to be a conversation in order to
        // be a conversation action.
        // So, checking messages table would suffice.

        $hasdata = false;
        $hasdata = $hasdata || $DB->record_exists_select('notifications', 'useridfrom = ? OR useridto = ?', [$userid, $userid]);
        $sql = "SELECT mc.id
              FROM {message_conversations} mc
              JOIN {message_conversation_members} mcm
                ON (mcm.conversationid = mc.id AND mcm.userid = :userid)
             WHERE mc.contextid IS NULL";
        $hasdata = $hasdata || $DB->record_exists_sql($sql, ['userid' => $userid]);
        $sql = "SELECT mc.id
              FROM {message_conversations} mc
              JOIN {messages} m
                ON (m.conversationid = mc.id AND m.useridfrom = :useridfrom)
             WHERE mc.contextid IS NULL";
        $hasdata = $hasdata || $DB->record_exists_sql($sql, ['useridfrom' => $userid]);
        $hasdata = $hasdata || $DB->record_exists_select('message_contacts', 'userid = ? OR contactid = ?', [$userid, $userid]);
        $hasdata = $hasdata || $DB->record_exists_select('message_users_blocked', 'userid = ? OR blockeduserid = ?',
                [$userid, $userid]);
        $hasdata = $hasdata || $DB->record_exists_select('message_contact_requests', 'userid = ? OR requesteduserid = ?',
                [$userid, $userid]);

        if ($hasdata) {
            $contextlist->add_user_context($userid);
        }

        // Add favourite conversations.
        \core_favourites\privacy\provider::add_contexts_for_userid($contextlist, $userid, 'core_message', 'message_conversations');

        return $contextlist;
    }
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;
    }
1358618
public static function user_competency_request_review($userid, $competencyid) {
        static::require_enabled();
        $uc = user_competency::get_record(array('userid' => $userid, 'competencyid' => $competencyid));
        if (!$uc) {
            $uc = user_competency::create_relation($userid, $competencyid);
            $uc->create();
        }

        if (!$uc->can_read()) {
            throw new required_capability_exception($uc->get_context(), 'moodle/competency:usercompetencyview',
                'nopermissions', '');
        } else if ($uc->get('status') != user_competency::STATUS_IDLE) {
            throw new coding_exception('The competency can not be sent for review at this stage.');
        } else if (!$uc->can_request_review()) {
            throw new required_capability_exception($uc->get_context(), 'moodle/competency:usercompetencyrequestreview',
                'nopermissions', '');
        }

        $uc->set('status', user_competency::STATUS_WAITING_FOR_REVIEW);
        $result = $uc->update();
        if ($result) {
            \core\event\competency_user_competency_review_requested::create_from_user_competency($uc)->trigger();
        }
        return $result;
    }
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;
    }
586815
public function loadPoliciesByUserId($userId)
    {
        $groupIds = $this->fetchUserGroups($userId);
        $groupIds[] = $userId;

        return $this->loadRolesForContentObjects($groupIds);
    }
1357514
public static function block_user(int $userid, int $blockeduserid) {
        global $CFG, $USER;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        // Validate context.
        $context = context_system::instance();
        self::validate_context($context);

        $params = ['userid' => $userid, 'blockeduserid' => $blockeduserid];
        $params = self::validate_parameters(self::block_user_parameters(), $params);

        $capability = 'moodle/site:manageallmessaging';
        if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
            throw new required_capability_exception($context, $capability, 'nopermissions', '');
        }

        if (!\core_message\api::is_blocked($params['userid'], $params['blockeduserid'])) {
            \core_message\api::block_user($params['userid'], $params['blockeduserid']);
        }

        return [];
    }
407845
public static function export_user_preferences(int $userid) {
        $preference = get_user_preferences('quiz_overview_slotmarks', null);
        if (null !== $preference) {
            if (empty($preference)) {
                $description = get_string('privacy:preference:slotmarks:no', 'quiz_overview');
            } else {
                $description = get_string('privacy:preference:slotmarks:yes', 'quiz_overview');
            }

            writer::export_user_preference(
                'quiz_overview',
                'slotmarks',
                transform::yesno($preference),
                $description
            );
        }
    }