protected function get_glossary_cm() {
        global $DB;
        if (empty($this->config->glossary)) {
            // No glossary is configured.
            return null;
        }

        if (!empty($this->glossarycm)) {
            return $this->glossarycm;
        }

        if (!empty($this->page->course->id)) {
            // First check if glossary belongs to the current course (we don't need to make any DB queries to find it).
            $modinfo = get_fast_modinfo($this->page->course);
            if (isset($modinfo->instances['glossary'][$this->config->glossary])) {
                $this->glossarycm = $modinfo->instances['glossary'][$this->config->glossary];
                if ($this->glossarycm->uservisible) {
                    // The glossary is in the same course and is already visible to the current user,
                    // no need to check if it is global, save on DB query.
                    return $this->glossarycm;
                }
            }
        }

        // Find course module id for the given glossary, only if it is global.
        $cm = $DB->get_record_sql("SELECT cm.id, cm.visible AS uservisible
              FROM {course_modules} cm
                   JOIN {modules} md ON md.id = cm.module
                   JOIN {glossary} g ON g.id = cm.instance
             WHERE g.id = :instance AND md.name = :modulename AND g.globalglossary = 1",
            ['instance' => $this->config->glossary, 'modulename' => 'glossary']);

        if ($cm) {
            // This is a global glossary, create an object with properties 'id' and 'uservisible'. We don't need any
            // other information so why bother retrieving it. Full access check is skipped for global glossaries for
            // performance reasons.
            $this->glossarycm = $cm;
        } else if (empty($this->glossarycm)) {
            // Glossary does not exist. Remove it in the config so we don't repeat this check again later.
            $this->config->glossary = 0;
            $this->instance_config_commit();
        }

        return $this->glossarycm;
    }