public static function data_for_messagearea_messages($currentuserid, $otheruserid, $limitfrom = 0, $limitnum = 0,
                                                         $newest = false, $timefrom = 0) {
        global $CFG, $PAGE, $USER;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        $systemcontext = context_system::instance();

        $params = array(
            'currentuserid' => $currentuserid,
            'otheruserid' => $otheruserid,
            'limitfrom' => $limitfrom,
            'limitnum' => $limitnum,
            'newest' => $newest,
            'timefrom' => $timefrom,
        );
        $params = self::validate_parameters(self::data_for_messagearea_messages_parameters(), $params);
        self::validate_context($systemcontext);

        if (($USER->id != $params['currentuserid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
            throw new moodle_exception('You do not have permission to perform this action.');
        }

        if ($params['newest']) {
            $sort = 'timecreated DESC';
        } else {
            $sort = 'timecreated ASC';
        }

        // We need to enforce a one second delay on messages to avoid race conditions of current
        // messages still being sent.
        //
        // There is a chance that we could request messages before the current time's
        // second has elapsed and while other messages are being sent in that same second. In which
        // case those messages will be lost.
        //
        // Instead we ignore the current time in the result set to ensure that second is allowed to finish.
        if (!empty($params['timefrom'])) {
            $timeto = time() - 1;
        } else {
            $timeto = 0;
        }

        // No requesting messages from the current time, as stated above.
        if ($params['timefrom'] == time()) {
            $messages = [];
        } else {
            $messages = \core_message\api::get_messages($params['currentuserid'], $params['otheruserid'], $params['limitfrom'],
                                                        $params['limitnum'], $sort, $params['timefrom'], $timeto);
        }

        $messages = new \core_message\output\messagearea\messages($params['currentuserid'], $params['otheruserid'], $messages);

        $renderer = $PAGE->get_renderer('core_message');
        return $messages->export_for_template($renderer);
    }