MDL-63968 message: Correct use of get_in_or_equal
[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             }
1093             $this->assertObjectHasAttribute('messages', $conv);
1094             foreach ($conv->messages as $message) {
1095                 $this->assertObjectHasAttribute('id', $message);
1096                 $this->assertObjectHasAttribute('useridfrom', $message);
1097                 $this->assertObjectHasAttribute('text', $message);
1098                 $this->assertObjectHasAttribute('timecreated', $message);
1099             }
1100         }
1101     }
1103     /**
1104      * Test verifying that html format messages are supported, and that message_format_message_text() is being called appropriately.
1105      */
1106     public function test_get_conversations_message_format() {
1107         global $DB;
1108         // Create some users.
1109         $user1 = self::getDataGenerator()->create_user();
1110         $user2 = self::getDataGenerator()->create_user();
1112         // Create conversation.
1113         $conversation = \core_message\api::create_conversation(
1114             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1115             [$user1->id, $user2->id]
1116         );
1118         // Send some messages back and forth.
1119         $time = 1;
1120         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 1);
1121         $mid = testhelper::send_fake_message_to_conversation($user1, $conversation->id, '<a href="#">A link</a>', $time + 2);
1123         // Verify the format of the html message.
1124         $message = $DB->get_record('messages', ['id' => $mid]);
1125         $expectedmessagetext = message_format_message_text($message);
1126         $conversations = \core_message\api::get_conversations($user1->id);
1127         $messages = $conversations[0]->messages;
1128         $this->assertEquals($expectedmessagetext, $messages[0]->text);
1129     }
1131     /**
1132      * Tests retrieving conversations with a limit and offset to ensure pagination works correctly.
1133      */
1134     public function test_get_conversations_limit_offset() {
1135         // Get a bunch of conversations, some group, some individual and in different states.
1136         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1137             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1139         // Get all conversations for user1, limited to 1 result.
1140         $conversations = core_message\api::get_conversations($user1->id, 0, 1);
1142         // Verify the first conversation.
1143         $this->assertCount(1, $conversations);
1144         $conversation = array_shift($conversations);
1145         $this->assertEquals($conversation->id, $gc3->id);
1147         // Verify the next conversation.
1148         $conversations = \core_message\api::get_conversations($user1->id, 1, 1);
1149         $this->assertCount(1, $conversations);
1150         $this->assertEquals($gc2->id, $conversations[0]->id);
1152         // Verify the next conversation.
1153         $conversations = \core_message\api::get_conversations($user1->id, 2, 1);
1154         $this->assertCount(1, $conversations);
1155         $this->assertEquals($ic2->id, $conversations[0]->id);
1157         // Skip one and get both empty conversations.
1158         $conversations = \core_message\api::get_conversations($user1->id, 4, 2);
1159         $this->assertCount(2, $conversations);
1160         $this->assertEquals($gc5->id, $conversations[0]->id);
1161         $this->assertEmpty($conversations[0]->messages);
1162         $this->assertEquals($gc4->id, $conversations[1]->id);
1163         $this->assertEmpty($conversations[1]->messages);
1165         // Ask for an offset that doesn't exist and verify no conversations are returned.
1166         $conversations = \core_message\api::get_conversations($user1->id, 10, 1);
1167         $this->assertCount(0, $conversations);
1168     }
1170     /**
1171      * Test verifying the type filtering behaviour of the
1172      */
1173     public function test_get_conversations_type_filter() {
1174         // Get a bunch of conversations, some group, some individual and in different states.
1175         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1176             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1178         // Verify we can ask for only individual conversations.
1179         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
1180             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL);
1181         $this->assertCount(2, $conversations);
1183         // Verify we can ask for only group conversations.
1184         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
1185             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP);
1186         $this->assertCount(4, $conversations);
1188         // Verify an exception is thrown if an unrecognized type is specified.
1189         $this->expectException(\moodle_exception::class);
1190         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, 0);
1191     }
1193     /**
1194      * Tests retrieving conversations when a conversation contains a deleted user.
1195      */
1196     public function test_get_conversations_with_deleted_user() {
1197         // Get a bunch of conversations, some group, some individual and in different states.
1198         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1199             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1201         // Delete the second user and retrieve the conversations.
1202         // We should have 5, as $ic1 drops off the list.
1203         // Group conversations remain albeit with less members.
1204         delete_user($user2);
1205         $conversations = \core_message\api::get_conversations($user1->id);
1206         $this->assertCount(5, $conversations);
1207         $this->assertEquals($gc3->id, $conversations[0]->id);
1208         $this->assertcount(1, $conversations[0]->members);
1209         $this->assertEquals($gc2->id, $conversations[1]->id);
1210         $this->assertcount(1, $conversations[1]->members);
1211         $this->assertEquals($ic2->id, $conversations[2]->id);
1212         $this->assertEquals($gc5->id, $conversations[3]->id);
1213         $this->assertEquals($gc4->id, $conversations[4]->id);
1215         // Delete a user from a group conversation where that user had sent the most recent message.
1216         // This user will still be present in the members array, as will the message in the messages array.
1217         delete_user($user4);
1218         $conversations = \core_message\api::get_conversations($user1->id);
1219         $this->assertCount(5, $conversations);
1220         $this->assertEquals($gc2->id, $conversations[1]->id);
1221         $this->assertcount(1, $conversations[1]->members);
1222         $this->assertEquals($user4->id, $conversations[1]->members[$user4->id]->id);
1223         $this->assertcount(1, $conversations[1]->messages);
1224         $this->assertEquals($user4->id, $conversations[1]->messages[0]->useridfrom);
1226         // Delete the third user and retrieve the conversations.
1227         // We should have 4, as $ic1, $ic2 drop off the list.
1228         // Group conversations remain albeit with less members.
1229         delete_user($user3);
1230         $conversations = \core_message\api::get_conversations($user1->id);
1231         $this->assertCount(4, $conversations);
1232         $this->assertEquals($gc3->id, $conversations[0]->id);
1233         $this->assertcount(1, $conversations[0]->members);
1234         $this->assertEquals($gc2->id, $conversations[1]->id);
1235         $this->assertcount(1, $conversations[1]->members);
1236         $this->assertEquals($gc5->id, $conversations[2]->id);
1237         $this->assertEquals($gc4->id, $conversations[3]->id);
1238     }
1240     /**
1241      * Test confirming the behaviour of get_conversations() when users delete all messages.
1242      */
1243     public function test_get_conversations_deleted_messages() {
1244         // Get a bunch of conversations, some group, some individual and in different states.
1245         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1246             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1248         $conversations = \core_message\api::get_conversations($user1->id);
1249         $this->assertCount(6, $conversations);
1251         // Delete all messages from a group conversation the user is in - it should be returned.
1252         $this->assertTrue(\core_message\api::is_user_in_conversation($user1->id, $gc2->id));
1253         $convmessages = \core_message\api::get_conversation_messages($user1->id, $gc2->id);
1254         $messages = $convmessages['messages'];
1255         foreach ($messages as $message) {
1256             \core_message\api::delete_message($user1->id, $message->id);
1257         }
1258         $conversations = \core_message\api::get_conversations($user1->id);
1259         $this->assertCount(6, $conversations);
1260         $this->assertContains($gc2->id, array_column($conversations, 'id'));
1262         // Delete all messages from an individual conversation the user is in - it should not be returned.
1263         $this->assertTrue(\core_message\api::is_user_in_conversation($user1->id, $ic1->id));
1264         $convmessages = \core_message\api::get_conversation_messages($user1->id, $ic1->id);
1265         $messages = $convmessages['messages'];
1266         foreach ($messages as $message) {
1267             \core_message\api::delete_message($user1->id, $message->id);
1268         }
1269         $conversations = \core_message\api::get_conversations($user1->id);
1270         $this->assertCount(5, $conversations);
1271         $this->assertNotContains($ic1->id, array_column($conversations, 'id'));
1272     }
1274     /**
1275      * Test verifying the behaviour of get_conversations() when fetching favourite conversations with only a single
1276      * favourite.
1277      */
1278     public function test_get_conversations_favourite_conversations_single() {
1279         // Get a bunch of conversations, some group, some individual and in different states.
1280         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1281             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1283         // Mark a single conversation as favourites.
1284         \core_message\api::set_favourite_conversation($ic2->id, $user1->id);
1286         // Get the conversation, first with no restrictions, confirming the favourite status of the conversations.
1287         $conversations = \core_message\api::get_conversations($user1->id);
1288         $this->assertCount(6, $conversations);
1289         foreach ($conversations as $conv) {
1290             if (in_array($conv->id, [$ic2->id])) {
1291                 $this->assertTrue($conv->isfavourite);
1292             } else {
1293                 $this->assertFalse($conv->isfavourite);
1294             }
1295         }
1297         // Now, get ONLY favourite conversations.
1298         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, true);
1299         $this->assertCount(1, $conversations);
1300         foreach ($conversations as $conv) {
1301             $this->assertTrue($conv->isfavourite);
1302             $this->assertEquals($ic2->id, $conv->id);
1303         }
1305         // Now, try ONLY favourites of type 'group'.
1306         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
1307             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, true);
1308         $this->assertEmpty($conversations);
1310         // And NO favourite conversations.
1311         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, false);
1312         $this->assertCount(5, $conversations);
1313         foreach ($conversations as $conv) {
1314             $this->assertFalse($conv->isfavourite);
1315             $this->assertNotEquals($ic2, $conv->id);
1316         }
1317     }
1319     /**
1320      * Test verifying the behaviour of get_conversations() when fetching favourite conversations.
1321      */
1322     public function test_get_conversations_favourite_conversations() {
1323         // Get a bunch of conversations, some group, some individual and in different states.
1324         list($user1, $user2, $user3, $user4, $ic1, $ic2, $ic3,
1325             $gc1, $gc2, $gc3, $gc4, $gc5, $gc6) = $this->create_conversation_test_data();
1327         // Try to get ONLY favourite conversations, when no favourites exist.
1328         $this->assertEquals([], \core_message\api::get_conversations($user1->id, 0, 20, null, true));
1330         // Try to get NO favourite conversations, when no favourites exist.
1331         $this->assertCount(6, \core_message\api::get_conversations($user1->id, 0, 20, null, false));
1333         // Mark a few conversations as favourites.
1334         \core_message\api::set_favourite_conversation($ic1->id, $user1->id);
1335         \core_message\api::set_favourite_conversation($gc2->id, $user1->id);
1336         \core_message\api::set_favourite_conversation($gc5->id, $user1->id);
1337         $favouriteids = [$ic1->id, $gc2->id, $gc5->id];
1339         // Get the conversations, first with no restrictions, confirming the favourite status of the conversations.
1340         $conversations = \core_message\api::get_conversations($user1->id);
1341         $this->assertCount(6, $conversations);
1342         foreach ($conversations as $conv) {
1343             if (in_array($conv->id, $favouriteids)) {
1344                 $this->assertTrue($conv->isfavourite);
1345             } else {
1346                 $this->assertFalse($conv->isfavourite);
1347             }
1348         }
1350         // Now, get ONLY favourite conversations.
1351         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, true);
1352         $this->assertCount(3, $conversations);
1353         foreach ($conversations as $conv) {
1354             $this->assertTrue($conv->isfavourite);
1355             $this->assertNotFalse(array_search($conv->id, $favouriteids));
1356         }
1358         // Now, try ONLY favourites of type 'group'.
1359         $conversations = \core_message\api::get_conversations($user1->id, 0, 20,
1360             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, true);
1361         $this->assertCount(2, $conversations);
1362         foreach ($conversations as $conv) {
1363             $this->assertTrue($conv->isfavourite);
1364             $this->assertNotFalse(array_search($conv->id, [$gc2->id, $gc5->id]));
1365         }
1367         // And NO favourite conversations.
1368         $conversations = \core_message\api::get_conversations($user1->id, 0, 20, null, false);
1369         $this->assertCount(3, $conversations);
1370         foreach ($conversations as $conv) {
1371             $this->assertFalse($conv->isfavourite);
1372             $this->assertFalse(array_search($conv->id, $favouriteids));
1373         }
1374     }
1376     /**
1377      * Test verifying that group linked conversations are returned and contain a subname matching the course name.
1378      */
1379     public function test_get_conversations_group_linked() {
1380         global $CFG;
1382         // Create some users.
1383         $user1 = self::getDataGenerator()->create_user();
1384         $user2 = self::getDataGenerator()->create_user();
1385         $user3 = self::getDataGenerator()->create_user();
1387         $course1 = $this->getDataGenerator()->create_course();
1389         // Create a group with a linked conversation and a valid image.
1390         $this->setAdminUser();
1391         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1392         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1393         $this->getDataGenerator()->enrol_user($user3->id, $course1->id);
1394         $group1 = $this->getDataGenerator()->create_group([
1395             'courseid' => $course1->id,
1396             'enablemessaging' => 1,
1397             'picturepath' => $CFG->dirroot . '/lib/tests/fixtures/gd-logo.png'
1398         ]);
1400         // Add users to group1.
1401         $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user1->id));
1402         $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user2->id));
1404         // Verify the group with the image works as expected.
1405         $conversations = \core_message\api::get_conversations($user1->id);
1406         $this->assertEquals(2, $conversations[0]->membercount);
1407         $this->assertEquals($course1->shortname, $conversations[0]->subname);
1408         $groupimageurl = get_group_picture_url($group1, $group1->courseid, true);
1409         $this->assertEquals($groupimageurl, $conversations[0]->imageurl);
1411         // Create a group with a linked conversation and without any image.
1412         $group2 = $this->getDataGenerator()->create_group([
1413             'courseid' => $course1->id,
1414             'enablemessaging' => 1,
1415         ]);
1417         // Add users to group2.
1418         $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $user2->id));
1419         $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $user3->id));
1421         // Verify the group without any image works as expected too.
1422         $conversations = \core_message\api::get_conversations($user3->id);
1423         $this->assertEquals(2, $conversations[0]->membercount);
1424         $this->assertEquals($course1->shortname, $conversations[0]->subname);
1425         $groupimageurl = get_group_picture_url($group2, $group2->courseid, true);
1426         $this->assertEquals($groupimageurl, $conversations[0]->imageurl);
1427     }
1429    /**
1430     * The data provider for get_conversations_mixed.
1431     *
1432     * This provides sets of data to for testing.
1433     * @return array
1434     */
1435    public function get_conversations_mixed_provider() {
1436        return array(
1437             'Test that conversations with messages contacts is correctly ordered.' => array(
1438                 'users' => array(
1439                     'user1',
1440                     'user2',
1441                     'user3',
1442                 ),
1443                 'contacts' => array(
1444                 ),
1445                 'messages' => array(
1446                     array(
1447                         'from'          => 'user1',
1448                         'to'            => 'user2',
1449                         'state'         => 'unread',
1450                         'subject'       => 'S1',
1451                     ),
1452                     array(
1453                         'from'          => 'user2',
1454                         'to'            => 'user1',
1455                         'state'         => 'unread',
1456                         'subject'       => 'S2',
1457                     ),
1458                     array(
1459                         'from'          => 'user1',
1460                         'to'            => 'user2',
1461                         'state'         => 'unread',
1462                         'timecreated'   => 0,
1463                         'subject'       => 'S3',
1464                     ),
1465                     array(
1466                         'from'          => 'user1',
1467                         'to'            => 'user3',
1468                         'state'         => 'read',
1469                         'timemodifier'  => 1,
1470                         'subject'       => 'S4',
1471                     ),
1472                     array(
1473                         'from'          => 'user3',
1474                         'to'            => 'user1',
1475                         'state'         => 'read',
1476                         'timemodifier'  => 1,
1477                         'subject'       => 'S5',
1478                     ),
1479                     array(
1480                         'from'          => 'user1',
1481                         'to'            => 'user3',
1482                         'state'         => 'read',
1483                         'timecreated'   => 0,
1484                         'subject'       => 'S6',
1485                     ),
1486                 ),
1487                 'expectations' => array(
1488                     'user1' => array(
1489                         // User1 has conversed most recently with user3. The most recent message is M5.
1490                         array(
1491                             'messageposition'   => 0,
1492                             'with'              => 'user3',
1493                             'subject'           => '<p>S5</p>',
1494                             'unreadcount'       => 0,
1495                         ),
1496                         // User1 has also conversed with user2. The most recent message is S2.
1497                         array(
1498                             'messageposition'   => 1,
1499                             'with'              => 'user2',
1500                             'subject'           => '<p>S2</p>',
1501                             'unreadcount'       => 1,
1502                         ),
1503                     ),
1504                     'user2' => array(
1505                         // User2 has only conversed with user1. Their most recent shared message was S2.
1506                         array(
1507                             'messageposition'   => 0,
1508                             'with'              => 'user1',
1509                             'subject'           => '<p>S2</p>',
1510                             'unreadcount'       => 2,
1511                         ),
1512                     ),
1513                     'user3' => array(
1514                         // User3 has only conversed with user1. Their most recent shared message was S5.
1515                         array(
1516                             'messageposition'   => 0,
1517                             'with'              => 'user1',
1518                             'subject'           => '<p>S5</p>',
1519                             'unreadcount'       => 0,
1520                         ),
1521                     ),
1522                 ),
1523             ),
1524             'Test conversations with a single user, where some messages are read and some are not.' => array(
1525                 'users' => array(
1526                     'user1',
1527                     'user2',
1528                 ),
1529                 'contacts' => array(
1530                 ),
1531                 'messages' => array(
1532                     array(
1533                         'from'          => 'user1',
1534                         'to'            => 'user2',
1535                         'state'         => 'read',
1536                         'subject'       => 'S1',
1537                     ),
1538                     array(
1539                         'from'          => 'user2',
1540                         'to'            => 'user1',
1541                         'state'         => 'read',
1542                         'subject'       => 'S2',
1543                     ),
1544                     array(
1545                         'from'          => 'user1',
1546                         'to'            => 'user2',
1547                         'state'         => 'unread',
1548                         'timemodifier'  => 1,
1549                         'subject'       => 'S3',
1550                     ),
1551                     array(
1552                         'from'          => 'user1',
1553                         'to'            => 'user2',
1554                         'state'         => 'unread',
1555                         'timemodifier'  => 1,
1556                         'subject'       => 'S4',
1557                     ),
1558                 ),
1559                 'expectations' => array(
1560                     // The most recent message between user1 and user2 was S4.
1561                     'user1' => array(
1562                         array(
1563                             'messageposition'   => 0,
1564                             'with'              => 'user2',
1565                             'subject'           => '<p>S4</p>',
1566                             'unreadcount'       => 0,
1567                         ),
1568                     ),
1569                     'user2' => array(
1570                         // The most recent message between user1 and user2 was S4.
1571                         array(
1572                             'messageposition'   => 0,
1573                             'with'              => 'user1',
1574                             'subject'           => '<p>S4</p>',
1575                             'unreadcount'       => 2,
1576                         ),
1577                     ),
1578                 ),
1579             ),
1580             'Test conversations with a single user, where some messages are read and some are not, and messages ' .
1581             'are out of order' => array(
1582             // This can happen through a combination of factors including multi-master DB replication with messages
1583             // read somehow (e.g. API).
1584                 'users' => array(
1585                     'user1',
1586                     'user2',
1587                 ),
1588                 'contacts' => array(
1589                 ),
1590                 'messages' => array(
1591                     array(
1592                         'from'          => 'user1',
1593                         'to'            => 'user2',
1594                         'state'         => 'read',
1595                         'subject'       => 'S1',
1596                         'timemodifier'  => 1,
1597                     ),
1598                     array(
1599                         'from'          => 'user2',
1600                         'to'            => 'user1',
1601                         'state'         => 'read',
1602                         'subject'       => 'S2',
1603                         'timemodifier'  => 2,
1604                     ),
1605                     array(
1606                         'from'          => 'user1',
1607                         'to'            => 'user2',
1608                         'state'         => 'unread',
1609                         'subject'       => 'S3',
1610                     ),
1611                     array(
1612                         'from'          => 'user1',
1613                         'to'            => 'user2',
1614                         'state'         => 'unread',
1615                         'subject'       => 'S4',
1616                     ),
1617                 ),
1618                 'expectations' => array(
1619                     // The most recent message between user1 and user2 was S2, even though later IDs have not been read.
1620                     'user1' => array(
1621                         array(
1622                             'messageposition'   => 0,
1623                             'with'              => 'user2',
1624                             'subject'           => '<p>S2</p>',
1625                             'unreadcount'       => 0,
1626                         ),
1627                     ),
1628                     'user2' => array(
1629                         array(
1630                             'messageposition'   => 0,
1631                             'with'              => 'user1',
1632                             'subject'           => '<p>S2</p>',
1633                             'unreadcount'       => 2
1634                         ),
1635                     ),
1636                 ),
1637             ),
1638             'Test unread message count is correct for both users' => array(
1639                 'users' => array(
1640                     'user1',
1641                     'user2',
1642                 ),
1643                 'contacts' => array(
1644                 ),
1645                 'messages' => array(
1646                     array(
1647                         'from'          => 'user1',
1648                         'to'            => 'user2',
1649                         'state'         => 'read',
1650                         'subject'       => 'S1',
1651                         'timemodifier'  => 1,
1652                     ),
1653                     array(
1654                         'from'          => 'user2',
1655                         'to'            => 'user1',
1656                         'state'         => 'read',
1657                         'subject'       => 'S2',
1658                         'timemodifier'  => 2,
1659                     ),
1660                     array(
1661                         'from'          => 'user1',
1662                         'to'            => 'user2',
1663                         'state'         => 'read',
1664                         'subject'       => 'S3',
1665                         'timemodifier'  => 3,
1666                     ),
1667                     array(
1668                         'from'          => 'user1',
1669                         'to'            => 'user2',
1670                         'state'         => 'read',
1671                         'subject'       => 'S4',
1672                         'timemodifier'  => 4,
1673                     ),
1674                     array(
1675                         'from'          => 'user1',
1676                         'to'            => 'user2',
1677                         'state'         => 'unread',
1678                         'subject'       => 'S5',
1679                         'timemodifier'  => 5,
1680                     ),
1681                     array(
1682                         'from'          => 'user2',
1683                         'to'            => 'user1',
1684                         'state'         => 'unread',
1685                         'subject'       => 'S6',
1686                         'timemodifier'  => 6,
1687                     ),
1688                     array(
1689                         'from'          => 'user1',
1690                         'to'            => 'user2',
1691                         'state'         => 'unread',
1692                         'subject'       => 'S7',
1693                         'timemodifier'  => 7,
1694                     ),
1695                     array(
1696                         'from'          => 'user1',
1697                         'to'            => 'user2',
1698                         'state'         => 'unread',
1699                         'subject'       => 'S8',
1700                         'timemodifier'  => 8,
1701                     ),
1702                 ),
1703                 'expectations' => array(
1704                     // The most recent message between user1 and user2 was S2, even though later IDs have not been read.
1705                     'user1' => array(
1706                         array(
1707                             'messageposition'   => 0,
1708                             'with'              => 'user2',
1709                             'subject'           => '<p>S8</p>',
1710                             'unreadcount'       => 1,
1711                         ),
1712                     ),
1713                     'user2' => array(
1714                         array(
1715                             'messageposition'   => 0,
1716                             'with'              => 'user1',
1717                             'subject'           => '<p>S8</p>',
1718                             'unreadcount'       => 3,
1719                         ),
1720                     ),
1721                 ),
1722             ),
1723         );
1724     }
1726     /**
1727      * Test get_conversations with a mixture of messages.
1728      *
1729      * @dataProvider get_conversations_mixed_provider
1730      * @param array $usersdata The list of users to create for this test.
1731      * @param array $messagesdata The list of messages to create.
1732      * @param array $expectations The list of expected outcomes.
1733      */
1734     public function test_get_conversations_mixed($usersdata, $contacts, $messagesdata, $expectations) {
1735         global $DB;
1737         // Create all of the users.
1738         $users = array();
1739         foreach ($usersdata as $username) {
1740             $users[$username] = $this->getDataGenerator()->create_user(array('username' => $username));
1741         }
1743         foreach ($contacts as $username => $contact) {
1744             foreach ($contact as $contactname => $blocked) {
1745                 $record = new stdClass();
1746                 $record->userid     = $users[$username]->id;
1747                 $record->contactid  = $users[$contactname]->id;
1748                 $record->blocked    = $blocked;
1749                 $record->id = $DB->insert_record('message_contacts', $record);
1750             }
1751         }
1753         $defaulttimecreated = time();
1754         foreach ($messagesdata as $messagedata) {
1755             $from       = $users[$messagedata['from']];
1756             $to         = $users[$messagedata['to']];
1757             $subject    = $messagedata['subject'];
1759             if (isset($messagedata['state']) && $messagedata['state'] == 'unread') {
1760                 $messageid = $this->send_fake_message($from, $to, $subject);
1761             } else {
1762                 // If there is no state, or the state is not 'unread', assume the message is read.
1763                 $messageid = message_post_message($from, $to, $subject, FORMAT_PLAIN);
1764             }
1766             $updatemessage = new stdClass();
1767             $updatemessage->id = $messageid;
1768             if (isset($messagedata['timecreated'])) {
1769                 $updatemessage->timecreated = $messagedata['timecreated'];
1770             } else if (isset($messagedata['timemodifier'])) {
1771                 $updatemessage->timecreated = $defaulttimecreated + $messagedata['timemodifier'];
1772             } else {
1773                 $updatemessage->timecreated = $defaulttimecreated;
1774             }
1776             $DB->update_record('messages', $updatemessage);
1777         }
1779         foreach ($expectations as $username => $data) {
1780             // Get the recent conversations for the specified user.
1781             $user = $users[$username];
1782             $conversations = array_values(\core_message\api::get_conversations($user->id));
1783             foreach ($data as $expectation) {
1784                 $otheruser = $users[$expectation['with']];
1785                 $conversation = $conversations[$expectation['messageposition']];
1786                 $this->assertEquals($otheruser->id, $conversation->members[$otheruser->id]->id);
1787                 $this->assertEquals($expectation['subject'], $conversation->messages[0]->text);
1788                 $this->assertEquals($expectation['unreadcount'], $conversation->unreadcount);
1789             }
1790         }
1791     }
1793     /**
1794      * Tests retrieving contacts.
1795      */
1796     public function test_get_contacts() {
1797         // Create some users.
1798         $user1 = self::getDataGenerator()->create_user();
1800         // Set as the user.
1801         $this->setUser($user1);
1803         $user2 = new stdClass();
1804         $user2->firstname = 'User';
1805         $user2->lastname = 'A';
1806         $user2 = self::getDataGenerator()->create_user($user2);
1808         $user3 = new stdClass();
1809         $user3->firstname = 'User';
1810         $user3->lastname = 'B';
1811         $user3 = self::getDataGenerator()->create_user($user3);
1813         $user4 = new stdClass();
1814         $user4->firstname = 'User';
1815         $user4->lastname = 'C';
1816         $user4 = self::getDataGenerator()->create_user($user4);
1818         $user5 = new stdClass();
1819         $user5->firstname = 'User';
1820         $user5->lastname = 'D';
1821         $user5 = self::getDataGenerator()->create_user($user5);
1823         // Add some users as contacts.
1824         \core_message\api::add_contact($user1->id, $user2->id);
1825         \core_message\api::add_contact($user1->id, $user3->id);
1826         \core_message\api::add_contact($user1->id, $user4->id);
1828         // Retrieve the contacts.
1829         $contacts = \core_message\api::get_contacts($user1->id);
1831         // Confirm the data is correct.
1832         $this->assertEquals(3, count($contacts));
1833         usort($contacts, ['static', 'sort_contacts']);
1835         $contact1 = $contacts[0];
1836         $contact2 = $contacts[1];
1837         $contact3 = $contacts[2];
1839         $this->assertEquals($user2->id, $contact1->userid);
1840         $this->assertEmpty($contact1->useridfrom);
1841         $this->assertFalse($contact1->ismessaging);
1842         $this->assertNull($contact1->lastmessage);
1843         $this->assertNull($contact1->messageid);
1844         $this->assertNull($contact1->isonline);
1845         $this->assertFalse($contact1->isread);
1846         $this->assertFalse($contact1->isblocked);
1847         $this->assertNull($contact1->unreadcount);
1849         $this->assertEquals($user3->id, $contact2->userid);
1850         $this->assertEmpty($contact2->useridfrom);
1851         $this->assertFalse($contact2->ismessaging);
1852         $this->assertNull($contact2->lastmessage);
1853         $this->assertNull($contact2->messageid);
1854         $this->assertNull($contact2->isonline);
1855         $this->assertFalse($contact2->isread);
1856         $this->assertFalse($contact2->isblocked);
1857         $this->assertNull($contact2->unreadcount);
1859         $this->assertEquals($user4->id, $contact3->userid);
1860         $this->assertEmpty($contact3->useridfrom);
1861         $this->assertFalse($contact3->ismessaging);
1862         $this->assertNull($contact3->lastmessage);
1863         $this->assertNull($contact3->messageid);
1864         $this->assertNull($contact3->isonline);
1865         $this->assertFalse($contact3->isread);
1866         $this->assertFalse($contact3->isblocked);
1867         $this->assertNull($contact3->unreadcount);
1868     }
1870     /**
1871      * Tests retrieving messages.
1872      */
1873     public function test_get_messages() {
1874         // Create some users.
1875         $user1 = self::getDataGenerator()->create_user();
1876         $user2 = self::getDataGenerator()->create_user();
1878         // The person doing the search.
1879         $this->setUser($user1);
1881         // Send some messages back and forth.
1882         $time = 1;
1883         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
1884         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
1885         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
1886         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
1888         // Retrieve the messages.
1889         $messages = \core_message\api::get_messages($user1->id, $user2->id);
1890         $this->assertDebuggingCalledCount(3);
1892         // Confirm the message data is correct.
1893         $this->assertEquals(4, count($messages));
1895         $message1 = $messages[0];
1896         $message2 = $messages[1];
1897         $message3 = $messages[2];
1898         $message4 = $messages[3];
1900         $this->assertEquals($user1->id, $message1->useridfrom);
1901         $this->assertEquals($user2->id, $message1->useridto);
1902         $this->assertTrue($message1->displayblocktime);
1903         $this->assertContains('Yo!', $message1->text);
1905         $this->assertEquals($user2->id, $message2->useridfrom);
1906         $this->assertEquals($user1->id, $message2->useridto);
1907         $this->assertFalse($message2->displayblocktime);
1908         $this->assertContains('Sup mang?', $message2->text);
1910         $this->assertEquals($user1->id, $message3->useridfrom);
1911         $this->assertEquals($user2->id, $message3->useridto);
1912         $this->assertFalse($message3->displayblocktime);
1913         $this->assertContains('Writing PHPUnit tests!', $message3->text);
1915         $this->assertEquals($user2->id, $message4->useridfrom);
1916         $this->assertEquals($user1->id, $message4->useridto);
1917         $this->assertFalse($message4->displayblocktime);
1918         $this->assertContains('Word.', $message4->text);
1919     }
1921     /**
1922      * Tests retrieving conversation messages.
1923      */
1924     public function test_get_conversation_messages() {
1925         // Create some users.
1926         $user1 = self::getDataGenerator()->create_user();
1927         $user2 = self::getDataGenerator()->create_user();
1929         // Create conversation.
1930         $conversation = \core_message\api::create_conversation(
1931             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1932             [$user1->id, $user2->id]
1933         );
1935         // The person doing the search.
1936         $this->setUser($user1);
1938         // Send some messages back and forth.
1939         $time = 1;
1940         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
1941         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
1942         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
1943         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 4);
1945         // Retrieve the messages.
1946         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id);
1948         // Confirm the conversation id is correct.
1949         $this->assertEquals($conversation->id, $convmessages['id']);
1951         // Confirm the message data is correct.
1952         $messages = $convmessages['messages'];
1953         $this->assertEquals(4, count($messages));
1954         $message1 = $messages[0];
1955         $message2 = $messages[1];
1956         $message3 = $messages[2];
1957         $message4 = $messages[3];
1959         $this->assertEquals($user1->id, $message1->useridfrom);
1960         $this->assertContains('Yo!', $message1->text);
1962         $this->assertEquals($user2->id, $message2->useridfrom);
1963         $this->assertContains('Sup mang?', $message2->text);
1965         $this->assertEquals($user1->id, $message3->useridfrom);
1966         $this->assertContains('Writing PHPUnit tests!', $message3->text);
1968         $this->assertEquals($user1->id, $message4->useridfrom);
1969         $this->assertContains('Word.', $message4->text);
1971         // Confirm the members data is correct.
1972         $members = $convmessages['members'];
1973         $this->assertEquals(2, count($members));
1974     }
1976     /**
1977      * Tests retrieving group conversation messages.
1978      */
1979     public function test_get_group_conversation_messages() {
1980         // Create some users.
1981         $user1 = self::getDataGenerator()->create_user();
1982         $user2 = self::getDataGenerator()->create_user();
1983         $user3 = self::getDataGenerator()->create_user();
1984         $user4 = self::getDataGenerator()->create_user();
1986         // Create group conversation.
1987         $conversation = \core_message\api::create_conversation(
1988             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
1989             [$user1->id, $user2->id, $user3->id, $user4->id]
1990         );
1992         // The person doing the search.
1993         $this->setUser($user1);
1995         // Send some messages back and forth.
1996         $time = 1;
1997         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
1998         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
1999         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
2000         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 4);
2001         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Yeah!', $time + 5);
2003         // Retrieve the messages.
2004         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id);
2006         // Confirm the conversation id is correct.
2007         $this->assertEquals($conversation->id, $convmessages['id']);
2009         // Confirm the message data is correct.
2010         $messages = $convmessages['messages'];
2011         $this->assertEquals(5, count($messages));
2013         $message1 = $messages[0];
2014         $message2 = $messages[1];
2015         $message3 = $messages[2];
2016         $message4 = $messages[3];
2017         $message5 = $messages[4];
2019         $this->assertEquals($user1->id, $message1->useridfrom);
2020         $this->assertContains('Yo!', $message1->text);
2022         $this->assertEquals($user2->id, $message2->useridfrom);
2023         $this->assertContains('Sup mang?', $message2->text);
2025         $this->assertEquals($user3->id, $message3->useridfrom);
2026         $this->assertContains('Writing PHPUnit tests!', $message3->text);
2028         $this->assertEquals($user1->id, $message4->useridfrom);
2029         $this->assertContains('Word.', $message4->text);
2031         $this->assertEquals($user2->id, $message5->useridfrom);
2032         $this->assertContains('Yeah!', $message5->text);
2034         // Confirm the members data is correct.
2035         $members = $convmessages['members'];
2036         $this->assertEquals(3, count($members));
2037     }
2039     /**
2040      * Test verifying the sorting param for get_conversation_messages is respected().
2041      */
2042     public function test_get_conversation_messages_sorting() {
2043         // Create some users.
2044         $user1 = self::getDataGenerator()->create_user();
2045         $user2 = self::getDataGenerator()->create_user();
2046         $user3 = self::getDataGenerator()->create_user();
2048         // Create conversations - 1 group and 1 individual.
2049         $conversation = \core_message\api::create_conversation(
2050             \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2051             [$user1->id, $user2->id]
2052         );
2053         $conversation2 = \core_message\api::create_conversation(
2054             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2055             [$user1->id, $user2->id, $user3->id]
2056         );
2058         // Send some messages back and forth.
2059         $time = 1;
2060         $m1id = testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
2061         $m2id = testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
2062         $m3id = testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
2063         $m4id = testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Word.', $time + 4);
2065         $gm1id = testhelper::send_fake_message_to_conversation($user1, $conversation2->id, 'Yo!', $time + 1);
2066         $gm2id = testhelper::send_fake_message_to_conversation($user2, $conversation2->id, 'Sup mang?', $time + 2);
2067         $gm3id = testhelper::send_fake_message_to_conversation($user3, $conversation2->id, 'Writing PHPUnit tests!', $time + 3);
2068         $gm4id = testhelper::send_fake_message_to_conversation($user1, $conversation2->id, 'Word.', $time + 4);
2070         // The person doing the search.
2071         $this->setUser($user1);
2073         // Retrieve the messages using default sort ('timecreated ASC') and verify ordering.
2074         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id);
2075         $messages = $convmessages['messages'];
2076         $this->assertEquals($m1id, $messages[0]->id);
2077         $this->assertEquals($m2id, $messages[1]->id);
2078         $this->assertEquals($m3id, $messages[2]->id);
2079         $this->assertEquals($m4id, $messages[3]->id);
2081         // Retrieve the messages without specifying DESC sort ordering, and verify ordering.
2082         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated DESC');
2083         $messages = $convmessages['messages'];
2084         $this->assertEquals($m1id, $messages[3]->id);
2085         $this->assertEquals($m2id, $messages[2]->id);
2086         $this->assertEquals($m3id, $messages[1]->id);
2087         $this->assertEquals($m4id, $messages[0]->id);
2089         // Retrieve the messages using default sort ('timecreated ASC') and verify ordering.
2090         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation2->id);
2091         $messages = $convmessages['messages'];
2092         $this->assertEquals($gm1id, $messages[0]->id);
2093         $this->assertEquals($gm2id, $messages[1]->id);
2094         $this->assertEquals($gm3id, $messages[2]->id);
2095         $this->assertEquals($gm4id, $messages[3]->id);
2097         // Retrieve the messages without specifying DESC sort ordering, and verify ordering.
2098         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation2->id, 0, 0, 'timecreated DESC');
2099         $messages = $convmessages['messages'];
2100         $this->assertEquals($gm1id, $messages[3]->id);
2101         $this->assertEquals($gm2id, $messages[2]->id);
2102         $this->assertEquals($gm3id, $messages[1]->id);
2103         $this->assertEquals($gm4id, $messages[0]->id);
2104     }
2106     /**
2107      * Test retrieving conversation messages by providing a minimum timecreated value.
2108      */
2109     public function test_get_conversation_messages_time_from_only() {
2110         // Create some users.
2111         $user1 = self::getDataGenerator()->create_user();
2112         $user2 = self::getDataGenerator()->create_user();
2113         $user3 = self::getDataGenerator()->create_user();
2114         $user4 = self::getDataGenerator()->create_user();
2116         // Create group conversation.
2117         $conversation = \core_message\api::create_conversation(
2118             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2119             [$user1->id, $user2->id, $user3->id, $user4->id]
2120         );
2122         // The person doing the search.
2123         $this->setUser($user1);
2125         // Send some messages back and forth.
2126         $time = 1;
2127         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2128         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2129         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2130         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2132         // Retrieve the messages from $time, which should be all of them.
2133         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated ASC', $time);
2135         // Confirm the conversation id is correct.
2136         $this->assertEquals($conversation->id, $convmessages['id']);
2138         // Confirm the message data is correct.
2139         $messages = $convmessages['messages'];
2140         $this->assertEquals(4, count($messages));
2142         $message1 = $messages[0];
2143         $message2 = $messages[1];
2144         $message3 = $messages[2];
2145         $message4 = $messages[3];
2147         $this->assertContains('Message 1', $message1->text);
2148         $this->assertContains('Message 2', $message2->text);
2149         $this->assertContains('Message 3', $message3->text);
2150         $this->assertContains('Message 4', $message4->text);
2152         // Confirm the members data is correct.
2153         $members = $convmessages['members'];
2154         $this->assertEquals(3, count($members));
2156         // Retrieve the messages from $time + 3, which should only be the 2 last messages.
2157         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0,
2158             'timecreated ASC', $time + 3);
2160         // Confirm the conversation id is correct.
2161         $this->assertEquals($conversation->id, $convmessages['id']);
2163         // Confirm the message data is correct.
2164         $messages = $convmessages['messages'];
2165         $this->assertEquals(2, count($messages));
2167         $message1 = $messages[0];
2168         $message2 = $messages[1];
2170         $this->assertContains('Message 3', $message1->text);
2171         $this->assertContains('Message 4', $message2->text);
2173         // Confirm the members data is correct.
2174         $members = $convmessages['members'];
2175         $this->assertEquals(2, count($members));
2176     }
2178     /**
2179      * Test retrieving conversation messages by providing a maximum timecreated value.
2180      */
2181     public function test_get_conversation_messages_time_to_only() {
2182         // Create some users.
2183         $user1 = self::getDataGenerator()->create_user();
2184         $user2 = self::getDataGenerator()->create_user();
2185         $user3 = self::getDataGenerator()->create_user();
2186         $user4 = self::getDataGenerator()->create_user();
2188         // Create group conversation.
2189         $conversation = \core_message\api::create_conversation(
2190             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2191             [$user1->id, $user2->id, $user3->id, $user4->id]
2192         );
2194         // The person doing the search.
2195         $this->setUser($user1);
2197         // Send some messages back and forth.
2198         $time = 1;
2199         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2200         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2201         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2202         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2204         // Retrieve the messages up until $time + 4, which should be all of them.
2205         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated ASC',
2206             0, $time + 4);
2208         // Confirm the conversation id is correct.
2209         $this->assertEquals($conversation->id, $convmessages['id']);
2211         // Confirm the message data is correct.
2212         $messages = $convmessages['messages'];
2213         $this->assertEquals(4, count($messages));
2215         $message1 = $messages[0];
2216         $message2 = $messages[1];
2217         $message3 = $messages[2];
2218         $message4 = $messages[3];
2220         $this->assertContains('Message 1', $message1->text);
2221         $this->assertContains('Message 2', $message2->text);
2222         $this->assertContains('Message 3', $message3->text);
2223         $this->assertContains('Message 4', $message4->text);
2225         // Confirm the members data is correct.
2226         $members = $convmessages['members'];
2227         $this->assertEquals(3, count($members));
2229         // Retrieve the messages up until $time + 2, which should be the first two.
2230         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0, 'timecreated ASC',
2231             0, $time + 2);
2233         // Confirm the conversation id is correct.
2234         $this->assertEquals($conversation->id, $convmessages['id']);
2236         // Confirm the message data is correct.
2237         $messages = $convmessages['messages'];
2238         $this->assertEquals(2, count($messages));
2240         $message1 = $messages[0];
2241         $message2 = $messages[1];
2243         $this->assertContains('Message 1', $message1->text);
2244         $this->assertContains('Message 2', $message2->text);
2246         // Confirm the members data is correct.
2247         $members = $convmessages['members'];
2248         $this->assertEquals(2, count($members));
2249     }
2251     /**
2252      * Test retrieving conversation messages by providing a minimum and maximum timecreated value.
2253      */
2254     public function test_get_conversation_messages_time_from_and_to() {
2255         // Create some users.
2256         $user1 = self::getDataGenerator()->create_user();
2257         $user2 = self::getDataGenerator()->create_user();
2258         $user3 = self::getDataGenerator()->create_user();
2259         $user4 = self::getDataGenerator()->create_user();
2261         // Create group conversation.
2262         $conversation = \core_message\api::create_conversation(
2263             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2264             [$user1->id, $user2->id, $user3->id, $user4->id]
2265         );
2267         // The person doing the search.
2268         $this->setUser($user1);
2270         // Send some messages back and forth.
2271         $time = 1;
2272         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2273         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2274         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2275         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2277         // Retrieve the messages from $time + 2 up until $time + 3, which should be 2nd and 3rd message.
2278         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 0, 0,
2279             'timecreated ASC', $time + 2, $time + 3);
2281         // Confirm the conversation id is correct.
2282         $this->assertEquals($conversation->id, $convmessages['id']);
2284         // Confirm the message data is correct.
2285         $messages = $convmessages['messages'];
2286         $this->assertEquals(2, count($messages));
2288         $message1 = $messages[0];
2289         $message2 = $messages[1];
2291         $this->assertContains('Message 2', $message1->text);
2292         $this->assertContains('Message 3', $message2->text);
2294         // Confirm the members data is correct.
2295         $members = $convmessages['members'];
2296         $this->assertEquals(2, count($members));
2297     }
2300     /**
2301      * Test retrieving conversation messages by providing a limitfrom value.
2302      */
2303     public function test_get_conversation_messages_limitfrom_only() {
2304         // Create some users.
2305         $user1 = self::getDataGenerator()->create_user();
2306         $user2 = self::getDataGenerator()->create_user();
2307         $user3 = self::getDataGenerator()->create_user();
2308         $user4 = self::getDataGenerator()->create_user();
2310         // Create group conversation.
2311         $conversation = \core_message\api::create_conversation(
2312             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2313             [$user1->id, $user2->id, $user3->id, $user4->id]
2314         );
2316         // The person doing the search.
2317         $this->setUser($user1);
2319         // Send some messages back and forth.
2320         $time = 1;
2321         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2322         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2323         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2324         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2326         // Retrieve the messages from $time, which should be all of them.
2327         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 2);
2329         // Confirm the conversation id is correct.
2330         $messages = $convmessages['messages'];
2331         $this->assertEquals($conversation->id, $convmessages['id']);
2333         // Confirm the message data is correct.
2334         $this->assertEquals(2, count($messages));
2336         $message1 = $messages[0];
2337         $message2 = $messages[1];
2339         $this->assertContains('Message 3', $message1->text);
2340         $this->assertContains('Message 4', $message2->text);
2342         // Confirm the members data is correct.
2343         $members = $convmessages['members'];
2344         $this->assertEquals(2, count($members));
2345     }
2347     /**
2348      * Test retrieving conversation messages by providing a limitnum value.
2349      */
2350     public function test_get_conversation_messages_limitnum() {
2351         // Create some users.
2352         $user1 = self::getDataGenerator()->create_user();
2353         $user2 = self::getDataGenerator()->create_user();
2354         $user3 = self::getDataGenerator()->create_user();
2355         $user4 = self::getDataGenerator()->create_user();
2357         // Create group conversation.
2358         $conversation = \core_message\api::create_conversation(
2359             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2360             [$user1->id, $user2->id, $user3->id, $user4->id]
2361         );
2363         // The person doing the search.
2364         $this->setUser($user1);
2366         // Send some messages back and forth.
2367         $time = 1;
2368         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 1', $time + 1);
2369         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Message 2', $time + 2);
2370         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Message 3', $time + 3);
2371         testhelper::send_fake_message_to_conversation($user3, $conversation->id, 'Message 4', $time + 4);
2373         // Retrieve the messages from $time, which should be all of them.
2374         $convmessages = \core_message\api::get_conversation_messages($user1->id, $conversation->id, 2, 1);
2376         // Confirm the conversation id is correct.
2377         $messages = $convmessages['messages'];
2378         $this->assertEquals($conversation->id, $convmessages['id']);
2380         // Confirm the message data is correct.
2381         $messages = $convmessages['messages'];
2382         $this->assertEquals(1, count($messages));
2384         $message1 = $messages[0];
2386         $this->assertContains('Message 3', $message1->text);
2388         // Confirm the members data is correct.
2389         $members = $convmessages['members'];
2390         $this->assertEquals(1, count($members));
2391     }
2393     /**
2394      * Tests retrieving most recent message.
2395      */
2396     public function test_get_most_recent_message() {
2397         // Create some users.
2398         $user1 = self::getDataGenerator()->create_user();
2399         $user2 = self::getDataGenerator()->create_user();
2401         // The person doing the search.
2402         $this->setUser($user1);
2404         // Send some messages back and forth.
2405         $time = 1;
2406         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2407         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2408         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2409         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2411         // Retrieve the most recent messages.
2412         $message = \core_message\api::get_most_recent_message($user1->id, $user2->id);
2413         $this->assertDebuggingCalledCount(3);
2415         // Check the results are correct.
2416         $this->assertEquals($user2->id, $message->useridfrom);
2417         $this->assertEquals($user1->id, $message->useridto);
2418         $this->assertContains('Word.', $message->text);
2419     }
2421     /**
2422      * Tests retrieving most recent conversation message.
2423      */
2424     public function test_get_most_recent_conversation_message() {
2425         // Create some users.
2426         $user1 = self::getDataGenerator()->create_user();
2427         $user2 = self::getDataGenerator()->create_user();
2428         $user3 = self::getDataGenerator()->create_user();
2430         // Create group conversation.
2431         $conversation = \core_message\api::create_conversation(
2432             \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2433             [$user1->id, $user2->id, $user3->id]
2434         );
2436         // The person getting the most recent conversation message.
2437         $this->setUser($user1);
2439         // Send some messages back and forth.
2440         $time = 1;
2441         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Yo!', $time + 1);
2442         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Sup mang?', $time + 2);
2443         testhelper::send_fake_message_to_conversation($user1, $conversation->id, 'Writing PHPUnit tests!', $time + 3);
2444         testhelper::send_fake_message_to_conversation($user2, $conversation->id, 'Word.', $time + 4);
2446         // Retrieve the most recent messages.
2447         $message = \core_message\api::get_most_recent_conversation_message($conversation->id, $user1->id);
2449         // Check the results are correct.
2450         $this->assertEquals($user2->id, $message->useridfrom);
2451         $this->assertContains('Word.', $message->text);
2452     }
2454     /**
2455      * Tests retrieving a user's profile.
2456      */
2457     public function test_get_profile() {
2458         // Create some users.
2459         $user1 = self::getDataGenerator()->create_user();
2461         $user2 = new stdClass();
2462         $user2->country = 'AU';
2463         $user2->city = 'Perth';
2464         $user2 = self::getDataGenerator()->create_user($user2);
2466         // The person doing the search.
2467         $this->setUser($user1);
2469         // Get the profile.
2470         $profile = \core_message\api::get_profile($user1->id, $user2->id);
2472         $this->assertEquals($user2->id, $profile->userid);
2473         $this->assertEmpty($profile->email);
2474         $this->assertEmpty($profile->country);
2475         $this->assertEmpty($profile->city);
2476         $this->assertEquals(fullname($user2), $profile->fullname);
2477         $this->assertNull($profile->isonline);
2478         $this->assertFalse($profile->isblocked);
2479         $this->assertFalse($profile->iscontact);
2480     }
2482     /**
2483      * Tests retrieving a user's profile.
2484      */
2485     public function test_get_profile_as_admin() {
2486         // The person doing the search.
2487         $this->setAdminUser();
2489         // Create some users.
2490         $user1 = self::getDataGenerator()->create_user();
2492         $user2 = new stdClass();
2493         $user2->country = 'AU';
2494         $user2->city = 'Perth';
2495         $user2 = self::getDataGenerator()->create_user($user2);
2497         // Get the profile.
2498         $profile = \core_message\api::get_profile($user1->id, $user2->id);
2500         $this->assertEquals($user2->id, $profile->userid);
2501         $this->assertEquals($user2->email, $profile->email);
2502         $this->assertEquals($user2->country, $profile->country);
2503         $this->assertEquals($user2->city, $profile->city);
2504         $this->assertEquals(fullname($user2), $profile->fullname);
2505         $this->assertFalse($profile->isonline);
2506         $this->assertFalse($profile->isblocked);
2507         $this->assertFalse($profile->iscontact);
2508     }
2510     /**
2511      * Tests checking if a user can mark all messages as read.
2512      */
2513     public function test_can_mark_all_messages_as_read() {
2514         // Set as the admin.
2515         $this->setAdminUser();
2517         // Create some users.
2518         $user1 = self::getDataGenerator()->create_user();
2519         $user2 = self::getDataGenerator()->create_user();
2520         $user3 = self::getDataGenerator()->create_user();
2522         // Send some messages back and forth.
2523         $time = 1;
2524         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2525         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2526         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2527         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2529         $conversationid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2531         // The admin can do anything.
2532         $this->assertTrue(\core_message\api::can_mark_all_messages_as_read($user1->id, $conversationid));
2534         // Set as the user 1.
2535         $this->setUser($user1);
2537         // The user can mark the messages as he is in the conversation.
2538         $this->assertTrue(\core_message\api::can_mark_all_messages_as_read($user1->id, $conversationid));
2540         // User 1 can not mark the messages read for user 2.
2541         $this->assertFalse(\core_message\api::can_mark_all_messages_as_read($user2->id, $conversationid));
2543         // This user is not a part of the conversation.
2544         $this->assertFalse(\core_message\api::can_mark_all_messages_as_read($user3->id, $conversationid));
2545     }
2547     /**
2548      * Tests checking if a user can delete a conversation.
2549      */
2550     public function test_can_delete_conversation() {
2551         // Set as the admin.
2552         $this->setAdminUser();
2554         // Create some users.
2555         $user1 = self::getDataGenerator()->create_user();
2556         $user2 = self::getDataGenerator()->create_user();
2558         // Send some messages back and forth.
2559         $time = 1;
2560         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2561         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2562         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2563         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2565         $conversationid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2567         // The admin can do anything.
2568         $this->assertTrue(\core_message\api::can_delete_conversation($user1->id, $conversationid));
2570         // Set as the user 1.
2571         $this->setUser($user1);
2573         // They can delete their own messages.
2574         $this->assertTrue(\core_message\api::can_delete_conversation($user1->id, $conversationid));
2576         // They can't delete someone elses.
2577         $this->assertFalse(\core_message\api::can_delete_conversation($user2->id, $conversationid));
2578     }
2580     /**
2581      * Tests deleting a conversation.
2582      */
2583     public function test_delete_conversation() {
2584         global $DB;
2586         // Create some users.
2587         $user1 = self::getDataGenerator()->create_user();
2588         $user2 = self::getDataGenerator()->create_user();
2590         // The person doing the search.
2591         $this->setUser($user1);
2593         // Send some messages back and forth.
2594         $time = 1;
2595         $m1id = $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2596         $m2id = $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2597         $m3id = $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2598         $m4id = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2600         // Delete the conversation as user 1.
2601         \core_message\api::delete_conversation($user1->id, $user2->id);
2602         $this->assertDebuggingCalled();
2604         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
2605         $this->assertCount(4, $muas);
2606         // Sort by id.
2607         ksort($muas);
2609         $mua1 = array_shift($muas);
2610         $mua2 = array_shift($muas);
2611         $mua3 = array_shift($muas);
2612         $mua4 = array_shift($muas);
2614         $this->assertEquals($user1->id, $mua1->userid);
2615         $this->assertEquals($m1id, $mua1->messageid);
2616         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
2618         $this->assertEquals($user1->id, $mua2->userid);
2619         $this->assertEquals($m2id, $mua2->messageid);
2620         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
2622         $this->assertEquals($user1->id, $mua3->userid);
2623         $this->assertEquals($m3id, $mua3->messageid);
2624         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
2626         $this->assertEquals($user1->id, $mua4->userid);
2627         $this->assertEquals($m4id, $mua4->messageid);
2628         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
2629     }
2631     /**
2632      * Tests deleting a conversation by conversation id.
2633      */
2634     public function test_delete_conversation_by_id() {
2635         global $DB;
2637         // Create some users.
2638         $user1 = self::getDataGenerator()->create_user();
2639         $user2 = self::getDataGenerator()->create_user();
2641         // The person doing the search.
2642         $this->setUser($user1);
2644         // Send some messages back and forth.
2645         $time = 1;
2646         $m1id = $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
2647         $m2id = $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
2648         $m3id = $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
2649         $m4id = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
2651         // Delete the conversation as user 1.
2652         $conversationid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2653         \core_message\api::delete_conversation_by_id($user1->id, $conversationid);
2655         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
2656         $this->assertCount(4, $muas);
2657         // Sort by id.
2658         ksort($muas);
2660         $mua1 = array_shift($muas);
2661         $mua2 = array_shift($muas);
2662         $mua3 = array_shift($muas);
2663         $mua4 = array_shift($muas);
2665         $this->assertEquals($user1->id, $mua1->userid);
2666         $this->assertEquals($m1id, $mua1->messageid);
2667         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
2669         $this->assertEquals($user1->id, $mua2->userid);
2670         $this->assertEquals($m2id, $mua2->messageid);
2671         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
2673         $this->assertEquals($user1->id, $mua3->userid);
2674         $this->assertEquals($m3id, $mua3->messageid);
2675         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
2677         $this->assertEquals($user1->id, $mua4->userid);
2678         $this->assertEquals($m4id, $mua4->messageid);
2679         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
2680     }
2682     /**
2683      * Tests counting unread conversations.
2684      */
2685     public function test_count_unread_conversations() {
2686         $this->resetAfterTest(true);
2688         // Create some users.
2689         $user1 = self::getDataGenerator()->create_user();
2690         $user2 = self::getDataGenerator()->create_user();
2691         $user3 = self::getDataGenerator()->create_user();
2692         $user4 = self::getDataGenerator()->create_user();
2694         // The person wanting the conversation count.
2695         $this->setUser($user1);
2697         // Send some messages back and forth, have some different conversations with different users.
2698         $this->send_fake_message($user1, $user2, 'Yo!');
2699         $this->send_fake_message($user2, $user1, 'Sup mang?');
2700         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!');
2701         $this->send_fake_message($user2, $user1, 'Word.');
2703         $this->send_fake_message($user1, $user3, 'Booyah');
2704         $this->send_fake_message($user3, $user1, 'Whaaat?');
2705         $this->send_fake_message($user1, $user3, 'Nothing.');
2706         $this->send_fake_message($user3, $user1, 'Cool.');
2708         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
2709         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
2710         $this->send_fake_message($user1, $user4, 'Dope.');
2712         // Check the amount for the current user.
2713         $this->assertEquals(3, core_message\api::count_unread_conversations());
2715         // Check the amount for the second user.
2716         $this->assertEquals(1, core_message\api::count_unread_conversations($user2));
2717     }
2719     /**
2720      * Tests deleting a conversation.
2721      */
2722     public function test_get_all_message_preferences() {
2723         $user = self::getDataGenerator()->create_user();
2724         $this->setUser($user);
2726         // Set a couple of preferences to test.
2727         set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
2728         set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
2730         $processors = get_message_processors();
2731         $providers = message_get_providers_for_user($user->id);
2732         $prefs = \core_message\api::get_all_message_preferences($processors, $providers, $user);
2734         $this->assertEquals(1, $prefs->mod_assign_assign_notification_loggedin['popup']);
2735         $this->assertEquals(1, $prefs->mod_assign_assign_notification_loggedoff['email']);
2736     }
2738     /**
2739      * Tests the user can post a message.
2740      */
2741     public function test_can_post_message() {
2742         // Create some users.
2743         $user1 = self::getDataGenerator()->create_user();
2744         $user2 = self::getDataGenerator()->create_user();
2746         // Set as the first user.
2747         $this->setUser($user1);
2749         // With the default privacy setting, users can't message them.
2750         $this->assertFalse(\core_message\api::can_post_message($user2));
2752         // Enrol users to the same course.
2753         $course = $this->getDataGenerator()->create_course();
2754         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
2755         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
2756         // After enrolling users to the course, they should be able to message them with the default privacy setting.
2757         $this->assertTrue(\core_message\api::can_post_message($user2));
2758     }
2760     /**
2761      * Tests the user can't post a message without proper capability.
2762      */
2763     public function test_can_post_message_without_sendmessage_cap() {
2764         global $DB;
2766         // Create some users.
2767         $user1 = self::getDataGenerator()->create_user();
2768         $user2 = self::getDataGenerator()->create_user();
2770         // Set as the user 1.
2771         $this->setUser($user1);
2773         // Remove the capability to send a message.
2774         $roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
2775         unassign_capability('moodle/site:sendmessage', $roleids['user'],
2776             context_system::instance());
2778         // Check that we can not post a message without the capability.
2779         $this->assertFalse(\core_message\api::can_post_message($user2));
2780     }
2782     /**
2783      * Tests the user can post a message when they are contact.
2784      */
2785     public function test_can_post_message_when_contact() {
2786         // Create some users.
2787         $user1 = self::getDataGenerator()->create_user();
2788         $user2 = self::getDataGenerator()->create_user();
2790         // Set as the first user.
2791         $this->setUser($user1);
2793         // Check that we can not send user2 a message.
2794         $this->assertFalse(\core_message\api::can_post_message($user2));
2796         // Add users as contacts.
2797         \core_message\api::add_contact($user1->id, $user2->id);
2799         // Check that the return result is now true.
2800         $this->assertTrue(\core_message\api::can_post_message($user2));
2801     }
2803     /**
2804      * Tests the user can't post a message if they are not a contact and the user
2805      * has requested messages only from contacts.
2806      */
2807     public function test_can_post_message_when_not_contact() {
2808         // Create some users.
2809         $user1 = self::getDataGenerator()->create_user();
2810         $user2 = self::getDataGenerator()->create_user();
2812         // Set as the first user.
2813         $this->setUser($user1);
2815         // Set the second user's preference to not receive messages from non-contacts.
2816         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
2818         // Check that we can not send user 2 a message.
2819         $this->assertFalse(\core_message\api::can_post_message($user2));
2820     }
2822     /**
2823      * Tests the user can't post a message if they are blocked.
2824      */
2825     public function test_can_post_message_when_blocked() {
2826         // Create some users.
2827         $user1 = self::getDataGenerator()->create_user();
2828         $user2 = self::getDataGenerator()->create_user();
2830         // Set the user.
2831         $this->setUser($user1);
2833         // Block the second user.
2834         \core_message\api::block_user($user1->id, $user2->id);
2836         // Check that the second user can no longer send the first user a message.
2837         $this->assertFalse(\core_message\api::can_post_message($user1, $user2));
2838     }
2840     /**
2841      * Tests the user can post a message when site-wide messaging setting is enabled,
2842      * even if they are not a contact and are not members of the same course.
2843      */
2844     public function test_can_post_message_site_messaging_setting() {
2845         // Create some users.
2846         $user1 = self::getDataGenerator()->create_user();
2847         $user2 = self::getDataGenerator()->create_user();
2849         // Set as the first user.
2850         $this->setUser($user1);
2852         // By default, user only can be messaged by contacts and members of any of his/her courses.
2853         $this->assertFalse(\core_message\api::can_post_message($user2));
2855         // Enable site-wide messagging privacy setting. The user will be able to receive messages from everybody.
2856         set_config('messagingallusers', true);
2858         // Set the second user's preference to receive messages from everybody.
2859         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_SITE, $user2->id);
2861         // Check that we can send user2 a message.
2862         $this->assertTrue(\core_message\api::can_post_message($user2));
2864         // Disable site-wide messagging privacy setting. The user will be able to receive messages from contacts
2865         // and members sharing a course with her.
2866         set_config('messagingallusers', false);
2868         // As site-wide messaging setting is disabled, the value for user2 will be changed to MESSAGE_PRIVACY_COURSEMEMBER.
2869         $this->assertFalse(\core_message\api::can_post_message($user2));
2871         // Enrol users to the same course.
2872         $course = $this->getDataGenerator()->create_course();
2873         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
2874         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
2875         // Check that we can send user2 a message because they are sharing a course.
2876         $this->assertTrue(\core_message\api::can_post_message($user2));
2878         // Set the second user's preference to receive messages only from contacts.
2879         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
2880         // Check that now the user2 can't be contacted because user1 is not their contact.
2881         $this->assertFalse(\core_message\api::can_post_message($user2));
2883         // Make contacts user1 and user2.
2884         \core_message\api::add_contact($user2->id, $user1->id);
2885         // Check that we can send user2 a message because they are contacts.
2886         $this->assertTrue(\core_message\api::can_post_message($user2));
2887     }
2889     /**
2890      * Tests the user with the messageanyuser capability can post a message.
2891      */
2892     public function test_can_post_message_with_messageanyuser_cap() {
2893         global $DB;
2895         // Create some users.
2896         $teacher1 = self::getDataGenerator()->create_user();
2897         $student1 = self::getDataGenerator()->create_user();
2898         $student2 = self::getDataGenerator()->create_user();
2900         // Create users not enrolled in any course.
2901         $user1 = self::getDataGenerator()->create_user();
2903         // Create a course.
2904         $course1 = $this->getDataGenerator()->create_course();
2906         // Enrol the users in the course.
2907         $this->getDataGenerator()->enrol_user($teacher1->id, $course1->id, 'editingteacher');
2908         $this->getDataGenerator()->enrol_user($student1->id, $course1->id, 'student');
2909         $this->getDataGenerator()->enrol_user($student2->id, $course1->id, 'student');
2911         // Set some student preferences to not receive messages from non-contacts.
2912         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $student1->id);
2914         // Check that we can send student1 a message because teacher has the messageanyuser cap by default.
2915         $this->assertTrue(\core_message\api::can_post_message($student1, $teacher1));
2916         // Check that the teacher can't contact user1 because it's not his teacher.
2917         $this->assertFalse(\core_message\api::can_post_message($user1, $teacher1));
2919         // Remove the messageanyuser capability from the course1 for teachers.
2920         $coursecontext = context_course::instance($course1->id);
2921         $teacherrole = $DB->get_record('role', ['shortname' => 'editingteacher']);
2922         assign_capability('moodle/site:messageanyuser', CAP_PROHIBIT, $teacherrole->id, $coursecontext->id);
2923         $coursecontext->mark_dirty();
2925         // Check that we can't send user1 a message because they are not contacts.
2926         $this->assertFalse(\core_message\api::can_post_message($student1, $teacher1));
2927         // However, teacher can message student2 because they are sharing a course.
2928         $this->assertTrue(\core_message\api::can_post_message($student2, $teacher1));
2929     }
2931     /**
2932      * Tests get_user_privacy_messaging_preference method.
2933      */
2934     public function test_get_user_privacy_messaging_preference() {
2935         // Create some users.
2936         $user1 = self::getDataGenerator()->create_user();
2937         $user2 = self::getDataGenerator()->create_user();
2938         $user3 = self::getDataGenerator()->create_user();
2940         // Enable site-wide messagging privacy setting. The user will be able to receive messages from everybody.
2941         set_config('messagingallusers', true);
2943         // Set some user preferences.
2944         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_SITE, $user1->id);
2945         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
2947         // Check the returned value for each user.
2948         $this->assertEquals(
2949             \core_message\api::MESSAGE_PRIVACY_SITE,
2950             \core_message\api::get_user_privacy_messaging_preference($user1->id)
2951         );
2952         $this->assertEquals(
2953             \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
2954             \core_message\api::get_user_privacy_messaging_preference($user2->id)
2955         );
2956         $this->assertEquals(
2957             \core_message\api::MESSAGE_PRIVACY_SITE,
2958             \core_message\api::get_user_privacy_messaging_preference($user3->id)
2959         );
2961         // Disable site-wide messagging privacy setting. The user will be able to receive messages from members of their course.
2962         set_config('messagingallusers', false);
2964         // Check the returned value for each user.
2965         $this->assertEquals(
2966             \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
2967             \core_message\api::get_user_privacy_messaging_preference($user1->id)
2968         );
2969         $this->assertEquals(
2970             \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
2971             \core_message\api::get_user_privacy_messaging_preference($user2->id)
2972         );
2973         $this->assertEquals(
2974             \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
2975             \core_message\api::get_user_privacy_messaging_preference($user3->id)
2976         );
2977     }
2979     /**
2980      * Tests that when blocking messages from non-contacts is enabled that
2981      * non-contacts trying to send a message return false.
2982      */
2983     public function test_is_user_non_contact_blocked() {
2984         // Create some users.
2985         $user1 = self::getDataGenerator()->create_user();
2986         $user2 = self::getDataGenerator()->create_user();
2988         // Set as the first user.
2989         $this->setUser($user1);
2991         // By default, user only can be messaged by contacts and members of any of his/her courses.
2992         $this->assertTrue(\core_message\api::is_user_non_contact_blocked($user2));
2993         $this->assertDebuggingCalled();
2995         // Enable all users privacy messaging and check now the default user's preference has been set to allow receiving
2996         // messages from everybody.
2997         set_config('messagingallusers', true);
2998         // Check that the return result is now false because any site user can contact him/her.
2999         $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
3000         $this->assertDebuggingCalled();
3002         // Set the second user's preference to not receive messages from non-contacts.
3003         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
3004         // Check that the return result is still true (because is even more restricted).
3005         $this->assertTrue(\core_message\api::is_user_non_contact_blocked($user2));
3006         $this->assertDebuggingCalled();
3008         // Add the first user as a contact for the second user.
3009         \core_message\api::add_contact($user2->id, $user1->id);
3011         // Check that the return result is now false.
3012         $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
3013         $this->assertDebuggingCalled();
3015         // Set the second user's preference to receive messages from course members.
3016         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER, $user2->id);
3017         // Check that the return result is still false (because $user1 is still his/her contact).
3018         $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
3019         $this->assertDebuggingCalled();
3020     }
3022     /**
3023      * Tests that we return true when a user is blocked, or false
3024      * if they are not blocked.
3025      */
3026     public function test_is_user_blocked() {
3027         // Create some users.
3028         $user1 = self::getDataGenerator()->create_user();
3029         $user2 = self::getDataGenerator()->create_user();
3031         // Set the user.
3032         $this->setUser($user1);
3034         // User shouldn't be blocked.
3035         $this->assertFalse(\core_message\api::is_user_blocked($user1->id, $user2->id));
3036         $this->assertDebuggingCalled();
3038         // Block the user.
3039         \core_message\api::block_user($user1->id, $user2->id);
3041         // User should be blocked.
3042         $this->assertTrue(\core_message\api::is_user_blocked($user1->id, $user2->id));
3043         $this->assertDebuggingCalled();
3045         // Unblock the user.
3046         \core_message\api::unblock_user($user1->id, $user2->id);
3047         $this->assertFalse(\core_message\api::is_user_blocked($user1->id, $user2->id));
3048         $this->assertDebuggingCalled();
3049     }
3051     /**
3052      * Tests that the admin is not blocked even if someone has chosen to block them.
3053      */
3054     public function test_is_user_blocked_as_admin() {
3055         // Create a user.
3056         $user1 = self::getDataGenerator()->create_user();
3058         // Set the user.
3059         $this->setUser($user1);
3061         // Block the admin user.
3062         \core_message\api::block_user($user1->id, 2);
3064         // Now change to the admin user.
3065         $this->setAdminUser();
3067         // As the admin you should still be able to send messages to the user.
3068         $this->assertFalse(\core_message\api::is_user_blocked($user1->id));
3069         $this->assertDebuggingCalled();
3070     }
3072     /*
3073      * Tes get_message_processor api.
3074      */
3075     public function test_get_message_processor() {
3076         $processors = get_message_processors(true);
3077         if (empty($processors)) {
3078             $this->markTestSkipped("No message processors found");
3079         }
3081         $name = key($processors);
3082         $processor = current($processors);
3083         $testprocessor = \core_message\api::get_message_processor($name);
3084         $this->assertEquals($processor->name, $testprocessor->name);
3085         $this->assertEquals($processor->enabled, $testprocessor->enabled);
3086         $this->assertEquals($processor->available, $testprocessor->available);
3087         $this->assertEquals($processor->configured, $testprocessor->configured);
3089         // Disable processor and test.
3090         \core_message\api::update_processor_status($testprocessor, 0);
3091         $testprocessor = \core_message\api::get_message_processor($name, true);
3092         $this->assertEmpty($testprocessor);
3093         $testprocessor = \core_message\api::get_message_processor($name);
3094         $this->assertEquals($processor->name, $testprocessor->name);
3095         $this->assertEquals(0, $testprocessor->enabled);
3097         // Enable again and test.
3098         \core_message\api::update_processor_status($testprocessor, 1);
3099         $testprocessor = \core_message\api::get_message_processor($name, true);
3100         $this->assertEquals($processor->name, $testprocessor->name);
3101         $this->assertEquals(1, $testprocessor->enabled);
3102         $testprocessor = \core_message\api::get_message_processor($name);
3103         $this->assertEquals($processor->name, $testprocessor->name);
3104         $this->assertEquals(1, $testprocessor->enabled);
3105     }
3107     /**
3108      * Test method update_processor_status.
3109      */
3110     public function test_update_processor_status() {
3111         $processors = get_message_processors();
3112         if (empty($processors)) {
3113             $this->markTestSkipped("No message processors found");
3114         }
3115         $name = key($processors);
3116         $testprocessor = current($processors);
3118         // Enable.
3119         \core_message\api::update_processor_status($testprocessor, 1);
3120         $testprocessor = \core_message\api::get_message_processor($name);
3121         $this->assertEquals(1, $testprocessor->enabled);
3123         // Disable.
3124         \core_message\api::update_processor_status($testprocessor, 0);
3125         $testprocessor = \core_message\api::get_message_processor($name);
3126         $this->assertEquals(0, $testprocessor->enabled);
3128         // Enable again.
3129         \core_message\api::update_processor_status($testprocessor, 1);
3130         $testprocessor = \core_message\api::get_message_processor($name);
3131         $this->assertEquals(1, $testprocessor->enabled);
3132     }
3134     /**
3135      * Test method is_user_enabled.
3136      */
3137     public function is_user_enabled() {
3138         $processors = get_message_processors();
3139         if (empty($processors)) {
3140             $this->markTestSkipped("No message processors found");
3141         }
3142         $name = key($processors);
3143         $testprocessor = current($processors);
3145         // Enable.
3146         \core_message\api::update_processor_status($testprocessor, 1);
3147         $status = \core_message\api::is_processor_enabled($name);
3148         $this->assertEquals(1, $status);
3150         // Disable.
3151         \core_message\api::update_processor_status($testprocessor, 0);
3152         $status = \core_message\api::is_processor_enabled($name);
3153         $this->assertEquals(0, $status);
3155         // Enable again.
3156         \core_message\api::update_processor_status($testprocessor, 1);
3157         $status = \core_message\api::is_processor_enabled($name);
3158         $this->assertEquals(1, $status);
3159     }
3161     /**
3162      * Test retrieving messages by providing a minimum timecreated value.
3163      */
3164     public function test_get_messages_time_from_only() {
3165         // Create some users.
3166         $user1 = self::getDataGenerator()->create_user();
3167         $user2 = self::getDataGenerator()->create_user();
3169         // The person doing the search.
3170         $this->setUser($user1);
3172         // Send some messages back and forth.
3173         $time = 1;
3174         $this->send_fake_message($user1, $user2, 'Message 1', 0, $time + 1);
3175         $this->send_fake_message($user2, $user1, 'Message 2', 0, $time + 2);
3176         $this->send_fake_message($user1, $user2, 'Message 3', 0, $time + 3);
3177         $this->send_fake_message($user2, $user1, 'Message 4', 0, $time + 4);
3179         // Retrieve the messages from $time, which should be all of them.
3180         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', $time);
3181         $this->assertDebuggingCalledCount(3);
3183         // Confirm the message data is correct.
3184         $this->assertEquals(4, count($messages));
3186         $message1 = $messages[0];
3187         $message2 = $messages[1];
3188         $message3 = $messages[2];
3189         $message4 = $messages[3];
3191         $this->assertContains('Message 1', $message1->text);
3192         $this->assertContains('Message 2', $message2->text);
3193         $this->assertContains('Message 3', $message3->text);
3194         $this->assertContains('Message 4', $message4->text);
3196         // Retrieve the messages from $time + 3, which should only be the 2 last messages.
3197         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', $time + 3);
3198         $this->assertDebuggingCalledCount(3);
3200         // Confirm the message data is correct.
3201         $this->assertEquals(2, count($messages));
3203         $message1 = $messages[0];
3204         $message2 = $messages[1];
3206         $this->assertContains('Message 3', $message1->text);
3207         $this->assertContains('Message 4', $message2->text);
3208     }
3210     /**
3211      * Test retrieving messages by providing a maximum timecreated value.
3212      */
3213     public function test_get_messages_time_to_only() {
3214         // Create some users.
3215         $user1 = self::getDataGenerator()->create_user();
3216         $user2 = self::getDataGenerator()->create_user();
3218         // The person doing the search.
3219         $this->setUser($user1);
3221         // Send some messages back and forth.
3222         $time = 1;
3223         $this->send_fake_message($user1, $user2, 'Message 1', 0, $time + 1);
3224         $this->send_fake_message($user2, $user1, 'Message 2', 0, $time + 2);
3225         $this->send_fake_message($user1, $user2, 'Message 3', 0, $time + 3);
3226         $this->send_fake_message($user2, $user1, 'Message 4', 0, $time + 4);
3228         // Retrieve the messages up until $time + 4, which should be all of them.
3229         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', 0, $time + 4);
3230         $this->assertDebuggingCalledCount(3);
3232         // Confirm the message data is correct.
3233         $this->assertEquals(4, count($messages));
3235         $message1 = $messages[0];
3236         $message2 = $messages[1];
3237         $message3 = $messages[2];
3238         $message4 = $messages[3];
3240         $this->assertContains('Message 1', $message1->text);
3241         $this->assertContains('Message 2', $message2->text);
3242         $this->assertContains('Message 3', $message3->text);
3243         $this->assertContains('Message 4', $message4->text);
3245         // Retrieve the messages up until $time + 2, which should be the first two.
3246         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', 0, $time + 2);
3247         $this->assertDebuggingCalledCount(3);
3249         // Confirm the message data is correct.
3250         $this->assertEquals(2, count($messages));
3252         $message1 = $messages[0];
3253         $message2 = $messages[1];
3255         $this->assertContains('Message 1', $message1->text);
3256         $this->assertContains('Message 2', $message2->text);
3257     }
3259     /**
3260      * Test retrieving messages by providing a minimum and maximum timecreated value.
3261      */
3262     public function test_get_messages_time_from_and_to() {
3263         // Create some users.
3264         $user1 = self::getDataGenerator()->create_user();
3265         $user2 = self::getDataGenerator()->create_user();
3267         // The person doing the search.
3268         $this->setUser($user1);
3270         // Send some messages back and forth.
3271         $time = 1;
3272         $this->send_fake_message($user1, $user2, 'Message 1', 0, $time + 1);
3273         $this->send_fake_message($user2, $user1, 'Message 2', 0, $time + 2);
3274         $this->send_fake_message($user1, $user2, 'Message 3', 0, $time + 3);
3275         $this->send_fake_message($user2, $user1, 'Message 4', 0, $time + 4);
3277         // Retrieve the messages from $time + 2 up until $time + 3, which should be 2nd and 3rd message.
3278         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', $time + 2, $time + 3);
3279         $this->assertDebuggingCalledCount(3);
3281         // Confirm the message data is correct.
3282         $this->assertEquals(2, count($messages));
3284         $message1 = $messages[0];
3285         $message2 = $messages[1];
3287         $this->assertContains('Message 2', $message1->text);
3288         $this->assertContains('Message 3', $message2->text);
3289     }
3291     /**
3292      * Test returning blocked users.
3293      */
3294     public function test_get_blocked_users() {
3295         global $USER;
3297         // Set this user as the admin.
3298         $this->setAdminUser();
3300         // Create a user to add to the admin's contact list.
3301         $user1 = $this->getDataGenerator()->create_user();
3302         $user2 = $this->getDataGenerator()->create_user();
3304         // Add users to the admin's contact list.
3305         \core_message\api::block_user($USER->id, $user2->id);
3307         $this->assertCount(1, \core_message\api::get_blocked_users($USER->id));
3309         // Block other user.
3310         \core_message\api::block_user($USER->id, $user1->id);
3311