From d89d0d659333e8f7323d7a1e71131cc2849b0677 Mon Sep 17 00:00:00 2001 From: Sara Arjona Date: Fri, 19 Oct 2018 13:23:17 +0200 Subject: [PATCH] MDL-63466 core_message: Added format_conversation_messages helper The format_conversation_messages function has been added. It returns the messages and the array of users who have sent any of these messages. --- message/classes/helper.php | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/message/classes/helper.php b/message/classes/helper.php index 211a8a2342b..b39110a3b55 100644 --- a/message/classes/helper.php +++ b/message/classes/helper.php @@ -108,6 +108,57 @@ class helper { return $messages; } + /** + * Helper function to return a conversation messages with the involved members (only the ones + * who have sent any of these messages). + * + * @param int $userid The current userid. + * @param int $convid The conversation id. + * @param array $messages The formated array messages. + * @return array A conversation array with the messages and the involved members. + */ + public static function format_conversation_messages(int $userid, int $convid, array $messages) : array { + global $USER; + + // Create the conversation array. + $conversation = array( + 'id' => $convid, + ); + + // Store the messages. + $arrmessages = array(); + + // We always view messages from oldest to newest, ensure we have it in that order. + $lastmessage = end($messages); + $firstmessage = reset($messages); + if ($lastmessage->timecreated < $firstmessage->timecreated) { + $messages = array_reverse($messages); + } + + foreach ($messages as $message) { + // Store the message information. + $msg = new \stdClass(); + $msg->id = $message->id; + $msg->useridfrom = $message->useridfrom; + $msg->text = message_format_message_text($message); + $msg->timecreated = $message->timecreated; + $arrmessages[] = $msg; + } + // Add the messages to the conversation. + $conversation['messages'] = $arrmessages; + + // Get the users who have sent any of the $messages. + $memberids = array_unique(array_map(function($message) { + return $message->useridfrom; + }, $messages)); + // Get members information. + $arrmembers = self::get_member_info($userid, $memberids); + // Add the members to the conversation. + $conversation['members'] = $arrmembers; + + return $conversation; + } + /** * Helper function to return an array of messages. *