public static function cleanup_instances() {
        global $DB;
        self::init_levels();

        $sqls = array();
        foreach (self::$alllevels as $level=>$classname) {
            $sqls[] = $classname::get_cleanup_sql();
        }

        $sql = implode(" UNION ", $sqls);

        // it is probably better to use transactions, it might be faster too
        $transaction = $DB->start_delegated_transaction();

        $rs = $DB->get_recordset_sql($sql);
        foreach ($rs as $record) {
            $context = context::create_instance_from_record($record);
            $context->delete();
        }
        $rs->close();

        $transaction->allow_commit();
    }