protected static function delete_orphan_historical_grades($userid) {
        global $DB;
        $sql = "
            SELECT ggh.id
              FROM {grade_grades_history} ggh
         LEFT JOIN {grade_items} gi
                ON ggh.itemid = gi.id
             WHERE gi.id IS NULL
               AND ggh.userid = :userid";
        $ids = $DB->get_fieldset_sql($sql, ['userid' => $userid]);
        if (empty($ids)) {
            return;
        }
        list($insql, $inparams) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);

        // First, let's delete their files.
        $sql = "
            SELECT gi.id
              FROM {grade_grades_history} ggh
              JOIN {grade_items} gi
                ON gi.id = ggh.itemid
             WHERE ggh.userid = :userid";
        $params = ['userid' => $userid];
        $gradeitems = $DB->get_records_sql($sql, $params);
        if ($gradeitems) {
            $itemids = array_keys($gradeitems);
            self::delete_files($itemids, true, [$userid]);
        }

        $DB->delete_records_select('grade_grades_history', "id $insql", $inparams);
    }