MDL-63549 core_message: add group support to api::get_conversations
[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.
262         list($contacts, $courses, $noncontacts) = \core_message\api::search_users($user1->id, 'search');
264         // Check that we retrieved the correct contacts.
265         $this->assertEquals(2, count($contacts));
266         $this->assertEquals($user3->id, $contacts[0]->userid);
267         $this->assertEquals($user2->id, $contacts[1]->userid);
269         // Check that we retrieved the correct courses.
270         $this->assertEquals(2, count($courses));
271         $this->assertEquals($course3->id, $courses[0]->id);
272         $this->assertEquals($course1->id, $courses[1]->id);
274         // Check that we retrieved the correct non-contacts.
275         $this->assertEquals(1, count($noncontacts));
276         $this->assertEquals($user5->id, $noncontacts[0]->userid);
277     }
279     /**
280      * Tests searching messages.
281      */
282     public function test_search_messages() {
283         // Create some users.
284         $user1 = self::getDataGenerator()->create_user();
285         $user2 = self::getDataGenerator()->create_user();
286         $user3 = self::getDataGenerator()->create_user();
288         // The person doing the search.
289         $this->setUser($user1);
291         // Send some messages back and forth.
292         $time = 1;
293         $this->send_fake_message($user3, $user1, 'Don\'t block me.', 0, $time);
294         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
295         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
296         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
297         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
299         // Block user 3.
300         \core_message\api::block_user($user1->id, $user3->id);
302         // Perform a search.
303         $messages = \core_message\api::search_messages($user1->id, 'o');
305         // Confirm the data is correct.
306         $this->assertEquals(3, count($messages));
308         $message1 = $messages[0];
309         $message2 = $messages[1];
310         $message3 = $messages[2];
312         $this->assertEquals($user2->id, $message1->userid);
313         $this->assertEquals($user2->id, $message1->useridfrom);
314         $this->assertEquals(fullname($user2), $message1->fullname);
315         $this->assertTrue($message1->ismessaging);
316         $this->assertEquals('Word.', $message1->lastmessage);
317         $this->assertNotEmpty($message1->messageid);
318         $this->assertNull($message1->isonline);
319         $this->assertFalse($message1->isread);
320         $this->assertFalse($message1->isblocked);
321         $this->assertNull($message1->unreadcount);
323         $this->assertEquals($user2->id, $message2->userid);
324         $this->assertEquals($user1->id, $message2->useridfrom);
325         $this->assertEquals(fullname($user2), $message2->fullname);
326         $this->assertTrue($message2->ismessaging);
327         $this->assertEquals('Yo!', $message2->lastmessage);
328         $this->assertNotEmpty($message2->messageid);
329         $this->assertNull($message2->isonline);
330         $this->assertTrue($message2->isread);
331         $this->assertFalse($message2->isblocked);
332         $this->assertNull($message2->unreadcount);
334         $this->assertEquals($user3->id, $message3->userid);
335         $this->assertEquals($user3->id, $message3->useridfrom);
336         $this->assertEquals(fullname($user3), $message3->fullname);
337         $this->assertTrue($message3->ismessaging);
338         $this->assertEquals('Don\'t block me.', $message3->lastmessage);
339         $this->assertNotEmpty($message3->messageid);
340         $this->assertNull($message3->isonline);
341         $this->assertFalse($message3->isread);
342         $this->assertTrue($message3->isblocked);
343         $this->assertNull($message3->unreadcount);
344     }
346     /**
347      * Test verifying that favourited conversations can be retrieved.
348      */
349     public function test_get_favourite_conversations() {
350         // Create some users.
351         $user1 = self::getDataGenerator()->create_user();
352         $user2 = self::getDataGenerator()->create_user();
353         $user3 = self::getDataGenerator()->create_user();
354         $user4 = self::getDataGenerator()->create_user();
356         // The person doing the search.
357         $this->setUser($user1);
359         // No conversations yet.
360         $this->assertEquals([], \core_message\api::get_conversations($user1->id));
362         // Create some conversations for user1.
363         $time = 1;
364         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
365         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
366         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
367         $messageid1 = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
369         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
370         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
371         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
372         $messageid2 = $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
374         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 9);
375         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 10);
376         $messageid3 = $this->send_fake_message($user1, $user4, 'Dope.', 0, $time + 11);
378         // Favourite the first 2 conversations for user1.
379         $convoids = [];
380         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
381         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
382         $user1context = context_user::instance($user1->id);
383         $service = \core_favourites\service_factory::get_service_for_user_context($user1context);
384         foreach ($convoids as $convoid) {
385             $service->create_favourite('core_message', 'message_conversations', $convoid, $user1context);
386         }
388         // We should have 3 conversations.
389         $this->assertCount(3, \core_message\api::get_conversations($user1->id));
391         // And 2 favourited conversations.
392         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, true);
393         $this->assertCount(2, $conversations);
394     }
396     /**
397      * Tests retrieving favourite conversations with a limit and offset to ensure pagination works correctly.
398      */
399     public function test_get_favourite_conversations_limit_offset() {
400         // Create some users.
401         $user1 = self::getDataGenerator()->create_user();
402         $user2 = self::getDataGenerator()->create_user();
403         $user3 = self::getDataGenerator()->create_user();
404         $user4 = self::getDataGenerator()->create_user();
406         // The person doing the search.
407         $this->setUser($user1);
409         // No conversations yet.
410         $this->assertEquals([], \core_message\api::get_conversations($user1->id));
412         // Create some conversations for user1.
413         $time = 1;
414         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
415         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
416         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
417         $messageid1 = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
419         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
420         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
421         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
422         $messageid2 = $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
424         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 9);
425         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 10);
426         $messageid3 = $this->send_fake_message($user1, $user4, 'Dope.', 0, $time + 11);
428         // Favourite the all conversations for user1.
429         $convoids = [];
430         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
431         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
432         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user4->id]);
433         $user1context = context_user::instance($user1->id);
434         $service = \core_favourites\service_factory::get_service_for_user_context($user1context);
435         foreach ($convoids as $convoid) {
436             $service->create_favourite('core_message', 'message_conversations', $convoid, $user1context);
437         }
439         // Get all records, using offset 0 and large limit.
440         $this->assertCount(2, \core_message\api::get_conversations($user1->id, 1, 10, null, true));
442         // Now, get 10 conversations starting at the second record. We should see 2 conversations.
443         $this->assertCount(2, \core_message\api::get_conversations($user1->id, 1, 10, null, true));
445         // Now, try to get favourited conversations using an invalid offset.
446         $this->assertCount(0, \core_message\api::get_conversations($user1->id, 4, 10, null, true));
447     }
449     /**
450      * Tests retrieving favourite conversations when a conversation contains a deleted user.
451      */
452     public function test_get_favourite_conversations_with_deleted_user() {
453         // Create some users.
454         $user1 = self::getDataGenerator()->create_user();
455         $user2 = self::getDataGenerator()->create_user();
456         $user3 = self::getDataGenerator()->create_user();
458         // Send some messages back and forth, have some different conversations with different users.
459         $time = 1;
460         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
461         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
462         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
463         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
465         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
466         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
467         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
468         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
470         // Favourite the all conversations for user1.
471         $convoids = [];
472         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
473         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
474         $user1context = context_user::instance($user1->id);
475         $service = \core_favourites\service_factory::get_service_for_user_context($user1context);
476         foreach ($convoids as $convoid) {
477             $service->create_favourite('core_message', 'message_conversations', $convoid, $user1context);
478         }
480         // Delete the second user.
481         delete_user($user2);
483         // Retrieve the conversations.
484         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, true);
486         // We should only have one conversation because the other user was deleted.
487         $this->assertCount(1, $conversations);
489         // Confirm the conversation is from the non-deleted user.
490         $conversation = reset($conversations);
491         $this->assertEquals($convoids[1], $conversation->id);
492     }
494     /**
495      * Test confirming that conversations can be marked as favourites.
496      */
497     public function test_set_favourite_conversation() {
498         // Create some users.
499         $user1 = self::getDataGenerator()->create_user();
500         $user2 = self::getDataGenerator()->create_user();
501         $user3 = self::getDataGenerator()->create_user();
503         // Send some messages back and forth, have some different conversations with different users.
504         $time = 1;
505         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
506         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
507         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
508         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
510         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
511         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
512         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
513         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
515         // Favourite the first conversation as user 1.
516         $conversationid1 = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
517         \core_message\api::set_favourite_conversation($conversationid1, $user1->id);
519         // Verify we have a single favourite conversation a user 1.
520         $this->assertCount(1, \core_message\api::get_conversations($user1->id, 0, 20, null, true));
522         // Verify we have no favourites as user2, despite being a member in that conversation.
523         $this->assertCount(0, \core_message\api::get_conversations($user2->id, 0, 20, null, true));
525         // Try to favourite the same conversation again.
526         $this->expectException(\moodle_exception::class);
527         \core_message\api::set_favourite_conversation($conversationid1, $user1->id);
528     }
530     /**
531      * Test verifying that trying to mark a non-existent conversation as a favourite, results in an exception.
532      */
533     public function test_set_favourite_conversation_nonexistent_conversation() {
534         // Create some users.
535         $user1 = self::getDataGenerator()->create_user();
536         // Try to favourite a non-existent conversation.
537         $this->expectException(\moodle_exception::class);
538         \core_message\api::set_favourite_conversation(0, $user1->id);
539     }
541     /**
542      * Test verifying that a conversation cannot be marked as favourite unless the user is a member of that conversation.
543      */
544     public function test_set_favourite_conversation_non_member() {
545         // Create some users.
546         $user1 = self::getDataGenerator()->create_user();
547         $user2 = self::getDataGenerator()->create_user();
548         $user3 = self::getDataGenerator()->create_user();
550         // Send some messages back and forth, have some different conversations with different users.
551         $time = 1;
552         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
553         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
554         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
555         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
557         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
558         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
559         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
560         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
562         // Try to favourite the first conversation as user 3, who is not a member.
563         $conversationid1 = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
564         $this->expectException(\moodle_exception::class);
565         \core_message\api::set_favourite_conversation($conversationid1, $user3->id);
566     }
568     /**
569      * Test confirming that those conversations marked as favourites can be unfavourited.
570      */
571     public function test_unset_favourite_conversation() {
572         // Create some users.
573         $user1 = self::getDataGenerator()->create_user();
574         $user2 = self::getDataGenerator()->create_user();
575         $user3 = self::getDataGenerator()->create_user();
577         // Send some messages back and forth, have some different conversations with different users.
578         $time = 1;
579         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
580         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
581         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
582         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
584         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
585         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
586         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
587         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
589         // Favourite the first conversation as user 1 and the second as user 3.
590         $conversationid1 = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
591         $conversationid2 = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
592         \core_message\api::set_favourite_conversation($conversationid1, $user1->id);
593         \core_message\api::set_favourite_conversation($conversationid2, $user3->id);
595         // Verify we have a single favourite conversation for both user 1 and user 3.
596         $this->assertCount(1, \core_message\api::get_conversations($user1->id, 0, 20, null, true));
597         $this->assertCount(1, \core_message\api::get_conversations($user3->id, 0, 20, null, true));
599         // Now unfavourite the conversation as user 1.
600         \core_message\api::unset_favourite_conversation($conversationid1, $user1->id);
602         // Verify we have a single favourite conversation user 3 only, and none for user1.
603         $this->assertCount(1, \core_message\api::get_conversations($user3->id, 0, 20, null, true));
604         $this->assertCount(0, \core_message\api::get_conversations($user1->id, 0, 20, null, true));
606         // Try to favourite the same conversation again as user 1.
607         $this->expectException(\moodle_exception::class);
608         \core_message\api::unset_favourite_conversation($conversationid1, $user1->id);
609     }
611     /**
612      * Test verifying that a valid conversation cannot be unset as a favourite if it's not marked as a favourite.
613      */
614     public function test_unset_favourite_conversation_not_favourite() {
615         // Create some users.
616         $user1 = self::getDataGenerator()->create_user();
617         $user2 = self::getDataGenerator()->create_user();
619         // Send some messages back and forth, have some different conversations with different users.
620         $time = 1;
621         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
622         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
623         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
624         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
626         // Now try to unfavourite the conversation as user 1.
627         $conversationid1 = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
628         $this->expectException(\moodle_exception::class);
629         \core_message\api::unset_favourite_conversation($conversationid1, $user1->id);
630     }
632     /**
633      * Test verifying that a non-existent conversation cannot be unset as a favourite.
634      */
635     public function test_unset_favourite_conversation_non_existent_conversation() {
636         // Create some users.
637         $user1 = self::getDataGenerator()->create_user();
639         // Now try to unfavourite the conversation as user 1.
640         $this->expectException(\moodle_exception::class);
641         \core_message\api::unset_favourite_conversation(0, $user1->id);
642     }
644     /**
645      * Helper to seed the database with initial state.
646      */
647     protected function create_conversation_test_data() {
648         // Create some users.
649         $user1 = self::getDataGenerator()->create_user();
650         $user2 = self::getDataGenerator()->create_user();
651         $user3 = self::getDataGenerator()->create_user();
652         $user4 = self::getDataGenerator()->create_user();
654         $time = 1;
656         // Create some conversations. We want:
657         // 1) At least one of each type (group, individual) of which user1 IS a member and DID send the most recent message.
658         // 2) At least one of each type (group, individual) of which user1 IS a member and DID NOT send the most recent message.
659         // 3) At least one of each type (group, individual) of which user1 IS NOT a member.
660         // 4) At least two group conversation having 0 messages, of which user1 IS a member (To confirm conversationid ordering).
661         // 5) At least one group conversation having 0 messages, of which user1 IS NOT a member.
663         // Individual conversation, user1 is a member, last message from other user.
664         $ic1 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
665             [$user1->id, $user2->id]);
666         testhelper::send_fake_message_to_conversation($user1, $ic1->id, 'Message 1', $time);
667         testhelper::send_fake_message_to_conversation($user2, $ic1->id, 'Message 2', $time + 1);
669         // Individual conversation, user1 is a member, last message from user1.
670         $ic2 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
671             [$user1->id, $user3->id]);
672         testhelper::send_fake_message_to_conversation($user3, $ic2->id, 'Message 3', $time + 2);
673         testhelper::send_fake_message_to_conversation($user1, $ic2->id, 'Message 4', $time + 3);
675         // Individual conversation, user1 is not a member.
676         $ic3 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
677             [$user2->id, $user3->id]);
678         testhelper::send_fake_message_to_conversation($user2, $ic3->id, 'Message 5', $time + 4);
679         testhelper::send_fake_message_to_conversation($user3, $ic3->id, 'Message 6', $time + 5);
681         // Group conversation, user1 is not a member.
682         $gc1 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
683             [$user2->id, $user3->id, $user4->id], 'Project discussions');
684         testhelper::send_fake_message_to_conversation($user2, $gc1->id, 'Message 7', $time + 6);
685         testhelper::send_fake_message_to_conversation($user4, $gc1->id, 'Message 8', $time + 7);
687         // Group conversation, user1 is a member, last message from another user.
688         $gc2 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
689             [$user1->id, $user3->id, $user4->id], 'Group chat');
690         testhelper::send_fake_message_to_conversation($user1, $gc2->id, 'Message 9', $time + 8);
691         testhelper::send_fake_message_to_conversation($user3, $gc2->id, 'Message 10', $time + 9);
692         testhelper::send_fake_message_to_conversation($user4, $gc2->id, 'Message 11', $time + 10);
694         // Group conversation, user1 is a member, last message from user1.
695         $gc3 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
696             [$user1->id, $user2->id, $user3->id, $user4->id], 'Group chat again!');
697         testhelper::send_fake_message_to_conversation($user4, $gc3->id, 'Message 12', $time + 11);
698         testhelper::send_fake_message_to_conversation($user3, $gc3->id, 'Message 13', $time + 12);
699         testhelper::send_fake_message_to_conversation($user1, $gc3->id, 'Message 14', $time + 13);
701         // Empty group conversations (x2), user1 is a member.
702         $gc4 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
703             [$user1->id, $user2->id, $user3->id], 'Empty group');
704         $gc5 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
705             [$user1->id, $user2->id, $user4->id], 'Another empty group');
707         // Empty group conversation, user1 is NOT a member.
708         $gc6 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
709             [$user2->id, $user3->id, $user4->id], 'Empty group 3');
711         return [$user1, $user2, $user3, $user4, $ic1, $ic2, $ic3, $gc1, $gc2, $gc3, $gc4, $gc5, $gc6];
712     }
714     /**
715      * Test verifying get_conversations when no limits, offsets, type filters or favourite restrictions are used.
716      */
717     public function test_get_conversations_no_restrictions() {
718         // No conversations should exist yet.
719         $user1 = self::getDataGenerator()->create_user();
720         $this->assertEquals([], \core_message\api::get_conversations($user1->id));
722         // Get a bunch of conversations, some group, some individual and in different states.
723         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
724             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
726         // Get all conversations for user1.
727         $conversations = core_message\api::get_conversations($user1->id);
729         // Verify there are 2 individual conversation, 2 group conversations, and 2 empty group conversations.
730         // The conversations with the most recent messages should be listed first, followed by the empty
731         // conversations, with the most recently created first.
732         $this->assertCount(6, $conversations);
733         $typecounts  = array_count_values(array_column($conversations, 'type'));
734         $this->assertEquals(2, $typecounts[1]);
735         $this->assertEquals(4, $typecounts[2]);
737         // Those conversations having messages should be listed first, ordered by most recent message time.
738         $this->assertEquals($gc3->id, $conversations[0]->id);
739         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $conversations[0]->type);
740         $this->assertFalse($conversations[0]->isfavourite);
741         $this->assertCount(1, $conversations[0]->members);
742         $this->assertEquals(4, $conversations[0]->membercount);
743         $this->assertCount(1, $conversations[0]->messages);
744         $this->assertEquals("Message 14", $conversations[0]->messages[0]->text);
745         $this->assertEquals($user1->id, $conversations[0]->messages[0]->useridfrom);
747         $this->assertEquals($gc2->id, $conversations[1]->id);
748         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $conversations[1]->type);
749         $this->assertFalse($conversations[1]->isfavourite);
750         $this->assertCount(1, $conversations[1]->members);
751         $this->assertEquals(3, $conversations[1]->membercount);
752         $this->assertCount(1, $conversations[1]->messages);
753         $this->assertEquals("Message 11", $conversations[1]->messages[0]->text);
754         $this->assertEquals($user4->id, $conversations[1]->messages[0]->useridfrom);
756         $this->assertEquals($ic2->id, $conversations[2]->id);
757         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $conversations[2]->type);
758         $this->assertFalse($conversations[2]->isfavourite);
759         $this->assertCount(1, $conversations[2]->members);
760         $this->assertEquals($user3->id, $conversations[2]->members[$user3->id]->id);
761         $this->assertEquals(2, $conversations[2]->membercount);
762         $this->assertCount(1, $conversations[2]->messages);
763         $this->assertEquals("Message 4", $conversations[2]->messages[0]->text);
764         $this->assertEquals($user1->id, $conversations[2]->messages[0]->useridfrom);
766         $this->assertEquals($ic1->id, $conversations[3]->id);
767         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $conversations[3]->type);
768         $this->assertFalse($conversations[3]->isfavourite);
769         $this->assertCount(1, $conversations[3]->members);
770         $this->assertEquals(2, $conversations[3]->membercount);
771         $this->assertCount(1, $conversations[3]->messages);
772         $this->assertEquals("Message 2", $conversations[3]->messages[0]->text);
773         $this->assertEquals($user2->id, $conversations[3]->messages[0]->useridfrom);
775         // Of the groups without messages, we expect to see the most recently created first.
776         $this->assertEquals($gc5->id, $conversations[4]->id);
777         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $conversations[4]->type);
778         $this->assertFalse($conversations[4]->isfavourite);
779         $this->assertCount(0, $conversations[4]->members); // No members returned, because no recent messages exist.
780         $this->assertEquals(3, $conversations[4]->membercount);
781         $this->assertEmpty($conversations[4]->messages);
783         $this->assertEquals($gc4->id, $conversations[5]->id);
784         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $conversations[5]->type);
785         $this->assertFalse($conversations[5]->isfavourite);
786         $this->assertCount(0, $conversations[5]->members);
787         $this->assertEquals(3, $conversations[5]->membercount);
788         $this->assertEmpty($conversations[5]->messages);
790         // Verify format of the return structure.
791         foreach ($conversations as $conv) {
792             $this->assertObjectHasAttribute('id', $conv);
793             $this->assertObjectHasAttribute('name', $conv);
794             $this->assertObjectHasAttribute('subname', $conv);
795             $this->assertObjectHasAttribute('type', $conv);
796             $this->assertObjectHasAttribute('isfavourite', $conv);
797             $this->assertObjectHasAttribute('membercount', $conv);
798             $this->assertObjectHasAttribute('isread', $conv);
799             $this->assertObjectHasAttribute('unreadcount', $conv);
800             $this->assertObjectHasAttribute('members', $conv);
801             foreach ($conv->members as $member) {
802                 $this->assertObjectHasAttribute('id', $member);
803                 $this->assertObjectHasAttribute('fullname', $member);
804                 $this->assertObjectHasAttribute('profileimageurl', $member);
805                 $this->assertObjectHasAttribute('profileimageurlsmall', $member);
806                 $this->assertObjectHasAttribute('isonline', $member);
807                 $this->assertObjectHasAttribute('showonlinestatus', $member);
808                 $this->assertObjectHasAttribute('isblocked', $member);
809                 $this->assertObjectHasAttribute('iscontact', $member);
810             }
811             $this->assertObjectHasAttribute('messages', $conv);
812             foreach ($conv->messages as $message) {
813                 $this->assertObjectHasAttribute('id', $message);
814                 $this->assertObjectHasAttribute('useridfrom', $message);
815                 $this->assertObjectHasAttribute('text', $message);
816                 $this->assertObjectHasAttribute('timecreated', $message);
817             }
818         }
819     }
821     /**
822      * Tests retrieving conversations with a limit and offset to ensure pagination works correctly.
823      */
824     public function test_get_conversations_limit_offset() {
825         // Get a bunch of conversations, some group, some individual and in different states.
826         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
827             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
829         // Get all conversations for user1, limited to 1 result.
830         $conversations = core_message\api::get_conversations($user1->id, 0, 1);
832         // Verify the first conversation.
833         $this->assertCount(1, $conversations);
834         $conversation = array_shift($conversations);
835         $this->assertEquals($conversation->id, $gc3->id);
837         // Verify the next conversation.
838         $conversations = \core_message\api::get_conversations($user1->id, 1, 1);
839         $this->assertCount(1, $conversations);
840         $this->assertEquals($gc2->id, $conversations[0]->id);
842         // Verify the next conversation.
843         $conversations = \core_message\api::get_conversations($user1->id, 2, 1);
844         $this->assertCount(1, $conversations);
845         $this->assertEquals($ic2->id, $conversations[0]->id);
847         // Skip one and get both empty conversations.
848         $conversations = \core_message\api::get_conversations($user1->id, 4, 2);
849         $this->assertCount(2, $conversations);
850         $this->assertEquals($gc5->id, $conversations[0]->id);
851         $this->assertEmpty($conversations[0]->messages);
852         $this->assertEquals($gc4->id, $conversations[1]->id);
853         $this->assertEmpty($conversations[1]->messages);
855         // Ask for an offset that doesn't exist and verify no conversations are returned.
856         $conversations = \core_message\api::get_conversations($user1->id, 10, 1);
857         $this->assertCount(0, $conversations);
858     }
860     /**
861      * Test verifying the type filtering behaviour of the
862      */
863     public function test_get_conversations_type_filter() {
864         // Get a bunch of conversations, some group, some individual and in different states.
865         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
866             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
868         // Verify we can ask for only individual conversations.
869         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
870             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL);
871         $this->assertCount(2, $conversations);
873         // Verify we can ask for only group conversations.
874         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
875             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP);
876         $this->assertCount(4, $conversations);
878         // Verify an exception is thrown if an unrecognized type is specified.
879         $this->expectException(\moodle_exception::class);
880         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, 0);
881     }
883     /**
884      * Tests retrieving conversations when a conversation contains a deleted user.
885      */
886     public function test_get_conversations_with_deleted_user() {
887         // Get a bunch of conversations, some group, some individual and in different states.
888         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
889             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
891         // Delete the second user and retrieve the conversations.
892         // We should have 5, as $ic1 drops off the list.
893         // Group conversations remain albeit with less members.
894         delete_user($user2);
895         $conversations = \core_message\api::get_conversations($user1->id);
896         $this->assertCount(5, $conversations);
897         $this->assertEquals($gc3->id, $conversations[0]->id);
898         $this->assertcount(1, $conversations[0]->members);
899         $this->assertEquals($gc2->id, $conversations[1]->id);
900         $this->assertcount(1, $conversations[1]->members);
901         $this->assertEquals($ic2->id, $conversations[2]->id);
902         $this->assertEquals($gc5->id, $conversations[3]->id);
903         $this->assertEquals($gc4->id, $conversations[4]->id);
905         // Delete a user from a group conversation where that user had sent the most recent message.
906         // This user will still be present in the members array, as will the message in the messages array.
907         delete_user($user4);
908         $conversations = \core_message\api::get_conversations($user1->id);
909         $this->assertCount(5, $conversations);
910         $this->assertEquals($gc2->id, $conversations[1]->id);
911         $this->assertcount(1, $conversations[1]->members);
912         $this->assertEquals($user4->id, $conversations[1]->members[$user4->id]->id);
913         $this->assertcount(1, $conversations[1]->messages);
914         $this->assertEquals($user4->id, $conversations[1]->messages[0]->useridfrom);
916         // Delete the third user and retrieve the conversations.
917         // We should have 4, as $ic1, $ic2 drop off the list.
918         // Group conversations remain albeit with less members.
919         delete_user($user3);
920         $conversations = \core_message\api::get_conversations($user1->id);
921         $this->assertCount(4, $conversations);
922         $this->assertEquals($gc3->id, $conversations[0]->id);
923         $this->assertcount(1, $conversations[0]->members);
924         $this->assertEquals($gc2->id, $conversations[1]->id);
925         $this->assertcount(1, $conversations[1]->members);
926         $this->assertEquals($gc5->id, $conversations[2]->id);
927         $this->assertEquals($gc4->id, $conversations[3]->id);
928     }
930     /**
931      * Test verifying the behaviour of get_conversations() when fetching favourite conversations.
932      */
933     public function test_get_conversations_favourite_conversations() {
934         // Get a bunch of conversations, some group, some individual and in different states.
935         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
936             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
938         // Try to get ONLY favourite conversations, when no favourites exist.
939         $this->assertEquals([], \core_message\api::get_conversations($user1->id, 0, 20, null, true));
941         // Try to get NO favourite conversations, when no favourites exist.
942         $this->assertCount(6, \core_message\api::get_conversations($user1->id, 0, 20, null, false));
944         // Mark a few conversations as favourites.
945         \core_message\api::set_favourite_conversation($ic1->id, $user1->id);
946         \core_message\api::set_favourite_conversation($gc2->id, $user1->id);
947         \core_message\api::set_favourite_conversation($gc5->id, $user1->id);
949         // Get the conversations, first with no restrictions, confirming the favourite status of the conversations.
950         $conversations = \core_message\api::get_conversations($user1->id);
951         $this->assertCount(6, $conversations);
952         foreach ($conversations as $conv) {
953             if (in_array($conv->id, [$ic1->id, $gc2->id, $gc5->id])) {
954                 $this->assertTrue($conv->isfavourite);
955             }
956         }
958         // Now, get ONLY favourite conversations.
959         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, true);
960         $this->assertCount(3, $conversations);
961         foreach ($conversations as $conv) {
962             $this->assertTrue($conv->isfavourite);
963         }
965         // Now, try ONLY favourites of type 'group'.
966         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
967             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, true);
968         $this->assertCount(2, $conversations);
969         foreach ($conversations as $conv) {
970             $this->assertTrue($conv->isfavourite);
971         }
973         // And NO favourite conversations.
974         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, false);
975         $this->assertCount(3, $conversations);
976         foreach ($conversations as $conv) {
977             $this->assertFalse($conv->isfavourite);
978         }
979     }
981     /**
982      * Test verifying that group linked conversations are returned and contain a subname matching the course name.
983      */
984     public function test_get_conversations_group_linked() {
985         // Create some users.
986         $user1 = self::getDataGenerator()->create_user();
987         $user2 = self::getDataGenerator()->create_user();
988         $user3 = self::getDataGenerator()->create_user();
990         $course1 = $this->getDataGenerator()->create_course();
992         // Create a group with a linked conversation.
993         $this->setAdminUser();
994         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
995         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
996         $this->getDataGenerator()->enrol_user($user3->id, $course1->id);
997         $group1 = $this->getDataGenerator()->create_group(array('courseid' => $course1->id, 'enablemessaging' => 1));
999         // Add users to group1.
1000         $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user1->id));
1001         $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user2->id));
1003         $conversations = \core_message\api::get_conversations($user1->id);
1004         $this->assertEquals($course1->shortname, $conversations[0]->subname);
1005     }
1007    /**
1008     * The data provider for get_conversations_mixed.
1009     *
1010     * This provides sets of data to for testing.
1011     * @return array
1012     */
1013    public function get_conversations_mixed_provider() {
1014        return array(
1015             'Test that conversations with messages contacts is correctly ordered.' => array(
1016                 'users' => array(
1017                     'user1',
1018                     'user2',
1019                     'user3',
1020                 ),
1021                 'contacts' => array(
1022                 ),
1023                 'messages' => array(
1024                     array(
1025                         'from'          => 'user1',
1026                         'to'            => 'user2',
1027                         'state'         => 'unread',
1028                         'subject'       => 'S1',
1029                     ),
1030                     array(
1031                         'from'          => 'user2',
1032                         'to'            => 'user1',
1033                         'state'         => 'unread',
1034                         'subject'       => 'S2',
1035                     ),
1036                     array(
1037                         'from'          => 'user1',
1038                         'to'            => 'user2',
1039                         'state'         => 'unread',
1040                         'timecreated'   => 0,
1041                         'subject'       => 'S3',
1042                     ),
1043                     array(
1044                         'from'          => 'user1',
1045                         'to'            => 'user3',
1046                         'state'         => 'read',
1047                         'timemodifier'  => 1,
1048                         'subject'       => 'S4',
1049                     ),
1050                     array(
1051                         'from'          => 'user3',
1052                         'to'            => 'user1',
1053                         'state'         => 'read',
1054                         'timemodifier'  => 1,
1055                         'subject'       => 'S5',
1056                     ),
1057                     array(
1058                         'from'          => 'user1',
1059                         'to'            => 'user3',
1060                         'state'         => 'read',
1061                         'timecreated'   => 0,
1062                         'subject'       => 'S6',
1063                     ),
1064                 ),
1065                 'expectations' => array(
1066                     'user1' => array(
1067                         // User1 has conversed most recently with user3. The most recent message is M5.
1068                         array(
1069                             'messageposition'   => 0,
1070                             'with'              => 'user3',
1071                             'subject'           => 'S5',
1072                             'unreadcount'       => 0,
1073                         ),
1074                         // User1 has also conversed with user2. The most recent message is S2.
1075                         array(
1076                             'messageposition'   => 1,
1077                             'with'              => 'user2',
1078                             'subject'           => 'S2',
1079                             'unreadcount'       => 1,
1080                         ),
1081                     ),
1082                     'user2' => array(
1083                         // User2 has only conversed with user1. Their most recent shared message was S2.
1084                         array(
1085                             'messageposition'   => 0,
1086                             'with'              => 'user1',
1087                             'subject'           => 'S2',
1088                             'unreadcount'       => 2,
1089                         ),
1090                     ),
1091                     'user3' => array(
1092                         // User3 has only conversed with user1. Their most recent shared message was S5.
1093                         array(
1094                             'messageposition'   => 0,
1095                             'with'              => 'user1',
1096                             'subject'           => 'S5',
1097                             'unreadcount'       => 0,
1098                         ),
1099                     ),
1100                 ),
1101             ),
1102             'Test conversations with a single user, where some messages are read and some are not.' => array(
1103                 'users' => array(
1104                     'user1',
1105                     'user2',
1106                 ),
1107                 'contacts' => array(
1108                 ),
1109                 'messages' => array(
1110                     array(
1111                         'from'          => 'user1',
1112                         'to'            => 'user2',
1113                         'state'         => 'read',
1114                         'subject'       => 'S1',
1115                     ),
1116                     array(
1117                         'from'          => 'user2',
1118                         'to'            => 'user1',
1119                         'state'         => 'read',
1120                         'subject'       => 'S2',
1121                     ),
1122                     array(
1123                         'from'          => 'user1',
1124                         'to'            => 'user2',
1125                         'state'         => 'unread',
1126                         'timemodifier'  => 1,
1127                         'subject'       => 'S3',
1128                     ),
1129                     array(
1130                         'from'          => 'user1',
1131                         'to'            => 'user2',
1132                         'state'         => 'unread',
1133                         'timemodifier'  => 1,
1134                         'subject'       => 'S4',
1135                     ),
1136                 ),
1137                 'expectations' => array(
1138                     // The most recent message between user1 and user2 was S4.
1139                     'user1' => array(
1140                         array(
1141                             'messageposition'   => 0,
1142                             'with'              => 'user2',
1143                             'subject'           => 'S4',
1144                             'unreadcount'       => 0,
1145                         ),
1146                     ),
1147                     'user2' => array(
1148                         // The most recent message between user1 and user2 was S4.
1149                         array(
1150                             'messageposition'   => 0,
1151                             'with'              => 'user1',
1152                             'subject'           => 'S4',
1153                             'unreadcount'       => 2,
1154                         ),
1155                     ),
1156                 ),
1157             ),
1158             'Test conversations with a single user, where some messages are read and some are not, and messages ' .
1159             'are out of order' => array(
1160             // This can happen through a combination of factors including multi-master DB replication with messages
1161             // read somehow (e.g. API).
1162                 'users' => array(
1163                     'user1',
1164                     'user2',
1165                 ),
1166                 'contacts' => array(
1167                 ),
1168                 'messages' => array(
1169                     array(
1170                         'from'          => 'user1',
1171                         'to'            => 'user2',
1172                         'state'         => 'read',
1173                         'subject'       => 'S1',
1174                         'timemodifier'  => 1,
1175                     ),
1176                     array(
1177                         'from'          => 'user2',
1178                         'to'            => 'user1',
1179                         'state'         => 'read',
1180                         'subject'       => 'S2',
1181                         'timemodifier'  => 2,
1182                     ),
1183                     array(
1184                         'from'          => 'user1',
1185                         'to'            => 'user2',
1186                         'state'         => 'unread',
1187                         'subject'       => 'S3',
1188                     ),
1189                     array(
1190                         'from'          => 'user1',
1191                         'to'            => 'user2',
1192                         'state'         => 'unread',
1193                         'subject'       => 'S4',
1194                     ),
1195                 ),
1196                 'expectations' => array(
1197                     // The most recent message between user1 and user2 was S2, even though later IDs have not been read.
1198                     'user1' => array(
1199                         array(
1200                             'messageposition'   => 0,
1201                             'with'              => 'user2',
1202                             'subject'           => 'S2',
1203                             'unreadcount'       => 0,
1204                         ),
1205                     ),
1206                     'user2' => array(
1207                         array(
1208                             'messageposition'   => 0,
1209                             'with'              => 'user1',
1210                             'subject'           => 'S2',
1211                             'unreadcount'       => 2
1212                         ),
1213                     ),
1214                 ),
1215             ),
1216             'Test unread message count is correct for both users' => array(
1217                 'users' => array(
1218                     'user1',
1219                     'user2',
1220                 ),
1221                 'contacts' => array(
1222                 ),
1223                 'messages' => array(
1224                     array(
1225                         'from'          => 'user1',
1226                         'to'            => 'user2',
1227                         'state'         => 'read',
1228                         'subject'       => 'S1',
1229                         'timemodifier'  => 1,
1230                     ),
1231                     array(
1232                         'from'          => 'user2',
1233                         'to'            => 'user1',
1234                         'state'         => 'read',
1235                         'subject'       => 'S2',
1236                         'timemodifier'  => 2,
1237                     ),
1238                     array(
1239                         'from'          => 'user1',
1240                         'to'            => 'user2',
1241                         'state'         => 'read',
1242                         'subject'       => 'S3',
1243                         'timemodifier'  => 3,
1244                     ),
1245                     array(
1246                         'from'          => 'user1',
1247                         'to'            => 'user2',
1248                         'state'         => 'read',
1249                         'subject'       => 'S4',
1250                         'timemodifier'  => 4,
1251                     ),
1252                     array(
1253                         'from'          => 'user1',
1254                         'to'            => 'user2',
1255                         'state'         => 'unread',
1256                         'subject'       => 'S5',
1257                         'timemodifier'  => 5,
1258                     ),
1259                     array(
1260                         'from'          => 'user2',
1261                         'to'            => 'user1',
1262                         'state'         => 'unread',
1263                         'subject'       => 'S6',
1264                         'timemodifier'  => 6,
1265                     ),
1266                     array(
1267                         'from'          => 'user1',
1268                         'to'            => 'user2',
1269                         'state'         => 'unread',
1270                         'subject'       => 'S7',
1271                         'timemodifier'  => 7,
1272                     ),
1273                     array(
1274                         'from'          => 'user1',
1275                         'to'            => 'user2',
1276                         'state'         => 'unread',
1277                         'subject'       => 'S8',
1278                         'timemodifier'  => 8,
1279                     ),
1280                 ),
1281                 'expectations' => array(
1282                     // The most recent message between user1 and user2 was S2, even though later IDs have not been read.
1283                     'user1' => array(
1284                         array(
1285                             'messageposition'   => 0,
1286                             'with'              => 'user2',
1287                             'subject'           => 'S8',
1288                             'unreadcount'       => 1,
1289                         ),
1290                     ),
1291                     'user2' => array(
1292                         array(
1293                             'messageposition'   => 0,
1294                             'with'              => 'user1',
1295                             'subject'           => 'S8',
1296                             'unreadcount'       => 3,
1297                         ),
1298                     ),
1299                 ),
1300             ),
1301         );
1302     }
1304     /**
1305      * Test get_conversations with a mixture of messages.
1306      *
1307      * @dataProvider get_conversations_mixed_provider
1308      * @param array $usersdata The list of users to create for this test.
1309      * @param array $messagesdata The list of messages to create.
1310      * @param array $expectations The list of expected outcomes.
1311      */
1312     public function test_get_conversations_mixed($usersdata, $contacts, $messagesdata, $expectations) {
1313         global $DB;
1315         // Create all of the users.
1316         $users = array();
1317         foreach ($usersdata as $username) {
1318             $users[$username] = $this->getDataGenerator()->create_user(array('username' => $username));
1319         }
1321         foreach ($contacts as $username => $contact) {
1322             foreach ($contact as $contactname => $blocked) {
1323                 $record = new stdClass();
1324                 $record->userid     = $users[$username]->id;
1325                 $record->contactid  = $users[$contactname]->id;
1326                 $record->blocked    = $blocked;
1327                 $record->id = $DB->insert_record('message_contacts', $record);
1328             }
1329         }
1331         $defaulttimecreated = time();
1332         foreach ($messagesdata as $messagedata) {
1333             $from       = $users[$messagedata['from']];
1334             $to         = $users[$messagedata['to']];
1335             $subject    = $messagedata['subject'];
1337             if (isset($messagedata['state']) && $messagedata['state'] == 'unread') {
1338                 $messageid = $this->send_fake_message($from, $to, $subject);
1339             } else {
1340                 // If there is no state, or the state is not 'unread', assume the message is read.
1341                 $messageid = message_post_message($from, $to, $subject, FORMAT_PLAIN);
1342             }
1344             $updatemessage = new stdClass();
1345             $updatemessage->id = $messageid;
1346             if (isset($messagedata['timecreated'])) {
1347                 $updatemessage->timecreated = $messagedata['timecreated'];
1348             } else if (isset($messagedata['timemodifier'])) {
1349                 $updatemessage->timecreated = $defaulttimecreated + $messagedata['timemodifier'];
1350             } else {
1351                 $updatemessage->timecreated = $defaulttimecreated;
1352             }
1354             $DB->update_record('messages', $updatemessage);
1355         }
1357         foreach ($expectations as $username => $data) {
1358             // Get the recent conversations for the specified user.
1359             $user = $users[$username];
1360             $conversations = array_values(\core_message\api::get_conversations($user->id));
1361             foreach ($data as $expectation) {
1362                 $otheruser = $users[$expectation['with']];
1363                 $conversation = $conversations[$expectation['messageposition']];
1364                 $this->assertEquals($otheruser->id, $conversation->members[$otheruser->id]->id);
1365                 $this->assertEquals($expectation['subject'], $conversation->messages[0]->text);
1366                 $this->assertEquals($expectation['unreadcount'], $conversation->unreadcount);
1367             }
1368         }
1369     }
1371     /**
1372      * Tests retrieving contacts.
1373      */
1374     public function test_get_contacts() {
1375         // Create some users.
1376         $user1 = self::getDataGenerator()->create_user();
1378         // Set as the user.
1379         $this->setUser($user1);
1381         $user2 = new stdClass();
1382         $user2->firstname = 'User';
1383         $user2->lastname = 'A';
1384         $user2 = self::getDataGenerator()->create_user($user2);
1386         $user3 = new stdClass();
1387         $user3->firstname = 'User';
1388         $user3->lastname = 'B';
1389         $user3 = self::getDataGenerator()->create_user($user3);
1391         $user4 = new stdClass();
1392         $user4->firstname = 'User';
1393         $user4->lastname = 'C';
1394         $user4 = self::getDataGenerator()->create_user($user4);
1396         $user5 = new stdClass();
1397         $user5->firstname = 'User';
1398         $user5->lastname = 'D';
1399         $user5 = self::getDataGenerator()->create_user($user5);
1401         // Add some users as contacts.
1402         \core_message\api::add_contact($user1->id, $user2->id);
1403         \core_message\api::add_contact($user1->id, $user3->id);
1404         \core_message\api::add_contact($user1->id, $user4->id);
1406         // Retrieve the contacts.
1407         $contacts = \core_message\api::get_contacts($user1->id);
1409         // Confirm the data is correct.
1410         $this->assertEquals(3, count($contacts));
1411         usort($contacts, ['static', 'sort_contacts']);
1413         $contact1 = $contacts[0];
1414         $contact2 = $contacts[1];
1415         $contact3 = $contacts[2];
1417         $this->assertEquals($user2->id, $contact1->userid);
1418         $this->assertEmpty($contact1->useridfrom);
1419         $this->assertFalse($contact1->ismessaging);
1420         $this->assertNull($contact1->lastmessage);
1421         $this->assertNull($contact1->messageid);
1422         $this->assertNull($contact1->isonline);
1423         $this->assertFalse($contact1->isread);
1424         $this->assertFalse($contact1->isblocked);
1425         $this->assertNull($contact1->unreadcount);
1427         $this->assertEquals($user3->id, $contact2->userid);
1428         $this->assertEmpty($contact2->useridfrom);
1429         $this->assertFalse($contact2->ismessaging);
1430         $this->assertNull($contact2->lastmessage);
1431         $this->assertNull($contact2->messageid);
1432         $this->assertNull($contact2->isonline);
1433         $this->assertFalse($contact2->isread);
1434         $this->assertFalse($contact2->isblocked);
1435         $this->assertNull($contact2->unreadcount);
1437         $this->assertEquals($user4->id, $contact3->userid);
1438         $this->assertEmpty($contact3->useridfrom);
1439         $this->assertFalse($contact3->ismessaging);
1440         $this->assertNull($contact3->lastmessage);
1441         $this->assertNull($contact3->messageid);
1442         $this->assertNull($contact3->isonline);
1443         $this->assertFalse($contact3->isread);
1444         $this->assertFalse($contact3->isblocked);
1445         $this->assertNull($contact3->unreadcount);
1446     }
1448     /**
1449      * Tests retrieving messages.
1450      */
1451     public function test_get_messages() {
1452         // Create some users.
1453         $user1 = self::getDataGenerator()->create_user();
1454         $user2 = self::getDataGenerator()->create_user();
1456         // The person doing the search.
1457         $this->setUser($user1);
1459         // Send some messages back and forth.
1460         $time = 1;
1461         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
1462         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
1463         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
1464         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
1466         // Retrieve the messages.
1467         $messages = \core_message\api::get_messages($user1->id, $user2->id);
1468         $this->assertDebuggingCalledCount(3);
1470         // Confirm the message data is correct.
1471         $this->assertEquals(4, count($messages));
1473         $message1 = $messages[0];
1474         $message2 = $messages[1];
1475         $message3 = $messages[2];
1476         $message4 = $messages[3];
1478         $this->assertEquals($user1->id, $message1->useridfrom);
1479         $this->assertEquals($user2->id, $message1->useridto);
1480         $this->assertTrue($message1->displayblocktime);
1481         $this->assertContains('Yo!', $message1->text);
1483         $this->assertEquals($user2->id, $message2->useridfrom);
1484         $this->assertEquals($user1->id, $message2->useridto);
1485         $this->assertFalse($message2->displayblocktime);
1486         $this->assertContains('Sup mang?', $message2->text);
1488         $this->assertEquals($user1->id, $message3->useridfrom);
1489         $this->assertEquals($user2->id, $message3->useridto);
1490         $this->assertFalse($message3->displayblocktime);
1491         $this->assertContains('Writing PHPUnit tests!', $message3->text);
1493         $this->assertEquals($user2->id, $message4->useridfrom);
1494         $this->assertEquals($user1->id, $message4->useridto);
1495         $this->assertFalse($message4->displayblocktime);
1496         $this->assertContains('Word.', $message4->text);
1497     }
1499     /**
1500      * Tests retrieving conversation messages.
1501      */
1502     public function test_get_conversation_messages() {
1503         // Create some users.
1504         $user1 = self::getDataGenerator()->create_user();
1505         $user2 = self::getDataGenerator()->create_user();
1507         // Create conversation.
1508         $conversation = \core_message\api::create_conversation(
1509             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1510             [$user1->id, $user2->id]
1511         );
1513         // The person doing the search.
1514         $this->setUser($user1);
1516         // Send some messages back and forth.
1517         $time = 1;
1518         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
1519         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
1520         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
1521         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 4);
1523         // Retrieve the messages.
1524         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id);
1526         // Confirm the conversation id is correct.
1527         $this->assertEquals($conversation->id, $convmessages['id']);
1529         // Confirm the message data is correct.
1530         $messages = $convmessages['messages'];
1531         $this->assertEquals(4, count($messages));
1532         $message1 = $messages[0];
1533         $message2 = $messages[1];
1534         $message3 = $messages[2];
1535         $message4 = $messages[3];
1537         $this->assertEquals($user1->id, $message1->useridfrom);
1538         $this->assertContains('Yo!', $message1->text);
1540         $this->assertEquals($user2->id, $message2->useridfrom);
1541         $this->assertContains('Sup mang?', $message2->text);
1543         $this->assertEquals($user1->id, $message3->useridfrom);
1544         $this->assertContains('Writing PHPUnit tests!', $message3->text);
1546         $this->assertEquals($user1->id, $message4->useridfrom);
1547         $this->assertContains('Word.', $message4->text);
1549         // Confirm the members data is correct.
1550         $members = $convmessages['members'];
1551         $this->assertEquals(2, count($members));
1552     }
1554     /**
1555      * Tests retrieving group conversation messages.
1556      */
1557     public function test_get_group_conversation_messages() {
1558         // Create some users.
1559         $user1 = self::getDataGenerator()->create_user();
1560         $user2 = self::getDataGenerator()->create_user();
1561         $user3 = self::getDataGenerator()->create_user();
1562         $user4 = self::getDataGenerator()->create_user();
1564         // Create group conversation.
1565         $conversation = \core_message\api::create_conversation(
1566             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1567             [$user1->id, $user2->id, $user3->id, $user4->id]
1568         );
1570         // The person doing the search.
1571         $this->setUser($user1);
1573         // Send some messages back and forth.
1574         $time = 1;
1575         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
1576         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
1577         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
1578         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 4);
1579         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Yeah!', $time + 5);
1581         // Retrieve the messages.
1582         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id);
1584         // Confirm the conversation id is correct.
1585         $this->assertEquals($conversation->id, $convmessages['id']);
1587         // Confirm the message data is correct.
1588         $messages = $convmessages['messages'];
1589         $this->assertEquals(5, count($messages));
1591         $message1 = $messages[0];
1592         $message2 = $messages[1];
1593         $message3 = $messages[2];
1594         $message4 = $messages[3];
1595         $message5 = $messages[4];
1597         $this->assertEquals($user1->id, $message1->useridfrom);
1598         $this->assertContains('Yo!', $message1->text);
1600         $this->assertEquals($user2->id, $message2->useridfrom);
1601         $this->assertContains('Sup mang?', $message2->text);
1603         $this->assertEquals($user3->id, $message3->useridfrom);
1604         $this->assertContains('Writing PHPUnit tests!', $message3->text);
1606         $this->assertEquals($user1->id, $message4->useridfrom);
1607         $this->assertContains('Word.', $message4->text);
1609         $this->assertEquals($user2->id, $message5->useridfrom);
1610         $this->assertContains('Yeah!', $message5->text);
1612         // Confirm the members data is correct.
1613         $members = $convmessages['members'];
1614         $this->assertEquals(3, count($members));
1615     }
1617     /**
1618      * Test verifying the sorting param for get_conversation_messages is respected().
1619      */
1620     public function test_get_conversation_messages_sorting() {
1621         // Create some users.
1622         $user1 = self::getDataGenerator()->create_user();
1623         $user2 = self::getDataGenerator()->create_user();
1624         $user3 = self::getDataGenerator()->create_user();
1626         // Create conversations - 1 group and 1 individual.
1627         $conversation = \core_message\api::create_conversation(
1628             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1629             [$user1->id, $user2->id]
1630         );
1631         $conversation2 = \core_message\api::create_conversation(
1632             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1633             [$user1->id, $user2->id, $user3->id]
1634         );
1636         // Send some messages back and forth.
1637         $time = 1;
1638         $m1id = testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
1639         $m2id = testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
1640         $m3id = testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
1641         $m4id = testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 4);
1643         $gm1id = testhelper::send_fake_message_to_conversation($user1, $conversation2->id, 'Yo!', $time + 1);
1644         $gm2id = testhelper::send_fake_message_to_conversation($user2, $conversation2->id, 'Sup mang?', $time + 2);
1645         $gm3id = testhelper::send_fake_message_to_conversation($user3, $conversation2->id, 'Writing PHPUnit tests!', $time + 3);
1646         $gm4id = testhelper::send_fake_message_to_conversation($user1, $conversation2->id, 'Word.', $time + 4);
1648         // The person doing the search.
1649         $this->setUser($user1);
1651         // Retrieve the messages using default sort ('timecreated ASC') and verify ordering.
1652         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id);
1653         $messages = $convmessages['messages'];
1654         $this->assertEquals($m1id, $messages[0]->id);
1655         $this->assertEquals($m2id, $messages[1]->id);
1656         $this->assertEquals($m3id, $messages[2]->id);
1657         $this->assertEquals($m4id, $messages[3]->id);
1659         // Retrieve the messages without specifying DESC sort ordering, and verify ordering.
1660         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated DESC');
1661         $messages = $convmessages['messages'];
1662         $this->assertEquals($m1id, $messages[3]->id);
1663         $this->assertEquals($m2id, $messages[2]->id);
1664         $this->assertEquals($m3id, $messages[1]->id);
1665         $this->assertEquals($m4id, $messages[0]->id);
1667         // Retrieve the messages using default sort ('timecreated ASC') and verify ordering.
1668         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation2->id);
1669         $messages = $convmessages['messages'];
1670         $this->assertEquals($gm1id, $messages[0]->id);
1671         $this->assertEquals($gm2id, $messages[1]->id);
1672         $this->assertEquals($gm3id, $messages[2]->id);
1673         $this->assertEquals($gm4id, $messages[3]->id);
1675         // Retrieve the messages without specifying DESC sort ordering, and verify ordering.
1676         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation2->id, 0, 0, 'timecreated DESC');
1677         $messages = $convmessages['messages'];
1678         $this->assertEquals($gm1id, $messages[3]->id);
1679         $this->assertEquals($gm2id, $messages[2]->id);
1680         $this->assertEquals($gm3id, $messages[1]->id);
1681         $this->assertEquals($gm4id, $messages[0]->id);
1682     }
1684     /**
1685      * Test retrieving conversation messages by providing a minimum timecreated value.
1686      */
1687     public function test_get_conversation_messages_time_from_only() {
1688         // Create some users.
1689         $user1 = self::getDataGenerator()->create_user();
1690         $user2 = self::getDataGenerator()->create_user();
1691         $user3 = self::getDataGenerator()->create_user();
1692         $user4 = self::getDataGenerator()->create_user();
1694         // Create group conversation.
1695         $conversation = \core_message\api::create_conversation(
1696             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1697             [$user1->id, $user2->id, $user3->id, $user4->id]
1698         );
1700         // The person doing the search.
1701         $this->setUser($user1);
1703         // Send some messages back and forth.
1704         $time = 1;
1705         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
1706         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
1707         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
1708         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
1710         // Retrieve the messages from $time, which should be all of them.
1711         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated ASC', $time);
1713         // Confirm the conversation id is correct.
1714         $this->assertEquals($conversation->id, $convmessages['id']);
1716         // Confirm the message data is correct.
1717         $messages = $convmessages['messages'];
1718         $this->assertEquals(4, count($messages));
1720         $message1 = $messages[0];
1721         $message2 = $messages[1];
1722         $message3 = $messages[2];
1723         $message4 = $messages[3];
1725         $this->assertContains('Message 1', $message1->text);
1726         $this->assertContains('Message 2', $message2->text);
1727         $this->assertContains('Message 3', $message3->text);
1728         $this->assertContains('Message 4', $message4->text);
1730         // Confirm the members data is correct.
1731         $members = $convmessages['members'];
1732         $this->assertEquals(3, count($members));
1734         // Retrieve the messages from $time + 3, which should only be the 2 last messages.
1735         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0,
1736             'timecreated ASC', $time + 3);
1738         // Confirm the conversation id is correct.
1739         $this->assertEquals($conversation->id, $convmessages['id']);
1741         // Confirm the message data is correct.
1742         $messages = $convmessages['messages'];
1743         $this->assertEquals(2, count($messages));
1745         $message1 = $messages[0];
1746         $message2 = $messages[1];
1748         $this->assertContains('Message 3', $message1->text);
1749         $this->assertContains('Message 4', $message2->text);
1751         // Confirm the members data is correct.
1752         $members = $convmessages['members'];
1753         $this->assertEquals(2, count($members));
1754     }
1756     /**
1757      * Test retrieving conversation messages by providing a maximum timecreated value.
1758      */
1759     public function test_get_conversation_messages_time_to_only() {
1760         // Create some users.
1761         $user1 = self::getDataGenerator()->create_user();
1762         $user2 = self::getDataGenerator()->create_user();
1763         $user3 = self::getDataGenerator()->create_user();
1764         $user4 = self::getDataGenerator()->create_user();
1766         // Create group conversation.
1767         $conversation = \core_message\api::create_conversation(
1768             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1769             [$user1->id, $user2->id, $user3->id, $user4->id]
1770         );
1772         // The person doing the search.
1773         $this->setUser($user1);
1775         // Send some messages back and forth.
1776         $time = 1;
1777         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
1778         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
1779         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
1780         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
1782         // Retrieve the messages up until $time + 4, which should be all of them.
1783         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated ASC',
1784             0, $time + 4);
1786         // Confirm the conversation id is correct.
1787         $this->assertEquals($conversation->id, $convmessages['id']);
1789         // Confirm the message data is correct.
1790         $messages = $convmessages['messages'];
1791         $this->assertEquals(4, count($messages));
1793         $message1 = $messages[0];
1794         $message2 = $messages[1];
1795         $message3 = $messages[2];
1796         $message4 = $messages[3];
1798         $this->assertContains('Message 1', $message1->text);
1799         $this->assertContains('Message 2', $message2->text);
1800         $this->assertContains('Message 3', $message3->text);
1801         $this->assertContains('Message 4', $message4->text);
1803         // Confirm the members data is correct.
1804         $members = $convmessages['members'];
1805         $this->assertEquals(3, count($members));
1807         // Retrieve the messages up until $time + 2, which should be the first two.
1808         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated ASC',
1809             0, $time + 2);
1811         // Confirm the conversation id is correct.
1812         $this->assertEquals($conversation->id, $convmessages['id']);
1814         // Confirm the message data is correct.
1815         $messages = $convmessages['messages'];
1816         $this->assertEquals(2, count($messages));
1818         $message1 = $messages[0];
1819         $message2 = $messages[1];
1821         $this->assertContains('Message 1', $message1->text);
1822         $this->assertContains('Message 2', $message2->text);
1824         // Confirm the members data is correct.
1825         $members = $convmessages['members'];
1826         $this->assertEquals(2, count($members));
1827     }
1829     /**
1830      * Test retrieving conversation messages by providing a minimum and maximum timecreated value.
1831      */
1832     public function test_get_conversation_messages_time_from_and_to() {
1833         // Create some users.
1834         $user1 = self::getDataGenerator()->create_user();
1835         $user2 = self::getDataGenerator()->create_user();
1836         $user3 = self::getDataGenerator()->create_user();
1837         $user4 = self::getDataGenerator()->create_user();
1839         // Create group conversation.
1840         $conversation = \core_message\api::create_conversation(
1841             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1842             [$user1->id, $user2->id, $user3->id, $user4->id]
1843         );
1845         // The person doing the search.
1846         $this->setUser($user1);
1848         // Send some messages back and forth.
1849         $time = 1;
1850         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
1851         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
1852         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
1853         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
1855         // Retrieve the messages from $time + 2 up until $time + 3, which should be 2nd and 3rd message.
1856         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0,
1857             'timecreated ASC', $time + 2, $time + 3);
1859         // Confirm the conversation id is correct.
1860         $this->assertEquals($conversation->id, $convmessages['id']);
1862         // Confirm the message data is correct.
1863         $messages = $convmessages['messages'];
1864         $this->assertEquals(2, count($messages));
1866         $message1 = $messages[0];
1867         $message2 = $messages[1];
1869         $this->assertContains('Message 2', $message1->text);
1870         $this->assertContains('Message 3', $message2->text);
1872         // Confirm the members data is correct.
1873         $members = $convmessages['members'];
1874         $this->assertEquals(2, count($members));
1875     }
1878     /**
1879      * Test retrieving conversation messages by providing a limitfrom value.
1880      */
1881     public function test_get_conversation_messages_limitfrom_only() {
1882         // Create some users.
1883         $user1 = self::getDataGenerator()->create_user();
1884         $user2 = self::getDataGenerator()->create_user();
1885         $user3 = self::getDataGenerator()->create_user();
1886         $user4 = self::getDataGenerator()->create_user();
1888         // Create group conversation.
1889         $conversation = \core_message\api::create_conversation(
1890             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1891             [$user1->id, $user2->id, $user3->id, $user4->id]
1892         );
1894         // The person doing the search.
1895         $this->setUser($user1);
1897         // Send some messages back and forth.
1898         $time = 1;
1899         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
1900         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
1901         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
1902         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
1904         // Retrieve the messages from $time, which should be all of them.
1905         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 2);
1907         // Confirm the conversation id is correct.
1908         $messages = $convmessages['messages'];
1909         $this->assertEquals($conversation->id, $convmessages['id']);
1911         // Confirm the message data is correct.
1912         $this->assertEquals(2, count($messages));
1914         $message1 = $messages[0];
1915         $message2 = $messages[1];
1917         $this->assertContains('Message 3', $message1->text);
1918         $this->assertContains('Message 4', $message2->text);
1920         // Confirm the members data is correct.
1921         $members = $convmessages['members'];
1922         $this->assertEquals(2, count($members));
1923     }
1925     /**
1926      * Test retrieving conversation messages by providing a limitnum value.
1927      */
1928     public function test_get_conversation_messages_limitnum() {
1929         // Create some users.
1930         $user1 = self::getDataGenerator()->create_user();
1931         $user2 = self::getDataGenerator()->create_user();
1932         $user3 = self::getDataGenerator()->create_user();
1933         $user4 = self::getDataGenerator()->create_user();
1935         // Create group conversation.
1936         $conversation = \core_message\api::create_conversation(
1937             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1938             [$user1->id, $user2->id, $user3->id, $user4->id]
1939         );
1941         // The person doing the search.
1942         $this->setUser($user1);
1944         // Send some messages back and forth.
1945         $time = 1;
1946         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
1947         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
1948         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
1949         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
1951         // Retrieve the messages from $time, which should be all of them.
1952         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 2, 1);
1954         // Confirm the conversation id is correct.
1955         $messages = $convmessages['messages'];
1956         $this->assertEquals($conversation->id, $convmessages['id']);
1958         // Confirm the message data is correct.
1959         $messages = $convmessages['messages'];
1960         $this->assertEquals(1, count($messages));
1962         $message1 = $messages[0];
1964         $this->assertContains('Message 3', $message1->text);
1966         // Confirm the members data is correct.
1967         $members = $convmessages['members'];
1968         $this->assertEquals(1, count($members));
1969     }
1971     /**
1972      * Tests retrieving most recent message.
1973      */
1974     public function test_get_most_recent_message() {
1975         // Create some users.
1976         $user1 = self::getDataGenerator()->create_user();
1977         $user2 = self::getDataGenerator()->create_user();
1979         // The person doing the search.
1980         $this->setUser($user1);
1982         // Send some messages back and forth.
1983         $time = 1;
1984         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
1985         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
1986         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
1987         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
1989         // Retrieve the most recent messages.
1990         $message = \core_message\api::get_most_recent_message($user1->id, $user2->id);
1991         $this->assertDebuggingCalledCount(3);
1993         // Check the results are correct.
1994         $this->assertEquals($user2->id, $message->useridfrom);
1995         $this->assertEquals($user1->id, $message->useridto);
1996         $this->assertContains('Word.', $message->text);
1997     }
1999     /**
2000      * Tests retrieving most recent conversation message.
2001      */
2002     public function test_get_most_recent_conversation_message() {
2003         // Create some users.
2004         $user1 = self::getDataGenerator()->create_user();
2005         $user2 = self::getDataGenerator()->create_user();
2006         $user3 = self::getDataGenerator()->create_user();
2008         // Create group conversation.
2009         $conversation = \core_message\api::create_conversation(
2010             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2011             [$user1->id, $user2->id, $user3->id]
2012         );
2014         // The person getting the most recent conversation message.
2015         $this->setUser($user1);
2017         // Send some messages back and forth.
2018         $time = 1;
2019         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
2020         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
2021         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
2022         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Word.', $time + 4);
2024         // Retrieve the most recent messages.
2025         $message = \core_message\api::get_most_recent_conversation_message($conversation->id, $user1->id);
2027         // Check the results are correct.
2028         $this->assertEquals($user2->id, $message->useridfrom);
2029         $this->assertContains('Word.', $message->text);
2030     }
2032     /**
2033      * Tests retrieving a user's profile.
2034      */
2035     public function test_get_profile() {
2036         // Create some users.
2037         $user1 = self::getDataGenerator()->create_user();
2039         $user2 = new stdClass();
2040         $user2->country = 'AU';
2041         $user2->city = 'Perth';
2042         $user2 = self::getDataGenerator()->create_user($user2);
2044         // The person doing the search.
2045         $this->setUser($user1);
2047         // Get the profile.
2048         $profile = \core_message\api::get_profile($user1->id, $user2->id);
2050         $this->assertEquals($user2->id, $profile->userid);
2051         $this->assertEmpty($profile->email);
2052         $this->assertEmpty($profile->country);
2053         $this->assertEmpty($profile->city);
2054         $this->assertEquals(fullname($user2), $profile->fullname);
2055         $this->assertNull($profile->isonline);
2056         $this->assertFalse($profile->isblocked);
2057         $this->assertFalse($profile->iscontact);
2058     }
2060     /**
2061      * Tests retrieving a user's profile.
2062      */
2063     public function test_get_profile_as_admin() {
2064         // The person doing the search.
2065         $this->setAdminUser();
2067         // Create some users.
2068         $user1 = self::getDataGenerator()->create_user();
2070         $user2 = new stdClass();
2071         $user2->country = 'AU';
2072         $user2->city = 'Perth';
2073         $user2 = self::getDataGenerator()->create_user($user2);
2075         // Get the profile.
2076         $profile = \core_message\api::get_profile($user1->id, $user2->id);
2078         $this->assertEquals($user2->id, $profile->userid);
2079         $this->assertEquals($user2->email, $profile->email);
2080         $this->assertEquals($user2->country, $profile->country);
2081         $this->assertEquals($user2->city, $profile->city);
2082         $this->assertEquals(fullname($user2), $profile->fullname);
2083         $this->assertFalse($profile->isonline);
2084         $this->assertFalse($profile->isblocked);
2085         $this->assertFalse($profile->iscontact);
2086     }
2088     /**
2089      * Tests checking if a user can mark all messages as read.
2090      */
2091     public function test_can_mark_all_messages_as_read() {
2092         // Set as the admin.
2093         $this->setAdminUser();
2095         // Create some users.
2096         $user1 = self::getDataGenerator()->create_user();
2097         $user2 = self::getDataGenerator()->create_user();
2098         $user3 = self::getDataGenerator()->create_user();
2100         // Send some messages back and forth.
2101         $time = 1;
2102         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2103         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2104         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2105         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2107         $conversationid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2109         // The admin can do anything.
2110         $this->assertTrue(\core_message\api::can_mark_all_messages_as_read($user1->id, $conversationid));
2112         // Set as the user 1.
2113         $this->setUser($user1);
2115         // The user can mark the messages as he is in the conversation.
2116         $this->assertTrue(\core_message\api::can_mark_all_messages_as_read($user1->id, $conversationid));
2118         // User 1 can not mark the messages read for user 2.
2119         $this->assertFalse(\core_message\api::can_mark_all_messages_as_read($user2->id, $conversationid));
2121         // This user is not a part of the conversation.
2122         $this->assertFalse(\core_message\api::can_mark_all_messages_as_read($user3->id, $conversationid));
2123     }
2125     /**
2126      * Tests checking if a user can delete a conversation.
2127      */
2128     public function test_can_delete_conversation() {
2129         // Set as the admin.
2130         $this->setAdminUser();
2132         // Create some users.
2133         $user1 = self::getDataGenerator()->create_user();
2134         $user2 = self::getDataGenerator()->create_user();
2136         // Send some messages back and forth.
2137         $time = 1;
2138         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2139         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2140         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2141         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2143         $conversationid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2145         // The admin can do anything.
2146         $this->assertTrue(\core_message\api::can_delete_conversation($user1->id, $conversationid));
2148         // Set as the user 1.
2149         $this->setUser($user1);
2151         // They can delete their own messages.
2152         $this->assertTrue(\core_message\api::can_delete_conversation($user1->id, $conversationid));
2154         // They can't delete someone elses.
2155         $this->assertFalse(\core_message\api::can_delete_conversation($user2->id, $conversationid));
2156     }
2158     /**
2159      * Tests deleting a conversation.
2160      */
2161     public function test_delete_conversation() {
2162         global $DB;
2164         // Create some users.
2165         $user1 = self::getDataGenerator()->create_user();
2166         $user2 = self::getDataGenerator()->create_user();
2168         // The person doing the search.
2169         $this->setUser($user1);
2171         // Send some messages back and forth.
2172         $time = 1;
2173         $m1id = $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2174         $m2id = $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2175         $m3id = $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2176         $m4id = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2178         // Delete the conversation as user 1.
2179         \core_message\api::delete_conversation($user1->id, $user2->id);
2180         $this->assertDebuggingCalled();
2182         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
2183         $this->assertCount(4, $muas);
2184         // Sort by id.
2185         ksort($muas);
2187         $mua1 = array_shift($muas);
2188         $mua2 = array_shift($muas);
2189         $mua3 = array_shift($muas);
2190         $mua4 = array_shift($muas);
2192         $this->assertEquals($user1->id, $mua1->userid);
2193         $this->assertEquals($m1id, $mua1->messageid);
2194         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
2196         $this->assertEquals($user1->id, $mua2->userid);
2197         $this->assertEquals($m2id, $mua2->messageid);
2198         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
2200         $this->assertEquals($user1->id, $mua3->userid);
2201         $this->assertEquals($m3id, $mua3->messageid);
2202         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
2204         $this->assertEquals($user1->id, $mua4->userid);
2205         $this->assertEquals($m4id, $mua4->messageid);
2206         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
2207     }
2209     /**
2210      * Tests deleting a conversation by conversation id.
2211      */
2212     public function test_delete_conversation_by_id() {
2213         global $DB;
2215         // Create some users.
2216         $user1 = self::getDataGenerator()->create_user();
2217         $user2 = self::getDataGenerator()->create_user();
2219         // The person doing the search.
2220         $this->setUser($user1);
2222         // Send some messages back and forth.
2223         $time = 1;
2224         $m1id = $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2225         $m2id = $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2226         $m3id = $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2227         $m4id = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2229         // Delete the conversation as user 1.
2230         $conversationid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2231         \core_message\api::delete_conversation_by_id($user1->id, $conversationid);
2233         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
2234         $this->assertCount(4, $muas);
2235         // Sort by id.
2236         ksort($muas);
2238         $mua1 = array_shift($muas);
2239         $mua2 = array_shift($muas);
2240         $mua3 = array_shift($muas);
2241         $mua4 = array_shift($muas);
2243         $this->assertEquals($user1->id, $mua1->userid);
2244         $this->assertEquals($m1id, $mua1->messageid);
2245         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
2247         $this->assertEquals($user1->id, $mua2->userid);
2248         $this->assertEquals($m2id, $mua2->messageid);
2249         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
2251         $this->assertEquals($user1->id, $mua3->userid);
2252         $this->assertEquals($m3id, $mua3->messageid);
2253         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
2255         $this->assertEquals($user1->id, $mua4->userid);
2256         $this->assertEquals($m4id, $mua4->messageid);
2257         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
2258     }
2260     /**
2261      * Tests counting unread conversations.
2262      */
2263     public function test_count_unread_conversations() {
2264         $this->resetAfterTest(true);
2266         // Create some users.
2267         $user1 = self::getDataGenerator()->create_user();
2268         $user2 = self::getDataGenerator()->create_user();
2269         $user3 = self::getDataGenerator()->create_user();
2270         $user4 = self::getDataGenerator()->create_user();
2272         // The person wanting the conversation count.
2273         $this->setUser($user1);
2275         // Send some messages back and forth, have some different conversations with different users.
2276         $this->send_fake_message($user1, $user2, 'Yo!');
2277         $this->send_fake_message($user2, $user1, 'Sup mang?');
2278         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!');
2279         $this->send_fake_message($user2, $user1, 'Word.');
2281         $this->send_fake_message($user1, $user3, 'Booyah');
2282         $this->send_fake_message($user3, $user1, 'Whaaat?');
2283         $this->send_fake_message($user1, $user3, 'Nothing.');
2284         $this->send_fake_message($user3, $user1, 'Cool.');
2286         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
2287         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
2288         $this->send_fake_message($user1, $user4, 'Dope.');
2290         // Check the amount for the current user.
2291         $this->assertEquals(3, core_message\api::count_unread_conversations());
2293         // Check the amount for the second user.
2294         $this->assertEquals(1, core_message\api::count_unread_conversations($user2));
2295     }
2297     /**
2298      * Tests deleting a conversation.
2299      */
2300     public function test_get_all_message_preferences() {
2301         $user = self::getDataGenerator()->create_user();
2302         $this->setUser($user);
2304         // Set a couple of preferences to test.
2305         set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
2306         set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
2308         $processors = get_message_processors();
2309         $providers = message_get_providers_for_user($user->id);
2310         $prefs = \core_message\api::get_all_message_preferences($processors, $providers, $user);
2312         $this->assertEquals(1, $prefs->mod_assign_assign_notification_loggedin['popup']);
2313         $this->assertEquals(1, $prefs->mod_assign_assign_notification_loggedoff['email']);
2314     }
2316     /**
2317      * Tests the user can post a message.
2318      */
2319     public function test_can_post_message() {
2320         // Create some users.
2321         $user1 = self::getDataGenerator()->create_user();
2322         $user2 = self::getDataGenerator()->create_user();
2324         // Set as the first user.
2325         $this->setUser($user1);
2327         // With the default privacy setting, users can't message them.
2328         $this->assertFalse(\core_message\api::can_post_message($user2));
2330         // Enrol users to the same course.
2331         $course = $this->getDataGenerator()->create_course();
2332         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
2333         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
2334         // After enrolling users to the course, they should be able to message them with the default privacy setting.
2335         $this->assertTrue(\core_message\api::can_post_message($user2));
2336     }
2338     /**
2339      * Tests the user can't post a message without proper capability.
2340      */
2341     public function test_can_post_message_without_sendmessage_cap() {
2342         global $DB;
2344         // Create some users.
2345         $user1 = self::getDataGenerator()->create_user();
2346         $user2 = self::getDataGenerator()->create_user();
2348         // Set as the user 1.
2349         $this->setUser($user1);
2351         // Remove the capability to send a message.
2352         $roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
2353         unassign_capability('moodle/site:sendmessage', $roleids['user'],
2354             context_system::instance());
2356         // Check that we can not post a message without the capability.
2357         $this->assertFalse(\core_message\api::can_post_message($user2));
2358     }
2360     /**
2361      * Tests the user can post a message when they are contact.
2362      */
2363     public function test_can_post_message_when_contact() {
2364         // Create some users.
2365         $user1 = self::getDataGenerator()->create_user();
2366         $user2 = self::getDataGenerator()->create_user();
2368         // Set as the first user.
2369         $this->setUser($user1);
2371         // Check that we can not send user2 a message.
2372         $this->assertFalse(\core_message\api::can_post_message($user2));
2374         // Add users as contacts.
2375         \core_message\api::add_contact($user1->id, $user2->id);
2377         // Check that the return result is now true.
2378         $this->assertTrue(\core_message\api::can_post_message($user2));
2379     }
2381     /**
2382      * Tests the user can't post a message if they are not a contact and the user
2383      * has requested messages only from contacts.
2384      */
2385     public function test_can_post_message_when_not_contact() {
2386         // Create some users.
2387         $user1 = self::getDataGenerator()->create_user();
2388         $user2 = self::getDataGenerator()->create_user();
2390         // Set as the first user.
2391         $this->setUser($user1);
2393         // Set the second user's preference to not receive messages from non-contacts.
2394         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
2396         // Check that we can not send user 2 a message.
2397         $this->assertFalse(\core_message\api::can_post_message($user2));
2398     }
2400     /**
2401      * Tests the user can't post a message if they are blocked.
2402      */
2403     public function test_can_post_message_when_blocked() {
2404         // Create some users.
2405         $user1 = self::getDataGenerator()->create_user();
2406         $user2 = self::getDataGenerator()->create_user();
2408         // Set the user.
2409         $this->setUser($user1);
2411         // Block the second user.
2412         \core_message\api::block_user($user1->id, $user2->id);
2414         // Check that the second user can no longer send the first user a message.
2415         $this->assertFalse(\core_message\api::can_post_message($user1, $user2));
2416     }
2418     /**
2419      * Tests the user can post a message when site-wide messaging setting is enabled,
2420      * even if they are not a contact and are not members of the same course.
2421      */
2422     public function test_can_post_message_site_messaging_setting() {
2423         // Create some users.
2424         $user1 = self::getDataGenerator()->create_user();
2425         $user2 = self::getDataGenerator()->create_user();
2427         // Set as the first user.
2428         $this->setUser($user1);
2430         // By default, user only can be messaged by contacts and members of any of his/her courses.
2431         $this->assertFalse(\core_message\api::can_post_message($user2));
2433         // Enable site-wide messagging privacy setting. The user will be able to receive messages from everybody.
2434         set_config('messagingallusers', true);
2436         // Set the second user's preference to receive messages from everybody.
2437         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_SITE, $user2->id);
2439         // Check that we can send user2 a message.
2440         $this->assertTrue(\core_message\api::can_post_message($user2));
2442         // Disable site-wide messagging privacy setting. The user will be able to receive messages from contacts
2443         // and members sharing a course with her.
2444         set_config('messagingallusers', false);
2446         // As site-wide messaging setting is disabled, the value for user2 will be changed to MESSAGE_PRIVACY_COURSEMEMBER.
2447         $this->assertFalse(\core_message\api::can_post_message($user2));
2449         // Enrol users to the same course.
2450         $course = $this->getDataGenerator()->create_course();
2451         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
2452         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
2453         // Check that we can send user2 a message because they are sharing a course.
2454         $this->assertTrue(\core_message\api::can_post_message($user2));
2456         // Set the second user's preference to receive messages only from contacts.
2457         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
2458         // Check that now the user2 can't be contacted because user1 is not their contact.
2459         $this->assertFalse(\core_message\api::can_post_message($user2));
2461         // Make contacts user1 and user2.
2462         \core_message\api::add_contact($user2->id, $user1->id);
2463         // Check that we can send user2 a message because they are contacts.
2464         $this->assertTrue(\core_message\api::can_post_message($user2));
2465     }
2467     /**
2468      * Tests the user with the messageanyuser capability can post a message.
2469      */
2470     public function test_can_post_message_with_messageanyuser_cap() {
2471         global $DB;
2473         // Create some users.
2474         $teacher1 = self::getDataGenerator()->create_user();
2475         $student1 = self::getDataGenerator()->create_user();
2476         $student2 = self::getDataGenerator()->create_user();
2478         // Create users not enrolled in any course.
2479         $user1 = self::getDataGenerator()->create_user();
2481         // Create a course.
2482         $course1 = $this->getDataGenerator()->create_course();
2484         // Enrol the users in the course.
2485         $this->getDataGenerator()->enrol_user($teacher1->id, $course1->id, 'editingteacher');
2486         $this->getDataGenerator()->enrol_user($student1->id, $course1->id, 'student');
2487         $this->getDataGenerator()->enrol_user($student2->id, $course1->id, 'student');
2489         // Set some student preferences to not receive messages from non-contacts.
2490         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $student1->id);
2492         // Check that we can send student1 a message because teacher has the messageanyuser cap by default.
2493         $this->assertTrue(\core_message\api::can_post_message($student1, $teacher1));
2494         // Check that the teacher can't contact user1 because it's not his teacher.
2495         $this->assertFalse(\core_message\api::can_post_message($user1, $teacher1));
2497         // Remove the messageanyuser capability from the course1 for teachers.
2498         $coursecontext = context_course::instance($course1->id);
2499         $teacherrole = $DB->get_record('role', ['shortname' => 'editingteacher']);
2500         assign_capability('moodle/site:messageanyuser', CAP_PROHIBIT, $teacherrole->id, $coursecontext->id);
2501         $coursecontext->mark_dirty();
2503         // Check that we can't send user1 a message because they are not contacts.
2504         $this->assertFalse(\core_message\api::can_post_message($student1, $teacher1));
2505         // However, teacher can message student2 because they are sharing a course.
2506         $this->assertTrue(\core_message\api::can_post_message($student2, $teacher1));
2507     }
2509     /**
2510      * Tests get_user_privacy_messaging_preference method.
2511      */
2512     public function test_get_user_privacy_messaging_preference() {
2513         // Create some users.
2514         $user1 = self::getDataGenerator()->create_user();
2515         $user2 = self::getDataGenerator()->create_user();
2516         $user3 = self::getDataGenerator()->create_user();
2518         // Enable site-wide messagging privacy setting. The user will be able to receive messages from everybody.
2519         set_config('messagingallusers', true);
2521         // Set some user preferences.
2522         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_SITE, $user1->id);
2523         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
2525         // Check the returned value for each user.
2526         $this->assertEquals(
2527             \core_message\api::MESSAGE_PRIVACY_SITE,
2528             \core_message\api::get_user_privacy_messaging_preference($user1->id)
2529         );
2530         $this->assertEquals(
2531             \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
2532             \core_message\api::get_user_privacy_messaging_preference($user2->id)
2533         );
2534         $this->assertEquals(
2535             \core_message\api::MESSAGE_PRIVACY_SITE,
2536             \core_message\api::get_user_privacy_messaging_preference($user3->id)
2537         );
2539         // Disable site-wide messagging privacy setting. The user will be able to receive messages from members of their course.
2540         set_config('messagingallusers', false);
2542         // Check the returned value for each user.
2543         $this->assertEquals(
2544             \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
2545             \core_message\api::get_user_privacy_messaging_preference($user1->id)
2546         );
2547         $this->assertEquals(
2548             \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
2549             \core_message\api::get_user_privacy_messaging_preference($user2->id)
2550         );
2551         $this->assertEquals(
2552             \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
2553             \core_message\api::get_user_privacy_messaging_preference($user3->id)
2554         );
2555     }
2557     /**
2558      * Tests that when blocking messages from non-contacts is enabled that
2559      * non-contacts trying to send a message return false.
2560      */
2561     public function test_is_user_non_contact_blocked() {
2562         // Create some users.
2563         $user1 = self::getDataGenerator()->create_user();
2564         $user2 = self::getDataGenerator()->create_user();
2566         // Set as the first user.
2567         $this->setUser($user1);
2569         // By default, user only can be messaged by contacts and members of any of his/her courses.
2570         $this->assertTrue(\core_message\api::is_user_non_contact_blocked($user2));
2571         $this->assertDebuggingCalled();
2573         // Enable all users privacy messaging and check now the default user's preference has been set to allow receiving
2574         // messages from everybody.
2575         set_config('messagingallusers', true);
2576         // Check that the return result is now false because any site user can contact him/her.
2577         $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
2578         $this->assertDebuggingCalled();
2580         // Set the second user's preference to not receive messages from non-contacts.
2581         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
2582         // Check that the return result is still true (because is even more restricted).
2583         $this->assertTrue(\core_message\api::is_user_non_contact_blocked($user2));
2584         $this->assertDebuggingCalled();
2586         // Add the first user as a contact for the second user.
2587         \core_message\api::add_contact($user2->id, $user1->id);
2589         // Check that the return result is now false.
2590         $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
2591         $this->assertDebuggingCalled();
2593         // Set the second user's preference to receive messages from course members.
2594         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER, $user2->id);
2595         // Check that the return result is still false (because $user1 is still his/her contact).
2596         $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
2597         $this->assertDebuggingCalled();
2598     }
2600     /**
2601      * Tests that we return true when a user is blocked, or false
2602      * if they are not blocked.
2603      */
2604     public function test_is_user_blocked() {
2605         // Create some users.
2606         $user1 = self::getDataGenerator()->create_user();
2607         $user2 = self::getDataGenerator()->create_user();
2609         // Set the user.
2610         $this->setUser($user1);
2612         // User shouldn't be blocked.
2613         $this->assertFalse(\core_message\api::is_user_blocked($user1->id, $user2->id));
2614         $this->assertDebuggingCalled();
2616         // Block the user.
2617         \core_message\api::block_user($user1->id, $user2->id);
2619         // User should be blocked.
2620         $this->assertTrue(\core_message\api::is_user_blocked($user1->id, $user2->id));
2621         $this->assertDebuggingCalled();
2623         // Unblock the user.
2624         \core_message\api::unblock_user($user1->id, $user2->id);
2625         $this->assertFalse(\core_message\api::is_user_blocked($user1->id, $user2->id));
2626         $this->assertDebuggingCalled();
2627     }
2629     /**
2630      * Tests that the admin is not blocked even if someone has chosen to block them.
2631      */
2632     public function test_is_user_blocked_as_admin() {
2633         // Create a user.
2634         $user1 = self::getDataGenerator()->create_user();
2636         // Set the user.
2637         $this->setUser($user1);
2639         // Block the admin user.
2640         \core_message\api::block_user($user1->id, 2);
2642         // Now change to the admin user.
2643         $this->setAdminUser();
2645         // As the admin you should still be able to send messages to the user.
2646         $this->assertFalse(\core_message\api::is_user_blocked($user1->id));
2647         $this->assertDebuggingCalled();
2648     }
2650     /*
2651      * Tes get_message_processor api.
2652      */
2653     public function test_get_message_processor() {
2654         $processors = get_message_processors(true);
2655         if (empty($processors)) {
2656             $this->markTestSkipped("No message processors found");
2657         }
2659         $name = key($processors);
2660         $processor = current($processors);
2661         $testprocessor = \core_message\api::get_message_processor($name);
2662         $this->assertEquals($processor->name, $testprocessor->name);
2663         $this->assertEquals($processor->enabled, $testprocessor->enabled);
2664         $this->assertEquals($processor->available, $testprocessor->available);
2665         $this->assertEquals($processor->configured, $testprocessor->configured);
2667         // Disable processor and test.
2668         \core_message\api::update_processor_status($testprocessor, 0);
2669         $testprocessor = \core_message\api::get_message_processor($name, true);
2670         $this->assertEmpty($testprocessor);
2671         $testprocessor = \core_message\api::get_message_processor($name);
2672         $this->assertEquals($processor->name, $testprocessor->name);
2673         $this->assertEquals(0, $testprocessor->enabled);
2675         // Enable again and test.
2676         \core_message\api::update_processor_status($testprocessor, 1);
2677         $testprocessor = \core_message\api::get_message_processor($name, true);
2678         $this->assertEquals($processor->name, $testprocessor->name);
2679         $this->assertEquals(1, $testprocessor->enabled);
2680         $testprocessor = \core_message\api::get_message_processor($name);
2681         $this->assertEquals($processor->name, $testprocessor->name);
2682         $this->assertEquals(1, $testprocessor->enabled);
2683     }
2685     /**
2686      * Test method update_processor_status.
2687      */
2688     public function test_update_processor_status() {
2689         $processors = get_message_processors();
2690         if (empty($processors)) {
2691             $this->markTestSkipped("No message processors found");
2692         }
2693         $name = key($processors);
2694         $testprocessor = current($processors);
2696         // Enable.
2697         \core_message\api::update_processor_status($testprocessor, 1);
2698         $testprocessor = \core_message\api::get_message_processor($name);
2699         $this->assertEquals(1, $testprocessor->enabled);
2701         // Disable.
2702         \core_message\api::update_processor_status($testprocessor, 0);
2703         $testprocessor = \core_message\api::get_message_processor($name);
2704         $this->assertEquals(0, $testprocessor->enabled);
2706         // Enable again.
2707         \core_message\api::update_processor_status($testprocessor, 1);
2708         $testprocessor = \core_message\api::get_message_processor($name);
2709         $this->assertEquals(1, $testprocessor->enabled);
2710     }
2712     /**
2713      * Test method is_user_enabled.
2714      */
2715     public function is_user_enabled() {
2716         $processors = get_message_processors();
2717         if (empty($processors)) {
2718             $this->markTestSkipped("No message processors found");
2719         }
2720         $name = key($processors);
2721         $testprocessor = current($processors);
2723         // Enable.
2724         \core_message\api::update_processor_status($testprocessor, 1);
2725         $status = \core_message\api::is_processor_enabled($name);
2726         $this->assertEquals(1, $status);
2728         // Disable.
2729         \core_message\api::update_processor_status($testprocessor, 0);
2730         $status = \core_message\api::is_processor_enabled($name);
2731         $this->assertEquals(0, $status);
2733         // Enable again.
2734         \core_message\api::update_processor_status($testprocessor, 1);
2735         $status = \core_message\api::is_processor_enabled($name);
2736         $this->assertEquals(1, $status);
2737     }
2739     /**
2740      * Test retrieving messages by providing a minimum timecreated value.
2741      */
2742     public function test_get_messages_time_from_only() {
2743         // Create some users.
2744         $user1 = self::getDataGenerator()->create_user();
2745         $user2 = self::getDataGenerator()->create_user();
2747         // The person doing the search.
2748         $this->setUser($user1);
2750         // Send some messages back and forth.
2751         $time = 1;
2752         $this->send_fake_message($user1, $user2, 'Message 1', 0, $time + 1);
2753         $this->send_fake_message($user2, $user1, 'Message 2', 0, $time + 2);
2754         $this->send_fake_message($user1, $user2, 'Message 3', 0, $time + 3);
2755         $this->send_fake_message($user2, $user1, 'Message 4', 0, $time + 4);
2757         // Retrieve the messages from $time, which should be all of them.
2758         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', $time);
2759         $this->assertDebuggingCalledCount(3);
2761         // Confirm the message data is correct.
2762         $this->assertEquals(4, count($messages));
2764         $message1 = $messages[0];
2765         $message2 = $messages[1];
2766         $message3 = $messages[2];
2767         $message4 = $messages[3];
2769         $this->assertContains('Message 1', $message1->text);
2770         $this->assertContains('Message 2', $message2->text);
2771         $this->assertContains('Message 3', $message3->text);
2772         $this->assertContains('Message 4', $message4->text);
2774         // Retrieve the messages from $time + 3, which should only be the 2 last messages.
2775         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', $time + 3);
2776         $this->assertDebuggingCalledCount(3);
2778         // Confirm the message data is correct.
2779         $this->assertEquals(2, count($messages));
2781         $message1 = $messages[0];
2782         $message2 = $messages[1];
2784         $this->assertContains('Message 3', $message1->text);
2785         $this->assertContains('Message 4', $message2->text);
2786     }
2788     /**
2789      * Test retrieving messages by providing a maximum timecreated value.
2790      */
2791     public function test_get_messages_time_to_only() {
2792         // Create some users.
2793         $user1 = self::getDataGenerator()->create_user();
2794         $user2 = self::getDataGenerator()->create_user();
2796         // The person doing the search.
2797         $this->setUser($user1);
2799         // Send some messages back and forth.
2800         $time = 1;
2801         $this->send_fake_message($user1, $user2, 'Message 1', 0, $time + 1);
2802         $this->send_fake_message($user2, $user1, 'Message 2', 0, $time + 2);
2803         $this->send_fake_message($user1, $user2, 'Message 3', 0, $time + 3);
2804         $this->send_fake_message($user2, $user1, 'Message 4', 0, $time + 4);
2806         // Retrieve the messages up until $time + 4, which should be all of them.
2807         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', 0, $time + 4);
2808         $this->assertDebuggingCalledCount(3);
2810         // Confirm the message data is correct.
2811         $this->assertEquals(4, count($messages));
2813         $message1 = $messages[0];
2814         $message2 = $messages[1];
2815         $message3 = $messages[2];
2816         $message4 = $messages[3];
2818         $this->assertContains('Message 1', $message1->text);
2819         $this->assertContains('Message 2', $message2->text);
2820         $this->assertContains('Message 3', $message3->text);
2821         $this->assertContains('Message 4', $message4->text);
2823         // Retrieve the messages up until $time + 2, which should be the first two.
2824         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', 0, $time + 2);
2825         $this->assertDebuggingCalledCount(3);
2827         // Confirm the message data is correct.
2828         $this->assertEquals(2, count($messages));
2830         $message1 = $messages[0];
2831         $message2 = $messages[1];
2833         $this->assertContains('Message 1', $message1->text);
2834         $this->assertContains('Message 2', $message2->text);
2835     }
2837     /**
2838      * Test retrieving messages by providing a minimum and maximum timecreated value.
2839      */
2840     public function test_get_messages_time_from_and_to() {
2841         // Create some users.
2842         $user1 = self::getDataGenerator()->create_user();
2843         $user2 = self::getDataGenerator()->create_user();
2845         // The person doing the search.
2846         $this->setUser($user1);
2848         // Send some messages back and forth.
2849         $time = 1;
2850         $this->send_fake_message($user1, $user2, 'Message 1', 0, $time + 1);
2851         $this->send_fake_message($user2, $user1, 'Message 2', 0, $time + 2);
2852         $this->send_fake_message($user1, $user2, 'Message 3', 0, $time + 3);
2853         $this->send_fake_message($user2, $user1, 'Message 4', 0, $time + 4);
2855         // Retrieve the messages from $time + 2 up until $time + 3, which should be 2nd and 3rd message.
2856         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', $time + 2, $time + 3);
2857         $this->assertDebuggingCalledCount(3);
2859         // Confirm the message data is correct.
2860         $this->assertEquals(2, count($messages));
2862         $message1 = $messages[0];
2863         $message2 = $messages[1];
2865         $this->assertContains('Message 2', $message1->text);
2866         $this->assertContains('Message 3', $message2->text);
2867     }
2869     /**
2870      * Test returning blocked users.
2871      */
2872     public function test_get_blocked_users() {
2873         global $USER;
2875         // Set this user as the admin.
2876         $this->setAdminUser();
2878         // Create a user to add to the admin's contact list.
2879         $user1 = $this->getDataGenerator()->create_user();
2880         $user2 = $this->getDataGenerator()->create_user();
2882         // Add users to the admin's contact list.
2883         \core_message\api::block_user($USER->id, $user2->id);
2885         $this->assertCount(1, \core_message\api::get_blocked_users($USER->id));
2887         // Block other user.
2888         \core_message\api::block_user($USER->id, $user1->id);
2889         $this->assertCount(2, \core_message\api::get_blocked_users($USER->id));
2891         // Test deleting users.
2892         delete_user($user1);
2893         $this->assertCount(1, \core_message\api::get_blocked_users($USER->id));
2894     }
2896     /**
2897      * Test returning contacts with unread message count.
2898      */
2899     public function test_get_contacts_with_unread_message_count() {
2900         global $DB;
2902         $user1 = self::getDataGenerator()->create_user();
2903         $user2 = self::getDataGenerator()->create_user();
2904         $user3 = self::getDataGenerator()->create_user();
2905         $user4 = self::getDataGenerator()->create_user();
2907         // Add the users to each of their contacts.
2908         \core_message\api::add_contact($user1->id, $user2->id);
2909         \core_message\api::add_contact($user2->id, $user3->id);
2911         $this->send_fake_message($user1, $user2);
2912         $this->send_fake_message($user1, $user2);
2913         $this->send_fake_message($user1, $user2);
2914         $message4id = $this->send_fake_message($user1, $user2);
2916         $this->send_fake_message($user3, $user2);
2917         $message6id = $this->send_fake_message($user3, $user2);
2918         $this->send_fake_message($user3, $user2);
2919         $this->send_fake_message($user3, $user2);
2920         $this->send_fake_message($user3, $user2);
2922         // Send a message that should never be included as the user is not a contact.
2923         $this->send_fake_message($user4, $user2);
2925         // Get the contacts and the unread message count.
2926         $messages = \core_message\api::get_contacts_with_unread_message_count($user2->id);
2928         // Confirm the size is correct.
2929         $this->assertCount(2, $messages);
2930         ksort($messages);
2932         $messageinfo1 = array_shift($messages);
2933         $messageinfo2 = array_shift($messages);
2935         $this->assertEquals($user1->id, $messageinfo1->id);
2936         $this->assertEquals(4, $messageinfo1->messagecount);
2937         $this->assertEquals($user3->id, $messageinfo2->id);
2938         $this->assertEquals(5, $messageinfo2->messagecount);
2940         // Mark some of the messages as read.
2941         $m4 = $DB->get_record('messages', ['id' => $message4id]);
2942         $m6 = $DB->get_record('messages', ['id' => $message6id]);
2943         \core_message\api::mark_message_as_read($user2->id, $m4);
2944         \core_message\api::mark_message_as_read($user2->id, $m6);
2946         // Get the contacts and the unread message count.
2947         $messages = \core_message\api::get_contacts_with_unread_message_count($user2->id);
2949         // Confirm the size is correct.
2950         $this->assertCount(2, $messages);
2951         ksort($messages);
2953         // Confirm read messages are not included.
2954         $messageinfo1 = array_shift($messages);
2955         $messageinfo2 = array_shift($messages);
2956         $this->assertEquals($user1->id, $messageinfo1->id);
2957         $this->assertEquals(3, $messageinfo1->messagecount);
2958         $this->assertEquals($user3->id, $messageinfo2->id);
2959         $this->assertEquals(4, $messageinfo2->messagecount);
2961         // Now, let's populate the database with messages from user2 to user 1.
2962         $this->send_fake_message($user2, $user1);
2963         $this->send_fake_message($user2, $user1);
2964         $messageid = $this->send_fake_message($user2, $user1);
2966         // Send a message that should never be included as the user is not a contact.
2967         $this->send_fake_message($user4, $user1);
2969         // Get the contacts and the unread message count.
2970         $messages = \core_message\api::get_contacts_with_unread_message_count($user1->id);
2972         // Confirm the size is correct.
2973         $this->assertCount(1, $messages);
2974         $messageinfo1 = array_shift($messages);
2975         $this->assertEquals($user2->id, $messageinfo1->id);
2976         $this->assertEquals(3, $messageinfo1->messagecount);
2978         // Mark the last message as read.
2979         $m = $DB->get_record('messages', ['id' => $messageid]);
2980         \core_message\api::mark_message_as_read($user1->id, $m);
2982         $messages = \core_message\api::get_contacts_with_unread_message_count($user1->id);
2984         // Confirm the size is correct.
2985         $this->assertCount(1, $messages);
2987         // Confirm read messages are not included.
2988         $messageinfo1 = array_shift($messages);
2989         $this->assertEquals($user2->id, $messageinfo1->id);
2990         $this->assertEquals(2, $messageinfo1->messagecount);
2991     }
2993     /**
2994      * Test returning contacts with unread message count when there are no messages.
2995      */
2996     public function test_get_contacts_with_unread_message_count_no_messages() {
2997         $user1 = self::getDataGenerator()->create_user();
2998         $user2 = self::getDataGenerator()->create_user();
3000         // Add the users to each of their contacts.
3001         \core_message\api::add_contact($user2->id, $user1->id);
3003         // Check we get the correct message count.
3004         $messages = \core_message\api::get_contacts_with_unread_message_count($user2->id);
3006         // Confirm the size is correct.
3007         $this->assertCount(1, $messages);
3009         $messageinfo = array_shift($messages);
3011         $this->assertEquals($user1->id, $messageinfo->id);
3012         $this->assertEquals(0, $messageinfo->messagecount);
3013     }
3015     /**
3016      * Test returning non-contacts with unread message count.
3017      */
3018     public function test_get_non_contacts_with_unread_message_count() {
3019         global $DB;
3021         $user1 = self::getDataGenerator()->create_user();
3022         $user2 = self::getDataGenerator()->create_user();
3023         $user3 = self::getDataGenerator()->create_user();
3024         $user4 = self::getDataGenerator()->create_user();
3026         // Add a user to the contact list of the users we are testing this function with.
3027         \core_message\api::add_contact($user1->id, $user4->id);
3028         \core_message\api::add_contact($user2->id, $user4->id);
3030         $this->send_fake_message($user1, $user2);
3031         $this->send_fake_message($user1, $user2);
3032         $this->send_fake_message($user1, $user2);
3033         $message4id = $this->send_fake_message($user1, $user2);
3035         $this->send_fake_message($user3, $user2);
3036         $message6id = $this->send_fake_message($user3, $user2);
3037         $this->send_fake_message($user3, $user2);
3038         $this->send_fake_message($user3, $user2);
3039         $this->send_fake_message($user3, $user2);
3041         // Send a message that should never be included as the user is a contact.
3042         $this->send_fake_message($user4, $user2);
3044         // Get the non-contacts and the unread message count.
3045         $messages = \core_message\api::get_non_contacts_with_unread_message_count($user2->id);
3047         // Check we get the correct message count.
3048         ksort($messages);
3049         $this->assertCount(2, $messages);
3050         $messageinfo1 = array_shift($messages);
3051         $messageinfo2 = array_shift($messages);
3052         $this->assertEquals($user1->id, $messageinfo1->id);
3053         $this->assertEquals(4, $messageinfo1->messagecount);
3054         $this->assertEquals($user3->id, $messageinfo2->id);
3055         $this->assertEquals(5, $messageinfo2->messagecount);
3057         // Mark some of the messages as read.
3058         $m4 = $DB->get_record('messages', ['id' => $message4id]);
3059         $m6 = $DB->get_record('messages', ['id' => $message6id]);
3060         \core_message\api::mark_message_as_read($user2->id, $m4);
3061         \core_message\api::mark_message_as_read($user2->id, $m6);
3063         // Get the non-contacts and the unread message count.
3064         $messages = \core_message\api::get_non_contacts_with_unread_message_count($user2->id);
3066         // Check the marked message is not returned in the message count.
3067         ksort($messages);
3068         $this->assertCount(2, $messages);
3069         $messageinfo1 = array_shift($messages);
3070         $messageinfo2 = array_shift($messages);
3071         $this->assertEquals($user1->id, $messageinfo1->id);
3072         $this->assertEquals(3, $messageinfo1->messagecount);
3073         $this->assertEquals($user3->id, $messageinfo2->id);
3074         $this->assertEquals(4, $messageinfo2->messagecount);
3076         // Now, let's populate the database with messages from user2 to user 1.
3077         $this->send_fake_message($user2, $user1);
3078         $this->send_fake_message($user2, $user1);
3079         $messageid = $this->send_fake_message($user2, $user1);
3081         // Send a message that should never be included as the user is a contact.
3082         $this->send_fake_message($user4, $user1);
3084         // Get the non-contacts and the unread message count.
3085         $messages = \core_message\api::get_non_contacts_with_unread_message_count($user1->id);
3087         // Confirm the size is correct.
3088         $this->assertCount(1, $messages);
3089         $messageinfo1 = array_shift($messages);
3090         $this->assertEquals($user2->id, $messageinfo1->id);
3091         $this->assertEquals(3, $messageinfo1->messagecount);
3093         // Mark the last message as read.
3094         $m = $DB->get_record('messages', ['id' => $messageid]);
3095         \core_message\api::mark_message_as_read($user1->id, $m);
3097         // Get the non-contacts and the unread message count.
3098         $messages = \core_message\api::get_non_contacts_with_unread_message_count($user1->id);
3100         // Check the marked message is not returned in the message count.
3101         $this->assertCount(1, $messages);
3102         $messageinfo1 = array_shift($messages);
3103         $this->assertEquals($user2->id, $messageinfo1->id);
3104         $this->assertEquals(2, $messageinfo1->messagecount);
3105     }
3107     /**
3108      * Test marking a message as read.
3109      */
3110     public function test_mark_message_as_read() {
3111         global $DB;
3113         $user1 = self::getDataGenerator()->create_user();
3114         $user2 = self::getDataGenerator()->create_user();
3116         $this->send_fake_message($user1, $user2);
3117         $m2id = $this->send_fake_message($user1, $user2);
3118         $this->send_fake_message($user2, $user1);
3119         $m4id = $this->send_fake_message($user2, $user1);
3121         $m2 = $DB->get_record('messages', ['id' => $m2id]);
3122         $m4 = $DB->get_record('messages', ['id' => $m4id]);
3123         \core_message\api::mark_message_as_read($user2->id, $m2, 11);
3124         \core_message\api::mark_message_as_read($user1->id, $m4, 12);
3126         // Confirm there are two user actions.
3127         $muas = $DB->get_records('message_user_actions', [], 'timecreated ASC');
3128         $this->assertEquals(2, count($muas));
3130         // Confirm they are correct.
3131         $mua1 = array_shift($muas);
3132         $mua2 = array_shift($muas);
3134         // Confirm first action.
3135         $this->assertEquals($user2->id, $mua1->userid);
3136         $this->assertEquals($m2id, $mua1->messageid);
3137         $this->assertEquals(\core_message\api::MESSAGE_ACTION_READ, $mua1->action);
3138         $this->assertEquals(11, $mua1->timecreated);
3140         // Confirm second action.
3141         $this->assertEquals($user1->id, $mua2->userid);
3142         $this->assertEquals($m4id, $mua2->messageid);
3143         $this->assertEquals(\core_message\api::MESSAGE_ACTION_READ, $mua2->action);
3144         $this->assertEquals(12, $mua2->timecreated);
3145     }
3147     /**
3148      * Test marking a notification as read.
3149      */
3150     public function test_mark_notification_as_read() {
3151         global $DB;
3153         $user1 = self::getDataGenerator()->create_user();
3154         $user2 = self::getDataGenerator()->create_user();
3156         $this->send_fake_message($user1, $user2, 'Notification 1', 1);
3157         $n2id = $this->send_fake_message($user1, $user2, 'Notification 2', 1);
3158         $this->send_fake_message($user2, $user1, 'Notification 3', 1);
3159         $n4id = $this->send_fake_message($user2, $user1, 'Notification 4', 1);
3161         $n2 = $DB->get_record('notifications', ['id' => $n2id]);
3162         $n4 = $DB->get_record('notifications', ['id' => $n4id]);
3164         \core_message\api::mark_notification_as_read($n2, 11);
3165         \core_message\api::mark_notification_as_read($n4, 12);
3167         // Retrieve the notifications.
3168         $n2 = $DB->get_record('notifications', ['id' => $n2id]);
3169         $n4 = $DB->get_record('notifications', ['id' => $n4id]);
3171         // Confirm they have been marked as read.
3172         $this->assertEquals(11, $n2->timeread);
3173         $this->assertEquals(12, $n4->timeread);
3174     }
3176     /**
3177      * Test a conversation is not returned if there is none.
3178      */
3179     public function test_get_conversation_between_users_no_conversation() {
3180         $user1 = self::getDataGenerator()->create_user();
3181         $user2 = self::getDataGenerator()->create_user();
3183         $this->assertFalse(\core_message\api::get_conversation_between_users([$user1->id, $user2->id]));
3184     }
3186     /**
3187      * Test we can return a conversation that exists between users.
3188      */
3189     public function test_get_conversation_between_users_with_existing_conversation() {
3190         $user1 = self::getDataGenerator()->create_user();
3191         $user2 = self::getDataGenerator()->create_user();
3193         $conversationid = \core_message\api::create_conversation_between_users([$user1->id, $user2->id]);
3194         $this->assertDebuggingCalled();
3196         $this->assertEquals($conversationid,
3197             \core_message\api::get_conversation_between_users([$user1->id, $user2->id]));
3198     }
3200     /**
3201      * Test count_conversation_members for non existing conversation.
3202      */
3203     public function test_count_conversation_members_no_existing_conversation() {
3204         $this->assertEquals(0,
3205             \core_message\api::count_conversation_members(0));
3206     }
3208     /**
3209      * Test count_conversation_members for existing conversation.
3210      */
3211     public function test_count_conversation_members_existing_conversation() {
3212         $user1 = self::getDataGenerator()->create_user();
3213         $user2 = self::getDataGenerator()->create_user();
3215         $conversation = \core_message\api::create_conversation(
3216             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3217             [
3218                 $user1->id,
3219                 $user2->id
3220             ]
3221         );
3222         $conversationid = $conversation->id;
3224         $this->assertEquals(2,
3225             \core_message\api::count_conversation_members($conversationid));
3226     }
3228     /**
3229      * Test add_members_to_conversation for an individual conversation.
3230      */
3231     public function test_add_members_to_individual_conversation() {
3232         $user1 = self::getDataGenerator()->create_user();
3233         $user2 = self::getDataGenerator()->create_user();
3234         $user3 = self::getDataGenerator()->create_user();
3236         $conversation = \core_message\api::create_conversation(
3237             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3238             [
3239                 $user1->id,
3240                 $user2->id
3241             ]
3242         );
3243         $conversationid = $conversation->id;
3245         $this->expectException('moodle_exception');
3246         \core_message\api::add_members_to_conversation([$user3->id], $conversationid);
3247     }
3249     /**
3250      * Test add_members_to_conversation for existing conversation.
3251      */
3252     public function test_add_members_to_existing_conversation() {
3253         $user1 = self::getDataGenerator()->create_user();
3254         $user2 = self::getDataGenerator()->create_user();
3255         $user3 = self::getDataGenerator()->create_user();
3257         $conversation = \core_message\api::create_conversation(
3258             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3259             [
3260                 $user1->id,
3261                 $user2->id
3262             ]
3263         );
3264         $conversationid = $conversation->id;
3266         $this->assertNull(\core_message\api::add_members_to_conversation([$user3->id], $conversationid));
3267         $this->assertEquals(3,
3268             \core_message\api::count_conversation_members($conversationid));
3269     }
3271     /**
3272      * Test add_members_to_conversation for non existing conversation.
3273      */
3274     public function test_add_members_to_no_existing_conversation() {
3275         $user1 = self::getDataGenerator()->create_user();
3277         // Throw dml_missing_record_exception for non existing conversation.
3278         $this->expectException('dml_missing_record_exception');
3279         \core_message\api::add_members_to_conversation([$user1->id], 0);
3280     }
3282     /**
3283      * Test add_member_to_conversation for non existing user.
3284      */
3285     public function test_add_members_to_no_existing_user() {
3286         $user1 = self::getDataGenerator()->create_user();
3287         $user2 = self::getDataGenerator()->create_user();
3289         $conversation = \core_message\api::create_conversation(
3290             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3291             [
3292                 $user1->id,
3293                 $user2->id
3294             ]
3295         );
3296         $conversationid = $conversation->id;
3298         // Don't throw an error for non existing user, but don't add it as a member.
3299         $this->assertNull(\core_message\api::add_members_to_conversation([0], $conversationid));
3300         $this->assertEquals(2,
3301             \core_message\api::count_conversation_members($conversationid));
3302     }
3304     /**
3305      * Test add_members_to_conversation for current conversation member.
3306      */
3307     public function test_add_members_to_current_conversation_member() {
3308         $user1 = self::getDataGenerator()->create_user();
3309         $user2 = self::getDataGenerator()->create_user();
3311         $conversation = \core_message\api::create_conversation(
3312             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3313             [
3314                 $user1->id,
3315                 $user2->id
3316             ]
3317         );
3318         $conversationid = $conversation->id;
3320         // Don't add as a member a user that is already conversation member.
3321         $this->assertNull(\core_message\api::add_members_to_conversation([$user1->id], $conversationid));
3322         $this->assertEquals(2,
3323             \core_message\api::count_conversation_members($conversationid));
3324     }
3326     /**