MDL-63214 message: Add privacy preferences to filter who can message
[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 class core_message_externallib_testcase extends externallib_advanced_testcase {
35     /**
36      * Tests set up
37      */
38     protected function setUp() {
39         global $CFG;
41         require_once($CFG->dirroot . '/message/lib.php');
42     }
44     /**
45      * Send a fake message.
46      *
47      * {@link message_send()} does not support transaction, this function will simulate a message
48      * sent from a user to another. We should stop using it once {@link message_send()} will support
49      * transactions. This is not clean at all, this is just used to add rows to the table.
50      *
51      * @param stdClass $userfrom user object of the one sending the message.
52      * @param stdClass $userto user object of the one receiving the message.
53      * @param string $message message to send.
54      * @param int $notification is the message a notification.
55      * @param int $time the time the message was sent
56      */
57     protected function send_message($userfrom, $userto, $message = 'Hello world!', $notification = 0, $time = 0) {
58         global $DB;
60         if (empty($time)) {
61             $time = time();
62         }
64         if ($notification) {
65             $record = new stdClass();
66             $record->useridfrom = $userfrom->id;
67             $record->useridto = $userto->id;
68             $record->subject = 'No subject';
69             $record->fullmessage = $message;
70             $record->smallmessage = $message;
71             $record->timecreated = $time;
73             return $DB->insert_record('notifications', $record);
74         }
76         if (!$conversationid = \core_message\api::get_conversation_between_users([$userfrom->id, $userto->id])) {
77             $conversationid = \core_message\api::create_conversation_between_users([$userfrom->id,
78                 $userto->id]);
79         }
81         // Ok, send the message.
82         $record = new stdClass();
83         $record->useridfrom = $userfrom->id;
84         $record->conversationid = $conversationid;
85         $record->subject = 'No subject';
86         $record->fullmessage = $message;
87         $record->smallmessage = $message;
88         $record->timecreated = $time;
90         return $DB->insert_record('messages', $record);
91     }
93     /**
94      * Test send_instant_messages.
95      */
96     public function test_send_instant_messages() {
97         global $DB, $USER;
99         $this->resetAfterTest();
101         // Transactions used in tests, tell phpunit use alternative reset method.
102         $this->preventResetByRollback();
104         $user1 = self::getDataGenerator()->create_user();
105         $user2 = self::getDataGenerator()->create_user();
107         $this->setUser($user1);
109         // Create test message data.
110         $message1 = array();
111         $message1['touserid'] = $user2->id;
112         $message1['text'] = 'the message.';
113         $message1['clientmsgid'] = 4;
114         $messages = array($message1);
116         $sentmessages = core_message_external::send_instant_messages($messages);
117         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
118         $this->assertEquals(
119             get_string('usercantbemessaged', 'message', fullname(\core_user::get_user($message1['touserid']))),
120             array_pop($sentmessages)['errormessage']
121         );
123         // Add the user1 as a contact.
124         \core_message\api::add_contact($user1->id, $user2->id);
126         // Send message again. Now it should work properly.
127         $sentmessages = core_message_external::send_instant_messages($messages);
128         // We need to execute the return values cleaning process to simulate the web service server.
129         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
131         $sentmessage = reset($sentmessages);
133         $sql = "SELECT m.*, mcm.userid as useridto
134                  FROM {messages} m
135            INNER JOIN {message_conversations} mc
136                    ON m.conversationid = mc.id
137            INNER JOIN {message_conversation_members} mcm
138                    ON mcm.conversationid = mc.id
139                 WHERE mcm.userid != ?
140                   AND m.id = ?";
141         $themessage = $DB->get_record_sql($sql, [$USER->id, $sentmessage['msgid']]);
143         // Confirm that the message was inserted correctly.
144         $this->assertEquals($themessage->useridfrom, $user1->id);
145         $this->assertEquals($themessage->useridto, $message1['touserid']);
146         $this->assertEquals($themessage->smallmessage, $message1['text']);
147         $this->assertEquals($sentmessage['clientmsgid'], $message1['clientmsgid']);
148     }
150     /**
151      * Test send_instant_messages to a user who has blocked you.
152      */
153     public function test_send_instant_messages_blocked_user() {
154         global $DB;
156         $this->resetAfterTest();
158         // Transactions used in tests, tell phpunit use alternative reset method.
159         $this->preventResetByRollback();
161         $user1 = self::getDataGenerator()->create_user();
162         $user2 = self::getDataGenerator()->create_user();
164         $this->setUser($user1);
166         \core_message\api::block_user($user2->id, $user1->id);
168         // Create test message data.
169         $message1 = array();
170         $message1['touserid'] = $user2->id;
171         $message1['text'] = 'the message.';
172         $message1['clientmsgid'] = 4;
173         $messages = array($message1);
175         $sentmessages = core_message_external::send_instant_messages($messages);
176         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
178         $sentmessage = reset($sentmessages);
180         $this->assertEquals(get_string('usercantbemessaged', 'message', fullname($user2)), $sentmessage['errormessage']);
182         $this->assertEquals(0, $DB->count_records('messages'));
183     }
185     /**
186      * Test send_instant_messages when sending a message to a non-contact who has blocked non-contacts.
187      */
188     public function test_send_instant_messages_block_non_contacts() {
189         global $DB;
191         $this->resetAfterTest(true);
193         // Transactions used in tests, tell phpunit use alternative reset method.
194         $this->preventResetByRollback();
196         $user1 = self::getDataGenerator()->create_user();
197         $user2 = self::getDataGenerator()->create_user();
199         $this->setUser($user1);
201         // Set the user preference so user 2 does not accept messages from non-contacts.
202         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2);
204         // Create test message data.
205         $message1 = array();
206         $message1['touserid'] = $user2->id;
207         $message1['text'] = 'the message.';
208         $message1['clientmsgid'] = 4;
209         $messages = array($message1);
211         $sentmessages = core_message_external::send_instant_messages($messages);
212         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
214         $sentmessage = reset($sentmessages);
216         $this->assertEquals(get_string('usercantbemessaged', 'message', fullname($user2)), $sentmessage['errormessage']);
218         $this->assertEquals(0, $DB->count_records('messages'));
219     }
221     /**
222      * Test send_instant_messages when sending a message to a contact who has blocked non-contacts.
223      */
224     public function test_send_instant_messages_block_non_contacts_but_am_contact() {
225         global $DB, $USER;
227         $this->resetAfterTest(true);
229         // Transactions used in tests, tell phpunit use alternative reset method.
230         $this->preventResetByRollback();
232         $user1 = self::getDataGenerator()->create_user();
233         $user2 = self::getDataGenerator()->create_user();
235         $this->setUser($user1);
237         // Set the user preference so user 2 does not accept messages from non-contacts.
238         set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2);
240         \core_message\api::add_contact($user1->id, $user2->id);
242         // Create test message data.
243         $message1 = array();
244         $message1['touserid'] = $user2->id;
245         $message1['text'] = 'the message.';
246         $message1['clientmsgid'] = 4;
247         $messages = array($message1);
249         $sentmessages = core_message_external::send_instant_messages($messages);
250         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
252         $sentmessage = reset($sentmessages);
254         $sql = "SELECT m.*, mcm.userid as useridto
255                  FROM {messages} m
256            INNER JOIN {message_conversations} mc
257                    ON m.conversationid = mc.id
258            INNER JOIN {message_conversation_members} mcm
259                    ON mcm.conversationid = mc.id
260                 WHERE mcm.userid != ?
261                   AND m.id = ?";
262         $themessage = $DB->get_record_sql($sql, [$USER->id, $sentmessage['msgid']]);
264         // Confirm that the message was inserted correctly.
265         $this->assertEquals($themessage->useridfrom, $user1->id);
266         $this->assertEquals($themessage->useridto, $message1['touserid']);
267         $this->assertEquals($themessage->smallmessage, $message1['text']);
268         $this->assertEquals($sentmessage['clientmsgid'], $message1['clientmsgid']);
269     }
271     /**
272      * Test send_instant_messages with no capabilities
273      */
274     public function test_send_instant_messages_no_capability() {
275         global $DB;
277         $this->resetAfterTest(true);
279         // Transactions used in tests, tell phpunit use alternative reset method.
280         $this->preventResetByRollback();
282         $user1 = self::getDataGenerator()->create_user();
283         $user2 = self::getDataGenerator()->create_user();
285         $this->setUser($user1);
287         // Unset the required capabilities by the external function.
288         $contextid = context_system::instance()->id;
289         $userrole = $DB->get_record('role', array('shortname' => 'user'));
290         $this->unassignUserCapability('moodle/site:sendmessage', $contextid, $userrole->id);
292         // Create test message data.
293         $message1 = array();
294         $message1['touserid'] = $user2->id;
295         $message1['text'] = 'the message.';
296         $message1['clientmsgid'] = 4;
297         $messages = array($message1);
299         $this->expectException('required_capability_exception');
300         core_message_external::send_instant_messages($messages);
301     }
303     /**
304      * Test send_instant_messages when messaging is disabled.
305      */
306     public function test_send_instant_messages_messaging_disabled() {
307         global $CFG;
309         $this->resetAfterTest(true);
311         // Transactions used in tests, tell phpunit use alternative reset method.
312         $this->preventResetByRollback();
314         $user1 = self::getDataGenerator()->create_user();
315         $user2 = self::getDataGenerator()->create_user();
317         $this->setUser($user1);
319         // Disable messaging.
320         $CFG->messaging = 0;
322         // Create test message data.
323         $message1 = array();
324         $message1['touserid'] = $user2->id;
325         $message1['text'] = 'the message.';
326         $message1['clientmsgid'] = 4;
327         $messages = array($message1);
329         $this->expectException('moodle_exception');
330         core_message_external::send_instant_messages($messages);
331     }
333     /**
334      * Test create_contacts.
335      */
336     public function test_create_contacts() {
337         $this->resetAfterTest(true);
339         $user1 = self::getDataGenerator()->create_user();
340         $user2 = self::getDataGenerator()->create_user();
341         $user3 = self::getDataGenerator()->create_user();
342         $user4 = self::getDataGenerator()->create_user();
343         $user5 = self::getDataGenerator()->create_user();
344         $this->setUser($user1);
346         // Adding a contact.
347         $return = core_message_external::create_contacts(array($user2->id));
348         $this->assertDebuggingCalled();
349         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
350         $this->assertEquals(array(), $return);
352         // Adding a contact who is already a contact.
353         $return = core_message_external::create_contacts(array($user2->id));
354         $this->assertDebuggingCalled();
355         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
356         $this->assertEquals(array(), $return);
358         // Adding multiple contacts.
359         $return = core_message_external::create_contacts(array($user3->id, $user4->id));
360         $this->assertDebuggingCalledCount(2);
361         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
362         $this->assertEquals(array(), $return);
364         // Adding a non-existing user.
365         $return = core_message_external::create_contacts(array(99999));
366         $this->assertDebuggingCalled();
367         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
368         $this->assertCount(1, $return);
369         $return = array_pop($return);
370         $this->assertEquals($return['warningcode'], 'contactnotcreated');
371         $this->assertEquals($return['itemid'], 99999);
373         // Adding contacts with valid and invalid parameters.
374         $return = core_message_external::create_contacts(array($user5->id, 99999));
375         $this->assertDebuggingCalledCount(2);
376         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
377         $this->assertCount(1, $return);
378         $return = array_pop($return);
379         $this->assertEquals($return['warningcode'], 'contactnotcreated');
380         $this->assertEquals($return['itemid'], 99999);
382         // Try to add a contact to another user, should throw an exception.
383         // All assertions must be added before this point.
384         $this->expectException('required_capability_exception');
385         core_message_external::create_contacts(array($user2->id), $user3->id);
386     }
388     /**
389      * Test delete_contacts.
390      */
391     public function test_delete_contacts() {
392         $this->resetAfterTest(true);
394         $user1 = self::getDataGenerator()->create_user();
395         $user2 = self::getDataGenerator()->create_user();
396         $user3 = self::getDataGenerator()->create_user();
397         $user4 = self::getDataGenerator()->create_user();
398         $user5 = self::getDataGenerator()->create_user();
399         $user6 = self::getDataGenerator()->create_user();
400         $this->setUser($user1);
402         \core_message\api::add_contact($user1->id, $user3->id);
403         \core_message\api::add_contact($user1->id, $user4->id);
404         \core_message\api::add_contact($user1->id, $user5->id);
405         \core_message\api::add_contact($user1->id, $user6->id);
407         // Removing a non-contact.
408         $return = core_message_external::delete_contacts(array($user2->id));
409         $this->assertNull($return);
411         // Removing one contact.
412         $return = core_message_external::delete_contacts(array($user3->id));
413         $this->assertNull($return);
415         // Removing multiple contacts.
416         $return = core_message_external::delete_contacts(array($user4->id, $user5->id));
417         $this->assertNull($return);
419         // Removing contact from unexisting user.
420         $return = core_message_external::delete_contacts(array(99999));
421         $this->assertNull($return);
423         // Removing mixed valid and invalid data.
424         $return = core_message_external::delete_contacts(array($user6->id, 99999));
425         $this->assertNull($return);
427         // Try to delete a contact of another user contact list, should throw an exception.
428         // All assertions must be added before this point.
429         $this->expectException('required_capability_exception');
430         core_message_external::delete_contacts(array($user2->id), $user3->id);
431     }
433     /**
434      * Test block_contacts.
435      */
436     public function test_block_contacts() {
437         $this->resetAfterTest(true);
439         $user1 = self::getDataGenerator()->create_user();
440         $user2 = self::getDataGenerator()->create_user();
441         $user3 = self::getDataGenerator()->create_user();
442         $user4 = self::getDataGenerator()->create_user();
443         $user5 = self::getDataGenerator()->create_user();
444         $this->setUser($user1);
446         \core_message\api::add_contact($user1->id, $user3->id);
447         \core_message\api::add_contact($user1->id, $user4->id);
448         \core_message\api::add_contact($user1->id, $user5->id);
450         // Blocking a contact.
451         $return = core_message_external::block_contacts(array($user2->id));
452         $this->assertDebuggingCalled();
453         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
454         $this->assertEquals(array(), $return);
456         // Blocking a contact who is already a contact.
457         $return = core_message_external::block_contacts(array($user2->id));
458         $this->assertDebuggingCalled();
459         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
460         $this->assertEquals(array(), $return);
462         // Blocking multiple contacts.
463         $return = core_message_external::block_contacts(array($user3->id, $user4->id));
464         $this->assertDebuggingCalledCount(2);
465         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
466         $this->assertEquals(array(), $return);
468         // Blocking a non-existing user.
469         $return = core_message_external::block_contacts(array(99999));
470         $this->assertDebuggingCalled();
471         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
472         $this->assertCount(1, $return);
473         $return = array_pop($return);
474         $this->assertEquals($return['warningcode'], 'contactnotblocked');
475         $this->assertEquals($return['itemid'], 99999);
477         // Blocking contacts with valid and invalid parameters.
478         $return = core_message_external::block_contacts(array($user5->id, 99999));
479         $this->assertDebuggingCalledCount(2);
480         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
481         $this->assertCount(1, $return);
482         $return = array_pop($return);
483         $this->assertEquals($return['warningcode'], 'contactnotblocked');
484         $this->assertEquals($return['itemid'], 99999);
486         // Try to block a contact of another user contact list, should throw an exception.
487         // All assertions must be added before this point.
488         $this->expectException('required_capability_exception');
489         core_message_external::block_contacts(array($user2->id), $user3->id);
490     }
492     /**
493      * Test unblock_contacts.
494      */
495     public function test_unblock_contacts() {
496         $this->resetAfterTest(true);
498         $user1 = self::getDataGenerator()->create_user();
499         $user2 = self::getDataGenerator()->create_user();
500         $user3 = self::getDataGenerator()->create_user();
501         $user4 = self::getDataGenerator()->create_user();
502         $user5 = self::getDataGenerator()->create_user();
503         $user6 = self::getDataGenerator()->create_user();
504         $this->setUser($user1);
506         \core_message\api::add_contact($user1->id, $user3->id);
507         \core_message\api::add_contact($user1->id, $user4->id);
508         \core_message\api::add_contact($user1->id, $user5->id);
509         \core_message\api::add_contact($user1->id, $user6->id);
511         // Removing a non-contact.
512         $return = core_message_external::unblock_contacts(array($user2->id));
513         $this->assertDebuggingCalled();
514         $this->assertNull($return);
516         // Removing one contact.
517         $return = core_message_external::unblock_contacts(array($user3->id));
518         $this->assertDebuggingCalled();
519         $this->assertNull($return);
521         // Removing multiple contacts.
522         $return = core_message_external::unblock_contacts(array($user4->id, $user5->id));
523         $this->assertDebuggingCalledCount(2);
524         $this->assertNull($return);
526         // Removing contact from unexisting user.
527         $return = core_message_external::unblock_contacts(array(99999));
528         $this->assertDebuggingCalled();
529         $this->assertNull($return);
531         // Removing mixed valid and invalid data.
532         $return = core_message_external::unblock_contacts(array($user6->id, 99999));
533         $this->assertDebuggingCalledCount(2);
534         $this->assertNull($return);
536         // Try to unblock a contact of another user contact list, should throw an exception.
537         // All assertions must be added before this point.
538         $this->expectException('required_capability_exception');
539         core_message_external::unblock_contacts(array($user2->id), $user3->id);
540         $this->assertDebuggingCalled();
541     }
543     /**
544      * Test getting contact requests.
545      */
546     public function test_get_contact_requests() {
547         $this->resetAfterTest();
549         $user1 = self::getDataGenerator()->create_user();
550         $user2 = self::getDataGenerator()->create_user();
551         $user3 = self::getDataGenerator()->create_user();
553         $this->setUser($user1);
555         // Block one user, their request should not show up.
556         \core_message\api::block_user($user1->id, $user3->id);
558         \core_message\api::create_contact_request($user2->id, $user1->id);
559         \core_message\api::create_contact_request($user3->id, $user1->id);
561         $requests = core_message_external::get_contact_requests($user1->id);
562         $requests = external_api::clean_returnvalue(core_message_external::get_contact_requests_returns(), $requests);
564         $this->assertCount(1, $requests);
566         $request = reset($requests);
568         $this->assertEquals($user2->id, $request['id']);
569         $this->assertEquals($user2->picture, $request['picture']);
570         $this->assertEquals($user2->firstname, $request['firstname']);
571         $this->assertEquals($user2->lastname, $request['lastname']);
572         $this->assertEquals($user2->firstnamephonetic, $request['firstnamephonetic']);
573         $this->assertEquals($user2->lastnamephonetic, $request['lastnamephonetic']);
574         $this->assertEquals($user2->middlename, $request['middlename']);
575         $this->assertEquals($user2->alternatename, $request['alternatename']);
576         $this->assertEquals($user2->email, $request['email']);
577     }
579     /**
580      * Test getting contact requests with messaging disabled.
581      */
582     public function test_get_contact_requests_messaging_disabled() {
583         global $CFG;
585         $this->resetAfterTest();
587         // Create some skeleton data just so we can call the WS.
588         $user1 = self::getDataGenerator()->create_user();
590         $this->setUser($user1);
592         // Disable messaging.
593         $CFG->messaging = 0;
595         // Ensure an exception is thrown.
596         $this->expectException('moodle_exception');
597         core_message_external::get_contact_requests($user1->id);
598     }
600     /**
601      * Test getting contact requests with no permission.
602      */
603     public function test_get_contact_requests_no_permission() {
604         $this->resetAfterTest();
606         // Create some skeleton data just so we can call the WS.
607         $user1 = self::getDataGenerator()->create_user();
608         $user2 = self::getDataGenerator()->create_user();
609         $user3 = self::getDataGenerator()->create_user();
611         $this->setUser($user3);
613         // Ensure an exception is thrown.
614         $this->expectException('required_capability_exception');
615         core_message_external::create_contact_request($user1->id, $user2->id);
616     }
618     /**
619      * Test creating a contact request.
620      */
621     public function test_create_contact_request() {
622         global $CFG, $DB;
624         $this->resetAfterTest();
626         $user1 = self::getDataGenerator()->create_user();
627         $user2 = self::getDataGenerator()->create_user();
629         $this->setUser($user1);
631         // Allow users to message anyone site-wide.
632         $CFG->messagingallusers = 1;
634         $return = core_message_external::create_contact_request($user1->id, $user2->id);
635         $return = external_api::clean_returnvalue(core_message_external::create_contact_request_returns(), $return);
636         $this->assertEquals(array(), $return);
638         $request = $DB->get_records('message_contact_requests');
640         $this->assertCount(1, $request);
642         $request = reset($request);
644         $this->assertEquals($user1->id, $request->userid);
645         $this->assertEquals($user2->id, $request->requesteduserid);
646     }
648     /**
649      * Test creating a contact request when not allowed.
650      */
651     public function test_create_contact_request_not_allowed() {
652         global $CFG;
654         $this->resetAfterTest();
656         $user1 = self::getDataGenerator()->create_user();
657         $user2 = self::getDataGenerator()->create_user();
659         $this->setUser($user1);
661         $CFG->messagingallusers = 0;
663         $return = core_message_external::create_contact_request($user1->id, $user2->id);
664         $return = external_api::clean_returnvalue(core_message_external::create_contact_request_returns(), $return);
666         $warning = reset($return);
668         $this->assertEquals('user', $warning['item']);
669         $this->assertEquals($user2->id, $warning['itemid']);
670         $this->assertEquals('cannotcreatecontactrequest', $warning['warningcode']);
671         $this->assertEquals('You are unable to create a contact request for this user', $warning['message']);
672     }
674     /**
675      * Test creating a contact request with messaging disabled.
676      */
677     public function test_create_contact_request_messaging_disabled() {
678         global $CFG;
680         $this->resetAfterTest();
682         // Create some skeleton data just so we can call the WS.
683         $user1 = self::getDataGenerator()->create_user();
684         $user2 = self::getDataGenerator()->create_user();
686         $this->setUser($user1);
688         // Disable messaging.
689         $CFG->messaging = 0;
691         // Ensure an exception is thrown.
692         $this->expectException('moodle_exception');
693         core_message_external::create_contact_request($user1->id, $user2->id);
694     }
696     /**
697      * Test creating a contact request with no permission.
698      */
699     public function test_create_contact_request_no_permission() {
700         $this->resetAfterTest();
702         // Create some skeleton data just so we can call the WS.
703         $user1 = self::getDataGenerator()->create_user();
704         $user2 = self::getDataGenerator()->create_user();
705         $user3 = self::getDataGenerator()->create_user();
707         $this->setUser($user3);
709         // Ensure an exception is thrown.
710         $this->expectException('required_capability_exception');
711         core_message_external::create_contact_request($user1->id, $user2->id);
712     }
714     /**
715      * Test confirming a contact request.
716      */
717     public function test_confirm_contact_request() {
718         global $DB;
720         $this->resetAfterTest();
722         $user1 = self::getDataGenerator()->create_user();
723         $user2 = self::getDataGenerator()->create_user();
725         $this->setUser($user1);
727         \core_message\api::create_contact_request($user1->id, $user2->id);
729         $this->setUser($user2);
731         $return = core_message_external::confirm_contact_request($user1->id, $user2->id);
732         $return = external_api::clean_returnvalue(core_message_external::confirm_contact_request_returns(), $return);
733         $this->assertEquals(array(), $return);
735         $this->assertEquals(0, $DB->count_records('message_contact_requests'));
737         $contact = $DB->get_records('message_contacts');
739         $this->assertCount(1, $contact);
741         $contact = reset($contact);
743         $this->assertEquals($user1->id, $contact->userid);
744         $this->assertEquals($user2->id, $contact->contactid);
745     }
747     /**
748      * Test confirming a contact request with messaging disabled.
749      */
750     public function test_confirm_contact_request_messaging_disabled() {
751         global $CFG;
753         $this->resetAfterTest();
755         // Create some skeleton data just so we can call the WS.
756         $user1 = self::getDataGenerator()->create_user();
757         $user2 = self::getDataGenerator()->create_user();
759         $this->setUser($user1);
761         // Disable messaging.
762         $CFG->messaging = 0;
764         // Ensure an exception is thrown.
765         $this->expectException('moodle_exception');
766         core_message_external::confirm_contact_request($user1->id, $user2->id);
767     }
769     /**
770      * Test confirming a contact request with no permission.
771      */
772     public function test_confirm_contact_request_no_permission() {
773         $this->resetAfterTest();
775         // Create some skeleton data just so we can call the WS.
776         $user1 = self::getDataGenerator()->create_user();
777         $user2 = self::getDataGenerator()->create_user();
778         $user3 = self::getDataGenerator()->create_user();
780         $this->setUser($user3);
782         // Ensure an exception is thrown.
783         $this->expectException('required_capability_exception');
784         core_message_external::confirm_contact_request($user1->id, $user2->id);
785     }
787     /**
788      * Test declining a contact request.
789      */
790     public function test_decline_contact_request() {
791         global $DB;
793         $this->resetAfterTest();
795         $user1 = self::getDataGenerator()->create_user();
796         $user2 = self::getDataGenerator()->create_user();
798         $this->setUser($user1);
800         \core_message\api::create_contact_request($user1->id, $user2->id);
802         $this->setUser($user2);
804         $return = core_message_external::decline_contact_request($user1->id, $user2->id);
805         $return = external_api::clean_returnvalue(core_message_external::decline_contact_request_returns(), $return);
806         $this->assertEquals(array(), $return);
808         $this->assertEquals(0, $DB->count_records('message_contact_requests'));
809         $this->assertEquals(0, $DB->count_records('message_contacts'));
810     }
812     /**
813      * Test declining a contact request with messaging disabled.
814      */
815     public function test_decline_contact_request_messaging_disabled() {
816         global $CFG;
818         $this->resetAfterTest();
820         // Create some skeleton data just so we can call the WS.
821         $user1 = self::getDataGenerator()->create_user();
822         $user2 = self::getDataGenerator()->create_user();
824         $this->setUser($user1);
826         // Disable messaging.
827         $CFG->messaging = 0;
829         // Ensure an exception is thrown.
830         $this->expectException('moodle_exception');
831         core_message_external::decline_contact_request($user1->id, $user2->id);
832     }
834     /**
835      * Test declining a contact request with no permission.
836      */
837     public function test_decline_contact_request_no_permission() {
838         $this->resetAfterTest();
840         // Create some skeleton data just so we can call the WS.
841         $user1 = self::getDataGenerator()->create_user();
842         $user2 = self::getDataGenerator()->create_user();
843         $user3 = self::getDataGenerator()->create_user();
845         $this->setUser($user3);
847         // Ensure an exception is thrown.
848         $this->expectException('required_capability_exception');
849         core_message_external::decline_contact_request($user1->id, $user2->id);
850     }
852     /**
853      * Test blocking a user.
854      */
855     public function test_block_user() {
856         global $DB;
858         $this->resetAfterTest(true);
860         $user1 = self::getDataGenerator()->create_user();
861         $user2 = self::getDataGenerator()->create_user();
863         $this->setUser($user1);
865         // Blocking a user.
866         $return = core_message_external::block_user($user1->id, $user2->id);
867         $return = external_api::clean_returnvalue(core_message_external::block_user_returns(), $return);
868         $this->assertEquals(array(), $return);
870         // Get list of blocked users.
871         $record = $DB->get_record('message_users_blocked', []);
873         $this->assertEquals($user1->id, $record->userid);
874         $this->assertEquals($user2->id, $record->blockeduserid);
876         // Blocking a user who is already blocked.
877         $return = core_message_external::block_user($user1->id, $user2->id);
878         $return = external_api::clean_returnvalue(core_message_external::block_user_returns(), $return);
879         $this->assertEquals(array(), $return);
881         $this->assertEquals(1, $DB->count_records('message_users_blocked'));
882     }
884     /**
885      * Test blocking a user with messaging disabled.
886      */
887     public function test_block_user_messaging_disabled() {
888         global $CFG;
890         $this->resetAfterTest();
892         // Create some skeleton data just so we can call the WS.
893         $user1 = self::getDataGenerator()->create_user();
894         $user2 = self::getDataGenerator()->create_user();
896         $this->setUser($user1);
898         // Disable messaging.
899         $CFG->messaging = 0;
901         // Ensure an exception is thrown.
902         $this->expectException('moodle_exception');
903         core_message_external::block_user($user1->id, $user2->id);
904     }
906     /**
907      * Test blocking a user with no permission.
908      */
909     public function test_block_user_no_permission() {
910         $this->resetAfterTest();
912         // Create some skeleton data just so we can call the WS.
913         $user1 = self::getDataGenerator()->create_user();
914         $user2 = self::getDataGenerator()->create_user();
915         $user3 = self::getDataGenerator()->create_user();
917         $this->setUser($user3);
919         // Ensure an exception is thrown.
920         $this->expectException('required_capability_exception');
921         core_message_external::block_user($user1->id, $user2->id);
922     }
924     /**
925      * Test unblocking a user.
926      */
927     public function test_unblock_user() {
928         global $DB;
930         $this->resetAfterTest(true);
932         $user1 = self::getDataGenerator()->create_user();
933         $user2 = self::getDataGenerator()->create_user();
935         $this->setUser($user1);
937         // Block the user.
938         \core_message\api::block_user($user1->id, $user2->id);
940         // Unblocking a user.
941         $return = core_message_external::unblock_user($user1->id, $user2->id);
942         $return = external_api::clean_returnvalue(core_message_external::unblock_user_returns(), $return);
943         $this->assertEquals(array(), $return);
945         $this->assertEquals(0, $DB->count_records('message_users_blocked'));
947         // Unblocking a user who is already unblocked.
948         $return = core_message_external::unblock_user($user1->id, $user2->id);
949         $return = external_api::clean_returnvalue(core_message_external::unblock_user_returns(), $return);
950         $this->assertEquals(array(), $return);
952         $this->assertEquals(0, $DB->count_records('message_users_blocked'));
953     }
955     /**
956      * Test unblocking a user with messaging disabled.
957      */
958     public function test_unblock_user_messaging_disabled() {
959         global $CFG;
961         $this->resetAfterTest();
963         // Create some skeleton data just so we can call the WS.
964         $user1 = self::getDataGenerator()->create_user();
965         $user2 = self::getDataGenerator()->create_user();
967         $this->setUser($user1);
969         // Disable messaging.
970         $CFG->messaging = 0;
972         // Ensure an exception is thrown.
973         $this->expectException('moodle_exception');
974         core_message_external::unblock_user($user1->id, $user2->id);
975     }
977     /**
978      * Test unblocking a user with no permission.
979      */
980     public function test_unblock_user_no_permission() {
981         $this->resetAfterTest();
983         // Create some skeleton data just so we can call the WS.
984         $user1 = self::getDataGenerator()->create_user();
985         $user2 = self::getDataGenerator()->create_user();
986         $user3 = self::getDataGenerator()->create_user();
988         $this->setUser($user3);
990         // Ensure an exception is thrown.
991         $this->expectException('required_capability_exception');
992         core_message_external::unblock_user($user1->id, $user2->id);
993     }
995     /**
996      * Test get_contacts.
997      */
998     public function test_get_contacts() {
999         $this->resetAfterTest(true);
1001         $user1 = self::getDataGenerator()->create_user();
1002         $user_stranger = self::getDataGenerator()->create_user();
1003         $user_offline1 = self::getDataGenerator()->create_user();
1004         $user_offline2 = self::getDataGenerator()->create_user();
1005         $user_offline3 = self::getDataGenerator()->create_user();
1006         $user_online = new stdClass();
1007         $user_online->lastaccess = time();
1008         $user_online = self::getDataGenerator()->create_user($user_online);
1009         $user_blocked = self::getDataGenerator()->create_user();
1010         $noreplyuser = core_user::get_user(core_user::NOREPLY_USER);
1012         // Login as user1.
1013         $this->setUser($user1);
1014         \core_message\api::add_contact($user1->id, $user_offline1->id);
1015         \core_message\api::add_contact($user1->id, $user_offline2->id);
1016         \core_message\api::add_contact($user1->id, $user_offline3->id);
1017         \core_message\api::add_contact($user1->id, $user_online->id);
1019         // User_stranger sends a couple of messages to user1.
1020         $this->send_message($user_stranger, $user1, 'Hello there!');
1021         $this->send_message($user_stranger, $user1, 'How you goin?');
1022         $this->send_message($user_stranger, $user1, 'Cya!');
1023         $this->send_message($noreplyuser, $user1, 'I am not a real user');
1025         // User_blocked sends a message to user1.
1026         $this->send_message($user_blocked, $user1, 'Here, have some spam.');
1028         // Retrieve the contacts of the user.
1029         $this->setUser($user1);
1030         $contacts = core_message_external::get_contacts();
1031         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1032         $this->assertCount(3, $contacts['offline']);
1033         $this->assertCount(1, $contacts['online']);
1034         $this->assertCount(3, $contacts['strangers']);
1035         core_message_external::block_contacts(array($user_blocked->id));
1036         $this->assertDebuggingCalled();
1037         $contacts = core_message_external::get_contacts();
1038         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1039         $this->assertCount(3, $contacts['offline']);
1040         $this->assertCount(1, $contacts['online']);
1041         $this->assertCount(2, $contacts['strangers']);
1043         // Checking some of the fields returned.
1044         $stranger = array_pop($contacts['strangers']);
1046         $this->assertEquals(core_user::NOREPLY_USER, $stranger['id']);
1047         $this->assertEquals(1, $stranger['unread']);
1049         // Check that deleted users are not returned.
1050         delete_user($user_offline1);
1051         delete_user($user_stranger);
1052         delete_user($user_online);
1053         $contacts = core_message_external::get_contacts();
1054         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1055         $this->assertCount(2, $contacts['offline']);
1056         $this->assertCount(0, $contacts['online']);
1057         $this->assertCount(1, $contacts['strangers']);
1058     }
1060     /**
1061      * Test search_contacts.
1062      * @expectedException moodle_exception
1063      */
1064     public function test_search_contacts() {
1065         global $DB;
1066         $this->resetAfterTest(true);
1068         $course1 = $this->getDataGenerator()->create_course();
1069         $course2 = $this->getDataGenerator()->create_course();
1071         $user1 = new stdClass();
1072         $user1->firstname = 'X';
1073         $user1->lastname = 'X';
1074         $user1 = $this->getDataGenerator()->create_user($user1);
1075         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1076         $this->getDataGenerator()->enrol_user($user1->id, $course2->id);
1078         $user2 = new stdClass();
1079         $user2->firstname = 'Eric';
1080         $user2->lastname = 'Cartman';
1081         $user2 = self::getDataGenerator()->create_user($user2);
1082         $user3 = new stdClass();
1083         $user3->firstname = 'Stan';
1084         $user3->lastname = 'Marsh';
1085         $user3 = self::getDataGenerator()->create_user($user3);
1086         self::getDataGenerator()->enrol_user($user3->id, $course1->id);
1087         $user4 = new stdClass();
1088         $user4->firstname = 'Kyle';
1089         $user4->lastname = 'Broflovski';
1090         $user4 = self::getDataGenerator()->create_user($user4);
1091         $user5 = new stdClass();
1092         $user5->firstname = 'Kenny';
1093         $user5->lastname = 'McCormick';
1094         $user5 = self::getDataGenerator()->create_user($user5);
1095         self::getDataGenerator()->enrol_user($user5->id, $course2->id);
1097         $this->setUser($user1);
1099         $results = core_message_external::search_contacts('r');
1100         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1101         $this->assertCount(5, $results); // Users 2 through 5 + admin
1103         $results = core_message_external::search_contacts('r', true);
1104         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1105         $this->assertCount(2, $results);
1107         $results = core_message_external::search_contacts('Kyle', false);
1108         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1109         $this->assertCount(1, $results);
1110         $result = reset($results);
1111         $this->assertEquals($user4->id, $result['id']);
1113         $results = core_message_external::search_contacts('y', false);
1114         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1115         $this->assertCount(2, $results);
1117         $results = core_message_external::search_contacts('y', true);
1118         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1119         $this->assertCount(1, $results);
1120         $result = reset($results);
1121         $this->assertEquals($user5->id, $result['id']);
1123         // Empty query, will throw an exception.
1124         $results = core_message_external::search_contacts('');
1125     }
1127     /**
1128      * Test get_messages.
1129      */
1130     public function test_get_messages() {
1131         global $CFG, $DB;
1132         $this->resetAfterTest(true);
1134         $this->preventResetByRollback();
1135         // This mark the messages as read!.
1136         $sink = $this->redirectMessages();
1138         $user1 = self::getDataGenerator()->create_user();
1139         $user2 = self::getDataGenerator()->create_user();
1140         $user3 = self::getDataGenerator()->create_user();
1142         $course = self::getDataGenerator()->create_course();
1144         // Send a message from one user to another.
1145         message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
1146         message_post_message($user1, $user3, 'some random text 2', FORMAT_MOODLE);
1147         message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
1148         message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
1149         message_post_message($user3, $user1, 'some random text 5', FORMAT_MOODLE);
1151         $this->setUser($user1);
1152         // Get read conversations from user1 to user2.
1153         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
1154         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1155         $this->assertCount(1, $messages['messages']);
1157         // Delete the message.
1158         $message = array_shift($messages['messages']);
1159         \core_message\api::delete_message($user1->id, $message['id']);
1161         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
1162         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1163         $this->assertCount(0, $messages['messages']);
1165         // Get unread conversations from user1 to user2.
1166         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', false, true, 0, 0);
1167         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1168         $this->assertCount(0, $messages['messages']);
1170         // Get read messages send from user1.
1171         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1172         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1173         $this->assertCount(1, $messages['messages']);
1175         $this->setUser($user2);
1176         // Get read conversations from any user to user2.
1177         $messages = core_message_external::get_messages($user2->id, 0, 'conversations', true, true, 0, 0);
1178         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1179         $this->assertCount(2, $messages['messages']);
1181         // Conversations from user3 to user2.
1182         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
1183         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1184         $this->assertCount(1, $messages['messages']);
1186         // Delete the message.
1187         $message = array_shift($messages['messages']);
1188         \core_message\api::delete_message($user2->id, $message['id']);
1190         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
1191         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1192         $this->assertCount(0, $messages['messages']);
1194         $this->setUser($user3);
1195         // Get read notifications received by user3.
1196         $messages = core_message_external::get_messages($user3->id, 0, 'notifications', true, true, 0, 0);
1197         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1198         $this->assertCount(0, $messages['messages']);
1200         // Now, create some notifications...
1201         // We are creating fake notifications but based on real ones.
1203         // This one comes from a disabled plugin's provider and therefore is not sent.
1204         $eventdata = new \core\message\message();
1205         $eventdata->courseid          = $course->id;
1206         $eventdata->notification      = 1;
1207         $eventdata->modulename        = 'moodle';
1208         $eventdata->component         = 'enrol_paypal';
1209         $eventdata->name              = 'paypal_enrolment';
1210         $eventdata->userfrom          = get_admin();
1211         $eventdata->userto            = $user1;
1212         $eventdata->subject           = "Moodle: PayPal payment";
1213         $eventdata->fullmessage       = "Your PayPal payment is pending.";
1214         $eventdata->fullmessageformat = FORMAT_PLAIN;
1215         $eventdata->fullmessagehtml   = '';
1216         $eventdata->smallmessage      = '';
1217         message_send($eventdata);
1218         $this->assertDebuggingCalled('Attempt to send msg from a provider enrol_paypal/paypal_enrolment '.
1219             'that is inactive or not allowed for the user id='.$user1->id);
1221         // This one omits notification = 1.
1222         $message = new \core\message\message();
1223         $message->courseid          = $course->id;
1224         $message->component         = 'enrol_manual';
1225         $message->name              = 'expiry_notification';
1226         $message->userfrom          = $user2;
1227         $message->userto            = $user1;
1228         $message->subject           = 'Test: This is not a notification but otherwise is valid';
1229         $message->fullmessage       = 'Test: Full message';
1230         $message->fullmessageformat = FORMAT_MARKDOWN;
1231         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
1232         $message->smallmessage      = $message->subject;
1233         $message->contexturlname    = $course->fullname;
1234         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
1235         message_send($message);
1237         $message = new \core\message\message();
1238         $message->courseid          = $course->id;
1239         $message->notification      = 1;
1240         $message->component         = 'enrol_manual';
1241         $message->name              = 'expiry_notification';
1242         $message->userfrom          = $user2;
1243         $message->userto            = $user1;
1244         $message->subject           = 'Enrolment expired';
1245         $message->fullmessage       = 'Enrolment expired blah blah blah';
1246         $message->fullmessageformat = FORMAT_MARKDOWN;
1247         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
1248         $message->smallmessage      = $message->subject;
1249         $message->contexturlname    = $course->fullname;
1250         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
1251         message_send($message);
1253         $userfrom = core_user::get_noreply_user();
1254         $userfrom->maildisplay = true;
1255         $eventdata = new \core\message\message();
1256         $eventdata->courseid          = $course->id;
1257         $eventdata->component         = 'moodle';
1258         $eventdata->name              = 'badgecreatornotice';
1259         $eventdata->userfrom          = $userfrom;
1260         $eventdata->userto            = $user1;
1261         $eventdata->notification      = 1;
1262         $eventdata->subject           = 'New badge';
1263         $eventdata->fullmessage       = format_text_email($eventdata->subject, FORMAT_HTML);
1264         $eventdata->fullmessageformat = FORMAT_PLAIN;
1265         $eventdata->fullmessagehtml   = $eventdata->subject;
1266         $eventdata->smallmessage      = $eventdata->subject;
1267         message_send($eventdata);
1269         $eventdata = new \core\message\message();
1270         $eventdata->courseid         = $course->id;
1271         $eventdata->name             = 'submission';
1272         $eventdata->component        = 'mod_feedback';
1273         $eventdata->userfrom         = $user1;
1274         $eventdata->userto           = $user2;
1275         $eventdata->subject          = 'Feedback submitted';
1276         $eventdata->fullmessage      = 'Feedback submitted from an user';
1277         $eventdata->fullmessageformat = FORMAT_PLAIN;
1278         $eventdata->fullmessagehtml  = '<strong>Feedback submitted</strong>';
1279         $eventdata->smallmessage     = '';
1280         message_send($eventdata);
1282         $this->setUser($user1);
1283         // Get read notifications from any user to user1.
1284         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 0);
1285         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1286         $this->assertCount(3, $messages['messages']);
1288         // Get one read notifications from any user to user1.
1289         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 1);
1290         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1291         $this->assertCount(1, $messages['messages']);
1293         // Get unread notifications from any user to user1.
1294         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', false, true, 0, 0);
1295         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1296         $this->assertCount(0, $messages['messages']);
1298         // Get read both type of messages from any user to user1.
1299         $messages = core_message_external::get_messages($user1->id, 0, 'both', true, true, 0, 0);
1300         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1301         $this->assertCount(4, $messages['messages']);
1303         // Get read notifications from no-reply-user to user1.
1304         $messages = core_message_external::get_messages($user1->id, $userfrom->id, 'notifications', true, true, 0, 0);
1305         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1306         $this->assertCount(1, $messages['messages']);
1308         // Get notifications send by user1 to any user.
1309         $messages = core_message_external::get_messages(0, $user1->id, 'notifications', true, true, 0, 0);
1310         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1311         $this->assertCount(1, $messages['messages']);
1313         // Test warnings.
1314         $CFG->messaging = 0;
1316         $messages = core_message_external::get_messages(0, $user1->id, 'both', true, true, 0, 0);
1317         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1318         $this->assertCount(1, $messages['warnings']);
1320         // Test exceptions.
1322         // Messaging disabled.
1323         try {
1324             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1325             $this->fail('Exception expected due messaging disabled.');
1326         } catch (moodle_exception $e) {
1327             $this->assertEquals('disabled', $e->errorcode);
1328         }
1330         $CFG->messaging = 1;
1332         // Invalid users.
1333         try {
1334             $messages = core_message_external::get_messages(0, 0, 'conversations', true, true, 0, 0);
1335             $this->fail('Exception expected due invalid users.');
1336         } catch (moodle_exception $e) {
1337             $this->assertEquals('accessdenied', $e->errorcode);
1338         }
1340         // Invalid user ids.
1341         try {
1342             $messages = core_message_external::get_messages(2500, 0, 'conversations', true, true, 0, 0);
1343             $this->fail('Exception expected due invalid users.');
1344         } catch (moodle_exception $e) {
1345             $this->assertEquals('invaliduser', $e->errorcode);
1346         }
1348         // Invalid users (permissions).
1349         $this->setUser($user2);
1350         try {
1351             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1352             $this->fail('Exception expected due invalid user.');
1353         } catch (moodle_exception $e) {
1354             $this->assertEquals('accessdenied', $e->errorcode);
1355         }
1357     }
1359     /**
1360      * Test get_messages where we want all messages from a user, sent to any user.
1361      */
1362     public function test_get_messages_useridto_all() {
1363         $this->resetAfterTest(true);
1365         $user1 = self::getDataGenerator()->create_user();
1366         $user2 = self::getDataGenerator()->create_user();
1367         $user3 = self::getDataGenerator()->create_user();
1369         $this->setUser($user1);
1371         // Send a message from user 1 to two other users.
1372         $this->send_message($user1, $user2, 'some random text 1', 0, 1);
1373         $this->send_message($user1, $user3, 'some random text 2', 0, 2);
1375         // Get messages sent from user 1.
1376         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', false, false, 0, 0);
1377         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1379         // Confirm the data is correct.
1380         $messages = $messages['messages'];
1381         $this->assertCount(2, $messages);
1383         $message1 = array_shift($messages);
1384         $message2 = array_shift($messages);
1386         $this->assertEquals($user1->id, $message1['useridfrom']);
1387         $this->assertEquals($user2->id, $message1['useridto']);
1389         $this->assertEquals($user1->id, $message2['useridfrom']);
1390         $this->assertEquals($user3->id, $message2['useridto']);
1391     }
1393     /**
1394      * Test get_messages where we want all messages to a user, sent by any user.
1395      */
1396     public function test_get_messages_useridfrom_all() {
1397         $this->resetAfterTest();
1399         $user1 = self::getDataGenerator()->create_user();
1400         $user2 = self::getDataGenerator()->create_user();
1401         $user3 = self::getDataGenerator()->create_user();
1403         $this->setUser($user1);
1405         // Send a message to user 1 from two other users.
1406         $this->send_message($user2, $user1, 'some random text 1', 0, 1);
1407         $this->send_message($user3, $user1, 'some random text 2', 0, 2);
1409         // Get messages sent to user 1.
1410         $messages = core_message_external::get_messages($user1->id, 0, 'conversations', false, false, 0, 0);
1411         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1413         // Confirm the data is correct.
1414         $messages = $messages['messages'];
1415         $this->assertCount(2, $messages);
1417         $message1 = array_shift($messages);
1418         $message2 = array_shift($messages);
1420         $this->assertEquals($user2->id, $message1['useridfrom']);
1421         $this->assertEquals($user1->id, $message1['useridto']);
1423         $this->assertEquals($user3->id, $message2['useridfrom']);
1424         $this->assertEquals($user1->id, $message2['useridto']);
1425     }
1427     /**
1428      * Test get_blocked_users.
1429      */
1430     public function test_get_blocked_users() {
1431         $this->resetAfterTest(true);
1433         $user1 = self::getDataGenerator()->create_user();
1434         $userstranger = self::getDataGenerator()->create_user();
1435         $useroffline1 = self::getDataGenerator()->create_user();
1436         $useroffline2 = self::getDataGenerator()->create_user();
1437         $userblocked = self::getDataGenerator()->create_user();
1439         // Login as user1.
1440         $this->setUser($user1);
1442         \core_message\api::add_contact($user1->id, $useroffline1->id);
1443         \core_message\api::add_contact($user1->id, $useroffline2->id);
1445         // The userstranger sends a couple of messages to user1.
1446         $this->send_message($userstranger, $user1, 'Hello there!');
1447         $this->send_message($userstranger, $user1, 'How you goin?');
1449         // The userblocked sends a message to user1.
1450         // Note that this user is not blocked at this point.
1451         $this->send_message($userblocked, $user1, 'Here, have some spam.');
1453         // Retrieve the list of blocked users.
1454         $this->setUser($user1);
1455         $blockedusers = core_message_external::get_blocked_users($user1->id);
1456         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1457         $this->assertCount(0, $blockedusers['users']);
1459         // Block the $userblocked and retrieve again the list.
1460         core_message_external::block_contacts(array($userblocked->id));
1461         $this->assertDebuggingCalled();
1462         $blockedusers = core_message_external::get_blocked_users($user1->id);
1463         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1464         $this->assertCount(1, $blockedusers['users']);
1466         // Remove the $userblocked and check that the list now is empty.
1467         delete_user($userblocked);
1468         $blockedusers = core_message_external::get_blocked_users($user1->id);
1469         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1470         $this->assertCount(0, $blockedusers['users']);
1471     }
1473     /**
1474      * Test mark_message_read.
1475      */
1476     public function test_mark_message_read() {
1477         $this->resetAfterTest(true);
1479         $user1 = self::getDataGenerator()->create_user();
1480         $user2 = self::getDataGenerator()->create_user();
1481         $user3 = self::getDataGenerator()->create_user();
1483         // Login as user1.
1484         $this->setUser($user1);
1485         \core_message\api::add_contact($user1->id, $user2->id);
1486         \core_message\api::add_contact($user1->id, $user3->id);
1488         // The user2 sends a couple of messages to user1.
1489         $this->send_message($user2, $user1, 'Hello there!');
1490         $this->send_message($user2, $user1, 'How you goin?');
1491         $this->send_message($user3, $user1, 'How you goin?');
1492         $this->send_message($user3, $user2, 'How you goin?');
1494         // Retrieve all messages sent by user2 (they are currently unread).
1495         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
1497         $messageids = array();
1498         foreach ($lastmessages as $m) {
1499             $messageid = core_message_external::mark_message_read($m->id, time());
1500             $messageids[] = external_api::clean_returnvalue(core_message_external::mark_message_read_returns(), $messageid);
1501         }
1503         // Retrieve all messages sent (they are currently read).
1504         $lastmessages = message_get_messages($user1->id, $user2->id, 0, true);
1505         $this->assertCount(2, $lastmessages);
1506         $this->assertArrayHasKey($messageids[0]['messageid'], $lastmessages);
1507         $this->assertArrayHasKey($messageids[1]['messageid'], $lastmessages);
1509         // Retrieve all messages sent by any user (that are currently unread).
1510         $lastmessages = message_get_messages($user1->id, 0, 0, false);
1511         $this->assertCount(1, $lastmessages);
1513         // Invalid message ids.
1514         try {
1515             $messageid = core_message_external::mark_message_read(1337, time());
1516             $this->fail('Exception expected due invalid messageid.');
1517         } catch (dml_missing_record_exception $e) {
1518             $this->assertEquals('invalidrecordunknown', $e->errorcode);
1519         }
1521         // A message to a different user.
1522         $lastmessages = message_get_messages($user2->id, $user3->id, 0, false);
1523         $messageid = array_pop($lastmessages)->id;
1524         try {
1525             $messageid = core_message_external::mark_message_read($messageid, time());
1526             $this->fail('Exception expected due invalid messageid.');
1527         } catch (invalid_parameter_exception $e) {
1528             $this->assertEquals('invalidparameter', $e->errorcode);
1529         }
1530     }
1532     /**
1533      * Test mark_notification_read.
1534      */
1535     public function test_mark_notification_read() {
1536         $this->resetAfterTest(true);
1538         $user1 = self::getDataGenerator()->create_user();
1539         $user2 = self::getDataGenerator()->create_user();
1540         $user3 = self::getDataGenerator()->create_user();
1542         // Login as user1.
1543         $this->setUser($user1);
1544         \core_message\api::add_contact($user1->id, $user2->id);
1545         \core_message\api::add_contact($user1->id, $user3->id);
1547         // The user2 sends a couple of notifications to user1.
1548         $this->send_message($user2, $user1, 'Hello there!', 1);
1549         $this->send_message($user2, $user1, 'How you goin?', 1);
1550         $this->send_message($user3, $user1, 'How you goin?', 1);
1551         $this->send_message($user3, $user2, 'How you goin?', 1);
1553         // Retrieve all notifications sent by user2 (they are currently unread).
1554         $lastnotifications = message_get_messages($user1->id, $user2->id, 1, false);
1556         $notificationids = array();
1557         foreach ($lastnotifications as $n) {
1558             $notificationid = core_message_external::mark_notification_read($n->id, time());
1559             $notificationids[] = external_api::clean_returnvalue(core_message_external::mark_notification_read_returns(),
1560                 $notificationid);
1561         }
1563         // Retrieve all notifications sent (they are currently read).
1564         $lastnotifications = message_get_messages($user1->id, $user2->id, 1, true);
1565         $this->assertCount(2, $lastnotifications);
1566         $this->assertArrayHasKey($notificationids[1]['notificationid'], $lastnotifications);
1567         $this->assertArrayHasKey($notificationids[0]['notificationid'], $lastnotifications);
1569         // Retrieve all notifications sent by any user (that are currently unread).
1570         $lastnotifications = message_get_messages($user1->id, 0, 1, false);
1571         $this->assertCount(1, $lastnotifications);
1573         // Invalid notification ids.
1574         try {
1575             $notificationid = core_message_external::mark_notification_read(1337, time());
1576             $this->fail('Exception expected due invalid notificationid.');
1577         } catch (dml_missing_record_exception $e) {
1578             $this->assertEquals('invalidrecord', $e->errorcode);
1579         }
1581         // A notification to a different user.
1582         $lastnotifications = message_get_messages($user2->id, $user3->id, 1, false);
1583         $notificationid = array_pop($lastnotifications)->id;
1584         try {
1585             $notificationid = core_message_external::mark_notification_read($notificationid, time());
1586             $this->fail('Exception expected due invalid notificationid.');
1587         } catch (invalid_parameter_exception $e) {
1588             $this->assertEquals('invalidparameter', $e->errorcode);
1589         }
1590     }
1592     /**
1593      * Test delete_message.
1594      */
1595     public function test_delete_message() {
1596         global $DB;
1597         $this->resetAfterTest(true);
1599         $user1 = self::getDataGenerator()->create_user();
1600         $user2 = self::getDataGenerator()->create_user();
1601         $user3 = self::getDataGenerator()->create_user();
1602         $user4 = self::getDataGenerator()->create_user();
1604         // Login as user1.
1605         $this->setUser($user1);
1606         \core_message\api::add_contact($user1->id, $user2->id);
1607         \core_message\api::add_contact($user1->id, $user3->id);
1609         // User user1 does not interchange messages with user3.
1610         $m1to2 = message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
1611         $m2to3 = message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
1612         $m3to2 = message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
1613         $m3to4 = message_post_message($user3, $user4, 'some random text 4', FORMAT_MOODLE);
1615         // Retrieve all messages sent by user2 (they are currently unread).
1616         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
1618         // Delete a message not read, as a user from.
1619         $result = core_message_external::delete_message($m1to2, $user1->id, false);
1620         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1621         $this->assertTrue($result['status']);
1622         $this->assertCount(0, $result['warnings']);
1623         $mua = $DB->get_record('message_user_actions', array('messageid' => $m1to2, 'userid' => $user1->id));
1624         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua->action);
1626         // Try to delete the same message again.
1627         $result = core_message_external::delete_message($m1to2, $user1->id, false);
1628         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1629         $this->assertFalse($result['status']);
1631         // Try to delete a message that does not belong to me.
1632         try {
1633             $messageid = core_message_external::delete_message($m2to3, $user3->id, false);
1634             $this->fail('Exception expected due invalid messageid.');
1635         } catch (moodle_exception $e) {
1636             $this->assertEquals('You do not have permission to delete this message', $e->errorcode);
1637         }
1639         $this->setUser($user3);
1640         // Delete a message not read, as a user to.
1641         $result = core_message_external::delete_message($m2to3, $user3->id, false);
1642         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1643         $this->assertTrue($result['status']);
1644         $this->assertCount(0, $result['warnings']);
1645         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m2to3, 'userid' => $user3->id,
1646             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1648         // Delete a message read.
1649         $message = $DB->get_record('messages', ['id' => $m3to2]);
1650         \core_message\api::mark_message_as_read($user3->id, $message, time());
1651         $result = core_message_external::delete_message($m3to2, $user3->id);
1652         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1653         $this->assertTrue($result['status']);
1654         $this->assertCount(0, $result['warnings']);
1655         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to2, 'userid' => $user3->id,
1656             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1658         // Invalid message ids.
1659         try {
1660             $result = core_message_external::delete_message(-1, $user1->id);
1661             $this->fail('Exception expected due invalid messageid.');
1662         } catch (dml_missing_record_exception $e) {
1663             $this->assertEquals('invalidrecordunknown', $e->errorcode);
1664         }
1666         // Invalid user.
1667         try {
1668             $result = core_message_external::delete_message($m1to2, -1, false);
1669             $this->fail('Exception expected due invalid user.');
1670         } catch (moodle_exception $e) {
1671             $this->assertEquals('invaliduser', $e->errorcode);
1672         }
1674         // Not active user.
1675         delete_user($user2);
1676         try {
1677             $result = core_message_external::delete_message($m1to2, $user2->id, false);
1678             $this->fail('Exception expected due invalid user.');
1679         } catch (moodle_exception $e) {
1680             $this->assertEquals('userdeleted', $e->errorcode);
1681         }
1683         // Now, as an admin, try to delete any message.
1684         $this->setAdminUser();
1685         $result = core_message_external::delete_message($m3to4, $user4->id, false);
1686         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1687         $this->assertTrue($result['status']);
1688         $this->assertCount(0, $result['warnings']);
1689         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to4, 'userid' => $user4->id,
1690             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1692     }
1694     public function test_mark_all_notifications_as_read_invalid_user_exception() {
1695         $this->resetAfterTest(true);
1697         $this->expectException('moodle_exception');
1698         core_message_external::mark_all_notifications_as_read(-2132131, 0);
1699     }
1701     public function test_mark_all_notifications_as_read_access_denied_exception() {
1702         $this->resetAfterTest(true);
1704         $sender = $this->getDataGenerator()->create_user();
1705         $user = $this->getDataGenerator()->create_user();
1707         $this->setUser($user);
1708         $this->expectException('moodle_exception');
1709         core_message_external::mark_all_notifications_as_read($sender->id, 0);
1710     }
1712     public function test_mark_all_notifications_as_read_missing_from_user_exception() {
1713         $this->resetAfterTest(true);
1715         $sender = $this->getDataGenerator()->create_user();
1717         $this->setUser($sender);
1718         $this->expectException('moodle_exception');
1719         core_message_external::mark_all_notifications_as_read($sender->id, 99999);
1720     }
1722     public function test_mark_all_notifications_as_read() {
1723         global $DB;
1725         $this->resetAfterTest(true);
1727         $sender1 = $this->getDataGenerator()->create_user();
1728         $sender2 = $this->getDataGenerator()->create_user();
1729         $sender3 = $this->getDataGenerator()->create_user();
1730         $recipient = $this->getDataGenerator()->create_user();
1732         $this->setUser($recipient);
1734         $this->send_message($sender1, $recipient, 'Notification', 1);
1735         $this->send_message($sender1, $recipient, 'Notification', 1);
1736         $this->send_message($sender2, $recipient, 'Notification', 1);
1737         $this->send_message($sender2, $recipient, 'Notification', 1);
1738         $this->send_message($sender3, $recipient, 'Notification', 1);
1739         $this->send_message($sender3, $recipient, 'Notification', 1);
1741         core_message_external::mark_all_notifications_as_read($recipient->id, $sender1->id);
1742         $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1743         $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
1745         $this->assertCount(2, $readnotifications);
1746         $this->assertCount(4, $unreadnotifications);
1748         core_message_external::mark_all_notifications_as_read($recipient->id, 0);
1749         $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1750         $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
1752         $this->assertCount(6, $readnotifications);
1753         $this->assertCount(0, $unreadnotifications);
1754     }
1756     /**
1757      * Test get_user_notification_preferences
1758      */
1759     public function test_get_user_notification_preferences() {
1760         $this->resetAfterTest(true);
1762         $user = self::getDataGenerator()->create_user();
1763         $this->setUser($user);
1765         // Set a couple of preferences to test.
1766         set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
1767         set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
1769         $prefs = core_message_external::get_user_notification_preferences();
1770         $prefs = external_api::clean_returnvalue(core_message_external::get_user_notification_preferences_returns(), $prefs);
1771         // Check processors.
1772         $this->assertGreaterThanOrEqual(2, count($prefs['preferences']['processors']));
1773         $this->assertEquals($user->id, $prefs['preferences']['userid']);
1775         // Check components.
1776         $this->assertGreaterThanOrEqual(8, count($prefs['preferences']['components']));
1778         // Check some preferences that we previously set.
1779         $found = 0;
1780         foreach ($prefs['preferences']['components'] as $component) {
1781             foreach ($component['notifications'] as $prefdata) {
1782                 if ($prefdata['preferencekey'] != 'message_provider_mod_assign_assign_notification') {
1783                     continue;
1784                 }
1785                 foreach ($prefdata['processors'] as $processor) {
1786                     if ($processor['name'] == 'popup') {
1787                         $this->assertTrue($processor['loggedin']['checked']);
1788                         $found++;
1789                     } else if ($processor['name'] == 'email') {
1790                         $this->assertTrue($processor['loggedoff']['checked']);
1791                         $found++;
1792                     }
1793                 }
1794             }
1795         }
1796         $this->assertEquals(2, $found);
1797     }
1799     /**
1800      * Test get_user_notification_preferences permissions
1801      */
1802     public function test_get_user_notification_preferences_permissions() {
1803         $this->resetAfterTest(true);
1805         $user = self::getDataGenerator()->create_user();
1806         $otheruser = self::getDataGenerator()->create_user();
1807         $this->setUser($user);
1809         $this->expectException('moodle_exception');
1810         $prefs = core_message_external::get_user_notification_preferences($otheruser->id);
1811     }
1813     /**
1814      * Tests searching users in a course.
1815      */
1816     public function test_messagearea_search_users_in_course() {
1817         $this->resetAfterTest(true);
1819         // Create some users.
1820         $user1 = new stdClass();
1821         $user1->firstname = 'User';
1822         $user1->lastname = 'One';
1823         $user1 = self::getDataGenerator()->create_user($user1);
1825         // The person doing the search.
1826         $this->setUser($user1);
1828         // Set the second user's status to online by setting their last access to now.
1829         $user2 = new stdClass();
1830         $user2->firstname = 'User';
1831         $user2->lastname = 'Two';
1832         $user2->lastaccess = time();
1833         $user2 = self::getDataGenerator()->create_user($user2);
1835         // Block the second user.
1836         \core_message\api::block_user($user1->id, $user2->id);
1838         $user3 = new stdClass();
1839         $user3->firstname = 'User';
1840         $user3->lastname = 'Three';
1841         $user3 = self::getDataGenerator()->create_user($user3);
1843         // Create a course.
1844         $course1 = new stdClass();
1845         $course1->fullname = 'Course';
1846         $course1->shortname = 'One';
1847         $course1 = $this->getDataGenerator()->create_course();
1849         // Enrol the user we are doing the search for and one user in the course.
1850         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1851         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1853         // Perform a search.
1854         $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
1856         // We need to execute the return values cleaning process to simulate the web service.
1857         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
1858             $result);
1860         // Check that we only retrieved a user that was enrolled, and that the user performing the search was not returned.
1861         $users = $result['contacts'];
1862         $this->assertCount(1, $users);
1864         $user = $users[0];
1865         $this->assertEquals($user2->id, $user['userid']);
1866         $this->assertEquals(fullname($user2), $user['fullname']);
1867         $this->assertFalse($user['ismessaging']);
1868         $this->assertFalse($user['sentfromcurrentuser']);
1869         $this->assertNull($user['lastmessage']);
1870         $this->assertNull($user['messageid']);
1871         $this->assertNull($user['isonline']);
1872         $this->assertFalse($user['isread']);
1873         $this->assertTrue($user['isblocked']);
1874         $this->assertNull($user['unreadcount']);
1875     }
1877     /**
1878      * Tests searching users in course as another user.
1879      */
1880     public function test_messagearea_search_users_in_course_as_other_user() {
1881         $this->resetAfterTest(true);
1883         // The person doing the search for another user.
1884         $this->setAdminUser();
1886         // Create some users.
1887         $user1 = new stdClass();
1888         $user1->firstname = 'User';
1889         $user1->lastname = 'One';
1890         $user1 = self::getDataGenerator()->create_user($user1);
1892         $user2 = new stdClass();
1893         $user2->firstname = 'User';
1894         $user2->lastname = 'Two';
1895         $user2 = self::getDataGenerator()->create_user($user2);
1897         $user3 = new stdClass();
1898         $user3->firstname = 'User';
1899         $user3->lastname = 'Three';
1900         $user3 = self::getDataGenerator()->create_user($user3);
1902         // Create a course.
1903         $course1 = new stdClass();
1904         $course1->fullname = 'Course';
1905         $course1->shortname = 'One';
1906         $course1 = $this->getDataGenerator()->create_course();
1908         // Enrol the user we are doing the search for and one user in the course.
1909         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1910         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1912         // Perform a search.
1913         $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
1915         // We need to execute the return values cleaning process to simulate the web service server.
1916         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
1917             $result);
1919         // Check that we got the user enrolled, and that the user we are performing the search on behalf of was not returned.
1920         $users = $result['contacts'];
1921         $this->assertCount(1, $users);
1923         $user = $users[0];
1924         $this->assertEquals($user2->id, $user['userid']);
1925         $this->assertEquals(fullname($user2), $user['fullname']);
1926         $this->assertFalse($user['ismessaging']);
1927         $this->assertFalse($user['sentfromcurrentuser']);
1928         $this->assertNull($user['lastmessage']);
1929         $this->assertNull($user['messageid']);
1930         $this->assertFalse($user['isonline']);
1931         $this->assertFalse($user['isread']);
1932         $this->assertFalse($user['isblocked']);
1933         $this->assertNull($user['unreadcount']);
1934     }
1936     /**
1937      * Tests searching users in course as another user without the proper capabilities.
1938      */
1939     public function test_messagearea_search_users_in_course_as_other_user_without_cap() {
1940         $this->resetAfterTest(true);
1942         // Create some users.
1943         $user1 = self::getDataGenerator()->create_user();
1944         $user2 = self::getDataGenerator()->create_user();
1946         // The person doing the search for another user.
1947         $this->setUser($user1);
1949         // Create a course.
1950         $course = $this->getDataGenerator()->create_course();
1952         // Ensure an exception is thrown.
1953         $this->expectException('moodle_exception');
1954         core_message_external::data_for_messagearea_search_users_in_course($user2->id, $course->id, 'User');
1955     }
1957     /**
1958      * Tests searching users in course with messaging disabled.
1959      */
1960     public function test_messagearea_search_users_in_course_messaging_disabled() {
1961         global $CFG;
1963         $this->resetAfterTest(true);
1965         // Create some skeleton data just so we can call the WS..
1966         $user = self::getDataGenerator()->create_user();
1967         $course = $this->getDataGenerator()->create_course();
1969         // The person doing the search for another user.
1970         $this->setUser($user);
1972         // Disable messaging.
1973         $CFG->messaging = 0;
1975         // Ensure an exception is thrown.
1976         $this->expectException('moodle_exception');
1977         core_message_external::data_for_messagearea_search_users_in_course($user->id, $course->id, 'User');
1978     }
1980     /**
1981      * Tests searching users.
1982      */
1983     public function test_messagearea_search_users() {
1984         $this->resetAfterTest(true);
1986         // Create some users.
1987         $user1 = new stdClass();
1988         $user1->firstname = 'User';
1989         $user1->lastname = 'One';
1990         $user1 = self::getDataGenerator()->create_user($user1);
1992         // Set as the user performing the search.
1993         $this->setUser($user1);
1995         $user2 = new stdClass();
1996         $user2->firstname = 'User search';
1997         $user2->lastname = 'Two';
1998         $user2 = self::getDataGenerator()->create_user($user2);
2000         $user3 = new stdClass();
2001         $user3->firstname = 'User search';
2002         $user3->lastname = 'Three';
2003         $user3 = self::getDataGenerator()->create_user($user3);
2005         $user4 = new stdClass();
2006         $user4->firstname = 'User';
2007         $user4->lastname = 'Four';
2008         $user4 = self::getDataGenerator()->create_user($user4);
2010         $user5 = new stdClass();
2011         $user5->firstname = 'User search';
2012         $user5->lastname = 'Five';
2013         $user5 = self::getDataGenerator()->create_user($user5);
2015         $user6 = new stdClass();
2016         $user6->firstname = 'User';
2017         $user6->lastname = 'Six';
2018         $user6 = self::getDataGenerator()->create_user($user6);
2020         // Create some courses.
2021         $course1 = new stdClass();
2022         $course1->fullname = 'Course search';
2023         $course1->shortname = 'One';
2024         $course1 = $this->getDataGenerator()->create_course($course1);
2026         $course2 = new stdClass();
2027         $course2->fullname = 'Course';
2028         $course2->shortname = 'Two';
2029         $course2 = $this->getDataGenerator()->create_course($course2);
2031         $course3 = new stdClass();
2032         $course3->fullname = 'Course';
2033         $course3->shortname = 'Three search';
2034         $course3 = $this->getDataGenerator()->create_course($course3);
2036         $course4 = new stdClass();
2037         $course4->fullname = 'Course Four';
2038         $course4->shortname = 'CF100';
2039         $course4 = $this->getDataGenerator()->create_course($course4);
2041         $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'student');
2042         $this->getDataGenerator()->enrol_user($user1->id, $course2->id, 'student');
2043         $this->getDataGenerator()->enrol_user($user1->id, $course3->id, 'student');
2045         // Add some users as contacts.
2046         \core_message\api::add_contact($user1->id, $user2->id);
2047         \core_message\api::add_contact($user1->id, $user3->id);
2048         \core_message\api::add_contact($user1->id, $user4->id);
2050         // Perform a search.
2051         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
2053         // We need to execute the return values cleaning process to simulate the web service server.
2054         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
2055             $result);
2057         // Confirm that we returns contacts, courses and non-contacts.
2058         $contacts = $result['contacts'];
2059         $courses = $result['courses'];
2060         $noncontacts = $result['noncontacts'];
2062         // Check that we retrieved the correct contacts.
2063         $this->assertCount(2, $contacts);
2064         $this->assertEquals($user3->id, $contacts[0]['userid']);
2065         $this->assertEquals($user2->id, $contacts[1]['userid']);
2067         // Check that we retrieved the correct courses.
2068         $this->assertCount(2, $courses);
2069         $this->assertEquals($course3->id, $courses[0]['id']);
2070         $this->assertEquals($course1->id, $courses[1]['id']);
2072         // Check that we retrieved the correct non-contacts.
2073         $this->assertCount(1, $noncontacts);
2074         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
2075     }
2077     /**
2078      * Tests searching users as another user.
2079      */
2080     public function test_messagearea_search_users_as_other_user() {
2081         $this->resetAfterTest(true);
2083         // The person doing the search.
2084         $this->setAdminUser();
2086         // Create some users.
2087         $user1 = new stdClass();
2088         $user1->firstname = 'User';
2089         $user1->lastname = 'One';
2090         $user1 = self::getDataGenerator()->create_user($user1);
2092         $user2 = new stdClass();
2093         $user2->firstname = 'User search';
2094         $user2->lastname = 'Two';
2095         $user2 = self::getDataGenerator()->create_user($user2);
2097         $user3 = new stdClass();
2098         $user3->firstname = 'User search';
2099         $user3->lastname = 'Three';
2100         $user3 = self::getDataGenerator()->create_user($user3);
2102         $user4 = new stdClass();
2103         $user4->firstname = 'User';
2104         $user4->lastname = 'Four';
2105         $user4 = self::getDataGenerator()->create_user($user4);
2107         $user5 = new stdClass();
2108         $user5->firstname = 'User search';
2109         $user5->lastname = 'Five';
2110         $user5 = self::getDataGenerator()->create_user($user5);
2112         $user6 = new stdClass();
2113         $user6->firstname = 'User';
2114         $user6->lastname = 'Six';
2115         $user6 = self::getDataGenerator()->create_user($user6);
2117         // Create some courses.
2118         $course1 = new stdClass();
2119         $course1->fullname = 'Course search';
2120         $course1->shortname = 'One';
2121         $course1 = $this->getDataGenerator()->create_course($course1);
2123         $course2 = new stdClass();
2124         $course2->fullname = 'Course';
2125         $course2->shortname = 'Two';
2126         $course2 = $this->getDataGenerator()->create_course($course2);
2128         $course3 = new stdClass();
2129         $course3->fullname = 'Course';
2130         $course3->shortname = 'Three search';
2131         $course3 = $this->getDataGenerator()->create_course($course3);
2133         // Add some users as contacts.
2134         \core_message\api::add_contact($user1->id, $user2->id);
2135         \core_message\api::add_contact($user1->id, $user3->id);
2136         \core_message\api::add_contact($user1->id, $user4->id);
2138         // Perform a search.
2139         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
2141         // We need to execute the return values cleaning process to simulate the web service server.
2142         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
2143             $result);
2145         // Confirm that we returns contacts, courses and non-contacts.
2146         $contacts = $result['contacts'];
2147         $courses = $result['courses'];
2148         $noncontacts = $result['noncontacts'];
2150         // Check that we retrieved the correct contacts.
2151         $this->assertCount(2, $contacts);
2152         $this->assertEquals($user3->id, $contacts[0]['userid']);
2153         $this->assertEquals($user2->id, $contacts[1]['userid']);
2155         // Check that we retrieved the correct courses.
2156         $this->assertCount(0, $courses);
2158         // Check that we retrieved the correct non-contacts.
2159         $this->assertCount(1, $noncontacts);
2160         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
2161     }
2163     /**
2164      * Tests searching users as another user without the proper capabilities.
2165      */
2166     public function test_messagearea_search_users_as_other_user_without_cap() {
2167         $this->resetAfterTest(true);
2169         // Create some users.
2170         $user1 = self::getDataGenerator()->create_user();
2171         $user2 = self::getDataGenerator()->create_user();
2173         // The person doing the search for another user.
2174         $this->setUser($user1);
2176         // Ensure an exception is thrown.
2177         $this->expectException('moodle_exception');
2178         core_message_external::data_for_messagearea_search_users($user2->id, 'User');
2179     }
2181     /**
2182      * Tests searching users with messaging disabled.
2183      */
2184     public function test_messagearea_search_users_messaging_disabled() {
2185         global $CFG;
2187         $this->resetAfterTest(true);
2189         // Create some skeleton data just so we can call the WS.
2190         $user = self::getDataGenerator()->create_user();
2192         // The person doing the search.
2193         $this->setUser($user);
2195         // Disable messaging.
2196         $CFG->messaging = 0;
2198         // Ensure an exception is thrown.
2199         $this->expectException('moodle_exception');
2200         core_message_external::data_for_messagearea_search_users($user->id, 'User');
2201     }
2203     /**
2204      * Tests searching messages.
2205      */
2206     public function test_messagearea_search_messages() {
2207         $this->resetAfterTest(true);
2209         // Create some users.
2210         $user1 = self::getDataGenerator()->create_user();
2211         $user2 = self::getDataGenerator()->create_user();
2213         // The person doing the search.
2214         $this->setUser($user1);
2216         // Send some messages back and forth.
2217         $time = time();
2218         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2219         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2220         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2221         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2223         // Perform a search.
2224         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2226         // We need to execute the return values cleaning process to simulate the web service server.
2227         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
2228             $result);
2230         // Confirm the data is correct.
2231         $messages = $result['contacts'];
2232         $this->assertCount(2, $messages);
2234         $message1 = $messages[0];
2235         $message2 = $messages[1];
2237         $this->assertEquals($user2->id, $message1['userid']);
2238         $this->assertEquals(fullname($user2), $message1['fullname']);
2239         $this->assertTrue($message1['ismessaging']);
2240         $this->assertFalse($message1['sentfromcurrentuser']);
2241         $this->assertEquals('Word.', $message1['lastmessage']);
2242         $this->assertNotEmpty($message1['messageid']);
2243         $this->assertNull($message1['isonline']);
2244         $this->assertFalse($message1['isread']);
2245         $this->assertFalse($message1['isblocked']);
2246         $this->assertNull($message1['unreadcount']);
2248         $this->assertEquals($user2->id, $message2['userid']);
2249         $this->assertEquals(fullname($user2), $message2['fullname']);
2250         $this->assertTrue($message2['ismessaging']);
2251         $this->assertTrue($message2['sentfromcurrentuser']);
2252         $this->assertEquals('Yo!', $message2['lastmessage']);
2253         $this->assertNotEmpty($message2['messageid']);
2254         $this->assertNull($message2['isonline']);
2255         $this->assertTrue($message2['isread']);
2256         $this->assertFalse($message2['isblocked']);
2257         $this->assertNull($message2['unreadcount']);
2258     }
2260     /**
2261      * Tests searching messages as another user.
2262      */
2263     public function test_messagearea_search_messages_as_other_user() {
2264         $this->resetAfterTest(true);
2266         // The person doing the search.
2267         $this->setAdminUser();
2269         // Create some users.
2270         $user1 = self::getDataGenerator()->create_user();
2271         $user2 = self::getDataGenerator()->create_user();
2273         // Send some messages back and forth.
2274         $time = time();
2275         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2276         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2277         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2278         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2280         // Perform a search.
2281         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2283         // We need to execute the return values cleaning process to simulate the web service server.
2284         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
2285             $result);
2287         // Confirm the data is correct.
2288         $messages = $result['contacts'];
2289         $this->assertCount(2, $messages);
2291         $message1 = $messages[0];
2292         $message2 = $messages[1];
2294         $this->assertEquals($user2->id, $message1['userid']);
2295         $this->assertEquals(fullname($user2), $message1['fullname']);
2296         $this->assertTrue($message1['ismessaging']);
2297         $this->assertFalse($message1['sentfromcurrentuser']);
2298         $this->assertEquals('Word.', $message1['lastmessage']);
2299         $this->assertNotEmpty($message1['messageid']);
2300         $this->assertFalse($message1['isonline']);
2301         $this->assertFalse($message1['isread']);
2302         $this->assertFalse($message1['isblocked']);
2303         $this->assertNull($message1['unreadcount']);
2305         $this->assertEquals($user2->id, $message2['userid']);
2306         $this->assertEquals(fullname($user2), $message2['fullname']);
2307         $this->assertTrue($message2['ismessaging']);
2308         $this->assertTrue($message2['sentfromcurrentuser']);
2309         $this->assertEquals('Yo!', $message2['lastmessage']);
2310         $this->assertNotEmpty($message2['messageid']);
2311         $this->assertFalse($message2['isonline']);
2312         $this->assertTrue($message2['isread']);
2313         $this->assertFalse($message2['isblocked']);
2314         $this->assertNull($message2['unreadcount']);
2315     }
2317     /**
2318      * Tests searching messages as another user without the proper capabilities.
2319      */
2320     public function test_messagearea_search_messages_as_other_user_without_cap() {
2321         $this->resetAfterTest(true);
2323         // Create some users.
2324         $user1 = self::getDataGenerator()->create_user();
2325         $user2 = self::getDataGenerator()->create_user();
2327         // The person doing the search for another user.
2328         $this->setUser($user1);
2330         // Ensure an exception is thrown.
2331         $this->expectException('moodle_exception');
2332         core_message_external::data_for_messagearea_search_messages($user2->id, 'Search');
2333     }
2335     /**
2336      * Tests searching messages with messaging disabled
2337      */
2338     public function test_messagearea_search_messages_messaging_disabled() {
2339         global $CFG;
2341         $this->resetAfterTest(true);
2343         // Create some skeleton data just so we can call the WS.
2344         $user = self::getDataGenerator()->create_user();
2346         // The person doing the search .
2347         $this->setUser($user);
2349         // Disable messaging.
2350         $CFG->messaging = 0;
2352         // Ensure an exception is thrown.
2353         $this->expectException('moodle_exception');
2354         core_message_external::data_for_messagearea_search_messages($user->id, 'Search');
2355     }
2357     /**
2358      * Tests retrieving conversations.
2359      */
2360     public function test_messagearea_conversations() {
2361         $this->resetAfterTest(true);
2363         // Create some users.
2364         $user1 = self::getDataGenerator()->create_user();
2365         $user2 = self::getDataGenerator()->create_user();
2366         $user3 = self::getDataGenerator()->create_user();
2367         $user4 = self::getDataGenerator()->create_user();
2369         // The person retrieving the conversations.
2370         $this->setUser($user1);
2372         // Send some messages back and forth, have some different conversations with different users.
2373         $time = time();
2374         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2375         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2376         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2377         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2379         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
2380         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
2381         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
2382         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
2384         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
2385         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
2386         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
2388         // Retrieve the conversations.
2389         $result = core_message_external::data_for_messagearea_conversations($user1->id);
2391         // We need to execute the return values cleaning process to simulate the web service server.
2392         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
2393             $result);
2395         // Confirm the data is correct.
2396         $messages = $result['contacts'];
2397         $this->assertCount(3, $messages);
2399         $message1 = $messages[0];
2400         $message2 = $messages[1];
2401         $message3 = $messages[2];
2403         $this->assertEquals($user4->id, $message1['userid']);
2404         $this->assertTrue($message1['ismessaging']);
2405         $this->assertTrue($message1['sentfromcurrentuser']);
2406         $this->assertEquals('Dope.', $message1['lastmessage']);
2407         $this->assertEquals($messageid3, $message1['messageid']);
2408         $this->assertNull($message1['isonline']);
2409         $this->assertFalse($message1['isread']);
2410         $this->assertFalse($message1['isblocked']);
2411         $this->assertEquals(1, $message1['unreadcount']);
2413         $this->assertEquals($user3->id, $message2['userid']);
2414         $this->assertTrue($message2['ismessaging']);
2415         $this->assertFalse($message2['sentfromcurrentuser']);
2416         $this->assertEquals('Cool.', $message2['lastmessage']);
2417         $this->assertEquals($messageid2, $message2['messageid']);
2418         $this->assertNull($message2['isonline']);
2419         $this->assertFalse($message2['isread']);
2420         $this->assertFalse($message2['isblocked']);
2421         $this->assertEquals(2, $message2['unreadcount']);
2423         $this->assertEquals($user2->id, $message3['userid']);
2424         $this->assertTrue($message3['ismessaging']);
2425         $this->assertFalse($message3['sentfromcurrentuser']);
2426         $this->assertEquals('Word.', $message3['lastmessage']);
2427         $this->assertEquals($messageid1, $message3['messageid']);
2428         $this->assertNull($message3['isonline']);
2429         $this->assertFalse($message3['isread']);
2430         $this->assertFalse($message3['isblocked']);
2431         $this->assertEquals(2, $message3['unreadcount']);
2432     }
2434     /**
2435      * Tests retrieving conversations as another user.
2436      */
2437     public function test_messagearea_conversations_as_other_user() {
2438         $this->resetAfterTest(true);
2440         // Set as admin.
2441         $this->setAdminUser();
2443         // Create some users.
2444         $user1 = self::getDataGenerator()->create_user();
2445         $user2 = self::getDataGenerator()->create_user();
2446         $user3 = self::getDataGenerator()->create_user();
2447         $user4 = self::getDataGenerator()->create_user();
2449         // Send some messages back and forth, have some different conversations with different users.
2450         $time = time();
2451         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2452         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2453         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2454         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2456         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
2457         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
2458         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
2459         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
2461         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
2462         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
2463         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
2465         // Retrieve the conversations.
2466         $result = core_message_external::data_for_messagearea_conversations($user1->id);
2468         // We need to execute the return values cleaning process to simulate the web service server.
2469         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
2470             $result);
2472         // Confirm the data is correct.
2473         $messages = $result['contacts'];
2474         $this->assertCount(3, $messages);
2476         $message1 = $messages[0];
2477         $message2 = $messages[1];
2478         $message3 = $messages[2];
2480         $this->assertEquals($user4->id, $message1['userid']);
2481         $this->assertTrue($message1['ismessaging']);
2482         $this->assertTrue($message1['sentfromcurrentuser']);
2483         $this->assertEquals('Dope.', $message1['lastmessage']);
2484         $this->assertEquals($messageid3, $message1['messageid']);
2485         $this->assertFalse($message1['isonline']);
2486         $this->assertFalse($message1['isread']);
2487         $this->assertFalse($message1['isblocked']);
2488         $this->assertEquals(1, $message1['unreadcount']);
2490         $this->assertEquals($user3->id, $message2['userid']);
2491         $this->assertTrue($message2['ismessaging']);
2492         $this->assertFalse($message2['sentfromcurrentuser']);
2493         $this->assertEquals('Cool.', $message2['lastmessage']);
2494         $this->assertEquals($messageid2, $message2['messageid']);
2495         $this->assertFalse($message2['isonline']);
2496         $this->assertFalse($message2['isread']);
2497         $this->assertFalse($message2['isblocked']);
2498         $this->assertEquals(2, $message2['unreadcount']);
2500         $this->assertEquals($user2->id, $message3['userid']);
2501         $this->assertTrue($message3['ismessaging']);
2502         $this->assertFalse($message3['sentfromcurrentuser']);
2503         $this->assertEquals('Word.', $message3['lastmessage']);
2504         $this->assertEquals($messageid1, $message3['messageid']);
2505         $this->assertFalse($message3['isonline']);
2506         $this->assertFalse($message3['isread']);
2507         $this->assertFalse($message3['isblocked']);
2508         $this->assertEquals(2, $message3['unreadcount']);
2509     }
2511     /**
2512      * Tests retrieving conversations as another user without the proper capabilities.
2513      */
2514     public function test_messagearea_conversations_as_other_user_without_cap() {
2515         $this->resetAfterTest(true);
2517         // Create some users.
2518         $user1 = self::getDataGenerator()->create_user();
2519         $user2 = self::getDataGenerator()->create_user();
2521         // The person retrieving the conversations for another user.
2522         $this->setUser($user1);
2524         // Ensure an exception is thrown.
2525         $this->expectException('moodle_exception');
2526         core_message_external::data_for_messagearea_conversations($user2->id);
2527     }
2529     /**
2530      * Tests retrieving conversations with messaging disabled.
2531      */
2532     public function test_messagearea_conversations_messaging_disabled() {
2533         global $CFG;
2535         $this->resetAfterTest(true);
2537         // Create some skeleton data just so we can call the WS.
2538         $user = self::getDataGenerator()->create_user();
2540         // The person retrieving the conversations.
2541         $this->setUser($user);
2543         // Disable messaging.
2544         $CFG->messaging = 0;
2546         // Ensure an exception is thrown.
2547         $this->expectException('moodle_exception');
2548         core_message_external::data_for_messagearea_conversations($user->id);
2549     }
2551     /**
2552      * Tests retrieving contacts.
2553      */
2554     public function test_messagearea_contacts() {
2555         $this->resetAfterTest(true);
2557         // Create some users.
2558         $user1 = self::getDataGenerator()->create_user();
2560         // Set as the user.
2561         $this->setUser($user1);
2563         $user2 = new stdClass();
2564         $user2->firstname = 'User';
2565         $user2->lastname = 'A';
2566         $user2 = self::getDataGenerator()->create_user($user2);
2568         $user3 = new stdClass();
2569         $user3->firstname = 'User';
2570         $user3->lastname = 'B';
2571         $user3 = self::getDataGenerator()->create_user($user3);
2573         $user4 = new stdClass();
2574         $user4->firstname = 'User';
2575         $user4->lastname = 'C';
2576         $user4 = self::getDataGenerator()->create_user($user4);
2578         $user5 = new stdClass();
2579         $user5->firstname = 'User';
2580         $user5->lastname = 'D';
2581         $user5 = self::getDataGenerator()->create_user($user5);
2583         // Add some users as contacts.
2584         \core_message\api::add_contact($user1->id, $user2->id);
2585         \core_message\api::add_contact($user1->id, $user3->id);
2586         \core_message\api::add_contact($user1->id, $user4->id);
2588         // Retrieve the contacts.
2589         $result = core_message_external::data_for_messagearea_contacts($user1->id);
2591         // We need to execute the return values cleaning process to simulate the web service server.
2592         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
2593             $result);
2595         // Confirm the data is correct.
2596         $contacts = $result['contacts'];
2597         usort($contacts, ['static', 'sort_contacts']);
2598         $this->assertCount(3, $contacts);
2600         $contact1 = $contacts[0];
2601         $contact2 = $contacts[1];
2602         $contact3 = $contacts[2];
2604         $this->assertEquals($user2->id, $contact1['userid']);
2605         $this->assertFalse($contact1['ismessaging']);
2606         $this->assertFalse($contact1['sentfromcurrentuser']);
2607         $this->assertNull($contact1['lastmessage']);
2608         $this->assertNull($contact1['messageid']);
2609         $this->assertNull($contact1['isonline']);
2610         $this->assertFalse($contact1['isread']);
2611         $this->assertFalse($contact1['isblocked']);
2612         $this->assertNull($contact1['unreadcount']);
2614         $this->assertEquals($user3->id, $contact2['userid']);
2615         $this->assertFalse($contact2['ismessaging']);
2616         $this->assertFalse($contact2['sentfromcurrentuser']);
2617         $this->assertNull($contact2['lastmessage']);
2618         $this->assertNull($contact2['messageid']);
2619         $this->assertNull($contact2['isonline']);
2620         $this->assertFalse($contact2['isread']);
2621         $this->assertFalse($contact2['isblocked']);
2622         $this->assertNull($contact2['unreadcount']);
2624         $this->assertEquals($user4->id, $contact3['userid']);
2625         $this->assertFalse($contact3['ismessaging']);
2626         $this->assertFalse($contact3['sentfromcurrentuser']);
2627         $this->assertNull($contact3['lastmessage']);
2628         $this->assertNull($contact3['messageid']);
2629         $this->assertNull($contact3['isonline']);
2630         $this->assertFalse($contact3['isread']);
2631         $this->assertFalse($contact3['isblocked']);
2632         $this->assertNull($contact3['unreadcount']);
2633     }
2635     /**
2636      * Tests retrieving contacts as another user.
2637      */
2638     public function test_messagearea_contacts_as_other_user() {
2639         $this->resetAfterTest(true);
2641         $this->setAdminUser();
2643         // Create some users.
2644         $user1 = self::getDataGenerator()->create_user();
2646         $user2 = new stdClass();
2647         $user2->firstname = 'User';
2648         $user2->lastname = 'A';
2649         $user2 = self::getDataGenerator()->create_user($user2);
2651         $user3 = new stdClass();
2652         $user3->firstname = 'User';
2653         $user3->lastname = 'B';
2654         $user3 = self::getDataGenerator()->create_user($user3);
2656         $user4 = new stdClass();
2657         $user4->firstname = 'User';
2658         $user4->lastname = 'C';
2659         $user4 = self::getDataGenerator()->create_user($user4);
2661         $user5 = new stdClass();
2662         $user5->firstname = 'User';
2663         $user5->lastname = 'D';
2664         $user5 = self::getDataGenerator()->create_user($user5);
2666         // Add some users as contacts.
2667         \core_message\api::add_contact($user1->id, $user2->id);
2668         \core_message\api::add_contact($user1->id, $user3->id);
2669         \core_message\api::add_contact($user1->id, $user4->id);
2671         // Retrieve the contacts.
2672         $result = core_message_external::data_for_messagearea_contacts($user1->id);
2674         // We need to execute the return values cleaning process to simulate the web service server.
2675         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
2676             $result);
2678         // Confirm the data is correct.
2679         $contacts = $result['contacts'];
2680         usort($contacts, ['static', 'sort_contacts']);
2681         $this->assertCount(3, $contacts);
2683         $contact1 = $contacts[0];
2684         $contact2 = $contacts[1];
2685         $contact3 = $contacts[2];
2687         $this->assertEquals($user2->id, $contact1['userid']);
2688         $this->assertFalse($contact1['ismessaging']);
2689         $this->assertFalse($contact1['sentfromcurrentuser']);
2690         $this->assertNull($contact1['lastmessage']);
2691         $this->assertNull($contact1['messageid']);
2692         $this->assertFalse($contact1['isonline']);
2693         $this->assertFalse($contact1['isread']);
2694         $this->assertFalse($contact1['isblocked']);
2695         $this->assertNull($contact1['unreadcount']);
2697         $this->assertEquals($user3->id, $contact2['userid']);
2698         $this->assertFalse($contact2['ismessaging']);
2699         $this->assertFalse($contact2['sentfromcurrentuser']);
2700         $this->assertNull($contact2['lastmessage']);
2701         $this->assertNull($contact2['messageid']);
2702         $this->assertFalse($contact2['isonline']);
2703         $this->assertFalse($contact2['isread']);
2704         $this->assertFalse($contact2['isblocked']);
2705         $this->assertNull($contact2['unreadcount']);
2707         $this->assertEquals($user4->id, $contact3['userid']);
2708         $this->assertFalse($contact3['ismessaging']);
2709         $this->assertFalse($contact3['sentfromcurrentuser']);
2710         $this->assertNull($contact3['lastmessage']);
2711         $this->assertNull($contact3['messageid']);
2712         $this->assertFalse($contact3['isonline']);
2713         $this->assertFalse($contact3['isread']);
2714         $this->assertFalse($contact3['isblocked']);
2715         $this->assertNull($contact3['unreadcount']);
2716     }
2718     /**
2719      * Tests retrieving contacts as another user without the proper capabilities.
2720      */
2721     public function test_messagearea_contacts_as_other_user_without_cap() {
2722         $this->resetAfterTest(true);
2724         // Create some users.
2725         $user1 = self::getDataGenerator()->create_user();
2726         $user2 = self::getDataGenerator()->create_user();
2728         // The person retrieving the contacts for another user.
2729         $this->setUser($user1);
2731         // Perform the WS call and ensure an exception is thrown.
2732         $this->expectException('moodle_exception');
2733         core_message_external::data_for_messagearea_contacts($user2->id);
2734     }
2736     /**
2737      * Tests retrieving contacts with messaging disabled.
2738      */
2739     public function test_messagearea_contacts_messaging_disabled() {
2740         global $CFG;
2742         $this->resetAfterTest(true);
2744         // Create some skeleton data just so we can call the WS.
2745         $user = self::getDataGenerator()->create_user();
2747         // The person retrieving the contacts.
2748         $this->setUser($user);
2750         // Disable messaging.
2751         $CFG->messaging = 0;
2753         // Perform the WS call and ensure we are shown that it is disabled.
2754         $this->expectException('moodle_exception');
2755         core_message_external::data_for_messagearea_contacts($user->id);
2756     }
2758     /**
2759      * Tests retrieving messages.
2760      */
2761     public function test_messagearea_messages() {
2762         $this->resetAfterTest(true);
2764         // Create some users.
2765         $user1 = self::getDataGenerator()->create_user();
2766         $user2 = self::getDataGenerator()->create_user();
2768         // The person asking for the messages.
2769         $this->setUser($user1);
2771         // Send some messages back and forth.
2772         $time = time();
2773         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2774         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2775         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2776         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2778         // Retrieve the messages.
2779         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2781         // We need to execute the return values cleaning process to simulate the web service server.
2782         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2783             $result);
2785         // Check the results are correct.
2786         $this->assertTrue($result['iscurrentuser']);
2787         $this->assertEquals($user1->id, $result['currentuserid']);
2788         $this->assertEquals($user2->id, $result['otheruserid']);
2789         $this->assertEquals(fullname($user2), $result['otheruserfullname']);
2790         $this->assertNull($result['isonline']);
2792         // Confirm the message data is correct.
2793         $messages = $result['messages'];
2794         $this->assertCount(4, $messages);
2796         $message1 = $messages[0];
2797         $message2 = $messages[1];
2798         $message3 = $messages[2];
2799         $message4 = $messages[3];
2801         $this->assertEquals($user1->id, $message1['useridfrom']);
2802         $this->assertEquals($user2->id, $message1['useridto']);
2803         $this->assertTrue($message1['displayblocktime']);
2804         $this->assertContains('Yo!', $message1['text']);
2806         $this->assertEquals($user2->id, $message2['useridfrom']);
2807         $this->assertEquals($user1->id, $message2['useridto']);
2808         $this->assertFalse($message2['displayblocktime']);
2809         $this->assertContains('Sup mang?', $message2['text']);
2811         $this->assertEquals($user1->id, $message3['useridfrom']);
2812         $this->assertEquals($user2->id, $message3['useridto']);
2813         $this->assertFalse($message3['displayblocktime']);
2814         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
2816         $this->assertEquals($user2->id, $message4['useridfrom']);
2817         $this->assertEquals($user1->id, $message4['useridto']);
2818         $this->assertFalse($message4['displayblocktime']);
2819         $this->assertContains('Word.', $message4['text']);
2820     }
2822     /**
2823      * Tests retrieving messages.
2824      */
2825     public function test_messagearea_messages_timefrom() {
2826         $this->resetAfterTest(true);
2828         // Create some users.
2829         $user1 = self::getDataGenerator()->create_user();
2830         $user2 = self::getDataGenerator()->create_user();
2832         // The person asking for the messages.
2833         $this->setUser($user1);
2835         // Send some messages back and forth.
2836         $time = time();
2837         $this->send_message($user1, $user2, 'Message 1', 0, $time - 4);
2838         $this->send_message($user2, $user1, 'Message 2', 0, $time - 3);
2839         $this->send_message($user1, $user2, 'Message 3', 0, $time - 2);
2840         $this->send_message($user2, $user1, 'Message 4', 0, $time - 1);
2842         // Retrieve the messages from $time - 3, which should be the 3 most recent messages.
2843         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id, 0, 0, false, $time - 3);
2845         // We need to execute the return values cleaning process to simulate the web service server.
2846         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2847             $result);
2849         // Confirm the message data is correct. We shouldn't get 'Message 1' back.
2850         $messages = $result['messages'];
2851         $this->assertCount(3, $messages);
2853         $message1 = $messages[0];
2854         $message2 = $messages[1];
2855         $message3 = $messages[2];
2857         $this->assertContains('Message 2', $message1['text']);
2858         $this->assertContains('Message 3', $message2['text']);
2859         $this->assertContains('Message 4', $message3['text']);
2860     }
2862     /**
2863      * Tests retrieving messages as another user.
2864      */
2865     public function test_messagearea_messages_as_other_user() {
2866         $this->resetAfterTest(true);
2868         // Set as admin.
2869         $this->setAdminUser();
2871         // Create some users.
2872         $user1 = self::getDataGenerator()->create_user();
2873         $user2 = self::getDataGenerator()->create_user();
2875         // Send some messages back and forth.
2876         $time = time();
2877         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2878         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2879         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2880         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2882         // Retrieve the messages.
2883         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2885         // We need to execute the return values cleaning process to simulate the web service server.
2886         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2887             $result);
2889         // Check the results are correct.
2890         $this->assertFalse($result['iscurrentuser']);
2891         $this->assertEquals($user1->id, $result['currentuserid']);
2892         $this->assertEquals($user2->id, $result['otheruserid']);
2893         $this->assertEquals(fullname($user2), $result['otheruserfullname']);
2894         $this->assertFalse($result['isonline']);
2896         // Confirm the message data is correct.
2897         $messages = $result['messages'];
2898         $this->assertCount(4, $messages);
2900         $message1 = $messages[0];
2901         $message2 = $messages[1];
2902         $message3 = $messages[2];
2903         $message4 = $messages[3];
2905         $this->assertEquals($user1->id, $message1['useridfrom']);
2906         $this->assertEquals($user2->id, $message1['useridto']);
2907         $this->assertTrue($message1['displayblocktime']);
2908         $this->assertContains('Yo!', $message1['text']);
2910         $this->assertEquals($user2->id, $message2['useridfrom']);
2911         $this->assertEquals($user1->id, $message2['useridto']);
2912         $this->assertFalse($message2['displayblocktime']);
2913         $this->assertContains('Sup mang?', $message2['text']);
2915         $this->assertEquals($user1->id, $message3['useridfrom']);
2916         $this->assertEquals($user2->id, $message3['useridto']);
2917         $this->assertFalse($message3['displayblocktime']);
2918         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
2920         $this->assertEquals($user2->id, $message4['useridfrom']);
2921         $this->assertEquals($user1->id, $message4['useridto']);
2922         $this->assertFalse($message4['displayblocktime']);
2923         $this->assertContains('Word.', $message4['text']);
2924     }
2926     /**
2927      * Tests retrieving messages as another user without the proper capabilities.
2928      */
2929     public function test_messagearea_messages_as_other_user_without_cap() {
2930         $this->resetAfterTest(true);
2932         // Create some users.
2933         $user1 = self::getDataGenerator()->create_user();
2934         $user2 = self::getDataGenerator()->create_user();
2935         $user3 = self::getDataGenerator()->create_user();
2937         // The person asking for the messages for another user.
2938         $this->setUser($user1);
2940         // Ensure an exception is thrown.
2941         $this->expectException('moodle_exception');
2942         core_message_external::data_for_messagearea_messages($user2->id, $user3->id);
2943     }
2945     /**
2946      * Tests retrieving messages with messaging disabled.
2947      */
2948     public function test_messagearea_messages_messaging_disabled() {
2949         global $CFG;
2951         $this->resetAfterTest(true);
2953         // Create some skeleton data just so we can call the WS.
2954         $user1 = self::getDataGenerator()->create_user();
2955         $user2 = self::getDataGenerator()->create_user();
2957         // The person asking for the messages for another user.
2958         $this->setUser($user1);
2960         // Disable messaging.
2961         $CFG->messaging = 0;
2963         // Ensure an exception is thrown.
2964         $this->expectException('moodle_exception');
2965         core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2966     }
2968     /**
2969      * Tests retrieving most recent message.
2970      */
2971     public function test_messagearea_get_most_recent_message() {
2972         $this->resetAfterTest(true);
2974         // Create some users.
2975         $user1 = self::getDataGenerator()->create_user();
2976         $user2 = self::getDataGenerator()->create_user();
2978         // The person doing the search.
2979         $this->setUser($user1);
2981         // Send some messages back and forth.
2982         $time = time();
2983         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2984         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2985         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2986         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2988         // Get the most recent message.
2989         $result = core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
2991         // We need to execute the return values cleaning process to simulate the web service server.
2992         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_most_recent_message_returns(),
2993             $result);
2995         // Check the results are correct.
2996         $this->assertEquals($user2->id, $result['useridfrom']);
2997         $this->assertEquals($user1->id, $result['useridto']);
2998         $this->assertContains('Word.', $result['text']);
2999     }
3001     /**
3002      * Tests retrieving most recent message as another user.
3003      */
3004     public function test_messagearea_get_most_recent_message_as_other_user() {
3005         $this->resetAfterTest(true);
3007         // The person doing the search.
3008         $this->setAdminUser();
3010         // Create some users.
3011         $user1 = self::getDataGenerator()->create_user();
3012         $user2 = self::getDataGenerator()->create_user();
3014         // Send some messages back and forth.
3015         $time = time();
3016         $this->send_message($user1, $user2, 'Yo!', 0, $time);
3017         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3018         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
3019         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
3021         // Get the most recent message.
3022         $result = core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
3024         // We need to execute the return values cleaning process to simulate the web service server.
3025         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_most_recent_message_returns(),
3026             $result);
3028         // Check the results are correct.
3029         $this->assertEquals($user2->id, $result['useridfrom']);
3030         $this->assertEquals($user1->id, $result['useridto']);
3031         $this->assertContains('Word.', $result['text']);
3032     }
3034     /**
3035      * Tests retrieving most recent message as another user without the proper capabilities.
3036      */
3037     public function test_messagearea_get_most_recent_message_as_other_user_without_cap() {
3038         $this->resetAfterTest(true);
3040         // Create some users.
3041         $user1 = self::getDataGenerator()->create_user();
3042         $user2 = self::getDataGenerator()->create_user();
3043         $user3 = self::getDataGenerator()->create_user();
3045         // The person asking for the most recent message for another user.
3046         $this->setUser($user1);
3048         // Ensure an exception is thrown.
3049         $this->expectException('moodle_exception');
3050         core_message_external::data_for_messagearea_get_most_recent_message($user2->id, $user3->id);
3051     }
3053     /**
3054      * Tests retrieving most recent message with messaging disabled.
3055      */
3056     public function test_messagearea_get_most_recent_message_messaging_disabled() {
3057         global $CFG;
3059         $this->resetAfterTest(true);
3061         // Create some skeleton data just so we can call the WS.
3062         $user1 = self::getDataGenerator()->create_user();
3063         $user2 = self::getDataGenerator()->create_user();
3065         // The person asking for the most recent message.
3066         $this->setUser($user1);
3068         // Disable messaging.
3069         $CFG->messaging = 0;
3071         // Ensure an exception is thrown.
3072         $this->expectException('moodle_exception');
3073         core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
3074     }
3076     /**
3077      * Tests retrieving a user's profile.
3078      */
3079     public function test_messagearea_get_profile() {
3080         $this->resetAfterTest(true);
3082         // Create some users.
3083         $user1 = self::getDataGenerator()->create_user();
3084         $user2 = self::getDataGenerator()->create_user();
3086         // The person asking for the profile information.
3087         $this->setUser($user1);
3089         // Get the profile.
3090         $result = core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
3092         // We need to execute the return values cleaning process to simulate the web service server.
3093         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_profile_returns(),
3094             $result);
3096         $this->assertEquals($user2->id, $result['userid']);
3097         $this->assertEmpty($result['email']);
3098         $this->assertEmpty($result['country']);
3099         $this->assertEmpty($result['city']);
3100         $this->assertEquals(fullname($user2), $result['fullname']);
3101         $this->assertNull($result['isonline']);
3102         $this->assertFalse($result['isblocked']);
3103         $this->assertFalse($result['iscontact']);
3104     }
3106     /**
3107      * Tests retrieving a user's profile as another user.
3108      */
3109     public function test_messagearea_profile_as_other_user() {
3110         $this->resetAfterTest(true);
3112         // The person asking for the profile information.
3113         $this->setAdminUser();
3115         // Create some users.
3116         $user1 = self::getDataGenerator()->create_user();
3118         $user2 = new stdClass();
3119         $user2->country = 'AU';
3120         $user2->city = 'Perth';
3121         $user2 = self::getDataGenerator()->create_user($user2);
3123         // Get the profile.
3124         $result = core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
3126         // We need to execute the return values cleaning process to simulate the web service server.
3127         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_profile_returns(),
3128             $result);
3130         $this->assertEquals($user2->id, $result['userid']);
3131         $this->assertEquals($user2->email, $result['email']);
3132         $this->assertEquals(get_string($user2->country, 'countries'), $result['country']);
3133         $this->assertEquals($user2->city, $result['city']);
3134         $this->assertEquals(fullname($user2), $result['fullname']);
3135         $this->assertFalse($result['isonline']);
3136         $this->assertFalse($result['isblocked']);
3137         $this->assertFalse($result['iscontact']);
3138     }
3140     /**
3141      * Tests retrieving a user's profile as another user without the proper capabilities.
3142      */
3143     public function test_messagearea_profile_as_other_user_without_cap() {
3144         $this->resetAfterTest(true);
3146         // Create some users.
3147         $user1 = self::getDataGenerator()->create_user();
3148         $user2 = self::getDataGenerator()->create_user();
3149         $user3 = self::getDataGenerator()->create_user();
3151         // The person asking for the profile information for another user.
3152         $this->setUser($user1);
3154         // Ensure an exception is thrown.
3155         $this->expectException('moodle_exception');
3156         core_message_external::data_for_messagearea_get_profile($user2->id, $user3->id);
3157     }
3159     /**
3160      * Tests retrieving a user's profile with messaging disabled.
3161      */
3162     public function test_messagearea_profile_messaging_disabled() {
3163         global $CFG;
3165         $this->resetAfterTest(true);
3167         // Create some skeleton data just so we can call the WS.
3168         $user1 = self::getDataGenerator()->create_user();
3169         $user2 = self::getDataGenerator()->create_user();
3171         // The person asking for the profile information.
3172         $this->setUser($user1);
3174         // Disable messaging.
3175         $CFG->messaging = 0;
3177         // Ensure an exception is thrown.
3178         $this->expectException('moodle_exception');
3179         core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
3180     }
3182     /**
3183      * Test marking all message as read with an invalid user.
3184      */
3185     public function test_mark_all_messages_as_read_invalid_user_exception() {
3186         $this->resetAfterTest(true);
3188         $this->expectException('moodle_exception');
3189         core_message_external::mark_all_messages_as_read(-2132131, 0);
3190     }
3192     /**
3193      * Test marking all message as read without proper access.
3194      */
3195     public function test_mark_all_messages_as_read_access_denied_exception() {
3196         $this->resetAfterTest(true);
3198         $sender = $this->getDataGenerator()->create_user();
3199         $user = $this->getDataGenerator()->create_user();
3201         $this->setUser($user);
3202         $this->expectException('moodle_exception');
3203         core_message_external::mark_all_messages_as_read($sender->id, 0);
3204     }
3206     /**
3207      * Test marking all message as read with missing from user.
3208      */
3209     public function test_mark_all_messages_as_read_missing_from_user_exception() {
3210         $this->resetAfterTest(true);
3212         $sender = $this->getDataGenerator()->create_user();
3214         $this->setUser($sender);
3215         $this->expectException('moodle_exception');
3216         core_message_external::mark_all_messages_as_read($sender->id, 99999);
3217     }
3219     /**
3220      * Test marking all message as read.
3221      */
3222     public function test_mark_all_messages_as_read() {
3223         global $DB;
3225         $this->resetAfterTest(true);
3227         $sender1 = $this->getDataGenerator()->create_user();
3228         $sender2 = $this->getDataGenerator()->create_user();
3229         $sender3 = $this->getDataGenerator()->create_user();
3230         $recipient = $this->getDataGenerator()->create_user();
3232         $this->setUser($recipient);
3234         $this->send_message($sender1, $recipient, 'Message');
3235         $this->send_message($sender1, $recipient, 'Message');
3236         $this->send_message($sender2, $recipient, 'Message');
3237         $this->send_message($sender2, $recipient, 'Message');
3238         $this->send_message($sender3, $recipient, 'Message');
3239         $this->send_message($sender3, $recipient, 'Message');
3241         core_message_external::mark_all_messages_as_read($recipient->id, $sender1->id);
3242         $this->assertEquals(2, $DB->count_records('message_user_actions'));
3244         core_message_external::mark_all_messages_as_read($recipient->id, 0);
3245         $this->assertEquals(6, $DB->count_records('message_user_actions'));
3246     }
3248     /**
3249      * Test getting unread conversation count.
3250      */
3251     public function test_get_unread_conversations_count() {
3252         $this->resetAfterTest(true);
3254         // Create some users.
3255         $user1 = self::getDataGenerator()->create_user();
3256         $user2 = self::getDataGenerator()->create_user();
3257         $user3 = self::getDataGenerator()->create_user();
3258         $user4 = self::getDataGenerator()->create_user();
3260         // The person wanting the conversation count.
3261         $this->setUser($user1);
3263         // Send some messages back and forth, have some different conversations with different users.
3264         $this->send_message($user1, $user2, 'Yo!');
3265         $this->send_message($user2, $user1, 'Sup mang?');
3266         $this->send_message($user1, $user2, 'Writing PHPUnit tests!');
3267         $this->send_message($user2, $user1, 'Word.');
3269         $this->send_message($user1, $user3, 'Booyah');
3270         $this->send_message($user3, $user1, 'Whaaat?');
3271         $this->send_message($user1, $user3, 'Nothing.');
3272         $this->send_message($user3, $user1, 'Cool.');
3274         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
3275         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
3276         $this->send_message($user1, $user4, 'Dope.');
3278         // Get the unread conversation count.
3279         $result = core_message_external::get_unread_conversations_count($user1->id);
3281         // We need to execute the return values cleaning process to simulate the web service server.
3282         $result = external_api::clean_returnvalue(core_message_external::get_unread_conversations_count_returns(),
3283             $result);
3285         $this->assertEquals(3, $result);
3286     }
3288     /**
3289      * Test getting unread conversation count as other user.
3290      */
3291     public function test_get_unread_conversations_count_as_other_user() {
3292         $this->resetAfterTest(true);
3294         // The person wanting the conversation count.
3295         $this->setAdminUser();
3297         // Create some users.
3298         $user1 = self::getDataGenerator()->create_user();
3299         $user2 = self::getDataGenerator()->create_user();
3300         $user3 = self::getDataGenerator()->create_user();
3301         $user4 = self::getDataGenerator()->create_user();
3303         // Send some messages back and forth, have some different conversations with different users.
3304         $this->send_message($user1, $user2, 'Yo!');
3305         $this->send_message($user2, $user1, 'Sup mang?');
3306         $this->send_message($user1, $user2, 'Writing PHPUnit tests!');
3307         $this->send_message($user2, $user1, 'Word.');
3309         $this->send_message($user1, $user3, 'Booyah');
3310         $this->send_message($user3, $user1, 'Whaaat?');
3311         $this->send_message($user1, $user3, 'Nothing.');
3312         $this->send_message($user3, $user1, 'Cool.');
3314         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
3315         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
3316         $this->send_message($user1, $user4, 'Dope.');
3318         // Get the unread conversation count.
3319         $result = core_message_external::get_unread_conversations_count($user1->id);
3321         // We need to execute the return values cleaning process to simulate the web service server.
3322         $result = external_api::clean_returnvalue(core_message_external::get_unread_conversations_count_returns(),
3323             $result);
3325         $this->assertEquals(3, $result);
3326     }
3328     /**
3329      * Test getting unread conversation count as other user without proper capability.
3330      */
3331     public function test_get_unread_conversations_count_as_other_user_without_cap() {
3332         $this->resetAfterTest(true);
3334         // Create some users.
3335         $user1 = self::getDataGenerator()->create_user();
3336         $user2 = self::getDataGenerator()->create_user();
3338         // The person wanting the conversation count.
3339         $this->setUser($user1);
3341         // Ensure an exception is thrown.
3342         $this->expectException('moodle_exception');
3343         core_message_external::get_unread_conversations_count($user2->id);
3344     }
3346     /**
3347      * Test deleting conversation.
3348      */
3349     public function test_delete_conversation() {
3350         global $DB;
3352         $this->resetAfterTest(true);
3354         // Create some users.
3355         $user1 = self::getDataGenerator()->create_user();
3356         $user2 = self::getDataGenerator()->create_user();
3358         // The person wanting to delete the conversation.
3359         $this->setUser($user1);
3361         // Send some messages back and forth.
3362         $time = time();
3363         $m1id = $this->send_message($user1, $user2, 'Yo!', 0, $time);
3364         $m2id = $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3365         $m3id = $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
3366         $m4id = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
3368         // Delete the conversation.
3369         core_message_external::delete_conversation($user1->id, $user2->id);
3371         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
3372         $this->assertCount(4, $muas);
3373         // Sort by id.
3374         ksort($muas);
3376         $mua1 = array_shift($muas);
3377         $mua2 = array_shift($muas);
3378         $mua3 = array_shift($muas);
3379         $mua4 = array_shift($muas);
3381         $this->assertEquals($user1->id, $mua1->userid);
3382         $this->assertEquals($m1id, $mua1->messageid);
3383         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
3385         $this->assertEquals($user1->id, $mua2->userid);
3386         $this->assertEquals($m2id, $mua2->messageid);
3387         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
3389         $this->assertEquals($user1->id, $mua3->userid);
3390         $this->assertEquals($m3id, $mua3->messageid);
3391         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
3393         $this->assertEquals($user1->id, $mua4->userid);
3394         $this->assertEquals($m4id, $mua4->messageid);
3395         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
3396     }
3398     /**
3399      * Test deleting conversation as other user.
3400      */
3401     public function test_delete_conversation_as_other_user() {
3402         global $DB;
3404         $this->resetAfterTest(true);