public static function is_user_visible($cmorid, $userid = 0, $checkcourse = true) {
        global $USER, $DB, $CFG;

        // Evaluate user id.
        if (!$userid) {
            $userid = $USER->id;
        }

        // If this happens to be already called with a cm_info for the right user
        // then just return uservisible.
        if (($cmorid instanceof \cm_info) && $cmorid->get_modinfo()->userid == $userid) {
            return $cmorid->uservisible;
        }

        // If the $cmorid isn't an object or doesn't have required fields, load it.
        if (is_object($cmorid) && isset($cmorid->course) && isset($cmorid->visible)) {
            $cm = $cmorid;
        } else {
            if (is_object($cmorid)) {
                $cmorid = $cmorid->id;
            }
            $cm = $DB->get_record('course_modules', array('id' => $cmorid));
            if (!$cm) {
                // In some error cases, the course module may not exist.
                debugging('info_module::is_user_visible called with invalid cmid ' . $cmorid, DEBUG_DEVELOPER);
                return false;
            }
        }

        // If requested, check user can access the course.
        if ($checkcourse) {
            $coursecontext = \context_course::instance($cm->course);
            if (!is_enrolled($coursecontext, $userid, '', true) &&
                    !has_capability('moodle/course:view', $coursecontext, $userid)) {
                return false;
            }
        }

        // If availability is disabled, then all we need to do is check the visible flag.
        if (!$CFG->enableavailability && $cm->visible) {
            return true;
        }

        // When availability is enabled, access can depend on 3 things:
        // 1. $cm->visible
        // 2. $cm->availability
        // 3. $section->availability (for activity section and possibly for
        //    parent sections)
        // As a result we cannot take short cuts any longer and must get
        // standard modinfo.
        $modinfo = get_fast_modinfo($cm->course, $userid);
        $cms = $modinfo->get_cms();
        if (!isset($cms[$cm->id])) {
            // In some cases this might get called with a cmid that is no longer
            // available, for example when a module is hidden at system level.
            debugging('info_module::is_user_visible called with invalid cmid ' . $cm->id, DEBUG_DEVELOPER);
            return false;
        }
        return $cms[$cm->id]->uservisible;
    }