From e66b915c40518bd1d9885c907fd2bb4ae0fd8135 Mon Sep 17 00:00:00 2001 From: Mark Nelson Date: Thu, 18 Oct 2018 21:17:12 +0800 Subject: [PATCH] MDL-63691 core_message: added api::can_create_group_conversation --- message/classes/api.php | 19 +++++++++++++++++++ message/tests/api_test.php | 29 +++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/message/classes/api.php b/message/classes/api.php index b3e78288352..317d40d2b6e 100644 --- a/message/classes/api.php +++ b/message/classes/api.php @@ -1385,6 +1385,25 @@ class api { return $conversation->id; } + /** + * Checks if a user can create a group conversation. + * + * @param int $userid The id of the user attempting to create the conversation + * @param \context $context The context they are creating the conversation from, most likely course context + * @return bool + */ + public static function can_create_group_conversation(int $userid, \context $context) : bool { + global $CFG; + + // If we can't message at all, then we can't create a conversation. + if (empty($CFG->messaging)) { + return false; + } + + // We need to check they have the capability to create the conversation. + return has_capability('moodle/course:creategroupconversations', $context, $userid); + } + /** * Checks if a user can create a contact request. * diff --git a/message/tests/api_test.php b/message/tests/api_test.php index 8be0f3f6070..d67f36363a6 100644 --- a/message/tests/api_test.php +++ b/message/tests/api_test.php @@ -2416,6 +2416,35 @@ class core_message_api_testcase extends core_message_messagelib_testcase { $this->assertFalse(\core_message\api::is_user_in_conversation($user3->id, $conversationid)); } + /** + * Test can create a group conversation. + */ + public function test_can_create_group_conversation() { + global $CFG; + + $student = self::getDataGenerator()->create_user(); + $teacher = self::getDataGenerator()->create_user(); + $course = self::getDataGenerator()->create_course(); + + $coursecontext = context_course::instance($course->id); + + $this->getDataGenerator()->enrol_user($student->id, $course->id); + $this->getDataGenerator()->enrol_user($teacher->id, $course->id, 'editingteacher'); + + // Disable messaging. + $CFG->messaging = 0; + $this->assertFalse(\core_message\api::can_create_group_conversation($student->id, $coursecontext)); + + // Re-enable messaging. + $CFG->messaging = 1; + + // Student shouldn't be able to. + $this->assertFalse(\core_message\api::can_create_group_conversation($student->id, $coursecontext)); + + // Teacher should. + $this->assertTrue(\core_message\api::can_create_group_conversation($teacher->id, $coursecontext)); + } + /** * Comparison function for sorting contacts. *