MDL-63214 message: Add privacy preferences to filter who can message
[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 /**
33  * Test message API.
34  *
35  * @package core_message
36  * @category test
37  * @copyright 2016 Mark Nelson <markn@moodle.com>
38  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39  */
40 class core_message_api_testcase extends core_message_messagelib_testcase {
42     public function test_mark_all_read_for_user_touser() {
43         $sender = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
44         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
46         $this->send_fake_message($sender, $recipient, 'Notification', 1);
47         $this->send_fake_message($sender, $recipient, 'Notification', 1);
48         $this->send_fake_message($sender, $recipient, 'Notification', 1);
49         $this->send_fake_message($sender, $recipient);
50         $this->send_fake_message($sender, $recipient);
51         $this->send_fake_message($sender, $recipient);
53         \core_message\api::mark_all_read_for_user($recipient->id);
54         $this->assertDebuggingCalled();
55         $this->assertEquals(message_count_unread_messages($recipient), 0);
56     }
58     public function test_mark_all_read_for_user_touser_with_fromuser() {
59         $sender1 = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
60         $sender2 = $this->getDataGenerator()->create_user(array('firstname' => 'Test3', 'lastname' => 'User3'));
61         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
63         $this->send_fake_message($sender1, $recipient, 'Notification', 1);
64         $this->send_fake_message($sender1, $recipient, 'Notification', 1);
65         $this->send_fake_message($sender1, $recipient, 'Notification', 1);
66         $this->send_fake_message($sender1, $recipient);
67         $this->send_fake_message($sender1, $recipient);
68         $this->send_fake_message($sender1, $recipient);
69         $this->send_fake_message($sender2, $recipient, 'Notification', 1);
70         $this->send_fake_message($sender2, $recipient, 'Notification', 1);
71         $this->send_fake_message($sender2, $recipient, 'Notification', 1);
72         $this->send_fake_message($sender2, $recipient);
73         $this->send_fake_message($sender2, $recipient);
74         $this->send_fake_message($sender2, $recipient);
76         \core_message\api::mark_all_read_for_user($recipient->id, $sender1->id);
77         $this->assertDebuggingCalled();
78         $this->assertEquals(message_count_unread_messages($recipient), 3);
79     }
81     public function test_mark_all_read_for_user_touser_with_type() {
82         $sender = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
83         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
85         $this->send_fake_message($sender, $recipient, 'Notification', 1);
86         $this->send_fake_message($sender, $recipient, 'Notification', 1);
87         $this->send_fake_message($sender, $recipient, 'Notification', 1);
88         $this->send_fake_message($sender, $recipient);
89         $this->send_fake_message($sender, $recipient);
90         $this->send_fake_message($sender, $recipient);
92         \core_message\api::mark_all_read_for_user($recipient->id, 0, MESSAGE_TYPE_NOTIFICATION);
93         $this->assertDebuggingCalled();
94         $this->assertEquals(message_count_unread_messages($recipient), 3);
96         \core_message\api::mark_all_read_for_user($recipient->id, 0, MESSAGE_TYPE_MESSAGE);
97         $this->assertDebuggingCalled();
98         $this->assertEquals(message_count_unread_messages($recipient), 0);
99     }
101     /**
102      * Test count_blocked_users.
103      */
104     public function test_count_blocked_users() {
105         global $USER;
107         // Set this user as the admin.
108         $this->setAdminUser();
110         // Create user to add to the admin's block list.
111         $user1 = $this->getDataGenerator()->create_user();
112         $user2 = $this->getDataGenerator()->create_user();
114         $this->assertEquals(0, \core_message\api::count_blocked_users());
116         // Add 1 blocked user to admin's blocked user list.
117         \core_message\api::block_user($USER->id, $user1->id);
119         $this->assertEquals(0, \core_message\api::count_blocked_users($user1));
120         $this->assertEquals(1, \core_message\api::count_blocked_users());
121     }
123     /**
124      * Tests searching users in a course.
125      */
126     public function test_search_users_in_course() {
127         // Create some users.
128         $user1 = new stdClass();
129         $user1->firstname = 'User';
130         $user1->lastname = 'One';
131         $user1 = self::getDataGenerator()->create_user($user1);
133         // The person doing the search.
134         $this->setUser($user1);
136         // Second user is going to have their last access set to now, so they are online.
137         $user2 = new stdClass();
138         $user2->firstname = 'User';
139         $user2->lastname = 'Two';
140         $user2->lastaccess = time();
141         $user2 = self::getDataGenerator()->create_user($user2);
143         // Block the second user.
144         \core_message\api::block_user($user1->id, $user2->id);
146         $user3 = new stdClass();
147         $user3->firstname = 'User';
148         $user3->lastname = 'Three';
149         $user3 = self::getDataGenerator()->create_user($user3);
151         // Create a course.
152         $course1 = new stdClass();
153         $course1->fullname = 'Course';
154         $course1->shortname = 'One';
155         $course1 = $this->getDataGenerator()->create_course($course1);
157         // Enrol the searcher and one user in the course.
158         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
159         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
161         // Perform a search.
162         $results = \core_message\api::search_users_in_course($user1->id, $course1->id, 'User');
164         $this->assertEquals(1, count($results));
166         $user = $results[0];
167         $this->assertEquals($user2->id, $user->userid);
168         $this->assertEquals(fullname($user2), $user->fullname);
169         $this->assertFalse($user->ismessaging);
170         $this->assertNull($user->lastmessage);
171         $this->assertNull($user->messageid);
172         $this->assertNull($user->isonline);
173         $this->assertFalse($user->isread);
174         $this->assertTrue($user->isblocked);
175         $this->assertNull($user->unreadcount);
176     }
178     /**
179      * Tests searching users.
180      */
181     public function test_search_users() {
182         global $DB;
184         // Create some users.
185         $user1 = new stdClass();
186         $user1->firstname = 'User';
187         $user1->lastname = 'One';
188         $user1 = self::getDataGenerator()->create_user($user1);
190         // Set as the user performing the search.
191         $this->setUser($user1);
193         $user2 = new stdClass();
194         $user2->firstname = 'User search';
195         $user2->lastname = 'Two';
196         $user2 = self::getDataGenerator()->create_user($user2);
198         $user3 = new stdClass();
199         $user3->firstname = 'User search';
200         $user3->lastname = 'Three';
201         $user3 = self::getDataGenerator()->create_user($user3);
203         $user4 = new stdClass();
204         $user4->firstname = 'User';
205         $user4->lastname = 'Four';
206         $user4 = self::getDataGenerator()->create_user($user4);
208         $user5 = new stdClass();
209         $user5->firstname = 'User search';
210         $user5->lastname = 'Five';
211         $user5 = self::getDataGenerator()->create_user($user5);
213         $user6 = new stdClass();
214         $user6->firstname = 'User';
215         $user6->lastname = 'Six';
216         $user6 = self::getDataGenerator()->create_user($user6);
218         // Create some courses.
219         $course1 = new stdClass();
220         $course1->fullname = 'Course search';
221         $course1->shortname = 'One';
222         $course1 = $this->getDataGenerator()->create_course($course1);
224         $course2 = new stdClass();
225         $course2->fullname = 'Course';
226         $course2->shortname = 'Two';
227         $course2 = $this->getDataGenerator()->create_course($course2);
229         $course3 = new stdClass();
230         $course3->fullname = 'Course';
231         $course3->shortname = 'Three search';
232         $course3 = $this->getDataGenerator()->create_course($course3);
234         $course4 = new stdClass();
235         $course4->fullname = 'Course Four';
236         $course4->shortname = 'CF100';
237         $course4 = $this->getDataGenerator()->create_course($course4);
239         $course5 = new stdClass();
240         $course5->fullname = 'Course';
241         $course5->shortname = 'Five search';
242         $course5 = $this->getDataGenerator()->create_course($course5);
244         $role = $DB->get_record('role', ['shortname' => 'student']);
245         $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $role->id);
246         $this->getDataGenerator()->enrol_user($user1->id, $course2->id, $role->id);
247         $this->getDataGenerator()->enrol_user($user1->id, $course3->id, $role->id);
248         $this->getDataGenerator()->enrol_user($user1->id, $course5->id, $role->id);
250         // Add some users as contacts.
251         \core_message\api::add_contact($user1->id, $user2->id);
252         \core_message\api::add_contact($user1->id, $user3->id);
253         \core_message\api::add_contact($user1->id, $user4->id);
255         // Remove the viewparticipants capability from one of the courses.
256         $course5context = context_course::instance($course5->id);
257         assign_capability('moodle/course:viewparticipants', CAP_PROHIBIT, $role->id, $course5context->id);
259         // Perform a search.
260         list($contacts, $courses, $noncontacts) = \core_message\api::search_users($user1->id, 'search');
262         // Check that we retrieved the correct contacts.
263         $this->assertEquals(2, count($contacts));
264         $this->assertEquals($user3->id, $contacts[0]->userid);
265         $this->assertEquals($user2->id, $contacts[1]->userid);
267         // Check that we retrieved the correct courses.
268         $this->assertEquals(2, count($courses));
269         $this->assertEquals($course3->id, $courses[0]->id);
270         $this->assertEquals($course1->id, $courses[1]->id);
272         // Check that we retrieved the correct non-contacts.
273         $this->assertEquals(1, count($noncontacts));
274         $this->assertEquals($user5->id, $noncontacts[0]->userid);
275     }
277     /**
278      * Tests searching messages.
279      */
280     public function test_search_messages() {
281         // Create some users.
282         $user1 = self::getDataGenerator()->create_user();
283         $user2 = self::getDataGenerator()->create_user();
284         $user3 = self::getDataGenerator()->create_user();
286         // The person doing the search.
287         $this->setUser($user1);
289         // Send some messages back and forth.
290         $time = 1;
291         $this->send_fake_message($user3, $user1, 'Don\'t block me.', 0, $time);
292         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
293         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
294         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
295         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
297         // Block user 3.
298         \core_message\api::block_user($user1->id, $user3->id);
300         // Perform a search.
301         $messages = \core_message\api::search_messages($user1->id, 'o');
303         // Confirm the data is correct.
304         $this->assertEquals(3, count($messages));
306         $message1 = $messages[0];
307         $message2 = $messages[1];
308         $message3 = $messages[2];
310         $this->assertEquals($user2->id, $message1->userid);
311         $this->assertEquals($user2->id, $message1->useridfrom);
312         $this->assertEquals(fullname($user2), $message1->fullname);
313         $this->assertTrue($message1->ismessaging);
314         $this->assertEquals('Word.', $message1->lastmessage);
315         $this->assertNotEmpty($message1->messageid);
316         $this->assertNull($message1->isonline);
317         $this->assertFalse($message1->isread);
318         $this->assertFalse($message1->isblocked);
319         $this->assertNull($message1->unreadcount);
321         $this->assertEquals($user2->id, $message2->userid);
322         $this->assertEquals($user1->id, $message2->useridfrom);
323         $this->assertEquals(fullname($user2), $message2->fullname);
324         $this->assertTrue($message2->ismessaging);
325         $this->assertEquals('Yo!', $message2->lastmessage);
326         $this->assertNotEmpty($message2->messageid);
327         $this->assertNull($message2->isonline);
328         $this->assertTrue($message2->isread);
329         $this->assertFalse($message2->isblocked);
330         $this->assertNull($message2->unreadcount);
332         $this->assertEquals($user3->id, $message3->userid);
333         $this->assertEquals($user3->id, $message3->useridfrom);
334         $this->assertEquals(fullname($user3), $message3->fullname);
335         $this->assertTrue($message3->ismessaging);
336         $this->assertEquals('Don\'t block me.', $message3->lastmessage);
337         $this->assertNotEmpty($message3->messageid);
338         $this->assertNull($message3->isonline);
339         $this->assertFalse($message3->isread);
340         $this->assertTrue($message3->isblocked);
341         $this->assertNull($message3->unreadcount);
342     }
344     /**
345      * Tests retrieving conversations.
346      */
347     public function test_get_conversations() {
348         // Create some users.
349         $user1 = self::getDataGenerator()->create_user();
350         $user2 = self::getDataGenerator()->create_user();
351         $user3 = self::getDataGenerator()->create_user();
352         $user4 = self::getDataGenerator()->create_user();
354         // The person doing the search.
355         $this->setUser($user1);
357         // No conversations yet.
358         $this->assertEquals([], \core_message\api::get_conversations($user1->id));
360         // Send some messages back and forth, have some different conversations with different users.
361         $time = 1;
362         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
363         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
364         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
365         $messageid1 = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
367         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
368         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
369         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
370         $messageid2 = $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
372         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 9);
373         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 10);
374         $messageid3 = $this->send_fake_message($user1, $user4, 'Dope.', 0, $time + 11);
376         // Retrieve the conversations.
377         $conversations = \core_message\api::get_conversations($user1->id);
379         // Confirm the data is correct.
380         $this->assertEquals(3, count($conversations));
382         $message1 = array_shift($conversations);
383         $message2 = array_shift($conversations);
384         $message3 = array_shift($conversations);
386         $this->assertEquals($user4->id, $message1->userid);
387         $this->assertEquals($user1->id, $message1->useridfrom);
388         $this->assertTrue($message1->ismessaging);
389         $this->assertEquals('Dope.', $message1->lastmessage);
390         $this->assertEquals($messageid3, $message1->messageid);
391         $this->assertNull($message1->isonline);
392         $this->assertFalse($message1->isread);
393         $this->assertFalse($message1->isblocked);
394         $this->assertEquals(1, $message1->unreadcount);
396         $this->assertEquals($user3->id, $message2->userid);
397         $this->assertEquals($user3->id, $message2->useridfrom);
398         $this->assertTrue($message2->ismessaging);
399         $this->assertEquals('Cool.', $message2->lastmessage);
400         $this->assertEquals($messageid2, $message2->messageid);
401         $this->assertNull($message2->isonline);
402         $this->assertFalse($message2->isread);
403         $this->assertFalse($message2->isblocked);
404         $this->assertEquals(2, $message2->unreadcount);
406         $this->assertEquals($user2->id, $message3->userid);
407         $this->assertEquals($user2->id, $message3->useridfrom);
408         $this->assertTrue($message3->ismessaging);
409         $this->assertEquals('Word.', $message3->lastmessage);
410         $this->assertEquals($messageid1, $message3->messageid);
411         $this->assertNull($message3->isonline);
412         $this->assertFalse($message3->isread);
413         $this->assertFalse($message3->isblocked);
414         $this->assertEquals(2, $message3->unreadcount);
415     }
417     /**
418      * Tests retrieving conversations with a limit and offset to ensure pagination works correctly.
419      */
420     public function test_get_conversations_limit_offset() {
421         // Create some users.
422         $user1 = self::getDataGenerator()->create_user();
423         $user2 = self::getDataGenerator()->create_user();
424         $user3 = self::getDataGenerator()->create_user();
425         $user4 = self::getDataGenerator()->create_user();
427         // The person doing the search.
428         $this->setUser($user1);
430         // Send some messages back and forth, have some different conversations with different users.
431         $time = 1;
432         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
433         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
434         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
435         $messageid1 = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
437         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
438         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
439         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
440         $messageid2 = $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
442         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 9);
443         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 10);
444         $messageid3 = $this->send_fake_message($user1, $user4, 'Dope.', 0, $time + 11);
446         // Retrieve the conversations.
447         $conversations = \core_message\api::get_conversations($user1->id, 1, 1);
449         // We should only have one conversation because of the limit.
450         $this->assertCount(1, $conversations);
452         $conversation = array_shift($conversations);
454         $this->assertEquals($user3->id, $conversation->userid);
455         $this->assertEquals($user3->id, $conversation->useridfrom);
456         $this->assertTrue($conversation->ismessaging);
457         $this->assertEquals('Cool.', $conversation->lastmessage);
458         $this->assertEquals($messageid2, $conversation->messageid);
459         $this->assertNull($conversation->isonline);
460         $this->assertFalse($conversation->isread);
461         $this->assertFalse($conversation->isblocked);
462         $this->assertEquals(2, $conversation->unreadcount);
464         // Retrieve the next conversation.
465         $conversations = \core_message\api::get_conversations($user1->id, 2, 1);
467         // We should only have one conversation because of the limit.
468         $this->assertCount(1, $conversations);
470         $conversation = array_shift($conversations);
472         $this->assertEquals($user2->id, $conversation->userid);
473         $this->assertEquals($user2->id, $conversation->useridfrom);
474         $this->assertTrue($conversation->ismessaging);
475         $this->assertEquals('Word.', $conversation->lastmessage);
476         $this->assertEquals($messageid1, $conversation->messageid);
477         $this->assertNull($conversation->isonline);
478         $this->assertFalse($conversation->isread);
479         $this->assertFalse($conversation->isblocked);
480         $this->assertEquals(2, $conversation->unreadcount);
482         // Ask for an offset that doesn't exist.
483         $conversations = \core_message\api::get_conversations($user1->id, 4, 1);
485         // We should not get any conversations back.
486         $this->assertCount(0, $conversations);
487     }
489     /**
490      * Tests retrieving conversations when a conversation contains a deleted user.
491      */
492     public function test_get_conversations_with_deleted_user() {
493         // Create some users.
494         $user1 = self::getDataGenerator()->create_user();
495         $user2 = self::getDataGenerator()->create_user();
496         $user3 = self::getDataGenerator()->create_user();
498         // Send some messages back and forth, have some different conversations with different users.
499         $time = 1;
500         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
501         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
502         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
503         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
505         $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
506         $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
507         $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
508         $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
510         // Delete the second user.
511         delete_user($user2);
513         // Retrieve the conversations.
514         $conversations = \core_message\api::get_conversations($user1->id);
516         // We should only have one conversation because the other user was deleted.
517         $this->assertCount(1, $conversations);
519         // Confirm the conversation is from the non-deleted user.
520         $conversation = reset($conversations);
521         $this->assertEquals($user3->id, $conversation->userid);
522     }
524    /**
525     * The data provider for get_conversations_mixed.
526     *
527     * This provides sets of data to for testing.
528     * @return array
529     */
530    public function get_conversations_mixed_provider() {
531        return array(
532             'Test that conversations with messages contacts is correctly ordered.' => array(
533                 'users' => array(
534                     'user1',
535                     'user2',
536                     'user3',
537                 ),
538                 'contacts' => array(
539                 ),
540                 'messages' => array(
541                     array(
542                         'from'          => 'user1',
543                         'to'            => 'user2',
544                         'state'         => 'unread',
545                         'subject'       => 'S1',
546                     ),
547                     array(
548                         'from'          => 'user2',
549                         'to'            => 'user1',
550                         'state'         => 'unread',
551                         'subject'       => 'S2',
552                     ),
553                     array(
554                         'from'          => 'user1',
555                         'to'            => 'user2',
556                         'state'         => 'unread',
557                         'timecreated'   => 0,
558                         'subject'       => 'S3',
559                     ),
560                     array(
561                         'from'          => 'user1',
562                         'to'            => 'user3',
563                         'state'         => 'read',
564                         'timemodifier'  => 1,
565                         'subject'       => 'S4',
566                     ),
567                     array(
568                         'from'          => 'user3',
569                         'to'            => 'user1',
570                         'state'         => 'read',
571                         'timemodifier'  => 1,
572                         'subject'       => 'S5',
573                     ),
574                     array(
575                         'from'          => 'user1',
576                         'to'            => 'user3',
577                         'state'         => 'read',
578                         'timecreated'   => 0,
579                         'subject'       => 'S6',
580                     ),
581                 ),
582                 'expectations' => array(
583                     'user1' => array(
584                         // User1 has conversed most recently with user3. The most recent message is M5.
585                         array(
586                             'messageposition'   => 0,
587                             'with'              => 'user3',
588                             'subject'           => 'S5',
589                             'unreadcount'       => 0,
590                         ),
591                         // User1 has also conversed with user2. The most recent message is S2.
592                         array(
593                             'messageposition'   => 1,
594                             'with'              => 'user2',
595                             'subject'           => 'S2',
596                             'unreadcount'       => 1,
597                         ),
598                     ),
599                     'user2' => array(
600                         // User2 has only conversed with user1. Their most recent shared message was S2.
601                         array(
602                             'messageposition'   => 0,
603                             'with'              => 'user1',
604                             'subject'           => 'S2',
605                             'unreadcount'       => 2,
606                         ),
607                     ),
608                     'user3' => array(
609                         // User3 has only conversed with user1. Their most recent shared message was S5.
610                         array(
611                             'messageposition'   => 0,
612                             'with'              => 'user1',
613                             'subject'           => 'S5',
614                             'unreadcount'       => 0,
615                         ),
616                     ),
617                 ),
618             ),
619             'Test that users with contacts and messages to self work as expected' => array(
620                 'users' => array(
621                     'user1',
622                     'user2',
623                     'user3',
624                 ),
625                 'contacts' => array(
626                     'user1' => array(
627                         'user2' => 0,
628                         'user3' => 0,
629                     ),
630                     'user2' => array(
631                         'user3' => 0,
632                     ),
633                 ),
634                 'messages' => array(
635                     array(
636                         'from'          => 'user1',
637                         'to'            => 'user1',
638                         'state'         => 'unread',
639                         'subject'       => 'S1',
640                     ),
641                     array(
642                         'from'          => 'user1',
643                         'to'            => 'user1',
644                         'state'         => 'unread',
645                         'subject'       => 'S2',
646                     ),
647                 ),
648                 'expectations' => array(
649                     'user1' => array(
650                         // User1 has conversed most recently with user1. The most recent message is S2.
651                         array(
652                             'messageposition'   => 0,
653                             'with'              => 'user1',
654                             'subject'           => 'S2',
655                             'unreadcount'       => 0, // Messages sent to and from the same user are counted as read.
656                         ),
657                     ),
658                 ),
659             ),
660             'Test conversations with a single user, where some messages are read and some are not.' => array(
661                 'users' => array(
662                     'user1',
663                     'user2',
664                 ),
665                 'contacts' => array(
666                 ),
667                 'messages' => array(
668                     array(
669                         'from'          => 'user1',
670                         'to'            => 'user2',
671                         'state'         => 'read',
672                         'subject'       => 'S1',
673                     ),
674                     array(
675                         'from'          => 'user2',
676                         'to'            => 'user1',
677                         'state'         => 'read',
678                         'subject'       => 'S2',
679                     ),
680                     array(
681                         'from'          => 'user1',
682                         'to'            => 'user2',
683                         'state'         => 'unread',
684                         'timemodifier'  => 1,
685                         'subject'       => 'S3',
686                     ),
687                     array(
688                         'from'          => 'user1',
689                         'to'            => 'user2',
690                         'state'         => 'unread',
691                         'timemodifier'  => 1,
692                         'subject'       => 'S4',
693                     ),
694                 ),
695                 'expectations' => array(
696                     // The most recent message between user1 and user2 was S4.
697                     'user1' => array(
698                         array(
699                             'messageposition'   => 0,
700                             'with'              => 'user2',
701                             'subject'           => 'S4',
702                             'unreadcount'       => 0,
703                         ),
704                     ),
705                     'user2' => array(
706                         // The most recent message between user1 and user2 was S4.
707                         array(
708                             'messageposition'   => 0,
709                             'with'              => 'user1',
710                             'subject'           => 'S4',
711                             'unreadcount'       => 2,
712                         ),
713                     ),
714                 ),
715             ),
716             'Test conversations with a single user, where some messages are read and some are not, and messages ' .
717             'are out of order' => array(
718             // This can happen through a combination of factors including multi-master DB replication with messages
719             // read somehow (e.g. API).
720                 'users' => array(
721                     'user1',
722                     'user2',
723                 ),
724                 'contacts' => array(
725                 ),
726                 'messages' => array(
727                     array(
728                         'from'          => 'user1',
729                         'to'            => 'user2',
730                         'state'         => 'read',
731                         'subject'       => 'S1',
732                         'timemodifier'  => 1,
733                     ),
734                     array(
735                         'from'          => 'user2',
736                         'to'            => 'user1',
737                         'state'         => 'read',
738                         'subject'       => 'S2',
739                         'timemodifier'  => 2,
740                     ),
741                     array(
742                         'from'          => 'user1',
743                         'to'            => 'user2',
744                         'state'         => 'unread',
745                         'subject'       => 'S3',
746                     ),
747                     array(
748                         'from'          => 'user1',
749                         'to'            => 'user2',
750                         'state'         => 'unread',
751                         'subject'       => 'S4',
752                     ),
753                 ),
754                 'expectations' => array(
755                     // The most recent message between user1 and user2 was S2, even though later IDs have not been read.
756                     'user1' => array(
757                         array(
758                             'messageposition'   => 0,
759                             'with'              => 'user2',
760                             'subject'           => 'S2',
761                             'unreadcount'       => 0,
762                         ),
763                     ),
764                     'user2' => array(
765                         array(
766                             'messageposition'   => 0,
767                             'with'              => 'user1',
768                             'subject'           => 'S2',
769                             'unreadcount'       => 2
770                         ),
771                     ),
772                 ),
773             ),
774             'Test unread message count is correct for both users' => array(
775                 'users' => array(
776                     'user1',
777                     'user2',
778                 ),
779                 'contacts' => array(
780                 ),
781                 'messages' => array(
782                     array(
783                         'from'          => 'user1',
784                         'to'            => 'user2',
785                         'state'         => 'read',
786                         'subject'       => 'S1',
787                         'timemodifier'  => 1,
788                     ),
789                     array(
790                         'from'          => 'user2',
791                         'to'            => 'user1',
792                         'state'         => 'read',
793                         'subject'       => 'S2',
794                         'timemodifier'  => 2,
795                     ),
796                     array(
797                         'from'          => 'user1',
798                         'to'            => 'user2',
799                         'state'         => 'read',
800                         'subject'       => 'S3',
801                         'timemodifier'  => 3,
802                     ),
803                     array(
804                         'from'          => 'user1',
805                         'to'            => 'user2',
806                         'state'         => 'read',
807                         'subject'       => 'S4',
808                         'timemodifier'  => 4,
809                     ),
810                     array(
811                         'from'          => 'user1',
812                         'to'            => 'user2',
813                         'state'         => 'unread',
814                         'subject'       => 'S5',
815                         'timemodifier'  => 5,
816                     ),
817                     array(
818                         'from'          => 'user2',
819                         'to'            => 'user1',
820                         'state'         => 'unread',
821                         'subject'       => 'S6',
822                         'timemodifier'  => 6,
823                     ),
824                     array(
825                         'from'          => 'user1',
826                         'to'            => 'user2',
827                         'state'         => 'unread',
828                         'subject'       => 'S7',
829                         'timemodifier'  => 7,
830                     ),
831                     array(
832                         'from'          => 'user1',
833                         'to'            => 'user2',
834                         'state'         => 'unread',
835                         'subject'       => 'S8',
836                         'timemodifier'  => 8,
837                     ),
838                 ),
839                 'expectations' => array(
840                     // The most recent message between user1 and user2 was S2, even though later IDs have not been read.
841                     'user1' => array(
842                         array(
843                             'messageposition'   => 0,
844                             'with'              => 'user2',
845                             'subject'           => 'S8',
846                             'unreadcount'       => 1,
847                         ),
848                     ),
849                     'user2' => array(
850                         array(
851                             'messageposition'   => 0,
852                             'with'              => 'user1',
853                             'subject'           => 'S8',
854                             'unreadcount'       => 3,
855                         ),
856                     ),
857                 ),
858             ),
859         );
860     }
862     /**
863      * Test get_conversations with a mixture of messages.
864      *
865      * @dataProvider get_conversations_mixed_provider
866      * @param array $usersdata The list of users to create for this test.
867      * @param array $messagesdata The list of messages to create.
868      * @param array $expectations The list of expected outcomes.
869      */
870     public function test_get_conversations_mixed($usersdata, $contacts, $messagesdata, $expectations) {
871         global $DB;
873         // Create all of the users.
874         $users = array();
875         foreach ($usersdata as $username) {
876             $users[$username] = $this->getDataGenerator()->create_user(array('username' => $username));
877         }
879         foreach ($contacts as $username => $contact) {
880             foreach ($contact as $contactname => $blocked) {
881                 $record = new stdClass();
882                 $record->userid     = $users[$username]->id;
883                 $record->contactid  = $users[$contactname]->id;
884                 $record->blocked    = $blocked;
885                 $record->id = $DB->insert_record('message_contacts', $record);
886             }
887         }
889         $defaulttimecreated = time();
890         foreach ($messagesdata as $messagedata) {
891             $from       = $users[$messagedata['from']];
892             $to         = $users[$messagedata['to']];
893             $subject    = $messagedata['subject'];
895             if (isset($messagedata['state']) && $messagedata['state'] == 'unread') {
896                 $messageid = $this->send_fake_message($from, $to, $subject);
897             } else {
898                 // If there is no state, or the state is not 'unread', assume the message is read.
899                 $messageid = message_post_message($from, $to, $subject, FORMAT_PLAIN);
900             }
902             $updatemessage = new stdClass();
903             $updatemessage->id = $messageid;
904             if (isset($messagedata['timecreated'])) {
905                 $updatemessage->timecreated = $messagedata['timecreated'];
906             } else if (isset($messagedata['timemodifier'])) {
907                 $updatemessage->timecreated = $defaulttimecreated + $messagedata['timemodifier'];
908             } else {
909                 $updatemessage->timecreated = $defaulttimecreated;
910             }
912             $DB->update_record('messages', $updatemessage);
913         }
915         foreach ($expectations as $username => $data) {
916             // Get the recent conversations for the specified user.
917             $user = $users[$username];
918             $conversations = array_values(\core_message\api::get_conversations($user->id));
919             foreach ($data as $expectation) {
920                 $otheruser = $users[$expectation['with']];
921                 $conversation = $conversations[$expectation['messageposition']];
922                 $this->assertEquals($otheruser->id, $conversation->userid);
923                 $this->assertEquals($expectation['subject'], $conversation->lastmessage);
924                 $this->assertEquals($expectation['unreadcount'], $conversation->unreadcount);
925             }
926         }
927     }
929     /**
930      * Tests retrieving contacts.
931      */
932     public function test_get_contacts() {
933         // Create some users.
934         $user1 = self::getDataGenerator()->create_user();
936         // Set as the user.
937         $this->setUser($user1);
939         $user2 = new stdClass();
940         $user2->firstname = 'User';
941         $user2->lastname = 'A';
942         $user2 = self::getDataGenerator()->create_user($user2);
944         $user3 = new stdClass();
945         $user3->firstname = 'User';
946         $user3->lastname = 'B';
947         $user3 = self::getDataGenerator()->create_user($user3);
949         $user4 = new stdClass();
950         $user4->firstname = 'User';
951         $user4->lastname = 'C';
952         $user4 = self::getDataGenerator()->create_user($user4);
954         $user5 = new stdClass();
955         $user5->firstname = 'User';
956         $user5->lastname = 'D';
957         $user5 = self::getDataGenerator()->create_user($user5);
959         // Add some users as contacts.
960         \core_message\api::add_contact($user1->id, $user2->id);
961         \core_message\api::add_contact($user1->id, $user3->id);
962         \core_message\api::add_contact($user1->id, $user4->id);
964         // Retrieve the contacts.
965         $contacts = \core_message\api::get_contacts($user1->id);
967         // Confirm the data is correct.
968         $this->assertEquals(3, count($contacts));
969         usort($contacts, ['static', 'sort_contacts']);
971         $contact1 = $contacts[0];
972         $contact2 = $contacts[1];
973         $contact3 = $contacts[2];
975         $this->assertEquals($user2->id, $contact1->userid);
976         $this->assertEmpty($contact1->useridfrom);
977         $this->assertFalse($contact1->ismessaging);
978         $this->assertNull($contact1->lastmessage);
979         $this->assertNull($contact1->messageid);
980         $this->assertNull($contact1->isonline);
981         $this->assertFalse($contact1->isread);
982         $this->assertFalse($contact1->isblocked);
983         $this->assertNull($contact1->unreadcount);
985         $this->assertEquals($user3->id, $contact2->userid);
986         $this->assertEmpty($contact2->useridfrom);
987         $this->assertFalse($contact2->ismessaging);
988         $this->assertNull($contact2->lastmessage);
989         $this->assertNull($contact2->messageid);
990         $this->assertNull($contact2->isonline);
991         $this->assertFalse($contact2->isread);
992         $this->assertFalse($contact2->isblocked);
993         $this->assertNull($contact2->unreadcount);
995         $this->assertEquals($user4->id, $contact3->userid);
996         $this->assertEmpty($contact3->useridfrom);
997         $this->assertFalse($contact3->ismessaging);
998         $this->assertNull($contact3->lastmessage);
999         $this->assertNull($contact3->messageid);
1000         $this->assertNull($contact3->isonline);
1001         $this->assertFalse($contact3->isread);
1002         $this->assertFalse($contact3->isblocked);
1003         $this->assertNull($contact3->unreadcount);
1004     }
1006     /**
1007      * Tests retrieving messages.
1008      */
1009     public function test_get_messages() {
1010         // Create some users.
1011         $user1 = self::getDataGenerator()->create_user();
1012         $user2 = self::getDataGenerator()->create_user();
1014         // The person doing the search.
1015         $this->setUser($user1);
1017         // Send some messages back and forth.
1018         $time = 1;
1019         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
1020         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
1021         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
1022         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
1024         // Retrieve the messages.
1025         $messages = \core_message\api::get_messages($user1->id, $user2->id);
1027         // Confirm the message data is correct.
1028         $this->assertEquals(4, count($messages));
1030         $message1 = $messages[0];
1031         $message2 = $messages[1];
1032         $message3 = $messages[2];
1033         $message4 = $messages[3];
1035         $this->assertEquals($user1->id, $message1->useridfrom);
1036         $this->assertEquals($user2->id, $message1->useridto);
1037         $this->assertTrue($message1->displayblocktime);
1038         $this->assertContains('Yo!', $message1->text);
1040         $this->assertEquals($user2->id, $message2->useridfrom);
1041         $this->assertEquals($user1->id, $message2->useridto);
1042         $this->assertFalse($message2->displayblocktime);
1043         $this->assertContains('Sup mang?', $message2->text);
1045         $this->assertEquals($user1->id, $message3->useridfrom);
1046         $this->assertEquals($user2->id, $message3->useridto);
1047         $this->assertFalse($message3->displayblocktime);
1048         $this->assertContains('Writing PHPUnit tests!', $message3->text);
1050         $this->assertEquals($user2->id, $message4->useridfrom);
1051         $this->assertEquals($user1->id, $message4->useridto);
1052         $this->assertFalse($message4->displayblocktime);
1053         $this->assertContains('Word.', $message4->text);
1054     }
1056     /**
1057      * Tests retrieving most recent message.
1058      */
1059     public function test_get_most_recent_message() {
1060         // Create some users.
1061         $user1 = self::getDataGenerator()->create_user();
1062         $user2 = self::getDataGenerator()->create_user();
1064         // The person doing the search.
1065         $this->setUser($user1);
1067         // Send some messages back and forth.
1068         $time = 1;
1069         $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
1070         $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
1071         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
1072         $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
1074         // Retrieve the most recent messages.
1075         $message = \core_message\api::get_most_recent_message($user1->id, $user2->id);
1077         // Check the results are correct.
1078         $this->assertEquals($user2->id, $message->useridfrom);
1079         $this->assertEquals($user1->id, $message->useridto);
1080         $this->assertContains('Word.', $message->text);
1081     }
1083     /**
1084      * Tests retrieving a user's profile.
1085      */
1086     public function test_get_profile() {
1087         // Create some users.
1088         $user1 = self::getDataGenerator()->create_user();
1090         $user2 = new stdClass();
1091         $user2->country = 'AU';
1092         $user2->city = 'Perth';
1093         $user2 = self::getDataGenerator()->create_user($user2);
1095         // The person doing the search.
1096         $this->setUser($user1);
1098         // Get the profile.
1099         $profile = \core_message\api::get_profile($user1->id, $user2->id);
1101         $this->assertEquals($user2->id, $profile->userid);
1102         $this->assertEmpty($profile->email);
1103         $this->assertEmpty($profile->country);
1104         $this->assertEmpty($profile->city);
1105         $this->assertEquals(fullname($user2), $profile->fullname);
1106         $this->assertNull($profile->isonline);
1107         $this->assertFalse($profile->isblocked);
1108         $this->assertFalse($profile->iscontact);
1109     }
1111     /**
1112      * Tests retrieving a user's profile.
1113      */
1114     public function test_get_profile_as_admin() {
1115         // The person doing the search.
1116         $this->setAdminUser();
1118         // Create some users.
1119         $user1 = self::getDataGenerator()->create_user();
1121         $user2 = new stdClass();
1122         $user2->country = 'AU';
1123         $user2->city = 'Perth';
1124         $user2 = self::getDataGenerator()->create_user($user2);
1126         // Get the profile.
1127         $profile = \core_message\api::get_profile($user1->id, $user2->id);
1129         $this->assertEquals($user2->id, $profile->userid);
1130         $this->assertEquals($user2->email, $profile->email);
1131         $this->assertEquals($user2->country, $profile->country);
1132         $this->assertEquals($user2->city, $profile->city);
1133         $this->assertEquals(fullname($user2), $profile->fullname);
1134         $this->assertFalse($profile->isonline);
1135         $this->assertFalse($profile->isblocked);
1136         $this->assertFalse($profile->iscontact);
1137     }
1139     /**
1140      * Tests checking if a user can delete a conversation.
1141      */
1142     public function test_can_delete_conversation() {
1143         // Set as the admin.
1144         $this->setAdminUser();
1146         // Create some users.
1147         $user1 = self::getDataGenerator()->create_user();
1148         $user2 = self::getDataGenerator()->create_user();
1150         // The admin can do anything.
1151         $this->assertTrue(\core_message\api::can_delete_conversation($user1->id));
1153         // Set as the user 1.
1154         $this->setUser($user1);
1156         // They can delete their own messages.
1157         $this->assertTrue(\core_message\api::can_delete_conversation($user1->id));
1159         // They can't delete someone elses.
1160         $this->assertFalse(\core_message\api::can_delete_conversation($user2->id));
1161     }
1163     /**
1164      * Tests deleting a conversation.
1165      */
1166     public function test_delete_conversation() {
1167         global $DB;
1169         // Create some users.
1170         $user1 = self::getDataGenerator()->create_user();
1171         $user2 = self::getDataGenerator()->create_user();
1173         // The person doing the search.
1174         $this->setUser($user1);
1176         // Send some messages back and forth.
1177         $time = 1;
1178         $m1id = $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
1179         $m2id = $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
1180         $m3id = $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
1181         $m4id = $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
1183         // Delete the conversation as user 1.
1184         \core_message\api::delete_conversation($user1->id, $user2->id);
1186         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
1187         $this->assertCount(4, $muas);
1188         // Sort by id.
1189         ksort($muas);
1191         $mua1 = array_shift($muas);
1192         $mua2 = array_shift($muas);
1193         $mua3 = array_shift($muas);
1194         $mua4 = array_shift($muas);
1196         $this->assertEquals($user1->id, $mua1->userid);
1197         $this->assertEquals($m1id, $mua1->messageid);
1198         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
1200         $this->assertEquals($user1->id, $mua2->userid);
1201         $this->assertEquals($m2id, $mua2->messageid);
1202         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
1204         $this->assertEquals($user1->id, $mua3->userid);
1205         $this->assertEquals($m3id, $mua3->messageid);
1206         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
1208         $this->assertEquals($user1->id, $mua4->userid);
1209         $this->assertEquals($m4id, $mua4->messageid);
1210         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
1211     }
1213     /**
1214      * Tests counting unread conversations.
1215      */
1216     public function test_count_unread_conversations() {
1217         $this->resetAfterTest(true);
1219         // Create some users.
1220         $user1 = self::getDataGenerator()->create_user();
1221         $user2 = self::getDataGenerator()->create_user();
1222         $user3 = self::getDataGenerator()->create_user();
1223         $user4 = self::getDataGenerator()->create_user();
1225         // The person wanting the conversation count.
1226         $this->setUser($user1);
1228         // Send some messages back and forth, have some different conversations with different users.
1229         $this->send_fake_message($user1, $user2, 'Yo!');
1230         $this->send_fake_message($user2, $user1, 'Sup mang?');
1231         $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!');
1232         $this->send_fake_message($user2, $user1, 'Word.');
1234         $this->send_fake_message($user1, $user3, 'Booyah');
1235         $this->send_fake_message($user3, $user1, 'Whaaat?');
1236         $this->send_fake_message($user1, $user3, 'Nothing.');
1237         $this->send_fake_message($user3, $user1, 'Cool.');
1239         $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
1240         $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
1241         $this->send_fake_message($user1, $user4, 'Dope.');
1243         // Check the amount for the current user.
1244         $this->assertEquals(3, core_message\api::count_unread_conversations());
1246         // Check the amount for the second user.
1247         $this->assertEquals(1, core_message\api::count_unread_conversations($user2));
1248     }
1250     /**
1251      * Tests deleting a conversation.
1252      */
1253     public function test_get_all_message_preferences() {
1254         $user = self::getDataGenerator()->create_user();
1255         $this->setUser($user);
1257         // Set a couple of preferences to test.
1258         set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
1259         set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
1261         $processors = get_message_processors();
1262         $providers = message_get_providers_for_user($user->id);
1263         $prefs = \core_message\api::get_all_message_preferences($processors, $providers, $user);
1265         $this->assertEquals(1, $prefs->mod_assign_assign_notification_loggedin['popup']);
1266         $this->assertEquals(1, $prefs->mod_assign_assign_notification_loggedoff['email']);
1267     }
1269     /**
1270      * Tests the user can post a message.
1271      */
1272     public function test_can_post_message() {
1273         // Create some users.
1274         $user1 = self::getDataGenerator()->create_user();
1275         $user2 = self::getDataGenerator()->create_user();
1277         // Set as the first user.
1278         $this->setUser($user1);
1280         // With the default privacy setting, users can't message them.
1281         $this->assertFalse(\core_message\api::can_post_message($user2));
1283         // Enrol users to the same course.
1284         $course = $this->getDataGenerator()->create_course();
1285         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
1286         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
1287         // After enrolling users to the course, they should be able to message them with the default privacy setting.
1288         $this->assertTrue(\core_message\api::can_post_message($user2));
1289     }
1291     /**
1292      * Tests the user can't post a message without proper capability.
1293      */
1294     public function test_can_post_message_without_cap() {
1295         global $DB;
1297         // Create some users.
1298         $user1 = self::getDataGenerator()->create_user();
1299         $user2 = self::getDataGenerator()->create_user();
1301         // Set as the user 1.
1302         $this->setUser($user1);
1304         // Remove the capability to send a message.
1305         $roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
1306         unassign_capability('moodle/site:sendmessage', $roleids['user'],
1307             context_system::instance());
1309         // Check that we can not post a message without the capability.
1310         $this->assertFalse(\core_message\api::can_post_message($user2));
1311     }
1313     /**
1314      * Tests the user can post a message when they are contact.
1315      */
1316     public function test_can_post_message_when_contact() {
1317         // Create some users.
1318         $user1 = self::getDataGenerator()->create_user();
1319         $user2 = self::getDataGenerator()->create_user();
1321         // Set as the first user.
1322         $this->setUser($user1);
1324         // Check that we can not send user2 a message.
1325         $this->assertFalse(\core_message\api::can_post_message($user2));
1327         // Add users as contacts.
1328         \core_message\api::add_contact($user1->id, $user2->id);
1330         // Check that the return result is now true.
1331         $this->assertTrue(\core_message\api::can_post_message($user2));
1332     }
1334     /**
1335      * Tests the user can't post a message if they are not a contact and the user
1336      * has requested messages only from contacts.
1337      */
1338     public function test_can_post_message_when_not_contact() {
1339         // Create some users.
1340         $user1 = self::getDataGenerator()->create_user();
1341         $user2 = self::getDataGenerator()->create_user();
1343         // Set as the first user.
1344         $this->setUser($user1);
1346         // Set the second user's preference to not receive messages from non-contacts.
1347         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
1349         // Check that we can not send user 2 a message.
1350         $this->assertFalse(\core_message\api::can_post_message($user2));
1351     }
1353     /**
1354      * Tests the user can't post a message if they are blocked.
1355      */
1356     public function test_can_post_message_when_blocked() {
1357         // Create some users.
1358         $user1 = self::getDataGenerator()->create_user();
1359         $user2 = self::getDataGenerator()->create_user();
1361         // Set the user.
1362         $this->setUser($user1);
1364         // Block the second user.
1365         \core_message\api::block_user($user1->id, $user2->id);
1367         // Check that the second user can no longer send the first user a message.
1368         $this->assertFalse(\core_message\api::can_post_message($user1, $user2));
1369     }
1371     /**
1372      * Tests the user can post a message when site-wide messaging setting is enabled,
1373      * even if they are not a contact and are not members of the same course.
1374      */
1375     public function test_can_post_message_site_messaging_setting() {
1376         // Create some users.
1377         $user1 = self::getDataGenerator()->create_user();
1378         $user2 = self::getDataGenerator()->create_user();
1380         // Set as the first user.
1381         $this->setUser($user1);
1383         // Set the second user's preference to receive messages from everybody. As site-wide messaging setting
1384         // is disabled by default, the value will be changed to MESSAGE_PRIVACY_COURSEMEMBER.
1385         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_SITE, $user2->id);
1386         $this->assertFalse(\core_message\api::can_post_message($user2));
1388         // Enable site-wide messagging privacy setting. The user will be able to receive messages from everybody.
1389         set_config('messagingallusers', true);
1390         // Check that we can send user2 a message.
1391         $this->assertTrue(\core_message\api::can_post_message($user2));
1392     }
1394     /**
1395      * Tests get_user_privacy_messaging_preference method.
1396      */
1397     public function test_get_user_privacy_messaging_preference() {
1398         // Create some users.
1399         $user1 = self::getDataGenerator()->create_user();
1400         $user2 = self::getDataGenerator()->create_user();
1401         $user3 = self::getDataGenerator()->create_user();
1403         // Enable site-wide messagging privacy setting. The user will be able to receive messages from everybody.
1404         set_config('messagingallusers', true);
1406         // Set some user preferences.
1407         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_SITE, $user1->id);
1408         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
1410         // Check the returned value for each user.
1411         $this->assertEquals(
1412             \core_message\api::MESSAGE_PRIVACY_SITE,
1413             \core_message\api::get_user_privacy_messaging_preference($user1->id)
1414         );
1415         $this->assertEquals(
1416             \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
1417             \core_message\api::get_user_privacy_messaging_preference($user2->id)
1418         );
1419         $this->assertEquals(
1420             \core_message\api::MESSAGE_PRIVACY_SITE,
1421             \core_message\api::get_user_privacy_messaging_preference($user3->id)
1422         );
1424         // Disable site-wide messagging privacy setting. The user will be able to receive messages from members of their course.
1425         set_config('messagingallusers', false);
1427         // Check the returned value for each user.
1428         $this->assertEquals(
1429             \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
1430             \core_message\api::get_user_privacy_messaging_preference($user1->id)
1431         );
1432         $this->assertEquals(
1433             \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
1434             \core_message\api::get_user_privacy_messaging_preference($user2->id)
1435         );
1436         $this->assertEquals(
1437             \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
1438             \core_message\api::get_user_privacy_messaging_preference($user3->id)
1439         );
1440     }
1442     /**
1443      * Tests that when blocking messages from non-contacts is enabled that
1444      * non-contacts trying to send a message return false.
1445      */
1446     public function test_is_user_non_contact_blocked() {
1447         // Create some users.
1448         $user1 = self::getDataGenerator()->create_user();
1449         $user2 = self::getDataGenerator()->create_user();
1451         // Set as the first user.
1452         $this->setUser($user1);
1454         // By default, user only can be messaged by contacts and members of any of his/her courses.
1455         $this->assertTrue(\core_message\api::is_user_non_contact_blocked($user2));
1457         // Enable all users privacy messaging and check now the default user's preference has been set to allow receiving
1458         // messages from everybody.
1459         set_config('messagingallusers', true);
1460         // Check that the return result is now false because any site user can contact him/her.
1461         $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
1463         // Set the second user's preference to not receive messages from non-contacts.
1464         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2->id);
1465         // Check that the return result is still true (because is even more restricted).
1466         $this->assertTrue(\core_message\api::is_user_non_contact_blocked($user2));
1468         // Add the first user as a contact for the second user.
1469         \core_message\api::add_contact($user2->id, $user1->id);
1471         // Check that the return result is now false.
1472         $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
1474         // Set the second user's preference to receive messages from course members.
1475         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER, $user2->id);
1476         // Check that the return result is still false (because $user1 is still his/her contact).
1477         $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
1478     }
1480     /**
1481      * Tests that we return true when a user is blocked, or false
1482      * if they are not blocked.
1483      */
1484     public function test_is_user_blocked() {
1485         // Create some users.
1486         $user1 = self::getDataGenerator()->create_user();
1487         $user2 = self::getDataGenerator()->create_user();
1489         // Set the user.
1490         $this->setUser($user1);
1492         // User shouldn't be blocked.
1493         $this->assertFalse(\core_message\api::is_user_blocked($user1->id, $user2->id));
1494         $this->assertDebuggingCalled();
1496         // Block the user.
1497         \core_message\api::block_user($user1->id, $user2->id);
1499         // User should be blocked.
1500         $this->assertTrue(\core_message\api::is_user_blocked($user1->id, $user2->id));
1501         $this->assertDebuggingCalled();
1503         // Unblock the user.
1504         \core_message\api::unblock_user($user1->id, $user2->id);
1505         $this->assertFalse(\core_message\api::is_user_blocked($user1->id, $user2->id));
1506         $this->assertDebuggingCalled();
1507     }
1509     /**
1510      * Tests that the admin is not blocked even if someone has chosen to block them.
1511      */
1512     public function test_is_user_blocked_as_admin() {
1513         // Create a user.
1514         $user1 = self::getDataGenerator()->create_user();
1516         // Set the user.
1517         $this->setUser($user1);
1519         // Block the admin user.
1520         \core_message\api::block_user($user1->id, 2);
1522         // Now change to the admin user.
1523         $this->setAdminUser();
1525         // As the admin you should still be able to send messages to the user.
1526         $this->assertFalse(\core_message\api::is_user_blocked($user1->id));
1527         $this->assertDebuggingCalled();
1528     }
1530     /*
1531      * Tes get_message_processor api.
1532      */
1533     public function test_get_message_processor() {
1534         $processors = get_message_processors(true);
1535         if (empty($processors)) {
1536             $this->markTestSkipped("No message processors found");
1537         }
1539         $name = key($processors);
1540         $processor = current($processors);
1541         $testprocessor = \core_message\api::get_message_processor($name);
1542         $this->assertEquals($processor->name, $testprocessor->name);
1543         $this->assertEquals($processor->enabled, $testprocessor->enabled);
1544         $this->assertEquals($processor->available, $testprocessor->available);
1545         $this->assertEquals($processor->configured, $testprocessor->configured);
1547         // Disable processor and test.
1548         \core_message\api::update_processor_status($testprocessor, 0);
1549         $testprocessor = \core_message\api::get_message_processor($name, true);
1550         $this->assertEmpty($testprocessor);
1551         $testprocessor = \core_message\api::get_message_processor($name);
1552         $this->assertEquals($processor->name, $testprocessor->name);
1553         $this->assertEquals(0, $testprocessor->enabled);
1555         // Enable again and test.
1556         \core_message\api::update_processor_status($testprocessor, 1);
1557         $testprocessor = \core_message\api::get_message_processor($name, true);
1558         $this->assertEquals($processor->name, $testprocessor->name);
1559         $this->assertEquals(1, $testprocessor->enabled);
1560         $testprocessor = \core_message\api::get_message_processor($name);
1561         $this->assertEquals($processor->name, $testprocessor->name);
1562         $this->assertEquals(1, $testprocessor->enabled);
1563     }
1565     /**
1566      * Test method update_processor_status.
1567      */
1568     public function test_update_processor_status() {
1569         $processors = get_message_processors();
1570         if (empty($processors)) {
1571             $this->markTestSkipped("No message processors found");
1572         }
1573         $name = key($processors);
1574         $testprocessor = current($processors);
1576         // Enable.
1577         \core_message\api::update_processor_status($testprocessor, 1);
1578         $testprocessor = \core_message\api::get_message_processor($name);
1579         $this->assertEquals(1, $testprocessor->enabled);
1581         // Disable.
1582         \core_message\api::update_processor_status($testprocessor, 0);
1583         $testprocessor = \core_message\api::get_message_processor($name);
1584         $this->assertEquals(0, $testprocessor->enabled);
1586         // Enable again.
1587         \core_message\api::update_processor_status($testprocessor, 1);
1588         $testprocessor = \core_message\api::get_message_processor($name);
1589         $this->assertEquals(1, $testprocessor->enabled);
1590     }
1592     /**
1593      * Test method is_user_enabled.
1594      */
1595     public function is_user_enabled() {
1596         $processors = get_message_processors();
1597         if (empty($processors)) {
1598             $this->markTestSkipped("No message processors found");
1599         }
1600         $name = key($processors);
1601         $testprocessor = current($processors);
1603         // Enable.
1604         \core_message\api::update_processor_status($testprocessor, 1);
1605         $status = \core_message\api::is_processor_enabled($name);
1606         $this->assertEquals(1, $status);
1608         // Disable.
1609         \core_message\api::update_processor_status($testprocessor, 0);
1610         $status = \core_message\api::is_processor_enabled($name);
1611         $this->assertEquals(0, $status);
1613         // Enable again.
1614         \core_message\api::update_processor_status($testprocessor, 1);
1615         $status = \core_message\api::is_processor_enabled($name);
1616         $this->assertEquals(1, $status);
1617     }
1619     /**
1620      * Test retrieving messages by providing a minimum timecreated value.
1621      */
1622     public function test_get_messages_time_from_only() {
1623         // Create some users.
1624         $user1 = self::getDataGenerator()->create_user();
1625         $user2 = self::getDataGenerator()->create_user();
1627         // The person doing the search.
1628         $this->setUser($user1);
1630         // Send some messages back and forth.
1631         $time = 1;
1632         $this->send_fake_message($user1, $user2, 'Message 1', 0, $time + 1);
1633         $this->send_fake_message($user2, $user1, 'Message 2', 0, $time + 2);
1634         $this->send_fake_message($user1, $user2, 'Message 3', 0, $time + 3);
1635         $this->send_fake_message($user2, $user1, 'Message 4', 0, $time + 4);
1637         // Retrieve the messages from $time, which should be all of them.
1638         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', $time);
1640         // Confirm the message data is correct.
1641         $this->assertEquals(4, count($messages));
1643         $message1 = $messages[0];
1644         $message2 = $messages[1];
1645         $message3 = $messages[2];
1646         $message4 = $messages[3];
1648         $this->assertContains('Message 1', $message1->text);
1649         $this->assertContains('Message 2', $message2->text);
1650         $this->assertContains('Message 3', $message3->text);
1651         $this->assertContains('Message 4', $message4->text);
1653         // Retrieve the messages from $time + 3, which should only be the 2 last messages.
1654         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', $time + 3);
1656         // Confirm the message data is correct.
1657         $this->assertEquals(2, count($messages));
1659         $message1 = $messages[0];
1660         $message2 = $messages[1];
1662         $this->assertContains('Message 3', $message1->text);
1663         $this->assertContains('Message 4', $message2->text);
1664     }
1666     /**
1667      * Test retrieving messages by providing a maximum timecreated value.
1668      */
1669     public function test_get_messages_time_to_only() {
1670         // Create some users.
1671         $user1 = self::getDataGenerator()->create_user();
1672         $user2 = self::getDataGenerator()->create_user();
1674         // The person doing the search.
1675         $this->setUser($user1);
1677         // Send some messages back and forth.
1678         $time = 1;
1679         $this->send_fake_message($user1, $user2, 'Message 1', 0, $time + 1);
1680         $this->send_fake_message($user2, $user1, 'Message 2', 0, $time + 2);
1681         $this->send_fake_message($user1, $user2, 'Message 3', 0, $time + 3);
1682         $this->send_fake_message($user2, $user1, 'Message 4', 0, $time + 4);
1684         // Retrieve the messages up until $time + 4, which should be all of them.
1685         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', 0, $time + 4);
1687         // Confirm the message data is correct.
1688         $this->assertEquals(4, count($messages));
1690         $message1 = $messages[0];
1691         $message2 = $messages[1];
1692         $message3 = $messages[2];
1693         $message4 = $messages[3];
1695         $this->assertContains('Message 1', $message1->text);
1696         $this->assertContains('Message 2', $message2->text);
1697         $this->assertContains('Message 3', $message3->text);
1698         $this->assertContains('Message 4', $message4->text);
1700         // Retrieve the messages up until $time + 2, which should be the first two.
1701         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', 0, $time + 2);
1703         // Confirm the message data is correct.
1704         $this->assertEquals(2, count($messages));
1706         $message1 = $messages[0];
1707         $message2 = $messages[1];
1709         $this->assertContains('Message 1', $message1->text);
1710         $this->assertContains('Message 2', $message2->text);
1711     }
1713     /**
1714      * Test retrieving messages by providing a minimum and maximum timecreated value.
1715      */
1716     public function test_get_messages_time_from_and_to() {
1717         // Create some users.
1718         $user1 = self::getDataGenerator()->create_user();
1719         $user2 = self::getDataGenerator()->create_user();
1721         // The person doing the search.
1722         $this->setUser($user1);
1724         // Send some messages back and forth.
1725         $time = 1;
1726         $this->send_fake_message($user1, $user2, 'Message 1', 0, $time + 1);
1727         $this->send_fake_message($user2, $user1, 'Message 2', 0, $time + 2);
1728         $this->send_fake_message($user1, $user2, 'Message 3', 0, $time + 3);
1729         $this->send_fake_message($user2, $user1, 'Message 4', 0, $time + 4);
1731         // Retrieve the messages from $time + 2 up until $time + 3, which should be 2nd and 3rd message.
1732         $messages = \core_message\api::get_messages($user1->id, $user2->id, 0, 0, 'timecreated ASC', $time + 2, $time + 3);
1734         // Confirm the message data is correct.
1735         $this->assertEquals(2, count($messages));
1737         $message1 = $messages[0];
1738         $message2 = $messages[1];
1740         $this->assertContains('Message 2', $message1->text);
1741         $this->assertContains('Message 3', $message2->text);
1742     }
1744     /**
1745      * Test returning blocked users.
1746      */
1747     public function test_get_blocked_users() {
1748         global $USER;
1750         // Set this user as the admin.
1751         $this->setAdminUser();
1753         // Create a user to add to the admin's contact list.
1754         $user1 = $this->getDataGenerator()->create_user();
1755         $user2 = $this->getDataGenerator()->create_user();
1757         // Add users to the admin's contact list.
1758         \core_message\api::block_user($USER->id, $user2->id);
1760         $this->assertCount(1, \core_message\api::get_blocked_users($USER->id));
1762         // Block other user.
1763         \core_message\api::block_user($USER->id, $user1->id);
1764         $this->assertCount(2, \core_message\api::get_blocked_users($USER->id));
1766         // Test deleting users.
1767         delete_user($user1);
1768         $this->assertCount(1, \core_message\api::get_blocked_users($USER->id));
1769     }
1771     /**
1772      * Test returning contacts with unread message count.
1773      */
1774     public function test_get_contacts_with_unread_message_count() {
1775         global $DB;
1777         $user1 = self::getDataGenerator()->create_user();
1778         $user2 = self::getDataGenerator()->create_user();
1779         $user3 = self::getDataGenerator()->create_user();
1780         $user4 = self::getDataGenerator()->create_user();
1782         // Add the users to each of their contacts.
1783         \core_message\api::add_contact($user1->id, $user2->id);
1784         \core_message\api::add_contact($user2->id, $user3->id);
1786         $this->send_fake_message($user1, $user2);
1787         $this->send_fake_message($user1, $user2);
1788         $this->send_fake_message($user1, $user2);
1789         $message4id = $this->send_fake_message($user1, $user2);
1791         $this->send_fake_message($user3, $user2);
1792         $message6id = $this->send_fake_message($user3, $user2);
1793         $this->send_fake_message($user3, $user2);
1794         $this->send_fake_message($user3, $user2);
1795         $this->send_fake_message($user3, $user2);
1797         // Send a message that should never be included as the user is not a contact.
1798         $this->send_fake_message($user4, $user2);
1800         // Get the contacts and the unread message count.
1801         $messages = \core_message\api::get_contacts_with_unread_message_count($user2->id);
1803         // Confirm the size is correct.
1804         $this->assertCount(2, $messages);
1805         ksort($messages);
1807         $messageinfo1 = array_shift($messages);
1808         $messageinfo2 = array_shift($messages);
1810         $this->assertEquals($user1->id, $messageinfo1->id);
1811         $this->assertEquals(4, $messageinfo1->messagecount);
1812         $this->assertEquals($user3->id, $messageinfo2->id);
1813         $this->assertEquals(5, $messageinfo2->messagecount);
1815         // Mark some of the messages as read.
1816         $m4 = $DB->get_record('messages', ['id' => $message4id]);
1817         $m6 = $DB->get_record('messages', ['id' => $message6id]);
1818         \core_message\api::mark_message_as_read($user2->id, $m4);
1819         \core_message\api::mark_message_as_read($user2->id, $m6);
1821         // Get the contacts and the unread message count.
1822         $messages = \core_message\api::get_contacts_with_unread_message_count($user2->id);
1824         // Confirm the size is correct.
1825         $this->assertCount(2, $messages);
1826         ksort($messages);
1828         // Confirm read messages are not included.
1829         $messageinfo1 = array_shift($messages);
1830         $messageinfo2 = array_shift($messages);
1831         $this->assertEquals($user1->id, $messageinfo1->id);
1832         $this->assertEquals(3, $messageinfo1->messagecount);
1833         $this->assertEquals($user3->id, $messageinfo2->id);
1834         $this->assertEquals(4, $messageinfo2->messagecount);
1836         // Now, let's populate the database with messages from user2 to user 1.
1837         $this->send_fake_message($user2, $user1);
1838         $this->send_fake_message($user2, $user1);
1839         $messageid = $this->send_fake_message($user2, $user1);
1841         // Send a message that should never be included as the user is not a contact.
1842         $this->send_fake_message($user4, $user1);
1844         // Get the contacts and the unread message count.
1845         $messages = \core_message\api::get_contacts_with_unread_message_count($user1->id);
1847         // Confirm the size is correct.
1848         $this->assertCount(1, $messages);
1849         $messageinfo1 = array_shift($messages);
1850         $this->assertEquals($user2->id, $messageinfo1->id);
1851         $this->assertEquals(3, $messageinfo1->messagecount);
1853         // Mark the last message as read.
1854         $m = $DB->get_record('messages', ['id' => $messageid]);
1855         \core_message\api::mark_message_as_read($user1->id, $m);
1857         $messages = \core_message\api::get_contacts_with_unread_message_count($user1->id);
1859         // Confirm the size is correct.
1860         $this->assertCount(1, $messages);
1862         // Confirm read messages are not included.
1863         $messageinfo1 = array_shift($messages);
1864         $this->assertEquals($user2->id, $messageinfo1->id);
1865         $this->assertEquals(2, $messageinfo1->messagecount);
1866     }
1868     /**
1869      * Test returning contacts with unread message count when there are no messages.
1870      */
1871     public function test_get_contacts_with_unread_message_count_no_messages() {
1872         $user1 = self::getDataGenerator()->create_user();
1873         $user2 = self::getDataGenerator()->create_user();
1875         // Add the users to each of their contacts.
1876         \core_message\api::add_contact($user2->id, $user1->id);
1878         // Check we get the correct message count.
1879         $messages = \core_message\api::get_contacts_with_unread_message_count($user2->id);
1881         // Confirm the size is correct.
1882         $this->assertCount(1, $messages);
1884         $messageinfo = array_shift($messages);
1886         $this->assertEquals($user1->id, $messageinfo->id);
1887         $this->assertEquals(0, $messageinfo->messagecount);
1888     }
1890     /**
1891      * Test returning non-contacts with unread message count.
1892      */
1893     public function test_get_non_contacts_with_unread_message_count() {
1894         global $DB;
1896         $user1 = self::getDataGenerator()->create_user();
1897         $user2 = self::getDataGenerator()->create_user();
1898         $user3 = self::getDataGenerator()->create_user();
1899         $user4 = self::getDataGenerator()->create_user();
1901         // Add a user to the contact list of the users we are testing this function with.
1902         \core_message\api::add_contact($user1->id, $user4->id);
1903         \core_message\api::add_contact($user2->id, $user4->id);
1905         $this->send_fake_message($user1, $user2);
1906         $this->send_fake_message($user1, $user2);
1907         $this->send_fake_message($user1, $user2);
1908         $message4id = $this->send_fake_message($user1, $user2);
1910         $this->send_fake_message($user3, $user2);
1911         $message6id = $this->send_fake_message($user3, $user2);
1912         $this->send_fake_message($user3, $user2);
1913         $this->send_fake_message($user3, $user2);
1914         $this->send_fake_message($user3, $user2);
1916         // Send a message that should never be included as the user is a contact.
1917         $this->send_fake_message($user4, $user2);
1919         // Get the non-contacts and the unread message count.
1920         $messages = \core_message\api::get_non_contacts_with_unread_message_count($user2->id);
1922         // Check we get the correct message count.
1923         ksort($messages);
1924         $this->assertCount(2, $messages);
1925         $messageinfo1 = array_shift($messages);
1926         $messageinfo2 = array_shift($messages);
1927         $this->assertEquals($user1->id, $messageinfo1->id);
1928         $this->assertEquals(4, $messageinfo1->messagecount);
1929         $this->assertEquals($user3->id, $messageinfo2->id);
1930         $this->assertEquals(5, $messageinfo2->messagecount);
1932         // Mark some of the messages as read.
1933         $m4 = $DB->get_record('messages', ['id' => $message4id]);
1934         $m6 = $DB->get_record('messages', ['id' => $message6id]);
1935         \core_message\api::mark_message_as_read($user2->id, $m4);
1936         \core_message\api::mark_message_as_read($user2->id, $m6);
1938         // Get the non-contacts and the unread message count.
1939         $messages = \core_message\api::get_non_contacts_with_unread_message_count($user2->id);
1941         // Check the marked message is not returned in the message count.
1942         ksort($messages);
1943         $this->assertCount(2, $messages);
1944         $messageinfo1 = array_shift($messages);
1945         $messageinfo2 = array_shift($messages);
1946         $this->assertEquals($user1->id, $messageinfo1->id);
1947         $this->assertEquals(3, $messageinfo1->messagecount);
1948         $this->assertEquals($user3->id, $messageinfo2->id);
1949         $this->assertEquals(4, $messageinfo2->messagecount);
1951         // Now, let's populate the database with messages from user2 to user 1.
1952         $this->send_fake_message($user2, $user1);
1953         $this->send_fake_message($user2, $user1);
1954         $messageid = $this->send_fake_message($user2, $user1);
1956         // Send a message that should never be included as the user is a contact.
1957         $this->send_fake_message($user4, $user1);
1959         // Get the non-contacts and the unread message count.
1960         $messages = \core_message\api::get_non_contacts_with_unread_message_count($user1->id);
1962         // Confirm the size is correct.
1963         $this->assertCount(1, $messages);
1964         $messageinfo1 = array_shift($messages);
1965         $this->assertEquals($user2->id, $messageinfo1->id);
1966         $this->assertEquals(3, $messageinfo1->messagecount);
1968         // Mark the last message as read.
1969         $m = $DB->get_record('messages', ['id' => $messageid]);
1970         \core_message\api::mark_message_as_read($user1->id, $m);
1972         // Get the non-contacts and the unread message count.
1973         $messages = \core_message\api::get_non_contacts_with_unread_message_count($user1->id);
1975         // Check the marked message is not returned in the message count.
1976         $this->assertCount(1, $messages);
1977         $messageinfo1 = array_shift($messages);
1978         $this->assertEquals($user2->id, $messageinfo1->id);
1979         $this->assertEquals(2, $messageinfo1->messagecount);
1980     }
1982     /**
1983      * Test marking a message as read.
1984      */
1985     public function test_mark_message_as_read() {
1986         global $DB;
1988         $user1 = self::getDataGenerator()->create_user();
1989         $user2 = self::getDataGenerator()->create_user();
1991         $this->send_fake_message($user1, $user2);
1992         $m2id = $this->send_fake_message($user1, $user2);
1993         $this->send_fake_message($user2, $user1);
1994         $m4id = $this->send_fake_message($user2, $user1);
1996         $m2 = $DB->get_record('messages', ['id' => $m2id]);
1997         $m4 = $DB->get_record('messages', ['id' => $m4id]);
1998         \core_message\api::mark_message_as_read($user2->id, $m2, 11);
1999         \core_message\api::mark_message_as_read($user1->id, $m4, 12);
2001         // Confirm there are two user actions.
2002         $muas = $DB->get_records('message_user_actions', [], 'timecreated ASC');
2003         $this->assertEquals(2, count($muas));
2005         // Confirm they are correct.
2006         $mua1 = array_shift($muas);
2007         $mua2 = array_shift($muas);
2009         // Confirm first action.
2010         $this->assertEquals($user2->id, $mua1->userid);
2011         $this->assertEquals($m2id, $mua1->messageid);
2012         $this->assertEquals(\core_message\api::MESSAGE_ACTION_READ, $mua1->action);
2013         $this->assertEquals(11, $mua1->timecreated);
2015         // Confirm second action.
2016         $this->assertEquals($user1->id, $mua2->userid);
2017         $this->assertEquals($m4id, $mua2->messageid);
2018         $this->assertEquals(\core_message\api::MESSAGE_ACTION_READ, $mua2->action);
2019         $this->assertEquals(12, $mua2->timecreated);
2020     }
2022     /**
2023      * Test marking a notification as read.
2024      */
2025     public function test_mark_notification_as_read() {
2026         global $DB;
2028         $user1 = self::getDataGenerator()->create_user();
2029         $user2 = self::getDataGenerator()->create_user();
2031         $this->send_fake_message($user1, $user2, 'Notification 1', 1);
2032         $n2id = $this->send_fake_message($user1, $user2, 'Notification 2', 1);
2033         $this->send_fake_message($user2, $user1, 'Notification 3', 1);
2034         $n4id = $this->send_fake_message($user2, $user1, 'Notification 4', 1);
2036         $n2 = $DB->get_record('notifications', ['id' => $n2id]);
2037         $n4 = $DB->get_record('notifications', ['id' => $n4id]);
2039         \core_message\api::mark_notification_as_read($n2, 11);
2040         \core_message\api::mark_notification_as_read($n4, 12);
2042         // Retrieve the notifications.
2043         $n2 = $DB->get_record('notifications', ['id' => $n2id]);
2044         $n4 = $DB->get_record('notifications', ['id' => $n4id]);
2046         // Confirm they have been marked as read.
2047         $this->assertEquals(11, $n2->timeread);
2048         $this->assertEquals(12, $n4->timeread);
2049     }
2051     /**
2052      * Test a conversation is not returned if there is none.
2053      */
2054     public function test_get_conversation_between_users_no_conversation() {
2055         $user1 = self::getDataGenerator()->create_user();
2056         $user2 = self::getDataGenerator()->create_user();
2058         $this->assertFalse(\core_message\api::get_conversation_between_users([$user1->id, $user2->id]));
2059     }
2061     /**
2062      * Test we can return a conversation that exists between users.
2063      */
2064     public function test_get_conversation_between_users_with_existing_conversation() {
2065         $user1 = self::getDataGenerator()->create_user();
2066         $user2 = self::getDataGenerator()->create_user();
2068         $conversationid = \core_message\api::create_conversation_between_users([$user1->id, $user2->id]);
2070         $this->assertEquals($conversationid,
2071             \core_message\api::get_conversation_between_users([$user1->id, $user2->id]));
2072     }
2074     /**
2075      * Test can create a contact request.
2076      */
2077     public function test_can_create_contact_request() {
2078         global $CFG;
2080         $user1 = self::getDataGenerator()->create_user();
2081         $user2 = self::getDataGenerator()->create_user();
2083         // Disable messaging.
2084         $CFG->messaging = 0;
2085         $this->assertFalse(\core_message\api::can_create_contact($user1->id, $user2->id));
2087         // Re-enable messaging.
2088         $CFG->messaging = 1;
2090         // Allow users to message anyone site-wide.
2091         $CFG->messagingallusers = 1;
2092         $this->assertTrue(\core_message\api::can_create_contact($user1->id, $user2->id));
2094         // Disallow users from messaging anyone site-wide.
2095         $CFG->messagingallusers = 0;
2096         $this->assertFalse(\core_message\api::can_create_contact($user1->id, $user2->id));
2098         // Put the users in the same course so a contact request should be possible.
2099         $course = self::getDataGenerator()->create_course();
2100         $this->getDataGenerator()->enrol_user($user1->id, $course->id);
2101         $this->getDataGenerator()->enrol_user($user2->id, $course->id);
2102         $this->assertTrue(\core_message\api::can_create_contact($user1->id, $user2->id));
2103     }
2105     /**
2106      * Test creating a contact request.
2107      */
2108     public function test_create_contact_request() {
2109         global $DB;
2111         $user1 = self::getDataGenerator()->create_user();
2112         $user2 = self::getDataGenerator()->create_user();
2114         \core_message\api::create_contact_request($user1->id, $user2->id);
2116         $request = $DB->get_records('message_contact_requests');
2118         $this->assertCount(1, $request);
2120         $request = reset($request);
2122         $this->assertEquals($user1->id, $request->userid);
2123         $this->assertEquals($user2->id, $request->requesteduserid);
2124     }
2126     /**
2127      * Test confirming a contact request.
2128      */
2129     public function test_confirm_contact_request() {
2130         global $DB;
2132         $user1 = self::getDataGenerator()->create_user();
2133         $user2 = self::getDataGenerator()->create_user();
2135         \core_message\api::create_contact_request($user1->id, $user2->id);
2137         \core_message\api::confirm_contact_request($user1->id, $user2->id);
2139         $this->assertEquals(0, $DB->count_records('message_contact_requests'));
2141         $contact = $DB->get_records('message_contacts');
2143         $this->assertCount(1, $contact);
2145         $contact = reset($contact);
2147         $this->assertEquals($user1->id, $contact->userid);
2148         $this->assertEquals($user2->id, $contact->contactid);
2149     }
2151     /**
2152      * Test declining a contact request.
2153      */
2154     public function test_decline_contact_request() {
2155         global $DB;
2157         $user1 = self::getDataGenerator()->create_user();
2158         $user2 = self::getDataGenerator()->create_user();
2160         \core_message\api::create_contact_request($user1->id, $user2->id);
2162         \core_message\api::decline_contact_request($user1->id, $user2->id);
2164         $this->assertEquals(0, $DB->count_records('message_contact_requests'));
2165         $this->assertEquals(0, $DB->count_records('message_contacts'));
2166     }
2168     /**
2169      * Test retrieving contact requests.
2170      */
2171     public function test_get_contact_requests() {
2172         $user1 = self::getDataGenerator()->create_user();
2173         $user2 = self::getDataGenerator()->create_user();
2174         $user3 = self::getDataGenerator()->create_user();
2176         // Block one user, their request should not show up.
2177         \core_message\api::block_user($user1->id, $user3->id);
2179         \core_message\api::create_contact_request($user2->id, $user1->id);
2180         \core_message\api::create_contact_request($user3->id, $user1->id);
2182         $requests = \core_message\api::get_contact_requests($user1->id);
2184         $this->assertCount(1, $requests);
2186         $request = reset($requests);
2188         $this->assertEquals($user2->id, $request->id);
2189         $this->assertEquals($user2->picture, $request->picture);
2190         $this->assertEquals($user2->firstname, $request->firstname);
2191         $this->assertEquals($user2->lastname, $request->lastname);
2192         $this->assertEquals($user2->firstnamephonetic, $request->firstnamephonetic);
2193         $this->assertEquals($user2->lastnamephonetic, $request->lastnamephonetic);
2194         $this->assertEquals($user2->middlename, $request->middlename);
2195         $this->assertEquals($user2->alternatename, $request->alternatename);
2196         $this->assertEquals($user2->email, $request->email);
2197     }
2199     /**
2200      * Test adding contacts.
2201      */
2202     public function test_add_contact() {
2203         global $DB;
2205         $user1 = self::getDataGenerator()->create_user();
2206         $user2 = self::getDataGenerator()->create_user();
2208         \core_message\api::add_contact($user1->id, $user2->id);
2210         $contact = $DB->get_records('message_contacts');
2212         $this->assertCount(1, $contact);
2214         $contact = reset($contact);
2216         $this->assertEquals($user1->id, $contact->userid);
2217         $this->assertEquals($user2->id, $contact->contactid);
2218     }
2220     /**
2221      * Test removing contacts.
2222      */
2223     public function test_remove_contact() {
2224         global $DB;
2226         $user1 = self::getDataGenerator()->create_user();
2227         $user2 = self::getDataGenerator()->create_user();
2229         \core_message\api::add_contact($user1->id, $user2->id);
2230         \core_message\api::remove_contact($user1->id, $user2->id);
2232         $this->assertEquals(0, $DB->count_records('message_contacts'));
2233     }
2235     /**
2236      * Test blocking users.
2237      */
2238     public function test_block_user() {
2239         global $DB;
2241         $user1 = self::getDataGenerator()->create_user();
2242         $user2 = self::getDataGenerator()->create_user();
2244         \core_message\api::block_user($user1->id, $user2->id);
2246         $blockedusers = $DB->get_records('message_users_blocked');
2248         $this->assertCount(1, $blockedusers);
2250         $blockeduser = reset($blockedusers);
2252         $this->assertEquals($user1->id, $blockeduser->userid);
2253         $this->assertEquals($user2->id, $blockeduser->blockeduserid);
2254     }
2256     /**
2257      * Test unblocking users.
2258      */
2259     public function test_unblock_user() {
2260         global $DB;
2262         $user1 = self::getDataGenerator()->create_user();
2263         $user2 = self::getDataGenerator()->create_user();
2265         \core_message\api::block_user($user1->id, $user2->id);
2266         \core_message\api::unblock_user($user1->id, $user2->id);
2268         $this->assertEquals(0, $DB->count_records('message_users_blocked'));
2269     }
2271     /**
2272      * Test is contact check.
2273      */
2274     public function test_is_contact() {
2275         $user1 = self::getDataGenerator()->create_user();
2276         $user2 = self::getDataGenerator()->create_user();
2277         $user3 = self::getDataGenerator()->create_user();
2279         \core_message\api::add_contact($user1->id, $user2->id);
2281         $this->assertTrue(\core_message\api::is_contact($user1->id, $user2->id));
2282         $this->assertTrue(\core_message\api::is_contact($user2->id, $user1->id));
2283         $this->assertFalse(\core_message\api::is_contact($user2->id, $user3->id));
2284     }
2286     /**
2287      * Test get contact.
2288      */
2289     public function test_get_contact() {
2290         $user1 = self::getDataGenerator()->create_user();
2291         $user2 = self::getDataGenerator()->create_user();
2293         \core_message\api::add_contact($user1->id, $user2->id);
2295         $contact = \core_message\api::get_contact($user1->id, $user2->id);
2297         $this->assertEquals($user1->id, $contact->userid);
2298         $this->assertEquals($user2->id, $contact->contactid);
2299     }
2301     /**
2302      * Test is blocked checked.
2303      */
2304     public function test_is_blocked() {
2305         $user1 = self::getDataGenerator()->create_user();
2306         $user2 = self::getDataGenerator()->create_user();
2308         $this->assertFalse(\core_message\api::is_blocked($user1->id, $user2->id));
2309         $this->assertFalse(\core_message\api::is_blocked($user2->id, $user1->id));
2311         \core_message\api::block_user($user1->id, $user2->id);
2313         $this->assertTrue(\core_message\api::is_blocked($user1->id, $user2->id));
2314         $this->assertFalse(\core_message\api::is_blocked($user2->id, $user1->id));
2315     }
2317     /**
2318      * Test the contact request exist check.
2319      */
2320     public function test_does_contact_request_exist() {
2321         $user1 = self::getDataGenerator()->create_user();
2322         $user2 = self::getDataGenerator()->create_user();
2324         $this->assertFalse(\core_message\api::does_contact_request_exist($user1->id, $user2->id));
2325         $this->assertFalse(\core_message\api::does_contact_request_exist($user2->id, $user1->id));
2327         \core_message\api::create_contact_request($user1->id, $user2->id);
2329         $this->assertTrue(\core_message\api::does_contact_request_exist($user1->id, $user2->id));
2330         $this->assertTrue(\core_message\api::does_contact_request_exist($user2->id, $user1->id));
2331     }
2333     /**
2334      * Comparison function for sorting contacts.
2335      *
2336      * @param stdClass $a
2337      * @param stdClass $b
2338      * @return bool
2339      */
2340     protected static function sort_contacts($a, $b) {
2341         return $a->userid > $b->userid;
2342     }