MDL-63547 core_message: added delete_conversation_by_id web service
[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);
119         $sentmessage = reset($sentmessages);
121         $sql = "SELECT m.*, mcm.userid as useridto
122                  FROM {messages} m
123            INNER JOIN {message_conversations} mc
124                    ON m.conversationid = mc.id
125            INNER JOIN {message_conversation_members} mcm
126                    ON mcm.conversationid = mc.id
127                 WHERE mcm.userid != ?
128                   AND m.id = ?";
129         $themessage = $DB->get_record_sql($sql, [$USER->id, $sentmessage['msgid']]);
131         // Confirm that the message was inserted correctly.
132         $this->assertEquals($themessage->useridfrom, $user1->id);
133         $this->assertEquals($themessage->useridto, $message1['touserid']);
134         $this->assertEquals($themessage->smallmessage, $message1['text']);
135         $this->assertEquals($sentmessage['clientmsgid'], $message1['clientmsgid']);
136     }
138     /**
139      * Test send_instant_messages to a user who has blocked you.
140      */
141     public function test_send_instant_messages_blocked_user() {
142         global $DB;
144         $this->resetAfterTest();
146         // Transactions used in tests, tell phpunit use alternative reset method.
147         $this->preventResetByRollback();
149         $user1 = self::getDataGenerator()->create_user();
150         $user2 = self::getDataGenerator()->create_user();
152         $this->setUser($user1);
154         \core_message\api::block_user($user2->id, $user1->id);
156         // Create test message data.
157         $message1 = array();
158         $message1['touserid'] = $user2->id;
159         $message1['text'] = 'the message.';
160         $message1['clientmsgid'] = 4;
161         $messages = array($message1);
163         $sentmessages = core_message_external::send_instant_messages($messages);
164         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
166         $sentmessage = reset($sentmessages);
168         $this->assertEquals(get_string('userisblockingyou', 'message'), $sentmessage['errormessage']);
170         $this->assertEquals(0, $DB->count_records('messages'));
171     }
173     /**
174      * Test send_instant_messages when sending a message to a non-contact who has blocked non-contacts.
175      */
176     public function test_send_instant_messages_block_non_contacts() {
177         global $DB;
179         $this->resetAfterTest(true);
181         // Transactions used in tests, tell phpunit use alternative reset method.
182         $this->preventResetByRollback();
184         $user1 = self::getDataGenerator()->create_user();
185         $user2 = self::getDataGenerator()->create_user();
187         $this->setUser($user1);
189         // Set the user preference so user 2 does not accept messages from non-contacts.
190         set_user_preference('message_blocknoncontacts', 1, $user2);
192         // Create test message data.
193         $message1 = array();
194         $message1['touserid'] = $user2->id;
195         $message1['text'] = 'the message.';
196         $message1['clientmsgid'] = 4;
197         $messages = array($message1);
199         $sentmessages = core_message_external::send_instant_messages($messages);
200         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
202         $sentmessage = reset($sentmessages);
204         $this->assertEquals(get_string('userisblockingyounoncontact', 'message', fullname($user2)), $sentmessage['errormessage']);
206         $this->assertEquals(0, $DB->count_records('messages'));
207     }
209     /**
210      * Test send_instant_messages when sending a message to a contact who has blocked non-contacts.
211      */
212     public function test_send_instant_messages_block_non_contacts_but_am_contact() {
213         global $DB, $USER;
215         $this->resetAfterTest(true);
217         // Transactions used in tests, tell phpunit use alternative reset method.
218         $this->preventResetByRollback();
220         $user1 = self::getDataGenerator()->create_user();
221         $user2 = self::getDataGenerator()->create_user();
223         $this->setUser($user1);
225         // Set the user preference so user 2 does not accept messages from non-contacts.
226         set_user_preference('message_blocknoncontacts', 1, $user2);
228         \core_message\api::add_contact($user1->id, $user2->id);
230         // Create test message data.
231         $message1 = array();
232         $message1['touserid'] = $user2->id;
233         $message1['text'] = 'the message.';
234         $message1['clientmsgid'] = 4;
235         $messages = array($message1);
237         $sentmessages = core_message_external::send_instant_messages($messages);
238         $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
240         $sentmessage = reset($sentmessages);
242         $sql = "SELECT m.*, mcm.userid as useridto
243                  FROM {messages} m
244            INNER JOIN {message_conversations} mc
245                    ON m.conversationid = mc.id
246            INNER JOIN {message_conversation_members} mcm
247                    ON mcm.conversationid = mc.id
248                 WHERE mcm.userid != ?
249                   AND m.id = ?";
250         $themessage = $DB->get_record_sql($sql, [$USER->id, $sentmessage['msgid']]);
252         // Confirm that the message was inserted correctly.
253         $this->assertEquals($themessage->useridfrom, $user1->id);
254         $this->assertEquals($themessage->useridto, $message1['touserid']);
255         $this->assertEquals($themessage->smallmessage, $message1['text']);
256         $this->assertEquals($sentmessage['clientmsgid'], $message1['clientmsgid']);
257     }
259     /**
260      * Test send_instant_messages with no capabilities
261      */
262     public function test_send_instant_messages_no_capability() {
263         global $DB;
265         $this->resetAfterTest(true);
267         // Transactions used in tests, tell phpunit use alternative reset method.
268         $this->preventResetByRollback();
270         $user1 = self::getDataGenerator()->create_user();
271         $user2 = self::getDataGenerator()->create_user();
273         $this->setUser($user1);
275         // Unset the required capabilities by the external function.
276         $contextid = context_system::instance()->id;
277         $userrole = $DB->get_record('role', array('shortname' => 'user'));
278         $this->unassignUserCapability('moodle/site:sendmessage', $contextid, $userrole->id);
280         // Create test message data.
281         $message1 = array();
282         $message1['touserid'] = $user2->id;
283         $message1['text'] = 'the message.';
284         $message1['clientmsgid'] = 4;
285         $messages = array($message1);
287         $this->expectException('required_capability_exception');
288         core_message_external::send_instant_messages($messages);
289     }
291     /**
292      * Test send_instant_messages when messaging is disabled.
293      */
294     public function test_send_instant_messages_messaging_disabled() {
295         global $CFG;
297         $this->resetAfterTest(true);
299         // Transactions used in tests, tell phpunit use alternative reset method.
300         $this->preventResetByRollback();
302         $user1 = self::getDataGenerator()->create_user();
303         $user2 = self::getDataGenerator()->create_user();
305         $this->setUser($user1);
307         // Disable messaging.
308         $CFG->messaging = 0;
310         // Create test message data.
311         $message1 = array();
312         $message1['touserid'] = $user2->id;
313         $message1['text'] = 'the message.';
314         $message1['clientmsgid'] = 4;
315         $messages = array($message1);
317         $this->expectException('moodle_exception');
318         core_message_external::send_instant_messages($messages);
319     }
321     /**
322      * Test create_contacts.
323      */
324     public function test_create_contacts() {
325         $this->resetAfterTest(true);
327         $user1 = self::getDataGenerator()->create_user();
328         $user2 = self::getDataGenerator()->create_user();
329         $user3 = self::getDataGenerator()->create_user();
330         $user4 = self::getDataGenerator()->create_user();
331         $user5 = self::getDataGenerator()->create_user();
332         $this->setUser($user1);
334         // Adding a contact.
335         $return = core_message_external::create_contacts(array($user2->id));
336         $this->assertDebuggingCalled();
337         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
338         $this->assertEquals(array(), $return);
340         // Adding a contact who is already a contact.
341         $return = core_message_external::create_contacts(array($user2->id));
342         $this->assertDebuggingCalled();
343         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
344         $this->assertEquals(array(), $return);
346         // Adding multiple contacts.
347         $return = core_message_external::create_contacts(array($user3->id, $user4->id));
348         $this->assertDebuggingCalledCount(2);
349         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
350         $this->assertEquals(array(), $return);
352         // Adding a non-existing user.
353         $return = core_message_external::create_contacts(array(99999));
354         $this->assertDebuggingCalled();
355         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
356         $this->assertCount(1, $return);
357         $return = array_pop($return);
358         $this->assertEquals($return['warningcode'], 'contactnotcreated');
359         $this->assertEquals($return['itemid'], 99999);
361         // Adding contacts with valid and invalid parameters.
362         $return = core_message_external::create_contacts(array($user5->id, 99999));
363         $this->assertDebuggingCalledCount(2);
364         $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
365         $this->assertCount(1, $return);
366         $return = array_pop($return);
367         $this->assertEquals($return['warningcode'], 'contactnotcreated');
368         $this->assertEquals($return['itemid'], 99999);
370         // Try to add a contact to another user, should throw an exception.
371         // All assertions must be added before this point.
372         $this->expectException('required_capability_exception');
373         core_message_external::create_contacts(array($user2->id), $user3->id);
374     }
376     /**
377      * Test delete_contacts.
378      */
379     public function test_delete_contacts() {
380         $this->resetAfterTest(true);
382         $user1 = self::getDataGenerator()->create_user();
383         $user2 = self::getDataGenerator()->create_user();
384         $user3 = self::getDataGenerator()->create_user();
385         $user4 = self::getDataGenerator()->create_user();
386         $user5 = self::getDataGenerator()->create_user();
387         $user6 = self::getDataGenerator()->create_user();
388         $this->setUser($user1);
390         \core_message\api::add_contact($user1->id, $user3->id);
391         \core_message\api::add_contact($user1->id, $user4->id);
392         \core_message\api::add_contact($user1->id, $user5->id);
393         \core_message\api::add_contact($user1->id, $user6->id);
395         // Removing a non-contact.
396         $return = core_message_external::delete_contacts(array($user2->id));
397         $this->assertNull($return);
399         // Removing one contact.
400         $return = core_message_external::delete_contacts(array($user3->id));
401         $this->assertNull($return);
403         // Removing multiple contacts.
404         $return = core_message_external::delete_contacts(array($user4->id, $user5->id));
405         $this->assertNull($return);
407         // Removing contact from unexisting user.
408         $return = core_message_external::delete_contacts(array(99999));
409         $this->assertNull($return);
411         // Removing mixed valid and invalid data.
412         $return = core_message_external::delete_contacts(array($user6->id, 99999));
413         $this->assertNull($return);
415         // Try to delete a contact of another user contact list, should throw an exception.
416         // All assertions must be added before this point.
417         $this->expectException('required_capability_exception');
418         core_message_external::delete_contacts(array($user2->id), $user3->id);
419     }
421     /**
422      * Test block_contacts.
423      */
424     public function test_block_contacts() {
425         $this->resetAfterTest(true);
427         $user1 = self::getDataGenerator()->create_user();
428         $user2 = self::getDataGenerator()->create_user();
429         $user3 = self::getDataGenerator()->create_user();
430         $user4 = self::getDataGenerator()->create_user();
431         $user5 = self::getDataGenerator()->create_user();
432         $this->setUser($user1);
434         \core_message\api::add_contact($user1->id, $user3->id);
435         \core_message\api::add_contact($user1->id, $user4->id);
436         \core_message\api::add_contact($user1->id, $user5->id);
438         // Blocking a contact.
439         $return = core_message_external::block_contacts(array($user2->id));
440         $this->assertDebuggingCalled();
441         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
442         $this->assertEquals(array(), $return);
444         // Blocking a contact who is already a contact.
445         $return = core_message_external::block_contacts(array($user2->id));
446         $this->assertDebuggingCalled();
447         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
448         $this->assertEquals(array(), $return);
450         // Blocking multiple contacts.
451         $return = core_message_external::block_contacts(array($user3->id, $user4->id));
452         $this->assertDebuggingCalledCount(2);
453         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
454         $this->assertEquals(array(), $return);
456         // Blocking a non-existing user.
457         $return = core_message_external::block_contacts(array(99999));
458         $this->assertDebuggingCalled();
459         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
460         $this->assertCount(1, $return);
461         $return = array_pop($return);
462         $this->assertEquals($return['warningcode'], 'contactnotblocked');
463         $this->assertEquals($return['itemid'], 99999);
465         // Blocking contacts with valid and invalid parameters.
466         $return = core_message_external::block_contacts(array($user5->id, 99999));
467         $this->assertDebuggingCalledCount(2);
468         $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
469         $this->assertCount(1, $return);
470         $return = array_pop($return);
471         $this->assertEquals($return['warningcode'], 'contactnotblocked');
472         $this->assertEquals($return['itemid'], 99999);
474         // Try to block a contact of another user contact list, should throw an exception.
475         // All assertions must be added before this point.
476         $this->expectException('required_capability_exception');
477         core_message_external::block_contacts(array($user2->id), $user3->id);
478     }
480     /**
481      * Test unblock_contacts.
482      */
483     public function test_unblock_contacts() {
484         $this->resetAfterTest(true);
486         $user1 = self::getDataGenerator()->create_user();
487         $user2 = self::getDataGenerator()->create_user();
488         $user3 = self::getDataGenerator()->create_user();
489         $user4 = self::getDataGenerator()->create_user();
490         $user5 = self::getDataGenerator()->create_user();
491         $user6 = self::getDataGenerator()->create_user();
492         $this->setUser($user1);
494         \core_message\api::add_contact($user1->id, $user3->id);
495         \core_message\api::add_contact($user1->id, $user4->id);
496         \core_message\api::add_contact($user1->id, $user5->id);
497         \core_message\api::add_contact($user1->id, $user6->id);
499         // Removing a non-contact.
500         $return = core_message_external::unblock_contacts(array($user2->id));
501         $this->assertDebuggingCalled();
502         $this->assertNull($return);
504         // Removing one contact.
505         $return = core_message_external::unblock_contacts(array($user3->id));
506         $this->assertDebuggingCalled();
507         $this->assertNull($return);
509         // Removing multiple contacts.
510         $return = core_message_external::unblock_contacts(array($user4->id, $user5->id));
511         $this->assertDebuggingCalledCount(2);
512         $this->assertNull($return);
514         // Removing contact from unexisting user.
515         $return = core_message_external::unblock_contacts(array(99999));
516         $this->assertDebuggingCalled();
517         $this->assertNull($return);
519         // Removing mixed valid and invalid data.
520         $return = core_message_external::unblock_contacts(array($user6->id, 99999));
521         $this->assertDebuggingCalledCount(2);
522         $this->assertNull($return);
524         // Try to unblock a contact of another user contact list, should throw an exception.
525         // All assertions must be added before this point.
526         $this->expectException('required_capability_exception');
527         core_message_external::unblock_contacts(array($user2->id), $user3->id);
528         $this->assertDebuggingCalled();
529     }
531     /**
532      * Test getting contact requests.
533      */
534     public function test_get_contact_requests() {
535         $this->resetAfterTest();
537         $user1 = self::getDataGenerator()->create_user();
538         $user2 = self::getDataGenerator()->create_user();
539         $user3 = self::getDataGenerator()->create_user();
541         $this->setUser($user1);
543         // Block one user, their request should not show up.
544         \core_message\api::block_user($user1->id, $user3->id);
546         \core_message\api::create_contact_request($user2->id, $user1->id);
547         \core_message\api::create_contact_request($user3->id, $user1->id);
549         $requests = core_message_external::get_contact_requests($user1->id);
550         $requests = external_api::clean_returnvalue(core_message_external::get_contact_requests_returns(), $requests);
552         $this->assertCount(1, $requests);
554         $request = reset($requests);
556         $this->assertEquals($user2->id, $request['id']);
557         $this->assertEquals($user2->picture, $request['picture']);
558         $this->assertEquals($user2->firstname, $request['firstname']);
559         $this->assertEquals($user2->lastname, $request['lastname']);
560         $this->assertEquals($user2->firstnamephonetic, $request['firstnamephonetic']);
561         $this->assertEquals($user2->lastnamephonetic, $request['lastnamephonetic']);
562         $this->assertEquals($user2->middlename, $request['middlename']);
563         $this->assertEquals($user2->alternatename, $request['alternatename']);
564         $this->assertEquals($user2->email, $request['email']);
565     }
567     /**
568      * Test getting contact requests with messaging disabled.
569      */
570     public function test_get_contact_requests_messaging_disabled() {
571         global $CFG;
573         $this->resetAfterTest();
575         // Create some skeleton data just so we can call the WS.
576         $user1 = self::getDataGenerator()->create_user();
578         $this->setUser($user1);
580         // Disable messaging.
581         $CFG->messaging = 0;
583         // Ensure an exception is thrown.
584         $this->expectException('moodle_exception');
585         core_message_external::get_contact_requests($user1->id);
586     }
588     /**
589      * Test getting contact requests with no permission.
590      */
591     public function test_get_contact_requests_no_permission() {
592         $this->resetAfterTest();
594         // Create some skeleton data just so we can call the WS.
595         $user1 = self::getDataGenerator()->create_user();
596         $user2 = self::getDataGenerator()->create_user();
597         $user3 = self::getDataGenerator()->create_user();
599         $this->setUser($user3);
601         // Ensure an exception is thrown.
602         $this->expectException('required_capability_exception');
603         core_message_external::create_contact_request($user1->id, $user2->id);
604     }
606     /**
607      * Test creating a contact request.
608      */
609     public function test_create_contact_request() {
610         global $CFG, $DB;
612         $this->resetAfterTest();
614         $user1 = self::getDataGenerator()->create_user();
615         $user2 = self::getDataGenerator()->create_user();
617         $this->setUser($user1);
619         // Allow users to message anyone site-wide.
620         $CFG->messagingallusers = 1;
622         $return = core_message_external::create_contact_request($user1->id, $user2->id);
623         $return = external_api::clean_returnvalue(core_message_external::create_contact_request_returns(), $return);
624         $this->assertEquals(array(), $return);
626         $request = $DB->get_records('message_contact_requests');
628         $this->assertCount(1, $request);
630         $request = reset($request);
632         $this->assertEquals($user1->id, $request->userid);
633         $this->assertEquals($user2->id, $request->requesteduserid);
634     }
636     /**
637      * Test creating a contact request when not allowed.
638      */
639     public function test_create_contact_request_not_allowed() {
640         global $CFG;
642         $this->resetAfterTest();
644         $user1 = self::getDataGenerator()->create_user();
645         $user2 = self::getDataGenerator()->create_user();
647         $this->setUser($user1);
649         $CFG->messagingallusers = 0;
651         $return = core_message_external::create_contact_request($user1->id, $user2->id);
652         $return = external_api::clean_returnvalue(core_message_external::create_contact_request_returns(), $return);
654         $warning = reset($return);
656         $this->assertEquals('user', $warning['item']);
657         $this->assertEquals($user2->id, $warning['itemid']);
658         $this->assertEquals('cannotcreatecontactrequest', $warning['warningcode']);
659         $this->assertEquals('You are unable to create a contact request for this user', $warning['message']);
660     }
662     /**
663      * Test creating a contact request with messaging disabled.
664      */
665     public function test_create_contact_request_messaging_disabled() {
666         global $CFG;
668         $this->resetAfterTest();
670         // Create some skeleton data just so we can call the WS.
671         $user1 = self::getDataGenerator()->create_user();
672         $user2 = self::getDataGenerator()->create_user();
674         $this->setUser($user1);
676         // Disable messaging.
677         $CFG->messaging = 0;
679         // Ensure an exception is thrown.
680         $this->expectException('moodle_exception');
681         core_message_external::create_contact_request($user1->id, $user2->id);
682     }
684     /**
685      * Test creating a contact request with no permission.
686      */
687     public function test_create_contact_request_no_permission() {
688         $this->resetAfterTest();
690         // Create some skeleton data just so we can call the WS.
691         $user1 = self::getDataGenerator()->create_user();
692         $user2 = self::getDataGenerator()->create_user();
693         $user3 = self::getDataGenerator()->create_user();
695         $this->setUser($user3);
697         // Ensure an exception is thrown.
698         $this->expectException('required_capability_exception');
699         core_message_external::create_contact_request($user1->id, $user2->id);
700     }
702     /**
703      * Test confirming a contact request.
704      */
705     public function test_confirm_contact_request() {
706         global $DB;
708         $this->resetAfterTest();
710         $user1 = self::getDataGenerator()->create_user();
711         $user2 = self::getDataGenerator()->create_user();
713         $this->setUser($user1);
715         \core_message\api::create_contact_request($user1->id, $user2->id);
717         $this->setUser($user2);
719         $return = core_message_external::confirm_contact_request($user1->id, $user2->id);
720         $return = external_api::clean_returnvalue(core_message_external::confirm_contact_request_returns(), $return);
721         $this->assertEquals(array(), $return);
723         $this->assertEquals(0, $DB->count_records('message_contact_requests'));
725         $contact = $DB->get_records('message_contacts');
727         $this->assertCount(1, $contact);
729         $contact = reset($contact);
731         $this->assertEquals($user1->id, $contact->userid);
732         $this->assertEquals($user2->id, $contact->contactid);
733     }
735     /**
736      * Test confirming a contact request with messaging disabled.
737      */
738     public function test_confirm_contact_request_messaging_disabled() {
739         global $CFG;
741         $this->resetAfterTest();
743         // Create some skeleton data just so we can call the WS.
744         $user1 = self::getDataGenerator()->create_user();
745         $user2 = self::getDataGenerator()->create_user();
747         $this->setUser($user1);
749         // Disable messaging.
750         $CFG->messaging = 0;
752         // Ensure an exception is thrown.
753         $this->expectException('moodle_exception');
754         core_message_external::confirm_contact_request($user1->id, $user2->id);
755     }
757     /**
758      * Test confirming a contact request with no permission.
759      */
760     public function test_confirm_contact_request_no_permission() {
761         $this->resetAfterTest();
763         // Create some skeleton data just so we can call the WS.
764         $user1 = self::getDataGenerator()->create_user();
765         $user2 = self::getDataGenerator()->create_user();
766         $user3 = self::getDataGenerator()->create_user();
768         $this->setUser($user3);
770         // Ensure an exception is thrown.
771         $this->expectException('required_capability_exception');
772         core_message_external::confirm_contact_request($user1->id, $user2->id);
773     }
775     /**
776      * Test declining a contact request.
777      */
778     public function test_decline_contact_request() {
779         global $DB;
781         $this->resetAfterTest();
783         $user1 = self::getDataGenerator()->create_user();
784         $user2 = self::getDataGenerator()->create_user();
786         $this->setUser($user1);
788         \core_message\api::create_contact_request($user1->id, $user2->id);
790         $this->setUser($user2);
792         $return = core_message_external::decline_contact_request($user1->id, $user2->id);
793         $return = external_api::clean_returnvalue(core_message_external::decline_contact_request_returns(), $return);
794         $this->assertEquals(array(), $return);
796         $this->assertEquals(0, $DB->count_records('message_contact_requests'));
797         $this->assertEquals(0, $DB->count_records('message_contacts'));
798     }
800     /**
801      * Test declining a contact request with messaging disabled.
802      */
803     public function test_decline_contact_request_messaging_disabled() {
804         global $CFG;
806         $this->resetAfterTest();
808         // Create some skeleton data just so we can call the WS.
809         $user1 = self::getDataGenerator()->create_user();
810         $user2 = self::getDataGenerator()->create_user();
812         $this->setUser($user1);
814         // Disable messaging.
815         $CFG->messaging = 0;
817         // Ensure an exception is thrown.
818         $this->expectException('moodle_exception');
819         core_message_external::decline_contact_request($user1->id, $user2->id);
820     }
822     /**
823      * Test declining a contact request with no permission.
824      */
825     public function test_decline_contact_request_no_permission() {
826         $this->resetAfterTest();
828         // Create some skeleton data just so we can call the WS.
829         $user1 = self::getDataGenerator()->create_user();
830         $user2 = self::getDataGenerator()->create_user();
831         $user3 = self::getDataGenerator()->create_user();
833         $this->setUser($user3);
835         // Ensure an exception is thrown.
836         $this->expectException('required_capability_exception');
837         core_message_external::decline_contact_request($user1->id, $user2->id);
838     }
840     /**
841      * Test blocking a user.
842      */
843     public function test_block_user() {
844         global $DB;
846         $this->resetAfterTest(true);
848         $user1 = self::getDataGenerator()->create_user();
849         $user2 = self::getDataGenerator()->create_user();
851         $this->setUser($user1);
853         // Blocking a user.
854         $return = core_message_external::block_user($user1->id, $user2->id);
855         $return = external_api::clean_returnvalue(core_message_external::block_user_returns(), $return);
856         $this->assertEquals(array(), $return);
858         // Get list of blocked users.
859         $record = $DB->get_record('message_users_blocked', []);
861         $this->assertEquals($user1->id, $record->userid);
862         $this->assertEquals($user2->id, $record->blockeduserid);
864         // Blocking a user who is already blocked.
865         $return = core_message_external::block_user($user1->id, $user2->id);
866         $return = external_api::clean_returnvalue(core_message_external::block_user_returns(), $return);
867         $this->assertEquals(array(), $return);
869         $this->assertEquals(1, $DB->count_records('message_users_blocked'));
870     }
872     /**
873      * Test blocking a user with messaging disabled.
874      */
875     public function test_block_user_messaging_disabled() {
876         global $CFG;
878         $this->resetAfterTest();
880         // Create some skeleton data just so we can call the WS.
881         $user1 = self::getDataGenerator()->create_user();
882         $user2 = self::getDataGenerator()->create_user();
884         $this->setUser($user1);
886         // Disable messaging.
887         $CFG->messaging = 0;
889         // Ensure an exception is thrown.
890         $this->expectException('moodle_exception');
891         core_message_external::block_user($user1->id, $user2->id);
892     }
894     /**
895      * Test blocking a user with no permission.
896      */
897     public function test_block_user_no_permission() {
898         $this->resetAfterTest();
900         // Create some skeleton data just so we can call the WS.
901         $user1 = self::getDataGenerator()->create_user();
902         $user2 = self::getDataGenerator()->create_user();
903         $user3 = self::getDataGenerator()->create_user();
905         $this->setUser($user3);
907         // Ensure an exception is thrown.
908         $this->expectException('required_capability_exception');
909         core_message_external::block_user($user1->id, $user2->id);
910     }
912     /**
913      * Test unblocking a user.
914      */
915     public function test_unblock_user() {
916         global $DB;
918         $this->resetAfterTest(true);
920         $user1 = self::getDataGenerator()->create_user();
921         $user2 = self::getDataGenerator()->create_user();
923         $this->setUser($user1);
925         // Block the user.
926         \core_message\api::block_user($user1->id, $user2->id);
928         // Unblocking a user.
929         $return = core_message_external::unblock_user($user1->id, $user2->id);
930         $return = external_api::clean_returnvalue(core_message_external::unblock_user_returns(), $return);
931         $this->assertEquals(array(), $return);
933         $this->assertEquals(0, $DB->count_records('message_users_blocked'));
935         // Unblocking a user who is already unblocked.
936         $return = core_message_external::unblock_user($user1->id, $user2->id);
937         $return = external_api::clean_returnvalue(core_message_external::unblock_user_returns(), $return);
938         $this->assertEquals(array(), $return);
940         $this->assertEquals(0, $DB->count_records('message_users_blocked'));
941     }
943     /**
944      * Test unblocking a user with messaging disabled.
945      */
946     public function test_unblock_user_messaging_disabled() {
947         global $CFG;
949         $this->resetAfterTest();
951         // Create some skeleton data just so we can call the WS.
952         $user1 = self::getDataGenerator()->create_user();
953         $user2 = self::getDataGenerator()->create_user();
955         $this->setUser($user1);
957         // Disable messaging.
958         $CFG->messaging = 0;
960         // Ensure an exception is thrown.
961         $this->expectException('moodle_exception');
962         core_message_external::unblock_user($user1->id, $user2->id);
963     }
965     /**
966      * Test unblocking a user with no permission.
967      */
968     public function test_unblock_user_no_permission() {
969         $this->resetAfterTest();
971         // Create some skeleton data just so we can call the WS.
972         $user1 = self::getDataGenerator()->create_user();
973         $user2 = self::getDataGenerator()->create_user();
974         $user3 = self::getDataGenerator()->create_user();
976         $this->setUser($user3);
978         // Ensure an exception is thrown.
979         $this->expectException('required_capability_exception');
980         core_message_external::unblock_user($user1->id, $user2->id);
981     }
983     /**
984      * Test get_contacts.
985      */
986     public function test_get_contacts() {
987         $this->resetAfterTest(true);
989         $user1 = self::getDataGenerator()->create_user();
990         $user_stranger = self::getDataGenerator()->create_user();
991         $user_offline1 = self::getDataGenerator()->create_user();
992         $user_offline2 = self::getDataGenerator()->create_user();
993         $user_offline3 = self::getDataGenerator()->create_user();
994         $user_online = new stdClass();
995         $user_online->lastaccess = time();
996         $user_online = self::getDataGenerator()->create_user($user_online);
997         $user_blocked = self::getDataGenerator()->create_user();
998         $noreplyuser = core_user::get_user(core_user::NOREPLY_USER);
1000         // Login as user1.
1001         $this->setUser($user1);
1002         \core_message\api::add_contact($user1->id, $user_offline1->id);
1003         \core_message\api::add_contact($user1->id, $user_offline2->id);
1004         \core_message\api::add_contact($user1->id, $user_offline3->id);
1005         \core_message\api::add_contact($user1->id, $user_online->id);
1007         // User_stranger sends a couple of messages to user1.
1008         $this->send_message($user_stranger, $user1, 'Hello there!');
1009         $this->send_message($user_stranger, $user1, 'How you goin?');
1010         $this->send_message($user_stranger, $user1, 'Cya!');
1011         $this->send_message($noreplyuser, $user1, 'I am not a real user');
1013         // User_blocked sends a message to user1.
1014         $this->send_message($user_blocked, $user1, 'Here, have some spam.');
1016         // Retrieve the contacts of the user.
1017         $this->setUser($user1);
1018         $contacts = core_message_external::get_contacts();
1019         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1020         $this->assertCount(3, $contacts['offline']);
1021         $this->assertCount(1, $contacts['online']);
1022         $this->assertCount(3, $contacts['strangers']);
1023         core_message_external::block_contacts(array($user_blocked->id));
1024         $this->assertDebuggingCalled();
1025         $contacts = core_message_external::get_contacts();
1026         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1027         $this->assertCount(3, $contacts['offline']);
1028         $this->assertCount(1, $contacts['online']);
1029         $this->assertCount(2, $contacts['strangers']);
1031         // Checking some of the fields returned.
1032         $stranger = array_pop($contacts['strangers']);
1034         $this->assertEquals(core_user::NOREPLY_USER, $stranger['id']);
1035         $this->assertEquals(1, $stranger['unread']);
1037         // Check that deleted users are not returned.
1038         delete_user($user_offline1);
1039         delete_user($user_stranger);
1040         delete_user($user_online);
1041         $contacts = core_message_external::get_contacts();
1042         $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1043         $this->assertCount(2, $contacts['offline']);
1044         $this->assertCount(0, $contacts['online']);
1045         $this->assertCount(1, $contacts['strangers']);
1046     }
1048     /**
1049      * Test search_contacts.
1050      * @expectedException moodle_exception
1051      */
1052     public function test_search_contacts() {
1053         global $DB;
1054         $this->resetAfterTest(true);
1056         $course1 = $this->getDataGenerator()->create_course();
1057         $course2 = $this->getDataGenerator()->create_course();
1059         $user1 = new stdClass();
1060         $user1->firstname = 'X';
1061         $user1->lastname = 'X';
1062         $user1 = $this->getDataGenerator()->create_user($user1);
1063         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1064         $this->getDataGenerator()->enrol_user($user1->id, $course2->id);
1066         $user2 = new stdClass();
1067         $user2->firstname = 'Eric';
1068         $user2->lastname = 'Cartman';
1069         $user2 = self::getDataGenerator()->create_user($user2);
1070         $user3 = new stdClass();
1071         $user3->firstname = 'Stan';
1072         $user3->lastname = 'Marsh';
1073         $user3 = self::getDataGenerator()->create_user($user3);
1074         self::getDataGenerator()->enrol_user($user3->id, $course1->id);
1075         $user4 = new stdClass();
1076         $user4->firstname = 'Kyle';
1077         $user4->lastname = 'Broflovski';
1078         $user4 = self::getDataGenerator()->create_user($user4);
1079         $user5 = new stdClass();
1080         $user5->firstname = 'Kenny';
1081         $user5->lastname = 'McCormick';
1082         $user5 = self::getDataGenerator()->create_user($user5);
1083         self::getDataGenerator()->enrol_user($user5->id, $course2->id);
1085         $this->setUser($user1);
1087         $results = core_message_external::search_contacts('r');
1088         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1089         $this->assertCount(5, $results); // Users 2 through 5 + admin
1091         $results = core_message_external::search_contacts('r', true);
1092         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1093         $this->assertCount(2, $results);
1095         $results = core_message_external::search_contacts('Kyle', false);
1096         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1097         $this->assertCount(1, $results);
1098         $result = reset($results);
1099         $this->assertEquals($user4->id, $result['id']);
1101         $results = core_message_external::search_contacts('y', false);
1102         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1103         $this->assertCount(2, $results);
1105         $results = core_message_external::search_contacts('y', true);
1106         $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1107         $this->assertCount(1, $results);
1108         $result = reset($results);
1109         $this->assertEquals($user5->id, $result['id']);
1111         // Empty query, will throw an exception.
1112         $results = core_message_external::search_contacts('');
1113     }
1115     /**
1116      * Test get_messages.
1117      */
1118     public function test_get_messages() {
1119         global $CFG, $DB;
1120         $this->resetAfterTest(true);
1122         $this->preventResetByRollback();
1123         // This mark the messages as read!.
1124         $sink = $this->redirectMessages();
1126         $user1 = self::getDataGenerator()->create_user();
1127         $user2 = self::getDataGenerator()->create_user();
1128         $user3 = self::getDataGenerator()->create_user();
1130         $course = self::getDataGenerator()->create_course();
1132         // Send a message from one user to another.
1133         message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
1134         message_post_message($user1, $user3, 'some random text 2', FORMAT_MOODLE);
1135         message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
1136         message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
1137         message_post_message($user3, $user1, 'some random text 5', FORMAT_MOODLE);
1139         $this->setUser($user1);
1140         // Get read conversations from user1 to user2.
1141         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
1142         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1143         $this->assertCount(1, $messages['messages']);
1145         // Delete the message.
1146         $message = array_shift($messages['messages']);
1147         \core_message\api::delete_message($user1->id, $message['id']);
1149         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
1150         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1151         $this->assertCount(0, $messages['messages']);
1153         // Get unread conversations from user1 to user2.
1154         $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', false, true, 0, 0);
1155         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1156         $this->assertCount(0, $messages['messages']);
1158         // Get read messages send from user1.
1159         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1160         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1161         $this->assertCount(1, $messages['messages']);
1163         $this->setUser($user2);
1164         // Get read conversations from any user to user2.
1165         $messages = core_message_external::get_messages($user2->id, 0, 'conversations', true, true, 0, 0);
1166         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1167         $this->assertCount(2, $messages['messages']);
1169         // Conversations from user3 to user2.
1170         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
1171         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1172         $this->assertCount(1, $messages['messages']);
1174         // Delete the message.
1175         $message = array_shift($messages['messages']);
1176         \core_message\api::delete_message($user2->id, $message['id']);
1178         $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
1179         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1180         $this->assertCount(0, $messages['messages']);
1182         $this->setUser($user3);
1183         // Get read notifications received by user3.
1184         $messages = core_message_external::get_messages($user3->id, 0, 'notifications', true, true, 0, 0);
1185         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1186         $this->assertCount(0, $messages['messages']);
1188         // Now, create some notifications...
1189         // We are creating fake notifications but based on real ones.
1191         // This one comes from a disabled plugin's provider and therefore is not sent.
1192         $eventdata = new \core\message\message();
1193         $eventdata->courseid          = $course->id;
1194         $eventdata->notification      = 1;
1195         $eventdata->modulename        = 'moodle';
1196         $eventdata->component         = 'enrol_paypal';
1197         $eventdata->name              = 'paypal_enrolment';
1198         $eventdata->userfrom          = get_admin();
1199         $eventdata->userto            = $user1;
1200         $eventdata->subject           = "Moodle: PayPal payment";
1201         $eventdata->fullmessage       = "Your PayPal payment is pending.";
1202         $eventdata->fullmessageformat = FORMAT_PLAIN;
1203         $eventdata->fullmessagehtml   = '';
1204         $eventdata->smallmessage      = '';
1205         message_send($eventdata);
1206         $this->assertDebuggingCalled('Attempt to send msg from a provider enrol_paypal/paypal_enrolment '.
1207             'that is inactive or not allowed for the user id='.$user1->id);
1209         // This one omits notification = 1.
1210         $message = new \core\message\message();
1211         $message->courseid          = $course->id;
1212         $message->component         = 'enrol_manual';
1213         $message->name              = 'expiry_notification';
1214         $message->userfrom          = $user2;
1215         $message->userto            = $user1;
1216         $message->subject           = 'Test: This is not a notification but otherwise is valid';
1217         $message->fullmessage       = 'Test: Full message';
1218         $message->fullmessageformat = FORMAT_MARKDOWN;
1219         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
1220         $message->smallmessage      = $message->subject;
1221         $message->contexturlname    = $course->fullname;
1222         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
1223         message_send($message);
1225         $message = new \core\message\message();
1226         $message->courseid          = $course->id;
1227         $message->notification      = 1;
1228         $message->component         = 'enrol_manual';
1229         $message->name              = 'expiry_notification';
1230         $message->userfrom          = $user2;
1231         $message->userto            = $user1;
1232         $message->subject           = 'Enrolment expired';
1233         $message->fullmessage       = 'Enrolment expired blah blah blah';
1234         $message->fullmessageformat = FORMAT_MARKDOWN;
1235         $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
1236         $message->smallmessage      = $message->subject;
1237         $message->contexturlname    = $course->fullname;
1238         $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
1239         message_send($message);
1241         $userfrom = core_user::get_noreply_user();
1242         $userfrom->maildisplay = true;
1243         $eventdata = new \core\message\message();
1244         $eventdata->courseid          = $course->id;
1245         $eventdata->component         = 'moodle';
1246         $eventdata->name              = 'badgecreatornotice';
1247         $eventdata->userfrom          = $userfrom;
1248         $eventdata->userto            = $user1;
1249         $eventdata->notification      = 1;
1250         $eventdata->subject           = 'New badge';
1251         $eventdata->fullmessage       = format_text_email($eventdata->subject, FORMAT_HTML);
1252         $eventdata->fullmessageformat = FORMAT_PLAIN;
1253         $eventdata->fullmessagehtml   = $eventdata->subject;
1254         $eventdata->smallmessage      = $eventdata->subject;
1255         message_send($eventdata);
1257         $eventdata = new \core\message\message();
1258         $eventdata->courseid         = $course->id;
1259         $eventdata->name             = 'submission';
1260         $eventdata->component        = 'mod_feedback';
1261         $eventdata->userfrom         = $user1;
1262         $eventdata->userto           = $user2;
1263         $eventdata->subject          = 'Feedback submitted';
1264         $eventdata->fullmessage      = 'Feedback submitted from an user';
1265         $eventdata->fullmessageformat = FORMAT_PLAIN;
1266         $eventdata->fullmessagehtml  = '<strong>Feedback submitted</strong>';
1267         $eventdata->smallmessage     = '';
1268         message_send($eventdata);
1270         $this->setUser($user1);
1271         // Get read notifications from any user to user1.
1272         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 0);
1273         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1274         $this->assertCount(3, $messages['messages']);
1276         // Get one read notifications from any user to user1.
1277         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 1);
1278         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1279         $this->assertCount(1, $messages['messages']);
1281         // Get unread notifications from any user to user1.
1282         $messages = core_message_external::get_messages($user1->id, 0, 'notifications', false, true, 0, 0);
1283         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1284         $this->assertCount(0, $messages['messages']);
1286         // Get read both type of messages from any user to user1.
1287         $messages = core_message_external::get_messages($user1->id, 0, 'both', true, true, 0, 0);
1288         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1289         $this->assertCount(4, $messages['messages']);
1291         // Get read notifications from no-reply-user to user1.
1292         $messages = core_message_external::get_messages($user1->id, $userfrom->id, 'notifications', true, true, 0, 0);
1293         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1294         $this->assertCount(1, $messages['messages']);
1296         // Get notifications send by user1 to any user.
1297         $messages = core_message_external::get_messages(0, $user1->id, 'notifications', true, true, 0, 0);
1298         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1299         $this->assertCount(1, $messages['messages']);
1301         // Test warnings.
1302         $CFG->messaging = 0;
1304         $messages = core_message_external::get_messages(0, $user1->id, 'both', true, true, 0, 0);
1305         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1306         $this->assertCount(1, $messages['warnings']);
1308         // Test exceptions.
1310         // Messaging disabled.
1311         try {
1312             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1313             $this->fail('Exception expected due messaging disabled.');
1314         } catch (moodle_exception $e) {
1315             $this->assertEquals('disabled', $e->errorcode);
1316         }
1318         $CFG->messaging = 1;
1320         // Invalid users.
1321         try {
1322             $messages = core_message_external::get_messages(0, 0, 'conversations', true, true, 0, 0);
1323             $this->fail('Exception expected due invalid users.');
1324         } catch (moodle_exception $e) {
1325             $this->assertEquals('accessdenied', $e->errorcode);
1326         }
1328         // Invalid user ids.
1329         try {
1330             $messages = core_message_external::get_messages(2500, 0, 'conversations', true, true, 0, 0);
1331             $this->fail('Exception expected due invalid users.');
1332         } catch (moodle_exception $e) {
1333             $this->assertEquals('invaliduser', $e->errorcode);
1334         }
1336         // Invalid users (permissions).
1337         $this->setUser($user2);
1338         try {
1339             $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1340             $this->fail('Exception expected due invalid user.');
1341         } catch (moodle_exception $e) {
1342             $this->assertEquals('accessdenied', $e->errorcode);
1343         }
1345     }
1347     /**
1348      * Test get_messages where we want all messages from a user, sent to any user.
1349      */
1350     public function test_get_messages_useridto_all() {
1351         $this->resetAfterTest(true);
1353         $user1 = self::getDataGenerator()->create_user();
1354         $user2 = self::getDataGenerator()->create_user();
1355         $user3 = self::getDataGenerator()->create_user();
1357         $this->setUser($user1);
1359         // Send a message from user 1 to two other users.
1360         $this->send_message($user1, $user2, 'some random text 1', 0, 1);
1361         $this->send_message($user1, $user3, 'some random text 2', 0, 2);
1363         // Get messages sent from user 1.
1364         $messages = core_message_external::get_messages(0, $user1->id, 'conversations', false, false, 0, 0);
1365         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1367         // Confirm the data is correct.
1368         $messages = $messages['messages'];
1369         $this->assertCount(2, $messages);
1371         $message1 = array_shift($messages);
1372         $message2 = array_shift($messages);
1374         $this->assertEquals($user1->id, $message1['useridfrom']);
1375         $this->assertEquals($user2->id, $message1['useridto']);
1377         $this->assertEquals($user1->id, $message2['useridfrom']);
1378         $this->assertEquals($user3->id, $message2['useridto']);
1379     }
1381     /**
1382      * Test get_messages where we want all messages to a user, sent by any user.
1383      */
1384     public function test_get_messages_useridfrom_all() {
1385         $this->resetAfterTest();
1387         $user1 = self::getDataGenerator()->create_user();
1388         $user2 = self::getDataGenerator()->create_user();
1389         $user3 = self::getDataGenerator()->create_user();
1391         $this->setUser($user1);
1393         // Send a message to user 1 from two other users.
1394         $this->send_message($user2, $user1, 'some random text 1', 0, 1);
1395         $this->send_message($user3, $user1, 'some random text 2', 0, 2);
1397         // Get messages sent to user 1.
1398         $messages = core_message_external::get_messages($user1->id, 0, 'conversations', false, false, 0, 0);
1399         $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1401         // Confirm the data is correct.
1402         $messages = $messages['messages'];
1403         $this->assertCount(2, $messages);
1405         $message1 = array_shift($messages);
1406         $message2 = array_shift($messages);
1408         $this->assertEquals($user2->id, $message1['useridfrom']);
1409         $this->assertEquals($user1->id, $message1['useridto']);
1411         $this->assertEquals($user3->id, $message2['useridfrom']);
1412         $this->assertEquals($user1->id, $message2['useridto']);
1413     }
1415     /**
1416      * Test get_blocked_users.
1417      */
1418     public function test_get_blocked_users() {
1419         $this->resetAfterTest(true);
1421         $user1 = self::getDataGenerator()->create_user();
1422         $userstranger = self::getDataGenerator()->create_user();
1423         $useroffline1 = self::getDataGenerator()->create_user();
1424         $useroffline2 = self::getDataGenerator()->create_user();
1425         $userblocked = self::getDataGenerator()->create_user();
1427         // Login as user1.
1428         $this->setUser($user1);
1430         \core_message\api::add_contact($user1->id, $useroffline1->id);
1431         \core_message\api::add_contact($user1->id, $useroffline2->id);
1433         // The userstranger sends a couple of messages to user1.
1434         $this->send_message($userstranger, $user1, 'Hello there!');
1435         $this->send_message($userstranger, $user1, 'How you goin?');
1437         // The userblocked sends a message to user1.
1438         // Note that this user is not blocked at this point.
1439         $this->send_message($userblocked, $user1, 'Here, have some spam.');
1441         // Retrieve the list of blocked users.
1442         $this->setUser($user1);
1443         $blockedusers = core_message_external::get_blocked_users($user1->id);
1444         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1445         $this->assertCount(0, $blockedusers['users']);
1447         // Block the $userblocked and retrieve again the list.
1448         core_message_external::block_contacts(array($userblocked->id));
1449         $this->assertDebuggingCalled();
1450         $blockedusers = core_message_external::get_blocked_users($user1->id);
1451         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1452         $this->assertCount(1, $blockedusers['users']);
1454         // Remove the $userblocked and check that the list now is empty.
1455         delete_user($userblocked);
1456         $blockedusers = core_message_external::get_blocked_users($user1->id);
1457         $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1458         $this->assertCount(0, $blockedusers['users']);
1459     }
1461     /**
1462      * Test mark_message_read.
1463      */
1464     public function test_mark_message_read() {
1465         $this->resetAfterTest(true);
1467         $user1 = self::getDataGenerator()->create_user();
1468         $user2 = self::getDataGenerator()->create_user();
1469         $user3 = self::getDataGenerator()->create_user();
1471         // Login as user1.
1472         $this->setUser($user1);
1473         \core_message\api::add_contact($user1->id, $user2->id);
1474         \core_message\api::add_contact($user1->id, $user3->id);
1476         // The user2 sends a couple of messages to user1.
1477         $this->send_message($user2, $user1, 'Hello there!');
1478         $this->send_message($user2, $user1, 'How you goin?');
1479         $this->send_message($user3, $user1, 'How you goin?');
1480         $this->send_message($user3, $user2, 'How you goin?');
1482         // Retrieve all messages sent by user2 (they are currently unread).
1483         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
1485         $messageids = array();
1486         foreach ($lastmessages as $m) {
1487             $messageid = core_message_external::mark_message_read($m->id, time());
1488             $messageids[] = external_api::clean_returnvalue(core_message_external::mark_message_read_returns(), $messageid);
1489         }
1491         // Retrieve all messages sent (they are currently read).
1492         $lastmessages = message_get_messages($user1->id, $user2->id, 0, true);
1493         $this->assertCount(2, $lastmessages);
1494         $this->assertArrayHasKey($messageids[0]['messageid'], $lastmessages);
1495         $this->assertArrayHasKey($messageids[1]['messageid'], $lastmessages);
1497         // Retrieve all messages sent by any user (that are currently unread).
1498         $lastmessages = message_get_messages($user1->id, 0, 0, false);
1499         $this->assertCount(1, $lastmessages);
1501         // Invalid message ids.
1502         try {
1503             $messageid = core_message_external::mark_message_read(1337, time());
1504             $this->fail('Exception expected due invalid messageid.');
1505         } catch (dml_missing_record_exception $e) {
1506             $this->assertEquals('invalidrecordunknown', $e->errorcode);
1507         }
1509         // A message to a different user.
1510         $lastmessages = message_get_messages($user2->id, $user3->id, 0, false);
1511         $messageid = array_pop($lastmessages)->id;
1512         try {
1513             $messageid = core_message_external::mark_message_read($messageid, time());
1514             $this->fail('Exception expected due invalid messageid.');
1515         } catch (invalid_parameter_exception $e) {
1516             $this->assertEquals('invalidparameter', $e->errorcode);
1517         }
1518     }
1520     /**
1521      * Test mark_notification_read.
1522      */
1523     public function test_mark_notification_read() {
1524         $this->resetAfterTest(true);
1526         $user1 = self::getDataGenerator()->create_user();
1527         $user2 = self::getDataGenerator()->create_user();
1528         $user3 = self::getDataGenerator()->create_user();
1530         // Login as user1.
1531         $this->setUser($user1);
1532         \core_message\api::add_contact($user1->id, $user2->id);
1533         \core_message\api::add_contact($user1->id, $user3->id);
1535         // The user2 sends a couple of notifications to user1.
1536         $this->send_message($user2, $user1, 'Hello there!', 1);
1537         $this->send_message($user2, $user1, 'How you goin?', 1);
1538         $this->send_message($user3, $user1, 'How you goin?', 1);
1539         $this->send_message($user3, $user2, 'How you goin?', 1);
1541         // Retrieve all notifications sent by user2 (they are currently unread).
1542         $lastnotifications = message_get_messages($user1->id, $user2->id, 1, false);
1544         $notificationids = array();
1545         foreach ($lastnotifications as $n) {
1546             $notificationid = core_message_external::mark_notification_read($n->id, time());
1547             $notificationids[] = external_api::clean_returnvalue(core_message_external::mark_notification_read_returns(),
1548                 $notificationid);
1549         }
1551         // Retrieve all notifications sent (they are currently read).
1552         $lastnotifications = message_get_messages($user1->id, $user2->id, 1, true);
1553         $this->assertCount(2, $lastnotifications);
1554         $this->assertArrayHasKey($notificationids[1]['notificationid'], $lastnotifications);
1555         $this->assertArrayHasKey($notificationids[0]['notificationid'], $lastnotifications);
1557         // Retrieve all notifications sent by any user (that are currently unread).
1558         $lastnotifications = message_get_messages($user1->id, 0, 1, false);
1559         $this->assertCount(1, $lastnotifications);
1561         // Invalid notification ids.
1562         try {
1563             $notificationid = core_message_external::mark_notification_read(1337, time());
1564             $this->fail('Exception expected due invalid notificationid.');
1565         } catch (dml_missing_record_exception $e) {
1566             $this->assertEquals('invalidrecord', $e->errorcode);
1567         }
1569         // A notification to a different user.
1570         $lastnotifications = message_get_messages($user2->id, $user3->id, 1, false);
1571         $notificationid = array_pop($lastnotifications)->id;
1572         try {
1573             $notificationid = core_message_external::mark_notification_read($notificationid, time());
1574             $this->fail('Exception expected due invalid notificationid.');
1575         } catch (invalid_parameter_exception $e) {
1576             $this->assertEquals('invalidparameter', $e->errorcode);
1577         }
1578     }
1580     /**
1581      * Test delete_message.
1582      */
1583     public function test_delete_message() {
1584         global $DB;
1585         $this->resetAfterTest(true);
1587         $user1 = self::getDataGenerator()->create_user();
1588         $user2 = self::getDataGenerator()->create_user();
1589         $user3 = self::getDataGenerator()->create_user();
1590         $user4 = self::getDataGenerator()->create_user();
1592         // Login as user1.
1593         $this->setUser($user1);
1594         \core_message\api::add_contact($user1->id, $user2->id);
1595         \core_message\api::add_contact($user1->id, $user3->id);
1597         // User user1 does not interchange messages with user3.
1598         $m1to2 = message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
1599         $m2to3 = message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
1600         $m3to2 = message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
1601         $m3to4 = message_post_message($user3, $user4, 'some random text 4', FORMAT_MOODLE);
1603         // Retrieve all messages sent by user2 (they are currently unread).
1604         $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
1606         // Delete a message not read, as a user from.
1607         $result = core_message_external::delete_message($m1to2, $user1->id, false);
1608         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1609         $this->assertTrue($result['status']);
1610         $this->assertCount(0, $result['warnings']);
1611         $mua = $DB->get_record('message_user_actions', array('messageid' => $m1to2, 'userid' => $user1->id));
1612         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua->action);
1614         // Try to delete the same message again.
1615         $result = core_message_external::delete_message($m1to2, $user1->id, false);
1616         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1617         $this->assertFalse($result['status']);
1619         // Try to delete a message that does not belong to me.
1620         try {
1621             $messageid = core_message_external::delete_message($m2to3, $user3->id, false);
1622             $this->fail('Exception expected due invalid messageid.');
1623         } catch (moodle_exception $e) {
1624             $this->assertEquals('You do not have permission to delete this message', $e->errorcode);
1625         }
1627         $this->setUser($user3);
1628         // Delete a message not read, as a user to.
1629         $result = core_message_external::delete_message($m2to3, $user3->id, false);
1630         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1631         $this->assertTrue($result['status']);
1632         $this->assertCount(0, $result['warnings']);
1633         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m2to3, 'userid' => $user3->id,
1634             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1636         // Delete a message read.
1637         $message = $DB->get_record('messages', ['id' => $m3to2]);
1638         \core_message\api::mark_message_as_read($user3->id, $message, time());
1639         $result = core_message_external::delete_message($m3to2, $user3->id);
1640         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1641         $this->assertTrue($result['status']);
1642         $this->assertCount(0, $result['warnings']);
1643         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to2, 'userid' => $user3->id,
1644             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1646         // Invalid message ids.
1647         try {
1648             $result = core_message_external::delete_message(-1, $user1->id);
1649             $this->fail('Exception expected due invalid messageid.');
1650         } catch (dml_missing_record_exception $e) {
1651             $this->assertEquals('invalidrecord', $e->errorcode);
1652         }
1654         // Invalid user.
1655         try {
1656             $result = core_message_external::delete_message($m1to2, -1, false);
1657             $this->fail('Exception expected due invalid user.');
1658         } catch (moodle_exception $e) {
1659             $this->assertEquals('invaliduser', $e->errorcode);
1660         }
1662         // Not active user.
1663         delete_user($user2);
1664         try {
1665             $result = core_message_external::delete_message($m1to2, $user2->id, false);
1666             $this->fail('Exception expected due invalid user.');
1667         } catch (moodle_exception $e) {
1668             $this->assertEquals('userdeleted', $e->errorcode);
1669         }
1671         // Now, as an admin, try to delete any message.
1672         $this->setAdminUser();
1673         $result = core_message_external::delete_message($m3to4, $user4->id, false);
1674         $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1675         $this->assertTrue($result['status']);
1676         $this->assertCount(0, $result['warnings']);
1677         $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to4, 'userid' => $user4->id,
1678             'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
1680     }
1682     public function test_mark_all_notifications_as_read_invalid_user_exception() {
1683         $this->resetAfterTest(true);
1685         $this->expectException('moodle_exception');
1686         core_message_external::mark_all_notifications_as_read(-2132131, 0);
1687     }
1689     public function test_mark_all_notifications_as_read_access_denied_exception() {
1690         $this->resetAfterTest(true);
1692         $sender = $this->getDataGenerator()->create_user();
1693         $user = $this->getDataGenerator()->create_user();
1695         $this->setUser($user);
1696         $this->expectException('moodle_exception');
1697         core_message_external::mark_all_notifications_as_read($sender->id, 0);
1698     }
1700     public function test_mark_all_notifications_as_read_missing_from_user_exception() {
1701         $this->resetAfterTest(true);
1703         $sender = $this->getDataGenerator()->create_user();
1705         $this->setUser($sender);
1706         $this->expectException('moodle_exception');
1707         core_message_external::mark_all_notifications_as_read($sender->id, 99999);
1708     }
1710     public function test_mark_all_notifications_as_read() {
1711         global $DB;
1713         $this->resetAfterTest(true);
1715         $sender1 = $this->getDataGenerator()->create_user();
1716         $sender2 = $this->getDataGenerator()->create_user();
1717         $sender3 = $this->getDataGenerator()->create_user();
1718         $recipient = $this->getDataGenerator()->create_user();
1720         $this->setUser($recipient);
1722         $this->send_message($sender1, $recipient, 'Notification', 1);
1723         $this->send_message($sender1, $recipient, 'Notification', 1);
1724         $this->send_message($sender2, $recipient, 'Notification', 1);
1725         $this->send_message($sender2, $recipient, 'Notification', 1);
1726         $this->send_message($sender3, $recipient, 'Notification', 1);
1727         $this->send_message($sender3, $recipient, 'Notification', 1);
1729         core_message_external::mark_all_notifications_as_read($recipient->id, $sender1->id);
1730         $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1731         $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
1733         $this->assertCount(2, $readnotifications);
1734         $this->assertCount(4, $unreadnotifications);
1736         core_message_external::mark_all_notifications_as_read($recipient->id, 0);
1737         $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1738         $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
1740         $this->assertCount(6, $readnotifications);
1741         $this->assertCount(0, $unreadnotifications);
1742     }
1744     /**
1745      * Test get_user_notification_preferences
1746      */
1747     public function test_get_user_notification_preferences() {
1748         $this->resetAfterTest(true);
1750         $user = self::getDataGenerator()->create_user();
1751         $this->setUser($user);
1753         // Set a couple of preferences to test.
1754         set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
1755         set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
1757         $prefs = core_message_external::get_user_notification_preferences();
1758         $prefs = external_api::clean_returnvalue(core_message_external::get_user_notification_preferences_returns(), $prefs);
1759         // Check processors.
1760         $this->assertGreaterThanOrEqual(2, count($prefs['preferences']['processors']));
1761         $this->assertEquals($user->id, $prefs['preferences']['userid']);
1763         // Check components.
1764         $this->assertGreaterThanOrEqual(8, count($prefs['preferences']['components']));
1766         // Check some preferences that we previously set.
1767         $found = 0;
1768         foreach ($prefs['preferences']['components'] as $component) {
1769             foreach ($component['notifications'] as $prefdata) {
1770                 if ($prefdata['preferencekey'] != 'message_provider_mod_assign_assign_notification') {
1771                     continue;
1772                 }
1773                 foreach ($prefdata['processors'] as $processor) {
1774                     if ($processor['name'] == 'popup') {
1775                         $this->assertTrue($processor['loggedin']['checked']);
1776                         $found++;
1777                     } else if ($processor['name'] == 'email') {
1778                         $this->assertTrue($processor['loggedoff']['checked']);
1779                         $found++;
1780                     }
1781                 }
1782             }
1783         }
1784         $this->assertEquals(2, $found);
1785     }
1787     /**
1788      * Test get_user_notification_preferences permissions
1789      */
1790     public function test_get_user_notification_preferences_permissions() {
1791         $this->resetAfterTest(true);
1793         $user = self::getDataGenerator()->create_user();
1794         $otheruser = self::getDataGenerator()->create_user();
1795         $this->setUser($user);
1797         $this->expectException('moodle_exception');
1798         $prefs = core_message_external::get_user_notification_preferences($otheruser->id);
1799     }
1801     /**
1802      * Tests searching users in a course.
1803      */
1804     public function test_messagearea_search_users_in_course() {
1805         $this->resetAfterTest(true);
1807         // Create some users.
1808         $user1 = new stdClass();
1809         $user1->firstname = 'User';
1810         $user1->lastname = 'One';
1811         $user1 = self::getDataGenerator()->create_user($user1);
1813         // The person doing the search.
1814         $this->setUser($user1);
1816         // Set the second user's status to online by setting their last access to now.
1817         $user2 = new stdClass();
1818         $user2->firstname = 'User';
1819         $user2->lastname = 'Two';
1820         $user2->lastaccess = time();
1821         $user2 = self::getDataGenerator()->create_user($user2);
1823         // Block the second user.
1824         \core_message\api::block_user($user1->id, $user2->id);
1826         $user3 = new stdClass();
1827         $user3->firstname = 'User';
1828         $user3->lastname = 'Three';
1829         $user3 = self::getDataGenerator()->create_user($user3);
1831         // Create a course.
1832         $course1 = new stdClass();
1833         $course1->fullname = 'Course';
1834         $course1->shortname = 'One';
1835         $course1 = $this->getDataGenerator()->create_course();
1837         // Enrol the user we are doing the search for and one user in the course.
1838         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1839         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1841         // Perform a search.
1842         $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
1844         // We need to execute the return values cleaning process to simulate the web service.
1845         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
1846             $result);
1848         // Check that we only retrieved a user that was enrolled, and that the user performing the search was not returned.
1849         $users = $result['contacts'];
1850         $this->assertCount(1, $users);
1852         $user = $users[0];
1853         $this->assertEquals($user2->id, $user['userid']);
1854         $this->assertEquals(fullname($user2), $user['fullname']);
1855         $this->assertFalse($user['ismessaging']);
1856         $this->assertFalse($user['sentfromcurrentuser']);
1857         $this->assertNull($user['lastmessage']);
1858         $this->assertNull($user['messageid']);
1859         $this->assertNull($user['isonline']);
1860         $this->assertFalse($user['isread']);
1861         $this->assertTrue($user['isblocked']);
1862         $this->assertNull($user['unreadcount']);
1863     }
1865     /**
1866      * Tests searching users in course as another user.
1867      */
1868     public function test_messagearea_search_users_in_course_as_other_user() {
1869         $this->resetAfterTest(true);
1871         // The person doing the search for another user.
1872         $this->setAdminUser();
1874         // Create some users.
1875         $user1 = new stdClass();
1876         $user1->firstname = 'User';
1877         $user1->lastname = 'One';
1878         $user1 = self::getDataGenerator()->create_user($user1);
1880         $user2 = new stdClass();
1881         $user2->firstname = 'User';
1882         $user2->lastname = 'Two';
1883         $user2 = self::getDataGenerator()->create_user($user2);
1885         $user3 = new stdClass();
1886         $user3->firstname = 'User';
1887         $user3->lastname = 'Three';
1888         $user3 = self::getDataGenerator()->create_user($user3);
1890         // Create a course.
1891         $course1 = new stdClass();
1892         $course1->fullname = 'Course';
1893         $course1->shortname = 'One';
1894         $course1 = $this->getDataGenerator()->create_course();
1896         // Enrol the user we are doing the search for and one user in the course.
1897         $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1898         $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
1900         // Perform a search.
1901         $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
1903         // We need to execute the return values cleaning process to simulate the web service server.
1904         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
1905             $result);
1907         // Check that we got the user enrolled, and that the user we are performing the search on behalf of was not returned.
1908         $users = $result['contacts'];
1909         $this->assertCount(1, $users);
1911         $user = $users[0];
1912         $this->assertEquals($user2->id, $user['userid']);
1913         $this->assertEquals(fullname($user2), $user['fullname']);
1914         $this->assertFalse($user['ismessaging']);
1915         $this->assertFalse($user['sentfromcurrentuser']);
1916         $this->assertNull($user['lastmessage']);
1917         $this->assertNull($user['messageid']);
1918         $this->assertFalse($user['isonline']);
1919         $this->assertFalse($user['isread']);
1920         $this->assertFalse($user['isblocked']);
1921         $this->assertNull($user['unreadcount']);
1922     }
1924     /**
1925      * Tests searching users in course as another user without the proper capabilities.
1926      */
1927     public function test_messagearea_search_users_in_course_as_other_user_without_cap() {
1928         $this->resetAfterTest(true);
1930         // Create some users.
1931         $user1 = self::getDataGenerator()->create_user();
1932         $user2 = self::getDataGenerator()->create_user();
1934         // The person doing the search for another user.
1935         $this->setUser($user1);
1937         // Create a course.
1938         $course = $this->getDataGenerator()->create_course();
1940         // Ensure an exception is thrown.
1941         $this->expectException('moodle_exception');
1942         core_message_external::data_for_messagearea_search_users_in_course($user2->id, $course->id, 'User');
1943     }
1945     /**
1946      * Tests searching users in course with messaging disabled.
1947      */
1948     public function test_messagearea_search_users_in_course_messaging_disabled() {
1949         global $CFG;
1951         $this->resetAfterTest(true);
1953         // Create some skeleton data just so we can call the WS..
1954         $user = self::getDataGenerator()->create_user();
1955         $course = $this->getDataGenerator()->create_course();
1957         // The person doing the search for another user.
1958         $this->setUser($user);
1960         // Disable messaging.
1961         $CFG->messaging = 0;
1963         // Ensure an exception is thrown.
1964         $this->expectException('moodle_exception');
1965         core_message_external::data_for_messagearea_search_users_in_course($user->id, $course->id, 'User');
1966     }
1968     /**
1969      * Tests searching users.
1970      */
1971     public function test_messagearea_search_users() {
1972         $this->resetAfterTest(true);
1974         // Create some users.
1975         $user1 = new stdClass();
1976         $user1->firstname = 'User';
1977         $user1->lastname = 'One';
1978         $user1 = self::getDataGenerator()->create_user($user1);
1980         // Set as the user performing the search.
1981         $this->setUser($user1);
1983         $user2 = new stdClass();
1984         $user2->firstname = 'User search';
1985         $user2->lastname = 'Two';
1986         $user2 = self::getDataGenerator()->create_user($user2);
1988         $user3 = new stdClass();
1989         $user3->firstname = 'User search';
1990         $user3->lastname = 'Three';
1991         $user3 = self::getDataGenerator()->create_user($user3);
1993         $user4 = new stdClass();
1994         $user4->firstname = 'User';
1995         $user4->lastname = 'Four';
1996         $user4 = self::getDataGenerator()->create_user($user4);
1998         $user5 = new stdClass();
1999         $user5->firstname = 'User search';
2000         $user5->lastname = 'Five';
2001         $user5 = self::getDataGenerator()->create_user($user5);
2003         $user6 = new stdClass();
2004         $user6->firstname = 'User';
2005         $user6->lastname = 'Six';
2006         $user6 = self::getDataGenerator()->create_user($user6);
2008         // Create some courses.
2009         $course1 = new stdClass();
2010         $course1->fullname = 'Course search';
2011         $course1->shortname = 'One';
2012         $course1 = $this->getDataGenerator()->create_course($course1);
2014         $course2 = new stdClass();
2015         $course2->fullname = 'Course';
2016         $course2->shortname = 'Two';
2017         $course2 = $this->getDataGenerator()->create_course($course2);
2019         $course3 = new stdClass();
2020         $course3->fullname = 'Course';
2021         $course3->shortname = 'Three search';
2022         $course3 = $this->getDataGenerator()->create_course($course3);
2024         $course4 = new stdClass();
2025         $course4->fullname = 'Course Four';
2026         $course4->shortname = 'CF100';
2027         $course4 = $this->getDataGenerator()->create_course($course4);
2029         $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'student');
2030         $this->getDataGenerator()->enrol_user($user1->id, $course2->id, 'student');
2031         $this->getDataGenerator()->enrol_user($user1->id, $course3->id, 'student');
2033         // Add some users as contacts.
2034         \core_message\api::add_contact($user1->id, $user2->id);
2035         \core_message\api::add_contact($user1->id, $user3->id);
2036         \core_message\api::add_contact($user1->id, $user4->id);
2038         // Perform a search.
2039         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
2041         // We need to execute the return values cleaning process to simulate the web service server.
2042         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
2043             $result);
2045         // Confirm that we returns contacts, courses and non-contacts.
2046         $contacts = $result['contacts'];
2047         $courses = $result['courses'];
2048         $noncontacts = $result['noncontacts'];
2050         // Check that we retrieved the correct contacts.
2051         $this->assertCount(2, $contacts);
2052         $this->assertEquals($user3->id, $contacts[0]['userid']);
2053         $this->assertEquals($user2->id, $contacts[1]['userid']);
2055         // Check that we retrieved the correct courses.
2056         $this->assertCount(2, $courses);
2057         $this->assertEquals($course3->id, $courses[0]['id']);
2058         $this->assertEquals($course1->id, $courses[1]['id']);
2060         // Check that we retrieved the correct non-contacts.
2061         $this->assertCount(1, $noncontacts);
2062         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
2063     }
2065     /**
2066      * Tests searching users as another user.
2067      */
2068     public function test_messagearea_search_users_as_other_user() {
2069         $this->resetAfterTest(true);
2071         // The person doing the search.
2072         $this->setAdminUser();
2074         // Create some users.
2075         $user1 = new stdClass();
2076         $user1->firstname = 'User';
2077         $user1->lastname = 'One';
2078         $user1 = self::getDataGenerator()->create_user($user1);
2080         $user2 = new stdClass();
2081         $user2->firstname = 'User search';
2082         $user2->lastname = 'Two';
2083         $user2 = self::getDataGenerator()->create_user($user2);
2085         $user3 = new stdClass();
2086         $user3->firstname = 'User search';
2087         $user3->lastname = 'Three';
2088         $user3 = self::getDataGenerator()->create_user($user3);
2090         $user4 = new stdClass();
2091         $user4->firstname = 'User';
2092         $user4->lastname = 'Four';
2093         $user4 = self::getDataGenerator()->create_user($user4);
2095         $user5 = new stdClass();
2096         $user5->firstname = 'User search';
2097         $user5->lastname = 'Five';
2098         $user5 = self::getDataGenerator()->create_user($user5);
2100         $user6 = new stdClass();
2101         $user6->firstname = 'User';
2102         $user6->lastname = 'Six';
2103         $user6 = self::getDataGenerator()->create_user($user6);
2105         // Create some courses.
2106         $course1 = new stdClass();
2107         $course1->fullname = 'Course search';
2108         $course1->shortname = 'One';
2109         $course1 = $this->getDataGenerator()->create_course($course1);
2111         $course2 = new stdClass();
2112         $course2->fullname = 'Course';
2113         $course2->shortname = 'Two';
2114         $course2 = $this->getDataGenerator()->create_course($course2);
2116         $course3 = new stdClass();
2117         $course3->fullname = 'Course';
2118         $course3->shortname = 'Three search';
2119         $course3 = $this->getDataGenerator()->create_course($course3);
2121         // Add some users as contacts.
2122         \core_message\api::add_contact($user1->id, $user2->id);
2123         \core_message\api::add_contact($user1->id, $user3->id);
2124         \core_message\api::add_contact($user1->id, $user4->id);
2126         // Perform a search.
2127         $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
2129         // We need to execute the return values cleaning process to simulate the web service server.
2130         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
2131             $result);
2133         // Confirm that we returns contacts, courses and non-contacts.
2134         $contacts = $result['contacts'];
2135         $courses = $result['courses'];
2136         $noncontacts = $result['noncontacts'];
2138         // Check that we retrieved the correct contacts.
2139         $this->assertCount(2, $contacts);
2140         $this->assertEquals($user3->id, $contacts[0]['userid']);
2141         $this->assertEquals($user2->id, $contacts[1]['userid']);
2143         // Check that we retrieved the correct courses.
2144         $this->assertCount(0, $courses);
2146         // Check that we retrieved the correct non-contacts.
2147         $this->assertCount(1, $noncontacts);
2148         $this->assertEquals($user5->id, $noncontacts[0]['userid']);
2149     }
2151     /**
2152      * Tests searching users as another user without the proper capabilities.
2153      */
2154     public function test_messagearea_search_users_as_other_user_without_cap() {
2155         $this->resetAfterTest(true);
2157         // Create some users.
2158         $user1 = self::getDataGenerator()->create_user();
2159         $user2 = self::getDataGenerator()->create_user();
2161         // The person doing the search for another user.
2162         $this->setUser($user1);
2164         // Ensure an exception is thrown.
2165         $this->expectException('moodle_exception');
2166         core_message_external::data_for_messagearea_search_users($user2->id, 'User');
2167     }
2169     /**
2170      * Tests searching users with messaging disabled.
2171      */
2172     public function test_messagearea_search_users_messaging_disabled() {
2173         global $CFG;
2175         $this->resetAfterTest(true);
2177         // Create some skeleton data just so we can call the WS.
2178         $user = self::getDataGenerator()->create_user();
2180         // The person doing the search.
2181         $this->setUser($user);
2183         // Disable messaging.
2184         $CFG->messaging = 0;
2186         // Ensure an exception is thrown.
2187         $this->expectException('moodle_exception');
2188         core_message_external::data_for_messagearea_search_users($user->id, 'User');
2189     }
2191     /**
2192      * Tests searching messages.
2193      */
2194     public function test_messagearea_search_messages() {
2195         $this->resetAfterTest(true);
2197         // Create some users.
2198         $user1 = self::getDataGenerator()->create_user();
2199         $user2 = self::getDataGenerator()->create_user();
2201         // The person doing the search.
2202         $this->setUser($user1);
2204         // Send some messages back and forth.
2205         $time = time();
2206         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2207         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2208         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2209         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2211         // Perform a search.
2212         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2214         // We need to execute the return values cleaning process to simulate the web service server.
2215         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
2216             $result);
2218         // Confirm the data is correct.
2219         $messages = $result['contacts'];
2220         $this->assertCount(2, $messages);
2222         $message1 = $messages[0];
2223         $message2 = $messages[1];
2225         $this->assertEquals($user2->id, $message1['userid']);
2226         $this->assertEquals(fullname($user2), $message1['fullname']);
2227         $this->assertTrue($message1['ismessaging']);
2228         $this->assertFalse($message1['sentfromcurrentuser']);
2229         $this->assertEquals('Word.', $message1['lastmessage']);
2230         $this->assertNotEmpty($message1['messageid']);
2231         $this->assertNull($message1['isonline']);
2232         $this->assertFalse($message1['isread']);
2233         $this->assertFalse($message1['isblocked']);
2234         $this->assertNull($message1['unreadcount']);
2236         $this->assertEquals($user2->id, $message2['userid']);
2237         $this->assertEquals(fullname($user2), $message2['fullname']);
2238         $this->assertTrue($message2['ismessaging']);
2239         $this->assertTrue($message2['sentfromcurrentuser']);
2240         $this->assertEquals('Yo!', $message2['lastmessage']);
2241         $this->assertNotEmpty($message2['messageid']);
2242         $this->assertNull($message2['isonline']);
2243         $this->assertTrue($message2['isread']);
2244         $this->assertFalse($message2['isblocked']);
2245         $this->assertNull($message2['unreadcount']);
2246     }
2248     /**
2249      * Tests searching messages as another user.
2250      */
2251     public function test_messagearea_search_messages_as_other_user() {
2252         $this->resetAfterTest(true);
2254         // The person doing the search.
2255         $this->setAdminUser();
2257         // Create some users.
2258         $user1 = self::getDataGenerator()->create_user();
2259         $user2 = self::getDataGenerator()->create_user();
2261         // Send some messages back and forth.
2262         $time = time();
2263         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2264         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2265         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2266         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2268         // Perform a search.
2269         $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2271         // We need to execute the return values cleaning process to simulate the web service server.
2272         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
2273             $result);
2275         // Confirm the data is correct.
2276         $messages = $result['contacts'];
2277         $this->assertCount(2, $messages);
2279         $message1 = $messages[0];
2280         $message2 = $messages[1];
2282         $this->assertEquals($user2->id, $message1['userid']);
2283         $this->assertEquals(fullname($user2), $message1['fullname']);
2284         $this->assertTrue($message1['ismessaging']);
2285         $this->assertFalse($message1['sentfromcurrentuser']);
2286         $this->assertEquals('Word.', $message1['lastmessage']);
2287         $this->assertNotEmpty($message1['messageid']);
2288         $this->assertFalse($message1['isonline']);
2289         $this->assertFalse($message1['isread']);
2290         $this->assertFalse($message1['isblocked']);
2291         $this->assertNull($message1['unreadcount']);
2293         $this->assertEquals($user2->id, $message2['userid']);
2294         $this->assertEquals(fullname($user2), $message2['fullname']);
2295         $this->assertTrue($message2['ismessaging']);
2296         $this->assertTrue($message2['sentfromcurrentuser']);
2297         $this->assertEquals('Yo!', $message2['lastmessage']);
2298         $this->assertNotEmpty($message2['messageid']);
2299         $this->assertFalse($message2['isonline']);
2300         $this->assertTrue($message2['isread']);
2301         $this->assertFalse($message2['isblocked']);
2302         $this->assertNull($message2['unreadcount']);
2303     }
2305     /**
2306      * Tests searching messages as another user without the proper capabilities.
2307      */
2308     public function test_messagearea_search_messages_as_other_user_without_cap() {
2309         $this->resetAfterTest(true);
2311         // Create some users.
2312         $user1 = self::getDataGenerator()->create_user();
2313         $user2 = self::getDataGenerator()->create_user();
2315         // The person doing the search for another user.
2316         $this->setUser($user1);
2318         // Ensure an exception is thrown.
2319         $this->expectException('moodle_exception');
2320         core_message_external::data_for_messagearea_search_messages($user2->id, 'Search');
2321     }
2323     /**
2324      * Tests searching messages with messaging disabled
2325      */
2326     public function test_messagearea_search_messages_messaging_disabled() {
2327         global $CFG;
2329         $this->resetAfterTest(true);
2331         // Create some skeleton data just so we can call the WS.
2332         $user = self::getDataGenerator()->create_user();
2334         // The person doing the search .
2335         $this->setUser($user);
2337         // Disable messaging.
2338         $CFG->messaging = 0;
2340         // Ensure an exception is thrown.
2341         $this->expectException('moodle_exception');
2342         core_message_external::data_for_messagearea_search_messages($user->id, 'Search');
2343     }
2345     /**
2346      * Tests retrieving conversations.
2347      */
2348     public function test_messagearea_conversations() {
2349         $this->resetAfterTest(true);
2351         // Create some users.
2352         $user1 = self::getDataGenerator()->create_user();
2353         $user2 = self::getDataGenerator()->create_user();
2354         $user3 = self::getDataGenerator()->create_user();
2355         $user4 = self::getDataGenerator()->create_user();
2357         // The person retrieving the conversations.
2358         $this->setUser($user1);
2360         // Send some messages back and forth, have some different conversations with different users.
2361         $time = time();
2362         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2363         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2364         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2365         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2367         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
2368         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
2369         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
2370         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
2372         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
2373         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
2374         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
2376         // Retrieve the conversations.
2377         $result = core_message_external::data_for_messagearea_conversations($user1->id);
2379         // We need to execute the return values cleaning process to simulate the web service server.
2380         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
2381             $result);
2383         // Confirm the data is correct.
2384         $messages = $result['contacts'];
2385         $this->assertCount(3, $messages);
2387         $message1 = $messages[0];
2388         $message2 = $messages[1];
2389         $message3 = $messages[2];
2391         $this->assertEquals($user4->id, $message1['userid']);
2392         $this->assertTrue($message1['ismessaging']);
2393         $this->assertTrue($message1['sentfromcurrentuser']);
2394         $this->assertEquals('Dope.', $message1['lastmessage']);
2395         $this->assertEquals($messageid3, $message1['messageid']);
2396         $this->assertNull($message1['isonline']);
2397         $this->assertFalse($message1['isread']);
2398         $this->assertFalse($message1['isblocked']);
2399         $this->assertEquals(1, $message1['unreadcount']);
2401         $this->assertEquals($user3->id, $message2['userid']);
2402         $this->assertTrue($message2['ismessaging']);
2403         $this->assertFalse($message2['sentfromcurrentuser']);
2404         $this->assertEquals('Cool.', $message2['lastmessage']);
2405         $this->assertEquals($messageid2, $message2['messageid']);
2406         $this->assertNull($message2['isonline']);
2407         $this->assertFalse($message2['isread']);
2408         $this->assertFalse($message2['isblocked']);
2409         $this->assertEquals(2, $message2['unreadcount']);
2411         $this->assertEquals($user2->id, $message3['userid']);
2412         $this->assertTrue($message3['ismessaging']);
2413         $this->assertFalse($message3['sentfromcurrentuser']);
2414         $this->assertEquals('Word.', $message3['lastmessage']);
2415         $this->assertEquals($messageid1, $message3['messageid']);
2416         $this->assertNull($message3['isonline']);
2417         $this->assertFalse($message3['isread']);
2418         $this->assertFalse($message3['isblocked']);
2419         $this->assertEquals(2, $message3['unreadcount']);
2420     }
2422     /**
2423      * Tests retrieving conversations as another user.
2424      */
2425     public function test_messagearea_conversations_as_other_user() {
2426         $this->resetAfterTest(true);
2428         // Set as admin.
2429         $this->setAdminUser();
2431         // Create some users.
2432         $user1 = self::getDataGenerator()->create_user();
2433         $user2 = self::getDataGenerator()->create_user();
2434         $user3 = self::getDataGenerator()->create_user();
2435         $user4 = self::getDataGenerator()->create_user();
2437         // Send some messages back and forth, have some different conversations with different users.
2438         $time = time();
2439         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2440         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2441         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2442         $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2444         $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
2445         $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
2446         $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
2447         $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
2449         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
2450         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
2451         $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
2453         // Retrieve the conversations.
2454         $result = core_message_external::data_for_messagearea_conversations($user1->id);
2456         // We need to execute the return values cleaning process to simulate the web service server.
2457         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
2458             $result);
2460         // Confirm the data is correct.
2461         $messages = $result['contacts'];
2462         $this->assertCount(3, $messages);
2464         $message1 = $messages[0];
2465         $message2 = $messages[1];
2466         $message3 = $messages[2];
2468         $this->assertEquals($user4->id, $message1['userid']);
2469         $this->assertTrue($message1['ismessaging']);
2470         $this->assertTrue($message1['sentfromcurrentuser']);
2471         $this->assertEquals('Dope.', $message1['lastmessage']);
2472         $this->assertEquals($messageid3, $message1['messageid']);
2473         $this->assertFalse($message1['isonline']);
2474         $this->assertFalse($message1['isread']);
2475         $this->assertFalse($message1['isblocked']);
2476         $this->assertEquals(1, $message1['unreadcount']);
2478         $this->assertEquals($user3->id, $message2['userid']);
2479         $this->assertTrue($message2['ismessaging']);
2480         $this->assertFalse($message2['sentfromcurrentuser']);
2481         $this->assertEquals('Cool.', $message2['lastmessage']);
2482         $this->assertEquals($messageid2, $message2['messageid']);
2483         $this->assertFalse($message2['isonline']);
2484         $this->assertFalse($message2['isread']);
2485         $this->assertFalse($message2['isblocked']);
2486         $this->assertEquals(2, $message2['unreadcount']);
2488         $this->assertEquals($user2->id, $message3['userid']);
2489         $this->assertTrue($message3['ismessaging']);
2490         $this->assertFalse($message3['sentfromcurrentuser']);
2491         $this->assertEquals('Word.', $message3['lastmessage']);
2492         $this->assertEquals($messageid1, $message3['messageid']);
2493         $this->assertFalse($message3['isonline']);
2494         $this->assertFalse($message3['isread']);
2495         $this->assertFalse($message3['isblocked']);
2496         $this->assertEquals(2, $message3['unreadcount']);
2497     }
2499     /**
2500      * Tests retrieving conversations as another user without the proper capabilities.
2501      */
2502     public function test_messagearea_conversations_as_other_user_without_cap() {
2503         $this->resetAfterTest(true);
2505         // Create some users.
2506         $user1 = self::getDataGenerator()->create_user();
2507         $user2 = self::getDataGenerator()->create_user();
2509         // The person retrieving the conversations for another user.
2510         $this->setUser($user1);
2512         // Ensure an exception is thrown.
2513         $this->expectException('moodle_exception');
2514         core_message_external::data_for_messagearea_conversations($user2->id);
2515     }
2517     /**
2518      * Tests retrieving conversations with messaging disabled.
2519      */
2520     public function test_messagearea_conversations_messaging_disabled() {
2521         global $CFG;
2523         $this->resetAfterTest(true);
2525         // Create some skeleton data just so we can call the WS.
2526         $user = self::getDataGenerator()->create_user();
2528         // The person retrieving the conversations.
2529         $this->setUser($user);
2531         // Disable messaging.
2532         $CFG->messaging = 0;
2534         // Ensure an exception is thrown.
2535         $this->expectException('moodle_exception');
2536         core_message_external::data_for_messagearea_conversations($user->id);
2537     }
2539     /**
2540      * Tests retrieving contacts.
2541      */
2542     public function test_messagearea_contacts() {
2543         $this->resetAfterTest(true);
2545         // Create some users.
2546         $user1 = self::getDataGenerator()->create_user();
2548         // Set as the user.
2549         $this->setUser($user1);
2551         $user2 = new stdClass();
2552         $user2->firstname = 'User';
2553         $user2->lastname = 'A';
2554         $user2 = self::getDataGenerator()->create_user($user2);
2556         $user3 = new stdClass();
2557         $user3->firstname = 'User';
2558         $user3->lastname = 'B';
2559         $user3 = self::getDataGenerator()->create_user($user3);
2561         $user4 = new stdClass();
2562         $user4->firstname = 'User';
2563         $user4->lastname = 'C';
2564         $user4 = self::getDataGenerator()->create_user($user4);
2566         $user5 = new stdClass();
2567         $user5->firstname = 'User';
2568         $user5->lastname = 'D';
2569         $user5 = self::getDataGenerator()->create_user($user5);
2571         // Add some users as contacts.
2572         \core_message\api::add_contact($user1->id, $user2->id);
2573         \core_message\api::add_contact($user1->id, $user3->id);
2574         \core_message\api::add_contact($user1->id, $user4->id);
2576         // Retrieve the contacts.
2577         $result = core_message_external::data_for_messagearea_contacts($user1->id);
2579         // We need to execute the return values cleaning process to simulate the web service server.
2580         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
2581             $result);
2583         // Confirm the data is correct.
2584         $contacts = $result['contacts'];
2585         usort($contacts, ['static', 'sort_contacts']);
2586         $this->assertCount(3, $contacts);
2588         $contact1 = $contacts[0];
2589         $contact2 = $contacts[1];
2590         $contact3 = $contacts[2];
2592         $this->assertEquals($user2->id, $contact1['userid']);
2593         $this->assertFalse($contact1['ismessaging']);
2594         $this->assertFalse($contact1['sentfromcurrentuser']);
2595         $this->assertNull($contact1['lastmessage']);
2596         $this->assertNull($contact1['messageid']);
2597         $this->assertNull($contact1['isonline']);
2598         $this->assertFalse($contact1['isread']);
2599         $this->assertFalse($contact1['isblocked']);
2600         $this->assertNull($contact1['unreadcount']);
2602         $this->assertEquals($user3->id, $contact2['userid']);
2603         $this->assertFalse($contact2['ismessaging']);
2604         $this->assertFalse($contact2['sentfromcurrentuser']);
2605         $this->assertNull($contact2['lastmessage']);
2606         $this->assertNull($contact2['messageid']);
2607         $this->assertNull($contact2['isonline']);
2608         $this->assertFalse($contact2['isread']);
2609         $this->assertFalse($contact2['isblocked']);
2610         $this->assertNull($contact2['unreadcount']);
2612         $this->assertEquals($user4->id, $contact3['userid']);
2613         $this->assertFalse($contact3['ismessaging']);
2614         $this->assertFalse($contact3['sentfromcurrentuser']);
2615         $this->assertNull($contact3['lastmessage']);
2616         $this->assertNull($contact3['messageid']);
2617         $this->assertNull($contact3['isonline']);
2618         $this->assertFalse($contact3['isread']);
2619         $this->assertFalse($contact3['isblocked']);
2620         $this->assertNull($contact3['unreadcount']);
2621     }
2623     /**
2624      * Tests retrieving contacts as another user.
2625      */
2626     public function test_messagearea_contacts_as_other_user() {
2627         $this->resetAfterTest(true);
2629         $this->setAdminUser();
2631         // Create some users.
2632         $user1 = self::getDataGenerator()->create_user();
2634         $user2 = new stdClass();
2635         $user2->firstname = 'User';
2636         $user2->lastname = 'A';
2637         $user2 = self::getDataGenerator()->create_user($user2);
2639         $user3 = new stdClass();
2640         $user3->firstname = 'User';
2641         $user3->lastname = 'B';
2642         $user3 = self::getDataGenerator()->create_user($user3);
2644         $user4 = new stdClass();
2645         $user4->firstname = 'User';
2646         $user4->lastname = 'C';
2647         $user4 = self::getDataGenerator()->create_user($user4);
2649         $user5 = new stdClass();
2650         $user5->firstname = 'User';
2651         $user5->lastname = 'D';
2652         $user5 = self::getDataGenerator()->create_user($user5);
2654         // Add some users as contacts.
2655         \core_message\api::add_contact($user1->id, $user2->id);
2656         \core_message\api::add_contact($user1->id, $user3->id);
2657         \core_message\api::add_contact($user1->id, $user4->id);
2659         // Retrieve the contacts.
2660         $result = core_message_external::data_for_messagearea_contacts($user1->id);
2662         // We need to execute the return values cleaning process to simulate the web service server.
2663         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
2664             $result);
2666         // Confirm the data is correct.
2667         $contacts = $result['contacts'];
2668         usort($contacts, ['static', 'sort_contacts']);
2669         $this->assertCount(3, $contacts);
2671         $contact1 = $contacts[0];
2672         $contact2 = $contacts[1];
2673         $contact3 = $contacts[2];
2675         $this->assertEquals($user2->id, $contact1['userid']);
2676         $this->assertFalse($contact1['ismessaging']);
2677         $this->assertFalse($contact1['sentfromcurrentuser']);
2678         $this->assertNull($contact1['lastmessage']);
2679         $this->assertNull($contact1['messageid']);
2680         $this->assertFalse($contact1['isonline']);
2681         $this->assertFalse($contact1['isread']);
2682         $this->assertFalse($contact1['isblocked']);
2683         $this->assertNull($contact1['unreadcount']);
2685         $this->assertEquals($user3->id, $contact2['userid']);
2686         $this->assertFalse($contact2['ismessaging']);
2687         $this->assertFalse($contact2['sentfromcurrentuser']);
2688         $this->assertNull($contact2['lastmessage']);
2689         $this->assertNull($contact2['messageid']);
2690         $this->assertFalse($contact2['isonline']);
2691         $this->assertFalse($contact2['isread']);
2692         $this->assertFalse($contact2['isblocked']);
2693         $this->assertNull($contact2['unreadcount']);
2695         $this->assertEquals($user4->id, $contact3['userid']);
2696         $this->assertFalse($contact3['ismessaging']);
2697         $this->assertFalse($contact3['sentfromcurrentuser']);
2698         $this->assertNull($contact3['lastmessage']);
2699         $this->assertNull($contact3['messageid']);
2700         $this->assertFalse($contact3['isonline']);
2701         $this->assertFalse($contact3['isread']);
2702         $this->assertFalse($contact3['isblocked']);
2703         $this->assertNull($contact3['unreadcount']);
2704     }
2706     /**
2707      * Tests retrieving contacts as another user without the proper capabilities.
2708      */
2709     public function test_messagearea_contacts_as_other_user_without_cap() {
2710         $this->resetAfterTest(true);
2712         // Create some users.
2713         $user1 = self::getDataGenerator()->create_user();
2714         $user2 = self::getDataGenerator()->create_user();
2716         // The person retrieving the contacts for another user.
2717         $this->setUser($user1);
2719         // Perform the WS call and ensure an exception is thrown.
2720         $this->expectException('moodle_exception');
2721         core_message_external::data_for_messagearea_contacts($user2->id);
2722     }
2724     /**
2725      * Tests retrieving contacts with messaging disabled.
2726      */
2727     public function test_messagearea_contacts_messaging_disabled() {
2728         global $CFG;
2730         $this->resetAfterTest(true);
2732         // Create some skeleton data just so we can call the WS.
2733         $user = self::getDataGenerator()->create_user();
2735         // The person retrieving the contacts.
2736         $this->setUser($user);
2738         // Disable messaging.
2739         $CFG->messaging = 0;
2741         // Perform the WS call and ensure we are shown that it is disabled.
2742         $this->expectException('moodle_exception');
2743         core_message_external::data_for_messagearea_contacts($user->id);
2744     }
2746     /**
2747      * Tests retrieving messages.
2748      */
2749     public function test_messagearea_messages() {
2750         $this->resetAfterTest(true);
2752         // Create some users.
2753         $user1 = self::getDataGenerator()->create_user();
2754         $user2 = self::getDataGenerator()->create_user();
2756         // The person asking for the messages.
2757         $this->setUser($user1);
2759         // Send some messages back and forth.
2760         $time = time();
2761         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2762         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2763         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2764         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2766         // Retrieve the messages.
2767         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2769         // We need to execute the return values cleaning process to simulate the web service server.
2770         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2771             $result);
2773         // Check the results are correct.
2774         $this->assertTrue($result['iscurrentuser']);
2775         $this->assertEquals($user1->id, $result['currentuserid']);
2776         $this->assertEquals($user2->id, $result['otheruserid']);
2777         $this->assertEquals(fullname($user2), $result['otheruserfullname']);
2778         $this->assertNull($result['isonline']);
2780         // Confirm the message data is correct.
2781         $messages = $result['messages'];
2782         $this->assertCount(4, $messages);
2784         $message1 = $messages[0];
2785         $message2 = $messages[1];
2786         $message3 = $messages[2];
2787         $message4 = $messages[3];
2789         $this->assertEquals($user1->id, $message1['useridfrom']);
2790         $this->assertEquals($user2->id, $message1['useridto']);
2791         $this->assertTrue($message1['displayblocktime']);
2792         $this->assertContains('Yo!', $message1['text']);
2794         $this->assertEquals($user2->id, $message2['useridfrom']);
2795         $this->assertEquals($user1->id, $message2['useridto']);
2796         $this->assertFalse($message2['displayblocktime']);
2797         $this->assertContains('Sup mang?', $message2['text']);
2799         $this->assertEquals($user1->id, $message3['useridfrom']);
2800         $this->assertEquals($user2->id, $message3['useridto']);
2801         $this->assertFalse($message3['displayblocktime']);
2802         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
2804         $this->assertEquals($user2->id, $message4['useridfrom']);
2805         $this->assertEquals($user1->id, $message4['useridto']);
2806         $this->assertFalse($message4['displayblocktime']);
2807         $this->assertContains('Word.', $message4['text']);
2808     }
2810     /**
2811      * Tests retrieving messages.
2812      */
2813     public function test_messagearea_messages_timefrom() {
2814         $this->resetAfterTest(true);
2816         // Create some users.
2817         $user1 = self::getDataGenerator()->create_user();
2818         $user2 = self::getDataGenerator()->create_user();
2820         // The person asking for the messages.
2821         $this->setUser($user1);
2823         // Send some messages back and forth.
2824         $time = time();
2825         $this->send_message($user1, $user2, 'Message 1', 0, $time - 4);
2826         $this->send_message($user2, $user1, 'Message 2', 0, $time - 3);
2827         $this->send_message($user1, $user2, 'Message 3', 0, $time - 2);
2828         $this->send_message($user2, $user1, 'Message 4', 0, $time - 1);
2830         // Retrieve the messages from $time - 3, which should be the 3 most recent messages.
2831         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id, 0, 0, false, $time - 3);
2833         // We need to execute the return values cleaning process to simulate the web service server.
2834         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2835             $result);
2837         // Confirm the message data is correct. We shouldn't get 'Message 1' back.
2838         $messages = $result['messages'];
2839         $this->assertCount(3, $messages);
2841         $message1 = $messages[0];
2842         $message2 = $messages[1];
2843         $message3 = $messages[2];
2845         $this->assertContains('Message 2', $message1['text']);
2846         $this->assertContains('Message 3', $message2['text']);
2847         $this->assertContains('Message 4', $message3['text']);
2848     }
2850     /**
2851      * Tests retrieving messages as another user.
2852      */
2853     public function test_messagearea_messages_as_other_user() {
2854         $this->resetAfterTest(true);
2856         // Set as admin.
2857         $this->setAdminUser();
2859         // Create some users.
2860         $user1 = self::getDataGenerator()->create_user();
2861         $user2 = self::getDataGenerator()->create_user();
2863         // Send some messages back and forth.
2864         $time = time();
2865         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2866         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2867         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2868         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2870         // Retrieve the messages.
2871         $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2873         // We need to execute the return values cleaning process to simulate the web service server.
2874         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
2875             $result);
2877         // Check the results are correct.
2878         $this->assertFalse($result['iscurrentuser']);
2879         $this->assertEquals($user1->id, $result['currentuserid']);
2880         $this->assertEquals($user2->id, $result['otheruserid']);
2881         $this->assertEquals(fullname($user2), $result['otheruserfullname']);
2882         $this->assertFalse($result['isonline']);
2884         // Confirm the message data is correct.
2885         $messages = $result['messages'];
2886         $this->assertCount(4, $messages);
2888         $message1 = $messages[0];
2889         $message2 = $messages[1];
2890         $message3 = $messages[2];
2891         $message4 = $messages[3];
2893         $this->assertEquals($user1->id, $message1['useridfrom']);
2894         $this->assertEquals($user2->id, $message1['useridto']);
2895         $this->assertTrue($message1['displayblocktime']);
2896         $this->assertContains('Yo!', $message1['text']);
2898         $this->assertEquals($user2->id, $message2['useridfrom']);
2899         $this->assertEquals($user1->id, $message2['useridto']);
2900         $this->assertFalse($message2['displayblocktime']);
2901         $this->assertContains('Sup mang?', $message2['text']);
2903         $this->assertEquals($user1->id, $message3['useridfrom']);
2904         $this->assertEquals($user2->id, $message3['useridto']);
2905         $this->assertFalse($message3['displayblocktime']);
2906         $this->assertContains('Writing PHPUnit tests!', $message3['text']);
2908         $this->assertEquals($user2->id, $message4['useridfrom']);
2909         $this->assertEquals($user1->id, $message4['useridto']);
2910         $this->assertFalse($message4['displayblocktime']);
2911         $this->assertContains('Word.', $message4['text']);
2912     }
2914     /**
2915      * Tests retrieving messages as another user without the proper capabilities.
2916      */
2917     public function test_messagearea_messages_as_other_user_without_cap() {
2918         $this->resetAfterTest(true);
2920         // Create some users.
2921         $user1 = self::getDataGenerator()->create_user();
2922         $user2 = self::getDataGenerator()->create_user();
2923         $user3 = self::getDataGenerator()->create_user();
2925         // The person asking for the messages for another user.
2926         $this->setUser($user1);
2928         // Ensure an exception is thrown.
2929         $this->expectException('moodle_exception');
2930         core_message_external::data_for_messagearea_messages($user2->id, $user3->id);
2931     }
2933     /**
2934      * Tests retrieving messages with messaging disabled.
2935      */
2936     public function test_messagearea_messages_messaging_disabled() {
2937         global $CFG;
2939         $this->resetAfterTest(true);
2941         // Create some skeleton data just so we can call the WS.
2942         $user1 = self::getDataGenerator()->create_user();
2943         $user2 = self::getDataGenerator()->create_user();
2945         // The person asking for the messages for another user.
2946         $this->setUser($user1);
2948         // Disable messaging.
2949         $CFG->messaging = 0;
2951         // Ensure an exception is thrown.
2952         $this->expectException('moodle_exception');
2953         core_message_external::data_for_messagearea_messages($user1->id, $user2->id);
2954     }
2956     /**
2957      * Tests retrieving most recent message.
2958      */
2959     public function test_messagearea_get_most_recent_message() {
2960         $this->resetAfterTest(true);
2962         // Create some users.
2963         $user1 = self::getDataGenerator()->create_user();
2964         $user2 = self::getDataGenerator()->create_user();
2966         // The person doing the search.
2967         $this->setUser($user1);
2969         // Send some messages back and forth.
2970         $time = time();
2971         $this->send_message($user1, $user2, 'Yo!', 0, $time);
2972         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2973         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2974         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2976         // Get the most recent message.
2977         $result = core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
2979         // We need to execute the return values cleaning process to simulate the web service server.
2980         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_most_recent_message_returns(),
2981             $result);
2983         // Check the results are correct.
2984         $this->assertEquals($user2->id, $result['useridfrom']);
2985         $this->assertEquals($user1->id, $result['useridto']);
2986         $this->assertContains('Word.', $result['text']);
2987     }
2989     /**
2990      * Tests retrieving most recent message as another user.
2991      */
2992     public function test_messagearea_get_most_recent_message_as_other_user() {
2993         $this->resetAfterTest(true);
2995         // The person doing the search.
2996         $this->setAdminUser();
2998         // Create some users.
2999         $user1 = self::getDataGenerator()->create_user();
3000         $user2 = self::getDataGenerator()->create_user();
3002         // Send some messages back and forth.
3003         $time = time();
3004         $this->send_message($user1, $user2, 'Yo!', 0, $time);
3005         $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3006         $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
3007         $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
3009         // Get the most recent message.
3010         $result = core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
3012         // We need to execute the return values cleaning process to simulate the web service server.
3013         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_most_recent_message_returns(),
3014             $result);
3016         // Check the results are correct.
3017         $this->assertEquals($user2->id, $result['useridfrom']);
3018         $this->assertEquals($user1->id, $result['useridto']);
3019         $this->assertContains('Word.', $result['text']);
3020     }
3022     /**
3023      * Tests retrieving most recent message as another user without the proper capabilities.
3024      */
3025     public function test_messagearea_get_most_recent_message_as_other_user_without_cap() {
3026         $this->resetAfterTest(true);
3028         // Create some users.
3029         $user1 = self::getDataGenerator()->create_user();
3030         $user2 = self::getDataGenerator()->create_user();
3031         $user3 = self::getDataGenerator()->create_user();
3033         // The person asking for the most recent message for another user.
3034         $this->setUser($user1);
3036         // Ensure an exception is thrown.
3037         $this->expectException('moodle_exception');
3038         core_message_external::data_for_messagearea_get_most_recent_message($user2->id, $user3->id);
3039     }
3041     /**
3042      * Tests retrieving most recent message with messaging disabled.
3043      */
3044     public function test_messagearea_get_most_recent_message_messaging_disabled() {
3045         global $CFG;
3047         $this->resetAfterTest(true);
3049         // Create some skeleton data just so we can call the WS.
3050         $user1 = self::getDataGenerator()->create_user();
3051         $user2 = self::getDataGenerator()->create_user();
3053         // The person asking for the most recent message.
3054         $this->setUser($user1);
3056         // Disable messaging.
3057         $CFG->messaging = 0;
3059         // Ensure an exception is thrown.
3060         $this->expectException('moodle_exception');
3061         core_message_external::data_for_messagearea_get_most_recent_message($user1->id, $user2->id);
3062     }
3064     /**
3065      * Tests retrieving a user's profile.
3066      */
3067     public function test_messagearea_get_profile() {
3068         $this->resetAfterTest(true);
3070         // Create some users.
3071         $user1 = self::getDataGenerator()->create_user();
3072         $user2 = self::getDataGenerator()->create_user();
3074         // The person asking for the profile information.
3075         $this->setUser($user1);
3077         // Get the profile.
3078         $result = core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
3080         // We need to execute the return values cleaning process to simulate the web service server.
3081         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_profile_returns(),
3082             $result);
3084         $this->assertEquals($user2->id, $result['userid']);
3085         $this->assertEmpty($result['email']);
3086         $this->assertEmpty($result['country']);
3087         $this->assertEmpty($result['city']);
3088         $this->assertEquals(fullname($user2), $result['fullname']);
3089         $this->assertNull($result['isonline']);
3090         $this->assertFalse($result['isblocked']);
3091         $this->assertFalse($result['iscontact']);
3092     }
3094     /**
3095      * Tests retrieving a user's profile as another user.
3096      */
3097     public function test_messagearea_profile_as_other_user() {
3098         $this->resetAfterTest(true);
3100         // The person asking for the profile information.
3101         $this->setAdminUser();
3103         // Create some users.
3104         $user1 = self::getDataGenerator()->create_user();
3106         $user2 = new stdClass();
3107         $user2->country = 'AU';
3108         $user2->city = 'Perth';
3109         $user2 = self::getDataGenerator()->create_user($user2);
3111         // Get the profile.
3112         $result = core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
3114         // We need to execute the return values cleaning process to simulate the web service server.
3115         $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_get_profile_returns(),
3116             $result);
3118         $this->assertEquals($user2->id, $result['userid']);
3119         $this->assertEquals($user2->email, $result['email']);
3120         $this->assertEquals(get_string($user2->country, 'countries'), $result['country']);
3121         $this->assertEquals($user2->city, $result['city']);
3122         $this->assertEquals(fullname($user2), $result['fullname']);
3123         $this->assertFalse($result['isonline']);
3124         $this->assertFalse($result['isblocked']);
3125         $this->assertFalse($result['iscontact']);
3126     }
3128     /**
3129      * Tests retrieving a user's profile as another user without the proper capabilities.
3130      */
3131     public function test_messagearea_profile_as_other_user_without_cap() {
3132         $this->resetAfterTest(true);
3134         // Create some users.
3135         $user1 = self::getDataGenerator()->create_user();
3136         $user2 = self::getDataGenerator()->create_user();
3137         $user3 = self::getDataGenerator()->create_user();
3139         // The person asking for the profile information for another user.
3140         $this->setUser($user1);
3142         // Ensure an exception is thrown.
3143         $this->expectException('moodle_exception');
3144         core_message_external::data_for_messagearea_get_profile($user2->id, $user3->id);
3145     }
3147     /**
3148      * Tests retrieving a user's profile with messaging disabled.
3149      */
3150     public function test_messagearea_profile_messaging_disabled() {
3151         global $CFG;
3153         $this->resetAfterTest(true);
3155         // Create some skeleton data just so we can call the WS.
3156         $user1 = self::getDataGenerator()->create_user();
3157         $user2 = self::getDataGenerator()->create_user();
3159         // The person asking for the profile information.
3160         $this->setUser($user1);
3162         // Disable messaging.
3163         $CFG->messaging = 0;
3165         // Ensure an exception is thrown.
3166         $this->expectException('moodle_exception');
3167         core_message_external::data_for_messagearea_get_profile($user1->id, $user2->id);
3168     }
3170     /**
3171      * Test marking all message as read with an invalid user.
3172      */
3173     public function test_mark_all_messages_as_read_invalid_user_exception() {
3174         $this->resetAfterTest(true);
3176         $this->expectException('moodle_exception');
3177         core_message_external::mark_all_messages_as_read(-2132131, 0);
3178     }
3180     /**
3181      * Test marking all message as read without proper access.
3182      */
3183     public function test_mark_all_messages_as_read_access_denied_exception() {
3184         $this->resetAfterTest(true);
3186         $sender = $this->getDataGenerator()->create_user();
3187         $user = $this->getDataGenerator()->create_user();
3189         $this->setUser($user);
3190         $this->expectException('moodle_exception');
3191         core_message_external::mark_all_messages_as_read($sender->id, 0);
3192     }
3194     /**
3195      * Test marking all message as read with missing from user.
3196      */
3197     public function test_mark_all_messages_as_read_missing_from_user_exception() {
3198         $this->resetAfterTest(true);
3200         $sender = $this->getDataGenerator()->create_user();
3202         $this->setUser($sender);
3203         $this->expectException('moodle_exception');
3204         core_message_external::mark_all_messages_as_read($sender->id, 99999);
3205     }
3207     /**
3208      * Test marking all message as read.
3209      */
3210     public function test_mark_all_messages_as_read() {
3211         global $DB;
3213         $this->resetAfterTest(true);
3215         $sender1 = $this->getDataGenerator()->create_user();
3216         $sender2 = $this->getDataGenerator()->create_user();
3217         $sender3 = $this->getDataGenerator()->create_user();
3218         $recipient = $this->getDataGenerator()->create_user();
3220         $this->setUser($recipient);
3222         $this->send_message($sender1, $recipient, 'Message');
3223         $this->send_message($sender1, $recipient, 'Message');
3224         $this->send_message($sender2, $recipient, 'Message');
3225         $this->send_message($sender2, $recipient, 'Message');
3226         $this->send_message($sender3, $recipient, 'Message');
3227         $this->send_message($sender3, $recipient, 'Message');
3229         core_message_external::mark_all_messages_as_read($recipient->id, $sender1->id);
3230         $this->assertEquals(2, $DB->count_records('message_user_actions'));
3232         core_message_external::mark_all_messages_as_read($recipient->id, 0);
3233         $this->assertEquals(6, $DB->count_records('message_user_actions'));
3234     }
3236     /**
3237      * Test getting unread conversation count.
3238      */
3239     public function test_get_unread_conversations_count() {
3240         $this->resetAfterTest(true);
3242         // Create some users.
3243         $user1 = self::getDataGenerator()->create_user();
3244         $user2 = self::getDataGenerator()->create_user();
3245         $user3 = self::getDataGenerator()->create_user();
3246         $user4 = self::getDataGenerator()->create_user();
3248         // The person wanting the conversation count.
3249         $this->setUser($user1);
3251         // Send some messages back and forth, have some different conversations with different users.
3252         $this->send_message($user1, $user2, 'Yo!');
3253         $this->send_message($user2, $user1, 'Sup mang?');
3254         $this->send_message($user1, $user2, 'Writing PHPUnit tests!');
3255         $this->send_message($user2, $user1, 'Word.');
3257         $this->send_message($user1, $user3, 'Booyah');
3258         $this->send_message($user3, $user1, 'Whaaat?');
3259         $this->send_message($user1, $user3, 'Nothing.');
3260         $this->send_message($user3, $user1, 'Cool.');
3262         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
3263         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
3264         $this->send_message($user1, $user4, 'Dope.');
3266         // Get the unread conversation count.
3267         $result = core_message_external::get_unread_conversations_count($user1->id);
3269         // We need to execute the return values cleaning process to simulate the web service server.
3270         $result = external_api::clean_returnvalue(core_message_external::get_unread_conversations_count_returns(),
3271             $result);
3273         $this->assertEquals(3, $result);
3274     }
3276     /**
3277      * Test getting unread conversation count as other user.
3278      */
3279     public function test_get_unread_conversations_count_as_other_user() {
3280         $this->resetAfterTest(true);
3282         // The person wanting the conversation count.
3283         $this->setAdminUser();
3285         // Create some users.
3286         $user1 = self::getDataGenerator()->create_user();
3287         $user2 = self::getDataGenerator()->create_user();
3288         $user3 = self::getDataGenerator()->create_user();
3289         $user4 = self::getDataGenerator()->create_user();
3291         // Send some messages back and forth, have some different conversations with different users.
3292         $this->send_message($user1, $user2, 'Yo!');
3293         $this->send_message($user2, $user1, 'Sup mang?');
3294         $this->send_message($user1, $user2, 'Writing PHPUnit tests!');
3295         $this->send_message($user2, $user1, 'Word.');
3297         $this->send_message($user1, $user3, 'Booyah');
3298         $this->send_message($user3, $user1, 'Whaaat?');
3299         $this->send_message($user1, $user3, 'Nothing.');
3300         $this->send_message($user3, $user1, 'Cool.');
3302         $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
3303         $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
3304         $this->send_message($user1, $user4, 'Dope.');
3306         // Get the unread conversation count.
3307         $result = core_message_external::get_unread_conversations_count($user1->id);
3309         // We need to execute the return values cleaning process to simulate the web service server.
3310         $result = external_api::clean_returnvalue(core_message_external::get_unread_conversations_count_returns(),
3311             $result);
3313         $this->assertEquals(3, $result);
3314     }
3316     /**
3317      * Test getting unread conversation count as other user without proper capability.
3318      */
3319     public function test_get_unread_conversations_count_as_other_user_without_cap() {
3320         $this->resetAfterTest(true);
3322         // Create some users.
3323         $user1 = self::getDataGenerator()->create_user();
3324         $user2 = self::getDataGenerator()->create_user();
3326         // The person wanting the conversation count.
3327         $this->setUser($user1);
3329         // Ensure an exception is thrown.
3330         $this->expectException('moodle_exception');
3331         core_message_external::get_unread_conversations_count($user2->id);
3332     }
3334     /**
3335      * Test deleting conversation.
3336      */
3337     public function test_delete_conversation() {
3338         global $DB;
3340         $this->resetAfterTest(true);
3342         // Create some users.
3343         $user1 = self::getDataGenerator()->create_user();
3344         $user2 = self::getDataGenerator()->create_user();
3346         // The person wanting to delete the conversation.
3347         $this->setUser($user1);
3349         // Send some messages back and forth.
3350         $time = time();
3351         $m1id = $this->send_message($user1, $user2, 'Yo!', 0, $time);
3352         $m2id = $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3353         $m3id = $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
3354         $m4id = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
3356         // Delete the conversation.
3357         core_message_external::delete_conversation($user1->id, $user2->id);
3359         $muas = $DB->get_records('message_user_actions', array(), 'timecreated ASC');
3360         $this->assertCount(4, $muas);
3361         // Sort by id.
3362         ksort($muas);
3364         $mua1 = array_shift($muas);
3365         $mua2 = array_shift($muas);
3366         $mua3 = array_shift($muas);
3367         $mua4 = array_shift($muas);
3369         $this->assertEquals($user1->id, $mua1->userid);
3370         $this->assertEquals($m1id, $mua1->messageid);
3371         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua1->action);
3373         $this->assertEquals($user1->id, $mua2->userid);
3374         $this->assertEquals($m2id, $mua2->messageid);
3375         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua2->action);
3377         $this->assertEquals($user1->id, $mua3->userid);
3378         $this->assertEquals($m3id, $mua3->messageid);
3379         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua3->action);
3381         $this->assertEquals($user1->id, $mua4->userid);
3382         $this->assertEquals($m4id, $mua4->messageid);
3383         $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua4->action);
3384     }
3386     /**
3387      * Test deleting conversation as other user.
3388      */
3389     public function test_delete_conversation_as_other_user() {
3390         global $DB;
3392         $this->resetAfterTest(true);
3394         $this->setAdminUser();
3396         // Create some users.
3397         $user1 = self::getDataGenerator()->create_user();
3398         $user2 = self::getDataGenerator()->create_user();
3400         // Send some messages back and forth.
3401         $time = time();
3402         $m1id = $this->send_message($user1, $user2, 'Yo!', 0, $time);
3403         $m2id = $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3404         $m3id = $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
3405         $m4id = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);