6f8d26699985b18379e566f9fe963983e0a9393c
[moodle.git] / message / tests / api_test.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Test message API.
19  *
20  * @package core_message
21  * @category test
22  * @copyright 2016 Mark Nelson <markn@moodle.com>
23  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 global $CFG;
30 require_once($CFG->dirroot . '/message/tests/messagelib_test.php');
32 use \core_message\tests\helper as testhelper;
34 /**
35  * Test message API.
36  *
37  * @package core_message
38  * @category test
39  * @copyright 2016 Mark Nelson <markn@moodle.com>
40  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41  */
42 class core_message_api_testcase extends core_message_messagelib_testcase {
44     public function test_mark_all_read_for_user_touser() {
45         $sender = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
46         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
48         $this->send_fake_message($sender, $recipient, 'Notification', 1);
49         $this->send_fake_message($sender, $recipient, 'Notification', 1);
50         $this->send_fake_message($sender, $recipient, 'Notification', 1);
51         $this->send_fake_message($sender, $recipient);
52         $this->send_fake_message($sender, $recipient);
53         $this->send_fake_message($sender, $recipient);
55         \core_message\api::mark_all_read_for_user($recipient->id);
56         $this->assertDebuggingCalled();
57         $this->assertEquals(message_count_unread_messages($recipient), 0);
58     }
60     public function test_mark_all_read_for_user_touser_with_fromuser() {
61         $sender1 = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
62         $sender2 = $this->getDataGenerator()->create_user(array('firstname' => 'Test3', 'lastname' => 'User3'));
63         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
65         $this->send_fake_message($sender1, $recipient, 'Notification', 1);
66         $this->send_fake_message($sender1, $recipient, 'Notification', 1);
67         $this->send_fake_message($sender1, $recipient, 'Notification', 1);
68         $this->send_fake_message($sender1, $recipient);
69         $this->send_fake_message($sender1, $recipient);
70         $this->send_fake_message($sender1, $recipient);
71         $this->send_fake_message($sender2, $recipient, 'Notification', 1);
72         $this->send_fake_message($sender2, $recipient, 'Notification', 1);
73         $this->send_fake_message($sender2, $recipient, 'Notification', 1);
74         $this->send_fake_message($sender2, $recipient);
75         $this->send_fake_message($sender2, $recipient);
76         $this->send_fake_message($sender2, $recipient);
78         \core_message\api::mark_all_read_for_user($recipient->id, $sender1->id);
79         $this->assertDebuggingCalled();
80         $this->assertEquals(message_count_unread_messages($recipient), 3);
81     }
83     public function test_mark_all_read_for_user_touser_with_type() {
84         $sender = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
85         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
87         $this->send_fake_message($sender, $recipient, 'Notification', 1);
88         $this->send_fake_message($sender, $recipient, 'Notification', 1);
89         $this->send_fake_message($sender, $recipient, 'Notification', 1);
90         $this->send_fake_message($sender, $recipient);
91         $this->send_fake_message($sender, $recipient);
92         $this->send_fake_message($sender, $recipient);
94         \core_message\api::mark_all_read_for_user($recipient->id, 0, MESSAGE_TYPE_NOTIFICATION);
95         $this->assertDebuggingCalled();
96         $this->assertEquals(message_count_unread_messages($recipient), 3);
98         \core_message\api::mark_all_read_for_user($recipient->id, 0, MESSAGE_TYPE_MESSAGE);
99         $this->assertDebuggingCalled();
100         $this->assertEquals(message_count_unread_messages($recipient), 0);
101     }
103     /**
104      * Test count_blocked_users.
105      */
106     public function test_count_blocked_users() {
107         global $USER;
109         // Set this user as the admin.
110         $this->setAdminUser();
112         // Create user to add to the admin's block list.
113         $user1 = $this->getDataGenerator()->create_user();
114         $user2 = $this->getDataGenerator()->create_user();
116         $this->assertEquals(0, \core_message\api::count_blocked_users());
118         // Add 1 blocked user to admin's blocked user list.
119         \core_message\api::block_user($USER->id, $user1->id);
121         $this->assertEquals(0, \core_message\api::count_blocked_users($user1));
122         $this->assertEquals(1, \core_message\api::count_blocked_users());
123     }
125     /**
126      * Tests searching users in a course.
127      */
128     public function test_search_users_in_course() {
129         // Create some users.
130         $user1 = new stdClass();
131         $user1->firstname = 'User';
132         $user1->lastname = 'One';
133         $user1 = self::getDataGenerator()->create_user($user1);
135         // The person doing the search.
136         $this->setUser($user1);
138         // Second user is going to have their last access set to now, so they are online.
139         $user2 = new stdClass();
140         $user2->firstname = 'User';
141         $user2->lastname = 'Two';
142         $user2->lastaccess = time();
143         $user2 = self::getDataGenerator()->create_user($user2);
145         // Block the second user.
146         \core_message\api::block_user($user1->id, $user2->id);
148         $user3 = new stdClass();
149         $user3->firstname = 'User';
150         $user3->lastname = 'Three';
151         $user3 = self::getDataGenerator()->create_user($user3);
153         // Create a course.
154         $course1 = new stdClass();
155         $course1->fullname = 'Course';
156         $course1->shortname = 'One';
157         $course1 = $this->getDataGenerator()->create_course($course1);
159         // Enrol the searcher and one user in the course.
160         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
161         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
163         // Perform a search.
164         $results = \core_message\api::search_users_in_course($user1->id, $course1->id, 'User');
166         $this->assertEquals(1, count($results));
168         $user = $results[0];
169         $this->assertEquals($user2->id, $user->userid);
170         $this->assertEquals(fullname($user2), $user->fullname);
171         $this->assertFalse($user->ismessaging);
172         $this->assertNull($user->lastmessage);
173         $this->assertNull($user->messageid);
174         $this->assertNull($user->isonline);
175         $this->assertFalse($user->isread);
176         $this->assertTrue($user->isblocked);
177         $this->assertNull($user->unreadcount);
178     }
180     /**
181      * Tests searching users.
182      */
183     public function test_search_users() {
184         global $DB;
186         // Create some users.
187         $user1 = new stdClass();
188         $user1->firstname = 'User';
189         $user1->lastname = 'One';
190         $user1 = self::getDataGenerator()->create_user($user1);
192         // Set as the user performing the search.
193         $this->setUser($user1);
195         $user2 = new stdClass();
196         $user2->firstname = 'User search';
197         $user2->lastname = 'Two';
198         $user2 = self::getDataGenerator()->create_user($user2);
200         $user3 = new stdClass();
201         $user3->firstname = 'User search';
202         $user3->lastname = 'Three';
203         $user3 = self::getDataGenerator()->create_user($user3);
205         $user4 = new stdClass();
206         $user4->firstname = 'User';
207         $user4->lastname = 'Four';
208         $user4 = self::getDataGenerator()->create_user($user4);
210         $user5 = new stdClass();
211         $user5->firstname = 'User search';
212         $user5->lastname = 'Five';
213         $user5 = self::getDataGenerator()->create_user($user5);
215         $user6 = new stdClass();
216         $user6->firstname = 'User';
217         $user6->lastname = 'Six';
218         $user6 = self::getDataGenerator()->create_user($user6);
220         // Create some courses.
221         $course1 = new stdClass();
222         $course1->fullname = 'Course search';
223         $course1->shortname = 'One';
224         $course1 = $this->getDataGenerator()->create_course($course1);
226         $course2 = new stdClass();
227         $course2->fullname = 'Course';
228         $course2->shortname = 'Two';
229         $course2 = $this->getDataGenerator()->create_course($course2);
231         $course3 = new stdClass();
232         $course3->fullname = 'Course';
233         $course3->shortname = 'Three search';
234         $course3 = $this->getDataGenerator()->create_course($course3);
236         $course4 = new stdClass();
237         $course4->fullname = 'Course Four';
238         $course4->shortname = 'CF100';
239         $course4 = $this->getDataGenerator()->create_course($course4);
241         $course5 = new stdClass();
242         $course5->fullname = 'Course';
243         $course5->shortname = 'Five search';
244         $course5 = $this->getDataGenerator()->create_course($course5);
246         $role = $DB->get_record('role', ['shortname' => 'student']);
247         $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $role->id);
248         $this->getDataGenerator()->enrol_user($user1->id, $course2->id, $role->id);
249         $this->getDataGenerator()->enrol_user($user1->id, $course3->id, $role->id);
250         $this->getDataGenerator()->enrol_user($user1->id, $course5->id, $role->id);
252         // Add some users as contacts.
253         \core_message\api::add_contact($user1->id, $user2->id);
254         \core_message\api::add_contact($user1->id, $user3->id);
255         \core_message\api::add_contact($user1->id, $user4->id);
257         // Remove the viewparticipants capability from one of the courses.
258         $course5context = context_course::instance($course5->id);
259         assign_capability('moodle/course:viewparticipants', CAP_PROHIBIT, $role->id, $course5context->id);
261         // Perform a search $CFG->messagingallusers setting enabled.
262         set_config('messagingallusers', 1);
263         list($contacts, $courses, $noncontacts) = \core_message\api::search_users($user1->id, 'search');
265         // Check that we retrieved the correct contacts.
266         $this->assertEquals(2, count($contacts));
267         $this->assertEquals($user3->id, $contacts[0]->userid);
268         $this->assertEquals($user2->id, $contacts[1]->userid);
270         // Check that we retrieved the correct courses.
271         $this->assertEquals(2, count($courses));
272         $this->assertEquals($course3->id, $courses[0]->id);
273         $this->assertEquals($course1->id, $courses[1]->id);
275         // Check that we retrieved the correct non-contacts.
276         $this->assertEquals(1, count($noncontacts));
277         $this->assertEquals($user5->id, $noncontacts[0]->userid);
278     }
280     /**
281      * Tests searching users with empty result.
282      */
283     public function test_search_users_with_empty_result() {
285         // Create some users.
286         $user1 = new stdClass();
287         $user1->firstname = 'User';
288         $user1->lastname = 'One';
289         $user1 = self::getDataGenerator()->create_user($user1);
291         // Set as the user performing the search.
292         $this->setUser($user1);
294         $user2 = new stdClass();
295         $user2->firstname = 'User';
296         $user2->lastname = 'Two';
297         $user2 = self::getDataGenerator()->create_user($user2);
299         // Perform a search $CFG->messagingallusers setting enabled.
300         set_config('messagingallusers', 1);
301         list($contacts, $courses, $noncontacts) = \core_message\api::search_users($user1->id, 'search');
303         // Check results are empty.
304         $this->assertEquals(0, count($contacts));
305         $this->assertEquals(0, count($courses));
306         $this->assertEquals(0, count($noncontacts));
307     }
309     /**
310      * Tests searching for users when site-wide messaging is disabled.
311      *
312      * This test verifies that any contacts are returned, as well as any non-contacts whose profile we can view.
313      * If checks this by placing some users in the same course, where default caps would permit a user to view another user's
314      * profile.
315      */
316     public function test_message_search_users_messagingallusers_disabled() {
317         $this->resetAfterTest();
319         // Create some users.
320         $users = [];
321         foreach (range(1, 7) as $i) {
322             $user = new stdClass();
323             $user->firstname = ($i == 4) ? 'User' : 'User search'; // Ensure the fourth user won't match the search term.
324             $user->lastname = $i;
325             $user = $this->getDataGenerator()->create_user($user);
326             $users[$i] = $user;
327         }
329         // Enrol a few users in the same course, but leave them as non-contacts.
330         $course1 = $this->getDataGenerator()->create_course();
331         $this->setAdminUser();
332         $this->getDataGenerator()->enrol_user($users[1]->id, $course1->id);
333         $this->getDataGenerator()->enrol_user($users[6]->id, $course1->id);
334         $this->getDataGenerator()->enrol_user($users[7]->id, $course1->id);
336         // Add some other users as contacts.
337         \core_message\api::add_contact($users[1]->id, $users[2]->id);
338         \core_message\api::add_contact($users[3]->id, $users[1]->id);
339         \core_message\api::add_contact($users[1]->id, $users[4]->id);
341         // Create individual conversations between some users, one contact and one non-contact.
342         $ic1 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
343             [$users[1]->id, $users[2]->id]);
344         $ic2 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
345             [$users[6]->id, $users[1]->id]);
347         // Create a group conversation between 4 users, including a contact and a non-contact.
348         $gc1 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
349             [$users[1]->id, $users[2]->id, $users[4]->id, $users[7]->id], 'Project chat');
351         // Set as the user performing the search.
352         $this->setUser($users[1]);
354         // Perform a search with $CFG->messagingallusers disabled.
355         set_config('messagingallusers', 0);
356         $result = \core_message\api::message_search_users($users[1]->id, 'search');
358         // Confirm that we returns contacts and non-contacts.
359         $this->assertArrayHasKey(0, $result);
360         $this->assertArrayHasKey(1, $result);
361         $contacts = $result[0];
362         $noncontacts = $result[1];
364         // Check that we retrieved the correct contacts.
365         $this->assertCount(2, $contacts);
366         $this->assertEquals($users[2]->id, $contacts[0]->id);
367         $this->assertEquals($users[3]->id, $contacts[1]->id);
369         // Verify the correct conversations were returned for the contacts.
370         $this->assertCount(2, $contacts[0]->conversations);
371         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $contacts[0]->conversations[$gc1->id]->type);
372         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $contacts[0]->conversations[$ic1->id]->type);
374         $this->assertCount(0, $contacts[1]->conversations);
376         // Check that we retrieved the correct non-contacts.
377         // When site wide messaging is disabled, we expect to see only those users whose profiles we can view.
378         $this->assertCount(2, $noncontacts);
379         $this->assertEquals($users[6]->id, $noncontacts[0]->id);
380         $this->assertEquals($users[7]->id, $noncontacts[1]->id);
382         // Verify the correct conversations were returned for the non-contacts.
383         $this->assertCount(1, $noncontacts[0]->conversations);
384         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
385             $noncontacts[0]->conversations[$ic2->id]->type);
387         $this->assertCount(1, $noncontacts[1]->conversations);
388         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $noncontacts[1]->conversations[$gc1->id]->type);
389     }
391     /**
392      * Tests searching for users when site-wide messaging is enabled.
393      *
394      * This test verifies that any contacts are returned, as well as any non-contacts, regardless of whether the searching user
395      * can view their respective profile.
396      */
397     public function test_message_search_users_messagingallusers_enabled() {
398         $this->resetAfterTest();
400         // Create some users.
401         $users = [];
402         foreach (range(1, 8) as $i) {
403             $user = new stdClass();
404             $user->firstname = ($i == 4) ? 'User' : 'User search'; // Ensure the fourth user won't match the search term.
405             $user->lastname = $i;
406             $user = $this->getDataGenerator()->create_user($user);
407             $users[$i] = $user;
408         }
410         // Enrol a few users in the same course, but leave them as non-contacts.
411         $course1 = $this->getDataGenerator()->create_course();
412         $this->setAdminUser();
413         $this->getDataGenerator()->enrol_user($users[1]->id, $course1->id);
414         $this->getDataGenerator()->enrol_user($users[6]->id, $course1->id);
415         $this->getDataGenerator()->enrol_user($users[7]->id, $course1->id);
417         // Add some other users as contacts.
418         \core_message\api::add_contact($users[1]->id, $users[2]->id);
419         \core_message\api::add_contact($users[3]->id, $users[1]->id);
420         \core_message\api::add_contact($users[1]->id, $users[4]->id);
422         // Create individual conversations between some users, one contact and one non-contact.
423         $ic1 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
424             [$users[1]->id, $users[2]->id]);
425         $ic2 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
426             [$users[6]->id, $users[1]->id]);
428         // Create a group conversation between 5 users, including a contact and a non-contact, and a user NOT in a shared course.
429         $gc1 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
430             [$users[1]->id, $users[2]->id, $users[4]->id, $users[7]->id, $users[8]->id], 'Project chat');
432         // Set as the user performing the search.
433         $this->setUser($users[1]);
435         // Perform a search with $CFG->messagingallusers enabled.
436         set_config('messagingallusers', 1);
437         $result = \core_message\api::message_search_users($users[1]->id, 'search');
439         // Confirm that we returns contacts and non-contacts.
440         $this->assertArrayHasKey(0, $result);
441         $this->assertArrayHasKey(1, $result);
442         $contacts = $result[0];
443         $noncontacts = $result[1];
445         // Check that we retrieved the correct contacts.
446         $this->assertCount(2, $contacts);
447         $this->assertEquals($users[2]->id, $contacts[0]->id);
448         $this->assertEquals($users[3]->id, $contacts[1]->id);
450         // Verify the correct conversations were returned for the contacts.
451         $this->assertCount(2, $contacts[0]->conversations);
452         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $contacts[0]->conversations[$gc1->id]->type);
453         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $contacts[0]->conversations[$ic1->id]->type);
455         $this->assertCount(0, $contacts[1]->conversations);
457         // Check that we retrieved the correct non-contacts.
458         // If site wide messaging is enabled, we expect to be able to search for any users.
459         $this->assertCount(4, $noncontacts);
460         $this->assertEquals($users[5]->id, $noncontacts[0]->id);
461         $this->assertEquals($users[6]->id, $noncontacts[1]->id);
462         $this->assertEquals($users[7]->id, $noncontacts[2]->id);
463         $this->assertEquals($users[8]->id, $noncontacts[3]->id);
465         // Verify the correct conversations were returned for the non-contacts.
466         $this->assertCount(0, $noncontacts[0]->conversations);
468         $this->assertCount(1, $noncontacts[1]->conversations);
469         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
470             $noncontacts[1]->conversations[$ic2->id]->type);
472         $this->assertCount(1, $noncontacts[2]->conversations);
473         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $noncontacts[2]->conversations[$gc1->id]->type);
475         $this->assertCount(1, $noncontacts[3]->conversations);
476         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $noncontacts[3]->conversations[$gc1->id]->type);
477     }
479     /**
480      * Verify searching for users works even if no matching users from either contacts, or non-contacts can be found.
481      */
482     public function test_message_search_users_with_empty_result() {
483         $this->resetAfterTest();
485         // Create some users, but make sure neither will match the search term.
486         $user1 = new stdClass();
487         $user1->firstname = 'User';
488         $user1->lastname = 'One';
489         $user1 = $this->getDataGenerator()->create_user($user1);
490         $user2 = new stdClass();
491         $user2->firstname = 'User';
492         $user2->lastname = 'Two';
493         $user2 = $this->getDataGenerator()->create_user($user2);
495         // Perform a search as user1.
496         $this->setUser($user1);
497         $result = \core_message\api::message_search_users($user1->id, 'search');
499         // Check results are empty.
500         $this->assertCount(0, $result[0]);
501         $this->assertCount(0, $result[1]);
502     }
504     /**
505      * Test verifying that limits and offsets work for both the contacts and non-contacts return data.
506      */
507     public function test_message_search_users_limit_offset() {
508         $this->resetAfterTest();
510         // Create 20 users.
511         $users = [];
512         foreach (range(1, 20) as $i) {
513             $user = new stdClass();
514             $user->firstname = "User search";
515             $user->lastname = $i;
516             $user = $this->getDataGenerator()->create_user($user);
517             $users[$i] = $user;
518         }
520         // Enrol the first 9 users in the same course, but leave them as non-contacts.
521         $this->setAdminUser();
522         $course1 = $this->getDataGenerator()->create_course();
523         foreach (range(1, 9) as $i) {
524             $this->getDataGenerator()->enrol_user($users[$i]->id, $course1->id);
525         }
527         // Add 5 users, starting at the 11th user, as contacts for user1.
528         foreach (range(11, 15) as $i) {
529             \core_message\api::add_contact($users[1]->id, $users[$i]->id);
530         }
532         // Set as the user performing the search.
533         $this->setUser($users[1]);
535         // Search using a limit of 3.
536         // This tests the case where we have more results than the limit for both contacts and non-contacts.
537         $result = \core_message\api::message_search_users($users[1]->id, 'search', 0, 3);
538         $contacts = $result[0];
539         $noncontacts = $result[1];
541         // Check that we retrieved the correct contacts.
542         $this->assertCount(3, $contacts);
543         $this->assertEquals($users[11]->id, $contacts[0]->id);
544         $this->assertEquals($users[12]->id, $contacts[1]->id);
545         $this->assertEquals($users[13]->id, $contacts[2]->id);
547         // Check that we retrieved the correct non-contacts.
548         $this->assertCount(3, $noncontacts);
549         $this->assertEquals($users[2]->id, $noncontacts[0]->id);
550         $this->assertEquals($users[3]->id, $noncontacts[1]->id);
551         $this->assertEquals($users[4]->id, $noncontacts[2]->id);
553         // Now, offset to get the next batch of results.
554         // We expect to see 2 contacts, and 3 non-contacts.
555         $result = \core_message\api::message_search_users($users[1]->id, 'search', 3, 3);
556         $contacts = $result[0];
557         $noncontacts = $result[1];
558         $this->assertCount(2, $contacts);
559         $this->assertEquals($users[14]->id, $contacts[0]->id);
560         $this->assertEquals($users[15]->id, $contacts[1]->id);
562         $this->assertCount(3, $noncontacts);
563         $this->assertEquals($users[5]->id, $noncontacts[0]->id);
564         $this->assertEquals($users[6]->id, $noncontacts[1]->id);
565         $this->assertEquals($users[7]->id, $noncontacts[2]->id);
567         // Now, offset to get the next batch of results.
568         // We expect to see 0 contacts, and 2 non-contacts.
569         $result = \core_message\api::message_search_users($users[1]->id, 'search', 6, 3);
570         $contacts = $result[0];
571         $noncontacts = $result[1];
572         $this->assertCount(0, $contacts);
574         $this->assertCount(2, $noncontacts);
575         $this->assertEquals($users[8]->id, $noncontacts[0]->id);
576         $this->assertEquals($users[9]->id, $noncontacts[1]->id);
577     }
579     /**
580      * Tests searching users as a user having the 'moodle/user:viewdetails' capability.
581      */
582     public function test_message_search_users_with_cap() {
583         $this->resetAfterTest();
584         global $DB;
586         // Create some users.
587         $users = [];
588         foreach (range(1, 8) as $i) {
589             $user = new stdClass();
590             $user->firstname = ($i == 4) ? 'User' : 'User search'; // Ensure the fourth user won't match the search term.
591             $user->lastname = $i;
592             $user = $this->getDataGenerator()->create_user($user);
593             $users[$i] = $user;
594         }
596         // Enrol a few users in the same course, but leave them as non-contacts.
597         $course1 = $this->getDataGenerator()->create_course();
598         $this->setAdminUser();
599         $this->getDataGenerator()->enrol_user($users[1]->id, $course1->id);
600         $this->getDataGenerator()->enrol_user($users[6]->id, $course1->id);
601         $this->getDataGenerator()->enrol_user($users[7]->id, $course1->id);
603         // Add some other users as contacts.
604         \core_message\api::add_contact($users[1]->id, $users[2]->id);
605         \core_message\api::add_contact($users[3]->id, $users[1]->id);
606         \core_message\api::add_contact($users[1]->id, $users[4]->id);
608         // Set as the user performing the search.
609         $this->setUser($users[1]);
611         // Grant the authenticated user role the capability 'user:viewdetails' at site context.
612         $authenticatedrole = $DB->get_record('role', ['shortname' => 'user'], '*', MUST_EXIST);
613         assign_capability('moodle/user:viewdetails', CAP_ALLOW, $authenticatedrole->id, context_system::instance());
615         // Perform a search with $CFG->messagingallusers disabled.
616         set_config('messagingallusers', 0);
617         $result = \core_message\api::message_search_users($users[1]->id, 'search');
618         $contacts = $result[0];
619         $noncontacts = $result[1];
621         // Check that we retrieved the correct contacts.
622         $this->assertCount(2, $contacts);
623         $this->assertEquals($users[2]->id, $contacts[0]->id);
624         $this->assertEquals($users[3]->id, $contacts[1]->id);
626         // Check that we retrieved the correct non-contacts.
627         // Site-wide messaging is disabled, but since we can see all users, we expect to be able to search for any users.
628         $this->assertCount(4, $noncontacts);
629         $this->assertEquals($users[5]->id, $noncontacts[0]->id);
630         $this->assertEquals($users[6]->id, $noncontacts[1]->id);
631         $this->assertEquals($users[7]->id, $noncontacts[2]->id);
632         $this->assertEquals($users[8]->id, $noncontacts[3]->id);
633     }
635     /**
636      * Tests searching users with messaging disabled.
637      */
638     public function test_message_search_users_messaging_disabled() {
639         $this->resetAfterTest();
641         // Create a user.
642         $user = $this->getDataGenerator()->create_user();
644         // Disable messaging.
645         set_config('messaging', 0);
647         // Ensure an exception is thrown.
648         $this->expectException('moodle_exception');
649         \core_message\api::message_search_users($user->id, 'User');
650     }
652     /**
653      * Tests getting conversations between 2 users.
654      */
655     public function test_get_conversations_between_users() {
656         // Create some users.
657         $user1 = new stdClass();
658         $user1->firstname = 'User';
659         $user1->lastname = 'One';
660         $user1 = self::getDataGenerator()->create_user($user1);
662         $user2 = new stdClass();
663         $user2->firstname = 'User';
664         $user2->lastname = 'Two';
665         $user2 = self::getDataGenerator()->create_user($user2);
667         $user3 = new stdClass();
668         $user3->firstname = 'User search';
669         $user3->lastname = 'Three';
670         $user3 = self::getDataGenerator()->create_user($user3);
672         $user4 = new stdClass();
673         $user4->firstname = 'User';
674         $user4->lastname = 'Four';
675         $user4 = self::getDataGenerator()->create_user($user4);
677         $user5 = new stdClass();
678         $user5->firstname = 'User';
679         $user5->lastname = 'Five';
680         $user5 = self::getDataGenerator()->create_user($user5);
682         $user6 = new stdClass();
683         $user6->firstname = 'User search';
684         $user6->lastname = 'Six';
685         $user6 = self::getDataGenerator()->create_user($user6);
687         // Add some users as contacts.
688         \core_message\api::add_contact($user1->id, $user2->id);
689         \core_message\api::add_contact($user6->id, $user1->id);
691         // Create private conversations with some users.
692         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
693             array($user1->id, $user2->id));
694         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
695             array($user3->id, $user1->id));
697         // Create a group conversation with users.
698         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
699             array($user1->id, $user2->id, $user3->id, $user4->id),
700             'Project chat');
702         // Check that we retrieved the correct conversations.
703         $this->assertCount(2, \core_message\api::get_conversations_between_users($user1->id, $user2->id));
704         $this->assertCount(2, \core_message\api::get_conversations_between_users($user2->id, $user1->id));
705         $this->assertCount(2, \core_message\api::get_conversations_between_users($user1->id, $user3->id));
706         $this->assertCount(2, \core_message\api::get_conversations_between_users($user3->id, $user1->id));
707         $this->assertCount(1, \core_message\api::get_conversations_between_users($user1->id, $user4->id));
708         $this->assertCount(1, \core_message\api::get_conversations_between_users($user4->id, $user1->id));
709         $this->assertCount(0, \core_message\api::get_conversations_between_users($user1->id, $user5->id));
710         $this->assertCount(0, \core_message\api::get_conversations_between_users($user5->id, $user1->id));
711         $this->assertCount(0, \core_message\api::get_conversations_between_users($user1->id, $user6->id));
712         $this->assertCount(0, \core_message\api::get_conversations_between_users($user6->id, $user1->id));
713     }
715     /**
716      * Tests searching messages.
717      */
718     public function test_search_messages() {
719         // Create some users.
720         $user1 = self::getDataGenerator()->create_user();
721         $user2 = self::getDataGenerator()->create_user();
722         $user3 = self::getDataGenerator()->create_user();
724         // The person doing the search.
725         $this->setUser($user1);
727         // Send some messages back and forth.
728         $time = 1;
729         $this->send_fake_message($user3, $user1, 'Don\'t block me.', 0, $time);
730         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
731         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
732         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
733         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
735         $convid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
736         $conv2id = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
738         // Block user 3.
739         \core_message\api::block_user($user1->id, $user3->id);
741         // Perform a search.
742         $messages = \core_message\api::search_messages($user1->id, 'o');
744         // Confirm the data is correct.
745         $this->assertEquals(3, count($messages));
747         $message1 = $messages[0];
748         $message2 = $messages[1];
749         $message3 = $messages[2];
751         $this->assertEquals($user2->id, $message1->userid);
752         $this->assertEquals($user2->id, $message1->useridfrom);
753         $this->assertEquals(fullname($user2), $message1->fullname);
754         $this->assertTrue($message1->ismessaging);
755         $this->assertEquals('Word.', $message1->lastmessage);
756         $this->assertNotEmpty($message1->messageid);
757         $this->assertNull($message1->isonline);
758         $this->assertFalse($message1->isread);
759         $this->assertFalse($message1->isblocked);
760         $this->assertNull($message1->unreadcount);
761         $this->assertEquals($convid, $message1->conversationid);
763         $this->assertEquals($user2->id, $message2->userid);
764         $this->assertEquals($user1->id, $message2->useridfrom);
765         $this->assertEquals(fullname($user2), $message2->fullname);
766         $this->assertTrue($message2->ismessaging);
767         $this->assertEquals('Yo!', $message2->lastmessage);
768         $this->assertNotEmpty($message2->messageid);
769         $this->assertNull($message2->isonline);
770         $this->assertTrue($message2->isread);
771         $this->assertFalse($message2->isblocked);
772         $this->assertNull($message2->unreadcount);
773         $this->assertEquals($convid, $message2->conversationid);
775         $this->assertEquals($user3->id, $message3->userid);
776         $this->assertEquals($user3->id, $message3->useridfrom);
777         $this->assertEquals(fullname($user3), $message3->fullname);
778         $this->assertTrue($message3->ismessaging);
779         $this->assertEquals('Don\'t block me.', $message3->lastmessage);
780         $this->assertNotEmpty($message3->messageid);
781         $this->assertNull($message3->isonline);
782         $this->assertFalse($message3->isread);
783         $this->assertTrue($message3->isblocked);
784         $this->assertNull($message3->unreadcount);
785         $this->assertEquals($conv2id, $message3->conversationid);
786     }
788     /**
789      * Test verifying that favourited conversations can be retrieved.
790      */
791     public function test_get_favourite_conversations() {
792         // Create some users.
793         $user1 = self::getDataGenerator()->create_user();
794         $user2 = self::getDataGenerator()->create_user();
795         $user3 = self::getDataGenerator()->create_user();
796         $user4 = self::getDataGenerator()->create_user();
798         // The person doing the search.
799         $this->setUser($user1);
801         // No conversations yet.
802         $this->assertEquals([], \core_message\api::get_conversations($user1->id));
804         // Create some conversations for user1.
805         $time = 1;
806         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
807         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
808         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
809         $messageid1 = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
811         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
812         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
813         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
814         $messageid2 = $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
816         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 9);
817         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 10);
818         $messageid3 = $this->send_fake_message($user1, $user4, 'Dope.', 0, $time + 11);
820         // Favourite the first 2 conversations for user1.
821         $convoids = [];
822         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
823         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
824         $user1context = context_user::instance($user1->id);
825         $service = \core_favourites\service_factory::get_service_for_user_context($user1context);
826         foreach ($convoids as $convoid) {
827             $service->create_favourite('core_message', 'message_conversations', $convoid, $user1context);
828         }
830         // We should have 3 conversations.
831         $this->assertCount(3, \core_message\api::get_conversations($user1->id));
833         // And 2 favourited conversations.
834         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, true);
835         $this->assertCount(2, $conversations);
836     }
838     /**
839      * Tests retrieving favourite conversations with a limit and offset to ensure pagination works correctly.
840      */
841     public function test_get_favourite_conversations_limit_offset() {
842         // Create some users.
843         $user1 = self::getDataGenerator()->create_user();
844         $user2 = self::getDataGenerator()->create_user();
845         $user3 = self::getDataGenerator()->create_user();
846         $user4 = self::getDataGenerator()->create_user();
848         // The person doing the search.
849         $this->setUser($user1);
851         // No conversations yet.
852         $this->assertEquals([], \core_message\api::get_conversations($user1->id));
854         // Create some conversations for user1.
855         $time = 1;
856         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
857         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
858         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
859         $messageid1 = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
861         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
862         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
863         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
864         $messageid2 = $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
866         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 9);
867         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 10);
868         $messageid3 = $this->send_fake_message($user1, $user4, 'Dope.', 0, $time + 11);
870         // Favourite the all conversations for user1.
871         $convoids = [];
872         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
873         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
874         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user4->id]);
875         $user1context = context_user::instance($user1->id);
876         $service = \core_favourites\service_factory::get_service_for_user_context($user1context);
877         foreach ($convoids as $convoid) {
878             $service->create_favourite('core_message', 'message_conversations', $convoid, $user1context);
879         }
881         // Get all records, using offset 0 and large limit.
882         $this->assertCount(2, \core_message\api::get_conversations($user1->id, 1, 10, null, true));
884         // Now, get 10 conversations starting at the second record. We should see 2 conversations.
885         $this->assertCount(2, \core_message\api::get_conversations($user1->id, 1, 10, null, true));
887         // Now, try to get favourited conversations using an invalid offset.
888         $this->assertCount(0, \core_message\api::get_conversations($user1->id, 4, 10, null, true));
889     }
891     /**
892      * Tests retrieving favourite conversations when a conversation contains a deleted user.
893      */
894     public function test_get_favourite_conversations_with_deleted_user() {
895         // Create some users.
896         $user1 = self::getDataGenerator()->create_user();
897         $user2 = self::getDataGenerator()->create_user();
898         $user3 = self::getDataGenerator()->create_user();
900         // Send some messages back and forth, have some different conversations with different users.
901         $time = 1;
902         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
903         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
904         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
905         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
907         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
908         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
909         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
910         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
912         // Favourite the all conversations for user1.
913         $convoids = [];
914         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
915         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
916         $user1context = context_user::instance($user1->id);
917         $service = \core_favourites\service_factory::get_service_for_user_context($user1context);
918         foreach ($convoids as $convoid) {
919             $service->create_favourite('core_message', 'message_conversations', $convoid, $user1context);
920         }
922         // Delete the second user.
923         delete_user($user2);
925         // Retrieve the conversations.
926         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, true);
928         // We should have both conversations, despite the other user being soft-deleted.
929         $this->assertCount(2, $conversations);
931         // Confirm the conversation is from the non-deleted user.
932         $conversation = reset($conversations);
933         $this->assertEquals($convoids[1], $conversation->id);
934     }
936     /**
937      * Test confirming that conversations can be marked as favourites.
938      */
939     public function test_set_favourite_conversation() {
940         // Create some users.
941         $user1 = self::getDataGenerator()->create_user();
942         $user2 = self::getDataGenerator()->create_user();
943         $user3 = self::getDataGenerator()->create_user();
945         // Send some messages back and forth, have some different conversations with different users.
946         $time = 1;
947         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
948         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
949         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
950         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
952         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
953         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
954         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
955         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
957         // Favourite the first conversation as user 1.
958         $conversationid1 = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
959         $favourite = \core_message\api::set_favourite_conversation($conversationid1, $user1->id);
961         // Verify we have a single favourite conversation a user 1.
962         $this->assertCount(1, \core_message\api::get_conversations($user1->id, 0, 20, null, true));
964         // Verify we have no favourites as user2, despite being a member in that conversation.
965         $this->assertCount(0, \core_message\api::get_conversations($user2->id, 0, 20, null, true));
967         // Try to favourite the same conversation again should just return the existing favourite.
968         $repeatresult = \core_message\api::set_favourite_conversation($conversationid1, $user1->id);
969         $this->assertEquals($favourite->id, $repeatresult->id);
970     }
972     /**
973      * Test verifying that trying to mark a non-existent conversation as a favourite, results in an exception.
974      */
975     public function test_set_favourite_conversation_nonexistent_conversation() {
976         // Create some users.
977         $user1 = self::getDataGenerator()->create_user();
978         // Try to favourite a non-existent conversation.
979         $this->expectException(\moodle_exception::class);
980         \core_message\api::set_favourite_conversation(0, $user1->id);
981     }
983     /**
984      * Test verifying that a conversation cannot be marked as favourite unless the user is a member of that conversation.
985      */
986     public function test_set_favourite_conversation_non_member() {
987         // Create some users.
988         $user1 = self::getDataGenerator()->create_user();
989         $user2 = self::getDataGenerator()->create_user();
990         $user3 = self::getDataGenerator()->create_user();
992         // Send some messages back and forth, have some different conversations with different users.
993         $time = 1;
994         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
995         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
996         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
997         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
999         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
1000         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
1001         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
1002         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
1004         // Try to favourite the first conversation as user 3, who is not a member.
1005         $conversationid1 = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
1006         $this->expectException(\moodle_exception::class);
1007         \core_message\api::set_favourite_conversation($conversationid1, $user3->id);
1008     }
1010     /**
1011      * Test confirming that those conversations marked as favourites can be unfavourited.
1012      */
1013     public function test_unset_favourite_conversation() {
1014         // Create some users.
1015         $user1 = self::getDataGenerator()->create_user();
1016         $user2 = self::getDataGenerator()->create_user();
1017         $user3 = self::getDataGenerator()->create_user();
1019         // Send some messages back and forth, have some different conversations with different users.
1020         $time = 1;
1021         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
1022         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
1023         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
1024         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
1026         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
1027         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
1028         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
1029         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
1031         // Favourite the first conversation as user 1 and the second as user 3.
1032         $conversationid1 = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
1033         $conversationid2 = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
1034         \core_message\api::set_favourite_conversation($conversationid1, $user1->id);
1035         \core_message\api::set_favourite_conversation($conversationid2, $user3->id);
1037         // Verify we have a single favourite conversation for both user 1 and user 3.
1038         $this->assertCount(1, \core_message\api::get_conversations($user1->id, 0, 20, null, true));
1039         $this->assertCount(1, \core_message\api::get_conversations($user3->id, 0, 20, null, true));
1041         // Now unfavourite the conversation as user 1.
1042         \core_message\api::unset_favourite_conversation($conversationid1, $user1->id);
1044         // Verify we have a single favourite conversation user 3 only, and none for user1.
1045         $this->assertCount(1, \core_message\api::get_conversations($user3->id, 0, 20, null, true));
1046         $this->assertCount(0, \core_message\api::get_conversations($user1->id, 0, 20, null, true));
1048         // Try to favourite the same conversation again as user 1.
1049         $this->expectException(\moodle_exception::class);
1050         \core_message\api::unset_favourite_conversation($conversationid1, $user1->id);
1051     }
1053     /**
1054      * Test verifying that a valid conversation cannot be unset as a favourite if it's not marked as a favourite.
1055      */
1056     public function test_unset_favourite_conversation_not_favourite() {
1057         // Create some users.
1058         $user1 = self::getDataGenerator()->create_user();
1059         $user2 = self::getDataGenerator()->create_user();
1061         // Send some messages back and forth, have some different conversations with different users.
1062         $time = 1;
1063         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
1064         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
1065         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
1066         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
1068         // Now try to unfavourite the conversation as user 1.
1069         $conversationid1 = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
1070         $this->expectException(\moodle_exception::class);
1071         \core_message\api::unset_favourite_conversation($conversationid1, $user1->id);
1072     }
1074     /**
1075      * Test verifying that a non-existent conversation cannot be unset as a favourite.
1076      */
1077     public function test_unset_favourite_conversation_non_existent_conversation() {
1078         // Create some users.
1079         $user1 = self::getDataGenerator()->create_user();
1081         // Now try to unfavourite the conversation as user 1.
1082         $this->expectException(\moodle_exception::class);
1083         \core_message\api::unset_favourite_conversation(0, $user1->id);
1084     }
1086     /**
1087      * Helper to seed the database with initial state.
1088      */
1089     protected function create_conversation_test_data() {
1090         // Create some users.
1091         $user1 = self::getDataGenerator()->create_user();
1092         $user2 = self::getDataGenerator()->create_user();
1093         $user3 = self::getDataGenerator()->create_user();
1094         $user4 = self::getDataGenerator()->create_user();
1096         $time = 1;
1098         // Create some conversations. We want:
1099         // 1) At least one of each type (group, individual) of which user1 IS a member and DID send the most recent message.
1100         // 2) At least one of each type (group, individual) of which user1 IS a member and DID NOT send the most recent message.
1101         // 3) At least one of each type (group, individual) of which user1 IS NOT a member.
1102         // 4) At least two group conversation having 0 messages, of which user1 IS a member (To confirm conversationid ordering).
1103         // 5) At least one group conversation having 0 messages, of which user1 IS NOT a member.
1105         // Individual conversation, user1 is a member, last message from other user.
1106         $ic1 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1107             [$user1->id, $user2->id]);
1108         testhelper::send_fake_message_to_conversation($user1, $ic1->id, 'Message 1', $time);
1109         testhelper::send_fake_message_to_conversation($user2, $ic1->id, 'Message 2', $time + 1);
1111         // Individual conversation, user1 is a member, last message from user1.
1112         $ic2 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1113             [$user1->id, $user3->id]);
1114         testhelper::send_fake_message_to_conversation($user3, $ic2->id, 'Message 3', $time + 2);
1115         testhelper::send_fake_message_to_conversation($user1, $ic2->id, 'Message 4', $time + 3);
1117         // Individual conversation, user1 is not a member.
1118         $ic3 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1119             [$user2->id, $user3->id]);
1120         testhelper::send_fake_message_to_conversation($user2, $ic3->id, 'Message 5', $time + 4);
1121         testhelper::send_fake_message_to_conversation($user3, $ic3->id, 'Message 6', $time + 5);
1123         // Group conversation, user1 is not a member.
1124         $gc1 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1125             [$user2->id, $user3->id, $user4->id], 'Project discussions');
1126         testhelper::send_fake_message_to_conversation($user2, $gc1->id, 'Message 7', $time + 6);
1127         testhelper::send_fake_message_to_conversation($user4, $gc1->id, 'Message 8', $time + 7);
1129         // Group conversation, user1 is a member, last message from another user.
1130         $gc2 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1131             [$user1->id, $user3->id, $user4->id], 'Group chat');
1132         testhelper::send_fake_message_to_conversation($user1, $gc2->id, 'Message 9', $time + 8);
1133         testhelper::send_fake_message_to_conversation($user3, $gc2->id, 'Message 10', $time + 9);
1134         testhelper::send_fake_message_to_conversation($user4, $gc2->id, 'Message 11', $time + 10);
1136         // Group conversation, user1 is a member, last message from user1.
1137         $gc3 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1138             [$user1->id, $user2->id, $user3->id, $user4->id], 'Group chat again!');
1139         testhelper::send_fake_message_to_conversation($user4, $gc3->id, 'Message 12', $time + 11);
1140         testhelper::send_fake_message_to_conversation($user3, $gc3->id, 'Message 13', $time + 12);
1141         testhelper::send_fake_message_to_conversation($user1, $gc3->id, 'Message 14', $time + 13);
1143         // Empty group conversations (x2), user1 is a member.
1144         $gc4 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1145             [$user1->id, $user2->id, $user3->id], 'Empty group');
1146         $gc5 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1147             [$user1->id, $user2->id, $user4->id], 'Another empty group');
1149         // Empty group conversation, user1 is NOT a member.
1150         $gc6 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1151             [$user2->id, $user3->id, $user4->id], 'Empty group 3');
1153         return [$user1, $user2, $user3, $user4, $ic1, $ic2, $ic3, $gc1, $gc2, $gc3, $gc4, $gc5, $gc6];
1154     }
1156     /**
1157      * Test verifying get_conversations when no limits, offsets, type filters or favourite restrictions are used.
1158      */
1159     public function test_get_conversations_no_restrictions() {
1160         global $DB;
1161         // No conversations should exist yet.
1162         $user1 = self::getDataGenerator()->create_user();
1163         $this->assertEquals([], \core_message\api::get_conversations($user1->id));
1165         // Get a bunch of conversations, some group, some individual and in different states.
1166         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1167             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1169         // Get all conversations for user1.
1170         $conversations = core_message\api::get_conversations($user1->id);
1172         // Verify there are 2 individual conversation, 2 group conversations, and 2 empty group conversations.
1173         // The conversations with the most recent messages should be listed first, followed by the empty
1174         // conversations, with the most recently created first.
1175         $this->assertCount(6, $conversations);
1176         $typecounts  = array_count_values(array_column($conversations, 'type'));
1177         $this->assertEquals(2, $typecounts[1]);
1178         $this->assertEquals(4, $typecounts[2]);
1180         // Those conversations having messages should be listed first, ordered by most recent message time.
1181         $this->assertEquals($gc3->id, $conversations[0]->id);
1182         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $conversations[0]->type);
1183         $this->assertFalse($conversations[0]->isfavourite);
1184         $this->assertCount(1, $conversations[0]->members);
1185         $this->assertEquals(4, $conversations[0]->membercount);
1186         $this->assertCount(1, $conversations[0]->messages);
1187         $message = $DB->get_record('messages', ['id' => $conversations[0]->messages[0]->id]);
1188         $expectedmessagetext = message_format_message_text($message);
1189         $this->assertEquals($expectedmessagetext, $conversations[0]->messages[0]->text);
1190         $this->assertEquals($user1->id, $conversations[0]->messages[0]->useridfrom);
1192         $this->assertEquals($gc2->id, $conversations[1]->id);
1193         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $conversations[1]->type);
1194         $this->assertFalse($conversations[1]->isfavourite);
1195         $this->assertCount(1, $conversations[1]->members);
1196         $this->assertEquals(3, $conversations[1]->membercount);
1197         $this->assertCount(1, $conversations[1]->messages);
1198         $message = $DB->get_record('messages', ['id' => $conversations[1]->messages[0]->id]);
1199         $expectedmessagetext = message_format_message_text($message);
1200         $this->assertEquals($expectedmessagetext, $conversations[1]->messages[0]->text);
1201         $this->assertEquals($user4->id, $conversations[1]->messages[0]->useridfrom);
1203         $this->assertEquals($ic2->id, $conversations[2]->id);
1204         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $conversations[2]->type);
1205         $this->assertFalse($conversations[2]->isfavourite);
1206         $this->assertCount(1, $conversations[2]->members);
1207         $this->assertEquals($user3->id, $conversations[2]->members[$user3->id]->id);
1208         $this->assertEquals(2, $conversations[2]->membercount);
1209         $this->assertCount(1, $conversations[2]->messages);
1210         $message = $DB->get_record('messages', ['id' => $conversations[2]->messages[0]->id]);
1211         $expectedmessagetext = message_format_message_text($message);
1212         $this->assertEquals($expectedmessagetext, $conversations[2]->messages[0]->text);
1213         $this->assertEquals($user1->id, $conversations[2]->messages[0]->useridfrom);
1215         $this->assertEquals($ic1->id, $conversations[3]->id);
1216         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $conversations[3]->type);
1217         $this->assertFalse($conversations[3]->isfavourite);
1218         $this->assertCount(1, $conversations[3]->members);
1219         $this->assertEquals(2, $conversations[3]->membercount);
1220         $this->assertCount(1, $conversations[3]->messages);
1221         $message = $DB->get_record('messages', ['id' => $conversations[3]->messages[0]->id]);
1222         $expectedmessagetext = message_format_message_text($message);
1223         $this->assertEquals($expectedmessagetext, $conversations[3]->messages[0]->text);
1224         $this->assertEquals($user2->id, $conversations[3]->messages[0]->useridfrom);
1226         // Of the groups without messages, we expect to see the most recently created first.
1227         $this->assertEquals($gc5->id, $conversations[4]->id);
1228         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $conversations[4]->type);
1229         $this->assertFalse($conversations[4]->isfavourite);
1230         $this->assertCount(0, $conversations[4]->members); // No members returned, because no recent messages exist.
1231         $this->assertEquals(3, $conversations[4]->membercount);
1232         $this->assertEmpty($conversations[4]->messages);
1234         $this->assertEquals($gc4->id, $conversations[5]->id);
1235         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $conversations[5]->type);
1236         $this->assertFalse($conversations[5]->isfavourite);
1237         $this->assertCount(0, $conversations[5]->members);
1238         $this->assertEquals(3, $conversations[5]->membercount);
1239         $this->assertEmpty($conversations[5]->messages);
1241         // Verify format of the return structure.
1242         foreach ($conversations as $conv) {
1243             $this->assertObjectHasAttribute('id', $conv);
1244             $this->assertObjectHasAttribute('name', $conv);
1245             $this->assertObjectHasAttribute('subname', $conv);
1246             $this->assertObjectHasAttribute('imageurl', $conv);
1247             $this->assertObjectHasAttribute('type', $conv);
1248             $this->assertObjectHasAttribute('isfavourite', $conv);
1249             $this->assertObjectHasAttribute('membercount', $conv);
1250             $this->assertObjectHasAttribute('isread', $conv);
1251             $this->assertObjectHasAttribute('unreadcount', $conv);
1252             $this->assertObjectHasAttribute('members', $conv);
1253             foreach ($conv->members as $member) {
1254                 $this->assertObjectHasAttribute('id', $member);
1255                 $this->assertObjectHasAttribute('fullname', $member);
1256                 $this->assertObjectHasAttribute('profileimageurl', $member);
1257                 $this->assertObjectHasAttribute('profileimageurlsmall', $member);
1258                 $this->assertObjectHasAttribute('isonline', $member);
1259                 $this->assertObjectHasAttribute('showonlinestatus', $member);
1260                 $this->assertObjectHasAttribute('isblocked', $member);
1261                 $this->assertObjectHasAttribute('iscontact', $member);
1262                 $this->assertObjectHasAttribute('isdeleted', $member);
1263                 $this->assertObjectHasAttribute('canmessage', $member);
1264                 $this->assertObjectHasAttribute('requirescontact', $member);
1265                 $this->assertObjectHasAttribute('contactrequests', $member);
1266             }
1267             $this->assertObjectHasAttribute('messages', $conv);
1268             foreach ($conv->messages as $message) {
1269                 $this->assertObjectHasAttribute('id', $message);
1270                 $this->assertObjectHasAttribute('useridfrom', $message);
1271                 $this->assertObjectHasAttribute('text', $message);
1272                 $this->assertObjectHasAttribute('timecreated', $message);
1273             }
1274         }
1275     }
1277     /**
1278      * Test verifying that html format messages are supported, and that message_format_message_text() is being called appropriately.
1279      */
1280     public function test_get_conversations_message_format() {
1281         global $DB;
1282         // Create some users.
1283         $user1 = self::getDataGenerator()->create_user();
1284         $user2 = self::getDataGenerator()->create_user();
1286         // Create conversation.
1287         $conversation = \core_message\api::create_conversation(
1288             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1289             [$user1->id, $user2->id]
1290         );
1292         // Send some messages back and forth.
1293         $time = 1;
1294         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 1);
1295         $mid = testhelper::send_fake_message_to_conversation($user1, $conversation->id, '<a href="#">A link</a>', $time + 2);
1297         // Verify the format of the html message.
1298         $message = $DB->get_record('messages', ['id' => $mid]);
1299         $expectedmessagetext = message_format_message_text($message);
1300         $conversations = \core_message\api::get_conversations($user1->id);
1301         $messages = $conversations[0]->messages;
1302         $this->assertEquals($expectedmessagetext, $messages[0]->text);
1303     }
1305     /**
1306      * Tests retrieving conversations with a limit and offset to ensure pagination works correctly.
1307      */
1308     public function test_get_conversations_limit_offset() {
1309         // Get a bunch of conversations, some group, some individual and in different states.
1310         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1311             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1313         // Get all conversations for user1, limited to 1 result.
1314         $conversations = core_message\api::get_conversations($user1->id, 0, 1);
1316         // Verify the first conversation.
1317         $this->assertCount(1, $conversations);
1318         $conversation = array_shift($conversations);
1319         $this->assertEquals($conversation->id, $gc3->id);
1321         // Verify the next conversation.
1322         $conversations = \core_message\api::get_conversations($user1->id, 1, 1);
1323         $this->assertCount(1, $conversations);
1324         $this->assertEquals($gc2->id, $conversations[0]->id);
1326         // Verify the next conversation.
1327         $conversations = \core_message\api::get_conversations($user1->id, 2, 1);
1328         $this->assertCount(1, $conversations);
1329         $this->assertEquals($ic2->id, $conversations[0]->id);
1331         // Skip one and get both empty conversations.
1332         $conversations = \core_message\api::get_conversations($user1->id, 4, 2);
1333         $this->assertCount(2, $conversations);
1334         $this->assertEquals($gc5->id, $conversations[0]->id);
1335         $this->assertEmpty($conversations[0]->messages);
1336         $this->assertEquals($gc4->id, $conversations[1]->id);
1337         $this->assertEmpty($conversations[1]->messages);
1339         // Ask for an offset that doesn't exist and verify no conversations are returned.
1340         $conversations = \core_message\api::get_conversations($user1->id, 10, 1);
1341         $this->assertCount(0, $conversations);
1342     }
1344     /**
1345      * Test verifying the type filtering behaviour of the
1346      */
1347     public function test_get_conversations_type_filter() {
1348         // Get a bunch of conversations, some group, some individual and in different states.
1349         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1350             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1352         // Verify we can ask for only individual conversations.
1353         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
1354             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL);
1355         $this->assertCount(2, $conversations);
1357         // Verify we can ask for only group conversations.
1358         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
1359             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP);
1360         $this->assertCount(4, $conversations);
1362         // Verify an exception is thrown if an unrecognized type is specified.
1363         $this->expectException(\moodle_exception::class);
1364         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, 0);
1365     }
1367     /**
1368      * Tests retrieving conversations when a conversation contains a deleted user.
1369      */
1370     public function test_get_conversations_with_deleted_user() {
1371         // Get a bunch of conversations, some group, some individual and in different states.
1372         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1373             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1375         // Delete the second user and retrieve the conversations.
1376         // We should have 6 still, as conversations with soft-deleted users are still returned.
1377         // Group conversations are also present, albeit with less members.
1378         delete_user($user2);
1379         // This is to confirm an exception is not thrown when a user AND the user context is deleted.
1380         // We no longer delete the user context, but historically we did.
1381         context_helper::delete_instance(CONTEXT_USER, $user2->id);
1382         $conversations = \core_message\api::get_conversations($user1->id);
1383         $this->assertCount(6, $conversations);
1384         $this->assertEquals($gc3->id, $conversations[0]->id);
1385         $this->assertcount(1, $conversations[0]->members);
1386         $this->assertEquals($gc2->id, $conversations[1]->id);
1387         $this->assertcount(1, $conversations[1]->members);
1388         $this->assertEquals($ic2->id, $conversations[2]->id);
1389         $this->assertEquals($ic1->id, $conversations[3]->id);
1390         $this->assertEquals($gc5->id, $conversations[4]->id);
1391         $this->assertEquals($gc4->id, $conversations[5]->id);
1393         // Delete a user from a group conversation where that user had sent the most recent message.
1394         // This user will still be present in the members array, as will the message in the messages array.
1395         delete_user($user4);
1396         $conversations = \core_message\api::get_conversations($user1->id);
1397         $this->assertCount(6, $conversations);
1398         $this->assertEquals($gc2->id, $conversations[1]->id);
1399         $this->assertcount(1, $conversations[1]->members);
1400         $this->assertEquals($user4->id, $conversations[1]->members[$user4->id]->id);
1401         $this->assertcount(1, $conversations[1]->messages);
1402         $this->assertEquals($user4->id, $conversations[1]->messages[0]->useridfrom);
1404         // Delete the third user and retrieve the conversations.
1405         // We should have 6 still, as conversations with soft-deleted users are still returned.
1406         // Group conversations are also present, albeit with less members.
1407         delete_user($user3);
1408         $conversations = \core_message\api::get_conversations($user1->id);
1409         $this->assertCount(6, $conversations);
1410         $this->assertEquals($gc3->id, $conversations[0]->id);
1411         $this->assertcount(1, $conversations[0]->members);
1412         $this->assertEquals($gc2->id, $conversations[1]->id);
1413         $this->assertcount(1, $conversations[1]->members);
1414         $this->assertEquals($ic2->id, $conversations[2]->id);
1415         $this->assertEquals($ic1->id, $conversations[3]->id);
1416         $this->assertEquals($gc5->id, $conversations[4]->id);
1417         $this->assertEquals($gc4->id, $conversations[5]->id);
1418     }
1420     /**
1421      * Test confirming the behaviour of get_conversations() when users delete all messages.
1422      */
1423     public function test_get_conversations_deleted_messages() {
1424         // Get a bunch of conversations, some group, some individual and in different states.
1425         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1426             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1428         $conversations = \core_message\api::get_conversations($user1->id);
1429         $this->assertCount(6, $conversations);
1431         // Delete all messages from a group conversation the user is in - it should be returned.
1432         $this->assertTrue(\core_message\api::is_user_in_conversation($user1->id, $gc2->id));
1433         $convmessages = \core_message\api::get_conversation_messages($user1->id, $gc2->id);
1434         $messages = $convmessages['messages'];
1435         foreach ($messages as $message) {
1436             \core_message\api::delete_message($user1->id, $message->id);
1437         }
1438         $conversations = \core_message\api::get_conversations($user1->id);
1439         $this->assertCount(6, $conversations);
1440         $this->assertContains($gc2->id, array_column($conversations, 'id'));
1442         // Delete all messages from an individual conversation the user is in - it should not be returned.
1443         $this->assertTrue(\core_message\api::is_user_in_conversation($user1->id, $ic1->id));
1444         $convmessages = \core_message\api::get_conversation_messages($user1->id, $ic1->id);
1445         $messages = $convmessages['messages'];
1446         foreach ($messages as $message) {
1447             \core_message\api::delete_message($user1->id, $message->id);
1448         }
1449         $conversations = \core_message\api::get_conversations($user1->id);
1450         $this->assertCount(5, $conversations);
1451         $this->assertNotContains($ic1->id, array_column($conversations, 'id'));
1452     }
1454     /**
1455      * Test verifying the behaviour of get_conversations() when fetching favourite conversations with only a single
1456      * favourite.
1457      */
1458     public function test_get_conversations_favourite_conversations_single() {
1459         // Get a bunch of conversations, some group, some individual and in different states.
1460         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1461             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1463         // Mark a single conversation as favourites.
1464         \core_message\api::set_favourite_conversation($ic2->id, $user1->id);
1466         // Get the conversation, first with no restrictions, confirming the favourite status of the conversations.
1467         $conversations = \core_message\api::get_conversations($user1->id);
1468         $this->assertCount(6, $conversations);
1469         foreach ($conversations as $conv) {
1470             if (in_array($conv->id, [$ic2->id])) {
1471                 $this->assertTrue($conv->isfavourite);
1472             } else {
1473                 $this->assertFalse($conv->isfavourite);
1474             }
1475         }
1477         // Now, get ONLY favourite conversations.
1478         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, true);
1479         $this->assertCount(1, $conversations);
1480         foreach ($conversations as $conv) {
1481             $this->assertTrue($conv->isfavourite);
1482             $this->assertEquals($ic2->id, $conv->id);
1483         }
1485         // Now, try ONLY favourites of type 'group'.
1486         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
1487             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, true);
1488         $this->assertEmpty($conversations);
1490         // And NO favourite conversations.
1491         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, false);
1492         $this->assertCount(5, $conversations);
1493         foreach ($conversations as $conv) {
1494             $this->assertFalse($conv->isfavourite);
1495             $this->assertNotEquals($ic2, $conv->id);
1496         }
1497     }
1499     /**
1500      * Test verifying the behaviour of get_conversations() when fetching favourite conversations.
1501      */
1502     public function test_get_conversations_favourite_conversations() {
1503         // Get a bunch of conversations, some group, some individual and in different states.
1504         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1505             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1507         // Try to get ONLY favourite conversations, when no favourites exist.
1508         $this->assertEquals([], \core_message\api::get_conversations($user1->id, 0, 20, null, true));
1510         // Try to get NO favourite conversations, when no favourites exist.
1511         $this->assertCount(6, \core_message\api::get_conversations($user1->id, 0, 20, null, false));
1513         // Mark a few conversations as favourites.
1514         \core_message\api::set_favourite_conversation($ic1->id, $user1->id);
1515         \core_message\api::set_favourite_conversation($gc2->id, $user1->id);
1516         \core_message\api::set_favourite_conversation($gc5->id, $user1->id);
1517         $favouriteids = [$ic1->id, $gc2->id, $gc5->id];
1519         // Get the conversations, first with no restrictions, confirming the favourite status of the conversations.
1520         $conversations = \core_message\api::get_conversations($user1->id);
1521         $this->assertCount(6, $conversations);
1522         foreach ($conversations as $conv) {
1523             if (in_array($conv->id, $favouriteids)) {
1524                 $this->assertTrue($conv->isfavourite);
1525             } else {
1526                 $this->assertFalse($conv->isfavourite);
1527             }
1528         }
1530         // Now, get ONLY favourite conversations.
1531         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, true);
1532         $this->assertCount(3, $conversations);
1533         foreach ($conversations as $conv) {
1534             $this->assertTrue($conv->isfavourite);
1535             $this->assertNotFalse(array_search($conv->id, $favouriteids));
1536         }
1538         // Now, try ONLY favourites of type 'group'.
1539         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
1540             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, true);
1541         $this->assertCount(2, $conversations);
1542         foreach ($conversations as $conv) {
1543             $this->assertTrue($conv->isfavourite);
1544             $this->assertNotFalse(array_search($conv->id, [$gc2->id, $gc5->id]));
1545         }
1547         // And NO favourite conversations.
1548         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, false);
1549         $this->assertCount(3, $conversations);
1550         foreach ($conversations as $conv) {
1551             $this->assertFalse($conv->isfavourite);
1552             $this->assertFalse(array_search($conv->id, $favouriteids));
1553         }
1554     }
1556     /**
1557      * Test verifying get_conversations when there are users in a group and/or individual conversation. The reason this
1558      * test is performed is because we do not need as much data for group conversations (saving DB calls), so we want
1559      * to confirm this happens.
1560      */
1561     public function test_get_conversations_user_in_group_and_individual_chat() {
1562         $this->resetAfterTest();
1564         $user1 = self::getDataGenerator()->create_user();
1565         $user2 = self::getDataGenerator()->create_user();
1566         $user3 = self::getDataGenerator()->create_user();
1568         $conversation = \core_message\api::create_conversation(
1569             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1570             [
1571                 $user1->id,
1572                 $user2->id
1573             ],
1574             'Individual conversation'
1575         );
1577         testhelper::send_fake_message_to_conversation($user1, $conversation->id);
1579         $conversation = \core_message\api::create_conversation(
1580             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1581             [
1582                 $user1->id,
1583                 $user2->id,
1584             ],
1585             'Group conversation'
1586         );
1588         testhelper::send_fake_message_to_conversation($user1, $conversation->id);
1590         \core_message\api::create_contact_request($user1->id, $user2->id);
1591         \core_message\api::create_contact_request($user1->id, $user3->id);
1593         $conversations = \core_message\api::get_conversations($user2->id);
1595         $groupconversation = array_shift($conversations);
1596         $individualconversation = array_shift($conversations);
1598         $this->assertEquals('Group conversation', $groupconversation->name);
1599         $this->assertEquals('Individual conversation', $individualconversation->name);
1601         $this->assertCount(1, $groupconversation->members);
1602         $this->assertCount(1, $individualconversation->members);
1604         $groupmember = reset($groupconversation->members);
1605         $this->assertNull($groupmember->requirescontact);
1606         $this->assertNull($groupmember->canmessage);
1607         $this->assertEmpty($groupmember->contactrequests);
1609         $individualmember = reset($individualconversation->members);
1610         $this->assertNotNull($individualmember->requirescontact);
1611         $this->assertNotNull($individualmember->canmessage);
1612         $this->assertNotEmpty($individualmember->contactrequests);
1613     }
1615     /**
1616      * Test verifying that group linked conversations are returned and contain a subname matching the course name.
1617      */
1618     public function test_get_conversations_group_linked() {
1619         global $CFG, $DB;
1621         // Create some users.
1622         $user1 = self::getDataGenerator()->create_user();
1623         $user2 = self::getDataGenerator()->create_user();
1624         $user3 = self::getDataGenerator()->create_user();
1626         $course1 = $this->getDataGenerator()->create_course();
1628         // Create a group with a linked conversation and a valid image.
1629         $this->setAdminUser();
1630         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1631         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1632         $this->getDataGenerator()->enrol_user($user3->id, $course1->id);
1633         $group1 = $this->getDataGenerator()->create_group([
1634             'courseid' => $course1->id,
1635             'enablemessaging' => 1,
1636             'picturepath' => $CFG->dirroot . '/lib/tests/fixtures/gd-logo.png'
1637         ]);
1639         // Add users to group1.
1640         $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user1->id));
1641         $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user2->id));
1643         // Verify the group with the image works as expected.
1644         $conversations = \core_message\api::get_conversations($user1->id);
1645         $this->assertEquals(2, $conversations[0]->membercount);
1646         $this->assertEquals($course1->shortname, $conversations[0]->subname);
1647         $groupimageurl = get_group_picture_url($group1, $group1->courseid, true);
1648         $this->assertEquals($groupimageurl, $conversations[0]->imageurl);
1650         // Create a group with a linked conversation and without any image.
1651         $group2 = $this->getDataGenerator()->create_group([
1652             'courseid' => $course1->id,
1653             'enablemessaging' => 1,
1654         ]);
1656         // Add users to group2.
1657         $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $user2->id));
1658         $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $user3->id));
1660         // Verify the group without any image works as expected too.
1661         $conversations = \core_message\api::get_conversations($user3->id);
1662         $this->assertEquals(2, $conversations[0]->membercount);
1663         $this->assertEquals($course1->shortname, $conversations[0]->subname);
1664         $groupimageurl = get_group_picture_url($group2, $group2->courseid, true);
1665         $this->assertEquals($groupimageurl, $conversations[0]->imageurl);
1667         // Now, disable the conversation linked to the group and verify it's no longer returned.
1668         $DB->set_field('message_conversations', 'enabled', 0, ['id' => $conversations[0]->id]);
1669         $conversations = \core_message\api::get_conversations($user3->id);
1670         $this->assertCount(0, $conversations);
1671     }
1673    /**
1674     * The data provider for get_conversations_mixed.
1675     *
1676     * This provides sets of data to for testing.
1677     * @return array
1678     */
1679    public function get_conversations_mixed_provider() {
1680        return array(
1681             'Test that conversations with messages contacts is correctly ordered.' => array(
1682                 'users' => array(
1683                     'user1',
1684                     'user2',
1685                     'user3',
1686                 ),
1687                 'contacts' => array(
1688                 ),
1689                 'messages' => array(
1690                     array(
1691                         'from'          => 'user1',
1692                         'to'            => 'user2',
1693                         'state'         => 'unread',
1694                         'subject'       => 'S1',
1695                     ),
1696                     array(
1697                         'from'          => 'user2',
1698                         'to'            => 'user1',
1699                         'state'         => 'unread',
1700                         'subject'       => 'S2',
1701                     ),
1702                     array(
1703                         'from'          => 'user1',
1704                         'to'            => 'user2',
1705                         'state'         => 'unread',
1706                         'timecreated'   => 0,
1707                         'subject'       => 'S3',
1708                     ),
1709                     array(
1710                         'from'          => 'user1',
1711                         'to'            => 'user3',
1712                         'state'         => 'read',
1713                         'timemodifier'  => 1,
1714                         'subject'       => 'S4',
1715                     ),
1716                     array(
1717                         'from'          => 'user3',
1718                         'to'            => 'user1',
1719                         'state'         => 'read',
1720                         'timemodifier'  => 1,
1721                         'subject'       => 'S5',
1722                     ),
1723                     array(
1724                         'from'          => 'user1',
1725                         'to'            => 'user3',
1726                         'state'         => 'read',
1727                         'timecreated'   => 0,
1728                         'subject'       => 'S6',
1729                     ),
1730                 ),
1731                 'expectations' => array(
1732                     'user1' => array(
1733                         // User1 has conversed most recently with user3. The most recent message is M5.
1734                         array(
1735                             'messageposition'   => 0,
1736                             'with'              => 'user3',
1737                             'subject'           => '<p>S5</p>',
1738                             'unreadcount'       => 0,
1739                         ),
1740                         // User1 has also conversed with user2. The most recent message is S2.
1741                         array(
1742                             'messageposition'   => 1,
1743                             'with'              => 'user2',
1744                             'subject'           => '<p>S2</p>',
1745                             'unreadcount'       => 1,
1746                         ),
1747                     ),
1748                     'user2' => array(
1749                         // User2 has only conversed with user1. Their most recent shared message was S2.
1750                         array(
1751                             'messageposition'   => 0,
1752                             'with'              => 'user1',
1753                             'subject'           => '<p>S2</p>',
1754                             'unreadcount'       => 2,
1755                         ),
1756                     ),
1757                     'user3' => array(
1758                         // User3 has only conversed with user1. Their most recent shared message was S5.
1759                         array(
1760                             'messageposition'   => 0,
1761                             'with'              => 'user1',
1762                             'subject'           => '<p>S5</p>',
1763                             'unreadcount'       => 0,
1764                         ),
1765                     ),
1766                 ),
1767             ),
1768             'Test conversations with a single user, where some messages are read and some are not.' => array(
1769                 'users' => array(
1770                     'user1',
1771                     'user2',
1772                 ),
1773                 'contacts' => array(
1774                 ),
1775                 'messages' => array(
1776                     array(
1777                         'from'          => 'user1',
1778                         'to'            => 'user2',
1779                         'state'         => 'read',
1780                         'subject'       => 'S1',
1781                     ),
1782                     array(
1783                         'from'          => 'user2',
1784                         'to'            => 'user1',
1785                         'state'         => 'read',
1786                         'subject'       => 'S2',
1787                     ),
1788                     array(
1789                         'from'          => 'user1',
1790                         'to'            => 'user2',
1791                         'state'         => 'unread',
1792                         'timemodifier'  => 1,
1793                         'subject'       => 'S3',
1794                     ),
1795                     array(
1796                         'from'          => 'user1',
1797                         'to'            => 'user2',
1798                         'state'         => 'unread',
1799                         'timemodifier'  => 1,
1800                         'subject'       => 'S4',
1801                     ),
1802                 ),
1803                 'expectations' => array(
1804                     // The most recent message between user1 and user2 was S4.
1805                     'user1' => array(
1806                         array(
1807                             'messageposition'   => 0,
1808                             'with'              => 'user2',
1809                             'subject'           => '<p>S4</p>',
1810                             'unreadcount'       => 0,
1811                         ),
1812                     ),
1813                     'user2' => array(
1814                         // The most recent message between user1 and user2 was S4.
1815                         array(
1816                             'messageposition'   => 0,
1817                             'with'              => 'user1',
1818                             'subject'           => '<p>S4</p>',
1819                             'unreadcount'       => 2,
1820                         ),
1821                     ),
1822                 ),
1823             ),
1824             'Test conversations with a single user, where some messages are read and some are not, and messages ' .
1825             'are out of order' => array(
1826             // This can happen through a combination of factors including multi-master DB replication with messages
1827             // read somehow (e.g. API).
1828                 'users' => array(
1829                     'user1',
1830                     'user2',
1831                 ),
1832                 'contacts' => array(
1833                 ),
1834                 'messages' => array(
1835                     array(
1836                         'from'          => 'user1',
1837                         'to'            => 'user2',
1838                         'state'         => 'read',
1839                         'subject'       => 'S1',
1840                         'timemodifier'  => 1,
1841                     ),
1842                     array(
1843                         'from'          => 'user2',
1844                         'to'            => 'user1',
1845                         'state'         => 'read',
1846                         'subject'       => 'S2',
1847                         'timemodifier'  => 2,
1848                     ),
1849                     array(
1850                         'from'          => 'user1',
1851                         'to'            => 'user2',
1852                         'state'         => 'unread',
1853                         'subject'       => 'S3',
1854                     ),
1855                     array(
1856                         'from'          => 'user1',
1857                         'to'            => 'user2',
1858                         'state'         => 'unread',
1859                         'subject'       => 'S4',
1860                     ),
1861                 ),
1862                 'expectations' => array(
1863                     // The most recent message between user1 and user2 was S2, even though later IDs have not been read.
1864                     'user1' => array(
1865                         array(
1866                             'messageposition'   => 0,
1867                             'with'              => 'user2',
1868                             'subject'           => '<p>S2</p>',
1869                             'unreadcount'       => 0,
1870                         ),
1871                     ),
1872                     'user2' => array(
1873                         array(
1874                             'messageposition'   => 0,
1875                             'with'              => 'user1',
1876                             'subject'           => '<p>S2</p>',
1877                             'unreadcount'       => 2
1878                         ),
1879                     ),
1880                 ),
1881             ),
1882             'Test unread message count is correct for both users' => array(
1883                 'users' => array(
1884                     'user1',
1885                     'user2',
1886                 ),
1887                 'contacts' => array(
1888                 ),
1889                 'messages' => array(
1890                     array(
1891                         'from'          => 'user1',
1892                         'to'            => 'user2',
1893                         'state'         => 'read',
1894                         'subject'       => 'S1',
1895                         'timemodifier'  => 1,
1896                     ),
1897                     array(
1898                         'from'          => 'user2',
1899                         'to'            => 'user1',
1900                         'state'         => 'read',
1901                         'subject'       => 'S2',
1902                         'timemodifier'  => 2,
1903                     ),
1904                     array(
1905                         'from'          => 'user1',
1906                         'to'            => 'user2',
1907                         'state'         => 'read',
1908                         'subject'       => 'S3',
1909                         'timemodifier'  => 3,
1910                     ),
1911                     array(
1912                         'from'          => 'user1',
1913                         'to'            => 'user2',
1914                         'state'         => 'read',
1915                         'subject'       => 'S4',
1916                         'timemodifier'  => 4,
1917                     ),
1918                     array(
1919                         'from'          => 'user1',
1920                         'to'            => 'user2',
1921                         'state'         => 'unread',
1922                         'subject'       => 'S5',
1923                         'timemodifier'  => 5,
1924                     ),
1925                     array(
1926                         'from'          => 'user2',
1927                         'to'            => 'user1',
1928                         'state'         => 'unread',
1929                         'subject'       => 'S6',
1930                         'timemodifier'  => 6,
1931                     ),
1932                     array(
1933                         'from'          => 'user1',
1934                         'to'            => 'user2',
1935                         'state'         => 'unread',
1936                         'subject'       => 'S7',
1937                         'timemodifier'  => 7,
1938                     ),
1939                     array(
1940                         'from'          => 'user1',
1941                         'to'            => 'user2',
1942                         'state'         => 'unread',
1943                         'subject'       => 'S8',
1944                         'timemodifier'  => 8,
1945                     ),
1946                 ),
1947                 'expectations' => array(
1948                     // The most recent message between user1 and user2 was S2, even though later IDs have not been read.
1949                     'user1' => array(
1950                         array(
1951                             'messageposition'   => 0,
1952                             'with'              => 'user2',
1953                             'subject'           => '<p>S8</p>',
1954                             'unreadcount'       => 1,
1955                         ),
1956                     ),
1957                     'user2' => array(
1958                         array(
1959                             'messageposition'   => 0,
1960                             'with'              => 'user1',
1961                             'subject'           => '<p>S8</p>',
1962                             'unreadcount'       => 3,
1963                         ),
1964                     ),
1965                 ),
1966             ),
1967         );
1968     }
1970     /**
1971      * Test get_conversations with a mixture of messages.
1972      *
1973      * @dataProvider get_conversations_mixed_provider
1974      * @param array $usersdata The list of users to create for this test.
1975      * @param array $messagesdata The list of messages to create.
1976      * @param array $expectations The list of expected outcomes.
1977      */
1978     public function test_get_conversations_mixed($usersdata, $contacts, $messagesdata, $expectations) {
1979         global $DB;
1981         // Create all of the users.
1982         $users = array();
1983         foreach ($usersdata as $username) {
1984             $users[$username] = $this->getDataGenerator()->create_user(array('username' => $username));
1985         }
1987         foreach ($contacts as $username => $contact) {
1988             foreach ($contact as $contactname => $blocked) {
1989                 $record = new stdClass();
1990                 $record->userid     = $users[$username]->id;
1991                 $record->contactid  = $users[$contactname]->id;
1992                 $record->blocked    = $blocked;
1993                 $record->id = $DB->insert_record('message_contacts', $record);
1994             }
1995         }
1997         $defaulttimecreated = time();
1998         foreach ($messagesdata as $messagedata) {
1999             $from       = $users[$messagedata['from']];
2000             $to         = $users[$messagedata['to']];
2001             $subject    = $messagedata['subject'];
2003             if (isset($messagedata['state']) && $messagedata['state'] == 'unread') {
2004                 $messageid = $this->send_fake_message($from, $to, $subject);
2005             } else {
2006                 // If there is no state, or the state is not 'unread', assume the message is read.
2007                 $messageid = message_post_message($from, $to, $subject, FORMAT_PLAIN);
2008             }
2010             $updatemessage = new stdClass();
2011             $updatemessage->id = $messageid;
2012             if (isset($messagedata['timecreated'])) {
2013                 $updatemessage->timecreated = $messagedata['timecreated'];
2014             } else if (isset($messagedata['timemodifier'])) {
2015                 $updatemessage->timecreated = $defaulttimecreated + $messagedata['timemodifier'];
2016             } else {
2017                 $updatemessage->timecreated = $defaulttimecreated;
2018             }
2020             $DB->update_record('messages', $updatemessage);
2021         }
2023         foreach ($expectations as $username => $data) {
2024             // Get the recent conversations for the specified user.
2025             $user = $users[$username];
2026             $conversations = array_values(\core_message\api::get_conversations($user->id));
2027             foreach ($data as $expectation) {
2028                 $otheruser = $users[$expectation['with']];
2029                 $conversation = $conversations[$expectation['messageposition']];
2030                 $this->assertEquals($otheruser->id, $conversation->members[$otheruser->id]->id);
2031                 $this->assertEquals($expectation['subject'], $conversation->messages[0]->text);
2032                 $this->assertEquals($expectation['unreadcount'], $conversation->unreadcount);
2033             }
2034         }
2035     }
2037     /**
2038      * Tests retrieving contacts.
2039      */
2040     public function test_get_contacts() {
2041         // Create some users.
2042         $user1 = self::getDataGenerator()->create_user();
2044         // Set as the user.
2045         $this->setUser($user1);
2047         $user2 = new stdClass();
2048         $user2->firstname = 'User';
2049         $user2->lastname = 'A';
2050         $user2 = self::getDataGenerator()->create_user($user2);
2052         $user3 = new stdClass();
2053         $user3->firstname = 'User';
2054         $user3->lastname = 'B';
2055         $user3 = self::getDataGenerator()->create_user($user3);
2057         $user4 = new stdClass();
2058         $user4->firstname = 'User';
2059         $user4->lastname = 'C';
2060         $user4 = self::getDataGenerator()->create_user($user4);
2062         $user5 = new stdClass();
2063         $user5->firstname = 'User';
2064         $user5->lastname = 'D';
2065         $user5 = self::getDataGenerator()->create_user($user5);
2067         // Add some users as contacts.
2068         \core_message\api::add_contact($user1->id, $user2->id);
2069         \core_message\api::add_contact($user1->id, $user3->id);
2070         \core_message\api::add_contact($user1->id, $user4->id);
2072         // Retrieve the contacts.
2073         $contacts = \core_message\api::get_contacts($user1->id);
2075         // Confirm the data is correct.
2076         $this->assertEquals(3, count($contacts));
2077         usort($contacts, ['static', 'sort_contacts']);
2079         $contact1 = $contacts[0];
2080         $contact2 = $contacts[1];
2081         $contact3 = $contacts[2];
2083         $this->assertEquals($user2->id, $contact1->userid);
2084         $this->assertEmpty($contact1->useridfrom);
2085         $this->assertFalse($contact1->ismessaging);
2086         $this->assertNull($contact1->lastmessage);
2087         $this->assertNull($contact1->messageid);
2088         $this->assertNull($contact1->isonline);
2089         $this->assertFalse($contact1->isread);
2090         $this->assertFalse($contact1->isblocked);
2091         $this->assertNull($contact1->unreadcount);
2093         $this->assertEquals($user3->id, $contact2->userid);
2094         $this->assertEmpty($contact2->useridfrom);
2095         $this->assertFalse($contact2->ismessaging);
2096         $this->assertNull($contact2->lastmessage);
2097         $this->assertNull($contact2->messageid);
2098         $this->assertNull($contact2->isonline);
2099         $this->assertFalse($contact2->isread);
2100         $this->assertFalse($contact2->isblocked);
2101         $this->assertNull($contact2->unreadcount);
2103         $this->assertEquals($user4->id, $contact3->userid);
2104         $this->assertEmpty($contact3->useridfrom);
2105         $this->assertFalse($contact3->ismessaging);
2106         $this->assertNull($contact3->lastmessage);
2107         $this->assertNull($contact3->messageid);
2108         $this->assertNull($contact3->isonline);
2109         $this->assertFalse($contact3->isread);
2110         $this->assertFalse($contact3->isblocked);
2111         $this->assertNull($contact3->unreadcount);
2112     }
2114     /**
2115      * Tests retrieving user contacts.
2116      */
2117     public function test_get_user_contacts() {
2118         // Create some users.
2119         $user1 = self::getDataGenerator()->create_user();
2121         // Set as the user.
2122         $this->setUser($user1);
2124         $user2 = new stdClass();
2125         $user2->firstname = 'User';
2126         $user2->lastname = 'A';
2127         $user2 = self::getDataGenerator()->create_user($user2);
2129         $user3 = new stdClass();
2130         $user3->firstname = 'User';
2131         $user3->lastname = 'B';
2132         $user3 = self::getDataGenerator()->create_user($user3);
2134         $user4 = new stdClass();
2135         $user4->firstname = 'User';
2136         $user4->lastname = 'C';
2137         $user4 = self::getDataGenerator()->create_user($user4);
2139         $user5 = new stdClass();
2140         $user5->firstname = 'User';
2141         $user5->lastname = 'D';
2142         $user5 = self::getDataGenerator()->create_user($user5);
2144         // Add some users as contacts.
2145         \core_message\api::add_contact($user1->id, $user2->id);
2146         \core_message\api::add_contact($user1->id, $user3->id);
2147         \core_message\api::add_contact($user1->id, $user4->id);
2149         // Retrieve the contacts.
2150         $contacts = \core_message\api::get_user_contacts($user1->id);
2152         // Confirm the data is correct.
2153         $this->assertEquals(3, count($contacts));
2155         ksort($contacts);
2157         $contact1 = array_shift($contacts);
2158         $contact2 = array_shift($contacts);
2159         $contact3 = array_shift($contacts);
2161         $this->assertEquals($user2->id, $contact1->id);
2162         $this->assertEquals(fullname($user2), $contact1->fullname);
2163         $this->assertTrue($contact1->iscontact);
2165         $this->assertEquals($user3->id, $contact2->id);
2166         $this->assertEquals(fullname($user3), $contact2->fullname);
2167         $this->assertTrue($contact2->iscontact);
2169         $this->assertEquals($user4->id, $contact3->id);
2170         $this->assertEquals(fullname($user4), $contact3->fullname);
2171         $this->assertTrue($contact3->iscontact);
2172     }
2174     /**
2175      * Tests retrieving messages.
2176      */
2177     public function test_get_messages() {
2178         // Create some users.
2179         $user1 = self::getDataGenerator()->create_user();
2180         $user2 = self::getDataGenerator()->create_user();
2182         // The person doing the search.
2183         $this->setUser($user1);
2185         // Send some messages back and forth.
2186         $time = 1;
2187         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2188         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2189         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2190         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2192         // Retrieve the messages.
2193         $messages = \core_message\api::get_messages($user1->id, $user2->id);
2195         // Confirm the message data is correct.
2196         $this->assertEquals(4, count($messages));
2198         $message1 = $messages[0];
2199         $message2 = $messages[1];
2200         $message3 = $messages[2];
2201         $message4 = $messages[3];
2203         $this->assertEquals($user1->id, $message1->useridfrom);
2204         $this->assertEquals($user2->id, $message1->useridto);
2205         $this->assertTrue($message1->displayblocktime);
2206         $this->assertContains('Yo!', $message1->text);
2208         $this->assertEquals($user2->id, $message2->useridfrom);
2209         $this->assertEquals($user1->id, $message2->useridto);
2210         $this->assertFalse($message2->displayblocktime);
2211         $this->assertContains('Sup mang?', $message2->text);
2213         $this->assertEquals($user1->id, $message3->useridfrom);
2214         $this->assertEquals($user2->id, $message3->useridto);
2215         $this->assertFalse($message3->displayblocktime);
2216         $this->assertContains('Writing PHPUnit tests!', $message3->text);
2218         $this->assertEquals($user2->id, $message4->useridfrom);
2219         $this->assertEquals($user1->id, $message4->useridto);
2220         $this->assertFalse($message4->displayblocktime);
2221         $this->assertContains('Word.', $message4->text);
2222     }
2224     /**
2225      * Tests retrieving conversation messages.
2226      */
2227     public function test_get_conversation_messages() {
2228         // Create some users.
2229         $user1 = self::getDataGenerator()->create_user();
2230         $user2 = self::getDataGenerator()->create_user();
2232         // Create conversation.
2233         $conversation = \core_message\api::create_conversation(
2234             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2235             [$user1->id, $user2->id]
2236         );
2238         // The person doing the search.
2239         $this->setUser($user1);
2241         // Send some messages back and forth.
2242         $time = 1;
2243         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
2244         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
2245         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
2246         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 4);
2248         // Retrieve the messages.
2249         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id);
2251         // Confirm the conversation id is correct.
2252         $this->assertEquals($conversation->id, $convmessages['id']);
2254         // Confirm the message data is correct.
2255         $messages = $convmessages['messages'];
2256         $this->assertEquals(4, count($messages));
2257         $message1 = $messages[0];
2258         $message2 = $messages[1];
2259         $message3 = $messages[2];
2260         $message4 = $messages[3];
2262         $this->assertEquals($user1->id, $message1->useridfrom);
2263         $this->assertContains('Yo!', $message1->text);
2265         $this->assertEquals($user2->id, $message2->useridfrom);
2266         $this->assertContains('Sup mang?', $message2->text);
2268         $this->assertEquals($user1->id, $message3->useridfrom);
2269         $this->assertContains('Writing PHPUnit tests!', $message3->text);
2271         $this->assertEquals($user1->id, $message4->useridfrom);
2272         $this->assertContains('Word.', $message4->text);
2274         // Confirm the members data is correct.
2275         $members = $convmessages['members'];
2276         $this->assertEquals(2, count($members));
2277     }
2279     /**
2280      * Tests retrieving group conversation messages.
2281      */
2282     public function test_get_group_conversation_messages() {
2283         // Create some users.
2284         $user1 = self::getDataGenerator()->create_user();
2285         $user2 = self::getDataGenerator()->create_user();
2286         $user3 = self::getDataGenerator()->create_user();
2287         $user4 = self::getDataGenerator()->create_user();
2289         // Create group conversation.
2290         $conversation = \core_message\api::create_conversation(
2291             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2292             [$user1->id, $user2->id, $user3->id, $user4->id]
2293         );
2295         // The person doing the search.
2296         $this->setUser($user1);
2298         // Send some messages back and forth.
2299         $time = 1;
2300         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
2301         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
2302         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
2303         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 4);
2304         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Yeah!', $time + 5);
2306         // Retrieve the messages.
2307         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id);
2309         // Confirm the conversation id is correct.
2310         $this->assertEquals($conversation->id, $convmessages['id']);
2312         // Confirm the message data is correct.
2313         $messages = $convmessages['messages'];
2314         $this->assertEquals(5, count($messages));
2316         $message1 = $messages[0];
2317         $message2 = $messages[1];
2318         $message3 = $messages[2];
2319         $message4 = $messages[3];
2320         $message5 = $messages[4];
2322         $this->assertEquals($user1->id, $message1->useridfrom);
2323         $this->assertContains('Yo!', $message1->text);
2325         $this->assertEquals($user2->id, $message2->useridfrom);
2326         $this->assertContains('Sup mang?', $message2->text);
2328         $this->assertEquals($user3->id, $message3->useridfrom);
2329         $this->assertContains('Writing PHPUnit tests!', $message3->text);
2331         $this->assertEquals($user1->id, $message4->useridfrom);
2332         $this->assertContains('Word.', $message4->text);
2334         $this->assertEquals($user2->id, $message5->useridfrom);
2335         $this->assertContains('Yeah!', $message5->text);
2337         // Confirm the members data is correct.
2338         $members = $convmessages['members'];
2339         $this->assertEquals(3, count($members));
2340     }
2342     /**
2343      * Test verifying the sorting param for get_conversation_messages is respected().
2344      */
2345     public function test_get_conversation_messages_sorting() {
2346         // Create some users.
2347         $user1 = self::getDataGenerator()->create_user();
2348         $user2 = self::getDataGenerator()->create_user();
2349         $user3 = self::getDataGenerator()->create_user();
2351         // Create conversations - 1 group and 1 individual.
2352         $conversation = \core_message\api::create_conversation(
2353             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2354             [$user1->id, $user2->id]
2355         );
2356         $conversation2 = \core_message\api::create_conversation(
2357             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2358             [$user1->id, $user2->id, $user3->id]
2359         );
2361         // Send some messages back and forth.
2362         $time = 1;
2363         $m1id = testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
2364         $m2id = testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
2365         $m3id = testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
2366         $m4id = testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 4);
2368         $gm1id = testhelper::send_fake_message_to_conversation($user1, $conversation2->id, 'Yo!', $time + 1);
2369         $gm2id = testhelper::send_fake_message_to_conversation($user2, $conversation2->id, 'Sup mang?', $time + 2);
2370         $gm3id = testhelper::send_fake_message_to_conversation($user3, $conversation2->id, 'Writing PHPUnit tests!', $time + 3);
2371         $gm4id = testhelper::send_fake_message_to_conversation($user1, $conversation2->id, 'Word.', $time + 4);
2373         // The person doing the search.
2374         $this->setUser($user1);
2376         // Retrieve the messages using default sort ('timecreated ASC') and verify ordering.
2377         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id);
2378         $messages = $convmessages['messages'];
2379         $this->assertEquals($m1id, $messages[0]->id);
2380         $this->assertEquals($m2id, $messages[1]->id);
2381         $this->assertEquals($m3id, $messages[2]->id);
2382         $this->assertEquals($m4id, $messages[3]->id);
2384         // Retrieve the messages without specifying DESC sort ordering, and verify ordering.
2385         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated DESC');
2386         $messages = $convmessages['messages'];
2387         $this->assertEquals($m1id, $messages[3]->id);
2388         $this->assertEquals($m2id, $messages[2]->id);
2389         $this->assertEquals($m3id, $messages[1]->id);
2390         $this->assertEquals($m4id, $messages[0]->id);
2392         // Retrieve the messages using default sort ('timecreated ASC') and verify ordering.
2393         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation2->id);
2394         $messages = $convmessages['messages'];
2395         $this->assertEquals($gm1id, $messages[0]->id);
2396         $this->assertEquals($gm2id, $messages[1]->id);
2397         $this->assertEquals($gm3id, $messages[2]->id);
2398         $this->assertEquals($gm4id, $messages[3]->id);
2400         // Retrieve the messages without specifying DESC sort ordering, and verify ordering.
2401         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation2->id, 0, 0, 'timecreated DESC');
2402         $messages = $convmessages['messages'];
2403         $this->assertEquals($gm1id, $messages[3]->id);
2404         $this->assertEquals($gm2id, $messages[2]->id);
2405         $this->assertEquals($gm3id, $messages[1]->id);
2406         $this->assertEquals($gm4id, $messages[0]->id);
2407     }
2409     /**
2410      * Test retrieving conversation messages by providing a minimum timecreated value.
2411      */
2412     public function test_get_conversation_messages_time_from_only() {
2413         // Create some users.
2414         $user1 = self::getDataGenerator()->create_user();
2415         $user2 = self::getDataGenerator()->create_user();
2416         $user3 = self::getDataGenerator()->create_user();
2417         $user4 = self::getDataGenerator()->create_user();
2419         // Create group conversation.
2420         $conversation = \core_message\api::create_conversation(
2421             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2422             [$user1->id, $user2->id, $user3->id, $user4->id]
2423         );
2425         // The person doing the search.
2426         $this->setUser($user1);
2428         // Send some messages back and forth.
2429         $time = 1;
2430         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2431         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2432         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2433         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2435         // Retrieve the messages from $time, which should be all of them.
2436         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated ASC', $time);
2438         // Confirm the conversation id is correct.
2439         $this->assertEquals($conversation->id, $convmessages['id']);
2441         // Confirm the message data is correct.
2442         $messages = $convmessages['messages'];
2443         $this->assertEquals(4, count($messages));
2445         $message1 = $messages[0];
2446         $message2 = $messages[1];
2447         $message3 = $messages[2];
2448         $message4 = $messages[3];
2450         $this->assertContains('Message 1', $message1->text);
2451         $this->assertContains('Message 2', $message2->text);
2452         $this->assertContains('Message 3', $message3->text);
2453         $this->assertContains('Message 4', $message4->text);
2455         // Confirm the members data is correct.
2456         $members = $convmessages['members'];
2457         $this->assertEquals(3, count($members));
2459         // Retrieve the messages from $time + 3, which should only be the 2 last messages.
2460         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0,
2461             'timecreated ASC', $time + 3);
2463         // Confirm the conversation id is correct.
2464         $this->assertEquals($conversation->id, $convmessages['id']);
2466         // Confirm the message data is correct.
2467         $messages = $convmessages['messages'];
2468         $this->assertEquals(2, count($messages));
2470         $message1 = $messages[0];
2471         $message2 = $messages[1];
2473         $this->assertContains('Message 3', $message1->text);
2474         $this->assertContains('Message 4', $message2->text);
2476         // Confirm the members data is correct.
2477         $members = $convmessages['members'];
2478         $this->assertEquals(2, count($members));
2479     }
2481     /**
2482      * Test retrieving conversation messages by providing a maximum timecreated value.
2483      */
2484     public function test_get_conversation_messages_time_to_only() {
2485         // Create some users.
2486         $user1 = self::getDataGenerator()->create_user();
2487         $user2 = self::getDataGenerator()->create_user();
2488         $user3 = self::getDataGenerator()->create_user();
2489         $user4 = self::getDataGenerator()->create_user();
2491         // Create group conversation.
2492         $conversation = \core_message\api::create_conversation(
2493             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2494             [$user1->id, $user2->id, $user3->id, $user4->id]
2495         );
2497         // The person doing the search.
2498         $this->setUser($user1);
2500         // Send some messages back and forth.
2501         $time = 1;
2502         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2503         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2504         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2505         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2507         // Retrieve the messages up until $time + 4, which should be all of them.
2508         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated ASC',
2509             0, $time + 4);
2511         // Confirm the conversation id is correct.
2512         $this->assertEquals($conversation->id, $convmessages['id']);
2514         // Confirm the message data is correct.
2515         $messages = $convmessages['messages'];
2516         $this->assertEquals(4, count($messages));
2518         $message1 = $messages[0];
2519         $message2 = $messages[1];
2520         $message3 = $messages[2];
2521         $message4 = $messages[3];
2523         $this->assertContains('Message 1', $message1->text);
2524         $this->assertContains('Message 2', $message2->text);
2525         $this->assertContains('Message 3', $message3->text);
2526         $this->assertContains('Message 4', $message4->text);
2528         // Confirm the members data is correct.
2529         $members = $convmessages['members'];
2530         $this->assertEquals(3, count($members));
2532         // Retrieve the messages up until $time + 2, which should be the first two.
2533         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated ASC',
2534             0, $time + 2);
2536         // Confirm the conversation id is correct.
2537         $this->assertEquals($conversation->id, $convmessages['id']);
2539         // Confirm the message data is correct.
2540         $messages = $convmessages['messages'];
2541         $this->assertEquals(2, count($messages));
2543         $message1 = $messages[0];
2544         $message2 = $messages[1];
2546         $this->assertContains('Message 1', $message1->text);
2547         $this->assertContains('Message 2', $message2->text);
2549         // Confirm the members data is correct.
2550         $members = $convmessages['members'];
2551         $this->assertEquals(2, count($members));
2552     }
2554     /**
2555      * Test retrieving conversation messages by providing a minimum and maximum timecreated value.
2556      */
2557     public function test_get_conversation_messages_time_from_and_to() {
2558         // Create some users.
2559         $user1 = self::getDataGenerator()->create_user();
2560         $user2 = self::getDataGenerator()->create_user();
2561         $user3 = self::getDataGenerator()->create_user();
2562         $user4 = self::getDataGenerator()->create_user();
2564         // Create group conversation.
2565         $conversation = \core_message\api::create_conversation(
2566             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2567             [$user1->id, $user2->id, $user3->id, $user4->id]
2568         );
2570         // The person doing the search.
2571         $this->setUser($user1);
2573         // Send some messages back and forth.
2574         $time = 1;
2575         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2576         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2577         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2578         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2580         // Retrieve the messages from $time + 2 up until $time + 3, which should be 2nd and 3rd message.
2581         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0,
2582             'timecreated ASC', $time + 2, $time + 3);
2584         // Confirm the conversation id is correct.
2585         $this->assertEquals($conversation->id, $convmessages['id']);
2587         // Confirm the message data is correct.
2588         $messages = $convmessages['messages'];
2589         $this->assertEquals(2, count($messages));
2591         $message1 = $messages[0];
2592         $message2 = $messages[1];
2594         $this->assertContains('Message 2', $message1->text);
2595         $this->assertContains('Message 3', $message2->text);
2597         // Confirm the members data is correct.
2598         $members = $convmessages['members'];
2599         $this->assertEquals(2, count($members));
2600     }
2603     /**
2604      * Test retrieving conversation messages by providing a limitfrom value.
2605      */
2606     public function test_get_conversation_messages_limitfrom_only() {
2607         // Create some users.
2608         $user1 = self::getDataGenerator()->create_user();
2609         $user2 = self::getDataGenerator()->create_user();
2610         $user3 = self::getDataGenerator()->create_user();
2611         $user4 = self::getDataGenerator()->create_user();
2613         // Create group conversation.
2614         $conversation = \core_message\api::create_conversation(
2615             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2616             [$user1->id, $user2->id, $user3->id, $user4->id]
2617         );
2619         // The person doing the search.
2620         $this->setUser($user1);
2622         // Send some messages back and forth.
2623         $time = 1;
2624         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2625         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2626         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2627         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2629         // Retrieve the messages from $time, which should be all of them.
2630         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 2);
2632         // Confirm the conversation id is correct.
2633         $messages = $convmessages['messages'];
2634         $this->assertEquals($conversation->id, $convmessages['id']);
2636         // Confirm the message data is correct.
2637         $this->assertEquals(2, count($messages));
2639         $message1 = $messages[0];
2640         $message2 = $messages[1];
2642         $this->assertContains('Message 3', $message1->text);
2643         $this->assertContains('Message 4', $message2->text);
2645         // Confirm the members data is correct.
2646         $members = $convmessages['members'];
2647         $this->assertEquals(2, count($members));
2648     }
2650     /**
2651      * Test retrieving conversation messages by providing a limitnum value.
2652      */
2653     public function test_get_conversation_messages_limitnum() {
2654         // Create some users.
2655         $user1 = self::getDataGenerator()->create_user();
2656         $user2 = self::getDataGenerator()->create_user();
2657         $user3 = self::getDataGenerator()->create_user();
2658         $user4 = self::getDataGenerator()->create_user();
2660         // Create group conversation.
2661         $conversation = \core_message\api::create_conversation(
2662             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2663             [$user1->id, $user2->id, $user3->id, $user4->id]
2664         );
2666         // The person doing the search.
2667         $this->setUser($user1);
2669         // Send some messages back and forth.
2670         $time = 1;
2671         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2672         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2673         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2674         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2676         // Retrieve the messages from $time, which should be all of them.
2677         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 2, 1);
2679         // Confirm the conversation id is correct.
2680         $messages = $convmessages['messages'];
2681         $this->assertEquals($conversation->id, $convmessages['id']);
2683         // Confirm the message data is correct.
2684         $messages = $convmessages['messages'];
2685         $this->assertEquals(1, count($messages));
2687         $message1 = $messages[0];
2689         $this->assertContains('Message 3', $message1->text);
2691         // Confirm the members data is correct.
2692         $members = $convmessages['members'];
2693         $this->assertEquals(1, count($members));
2694     }
2696     /**
2697      * Tests retrieving most recent message.
2698      */
2699     public function test_get_most_recent_message() {
2700         // Create some users.
2701         $user1 = self::getDataGenerator()->create_user();
2702         $user2 = self::getDataGenerator()->create_user();
2704         // The person doing the search.
2705         $this->setUser($user1);
2707         // Send some messages back and forth.
2708         $time = 1;
2709         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2710         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2711         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2712         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2714         // Retrieve the most recent messages.
2715         $message = \core_message\api::get_most_recent_message($user1->id, $user2->id);
2717         // Check the results are correct.
2718         $this->assertEquals($user2->id, $message->useridfrom);
2719         $this->assertEquals($user1->id, $message->useridto);
2720         $this->assertContains('Word.', $message->text);
2721     }
2723     /**
2724      * Tests retrieving most recent conversation message.
2725      */
2726     public function test_get_most_recent_conversation_message() {
2727         // Create some users.
2728         $user1 = self::getDataGenerator()->create_user();
2729         $user2 = self::getDataGenerator()->create_user();
2730         $user3 = self::getDataGenerator()->create_user();
2732         // Create group conversation.
2733         $conversation = \core_message\api::create_conversation(
2734             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2735             [$user1->id, $user2->id, $user3->id]
2736         );
2738         // The person getting the most recent conversation message.
2739         $this->setUser($user1);
2741         // Send some messages back and forth.
2742         $time = 1;
2743         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
2744         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
2745         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
2746         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Word.', $time + 4);
2748         // Retrieve the most recent messages.
2749         $message = \core_message\api::get_most_recent_conversation_message($conversation->id, $user1->id);
2751         // Check the results are correct.
2752         $this->assertEquals($user2->id, $message->useridfrom);
2753         $this->assertContains('Word.', $message->text);
2754     }
2756     /**
2757      * Tests retrieving a user's profile.
2758      */
2759     public function test_get_profile() {
2760         // Create some users.
2761         $user1 = self::getDataGenerator()->create_user();
2763         $user2 = new stdClass();
2764         $user2->country = 'AU';
2765         $user2->city = 'Perth';
2766         $user2 = self::getDataGenerator()->create_user($user2);
2768         // The person doing the search.
2769         $this->setUser($user1);
2771         // Get the profile.
2772         $profile = \core_message\api::get_profile($user1->id, $user2->id);
2774         $this->assertEquals($user2->id, $profile->userid);
2775         $this->assertEmpty($profile->email);
2776         $this->assertEmpty($profile->country);
2777         $this->assertEmpty($profile->city);
2778         $this->assertEquals(fullname($user2), $profile->fullname);
2779         $this->assertNull($profile->isonline);
2780         $this->assertFalse($profile->isblocked);
2781         $this->assertFalse($profile->iscontact);
2782     }
2784     /**
2785      * Tests retrieving a user's profile.
2786      */
2787     public function test_get_profile_as_admin() {
2788         // The person doing the search.
2789         $this->setAdminUser();
2791         // Create some users.
2792         $user1 = self::getDataGenerator()->create_user();
2794         $user2 = new stdClass();
2795         $user2->country = 'AU';
2796         $user2->city = 'Perth';
2797         $user2 = self::getDataGenerator()->create_user($user2);
2799         // Get the profile.
2800         $profile = \core_message\api::get_profile($user1->id, $user2->id);
2802         $this->assertEquals($user2->id, $profile->userid);
2803         $this->assertEquals($user2->email, $profile->email);
2804         $this->assertEquals($user2->country, $profile->country);
2805         $this->assertEquals($user2->city, $profile->city);
2806         $this->assertEquals(fullname($user2), $profile->fullname);
2807         $this->assertFalse($profile->isonline);
2808         $this->assertFalse($profile->isblocked);
2809         $this->assertFalse($profile->iscontact);
2810     }
2812     /**
2813      * Tests checking if a user can mark all messages as read.
2814      */
2815     public function test_can_mark_all_messages_as_read() {
2816         // Set as the admin.
2817         $this->setAdminUser();
2819         // Create some users.
2820         $user1 = self::getDataGenerator()->create_user();
2821         $user2 = self::getDataGenerator()->create_user();
2822         $user3 = self::getDataGenerator()->create_user();
2824         // Send some messages back and forth.
2825         $time = 1;
2826         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2827         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2828         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2829         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2831         $conversationid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2833         // The admin can do anything.
2834         $this->assertTrue(\core_message\api::can_mark_all_messages_as_read($user1->id, $conversationid));
2836         // Set as the user 1.
2837         $this->setUser($user1);
2839         // The user can mark the messages as he is in the conversation.
2840         $this->assertTrue(\core_message\api::can_mark_all_messages_as_read($user1->id, $conversationid));
2842         // User 1 can not mark the messages read for user 2.
2843         $this->assertFalse(\core_message\api::can_mark_all_messages_as_read($user2->id, $conversationid));
2845         // This user is not a part of the conversation.
2846         $this->assertFalse(\core_message\api::can_mark_all_messages_as_read($user3->id, $conversationid));
2847     }
2849     /**
2850      * Tests checking if a user can delete a conversation.
2851      */
2852     public function test_can_delete_conversation() {
2853         // Set as the admin.
2854         $this->setAdminUser();
2856         // Create some users.
2857         $user1 = self::getDataGenerator()->create_user();
2858         $user2 = self::getDataGenerator()->create_user();
2860         // Send some messages back and forth.
2861         $time = 1;
2862         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2863         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2864         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2865         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2867         $conversationid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2869         // The admin can do anything.
2870         $this->assertTrue(\core_message\api::can_delete_conversation($user1->id, $conversationid));
2872         // Set as the user 1.
2873         $this->setUser($user1);
2875         // They can delete their own messages.
2876         $this->assertTrue(\core_message\api::can_delete_conversation($user1->id, $conversationid));
2878         // They can't delete someone elses.
2879         $this->assertFalse(\core_message\api::can_delete_conversation($user2->id, $conversationid));
2880     }
2882     /**
2883      * Tests deleting a conversation.
2884      */
2885     public function test_delete_conversation() {
2886         global $DB;
2888         // Create some users.
2889         $user1 = self::getDataGenerator()->create_user();
2890         $user2 = self::getDataGenerator()->create_user();
2892         // The person doing the search.
2893         $this->setUser($user1);
2895         // Send some messages back and forth.
2896         $time = 1;
2897         $m1id = $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2898         $m2id = $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2899         $m3id = $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2900         $m4id = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2902         // Delete the conversation as user 1.
2903         \core_message\api::delete_conversation($user1->id, $user2->id);
2904         $this->assertDebuggingCalled();
2906         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
2907         $this->assertCount(4, $muas);
2908         // Sort by id.
2909         ksort($muas);
2911         $mua1 = array_shift($muas);
2912         $mua2 = array_shift($muas);
2913         $mua3 = array_shift($muas);
2914         $mua4 = array_shift($muas);
2916         $this->assertEquals($user1->id, $mua1->userid);
2917         $this->assertEquals($m1id, $mua1->messageid);
2918         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
2920         $this->assertEquals($user1->id, $mua2->userid);
2921         $this->assertEquals($m2id, $mua2->messageid);
2922         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
2924         $this->assertEquals($user1->id, $mua3->userid);
2925         $this->assertEquals($m3id, $mua3->messageid);
2926         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
2928         $this->assertEquals($user1->id, $mua4->userid);
2929         $this->assertEquals($m4id, $mua4->messageid);
2930         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
2931     }
2933     /**
2934      * Tests deleting a conversation by conversation id.
2935      */
2936     public function test_delete_conversation_by_id() {
2937         global $DB;
2939         // Create some users.
2940         $user1 = self::getDataGenerator()->create_user();
2941         $user2 = self::getDataGenerator()->create_user();
2943         // The person doing the search.
2944         $this->setUser($user1);
2946         // Send some messages back and forth.
2947         $time = 1;
2948         $m1id = $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2949         $m2id = $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2950         $m3id = $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2951         $m4id = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2953         // Delete the conversation as user 1.
2954         $conversationid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2955         \core_message\api::delete_conversation_by_id($user1->id, $conversationid);
2957         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
2958         $this->assertCount(4, $muas);
2959         // Sort by id.
2960         ksort($muas);
2962         $mua1 = array_shift($muas);
2963         $mua2 = array_shift($muas);
2964         $mua3 = array_shift($muas);
2965         $mua4 = array_shift($muas);
2967         $this->assertEquals($user1->id, $mua1->userid);
2968         $this->assertEquals($m1id, $mua1->messageid);
2969         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
2971         $this->assertEquals($user1->id, $mua2->userid);
2972         $this->assertEquals($m2id, $mua2->messageid);
2973         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
2975         $this->assertEquals($user1->id, $mua3->userid);
2976         $this->assertEquals($m3id, $mua3->messageid);
2977         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
2979         $this->assertEquals($user1->id, $mua4->userid);
2980         $this->assertEquals($m4id, $mua4->messageid);
2981         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
2982     }
2984     /**
2985      * Tests counting unread conversations.
2986      */
2987     public function test_count_unread_conversations() {
2988         $this->resetAfterTest(true);
2990         // Create some users.
2991         $user1 = self::getDataGenerator()->create_user();
2992         $user2 = self::getDataGenerator()->create_user();
2993         $user3 = self::getDataGenerator()->create_user();
2994         $user4 = self::getDataGenerator()->create_user();
2996         // The person wanting the conversation count.
2997         $this->setUser($user1);
2999         // Send some messages back and forth, have some different conversations with different users.
3000         $this->send_fake_message($user1, $user2, 'Yo!');
3001         $this->send_fake_message($user2, $user1, 'Sup mang?');
3002         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!');
3003         $this->send_fake_message($user2, $user1, 'Word.');
3005         $this->send_fake_message($user1, $user3, 'Booyah');
3006         $this->send_fake_message($user3, $user1, 'Whaaat?');
3007         $this->send_fake_message($user1, $user3, 'Nothing.');
3008         $this->send_fake_message($user3, $user1, 'Cool.');
3010         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
3011         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
3012         $this->send_fake_message($user1, $user4, 'Dope.');
3014         // Check the amount for the current user.
3015         $this->assertEquals(3, core_message\api::count_unread_conversations());
3017         // Check the amount for the second user.
3018         $this->assertEquals(1, core_message\api::count_unread_conversations($user2));
3019     }
3021     /**
3022      * Tests deleting a conversation.
3023      */
3024     public function test_get_all_message_preferences() {
3025         $user = self::getDataGenerator()->create_user();
3026         $this->setUser($user);
3028         // Set a couple of preferences to test.
3029         set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
3030         set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
3032         $processors = get_message_processors();
3033         $providers = message_get_providers_for_user($user->id);
3034         $prefs = \core_message\api::get_all_message_preferences($processors, $providers, $user);
3036         $this->assertEquals(1, $prefs->mod_assign_assign_notification_loggedin['popup']);
3037         $this->assertEquals(1, $prefs->mod_assign_assign_notification_loggedoff['email']);
3038     }
3040     /**
3041      * Tests the user can post a message.
3042      */
3043     public function test_can_post_message() {
3044         // Create some users.
3045         $user1 = self::getDataGenerator()->create_user();
3046         $user2 = self::getDataGenerator()->create_user();
3048         // Set as the first user.
3049         $this->setUser($user1);
3051         // With the default privacy setting, users can't message them.
3052         $this->assertFalse(\core_message\api::can_post_message($user2));
3054         // Enrol users to the same course.
3055         $course = $this->getDataGenerator()->create_course();
3056         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
3057         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
3058         // After enrolling users to the course, they should be able to message them with the default privacy setting.
3059         $this->assertTrue(\core_message\api::can_post_message($user2));
3060     }
3062     /**
3063      * Tests the user can't post a message without proper capability.
3064      */
3065     public function test_can_post_message_without_sendmessage_cap() {
3066         global $DB;
3068         // Create some users.
3069         $user1 = self::getDataGenerator()->create_user();
3070         $user2 = self::getDataGenerator()->create_user();
3072         // Set as the user 1.
3073         $this->setUser($user1);
3075         // Remove the capability to send a message.
3076         $roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
3077         unassign_capability('moodle/site:sendmessage', $roleids['user'],
3078             context_system::instance());
3080         // Check that we can not post a message without the capability.
3081         $this->assertFalse(\core_message\api::can_post_message($user2));
3082     }
3084     /**
3085      * Tests the user can post a message when they are contact.
3086      */
3087     public function test_can_post_message_when_contact() {
3088         // Create some users.
3089         $user1 = self::getDataGenerator()->create_user();
3090         $user2 = self::getDataGenerator()->create_user();
3092         // Set as the first user.
3093         $this->setUser($user1);
3095         // Check that we can not send user2 a message.
3096         $this->assertFalse(\core_message\api::can_post_message($user2));
3098         // Add users as contacts.
3099         \core_message\api::add_contact($user1->id, $user2->id);
3101         // Check that the return result is now true.
3102         $this->assertTrue(\core_message\api::can_post_message($user2));
3103     }
3105     /**
3106      * Tests the user can't post a message if they are not a contact and the user
3107      * has requested messages only from contacts.
3108      */
3109     public function test_can_post_message_when_not_contact() {
3110         // Create some users.
3111         $user1 = self::getDataGenerator()->create_user();
3112         $user2 = self::getDataGenerator()->create_user();
3114         // Set as the first user.
3115         $this->setUser($user1);
3117         // Set the second user's preference to not receive messages from non-contacts.
3118         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
3120         // Check that we can not send user 2 a message.
3121         $this->assertFalse(\core_message\api::can_post_message($user2));
3122     }
3124     /**
3125      * Tests the user can't post a message if they are blocked.
3126      */
3127     public function test_can_post_message_when_blocked() {
3128         // Create some users.
3129         $user1 = self::getDataGenerator()->create_user();
3130         $user2 = self::getDataGenerator()->create_user();
3132         // Set the user.
3133         $this->setUser($user1);
3135         // Block the second user.
3136         \core_message\api::block_user($user1->id, $user2->id);
3138         // Check that the second user can no longer send the first user a message.
3139         $this->assertFalse(\core_message\api::can_post_message($user1, $user2));
3140     }
3142     /**
3143      * Tests the user can post a message when site-wide messaging setting is enabled,
3144      * even if they are not a contact and are not members of the same course.
3145      */
3146     public function test_can_post_message_site_messaging_setting() {
3147         // Create some users.
3148         $user1 = self::getDataGenerator()->create_user();
3149         $user2 = self::getDataGenerator()->create_user();
3151         // Set as the first user.
3152         $this->setUser($user1);
3154         // By default, user only can be messaged by contacts and members of any of his/her courses.
3155         $this->assertFalse(\core_message\api::can_post_message($user2));
3157         // Enable site-wide messagging privacy setting. The user will be able to receive messages from everybody.
3158         set_config('messagingallusers', true);
3160         // Set the second user's preference to receive messages from everybody.
3161         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_SITE, $user2->id);
3163         // Check that we can send user2 a message.
3164         $this->assertTrue(\core_message\api::can_post_message($user2));
3166         // Disable site-wide messagging privacy setting. The user will be able to receive messages from contacts
3167         // and members sharing a course with her.
3168         set_config('messagingallusers', false);
3170         // As site-wide messaging setting is disabled, the value for user2 will be changed to MESSAGE_PRIVACY_COURSEMEMBER.
3171         $this->assertFalse(\core_message\api::can_post_message($user2));
3173         // Enrol users to the same course.
3174         $course = $this->getDataGenerator()->create_course();
3175         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
3176         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
3177         // Check that we can send user2 a message because they are sharing a course.
3178         $this->assertTrue(\core_message\api::can_post_message($user2));
3180         // Set the second user's preference to receive messages only from contacts.
3181         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
3182         // Check that now the user2 can't be contacted because user1 is not their contact.
3183         $this->assertFalse(\core_message\api::can_post_message($user2));
3185         // Make contacts user1 and user2.
3186         \core_message\api::add_contact($user2->id, $user1->id);
3187         // Check that we can send user2 a message because they are contacts.
3188         $this->assertTrue(\core_message\api::can_post_message($user2));
3189     }
3191     /**
3192      * Tests the user with the messageanyuser capability can post a message.
3193      */
3194     public function test_can_post_message_with_messageanyuser_cap() {
3195         global $DB;
3197         // Create some users.
3198         $teacher1 = self::getDataGenerator()->create_user();
3199         $student1 = self::getDataGenerator()->create_user();
3200         $student2 = self::getDataGenerator()->create_user();
3202         // Create users not enrolled in any course.
3203         $user1 = self::getDataGenerator()->create_user();
3205         // Create a course.
3206         $course1 = $this->getDataGenerator()->create_course();
3208         // Enrol the users in the course.
3209         $this->getDataGenerator()->enrol_user($teacher1->id, $course1->id, 'editingteacher');
3210         $this->getDataGenerator()->enrol_user($student1->id, $course1->id, 'student');
3211         $this->getDataGenerator()->enrol_user($student2->id, $course1->id, 'student');
3213         // Set some student preferences to not receive messages from non-contacts.
3214         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $student1->id);
3216         // Check that we can send student1 a message because teacher has the messageanyuser cap by default.
3217         $this->assertTrue(\core_message\api::can_post_message($student1, $teacher1));
3218         // Check that the teacher can't contact user1 because it's not his teacher.
3219         $this->assertFalse(\core_message\api::can_post_message($user1, $teacher1));
3221         // Remove the messageanyuser capability from the course1 for teachers.
3222         $coursecontext = context_course::instance($course1->id);
3223         $teacherrole = $DB->get_record('role', ['shortname' => 'editingteacher']);
3224         assign_capability('moodle/site:messageanyuser', CAP_PROHIBIT, $teacherrole->id, $coursecontext->id);
3225         $coursecontext->mark_dirty();
3227         // Check that we can't send user1 a message because they are not contacts.
3228         $this->assertFalse(\core_message\api::can_post_message($student1, $teacher1));
3229         // However, teacher can message student2 because they are sharing a course.
3230         $this->assertTrue(\core_message\api::can_post_message($student2, $teacher1));
3231     }
3233     /**
3234      * Verify the expected behaviour of the can_send_message_to_conversation() method for authenticated users with default settings.
3235      */
3236     public function test_can_send_message_to_conversation_basic() {
3237         // Create some users.
3238         $user1 = self::getDataGenerator()->create_user();
3239         $user2 = self::getDataGenerator()->create_user();
3240         $user3 = self::getDataGenerator()->create_user();
3242         // Create an individual conversation between user1 and user2.
3243         $ic1 = \core_message\api::create_conversation(
3244             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3245             [
3246                 $user1->id,
3247                 $user2->id
3248             ]
3249         );
3251         // Create a group conversation between and users 1, 2 and 3.
3252         $gc1 = \core_message\api::create_conversation(
3253             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3254             [
3255                 $user1->id,
3256                 $user2->id,
3257                 $user3->id
3258             ]
3259         );
3261         // For group conversations, there are no user privacy checks, so only membership in the conversation is needed.
3262         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3264         // For individual conversations, the default privacy setting of 'only contacts and course members' applies.
3265         // Users are not in the same course, nor are they contacts, so messages cannot be sent.
3266         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3268         // Enrol the users into the same course.
3269         $course = $this->getDataGenerator()->create_course();
3270         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
3271         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
3273         // After enrolling users to the course, they should be able to message them with the default privacy setting.
3274         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3275     }
3277     /**
3278      * Verify the behaviour of can_send_message_to_conversation() for authenticated users without the sendmessage capability.
3279      */
3280     public function test_can_send_message_to_conversation_sendmessage_cap() {
3281         global $DB;
3283         $user1 = self::getDataGenerator()->create_user();
3284         $user2 = self::getDataGenerator()->create_user();
3285         $user3 = self::getDataGenerator()->create_user();
3287         // Enrol the users into the same course.
3288         $course = $this->getDataGenerator()->create_course();
3289         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
3290         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
3291         $this->getDataGenerator()->enrol_user($user3->id, $course->id);
3293         // Create an individual conversation between user1 and user2.
3294         $ic1 = \core_message\api::create_conversation(
3295             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3296             [
3297                 $user1->id,
3298                 $user2->id
3299             ]
3300         );
3302         // Group conversation between and users 1, 2 and 3.
3303         $gc1 = \core_message\api::create_conversation(
3304             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3305             [
3306                 $user1->id,
3307                 $user2->id,
3308                 $user3->id
3309             ]
3310         );
3312         // Default settings - user1 can send a message to both conversations.
3313         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3314         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3316         // Remove the capability to send a message.
3317         $roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
3318         unassign_capability('moodle/site:sendmessage', $roleids['user'], context_system::instance());
3320         // Verify that a user cannot send a message to either an individual or a group conversation.
3321         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3322         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3323     }
3325     /**
3326      * Verify the behaviour of can_send_message_to_conversation() for authenticated users without the messageanyuser capability.
3327      */
3328     public function test_can_send_message_to_conversation_messageanyuser_cap() {
3329         global $DB;
3331         $user1 = self::getDataGenerator()->create_user();
3332         $user2 = self::getDataGenerator()->create_user();
3333         $user3 = self::getDataGenerator()->create_user();
3335         // Enrol the users into the same course.
3336         $course = $this->getDataGenerator()->create_course();
3337         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
3338         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
3339         $this->getDataGenerator()->enrol_user($user3->id, $course->id);
3341         // Create an individual conversation between user1 and user2.
3342         $ic1 = \core_message\api::create_conversation(
3343             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3344             [
3345                 $user1->id,
3346                 $user2->id
3347             ]
3348         );
3350         // Group conversation between and users 1, 2 and 3.
3351         $gc1 = \core_message\api::create_conversation(
3352             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3353             [
3354                 $user1->id,
3355                 $user2->id,
3356                 $user3->id
3357             ]
3358         );
3360         // Update the message preference for user2, so they can only be messaged by contacts.
3361         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
3363         // Verify that the user cannot be contacted in the individual conversation and that groups are unaffected.
3364         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3365         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3367         // Assign the 'messageanyuser' capability to user1 at system context.
3368         $systemcontext = context_system::instance();
3369         $authenticateduser = $DB->get_record('role', ['shortname' => 'user']);
3370         assign_capability('moodle/site:messageanyuser', CAP_ALLOW, $authenticateduser->id, $systemcontext->id);
3372         // Check that user1 can now message user2 due to the capability, and that group conversations is again unaffected.
3373         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3374         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3375     }
3377     /**
3378      * Test verifying that users cannot send messages to conversations they are not a part of.
3379      */
3380     public function test_can_post_message_to_conversation_non_member() {
3381         // Create some users.
3382         $user1 = self::getDataGenerator()->create_user();
3383         $user2 = self::getDataGenerator()->create_user();
3384         $user3 = self::getDataGenerator()->create_user();
3385         $user4 = self::getDataGenerator()->create_user();
3387         // Enrol the users into the same course.
3388         $course = $this->getDataGenerator()->create_course();
3389         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
3390         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
3391         $this->getDataGenerator()->enrol_user($user3->id, $course->id);
3392         $this->getDataGenerator()->enrol_user($user4->id, $course->id);
3394         // Create an individual conversation between user1 and user2.
3395         $ic1 = \core_message\api::create_conversation(
3396             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3397             [
3398                 $user1->id,
3399                 $user2->id
3400             ]
3401         );
3403         // Create a group conversation between and users 1, 2 and 3.
3404         $gc1 = \core_message\api::create_conversation(
3405             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3406             [
3407                 $user1->id,
3408                 $user2->id,
3409                 $user3->id
3410             ]
3411         );
3413         // Verify, non members cannot send a message.
3414         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user4->id, $gc1->id));
3415         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user4->id, $ic1->id));
3416     }
3418     /**
3419      * Test verifying the behaviour of the can_send_message_to_conversation method when privacy is set to contacts only.
3420      */
3421     public function test_can_send_message_to_conversation_privacy_contacts_only() {
3422         // Create some users.
3423         $user1 = self::getDataGenerator()->create_user();
3424         $user2 = self::getDataGenerator()->create_user();
3425         $user3 = self::getDataGenerator()->create_user();
3427         // Create an individual conversation between user1 and user2.
3428         $ic1 = \core_message\api::create_conversation(
3429             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3430             [
3431                 $user1->id,
3432                 $user2->id
3433             ]
3434         );
3436         // Create a group conversation between and users 1, 2 and 3.
3437         $gc1 = \core_message\api::create_conversation(
3438             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3439             [
3440                 $user1->id,
3441                 $user2->id,
3442                 $user3->id
3443             ]
3444         );
3446         // Set the message privacy preference to 'contacts only' for user 2.
3447         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
3449         // Verify that user1 cannot send a message to the individual conversation, but that the group conversation is unaffected.
3450         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3451         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3453         // Now, simulate a contact request (and approval) between user1 and user2.
3454         \core_message\api::create_contact_request($user1->id, $user2->id);
3455         \core_message\api::confirm_contact_request($user1->id, $user2->id);
3457         // Verify user1 can now message user2 again via their individual conversation.
3458         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3459     }
3461     /**
3462      * Test verifying the behaviour of the can_send_message_to_conversation method when privacy is set to contacts / course members.
3463      */
3464     public function test_can_send_message_to_conversation_privacy_contacts_course() {
3465         // Create some users.
3466         $user1 = self::getDataGenerator()->create_user();
3467         $user2 = self::getDataGenerator()->create_user();
3468         $user3 = self::getDataGenerator()->create_user();
3470         // Set the message privacy preference to 'contacts + course members' for user 2.
3471         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER, $user2->id);
3473         // Create an individual conversation between user1 and user2.
3474         $ic1 = \core_message\api::create_conversation(
3475             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3476             [
3477                 $user1->id,
3478                 $user2->id
3479             ]
3480         );
3482         // Create a group conversation between and users 1, 2 and 3.
3483         $gc1 = \core_message\api::create_conversation(
3484             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3485             [
3486                 $user1->id,
3487                 $user2->id,
3488                 $user3->id
3489             ]
3490         );
3492         // Verify that users in a group conversation can message one another (i.e. privacy controls ignored).
3493         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3495         // Verify that user1 can not message user2 unless they are either contacts, or share a course.
3496         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3498         // Enrol the users into the same course.
3499         $course = $this->getDataGenerator()->create_course();
3500         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
3501         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
3502         $this->getDataGenerator()->enrol_user($user3->id, $course->id);
3504         // Verify that user1 can send a message to user2, based on the shared course, without being a contact.
3505         $this->assertFalse(\core_message\api::is_contact($user1->id, $user2->id));
3506         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3507     }
3509     /**
3510      * Test verifying the behaviour of the can_send_message_to_conversation method when privacy is set to any user.
3511      */
3512     public function test_can_send_message_to_conversation_privacy_sitewide() {
3513         // Create some users.
3514         $user1 = self::getDataGenerator()->create_user();
3515         $user2 = self::getDataGenerator()->create_user();
3516         $user3 = self::getDataGenerator()->create_user();
3518         // Create an individual conversation between user1 and user2.
3519         $ic1 = \core_message\api::create_conversation(
3520             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3521             [
3522                 $user1->id,
3523                 $user2->id
3524             ]
3525         );
3527         // Create a group conversation between and users 1, 2 and 3.
3528         $gc1 = \core_message\api::create_conversation(
3529             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3530             [
3531                 $user1->id,
3532                 $user2->id,
3533                 $user3->id
3534             ]
3535         );
3537         // By default, the messaging privacy dictates that users can only be contacted by contacts, and members of their courses.
3538         // Verify also, that groups are not restricted in this way.
3539         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3540         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3542         // Enable site-wide messagging privacy setting.
3543         // This enables a privacy option for users, allowing them to choose to be contactable by anybody on the site.
3544         set_config('messagingallusers', true);
3546         // Set the second user's preference to receive messages from everybody.
3547         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_SITE, $user2->id);
3549         // Check that user1 can send user2 a message, and that the group conversation is unaffected.
3550         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3551         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3553         // Disable site-wide messagging privacy setting. The user will be able to receive messages from contacts
3554         // and members sharing a course with her.
3555         set_config('messagingallusers', false);
3557         // As site-wide messaging setting is disabled, the value for user2 will be changed to MESSAGE_PRIVACY_COURSEMEMBER.
3558         // Verify also that the group conversation is unaffected.
3559         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3560         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3561     }
3563     /**
3564      * Test verifying the behaviour of the can_send_message_to_conversation method when a user is blocked.
3565      */
3566     public function test_can_send_message_to_conversation_when_blocked() {
3567         $user1 = self::getDataGenerator()->create_user();
3568         $user2 = self::getDataGenerator()->create_user();
3569         $user3 = self::getDataGenerator()->create_user();
3571         // Create an individual conversation between user1 and user2.
3572         $ic1 = \core_message\api::create_conversation(
3573             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3574             [
3575                 $user1->id,
3576                 $user2->id
3577             ]
3578         );
3580         // Create a group conversation between and users 1, 2 and 3.
3581         $gc1 = \core_message\api::create_conversation(
3582             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3583             [
3584                 $user1->id,
3585                 $user2->id,
3586                 $user3->id
3587             ]
3588         );
3590         // Enrol the users into the same course.
3591         $course = $this->getDataGenerator()->create_course();
3592         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
3593         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
3594         $this->getDataGenerator()->enrol_user($user3->id, $course->id);
3596         // Block the second user.
3597         \core_message\api::block_user($user1->id, $user2->id);
3599         // Check that user2 can not send user1 a message in their individual conversation.
3600         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user2->id, $ic1->id));
3602         // Verify that group conversations are unaffected.
3603         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3604         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user2->id, $gc1->id));
3605     }
3607     /**
3608      * Tests get_user_privacy_messaging_preference method.
3609      */
3610     public function test_get_user_privacy_messaging_preference() {
3611         // Create some users.
3612         $user1 = self::getDataGenerator()->create_user();
3613         $user2 = self::getDataGenerator()->create_user();
3614         $user3 = self::getDataGenerator()->create_user();
3616         // Enable site-wide messagging privacy setting. The user will be able to receive messages from everybody.
3617         set_config('messagingallusers', true);
3619         // Set some user preferences.
3620         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_SITE, $user1->id);
3621         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
3623         // Check the returned value for each user.
3624         $this->assertEquals(
3625             \core_message\api::MESSAGE_PRIVACY_SITE,
3626             \core_message\api::get_user_privacy_messaging_preference($user1->id)
3627         );
3628         $this->assertEquals(
3629             \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
3630             \core_message\api::get_user_privacy_messaging_preference($user2->id)
3631         );
3632         $this->assertEquals(
3633             \core_message\api::MESSAGE_PRIVACY_SITE,
3634             \core_message\api::get_user_privacy_messaging_preference($user3->id)
3635         );
3637         // Disable site-wide messagging privacy setting. The user will be able to receive messages from members of their course.
3638         set_config('messagingallusers', false);
3640         // Check the returned value for each user.
3641         $this->assertEquals(
3642             \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
3643             \core_message\api::get_user_privacy_messaging_preference($user1->id)
3644         );
3645         $this->assertEquals(
3646             \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
3647             \core_message\api::get_user_privacy_messaging_preference($user2->id)
3648         );
3649         $this->assertEquals(
3650             \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
3651             \core_message\api::get_user_privacy_messaging_preference($user3->id)
3652         );
3653     }
3655     /**
3656      * Tests that when blocking messages from non-contacts is enabled that
3657      * non-contacts trying to send a message return false.
3658      */
3659     public function test_is_user_non_contact_blocked() {
3660         // Create some users.
3661         $user1 = self::getDataGenerator()->create_user();
3662         $user2 = self::getDataGenerator()->create_user();
3664         // Set as the first user.
3665         $this->setUser($user1);
3667         // By default, user only can be messaged by contacts and members of any of his/her courses.
3668         $this->assertTrue(\core_message\api::is_user_non_contact_blocked($user2));
3669         $this->assertDebuggingCalled();
3671         // Enable all users privacy messaging and check now the default user's preference has been set to allow receiving
3672         // messages from everybody.
3673         set_config('messagingallusers', true);
3674         // Check that the return result is now false because any site user can contact him/her.
3675         $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
3676         $this->assertDebuggingCalled();
3678         // Set the second user's preference to not receive messages from non-contacts.
3679         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
3680         // Check that the return result is still true (because is even more restricted).
3681         $this->assertTrue(\core_message\api::is_user_non_contact_blocked($user2));
3682         $this->assertDebuggingCalled();
3684         // Add the first user as a contact for the second user.
3685         \core_message\api::add_contact($user2->id, $user1->id);
3687         // Check that the return result is now false.
3688         $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
3689         $this->assertDebuggingCalled();
3691         // Set the second user's preference to receive messages from course members.
3692         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER, $user2->id);
3693         // Check that the return result is still false (because $user1 is still his/her contact).
3694         $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
3695         $this->assertDebuggingCalled();
3696     }
3698     /**
3699      * Tests that we return true when a user is blocked, or false
3700      * if they are not blocked.
3701      */
3702     public function test_is_user_blocked() {
3703         // Create some users.
3704         $user1 = self::getDataGenerator()->create_user();
3705         $user2 = self::getDataGenerator()->create_user();
3707         // Set the user.
3708         $this->setUser($user1);
3710         // User shouldn't be blocked.
3711         $this->assertFalse(\core_message\api::is_user_blocked($user1->id, $user2->id));
3712         $this->assertDebuggingCalled();
3714         // Block the user.
3715         \core_message\api::block_user($user1->id, $user2->id);
3717         // User should be blocked.
3718         $this->assertTrue(\core_message\api::is_user_blocked($user1->id, $user2->id));
3719         $this->assertDebuggingCalled();
3721         // Unblock the user.
3722         \core_message\api::unblock_user($user1->id, $user2->id);
3723         $this->assertFalse(\core_message\api::is_user_blocked($user1->id, $user2->id));
3724         $this->assertDebuggingCalled();
3725     }
3727     /**
3728      * Tests that the admin is not blocked even if someone has chosen to block them.
3729      */
3730     public function test_is_user_blocked_as_admin() {
3731         // Create a user.
3732         $user1 = self::getDataGenerator()->create_user();
3734         // Set the user.
3735         $this->setUser($user1);
3737         // Block the admin user.
3738         \core_message\api::block_user($user1->id, 2);
3740         // Now change to the admin user.
3741         $this->setAdminUser();
3743         // As the admin you should still be able to send messages to the user.
3744         $this->assertFalse(\core_message\api::is_user_blocked($user1->id));
3745         $this->assertDebuggingCalled();
3746     }
3748     /*
3749      * Tes get_message_processor api.
3750      */
3751     public function test_get_message_processor() {
3752         $processors = get_message_processors(true);
3753         if (empty($processors)) {
3754             $this->markTestSkipped("No message processors found");
3755         }
3757         $name = key($processors);
3758         $processor = current($processors);
3759         $testprocessor = \core_message\api::get_message_processor($name);
3760         $this->assertEquals($processor->name, $testprocessor->name);
3761         $this->assertEquals($processor->enabled, $testprocessor->enabled);
3762         $this->assertEquals($processor->available, $testprocessor->available);
3763         $this->assertEquals($processor->configured, $testprocessor->configured);
3765         // Disable processor and test.
3766         \core_message\api::update_processor_status($testprocessor, 0);
3767         $testprocessor = \core_message\api::get_message_processor($name, true);
3768         $this->assertEmpty($testprocessor);
3769         $testprocessor = \core_message\api::get_message_processor($name);
3770         $this->assertEquals($processor->name, $testprocessor->name);
3771         $this->assertEquals(0, $testprocessor->enabled);
3773         // Enable again and test.
3774         \core_message\api::update_processor_status($testprocessor, 1);
3775         $testprocessor = \core_message\api::get_message_processor($name, true);
3776         $this->assertEquals($processor->name, $testprocessor->name);
3777         $this->assertEquals(1, $testprocessor->enabled);
3778         $testprocessor = \core_message\api::get_message_processor($name);
3779         $this->assertEquals($processor->name, $testprocessor->name);
3780         $this->assertEquals(1, $testprocessor->enabled);
3781     }
3783     /**
3784      * Test method update_processor_status.
3785      */
3786     public function test_update_processor_status() {
3787         $processors = get_message_processors();
3788         if (empty($processors)) {
3789             $this->markTestSkipped("No message processors found");
3790         }
3791         $name = key($processors);
3792         $testprocessor = current($processors);
3794         // Enable.
3795         \core_message\api::update_processor_status($testprocessor, 1);
3796         $testprocessor = \core_message\api::get_message_processor($name);
3797         $this->assertEquals(1, $testprocessor->enabled);
3799         // Disable.
3800         \core_message\api::update_processor_status($testprocessor, 0);
3801         $testprocessor = \core_message\api::get_message_processor($name);
3802         $this->assertEquals(0, $testprocessor->enabled);
3804         // Enable again.
3805         \core_message\api::update_processor_status($testprocessor, 1);
3806         $testprocessor = \core_message\api::get_message_processor($name);
3807         $this->assertEquals(1, $testprocessor->enabled);
3808     }
3810     /**
3811      * Test method is_user_enabled.
3812      */
3813     public function is_user_enabled() {
3814         $processors = get_message_processors();
3815         if (empty($processors)) {
3816             $this->markTestSkipped("No message processors found");
3817         }
3818         $name = key($processors);
3819         $testprocessor = current($processors);
3821         // Enable.
3822         \core_message\api::update_processor_status($testprocessor, 1);
3823         $status = \core_message\api::is_processor_enabled($name);
3824         $this->assertEquals(1, $status);
3826         // Disable.
3827         \core_message\api::update_processor_status($testprocessor, 0);
3828         $status = \core_message\api::is_processor_enabled($name);
3829         $this->assertEquals(0, $status);
3831         // Enable again.
3832         \core_message\api::update_processor_status($testprocessor, 1);
3833         $status = \core_message\api::is_processor_enabled($name);
3834         $this->assertEquals(1, $status);
3835     }
3837     /**
3838      * Test retrieving messages by providing a minimum timecreated value.
3839      */
3840     public function test_get_messages_time_from_only() {
3841         // Create some users.
3842         $user1 = self::getDataGenerator()->create_user();
3843         $user2 = self::getDataGenerator()->create_user();
3845         // The person doing the search.
3846         $this->setUser($user1);
3848         // Send some messages back and forth.