MDL-64632 core_message: fixed PHP error when users are deleted from DB
[moodle.git] / message / tests / externallib_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  * External message functions unit tests
19  *
20  * @package    core_message
21  * @category   external
22  * @copyright  2012 Jerome Mouneyrac
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 . '/webservice/tests/helpers.php');
31 require_once($CFG->dirroot . '/message/externallib.php');
33 use \core_message\tests\helper as testhelper;
35 class core_message_externallib_testcase extends externallib_advanced_testcase {
37     /**
38      * Tests set up
39      */
40     protected function setUp() {
41         global $CFG;
43         require_once($CFG->dirroot . '/message/lib.php');
44     }
46     /**
47      * Send a fake message.
48      *
49      * {@link message_send()} does not support transaction, this function will simulate a message
50      * sent from a user to another. We should stop using it once {@link message_send()} will support
51      * transactions. This is not clean at all, this is just used to add rows to the table.
52      *
53      * @param stdClass $userfrom user object of the one sending the message.
54      * @param stdClass $userto user object of the one receiving the message.
55      * @param string $message message to send.
56      * @param int $notification is the message a notification.
57      * @param int $time the time the message was sent
58      */
59     protected function send_message($userfrom, $userto, $message = 'Hello world!', $notification = 0, $time = 0) {
60         global $DB;
62         if (empty($time)) {
63             $time = time();
64         }
66         if ($notification) {
67             $record = new stdClass();
68             $record->useridfrom = $userfrom->id;
69             $record->useridto = $userto->id;
70             $record->subject = 'No subject';
71             $record->fullmessage = $message;
72             $record->smallmessage = $message;
73             $record->timecreated = $time;
75             return $DB->insert_record('notifications', $record);
76         }
78         if (!$conversationid = \core_message\api::get_conversation_between_users([$userfrom->id, $userto->id])) {
79             $conversation = \core_message\api::create_conversation(
80                 \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
81                 [
82                     $userfrom->id,
83                     $userto->id
84                 ]
85             );
86             $conversationid = $conversation->id;
87         }
89         // Ok, send the message.
90         $record = new stdClass();
91         $record->useridfrom = $userfrom->id;
92         $record->conversationid = $conversationid;
93         $record->subject = 'No subject';
94         $record->fullmessage = $message;
95         $record->smallmessage = $message;
96         $record->timecreated = $time;
98         return $DB->insert_record('messages', $record);
99     }
101     /**
102      * Test send_instant_messages.
103      */
104     public function test_send_instant_messages() {
105         global $DB, $USER;
107         $this->resetAfterTest();
109         // Transactions used in tests, tell phpunit use alternative reset method.
110         $this->preventResetByRollback();
112         $user1 = self::getDataGenerator()->create_user();
113         $user2 = self::getDataGenerator()->create_user();
115         $this->setUser($user1);
117         // Create test message data.
118         $message1 = array();
119         $message1['touserid'] = $user2->id;
120         $message1['text'] = 'the message.';
121         $message1['clientmsgid'] = 4;
122         $messages = array($message1);
124         $sentmessages = core_message_external::send_instant_messages($messages);
125         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
126         $this->assertEquals(
127             get_string('usercantbemessaged', 'message', fullname(\core_user::get_user($message1['touserid']))),
128             array_pop($sentmessages)['errormessage']
129         );
131         // Add the user1 as a contact.
132         \core_message\api::add_contact($user1->id, $user2->id);
134         // Send message again. Now it should work properly.
135         $sentmessages = core_message_external::send_instant_messages($messages);
136         // We need to execute the return values cleaning process to simulate the web service server.
137         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
139         $sentmessage = reset($sentmessages);
141         $sql = "SELECT m.*, mcm.userid as useridto
142                  FROM {messages} m
143            INNER JOIN {message_conversations} mc
144                    ON m.conversationid = mc.id
145            INNER JOIN {message_conversation_members} mcm
146                    ON mcm.conversationid = mc.id
147                 WHERE mcm.userid != ?
148                   AND m.id = ?";
149         $themessage = $DB->get_record_sql($sql, [$USER->id, $sentmessage['msgid']]);
151         // Confirm that the message was inserted correctly.
152         $this->assertEquals($themessage->useridfrom, $user1->id);
153         $this->assertEquals($themessage->useridto, $message1['touserid']);
154         $this->assertEquals($themessage->smallmessage, $message1['text']);
155         $this->assertEquals($sentmessage['clientmsgid'], $message1['clientmsgid']);
156     }
158     /**
159      * Test send_instant_messages to a user who has blocked you.
160      */
161     public function test_send_instant_messages_blocked_user() {
162         global $DB;
164         $this->resetAfterTest();
166         // Transactions used in tests, tell phpunit use alternative reset method.
167         $this->preventResetByRollback();
169         $user1 = self::getDataGenerator()->create_user();
170         $user2 = self::getDataGenerator()->create_user();
172         $this->setUser($user1);
174         \core_message\api::block_user($user2->id, $user1->id);
176         // Create test message data.
177         $message1 = array();
178         $message1['touserid'] = $user2->id;
179         $message1['text'] = 'the message.';
180         $message1['clientmsgid'] = 4;
181         $messages = array($message1);
183         $sentmessages = core_message_external::send_instant_messages($messages);
184         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
186         $sentmessage = reset($sentmessages);
188         $this->assertEquals(get_string('usercantbemessaged', 'message', fullname($user2)), $sentmessage['errormessage']);
190         $this->assertEquals(0, $DB->count_records('messages'));
191     }
193     /**
194      * Test send_instant_messages when sending a message to a non-contact who has blocked non-contacts.
195      */
196     public function test_send_instant_messages_block_non_contacts() {
197         global $DB;
199         $this->resetAfterTest(true);
201         // Transactions used in tests, tell phpunit use alternative reset method.
202         $this->preventResetByRollback();
204         $user1 = self::getDataGenerator()->create_user();
205         $user2 = self::getDataGenerator()->create_user();
207         $this->setUser($user1);
209         // Set the user preference so user 2 does not accept messages from non-contacts.
210         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2);
212         // Create test message data.
213         $message1 = array();
214         $message1['touserid'] = $user2->id;
215         $message1['text'] = 'the message.';
216         $message1['clientmsgid'] = 4;
217         $messages = array($message1);
219         $sentmessages = core_message_external::send_instant_messages($messages);
220         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
222         $sentmessage = reset($sentmessages);
224         $this->assertEquals(get_string('usercantbemessaged', 'message', fullname($user2)), $sentmessage['errormessage']);
226         $this->assertEquals(0, $DB->count_records('messages'));
227     }
229     /**
230      * Test send_instant_messages when sending a message to a contact who has blocked non-contacts.
231      */
232     public function test_send_instant_messages_block_non_contacts_but_am_contact() {
233         global $DB, $USER;
235         $this->resetAfterTest(true);
237         // Transactions used in tests, tell phpunit use alternative reset method.
238         $this->preventResetByRollback();
240         $user1 = self::getDataGenerator()->create_user();
241         $user2 = self::getDataGenerator()->create_user();
243         $this->setUser($user1);
245         // Set the user preference so user 2 does not accept messages from non-contacts.
246         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2);
248         \core_message\api::add_contact($user1->id, $user2->id);
250         // Create test message data.
251         $message1 = array();
252         $message1['touserid'] = $user2->id;
253         $message1['text'] = 'the message.';
254         $message1['clientmsgid'] = 4;
255         $messages = array($message1);
257         $sentmessages = core_message_external::send_instant_messages($messages);
258         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
260         $sentmessage = reset($sentmessages);
262         $sql = "SELECT m.*, mcm.userid as useridto
263                  FROM {messages} m
264            INNER JOIN {message_conversations} mc
265                    ON m.conversationid = mc.id
266            INNER JOIN {message_conversation_members} mcm
267                    ON mcm.conversationid = mc.id
268                 WHERE mcm.userid != ?
269                   AND m.id = ?";
270         $themessage = $DB->get_record_sql($sql, [$USER->id, $sentmessage['msgid']]);
272         // Confirm that the message was inserted correctly.
273         $this->assertEquals($themessage->useridfrom, $user1->id);
274         $this->assertEquals($themessage->useridto, $message1['touserid']);
275         $this->assertEquals($themessage->smallmessage, $message1['text']);
276         $this->assertEquals($sentmessage['clientmsgid'], $message1['clientmsgid']);
277     }
279     /**
280      * Test send_instant_messages with no capabilities
281      */
282     public function test_send_instant_messages_no_capability() {
283         global $DB;
285         $this->resetAfterTest(true);
287         // Transactions used in tests, tell phpunit use alternative reset method.
288         $this->preventResetByRollback();
290         $user1 = self::getDataGenerator()->create_user();
291         $user2 = self::getDataGenerator()->create_user();
293         $this->setUser($user1);
295         // Unset the required capabilities by the external function.
296         $contextid = context_system::instance()->id;
297         $userrole = $DB->get_record('role', array('shortname' => 'user'));
298         $this->unassignUserCapability('moodle/site:sendmessage', $contextid, $userrole->id);
300         // Create test message data.
301         $message1 = array();
302         $message1['touserid'] = $user2->id;
303         $message1['text'] = 'the message.';
304         $message1['clientmsgid'] = 4;
305         $messages = array($message1);
307         $this->expectException('required_capability_exception');
308         core_message_external::send_instant_messages($messages);
309     }
311     /**
312      * Test send_instant_messages when messaging is disabled.
313      */
314     public function test_send_instant_messages_messaging_disabled() {
315         global $CFG;
317         $this->resetAfterTest(true);
319         // Transactions used in tests, tell phpunit use alternative reset method.
320         $this->preventResetByRollback();
322         $user1 = self::getDataGenerator()->create_user();
323         $user2 = self::getDataGenerator()->create_user();
325         $this->setUser($user1);
327         // Disable messaging.
328         $CFG->messaging = 0;
330         // Create test message data.
331         $message1 = array();
332         $message1['touserid'] = $user2->id;
333         $message1['text'] = 'the message.';
334         $message1['clientmsgid'] = 4;
335         $messages = array($message1);
337         $this->expectException('moodle_exception');
338         core_message_external::send_instant_messages($messages);
339     }
341     /**
342      * Test create_contacts.
343      */
344     public function test_create_contacts() {
345         $this->resetAfterTest(true);
347         $user1 = self::getDataGenerator()->create_user();
348         $user2 = self::getDataGenerator()->create_user();
349         $user3 = self::getDataGenerator()->create_user();
350         $user4 = self::getDataGenerator()->create_user();
351         $user5 = self::getDataGenerator()->create_user();
352         $this->setUser($user1);
354         // Adding a contact.
355         $return = core_message_external::create_contacts(array($user2->id));
356         $this->assertDebuggingCalled();
357         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
358         $this->assertEquals(array(), $return);
360         // Adding a contact who is already a contact.
361         $return = core_message_external::create_contacts(array($user2->id));
362         $this->assertDebuggingCalled();
363         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
364         $this->assertEquals(array(), $return);
366         // Adding multiple contacts.
367         $return = core_message_external::create_contacts(array($user3->id, $user4->id));
368         $this->assertDebuggingCalledCount(2);
369         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
370         $this->assertEquals(array(), $return);
372         // Adding a non-existing user.
373         $return = core_message_external::create_contacts(array(99999));
374         $this->assertDebuggingCalled();
375         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
376         $this->assertCount(1, $return);
377         $return = array_pop($return);
378         $this->assertEquals($return['warningcode'], 'contactnotcreated');
379         $this->assertEquals($return['itemid'], 99999);
381         // Adding contacts with valid and invalid parameters.
382         $return = core_message_external::create_contacts(array($user5->id, 99999));
383         $this->assertDebuggingCalledCount(2);
384         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
385         $this->assertCount(1, $return);
386         $return = array_pop($return);
387         $this->assertEquals($return['warningcode'], 'contactnotcreated');
388         $this->assertEquals($return['itemid'], 99999);
390         // Try to add a contact to another user, should throw an exception.
391         // All assertions must be added before this point.
392         $this->expectException('required_capability_exception');
393         core_message_external::create_contacts(array($user2->id), $user3->id);
394     }
396     /**
397      * Test delete_contacts.
398      */
399     public function test_delete_contacts() {
400         $this->resetAfterTest(true);
402         $user1 = self::getDataGenerator()->create_user();
403         $user2 = self::getDataGenerator()->create_user();
404         $user3 = self::getDataGenerator()->create_user();
405         $user4 = self::getDataGenerator()->create_user();
406         $user5 = self::getDataGenerator()->create_user();
407         $user6 = self::getDataGenerator()->create_user();
408         $this->setUser($user1);
410         \core_message\api::add_contact($user1->id, $user3->id);
411         \core_message\api::add_contact($user1->id, $user4->id);
412         \core_message\api::add_contact($user1->id, $user5->id);
413         \core_message\api::add_contact($user1->id, $user6->id);
415         // Removing a non-contact.
416         $return = core_message_external::delete_contacts(array($user2->id));
417         $this->assertNull($return);
419         // Removing one contact.
420         $return = core_message_external::delete_contacts(array($user3->id));
421         $this->assertNull($return);
423         // Removing multiple contacts.
424         $return = core_message_external::delete_contacts(array($user4->id, $user5->id));
425         $this->assertNull($return);
427         // Removing contact from unexisting user.
428         $return = core_message_external::delete_contacts(array(99999));
429         $this->assertNull($return);
431         // Removing mixed valid and invalid data.
432         $return = core_message_external::delete_contacts(array($user6->id, 99999));
433         $this->assertNull($return);
435         // Try to delete a contact of another user contact list, should throw an exception.
436         // All assertions must be added before this point.
437         $this->expectException('required_capability_exception');
438         core_message_external::delete_contacts(array($user2->id), $user3->id);
439     }
441     /**
442      * Test block_contacts.
443      */
444     public function test_block_contacts() {
445         $this->resetAfterTest(true);
447         $user1 = self::getDataGenerator()->create_user();
448         $user2 = self::getDataGenerator()->create_user();
449         $user3 = self::getDataGenerator()->create_user();
450         $user4 = self::getDataGenerator()->create_user();
451         $user5 = self::getDataGenerator()->create_user();
452         $this->setUser($user1);
454         \core_message\api::add_contact($user1->id, $user3->id);
455         \core_message\api::add_contact($user1->id, $user4->id);
456         \core_message\api::add_contact($user1->id, $user5->id);
458         // Blocking a contact.
459         $return = core_message_external::block_contacts(array($user2->id));
460         $this->assertDebuggingCalled();
461         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
462         $this->assertEquals(array(), $return);
464         // Blocking a contact who is already a contact.
465         $return = core_message_external::block_contacts(array($user2->id));
466         $this->assertDebuggingCalled();
467         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
468         $this->assertEquals(array(), $return);
470         // Blocking multiple contacts.
471         $return = core_message_external::block_contacts(array($user3->id, $user4->id));
472         $this->assertDebuggingCalledCount(2);
473         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
474         $this->assertEquals(array(), $return);
476         // Blocking a non-existing user.
477         $return = core_message_external::block_contacts(array(99999));
478         $this->assertDebuggingCalled();
479         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
480         $this->assertCount(1, $return);
481         $return = array_pop($return);
482         $this->assertEquals($return['warningcode'], 'contactnotblocked');
483         $this->assertEquals($return['itemid'], 99999);
485         // Blocking contacts with valid and invalid parameters.
486         $return = core_message_external::block_contacts(array($user5->id, 99999));
487         $this->assertDebuggingCalledCount(2);
488         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
489         $this->assertCount(1, $return);
490         $return = array_pop($return);
491         $this->assertEquals($return['warningcode'], 'contactnotblocked');
492         $this->assertEquals($return['itemid'], 99999);
494         // Try to block a contact of another user contact list, should throw an exception.
495         // All assertions must be added before this point.
496         $this->expectException('required_capability_exception');
497         core_message_external::block_contacts(array($user2->id), $user3->id);
498     }
500     /**
501      * Test unblock_contacts.
502      */
503     public function test_unblock_contacts() {
504         $this->resetAfterTest(true);
506         $user1 = self::getDataGenerator()->create_user();
507         $user2 = self::getDataGenerator()->create_user();
508         $user3 = self::getDataGenerator()->create_user();
509         $user4 = self::getDataGenerator()->create_user();
510         $user5 = self::getDataGenerator()->create_user();
511         $user6 = self::getDataGenerator()->create_user();
512         $this->setUser($user1);
514         \core_message\api::add_contact($user1->id, $user3->id);
515         \core_message\api::add_contact($user1->id, $user4->id);
516         \core_message\api::add_contact($user1->id, $user5->id);
517         \core_message\api::add_contact($user1->id, $user6->id);
519         // Removing a non-contact.
520         $return = core_message_external::unblock_contacts(array($user2->id));
521         $this->assertDebuggingCalled();
522         $this->assertNull($return);
524         // Removing one contact.
525         $return = core_message_external::unblock_contacts(array($user3->id));
526         $this->assertDebuggingCalled();
527         $this->assertNull($return);
529         // Removing multiple contacts.
530         $return = core_message_external::unblock_contacts(array($user4->id, $user5->id));
531         $this->assertDebuggingCalledCount(2);
532         $this->assertNull($return);
534         // Removing contact from unexisting user.
535         $return = core_message_external::unblock_contacts(array(99999));
536         $this->assertDebuggingCalled();
537         $this->assertNull($return);
539         // Removing mixed valid and invalid data.
540         $return = core_message_external::unblock_contacts(array($user6->id, 99999));
541         $this->assertDebuggingCalledCount(2);
542         $this->assertNull($return);
544         // Try to unblock a contact of another user contact list, should throw an exception.
545         // All assertions must be added before this point.
546         $this->expectException('required_capability_exception');
547         core_message_external::unblock_contacts(array($user2->id), $user3->id);
548         $this->assertDebuggingCalled();
549     }
551     /**
552      * Test getting contact requests.
553      */
554     public function test_get_contact_requests() {
555         global $PAGE;
557         $this->resetAfterTest();
559         $user1 = self::getDataGenerator()->create_user();
560         $user2 = self::getDataGenerator()->create_user();
561         $user3 = self::getDataGenerator()->create_user();
563         $this->setUser($user1);
565         // Block one user, their request should not show up.
566         \core_message\api::block_user($user1->id, $user3->id);
568         \core_message\api::create_contact_request($user2->id, $user1->id);
569         \core_message\api::create_contact_request($user3->id, $user1->id);
571         $requests = core_message_external::get_contact_requests($user1->id);
572         $requests = external_api::clean_returnvalue(core_message_external::get_contact_requests_returns(), $requests);
574         $this->assertCount(1, $requests);
576         $request = reset($requests);
577         $userpicture = new \user_picture($user2);
578         $profileimageurl = $userpicture->get_url($PAGE)->out(false);
580         $this->assertEquals($user2->id, $request['id']);
581         $this->assertEquals(fullname($user2), $request['fullname']);
582         $this->assertArrayHasKey('profileimageurl', $request);
583         $this->assertArrayHasKey('profileimageurlsmall', $request);
584         $this->assertArrayHasKey('isonline', $request);
585         $this->assertArrayHasKey('showonlinestatus', $request);
586         $this->assertArrayHasKey('isblocked', $request);
587         $this->assertArrayHasKey('iscontact', $request);
588     }
590     /**
591      * Test the get_contact_requests() function when the user has blocked the sender of the request.
592      */
593     public function test_get_contact_requests_blocked_sender() {
594         $this->resetAfterTest();
595         $user1 = self::getDataGenerator()->create_user();
596         $user2 = self::getDataGenerator()->create_user();
598         // User1 blocks User2.
599         \core_message\api::block_user($user1->id, $user2->id);
601         // User2 tries to add User1 as a contact.
602         \core_message\api::create_contact_request($user2->id, $user1->id);
604         // Verify we don't see the contact request from the blocked user User2 in the requests for User1.
605         $this->setUser($user1);
606         $requests = core_message_external::get_contact_requests($user1->id);
607         $requests = external_api::clean_returnvalue(core_message_external::get_contact_requests_returns(), $requests);
609         $this->assertCount(0, $requests);
610     }
612     /**
613      * Test getting contact requests when there are none.
614      */
615     public function test_get_contact_requests_no_requests() {
616         $this->resetAfterTest();
618         $user1 = self::getDataGenerator()->create_user();
620         $this->setUser($user1);
622         $requests = core_message_external::get_contact_requests($user1->id);
623         $requests = external_api::clean_returnvalue(core_message_external::get_contact_requests_returns(), $requests);
625         $this->assertEmpty($requests);
626     }
628     /**
629      * Test getting contact requests with limits.
630      */
631     public function test_get_contact_requests_with_limits() {
632         $this->resetAfterTest();
634         $user1 = self::getDataGenerator()->create_user();
635         $user2 = self::getDataGenerator()->create_user();
636         $user3 = self::getDataGenerator()->create_user();
638         $this->setUser($user1);
640         \core_message\api::create_contact_request($user2->id, $user1->id);
641         \core_message\api::create_contact_request($user3->id, $user1->id);
643         $requests = core_message_external::get_contact_requests($user1->id, 0, 1);
644         $requests = external_api::clean_returnvalue(core_message_external::get_contact_requests_returns(), $requests);
646         $this->assertCount(1, $requests);
647     }
649     /**
650      * Test getting contact requests with messaging disabled.
651      */
652     public function test_get_contact_requests_messaging_disabled() {
653         global $CFG;
655         $this->resetAfterTest();
657         // Create some skeleton data just so we can call the WS.
658         $user1 = self::getDataGenerator()->create_user();
660         $this->setUser($user1);
662         // Disable messaging.
663         $CFG->messaging = 0;
665         // Ensure an exception is thrown.
666         $this->expectException('moodle_exception');
667         core_message_external::get_contact_requests($user1->id);
668     }
670     /**
671      * Test getting contact requests with no permission.
672      */
673     public function test_get_contact_requests_no_permission() {
674         $this->resetAfterTest();
676         // Create some skeleton data just so we can call the WS.
677         $user1 = self::getDataGenerator()->create_user();
678         $user2 = self::getDataGenerator()->create_user();
679         $user3 = self::getDataGenerator()->create_user();
681         $this->setUser($user3);
683         // Ensure an exception is thrown.
684         $this->expectException('required_capability_exception');
685         core_message_external::create_contact_request($user1->id, $user2->id);
686     }
688     /**
689      * Test getting the number of received contact requests.
690      */
691     public function test_get_received_contact_requests_count() {
692         $this->resetAfterTest();
694         $user1 = self::getDataGenerator()->create_user();
695         $user2 = self::getDataGenerator()->create_user();
696         $user3 = self::getDataGenerator()->create_user();
697         $user4 = self::getDataGenerator()->create_user();
699         $this->setUser($user1);
701         $contactrequestnumber = core_message_external::get_received_contact_requests_count($user1->id);
702         $contactrequestnumber = external_api::clean_returnvalue(
703             core_message_external::get_received_contact_requests_count_returns(), $contactrequestnumber);
704         $this->assertEquals(0, $contactrequestnumber);
706         \core_message\api::create_contact_request($user2->id, $user1->id);
708         $contactrequestnumber = core_message_external::get_received_contact_requests_count($user1->id);
709         $contactrequestnumber = external_api::clean_returnvalue(
710             core_message_external::get_received_contact_requests_count_returns(), $contactrequestnumber);
711         $this->assertEquals(1, $contactrequestnumber);
713         \core_message\api::create_contact_request($user3->id, $user1->id);
715         $contactrequestnumber = core_message_external::get_received_contact_requests_count($user1->id);
716         $contactrequestnumber = external_api::clean_returnvalue(
717             core_message_external::get_received_contact_requests_count_returns(), $contactrequestnumber);
718         $this->assertEquals(2, $contactrequestnumber);
720         \core_message\api::create_contact_request($user1->id, $user4->id);
722         // Web service should ignore sent requests.
723         $contactrequestnumber = core_message_external::get_received_contact_requests_count($user1->id);
724         $contactrequestnumber = external_api::clean_returnvalue(
725             core_message_external::get_received_contact_requests_count_returns(), $contactrequestnumber);
726         $this->assertEquals(2, $contactrequestnumber);
727     }
729     /**
730      * Test the get_received_contact_requests_count() function when the user has blocked the sender of the request.
731      */
732     public function test_get_received_contact_requests_count_blocked_sender() {
733         $this->resetAfterTest();
734         $user1 = self::getDataGenerator()->create_user();
735         $user2 = self::getDataGenerator()->create_user();
737         // User1 blocks User2.
738         \core_message\api::block_user($user1->id, $user2->id);
740         // User2 tries to add User1 as a contact.
741         \core_message\api::create_contact_request($user2->id, $user1->id);
743         // Verify we don't see the contact request from the blocked user User2 in the count for User1.
744         $this->setUser($user1);
745         $contactrequestnumber = core_message_external::get_received_contact_requests_count($user1->id);
746         $contactrequestnumber = external_api::clean_returnvalue(
747             core_message_external::get_received_contact_requests_count_returns(), $contactrequestnumber);
748         $this->assertEquals(0, $contactrequestnumber);
749     }
751     /**
752      * Test getting the number of received contact requests with no permissions.
753      */
754     public function test_get_received_contact_requests_count_no_permission() {
755         $this->resetAfterTest();
757         // Create some skeleton data just so we can call the WS.
758         $user1 = self::getDataGenerator()->create_user();
759         $user2 = self::getDataGenerator()->create_user();
761         $this->setUser($user2);
763         // Ensure an exception is thrown.
764         $this->expectException('required_capability_exception');
765         core_message_external::get_received_contact_requests_count($user1->id);
766     }
768     /**
769      * Test getting the number of received contact requests with messaging disabled.
770      */
771     public function test_get_received_contact_requests_count_messaging_disabled() {
772         global $CFG;
774         $this->resetAfterTest();
776         // Create some skeleton data just so we can call the WS.
777         $user1 = self::getDataGenerator()->create_user();
779         $this->setUser($user1);
781         // Disable messaging.
782         $CFG->messaging = 0;
784         // Ensure an exception is thrown.
785         $this->expectException('moodle_exception');
786         core_message_external::get_received_contact_requests_count($user1->id);
787     }
789     /**
790      * Test creating a contact request.
791      */
792     public function test_create_contact_request() {
793         global $CFG, $DB;
795         $this->resetAfterTest();
797         $user1 = self::getDataGenerator()->create_user();
798         $user2 = self::getDataGenerator()->create_user();
800         $this->setUser($user1);
802         // Allow users to message anyone site-wide.
803         $CFG->messagingallusers = 1;
805         $return = core_message_external::create_contact_request($user1->id, $user2->id);
806         $return = external_api::clean_returnvalue(core_message_external::create_contact_request_returns(), $return);
807         $this->assertEquals([], $return['warnings']);
809         $request = $DB->get_records('message_contact_requests');
811         $this->assertCount(1, $request);
813         $request = reset($request);
815         $this->assertEquals($request->id, $return['request']['id']);
816         $this->assertEquals($request->userid, $return['request']['userid']);
817         $this->assertEquals($request->requesteduserid, $return['request']['requesteduserid']);
818         $this->assertEquals($request->timecreated, $return['request']['timecreated']);
819     }
821     /**
822      * Test creating a contact request when not allowed.
823      */
824     public function test_create_contact_request_not_allowed() {
825         global $CFG;
827         $this->resetAfterTest();
829         $user1 = self::getDataGenerator()->create_user();
830         $user2 = self::getDataGenerator()->create_user();
832         $this->setUser($user1);
834         $CFG->messagingallusers = 0;
836         $return = core_message_external::create_contact_request($user1->id, $user2->id);
837         $return = external_api::clean_returnvalue(core_message_external::create_contact_request_returns(), $return);
839         $warning = reset($return['warnings']);
841         $this->assertEquals('user', $warning['item']);
842         $this->assertEquals($user2->id, $warning['itemid']);
843         $this->assertEquals('cannotcreatecontactrequest', $warning['warningcode']);
844         $this->assertEquals('You are unable to create a contact request for this user', $warning['message']);
845     }
847     /**
848      * Test creating a contact request with messaging disabled.
849      */
850     public function test_create_contact_request_messaging_disabled() {
851         global $CFG;
853         $this->resetAfterTest();
855         // Create some skeleton data just so we can call the WS.
856         $user1 = self::getDataGenerator()->create_user();
857         $user2 = self::getDataGenerator()->create_user();
859         $this->setUser($user1);
861         // Disable messaging.
862         $CFG->messaging = 0;
864         // Ensure an exception is thrown.
865         $this->expectException('moodle_exception');
866         core_message_external::create_contact_request($user1->id, $user2->id);
867     }
869     /**
870      * Test creating a contact request with no permission.
871      */
872     public function test_create_contact_request_no_permission() {
873         $this->resetAfterTest();
875         // Create some skeleton data just so we can call the WS.
876         $user1 = self::getDataGenerator()->create_user();
877         $user2 = self::getDataGenerator()->create_user();
878         $user3 = self::getDataGenerator()->create_user();
880         $this->setUser($user3);
882         // Ensure an exception is thrown.
883         $this->expectException('required_capability_exception');
884         core_message_external::create_contact_request($user1->id, $user2->id);
885     }
887     /**
888      * Test confirming a contact request.
889      */
890     public function test_confirm_contact_request() {
891         global $DB;
893         $this->resetAfterTest();
895         $user1 = self::getDataGenerator()->create_user();
896         $user2 = self::getDataGenerator()->create_user();
898         $this->setUser($user1);
900         \core_message\api::create_contact_request($user1->id, $user2->id);
902         $this->setUser($user2);
904         $return = core_message_external::confirm_contact_request($user1->id, $user2->id);
905         $return = external_api::clean_returnvalue(core_message_external::confirm_contact_request_returns(), $return);
906         $this->assertEquals(array(), $return);
908         $this->assertEquals(0, $DB->count_records('message_contact_requests'));
910         $contact = $DB->get_records('message_contacts');
912         $this->assertCount(1, $contact);
914         $contact = reset($contact);
916         $this->assertEquals($user1->id, $contact->userid);
917         $this->assertEquals($user2->id, $contact->contactid);
918     }
920     /**
921      * Test confirming a contact request with messaging disabled.
922      */
923     public function test_confirm_contact_request_messaging_disabled() {
924         global $CFG;
926         $this->resetAfterTest();
928         // Create some skeleton data just so we can call the WS.
929         $user1 = self::getDataGenerator()->create_user();
930         $user2 = self::getDataGenerator()->create_user();
932         $this->setUser($user1);
934         // Disable messaging.
935         $CFG->messaging = 0;
937         // Ensure an exception is thrown.
938         $this->expectException('moodle_exception');
939         core_message_external::confirm_contact_request($user1->id, $user2->id);
940     }
942     /**
943      * Test confirming a contact request with no permission.
944      */
945     public function test_confirm_contact_request_no_permission() {
946         $this->resetAfterTest();
948         // Create some skeleton data just so we can call the WS.
949         $user1 = self::getDataGenerator()->create_user();
950         $user2 = self::getDataGenerator()->create_user();
951         $user3 = self::getDataGenerator()->create_user();
953         $this->setUser($user3);
955         // Ensure an exception is thrown.
956         $this->expectException('required_capability_exception');
957         core_message_external::confirm_contact_request($user1->id, $user2->id);
958     }
960     /**
961      * Test declining a contact request.
962      */
963     public function test_decline_contact_request() {
964         global $DB;
966         $this->resetAfterTest();
968         $user1 = self::getDataGenerator()->create_user();
969         $user2 = self::getDataGenerator()->create_user();
971         $this->setUser($user1);
973         \core_message\api::create_contact_request($user1->id, $user2->id);
975         $this->setUser($user2);
977         $return = core_message_external::decline_contact_request($user1->id, $user2->id);
978         $return = external_api::clean_returnvalue(core_message_external::decline_contact_request_returns(), $return);
979         $this->assertEquals(array(), $return);
981         $this->assertEquals(0, $DB->count_records('message_contact_requests'));
982         $this->assertEquals(0, $DB->count_records('message_contacts'));
983     }
985     /**
986      * Test declining a contact request with messaging disabled.
987      */
988     public function test_decline_contact_request_messaging_disabled() {
989         global $CFG;
991         $this->resetAfterTest();
993         // Create some skeleton data just so we can call the WS.
994         $user1 = self::getDataGenerator()->create_user();
995         $user2 = self::getDataGenerator()->create_user();
997         $this->setUser($user1);
999         // Disable messaging.
1000         $CFG->messaging = 0;
1002         // Ensure an exception is thrown.
1003         $this->expectException('moodle_exception');
1004         core_message_external::decline_contact_request($user1->id, $user2->id);
1005     }
1007     /**
1008      * Test declining a contact request with no permission.
1009      */
1010     public function test_decline_contact_request_no_permission() {
1011         $this->resetAfterTest();
1013         // Create some skeleton data just so we can call the WS.
1014         $user1 = self::getDataGenerator()->create_user();
1015         $user2 = self::getDataGenerator()->create_user();
1016         $user3 = self::getDataGenerator()->create_user();
1018         $this->setUser($user3);
1020         // Ensure an exception is thrown.
1021         $this->expectException('required_capability_exception');
1022         core_message_external::decline_contact_request($user1->id, $user2->id);
1023     }
1025     /**
1026      * Test blocking a user.
1027      */
1028     public function test_block_user() {
1029         global $DB;
1031         $this->resetAfterTest(true);
1033         $user1 = self::getDataGenerator()->create_user();
1034         $user2 = self::getDataGenerator()->create_user();
1036         $this->setUser($user1);
1038         // Blocking a user.
1039         $return = core_message_external::block_user($user1->id, $user2->id);
1040         $return = external_api::clean_returnvalue(core_message_external::block_user_returns(), $return);
1041         $this->assertEquals(array(), $return);
1043         // Get list of blocked users.
1044         $record = $DB->get_record('message_users_blocked', []);
1046         $this->assertEquals($user1->id, $record->userid);
1047         $this->assertEquals($user2->id, $record->blockeduserid);
1049         // Blocking a user who is already blocked.
1050         $return = core_message_external::block_user($user1->id, $user2->id);
1051         $return = external_api::clean_returnvalue(core_message_external::block_user_returns(), $return);
1052         $this->assertEquals(array(), $return);
1054         $this->assertEquals(1, $DB->count_records('message_users_blocked'));
1055     }
1057     /**
1058      * Test blocking a user with messaging disabled.
1059      */
1060     public function test_block_user_messaging_disabled() {
1061         global $CFG;
1063         $this->resetAfterTest();
1065         // Create some skeleton data just so we can call the WS.
1066         $user1 = self::getDataGenerator()->create_user();
1067         $user2 = self::getDataGenerator()->create_user();
1069         $this->setUser($user1);
1071         // Disable messaging.
1072         $CFG->messaging = 0;
1074         // Ensure an exception is thrown.
1075         $this->expectException('moodle_exception');
1076         core_message_external::block_user($user1->id, $user2->id);
1077     }
1079     /**
1080      * Test blocking a user with no permission.
1081      */
1082     public function test_block_user_no_permission() {
1083         $this->resetAfterTest();
1085         // Create some skeleton data just so we can call the WS.
1086         $user1 = self::getDataGenerator()->create_user();
1087         $user2 = self::getDataGenerator()->create_user();
1088         $user3 = self::getDataGenerator()->create_user();
1090         $this->setUser($user3);
1092         // Ensure an exception is thrown.
1093         $this->expectException('required_capability_exception');
1094         core_message_external::block_user($user1->id, $user2->id);
1095     }
1097     /**
1098      * Test unblocking a user.
1099      */
1100     public function test_unblock_user() {
1101         global $DB;
1103         $this->resetAfterTest(true);
1105         $user1 = self::getDataGenerator()->create_user();
1106         $user2 = self::getDataGenerator()->create_user();
1108         $this->setUser($user1);
1110         // Block the user.
1111         \core_message\api::block_user($user1->id, $user2->id);
1113         // Unblocking a user.
1114         $return = core_message_external::unblock_user($user1->id, $user2->id);
1115         $return = external_api::clean_returnvalue(core_message_external::unblock_user_returns(), $return);
1116         $this->assertEquals(array(), $return);
1118         $this->assertEquals(0, $DB->count_records('message_users_blocked'));
1120         // Unblocking a user who is already unblocked.
1121         $return = core_message_external::unblock_user($user1->id, $user2->id);
1122         $return = external_api::clean_returnvalue(core_message_external::unblock_user_returns(), $return);
1123         $this->assertEquals(array(), $return);
1125         $this->assertEquals(0, $DB->count_records('message_users_blocked'));
1126     }
1128     /**
1129      * Test unblocking a user with messaging disabled.
1130      */
1131     public function test_unblock_user_messaging_disabled() {
1132         global $CFG;
1134         $this->resetAfterTest();
1136         // Create some skeleton data just so we can call the WS.
1137         $user1 = self::getDataGenerator()->create_user();
1138         $user2 = self::getDataGenerator()->create_user();
1140         $this->setUser($user1);
1142         // Disable messaging.
1143         $CFG->messaging = 0;
1145         // Ensure an exception is thrown.
1146         $this->expectException('moodle_exception');
1147         core_message_external::unblock_user($user1->id, $user2->id);
1148     }
1150     /**
1151      * Test unblocking a user with no permission.
1152      */
1153     public function test_unblock_user_no_permission() {
1154         $this->resetAfterTest();
1156         // Create some skeleton data just so we can call the WS.
1157         $user1 = self::getDataGenerator()->create_user();
1158         $user2 = self::getDataGenerator()->create_user();
1159         $user3 = self::getDataGenerator()->create_user();
1161         $this->setUser($user3);
1163         // Ensure an exception is thrown.
1164         $this->expectException('required_capability_exception');
1165         core_message_external::unblock_user($user1->id, $user2->id);
1166     }
1168     /**
1169      * Test get_contacts.
1170      */
1171     public function test_get_contacts() {
1172         $this->resetAfterTest(true);
1174         $user1 = self::getDataGenerator()->create_user();
1175         $user_stranger = self::getDataGenerator()->create_user();
1176         $user_offline1 = self::getDataGenerator()->create_user();
1177         $user_offline2 = self::getDataGenerator()->create_user();
1178         $user_offline3 = self::getDataGenerator()->create_user();
1179         $user_online = new stdClass();
1180         $user_online->lastaccess = time();
1181         $user_online = self::getDataGenerator()->create_user($user_online);
1182         $user_blocked = self::getDataGenerator()->create_user();
1183         $noreplyuser = core_user::get_user(core_user::NOREPLY_USER);
1185         // Login as user1.
1186         $this->setUser($user1);
1187         \core_message\api::add_contact($user1->id, $user_offline1->id);
1188         \core_message\api::add_contact($user1->id, $user_offline2->id);
1189         \core_message\api::add_contact($user1->id, $user_offline3->id);
1190         \core_message\api::add_contact($user1->id, $user_online->id);
1192         // User_stranger sends a couple of messages to user1.
1193         $this->send_message($user_stranger, $user1, 'Hello there!');
1194         $this->send_message($user_stranger, $user1, 'How you goin?');
1195         $this->send_message($user_stranger, $user1, 'Cya!');
1196         $this->send_message($noreplyuser, $user1, 'I am not a real user');
1198         // User_blocked sends a message to user1.
1199         $this->send_message($user_blocked, $user1, 'Here, have some spam.');
1201         // Retrieve the contacts of the user.
1202         $this->setUser($user1);
1203         $contacts = core_message_external::get_contacts();
1204         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1205         $this->assertCount(3, $contacts['offline']);
1206         $this->assertCount(1, $contacts['online']);
1207         $this->assertCount(3, $contacts['strangers']);
1208         core_message_external::block_contacts(array($user_blocked->id));
1209         $this->assertDebuggingCalled();
1210         $contacts = core_message_external::get_contacts();
1211         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1212         $this->assertCount(3, $contacts['offline']);
1213         $this->assertCount(1, $contacts['online']);
1214         $this->assertCount(2, $contacts['strangers']);
1216         // Checking some of the fields returned.
1217         $stranger = array_pop($contacts['strangers']);
1219         $this->assertEquals(core_user::NOREPLY_USER, $stranger['id']);
1220         $this->assertEquals(1, $stranger['unread']);
1222         // Check that deleted users are not returned.
1223         delete_user($user_offline1);
1224         delete_user($user_stranger);
1225         delete_user($user_online);
1226         $contacts = core_message_external::get_contacts();
1227         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1228         $this->assertCount(2, $contacts['offline']);
1229         $this->assertCount(0, $contacts['online']);
1230         $this->assertCount(1, $contacts['strangers']);
1231     }
1233     /**
1234      * Test search_contacts.
1235      * @expectedException moodle_exception
1236      */
1237     public function test_search_contacts() {
1238         global $DB;
1239         $this->resetAfterTest(true);
1241         $course1 = $this->getDataGenerator()->create_course();
1242         $course2 = $this->getDataGenerator()->create_course();
1244         $user1 = new stdClass();
1245         $user1->firstname = 'X';
1246         $user1->lastname = 'X';
1247         $user1 = $this->getDataGenerator()->create_user($user1);
1248         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1249         $this->getDataGenerator()->enrol_user($user1->id, $course2->id);
1251         $user2 = new stdClass();
1252         $user2->firstname = 'Eric';
1253         $user2->lastname = 'Cartman';
1254         $user2 = self::getDataGenerator()->create_user($user2);
1255         $user3 = new stdClass();
1256         $user3->firstname = 'Stan';
1257         $user3->lastname = 'Marsh';
1258         $user3 = self::getDataGenerator()->create_user($user3);
1259         self::getDataGenerator()->enrol_user($user3->id, $course1->id);
1260         $user4 = new stdClass();
1261         $user4->firstname = 'Kyle';
1262         $user4->lastname = 'Broflovski';
1263         $user4 = self::getDataGenerator()->create_user($user4);
1264         $user5 = new stdClass();
1265         $user5->firstname = 'Kenny';
1266         $user5->lastname = 'McCormick';
1267         $user5 = self::getDataGenerator()->create_user($user5);
1268         self::getDataGenerator()->enrol_user($user5->id, $course2->id);
1270         $this->setUser($user1);
1272         $results = core_message_external::search_contacts('r');
1273         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1274         $this->assertCount(5, $results); // Users 2 through 5 + admin
1276         $results = core_message_external::search_contacts('r', true);
1277         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1278         $this->assertCount(2, $results);
1280         $results = core_message_external::search_contacts('Kyle', false);
1281         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1282         $this->assertCount(1, $results);
1283         $result = reset($results);
1284         $this->assertEquals($user4->id, $result['id']);
1286         $results = core_message_external::search_contacts('y', false);
1287         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1288         $this->assertCount(2, $results);
1290         $results = core_message_external::search_contacts('y', true);
1291         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1292         $this->assertCount(1, $results);
1293         $result = reset($results);
1294         $this->assertEquals($user5->id, $result['id']);
1296         // Empty query, will throw an exception.
1297         $results = core_message_external::search_contacts('');
1298     }
1300     /**
1301      * Test get_messages.
1302      */
1303     public function test_get_messages() {
1304         global $CFG, $DB;
1305         $this->resetAfterTest(true);
1307         $this->preventResetByRollback();
1308         // This mark the messages as read!.
1309         $sink = $this->redirectMessages();
1311         $user1 = self::getDataGenerator()->create_user();
1312         $user2 = self::getDataGenerator()->create_user();
1313         $user3 = self::getDataGenerator()->create_user();
1315         $course = self::getDataGenerator()->create_course();
1317         // Send a message from one user to another.
1318         message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
1319         message_post_message($user1, $user3, 'some random text 2', FORMAT_MOODLE);
1320         message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
1321         message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
1322         message_post_message($user3, $user1, 'some random text 5', FORMAT_MOODLE);
1324         $this->setUser($user1);
1325         // Get read conversations from user1 to user2.
1326         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
1327         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1328         $this->assertCount(1, $messages['messages']);
1330         // Delete the message.
1331         $message = array_shift($messages['messages']);
1332         \core_message\api::delete_message($user1->id, $message['id']);
1334         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
1335         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1336         $this->assertCount(0, $messages['messages']);
1338         // Get unread conversations from user1 to user2.
1339         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', false, true, 0, 0);
1340         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1341         $this->assertCount(0, $messages['messages']);
1343         // Get read messages send from user1.
1344         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1345         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1346         $this->assertCount(1, $messages['messages']);
1348         $this->setUser($user2);
1349         // Get read conversations from any user to user2.
1350         $messages = core_message_external::get_messages($user2->id, 0, 'conversations', true, true, 0, 0);
1351         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1352         $this->assertCount(2, $messages['messages']);
1354         // Conversations from user3 to user2.
1355         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
1356         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1357         $this->assertCount(1, $messages['messages']);
1359         // Delete the message.
1360         $message = array_shift($messages['messages']);
1361         \core_message\api::delete_message($user2->id, $message['id']);
1363         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
1364         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1365         $this->assertCount(0, $messages['messages']);
1367         $this->setUser($user3);
1368         // Get read notifications received by user3.
1369         $messages = core_message_external::get_messages($user3->id, 0, 'notifications', true, true, 0, 0);
1370         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1371         $this->assertCount(0, $messages['messages']);
1373         // Now, create some notifications...
1374         // We are creating fake notifications but based on real ones.
1376         // This one comes from a disabled plugin's provider and therefore is not sent.
1377         $eventdata = new \core\message\message();
1378         $eventdata->courseid          = $course->id;
1379         $eventdata->notification      = 1;
1380         $eventdata->modulename        = 'moodle';
1381         $eventdata->component         = 'enrol_paypal';
1382         $eventdata->name              = 'paypal_enrolment';
1383         $eventdata->userfrom          = get_admin();
1384         $eventdata->userto            = $user1;
1385         $eventdata->subject           = "Moodle: PayPal payment";
1386         $eventdata->fullmessage       = "Your PayPal payment is pending.";
1387         $eventdata->fullmessageformat = FORMAT_PLAIN;
1388         $eventdata->fullmessagehtml   = '';
1389         $eventdata->smallmessage      = '';
1390         message_send($eventdata);
1391         $this->assertDebuggingCalled('Attempt to send msg from a provider enrol_paypal/paypal_enrolment '.
1392             'that is inactive or not allowed for the user id='.$user1->id);
1394         // This one omits notification = 1.
1395         $message = new \core\message\message();
1396         $message->courseid          = $course->id;
1397         $message->component         = 'enrol_manual';
1398         $message->name              = 'expiry_notification';
1399         $message->userfrom          = $user2;
1400         $message->userto            = $user1;
1401         $message->subject           = 'Test: This is not a notification but otherwise is valid';
1402         $message->fullmessage       = 'Test: Full message';
1403         $message->fullmessageformat = FORMAT_MARKDOWN;
1404         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
1405         $message->smallmessage      = $message->subject;
1406         $message->contexturlname    = $course->fullname;
1407         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
1408         message_send($message);
1410         $message = new \core\message\message();
1411         $message->courseid          = $course->id;
1412         $message->notification      = 1;
1413         $message->component         = 'enrol_manual';
1414         $message->name              = 'expiry_notification';
1415         $message->userfrom          = $user2;
1416         $message->userto            = $user1;
1417         $message->subject           = 'Enrolment expired';
1418         $message->fullmessage       = 'Enrolment expired blah blah blah';
1419         $message->fullmessageformat = FORMAT_MARKDOWN;
1420         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
1421         $message->smallmessage      = $message->subject;
1422         $message->contexturlname    = $course->fullname;
1423         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
1424         message_send($message);
1426         $userfrom = core_user::get_noreply_user();
1427         $userfrom->maildisplay = true;
1428         $eventdata = new \core\message\message();
1429         $eventdata->courseid          = $course->id;
1430         $eventdata->component         = 'moodle';
1431         $eventdata->name              = 'badgecreatornotice';
1432         $eventdata->userfrom          = $userfrom;
1433         $eventdata->userto            = $user1;
1434         $eventdata->notification      = 1;
1435         $eventdata->subject           = 'New badge';
1436         $eventdata->fullmessage       = format_text_email($eventdata->subject, FORMAT_HTML);
1437         $eventdata->fullmessageformat = FORMAT_PLAIN;
1438         $eventdata->fullmessagehtml   = $eventdata->subject;
1439         $eventdata->smallmessage      = $eventdata->subject;
1440         message_send($eventdata);
1442         $eventdata = new \core\message\message();
1443         $eventdata->courseid         = $course->id;
1444         $eventdata->name             = 'submission';
1445         $eventdata->component        = 'mod_feedback';
1446         $eventdata->userfrom         = $user1;
1447         $eventdata->userto           = $user2;
1448         $eventdata->subject          = 'Feedback submitted';
1449         $eventdata->fullmessage      = 'Feedback submitted from an user';
1450         $eventdata->fullmessageformat = FORMAT_PLAIN;
1451         $eventdata->fullmessagehtml  = '<strong>Feedback submitted</strong>';
1452         $eventdata->smallmessage     = '';
1453         message_send($eventdata);
1455         $this->setUser($user1);
1456         // Get read notifications from any user to user1.
1457         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 0);
1458         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1459         $this->assertCount(3, $messages['messages']);
1461         // Get one read notifications from any user to user1.
1462         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 1);
1463         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1464         $this->assertCount(1, $messages['messages']);
1466         // Get unread notifications from any user to user1.
1467         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', false, true, 0, 0);
1468         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1469         $this->assertCount(0, $messages['messages']);
1471         // Get read both type of messages from any user to user1.
1472         $messages = core_message_external::get_messages($user1->id, 0, 'both', true, true, 0, 0);
1473         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1474         $this->assertCount(4, $messages['messages']);
1476         // Get read notifications from no-reply-user to user1.
1477         $messages = core_message_external::get_messages($user1->id, $userfrom->id, 'notifications', true, true, 0, 0);
1478         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1479         $this->assertCount(1, $messages['messages']);
1481         // Get notifications send by user1 to any user.
1482         $messages = core_message_external::get_messages(0, $user1->id, 'notifications', true, true, 0, 0);
1483         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1484         $this->assertCount(1, $messages['messages']);
1486         // Test warnings.
1487         $CFG->messaging = 0;
1489         $messages = core_message_external::get_messages(0, $user1->id, 'both', true, true, 0, 0);
1490         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1491         $this->assertCount(1, $messages['warnings']);
1493         // Test exceptions.
1495         // Messaging disabled.
1496         try {
1497             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1498             $this->fail('Exception expected due messaging disabled.');
1499         } catch (moodle_exception $e) {
1500             $this->assertEquals('disabled', $e->errorcode);
1501         }
1503         $CFG->messaging = 1;
1505         // Invalid users.
1506         try {
1507             $messages = core_message_external::get_messages(0, 0, 'conversations', true, true, 0, 0);
1508             $this->fail('Exception expected due invalid users.');
1509         } catch (moodle_exception $e) {
1510             $this->assertEquals('accessdenied', $e->errorcode);
1511         }
1513         // Invalid user ids.
1514         try {
1515             $messages = core_message_external::get_messages(2500, 0, 'conversations', true, true, 0, 0);
1516             $this->fail('Exception expected due invalid users.');
1517         } catch (moodle_exception $e) {
1518             $this->assertEquals('invaliduser', $e->errorcode);
1519         }
1521         // Invalid users (permissions).
1522         $this->setUser($user2);
1523         try {
1524             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1525             $this->fail('Exception expected due invalid user.');
1526         } catch (moodle_exception $e) {
1527             $this->assertEquals('accessdenied', $e->errorcode);
1528         }
1530     }
1532     /**
1533      * Test get_messages where we want all messages from a user, sent to any user.
1534      */
1535     public function test_get_messages_useridto_all() {
1536         $this->resetAfterTest(true);
1538         $user1 = self::getDataGenerator()->create_user();
1539         $user2 = self::getDataGenerator()->create_user();
1540         $user3 = self::getDataGenerator()->create_user();
1542         $this->setUser($user1);
1544         // Send a message from user 1 to two other users.
1545         $this->send_message($user1, $user2, 'some random text 1', 0, 1);
1546         $this->send_message($user1, $user3, 'some random text 2', 0, 2);
1548         // Get messages sent from user 1.
1549         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', false, false, 0, 0);
1550         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1552         // Confirm the data is correct.
1553         $messages = $messages['messages'];
1554         $this->assertCount(2, $messages);
1556         $message1 = array_shift($messages);
1557         $message2 = array_shift($messages);
1559         $this->assertEquals($user1->id, $message1['useridfrom']);
1560         $this->assertEquals($user2->id, $message1['useridto']);
1562         $this->assertEquals($user1->id, $message2['useridfrom']);
1563         $this->assertEquals($user3->id, $message2['useridto']);
1564     }
1566     /**
1567      * Test get_messages where we want all messages to a user, sent by any user.
1568      */
1569     public function test_get_messages_useridfrom_all() {
1570         $this->resetAfterTest();
1572         $user1 = self::getDataGenerator()->create_user();
1573         $user2 = self::getDataGenerator()->create_user();
1574         $user3 = self::getDataGenerator()->create_user();
1576         $this->setUser($user1);
1578         // Send a message to user 1 from two other users.
1579         $this->send_message($user2, $user1, 'some random text 1', 0, 1);
1580         $this->send_message($user3, $user1, 'some random text 2', 0, 2);
1582         // Get messages sent to user 1.
1583         $messages = core_message_external::get_messages($user1->id, 0, 'conversations', false, false, 0, 0);
1584         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1586         // Confirm the data is correct.
1587         $messages = $messages['messages'];
1588         $this->assertCount(2, $messages);
1590         $message1 = array_shift($messages);
1591         $message2 = array_shift($messages);
1593         $this->assertEquals($user2->id, $message1['useridfrom']);
1594         $this->assertEquals($user1->id, $message1['useridto']);
1596         $this->assertEquals($user3->id, $message2['useridfrom']);
1597         $this->assertEquals($user1->id, $message2['useridto']);
1598     }
1600     /**
1601      * Test get_blocked_users.
1602      */
1603     public function test_get_blocked_users() {
1604         $this->resetAfterTest(true);
1606         $user1 = self::getDataGenerator()->create_user();
1607         $userstranger = self::getDataGenerator()->create_user();
1608         $useroffline1 = self::getDataGenerator()->create_user();
1609         $useroffline2 = self::getDataGenerator()->create_user();
1610         $userblocked = self::getDataGenerator()->create_user();
1612         // Login as user1.
1613         $this->setUser($user1);
1615         \core_message\api::add_contact($user1->id, $useroffline1->id);
1616         \core_message\api::add_contact($user1->id, $useroffline2->id);
1618         // The userstranger sends a couple of messages to user1.
1619         $this->send_message($userstranger, $user1, 'Hello there!');
1620         $this->send_message($userstranger, $user1, 'How you goin?');
1622         // The userblocked sends a message to user1.
1623         // Note that this user is not blocked at this point.
1624         $this->send_message($userblocked, $user1, 'Here, have some spam.');
1626         // Retrieve the list of blocked users.
1627         $this->setUser($user1);
1628         $blockedusers = core_message_external::get_blocked_users($user1->id);
1629         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1630         $this->assertCount(0, $blockedusers['users']);
1632         // Block the $userblocked and retrieve again the list.
1633         core_message_external::block_contacts(array($userblocked->id));
1634         $this->assertDebuggingCalled();
1635         $blockedusers = core_message_external::get_blocked_users($user1->id);
1636         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1637         $this->assertCount(1, $blockedusers['users']);
1639         // Remove the $userblocked and check that the list now is empty.
1640         delete_user($userblocked);
1641         $blockedusers = core_message_external::get_blocked_users($user1->id);
1642         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1643         $this->assertCount(0, $blockedusers['users']);
1644     }
1646     /**
1647      * Test mark_message_read.
1648      */
1649     public function test_mark_message_read() {
1650         $this->resetAfterTest(true);
1652         $user1 = self::getDataGenerator()->create_user();
1653         $user2 = self::getDataGenerator()->create_user();
1654         $user3 = self::getDataGenerator()->create_user();
1656         // Login as user1.
1657         $this->setUser($user1);
1658         \core_message\api::add_contact($user1->id, $user2->id);
1659         \core_message\api::add_contact($user1->id, $user3->id);
1661         // The user2 sends a couple of messages to user1.
1662         $this->send_message($user2, $user1, 'Hello there!');
1663         $this->send_message($user2, $user1, 'How you goin?');
1664         $this->send_message($user3, $user1, 'How you goin?');
1665         $this->send_message($user3, $user2, 'How you goin?');
1667         // Retrieve all messages sent by user2 (they are currently unread).
1668         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
1670         $messageids = array();
1671         foreach ($lastmessages as $m) {
1672             $messageid = core_message_external::mark_message_read($m->id, time());
1673             $messageids[] = external_api::clean_returnvalue(core_message_external::mark_message_read_returns(), $messageid);
1674         }
1676         // Retrieve all messages sent (they are currently read).
1677         $lastmessages = message_get_messages($user1->id, $user2->id, 0, true);
1678         $this->assertCount(2, $lastmessages);
1679         $this->assertArrayHasKey($messageids[0]['messageid'], $lastmessages);
1680         $this->assertArrayHasKey($messageids[1]['messageid'], $lastmessages);
1682         // Retrieve all messages sent by any user (that are currently unread).
1683         $lastmessages = message_get_messages($user1->id, 0, 0, false);
1684         $this->assertCount(1, $lastmessages);
1686         // Invalid message ids.
1687         try {
1688             $messageid = core_message_external::mark_message_read(1337, time());
1689             $this->fail('Exception expected due invalid messageid.');
1690         } catch (dml_missing_record_exception $e) {
1691             $this->assertEquals('invalidrecordunknown', $e->errorcode);
1692         }
1694         // A message to a different user.
1695         $lastmessages = message_get_messages($user2->id, $user3->id, 0, false);
1696         $messageid = array_pop($lastmessages)->id;
1697         try {
1698             $messageid = core_message_external::mark_message_read($messageid, time());
1699             $this->fail('Exception expected due invalid messageid.');
1700         } catch (invalid_parameter_exception $e) {
1701             $this->assertEquals('invalidparameter', $e->errorcode);
1702         }
1703     }
1705     /**
1706      * Test mark_notification_read.
1707      */
1708     public function test_mark_notification_read() {
1709         $this->resetAfterTest(true);
1711         $user1 = self::getDataGenerator()->create_user();
1712         $user2 = self::getDataGenerator()->create_user();
1713         $user3 = self::getDataGenerator()->create_user();
1715         // Login as user1.
1716         $this->setUser($user1);
1717         \core_message\api::add_contact($user1->id, $user2->id);
1718         \core_message\api::add_contact($user1->id, $user3->id);
1720         // The user2 sends a couple of notifications to user1.
1721         $this->send_message($user2, $user1, 'Hello there!', 1);
1722         $this->send_message($user2, $user1, 'How you goin?', 1);
1723         $this->send_message($user3, $user1, 'How you goin?', 1);
1724         $this->send_message($user3, $user2, 'How you goin?', 1);
1726         // Retrieve all notifications sent by user2 (they are currently unread).
1727         $lastnotifications = message_get_messages($user1->id, $user2->id, 1, false);
1729         $notificationids = array();
1730         foreach ($lastnotifications as $n) {
1731             $notificationid = core_message_external::mark_notification_read($n->id, time());
1732             $notificationids[] = external_api::clean_returnvalue(core_message_external::mark_notification_read_returns(),
1733                 $notificationid);
1734         }
1736         // Retrieve all notifications sent (they are currently read).
1737         $lastnotifications = message_get_messages($user1->id, $user2->id, 1, true);
1738         $this->assertCount(2, $lastnotifications);
1739         $this->assertArrayHasKey($notificationids[1]['notificationid'], $lastnotifications);
1740         $this->assertArrayHasKey($notificationids[0]['notificationid'], $lastnotifications);
1742         // Retrieve all notifications sent by any user (that are currently unread).
1743         $lastnotifications = message_get_messages($user1->id, 0, 1, false);
1744         $this->assertCount(1, $lastnotifications);
1746         // Invalid notification ids.
1747         try {
1748             $notificationid = core_message_external::mark_notification_read(1337, time());
1749             $this->fail('Exception expected due invalid notificationid.');
1750         } catch (dml_missing_record_exception $e) {
1751             $this->assertEquals('invalidrecord', $e->errorcode);
1752         }
1754         // A notification to a different user.
1755         $lastnotifications = message_get_messages($user2->id, $user3->id, 1, false);
1756         $notificationid = array_pop($lastnotifications)->id;
1757         try {
1758             $notificationid = core_message_external::mark_notification_read($notificationid, time());
1759             $this->fail('Exception expected due invalid notificationid.');
1760         } catch (invalid_parameter_exception $e) {
1761             $this->assertEquals('invalidparameter', $e->errorcode);
1762         }
1763     }
1765     /**
1766      * Test delete_message.
1767      */
1768     public function test_delete_message() {
1769         global $DB;
1770         $this->resetAfterTest(true);
1772         $user1 = self::getDataGenerator()->create_user();
1773         $user2 = self::getDataGenerator()->create_user();
1774         $user3 = self::getDataGenerator()->create_user();
1775         $user4 = self::getDataGenerator()->create_user();
1777         // Login as user1.
1778         $this->setUser($user1);
1779         \core_message\api::add_contact($user1->id, $user2->id);
1780         \core_message\api::add_contact($user1->id, $user3->id);
1782         // User user1 does not interchange messages with user3.
1783         $m1to2 = message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
1784         $m2to3 = message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
1785         $m3to2 = message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
1786         $m3to4 = message_post_message($user3, $user4, 'some random text 4', FORMAT_MOODLE);
1788         // Retrieve all messages sent by user2 (they are currently unread).
1789         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
1791         // Delete a message not read, as a user from.
1792         $result = core_message_external::delete_message($m1to2, $user1->id, false);
1793         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1794         $this->assertTrue($result['status']);
1795         $this->assertCount(0, $result['warnings']);
1796         $mua = $DB->get_record('message_user_actions', array('messageid' => $m1to2, 'userid' => $user1->id));
1797         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua->action);
1799         // Try to delete the same message again.
1800         $result = core_message_external::delete_message($m1to2, $user1->id, false);
1801         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1802         $this->assertFalse($result['status']);
1804         // Try to delete a message that does not belong to me.
1805         try {
1806             $messageid = core_message_external::delete_message($m2to3, $user3->id, false);
1807             $this->fail('Exception expected due invalid messageid.');
1808         } catch (moodle_exception $e) {
1809             $this->assertEquals('You do not have permission to delete this message', $e->errorcode);
1810         }
1812         $this->setUser($user3);
1813         // Delete a message not read, as a user to.
1814         $result = core_message_external::delete_message($m2to3, $user3->id, false);
1815         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1816         $this->assertTrue($result['status']);
1817         $this->assertCount(0, $result['warnings']);
1818         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m2to3, 'userid' => $user3->id,
1819             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1821         // Delete a message read.
1822         $message = $DB->get_record('messages', ['id' => $m3to2]);
1823         \core_message\api::mark_message_as_read($user3->id, $message, time());
1824         $result = core_message_external::delete_message($m3to2, $user3->id);
1825         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1826         $this->assertTrue($result['status']);
1827         $this->assertCount(0, $result['warnings']);
1828         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to2, 'userid' => $user3->id,
1829             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1831         // Invalid message ids.
1832         try {
1833             $result = core_message_external::delete_message(-1, $user1->id);
1834             $this->fail('Exception expected due invalid messageid.');
1835         } catch (dml_missing_record_exception $e) {
1836             $this->assertEquals('invalidrecord', $e->errorcode);
1837         }
1839         // Invalid user.
1840         try {
1841             $result = core_message_external::delete_message($m1to2, -1, false);
1842             $this->fail('Exception expected due invalid user.');
1843         } catch (moodle_exception $e) {
1844             $this->assertEquals('invaliduser', $e->errorcode);
1845         }
1847         // Not active user.
1848         delete_user($user2);
1849         try {
1850             $result = core_message_external::delete_message($m1to2, $user2->id, false);
1851             $this->fail('Exception expected due invalid user.');
1852         } catch (moodle_exception $e) {
1853             $this->assertEquals('userdeleted', $e->errorcode);
1854         }
1856         // Now, as an admin, try to delete any message.
1857         $this->setAdminUser();
1858         $result = core_message_external::delete_message($m3to4, $user4->id, false);
1859         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1860         $this->assertTrue($result['status']);
1861         $this->assertCount(0, $result['warnings']);
1862         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to4, 'userid' => $user4->id,
1863             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1865     }
1867     public function test_mark_all_notifications_as_read_invalid_user_exception() {
1868         $this->resetAfterTest(true);
1870         $this->expectException('moodle_exception');
1871         core_message_external::mark_all_notifications_as_read(-2132131, 0);
1872     }
1874     public function test_mark_all_notifications_as_read_access_denied_exception() {
1875         $this->resetAfterTest(true);
1877         $sender = $this->getDataGenerator()->create_user();
1878         $user = $this->getDataGenerator()->create_user();
1880         $this->setUser($user);
1881         $this->expectException('moodle_exception');
1882         core_message_external::mark_all_notifications_as_read($sender->id, 0);
1883     }
1885     public function test_mark_all_notifications_as_read_missing_from_user_exception() {
1886         $this->resetAfterTest(true);
1888         $sender = $this->getDataGenerator()->create_user();
1890         $this->setUser($sender);
1891         $this->expectException('moodle_exception');
1892         core_message_external::mark_all_notifications_as_read($sender->id, 99999);
1893     }
1895     public function test_mark_all_notifications_as_read() {
1896         global $DB;
1898         $this->resetAfterTest(true);
1900         $sender1 = $this->getDataGenerator()->create_user();
1901         $sender2 = $this->getDataGenerator()->create_user();
1902         $sender3 = $this->getDataGenerator()->create_user();
1903         $recipient = $this->getDataGenerator()->create_user();
1905         $this->setUser($recipient);
1907         $this->send_message($sender1, $recipient, 'Notification', 1);
1908         $this->send_message($sender1, $recipient, 'Notification', 1);
1909         $this->send_message($sender2, $recipient, 'Notification', 1);
1910         $this->send_message($sender2, $recipient, 'Notification', 1);
1911         $this->send_message($sender3, $recipient, 'Notification', 1);
1912         $this->send_message($sender3, $recipient, 'Notification', 1);
1914         core_message_external::mark_all_notifications_as_read($recipient->id, $sender1->id);
1915         $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1916         $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
1918         $this->assertCount(2, $readnotifications);
1919         $this->assertCount(4, $unreadnotifications);
1921         core_message_external::mark_all_notifications_as_read($recipient->id, 0);
1922         $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1923         $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
1925         $this->assertCount(6, $readnotifications);
1926         $this->assertCount(0, $unreadnotifications);
1927     }
1929     /**
1930      * Test get_user_notification_preferences
1931      */
1932     public function test_get_user_notification_preferences() {
1933         $this->resetAfterTest(true);
1935         $user = self::getDataGenerator()->create_user();
1936         $this->setUser($user);
1938         // Set a couple of preferences to test.
1939         set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
1940         set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
1942         $prefs = core_message_external::get_user_notification_preferences();
1943         $prefs = external_api::clean_returnvalue(core_message_external::get_user_notification_preferences_returns(), $prefs);
1944         // Check processors.
1945         $this->assertGreaterThanOrEqual(2, count($prefs['preferences']['processors']));
1946         $this->assertEquals($user->id, $prefs['preferences']['userid']);
1948         // Check components.
1949         $this->assertGreaterThanOrEqual(8, count($prefs['preferences']['components']));
1951         // Check some preferences that we previously set.
1952         $found = 0;
1953         foreach ($prefs['preferences']['components'] as $component) {
1954             foreach ($component['notifications'] as $prefdata) {
1955                 if ($prefdata['preferencekey'] != 'message_provider_mod_assign_assign_notification') {
1956                     continue;
1957                 }
1958                 foreach ($prefdata['processors'] as $processor) {
1959                     if ($processor['name'] == 'popup') {
1960                         $this->assertTrue($processor['loggedin']['checked']);
1961                         $found++;
1962                     } else if ($processor['name'] == 'email') {
1963                         $this->assertTrue($processor['loggedoff']['checked']);
1964                         $found++;
1965                     }
1966                 }
1967             }
1968         }
1969         $this->assertEquals(2, $found);
1970     }
1972     /**
1973      * Test get_user_notification_preferences permissions
1974      */
1975     public function test_get_user_notification_preferences_permissions() {
1976         $this->resetAfterTest(true);
1978         $user = self::getDataGenerator()->create_user();
1979         $otheruser = self::getDataGenerator()->create_user();
1980         $this->setUser($user);
1982         $this->expectException('moodle_exception');
1983         $prefs = core_message_external::get_user_notification_preferences($otheruser->id);
1984     }
1986     /**
1987      * Tests searching users in a course.
1988      */
1989     public function test_data_for_messagearea_search_users_in_course() {
1990         $this->resetAfterTest(true);
1992         // Create some users.
1993         $user1 = new stdClass();
1994         $user1->firstname = 'User';
1995         $user1->lastname = 'One';
1996         $user1 = self::getDataGenerator()->create_user($user1);
1998         // The person doing the search.
1999         $this->setUser($user1);
2001         // Set the second user's status to online by setting their last access to now.
2002         $user2 = new stdClass();
2003         $user2->firstname = 'User';
2004         $user2->lastname = 'Two';
2005         $user2->lastaccess = time();
2006         $user2 = self::getDataGenerator()->create_user($user2);
2008         // Block the second user.
2009         \core_message\api::block_user($user1->id, $user2->id);
2011         $user3 = new stdClass();
2012         $user3->firstname = 'User';
2013         $user3->lastname = 'Three';
2014         $user3 = self::getDataGenerator()->create_user($user3);
2016         // Create a course.
2017         $course1 = new stdClass();
2018         $course1->fullname = 'Course';
2019         $course1->shortname = 'One';
2020         $course1 = $this->getDataGenerator()->create_course();
2022         // Enrol the user we are doing the search for and one user in the course.
2023         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
2024         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
2026         // Perform a search.
2027         $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
2029         // We need to execute the return values cleaning process to simulate the web service.
2030         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
2031             $result);
2033         // Check that we only retrieved a user that was enrolled, and that the user performing the search was not returned.
2034         $users = $result['contacts'];
2035         $this->assertCount(1, $users);
2037         $user = $users[0];
2038         $this->assertEquals($user2->id, $user['userid']);
2039         $this->assertEquals(fullname($user2), $user['fullname']);
2040         $this->assertFalse($user['ismessaging']);
2041         $this->assertFalse($user['sentfromcurrentuser']);
2042         $this->assertNull($user['lastmessage']);
2043         $this->assertNull($user['messageid']);
2044         $this->assertNull($user['isonline']);
2045         $this->assertFalse($user['isread']);
2046         $this->assertTrue($user['isblocked']);
2047         $this->assertNull($user['unreadcount']);
2048     }
2050     /**
2051      * Tests searching users in course as another user.
2052      */
2053     public function test_data_for_messagearea_search_users_in_course_as_other_user() {
2054         $this->resetAfterTest(true);
2056         // The person doing the search for another user.
2057         $this->setAdminUser();
2059         // Create some users.
2060         $user1 = new stdClass();
2061         $user1->firstname = 'User';
2062         $user1->lastname = 'One';
2063         $user1 = self::getDataGenerator()->create_user($user1);
2065         $user2 = new stdClass();
2066         $user2->firstname = 'User';
2067         $user2->lastname = 'Two';
2068         $user2 = self::getDataGenerator()->create_user($user2);
2070         $user3 = new stdClass();
2071         $user3->firstname = 'User';
2072         $user3->lastname = 'Three';
2073         $user3 = self::getDataGenerator()->create_user($user3);
2075         // Create a course.
2076         $course1 = new stdClass();
2077         $course1->fullname = 'Course';
2078         $course1->shortname = 'One';
2079         $course1 = $this->getDataGenerator()->create_course();
2081         // Enrol the user we are doing the search for and one user in the course.
2082         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
2083         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
2085         // Perform a search.
2086         $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
2088         // We need to execute the return values cleaning process to simulate the web service server.
2089         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
2090             $result);
2092         // Check that we got the user enrolled, and that the user we are performing the search on behalf of was not returned.
2093         $users = $result['contacts'];
2094         $this->assertCount(1, $users);
2096         $user = $users[0];
2097         $this->assertEquals($user2->id, $user['userid']);
2098         $this->assertEquals(fullname($user2), $user['fullname']);
2099         $this->assertFalse($user['ismessaging']);
2100         $this->assertFalse($user['sentfromcurrentuser']);
2101         $this->assertNull($user['lastmessage']);
2102         $this->assertNull($user['messageid']);
2103         $this->assertFalse($user['isonline']);
2104         $this->assertFalse($user['isread']);
2105         $this->assertFalse($user['isblocked']);
2106         $this->assertNull($user['unreadcount']);
2107     }
2109     /**
2110      * Tests searching users in course as another user without the proper capabilities.
2111      */
2112     public function test_data_for_messagearea_search_users_in_course_as_other_user_without_cap() {
2113         $this->resetAfterTest(true);
2115         // Create some users.
2116         $user1 = self::getDataGenerator()->create_user();
2117         $user2 = self::getDataGenerator()->create_user();
2119         // The person doing the search for another user.
2120         $this->setUser($user1);
2122         // Create a course.
2123         $course = $this->getDataGenerator()->create_course();
2125         // Ensure an exception is thrown.
2126         $this->expectException('moodle_exception');
2127         core_message_external::data_for_messagearea_search_users_in_course($user2->id, $course->id, 'User');
2128         $this->assertDebuggingCalled();
2129     }
2131     /**
2132      * Tests searching users in course with messaging disabled.
2133      */
2134     public function test_data_for_messagearea_search_users_in_course_messaging_disabled() {
2135         global $CFG;
2137         $this->resetAfterTest(true);
2139         // Create some skeleton data just so we can call the WS..
2140         $user = self::getDataGenerator()->create_user();
2141         $course = $this->getDataGenerator()->create_course();
2143         // The person doing the search for another user.
2144         $this->setUser($user);
2146         // Disable messaging.
2147         $CFG->messaging = 0;
2149         // Ensure an exception is thrown.
2150         $this->expectException('moodle_exception');
2151         core_message_external::data_for_messagearea_search_users_in_course($user->id, $course->id, 'User');
2152         $this->assertDebuggingCalled();
2153     }
2155     /**
2156      * Tests searching users.
2157      */
2158     public function test_data_for_messagearea_search_users() {
2159         $this->resetAfterTest(true);
2161         // Create some users.
2162         $user1 = new stdClass();
2163         $user1->firstname = 'User';
2164         $user1->lastname = 'One';
2165         $user1 = self::getDataGenerator()->create_user($user1);
2167         // Set as the user performing the search.
2168         $this->setUser($user1);
2170         $user2 = new stdClass();
2171         $user2->firstname = 'User search';
2172         $user2->lastname = 'Two';
2173         $user2 = self::getDataGenerator()->create_user($user2);
2175         $user3 = new stdClass();
2176         $user3->firstname = 'User search';
2177         $user3->lastname = 'Three';
2178         $user3 = self::getDataGenerator()->create_user($user3);
2180         $user4 = new stdClass();
2181         $user4->firstname = 'User';
2182         $user4->lastname = 'Four';
2183         $user4 = self::getDataGenerator()->create_user($user4);
2185         $user5 = new stdClass();
2186         $user5->firstname = 'User search';
2187         $user5->lastname = 'Five';
2188         $user5 = self::getDataGenerator()->create_user($user5);
2190         $user6 = new stdClass();
2191         $user6->firstname = 'User';
2192         $user6->lastname = 'Six';
2193         $user6 = self::getDataGenerator()->create_user($user6);
2195         // Create some courses.
2196         $course1 = new stdClass();
2197         $course1->fullname = 'Course search';
2198         $course1->shortname = 'One';
2199         $course1 = $this->getDataGenerator()->create_course($course1);
2201         $course2 = new stdClass();
2202         $course2->fullname = 'Course';
2203         $course2->shortname = 'Two';
2204         $course2 = $this->getDataGenerator()->create_course($course2);
2206         $course3 = new stdClass();
2207         $course3->fullname = 'Course';
2208         $course3->shortname = 'Three search';
2209         $course3 = $this->getDataGenerator()->create_course($course3);
2211         $course4 = new stdClass();
2212         $course4->fullname = 'Course Four';
2213         $course4->shortname = 'CF100';
2214         $course4 = $this->getDataGenerator()->create_course($course4);
2216         $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'student');
2217         $this->getDataGenerator()->enrol_user($user1->id, $course2->id, 'student');
2218         $this->getDataGenerator()->enrol_user($user1->id, $course3->id, 'student');
2220         // Add some users as contacts.
2221         \core_message\api::add_contact($user1->id, $user2->id);
2222         \core_message\api::add_contact($user1->id, $user3->id);
2223         \core_message\api::add_contact($user1->id, $user4->id);
2225         // Perform a search $CFG->messagingallusers setting enabled.
2226         set_config('messagingallusers', 1);
2227         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
2229         // We need to execute the return values cleaning process to simulate the web service server.
2230         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
2231             $result);
2233         // Confirm that we returns contacts, courses and non-contacts.
2234         $contacts = $result['contacts'];
2235         $courses = $result['courses'];
2236         $noncontacts = $result['noncontacts'];
2238         // Check that we retrieved the correct contacts.
2239         $this->assertCount(2, $contacts);
2240         $this->assertEquals($user3->id, $contacts[0]['userid']);
2241         $this->assertEquals($user2->id, $contacts[1]['userid']);
2243         // Check that we retrieved the correct courses.
2244         $this->assertCount(2, $courses);
2245         $this->assertEquals($course3->id, $courses[0]['id']);
2246         $this->assertEquals($course1->id, $courses[1]['id']);
2248         // Check that we retrieved the correct non-contacts.
2249         $this->assertCount(1, $noncontacts);
2250         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
2251     }
2253     /**
2254      * Tests searching users as another user.
2255      */
2256     public function test_data_for_messagearea_search_users_as_other_user() {
2257         $this->resetAfterTest(true);
2259         // The person doing the search.
2260         $this->setAdminUser();
2262         // Create some users.
2263         $user1 = new stdClass();
2264         $user1->firstname = 'User';
2265         $user1->lastname = 'One';
2266         $user1 = self::getDataGenerator()->create_user($user1);
2268         $user2 = new stdClass();
2269         $user2->firstname = 'User search';
2270         $user2->lastname = 'Two';
2271         $user2 = self::getDataGenerator()->create_user($user2);
2273         $user3 = new stdClass();
2274         $user3->firstname = 'User search';
2275         $user3->lastname = 'Three';
2276         $user3 = self::getDataGenerator()->create_user($user3);
2278         $user4 = new stdClass();
2279         $user4->firstname = 'User';
2280         $user4->lastname = 'Four';
2281         $user4 = self::getDataGenerator()->create_user($user4);
2283         $user5 = new stdClass();
2284         $user5->firstname = 'User search';
2285         $user5->lastname = 'Five';
2286         $user5 = self::getDataGenerator()->create_user($user5);
2288         $user6 = new stdClass();
2289         $user6->firstname = 'User';
2290         $user6->lastname = 'Six';
2291         $user6 = self::getDataGenerator()->create_user($user6);
2293         // Create some courses.
2294         $course1 = new stdClass();
2295         $course1->fullname = 'Course search';
2296         $course1->shortname = 'One';
2297         $course1 = $this->getDataGenerator()->create_course($course1);
2299         $course2 = new stdClass();
2300         $course2->fullname = 'Course';
2301         $course2->shortname = 'Two';
2302         $course2 = $this->getDataGenerator()->create_course($course2);
2304         $course3 = new stdClass();
2305         $course3->fullname = 'Course';
2306         $course3->shortname = 'Three search';
2307         $course3 = $this->getDataGenerator()->create_course($course3);
2309         // Add some users as contacts.
2310         \core_message\api::add_contact($user1->id, $user2->id);
2311         \core_message\api::add_contact($user1->id, $user3->id);
2312         \core_message\api::add_contact($user1->id, $user4->id);
2314         // Perform a search $CFG->messagingallusers setting enabled.
2315         set_config('messagingallusers', 1);
2316         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
2318         // We need to execute the return values cleaning process to simulate the web service server.
2319         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
2320             $result);
2322         // Confirm that we returns contacts, courses and non-contacts.
2323         $contacts = $result['contacts'];
2324         $courses = $result['courses'];
2325         $noncontacts = $result['noncontacts'];
2327         // Check that we retrieved the correct contacts.
2328         $this->assertCount(2, $contacts);
2329         $this->assertEquals($user3->id, $contacts[0]['userid']);
2330         $this->assertEquals($user2->id, $contacts[1]['userid']);
2332         // Check that we retrieved the correct courses.
2333         $this->assertCount(0, $courses);
2335         // Check that we retrieved the correct non-contacts.
2336         $this->assertCount(1, $noncontacts);
2337         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
2338     }
2340     /**
2341      * Tests searching users as another user without the proper capabilities.
2342      */
2343     public function test_data_for_messagearea_search_users_as_other_user_without_cap() {
2344         $this->resetAfterTest(true);
2346         // Create some users.
2347         $user1 = self::getDataGenerator()->create_user();
2348         $user2 = self::getDataGenerator()->create_user();
2350         // The person doing the search for another user.
2351         $this->setUser($user1);
2353         // Ensure an exception is thrown.
2354         $this->expectException('moodle_exception');
2355         core_message_external::data_for_messagearea_search_users($user2->id, 'User');
2356         $this->assertDebuggingCalled();
2357     }
2359     /**
2360      * Tests searching users with messaging disabled.
2361      */
2362     public function test_data_for_messagearea_search_users_messaging_disabled() {
2363         global $CFG;
2365         $this->resetAfterTest(true);
2367         // Create some skeleton data just so we can call the WS.
2368         $user = self::getDataGenerator()->create_user();
2370         // The person doing the search.
2371         $this->setUser($user);
2373         // Disable messaging.
2374         $CFG->messaging = 0;
2376         // Ensure an exception is thrown.
2377         $this->expectException('moodle_exception');
2378         core_message_external::data_for_messagearea_search_users($user->id, 'User');
2379         $this->assertDebuggingCalled();
2380     }
2382     /**
2383      * Tests searching for users when site-wide messaging is disabled.
2384      *
2385      * This test verifies that any contacts are returned, as well as any non-contacts whose profile we can view.
2386      * If checks this by placing some users in the same course, where default caps would permit a user to view another user's
2387      * profile.
2388      */
2389     public function test_message_search_users_messagingallusers_disabled() {
2390         $this->resetAfterTest();
2392         // Create some users.
2393         $users = [];
2394         foreach (range(1, 7) as $i) {
2395             $user = new stdClass();
2396             $user->firstname = ($i == 4) ? 'User' : 'User search'; // Ensure the fourth user won't match the search term.
2397             $user->lastname = $i;
2398             $user = $this->getDataGenerator()->create_user($user);
2399             $users[$i] = $user;
2400         }
2402         // Enrol a few users in the same course, but leave them as non-contacts.
2403         $course1 = $this->getDataGenerator()->create_course();
2404         $this->setAdminUser();
2405         $this->getDataGenerator()->enrol_user($users[1]->id, $course1->id);
2406         $this->getDataGenerator()->enrol_user($users[6]->id, $course1->id);
2407         $this->getDataGenerator()->enrol_user($users[7]->id, $course1->id);
2409         // Add some other users as contacts.
2410         \core_message\api::add_contact($users[1]->id, $users[2]->id);
2411         \core_message\api::add_contact($users[3]->id, $users[1]->id);
2412         \core_message\api::add_contact($users[1]->id, $users[4]->id);
2414         // Create individual conversations between some users, one contact and one non-contact.
2415         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2416             [$users[1]->id, $users[2]->id]);
2417         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2418             [$users[6]->id, $users[1]->id]);
2420         // Create a group conversation between 4 users, including a contact and a non-contact.
2421         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2422             [$users[1]->id, $users[2]->id, $users[4]->id, $users[7]->id], 'Project chat');
2424         // Set as the user performing the search.
2425         $this->setUser($users[1]);
2427         // Perform a search with $CFG->messagingallusers disabled.
2428         set_config('messagingallusers', 0);
2429         $result = core_message_external::message_search_users($users[1]->id, 'search');
2430         $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
2432         // Confirm that we returns contacts and non-contacts.
2433         $this->assertArrayHasKey('contacts', $result);
2434         $this->assertArrayHasKey('noncontacts', $result);
2435         $contacts = $result['contacts'];
2436         $noncontacts = $result['noncontacts'];
2438         // Check that we retrieved the correct contacts.
2439         $this->assertCount(2, $contacts);
2440         $this->assertEquals($users[2]->id, $contacts[0]['id']);
2441         $this->assertEquals($users[3]->id, $contacts[1]['id']);
2443         // Verify the correct conversations were returned for the contacts.
2444         $this->assertCount(2, $contacts[0]['conversations']);
2445         // We can't rely on the ordering of conversations within the results, so sort by id first.
2446         usort($contacts[0]['conversations'], function($a, $b) {
2447             return $a['id'] < $b['id'];
2448         });
2449         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $contacts[0]['conversations'][0]['type']);
2450         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $contacts[0]['conversations'][1]['type']);
2452         $this->assertCount(0, $contacts[1]['conversations']);
2454         // Check that we retrieved the correct non-contacts.
2455         // When site wide messaging is disabled, we expect to see only those users whose profiles we can view.
2456         $this->assertCount(2, $noncontacts);
2457         $this->assertEquals($users[6]->id, $noncontacts[0]['id']);
2458         $this->assertEquals($users[7]->id, $noncontacts[1]['id']);
2460         // Verify the correct conversations were returned for the non-contacts.
2461         $this->assertCount(1, $noncontacts[0]['conversations']);
2462         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $noncontacts[0]['conversations'][0]['type']);
2464         $this->assertCount(1, $noncontacts[1]['conversations']);
2465         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $noncontacts[1]['conversations'][0]['type']);
2466     }
2468     /**
2469      * Tests searching for users when site-wide messaging is enabled.
2470      *
2471      * This test verifies that any contacts are returned, as well as any non-contacts, regardless of whether the searching user
2472      * can view their respective profile.
2473      */
2474     public function test_message_search_users_messagingallusers_enabled() {
2475         $this->resetAfterTest();
2477         // Create some users.
2478         $users = [];
2479         foreach (range(1, 8) as $i) {
2480             $user = new stdClass();
2481             $user->firstname = ($i == 4) ? 'User' : 'User search'; // Ensure the fourth user won't match the search term.
2482             $user->lastname = $i;
2483             $user = $this->getDataGenerator()->create_user($user);
2484             $users[$i] = $user;
2485         }
2487         // Enrol a few users in the same course, but leave them as non-contacts.
2488         $course1 = $this->getDataGenerator()->create_course();
2489         $this->setAdminUser();
2490         $this->getDataGenerator()->enrol_user($users[1]->id, $course1->id);
2491         $this->getDataGenerator()->enrol_user($users[6]->id, $course1->id);
2492         $this->getDataGenerator()->enrol_user($users[7]->id, $course1->id);
2494         // Add some other users as contacts.
2495         \core_message\api::add_contact($users[1]->id, $users[2]->id);
2496         \core_message\api::add_contact($users[3]->id, $users[1]->id);
2497         \core_message\api::add_contact($users[1]->id, $users[4]->id);
2499         // Create individual conversations between some users, one contact and one non-contact.
2500         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2501             [$users[1]->id, $users[2]->id]);
2502         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2503             [$users[6]->id, $users[1]->id]);
2505         // Create a group conversation between 5 users, including a contact and a non-contact, and a user NOT in a shared course.
2506         \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2507             [$users[1]->id, $users[2]->id, $users[4]->id, $users[7]->id, $users[8]->id], 'Project chat');
2509         // Set as the user performing the search.
2510         $this->setUser($users[1]);
2512         // Perform a search with $CFG->messagingallusers enabled.
2513         set_config('messagingallusers', 1);
2514         $result = core_message_external::message_search_users($users[1]->id, 'search');
2515         $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
2517         // Confirm that we returns contacts and non-contacts.
2518         $this->assertArrayHasKey('contacts', $result);
2519         $this->assertArrayHasKey('noncontacts', $result);
2520         $contacts = $result['contacts'];
2521         $noncontacts = $result['noncontacts'];
2523         // Check that we retrieved the correct contacts.
2524         $this->assertCount(2, $contacts);
2525         $this->assertEquals($users[2]->id, $contacts[0]['id']);
2526         $this->assertEquals($users[3]->id, $contacts[1]['id']);
2528         // Verify the correct conversations were returned for the contacts.
2529         $this->assertCount(2, $contacts[0]['conversations']);
2530         // We can't rely on the ordering of conversations within the results, so sort by id first.
2531         usort($contacts[0]['conversations'], function($a, $b) {
2532             return $a['id'] < $b['id'];
2533         });
2534         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $contacts[0]['conversations'][0]['type']);
2535         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $contacts[0]['conversations'][1]['type']);
2537         $this->assertCount(0, $contacts[1]['conversations']);
2539         // Check that we retrieved the correct non-contacts.
2540         // If site wide messaging is enabled, we expect to be able to search for any users.
2541         $this->assertCount(4, $noncontacts);
2542         $this->assertEquals($users[5]->id, $noncontacts[0]['id']);
2543         $this->assertEquals($users[6]->id, $noncontacts[1]['id']);
2544         $this->assertEquals($users[7]->id, $noncontacts[2]['id']);
2545         $this->assertEquals($users[8]->id, $noncontacts[3]['id']);
2547         // Verify the correct conversations were returned for the non-contacts.
2548         $this->assertCount(0, $noncontacts[0]['conversations']);
2550         $this->assertCount(1, $noncontacts[1]['conversations']);
2551         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $noncontacts[1]['conversations'][0]['type']);
2553         $this->assertCount(1, $noncontacts[2]['conversations']);
2554         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $noncontacts[2]['conversations'][0]['type']);
2556         $this->assertCount(1, $noncontacts[3]['conversations']);
2557         $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $noncontacts[3]['conversations'][0]['type']);
2558     }
2560     /**
2561      * Verify searching for users works even if no matching users from either contacts, or non-contacts can be found.
2562      */
2563     public function test_message_search_users_with_empty_result() {
2564         $this->resetAfterTest();
2566         // Create some users, but make sure neither will match the search term.
2567         $user1 = new stdClass();
2568         $user1->firstname = 'User';
2569         $user1->lastname = 'One';
2570         $user1 = $this->getDataGenerator()->create_user($user1);
2571         $user2 = new stdClass();
2572         $user2->firstname = 'User';
2573         $user2->lastname = 'Two';
2574         $user2 = $this->getDataGenerator()->create_user($user2);
2576         // Perform a search as user1.
2577         $this->setUser($user1);
2578         $result = core_message_external::message_search_users($user1->id, 'search');
2579         $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
2581         // Check results are empty.
2582         $this->assertCount(0, $result['contacts']);
2583         $this->assertCount(0, $result['noncontacts']);
2584     }
2586     /**
2587      * Test verifying that limits and offsets work for both the contacts and non-contacts return data.
2588      */
2589     public function test_message_search_users_limit_offset() {
2590         $this->resetAfterTest();
2592         // Create 20 users.
2593         $users = [];
2594         foreach (range(1, 20) as $i) {
2595             $user = new stdClass();
2596             $user->firstname = "User search";
2597             $user->lastname = $i;
2598             $user = $this->getDataGenerator()->create_user($user);
2599             $users[$i] = $user;
2600         }
2602         // Enrol the first 9 users in the same course, but leave them as non-contacts.
2603         $this->setAdminUser();
2604         $course1 = $this->getDataGenerator()->create_course();
2605         foreach (range(1, 9) as $i) {
2606             $this->getDataGenerator()->enrol_user($users[$i]->id, $course1->id);
2607         }
2609         // Add 5 users, starting at the 11th user, as contacts for user1.
2610         foreach (range(11, 15) as $i) {
2611             \core_message\api::add_contact($users[1]->id, $users[$i]->id);
2612         }
2614         // Set as the user performing the search.
2615         $this->setUser($users[1]);
2617         // Search using a limit of 3.
2618         // This tests the case where we have more results than the limit for both contacts and non-contacts.
2619         $result = core_message_external::message_search_users($users[1]->id, 'search', 0, 3);
2620         $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
2621         $contacts = $result['contacts'];
2622         $noncontacts = $result['noncontacts'];
2624         // Check that we retrieved the correct contacts.
2625         $this->assertCount(3, $contacts);
2626         $this->assertEquals($users[11]->id, $contacts[0]['id']);
2627         $this->assertEquals($users[12]->id, $contacts[1]['id']);
2628         $this->assertEquals($users[13]->id, $contacts[2]['id']);
2630         // Check that we retrieved the correct non-contacts.
2631         $this->assertCount(3, $noncontacts);
2632         $this->assertEquals($users[2]->id, $noncontacts[0]['id']);
2633         $this->assertEquals($users[3]->id, $noncontacts[1]['id']);
2634         $this->assertEquals($users[4]->id, $noncontacts[2]['id']);
2636         // Now, offset to get the next batch of results.
2637         // We expect to see 2 contacts, and 3 non-contacts.
2638         $result = core_message_external::message_search_users($users[1]->id, 'search', 3, 3);
2639         $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
2640         $contacts = $result['contacts'];
2641         $noncontacts = $result['noncontacts'];
2642         $this->assertCount(2, $contacts);
2643         $this->assertEquals($users[14]->id, $contacts[0]['id']);
2644         $this->assertEquals($users[15]->id, $contacts[1]['id']);
2646         $this->assertCount(3, $noncontacts);
2647         $this->assertEquals($users[5]->id, $noncontacts[0]['id']);
2648         $this->assertEquals($users[6]->id, $noncontacts[1]['id']);
2649         $this->assertEquals($users[7]->id, $noncontacts[2]['id']);
2651         // Now, offset to get the next batch of results.
2652         // We expect to see 0 contacts, and 2 non-contacts.
2653         $result = core_message_external::message_search_users($users[1]->id, 'search', 6, 3);
2654         $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
2655         $contacts = $result['contacts'];
2656         $noncontacts = $result['noncontacts'];
2657         $this->assertCount(0, $contacts);
2659         $this->assertCount(2, $noncontacts);
2660         $this->assertEquals($users[8]->id, $noncontacts[0]['id']);
2661         $this->assertEquals($users[9]->id, $noncontacts[1]['id']);
2662     }
2664     /**
2665      * Tests searching users as another user having the 'moodle/user:viewdetails' capability.
2666      */
2667     public function test_message_search_users_with_cap() {
2668         $this->resetAfterTest();
2669         global $DB;
2671         // Create some users.
2672         $users = [];
2673         foreach (range(1, 8) as $i) {
2674             $user = new stdClass();
2675             $user->firstname = ($i == 4) ? 'User' : 'User search'; // Ensure the fourth user won't match the search term.
2676             $user->lastname = $i;
2677             $user = $this->getDataGenerator()->create_user($user);
2678             $users[$i] = $user;
2679         }
2681         // Enrol a few users in the same course, but leave them as non-contacts.
2682         $course1 = $this->getDataGenerator()->create_course();
2683         $this->setAdminUser();
2684         $this->getDataGenerator()->enrol_user($users[1]->id, $course1->id);
2685         $this->getDataGenerator()->enrol_user($users[6]->id, $course1->id);
2686         $this->getDataGenerator()->enrol_user($users[7]->id, $course1->id);
2688         // Add some other users as contacts.
2689         \core_message\api::add_contact($users[1]->id, $users[2]->id);
2690         \core_message\api::add_contact($users[3]->id, $users[1]->id);
2691         \core_message\api::add_contact($users[1]->id, $users[4]->id);
2693         // Set as the user performing the search.
2694         $this->setUser($users[1]);
2696         // Grant the authenticated user role the capability 'user:viewdetails' at site context.
2697         $authenticatedrole = $DB->get_record('role', ['shortname' => 'user'], '*', MUST_EXIST);
2698         assign_capability('moodle/user:viewdetails', CAP_ALLOW, $authenticatedrole->id, context_system::instance());
2700         // Perform a search with $CFG->messagingallusers disabled.
2701         set_config('messagingallusers', 0);
2702         $result = core_message_external::message_search_users($users[1]->id, 'search');
2703         $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
2704         $contacts = $result['contacts'];
2705         $noncontacts = $result['noncontacts'];
2707         // Check that we retrieved the correct contacts.
2708         $this->assertCount(2, $contacts);
2709         $this->assertEquals($users[2]->id, $contacts[0]['id']);
2710         $this->assertEquals($users[3]->id, $contacts[1]['id']);
2712         // Check that we retrieved the correct non-contacts.
2713         // Site-wide messaging is disabled, but since we can see all users, we expect to be able to search for any users.
2714         $this->assertCount(4, $noncontacts);
2715         $this->assertEquals($users[5]->id, $noncontacts[0]['id']);
2716         $this->assertEquals($users[6]->id, $noncontacts[1]['id']);
2717         $this->assertEquals($users[7]->id, $noncontacts[2]['id']);
2718         $this->assertEquals($users[8]->id, $noncontacts[3]['id']);
2719     }
2721     /**
2722      * Tests searching users as another user without the 'moodle/user:viewdetails' capability.
2723      */
2724     public function test_message_search_users_without_cap() {
2725         $this->resetAfterTest();
2727         // Create some users.
2728         $user1 = $this->getDataGenerator()->create_user();
2729         $user2 = $this->getDataGenerator()->create_user();
2731         // The person doing the search for another user.
2732         $this->setUser($user1);
2734         // Ensure an exception is thrown.
2735         $this->expectException('moodle_exception');
2736         core_message_external::message_search_users($user2->id, 'User');
2737         $this->assertDebuggingCalled();
2738     }
2740     /**
2741      * Tests searching users with messaging disabled.
2742      */
2743     public function test_message_search_users_messaging_disabled() {
2744         $this->resetAfterTest();
2746         // Create some skeleton data just so we can call the WS.
2747         $user = $this->getDataGenerator()->create_user();
2749         // The person doing the search.
2750         $this->setUser($user);
2752         // Disable messaging.
2753         set_config('messaging', 0);
2755         // Ensure an exception is thrown.
2756         $this->expectException('moodle_exception');
2757         core_message_external::message_search_users($user->id, 'User');
2758     }
2760     /**
2761      * Tests searching messages.
2762      */
2763     public function test_messagearea_search_messages() {
2764         $this->resetAfterTest(true);
2766         // Create some users.
2767         $user1 = self::getDataGenerator()->create_user();
2768         $user2 = self::getDataGenerator()->create_user();
2770         // The person doing the search.
2771         $this->setUser($user1);
2773         // Send some messages back and forth.
2774         $time = time();
2775         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2776         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2777         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2778         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2779         $convid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
2781         // Perform a search.
2782         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2784         // We need to execute the return values cleaning process to simulate the web service server.
2785         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(), $result);
2787         // Confirm the data is correct.
2788         $messages = $result['contacts'];
2789         $this->assertCount(2, $messages);
2791         $message1 = $messages[0];
2792         $message2 = $messages[1];
2794         $this->assertEquals($user2->id, $message1['userid']);
2795         $this->assertEquals(fullname($user2), $message1['fullname']);
2796         $this->assertTrue($message1['ismessaging']);
2797         $this->assertFalse($message1['sentfromcurrentuser']);
2798         $this->assertEquals('Word.', $message1['lastmessage']);
2799         $this->assertNotEmpty($message1['messageid']);
2800         $this->assertNull($message1['isonline']);
2801         $this->assertFalse($message1['isread']);
2802         $this->assertFalse($message1['isblocked']);
2803         $this->assertNull($message1['unreadcount']);
2804         $this->assertEquals($convid, $message1['conversationid']);
2806         $this->assertEquals($user2->id, $message2['userid']);
2807         $this->assertEquals(fullname($user2), $message2['fullname']);
2808         $this->assertTrue($message2['ismessaging']);
2809         $this->assertTrue($message2['sentfromcurrentuser']);
2810         $this->assertEquals('Yo!', $message2['lastmessage']);
2811         $this->assertNotEmpty($message2['messageid']);
2812         $this->assertNull($message2['isonline']);
2813         $this->assertTrue($message2['isread']);
2814         $this->assertFalse($message2['isblocked']);
2815         $this->assertNull($message2['unreadcount']);
2816         $this->assertEquals($convid, $message2['conversationid']);
2817     }
2819     /**
2820      * Tests searching messages as another user.
2821      */
2822     public function test_messagearea_search_messages_as_other_user() {
2823         $this->resetAfterTest(true);
2825         // The person doing the search.
2826         $this->setAdminUser();
2828         // Create some users.
2829         $user1 = self::getDataGenerator()->create_user();
2830         $user2 = self::getDataGenerator()->create_user();
2832         // Send some messages back and forth.
2833         $time = time();
2834         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2835         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2836         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2837         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2839         // Perform a search.
2840         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2842         // We need to execute the return values cleaning process to simulate the web service server.
2843         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
2844             $result);
2846         // Confirm the data is correct.
2847         $messages = $result['contacts'];
2848         $this->assertCount(2, $messages);
2850         $message1 = $messages[0];
2851         $message2 = $messages[1];
2853         $this->assertEquals($user2->id, $message1['userid']);
2854         $this->assertEquals(fullname($user2), $message1['fullname']);
2855         $this->assertTrue($message1['ismessaging']);
2856         $this->assertFalse($message1['sentfromcurrentuser']);
2857         $this->assertEquals('Word.', $message1['lastmessage']);
2858         $this->assertNotEmpty($message1['messageid']);
2859         $this->assertFalse($message1['isonline']);
2860         $this->assertFalse($message1['isread']);
2861         $this->assertFalse($message1['isblocked']);
2862         $this->assertNull($message1['unreadcount']);
2864         $this->assertEquals($user2->id, $message2['userid']);
2865         $this->assertEquals(fullname($user2), $message2['fullname']);
2866         $this->assertTrue($message2['ismessaging']);
2867         $this->assertTrue($message2['sentfromcurrentuser']);
2868         $this->assertEquals('Yo!', $message2['lastmessage']);
2869         $this->assertNotEmpty($message2['messageid']);
2870         $this->assertFalse($message2['isonline']);
2871         $this->assertTrue($message2['isread']);
2872         $this->assertFalse($message2['isblocked']);
2873         $this->assertNull($message2['unreadcount']);
2874     }
2876     /**
2877      * Tests searching messages as another user without the proper capabilities.
2878      */
2879     public function test_messagearea_search_messages_as_other_user_without_cap() {
2880         $this->resetAfterTest(true);
2882         // Create some users.
2883         $user1 = self::getDataGenerator()->create_user();
2884         $user2 = self::getDataGenerator()->create_user();
2886         // The person doing the search for another user.
2887         $this->setUser($user1);
2889         // Ensure an exception is thrown.
2890         $this->expectException('moodle_exception');
2891         core_message_external::data_for_messagearea_search_messages($user2->id, 'Search');
2892     }
2894     /**
2895      * Tests searching messages with messaging disabled
2896      */
2897     public function test_messagearea_search_messages_messaging_disabled() {
2898         global $CFG;
2900         $this->resetAfterTest(true);
2902         // Create some skeleton data just so we can call the WS.
2903         $user = self::getDataGenerator()->create_user();
2905         // The person doing the search .
2906         $this->setUser($user);
2908         // Disable messaging.
2909         $CFG->messaging = 0;
2911         // Ensure an exception is thrown.
2912         $this->expectException('moodle_exception');
2913         core_message_external::data_for_messagearea_search_messages($user->id, 'Search');
2914     }
2916     /**
2917      * Tests retrieving conversations.
2918      */
2919     public function test_messagearea_conversations() {
2920         $this->resetAfterTest(true);
2922         // Create some users.
2923         $user1 = self::getDataGenerator()->create_user();
2924         $user2 = self::getDataGenerator()->create_user();
2925         $user3 = self::getDataGenerator()->create_user();
2926         $user4 = self::getDataGenerator()->create_user();
2928         // The person retrieving the conversations.
2929         $this->setUser($user1);
2931         // Send some messages back and forth, have some different conversations with different users.
2932         $time = time();
2933         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2934         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2935         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2936         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2938         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
2939         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
2940         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
2941         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
2943         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
2944         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
2945         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
2947         // Retrieve the conversations.
2948         $result = core_message_external::data_for_messagearea_conversations($user1->id);
2950         // We need to execute the return values cleaning process to simulate the web service server.
2951         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
2952             $result);
2954         // Confirm the data is correct.
2955         $messages = $result['contacts'];
2956         $this->assertCount(3, $messages);
2958         $message1 = $messages[0];
2959         $message2 = $messages[1];
2960         $message3 = $messages[2];
2962         $this->assertEquals($user4->id, $message1['userid']);
2963         $this->assertTrue($message1['ismessaging']);
2964         $this->assertTrue($message1['sentfromcurrentuser']);
2965         $this->assertEquals('Dope.', $message1['lastmessage']);
2966         $this->assertEquals($messageid3, $message1['messageid']);
2967         $this->assertNull($message1['isonline']);
2968         $this->assertFalse($message1['isread']);
2969         $this->assertFalse($message1['isblocked']);
2970         $this->assertEquals(1, $message1['unreadcount']);
2972         $this->assertEquals($user3->id, $message2['userid']);
2973         $this->assertTrue($message2['ismessaging']);
2974         $this->assertFalse($message2['sentfromcurrentuser']);
2975         $this->assertEquals('Cool.', $message2['lastmessage']);
2976         $this->assertEquals($messageid2, $message2['messageid']);
2977         $this->assertNull($message2['isonline']);
2978         $this->assertFalse($message2['isread']);
2979         $this->assertFalse($message2['isblocked']);
2980         $this->assertEquals(2, $message2['unreadcount']);
2982         $this->assertEquals($user2->id, $message3['userid']);
2983         $this->assertTrue($message3['ismessaging']);
2984         $this->assertFalse($message3['sentfromcurrentuser']);
2985         $this->assertEquals('Word.', $message3['lastmessage']);
2986         $this->assertEquals($messageid1, $message3['messageid']);
2987         $this->assertNull($message3['isonline']);
2988         $this->assertFalse($message3['isread']);
2989         $this->assertFalse($message3['isblocked']);
2990         $this->assertEquals(2, $message3['unreadcount']);
2991     }
2993     /**
2994      * Tests retrieving conversations as another user.
2995      */
2996     public function test_messagearea_conversations_as_other_user() {
2997         $this->resetAfterTest(true);
2999         // Set as admin.
3000         $this->setAdminUser();
3002         // Create some users.
3003         $user1 = self::getDataGenerator()->create_user();
3004         $user2 = self::getDataGenerator()->create_user();
3005         $user3 = self::getDataGenerator()->create_user();
3006         $user4 = self::getDataGenerator()->create_user();
3008         // Send some messages back and forth, have some different conversations with different users.
3009         $time = time();
3010         $this->send_message($user1, $user2, 'Yo!', 0, $time);
3011         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3012         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
3013         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
3015         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
3016         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
3017         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
3018         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
3020         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
3021         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
3022         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
3024         // Retrieve the conversations.
3025         $result = core_message_external::data_for_messagearea_conversations($user1->id);
3027         // We need to execute the return values cleaning process to simulate the web service server.
3028         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
3029             $result);
3031         // Confirm the data is correct.
3032         $messages = $result['contacts'];
3033         $this->assertCount(3, $messages);
3035         $message1 = $messages[0];
3036         $message2 = $messages[1];
3037         $message3 = $messages[2];
3039         $this->assertEquals($user4->id, $message1['userid']);
3040         $this->assertTrue($message1['ismessaging']);
3041         $this->assertTrue($message1['sentfromcurrentuser']);
3042         $this->assertEquals('Dope.', $message1['lastmessage']);
3043         $this->assertEquals($messageid3, $message1['messageid']);
3044         $this->assertFalse($message1['isonline']);
3045         $this->assertFalse($message1['isread']);
3046         $this->assertFalse($message1['isblocked']);
3047         $this->assertEquals(1, $message1['unreadcount']);
3049         $this->assertEquals($user3->id, $message2['userid']);
3050         $this->assertTrue($message2['ismessaging']);
3051         $this->assertFalse($message2['sentfromcurrentuser']);
3052         $this->assertEquals('Cool.', $message2['lastmessage']);
3053         $this->assertEquals($messageid2, $message2['messageid']);
3054         $this->assertFalse($message2['isonline']);
3055         $this->assertFalse($message2['isread']);
3056         $this->assertFalse($message2['isblocked']);
3057         $this->assertEquals(2, $message2['unreadcount']);
3059         $this->assertEquals($user2->id, $message3['userid']);
3060         $this->assertTrue($message3['ismessaging']);
3061         $this->assertFalse($message3['sentfromcurrentuser']);
3062         $this->assertEquals('Word.', $message3['lastmessage']);
3063         $this->assertEquals($messageid1, $message3['messageid']);
3064         $this->assertFalse($message3['isonline']);
3065         $this->assertFalse($message3['isread']);
3066         $this->assertFalse($message3['isblocked']);
3067         $this->assertEquals(2, $message3['unreadcount']);
3068     }
3070     /**
3071      * Tests retrieving conversations as another user without the proper capabilities.
3072      */
3073     public function test_messagearea_conversations_as_other_user_without_cap() {
3074         $this->resetAfterTest(true);
3076         // Create some users.
3077         $user1 = self::getDataGenerator()->create_user();
3078         $user2 = self::getDataGenerator()->create_user();
3080         // The person retrieving the conversations for another user.
3081         $this->setUser($user1);
3083         // Ensure an exception is thrown.
3084         $this->expectException('moodle_exception');
3085         core_message_external::data_for_messagearea_conversations($user2->id);
3086     }
3088     /**
3089      * Tests retrieving conversations with messaging disabled.
3090      */
3091     public function test_messagearea_conversations_messaging_disabled() {
3092         global $CFG;
3094         $this->resetAfterTest(true);
3096         // Create some skeleton data just so we can call the WS.
3097         $user = self::getDataGenerator()->create_user();
3099         // The person retrieving the conversations.
3100         $this->setUser($user);
3102         // Disable messaging.
3103         $CFG->messaging = 0;
3105         // Ensure an exception is thrown.
3106         $this->expectException('moodle_exception');
3107         core_message_external::data_for_messagearea_conversations($user->id);
3108     }
3110     /**
3111      * Tests retrieving contacts.
3112      */
3113     public function test_messagearea_contacts() {
3114         $this->resetAfterTest(true);
3116         // Create some users.
3117         $user1 = self::getDataGenerator()->create_user();
3119         // Set as the user.
3120         $this->setUser($user1);
3122         $user2 = new stdClass();
3123         $user2->firstname = 'User';
3124         $user2->lastname = 'A';
3125         $user2 = self::getDataGenerator()->create_user($user2);
3127         $user3 = new stdClass();
3128         $user3->firstname = 'User';
3129         $user3->lastname = 'B';
3130         $user3 = self::getDataGenerator()->create_user($user3);
3132         $user4 = new stdClass();
3133         $user4->firstname = 'User';
3134         $user4->lastname = 'C';
3135         $user4 = self::getDataGenerator()->create_user($user4);
3137         $user5 = new stdClass();
3138         $user5->firstname = 'User';
3139         $user5->lastname = 'D';
3140         $user5 = self::getDataGenerator()->create_user($user5);
3142         // Add some users as contacts.
3143         \core_message\api::add_contact($user1->id, $user2->id);
3144         \core_message\api::add_contact($user1->id, $user3->id);
3145         \core_message\api::add_contact($user1->id, $user4->id);
3147         // Retrieve the contacts.
3148         $result = core_message_external::data_for_messagearea_contacts($user1->id);
3150         // We need to execute the return values cleaning process to simulate the web service server.
3151         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
3152             $result);
3154         // Confirm the data is correct.
3155         $contacts = $result['contacts'];
3156         usort($contacts, ['static', 'sort_contacts']);
3157         $this->assertCount(3, $contacts);
3159         $contact1 = $contacts[0];
3160         $contact2 = $contacts[1];
3161         $contact3 = $contacts[2];
3163         $this->assertEquals($user2->id, $contact1['userid']);
3164         $this->assertFalse($contact1['ismessaging']);
3165         $this->assertFalse($contact1['sentfromcurrentuser']);
3166         $this->assertNull($contact1['lastmessage']);
3167         $this->assertNull($contact1['messageid']);
3168         $this->assertNull($contact1['isonline']);
3169         $this->assertFalse($contact1['isread']);
3170         $this->assertFalse($contact1['isblocked']);
3171         $this->assertNull($contact1['unreadcount']);
3173         $this->assertEquals($user3->id, $contact2['userid']);
3174         $this->assertFalse($contact2['ismessaging']);
3175         $this->assertFalse($contact2['sentfromcurrentuser']);
3176         $this->assertNull($contact2['lastmessage']);
3177         $this->assertNull($contact2['messageid']);
3178         $this->assertNull($contact2['isonline']);
3179         $this->assertFalse($contact2['isread']);
3180         $this->assertFalse($contact2['isblocked']);
3181         $this->assertNull($contact2['unreadcount']);
3183         $this->assertEquals($user4->id, $contact3['userid']);
3184         $this->assertFalse($contact3['ismessaging']);
3185         $this->assertFalse($contact3['sentfromcurrentuser']);
3186         $this->assertNull($contact3['lastmessage']);
3187         $this->assertNull($contact3['messageid']);
3188         $this->assertNull($contact3['isonline']);
3189         $this->assertFalse($contact3['isread']);
3190         $this->assertFalse($contact3['isblocked']);
3191         $this->assertNull($contact3['unreadcount']);
3192     }
3194     /**
3195      * Tests retrieving contacts as another user.
3196      */
3197     public function test_messagearea_contacts_as_other_user() {
3198         $this->resetAfterTest(true);
3200         $this->setAdminUser();
3202         // Create some users.
3203         $user1 = self::getDataGenerator()->create_user();
3205         $user2 = new stdClass();
3206         $user2->firstname = 'User';
3207         $user2->lastname = 'A';
3208         $user2 = self::getDataGenerator()->create_user($user2);
3210         $user3 = new stdClass();
3211         $user3->firstname = 'User';
3212         $user3->lastname = 'B';
3213         $user3 = self::getDataGenerator()->create_user($user3);
3215         $user4 = new stdClass();
3216         $user4->firstname = 'User';
3217         $user4->lastname = 'C';
3218         $user4 = self::getDataGenerator()->create_user($user4);
3220         $user5 = new stdClass();
3221         $user5->firstname = 'User';
3222         $user5->lastname = 'D';
3223         $user5 = self::getDataGenerator()->create_user($user5);
3225         // Add some users as contacts.
3226         \core_message\api::add_contact($user1->id, $user2->id);
3227         \core_message\api::add_contact($user1->id, $user3->id);
3228         \core_message\api::add_contact($user1->id, $user4->id);
3230         // Retrieve the contacts.
3231         $result = core_message_external::data_for_messagearea_contacts($user1->id);
3233         // We need to execute the return values cleaning process to simulate the web service server.
3234         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
3235             $result);
3237         // Confirm the data is correct.
3238         $contacts = $result['contacts'];
3239         usort($contacts, ['static', 'sort_contacts']);
3240         $this->assertCount(3, $contacts);
3242         $contact1 = $contacts[0];
3243         $contact2 = $contacts[1];
3244         $contact3 = $contacts[2];
3246         $this->assertEquals($user2->id, $contact1['userid']);
3247         $this->assertFalse($contact1['ismessaging']);
3248         $this->assertFalse($contact1['sentfromcurrentuser']);
3249         $this->assertNull($contact1['lastmessage']);
3250         $this->assertNull($contact1['messageid']);
3251         $this->assertFalse($contact1['isonline']);
3252         $this->assertFalse($contact1['isread']);
3253         $this->assertFalse($contact1['isblocked']);
3254         $this->assertNull($contact1['unreadcount']);
3256         $this->assertEquals($user3->id, $contact2['userid']);
3257         $this->assertFalse($contact2['ismessaging']);
3258         $this->assertFalse($contact2['sentfromcurrentuser']);
3259         $this->assertNull($contact2['lastmessage']);
3260         $this->assertNull($contact2['messageid']);
3261         $this->assertFalse($contact2['isonline']);
3262         $this->assertFalse($contact2['isread']);
3263         $this->assertFalse($contact2['isblocked']);
3264         $this->assertNull($contact2['unreadcount']);
3266         $this->assertEquals($user4->id, $contact3['userid']);
3267         $this->assertFalse($contact3['ismessaging']);
3268         $this->assertFalse($contact3['sentfromcurrentuser']);
3269         $this->assertNull($contact3['lastmessage']);
3270         $this->assertNull($contact3['messageid']);
3271         $this->assertFalse($contact3['isonline']);
3272         $this->assertFalse($contact3['isread']);
3273         $this->assertFalse($contact3['isblocked']);
3274         $this->assertNull($contact3['unreadcount']);
3275     }
3277     /**
3278      * Tests retrieving contacts as another user without the proper capabilities.
3279      */
3280     public function test_messagearea_contacts_as_other_user_without_cap() {
3281         $this->resetAfterTest(true);
3283         // Create some users.
3284         $user1 = self::getDataGenerator()->create_user();
3285         $user2 = self::getDataGenerator()->create_user();
3287         // The person retrieving the contacts for another user.
3288         $this->setUser($user1);
3290         // Perform the WS call and ensure an exception is thrown.
3291         $this->expectException('moodle_exception');
3292         core_message_external::data_for_messagearea_contacts($user2->id);
3293     }
3295     /**
3296      * Tests retrieving contacts with messaging disabled.
3297      */
3298     public function test_messagearea_contacts_messaging_disabled() {
3299         global $CFG;
3301         $this->resetAfterTest(true);
3303         // Create some skeleton data just so we can call the WS.
3304         $user = self::getDataGenerator()->create_user();
3306         // The person retrieving the contacts.
3307         $this->setUser($user);
3309         // Disable messaging.
3310         $CFG->messaging = 0;
3312         // Perform the WS call and ensure we are shown that it is disabled.
3313         $this->expectException('moodle_exception');
3314         core_message_external::data_for_messagearea_contacts($user->id);
3315     }
3317     /**
3318      * Tests retrieving contacts.
3319      */
3320     public function test_get_user_contacts() {
3321         $this->resetAfterTest(true);
3323         // Create some users.
3324         $user1 = self::getDataGenerator()->create_user();
3326         // Set as the user.
3327         $this->setUser($user1);
3329         $user2 = new stdClass();
3330         $user2->firstname = 'User';
3331         $user2->lastname = 'A';
3332         $user2 = self::getDataGenerator()->create_user($user2);
3334         $user3 = new stdClass();
3335         $user3->firstname = 'User';
3336         $user3->lastname = 'B';
3337         $user3 = self::getDataGenerator()->create_user($user3);
3339         $user4 = new stdClass();
3340         $user4->firstname = 'User';
3341         $user4->lastname = 'C';
3342         $user4 = self::getDataGenerator()->create_user($user4);
3344         $user5 = new stdClass();
3345         $user5->firstname = 'User';
3346         $user5->lastname = 'D';
3347         $user5 = self::getDataGenerator()->create_user($user5);
3349         // Add some users as contacts.
3350         \core_message\api::add_contact($user1->id, $user2->id);
3351         \core_message\api::add_contact($user1->id, $user3->id);
3352         \core_message\api::add_contact($user1->id, $user4->id);
3354         // Retrieve the contacts.
3355         $result = core_message_external::get_user_contacts($user1->id);
3357         // We need to execute the return values cleaning process to simulate the web service server.
3358         $result = external_api::clean_returnvalue(core_message_external::get_user_contacts_returns(),
3359             $result);
3361         // Confirm the data is correct.
3362         $contacts = $result;
3363         usort($contacts, ['static', 'sort_contacts_id']);
3364         $this->assertCount(3, $contacts);
3366         $contact1 = array_shift($contacts);
3367         $contact2 = array_shift($contacts);
3368         $contact3 = array_shift($contacts);
3370         $this->assertEquals($user2->id, $contact1['id']);
3371         $this->assertEquals(fullname($user2), $contact1['fullname']);
3372         $this->assertTrue($contact1['iscontact']);
3374         $this->assertEquals($user3->id, $contact2['id']);
3375         $this->assertEquals(fullname($user3), $contact2['fullname']);
3376         $this->assertTrue($contact2['iscontact']);
3378         $this->assertEquals($user4->id, $contact3['id']);
3379         $this->assertEquals(fullname($user4), $contact3['fullname']);
3380         $this->assertTrue($contact3['iscontact']);
3381     }
3383     /**