public function cleanup() {
        global $DB;

        // Get ids to delete from instances where the tag has been deleted. This should never happen apparently.
        $sql = "SELECT ti.id
                  FROM {tag_instance} ti
             LEFT JOIN {tag} t ON t.id = ti.tagid
                 WHERE t.id IS null";
        $tagids = $DB->get_records_sql($sql);
        $tagarray = array();
        foreach ($tagids as $tagid) {
            $tagarray[] = $tagid->id;
        }

        // Next get ids from instances that have an owner that has been deleted.
        $sql = "SELECT ti.id
                  FROM {tag_instance} ti, {user} u
                 WHERE ti.itemid = u.id
                   AND ti.itemtype = 'user'
                   AND ti.component = 'core'
                   AND u.deleted = 1";
        $tagids = $DB->get_records_sql($sql);
        foreach ($tagids as $tagid) {
            $tagarray[] = $tagid->id;
        }

        // Get the other itemtypes.
        $sql = "SELECT DISTINCT component, itemtype
                  FROM {tag_instance}
                 WHERE itemtype <> 'user' or component <> 'core'";
        $tagareas = $DB->get_recordset_sql($sql);
        foreach ($tagareas as $tagarea) {
            $sql = 'SELECT ti.id
                      FROM {tag_instance} ti
                 LEFT JOIN {' . $tagarea->itemtype . '} it ON it.id = ti.itemid
                     WHERE it.id IS null
                     AND ti.itemtype = ? AND ti.component = ?';
            $tagids = $DB->get_records_sql($sql, array($tagarea->itemtype, $tagarea->component));
            foreach ($tagids as $tagid) {
                $tagarray[] = $tagid->id;
            }
        }
        $tagareas->close();

        // Get instances for each of the ids to be deleted.
        if (count($tagarray) > 0) {
            list($sqlin, $params) = $DB->get_in_or_equal($tagarray);
            $sql = "SELECT ti.*, COALESCE(t.name, 'deleted') AS name, COALESCE(t.rawname, 'deleted') AS rawname
                      FROM {tag_instance} ti
                 LEFT JOIN {tag} t ON t.id = ti.tagid
                     WHERE ti.id $sqlin";
            $instances = $DB->get_records_sql($sql, $params);
            $this->bulk_delete_instances($instances);
        }

        core_tag_collection::cleanup_unused_tags();
    }