diff --git a/message/externallib.php b/message/externallib.php index c9c6631cfe2..834702098ac 100644 --- a/message/externallib.php +++ b/message/externallib.php @@ -2199,13 +2199,13 @@ class core_message_external extends external_api { * @param int $limitnum Return a subset comprising this many records in total (optional, required if $limitfrom is set). * @param bool $newest True for getting first newest messages, false otherwise. * @param int $timefrom The time from the conversation messages to get. - * @return stdClass The messages and members who have sent some of these messages. + * @return array The messages and members who have sent some of these messages. * @throws moodle_exception * @since 3.6 */ public static function get_conversation_messages(int $currentuserid, int $convid, int $limitfrom = 0, int $limitnum = 0, bool $newest = false, int $timefrom = 0) { - global $CFG, $PAGE, $USER; + global $CFG, $USER; // Check if messaging is enabled. if (empty($CFG->messaging)) { @@ -2229,6 +2229,11 @@ class core_message_external extends external_api { throw new moodle_exception('You do not have permission to perform this action.'); } + // Check that the user belongs to the conversation. + if (!\core_message\api::is_user_in_conversation($params['currentuserid'], $params['convid'])) { + throw new moodle_exception('User is not part of conversation.'); + } + $sort = $newest ? 'timecreated DESC' : 'timecreated ASC'; // We need to enforce a one second delay on messages to avoid race conditions of current diff --git a/message/tests/externallib_test.php b/message/tests/externallib_test.php index 78f7b7f64c8..bb53040953e 100644 --- a/message/tests/externallib_test.php +++ b/message/tests/externallib_test.php @@ -3945,6 +3945,31 @@ class core_message_externallib_testcase extends externallib_advanced_testcase { core_message_external::get_conversation_messages($user2->id, $conversation->id); } + /** + * Tests get_conversation_messages for retrieving messages as another user not in the conversation. + */ + public function test_get_conversation_messages_as_user_not_in_conversation() { + $this->resetAfterTest(true); + + // Create some users. + $user1 = self::getDataGenerator()->create_user(); + $user2 = self::getDataGenerator()->create_user(); + $user3 = self::getDataGenerator()->create_user(); // Not in group. + + // Create group conversation. + $conversation = \core_message\api::create_conversation( + \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, + [$user1->id, $user2->id] + ); + + // The person asking for the messages for a conversation he does not belong to. + $this->setUser($user3); + + // Ensure an exception is thrown. + $this->expectExceptionMessage('User is not part of conversation.'); + core_message_external::get_conversation_messages($user3->id, $conversation->id); + } + /** * Tests get_conversation_messages for retrieving messages with messaging disabled. */