protected static function clear_old_records() {
        global $DB;

        $sql = "SELECT dpctx.*
                  FROM {tool_dataprivacy_ctxexpired} dpctx
             LEFT JOIN {context} ctx ON ctx.id = dpctx.contextid
                 WHERE ctx.id IS NULL";

        $orphaned = $DB->get_recordset_sql($sql);
        foreach ($orphaned as $orphan) {
            $expiredcontext = new expired_context(0, $orphan);
            $expiredcontext->delete();
        }

        // Delete any child of a user context.
        $parentpath = $DB->sql_concat('ctxuser.path', "'/%'");
        $params = [
            'contextuser' => CONTEXT_USER,
        ];

        $sql = "SELECT dpctx.*
                  FROM {tool_dataprivacy_ctxexpired} dpctx
                 WHERE dpctx.contextid IN (
                    SELECT ctx.id
                        FROM {context} ctxuser
                        JOIN {context} ctx ON ctx.path LIKE {$parentpath}
                       WHERE ctxuser.contextlevel = :contextuser
                    )";
        $userchildren = $DB->get_recordset_sql($sql, $params);
        foreach ($userchildren as $child) {
            $expiredcontext = new expired_context(0, $child);
            $expiredcontext->delete();
        }
    }