public static function cleanup_unused_tags($collections = null) {
        global $DB, $CFG;

        $params = array();
        $sql = "SELECT tg.id FROM {tag} tg LEFT OUTER JOIN {tag_instance} ti ON ti.tagid = tg.id
                WHERE ti.id IS NULL AND tg.isstandard = 0";
        if ($collections) {
            list($sqlcoll, $params) = $DB->get_in_or_equal($collections, SQL_PARAMS_NAMED);
            $sql .= " AND tg.tagcollid " . $sqlcoll;
        }
        if ($unusedtags = $DB->get_fieldset_sql($sql, $params)) {
            core_tag_tag::delete_tags($unusedtags);
        }
    }