public static function record_expanded_category(\core_course_category $coursecat, $expanded = true) {
        // If this ever changes we are going to reset it and reload the categories as required.
        self::$expandedcategories = null;
        $categoryid = $coursecat->id;
        $path = $coursecat->get_parents();
        /* @var \cache_session $cache */
        $cache = \cache::make('core', 'userselections');
        $categories = $cache->get('categorymanagementexpanded');
        if (!is_array($categories)) {
            if (!$expanded) {
                // No categories recorded, nothing to remove.
                return;
            }
            $categories = array();
        }
        if ($expanded) {
            $ref =& $categories;
            foreach ($coursecat->get_parents() as $path) {
                if (!isset($ref[$path]) || !is_array($ref[$path])) {
                    $ref[$path] = array();
                }
                $ref =& $ref[$path];
            }
            if (!isset($ref[$categoryid])) {
                $ref[$categoryid] = true;
            }
        } else {
            $found = true;
            $ref =& $categories;
            foreach ($coursecat->get_parents() as $path) {
                if (!isset($ref[$path])) {
                    $found = false;
                    break;
                }
                $ref =& $ref[$path];
            }
            if ($found) {
                $ref[$categoryid] = null;
                unset($ref[$categoryid]);
            }
        }
        $cache->set('categorymanagementexpanded', $categories);
    }