Merge branch 'MDL-63945_master' of git://github.com/markn86/moodle
[moodle.git] / message / tests / api_test.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Test message API.
19  *
20  * @package core_message
21  * @category test
22  * @copyright 2016 Mark Nelson <markn@moodle.com>
23  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 global $CFG;
30 require_once($CFG->dirroot . '/message/tests/messagelib_test.php');
32 use \core_message\tests\helper as testhelper;
34 /**
35  * Test message API.
36  *
37  * @package core_message
38  * @category test
39  * @copyright 2016 Mark Nelson <markn@moodle.com>
40  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41  */
42 class core_message_api_testcase extends core_message_messagelib_testcase {
44     public function test_mark_all_read_for_user_touser() {
45         $sender = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
46         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
48         $this->send_fake_message($sender, $recipient, 'Notification', 1);
49         $this->send_fake_message($sender, $recipient, 'Notification', 1);
50         $this->send_fake_message($sender, $recipient, 'Notification', 1);
51         $this->send_fake_message($sender, $recipient);
52         $this->send_fake_message($sender, $recipient);
53         $this->send_fake_message($sender, $recipient);
55         \core_message\api::mark_all_read_for_user($recipient->id);
56         $this->assertDebuggingCalled();
57         $this->assertEquals(message_count_unread_messages($recipient), 0);
58     }
60     public function test_mark_all_read_for_user_touser_with_fromuser() {
61         $sender1 = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
62         $sender2 = $this->getDataGenerator()->create_user(array('firstname' => 'Test3', 'lastname' => 'User3'));
63         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
65         $this->send_fake_message($sender1, $recipient, 'Notification', 1);
66         $this->send_fake_message($sender1, $recipient, 'Notification', 1);
67         $this->send_fake_message($sender1, $recipient, 'Notification', 1);
68         $this->send_fake_message($sender1, $recipient);
69         $this->send_fake_message($sender1, $recipient);
70         $this->send_fake_message($sender1, $recipient);
71         $this->send_fake_message($sender2, $recipient, 'Notification', 1);
72         $this->send_fake_message($sender2, $recipient, 'Notification', 1);
73         $this->send_fake_message($sender2, $recipient, 'Notification', 1);
74         $this->send_fake_message($sender2, $recipient);
75         $this->send_fake_message($sender2, $recipient);
76         $this->send_fake_message($sender2, $recipient);
78         \core_message\api::mark_all_read_for_user($recipient->id, $sender1->id);
79         $this->assertDebuggingCalled();
80         $this->assertEquals(message_count_unread_messages($recipient), 3);
81     }
83     public function test_mark_all_read_for_user_touser_with_type() {
84         $sender = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
85         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
87         $this->send_fake_message($sender, $recipient, 'Notification', 1);
88         $this->send_fake_message($sender, $recipient, 'Notification', 1);
89         $this->send_fake_message($sender, $recipient, 'Notification', 1);
90         $this->send_fake_message($sender, $recipient);
91         $this->send_fake_message($sender, $recipient);
92         $this->send_fake_message($sender, $recipient);
94         \core_message\api::mark_all_read_for_user($recipient->id, 0, MESSAGE_TYPE_NOTIFICATION);
95         $this->assertDebuggingCalled();
96         $this->assertEquals(message_count_unread_messages($recipient), 3);
98         \core_message\api::mark_all_read_for_user($recipient->id, 0, MESSAGE_TYPE_MESSAGE);
99         $this->assertDebuggingCalled();
100         $this->assertEquals(message_count_unread_messages($recipient), 0);
101     }
103     /**
104      * Test count_blocked_users.
105      */
106     public function test_count_blocked_users() {
107         global $USER;
109         // Set this user as the admin.
110         $this->setAdminUser();
112         // Create user to add to the admin's block list.
113         $user1 = $this->getDataGenerator()->create_user();
114         $user2 = $this->getDataGenerator()->create_user();
116         $this->assertEquals(0, \core_message\api::count_blocked_users());
118         // Add 1 blocked user to admin's blocked user list.
119         \core_message\api::block_user($USER->id, $user1->id);
121         $this->assertEquals(0, \core_message\api::count_blocked_users($user1));
122         $this->assertEquals(1, \core_message\api::count_blocked_users());
123     }
125     /**
126      * Tests searching users in a course.
127      */
128     public function test_search_users_in_course() {
129         // Create some users.
130         $user1 = new stdClass();
131         $user1->firstname = 'User';
132         $user1->lastname = 'One';
133         $user1 = self::getDataGenerator()->create_user($user1);
135         // The person doing the search.
136         $this->setUser($user1);
138         // Second user is going to have their last access set to now, so they are online.
139         $user2 = new stdClass();
140         $user2->firstname = 'User';
141         $user2->lastname = 'Two';
142         $user2->lastaccess = time();
143         $user2 = self::getDataGenerator()->create_user($user2);
145         // Block the second user.
146         \core_message\api::block_user($user1->id, $user2->id);
148         $user3 = new stdClass();
149         $user3->firstname = 'User';
150         $user3->lastname = 'Three';
151         $user3 = self::getDataGenerator()->create_user($user3);
153         // Create a course.
154         $course1 = new stdClass();
155         $course1->fullname = 'Course';
156         $course1->shortname = 'One';
157         $course1 = $this->getDataGenerator()->create_course($course1);
159         // Enrol the searcher and one user in the course.
160         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
161         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
163         // Perform a search.
164         $results = \core_message\api::search_users_in_course($user1->id, $course1->id, 'User');
166         $this->assertEquals(1, count($results));
168         $user = $results[0];
169         $this->assertEquals($user2->id, $user->userid);
170         $this->assertEquals(fullname($user2), $user->fullname);
171         $this->assertFalse($user->ismessaging);
172         $this->assertNull($user->lastmessage);
173         $this->assertNull($user->messageid);
174         $this->assertNull($user->isonline);
175         $this->assertFalse($user->isread);
176         $this->assertTrue($user->isblocked);
177         $this->assertNull($user->unreadcount);
178     }
180     /**
181      * Tests searching users.
182      */
183     public function test_search_users() {
184         global $DB;
186         // Create some users.
187         $user1 = new stdClass();
188         $user1->firstname = 'User';
189         $user1->lastname = 'One';
190         $user1 = self::getDataGenerator()->create_user($user1);
192         // Set as the user performing the search.
193         $this->setUser($user1);
195         $user2 = new stdClass();
196         $user2->firstname = 'User search';
197         $user2->lastname = 'Two';
198         $user2 = self::getDataGenerator()->create_user($user2);
200         $user3 = new stdClass();
201         $user3->firstname = 'User search';
202         $user3->lastname = 'Three';
203         $user3 = self::getDataGenerator()->create_user($user3);
205         $user4 = new stdClass();
206         $user4->firstname = 'User';
207         $user4->lastname = 'Four';
208         $user4 = self::getDataGenerator()->create_user($user4);
210         $user5 = new stdClass();
211         $user5->firstname = 'User search';
212         $user5->lastname = 'Five';
213         $user5 = self::getDataGenerator()->create_user($user5);
215         $user6 = new stdClass();
216         $user6->firstname = 'User';
217         $user6->lastname = 'Six';
218         $user6 = self::getDataGenerator()->create_user($user6);
220         // Create some courses.
221         $course1 = new stdClass();
222         $course1->fullname = 'Course search';
223         $course1->shortname = 'One';
224         $course1 = $this->getDataGenerator()->create_course($course1);
226         $course2 = new stdClass();
227         $course2->fullname = 'Course';
228         $course2->shortname = 'Two';
229         $course2 = $this->getDataGenerator()->create_course($course2);
231         $course3 = new stdClass();
232         $course3->fullname = 'Course';
233         $course3->shortname = 'Three search';
234         $course3 = $this->getDataGenerator()->create_course($course3);
236         $course4 = new stdClass();
237         $course4->fullname = 'Course Four';
238         $course4->shortname = 'CF100';
239         $course4 = $this->getDataGenerator()->create_course($course4);
241         $course5 = new stdClass();
242         $course5->fullname = 'Course';
243         $course5->shortname = 'Five search';
244         $course5 = $this->getDataGenerator()->create_course($course5);
246         $role = $DB->get_record('role', ['shortname' => 'student']);
247         $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $role->id);
248         $this->getDataGenerator()->enrol_user($user1->id, $course2->id, $role->id);
249         $this->getDataGenerator()->enrol_user($user1->id, $course3->id, $role->id);
250         $this->getDataGenerator()->enrol_user($user1->id, $course5->id, $role->id);
252         // Add some users as contacts.
253         \core_message\api::add_contact($user1->id, $user2->id);
254         \core_message\api::add_contact($user1->id, $user3->id);
255         \core_message\api::add_contact($user1->id, $user4->id);
257         // Remove the viewparticipants capability from one of the courses.
258         $course5context = context_course::instance($course5->id);
259         assign_capability('moodle/course:viewparticipants', CAP_PROHIBIT, $role->id, $course5context->id);
261         // Perform a search $CFG->messagingallusers setting enabled.
262         set_config('messagingallusers', 1);
263         list($contacts, $courses, $noncontacts) = \core_message\api::search_users($user1->id, 'search');
265         // Check that we retrieved the correct contacts.
266         $this->assertEquals(2, count($contacts));
267         $this->assertEquals($user3->id, $contacts[0]->userid);
268         $this->assertEquals($user2->id, $contacts[1]->userid);
270         // Check that we retrieved the correct courses.
271         $this->assertEquals(2, count($courses));
272         $this->assertEquals($course3->id, $courses[0]->id);
273         $this->assertEquals($course1->id, $courses[1]->id);
275         // Check that we retrieved the correct non-contacts.
276         $this->assertEquals(1, count($noncontacts));
277         $this->assertEquals($user5->id, $noncontacts[0]->userid);
278     }
280     /**
281      * Tests searching users with empty result.
282      */
283     public function test_search_users_with_empty_result() {
285         // Create some users.
286         $user1 = new stdClass();
287         $user1->firstname = 'User';
288         $user1->lastname = 'One';
289         $user1 = self::getDataGenerator()->create_user($user1);
291         // Set as the user performing the search.
292         $this->setUser($user1);
294         $user2 = new stdClass();
295         $user2->firstname = 'User';
296         $user2->lastname = 'Two';
297         $user2 = self::getDataGenerator()->create_user($user2);
299         // Perform a search $CFG->messagingallusers setting enabled.
300         set_config('messagingallusers', 1);
301         list($contacts, $courses, $noncontacts) = \core_message\api::search_users($user1->id, 'search');
303         // Check results are empty.
304         $this->assertEquals(0, count($contacts));
305         $this->assertEquals(0, count($courses));
306         $this->assertEquals(0, count($noncontacts));
307     }
309     /**
310      * Tests searching users.
311      */
312     public function test_message_search_users() {
313         // Create some users.
314         $user1 = new stdClass();
315         $user1->firstname = 'User search';
316         $user1->lastname = 'One';
317         $user1 = self::getDataGenerator()->create_user($user1);
319         // Set as the user performing the search.
320         $this->setUser($user1);
322         $user2 = new stdClass();
323         $user2->firstname = 'User search';
324         $user2->lastname = 'Two';
325         $user2 = self::getDataGenerator()->create_user($user2);
327         $user3 = new stdClass();
328         $user3->firstname = 'User search';
329         $user3->lastname = 'Three';
330         $user3 = self::getDataGenerator()->create_user($user3);
332         $user4 = new stdClass();
333         $user4->firstname = 'User';
334         $user4->lastname = 'Four';
335         $user4 = self::getDataGenerator()->create_user($user4);
337         $user5 = new stdClass();
338         $user5->firstname = 'User search';
339         $user5->lastname = 'Five';
340         $user5 = self::getDataGenerator()->create_user($user5);
342         $user6 = new stdClass();
343         $user6->firstname = 'User search';
344         $user6->lastname = 'Six';
345         $user6 = self::getDataGenerator()->create_user($user6);
347         $user7 = new stdClass();
348         $user7->firstname = 'User search';
349         $user7->lastname = 'Seven';
350         $user7 = self::getDataGenerator()->create_user($user7);
352         // Add some users as contacts.
353         \core_message\api::add_contact($user1->id, $user2->id);
354         \core_message\api::add_contact($user3->id, $user1->id);
355         \core_message\api::add_contact($user1->id, $user4->id);
357         // Create private conversations with some users.
358         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
359             array($user1->id, $user6->id));
360         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
361             array($user7->id, $user1->id));
363         // Perform a search $CFG->messagingallusers setting enabled.
364         set_config('messagingallusers', 1);
365         list($contacts, $noncontacts) = \core_message\api::message_search_users($user1->id, 'search');
367         // Check that we retrieved the correct contacts.
368         $this->assertCount(2, $contacts);
369         $this->assertEquals($user3->id, $contacts[0]->id);
370         $this->assertEquals($user2->id, $contacts[1]->id);
372         // Check that we retrieved the correct non-contacts.
373         $this->assertCount(3, $noncontacts);
374         $this->assertEquals($user5->id, $noncontacts[0]->id);
375         $this->assertEquals($user7->id, $noncontacts[1]->id);
376         $this->assertEquals($user6->id, $noncontacts[2]->id);
378         // Perform a search $CFG->messagingallusers setting disabled.
379         set_config('messagingallusers', 0);
380         list($contacts, $noncontacts) = \core_message\api::message_search_users($user1->id, 'search');
382         // Check that we retrieved the correct contacts.
383         $this->assertCount(2, $contacts);
384         $this->assertEquals($user3->id, $contacts[0]->id);
385         $this->assertEquals($user2->id, $contacts[1]->id);
387         // Check that we retrieved the correct non-contacts.
388         $this->assertCount(2, $noncontacts);
389         $this->assertEquals($user7->id, $noncontacts[0]->id);
390         $this->assertEquals($user6->id, $noncontacts[1]->id);
391     }
393     /**
394      * Tests getting conversations between 2 users.
395      */
396     public function test_get_conversations_between_users() {
397         // Create some users.
398         $user1 = new stdClass();
399         $user1->firstname = 'User';
400         $user1->lastname = 'One';
401         $user1 = self::getDataGenerator()->create_user($user1);
403         $user2 = new stdClass();
404         $user2->firstname = 'User';
405         $user2->lastname = 'Two';
406         $user2 = self::getDataGenerator()->create_user($user2);
408         $user3 = new stdClass();
409         $user3->firstname = 'User search';
410         $user3->lastname = 'Three';
411         $user3 = self::getDataGenerator()->create_user($user3);
413         $user4 = new stdClass();
414         $user4->firstname = 'User';
415         $user4->lastname = 'Four';
416         $user4 = self::getDataGenerator()->create_user($user4);
418         $user5 = new stdClass();
419         $user5->firstname = 'User';
420         $user5->lastname = 'Five';
421         $user5 = self::getDataGenerator()->create_user($user5);
423         $user6 = new stdClass();
424         $user6->firstname = 'User search';
425         $user6->lastname = 'Six';
426         $user6 = self::getDataGenerator()->create_user($user6);
428         // Add some users as contacts.
429         \core_message\api::add_contact($user1->id, $user2->id);
430         \core_message\api::add_contact($user6->id, $user1->id);
432         // Create private conversations with some users.
433         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
434             array($user1->id, $user2->id));
435         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
436             array($user3->id, $user1->id));
438         // Create a group conversation with users.
439         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
440             array($user1->id, $user2->id, $user3->id, $user4->id),
441             'Project chat');
443         // Check that we retrieved the correct conversations.
444         $this->assertCount(2, \core_message\api::get_conversations_between_users($user1->id, $user2->id));
445         $this->assertCount(2, \core_message\api::get_conversations_between_users($user2->id, $user1->id));
446         $this->assertCount(2, \core_message\api::get_conversations_between_users($user1->id, $user3->id));
447         $this->assertCount(2, \core_message\api::get_conversations_between_users($user3->id, $user1->id));
448         $this->assertCount(1, \core_message\api::get_conversations_between_users($user1->id, $user4->id));
449         $this->assertCount(1, \core_message\api::get_conversations_between_users($user4->id, $user1->id));
450         $this->assertCount(0, \core_message\api::get_conversations_between_users($user1->id, $user5->id));
451         $this->assertCount(0, \core_message\api::get_conversations_between_users($user5->id, $user1->id));
452         $this->assertCount(0, \core_message\api::get_conversations_between_users($user1->id, $user6->id));
453         $this->assertCount(0, \core_message\api::get_conversations_between_users($user6->id, $user1->id));
454     }
456     /**
457      * Tests searching users with and without conversations.
458      */
459     public function test_message_search_users_with_and_without_conversations() {
460         // Create some users.
461         $user1 = new stdClass();
462         $user1->firstname = 'User search';
463         $user1->lastname = 'One';
464         $user1 = self::getDataGenerator()->create_user($user1);
466         // Set as the user performing the search.
467         $this->setUser($user1);
469         $user2 = new stdClass();
470         $user2->firstname = 'User search';
471         $user2->lastname = 'Two';
472         $user2 = self::getDataGenerator()->create_user($user2);
474         $user3 = new stdClass();
475         $user3->firstname = 'User search';
476         $user3->lastname = 'Three';
477         $user3 = self::getDataGenerator()->create_user($user3);
479         $user4 = new stdClass();
480         $user4->firstname = 'User';
481         $user4->lastname = 'Four';
482         $user4 = self::getDataGenerator()->create_user($user4);
484         $user5 = new stdClass();
485         $user5->firstname = 'User search';
486         $user5->lastname = 'Five';
487         $user5 = self::getDataGenerator()->create_user($user5);
489         // Add a user as contact.
490         \core_message\api::add_contact($user1->id, $user2->id);
492         // Create private conversations with some users.
493         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
494             array($user1->id, $user2->id));
495         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
496             array($user3->id, $user1->id));
498         // Create a group conversation with users.
499         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
500             array($user1->id, $user2->id, $user4->id),
501             'Project chat');
503         // Perform a search $CFG->messagingallusers setting enabled.
504         set_config('messagingallusers', 1);
505         list($contacts, $noncontacts) = \core_message\api::message_search_users($user1->id, 'search');
507         // Check that we retrieved the correct contacts.
508         $this->assertCount(1, $contacts);
510         // Check that we retrieved the correct conversations for contacts.
511         $this->assertCount(2, $contacts[0]->conversations);
513         // Check that we retrieved the correct non-contacts.
514         $this->assertCount(2, $noncontacts);
515         $this->assertEquals($user5->id, $noncontacts[0]->id);
516         $this->assertEquals($user3->id, $noncontacts[1]->id);
518         // Check that we retrieved the correct conversations for non-contacts.
519         $this->assertCount(0, $noncontacts[0]->conversations);
520         $this->assertCount(1, $noncontacts[1]->conversations);
521     }
523     /**
524      * Tests searching users with empty result.
525      */
526     public function test_message_search_users_with_empty_result() {
528         // Create some users.
529         $user1 = new stdClass();
530         $user1->firstname = 'User';
531         $user1->lastname = 'One';
532         $user1 = self::getDataGenerator()->create_user($user1);
534         // Set as the user performing the search.
535         $this->setUser($user1);
537         $user2 = new stdClass();
538         $user2->firstname = 'User';
539         $user2->lastname = 'Two';
540         $user2 = self::getDataGenerator()->create_user($user2);
542         // Perform a search $CFG->messagingallusers setting enabled.
543         set_config('messagingallusers', 1);
544         list($contacts, $noncontacts) = \core_message\api::message_search_users($user1->id, 'search');
546         // Check results are empty.
547         $this->assertEquals(0, count($contacts));
548         $this->assertEquals(0, count($noncontacts));
549     }
551     /**
552      * Tests searching messages.
553      */
554     public function test_search_messages() {
555         // Create some users.
556         $user1 = self::getDataGenerator()->create_user();
557         $user2 = self::getDataGenerator()->create_user();
558         $user3 = self::getDataGenerator()->create_user();
560         // The person doing the search.
561         $this->setUser($user1);
563         // Send some messages back and forth.
564         $time = 1;
565         $this->send_fake_message($user3, $user1, 'Don\'t block me.', 0, $time);
566         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
567         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
568         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
569         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
571         // Block user 3.
572         \core_message\api::block_user($user1->id, $user3->id);
574         // Perform a search.
575         $messages = \core_message\api::search_messages($user1->id, 'o');
577         // Confirm the data is correct.
578         $this->assertEquals(3, count($messages));
580         $message1 = $messages[0];
581         $message2 = $messages[1];
582         $message3 = $messages[2];
584         $this->assertEquals($user2->id, $message1->userid);
585         $this->assertEquals($user2->id, $message1->useridfrom);
586         $this->assertEquals(fullname($user2), $message1->fullname);
587         $this->assertTrue($message1->ismessaging);
588         $this->assertEquals('Word.', $message1->lastmessage);
589         $this->assertNotEmpty($message1->messageid);
590         $this->assertNull($message1->isonline);
591         $this->assertFalse($message1->isread);
592         $this->assertFalse($message1->isblocked);
593         $this->assertNull($message1->unreadcount);
595         $this->assertEquals($user2->id, $message2->userid);
596         $this->assertEquals($user1->id, $message2->useridfrom);
597         $this->assertEquals(fullname($user2), $message2->fullname);
598         $this->assertTrue($message2->ismessaging);
599         $this->assertEquals('Yo!', $message2->lastmessage);
600         $this->assertNotEmpty($message2->messageid);
601         $this->assertNull($message2->isonline);
602         $this->assertTrue($message2->isread);
603         $this->assertFalse($message2->isblocked);
604         $this->assertNull($message2->unreadcount);
606         $this->assertEquals($user3->id, $message3->userid);
607         $this->assertEquals($user3->id, $message3->useridfrom);
608         $this->assertEquals(fullname($user3), $message3->fullname);
609         $this->assertTrue($message3->ismessaging);
610         $this->assertEquals('Don\'t block me.', $message3->lastmessage);
611         $this->assertNotEmpty($message3->messageid);
612         $this->assertNull($message3->isonline);
613         $this->assertFalse($message3->isread);
614         $this->assertTrue($message3->isblocked);
615         $this->assertNull($message3->unreadcount);
616     }
618     /**
619      * Test verifying that favourited conversations can be retrieved.
620      */
621     public function test_get_favourite_conversations() {
622         // Create some users.
623         $user1 = self::getDataGenerator()->create_user();
624         $user2 = self::getDataGenerator()->create_user();
625         $user3 = self::getDataGenerator()->create_user();
626         $user4 = self::getDataGenerator()->create_user();
628         // The person doing the search.
629         $this->setUser($user1);
631         // No conversations yet.
632         $this->assertEquals([], \core_message\api::get_conversations($user1->id));
634         // Create some conversations for user1.
635         $time = 1;
636         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
637         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
638         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
639         $messageid1 = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
641         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
642         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
643         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
644         $messageid2 = $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
646         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 9);
647         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 10);
648         $messageid3 = $this->send_fake_message($user1, $user4, 'Dope.', 0, $time + 11);
650         // Favourite the first 2 conversations for user1.
651         $convoids = [];
652         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
653         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
654         $user1context = context_user::instance($user1->id);
655         $service = \core_favourites\service_factory::get_service_for_user_context($user1context);
656         foreach ($convoids as $convoid) {
657             $service->create_favourite('core_message', 'message_conversations', $convoid, $user1context);
658         }
660         // We should have 3 conversations.
661         $this->assertCount(3, \core_message\api::get_conversations($user1->id));
663         // And 2 favourited conversations.
664         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, true);
665         $this->assertCount(2, $conversations);
666     }
668     /**
669      * Tests retrieving favourite conversations with a limit and offset to ensure pagination works correctly.
670      */
671     public function test_get_favourite_conversations_limit_offset() {
672         // Create some users.
673         $user1 = self::getDataGenerator()->create_user();
674         $user2 = self::getDataGenerator()->create_user();
675         $user3 = self::getDataGenerator()->create_user();
676         $user4 = self::getDataGenerator()->create_user();
678         // The person doing the search.
679         $this->setUser($user1);
681         // No conversations yet.
682         $this->assertEquals([], \core_message\api::get_conversations($user1->id));
684         // Create some conversations for user1.
685         $time = 1;
686         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
687         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
688         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
689         $messageid1 = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
691         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
692         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
693         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
694         $messageid2 = $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
696         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 9);
697         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 10);
698         $messageid3 = $this->send_fake_message($user1, $user4, 'Dope.', 0, $time + 11);
700         // Favourite the all conversations for user1.
701         $convoids = [];
702         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
703         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
704         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user4->id]);
705         $user1context = context_user::instance($user1->id);
706         $service = \core_favourites\service_factory::get_service_for_user_context($user1context);
707         foreach ($convoids as $convoid) {
708             $service->create_favourite('core_message', 'message_conversations', $convoid, $user1context);
709         }
711         // Get all records, using offset 0 and large limit.
712         $this->assertCount(2, \core_message\api::get_conversations($user1->id, 1, 10, null, true));
714         // Now, get 10 conversations starting at the second record. We should see 2 conversations.
715         $this->assertCount(2, \core_message\api::get_conversations($user1->id, 1, 10, null, true));
717         // Now, try to get favourited conversations using an invalid offset.
718         $this->assertCount(0, \core_message\api::get_conversations($user1->id, 4, 10, null, true));
719     }
721     /**
722      * Tests retrieving favourite conversations when a conversation contains a deleted user.
723      */
724     public function test_get_favourite_conversations_with_deleted_user() {
725         // Create some users.
726         $user1 = self::getDataGenerator()->create_user();
727         $user2 = self::getDataGenerator()->create_user();
728         $user3 = self::getDataGenerator()->create_user();
730         // Send some messages back and forth, have some different conversations with different users.
731         $time = 1;
732         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
733         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
734         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
735         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
737         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
738         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
739         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
740         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
742         // Favourite the all conversations for user1.
743         $convoids = [];
744         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
745         $convoids[] = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
746         $user1context = context_user::instance($user1->id);
747         $service = \core_favourites\service_factory::get_service_for_user_context($user1context);
748         foreach ($convoids as $convoid) {
749             $service->create_favourite('core_message', 'message_conversations', $convoid, $user1context);
750         }
752         // Delete the second user.
753         delete_user($user2);
755         // Retrieve the conversations.
756         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, true);
758         // We should only have one conversation because the other user was deleted.
759         $this->assertCount(1, $conversations);
761         // Confirm the conversation is from the non-deleted user.
762         $conversation = reset($conversations);
763         $this->assertEquals($convoids[1], $conversation->id);
764     }
766     /**
767      * Test confirming that conversations can be marked as favourites.
768      */
769     public function test_set_favourite_conversation() {
770         // Create some users.
771         $user1 = self::getDataGenerator()->create_user();
772         $user2 = self::getDataGenerator()->create_user();
773         $user3 = self::getDataGenerator()->create_user();
775         // Send some messages back and forth, have some different conversations with different users.
776         $time = 1;
777         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
778         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
779         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
780         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
782         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
783         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
784         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
785         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
787         // Favourite the first conversation as user 1.
788         $conversationid1 = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
789         \core_message\api::set_favourite_conversation($conversationid1, $user1->id);
791         // Verify we have a single favourite conversation a user 1.
792         $this->assertCount(1, \core_message\api::get_conversations($user1->id, 0, 20, null, true));
794         // Verify we have no favourites as user2, despite being a member in that conversation.
795         $this->assertCount(0, \core_message\api::get_conversations($user2->id, 0, 20, null, true));
797         // Try to favourite the same conversation again.
798         $this->expectException(\moodle_exception::class);
799         \core_message\api::set_favourite_conversation($conversationid1, $user1->id);
800     }
802     /**
803      * Test verifying that trying to mark a non-existent conversation as a favourite, results in an exception.
804      */
805     public function test_set_favourite_conversation_nonexistent_conversation() {
806         // Create some users.
807         $user1 = self::getDataGenerator()->create_user();
808         // Try to favourite a non-existent conversation.
809         $this->expectException(\moodle_exception::class);
810         \core_message\api::set_favourite_conversation(0, $user1->id);
811     }
813     /**
814      * Test verifying that a conversation cannot be marked as favourite unless the user is a member of that conversation.
815      */
816     public function test_set_favourite_conversation_non_member() {
817         // Create some users.
818         $user1 = self::getDataGenerator()->create_user();
819         $user2 = self::getDataGenerator()->create_user();
820         $user3 = self::getDataGenerator()->create_user();
822         // Send some messages back and forth, have some different conversations with different users.
823         $time = 1;
824         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
825         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
826         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
827         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
829         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
830         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
831         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
832         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
834         // Try to favourite the first conversation as user 3, who is not a member.
835         $conversationid1 = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
836         $this->expectException(\moodle_exception::class);
837         \core_message\api::set_favourite_conversation($conversationid1, $user3->id);
838     }
840     /**
841      * Test confirming that those conversations marked as favourites can be unfavourited.
842      */
843     public function test_unset_favourite_conversation() {
844         // Create some users.
845         $user1 = self::getDataGenerator()->create_user();
846         $user2 = self::getDataGenerator()->create_user();
847         $user3 = self::getDataGenerator()->create_user();
849         // Send some messages back and forth, have some different conversations with different users.
850         $time = 1;
851         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
852         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
853         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
854         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
856         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
857         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
858         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
859         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
861         // Favourite the first conversation as user 1 and the second as user 3.
862         $conversationid1 = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
863         $conversationid2 = \core_message\api::get_conversation_between_users([$user1->id, $user3->id]);
864         \core_message\api::set_favourite_conversation($conversationid1, $user1->id);
865         \core_message\api::set_favourite_conversation($conversationid2, $user3->id);
867         // Verify we have a single favourite conversation for both user 1 and user 3.
868         $this->assertCount(1, \core_message\api::get_conversations($user1->id, 0, 20, null, true));
869         $this->assertCount(1, \core_message\api::get_conversations($user3->id, 0, 20, null, true));
871         // Now unfavourite the conversation as user 1.
872         \core_message\api::unset_favourite_conversation($conversationid1, $user1->id);
874         // Verify we have a single favourite conversation user 3 only, and none for user1.
875         $this->assertCount(1, \core_message\api::get_conversations($user3->id, 0, 20, null, true));
876         $this->assertCount(0, \core_message\api::get_conversations($user1->id, 0, 20, null, true));
878         // Try to favourite the same conversation again as user 1.
879         $this->expectException(\moodle_exception::class);
880         \core_message\api::unset_favourite_conversation($conversationid1, $user1->id);
881     }
883     /**
884      * Test verifying that a valid conversation cannot be unset as a favourite if it's not marked as a favourite.
885      */
886     public function test_unset_favourite_conversation_not_favourite() {
887         // Create some users.
888         $user1 = self::getDataGenerator()->create_user();
889         $user2 = self::getDataGenerator()->create_user();
891         // Send some messages back and forth, have some different conversations with different users.
892         $time = 1;
893         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
894         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
895         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
896         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
898         // Now try to unfavourite the conversation as user 1.
899         $conversationid1 = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
900         $this->expectException(\moodle_exception::class);
901         \core_message\api::unset_favourite_conversation($conversationid1, $user1->id);
902     }
904     /**
905      * Test verifying that a non-existent conversation cannot be unset as a favourite.
906      */
907     public function test_unset_favourite_conversation_non_existent_conversation() {
908         // Create some users.
909         $user1 = self::getDataGenerator()->create_user();
911         // Now try to unfavourite the conversation as user 1.
912         $this->expectException(\moodle_exception::class);
913         \core_message\api::unset_favourite_conversation(0, $user1->id);
914     }
916     /**
917      * Helper to seed the database with initial state.
918      */
919     protected function create_conversation_test_data() {
920         // Create some users.
921         $user1 = self::getDataGenerator()->create_user();
922         $user2 = self::getDataGenerator()->create_user();
923         $user3 = self::getDataGenerator()->create_user();
924         $user4 = self::getDataGenerator()->create_user();
926         $time = 1;
928         // Create some conversations. We want:
929         // 1) At least one of each type (group, individual) of which user1 IS a member and DID send the most recent message.
930         // 2) At least one of each type (group, individual) of which user1 IS a member and DID NOT send the most recent message.
931         // 3) At least one of each type (group, individual) of which user1 IS NOT a member.
932         // 4) At least two group conversation having 0 messages, of which user1 IS a member (To confirm conversationid ordering).
933         // 5) At least one group conversation having 0 messages, of which user1 IS NOT a member.
935         // Individual conversation, user1 is a member, last message from other user.
936         $ic1 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
937             [$user1->id, $user2->id]);
938         testhelper::send_fake_message_to_conversation($user1, $ic1->id, 'Message 1', $time);
939         testhelper::send_fake_message_to_conversation($user2, $ic1->id, 'Message 2', $time + 1);
941         // Individual conversation, user1 is a member, last message from user1.
942         $ic2 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
943             [$user1->id, $user3->id]);
944         testhelper::send_fake_message_to_conversation($user3, $ic2->id, 'Message 3', $time + 2);
945         testhelper::send_fake_message_to_conversation($user1, $ic2->id, 'Message 4', $time + 3);
947         // Individual conversation, user1 is not a member.
948         $ic3 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
949             [$user2->id, $user3->id]);
950         testhelper::send_fake_message_to_conversation($user2, $ic3->id, 'Message 5', $time + 4);
951         testhelper::send_fake_message_to_conversation($user3, $ic3->id, 'Message 6', $time + 5);
953         // Group conversation, user1 is not a member.
954         $gc1 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
955             [$user2->id, $user3->id, $user4->id], 'Project discussions');
956         testhelper::send_fake_message_to_conversation($user2, $gc1->id, 'Message 7', $time + 6);
957         testhelper::send_fake_message_to_conversation($user4, $gc1->id, 'Message 8', $time + 7);
959         // Group conversation, user1 is a member, last message from another user.
960         $gc2 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
961             [$user1->id, $user3->id, $user4->id], 'Group chat');
962         testhelper::send_fake_message_to_conversation($user1, $gc2->id, 'Message 9', $time + 8);
963         testhelper::send_fake_message_to_conversation($user3, $gc2->id, 'Message 10', $time + 9);
964         testhelper::send_fake_message_to_conversation($user4, $gc2->id, 'Message 11', $time + 10);
966         // Group conversation, user1 is a member, last message from user1.
967         $gc3 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
968             [$user1->id, $user2->id, $user3->id, $user4->id], 'Group chat again!');
969         testhelper::send_fake_message_to_conversation($user4, $gc3->id, 'Message 12', $time + 11);
970         testhelper::send_fake_message_to_conversation($user3, $gc3->id, 'Message 13', $time + 12);
971         testhelper::send_fake_message_to_conversation($user1, $gc3->id, 'Message 14', $time + 13);
973         // Empty group conversations (x2), user1 is a member.
974         $gc4 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
975             [$user1->id, $user2->id, $user3->id], 'Empty group');
976         $gc5 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
977             [$user1->id, $user2->id, $user4->id], 'Another empty group');
979         // Empty group conversation, user1 is NOT a member.
980         $gc6 = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
981             [$user2->id, $user3->id, $user4->id], 'Empty group 3');
983         return [$user1, $user2, $user3, $user4, $ic1, $ic2, $ic3, $gc1, $gc2, $gc3, $gc4, $gc5, $gc6];
984     }
986     /**
987      * Test verifying get_conversations when no limits, offsets, type filters or favourite restrictions are used.
988      */
989     public function test_get_conversations_no_restrictions() {
990         global $DB;
991         // No conversations should exist yet.
992         $user1 = self::getDataGenerator()->create_user();
993         $this->assertEquals([], \core_message\api::get_conversations($user1->id));
995         // Get a bunch of conversations, some group, some individual and in different states.
996         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
997             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
999         // Get all conversations for user1.
1000         $conversations = core_message\api::get_conversations($user1->id);
1002         // Verify there are 2 individual conversation, 2 group conversations, and 2 empty group conversations.
1003         // The conversations with the most recent messages should be listed first, followed by the empty
1004         // conversations, with the most recently created first.
1005         $this->assertCount(6, $conversations);
1006         $typecounts  = array_count_values(array_column($conversations, 'type'));
1007         $this->assertEquals(2, $typecounts[1]);
1008         $this->assertEquals(4, $typecounts[2]);
1010         // Those conversations having messages should be listed first, ordered by most recent message time.
1011         $this->assertEquals($gc3->id, $conversations[0]->id);
1012         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $conversations[0]->type);
1013         $this->assertFalse($conversations[0]->isfavourite);
1014         $this->assertCount(1, $conversations[0]->members);
1015         $this->assertEquals(4, $conversations[0]->membercount);
1016         $this->assertCount(1, $conversations[0]->messages);
1017         $message = $DB->get_record('messages', ['id' => $conversations[0]->messages[0]->id]);
1018         $expectedmessagetext = message_format_message_text($message);
1019         $this->assertEquals($expectedmessagetext, $conversations[0]->messages[0]->text);
1020         $this->assertEquals($user1->id, $conversations[0]->messages[0]->useridfrom);
1022         $this->assertEquals($gc2->id, $conversations[1]->id);
1023         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $conversations[1]->type);
1024         $this->assertFalse($conversations[1]->isfavourite);
1025         $this->assertCount(1, $conversations[1]->members);
1026         $this->assertEquals(3, $conversations[1]->membercount);
1027         $this->assertCount(1, $conversations[1]->messages);
1028         $message = $DB->get_record('messages', ['id' => $conversations[1]->messages[0]->id]);
1029         $expectedmessagetext = message_format_message_text($message);
1030         $this->assertEquals($expectedmessagetext, $conversations[1]->messages[0]->text);
1031         $this->assertEquals($user4->id, $conversations[1]->messages[0]->useridfrom);
1033         $this->assertEquals($ic2->id, $conversations[2]->id);
1034         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $conversations[2]->type);
1035         $this->assertFalse($conversations[2]->isfavourite);
1036         $this->assertCount(1, $conversations[2]->members);
1037         $this->assertEquals($user3->id, $conversations[2]->members[$user3->id]->id);
1038         $this->assertEquals(2, $conversations[2]->membercount);
1039         $this->assertCount(1, $conversations[2]->messages);
1040         $message = $DB->get_record('messages', ['id' => $conversations[2]->messages[0]->id]);
1041         $expectedmessagetext = message_format_message_text($message);
1042         $this->assertEquals($expectedmessagetext, $conversations[2]->messages[0]->text);
1043         $this->assertEquals($user1->id, $conversations[2]->messages[0]->useridfrom);
1045         $this->assertEquals($ic1->id, $conversations[3]->id);
1046         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $conversations[3]->type);
1047         $this->assertFalse($conversations[3]->isfavourite);
1048         $this->assertCount(1, $conversations[3]->members);
1049         $this->assertEquals(2, $conversations[3]->membercount);
1050         $this->assertCount(1, $conversations[3]->messages);
1051         $message = $DB->get_record('messages', ['id' => $conversations[3]->messages[0]->id]);
1052         $expectedmessagetext = message_format_message_text($message);
1053         $this->assertEquals($expectedmessagetext, $conversations[3]->messages[0]->text);
1054         $this->assertEquals($user2->id, $conversations[3]->messages[0]->useridfrom);
1056         // Of the groups without messages, we expect to see the most recently created first.
1057         $this->assertEquals($gc5->id, $conversations[4]->id);
1058         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $conversations[4]->type);
1059         $this->assertFalse($conversations[4]->isfavourite);
1060         $this->assertCount(0, $conversations[4]->members); // No members returned, because no recent messages exist.
1061         $this->assertEquals(3, $conversations[4]->membercount);
1062         $this->assertEmpty($conversations[4]->messages);
1064         $this->assertEquals($gc4->id, $conversations[5]->id);
1065         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $conversations[5]->type);
1066         $this->assertFalse($conversations[5]->isfavourite);
1067         $this->assertCount(0, $conversations[5]->members);
1068         $this->assertEquals(3, $conversations[5]->membercount);
1069         $this->assertEmpty($conversations[5]->messages);
1071         // Verify format of the return structure.
1072         foreach ($conversations as $conv) {
1073             $this->assertObjectHasAttribute('id', $conv);
1074             $this->assertObjectHasAttribute('name', $conv);
1075             $this->assertObjectHasAttribute('subname', $conv);
1076             $this->assertObjectHasAttribute('imageurl', $conv);
1077             $this->assertObjectHasAttribute('type', $conv);
1078             $this->assertObjectHasAttribute('isfavourite', $conv);
1079             $this->assertObjectHasAttribute('membercount', $conv);
1080             $this->assertObjectHasAttribute('isread', $conv);
1081             $this->assertObjectHasAttribute('unreadcount', $conv);
1082             $this->assertObjectHasAttribute('members', $conv);
1083             foreach ($conv->members as $member) {
1084                 $this->assertObjectHasAttribute('id', $member);
1085                 $this->assertObjectHasAttribute('fullname', $member);
1086                 $this->assertObjectHasAttribute('profileimageurl', $member);
1087                 $this->assertObjectHasAttribute('profileimageurlsmall', $member);
1088                 $this->assertObjectHasAttribute('isonline', $member);
1089                 $this->assertObjectHasAttribute('showonlinestatus', $member);
1090                 $this->assertObjectHasAttribute('isblocked', $member);
1091                 $this->assertObjectHasAttribute('iscontact', $member);
1092                 $this->assertObjectHasAttribute('isdeleted', $member);
1093                 $this->assertObjectHasAttribute('canmessage', $member);
1094                 $this->assertObjectHasAttribute('requirescontact', $member);
1095                 $this->assertObjectHasAttribute('contactrequests', $member);
1096             }
1097             $this->assertObjectHasAttribute('messages', $conv);
1098             foreach ($conv->messages as $message) {
1099                 $this->assertObjectHasAttribute('id', $message);
1100                 $this->assertObjectHasAttribute('useridfrom', $message);
1101                 $this->assertObjectHasAttribute('text', $message);
1102                 $this->assertObjectHasAttribute('timecreated', $message);
1103             }
1104         }
1105     }
1107     /**
1108      * Test verifying that html format messages are supported, and that message_format_message_text() is being called appropriately.
1109      */
1110     public function test_get_conversations_message_format() {
1111         global $DB;
1112         // Create some users.
1113         $user1 = self::getDataGenerator()->create_user();
1114         $user2 = self::getDataGenerator()->create_user();
1116         // Create conversation.
1117         $conversation = \core_message\api::create_conversation(
1118             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1119             [$user1->id, $user2->id]
1120         );
1122         // Send some messages back and forth.
1123         $time = 1;
1124         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 1);
1125         $mid = testhelper::send_fake_message_to_conversation($user1, $conversation->id, '<a href="#">A link</a>', $time + 2);
1127         // Verify the format of the html message.
1128         $message = $DB->get_record('messages', ['id' => $mid]);
1129         $expectedmessagetext = message_format_message_text($message);
1130         $conversations = \core_message\api::get_conversations($user1->id);
1131         $messages = $conversations[0]->messages;
1132         $this->assertEquals($expectedmessagetext, $messages[0]->text);
1133     }
1135     /**
1136      * Tests retrieving conversations with a limit and offset to ensure pagination works correctly.
1137      */
1138     public function test_get_conversations_limit_offset() {
1139         // Get a bunch of conversations, some group, some individual and in different states.
1140         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1141             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1143         // Get all conversations for user1, limited to 1 result.
1144         $conversations = core_message\api::get_conversations($user1->id, 0, 1);
1146         // Verify the first conversation.
1147         $this->assertCount(1, $conversations);
1148         $conversation = array_shift($conversations);
1149         $this->assertEquals($conversation->id, $gc3->id);
1151         // Verify the next conversation.
1152         $conversations = \core_message\api::get_conversations($user1->id, 1, 1);
1153         $this->assertCount(1, $conversations);
1154         $this->assertEquals($gc2->id, $conversations[0]->id);
1156         // Verify the next conversation.
1157         $conversations = \core_message\api::get_conversations($user1->id, 2, 1);
1158         $this->assertCount(1, $conversations);
1159         $this->assertEquals($ic2->id, $conversations[0]->id);
1161         // Skip one and get both empty conversations.
1162         $conversations = \core_message\api::get_conversations($user1->id, 4, 2);
1163         $this->assertCount(2, $conversations);
1164         $this->assertEquals($gc5->id, $conversations[0]->id);
1165         $this->assertEmpty($conversations[0]->messages);
1166         $this->assertEquals($gc4->id, $conversations[1]->id);
1167         $this->assertEmpty($conversations[1]->messages);
1169         // Ask for an offset that doesn't exist and verify no conversations are returned.
1170         $conversations = \core_message\api::get_conversations($user1->id, 10, 1);
1171         $this->assertCount(0, $conversations);
1172     }
1174     /**
1175      * Test verifying the type filtering behaviour of the
1176      */
1177     public function test_get_conversations_type_filter() {
1178         // Get a bunch of conversations, some group, some individual and in different states.
1179         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1180             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1182         // Verify we can ask for only individual conversations.
1183         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
1184             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL);
1185         $this->assertCount(2, $conversations);
1187         // Verify we can ask for only group conversations.
1188         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
1189             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP);
1190         $this->assertCount(4, $conversations);
1192         // Verify an exception is thrown if an unrecognized type is specified.
1193         $this->expectException(\moodle_exception::class);
1194         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, 0);
1195     }
1197     /**
1198      * Tests retrieving conversations when a conversation contains a deleted user.
1199      */
1200     public function test_get_conversations_with_deleted_user() {
1201         // Get a bunch of conversations, some group, some individual and in different states.
1202         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1203             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1205         // Delete the second user and retrieve the conversations.
1206         // We should have 5, as $ic1 drops off the list.
1207         // Group conversations remain albeit with less members.
1208         delete_user($user2);
1209         $conversations = \core_message\api::get_conversations($user1->id);
1210         $this->assertCount(5, $conversations);
1211         $this->assertEquals($gc3->id, $conversations[0]->id);
1212         $this->assertcount(1, $conversations[0]->members);
1213         $this->assertEquals($gc2->id, $conversations[1]->id);
1214         $this->assertcount(1, $conversations[1]->members);
1215         $this->assertEquals($ic2->id, $conversations[2]->id);
1216         $this->assertEquals($gc5->id, $conversations[3]->id);
1217         $this->assertEquals($gc4->id, $conversations[4]->id);
1219         // Delete a user from a group conversation where that user had sent the most recent message.
1220         // This user will still be present in the members array, as will the message in the messages array.
1221         delete_user($user4);
1222         $conversations = \core_message\api::get_conversations($user1->id);
1223         $this->assertCount(5, $conversations);
1224         $this->assertEquals($gc2->id, $conversations[1]->id);
1225         $this->assertcount(1, $conversations[1]->members);
1226         $this->assertEquals($user4->id, $conversations[1]->members[$user4->id]->id);
1227         $this->assertcount(1, $conversations[1]->messages);
1228         $this->assertEquals($user4->id, $conversations[1]->messages[0]->useridfrom);
1230         // Delete the third user and retrieve the conversations.
1231         // We should have 4, as $ic1, $ic2 drop off the list.
1232         // Group conversations remain albeit with less members.
1233         delete_user($user3);
1234         $conversations = \core_message\api::get_conversations($user1->id);
1235         $this->assertCount(4, $conversations);
1236         $this->assertEquals($gc3->id, $conversations[0]->id);
1237         $this->assertcount(1, $conversations[0]->members);
1238         $this->assertEquals($gc2->id, $conversations[1]->id);
1239         $this->assertcount(1, $conversations[1]->members);
1240         $this->assertEquals($gc5->id, $conversations[2]->id);
1241         $this->assertEquals($gc4->id, $conversations[3]->id);
1242     }
1244     /**
1245      * Test confirming the behaviour of get_conversations() when users delete all messages.
1246      */
1247     public function test_get_conversations_deleted_messages() {
1248         // Get a bunch of conversations, some group, some individual and in different states.
1249         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1250             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1252         $conversations = \core_message\api::get_conversations($user1->id);
1253         $this->assertCount(6, $conversations);
1255         // Delete all messages from a group conversation the user is in - it should be returned.
1256         $this->assertTrue(\core_message\api::is_user_in_conversation($user1->id, $gc2->id));
1257         $convmessages = \core_message\api::get_conversation_messages($user1->id, $gc2->id);
1258         $messages = $convmessages['messages'];
1259         foreach ($messages as $message) {
1260             \core_message\api::delete_message($user1->id, $message->id);
1261         }
1262         $conversations = \core_message\api::get_conversations($user1->id);
1263         $this->assertCount(6, $conversations);
1264         $this->assertContains($gc2->id, array_column($conversations, 'id'));
1266         // Delete all messages from an individual conversation the user is in - it should not be returned.
1267         $this->assertTrue(\core_message\api::is_user_in_conversation($user1->id, $ic1->id));
1268         $convmessages = \core_message\api::get_conversation_messages($user1->id, $ic1->id);
1269         $messages = $convmessages['messages'];
1270         foreach ($messages as $message) {
1271             \core_message\api::delete_message($user1->id, $message->id);
1272         }
1273         $conversations = \core_message\api::get_conversations($user1->id);
1274         $this->assertCount(5, $conversations);
1275         $this->assertNotContains($ic1->id, array_column($conversations, 'id'));
1276     }
1278     /**
1279      * Test verifying the behaviour of get_conversations() when fetching favourite conversations.
1280      */
1281     public function test_get_conversations_favourite_conversations() {
1282         // Get a bunch of conversations, some group, some individual and in different states.
1283         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1284             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1286         // Try to get ONLY favourite conversations, when no favourites exist.
1287         $this->assertEquals([], \core_message\api::get_conversations($user1->id, 0, 20, null, true));
1289         // Try to get NO favourite conversations, when no favourites exist.
1290         $this->assertCount(6, \core_message\api::get_conversations($user1->id, 0, 20, null, false));
1292         // Mark a few conversations as favourites.
1293         \core_message\api::set_favourite_conversation($ic1->id, $user1->id);
1294         \core_message\api::set_favourite_conversation($gc2->id, $user1->id);
1295         \core_message\api::set_favourite_conversation($gc5->id, $user1->id);
1297         // Get the conversations, first with no restrictions, confirming the favourite status of the conversations.
1298         $conversations = \core_message\api::get_conversations($user1->id);
1299         $this->assertCount(6, $conversations);
1300         foreach ($conversations as $conv) {
1301             if (in_array($conv->id, [$ic1->id, $gc2->id, $gc5->id])) {
1302                 $this->assertTrue($conv->isfavourite);
1303             }
1304         }
1306         // Now, get ONLY favourite conversations.
1307         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, true);
1308         $this->assertCount(3, $conversations);
1309         foreach ($conversations as $conv) {
1310             $this->assertTrue($conv->isfavourite);
1311         }
1313         // Now, try ONLY favourites of type 'group'.
1314         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
1315             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, true);
1316         $this->assertCount(2, $conversations);
1317         foreach ($conversations as $conv) {
1318             $this->assertTrue($conv->isfavourite);
1319         }
1321         // And NO favourite conversations.
1322         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, false);
1323         $this->assertCount(3, $conversations);
1324         foreach ($conversations as $conv) {
1325             $this->assertFalse($conv->isfavourite);
1326         }
1327     }
1329     /**
1330      * Test verifying get_conversations when there are users in a group and/or individual conversation. The reason this
1331      * test is performed is because we do not need as much data for group conversations (saving DB calls), so we want
1332      * to confirm this happens.
1333      */
1334     public function test_get_conversations_user_in_group_and_individual_chat() {
1335         $this->resetAfterTest();
1337         $user1 = self::getDataGenerator()->create_user();
1338         $user2 = self::getDataGenerator()->create_user();
1339         $user3 = self::getDataGenerator()->create_user();
1341         $conversation = \core_message\api::create_conversation(
1342             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1343             [
1344                 $user1->id,
1345                 $user2->id
1346             ],
1347             'Individual conversation'
1348         );
1350         testhelper::send_fake_message_to_conversation($user1, $conversation->id);
1352         $conversation = \core_message\api::create_conversation(
1353             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1354             [
1355                 $user1->id,
1356                 $user2->id,
1357             ],
1358             'Group conversation'
1359         );
1361         testhelper::send_fake_message_to_conversation($user1, $conversation->id);
1363         \core_message\api::create_contact_request($user1->id, $user2->id);
1364         \core_message\api::create_contact_request($user1->id, $user3->id);
1366         $conversations = \core_message\api::get_conversations($user2->id);
1368         $groupconversation = array_shift($conversations);
1369         $individualconversation = array_shift($conversations);
1371         $this->assertEquals('Group conversation', $groupconversation->name);
1372         $this->assertEquals('Individual conversation', $individualconversation->name);
1374         $this->assertCount(1, $groupconversation->members);
1375         $this->assertCount(1, $individualconversation->members);
1377         $groupmember = reset($groupconversation->members);
1378         $this->assertNull($groupmember->requirescontact);
1379         $this->assertNull($groupmember->canmessage);
1380         $this->assertEmpty($groupmember->contactrequests);
1382         $individualmember = reset($individualconversation->members);
1383         $this->assertNotNull($individualmember->requirescontact);
1384         $this->assertNotNull($individualmember->canmessage);
1385         $this->assertNotEmpty($individualmember->contactrequests);
1386     }
1388     /**
1389      * Test verifying that group linked conversations are returned and contain a subname matching the course name.
1390      */
1391     public function test_get_conversations_group_linked() {
1392         global $CFG;
1394         // Create some users.
1395         $user1 = self::getDataGenerator()->create_user();
1396         $user2 = self::getDataGenerator()->create_user();
1397         $user3 = self::getDataGenerator()->create_user();
1399         $course1 = $this->getDataGenerator()->create_course();
1401         // Create a group with a linked conversation and a valid image.
1402         $this->setAdminUser();
1403         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1404         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1405         $this->getDataGenerator()->enrol_user($user3->id, $course1->id);
1406         $group1 = $this->getDataGenerator()->create_group([
1407             'courseid' => $course1->id,
1408             'enablemessaging' => 1,
1409             'picturepath' => $CFG->dirroot . '/lib/tests/fixtures/gd-logo.png'
1410         ]);
1412         // Add users to group1.
1413         $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user1->id));
1414         $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user2->id));
1416         // Verify the group with the image works as expected.
1417         $conversations = \core_message\api::get_conversations($user1->id);
1418         $this->assertEquals(2, $conversations[0]->membercount);
1419         $this->assertEquals($course1->shortname, $conversations[0]->subname);
1420         $groupimageurl = get_group_picture_url($group1, $group1->courseid, true);
1421         $this->assertEquals($groupimageurl, $conversations[0]->imageurl);
1423         // Create a group with a linked conversation and without any image.
1424         $group2 = $this->getDataGenerator()->create_group([
1425             'courseid' => $course1->id,
1426             'enablemessaging' => 1,
1427         ]);
1429         // Add users to group2.
1430         $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $user2->id));
1431         $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $user3->id));
1433         // Verify the group without any image works as expected too.
1434         $conversations = \core_message\api::get_conversations($user3->id);
1435         $this->assertEquals(2, $conversations[0]->membercount);
1436         $this->assertEquals($course1->shortname, $conversations[0]->subname);
1437         $groupimageurl = get_group_picture_url($group2, $group2->courseid, true);
1438         $this->assertEquals($groupimageurl, $conversations[0]->imageurl);
1439     }
1441    /**
1442     * The data provider for get_conversations_mixed.
1443     *
1444     * This provides sets of data to for testing.
1445     * @return array
1446     */
1447    public function get_conversations_mixed_provider() {
1448        return array(
1449             'Test that conversations with messages contacts is correctly ordered.' => array(
1450                 'users' => array(
1451                     'user1',
1452                     'user2',
1453                     'user3',
1454                 ),
1455                 'contacts' => array(
1456                 ),
1457                 'messages' => array(
1458                     array(
1459                         'from'          => 'user1',
1460                         'to'            => 'user2',
1461                         'state'         => 'unread',
1462                         'subject'       => 'S1',
1463                     ),
1464                     array(
1465                         'from'          => 'user2',
1466                         'to'            => 'user1',
1467                         'state'         => 'unread',
1468                         'subject'       => 'S2',
1469                     ),
1470                     array(
1471                         'from'          => 'user1',
1472                         'to'            => 'user2',
1473                         'state'         => 'unread',
1474                         'timecreated'   => 0,
1475                         'subject'       => 'S3',
1476                     ),
1477                     array(
1478                         'from'          => 'user1',
1479                         'to'            => 'user3',
1480                         'state'         => 'read',
1481                         'timemodifier'  => 1,
1482                         'subject'       => 'S4',
1483                     ),
1484                     array(
1485                         'from'          => 'user3',
1486                         'to'            => 'user1',
1487                         'state'         => 'read',
1488                         'timemodifier'  => 1,
1489                         'subject'       => 'S5',
1490                     ),
1491                     array(
1492                         'from'          => 'user1',
1493                         'to'            => 'user3',
1494                         'state'         => 'read',
1495                         'timecreated'   => 0,
1496                         'subject'       => 'S6',
1497                     ),
1498                 ),
1499                 'expectations' => array(
1500                     'user1' => array(
1501                         // User1 has conversed most recently with user3. The most recent message is M5.
1502                         array(
1503                             'messageposition'   => 0,
1504                             'with'              => 'user3',
1505                             'subject'           => '<p>S5</p>',
1506                             'unreadcount'       => 0,
1507                         ),
1508                         // User1 has also conversed with user2. The most recent message is S2.
1509                         array(
1510                             'messageposition'   => 1,
1511                             'with'              => 'user2',
1512                             'subject'           => '<p>S2</p>',
1513                             'unreadcount'       => 1,
1514                         ),
1515                     ),
1516                     'user2' => array(
1517                         // User2 has only conversed with user1. Their most recent shared message was S2.
1518                         array(
1519                             'messageposition'   => 0,
1520                             'with'              => 'user1',
1521                             'subject'           => '<p>S2</p>',
1522                             'unreadcount'       => 2,
1523                         ),
1524                     ),
1525                     'user3' => array(
1526                         // User3 has only conversed with user1. Their most recent shared message was S5.
1527                         array(
1528                             'messageposition'   => 0,
1529                             'with'              => 'user1',
1530                             'subject'           => '<p>S5</p>',
1531                             'unreadcount'       => 0,
1532                         ),
1533                     ),
1534                 ),
1535             ),
1536             'Test conversations with a single user, where some messages are read and some are not.' => array(
1537                 'users' => array(
1538                     'user1',
1539                     'user2',
1540                 ),
1541                 'contacts' => array(
1542                 ),
1543                 'messages' => array(
1544                     array(
1545                         'from'          => 'user1',
1546                         'to'            => 'user2',
1547                         'state'         => 'read',
1548                         'subject'       => 'S1',
1549                     ),
1550                     array(
1551                         'from'          => 'user2',
1552                         'to'            => 'user1',
1553                         'state'         => 'read',
1554                         'subject'       => 'S2',
1555                     ),
1556                     array(
1557                         'from'          => 'user1',
1558                         'to'            => 'user2',
1559                         'state'         => 'unread',
1560                         'timemodifier'  => 1,
1561                         'subject'       => 'S3',
1562                     ),
1563                     array(
1564                         'from'          => 'user1',
1565                         'to'            => 'user2',
1566                         'state'         => 'unread',
1567                         'timemodifier'  => 1,
1568                         'subject'       => 'S4',
1569                     ),
1570                 ),
1571                 'expectations' => array(
1572                     // The most recent message between user1 and user2 was S4.
1573                     'user1' => array(
1574                         array(
1575                             'messageposition'   => 0,
1576                             'with'              => 'user2',
1577                             'subject'           => '<p>S4</p>',
1578                             'unreadcount'       => 0,
1579                         ),
1580                     ),
1581                     'user2' => array(
1582                         // The most recent message between user1 and user2 was S4.
1583                         array(
1584                             'messageposition'   => 0,
1585                             'with'              => 'user1',
1586                             'subject'           => '<p>S4</p>',
1587                             'unreadcount'       => 2,
1588                         ),
1589                     ),
1590                 ),
1591             ),
1592             'Test conversations with a single user, where some messages are read and some are not, and messages ' .
1593             'are out of order' => array(
1594             // This can happen through a combination of factors including multi-master DB replication with messages
1595             // read somehow (e.g. API).
1596                 'users' => array(
1597                     'user1',
1598                     'user2',
1599                 ),
1600                 'contacts' => array(
1601                 ),
1602                 'messages' => array(
1603                     array(
1604                         'from'          => 'user1',
1605                         'to'            => 'user2',
1606                         'state'         => 'read',
1607                         'subject'       => 'S1',
1608                         'timemodifier'  => 1,
1609                     ),
1610                     array(
1611                         'from'          => 'user2',
1612                         'to'            => 'user1',
1613                         'state'         => 'read',
1614                         'subject'       => 'S2',
1615                         'timemodifier'  => 2,
1616                     ),
1617                     array(
1618                         'from'          => 'user1',
1619                         'to'            => 'user2',
1620                         'state'         => 'unread',
1621                         'subject'       => 'S3',
1622                     ),
1623                     array(
1624                         'from'          => 'user1',
1625                         'to'            => 'user2',
1626                         'state'         => 'unread',
1627                         'subject'       => 'S4',
1628                     ),
1629                 ),
1630                 'expectations' => array(
1631                     // The most recent message between user1 and user2 was S2, even though later IDs have not been read.
1632                     'user1' => array(
1633                         array(
1634                             'messageposition'   => 0,
1635                             'with'              => 'user2',
1636                             'subject'           => '<p>S2</p>',
1637                             'unreadcount'       => 0,
1638                         ),
1639                     ),
1640                     'user2' => array(
1641                         array(
1642                             'messageposition'   => 0,
1643                             'with'              => 'user1',
1644                             'subject'           => '<p>S2</p>',
1645                             'unreadcount'       => 2
1646                         ),
1647                     ),
1648                 ),
1649             ),
1650             'Test unread message count is correct for both users' => array(
1651                 'users' => array(
1652                     'user1',
1653                     'user2',
1654                 ),
1655                 'contacts' => array(
1656                 ),
1657                 'messages' => array(
1658                     array(
1659                         'from'          => 'user1',
1660                         'to'            => 'user2',
1661                         'state'         => 'read',
1662                         'subject'       => 'S1',
1663                         'timemodifier'  => 1,
1664                     ),
1665                     array(
1666                         'from'          => 'user2',
1667                         'to'            => 'user1',
1668                         'state'         => 'read',
1669                         'subject'       => 'S2',
1670                         'timemodifier'  => 2,
1671                     ),
1672                     array(
1673                         'from'          => 'user1',
1674                         'to'            => 'user2',
1675                         'state'         => 'read',
1676                         'subject'       => 'S3',
1677                         'timemodifier'  => 3,
1678                     ),
1679                     array(
1680                         'from'          => 'user1',
1681                         'to'            => 'user2',
1682                         'state'         => 'read',
1683                         'subject'       => 'S4',
1684                         'timemodifier'  => 4,
1685                     ),
1686                     array(
1687                         'from'          => 'user1',
1688                         'to'            => 'user2',
1689                         'state'         => 'unread',
1690                         'subject'       => 'S5',
1691                         'timemodifier'  => 5,
1692                     ),
1693                     array(
1694                         'from'          => 'user2',
1695                         'to'            => 'user1',
1696                         'state'         => 'unread',
1697                         'subject'       => 'S6',
1698                         'timemodifier'  => 6,
1699                     ),
1700                     array(
1701                         'from'          => 'user1',
1702                         'to'            => 'user2',
1703                         'state'         => 'unread',
1704                         'subject'       => 'S7',
1705                         'timemodifier'  => 7,
1706                     ),
1707                     array(
1708                         'from'          => 'user1',
1709                         'to'            => 'user2',
1710                         'state'         => 'unread',
1711                         'subject'       => 'S8',
1712                         'timemodifier'  => 8,
1713                     ),
1714                 ),
1715                 'expectations' => array(
1716                     // The most recent message between user1 and user2 was S2, even though later IDs have not been read.
1717                     'user1' => array(
1718                         array(
1719                             'messageposition'   => 0,
1720                             'with'              => 'user2',
1721                             'subject'           => '<p>S8</p>',
1722                             'unreadcount'       => 1,
1723                         ),
1724                     ),
1725                     'user2' => array(
1726                         array(
1727                             'messageposition'   => 0,
1728                             'with'              => 'user1',
1729                             'subject'           => '<p>S8</p>',
1730                             'unreadcount'       => 3,
1731                         ),
1732                     ),
1733                 ),
1734             ),
1735         );
1736     }
1738     /**
1739      * Test get_conversations with a mixture of messages.
1740      *
1741      * @dataProvider get_conversations_mixed_provider
1742      * @param array $usersdata The list of users to create for this test.
1743      * @param array $messagesdata The list of messages to create.
1744      * @param array $expectations The list of expected outcomes.
1745      */
1746     public function test_get_conversations_mixed($usersdata, $contacts, $messagesdata, $expectations) {
1747         global $DB;
1749         // Create all of the users.
1750         $users = array();
1751         foreach ($usersdata as $username) {
1752             $users[$username] = $this->getDataGenerator()->create_user(array('username' => $username));
1753         }
1755         foreach ($contacts as $username => $contact) {
1756             foreach ($contact as $contactname => $blocked) {
1757                 $record = new stdClass();
1758                 $record->userid     = $users[$username]->id;
1759                 $record->contactid  = $users[$contactname]->id;
1760                 $record->blocked    = $blocked;
1761                 $record->id = $DB->insert_record('message_contacts', $record);
1762             }
1763         }
1765         $defaulttimecreated = time();
1766         foreach ($messagesdata as $messagedata) {
1767             $from       = $users[$messagedata['from']];
1768             $to         = $users[$messagedata['to']];
1769             $subject    = $messagedata['subject'];
1771             if (isset($messagedata['state']) && $messagedata['state'] == 'unread') {
1772                 $messageid = $this->send_fake_message($from, $to, $subject);
1773             } else {
1774                 // If there is no state, or the state is not 'unread', assume the message is read.
1775                 $messageid = message_post_message($from, $to, $subject, FORMAT_PLAIN);
1776             }
1778             $updatemessage = new stdClass();
1779             $updatemessage->id = $messageid;
1780             if (isset($messagedata['timecreated'])) {
1781                 $updatemessage->timecreated = $messagedata['timecreated'];
1782             } else if (isset($messagedata['timemodifier'])) {
1783                 $updatemessage->timecreated = $defaulttimecreated + $messagedata['timemodifier'];
1784             } else {
1785                 $updatemessage->timecreated = $defaulttimecreated;
1786             }
1788             $DB->update_record('messages', $updatemessage);
1789         }
1791         foreach ($expectations as $username => $data) {
1792             // Get the recent conversations for the specified user.
1793             $user = $users[$username];
1794             $conversations = array_values(\core_message\api::get_conversations($user->id));
1795             foreach ($data as $expectation) {
1796                 $otheruser = $users[$expectation['with']];
1797                 $conversation = $conversations[$expectation['messageposition']];
1798                 $this->assertEquals($otheruser->id, $conversation->members[$otheruser->id]->id);
1799                 $this->assertEquals($expectation['subject'], $conversation->messages[0]->text);
1800                 $this->assertEquals($expectation['unreadcount'], $conversation->unreadcount);
1801             }
1802         }
1803     }
1805     /**
1806      * Tests retrieving contacts.
1807      */
1808     public function test_get_contacts() {
1809         // Create some users.
1810         $user1 = self::getDataGenerator()->create_user();
1812         // Set as the user.
1813         $this->setUser($user1);
1815         $user2 = new stdClass();
1816         $user2->firstname = 'User';
1817         $user2->lastname = 'A';
1818         $user2 = self::getDataGenerator()->create_user($user2);
1820         $user3 = new stdClass();
1821         $user3->firstname = 'User';
1822         $user3->lastname = 'B';
1823         $user3 = self::getDataGenerator()->create_user($user3);
1825         $user4 = new stdClass();
1826         $user4->firstname = 'User';
1827         $user4->lastname = 'C';
1828         $user4 = self::getDataGenerator()->create_user($user4);
1830         $user5 = new stdClass();
1831         $user5->firstname = 'User';
1832         $user5->lastname = 'D';
1833         $user5 = self::getDataGenerator()->create_user($user5);
1835         // Add some users as contacts.
1836         \core_message\api::add_contact($user1->id, $user2->id);
1837         \core_message\api::add_contact($user1->id, $user3->id);
1838         \core_message\api::add_contact($user1->id, $user4->id);
1840         // Retrieve the contacts.
1841         $contacts = \core_message\api::get_contacts($user1->id);
1843         // Confirm the data is correct.
1844         $this->assertEquals(3, count($contacts));
1845         usort($contacts, ['static', 'sort_contacts']);
1847         $contact1 = $contacts[0];
1848         $contact2 = $contacts[1];
1849         $contact3 = $contacts[2];
1851         $this->assertEquals($user2->id, $contact1->userid);
1852         $this->assertEmpty($contact1->useridfrom);
1853         $this->assertFalse($contact1->ismessaging);
1854         $this->assertNull($contact1->lastmessage);
1855         $this->assertNull($contact1->messageid);
1856         $this->assertNull($contact1->isonline);
1857         $this->assertFalse($contact1->isread);
1858         $this->assertFalse($contact1->isblocked);
1859         $this->assertNull($contact1->unreadcount);
1861         $this->assertEquals($user3->id, $contact2->userid);
1862         $this->assertEmpty($contact2->useridfrom);
1863         $this->assertFalse($contact2->ismessaging);
1864         $this->assertNull($contact2->lastmessage);
1865         $this->assertNull($contact2->messageid);
1866         $this->assertNull($contact2->isonline);
1867         $this->assertFalse($contact2->isread);
1868         $this->assertFalse($contact2->isblocked);
1869         $this->assertNull($contact2->unreadcount);
1871         $this->assertEquals($user4->id, $contact3->userid);
1872         $this->assertEmpty($contact3->useridfrom);
1873         $this->assertFalse($contact3->ismessaging);
1874         $this->assertNull($contact3->lastmessage);
1875         $this->assertNull($contact3->messageid);
1876         $this->assertNull($contact3->isonline);
1877         $this->assertFalse($contact3->isread);
1878         $this->assertFalse($contact3->isblocked);
1879         $this->assertNull($contact3->unreadcount);
1880     }
1882     /**
1883      * Tests retrieving messages.
1884      */
1885     public function test_get_messages() {
1886         // Create some users.
1887         $user1 = self::getDataGenerator()->create_user();
1888         $user2 = self::getDataGenerator()->create_user();
1890         // The person doing the search.
1891         $this->setUser($user1);
1893         // Send some messages back and forth.
1894         $time = 1;
1895         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
1896         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
1897         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
1898         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
1900         // Retrieve the messages.
1901         $messages = \core_message\api::get_messages($user1->id, $user2->id);
1903         // Confirm the message data is correct.
1904         $this->assertEquals(4, count($messages));
1906         $message1 = $messages[0];
1907         $message2 = $messages[1];
1908         $message3 = $messages[2];
1909         $message4 = $messages[3];
1911         $this->assertEquals($user1->id, $message1->useridfrom);
1912         $this->assertEquals($user2->id, $message1->useridto);
1913         $this->assertTrue($message1->displayblocktime);
1914         $this->assertContains('Yo!', $message1->text);
1916         $this->assertEquals($user2->id, $message2->useridfrom);
1917         $this->assertEquals($user1->id, $message2->useridto);
1918         $this->assertFalse($message2->displayblocktime);
1919         $this->assertContains('Sup mang?', $message2->text);
1921         $this->assertEquals($user1->id, $message3->useridfrom);
1922         $this->assertEquals($user2->id, $message3->useridto);
1923         $this->assertFalse($message3->displayblocktime);
1924         $this->assertContains('Writing PHPUnit tests!', $message3->text);
1926         $this->assertEquals($user2->id, $message4->useridfrom);
1927         $this->assertEquals($user1->id, $message4->useridto);
1928         $this->assertFalse($message4->displayblocktime);
1929         $this->assertContains('Word.', $message4->text);
1930     }
1932     /**
1933      * Tests retrieving conversation messages.
1934      */
1935     public function test_get_conversation_messages() {
1936         // Create some users.
1937         $user1 = self::getDataGenerator()->create_user();
1938         $user2 = self::getDataGenerator()->create_user();
1940         // Create conversation.
1941         $conversation = \core_message\api::create_conversation(
1942             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1943             [$user1->id, $user2->id]
1944         );
1946         // The person doing the search.
1947         $this->setUser($user1);
1949         // Send some messages back and forth.
1950         $time = 1;
1951         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
1952         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
1953         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
1954         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 4);
1956         // Retrieve the messages.
1957         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id);
1959         // Confirm the conversation id is correct.
1960         $this->assertEquals($conversation->id, $convmessages['id']);
1962         // Confirm the message data is correct.
1963         $messages = $convmessages['messages'];
1964         $this->assertEquals(4, count($messages));
1965         $message1 = $messages[0];
1966         $message2 = $messages[1];
1967         $message3 = $messages[2];
1968         $message4 = $messages[3];
1970         $this->assertEquals($user1->id, $message1->useridfrom);
1971         $this->assertContains('Yo!', $message1->text);
1973         $this->assertEquals($user2->id, $message2->useridfrom);
1974         $this->assertContains('Sup mang?', $message2->text);
1976         $this->assertEquals($user1->id, $message3->useridfrom);
1977         $this->assertContains('Writing PHPUnit tests!', $message3->text);
1979         $this->assertEquals($user1->id, $message4->useridfrom);
1980         $this->assertContains('Word.', $message4->text);
1982         // Confirm the members data is correct.
1983         $members = $convmessages['members'];
1984         $this->assertEquals(2, count($members));
1985     }
1987     /**
1988      * Tests retrieving group conversation messages.
1989      */
1990     public function test_get_group_conversation_messages() {
1991         // Create some users.
1992         $user1 = self::getDataGenerator()->create_user();
1993         $user2 = self::getDataGenerator()->create_user();
1994         $user3 = self::getDataGenerator()->create_user();
1995         $user4 = self::getDataGenerator()->create_user();
1997         // Create group conversation.
1998         $conversation = \core_message\api::create_conversation(
1999             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2000             [$user1->id, $user2->id, $user3->id, $user4->id]
2001         );
2003         // The person doing the search.
2004         $this->setUser($user1);
2006         // Send some messages back and forth.
2007         $time = 1;
2008         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
2009         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
2010         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
2011         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 4);
2012         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Yeah!', $time + 5);
2014         // Retrieve the messages.
2015         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id);
2017         // Confirm the conversation id is correct.
2018         $this->assertEquals($conversation->id, $convmessages['id']);
2020         // Confirm the message data is correct.
2021         $messages = $convmessages['messages'];
2022         $this->assertEquals(5, count($messages));
2024         $message1 = $messages[0];
2025         $message2 = $messages[1];
2026         $message3 = $messages[2];
2027         $message4 = $messages[3];
2028         $message5 = $messages[4];
2030         $this->assertEquals($user1->id, $message1->useridfrom);
2031         $this->assertContains('Yo!', $message1->text);
2033         $this->assertEquals($user2->id, $message2->useridfrom);
2034         $this->assertContains('Sup mang?', $message2->text);
2036         $this->assertEquals($user3->id, $message3->useridfrom);
2037         $this->assertContains('Writing PHPUnit tests!', $message3->text);
2039         $this->assertEquals($user1->id, $message4->useridfrom);
2040         $this->assertContains('Word.', $message4->text);
2042         $this->assertEquals($user2->id, $message5->useridfrom);
2043         $this->assertContains('Yeah!', $message5->text);
2045         // Confirm the members data is correct.
2046         $members = $convmessages['members'];
2047         $this->assertEquals(3, count($members));
2048     }
2050     /**
2051      * Test verifying the sorting param for get_conversation_messages is respected().
2052      */
2053     public function test_get_conversation_messages_sorting() {
2054         // Create some users.
2055         $user1 = self::getDataGenerator()->create_user();
2056         $user2 = self::getDataGenerator()->create_user();
2057         $user3 = self::getDataGenerator()->create_user();
2059         // Create conversations - 1 group and 1 individual.
2060         $conversation = \core_message\api::create_conversation(
2061             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2062             [$user1->id, $user2->id]
2063         );
2064         $conversation2 = \core_message\api::create_conversation(
2065             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2066             [$user1->id, $user2->id, $user3->id]
2067         );
2069         // Send some messages back and forth.
2070         $time = 1;
2071         $m1id = testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
2072         $m2id = testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
2073         $m3id = testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
2074         $m4id = testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 4);
2076         $gm1id = testhelper::send_fake_message_to_conversation($user1, $conversation2->id, 'Yo!', $time + 1);
2077         $gm2id = testhelper::send_fake_message_to_conversation($user2, $conversation2->id, 'Sup mang?', $time + 2);
2078         $gm3id = testhelper::send_fake_message_to_conversation($user3, $conversation2->id, 'Writing PHPUnit tests!', $time + 3);
2079         $gm4id = testhelper::send_fake_message_to_conversation($user1, $conversation2->id, 'Word.', $time + 4);
2081         // The person doing the search.
2082         $this->setUser($user1);
2084         // Retrieve the messages using default sort ('timecreated ASC') and verify ordering.
2085         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id);
2086         $messages = $convmessages['messages'];
2087         $this->assertEquals($m1id, $messages[0]->id);
2088         $this->assertEquals($m2id, $messages[1]->id);
2089         $this->assertEquals($m3id, $messages[2]->id);
2090         $this->assertEquals($m4id, $messages[3]->id);
2092         // Retrieve the messages without specifying DESC sort ordering, and verify ordering.
2093         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated DESC');
2094         $messages = $convmessages['messages'];
2095         $this->assertEquals($m1id, $messages[3]->id);
2096         $this->assertEquals($m2id, $messages[2]->id);
2097         $this->assertEquals($m3id, $messages[1]->id);
2098         $this->assertEquals($m4id, $messages[0]->id);
2100         // Retrieve the messages using default sort ('timecreated ASC') and verify ordering.
2101         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation2->id);
2102         $messages = $convmessages['messages'];
2103         $this->assertEquals($gm1id, $messages[0]->id);
2104         $this->assertEquals($gm2id, $messages[1]->id);
2105         $this->assertEquals($gm3id, $messages[2]->id);
2106         $this->assertEquals($gm4id, $messages[3]->id);
2108         // Retrieve the messages without specifying DESC sort ordering, and verify ordering.
2109         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation2->id, 0, 0, 'timecreated DESC');
2110         $messages = $convmessages['messages'];
2111         $this->assertEquals($gm1id, $messages[3]->id);
2112         $this->assertEquals($gm2id, $messages[2]->id);
2113         $this->assertEquals($gm3id, $messages[1]->id);
2114         $this->assertEquals($gm4id, $messages[0]->id);
2115     }
2117     /**
2118      * Test retrieving conversation messages by providing a minimum timecreated value.
2119      */
2120     public function test_get_conversation_messages_time_from_only() {
2121         // Create some users.
2122         $user1 = self::getDataGenerator()->create_user();
2123         $user2 = self::getDataGenerator()->create_user();
2124         $user3 = self::getDataGenerator()->create_user();
2125         $user4 = self::getDataGenerator()->create_user();
2127         // Create group conversation.
2128         $conversation = \core_message\api::create_conversation(
2129             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2130             [$user1->id, $user2->id, $user3->id, $user4->id]
2131         );
2133         // The person doing the search.
2134         $this->setUser($user1);
2136         // Send some messages back and forth.
2137         $time = 1;
2138         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2139         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2140         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2141         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2143         // Retrieve the messages from $time, which should be all of them.
2144         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated ASC', $time);
2146         // Confirm the conversation id is correct.
2147         $this->assertEquals($conversation->id, $convmessages['id']);
2149         // Confirm the message data is correct.
2150         $messages = $convmessages['messages'];
2151         $this->assertEquals(4, count($messages));
2153         $message1 = $messages[0];
2154         $message2 = $messages[1];
2155         $message3 = $messages[2];
2156         $message4 = $messages[3];
2158         $this->assertContains('Message 1', $message1->text);
2159         $this->assertContains('Message 2', $message2->text);
2160         $this->assertContains('Message 3', $message3->text);
2161         $this->assertContains('Message 4', $message4->text);
2163         // Confirm the members data is correct.
2164         $members = $convmessages['members'];
2165         $this->assertEquals(3, count($members));
2167         // Retrieve the messages from $time + 3, which should only be the 2 last messages.
2168         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0,
2169             'timecreated ASC', $time + 3);
2171         // Confirm the conversation id is correct.
2172         $this->assertEquals($conversation->id, $convmessages['id']);
2174         // Confirm the message data is correct.
2175         $messages = $convmessages['messages'];
2176         $this->assertEquals(2, count($messages));
2178         $message1 = $messages[0];
2179         $message2 = $messages[1];
2181         $this->assertContains('Message 3', $message1->text);
2182         $this->assertContains('Message 4', $message2->text);
2184         // Confirm the members data is correct.
2185         $members = $convmessages['members'];
2186         $this->assertEquals(2, count($members));
2187     }
2189     /**
2190      * Test retrieving conversation messages by providing a maximum timecreated value.
2191      */
2192     public function test_get_conversation_messages_time_to_only() {
2193         // Create some users.
2194         $user1 = self::getDataGenerator()->create_user();
2195         $user2 = self::getDataGenerator()->create_user();
2196         $user3 = self::getDataGenerator()->create_user();
2197         $user4 = self::getDataGenerator()->create_user();
2199         // Create group conversation.
2200         $conversation = \core_message\api::create_conversation(
2201             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2202             [$user1->id, $user2->id, $user3->id, $user4->id]
2203         );
2205         // The person doing the search.
2206         $this->setUser($user1);
2208         // Send some messages back and forth.
2209         $time = 1;
2210         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2211         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2212         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2213         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2215         // Retrieve the messages up until $time + 4, which should be all of them.
2216         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated ASC',
2217             0, $time + 4);
2219         // Confirm the conversation id is correct.
2220         $this->assertEquals($conversation->id, $convmessages['id']);
2222         // Confirm the message data is correct.
2223         $messages = $convmessages['messages'];
2224         $this->assertEquals(4, count($messages));
2226         $message1 = $messages[0];
2227         $message2 = $messages[1];
2228         $message3 = $messages[2];
2229         $message4 = $messages[3];
2231         $this->assertContains('Message 1', $message1->text);
2232         $this->assertContains('Message 2', $message2->text);
2233         $this->assertContains('Message 3', $message3->text);
2234         $this->assertContains('Message 4', $message4->text);
2236         // Confirm the members data is correct.
2237         $members = $convmessages['members'];
2238         $this->assertEquals(3, count($members));
2240         // Retrieve the messages up until $time + 2, which should be the first two.
2241         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated ASC',
2242             0, $time + 2);
2244         // Confirm the conversation id is correct.
2245         $this->assertEquals($conversation->id, $convmessages['id']);
2247         // Confirm the message data is correct.
2248         $messages = $convmessages['messages'];
2249         $this->assertEquals(2, count($messages));
2251         $message1 = $messages[0];
2252         $message2 = $messages[1];
2254         $this->assertContains('Message 1', $message1->text);
2255         $this->assertContains('Message 2', $message2->text);
2257         // Confirm the members data is correct.
2258         $members = $convmessages['members'];
2259         $this->assertEquals(2, count($members));
2260     }
2262     /**
2263      * Test retrieving conversation messages by providing a minimum and maximum timecreated value.
2264      */
2265     public function test_get_conversation_messages_time_from_and_to() {
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         // Create group conversation.
2273         $conversation = \core_message\api::create_conversation(
2274             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2275             [$user1->id, $user2->id, $user3->id, $user4->id]
2276         );
2278         // The person doing the search.
2279         $this->setUser($user1);
2281         // Send some messages back and forth.
2282         $time = 1;
2283         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2284         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2285         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2286         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2288         // Retrieve the messages from $time + 2 up until $time + 3, which should be 2nd and 3rd message.
2289         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0,
2290             'timecreated ASC', $time + 2, $time + 3);
2292         // Confirm the conversation id is correct.
2293         $this->assertEquals($conversation->id, $convmessages['id']);
2295         // Confirm the message data is correct.
2296         $messages = $convmessages['messages'];
2297         $this->assertEquals(2, count($messages));
2299         $message1 = $messages[0];
2300         $message2 = $messages[1];
2302         $this->assertContains('Message 2', $message1->text);
2303         $this->assertContains('Message 3', $message2->text);
2305         // Confirm the members data is correct.
2306         $members = $convmessages['members'];
2307         $this->assertEquals(2, count($members));
2308     }
2311     /**
2312      * Test retrieving conversation messages by providing a limitfrom value.
2313      */
2314     public function test_get_conversation_messages_limitfrom_only() {
2315         // Create some users.
2316         $user1 = self::getDataGenerator()->create_user();
2317         $user2 = self::getDataGenerator()->create_user();
2318         $user3 = self::getDataGenerator()->create_user();
2319         $user4 = self::getDataGenerator()->create_user();
2321         // Create group conversation.
2322         $conversation = \core_message\api::create_conversation(
2323             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2324             [$user1->id, $user2->id, $user3->id, $user4->id]
2325         );
2327         // The person doing the search.
2328         $this->setUser($user1);
2330         // Send some messages back and forth.
2331         $time = 1;
2332         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2333         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2334         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2335         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2337         // Retrieve the messages from $time, which should be all of them.
2338         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 2);
2340         // Confirm the conversation id is correct.
2341         $messages = $convmessages['messages'];
2342         $this->assertEquals($conversation->id, $convmessages['id']);
2344         // Confirm the message data is correct.
2345         $this->assertEquals(2, count($messages));
2347         $message1 = $messages[0];
2348         $message2 = $messages[1];
2350         $this->assertContains('Message 3', $message1->text);
2351         $this->assertContains('Message 4', $message2->text);
2353         // Confirm the members data is correct.
2354         $members = $convmessages['members'];
2355         $this->assertEquals(2, count($members));
2356     }
2358     /**
2359      * Test retrieving conversation messages by providing a limitnum value.
2360      */
2361     public function test_get_conversation_messages_limitnum() {
2362         // Create some users.
2363         $user1 = self::getDataGenerator()->create_user();
2364         $user2 = self::getDataGenerator()->create_user();
2365         $user3 = self::getDataGenerator()->create_user();
2366         $user4 = self::getDataGenerator()->create_user();
2368         // Create group conversation.
2369         $conversation = \core_message\api::create_conversation(
2370             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2371             [$user1->id, $user2->id, $user3->id, $user4->id]
2372         );
2374         // The person doing the search.
2375         $this->setUser($user1);
2377         // Send some messages back and forth.
2378         $time = 1;
2379         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2380         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2381         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2382         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2384         // Retrieve the messages from $time, which should be all of them.
2385         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 2, 1);
2387         // Confirm the conversation id is correct.
2388         $messages = $convmessages['messages'];
2389         $this->assertEquals($conversation->id, $convmessages['id']);
2391         // Confirm the message data is correct.
2392         $messages = $convmessages['messages'];
2393         $this->assertEquals(1, count($messages));
2395         $message1 = $messages[0];
2397         $this->assertContains('Message 3', $message1->text);
2399         // Confirm the members data is correct.
2400         $members = $convmessages['members'];
2401         $this->assertEquals(1, count($members));
2402     }
2404     /**
2405      * Tests retrieving most recent message.
2406      */
2407     public function test_get_most_recent_message() {
2408         // Create some users.
2409         $user1 = self::getDataGenerator()->create_user();
2410         $user2 = self::getDataGenerator()->create_user();
2412         // The person doing the search.
2413         $this->setUser($user1);
2415         // Send some messages back and forth.
2416         $time = 1;
2417         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2418         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2419         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2420         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2422         // Retrieve the most recent messages.
2423         $message = \core_message\api::get_most_recent_message($user1->id, $user2->id);
2425         // Check the results are correct.
2426         $this->assertEquals($user2->id, $message->useridfrom);
2427         $this->assertEquals($user1->id, $message->useridto);
2428         $this->assertContains('Word.', $message->text);
2429     }
2431     /**
2432      * Tests retrieving most recent conversation message.
2433      */
2434     public function test_get_most_recent_conversation_message() {
2435         // Create some users.
2436         $user1 = self::getDataGenerator()->create_user();
2437         $user2 = self::getDataGenerator()->create_user();
2438         $user3 = self::getDataGenerator()->create_user();
2440         // Create group conversation.
2441         $conversation = \core_message\api::create_conversation(
2442             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2443             [$user1->id, $user2->id, $user3->id]
2444         );
2446         // The person getting the most recent conversation message.
2447         $this->setUser($user1);
2449         // Send some messages back and forth.
2450         $time = 1;
2451         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
2452         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
2453         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
2454         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Word.', $time + 4);
2456         // Retrieve the most recent messages.
2457         $message = \core_message\api::get_most_recent_conversation_message($conversation->id, $user1->id);
2459         // Check the results are correct.
2460         $this->assertEquals($user2->id, $message->useridfrom);
2461         $this->assertContains('Word.', $message->text);
2462     }
2464     /**
2465      * Tests retrieving a user's profile.
2466      */
2467     public function test_get_profile() {
2468         // Create some users.
2469         $user1 = self::getDataGenerator()->create_user();
2471         $user2 = new stdClass();
2472         $user2->country = 'AU';
2473         $user2->city = 'Perth';
2474         $user2 = self::getDataGenerator()->create_user($user2);
2476         // The person doing the search.
2477         $this->setUser($user1);
2479         // Get the profile.
2480         $profile = \core_message\api::get_profile($user1->id, $user2->id);
2482         $this->assertEquals($user2->id, $profile->userid);
2483         $this->assertEmpty($profile->email);
2484         $this->assertEmpty($profile->country);
2485         $this->assertEmpty($profile->city);
2486         $this->assertEquals(fullname($user2), $profile->fullname);
2487         $this->assertNull($profile->isonline);
2488         $this->assertFalse($profile->isblocked);
2489         $this->assertFalse($profile->iscontact);
2490     }
2492     /**
2493      * Tests retrieving a user's profile.
2494      */
2495     public function test_get_profile_as_admin() {
2496         // The person doing the search.
2497         $this->setAdminUser();
2499         // Create some users.
2500         $user1 = self::getDataGenerator()->create_user();
2502         $user2 = new stdClass();
2503         $user2->country = 'AU';
2504         $user2->city = 'Perth';
2505         $user2 = self::getDataGenerator()->create_user($user2);
2507         // Get the profile.
2508         $profile = \core_message\api::get_profile($user1->id, $user2->id);
2510         $this->assertEquals($user2->id, $profile->userid);
2511         $this->assertEquals($user2->email, $profile->email);
2512         $this->assertEquals($user2->country, $profile->country);
2513         $this->assertEquals($user2->city, $profile->city);
2514         $this->assertEquals(fullname($user2), $profile->fullname);
2515         $this->assertFalse($profile->isonline);
2516         $this->assertFalse($profile->isblocked);
2517         $this->assertFalse($profile->iscontact);
2518     }
2520     /**
2521      * Tests checking if a user can mark all messages as read.
2522      */
2523     public function test_can_mark_all_messages_as_read() {
2524         // Set as the admin.
2525         $this->setAdminUser();
2527         // Create some users.
2528         $user1 = self::getDataGenerator()->create_user();
2529         $user2 = self::getDataGenerator()->create_user();
2530         $user3 = self::getDataGenerator()->create_user();
2532         // Send some messages back and forth.
2533         $time = 1;
2534         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2535         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2536         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2537         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2539         $conversationid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2541         // The admin can do anything.
2542         $this->assertTrue(\core_message\api::can_mark_all_messages_as_read($user1->id, $conversationid));
2544         // Set as the user 1.
2545         $this->setUser($user1);
2547         // The user can mark the messages as he is in the conversation.
2548         $this->assertTrue(\core_message\api::can_mark_all_messages_as_read($user1->id, $conversationid));
2550         // User 1 can not mark the messages read for user 2.
2551         $this->assertFalse(\core_message\api::can_mark_all_messages_as_read($user2->id, $conversationid));
2553         // This user is not a part of the conversation.
2554         $this->assertFalse(\core_message\api::can_mark_all_messages_as_read($user3->id, $conversationid));
2555     }
2557     /**
2558      * Tests checking if a user can delete a conversation.
2559      */
2560     public function test_can_delete_conversation() {
2561         // Set as the admin.
2562         $this->setAdminUser();
2564         // Create some users.
2565         $user1 = self::getDataGenerator()->create_user();
2566         $user2 = self::getDataGenerator()->create_user();
2568         // Send some messages back and forth.
2569         $time = 1;
2570         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2571         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2572         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2573         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2575         $conversationid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2577         // The admin can do anything.
2578         $this->assertTrue(\core_message\api::can_delete_conversation($user1->id, $conversationid));
2580         // Set as the user 1.
2581         $this->setUser($user1);
2583         // They can delete their own messages.
2584         $this->assertTrue(\core_message\api::can_delete_conversation($user1->id, $conversationid));
2586         // They can't delete someone elses.
2587         $this->assertFalse(\core_message\api::can_delete_conversation($user2->id, $conversationid));
2588     }
2590     /**
2591      * Tests deleting a conversation.
2592      */
2593     public function test_delete_conversation() {
2594         global $DB;
2596         // Create some users.
2597         $user1 = self::getDataGenerator()->create_user();
2598         $user2 = self::getDataGenerator()->create_user();
2600         // The person doing the search.
2601         $this->setUser($user1);
2603         // Send some messages back and forth.
2604         $time = 1;
2605         $m1id = $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2606         $m2id = $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2607         $m3id = $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2608         $m4id = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2610         // Delete the conversation as user 1.
2611         \core_message\api::delete_conversation($user1->id, $user2->id);
2612         $this->assertDebuggingCalled();
2614         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
2615         $this->assertCount(4, $muas);
2616         // Sort by id.
2617         ksort($muas);
2619         $mua1 = array_shift($muas);
2620         $mua2 = array_shift($muas);
2621         $mua3 = array_shift($muas);
2622         $mua4 = array_shift($muas);
2624         $this->assertEquals($user1->id, $mua1->userid);
2625         $this->assertEquals($m1id, $mua1->messageid);
2626         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
2628         $this->assertEquals($user1->id, $mua2->userid);
2629         $this->assertEquals($m2id, $mua2->messageid);
2630         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
2632         $this->assertEquals($user1->id, $mua3->userid);
2633         $this->assertEquals($m3id, $mua3->messageid);
2634         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
2636         $this->assertEquals($user1->id, $mua4->userid);
2637         $this->assertEquals($m4id, $mua4->messageid);
2638         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
2639     }
2641     /**
2642      * Tests deleting a conversation by conversation id.
2643      */
2644     public function test_delete_conversation_by_id() {
2645         global $DB;
2647         // Create some users.
2648         $user1 = self::getDataGenerator()->create_user();
2649         $user2 = self::getDataGenerator()->create_user();
2651         // The person doing the search.
2652         $this->setUser($user1);
2654         // Send some messages back and forth.
2655         $time = 1;
2656         $m1id = $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2657         $m2id = $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2658         $m3id = $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2659         $m4id = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2661         // Delete the conversation as user 1.
2662         $conversationid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2663         \core_message\api::delete_conversation_by_id($user1->id, $conversationid);
2665         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
2666         $this->assertCount(4, $muas);
2667         // Sort by id.
2668         ksort($muas);
2670         $mua1 = array_shift($muas);
2671         $mua2 = array_shift($muas);
2672         $mua3 = array_shift($muas);
2673         $mua4 = array_shift($muas);
2675         $this->assertEquals($user1->id, $mua1->userid);
2676         $this->assertEquals($m1id, $mua1->messageid);
2677         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
2679         $this->assertEquals($user1->id, $mua2->userid);
2680         $this->assertEquals($m2id, $mua2->messageid);
2681         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
2683         $this->assertEquals($user1->id, $mua3->userid);
2684         $this->assertEquals($m3id, $mua3->messageid);
2685         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
2687         $this->assertEquals($user1->id, $mua4->userid);
2688         $this->assertEquals($m4id, $mua4->messageid);
2689         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
2690     }
2692     /**
2693      * Tests counting unread conversations.
2694      */
2695     public function test_count_unread_conversations() {
2696         $this->resetAfterTest(true);
2698         // Create some users.
2699         $user1 = self::getDataGenerator()->create_user();
2700         $user2 = self::getDataGenerator()->create_user();
2701         $user3 = self::getDataGenerator()->create_user();
2702         $user4 = self::getDataGenerator()->create_user();
2704         // The person wanting the conversation count.
2705         $this->setUser($user1);
2707         // Send some messages back and forth, have some different conversations with different users.
2708         $this->send_fake_message($user1, $user2, 'Yo!');
2709         $this->send_fake_message($user2, $user1, 'Sup mang?');
2710         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!');
2711         $this->send_fake_message($user2, $user1, 'Word.');
2713         $this->send_fake_message($user1, $user3, 'Booyah');
2714         $this->send_fake_message($user3, $user1, 'Whaaat?');
2715         $this->send_fake_message($user1, $user3, 'Nothing.');
2716         $this->send_fake_message($user3, $user1, 'Cool.');
2718         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
2719         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
2720         $this->send_fake_message($user1, $user4, 'Dope.');
2722         // Check the amount for the current user.
2723         $this->assertEquals(3, core_message\api::count_unread_conversations());
2725         // Check the amount for the second user.
2726         $this->assertEquals(1, core_message\api::count_unread_conversations($user2));
2727     }
2729     /**
2730      * Tests deleting a conversation.
2731      */
2732     public function test_get_all_message_preferences() {
2733         $user = self::getDataGenerator()->create_user();
2734         $this->setUser($user);
2736         // Set a couple of preferences to test.
2737         set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
2738         set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
2740         $processors = get_message_processors();
2741         $providers = message_get_providers_for_user($user->id);
2742         $prefs = \core_message\api::get_all_message_preferences($processors, $providers, $user);
2744         $this->assertEquals(1, $prefs->mod_assign_assign_notification_loggedin['popup']);
2745         $this->assertEquals(1, $prefs->mod_assign_assign_notification_loggedoff['email']);
2746     }
2748     /**
2749      * Tests the user can post a message.
2750      */
2751     public function test_can_post_message() {
2752         // Create some users.
2753         $user1 = self::getDataGenerator()->create_user();
2754         $user2 = self::getDataGenerator()->create_user();
2756         // Set as the first user.
2757         $this->setUser($user1);
2759         // With the default privacy setting, users can't message them.
2760         $this->assertFalse(\core_message\api::can_post_message($user2));
2762         // Enrol users to the same course.
2763         $course = $this->getDataGenerator()->create_course();
2764         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
2765         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
2766         // After enrolling users to the course, they should be able to message them with the default privacy setting.
2767         $this->assertTrue(\core_message\api::can_post_message($user2));
2768     }
2770     /**
2771      * Tests the user can't post a message without proper capability.
2772      */
2773     public function test_can_post_message_without_sendmessage_cap() {
2774         global $DB;
2776         // Create some users.
2777         $user1 = self::getDataGenerator()->create_user();
2778         $user2 = self::getDataGenerator()->create_user();
2780         // Set as the user 1.
2781         $this->setUser($user1);
2783         // Remove the capability to send a message.
2784         $roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
2785         unassign_capability('moodle/site:sendmessage', $roleids['user'],
2786             context_system::instance());
2788         // Check that we can not post a message without the capability.
2789         $this->assertFalse(\core_message\api::can_post_message($user2));
2790     }
2792     /**
2793      * Tests the user can post a message when they are contact.
2794      */
2795     public function test_can_post_message_when_contact() {
2796         // Create some users.
2797         $user1 = self::getDataGenerator()->create_user();
2798         $user2 = self::getDataGenerator()->create_user();
2800         // Set as the first user.
2801         $this->setUser($user1);
2803         // Check that we can not send user2 a message.
2804         $this->assertFalse(\core_message\api::can_post_message($user2));
2806         // Add users as contacts.
2807         \core_message\api::add_contact($user1->id, $user2->id);
2809         // Check that the return result is now true.
2810         $this->assertTrue(\core_message\api::can_post_message($user2));
2811     }
2813     /**
2814      * Tests the user can't post a message if they are not a contact and the user
2815      * has requested messages only from contacts.
2816      */
2817     public function test_can_post_message_when_not_contact() {
2818         // Create some users.
2819         $user1 = self::getDataGenerator()->create_user();
2820         $user2 = self::getDataGenerator()->create_user();
2822         // Set as the first user.
2823         $this->setUser($user1);
2825         // Set the second user's preference to not receive messages from non-contacts.
2826         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
2828         // Check that we can not send user 2 a message.
2829         $this->assertFalse(\core_message\api::can_post_message($user2));
2830     }
2832     /**
2833      * Tests the user can't post a message if they are blocked.
2834      */
2835     public function test_can_post_message_when_blocked() {
2836         // Create some users.
2837         $user1 = self::getDataGenerator()->create_user();
2838         $user2 = self::getDataGenerator()->create_user();
2840         // Set the user.
2841         $this->setUser($user1);
2843         // Block the second user.
2844         \core_message\api::block_user($user1->id, $user2->id);
2846         // Check that the second user can no longer send the first user a message.
2847         $this->assertFalse(\core_message\api::can_post_message($user1, $user2));
2848     }
2850     /**
2851      * Tests the user can post a message when site-wide messaging setting is enabled,
2852      * even if they are not a contact and are not members of the same course.
2853      */
2854     public function test_can_post_message_site_messaging_setting() {
2855         // Create some users.
2856         $user1 = self::getDataGenerator()->create_user();
2857         $user2 = self::getDataGenerator()->create_user();
2859         // Set as the first user.
2860         $this->setUser($user1);
2862         // By default, user only can be messaged by contacts and members of any of his/her courses.
2863         $this->assertFalse(\core_message\api::can_post_message($user2));
2865         // Enable site-wide messagging privacy setting. The user will be able to receive messages from everybody.
2866         set_config('messagingallusers', true);
2868         // Set the second user's preference to receive messages from everybody.
2869         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_SITE, $user2->id);
2871         // Check that we can send user2 a message.
2872         $this->assertTrue(\core_message\api::can_post_message($user2));
2874         // Disable site-wide messagging privacy setting. The user will be able to receive messages from contacts
2875         // and members sharing a course with her.
2876         set_config('messagingallusers', false);
2878         // As site-wide messaging setting is disabled, the value for user2 will be changed to MESSAGE_PRIVACY_COURSEMEMBER.
2879         $this->assertFalse(\core_message\api::can_post_message($user2));
2881         // Enrol users to the same course.
2882         $course = $this->getDataGenerator()->create_course();
2883         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
2884         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
2885         // Check that we can send user2 a message because they are sharing a course.
2886         $this->assertTrue(\core_message\api::can_post_message($user2));
2888         // Set the second user's preference to receive messages only from contacts.
2889         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
2890         // Check that now the user2 can't be contacted because user1 is not their contact.
2891         $this->assertFalse(\core_message\api::can_post_message($user2));
2893         // Make contacts user1 and user2.
2894         \core_message\api::add_contact($user2->id, $user1->id);
2895         // Check that we can send user2 a message because they are contacts.
2896         $this->assertTrue(\core_message\api::can_post_message($user2));
2897     }
2899     /**
2900      * Tests the user with the messageanyuser capability can post a message.
2901      */
2902     public function test_can_post_message_with_messageanyuser_cap() {
2903         global $DB;
2905         // Create some users.
2906         $teacher1 = self::getDataGenerator()->create_user();
2907         $student1 = self::getDataGenerator()->create_user();
2908         $student2 = self::getDataGenerator()->create_user();
2910         // Create users not enrolled in any course.
2911         $user1 = self::getDataGenerator()->create_user();
2913         // Create a course.
2914         $course1 = $this->getDataGenerator()->create_course();
2916         // Enrol the users in the course.
2917         $this->getDataGenerator()->enrol_user($teacher1->id, $course1->id, 'editingteacher');
2918         $this->getDataGenerator()->enrol_user($student1->id, $course1->id, 'student');
2919         $this->getDataGenerator()->enrol_user($student2->id, $course1->id, 'student');
2921         // Set some student preferences to not receive messages from non-contacts.
2922         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $student1->id);
2924         // Check that we can send student1 a message because teacher has the messageanyuser cap by default.
2925         $this->assertTrue(\core_message\api::can_post_message($student1, $teacher1));
2926         // Check that the teacher can't contact user1 because it's not his teacher.
2927         $this->assertFalse(\core_message\api::can_post_message($user1, $teacher1));
2929         // Remove the messageanyuser capability from the course1 for teachers.
2930         $coursecontext = context_course::instance($course1->id);
2931         $teacherrole = $DB->get_record('role', ['shortname' => 'editingteacher']);
2932         assign_capability('moodle/site:messageanyuser', CAP_PROHIBIT, $teacherrole->id, $coursecontext->id);
2933         $coursecontext->mark_dirty();
2935         // Check that we can't send user1 a message because they are not contacts.
2936         $this->assertFalse(\core_message\api::can_post_message($student1, $teacher1));
2937         // However, teacher can message student2 because they are sharing a course.
2938         $this->assertTrue(\core_message\api::can_post_message($student2, $teacher1));
2939     }
2941     /**
2942      * Verify the expected behaviour of the can_send_message_to_conversation() method for authenticated users with default settings.
2943      */
2944     public function test_can_send_message_to_conversation_basic() {
2945         // Create some users.
2946         $user1 = self::getDataGenerator()->create_user();
2947         $user2 = self::getDataGenerator()->create_user();
2948         $user3 = self::getDataGenerator()->create_user();
2950         // Create an individual conversation between user1 and user2.
2951         $ic1 = \core_message\api::create_conversation(
2952             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2953             [
2954                 $user1->id,
2955                 $user2->id
2956             ]
2957         );
2959         // Create a group conversation between and users 1, 2 and 3.
2960         $gc1 = \core_message\api::create_conversation(
2961             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2962             [
2963                 $user1->id,
2964                 $user2->id,
2965                 $user3->id
2966             ]
2967         );
2969         // For group conversations, there are no user privacy checks, so only membership in the conversation is needed.
2970         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
2972         // For individual conversations, the default privacy setting of 'only contacts and course members' applies.
2973         // Users are not in the same course, nor are they contacts, so messages cannot be sent.
2974         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
2976         // Enrol the users into the same course.
2977         $course = $this->getDataGenerator()->create_course();
2978         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
2979         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
2981         // After enrolling users to the course, they should be able to message them with the default privacy setting.
2982         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
2983     }
2985     /**
2986      * Verify the behaviour of can_send_message_to_conversation() for authenticated users without the sendmessage capability.
2987      */
2988     public function test_can_send_message_to_conversation_sendmessage_cap() {
2989         global $DB;
2991         $user1 = self::getDataGenerator()->create_user();
2992         $user2 = self::getDataGenerator()->create_user();
2993         $user3 = self::getDataGenerator()->create_user();
2995         // Enrol the users into the same course.
2996         $course = $this->getDataGenerator()->create_course();
2997         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
2998         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
2999         $this->getDataGenerator()->enrol_user($user3->id, $course->id);
3001         // Create an individual conversation between user1 and user2.
3002         $ic1 = \core_message\api::create_conversation(
3003             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3004             [
3005                 $user1->id,
3006                 $user2->id
3007             ]
3008         );
3010         // Group conversation between and users 1, 2 and 3.
3011         $gc1 = \core_message\api::create_conversation(
3012             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3013             [
3014                 $user1->id,
3015                 $user2->id,
3016                 $user3->id
3017             ]
3018         );
3020         // Default settings - user1 can send a message to both conversations.
3021         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3022         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3024         // Remove the capability to send a message.
3025         $roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
3026         unassign_capability('moodle/site:sendmessage', $roleids['user'], context_system::instance());
3028         // Verify that a user cannot send a message to either an individual or a group conversation.
3029         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3030         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3031     }
3033     /**
3034      * Verify the behaviour of can_send_message_to_conversation() for authenticated users without the messageanyuser capability.
3035      */
3036     public function test_can_send_message_to_conversation_messageanyuser_cap() {
3037         global $DB;
3039         $user1 = self::getDataGenerator()->create_user();
3040         $user2 = self::getDataGenerator()->create_user();
3041         $user3 = self::getDataGenerator()->create_user();
3043         // Enrol the users into the same course.
3044         $course = $this->getDataGenerator()->create_course();
3045         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
3046         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
3047         $this->getDataGenerator()->enrol_user($user3->id, $course->id);
3049         // Create an individual conversation between user1 and user2.
3050         $ic1 = \core_message\api::create_conversation(
3051             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3052             [
3053                 $user1->id,
3054                 $user2->id
3055             ]
3056         );
3058         // Group conversation between and users 1, 2 and 3.
3059         $gc1 = \core_message\api::create_conversation(
3060             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3061             [
3062                 $user1->id,
3063                 $user2->id,
3064                 $user3->id
3065             ]
3066         );
3068         // Update the message preference for user2, so they can only be messaged by contacts.
3069         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
3071         // Verify that the user cannot be contacted in the individual conversation and that groups are unaffected.
3072         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3073         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3075         // Assign the 'messageanyuser' capability to user1 at system context.
3076         $systemcontext = context_system::instance();
3077         $authenticateduser = $DB->get_record('role', ['shortname' => 'user']);
3078         assign_capability('moodle/site:messageanyuser', CAP_ALLOW, $authenticateduser->id, $systemcontext->id);
3080         // Check that user1 can now message user2 due to the capability, and that group conversations is again unaffected.
3081         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3082         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3083     }
3085     /**
3086      * Test verifying that users cannot send messages to conversations they are not a part of.
3087      */
3088     public function test_can_post_message_to_conversation_non_member() {
3089         // Create some users.
3090         $user1 = self::getDataGenerator()->create_user();
3091         $user2 = self::getDataGenerator()->create_user();
3092         $user3 = self::getDataGenerator()->create_user();
3093         $user4 = self::getDataGenerator()->create_user();
3095         // Enrol the users into the same course.
3096         $course = $this->getDataGenerator()->create_course();
3097         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
3098         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
3099         $this->getDataGenerator()->enrol_user($user3->id, $course->id);
3100         $this->getDataGenerator()->enrol_user($user4->id, $course->id);
3102         // Create an individual conversation between user1 and user2.
3103         $ic1 = \core_message\api::create_conversation(
3104             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3105             [
3106                 $user1->id,
3107                 $user2->id
3108             ]
3109         );
3111         // Create a group conversation between and users 1, 2 and 3.
3112         $gc1 = \core_message\api::create_conversation(
3113             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3114             [
3115                 $user1->id,
3116                 $user2->id,
3117                 $user3->id
3118             ]
3119         );
3121         // Verify, non members cannot send a message.
3122         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user4->id, $gc1->id));
3123         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user4->id, $ic1->id));
3124     }
3126     /**
3127      * Test verifying the behaviour of the can_send_message_to_conversation method when privacy is set to contacts only.
3128      */
3129     public function test_can_send_message_to_conversation_privacy_contacts_only() {
3130         // Create some users.
3131         $user1 = self::getDataGenerator()->create_user();
3132         $user2 = self::getDataGenerator()->create_user();
3133         $user3 = self::getDataGenerator()->create_user();
3135         // Create an individual conversation between user1 and user2.
3136         $ic1 = \core_message\api::create_conversation(
3137             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3138             [
3139                 $user1->id,
3140                 $user2->id
3141             ]
3142         );
3144         // Create a group conversation between and users 1, 2 and 3.
3145         $gc1 = \core_message\api::create_conversation(
3146             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3147             [
3148                 $user1->id,
3149                 $user2->id,
3150                 $user3->id
3151             ]
3152         );
3154         // Set the message privacy preference to 'contacts only' for user 2.
3155         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
3157         // Verify that user1 cannot send a message to the individual conversation, but that the group conversation is unaffected.
3158         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3159         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3161         // Now, simulate a contact request (and approval) between user1 and user2.
3162         \core_message\api::create_contact_request($user1->id, $user2->id);
3163         \core_message\api::confirm_contact_request($user1->id, $user2->id);
3165         // Verify user1 can now message user2 again via their individual conversation.
3166         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3167     }
3169     /**
3170      * Test verifying the behaviour of the can_send_message_to_conversation method when privacy is set to contacts / course members.
3171      */
3172     public function test_can_send_message_to_conversation_privacy_contacts_course() {
3173         // Create some users.
3174         $user1 = self::getDataGenerator()->create_user();
3175         $user2 = self::getDataGenerator()->create_user();
3176         $user3 = self::getDataGenerator()->create_user();
3178         // Set the message privacy preference to 'contacts + course members' for user 2.
3179         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER, $user2->id);
3181         // Create an individual conversation between user1 and user2.
3182         $ic1 = \core_message\api::create_conversation(
3183             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3184             [
3185                 $user1->id,
3186                 $user2->id
3187             ]
3188         );
3190         // Create a group conversation between and users 1, 2 and 3.
3191         $gc1 = \core_message\api::create_conversation(
3192             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3193             [
3194                 $user1->id,
3195                 $user2->id,
3196                 $user3->id
3197             ]
3198         );
3200         // Verify that users in a group conversation can message one another (i.e. privacy controls ignored).
3201         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3203         // Verify that user1 can not message user2 unless they are either contacts, or share a course.
3204         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3206         // Enrol the users into the same course.
3207         $course = $this->getDataGenerator()->create_course();
3208         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
3209         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
3210         $this->getDataGenerator()->enrol_user($user3->id, $course->id);
3212         // Verify that user1 can send a message to user2, based on the shared course, without being a contact.
3213         $this->assertFalse(\core_message\api::is_contact($user1->id, $user2->id));
3214         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3215     }
3217     /**
3218      * Test verifying the behaviour of the can_send_message_to_conversation method when privacy is set to any user.
3219      */
3220     public function test_can_send_message_to_conversation_privacy_sitewide() {
3221         // Create some users.
3222         $user1 = self::getDataGenerator()->create_user();
3223         $user2 = self::getDataGenerator()->create_user();
3224         $user3 = self::getDataGenerator()->create_user();
3226         // Create an individual conversation between user1 and user2.
3227         $ic1 = \core_message\api::create_conversation(
3228             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3229             [
3230                 $user1->id,
3231                 $user2->id
3232             ]
3233         );
3235         // Create a group conversation between and users 1, 2 and 3.
3236         $gc1 = \core_message\api::create_conversation(
3237             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3238             [
3239                 $user1->id,
3240                 $user2->id,
3241                 $user3->id
3242             ]
3243         );
3245         // By default, the messaging privacy dictates that users can only be contacted by contacts, and members of their courses.
3246         // Verify also, that groups are not restricted in this way.
3247         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3248         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3250         // Enable site-wide messagging privacy setting.
3251         // This enables a privacy option for users, allowing them to choose to be contactable by anybody on the site.
3252         set_config('messagingallusers', true);
3254         // Set the second user's preference to receive messages from everybody.
3255         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_SITE, $user2->id);
3257         // Check that user1 can send user2 a message, and that the group conversation is unaffected.
3258         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3259         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3261         // Disable site-wide messagging privacy setting. The user will be able to receive messages from contacts
3262         // and members sharing a course with her.
3263         set_config('messagingallusers', false);
3265         // As site-wide messaging setting is disabled, the value for user2 will be changed to MESSAGE_PRIVACY_COURSEMEMBER.
3266         // Verify also that the group conversation is unaffected.
3267         $this->assertFalse(\core_message\api::can_send_message_to_conversation($user1->id, $ic1->id));
3268         $this->assertTrue(\core_message\api::can_send_message_to_conversation($user1->id, $gc1->id));
3269     }
3271     /**
3272      * Test verifying the behaviour of the can_send_message_to_conversation method when a user is blocked.
3273      */
3274     public function test_can_send_message_to_conversation_when_blocked() {
3275         $user1 = self::getDataGenerator()->create_user();
3276         $user2 = self::getDataGenerator()->create_user();
3277         $user3 = self::getDataGenerator()->create_user();
3279         // Create an individual conversation between user1 and user2.
3280         $ic1 = \core_message\api::create_conversation(
3281             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
3282             [
3283                 $user1->id,
3284                 $user2->id
3285             ]
3286         );
3288         // Create a group conversation between and users 1, 2 and 3.
3289         $gc1 = \core_message\api::create_conversation(
3290             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
3291             [
3292                 $user1->id,
3293                 $user2->id,
3294                 $user3->id
3295             ]
3296    &nb