protected static function check_report_access($courseid, $userid, $groupid = 0) {
        global $USER;

        // Validate the parameter.
        $params = self::validate_parameters(self::get_grades_table_parameters(),
            array(
                'courseid' => $courseid,
                'userid' => $userid,
                'groupid' => $groupid,
            )
        );

        // Compact/extract functions are not recommended.
        $courseid = $params['courseid'];
        $userid   = $params['userid'];
        $groupid  = $params['groupid'];

        // Function get_course internally throws an exception if the course doesn't exist.
        $course = get_course($courseid);

        $context = context_course::instance($courseid);
        self::validate_context($context);

        // Specific capabilities.
        require_capability('gradereport/user:view', $context);

        $user = null;

        if (empty($userid)) {
            require_capability('moodle/grade:viewall', $context);
        } else {
            $user = core_user::get_user($userid, '*', MUST_EXIST);
            core_user::require_active_user($user);
            // Check if we can view the user group (if any).
            // When userid == 0, we are retrieving all the users, we'll check then if a groupid is required.
            if (!groups_user_groups_visible($course, $user->id)) {
                throw new moodle_exception('notingroup');
            }
        }

        $access = false;

        if (has_capability('moodle/grade:viewall', $context)) {
            // Can view all course grades.
            $access = true;
        } else if ($userid == $USER->id and has_capability('moodle/grade:view', $context) and $course->showgrades) {
            // View own grades.
            $access = true;
        }

        if (!$access) {
            throw new moodle_exception('nopermissiontoviewgrades', 'error');
        }

        if (!empty($groupid)) {
            // Determine is the group is visible to user.
            if (!groups_group_visible($groupid, $course)) {
                throw new moodle_exception('notingroup');
            }
        } else {
            // Check to see if groups are being used here.
            if ($groupmode = groups_get_course_groupmode($course)) {
                $groupid = groups_get_course_group($course);
                // Determine is the group is visible to user (this is particullary for the group 0).
                if (!groups_group_visible($groupid, $course)) {
                    throw new moodle_exception('notingroup');
                }
            } else {
                $groupid = 0;
            }
        }

        return array($params, $course, $context, $user, $groupid);
    }