protected function get_document_recordset_helper($modifiedfrom, \context $context = null,
            $userfield) {
        global $DB;

        if ($userfield == 'useridto') {
            $userfield = 'mcm.userid';
        } else {
            $userfield = 'm.useridfrom';
        }

        // Set up basic query.
        $where = $userfield . ' != :noreplyuser AND ' . $userfield .
                ' != :supportuser AND m.timecreated >= :modifiedfrom';
        $params = [
            'noreplyuser' => \core_user::NOREPLY_USER,
            'supportuser' => \core_user::SUPPORT_USER,
            'modifiedfrom' => $modifiedfrom
        ];

        // Check context to see whether to add other restrictions.
        if ($context === null) {
            $context = \context_system::instance();
        }
        switch ($context->contextlevel) {
            case CONTEXT_COURSECAT:
            case CONTEXT_COURSE:
            case CONTEXT_MODULE:
            case CONTEXT_BLOCK:
                // There are no messages in any of these contexts so nothing can be found.
                return null;

            case CONTEXT_USER:
                // Add extra restriction to specific user context.
                $where .= ' AND ' . $userfield . ' = :userid';
                $params['userid'] = $context->instanceid;
                break;

            case CONTEXT_SYSTEM:
                break;

            default:
                throw new \coding_exception('Unexpected contextlevel: ' . $context->contextlevel);
        }

        $sql = "SELECT m.*, mcm.userid as useridto
                  FROM {messages} m
            INNER JOIN {message_conversations} mc
                    ON m.conversationid = mc.id
            INNER JOIN {message_conversation_members} mcm
                    ON mcm.conversationid = mc.id
                 WHERE mcm.userid != m.useridfrom
                   AND $where
              ORDER BY m.timecreated ASC";
        return $DB->get_recordset_sql($sql, $params);
    }