protected static function set_collapsed_preferences($courseid, $collapsed) {
        global $DB;
        // In an unlikely case that the list of collapsed categories for one course is too big for the user preference size,
        // try to filter the list of categories since array may contain categories that were deleted.
        if (strlen(json_encode($collapsed)) >= 1333) {
            $collapsed = static::filter_collapsed_categories($courseid, $collapsed);
        }

        // If this did not help, "forget" about some of the collapsed categories. Still better than to loose all information.
        while (strlen(json_encode($collapsed)) >= 1333) {
            if (count($collapsed['aggregatesonly'])) {
                array_pop($collapsed['aggregatesonly']);
            }
            if (count($collapsed['gradesonly'])) {
                array_pop($collapsed['gradesonly']);
            }
        }

        if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) {
            set_user_preference('grade_report_grader_collapsed_categories'.$courseid, json_encode($collapsed));
        } else {
            unset_user_preference('grade_report_grader_collapsed_categories'.$courseid);
        }
    }